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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include <mitkImageCast.h>
#include <itkImage.h>
#include <itkCastImageFilter.h>
#include "itkDiffusionTensor3D.h"

namespace mitk
{
#ifndef DOXYGEN_SKIP
  template <typename ItkOutputImageType> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer<ItkOutputImageType>& itkOutputImage)
  {
    AccessFixedDimensionByItk_1(mitkImage, _CastToItkImage2Access, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
  }
#endif //DOXYGEN_SKIP

typedef itk::Image<double, 2>         itkImageD2;
typedef itk::Image<float, 2>          itkImageF2;
typedef itk::Image<int, 2>            itkImageSI2;
typedef itk::Image<unsigned int, 2>   itkImageUI2;
typedef itk::Image<short, 2>          itkImageSS2;
typedef itk::Image<unsigned short, 2> itkImageUS2;
typedef itk::Image<char, 2>           itkImageSC2;
typedef itk::Image<unsigned char, 2>  itkImageUC2;
typedef itk::Image<itk::RGBPixel<unsigned char>, 2>  itkImageRGBUC2;
typedef itk::Image<itk::DiffusionTensor3D<float>, 2>  itkImageDTIF2;
typedef itk::Image<itk::DiffusionTensor3D<double>, 2>  itkImageDTID2;

typedef itk::Image<double, 3>         itkImageD3;
typedef itk::Image<float, 3>          itkImageF3;
typedef itk::Image<int, 3>            itkImageSI3;
typedef itk::Image<unsigned int, 3>   itkImageUI3;
typedef itk::Image<short, 3>          itkImageSS3;
typedef itk::Image<unsigned short, 3> itkImageUS3;
typedef itk::Image<char, 3>           itkImageSC3;
typedef itk::Image<unsigned char, 3>  itkImageUC3;
typedef itk::Image<itk::RGBPixel<unsigned char>, 3>  itkImageRGBUC3;
typedef itk::Image<itk::DiffusionTensor3D<float>, 3>  itkImageDTIF3;
typedef itk::Image<itk::DiffusionTensor3D<double>, 3>  itkImageDTID3;

template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageD2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageF2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSI2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUI2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSS2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUS2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSC2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUC2>&);
//template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageDTIF2>&);
//template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageDTID2>&);
template <> void CastToItkImage<itkImageRGBUC2>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageRGBUC2>& itkOutputImage)
{
  typedef itkImageRGBUC2 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::RGBPixel<unsigned char>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}
template <> void CastToItkImage<itkImageDTIF2>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageDTIF2>& itkOutputImage)
{
  typedef itkImageDTIF2 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D<float>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}
template <> void CastToItkImage<itkImageDTID2>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageDTID2>& itkOutputImage)
{
  typedef itkImageRGBUC2 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D<double>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}

template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageD3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageF3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSI3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUI3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSS3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUS3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSC3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUC3>&);
//template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageDTIF3>&);
//template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageDTID3>&);
template <> void MITK_CORE_EXPORT CastToItkImage<itkImageRGBUC3>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageRGBUC3>& itkOutputImage)
{
  typedef itkImageRGBUC3 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::RGBPixel<unsigned char>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}
template <> void MITK_CORE_EXPORT CastToItkImage<itkImageDTIF3>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageDTIF3>& itkOutputImage)
{
  typedef itkImageRGBUC3 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D<float>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}
template <> void MITK_CORE_EXPORT CastToItkImage<itkImageDTID3>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageDTID3>& itkOutputImage)
{
  typedef itkImageRGBUC3 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D<double>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}

#ifndef DOXYGEN_SKIP
//// Extension for RGB (and maybe also for vector types)
//// Does not work yet, see comment below and bug 320
//template <typename ItkOutputImageType> void RGBCastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer<ItkOutputImageType>& itkOutputImage)
//{
//  assert(mitkImage->GetDimension()==::itk::GetImageDimension<ItkOutputImageType>::ImageDimension);
//
//  assert(mitkImage->GetPixelType().GetNumberOfComponents() == 3);
//
//  const std::type_info& typeId=*mitkImage->GetPixelType().GetTypeId();
//
//  // Currently, the following line always fails, see bug 320
//  assert( typeId == typeid(ItkOutputImageType::PixelType) );
//
//  const mitk::Image* constImage = mitkImage;
//  const_cast<mitk::Image*>(constImage)->Update();
//
//  typedef mitk::ImageToItk<ItkOutputImageType> ImageToItkType;
//  itk::SmartPointer<ImageToItkType> imagetoitk = ImageToItkType::New();
//  imagetoitk->SetInput(mitkImage);
//  imagetoitk->Update();
//  itkOutputImage = imagetoitk->GetOutput();
//}
//
//typedef itk::Image<itk::RGBPixel<unsigned char>, 2>  itkImageRGBUC2;
//typedef itk::Image<itk::RGBPixel<unsigned char>, 3>  itkImageRGBUC3;
//
//template <> void CastToItkImage<itkImageRGBUC2>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageRGBUC2>& itkOutputImage)
//{
//  typedef itkImageRGBUC2 ItkOutputImageType;
//  RGBCastToItkImage<ItkOutputImageType>(mitkImage, itkOutputImage);
//}
//
//template <> void CastToItkImage<itkImageRGBUC3>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageRGBUC3>& itkOutputImage)
//{
//  typedef itkImageRGBUC3 ItkOutputImageType;
//  RGBCastToItkImage<ItkOutputImageType>(mitkImage, itkOutputImage);
//}
#endif //DOXYGEN_SKIP

}
<commit_msg>FIX (#320): fixed erroneous typedefs for ItkOutputImageType in case of itk::DiffusionTensor3D cast<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include <mitkImageCast.h>
#include <itkImage.h>
#include <itkCastImageFilter.h>
#include "itkDiffusionTensor3D.h"

namespace mitk
{
#ifndef DOXYGEN_SKIP
  template <typename ItkOutputImageType> void CastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer<ItkOutputImageType>& itkOutputImage)
  {
    AccessFixedDimensionByItk_1(mitkImage, _CastToItkImage2Access, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
  }
#endif //DOXYGEN_SKIP

typedef itk::Image<double, 2>         itkImageD2;
typedef itk::Image<float, 2>          itkImageF2;
typedef itk::Image<int, 2>            itkImageSI2;
typedef itk::Image<unsigned int, 2>   itkImageUI2;
typedef itk::Image<short, 2>          itkImageSS2;
typedef itk::Image<unsigned short, 2> itkImageUS2;
typedef itk::Image<char, 2>           itkImageSC2;
typedef itk::Image<unsigned char, 2>  itkImageUC2;
typedef itk::Image<itk::RGBPixel<unsigned char>, 2>  itkImageRGBUC2;
typedef itk::Image<itk::DiffusionTensor3D<float>, 2>  itkImageDTIF2;
typedef itk::Image<itk::DiffusionTensor3D<double>, 2>  itkImageDTID2;

typedef itk::Image<double, 3>         itkImageD3;
typedef itk::Image<float, 3>          itkImageF3;
typedef itk::Image<int, 3>            itkImageSI3;
typedef itk::Image<unsigned int, 3>   itkImageUI3;
typedef itk::Image<short, 3>          itkImageSS3;
typedef itk::Image<unsigned short, 3> itkImageUS3;
typedef itk::Image<char, 3>           itkImageSC3;
typedef itk::Image<unsigned char, 3>  itkImageUC3;
typedef itk::Image<itk::RGBPixel<unsigned char>, 3>  itkImageRGBUC3;
typedef itk::Image<itk::DiffusionTensor3D<float>, 3>  itkImageDTIF3;
typedef itk::Image<itk::DiffusionTensor3D<double>, 3>  itkImageDTID3;

template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageD2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageF2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSI2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUI2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSS2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUS2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSC2>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUC2>&);
template <> void CastToItkImage<itkImageRGBUC2>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageRGBUC2>& itkOutputImage)
{
  typedef itkImageRGBUC2 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::RGBPixel<unsigned char>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}
template <> void CastToItkImage<itkImageDTIF2>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageDTIF2>& itkOutputImage)
{
  typedef itkImageDTIF2 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D<float>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}
template <> void CastToItkImage<itkImageDTID2>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageDTID2>& itkOutputImage)
{
  typedef itkImageDTID2 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D<double>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}

template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageD3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageF3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSI3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUI3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSS3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUS3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageSC3>&);
template void MITK_CORE_EXPORT CastToItkImage(const mitk::Image *, itk::SmartPointer<itkImageUC3>&);
template <> void MITK_CORE_EXPORT CastToItkImage<itkImageRGBUC3>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageRGBUC3>& itkOutputImage)
{
  typedef itkImageRGBUC3 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::RGBPixel<unsigned char>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}
template <> void MITK_CORE_EXPORT CastToItkImage<itkImageDTIF3>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageDTIF3>& itkOutputImage)
{
  typedef itkImageDTIF3 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D<float>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}
template <> void MITK_CORE_EXPORT CastToItkImage<itkImageDTID3>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageDTID3>& itkOutputImage)
{
  typedef itkImageDTID3 ItkOutputImageType;
  AccessFixedTypeByItk_1(mitkImage, _CastToItkImage2Access, itk::DiffusionTensor3D<double>, ::itk::GetImageDimension<ItkOutputImageType>::ImageDimension, itkOutputImage);
}

#ifndef DOXYGEN_SKIP
//// Extension for RGB (and maybe also for vector types)
//// Does not work yet, see comment below and bug 320
//template <typename ItkOutputImageType> void RGBCastToItkImage(const mitk::Image * mitkImage, itk::SmartPointer<ItkOutputImageType>& itkOutputImage)
//{
//  assert(mitkImage->GetDimension()==::itk::GetImageDimension<ItkOutputImageType>::ImageDimension);
//
//  assert(mitkImage->GetPixelType().GetNumberOfComponents() == 3);
//
//  const std::type_info& typeId=*mitkImage->GetPixelType().GetTypeId();
//
//  // Currently, the following line always fails, see bug 320
//  assert( typeId == typeid(ItkOutputImageType::PixelType) );
//
//  const mitk::Image* constImage = mitkImage;
//  const_cast<mitk::Image*>(constImage)->Update();
//
//  typedef mitk::ImageToItk<ItkOutputImageType> ImageToItkType;
//  itk::SmartPointer<ImageToItkType> imagetoitk = ImageToItkType::New();
//  imagetoitk->SetInput(mitkImage);
//  imagetoitk->Update();
//  itkOutputImage = imagetoitk->GetOutput();
//}
//
//typedef itk::Image<itk::RGBPixel<unsigned char>, 2>  itkImageRGBUC2;
//typedef itk::Image<itk::RGBPixel<unsigned char>, 3>  itkImageRGBUC3;
//
//template <> void CastToItkImage<itkImageRGBUC2>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageRGBUC2>& itkOutputImage)
//{
//  typedef itkImageRGBUC2 ItkOutputImageType;
//  RGBCastToItkImage<ItkOutputImageType>(mitkImage, itkOutputImage);
//}
//
//template <> void CastToItkImage<itkImageRGBUC3>(const mitk::Image * mitkImage, itk::SmartPointer<itkImageRGBUC3>& itkOutputImage)
//{
//  typedef itkImageRGBUC3 ItkOutputImageType;
//  RGBCastToItkImage<ItkOutputImageType>(mitkImage, itkOutputImage);
//}
#endif //DOXYGEN_SKIP

}
<|endoftext|>


<commit_before>// OPeNDAPDir.cc

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <iostream>

using std::cout ;
using std::endl ;

#include "OPeNDAPDir.h"
#include "GNURegex.h"

OPeNDAPDir::OPeNDAPDir( const string &dirName )
    : _dirName( dirName ),
      _fileExpr( "" ),
      _dirLoaded( false )
{
}

OPeNDAPDir::OPeNDAPDir( const string &dirName, const string &fileExpr )
    : _dirName( dirName ),
      _fileExpr( fileExpr ),
      _dirLoaded( false )
{
}

OPeNDAPDir::OPeNDAPDir( const OPeNDAPDir &copyFrom )
    : _dirName( copyFrom._dirName ),
      _fileExpr( copyFrom._fileExpr ),
      _dirLoaded( false )
{
}

OPeNDAPDir::~OPeNDAPDir()
{
}

OPeNDAPDir::dirIterator
OPeNDAPDir::beginOfDirList()
{
    if( _dirLoaded == false )
    {
	loadDir() ;
	_dirLoaded = true ;
    }
    return _dirList.begin() ;
}

OPeNDAPDir::dirIterator
OPeNDAPDir::endOfDirList()
{
    if( _dirLoaded == false )
    {
	loadDir() ;
	_dirLoaded = true ;
    }
    return _dirList.end() ;
}

OPeNDAPDir::fileIterator
OPeNDAPDir::beginOfFileList()
{
    if( _dirLoaded == false )
    {
	loadDir() ;
	_dirLoaded = true ;
    }
    return _fileList.begin() ;
}

OPeNDAPDir::fileIterator
OPeNDAPDir::endOfFileList()
{
    if( _dirLoaded == false )
    {
	loadDir() ;
	_dirLoaded = true ;
    }
    return _fileList.end() ;
}

void
OPeNDAPDir::loadDir()
{
    DIR * dip;
    struct dirent *dit;

    // open a directory stream
    // make sure the directory is valid and readable
    if( ( dip = opendir( _dirName.c_str() ) ) == NULL )
    {
	string err_str = "ERROR: failed to open directory '" + _dirName + "'" ;
	throw err_str ;
    }
    else
    {
	// read in the files in this directory
	// add each filename to the list of filenames
	while ( ( dit = readdir( dip ) ) != NULL )
	{
	    struct stat buf;
	    string dirEntry = dit->d_name ;
	    if( dirEntry != "." && dirEntry != ".." )
	    {
		string fullPath = _dirName + "/" + dirEntry ;
		stat( fullPath.c_str(), &buf ) ;

		// look at the mode and determine if this is a filename
		// or a directory name
		if ( S_ISDIR( buf.st_mode ) )
		{
		    _dirList.push_back( OPeNDAPDir( fullPath ) ) ;
		}
		else
		{
		    if( _fileExpr != "" )
		    {
			Regex reg_expr( _fileExpr.c_str() ) ;
			if( reg_expr.match( dirEntry.c_str(),
			                    dirEntry.length() ) != -1 )
			{
			    _fileList.push_back( OPeNDAPFile( _dirName, dirEntry ) );
			}
		    }
		    else
		    {
			_fileList.push_back( OPeNDAPFile( _dirName, dirEntry ) ) ;
		    }
		}
	    }
	}
    }

    // close the directory
    closedir( dip ) ;
}

<commit_msg>Tweek for win32 port<commit_after>// OPeNDAPDir.cc

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#ifdef WIN32
#include <config.h>  //  for S_ISDIR macro
#endif
#include <stdio.h>
#include <iostream>

using std::cout ;
using std::endl ;

#include "OPeNDAPDir.h"
#include "GNURegex.h"

OPeNDAPDir::OPeNDAPDir( const string &dirName )
    : _dirName( dirName ),
      _fileExpr( "" ),
      _dirLoaded( false )
{
}

OPeNDAPDir::OPeNDAPDir( const string &dirName, const string &fileExpr )
    : _dirName( dirName ),
      _fileExpr( fileExpr ),
      _dirLoaded( false )
{
}

OPeNDAPDir::OPeNDAPDir( const OPeNDAPDir &copyFrom )
    : _dirName( copyFrom._dirName ),
      _fileExpr( copyFrom._fileExpr ),
      _dirLoaded( false )
{
}

OPeNDAPDir::~OPeNDAPDir()
{
}

OPeNDAPDir::dirIterator
OPeNDAPDir::beginOfDirList()
{
    if( _dirLoaded == false )
    {
	loadDir() ;
	_dirLoaded = true ;
    }
    return _dirList.begin() ;
}

OPeNDAPDir::dirIterator
OPeNDAPDir::endOfDirList()
{
    if( _dirLoaded == false )
    {
	loadDir() ;
	_dirLoaded = true ;
    }
    return _dirList.end() ;
}

OPeNDAPDir::fileIterator
OPeNDAPDir::beginOfFileList()
{
    if( _dirLoaded == false )
    {
	loadDir() ;
	_dirLoaded = true ;
    }
    return _fileList.begin() ;
}

OPeNDAPDir::fileIterator
OPeNDAPDir::endOfFileList()
{
    if( _dirLoaded == false )
    {
	loadDir() ;
	_dirLoaded = true ;
    }
    return _fileList.end() ;
}

void
OPeNDAPDir::loadDir()
{
    DIR * dip;
    struct dirent *dit;

    // open a directory stream
    // make sure the directory is valid and readable
    if( ( dip = opendir( _dirName.c_str() ) ) == NULL )
    {
	string err_str = "ERROR: failed to open directory '" + _dirName + "'" ;
	throw err_str ;
    }
    else
    {
	// read in the files in this directory
	// add each filename to the list of filenames
	while ( ( dit = readdir( dip ) ) != NULL )
	{
	    struct stat buf;
	    string dirEntry = dit->d_name ;
	    if( dirEntry != "." && dirEntry != ".." )
	    {
		string fullPath = _dirName + "/" + dirEntry ;
		stat( fullPath.c_str(), &buf ) ;

		// look at the mode and determine if this is a filename
		// or a directory name
		if ( S_ISDIR( buf.st_mode ) )
		{
		    _dirList.push_back( OPeNDAPDir( fullPath ) ) ;
		}
		else
		{
		    if( _fileExpr != "" )
		    {
			Regex reg_expr( _fileExpr.c_str() ) ;
			if( reg_expr.match( dirEntry.c_str(),
			                    dirEntry.length() ) != -1 )
			{
			    _fileList.push_back( OPeNDAPFile( _dirName, dirEntry ) );
			}
		    }
		    else
		    {
			_fileList.push_back( OPeNDAPFile( _dirName, dirEntry ) ) ;
		    }
		}
	    }
	}
    }

    // close the directory
    closedir( dip ) ;
}

<|endoftext|>


<commit_before>#include "StateMachine.h"

//##ModelId=3E5B2DB301FD
mitk::StateMachine::StateMachine(std::string type)
: m_Type(type), m_CurrentState(0)
{}

//##ModelId=3E5B2DE30378
bool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)
{
	const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());

	State *tempState = tempTransition->GetNextState();
	if (tempState == NULL)
		return false;

	int tempSideEffectId = tempTransition->GetSideEffectId();

	//remember UNDO!!!!!
	/*new Operation for StateChange and Operation*/
	m_CurrentState = tempState;

	//remember UNDO!!!!!
	return Operation(tempSideEffectId);
}

//##ModelId=3E5B2E660087
std::string mitk::StateMachine::GetName() const
{
	return m_Type;
}

//##ModelId=3E5B2E170228
bool mitk::StateMachine::ExecuteSideEffect(int sideEffectId)
{
	return true;
}

<commit_msg>changed handleEvent<commit_after>#include "StateMachine.h"

//##ModelId=3E5B2DB301FD
mitk::StateMachine::StateMachine(std::string type)
: m_Type(type), m_CurrentState(0)
{}

//##ModelId=3E5B2DE30378
bool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)
{
	const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());

	State *tempState = tempTransition->GetNextState();
	if (tempState == NULL)
		return false;

	int tempSideEffectId = tempTransition->GetSideEffectId();

	//remember UNDO!!!!!
	/*first StateChange, then operation*/
	m_CurrentState = tempState;

	//remember UNDO!!!!!
	bool ok = ExecuteSideEffect(tempSideEffectId);
	return ok;
}

//##ModelId=3E5B2E660087
std::string mitk::StateMachine::GetName() const
{
	return m_Type;
}

//##ModelId=3E5B2E170228
bool mitk::StateMachine::ExecuteSideEffect(int sideEffectId)
{
	return true;
}

<|endoftext|>


<commit_before>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "MapUpdater.h"
#include "LFGMgr.h"
#include "Map.h"
#include "Metric.h"

class UpdateRequest
{
public:
    UpdateRequest() = default;
    virtual ~UpdateRequest() = default;

    virtual void call() = 0;
};

class MapUpdateRequest : public UpdateRequest
{
public:
    MapUpdateRequest(Map& m, MapUpdater& u, uint32 d, uint32 sd)
        : m_map(m), m_updater(u), m_diff(d), s_diff(sd)
    {
    }

    void call() override
    {
        METRIC_TIMER("map_update_time_diff", METRIC_TAG("map_id", std::to_string(m_map.GetId())));
        m_map.Update(m_diff, s_diff);
        m_updater.update_finished();
    }

private:
    Map& m_map;
    MapUpdater& m_updater;
    uint32 m_diff;
    uint32 s_diff;
};

class LFGUpdateRequest : public UpdateRequest
{
public:
    LFGUpdateRequest(MapUpdater& u, uint32 d) : m_updater(u), m_diff(d) {}

    void call() override
    {
        sLFGMgr->Update(m_diff, 1);
        m_updater.update_finished();
    }
private:
    MapUpdater& m_updater;
    uint32 m_diff;
};

MapUpdater::MapUpdater(): pending_requests(0)
{
}

void MapUpdater::activate(size_t num_threads)
{
    _workerThreads.reserve(num_threads);
    for (size_t i = 0; i < num_threads; ++i)
    {
        _workerThreads.push_back(std::thread(&MapUpdater::WorkerThread, this));
    }
}

void MapUpdater::deactivate()
{
    _cancelationToken = true;

    wait();

    _queue.Cancel();

    for (auto& thread : _workerThreads)
    {
        if (thread.joinable())
        {
            thread.join();
        }
    }
}

void MapUpdater::wait()
{
    std::unique_lock<std::mutex> guard(_lock);

    while (pending_requests > 0)
        _condition.wait(guard);

    guard.unlock();
}

void MapUpdater::schedule_update(Map& map, uint32 diff, uint32 s_diff)
{
    std::lock_guard<std::mutex> guard(_lock);

    ++pending_requests;

    _queue.Push(new MapUpdateRequest(map, *this, diff, s_diff));
}

void MapUpdater::schedule_lfg_update(uint32 diff)
{
    std::lock_guard<std::mutex> guard(_lock);

    ++pending_requests;

    _queue.Push(new LFGUpdateRequest(*this, diff));
}

bool MapUpdater::activated()
{
    return _workerThreads.size() > 0;
}

void MapUpdater::update_finished()
{
    std::lock_guard<std::mutex> lock(_lock);

    --pending_requests;

    _condition.notify_all();
}

void MapUpdater::WorkerThread()
{
    while (1)
    {
        UpdateRequest* request = nullptr;

        _queue.WaitAndPop(request);
        if (_cancelationToken)
            return;

        request->call();

        delete request;
    }
}
<commit_msg>Add (core\logging): Log sync db queries in mapupdater (#13638)<commit_after>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "DatabaseEnv.h"
#include "LFGMgr.h"
#include "Map.h"
#include "MapUpdater.h"
#include "Metric.h"

class UpdateRequest
{
public:
    UpdateRequest() = default;
    virtual ~UpdateRequest() = default;

    virtual void call() = 0;
};

class MapUpdateRequest : public UpdateRequest
{
public:
    MapUpdateRequest(Map& m, MapUpdater& u, uint32 d, uint32 sd)
        : m_map(m), m_updater(u), m_diff(d), s_diff(sd)
    {
    }

    void call() override
    {
        METRIC_TIMER("map_update_time_diff", METRIC_TAG("map_id", std::to_string(m_map.GetId())));
        m_map.Update(m_diff, s_diff);
        m_updater.update_finished();
    }

private:
    Map& m_map;
    MapUpdater& m_updater;
    uint32 m_diff;
    uint32 s_diff;
};

class LFGUpdateRequest : public UpdateRequest
{
public:
    LFGUpdateRequest(MapUpdater& u, uint32 d) : m_updater(u), m_diff(d) {}

    void call() override
    {
        sLFGMgr->Update(m_diff, 1);
        m_updater.update_finished();
    }
private:
    MapUpdater& m_updater;
    uint32 m_diff;
};

MapUpdater::MapUpdater(): pending_requests(0)
{
}

void MapUpdater::activate(size_t num_threads)
{
    _workerThreads.reserve(num_threads);
    for (size_t i = 0; i < num_threads; ++i)
    {
        _workerThreads.push_back(std::thread(&MapUpdater::WorkerThread, this));
    }
}

void MapUpdater::deactivate()
{
    _cancelationToken = true;

    wait();

    _queue.Cancel();

    for (auto& thread : _workerThreads)
    {
        if (thread.joinable())
        {
            thread.join();
        }
    }
}

void MapUpdater::wait()
{
    std::unique_lock<std::mutex> guard(_lock);

    while (pending_requests > 0)
        _condition.wait(guard);

    guard.unlock();
}

void MapUpdater::schedule_update(Map& map, uint32 diff, uint32 s_diff)
{
    std::lock_guard<std::mutex> guard(_lock);

    ++pending_requests;

    _queue.Push(new MapUpdateRequest(map, *this, diff, s_diff));
}

void MapUpdater::schedule_lfg_update(uint32 diff)
{
    std::lock_guard<std::mutex> guard(_lock);

    ++pending_requests;

    _queue.Push(new LFGUpdateRequest(*this, diff));
}

bool MapUpdater::activated()
{
    return _workerThreads.size() > 0;
}

void MapUpdater::update_finished()
{
    std::lock_guard<std::mutex> lock(_lock);

    --pending_requests;

    _condition.notify_all();
}

void MapUpdater::WorkerThread()
{
    LoginDatabase.WarnAboutSyncQueries(true);
    CharacterDatabase.WarnAboutSyncQueries(true);
    WorldDatabase.WarnAboutSyncQueries(true);

    while (1)
    {
        UpdateRequest* request = nullptr;

        _queue.WaitAndPop(request);
        if (_cancelationToken)
            return;

        request->call();

        delete request;
    }
}
<|endoftext|>


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

  Program:   Medical Imaging & Interaction Toolkit
  Module:    $RCSfile$
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "mitkStateMachine.h"
#include "mitkStateMachineFactory.h"
#include "mitkStateTransitionOperation.h"
#include "mitkOperationEvent.h"
#include "mitkUndoController.h"
#include "mitkStatusBar.h"
#include "mitkInteractionConst.h"
#include <itkMacro.h>
#include "mitkInteractor.h"

//##ModelId=3E5B2DB301FD
//##Documentation
//## Constructor
//## daclares a new StateMachine and connects
//## it to a StateMachine of Type type;
mitk::StateMachine::StateMachine(const char * type) : m_CurrentState(NULL)
{
  if(type!=NULL)
  {
    m_Type = type;
	  m_CurrentState = mitk::StateMachineFactory::GetStartState(type);
  }
  else
    mitk::StatusBar::DisplayText("Error! Sender: StateMachine; Message: Type of StateMachine is NULL!", 10000);

  m_UndoController = new UndoController(LIMITEDLINEARUNDO);//switch to LLU or add LLU
	m_UndoEnabled = true;
}

//##ModelId=3E5B2E660087
std::string mitk::StateMachine::GetType() const
{
	return m_Type;
}

const mitk::State* mitk::StateMachine::GetCurrentState() const
{
  if (m_CurrentState)
    return m_CurrentState;
  return NULL;
}

//##ModelId=3E5B2DE30378
bool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)
{
  if (m_CurrentState == NULL)
  return false;//m_CurrentState needs to be set first!

  //get the Transition from m_CurrentState which waits for this EventId
  const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());
  if (tempTransition == NULL) //no transition in this state for that EventId
  {
    return false;
  }

  //get next State
  State *tempNextState = tempTransition->GetNextState();
  if (tempNextState == NULL) //wrong built up statemachine!
    return false;

  //and ActionId to execute later on
  if ( m_CurrentState->GetId() != tempNextState->GetId() )//statechange only if there is a real statechange
  {
    if ( m_UndoEnabled )	//write to UndoMechanism if Undo is enabled
    {
      //UNDO for this statechange; since we directly change the state, we don't need the do-Operation in case m_UndoEnables == false
  	  StateTransitionOperation* doOp = new StateTransitionOperation(OpSTATECHANGE, tempNextState);
      StateTransitionOperation* undoOp = new StateTransitionOperation(OpSTATECHANGE, m_CurrentState);
	    OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp);
	    m_UndoController->SetOperationEvent(operationEvent);
    }

            #ifdef INTERDEBUG
            //Debug StateChanges through cout output! Thus very slow!
            std::cout<<this->GetType()<<": Changing from StateId "<<m_CurrentState->GetId()<<" to StateId "<<tempNextState->GetId()<<std::endl;
            std::cout<<this->GetType()<<": Changing from State "<<m_CurrentState->GetName()<<" to State "<<tempNextState->GetName()<<std::endl;
            #endif

    //first following StateChange(or calling ExecuteOperation(tempNextStateOp)), then operation(action)
    m_CurrentState = tempNextState;
  }

  std::vector<Action*>::iterator actionIdIterator = tempTransition->GetActionBeginIterator();
  const std::vector<Action*>::iterator actionIdIteratorEnd = tempTransition->GetActionEndIterator();
  bool ok = true;

  while ( actionIdIterator != actionIdIteratorEnd )
  {
    if ( !ExecuteAction(*actionIdIterator, stateEvent) )
    {
      #ifdef INTERDEBUG
      itkWarningMacro( << "Warning: no action defind for " << *actionIdIterator << " in " << m_Type );
      #endif

      ok = false;
    }
    actionIdIterator++;
  }
  return ok;
}

//##ModelId=3EDCAECB0175
void mitk::StateMachine::EnableUndo(bool enable)
{
	m_UndoEnabled = enable;
}

//##ModelId=3EF099EA03C0
void mitk::StateMachine::IncCurrGroupEventId()
{
	mitk::OperationEvent::IncCurrGroupEventId();
}

void mitk::StateMachine::ExecuteOperation(Operation* operation)
{
	switch (operation->GetOperationType())
	{
	case OpNOTHING:
		break;
	case OpSTATECHANGE:
		{
			mitk::StateTransitionOperation* stateTransOp = dynamic_cast<mitk::StateTransitionOperation *>(operation);
			if (stateTransOp == NULL)
			{
				mitk::StatusBar::DisplayText("Error! see mitkStateMachine.cpp", 10000);
				return;
			}
#ifdef INTERDEBUG
//Debug StateChanges through cout output! Thus very slow!
std::cout<<this->GetType()<<": Undo: Changing from StateId "<<m_CurrentState->GetId()<<" to StateId "<<stateTransOp->GetState()->GetId()<<std::endl;
std::cout<<this->GetType()<<": Undo: Changing from State "<<m_CurrentState->GetName()<<" to State "<<stateTransOp->GetState()->GetName()<<std::endl;
#endif
			m_CurrentState = stateTransOp->GetState();
		}
		break;
  case OpDELETE:
    {
      //delete this!
      //before all lower statemachines has to be deleted in a action
      //this->Delete();//might not work!!!check itk!
    }
  case OpUNDELETE:
    {
      //this is just new! and now the m_CurrentState has to be set on a special State
      //that way a delete of a StateMachine can be undone
      //IMPORTANT: The type has to be the same!!!Done by a higher instance, that creates this!
      mitk::StateTransitionOperation* stateTransOp = dynamic_cast<mitk::StateTransitionOperation *>(operation);
			if (stateTransOp != NULL)
      {
        m_CurrentState = stateTransOp->GetState();
      }
    }
	default:
		;
	}
}
<commit_msg>code cleanup<commit_after>/*=========================================================================

  Program:   Medical Imaging & Interaction Toolkit
  Module:    $RCSfile$
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "mitkStateMachine.h"
#include "mitkStateMachineFactory.h"
#include "mitkStateTransitionOperation.h"
#include "mitkOperationEvent.h"
#include "mitkUndoController.h"
#include "mitkInteractionConst.h"
#include <itkMacro.h>
#include "mitkInteractor.h"

//##ModelId=3E5B2DB301FD
//##Documentation
//## Constructor
//## daclares a new StateMachine and connects
//## it to a StateMachine of Type type;
mitk::StateMachine::StateMachine(const char * type) : m_CurrentState(NULL)
{
  if(type!=NULL)
  {
    m_Type = type;
	  m_CurrentState = mitk::StateMachineFactory::GetStartState(type);
    if (m_CurrentState == NULL)
      itkWarningMacro("Error from "<<this->GetNameOfClass()<<"; Message: did not recieve a pointer for start-state");
  }
  //else
  //  itkWarningMacro("Error from "<<this->GetNameOfClass()<<"; Message: Type of StateMachine is NULL!");
  //\*todo: check the process with BaseControllers, cause they are always instantiated with type ==NULL! So here we can't check and warn the user.

  m_UndoController = new UndoController(LIMITEDLINEARUNDO);//switch to LLU or add LLU
	m_UndoEnabled = true;
}

//##ModelId=3E5B2E660087
std::string mitk::StateMachine::GetType() const
{
	return m_Type;
}

const mitk::State* mitk::StateMachine::GetCurrentState() const
{
  if (m_CurrentState)
    return m_CurrentState;
  return NULL;
}

//##ModelId=3E5B2DE30378
bool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)
{
  if (m_CurrentState == NULL)
    return false;//m_CurrentState needs to be set first!

  //get the Transition from m_CurrentState which waits for this EventId
  const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());
  if (tempTransition == NULL) //no transition in this state for that EventId
  {
    return false;
  }

  //get next State
  State *tempNextState = tempTransition->GetNextState();
  if (tempNextState == NULL) //wrong built up statemachine!
    return false;

  //and ActionId to execute later on
  if ( m_CurrentState->GetId() != tempNextState->GetId() )//statechange only if there is a real statechange
  {
    if ( m_UndoEnabled )	//write to UndoMechanism if Undo is enabled
    {
      //UNDO for this statechange; since we directly change the state, we don't need the do-Operation in case m_UndoEnables == false
  	  StateTransitionOperation* doOp = new StateTransitionOperation(OpSTATECHANGE, tempNextState);
      StateTransitionOperation* undoOp = new StateTransitionOperation(OpSTATECHANGE, m_CurrentState);
	    OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), doOp, undoOp);
	    m_UndoController->SetOperationEvent(operationEvent);
    }

            #ifdef INTERDEBUG
            //Debug StateChanges through cout output! Thus very slow!
            std::cout<<this->GetType()<<": Changing from StateId "<<m_CurrentState->GetId()<<" to StateId "<<tempNextState->GetId()<<std::endl;
            std::cout<<this->GetType()<<": Changing from State "<<m_CurrentState->GetName()<<" to State "<<tempNextState->GetName()<<std::endl;
            #endif

    //first following StateChange(or calling ExecuteOperation(tempNextStateOp)), then operation(action)
    m_CurrentState = tempNextState;
  }

  std::vector<Action*>::iterator actionIdIterator = tempTransition->GetActionBeginIterator();
  const std::vector<Action*>::iterator actionIdIteratorEnd = tempTransition->GetActionEndIterator();
  bool ok = true;

  while ( actionIdIterator != actionIdIteratorEnd )
  {
    if ( !ExecuteAction(*actionIdIterator, stateEvent) )
    {
      #ifdef INTERDEBUG
      itkWarningMacro( << "Warning: no action defind for " << *actionIdIterator << " in " << m_Type );
      #endif

      ok = false;
    }
    actionIdIterator++;
  }
  return ok;
}

//##ModelId=3EDCAECB0175
void mitk::StateMachine::EnableUndo(bool enable)
{
	m_UndoEnabled = enable;
}

//##ModelId=3EF099EA03C0
void mitk::StateMachine::IncCurrGroupEventId()
{
	mitk::OperationEvent::IncCurrGroupEventId();
}

void mitk::StateMachine::ExecuteOperation(Operation* operation)
{
	switch (operation->GetOperationType())
	{
	case OpNOTHING:
		break;
	case OpSTATECHANGE:
		{
			mitk::StateTransitionOperation* stateTransOp = dynamic_cast<mitk::StateTransitionOperation *>(operation);
			if (stateTransOp == NULL)
			{
				itkWarningMacro("Error! see mitkStateMachine.cpp");
				return;
			}
#ifdef INTERDEBUG
//Debug StateChanges through cout output! Thus very slow!
std::cout<<this->GetType()<<": Undo: Changing from StateId "<<m_CurrentState->GetId()<<" to StateId "<<stateTransOp->GetState()->GetId()<<std::endl;
std::cout<<this->GetType()<<": Undo: Changing from State "<<m_CurrentState->GetName()<<" to State "<<stateTransOp->GetState()->GetName()<<std::endl;
#endif
			m_CurrentState = stateTransOp->GetState();
		}
		break;
  case OpDELETE:
    {
      //delete this!
      //before all lower statemachines has to be deleted in a action
      //this->Delete();//might not work!!!check itk!
    }
  case OpUNDELETE:
    {
      //this is just new! and now the m_CurrentState has to be set on a special State
      //that way a delete of a StateMachine can be undone
      //IMPORTANT: The type has to be the same!!!Done by a higher instance, that creates this!
      mitk::StateTransitionOperation* stateTransOp = dynamic_cast<mitk::StateTransitionOperation *>(operation);
			if (stateTransOp != NULL)
      {
        m_CurrentState = stateTransOp->GetState();
      }
    }
	default:
		;
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: PlottingPositionHelper.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: bm $ $Date: 2004-01-26 09:13:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CHART2_PLOTTINGPOSITIONHELPER_HXX
#define _CHART2_PLOTTINGPOSITIONHELPER_HXX

#include "DoubleRectangle.hxx"

#ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_
#include <com/sun/star/chart2/ExplicitScaleData.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_
#include <com/sun/star/chart2/XTransformation.hpp>
#endif

#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_
#include <com/sun/star/drawing/HomogenMatrix.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONSHAPE3D_HPP_
#include <com/sun/star/drawing/PolyPolygonShape3D.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_
#include <com/sun/star/drawing/Position3D.hpp>
#endif

#ifndef _B3D_HMATRIX_HXX
#include <goodies/hmatrix.hxx>
#endif
/*
//for WeakImplHelper1
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
*/
//.............................................................................
namespace chart
{
//.............................................................................

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

class PlottingPositionHelper
{
public:
    PlottingPositionHelper();
    virtual ~PlottingPositionHelper();

    void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix);

    void setScales( const ::com::sun::star::uno::Sequence<
            ::com::sun::star::chart2::ExplicitScaleData >& rScales );
    const ::com::sun::star::uno::Sequence<
            ::com::sun::star::chart2::ExplicitScaleData >& getScales() const;

    inline bool   isLogicVisible( double fX, double fY, double fZ ) const;
    inline void   doLogicScaling( double* pX, double* pY, double* pZ ) const;
    inline void   clipLogicValues( double* pX, double* pY, double* pZ ) const;

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >
                  getTransformationLogicToScene() const;

    virtual ::com::sun::star::drawing::Position3D
            transformLogicToScene( double fX, double fY, double fZ, bool bClip ) const;

    void    transformScaledLogicToScene( ::com::sun::star::drawing::PolyPolygonShape3D& rPoly ) const;

    inline double getLogicMinX() const;
    inline double getLogicMinY() const;
    inline double getLogicMinZ() const;
    inline double getLogicMaxX() const;
    inline double getLogicMaxY() const;
    inline double getLogicMaxZ() const;

    inline bool isMathematicalOrientationX() const;
    inline bool isMathematicalOrientationY() const;
    inline bool isMathematicalOrientationZ() const;

    DoubleRectangle     getScaledLogicClipDoubleRect() const;

protected: //member
    ::com::sun::star::uno::Sequence<
            ::com::sun::star::chart2::ExplicitScaleData > m_aScales;
    Matrix4D                                                      m_aMatrixScreenToScene;

    //this is calculated based on m_aScales and m_aMatrixScreenToScene
    mutable ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XTransformation >     m_xTransformationLogicToScene;
};

class PolarPlottingPositionHelper : public PlottingPositionHelper
    /*
                                  , public ::cppu::WeakImplHelper1<
                                ::com::sun::star::chart2::XTransformation >
                                */
{
public:
    PolarPlottingPositionHelper( bool bRadiusAxisMapsToFirstDimension );
    virtual ~PolarPlottingPositionHelper();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >
                  getTransformationLogicToScene() const;

    //the resulting values should be used for input to the transformation
    //received with 'getTransformationLogicToScene'
    double  transformToRadius( double fLogicValueOnRadiusAxis ) const;
    double  transformToAngleDegree( double fLogicValueOnAngleAxis ) const;
    double  getWidthAngleDegree( double& fStartLogicValueOnAngleAxis, double& fEndLogicValueOnAngleAxis ) const;
    //

    virtual ::com::sun::star::drawing::Position3D
            transformLogicToScene( double fX, double fY, double fZ, bool bClip ) const;
    ::com::sun::star::drawing::Position3D
            transformLogicToScene( double fLogicValueOnAngleAxis, double fLogicValueOnRadiusAxis, double fLogicZ ) const;

    double  getInnerLogicRadius() const;
    double  getOuterLogicRadius() const;

    /*
    // ____ XTransformation ____
    /// @see ::com::sun::star::chart2::XTransformation
    virtual ::com::sun::star::uno::Sequence< double > SAL_CALL transform(
        const ::com::sun::star::uno::Sequence< double >& rSourceValues )
        throw (::com::sun::star::lang::IllegalArgumentException,
               ::com::sun::star::uno::RuntimeException);
    /// @see ::com::sun::star::chart2::XTransformation
    virtual sal_Int32 SAL_CALL getSourceDimension()
        throw (::com::sun::star::uno::RuntimeException);
    /// @see ::com::sun::star::chart2::XTransformation
    virtual sal_Int32 SAL_CALL getTargetDimension()
        throw (::com::sun::star::uno::RuntimeException);
        */
public:
    //Offset for radius axis in absolute logic scaled values (1.0 == 1 category)
    double      m_fRadiusOffset;
    //Offset for angle axis in real degree
    double      m_fAngleDegreeOffset;

private:
    PolarPlottingPositionHelper();
    bool m_bRadiusAxisMapsToFirstDimension;
};

bool PlottingPositionHelper::isLogicVisible(
    double fX, double fY, double fZ ) const
{
    return fX >= m_aScales[0].Minimum && fX <= m_aScales[0].Maximum
        && fY >= m_aScales[1].Minimum && fY <= m_aScales[1].Maximum
        && fZ >= m_aScales[2].Minimum && fZ <= m_aScales[2].Maximum;
}

void PlottingPositionHelper::doLogicScaling( double* pX, double* pY, double* pZ ) const
{
    if(pX && m_aScales[0].Scaling.is())
        *pX = m_aScales[0].Scaling->doScaling(*pX);
    if(pY && m_aScales[1].Scaling.is())
        *pY = m_aScales[1].Scaling->doScaling(*pY);
    if(pZ && m_aScales[2].Scaling.is())
        *pZ = m_aScales[2].Scaling->doScaling(*pZ);
}

void PlottingPositionHelper::clipLogicValues( double* pX, double* pY, double* pZ ) const
{
    if(pX)
    {
        if( *pX < m_aScales[0].Minimum )
            *pX = m_aScales[0].Minimum;
        else if( *pX > m_aScales[0].Maximum )
            *pX = m_aScales[0].Maximum;
    }
    if(pY)
    {
        if( *pY < m_aScales[1].Minimum )
            *pY = m_aScales[1].Minimum;
        else if( *pY > m_aScales[1].Maximum )
            *pY = m_aScales[1].Maximum;
    }
    if(pZ)
    {
        if( *pZ < m_aScales[2].Minimum )
            *pZ = m_aScales[2].Minimum;
        else if( *pZ > m_aScales[2].Maximum )
            *pZ = m_aScales[2].Maximum;
    }
}

inline double PlottingPositionHelper::getLogicMinX() const
{
    return m_aScales[0].Minimum;
}
inline double PlottingPositionHelper::getLogicMinY() const
{
    return m_aScales[1].Minimum;
}
inline double PlottingPositionHelper::getLogicMinZ() const
{
    return m_aScales[2].Minimum;
}

inline double PlottingPositionHelper::getLogicMaxX() const
{
    return m_aScales[0].Maximum;
}
inline double PlottingPositionHelper::getLogicMaxY() const
{
    return m_aScales[1].Maximum;
}
inline double PlottingPositionHelper::getLogicMaxZ() const
{
    return m_aScales[2].Maximum;
}
inline bool PlottingPositionHelper::isMathematicalOrientationX() const
{
    return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[0].Orientation;
}
inline bool PlottingPositionHelper::isMathematicalOrientationY() const
{
    return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[1].Orientation;
}
inline bool PlottingPositionHelper::isMathematicalOrientationZ() const
{
    return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[2].Orientation;
}

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.110); FILE MERGED 2005/09/05 18:43:47 rt 1.7.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PlottingPositionHelper.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 01:43:50 $
 *
 *  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_PLOTTINGPOSITIONHELPER_HXX
#define _CHART2_PLOTTINGPOSITIONHELPER_HXX

#include "DoubleRectangle.hxx"

#ifndef _COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_
#include <com/sun/star/chart2/ExplicitScaleData.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_
#include <com/sun/star/chart2/XTransformation.hpp>
#endif

#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_
#include <com/sun/star/drawing/HomogenMatrix.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONSHAPE3D_HPP_
#include <com/sun/star/drawing/PolyPolygonShape3D.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_
#include <com/sun/star/drawing/Position3D.hpp>
#endif

#ifndef _B3D_HMATRIX_HXX
#include <goodies/hmatrix.hxx>
#endif
/*
//for WeakImplHelper1
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
*/
//.............................................................................
namespace chart
{
//.............................................................................

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

class PlottingPositionHelper
{
public:
    PlottingPositionHelper();
    virtual ~PlottingPositionHelper();

    void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix);

    void setScales( const ::com::sun::star::uno::Sequence<
            ::com::sun::star::chart2::ExplicitScaleData >& rScales );
    const ::com::sun::star::uno::Sequence<
            ::com::sun::star::chart2::ExplicitScaleData >& getScales() const;

    inline bool   isLogicVisible( double fX, double fY, double fZ ) const;
    inline void   doLogicScaling( double* pX, double* pY, double* pZ ) const;
    inline void   clipLogicValues( double* pX, double* pY, double* pZ ) const;

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >
                  getTransformationLogicToScene() const;

    virtual ::com::sun::star::drawing::Position3D
            transformLogicToScene( double fX, double fY, double fZ, bool bClip ) const;

    void    transformScaledLogicToScene( ::com::sun::star::drawing::PolyPolygonShape3D& rPoly ) const;

    inline double getLogicMinX() const;
    inline double getLogicMinY() const;
    inline double getLogicMinZ() const;
    inline double getLogicMaxX() const;
    inline double getLogicMaxY() const;
    inline double getLogicMaxZ() const;

    inline bool isMathematicalOrientationX() const;
    inline bool isMathematicalOrientationY() const;
    inline bool isMathematicalOrientationZ() const;

    DoubleRectangle     getScaledLogicClipDoubleRect() const;

protected: //member
    ::com::sun::star::uno::Sequence<
            ::com::sun::star::chart2::ExplicitScaleData > m_aScales;
    Matrix4D                                                      m_aMatrixScreenToScene;

    //this is calculated based on m_aScales and m_aMatrixScreenToScene
    mutable ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XTransformation >     m_xTransformationLogicToScene;
};

class PolarPlottingPositionHelper : public PlottingPositionHelper
    /*
                                  , public ::cppu::WeakImplHelper1<
                                ::com::sun::star::chart2::XTransformation >
                                */
{
public:
    PolarPlottingPositionHelper( bool bRadiusAxisMapsToFirstDimension );
    virtual ~PolarPlottingPositionHelper();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XTransformation >
                  getTransformationLogicToScene() const;

    //the resulting values should be used for input to the transformation
    //received with 'getTransformationLogicToScene'
    double  transformToRadius( double fLogicValueOnRadiusAxis ) const;
    double  transformToAngleDegree( double fLogicValueOnAngleAxis ) const;
    double  getWidthAngleDegree( double& fStartLogicValueOnAngleAxis, double& fEndLogicValueOnAngleAxis ) const;
    //

    virtual ::com::sun::star::drawing::Position3D
            transformLogicToScene( double fX, double fY, double fZ, bool bClip ) const;
    ::com::sun::star::drawing::Position3D
            transformLogicToScene( double fLogicValueOnAngleAxis, double fLogicValueOnRadiusAxis, double fLogicZ ) const;

    double  getInnerLogicRadius() const;
    double  getOuterLogicRadius() const;

    /*
    // ____ XTransformation ____
    /// @see ::com::sun::star::chart2::XTransformation
    virtual ::com::sun::star::uno::Sequence< double > SAL_CALL transform(
        const ::com::sun::star::uno::Sequence< double >& rSourceValues )
        throw (::com::sun::star::lang::IllegalArgumentException,
               ::com::sun::star::uno::RuntimeException);
    /// @see ::com::sun::star::chart2::XTransformation
    virtual sal_Int32 SAL_CALL getSourceDimension()
        throw (::com::sun::star::uno::RuntimeException);
    /// @see ::com::sun::star::chart2::XTransformation
    virtual sal_Int32 SAL_CALL getTargetDimension()
        throw (::com::sun::star::uno::RuntimeException);
        */
public:
    //Offset for radius axis in absolute logic scaled values (1.0 == 1 category)
    double      m_fRadiusOffset;
    //Offset for angle axis in real degree
    double      m_fAngleDegreeOffset;

private:
    PolarPlottingPositionHelper();
    bool m_bRadiusAxisMapsToFirstDimension;
};

bool PlottingPositionHelper::isLogicVisible(
    double fX, double fY, double fZ ) const
{
    return fX >= m_aScales[0].Minimum && fX <= m_aScales[0].Maximum
        && fY >= m_aScales[1].Minimum && fY <= m_aScales[1].Maximum
        && fZ >= m_aScales[2].Minimum && fZ <= m_aScales[2].Maximum;
}

void PlottingPositionHelper::doLogicScaling( double* pX, double* pY, double* pZ ) const
{
    if(pX && m_aScales[0].Scaling.is())
        *pX = m_aScales[0].Scaling->doScaling(*pX);
    if(pY && m_aScales[1].Scaling.is())
        *pY = m_aScales[1].Scaling->doScaling(*pY);
    if(pZ && m_aScales[2].Scaling.is())
        *pZ = m_aScales[2].Scaling->doScaling(*pZ);
}

void PlottingPositionHelper::clipLogicValues( double* pX, double* pY, double* pZ ) const
{
    if(pX)
    {
        if( *pX < m_aScales[0].Minimum )
            *pX = m_aScales[0].Minimum;
        else if( *pX > m_aScales[0].Maximum )
            *pX = m_aScales[0].Maximum;
    }
    if(pY)
    {
        if( *pY < m_aScales[1].Minimum )
            *pY = m_aScales[1].Minimum;
        else if( *pY > m_aScales[1].Maximum )
            *pY = m_aScales[1].Maximum;
    }
    if(pZ)
    {
        if( *pZ < m_aScales[2].Minimum )
            *pZ = m_aScales[2].Minimum;
        else if( *pZ > m_aScales[2].Maximum )
            *pZ = m_aScales[2].Maximum;
    }
}

inline double PlottingPositionHelper::getLogicMinX() const
{
    return m_aScales[0].Minimum;
}
inline double PlottingPositionHelper::getLogicMinY() const
{
    return m_aScales[1].Minimum;
}
inline double PlottingPositionHelper::getLogicMinZ() const
{
    return m_aScales[2].Minimum;
}

inline double PlottingPositionHelper::getLogicMaxX() const
{
    return m_aScales[0].Maximum;
}
inline double PlottingPositionHelper::getLogicMaxY() const
{
    return m_aScales[1].Maximum;
}
inline double PlottingPositionHelper::getLogicMaxZ() const
{
    return m_aScales[2].Maximum;
}
inline bool PlottingPositionHelper::isMathematicalOrientationX() const
{
    return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[0].Orientation;
}
inline bool PlottingPositionHelper::isMathematicalOrientationY() const
{
    return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[1].Orientation;
}
inline bool PlottingPositionHelper::isMathematicalOrientationZ() const
{
    return ::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[2].Orientation;
}

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


<commit_before>/*
 * This file is part of signon
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com>
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "signondaemonadaptor.h"
#include "accesscontrolmanager.h"

namespace SignonDaemonNS {

    SignonDaemonAdaptor::SignonDaemonAdaptor(SignonDaemon *parent)
        : QDBusAbstractAdaptor(parent),
          m_parent(parent)
    {
        setAutoRelaySignals(false);
    }

    SignonDaemonAdaptor::~SignonDaemonAdaptor()
    {}

    bool SignonDaemonAdaptor::initSecureStorage(const QByteArray &lockCode)
    {
        return m_parent->initSecureStorage(lockCode);
    }

    void SignonDaemonAdaptor::registerNewIdentity(QDBusObjectPath &objectPath)
    {
        m_parent->registerNewIdentity(objectPath);
    }

    void SignonDaemonAdaptor::securityErrorReply(const char *failedMethodName)
    {
        QString errMsg;
        QTextStream(&errMsg) << SSO_DAEMON_PERMISSION_DENIED_ERR_STR
                             << "Method:"
                             << failedMethodName;

        QDBusMessage errReply =
                    parentDBusContext().message().createErrorReply(
                                            SSO_DAEMON_PERMISSION_DENIED_ERR_NAME,
                                            errMsg);
        SIGNON_BUS.send(errReply);
        TRACE() << "\nMethod FAILED Access Control check:\n" << failedMethodName;
    }

    void SignonDaemonAdaptor::registerStoredIdentity(const quint32 id, QDBusObjectPath &objectPath, QList<QVariant> &identityData)
    {
        if (!AccessControlManager::isPeerAllowedToUseIdentity(
                                        parentDBusContext(), id)) {
            securityErrorReply(__func__);
            return;
        }

        m_parent->registerStoredIdentity(id, objectPath, identityData);
    }

    QStringList SignonDaemonAdaptor::queryMethods()
    {
        return m_parent->queryMethods();
    }

    QString SignonDaemonAdaptor::getAuthSessionObjectPath(const quint32 id, const QString &type)
    {
        /* Access Control */
        if (id != SSO_NEW_IDENTITY) {
            if (!AccessControlManager::isPeerAllowedToUseAuthSession(
                                            parentDBusContext(), id)) {
                securityErrorReply(__func__);
                return QString();
            }
        }

        return m_parent->getAuthSessionObjectPath(id, type);
    }

    QStringList SignonDaemonAdaptor::queryMechanisms(const QString &method)
    {
        return m_parent->queryMechanisms(method);
    }

    QList<QVariant> SignonDaemonAdaptor::queryIdentities(const QMap<QString, QVariant> &filter)
    {
        /* Access Control */
        if (!AccessControlManager::isPeerKeychainWidget(parentDBusContext())) {
            securityErrorReply(__func__);
            return QList<QVariant>();
        }

        return m_parent->queryIdentities(filter);
    }

    bool SignonDaemonAdaptor::clear()
    {
        /* Access Control */
        if (!AccessControlManager::isPeerKeychainWidget(parentDBusContext())) {
            securityErrorReply(__func__);
            return false;
        }

        return m_parent->clear();
    }

    bool SignonDaemonAdaptor::setDeviceLockCode(const QByteArray &oldLockCode,
                                                const QByteArray &newLockCode)
    {
        /* TODO - this should be access controlled, too. Have to identify the
                  caller process/es. */
        return m_parent->setDeviceLockCode(oldLockCode, newLockCode);
    }

    bool SignonDaemonAdaptor::setSim(const QByteArray &simData,
                                     const QByteArray &checkData)
    {
        /* TODO - this should be access controlled, too. Have to identify the
                  caller process/es. */
        return m_parent->setSim(simData, checkData);
    }

    bool SignonDaemonAdaptor::remoteLock(const QByteArray &lockCode)
    {
        /* TODO - this should be access controlled, too. Have to identify the
                  caller process/es. */
        return m_parent->remoteLock(lockCode);
    }

} //namespace SignonDaemonNS
<commit_msg>Check for disposable object in a few occasions<commit_after>/*
 * This file is part of signon
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com>
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "signondaemonadaptor.h"
#include "signondisposable.h"
#include "accesscontrolmanager.h"

namespace SignonDaemonNS {

    SignonDaemonAdaptor::SignonDaemonAdaptor(SignonDaemon *parent)
        : QDBusAbstractAdaptor(parent),
          m_parent(parent)
    {
        setAutoRelaySignals(false);
    }

    SignonDaemonAdaptor::~SignonDaemonAdaptor()
    {}

    bool SignonDaemonAdaptor::initSecureStorage(const QByteArray &lockCode)
    {
        return m_parent->initSecureStorage(lockCode);
    }

    void SignonDaemonAdaptor::registerNewIdentity(QDBusObjectPath &objectPath)
    {
        SignonDisposable::destroyUnused();

        m_parent->registerNewIdentity(objectPath);
    }

    void SignonDaemonAdaptor::securityErrorReply(const char *failedMethodName)
    {
        QString errMsg;
        QTextStream(&errMsg) << SSO_DAEMON_PERMISSION_DENIED_ERR_STR
                             << "Method:"
                             << failedMethodName;

        QDBusMessage errReply =
                    parentDBusContext().message().createErrorReply(
                                            SSO_DAEMON_PERMISSION_DENIED_ERR_NAME,
                                            errMsg);
        SIGNON_BUS.send(errReply);
        TRACE() << "\nMethod FAILED Access Control check:\n" << failedMethodName;
    }

    void SignonDaemonAdaptor::registerStoredIdentity(const quint32 id, QDBusObjectPath &objectPath, QList<QVariant> &identityData)
    {
        SignonDisposable::destroyUnused();

        if (!AccessControlManager::isPeerAllowedToUseIdentity(
                                        parentDBusContext(), id)) {
            securityErrorReply(__func__);
            return;
        }

        m_parent->registerStoredIdentity(id, objectPath, identityData);
    }

    QStringList SignonDaemonAdaptor::queryMethods()
    {
        return m_parent->queryMethods();
    }

    QString SignonDaemonAdaptor::getAuthSessionObjectPath(const quint32 id, const QString &type)
    {
        SignonDisposable::destroyUnused();

        /* Access Control */
        if (id != SSO_NEW_IDENTITY) {
            if (!AccessControlManager::isPeerAllowedToUseAuthSession(
                                            parentDBusContext(), id)) {
                securityErrorReply(__func__);
                return QString();
            }
        }

        return m_parent->getAuthSessionObjectPath(id, type);
    }

    QStringList SignonDaemonAdaptor::queryMechanisms(const QString &method)
    {
        return m_parent->queryMechanisms(method);
    }

    QList<QVariant> SignonDaemonAdaptor::queryIdentities(const QMap<QString, QVariant> &filter)
    {
        /* Access Control */
        if (!AccessControlManager::isPeerKeychainWidget(parentDBusContext())) {
            securityErrorReply(__func__);
            return QList<QVariant>();
        }

        return m_parent->queryIdentities(filter);
    }

    bool SignonDaemonAdaptor::clear()
    {
        /* Access Control */
        if (!AccessControlManager::isPeerKeychainWidget(parentDBusContext())) {
            securityErrorReply(__func__);
            return false;
        }

        return m_parent->clear();
    }

    bool SignonDaemonAdaptor::setDeviceLockCode(const QByteArray &oldLockCode,
                                                const QByteArray &newLockCode)
    {
        /* TODO - this should be access controlled, too. Have to identify the
                  caller process/es. */
        return m_parent->setDeviceLockCode(oldLockCode, newLockCode);
    }

    bool SignonDaemonAdaptor::setSim(const QByteArray &simData,
                                     const QByteArray &checkData)
    {
        /* TODO - this should be access controlled, too. Have to identify the
                  caller process/es. */
        return m_parent->setSim(simData, checkData);
    }

    bool SignonDaemonAdaptor::remoteLock(const QByteArray &lockCode)
    {
        /* TODO - this should be access controlled, too. Have to identify the
                  caller process/es. */
        return m_parent->remoteLock(lockCode);
    }

} //namespace SignonDaemonNS
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

void build_tree_from_preorder_inorder(string pre, string in) {
    int in_root_index = in.find(pre[0]);

    if (in.substr(0, in_root_index).length() > 0) {
        build_tree_from_preorder_inorder(
            pre.substr(1),
            in.substr(0, in_root_index));
    }
    if (in.substr(in_root_index + 1).length() > 0) {
        build_tree_from_preorder_inorder(
            pre.substr(in_root_index + 1),
            in.substr(in_root_index + 1));
    }

    cout << pre[0];
}

int main() {
    string pre, in;

    while (cin >> pre >> in) {
        build_tree_from_preorder_inorder(pre, in);
        cout << endl;
    }

    return 0;
}
<commit_msg>Renomeia função de contrução da árvore.<commit_after>#include <iostream>

using namespace std;

void postorder_print_from_preorder_inorder(string pre, string in) {
    int in_root_index = in.find(pre[0]);

    if (in.substr(0, in_root_index).length() > 0) {
        postorder_print_from_preorder_inorder(
            pre.substr(1),
            in.substr(0, in_root_index));
    }
    if (in.substr(in_root_index + 1).length() > 0) {
        postorder_print_from_preorder_inorder(
            pre.substr(in_root_index + 1),
            in.substr(in_root_index + 1));
    }

    cout << pre[0];
}

int main() {
    string pre, in;

    while (cin >> pre >> in) {
        postorder_print_from_preorder_inorder(pre, in);
        cout << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2017, Andrej Kislovskij
 *
 * This is PUBLIC DOMAIN software so use at your own risk as it comes
 * with no warranties. This code is yours to share, use and modify without
 * any restrictions or obligations.
 *
 * For more information see conwrap/LICENSE or refer refer to http://unlicense.org
 *
 * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)
 */

#pragma once

#include <conwrap2/ProcessorProxy.hpp>
#include <functional>
#include <memory>
#include <sstream>  // std::stringstream
#include <string>
#include <type_safe/optional.hpp>

#include "slim/Chunk.hpp"
#include "slim/EncoderBase.hpp"
#include "slim/EncoderBuilder.hpp"
#include "slim/log/log.hpp"
#include "slim/util/BigInteger.hpp"
#include "slim/util/BufferedAsyncWriter.hpp"

namespace slim
{
	namespace proto
	{
		namespace ts = type_safe;

		template<typename ConnectionType>
		class StreamingSession
		{
			public:
				StreamingSession(conwrap2::ProcessorProxy<std::unique_ptr<ContainerBase>> pp, std::reference_wrapper<ConnectionType> co, std::string id, EncoderBuilder eb)
				: processorProxy{pp}
				, connection{co}
				, clientID{id}
				, bufferedWriter{co}
				{
					LOG(DEBUG) << LABELS{"proto"} << "HTTP session object was created (id=" << this << ")";

					eb.setEncodedCallback([&](auto* data, auto size)
					{
						// do not feed writer with more data if there is no room in transfer buffer
						if (bufferedWriter.isBufferAvailable())
						{
							bufferedWriter.writeAsync(data, size, [](auto error, auto written) {});
						}
						else
						{
							LOG(WARNING) << LABELS{"proto"} << "Transfer buffer is full - skipping encoded chunk";
						}
					});
					encoderPtr = std::move(eb.build());
					encoderPtr->start();

					// creating response string
					std::stringstream ss;
					ss << "HTTP/1.1 200 OK\r\n"
					   << "Server: SlimStreamer ("
					   // TODO: provide version to the constructor
					   << VERSION
					   << ")\r\n"
					   << "Connection: close\r\n"
					   << "Content-Type: " << encoderPtr->getMIME() << "\r\n"
					   << "\r\n";

					// sending response string
					connection.get().write(ss.str());
				}

				~StreamingSession()
				{
					// canceling deferred operation
					ts::with(timer, [&](auto& timer)
					{
						timer.cancel();
					});

					LOG(DEBUG) << LABELS{"proto"} << "HTTP session object was deleted (id=" << this << ")";
				}

				StreamingSession(const StreamingSession&) = delete;             // non-copyable
				StreamingSession& operator=(const StreamingSession&) = delete;  // non-assignable
				StreamingSession(StreamingSession&& rhs) = delete;              // non-movable
				StreamingSession& operator=(StreamingSession&& rhs) = delete;   // non-movable-assignable

				inline auto getClientID()
				{
					return clientID;
				}

				inline auto getFramesProvided()
				{
					return framesProvided;
				}

				inline bool isRunning()
				{
					return running;
				}

				inline void onRequest(unsigned char* data, std::size_t size)
				{
					// TODO: make more strick validation
					std::string get{"GET"};
					std::string s{(char*)data, get.size()};
					if (get.compare(s))
					{
						// stopping this session due an error
						LOG(WARNING) << LABELS{"proto"} << "Wrong HTTP method provided";
						stop([] {});
					}
				}

				static auto parseClientID(std::string header)
				{
					auto result{ts::optional<std::string>{ts::nullopt}};
					auto separator{std::string{"="}};
					auto index{header.find(separator)};

					if (index != std::string::npos)
					{
						result = std::string{header.c_str() + index + separator.length(), header.length() - index - separator.length()};
					}

					return result;
				}

				inline void start()
				{
					running = true;
				}

				template <typename CallbackType>
				inline void stop(CallbackType callback)
				{
					if (running)
					{
						encoderPtr->stop([&, callback = std::move(callback)]
						{
							flush([&, callback = std::move(callback)]
							{
								running = false;
								callback();
							});
						});
					}
					else
					{
						callback();
					}
				}

				inline void streamChunk(const Chunk& chunk)
				{
					if (chunk.getSamplingRate() == encoderPtr->getSamplingRate())
					{
						encoderPtr->encode(chunk.getData(), chunk.getSize());
						framesProvided += chunk.getFrames();

						if (chunk.isEndOfStream())
						{
							// stopping this session
							stop([] {});
						}
					}
					else
					{
						LOG(ERROR) << LABELS{"proto"} << "Closing HTTP connection due to different sampling rate used by a client (session rate=" << encoderPtr->getSamplingRate() << "; data rate=" << chunk.getSamplingRate() << ")";

						// stopping this session
						stop([] {});
					}
				}

			protected:
				template <typename CallbackType>
				void flush(CallbackType callback)
				{
					if (bufferedWriter.isBufferAvailable())
					{
						// submitting an 'empty' chunk so that a callback gets invoked when all data has been transferred
						bufferedWriter.writeAsync(nullptr, 0, [callback = std::move(callback)](auto error, auto written)
						{
							callback();
						});
					}
					else
					{
						// waiting until data is transferred so a new 'empty' chunk can be submitted
						timer = ts::ref(processorProxy.processWithDelay([&, callback = std::move(callback)]
						{
							flush(std::move(callback));
						}, std::chrono::milliseconds{1}));
					}
				}

			private:
				conwrap2::ProcessorProxy<std::unique_ptr<ContainerBase>> processorProxy;
				std::reference_wrapper<ConnectionType>                   connection;
				std::string                                              clientID;
				// TODO: parameterize
				util::BufferedAsyncWriter<ConnectionType, 128>           bufferedWriter;
				std::unique_ptr<EncoderBase>                             encoderPtr;
				// TODO: implement more guards based on running
				bool                                                     running{false};
				ts::optional_ref<conwrap2::Timer>                        timer{ts::nullopt};
				util::BigInteger                                         framesProvided{0};
		};
	}
}
<commit_msg>Fixed a bug with End-of-Stream processing<commit_after>/*
 * Copyright 2017, Andrej Kislovskij
 *
 * This is PUBLIC DOMAIN software so use at your own risk as it comes
 * with no warranties. This code is yours to share, use and modify without
 * any restrictions or obligations.
 *
 * For more information see conwrap/LICENSE or refer refer to http://unlicense.org
 *
 * Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)
 */

#pragma once

#include <conwrap2/ProcessorProxy.hpp>
#include <functional>
#include <memory>
#include <sstream>  // std::stringstream
#include <string>
#include <type_safe/optional.hpp>

#include "slim/Chunk.hpp"
#include "slim/EncoderBase.hpp"
#include "slim/EncoderBuilder.hpp"
#include "slim/log/log.hpp"
#include "slim/util/BigInteger.hpp"
#include "slim/util/BufferedAsyncWriter.hpp"

namespace slim
{
	namespace proto
	{
		namespace ts = type_safe;

		template<typename ConnectionType>
		class StreamingSession
		{
			public:
				StreamingSession(conwrap2::ProcessorProxy<std::unique_ptr<ContainerBase>> pp, std::reference_wrapper<ConnectionType> co, std::string id, EncoderBuilder eb)
				: processorProxy{pp}
				, connection{co}
				, clientID{id}
				, bufferedWriter{co}
				{
					LOG(DEBUG) << LABELS{"proto"} << "HTTP session object was created (id=" << this << ")";

					eb.setEncodedCallback([&](auto* data, auto size)
					{
						// do not feed writer with more data if there is no room in transfer buffer
						if (bufferedWriter.isBufferAvailable())
						{
							bufferedWriter.writeAsync(data, size, [](auto error, auto written) {});
						}
						else
						{
							LOG(WARNING) << LABELS{"proto"} << "Transfer buffer is full - skipping encoded chunk";
						}
					});
					encoderPtr = std::move(eb.build());
					encoderPtr->start();

					// creating response string
					std::stringstream ss;
					ss << "HTTP/1.1 200 OK\r\n"
					   << "Server: SlimStreamer ("
					   // TODO: provide version to the constructor
					   << VERSION
					   << ")\r\n"
					   << "Connection: close\r\n"
					   << "Content-Type: " << encoderPtr->getMIME() << "\r\n"
					   << "\r\n";

					// sending response string
					connection.get().write(ss.str());
				}

				~StreamingSession()
				{
					// canceling deferred operation
					ts::with(timer, [&](auto& timer)
					{
						timer.cancel();
					});

					LOG(DEBUG) << LABELS{"proto"} << "HTTP session object was deleted (id=" << this << ")";
				}

				StreamingSession(const StreamingSession&) = delete;             // non-copyable
				StreamingSession& operator=(const StreamingSession&) = delete;  // non-assignable
				StreamingSession(StreamingSession&& rhs) = delete;              // non-movable
				StreamingSession& operator=(StreamingSession&& rhs) = delete;   // non-movable-assignable

				inline auto getClientID()
				{
					return clientID;
				}

				inline auto getFramesProvided()
				{
					return framesProvided;
				}

				inline bool isRunning()
				{
					return running;
				}

				inline void onRequest(unsigned char* data, std::size_t size)
				{
					// TODO: make more strick validation
					std::string get{"GET"};
					std::string s{(char*)data, get.size()};
					if (get.compare(s))
					{
						// stopping this session due an error
						LOG(WARNING) << LABELS{"proto"} << "Wrong HTTP method provided";
						stop([] {});
					}
				}

				static auto parseClientID(std::string header)
				{
					auto result{ts::optional<std::string>{ts::nullopt}};
					auto separator{std::string{"="}};
					auto index{header.find(separator)};

					if (index != std::string::npos)
					{
						result = std::string{header.c_str() + index + separator.length(), header.length() - index - separator.length()};
					}

					return result;
				}

				inline void start()
				{
					running = true;
				}

				template <typename CallbackType>
				inline void stop(CallbackType callback)
				{
					if (running)
					{
						encoderPtr->stop([&, callback = std::move(callback)]
						{
							flush([&, callback = std::move(callback)]
							{
								running = false;
								callback();
							});
						});
					}
					else
					{
						callback();
					}
				}

				inline void streamChunk(const Chunk& chunk)
				{
					if (chunk.getSamplingRate() == encoderPtr->getSamplingRate())
					{
						encoderPtr->encode(chunk.getData(), chunk.getSize());
						framesProvided += chunk.getFrames();

						if (chunk.isEndOfStream())
						{
							// stopping this session
							stop([&]
							{
								connection.get().stop();
							});
						}
					}
					else
					{
						LOG(ERROR) << LABELS{"proto"} << "Closing HTTP connection due to different sampling rate used by a client (session rate=" << encoderPtr->getSamplingRate() << "; data rate=" << chunk.getSamplingRate() << ")";

						// stopping this session
						stop([&]
						{
							connection.get().stop();
						});
					}
				}

			protected:
				template <typename CallbackType>
				void flush(CallbackType callback)
				{
					if (bufferedWriter.isBufferAvailable())
					{
						// submitting an 'empty' chunk so that a callback gets invoked when all data has been transferred
						bufferedWriter.writeAsync(nullptr, 0, [callback = std::move(callback)](auto error, auto written)
						{
							callback();
						});
					}
					else
					{
						// waiting until data is transferred so a new 'empty' chunk can be submitted
						timer = ts::ref(processorProxy.processWithDelay([&, callback = std::move(callback)]
						{
							flush(std::move(callback));
						}, std::chrono::milliseconds{1}));
					}
				}

			private:
				conwrap2::ProcessorProxy<std::unique_ptr<ContainerBase>> processorProxy;
				std::reference_wrapper<ConnectionType>                   connection;
				std::string                                              clientID;
				// TODO: parameterize
				util::BufferedAsyncWriter<ConnectionType, 128>           bufferedWriter;
				std::unique_ptr<EncoderBase>                             encoderPtr;
				// TODO: implement more guards based on running
				bool                                                     running{false};
				ts::optional_ref<conwrap2::Timer>                        timer{ts::nullopt};
				util::BigInteger                                         framesProvided{0};
		};
	}
}
<|endoftext|>