<commit_before>#include "Event.hh"
#include "Subject.hh"

#include <functional>
#include <iostream>

void freeObserver( const Event& event )
{
  if( event.type() == EventType::Creation )
    std::cout << __PRETTY_FUNCTION__ << ": Creation" << std::endl;
  else if( event.type() == EventType::Destruction )
    std::cout << __PRETTY_FUNCTION__ << ": Destruction" << std::endl;
}

class ClassObserver
{
public:
  void handleCreation( const Event& )
  {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
  }

  void handleDestruction( const Event& )
  {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
  }
};

int main( int, char** )
{
  ClassObserver classObserver;

  Subject s;
  s.registerObserver( EventType::Creation,    freeObserver );
  s.registerObserver( EventType::Destruction, freeObserver );
  //s.registerObserver( EventType::Creation,    std::bind( &classObserver.handleCreation, &classObserver ) );

  CreationEvent creation;
  DestructionEvent destruction;

  s.notify( creation );
  s.notify( destruction );

  return 0;
}
<commit_msg>Registered destruction event<commit_after>#include "Event.hh"
#include "Subject.hh"

#include <functional>
#include <iostream>

void freeObserver( const Event& event )
{
  if( event.type() == EventType::Creation )
    std::cout << __PRETTY_FUNCTION__ << ": Creation" << std::endl;
  else if( event.type() == EventType::Destruction )
    std::cout << __PRETTY_FUNCTION__ << ": Destruction" << std::endl;
}

class ClassObserver
{
public:
  void handleCreation( const Event& )
  {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
  }

  void handleDestruction( const Event& )
  {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
  }
};

int main( int, char** )
{
  ClassObserver classObserver;

  Subject s;
  s.registerObserver( EventType::Creation,    freeObserver );
  s.registerObserver( EventType::Destruction, freeObserver );
  s.registerObserver( EventType::Creation,    std::bind( &ClassObserver::handleCreation, &classObserver, std::placeholders::_1 ) );
  s.registerObserver( EventType::Destruction, std::bind( &ClassObserver::handleDestruction, &classObserver, std::placeholders::_1 ) );

  CreationEvent creation;
  DestructionEvent destruction;

  s.notify( creation );
  s.notify( destruction );

  return 0;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Image (gli.g-truc.net)
///
/// Copyright (c) 2008 - 2015 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @ref core
/// @file gli/core/save_ktx.inl
/// @date 2015-08-05 / 2015-08-05
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////

#include <cstdio>
#include <glm/gtc/round.hpp>

namespace gli{
namespace detail
{
	inline std::size_t compute_ktx_storage_size(texture const & Texture)
	{
		std::uint32_t const BlockSize = block_size(Texture.format());
		std::size_t TotalSize = sizeof(detail::ktxHeader);

		for(std::size_t Level = 0, Levels = Texture.levels(); Level < Levels; ++Level)
		{
			TotalSize += sizeof(std::uint32_t);

			for(std::size_t Layer = 0, Layers = Texture.layers(); Layer < Layers; ++Layer)
			{
				for(std::size_t Face = 0, Faces = Texture.faces(); Face < Faces; ++Face)
				{
					std::uint32_t const FaceSize = static_cast<std::uint32_t>(Texture.size(Level));
					std::uint32_t const PaddedSize = std::max(BlockSize, glm::ceilMultiple(FaceSize, static_cast<std::uint32_t>(4)));

					TotalSize += PaddedSize;
				}
			}
		}

		return TotalSize;
	}

}//namespace detail

	inline bool save_ktx(texture const & Texture, std::vector<char> & Memory)
	{
		if(Texture.empty())
			return false;

		gl GL;
		gl::format const & Format = GL.translate(Texture.format());
		target const Target = Texture.target();

		detail::formatInfo const & Desc = detail::get_format_info(Texture.format());

		Memory.resize(detail::compute_ktx_storage_size(Texture) + sizeof(detail::ktxHeader));

		detail::ktxHeader & Header = *reinterpret_cast<detail::ktxHeader*>(&Memory[0]);

		static unsigned char const Identifier[] =
		{
		   0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
		};

		memcpy(Header.Identifier, Identifier, sizeof(Header.Identifier));
		Header.Endianness = 0x04030201;
		Header.GLType = Format.Type;
		Header.GLTypeSize = Format.Type == gl::TYPE_NONE ? 1 : Desc.BlockSize;
		Header.GLFormat = Format.External;
		Header.GLInternalFormat = Format.Internal;
		Header.GLBaseInternalFormat = Format.External;
		Header.PixelWidth = static_cast<std::uint32_t>(Texture.dimensions().x);
		Header.PixelHeight = !is_target_1d(Target) ? static_cast<std::uint32_t>(Texture.dimensions().y) : 0;
		Header.PixelDepth = Target == TARGET_3D ? static_cast<std::uint32_t>(Texture.dimensions().z) : 0;
		Header.NumberOfArrayElements = is_target_array(Target) ? static_cast<std::uint32_t>(Texture.layers()) : 0;
		Header.NumberOfFaces = is_target_cube(Target) ? static_cast<std::uint32_t>(Texture.faces()) : 0;
		Header.NumberOfMipmapLevels = static_cast<std::uint32_t>(Texture.levels());
		Header.BytesOfKeyValueData = 0;

		std::size_t Offset = sizeof(detail::ktxHeader);

		for(std::size_t Level = 0, Levels = Texture.levels(); Level < Levels; ++Level)
		{
			std::uint32_t& ImageSize = *reinterpret_cast<std::uint32_t*>(&Memory[0] + Offset);
			Offset += sizeof(std::uint32_t);

			for(std::size_t Layer = 0, Layers = Texture.layers(); Layer < Layers; ++Layer)
			{
				for(std::size_t Face = 0, Faces = Texture.faces(); Face < Faces; ++Face)
				{
					std::uint32_t const FaceSize = static_cast<std::uint32_t>(Texture.size(Level));

					std::memcpy(&Memory[0] + Offset, Texture.data(Layer, Face, Level), FaceSize);

					std::uint32_t const PaddedSize = glm::ceilMultiple(FaceSize, static_cast<std::uint32_t>(4));

					ImageSize += PaddedSize;
					Offset += PaddedSize;

					assert(Offset <= Memory.size());
				}
			}

			ImageSize = glm::ceilMultiple(ImageSize, static_cast<std::uint32_t>(4));
		}

		return true;
	}

	inline bool save_ktx(texture const & Texture, char const * Filename)
	{
		if(Texture.empty())
			return false;

#if defined(__ANDROID__) || defined(__linux__)
		FILE* File = std::fopen(Filename, "wb");
#else
		FILE* File = 0;
		fopen_s(&File, Filename, "wb");
#endif

		std::vector<char> Memory;
		bool const Result = save_ktx(Texture, Memory);

		std::fwrite(&Memory[0], 1, Memory.size(), File);
		std::fclose(File);

		return Result;
	}

	inline bool save_ktx(texture const & Texture, std::string const & Filename)
	{
		return save_ktx(Texture, Filename.c_str());
	}
}//namespace gli
<commit_msg>* Added check for knowing if a file failed to open.<commit_after>///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Image (gli.g-truc.net)
///
/// Copyright (c) 2008 - 2015 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @ref core
/// @file gli/core/save_ktx.inl
/// @date 2015-08-05 / 2015-08-05
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////

#include <cstdio>
#include <glm/gtc/round.hpp>

namespace gli{
namespace detail
{
	inline std::size_t compute_ktx_storage_size(texture const & Texture)
	{
		std::uint32_t const BlockSize = block_size(Texture.format());
		std::size_t TotalSize = sizeof(detail::ktxHeader);

		for(std::size_t Level = 0, Levels = Texture.levels(); Level < Levels; ++Level)
		{
			TotalSize += sizeof(std::uint32_t);

			for(std::size_t Layer = 0, Layers = Texture.layers(); Layer < Layers; ++Layer)
			{
				for(std::size_t Face = 0, Faces = Texture.faces(); Face < Faces; ++Face)
				{
					std::uint32_t const FaceSize = static_cast<std::uint32_t>(Texture.size(Level));
					std::uint32_t const PaddedSize = std::max(BlockSize, glm::ceilMultiple(FaceSize, static_cast<std::uint32_t>(4)));

					TotalSize += PaddedSize;
				}
			}
		}

		return TotalSize;
	}

}//namespace detail

	inline bool save_ktx(texture const & Texture, std::vector<char> & Memory)
	{
		if(Texture.empty())
			return false;

		gl GL;
		gl::format const & Format = GL.translate(Texture.format());
		target const Target = Texture.target();

		detail::formatInfo const & Desc = detail::get_format_info(Texture.format());

		Memory.resize(detail::compute_ktx_storage_size(Texture) + sizeof(detail::ktxHeader));

		detail::ktxHeader & Header = *reinterpret_cast<detail::ktxHeader*>(&Memory[0]);

		static unsigned char const Identifier[] =
		{
		   0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
		};

		memcpy(Header.Identifier, Identifier, sizeof(Header.Identifier));
		Header.Endianness = 0x04030201;
		Header.GLType = Format.Type;
		Header.GLTypeSize = Format.Type == gl::TYPE_NONE ? 1 : Desc.BlockSize;
		Header.GLFormat = Format.External;
		Header.GLInternalFormat = Format.Internal;
		Header.GLBaseInternalFormat = Format.External;
		Header.PixelWidth = static_cast<std::uint32_t>(Texture.dimensions().x);
		Header.PixelHeight = !is_target_1d(Target) ? static_cast<std::uint32_t>(Texture.dimensions().y) : 0;
		Header.PixelDepth = Target == TARGET_3D ? static_cast<std::uint32_t>(Texture.dimensions().z) : 0;
		Header.NumberOfArrayElements = is_target_array(Target) ? static_cast<std::uint32_t>(Texture.layers()) : 0;
		Header.NumberOfFaces = is_target_cube(Target) ? static_cast<std::uint32_t>(Texture.faces()) : 0;
		Header.NumberOfMipmapLevels = static_cast<std::uint32_t>(Texture.levels());
		Header.BytesOfKeyValueData = 0;

		std::size_t Offset = sizeof(detail::ktxHeader);

		for(std::size_t Level = 0, Levels = Texture.levels(); Level < Levels; ++Level)
		{
			std::uint32_t& ImageSize = *reinterpret_cast<std::uint32_t*>(&Memory[0] + Offset);
			Offset += sizeof(std::uint32_t);

			for(std::size_t Layer = 0, Layers = Texture.layers(); Layer < Layers; ++Layer)
			{
				for(std::size_t Face = 0, Faces = Texture.faces(); Face < Faces; ++Face)
				{
					std::uint32_t const FaceSize = static_cast<std::uint32_t>(Texture.size(Level));

					std::memcpy(&Memory[0] + Offset, Texture.data(Layer, Face, Level), FaceSize);

					std::uint32_t const PaddedSize = glm::ceilMultiple(FaceSize, static_cast<std::uint32_t>(4));

					ImageSize += PaddedSize;
					Offset += PaddedSize;

					assert(Offset <= Memory.size());
				}
			}

			ImageSize = glm::ceilMultiple(ImageSize, static_cast<std::uint32_t>(4));
		}

		return true;
	}

	inline bool save_ktx(texture const & Texture, char const * Filename)
	{
		if(Texture.empty())
			return false;

#if defined(__ANDROID__) || defined(__linux__)
		FILE* File = std::fopen(Filename, "wb");
#else
		FILE* File = 0;
		fopen_s(&File, Filename, "wb");
#endif
		if(0 == File)
			return false;
		std::vector<char> Memory;
		bool const Result = save_ktx(Texture, Memory);

		std::fwrite(&Memory[0], 1, Memory.size(), File);
		std::fclose(File);

		return Result;
	}

	inline bool save_ktx(texture const & Texture, std::string const & Filename)
	{
		return save_ktx(Texture, Filename.c_str());
	}
}//namespace gli
<|endoftext|>


<commit_before>#include "mitkImageCast.h"

#include "mitkAutoCropImageFilter.h"

#include "mitkImageTimeSelector.h"
#include "itkLinearInterpolateImageFunction.h"
#include <itkBinaryMedianImageFilter.h>
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIterator.h>
#include <itkCropImageFilter.h>
#include <mitkImage.h>
#include <vtkLinearTransform.h>

mitk::AutoCropImageFilter::AutoCropImageFilter() : m_BackgroundValue(0), m_MarginFactor(1.0)
{
}

mitk::AutoCropImageFilter::~AutoCropImageFilter()
{
}

void mitk::AutoCropImageFilter::GenerateOutputInformation()
{
	mitk::Image::ConstPointer input  = this->GetInput();
	mitk::Image::Pointer output = this->GetOutput();

	itkDebugMacro(<<"GenerateOutputInformation()");

  int dim=(input->GetDimension()<3?input->GetDimension():3);
	output->Initialize(input->GetPixelType(), dim, input->GetDimensions());

  // initialize geometry
  output->SetGeometry(dynamic_cast<Geometry3D*>(input->GetSlicedGeometry()->Clone().GetPointer()));
  output->SetPropertyList(input->GetPropertyList()->Clone());
}

void mitk::AutoCropImageFilter::GenerateData()
{

  if ( this->GetInput()->GetDimension()==4)
  {
    mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
    timeSelector->SetInput( this->GetInput() );
    timeSelector->SetTimeNr( 0 );
    timeSelector->Update();
    this->Crop3DImage( timeSelector->GetOutput() );
  }
  else if (this->GetInput()->GetDimension() == 3 )
  {
    this->Crop3DImage( this->GetInput() );
  }

}

void mitk::AutoCropImageFilter::Crop3DImage(mitk::ImageToImageFilter::InputImageConstPointer img)
{
  typedef itk::Image<float,3>    ImageType;
  typedef ImageType::Pointer      ImagePointer;

  ImagePointer inputItk = ImageType::New();
  mitk::CastToItkImage( img , inputItk );
  typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
  ConstIteratorType inIt( inputItk,  inputItk->GetLargestPossibleRegion() );
  ImageType::IndexType minima,maxima;
  maxima = inputItk->GetLargestPossibleRegion().GetIndex();
  minima[0] = inputItk->GetLargestPossibleRegion().GetSize()[0];
  minima[1] = inputItk->GetLargestPossibleRegion().GetSize()[1];
  minima[2] = inputItk->GetLargestPossibleRegion().GetSize()[2];

  for ( inIt.GoToBegin(); !inIt.IsAtEnd(); ++inIt)
  {
    float pix_val = inIt.Get();
    if ( fabs(pix_val - m_BackgroundValue) > mitk::eps )
    {
      for (int i=0; i < 3; i++)
      {
        minima[i] = vnl_math_min((int)minima[i],(int)(inIt.GetIndex()[i]));
        maxima[i] = vnl_math_max((int)maxima[i],(int)(inIt.GetIndex()[i]));
      }
    }
  }

  ImageType::RegionType::SizeType regionSize;
  ImageType::RegionType::IndexType regionIndex;

  regionSize[0] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[0] - minima[0]));
  regionSize[1] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[1] - minima[1]));
  regionSize[2] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[2] - minima[2]));
  regionIndex = minima;
  regionIndex[0] -= (regionSize[0] - maxima[0] + minima[0])/2 ;
  regionIndex[1] -= (regionSize[1] - maxima[1] + minima[1])/2 ;
  regionIndex[2] -= (regionSize[2] - maxima[2] + minima[2])/2 ;

  for (int i = 0; i < 3; i++)
  {
    if (regionIndex[i] < 0) regionIndex[i] = 0;
    if (regionIndex[i] + regionSize[i] > inputItk->GetLargestPossibleRegion().GetSize()[i]-1) regionSize[i] = inputItk->GetLargestPossibleRegion().GetSize()[i] - regionIndex[i] - 1;

    // check if there was enough segmentation to do the registration and return otherwise
    if (regionSize[i] < 1) return;
  }

  ImagePointer outputItk = ImageType::New();
  typedef itk::CropImageFilter<ImageType,ImageType> CropFilterType;
  CropFilterType::SizeType lowerBounds,upperBounds;

  lowerBounds[0] = regionIndex[0];
  lowerBounds[1] = regionIndex[1];
  lowerBounds[2] = regionIndex[2];

  upperBounds[0] = inputItk->GetLargestPossibleRegion().GetSize()[0]-regionSize[0]-regionIndex[0];
  upperBounds[1] = inputItk->GetLargestPossibleRegion().GetSize()[1]-regionSize[1]-regionIndex[1];
  upperBounds[2] = inputItk->GetLargestPossibleRegion().GetSize()[2]-regionSize[2]-regionIndex[2];

  CropFilterType::Pointer cropFilter = CropFilterType::New();
  cropFilter->SetLowerBoundaryCropSize( lowerBounds );
  cropFilter->SetUpperBoundaryCropSize( upperBounds );
  cropFilter->SetInput( inputItk );
  cropFilter->Update();
  outputItk = cropFilter->GetOutput();

  float origin[3];
  origin[0] = regionIndex[0];
  origin[1] = regionIndex[1];
  origin[2] = regionIndex[2];
  outputItk->SetOrigin( origin );
  outputItk->SetSpacing( inputItk->GetSpacing() );

  mitk::Image::Pointer output = this->GetOutput();
  mitk::CastToMitkImage(outputItk, output);
  output->SetPropertyList(this->GetInput()->GetPropertyList()->Clone());
  output->SetGeometry( dynamic_cast<Geometry3D*>(this->GetInput()->GetSlicedGeometry()->Clone().GetPointer()) );
  Vector3D originVector;
  vtk2itk(origin, originVector);
  output->GetGeometry()->Translate(originVector);
  this->SetOutput(output);

}

void mitk::AutoCropImageFilter::GenerateInputRequestedRegion()
{
  //todo
}
<commit_msg>ENH: ...<commit_after>#include "mitkAutoCropImageFilter.h"

#include "mitkImageCast.h"
#include "mitkImageTimeSelector.h"
#include "itkLinearInterpolateImageFunction.h"
#include <itkBinaryMedianImageFilter.h>
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIterator.h>
#include <itkCropImageFilter.h>
#include <mitkImage.h>
#include <vtkLinearTransform.h>

mitk::AutoCropImageFilter::AutoCropImageFilter() : m_BackgroundValue(0), m_MarginFactor(1.0)
{
}

mitk::AutoCropImageFilter::~AutoCropImageFilter()
{
}

void mitk::AutoCropImageFilter::GenerateOutputInformation()
{
	mitk::Image::ConstPointer input  = this->GetInput();
	mitk::Image::Pointer output = this->GetOutput();

	itkDebugMacro(<<"GenerateOutputInformation()");

  int dim=(input->GetDimension()<3?input->GetDimension():3);
	output->Initialize(input->GetPixelType(), dim, input->GetDimensions());

  // initialize geometry
  output->SetGeometry(dynamic_cast<Geometry3D*>(input->GetSlicedGeometry()->Clone().GetPointer()));
  output->SetPropertyList(input->GetPropertyList()->Clone());
}

void mitk::AutoCropImageFilter::GenerateData()
{

  if ( this->GetInput()->GetDimension()==4)
  {
    mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
    timeSelector->SetInput( this->GetInput() );
    timeSelector->SetTimeNr( 0 );
    timeSelector->Update();
    this->Crop3DImage( timeSelector->GetOutput() );
  }
  else if (this->GetInput()->GetDimension() == 3 )
  {
    this->Crop3DImage( this->GetInput() );
  }

}

void mitk::AutoCropImageFilter::Crop3DImage(mitk::ImageToImageFilter::InputImageConstPointer img)
{
  typedef itk::Image<float,3>    ImageType;
  typedef ImageType::Pointer      ImagePointer;

  ImagePointer inputItk = ImageType::New();
  mitk::CastToItkImage( img , inputItk );
  typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
  ConstIteratorType inIt( inputItk,  inputItk->GetLargestPossibleRegion() );
  ImageType::IndexType minima,maxima;
  maxima = inputItk->GetLargestPossibleRegion().GetIndex();
  minima[0] = inputItk->GetLargestPossibleRegion().GetSize()[0];
  minima[1] = inputItk->GetLargestPossibleRegion().GetSize()[1];
  minima[2] = inputItk->GetLargestPossibleRegion().GetSize()[2];

  for ( inIt.GoToBegin(); !inIt.IsAtEnd(); ++inIt)
  {
    float pix_val = inIt.Get();
    if ( fabs(pix_val - m_BackgroundValue) > mitk::eps )
    {
      for (int i=0; i < 3; i++)
      {
        minima[i] = vnl_math_min((int)minima[i],(int)(inIt.GetIndex()[i]));
        maxima[i] = vnl_math_max((int)maxima[i],(int)(inIt.GetIndex()[i]));
      }
    }
  }

  ImageType::RegionType::SizeType regionSize;
  ImageType::RegionType::IndexType regionIndex;

  regionSize[0] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[0] - minima[0]));
  regionSize[1] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[1] - minima[1]));
  regionSize[2] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[2] - minima[2]));
  regionIndex = minima;
  regionIndex[0] -= (regionSize[0] - maxima[0] + minima[0])/2 ;
  regionIndex[1] -= (regionSize[1] - maxima[1] + minima[1])/2 ;
  regionIndex[2] -= (regionSize[2] - maxima[2] + minima[2])/2 ;

  for (int i = 0; i < 3; i++)
  {
    if (regionIndex[i] < 0) regionIndex[i] = 0;
    if (regionIndex[i] + regionSize[i] > inputItk->GetLargestPossibleRegion().GetSize()[i]-1) regionSize[i] = inputItk->GetLargestPossibleRegion().GetSize()[i] - regionIndex[i] - 1;

    // check if there was enough segmentation to do the registration and return otherwise
    if (regionSize[i] < 1) return;
  }

  ImagePointer outputItk = ImageType::New();
  typedef itk::CropImageFilter<ImageType,ImageType> CropFilterType;
  CropFilterType::SizeType lowerBounds,upperBounds;

  lowerBounds[0] = regionIndex[0];
  lowerBounds[1] = regionIndex[1];
  lowerBounds[2] = regionIndex[2];

  upperBounds[0] = inputItk->GetLargestPossibleRegion().GetSize()[0]-regionSize[0]-regionIndex[0];
  upperBounds[1] = inputItk->GetLargestPossibleRegion().GetSize()[1]-regionSize[1]-regionIndex[1];
  upperBounds[2] = inputItk->GetLargestPossibleRegion().GetSize()[2]-regionSize[2]-regionIndex[2];

  CropFilterType::Pointer cropFilter = CropFilterType::New();
  cropFilter->SetLowerBoundaryCropSize( lowerBounds );
  cropFilter->SetUpperBoundaryCropSize( upperBounds );
  cropFilter->SetInput( inputItk );
  cropFilter->Update();
  outputItk = cropFilter->GetOutput();

  float origin[3];
  origin[0] = regionIndex[0];
  origin[1] = regionIndex[1];
  origin[2] = regionIndex[2];
  outputItk->SetOrigin( origin );
  outputItk->SetSpacing( inputItk->GetSpacing() );

  mitk::Image::Pointer output = this->GetOutput();
  mitk::CastToMitkImage(outputItk, output);
  output->SetPropertyList(this->GetInput()->GetPropertyList()->Clone());
  output->SetGeometry( dynamic_cast<Geometry3D*>(this->GetInput()->GetSlicedGeometry()->Clone().GetPointer()) );
  Vector3D originVector;
  vtk2itk(origin, originVector);
  output->GetGeometry()->Translate(originVector);
  this->SetOutput(output);

}

void mitk::AutoCropImageFilter::GenerateInputRequestedRegion()
{
  //todo
}
<|endoftext|>


<commit_before>#include "config.h"
#include "except.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <fnmatch.h>

using namespace std;
using namespace Simulator;

template <>
string Config::lookupValue<string>(const string& name, const string& def, bool fail_if_not_found)
{
    string val;
    bool found = lookup(name, val, def, !fail_if_not_found);
    if (!found)
    {
        if (fail_if_not_found)
            throw exceptf<SimulationException>("No configuration key matches: %s", name.c_str());
        else
            return def;
    }
    return val;
}

template<>
double Config::convertToNumber<double>(const string& name, const string& value)
{
    const char *start = value.c_str();
    char *end;

    double val = strtod(start, &end);
    if (*end != '\0')
    {
        throw exceptf<SimulationException>("Configuration value for %s is not a floating-point number: %s", name.c_str(), start);
    }
    return val;
}

template<>
float Config::convertToNumber<float>(const string& name, const string& value)
{
    return convertToNumber<double>(name, value);
}

template <>
bool Config::convertToNumber<bool>(const string& name, const string& value)
{
    string val = value;
    transform(val.begin(), val.end(), val.begin(), ::toupper);

    // Check for the boolean values
    if (val == "TRUE" || val == "YES") return true;
    if (val == "FALSE" || val == "NO") return false;

    // Otherwise, try to interpret as an integer
    int i = convertToNumber<int>(name, val);
    return i != 0;
}

bool Config::lookup(const string& name_, string& result, const string &def, bool allow_default)
{
    string name(name_);

    string pat;
    // transform(name.begin(), name.end(), name.begin(), ::toupper);

    ConfigCache::const_iterator p = m_cache.find(name);
    if (p != m_cache.end())
    {
        result = p->second.first;
        return true;
    }

    bool found = false;
    for (ConfigMap::const_iterator p = m_overrides.begin(); p != m_overrides.end(); ++p)
    {
        pat = p->first;
        if (FNM_NOMATCH != fnmatch(pat.c_str(), name.c_str(), FNM_CASEFOLD))
        {
            // Return the overriden value
            result = p->second;
            found = true;
            break;
        }
    }

    if (!found)
    {
        for (ConfigMap::const_iterator p = m_data.begin(); p != m_data.end(); ++p)
        {
            pat = p->first;
            if (FNM_NOMATCH != fnmatch(pat.c_str(), name.c_str(), FNM_CASEFOLD))
            {
                // Return the configuration value
                result = p->second;
                found = true;
                break;
            }
        }
    }
    if (!found && allow_default)
    {
        pat = "default";
        result = def;
        found = true;
    }
    if (found)
    {
        m_cache[name] = make_pair(result, pat);
    }
    return found;
}

void Config::dumpConfiguration(ostream& os, const string& cf, bool raw) const
{
    if (raw)
    {
        os << "MGSimVersion=" << PACKAGE_VERSION << endl;
        for (size_t i = 0; i < m_overrides.size(); ++i)
            os << m_overrides[i].first << "=" << m_overrides[i].second << endl;
        for (ConfigCache::const_iterator p = m_cache.begin(); p != m_cache.end(); ++p)
            os << p->first << "=" << p->second.first << endl;
    }
    else
    {
        os << "### begin simulator configuration" << endl
           << "# overrides from command line:" << endl;
        for (size_t i = 0; i < m_overrides.size(); ++i)
            os << "# -o " << m_overrides[i].first << " = " << m_overrides[i].second << endl;
        os << "# configuration file: " << cf << endl;
        for (size_t i = 0; i < m_data.size(); ++i)
            os << "# -o " << m_data[i].first << " = " << m_data[i].second << endl;
        os << "# lookup matches:" << endl;
        for (ConfigCache::const_iterator p = m_cache.begin(); p != m_cache.end(); ++p)
            os << "# " << p->first << " = " << p->second.first << " (matches " << p->second.second << ')' << endl;
        os << "### end simulator configuration" << endl;
    }
}

vector<string> Config::getWordList(const string& name)
{
    vector<string> vals;
    istringstream stream(getValue<string>(name));
    string token = "";
    while (getline(stream, token, ','))
    {
        vals.push_back(token);
    }
    return vals;
}

vector<string> Config::getWordList(const Object& obj, const string& name)
{
    return getWordList(obj.GetFQN() + '.' + name);
}

Config::Config(const string& filename, const ConfigMap& overrides)
    : m_overrides(overrides)
{
    enum State
    {
        STATE_BEGIN,
        STATE_COMMENT,
        STATE_NAME,
        STATE_EQUALS,
        STATE_VALUE,
    };

    State state = STATE_BEGIN;
    string name;
    string value;

    ifstream input(filename.c_str());
    if (!input.is_open())
    {
        throw FileNotFoundException(filename);
    }

    while (!input.eof())
    {
        int c = input.get();
        if (input.fail())
        {
            break;
        }

        if (state == STATE_BEGIN && !isspace(c))
        {
            if (c == '#' || c == ';')
            {
                state = STATE_COMMENT;
            }
            else if (isalpha(c) || c == '_' || c == '*' || c == '.')
            {
                state = STATE_NAME;
                name = (char)c;
            }
        }
        else if (state == STATE_COMMENT)
        {
            if (c == '\n')
            {
                state = STATE_BEGIN;
            }
        }
        else if (state == STATE_NAME)
        {
            if (isalnum(c) || c == '_' || c == '*' || c == '.') name += (char)c;
            else
            {
                // transform(name.begin(), name.end(), name.begin(), ::toupper);
                state = STATE_EQUALS;
            }
        }

        if (state == STATE_EQUALS && !isspace(c))
        {
            if (c == '=') state = STATE_VALUE;
        }
        else if (state == STATE_VALUE)
        {
            if (isspace(c) && value.empty())
            {
            }
            else if (c == '\r' || c == '\n' || c == '#')
            {
                if (!value.empty())
                {
                    // Strip off all the spaces from the end
                    string::size_type pos = value.find_last_not_of("\r\n\t\v\f ");
                    if (pos != string::npos) {
                        value.erase(pos + 1);
                    }

                    m_data.push_back(make_pair(name,value));
                    name.clear();
                    value.clear();
                }
                state = (c == '#') ? STATE_COMMENT : STATE_BEGIN;
            }
            else
            {
                value = value + (char)c;
            }
        }
    }

    if (value != "")
    {
        m_data.push_back(make_pair(name,value));
    }
}

<commit_msg>[mgsim-refactor] Allow (and strip) spaces in string lists in the configuration.<commit_after>#include "config.h"
#include "except.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <fnmatch.h>
#include <cctype>

using namespace std;
using namespace Simulator;

template <>
string Config::lookupValue<string>(const string& name, const string& def, bool fail_if_not_found)
{
    string val;
    bool found = lookup(name, val, def, !fail_if_not_found);
    if (!found)
    {
        if (fail_if_not_found)
            throw exceptf<SimulationException>("No configuration key matches: %s", name.c_str());
        else
            return def;
    }
    return val;
}

template<>
double Config::convertToNumber<double>(const string& name, const string& value)
{
    const char *start = value.c_str();
    char *end;

    double val = strtod(start, &end);
    if (*end != '\0')
    {
        throw exceptf<SimulationException>("Configuration value for %s is not a floating-point number: %s", name.c_str(), start);
    }
    return val;
}

template<>
float Config::convertToNumber<float>(const string& name, const string& value)
{
    return convertToNumber<double>(name, value);
}

template <>
bool Config::convertToNumber<bool>(const string& name, const string& value)
{
    string val = value;
    transform(val.begin(), val.end(), val.begin(), ::toupper);

    // Check for the boolean values
    if (val == "TRUE" || val == "YES") return true;
    if (val == "FALSE" || val == "NO") return false;

    // Otherwise, try to interpret as an integer
    int i = convertToNumber<int>(name, val);
    return i != 0;
}

bool Config::lookup(const string& name_, string& result, const string &def, bool allow_default)
{
    string name(name_);

    string pat;
    // transform(name.begin(), name.end(), name.begin(), ::toupper);

    ConfigCache::const_iterator p = m_cache.find(name);
    if (p != m_cache.end())
    {
        result = p->second.first;
        return true;
    }

    bool found = false;
    for (ConfigMap::const_iterator p = m_overrides.begin(); p != m_overrides.end(); ++p)
    {
        pat = p->first;
        if (FNM_NOMATCH != fnmatch(pat.c_str(), name.c_str(), FNM_CASEFOLD))
        {
            // Return the overriden value
            result = p->second;
            found = true;
            break;
        }
    }

    if (!found)
    {
        for (ConfigMap::const_iterator p = m_data.begin(); p != m_data.end(); ++p)
        {
            pat = p->first;
            if (FNM_NOMATCH != fnmatch(pat.c_str(), name.c_str(), FNM_CASEFOLD))
            {
                // Return the configuration value
                result = p->second;
                found = true;
                break;
            }
        }
    }
    if (!found && allow_default)
    {
        pat = "default";
        result = def;
        found = true;
    }
    if (found)
    {
        m_cache[name] = make_pair(result, pat);
    }
    return found;
}

void Config::dumpConfiguration(ostream& os, const string& cf, bool raw) const
{
    if (raw)
    {
        os << "MGSimVersion=" << PACKAGE_VERSION << endl;
        for (size_t i = 0; i < m_overrides.size(); ++i)
            os << m_overrides[i].first << "=" << m_overrides[i].second << endl;
        for (ConfigCache::const_iterator p = m_cache.begin(); p != m_cache.end(); ++p)
            os << p->first << "=" << p->second.first << endl;
    }
    else
    {
        os << "### begin simulator configuration" << endl
           << "# overrides from command line:" << endl;
        for (size_t i = 0; i < m_overrides.size(); ++i)
            os << "# -o " << m_overrides[i].first << " = " << m_overrides[i].second << endl;
        os << "# configuration file: " << cf << endl;
        for (size_t i = 0; i < m_data.size(); ++i)
            os << "# -o " << m_data[i].first << " = " << m_data[i].second << endl;
        os << "# lookup matches:" << endl;
        for (ConfigCache::const_iterator p = m_cache.begin(); p != m_cache.end(); ++p)
            os << "# " << p->first << " = " << p->second.first << " (matches " << p->second.second << ')' << endl;
        os << "### end simulator configuration" << endl;
    }
}

vector<string> Config::getWordList(const string& name)
{
    vector<string> vals;
    istringstream stream(getValue<string>(name));
    string token = "";
    while (getline(stream, token, ','))
    {
        token.erase(remove(token.begin(), token.end(), ' '), token.end());
        vals.push_back(token);
    }
    return vals;
}

vector<string> Config::getWordList(const Object& obj, const string& name)
{
    return getWordList(obj.GetFQN() + '.' + name);
}

Config::Config(const string& filename, const ConfigMap& overrides)
    : m_overrides(overrides)
{
    enum State
    {
        STATE_BEGIN,
        STATE_COMMENT,
        STATE_NAME,
        STATE_EQUALS,
        STATE_VALUE,
    };

    State state = STATE_BEGIN;
    string name;
    string value;

    ifstream input(filename.c_str());
    if (!input.is_open())
    {
        throw FileNotFoundException(filename);
    }

    while (!input.eof())
    {
        int c = input.get();
        if (input.fail())
        {
            break;
        }

        if (state == STATE_BEGIN && !isspace(c))
        {
            if (c == '#' || c == ';')
            {
                state = STATE_COMMENT;
            }
            else if (isalpha(c) || c == '_' || c == '*' || c == '.')
            {
                state = STATE_NAME;
                name = (char)c;
            }
        }
        else if (state == STATE_COMMENT)
        {
            if (c == '\n')
            {
                state = STATE_BEGIN;
            }
        }
        else if (state == STATE_NAME)
        {
            if (isalnum(c) || c == '_' || c == '*' || c == '.') name += (char)c;
            else
            {
                // transform(name.begin(), name.end(), name.begin(), ::toupper);
                state = STATE_EQUALS;
            }
        }

        if (state == STATE_EQUALS && !isspace(c))
        {
            if (c == '=') state = STATE_VALUE;
        }
        else if (state == STATE_VALUE)
        {
            if (isspace(c) && value.empty())
            {
            }
            else if (c == '\r' || c == '\n' || c == '#')
            {
                if (!value.empty())
                {
                    // Strip off all the spaces from the end
                    string::size_type pos = value.find_last_not_of("\r\n\t\v\f ");
                    if (pos != string::npos) {
                        value.erase(pos + 1);
                    }

                    m_data.push_back(make_pair(name,value));
                    name.clear();
                    value.clear();
                }
                state = (c == '#') ? STATE_COMMENT : STATE_BEGIN;
            }
            else
            {
                value = value + (char)c;
            }
        }
    }

    if (value != "")
    {
        m_data.push_back(make_pair(name,value));
    }
}

<|endoftext|>


<commit_before>/*
 * Copyright 2012 BrewPi/Elco Jacobs.
 *
 * This file is part of BrewPi.
 *
 * BrewPi 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 3 of the License, or
 * (at your option) any later version.
 *
 * BrewPi 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 BrewPi.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * This Atmel Studio 6 project automatically includes all needed Arduino source files, you just have to point it to the right directories.
 * To compile this project on your computer, go the the project properties and change the following options:
 * AVR/GNU C++ Compiler --> Directories.
 * Change the two directories to point to your local Arduino installation. For the second directory, choose the Arduino variant that you are using.
 *		D:\arduino-1.0.1\hardware\arduino\cores\arduino
		D:\arduino-1.0.1\hardware\arduino\variants\leonardo
 * 'ArduinoFunctions.cpp' includes all the source files from Arduino that are used. You might have to edit it if you are not using a Leonardo.
 * That is all that is needed! No hassle with makefiles and compiling libraries.
 */

#include <arduino.h>

#include "Display.h"
#include "TempControl.h"
#include "PiLink.h"
#include "Menu.h"
#include "pins.h"
#include "RotaryEncoder.h"

// global class opbjects static and defined in class cpp and h files

void setup(void);
void loop (void);

void setup()
{

	Serial.begin(57600);

	pinMode(coolingPin, OUTPUT);
	pinMode(heatingPin, OUTPUT);

	#if(USE_INTERNAL_PULL_UP_RESISTORS)
		pinMode(doorPin, INPUT_PULLUP);
	#else
		pinMode(doorPin, INPUT);
	#endif

	tempControl.loadSettingsAndConstants(); //read previous settings from EEPROM

	delay(2000); // give LCD time to power up

	tempControl.init();

	display.init();
	display.printStationaryText();
	display.printState();

	tempControl.updatePID();
	tempControl.updateState();

	rotaryEncoder.init();

	piLink.printFridgeAnnotation(PSTR("Arduino restarted!"));
}

void main() __attribute__ ((noreturn)); // tell the compiler main doesn't return.

void main(void)
{
	init();

	#if defined(USBCON)
	USBDevice.attach();
	#endif

	setup();

	for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}
}

void loop(void)
{
	static unsigned long lastUpdate;
	if(millis() - lastUpdate > 1000){ //update settings every second
		lastUpdate=millis();

		tempControl.updateTemperatures();
		tempControl.detectPeaks();
		tempControl.updatePID();
		tempControl.updateState();
		tempControl.updateOutputs();

		display.printState();
		display.printAllTemperatures();
		display.printMode();
	}
	if(rotaryEncoder.pushed()){
		rotaryEncoder.resetPushed();
		menu.pickSettingToChange();
	}

	//listen for incoming serial connections while waiting top update
	piLink.receive();
}

/* catch bad interrupts here when debugging
ISR(BADISR_vect){
	while(1){
		;
	}
}
*/
<commit_msg>Updated instructions to compile the project<commit_after>/*
 * Copyright 2012 BrewPi/Elco Jacobs.
 *
 * This file is part of BrewPi.
 *
 * BrewPi 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 3 of the License, or
 * (at your option) any later version.
 *
 * BrewPi 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 BrewPi.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * This Atmel Studio 6 project automatically includes all needed Arduino source files, you just have to point it to the right directories.
 * To compile this project on your computer, you will have to set an environment variable to find your local Arduino installation.
 * Set the variable ARDUINO_HOME to point to your local Arduino path, without trailing slash, e.g. 'D:\arduino-1.01'. Instructions on the wiki here:
 * http://wiki.brewpi.com/index.php/Setting_up_the_brewpi-avr_Project
 * 'ArduinoFunctions.cpp' includes all the source files from Arduino that are used. You might have to edit it if you are not using a Leonardo.
 * That is all that is needed! No hassle with makefiles and compiling libraries.
 */

#include <arduino.h>

#include "Display.h"
#include "TempControl.h"
#include "PiLink.h"
#include "Menu.h"
#include "pins.h"
#include "RotaryEncoder.h"

// global class opbjects static and defined in class cpp and h files

void setup(void);
void loop (void);

void setup()
{

	Serial.begin(57600);

	pinMode(coolingPin, OUTPUT);
	pinMode(heatingPin, OUTPUT);

	#if(USE_INTERNAL_PULL_UP_RESISTORS)
		pinMode(doorPin, INPUT_PULLUP);
	#else
		pinMode(doorPin, INPUT);
	#endif

	tempControl.loadSettingsAndConstants(); //read previous settings from EEPROM

	delay(2000); // give LCD time to power up

	tempControl.init();

	display.init();
	display.printStationaryText();
	display.printState();

	tempControl.updatePID();
	tempControl.updateState();

	rotaryEncoder.init();

	piLink.printFridgeAnnotation(PSTR("Arduino restarted!"));
}

void main() __attribute__ ((noreturn)); // tell the compiler main doesn't return.

void main(void)
{
	init();

	#if defined(USBCON)
	USBDevice.attach();
	#endif

	setup();

	for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}
}

void loop(void)
{
	static unsigned long lastUpdate;
	if(millis() - lastUpdate > 1000){ //update settings every second
		lastUpdate=millis();

		tempControl.updateTemperatures();
		tempControl.detectPeaks();
		tempControl.updatePID();
		tempControl.updateState();
		tempControl.updateOutputs();

		display.printState();
		display.printAllTemperatures();
		display.printMode();
	}
	if(rotaryEncoder.pushed()){
		rotaryEncoder.resetPushed();
		menu.pickSettingToChange();
	}

	//listen for incoming serial connections while waiting top update
	piLink.receive();
}

/* catch bad interrupts here when debugging
ISR(BADISR_vect){
	while(1){
		;
	}
}
*/
<|endoftext|>


<commit_before>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP

#include <cassert>

#include <atomic>

#include <memory>

#include <utility>

#include <type_traits>

namespace generic
{

namespace detail
{
  using counter_type = unsigned;

  using atomic_type = ::std::atomic<counter_type>;

  template <typename T>
  using deleter_type = void (*)(T*);

  template <typename U>
  struct ref_type
  {
    using type = U&;
  };

  template <>
  struct ref_type<void>
  {
    using type = void;
  };
}

template <typename T>
struct light_ptr
{
  template <typename U, typename V>
  struct deletion_type
  {
    using type = V;
  };

  template <typename U, typename V>
  struct deletion_type<U[], V>
  {
    using type = V[];
  };

  template <typename U, typename V, ::std::size_t N>
  struct deletion_type<U[N], V>
  {
    using type = V[];
  };

  template <typename U>
  struct is_array_type : ::std::false_type { };

  template <typename U>
  struct is_array_type<U[]> : ::std::true_type { };

  template <typename U, ::std::size_t N>
  struct is_array_type<U[N]> : ::std::true_type { };

  template <typename U>
  struct remove_array
  {
    using type = U;
  };

  template <typename U>
  struct remove_array<U[]>
  {
    using type = U;
  };

  template <typename U, ::std::size_t N>
  struct remove_array<U[N]>
  {
    using type = U;
  };

  using element_type = typename remove_array<T>::type;

  using deleter_type = detail::deleter_type<element_type>;

  struct counter_base
  {
    using invoker_type = void (*)(counter_base*, element_type*);

    explicit counter_base(detail::counter_type c,
      invoker_type invoker) noexcept :
      counter_(c),
      invoker_(invoker)
    {
    }

    template <typename U>
    typename ::std::enable_if<!::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        typedef char type_must_be_complete[sizeof(U) ? 1 : -1];
        (void)sizeof(type_must_be_complete);
        invoker_(this, ptr);
      }
      // else do nothing
    }

    template <typename U>
    typename ::std::enable_if<::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        invoker_(this, ptr);
      }
      // else do nothing
    }

    void inc_ref() noexcept
    {
      //assert(counter_ptr);
      counter_.fetch_add(detail::counter_type(1),
        ::std::memory_order_relaxed);
    }

    detail::atomic_type counter_{};

    invoker_type invoker_;
  };

  template <typename U>
  struct counter : counter_base
  {
    explicit counter(detail::counter_type const c, U&& d) :
      counter_base(c, invoker),
      d_(::std::forward<U>(d))
    {
    }

  private:
    static void invoker(counter_base* const ptr, element_type* e)
    {
      auto const c(static_cast<counter<U>*>(ptr));

      typename ::std::decay<U>::type const d(::std::move(c->d_));

      delete c;

      d(e);
    }

  private:
    typename ::std::decay<U>::type d_;
  };

private:
  template <typename U> friend struct ::std::hash;

  counter_base* counter_{};

  element_type* ptr_{};

public:
  light_ptr() = default;

  template <typename U>
  explicit light_ptr(U* p)
  {
    reset(p);
  }

  template <typename U, typename D>
  explicit light_ptr(U* p, D&& d)
  {
    reset(p, ::std::forward<D>(d));
  }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }

  ~light_ptr()
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing
  }

  light_ptr& operator=(light_ptr const& rhs)
  {
    if (*this != rhs)
    {
      if (counter_)
      {
        counter_->dec_ref(ptr_);
      }
      // else do nothing

      if ((counter_ = rhs.counter_))
      {
        counter_->inc_ref();
      }
      // else do nothing

      ptr_ = rhs.ptr_;
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ = rhs.counter_;
    rhs.counter_ = nullptr;

    ptr_ = rhs.ptr_;
    rhs.ptr_ = nullptr;

    return *this;
  }

  light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }

  bool operator<(light_ptr const& rhs) const noexcept
  {
    return counter_ < rhs.counter_;
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ == rhs.counter_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; }

  bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; }

  explicit operator bool() const noexcept { return ptr_; }

  typename detail::ref_type<T>::type
  operator*() const noexcept
  {
    return *reinterpret_cast<T*>(ptr_);
  }

  T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); }

  template <typename U = T, typename =
    typename ::std::enable_if<is_array_type<U>{}>::type>
  typename detail::ref_type<element_type>::type operator[](
    ::std::size_t const i) const noexcept
  {
    return ptr_[i];
  }

  element_type* get() const noexcept { return ptr_; }

  void reset() { reset(nullptr); }

  void reset(::std::nullptr_t const)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);

      counter_ = {};
    }
    // else do nothing

    ptr_ = {};
  }

  template <typename U>
  void reset(U* const p)
  {
    reset(p, [](element_type* const p) {
      ::std::default_delete<typename deletion_type<T, U>::type>()(
        static_cast<U*>(p));
    });
  }

  template <typename U, typename D>
  void reset(U* const p, D&& d)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing

    counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d));

    ptr_ = p;
  }

  void swap(light_ptr& other) noexcept
  {
    ::std::swap(counter_, other.counter_);
    ::std::swap(ptr_, other.ptr_);
  }

  bool unique() const noexcept
  {
    return detail::counter_type(1) == use_count();
  }

  detail::counter_type use_count() const noexcept
  {
    return counter_ ?
      counter_->counter_.load(::std::memory_order_relaxed) :
      detail::counter_type{};
  }
};

template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
  return light_ptr<T>(new T(::std::forward<Args>(args)...));
}

}

namespace std
{
  template <typename T>
  struct hash<::generic::light_ptr<T> >
  {
    size_t operator()(::generic::light_ptr<T> const& l) const noexcept
    {
      return hash<typename ::generic::light_ptr<T>::element_type*>()(
        l.counter_);
    }
  };
}

#endif // LIGHTPTR_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP

#include <cassert>

#include <atomic>

#include <memory>

#include <utility>

#include <type_traits>

namespace generic
{

namespace detail
{
  using counter_type = unsigned;

  using atomic_type = ::std::atomic<counter_type>;

  template <typename T>
  using deleter_type = void (*)(T*);

  template <typename U>
  struct ref_type
  {
    using type = U&;
  };

  template <>
  struct ref_type<void>
  {
    using type = void;
  };
}

template <typename T>
struct light_ptr
{
  template <typename U, typename V>
  struct deletion_type
  {
    using type = V;
  };

  template <typename U, typename V>
  struct deletion_type<U[], V>
  {
    using type = V[];
  };

  template <typename U, typename V, ::std::size_t N>
  struct deletion_type<U[N], V>
  {
    using type = V[];
  };

  template <typename U>
  struct is_array_type : ::std::false_type { };

  template <typename U>
  struct is_array_type<U[]> : ::std::true_type { };

  template <typename U, ::std::size_t N>
  struct is_array_type<U[N]> : ::std::true_type { };

  template <typename U>
  struct remove_array
  {
    using type = U;
  };

  template <typename U>
  struct remove_array<U[]>
  {
    using type = U;
  };

  template <typename U, ::std::size_t N>
  struct remove_array<U[N]>
  {
    using type = U;
  };

  using element_type = typename remove_array<T>::type;

  using deleter_type = detail::deleter_type<element_type>;

  struct counter_base
  {
    using invoker_type = void (*)(counter_base*, element_type*);

    explicit counter_base(detail::counter_type c,
      invoker_type invoker) noexcept :
      counter_(c),
      invoker_(invoker)
    {
    }

    template <typename U>
    typename ::std::enable_if<!::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        typedef char type_must_be_complete[sizeof(U) ? 1 : -1];
        (void)sizeof(type_must_be_complete);
        invoker_(this, ptr);
      }
      // else do nothing
    }

    template <typename U>
    typename ::std::enable_if<::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        invoker_(this, ptr);
      }
      // else do nothing
    }

    void inc_ref() noexcept
    {
      //assert(counter_ptr);
      counter_.fetch_add(detail::counter_type(1),
        ::std::memory_order_relaxed);
    }

    detail::atomic_type counter_{};

    invoker_type invoker_;
  };

  template <typename U>
  struct counter : counter_base
  {
    explicit counter(detail::counter_type const c, U&& d) :
      counter_base(c, invoker),
      d_(::std::forward<U>(d))
    {
    }

  private:
    static void invoker(counter_base* const ptr, element_type* const e)
    {
      auto const c(static_cast<counter<U>*>(ptr));

      typename ::std::decay<U>::type const d(::std::move(c->d_));

      delete c;

      d(e);
    }

  private:
    typename ::std::decay<U>::type d_;
  };

private:
  template <typename U> friend struct ::std::hash;

  counter_base* counter_{};

  element_type* ptr_{};

public:
  light_ptr() = default;

  template <typename U>
  explicit light_ptr(U* p)
  {
    reset(p);
  }

  template <typename U, typename D>
  explicit light_ptr(U* p, D&& d)
  {
    reset(p, ::std::forward<D>(d));
  }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }

  ~light_ptr()
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing
  }

  light_ptr& operator=(light_ptr const& rhs)
  {
    if (*this != rhs)
    {
      if (counter_)
      {
        counter_->dec_ref(ptr_);
      }
      // else do nothing

      if ((counter_ = rhs.counter_))
      {
        counter_->inc_ref();
      }
      // else do nothing

      ptr_ = rhs.ptr_;
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ = rhs.counter_;
    rhs.counter_ = nullptr;

    ptr_ = rhs.ptr_;
    rhs.ptr_ = nullptr;

    return *this;
  }

  light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }

  bool operator<(light_ptr const& rhs) const noexcept
  {
    return counter_ < rhs.counter_;
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ == rhs.counter_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; }

  bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; }

  explicit operator bool() const noexcept { return ptr_; }

  typename detail::ref_type<T>::type
  operator*() const noexcept
  {
    return *reinterpret_cast<T*>(ptr_);
  }

  T* operator->() const noexcept { return reinterpret_cast<T*>(ptr_); }

  template <typename U = T, typename =
    typename ::std::enable_if<is_array_type<U>{}>::type>
  typename detail::ref_type<element_type>::type operator[](
    ::std::size_t const i) const noexcept
  {
    return ptr_[i];
  }

  element_type* get() const noexcept { return ptr_; }

  void reset() { reset(nullptr); }

  void reset(::std::nullptr_t const)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);

      counter_ = {};
    }
    // else do nothing

    ptr_ = {};
  }

  template <typename U>
  void reset(U* const p)
  {
    reset(p, [](element_type* const p) {
      ::std::default_delete<typename deletion_type<T, U>::type>()(
        static_cast<U*>(p));
    });
  }

  template <typename U, typename D>
  void reset(U* const p, D&& d)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing

    counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d));

    ptr_ = p;
  }

  void swap(light_ptr& other) noexcept
  {
    ::std::swap(counter_, other.counter_);
    ::std::swap(ptr_, other.ptr_);
  }

  bool unique() const noexcept
  {
    return detail::counter_type(1) == use_count();
  }

  detail::counter_type use_count() const noexcept
  {
    return counter_ ?
      counter_->counter_.load(::std::memory_order_relaxed) :
      detail::counter_type{};
  }
};

template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
  return light_ptr<T>(new T(::std::forward<Args>(args)...));
}

}

namespace std
{
  template <typename T>
  struct hash<::generic::light_ptr<T> >
  {
    size_t operator()(::generic::light_ptr<T> const& l) const noexcept
    {
      return hash<typename ::generic::light_ptr<T>::element_type*>()(
        l.counter_);
    }
  };
}

#endif // LIGHTPTR_HPP
<|endoftext|>


<commit_before>#include <stdexcept>
#include <iostream>

int opt_parse(int argc, char** argv) {
    // implement option parsing and call the real main
    // with everything ready to use
    return 0;
}

int main(int argc, char** argv) {
    try {
        return opt_parse(argc, argv);
    } catch (std::exception& e) {
        std::cerr << "Standard exception. What: " << e.what() << "\n";
        return 10;
    } catch (...) {
        std::cerr << "Unknown exception.\n";
        return 11;
    }
}
<commit_msg>Add sync_with_stdio(false), tour c++ pg132<commit_after>#include <stdexcept>
#include <iostream>

int opt_parse(int argc, char** argv) {
    // implement option parsing and call the real main
    // with everything ready to use
    return 0;
}

int main(int argc, char** argv) {
    //unless one needs C-style I/O
    std::ios_base::sync_with_stdio(false);
    try {
        return opt_parse(argc, argv);
    } catch (std::exception& e) {
        std::cerr << "Standard exception. What: " << e.what() << "\n";
        return 10;
    } catch (...) {
        std::cerr << "Unknown exception.\n";
        return 11;
    }
}
<|endoftext|>


<commit_before>#include "Map.h"
#include "Constants.h"

using namespace std;
/*
A Map represents the static parts of the map.
*/

/**
 * Creates a Map from a vector of strings. Width and height are set but has
 * nothing to do with map initialization.
 */
Map::Map(vector<string> stringmap, int width, int height) {
    for(unsigned int i = 0;i < stringmap.size();i++){
        vector<char> line;
        for(unsigned int j = 0;j < stringmap[i].size();j++){
            line.push_back(stringmap[i][j]); //not sure about order of i and j - but want first coordinate to be column.
        }
        map.push_back(line);
    }

	this->width = width;
	this->height = height;
}

Map::~Map(void) {
}

/**
 * Takes a position on the board as input, and answers true if it is a wall,
 * as defined by constans.cpp, false otherwise.
 */
bool Map::isWall(pos coords) {
	return (map[coords.x][coords.y] == WALL);
}

/**
 * Takes a position on the board as input, and answers true if it is a goal,
 * as defined by constans.cpp, false otherwise.
 */
bool Map::isGoal(pos coords ) {
	return (map[coords.x][coords.y] == GOAL || map[coords.x][coords.y] == BOX_ON_GOAL);
}

/* Getters for width and height */
int Map::getWidth() { return width; }
int Map::getHeight() { return height; }

/* Get a pointer to the starting map/board */
vector<vector<char> >* Map::getOriginalMap() {
	return ↦
}

/**
 * Searches the map for places that once a box is put there, the game is unsolvable.
 */
void Map::findStaticDeadLocks() {
	//TODO

	std::vector<pos> directions;
	directions.push_back(pos(0,-1));
	directions.push_back(pos(1, 0));
	directions.push_back(pos(0, 1));
	directions.push_back(pos(-1,0));
	pos curP;

	/*
	//Debug print without deadlocks
	fprintf(stderr, "Before detecting deadlocks:\n");
	for(int i = 0;i < map.size();i++){
        for(int j = 0;j < map[i].size();j++){
        	fprintf(stderr, "%c", map[i][j]);
        }
        fprintf(stderr, "\n");
    }
    */

	bool goals = false;
	for(int i = 1;i < map.size()-1;i++) {
		if (map[i][1] == GOAL) {
			goals = true;
		}
    }
	if (!goals) {
		for(int i = 1;i < map.size()-1;i++) {
			if (map[i][1] == FREE)
				map[i][1] = DEADLOCK;
		}
	}

	goals = false;
	for(int i = 1;i < map.size()-1;i++) {
		if (map[i][map[i].size()-2] == GOAL) {
			goals = true;
		}
    }
	if (!goals) {
		for(int i = 1;i < map.size()-1;i++) {
			if (map[i][map[i].size()-2] == FREE)
				map[i][map[i].size()-2] = DEADLOCK;
		}
	}

	goals = false;
	for(int i = 1;i < map[1].size()-1;i++) {
		if (map[1][i] == GOAL) {
			goals = true;
		}
    }
	if (!goals) {
		for(int i = 1;i < map[1].size()-1;i++) {
			if (map[1][i] == FREE)
				map[1][i] = DEADLOCK;
		}
	}

	goals = false;
	for(int i = 1;i < map[map.size()-2].size()-1;i++) {
		if (map[map.size()-2][i] == GOAL) {
			goals = true;
		}
    }
	if (!goals) {
		for(int i = 1;i < map[map.size()-2].size()-1;i++) {
			if (map[map.size()-2][i] == FREE)
				map[map.size()-2][i] = DEADLOCK;
		}
	}

	/*	//Aah, it's tricky to get it right
	for(int i = 1;i < map.size()-1;i++){
        for(int j = 1;j < map[i].size()-1;j++){
            //Do something about map[i][j];
            if (map[i][j] == FREE) {
            	//Only free spaces can be deadlocks

        		if (map[i-1][j] == WALL) {
        			//It's close to a wall, might be deadlock
        			for (int k = 1; map[i-1][j+k] == WALL ;k++) {
        				if (map[i][j+k] == WALL) {

        					for (int l = 1; map[i-1][j-l] == WALL ;l++) {
        						if (map[i][j-l] == WALL) {
        							//Found deadlock
        							for (int m = 0;m<l+k;m++) {
        								map[i][j-l+m] = 'X';
        							}

        						}
        					}

        				}
        			}
        		}

            }
        }
    }*/

    //Debug print with deadlocks
    fprintf(stderr, "After detecting deadlocks:\n");
	for(int i = 0;i < map.size();i++){
        for(int j = 0;j < map[i].size();j++){
        	fprintf(stderr, "%c", map[i][j]);
        }
        fprintf(stderr, "\n");
    }
}

/* Return true if the position renders the game session unsolvable. */
bool Map::isDeadlock(pos p){
    if(map[p.y][p.x] == 'X'){
        return true;
    }
    return false;
}

/* Return true if the position renders the game session unsolvable. */
set<pos> Map::getGoals(){
    set<pos> goals;
    for(unsigned int i = 0;i < map.size();i++){
        for(unsigned int j = 0;j < map[i].size();j++){
            pos p (j,i);
            if(isGoal(p)){
                goals.insert(p);
            }
        }
    }
    return goals;
}

<commit_msg>fixade isGoal<commit_after>#include "Map.h"
#include "Constants.h"

using namespace std;
/*
A Map represents the static parts of the map.
*/

/**
 * Creates a Map from a vector of strings. Width and height are set but has
 * nothing to do with map initialization.
 */
Map::Map(vector<string> stringmap, int width, int height) {
    for(unsigned int i = 0;i < stringmap.size();i++){
        vector<char> line;
        for(unsigned int j = 0;j < stringmap[i].size();j++){
            line.push_back(stringmap[i][j]); //not sure about order of i and j - but want first coordinate to be column.
        }
        map.push_back(line);
    }

	this->width = width;
	this->height = height;
}

Map::~Map(void) {
}

/**
 * Takes a position on the board as input, and answers true if it is a wall,
 * as defined by constans.cpp, false otherwise.
 */
bool Map::isWall(pos coords) {
	return (map[coords.x][coords.y] == WALL);
}

/**
 * Takes a position on the board as input, and answers true if it is a goal,
 * as defined by constans.cpp, false otherwise.
 */
bool Map::isGoal(pos coords ) {
	return (map[coords.x][coords.y] == GOAL || map[coords.x][coords.y] == BOX_ON_GOAL || map[coords.x][coords.y] == PLAYER_ON_GOAL);
}

/* Getters for width and height */
int Map::getWidth() { return width; }
int Map::getHeight() { return height; }

/* Get a pointer to the starting map/board */
vector<vector<char> >* Map::getOriginalMap() {
	return ↦
}

/**
 * Searches the map for places that once a box is put there, the game is unsolvable.
 */
void Map::findStaticDeadLocks() {
	//TODO

	std::vector<pos> directions;
	directions.push_back(pos(0,-1));
	directions.push_back(pos(1, 0));
	directions.push_back(pos(0, 1));
	directions.push_back(pos(-1,0));
	pos curP;

	/*
	//Debug print without deadlocks
	fprintf(stderr, "Before detecting deadlocks:\n");
	for(int i = 0;i < map.size();i++){
        for(int j = 0;j < map[i].size();j++){
        	fprintf(stderr, "%c", map[i][j]);
        }
        fprintf(stderr, "\n");
    }
    */

	bool goals = false;
	for(int i = 1;i < map.size()-1;i++) {
		if (map[i][1] == GOAL) {
			goals = true;
		}
    }
	if (!goals) {
		for(int i = 1;i < map.size()-1;i++) {
			if (map[i][1] == FREE)
				map[i][1] = DEADLOCK;
		}
	}

	goals = false;
	for(int i = 1;i < map.size()-1;i++) {
		if (map[i][map[i].size()-2] == GOAL) {
			goals = true;
		}
    }
	if (!goals) {
		for(int i = 1;i < map.size()-1;i++) {
			if (map[i][map[i].size()-2] == FREE)
				map[i][map[i].size()-2] = DEADLOCK;
		}
	}

	goals = false;
	for(int i = 1;i < map[1].size()-1;i++) {
		if (map[1][i] == GOAL) {
			goals = true;
		}
    }
	if (!goals) {
		for(int i = 1;i < map[1].size()-1;i++) {
			if (map[1][i] == FREE)
				map[1][i] = DEADLOCK;
		}
	}

	goals = false;
	for(int i = 1;i < map[map.size()-2].size()-1;i++) {
		if (map[map.size()-2][i] == GOAL) {
			goals = true;
		}
    }
	if (!goals) {
		for(int i = 1;i < map[map.size()-2].size()-1;i++) {
			if (map[map.size()-2][i] == FREE)
				map[map.size()-2][i] = DEADLOCK;
		}
	}

	/*	//Aah, it's tricky to get it right
	for(int i = 1;i < map.size()-1;i++){
        for(int j = 1;j < map[i].size()-1;j++){
            //Do something about map[i][j];
            if (map[i][j] == FREE) {
            	//Only free spaces can be deadlocks

        		if (map[i-1][j] == WALL) {
        			//It's close to a wall, might be deadlock
        			for (int k = 1; map[i-1][j+k] == WALL ;k++) {
        				if (map[i][j+k] == WALL) {

        					for (int l = 1; map[i-1][j-l] == WALL ;l++) {
        						if (map[i][j-l] == WALL) {
        							//Found deadlock
        							for (int m = 0;m<l+k;m++) {
        								map[i][j-l+m] = 'X';
        							}

        						}
        					}

        				}
        			}
        		}

            }
        }
    }*/

    //Debug print with deadlocks
    fprintf(stderr, "After detecting deadlocks:\n");
	for(int i = 0;i < map.size();i++){
        for(int j = 0;j < map[i].size();j++){
        	fprintf(stderr, "%c", map[i][j]);
        }
        fprintf(stderr, "\n");
    }
}

/* Return true if the position renders the game session unsolvable. */
bool Map::isDeadlock(pos p){
    if(map[p.y][p.x] == 'X'){
        return true;
    }
    return false;
}

/* Return true if the position renders the game session unsolvable. */
set<pos> Map::getGoals(){
    set<pos> goals;
    for(unsigned int i = 0;i < map.size();i++){
        for(unsigned int j = 0;j < map[i].size();j++){
            pos p (j,i);
            if(isGoal(p)){
                goals.insert(p);
            }
        }
    }
    return goals;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ExplicitValueProvider.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-10-22 16:53:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CHART2_EXPLICITVALUEPROVIDER_HXX
#define _CHART2_EXPLICITVALUEPROVIDER_HXX

#include <boost/shared_ptr.hpp>

#ifndef _COM_SUN_STAR_CHART2_EXPLICITINCREMENTDATA_HPP_
#include <com/sun/star/chart2/ExplicitIncrementData.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_
#include <com/sun/star/chart2/ExplicitScaleData.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XAXIS_HPP_
#include <com/sun/star/chart2/XAxis.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCOORDINATESYSTEM_HPP_
#include <com/sun/star/chart2/XCoordinateSystem.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDATASERIES_HPP_
#include <com/sun/star/chart2/XDataSeries.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/

class DrawModelWrapper;
class ExplicitValueProvider
{
public:
    /** Gives calculated scale and increment values for a given xAxis in the current view.
        In contrast to the model data these explicit values are always complete as misssing auto properties are calculated.
        If the given Axis could not be found or for another reason no correct output can be given false is returned.
     */
    virtual sal_Bool getExplicitValuesForAxis(
        ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XAxis > xAxis
        , ::com::sun::star::chart2::ExplicitScaleData&  rExplicitScale
        , ::com::sun::star::chart2::ExplicitIncrementData& rExplicitIncrement )=0;

    /** for rotated objects the shape size and position differs from the visible rectangle
        if bSnapRect is set to true you get the resulting visible position (left-top) and size
    */
    virtual ::com::sun::star::awt::Rectangle
        getRectangleOfObject( const rtl::OUString& rObjectCID, bool bSnapRect=false )=0;

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
        getShapeForCID( const rtl::OUString& rObjectCID )=0;

    virtual ::boost::shared_ptr< DrawModelWrapper > getDrawModelWrapper() = 0;

    static const com::sun::star::uno::Sequence<sal_Int8>& getUnoTunnelId();
    static ExplicitValueProvider* getExplicitValueProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xChartView );

    static ::com::sun::star::awt::Rectangle
        calculateDiagramPositionAndSizeInclusiveTitle(
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::frame::XModel >& xChartModel
            , const ::com::sun::star::uno::Reference<
                ::com::sun::star::uno::XInterface >& xChartView
            , const ::com::sun::star::awt::Rectangle& rExclusivePositionAndSize );

    static sal_Int32 getExplicitNumberFormatKeyForAxis(
              const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XAxis >& xAxis
            , const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem > & xCorrespondingCoordinateSystem
            , const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier );

    static sal_Int32 getPercentNumberFormat( const ::com::sun::star::uno::Reference<
                ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier );

    static sal_Int32 getExplicitNumberFormatKeyForLabel(
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xSeriesOrPointProp
            , const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries
            , sal_Int32 nPointIndex /*-1 for whole series*/
            , const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xAttachedAxisProps );

    static sal_Int32 getExplicitPercentageNumberFormatKeyForLabel(
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xSeriesOrPointProp
            , const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier );
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.66); FILE MERGED 2008/04/01 10:50:30 thb 1.5.66.2: #i85898# Stripping all external header guards 2008/03/28 16:44:01 rt 1.5.66.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ExplicitValueProvider.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CHART2_EXPLICITVALUEPROVIDER_HXX
#define _CHART2_EXPLICITVALUEPROVIDER_HXX

#include <boost/shared_ptr.hpp>
#include <com/sun/star/chart2/ExplicitIncrementData.hpp>
#include <com/sun/star/chart2/ExplicitScaleData.hpp>
#include <com/sun/star/chart2/XAxis.hpp>
#include <com/sun/star/chart2/XCoordinateSystem.hpp>
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/

class DrawModelWrapper;
class ExplicitValueProvider
{
public:
    /** Gives calculated scale and increment values for a given xAxis in the current view.
        In contrast to the model data these explicit values are always complete as misssing auto properties are calculated.
        If the given Axis could not be found or for another reason no correct output can be given false is returned.
     */
    virtual sal_Bool getExplicitValuesForAxis(
        ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XAxis > xAxis
        , ::com::sun::star::chart2::ExplicitScaleData&  rExplicitScale
        , ::com::sun::star::chart2::ExplicitIncrementData& rExplicitIncrement )=0;

    /** for rotated objects the shape size and position differs from the visible rectangle
        if bSnapRect is set to true you get the resulting visible position (left-top) and size
    */
    virtual ::com::sun::star::awt::Rectangle
        getRectangleOfObject( const rtl::OUString& rObjectCID, bool bSnapRect=false )=0;

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >
        getShapeForCID( const rtl::OUString& rObjectCID )=0;

    virtual ::boost::shared_ptr< DrawModelWrapper > getDrawModelWrapper() = 0;

    static const com::sun::star::uno::Sequence<sal_Int8>& getUnoTunnelId();
    static ExplicitValueProvider* getExplicitValueProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xChartView );

    static ::com::sun::star::awt::Rectangle
        calculateDiagramPositionAndSizeInclusiveTitle(
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::frame::XModel >& xChartModel
            , const ::com::sun::star::uno::Reference<
                ::com::sun::star::uno::XInterface >& xChartView
            , const ::com::sun::star::awt::Rectangle& rExclusivePositionAndSize );

    static sal_Int32 getExplicitNumberFormatKeyForAxis(
              const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XAxis >& xAxis
            , const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem > & xCorrespondingCoordinateSystem
            , const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier );

    static sal_Int32 getPercentNumberFormat( const ::com::sun::star::uno::Reference<
                ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier );

    static sal_Int32 getExplicitNumberFormatKeyForLabel(
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xSeriesOrPointProp
            , const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries
            , sal_Int32 nPointIndex /*-1 for whole series*/
            , const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xAttachedAxisProps );

    static sal_Int32 getExplicitPercentageNumberFormatKeyForLabel(
            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xSeriesOrPointProp
            , const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier );
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>


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

#include "chrome/browser/chromeos/login/rounded_rect_painter.h"

#include "app/resource_bundle.h"
#include "base/logging.h"
#include "gfx/canvas.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "third_party/skia/include/effects/SkBlurMaskFilter.h"
#include "views/border.h"
#include "views/painter.h"

namespace chromeos {

namespace {

const int kBackgroundPadding = 10;
const int kCornerRadius = 12;
const int kScreenShadow = 10;
const SkColor kScreenShadowColor = SkColorSetARGB(64, 34, 54, 115);
const SkColor kBackgroundTopColor = SkColorSetRGB(82, 139, 224);
const SkColor kBackgroundBottomColor = SkColorSetRGB(50, 102, 204);
const SkColor kShadowStrokeColor = SK_ColorLTGRAY;

static void DrawRoundedRect(
      gfx::Canvas* canvas,
      int x, int y,
      int w, int h,
      int corner_radius,
      SkColor top_color, SkColor bottom_color,
      SkColor stroke_color) {
  SkRect rect;
  rect.set(
      SkIntToScalar(x), SkIntToScalar(y),
      SkIntToScalar(x + w), SkIntToScalar(y + h));
  SkPath path;
  path.addRoundRect(
      rect, SkIntToScalar(corner_radius), SkIntToScalar(corner_radius));
  SkPaint paint;
  paint.setStyle(SkPaint::kFill_Style);
  paint.setFlags(SkPaint::kAntiAlias_Flag);
  if (top_color != bottom_color) {
    SkPoint p[2];
    p[0].set(SkIntToScalar(x), SkIntToScalar(y));
    p[1].set(SkIntToScalar(x), SkIntToScalar(y + h));
    SkColor colors[2] = { top_color, bottom_color };
    SkShader* s =
        SkGradientShader::CreateLinear(p, colors, NULL, 2,
                                       SkShader::kClamp_TileMode, NULL);
    paint.setShader(s);
    // Need to unref shader, otherwise never deleted.
    s->unref();
  } else {
    paint.setColor(top_color);
  }
  canvas->drawPath(path, paint);

  if (stroke_color != 0) {
    // Expand rect by 0.5px so resulting stroke will take the whole pixel.
    rect.set(
        SkIntToScalar(x) - SK_Scalar1 / 2,
        SkIntToScalar(y) - SK_Scalar1 / 2,
        SkIntToScalar(x + w) + SK_Scalar1 / 2,
        SkIntToScalar(y + h) + SK_Scalar1 / 2);
    paint.setShader(NULL);
    paint.setStyle(SkPaint::kStroke_Style);
    paint.setStrokeWidth(1);
    paint.setColor(stroke_color);
    canvas->drawPath(path, paint);
  }
}

static void DrawRoundedRectShadow(
    gfx::Canvas* canvas,
    int x, int y,
    int w, int h,
    int corner_radius,
    int shadow,
    SkColor color) {
  SkPaint paint;
  paint.setFlags(SkPaint::kAntiAlias_Flag);
  paint.setStyle(SkPaint::kFill_Style);
  paint.setColor(color);
  SkMaskFilter* filter = SkBlurMaskFilter::Create(
      shadow / 2, SkBlurMaskFilter::kNormal_BlurStyle);
  paint.setMaskFilter(filter)->unref();
  SkRect rect;
  rect.set(
      SkIntToScalar(x + shadow / 2), SkIntToScalar(y + shadow / 2),
      SkIntToScalar(x + w - shadow / 2), SkIntToScalar(y + h - shadow / 2));
  canvas->drawRoundRect(
      rect,
      SkIntToScalar(corner_radius), SkIntToScalar(corner_radius),
      paint);
  paint.setMaskFilter(NULL);
}

static void DrawRectWithBorder(int w,
                               int h,
                               const BorderDefinition* const border,
                               gfx::Canvas* canvas) {
  int padding = border->padding;
  SkColor padding_color = border->padding_color;
  int shadow = border->shadow;
  SkColor shadow_color = border->shadow_color;
  int corner_radius = border->corner_radius;
  SkColor top_color = border->top_color;
  SkColor bottom_color = border->bottom_color;
  if (padding > 0) {
    SkPaint paint;
    paint.setColor(padding_color);
    canvas->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0),
                           SkIntToScalar(w), SkIntToScalar(h), paint);
  }
  if (border->shadow > 0) {
    DrawRoundedRectShadow(
        canvas,
        padding, padding,
        w - 2 * padding, h - 2 * padding,
        corner_radius,
        shadow, shadow_color);
  }
  DrawRoundedRect(
        canvas,
        padding + shadow,
        padding + shadow - shadow / 3,
        w - 2 * padding - 2 * shadow,
        h - 2 * padding - 2 * shadow,
        corner_radius,
        top_color, bottom_color,
        shadow ? kShadowStrokeColor : 0);
}

// This Painter can be used to draw a background consistent cross all login
// screens. It draws a rect with padding, shadow and rounded corners.
class RoundedRectPainter : public views::Painter {
 public:
  explicit RoundedRectPainter(const BorderDefinition* const border)
      : border_(border) {
  }

  virtual void Paint(int w, int h, gfx::Canvas* canvas) {
    DrawRectWithBorder(w, h, border_, canvas);
  }

 private:
  const BorderDefinition* const border_;

  DISALLOW_COPY_AND_ASSIGN(RoundedRectPainter);
};

// This border can be used to draw shadow and rounded corners across all
// login screens.
class RoundedRectBorder : public views::Border {
 public:
  explicit RoundedRectBorder(const BorderDefinition* const border)
      : border_(border) {
  }

  virtual void Paint(const views::View& view, gfx::Canvas* canvas) const;
  virtual void GetInsets(gfx::Insets* insets) const;

 private:
  const BorderDefinition* const border_;

  DISALLOW_COPY_AND_ASSIGN(RoundedRectBorder);
};

void RoundedRectBorder::Paint(const views::View& view,
                              gfx::Canvas* canvas) const {
  gfx::Rect clip_rect;
  if (!canvas->GetClipRect(&clip_rect))
    return;  // Empty clip rectangle, nothing to paint.

  int w = view.width();
  int h = view.height();

  gfx::Insets insets;
  GetInsets(&insets);
  SkRect remove;
  remove.set(SkIntToScalar(insets.left()),
             SkIntToScalar(insets.top()),
             SkIntToScalar(w - insets.right()),
             SkIntToScalar(h - insets.bottom()));
  canvas->clipRect(remove, SkRegion::kDifference_Op);

  if (canvas->IntersectsClipRectInt(0, 0, w, h)) {
    DrawRectWithBorder(w, h, border_, canvas);
  }
  canvas->clipRect(remove, SkRegion::kIntersect_Op);
}

void RoundedRectBorder::GetInsets(gfx::Insets* insets) const {
  DCHECK(insets);
  int shadow = border_->shadow;
  int inset = border_->corner_radius / 2 + border_->padding + shadow;
  insets->Set(inset - shadow / 3, inset, inset + shadow / 3, inset);
}

}  //  namespace

// static
const BorderDefinition BorderDefinition::kWizardBorder = {
  kBackgroundPadding,
  SK_ColorBLACK,
  0,
  SK_ColorBLACK,
  kCornerRadius,
  kBackgroundTopColor,
  kBackgroundBottomColor
};
const BorderDefinition BorderDefinition::kScreenBorder = {
  0,
  SK_ColorBLACK,
  kScreenShadow,
  kScreenShadowColor,
  kCornerRadius,
  SK_ColorWHITE,
  SK_ColorWHITE
};

views::Painter* CreateWizardPainter(const BorderDefinition* const border) {
  return new RoundedRectPainter(border);
}

views::Border* CreateWizardBorder(const BorderDefinition* const border) {
  return new RoundedRectBorder(border);
}

}  // namespace chromeos
<commit_msg>OOBE screens stroke should on pixel boundary to looks less blurry.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/rounded_rect_painter.h"

#include "app/resource_bundle.h"
#include "base/logging.h"
#include "gfx/canvas.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "third_party/skia/include/effects/SkBlurMaskFilter.h"
#include "views/border.h"
#include "views/painter.h"

namespace chromeos {

namespace {

const int kBackgroundPadding = 10;
const int kCornerRadius = 12;
const int kScreenShadow = 10;
const SkColor kScreenShadowColor = SkColorSetARGB(64, 34, 54, 115);
const SkColor kBackgroundTopColor = SkColorSetRGB(82, 139, 224);
const SkColor kBackgroundBottomColor = SkColorSetRGB(50, 102, 204);
const SkColor kShadowStrokeColor = SkColorSetRGB(40, 90, 177);

static void DrawRoundedRect(
      gfx::Canvas* canvas,
      int x, int y,
      int w, int h,
      int corner_radius,
      SkColor top_color, SkColor bottom_color,
      SkColor stroke_color) {
  SkRect rect;
  rect.set(
      SkIntToScalar(x), SkIntToScalar(y),
      SkIntToScalar(x + w), SkIntToScalar(y + h));
  SkPath path;
  path.addRoundRect(
      rect, SkIntToScalar(corner_radius), SkIntToScalar(corner_radius));
  SkPaint paint;
  paint.setStyle(SkPaint::kFill_Style);
  paint.setFlags(SkPaint::kAntiAlias_Flag);
  if (top_color != bottom_color) {
    SkPoint p[2];
    p[0].set(SkIntToScalar(x), SkIntToScalar(y));
    p[1].set(SkIntToScalar(x), SkIntToScalar(y + h));
    SkColor colors[2] = { top_color, bottom_color };
    SkShader* s =
        SkGradientShader::CreateLinear(p, colors, NULL, 2,
                                       SkShader::kClamp_TileMode, NULL);
    paint.setShader(s);
    // Need to unref shader, otherwise never deleted.
    s->unref();
  } else {
    paint.setColor(top_color);
  }
  canvas->drawPath(path, paint);

  if (stroke_color != 0) {
    // Expand rect by 0.5px so resulting stroke will take the whole pixel.
    rect.set(
        SkIntToScalar(x) - SK_ScalarHalf,
        SkIntToScalar(y) - SK_ScalarHalf,
        SkIntToScalar(x + w) + SK_ScalarHalf,
        SkIntToScalar(y + h) + SK_ScalarHalf);
    paint.setShader(NULL);
    paint.setStyle(SkPaint::kStroke_Style);
    paint.setStrokeWidth(SkIntToScalar(SK_Scalar1));
    paint.setColor(stroke_color);
    canvas->drawRoundRect(
      rect,
      SkIntToScalar(corner_radius), SkIntToScalar(corner_radius),
      paint);
  }
}

static void DrawRoundedRectShadow(
    gfx::Canvas* canvas,
    int x, int y,
    int w, int h,
    int corner_radius,
    int shadow,
    SkColor color) {
  SkPaint paint;
  paint.setFlags(SkPaint::kAntiAlias_Flag);
  paint.setStyle(SkPaint::kFill_Style);
  paint.setColor(color);
  SkMaskFilter* filter = SkBlurMaskFilter::Create(
      shadow / 2, SkBlurMaskFilter::kNormal_BlurStyle);
  paint.setMaskFilter(filter)->unref();
  SkRect rect;
  rect.set(
      SkIntToScalar(x + shadow / 2), SkIntToScalar(y + shadow / 2),
      SkIntToScalar(x + w - shadow / 2), SkIntToScalar(y + h - shadow / 2));
  canvas->drawRoundRect(
      rect,
      SkIntToScalar(corner_radius), SkIntToScalar(corner_radius),
      paint);
  paint.setMaskFilter(NULL);
}

static void DrawRectWithBorder(int w,
                               int h,
                               const BorderDefinition* const border,
                               gfx::Canvas* canvas) {
  int padding = border->padding;
  SkColor padding_color = border->padding_color;
  int shadow = border->shadow;
  SkColor shadow_color = border->shadow_color;
  int corner_radius = border->corner_radius;
  SkColor top_color = border->top_color;
  SkColor bottom_color = border->bottom_color;
  if (padding > 0) {
    SkPaint paint;
    paint.setColor(padding_color);
    canvas->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0),
                           SkIntToScalar(w), SkIntToScalar(h), paint);
  }
  if (border->shadow > 0) {
    DrawRoundedRectShadow(
        canvas,
        padding, padding,
        w - 2 * padding, h - 2 * padding,
        corner_radius,
        shadow, shadow_color);
  }
  DrawRoundedRect(
        canvas,
        padding + shadow,
        padding + shadow - shadow / 3,
        w - 2 * padding - 2 * shadow,
        h - 2 * padding - 2 * shadow,
        corner_radius,
        top_color, bottom_color,
        shadow ? kShadowStrokeColor : 0);
}

// This Painter can be used to draw a background consistent cross all login
// screens. It draws a rect with padding, shadow and rounded corners.
class RoundedRectPainter : public views::Painter {
 public:
  explicit RoundedRectPainter(const BorderDefinition* const border)
      : border_(border) {
  }

  virtual void Paint(int w, int h, gfx::Canvas* canvas) {
    DrawRectWithBorder(w, h, border_, canvas);
  }

 private:
  const BorderDefinition* const border_;

  DISALLOW_COPY_AND_ASSIGN(RoundedRectPainter);
};

// This border can be used to draw shadow and rounded corners across all
// login screens.
class RoundedRectBorder : public views::Border {
 public:
  explicit RoundedRectBorder(const BorderDefinition* const border)
      : border_(border) {
  }

  virtual void Paint(const views::View& view, gfx::Canvas* canvas) const;
  virtual void GetInsets(gfx::Insets* insets) const;

 private:
  const BorderDefinition* const border_;

  DISALLOW_COPY_AND_ASSIGN(RoundedRectBorder);
};

void RoundedRectBorder::Paint(const views::View& view,
                              gfx::Canvas* canvas) const {
  gfx::Rect clip_rect;
  if (!canvas->GetClipRect(&clip_rect))
    return;  // Empty clip rectangle, nothing to paint.

  int w = view.width();
  int h = view.height();

  gfx::Insets insets;
  GetInsets(&insets);
  SkRect remove;
  remove.set(SkIntToScalar(insets.left()),
             SkIntToScalar(insets.top()),
             SkIntToScalar(w - insets.right()),
             SkIntToScalar(h - insets.bottom()));
  canvas->clipRect(remove, SkRegion::kDifference_Op);

  if (canvas->IntersectsClipRectInt(0, 0, w, h)) {
    DrawRectWithBorder(w, h, border_, canvas);
  }
  canvas->clipRect(remove, SkRegion::kIntersect_Op);
}

void RoundedRectBorder::GetInsets(gfx::Insets* insets) const {
  DCHECK(insets);
  int shadow = border_->shadow;
  int inset = border_->corner_radius / 2 + border_->padding + shadow;
  insets->Set(inset - shadow / 3, inset, inset + shadow / 3, inset);
}

}  //  namespace

// static
const BorderDefinition BorderDefinition::kWizardBorder = {
  kBackgroundPadding,
  SK_ColorBLACK,
  0,
  SK_ColorBLACK,
  kCornerRadius,
  kBackgroundTopColor,
  kBackgroundBottomColor
};
const BorderDefinition BorderDefinition::kScreenBorder = {
  0,
  SK_ColorBLACK,
  kScreenShadow,
  kScreenShadowColor,
  kCornerRadius,
  SK_ColorWHITE,
  SK_ColorWHITE
};

views::Painter* CreateWizardPainter(const BorderDefinition* const border) {
  return new RoundedRectPainter(border);
}

views::Border* CreateWizardBorder(const BorderDefinition* const border) {
  return new RoundedRectBorder(border);
}

}  // namespace chromeos
<|endoftext|>