diff --git a/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.h b/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.h index f94865e..70a73c2 100644 --- a/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.h +++ b/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.h @@ -1,83 +1,83 @@ // ----------------------------------------------------------------------- // MatchPoint - DKFZ translational registration framework // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See mapCopyright.txt or // http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html // // 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. // //------------------------------------------------------------------------ /*! // @file // @version $Revision$ (last changed revision) // @date $Date$ (last change date) // @author $Author$ (last changed by) // Subversion HeadURL: $HeadURL$ */ #ifndef __MAP_ITK_RIGID_MMI_HEADNECK_REGISTRATION_ALGORITHM_H #define __MAP_ITK_RIGID_MMI_HEADNECK_REGISTRATION_ALGORITHM_H #include "mapITKEuler3DMattesMIMultiResRegistrationAlgorithmTemplate.h" namespace map { namespace algorithm { namespace boxed { /** \class MultiModalRigidHeadNeckRegistrationAlgorithm * \ingroup Data_image MetaProperty Model_rigid Det_comp_iterative Det_stochastic Det_res_multi Dim_3D_3D Mod_multi PreInit_Geo * Algorithm is used for special cases where a head image should be registered onto a head/neck image (target image). It skips the lower part of * the target image if a preinitialization (via geometric center or centroid) is used, to establish a better initialization. By default initializes via geometric centers. */ template >, class TPyramideInitializationPolicy = algorithm::itk::NoComponentInitializationPolicy> class MultiModalRigidHeadNeckRegistrationAlgorithm : public map::algorithm::boxed::ITKEuler3DMattesMIMultiResRegistrationAlgorithm { public: typedef MultiModalRigidHeadNeckRegistrationAlgorithm Self; - typedef typename ITKEuler3DMattesMIMultiResRegistrationAlgorithm + typedef ITKEuler3DMattesMIMultiResRegistrationAlgorithm Superclass; typedef ::itk::SmartPointer Pointer; typedef ::itk::SmartPointer ConstPointer; itkTypeMacro(MultiModalRigidHeadNeckRegistrationAlgorithm, ITKEuler3DMattesMIMultiResRegistrationAlgorithm); mapNewAlgorithmMacro(Self); protected: MultiModalRigidHeadNeckRegistrationAlgorithm(); virtual ~MultiModalRigidHeadNeckRegistrationAlgorithm(); void configureAlgorithm(); void doInterLevelSetup(); void prepInitializeTransformation(); private: MultiModalRigidHeadNeckRegistrationAlgorithm(const Self& source); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } } } #ifndef MatchPoint_MANUAL_TPP #include "mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.tpp" #endif #endif diff --git a/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.tpp b/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.tpp index 47a18ff..f448b2e 100644 --- a/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.tpp +++ b/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMIHeadNeckRegistrationAlgorithmTemplate.tpp @@ -1,174 +1,174 @@ // ----------------------------------------------------------------------- // MatchPoint - DKFZ translational registration framework // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See mapCopyright.txt or // http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html // // 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. // //------------------------------------------------------------------------ #ifndef __ITK_RIGID_3D_MATTESMI_HEADNECK_REGISTRATION_ALGORITHM_TPP #define __ITK_RIGID_3D_MATTESMI_HEADNECK_REGISTRATION_ALGORITHM_TPP #include "itkRegionOfInterestImageFilter.h" namespace map { namespace algorithm { namespace boxed { template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> MultiModalRigidHeadNeckRegistrationAlgorithm:: MultiModalRigidHeadNeckRegistrationAlgorithm() { }; template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> MultiModalRigidHeadNeckRegistrationAlgorithm:: ~MultiModalRigidHeadNeckRegistrationAlgorithm() { }; template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> void MultiModalRigidHeadNeckRegistrationAlgorithm:: configureAlgorithm() { Superclass::configureAlgorithm(); this->setResolutionLevels(3); this->_preInitialize = true; this->_useCenterOfGravity = false; //optimizer - ConcreteOptimizerType::ScalesType scales(6); + typename Superclass::ConcreteOptimizerType::ScalesType scales(6); scales[0] = 10.0; scales[1] = 10.0; scales[2] = 10.0; scales[3] = 1.0 / 10000; scales[4] = 1.0 / 10000; scales[5] = 1.0 / 10000; this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetScales(scales); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetMaximumStepLength(3.00); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetMinimumStepLength(0.5); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetNumberOfIterations(200); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetRelaxationFactor(0.8); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetGradientMagnitudeTolerance(1e-4); //metric this->getConcreteMetricControl()->getConcreteMetric()->SetNumberOfHistogramBins(30); this->getConcreteMetricControl()->getConcreteMetric()->SetUseAllPixels(true); this->getConcreteMetricControl()->getConcreteMetric()->ReinitializeSeed(); this->getConcreteMetricControl()->getConcreteMetric()->UseExplicitPDFDerivativesOn(); } template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> void MultiModalRigidHeadNeckRegistrationAlgorithm:: doInterLevelSetup(){ - Superclass::doInterLevelSetup(); + Superclass::doInterLevelSetup(); if (this->getCurrentLevel() != 0) { - getConcreteMetricControl()->getConcreteMetric()->SetUseAllPixels(false); + this->getConcreteMetricControl()->getConcreteMetric()->SetUseAllPixels(false); - OptimizerBaseType::SVNLOptimizerBaseType::ScalesType scales(6); + typename Superclass::OptimizerBaseType::SVNLOptimizerBaseType::ScalesType scales(6); scales[0] = 1.0; scales[1] = 1.0; scales[2] = 1.0; scales[3] = 1.0 / 1000; scales[4] = 1.0 / 1000; scales[5] = 1.0 / 1000; - getConcreteOptimizerControl()->getConcreteOptimizer()->SetScales(scales); + this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetScales(scales); unsigned int nrOfSmpl = ::itk::Math::Round (this->getMovingImage()->GetLargestPossibleRegion().GetNumberOfPixels() * 0.15); - getConcreteMetricControl()->getConcreteMetric()->SetNumberOfSpatialSamples(nrOfSmpl); + this->getConcreteMetricControl()->getConcreteMetric()->SetNumberOfSpatialSamples(nrOfSmpl); //optimizer adjustment - getConcreteOptimizerControl()->getConcreteOptimizer()->SetMaximumStepLength( - getConcreteOptimizerControl()->getConcreteOptimizer()->GetCurrentStepLength() * 2.0); - getConcreteOptimizerControl()->getConcreteOptimizer()->SetMinimumStepLength( - getConcreteOptimizerControl()->getConcreteOptimizer()->GetMinimumStepLength() * 0.5); + this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetMaximumStepLength( + this->getConcreteOptimizerControl()->getConcreteOptimizer()->GetCurrentStepLength() * 2.0); + this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetMinimumStepLength( + this->getConcreteOptimizerControl()->getConcreteOptimizer()->GetMinimumStepLength() * 0.5); } } template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> void MultiModalRigidHeadNeckRegistrationAlgorithm:: prepInitializeTransformation(){ Superclass::Superclass::prepInitializeTransformation(); if (this->_preInitialize) { this->InvokeEvent(events::AlgorithmEvent(this, "Preinitialize transform.")); typedef ::itk::CenteredTransformInitializer InitializerType; typedef ::itk::RegionOfInterestImageFilter ROIFilterType; - InitializerType::Pointer spInitializer = InitializerType::New(); + typename InitializerType::Pointer spInitializer = InitializerType::New(); - ROIFilterType::Pointer spROIFilter = ROIFilterType::New(); + typename ROIFilterType::Pointer spROIFilter = ROIFilterType::New(); spROIFilter->SetInput(this->getInternalTargetImage()); - ROIFilterType::RegionType region = this->getInternalTargetImage()->GetLargestPossibleRegion(); - ROIFilterType::RegionType::SizeValueType zSize = region.GetSize(2); + typename ROIFilterType::RegionType region = this->getInternalTargetImage()->GetLargestPossibleRegion(); + typename ROIFilterType::RegionType::SizeValueType zSize = region.GetSize(2); region.SetIndex(2, zSize / 3); region.SetSize(2, 2 * zSize / 3); spROIFilter->SetRegionOfInterest(region); core::OStringStream stream; stream << region; this->InvokeEvent(events::AlgorithmEvent(this, "Prepare target region of interest. region: " + stream.str())); spROIFilter->Update(); spInitializer->SetMovingImage(this->getInternalMovingImage()); spInitializer->SetFixedImage(spROIFilter->GetOutput()); spInitializer->SetTransform(this->getConcreteTransformModel()); if (this->_useCenterOfGravity) { this->InvokeEvent(events::AlgorithmEvent(this, "Preinitialize by moments.")); spInitializer->MomentsOn(); } else { this->InvokeEvent(events::AlgorithmEvent(this, "Preinitialize by image geometry.")); spInitializer->GeometryOn(); } spInitializer->InitializeTransform(); } core::OStringStream os; os << "Preinitialized transform to: " << this->getConcreteTransformModel()->GetParameters(); //set the parameter of the transform model to the current transform parameters of the algorithm this->setCurrentTransformParameters( this->getConcreteTransformModel()->GetParameters()); this->getInternalRegistrationMethod().SetInitialTransformParameters( this->getConcreteTransformModel()->GetParameters()); this->InvokeEvent(events::AlgorithmEvent(this, os.str())); } } // end namespace itk } // end namespace algorithm } // end namespace map #endif diff --git a/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.h b/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.h index 26e28c1..832c980 100644 --- a/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.h +++ b/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.h @@ -1,75 +1,75 @@ // ----------------------------------------------------------------------- // MatchPoint - DKFZ translational registration framework // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See mapCopyright.txt or // http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html // // 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. // //------------------------------------------------------------------------ #ifndef __MAP_ITK_RIGID_MMI_SLABBED_HEAD_REGISTRATION_ALGORITHM_H #define __MAP_ITK_RIGID_MMI_SLABBED_HEAD_REGISTRATION_ALGORITHM_H #include "mapITKEuler3DMattesMIMultiResRegistrationAlgorithmTemplate.h" namespace map { namespace algorithm { namespace boxed { /** \class MultiModalRigidSlabbedHeadRegistrationAlgorithm * \ingroup Data_image MetaProperty Model_rigid Det_comp_iterative Det_stochastic Det_res_multi Dim_3D_3D Mod_multi PreInit_Geo * Algorithm is used to solve a special case of head registration problems. * It is configured to register the slabbed MRI head data (thus date where only a part of the head is visible) onto whole Head images * (e.g.CT planning data). * Uses 3 Resolution levels. By default initializes via image centers */ template >, class TPyramideInitializationPolicy = algorithm::itk::NoComponentInitializationPolicy> class MultiModalRigidSlabbedHeadRegistrationAlgorithm : public map::algorithm::boxed::ITKEuler3DMattesMIMultiResRegistrationAlgorithm { public: typedef MultiModalRigidSlabbedHeadRegistrationAlgorithm Self; - typedef typename ITKEuler3DMattesMIMultiResRegistrationAlgorithm + typedef ITKEuler3DMattesMIMultiResRegistrationAlgorithm Superclass; typedef ::itk::SmartPointer Pointer; typedef ::itk::SmartPointer ConstPointer; itkTypeMacro(MultiModalRigidSlabbedHeadRegistrationAlgorithm, ITKEuler3DMattesMIMultiResRegistrationAlgorithm); mapNewAlgorithmMacro(Self); protected: MultiModalRigidSlabbedHeadRegistrationAlgorithm(); virtual ~MultiModalRigidSlabbedHeadRegistrationAlgorithm(); void configureAlgorithm(); void doInterLevelSetup(); private: MultiModalRigidSlabbedHeadRegistrationAlgorithm(const Self& source); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } } } #ifndef MatchPoint_MANUAL_TPP #include "mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.tpp" #endif #endif diff --git a/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.tpp b/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.tpp index 5315b24..02db25d 100644 --- a/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.tpp +++ b/Code/Algorithms/ITK/boxed/mapITKRigid3DMattesMISlabbedHeadRegistrationAlgorithmTemplate.tpp @@ -1,110 +1,110 @@ // ----------------------------------------------------------------------- // MatchPoint - DKFZ translational registration framework // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See mapCopyright.txt or // http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html // // 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. // //------------------------------------------------------------------------ #ifndef __ITK_RIGID_3D_MATTESMI_SLABBEDHEAD_REGISTRATION_ALGORITHM_TPP #define __ITK_RIGID_3D_MATTESMI_SLABBEDHEAD_REGISTRATION_ALGORITHM_TPP namespace map { namespace algorithm { namespace boxed { template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> MultiModalRigidSlabbedHeadRegistrationAlgorithm:: MultiModalRigidSlabbedHeadRegistrationAlgorithm() { } template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> MultiModalRigidSlabbedHeadRegistrationAlgorithm:: ~MultiModalRigidSlabbedHeadRegistrationAlgorithm() { } template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> void MultiModalRigidSlabbedHeadRegistrationAlgorithm:: configureAlgorithm() { Superclass::configureAlgorithm(); this->setResolutionLevels(3); this->_preInitialize = true; this->_useCenterOfGravity = false; //optimizer - ConcreteOptimizerType::ScalesType scales(6); + typename Superclass::ConcreteOptimizerType::ScalesType scales(6); scales[0] = 10.0; scales[1] = 10.0; scales[2] = 10.0; scales[3] = 1.0 / 10000; scales[4] = 1.0 / 10000; scales[5] = 1.0 / 10000; this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetScales(scales); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetMaximumStepLength(3.00); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetMinimumStepLength(0.5); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetNumberOfIterations(200); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetRelaxationFactor(0.8); this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetGradientMagnitudeTolerance(1e-4); //metric this->getConcreteMetricControl()->getConcreteMetric()->SetNumberOfHistogramBins(30); this->getConcreteMetricControl()->getConcreteMetric()->SetUseAllPixels(true); this->getConcreteMetricControl()->getConcreteMetric()->ReinitializeSeed(); this->getConcreteMetricControl()->getConcreteMetric()->UseExplicitPDFDerivativesOn(); } template < class TImageType, class TIdentificationPolicy, class TInterpolatorPolicy, class TPyramideInitializationPolicy> void MultiModalRigidSlabbedHeadRegistrationAlgorithm:: doInterLevelSetup(){ Superclass::doInterLevelSetup(); if (this->getCurrentLevel() != 0) { - getConcreteMetricControl()->getConcreteMetric()->SetUseAllPixels(false); + this->getConcreteMetricControl()->getConcreteMetric()->SetUseAllPixels(false); - OptimizerBaseType::SVNLOptimizerBaseType::ScalesType scales(6); + typename Superclass::OptimizerBaseType::SVNLOptimizerBaseType::ScalesType scales(6); scales[0] = 1.0; scales[1] = 1.0; scales[2] = 1.0; scales[3] = 1.0 / 1000; scales[4] = 1.0 / 1000; scales[5] = 1.0 / 1000; - getConcreteOptimizerControl()->getConcreteOptimizer()->SetScales(scales); + this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetScales(scales); unsigned int nrOfSmpl = ::itk::Math::Round (this->getMovingImage()->GetLargestPossibleRegion().GetNumberOfPixels() * 0.15); - getConcreteMetricControl()->getConcreteMetric()->SetNumberOfSpatialSamples(nrOfSmpl); + this->getConcreteMetricControl()->getConcreteMetric()->SetNumberOfSpatialSamples(nrOfSmpl); //optimizer adjustment - getConcreteOptimizerControl()->getConcreteOptimizer()->SetMaximumStepLength( - getConcreteOptimizerControl()->getConcreteOptimizer()->GetCurrentStepLength() * 2.0); - getConcreteOptimizerControl()->getConcreteOptimizer()->SetMinimumStepLength( - getConcreteOptimizerControl()->getConcreteOptimizer()->GetMinimumStepLength() * 0.5); + this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetMaximumStepLength( + this->getConcreteOptimizerControl()->getConcreteOptimizer()->GetCurrentStepLength() * 2.0); + this->getConcreteOptimizerControl()->getConcreteOptimizer()->SetMinimumStepLength( + this->getConcreteOptimizerControl()->getConcreteOptimizer()->GetMinimumStepLength() * 0.5); } } } // end namespace itk } // end namespace algorithm } // end namespace map #endif diff --git a/Code/Core/include/mapFieldRepresentationDescriptor.tpp b/Code/Core/include/mapFieldRepresentationDescriptor.tpp index 8fd3731..0544db2 100644 --- a/Code/Core/include/mapFieldRepresentationDescriptor.tpp +++ b/Code/Core/include/mapFieldRepresentationDescriptor.tpp @@ -1,506 +1,506 @@ // ----------------------------------------------------------------------- // MatchPoint - DKFZ translational registration framework // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See mapCopyright.txt or // http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html // // 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. // //------------------------------------------------------------------------ /*! // @file // @version $Revision$ (last changed revision) // @date $Date$ (last change date) // @author $Author$ (last changed by) // Subversion HeadURL: $HeadURL$ */ #ifndef __FIELD_REPRESENTATION_DESCRIPTOR_TPP #define __FIELD_REPRESENTATION_DESCRIPTOR_TPP -#include "itkImageTransformHelper.h" +#include #include "mapFieldRepresentationDescriptor.h" #include "mapExceptionObject.h" #include "mapConvert.h" #include "mapSDITKStreamingHelper.h" namespace map { namespace core { // **** public methods **** // ************************ template inline const typename FieldRepresentationDescriptor::SizeType FieldRepresentationDescriptor:: getSize() const { return *_pFieldSize; } template void FieldRepresentationDescriptor:: setSize(const SizeType& value) { SizeType* pNewSize = new SizeType(value); delete _pFieldSize; _pFieldSize = pNewSize; } template inline const typename FieldRepresentationDescriptor::PointType FieldRepresentationDescriptor:: getOrigin() const { return *_pFieldOrigin; } template void FieldRepresentationDescriptor:: setOrigin(const PointType& value) { PointType* pNewPoint = new PointType(value); delete _pFieldOrigin; _pFieldOrigin = pNewPoint; } template inline const typename FieldRepresentationDescriptor::SpacingType FieldRepresentationDescriptor:: getSpacing() const { return *_pFieldSpacing; } template void FieldRepresentationDescriptor:: setSpacing(const SpacingType& value) { SpacingType* pNewSpacing = new SpacingType(value); delete _pFieldSpacing; _pFieldSpacing = pNewSpacing; } template inline const typename FieldRepresentationDescriptor::DirectionType FieldRepresentationDescriptor:: getDirection() const { return *_pFieldDirection; } template void FieldRepresentationDescriptor:: setDirection(const DirectionType& value) { DirectionType* pNewDirection = new DirectionType(value); delete _pFieldDirection; _pFieldDirection = pNewDirection; } template typename FieldRepresentationDescriptor::ImageRegionType FieldRepresentationDescriptor:: getRepresentedLocalImageRegion(const PointType& imageOrigin, const DirectionType& imageDirection) const { if (!(imageDirection == this->getDirection())) { mapDefaultExceptionMacro( << "Directions of field representation and image are not the same. Cannot determin image region. Field direction: " << this->getDirection() << "; image direction: " << imageDirection); } typename ImageRegionType::SizeType regionSize; typename ImageRegionType::IndexType regionIndex; DirectionType pointToIndexMatrix = computePhysicalPointToIndexMatrix(); ::itk::ImageTransformHelper < VDimensions, VDimensions - 1, VDimensions - 1 >::TransformPhysicalPointToIndex(pointToIndexMatrix, imageOrigin, this->getOrigin(), regionIndex); for (unsigned long i = 0; i < VDimensions; ++i) { regionSize[i] = static_cast(floor(( *_pFieldSize)[i] / (*_pFieldSpacing)[i])); } return ImageRegionType(regionIndex, regionSize); } template typename FieldRepresentationDescriptor::ImageRegionType FieldRepresentationDescriptor:: getRepresentedLocalImageRegion() const { return getRepresentedLocalImageRegion(this->getOrigin(), this->getDirection()); } template typename FieldRepresentationDescriptor::DirectionType FieldRepresentationDescriptor:: computePhysicalPointToIndexMatrix() const { DirectionType scale; DirectionType result; for (unsigned int i = 0; i < VDimensions; i++) { scale[i][i] = (*_pFieldSpacing)[i]; } if (vnl_determinant(_pFieldDirection->GetVnlMatrix()) == 0.0) { itkExceptionMacro( << "Bad direction, determinant is 0. Direction is " << *_pFieldDirection); } result = (*_pFieldDirection) * scale; result = result.GetInverse(); return result; } template inline const typename FieldRepresentationDescriptor::VolumeType FieldRepresentationDescriptor:: getRepresentedVolume() const { return VolumeType(*_pFieldOrigin, *_pFieldSize); } template bool FieldRepresentationDescriptor:: operator == (const Self& frd) const { bool result = this->getSize() == frd.getSize(); if (result) { result = this->getOrigin() == frd.getOrigin(); } if (result) { result = this->getSpacing() == frd.getSpacing(); } if (result) { result = this->getDirection() == frd.getDirection(); } return result; }; // **** protected methods **** // *************************** template FieldRepresentationDescriptor:: FieldRepresentationDescriptor() { _pFieldSize = new SizeType(); _pFieldSize->fill(0); _pFieldOrigin = new PointType(); _pFieldOrigin->Fill(0); _pFieldSpacing = new SpacingType(); _pFieldSpacing->Fill(0); _pFieldDirection = new DirectionType(); _pFieldDirection->SetIdentity(); } template FieldRepresentationDescriptor:: ~FieldRepresentationDescriptor() { delete _pFieldSize; delete _pFieldOrigin; delete _pFieldSpacing; delete _pFieldDirection; } template void FieldRepresentationDescriptor:: PrintSelf(std::ostream& os, itk::Indent indent) const { unsigned int i = 0; Superclass::PrintSelf(os, indent); // print field size os << indent << "field size: ("; for (i = 0; i < VDimensions; i++) { os << (*_pFieldSize)[i] << " "; } os << ")\n"; // print field origin os << indent << "field origin: ("; for (i = 0; i < VDimensions; i++) { os << (*_pFieldOrigin)[i] << " "; } os << ")\n"; // print field spacing os << indent << "field spacing: ("; for (i = 0; i < VDimensions; i++) { os << (*_pFieldSpacing)[i] << " "; } os << ")\n" << std::endl; // print field direction os << indent << "field direction: ("; os << *_pFieldSpacing; os << ")\n" << std::endl; } template ::map::structuredData::StreamingInterface::ElementPointer FieldRepresentationDescriptor:: streamToSDInternal() const { structuredData::Element::Pointer spNewSD = structuredData::Element::New(); spNewSD->setTag("FieldRepresentationDescriptor"); //save attributes spNewSD->setAttribute("Dimensions", convert::toStr(VDimensions)); //save size structuredData::Element::Pointer spSizeElement = SizeType::streamToStructuredData(this->getSize()); spSizeElement->setTag("Size"); spNewSD->addSubElement(spSizeElement); structuredData::Element::Pointer spOriginElement = structuredData::streamITKFixedArrayToSD( this->getOrigin()); spOriginElement->setTag("Origin"); spNewSD->addSubElement(spOriginElement); structuredData::Element::Pointer spSpacingElement = structuredData::streamITKFixedArrayToSD( this->getSpacing()); spSpacingElement->setTag("Spacing"); spNewSD->addSubElement(spSpacingElement); structuredData::Element::Pointer spDirectionElement = structuredData::streamITKMatrixToSD( this->getDirection()); spDirectionElement->setTag("Direction"); spNewSD->addSubElement(spDirectionElement); return spNewSD; }; template void FieldRepresentationDescriptor:: streamFromSDInternal(const structuredData::Element* pElement) { SizeType newSize; PointType newOrigin; SpacingType newSpacing; DirectionType newDirection; structuredData::Element::ConstSubElementIteratorType subPos = structuredData::findNextSubElement( pElement->getSubElementBegin(), pElement->getSubElementEnd(), "Size"); if (subPos == pElement->getSubElementEnd()) { mapDefaultExceptionMacro( << "Error: cannot stream from structured data. Reason: sub element \"Size\" is missing."); } newSize = SizeType::streamFromStructuredData(*subPos); subPos = structuredData::findNextSubElement( pElement->getSubElementBegin(), pElement->getSubElementEnd(), "Origin"); if (subPos == pElement->getSubElementEnd()) { mapDefaultExceptionMacro( << "Error: cannot stream from structured data. Reason: sub element \"Origin\" is missing."); } newOrigin = structuredData::streamSDToITKFixedArray(*subPos); subPos = structuredData::findNextSubElement( pElement->getSubElementBegin(), pElement->getSubElementEnd(), "Spacing"); if (subPos == pElement->getSubElementEnd()) { mapDefaultExceptionMacro( << "Error: cannot stream from structured data. Reason: sub element \"Spacing\" is missing."); } newSpacing = structuredData::streamSDToITKFixedArray(*subPos); subPos = structuredData::findNextSubElement( pElement->getSubElementBegin(), pElement->getSubElementEnd(), "Direction"); if (subPos == pElement->getSubElementEnd()) { mapDefaultExceptionMacro( << "Error: cannot stream from structured data. Reason: sub element \"Direction\" is missing."); } newDirection = structuredData::streamSDToITKMatrix(*subPos); this->setSize(newSize); this->setOrigin(newOrigin); this->setSpacing(newSpacing); this->setDirection(newDirection); }; // **** static methods **** // ************************ template typename FieldRepresentationDescriptor::Pointer createFieldRepresentation(const TImage& image) { typedef FieldRepresentationDescriptor FRDType; typename FRDType::Pointer spFRD = FRDType::New(); typename FRDType::SizeType size; typename TImage::RegionType region = image.GetLargestPossibleRegion(); typename TImage::SpacingType spacing = image.GetSpacing(); for (unsigned long i = 0; i < TImage::ImageDimension; ++i) { size[i] = static_cast(region.GetSize(i) * spacing[i]); } spFRD->setSize(size); spFRD->setSpacing(spacing); spFRD->setOrigin(image.GetOrigin()); spFRD->setDirection(image.GetDirection()); return spFRD; } template typename FieldRepresentationDescriptor::Pointer createFieldRepresentation(const itk::ImageRegion& region, const typename ::map::core::continuous::Elements::SpacingType& spacing) { typename FieldRepresentationDescriptor::DirectionType direction; typename FieldRepresentationDescriptor::PointType origin; direction.SetIdentity(); origin.Fill(0.0); return createFieldRepresentation(region, spacing, origin, direction); } template typename FieldRepresentationDescriptor::Pointer createFieldRepresentation(const itk::ImageRegion& region, const typename ::map::core::continuous::Elements::SpacingType& spacing, const typename FieldRepresentationDescriptor::PointType& imageOrigin, const typename FieldRepresentationDescriptor::DirectionType& direction) { typedef FieldRepresentationDescriptor FRDType; typename FRDType::Pointer spFRD = FRDType::New(); typename FRDType::DirectionType scale; typename FRDType::DirectionType indexToPointMatrix; typename FRDType::PointType origin; typename FRDType::SizeType size; typename FRDType::SpacingType fieldSpacing; for (unsigned long i = 0; i < VDimensions; ++i) { size[i] = static_cast(region.GetSize(i) * spacing[i]); fieldSpacing[i] = spacing[i]; scale[i][i] = spacing[i]; } indexToPointMatrix = direction * scale; ::itk::ImageTransformHelper < VDimensions, VDimensions - 1, VDimensions - 1 >::TransformIndexToPhysicalPoint(indexToPointMatrix, imageOrigin, region.GetIndex(), origin); spFRD->setSpacing(fieldSpacing); spFRD->setSize(size); spFRD->setOrigin(origin); spFRD->setDirection(direction); return spFRD; } template typename FieldRepresentationDescriptor::Pointer createFieldRepresentation(const TVolume& volume, const typename ::map::core::continuous::Elements::SpacingType& spacing, const typename FieldRepresentationDescriptor::DirectionType& direction) { typedef FieldRepresentationDescriptor FRDType; typename FRDType::Pointer spFRD = FRDType::New(); typename FRDType::PointType origin; typename FRDType::SizeType size; typename FRDType::SpacingType fieldSpacing; for (unsigned long i = 0; i < TVolume::VolumeDimension; ++i) { origin[i] = volume.getOrigin(i); size[i] = volume.getSize(i); fieldSpacing[i] = spacing[i]; } spFRD->setSpacing(fieldSpacing); spFRD->setSize(size); spFRD->setOrigin(origin); spFRD->setDirection(direction); return spFRD; } template typename FieldRepresentationDescriptor::Pointer createFieldRepresentation(const TVolume& volume, const typename ::map::core::continuous::Elements::SpacingType& spacing) { typename FieldRepresentationDescriptor::DirectionType direction; direction.SetIdentity(); return createFieldRepresentation(volume, spacing, direction); } } // end namespace core } // end namespace map #endif diff --git a/Code/Core/source/mapLogbook.cpp b/Code/Core/source/mapLogbook.cpp index b213068..331c32a 100644 --- a/Code/Core/source/mapLogbook.cpp +++ b/Code/Core/source/mapLogbook.cpp @@ -1,264 +1,264 @@ // ----------------------------------------------------------------------- // MatchPoint - DKFZ translational registration framework // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See mapCopyright.txt or // http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html // // 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. // //------------------------------------------------------------------------ /*! // @file // @version $Revision$ (last changed revision) // @date $Date$ (last change date) // @author $Author$ (last changed by) // Subversion HeadURL: $HeadURL$ */ #include "mapLogbook.h" #include "mapLogbookImplementation.h" #include "mapSmartMetaProperty.h" #include "mapMetaProperty.h" #include "itkMutexLockHolder.h" #include namespace map { namespace core { - Logbook::LogImplPointer Logbook::_spLoggerImpl = NULL; + Logbook::LogImplPointer Logbook::_spLoggerImpl = nullptr; itk::SimpleFastMutexLock Logbook::_testMutex; itk::SimpleFastMutexLock Logbook::_initMutex; Logbook::PriorityLevelType Logbook::_currentPriorityLevel = itk::LoggerBase::INFO; bool Logbook::_syncedAsDedicated = false; String Logbook::_defaultFilename = "MatchPoint.log"; void Logbook:: write(PriorityLevelType level, const String& content) { if (_spLoggerImpl.IsNull()) { initializeLogger(); } _spLoggerImpl->getLogger().Write(level, content.c_str()); }; void Logbook:: flush() { if (_spLoggerImpl.IsNotNull()) { _spLoggerImpl->getLogger().Flush(); } }; void Logbook:: setDefaultLogFileName(const String& fileName) { if (_spLoggerImpl.IsNotNull() && _defaultFilename != fileName) { //we need to exchange the implementation mapLogDebugStaticMacro( << "Attempt to change logbook default file. New file name: " << fileName); LogImplPointer spNewImpl = _spLoggerImpl->clone(fileName); //if we reached this point without exception the implementation //with the new file is open and established, thus swap the implmentations, //store the new default file and print the header. swapImplementations(spNewImpl); _defaultFilename = fileName; } else { _defaultFilename = fileName; } }; void Logbook:: addAdditionalLogOutput(OutputType* pOutput) { assert(pOutput); //must not be null if (_spLoggerImpl.IsNull()) { initializeLogger(); } mapLogDebugStaticMacro( << "Add output to logbook. Output: " << pOutput->GetNameOfClass()); LogImplPointer spNewImpl = _spLoggerImpl->clone(); spNewImpl->addAdditionalLogOutput(pOutput); swapImplementations(spNewImpl); }; void Logbook:: attachITKOutputWindow() { if (_spLoggerImpl.IsNull()) { initializeLogger(); } mapLogDebugStaticMacro( << "Attached itk ouput window to MatchPoint logbook"); itk::MutexLockHolder testHolder(_testMutex); itk::MutexLockHolder initHolder(_initMutex); if (_spLoggerImpl->_spItkOutputWindow.IsNull()) { itk::LoggerOutput::Pointer spNewLogger = itk::LoggerOutput::New(); itk::OutputWindow::SetInstance(spNewLogger); _spLoggerImpl->_spItkOutputWindow = spNewLogger; } _spLoggerImpl->_spItkOutputWindow->SetLogger(&(_spLoggerImpl->getLogger())); }; Logbook::PriorityLevelType Logbook:: getLogbookMode(void) { return _currentPriorityLevel; }; void Logbook:: setLogbookToDebugMode(void) { setLogbookMode(itk::LoggerBase::DEBUG); }; void Logbook:: setLogbookToInfoMode(void) { setLogbookMode(itk::LoggerBase::INFO); }; void Logbook:: setLogbookToCriticalMode(void) { setLogbookMode(itk::LoggerBase::CRITICAL); }; void Logbook:: setLogbookMode(PriorityLevelType level) { if (_spLoggerImpl.IsNotNull()) { _spLoggerImpl->getLogger().SetPriorityLevel(level); } _currentPriorityLevel = level; }; bool Logbook:: isInitialized(void) { return _spLoggerImpl.IsNotNull(); }; void Logbook:: initializeLogger(void) { itk::MutexLockHolder testHolder(_testMutex); if (_spLoggerImpl.IsNull()) { { //mutex lock holder scope itk::MutexLockHolder initHolder(_initMutex); LogImplPointer spNewImpl = LogbookImplementation::New(); spNewImpl->initializeOutputs(_defaultFilename); _spLoggerImpl = spNewImpl; } // end of mutex lock holder scope } }; void Logbook:: swapImplementations(LogbookImplementation* pImpl) { assert(pImpl); //must not be null; _testMutex.Lock(); _initMutex.Lock(); _spLoggerImpl = pImpl; _initMutex.Unlock(); _testMutex.Unlock(); }; void Logbook:: getSynchronization(deployment::SyncObject& syncObject) { core::MetaPropertyBase::Pointer prop = core::SmartMetaProperty::New(_spLoggerImpl).GetPointer(); deployment::SyncObject::SyncPropertyMapType::value_type valuePair("Logbook_Impl", prop); syncObject._map.insert(valuePair); prop = core::MetaProperty::New(_currentPriorityLevel).GetPointer(); deployment::SyncObject::SyncPropertyMapType::value_type valuePair2("Logbook_Priority", prop); syncObject._map.insert(valuePair2); }; void Logbook:: setSynchronization(const deployment::SyncObject& syncObject) { LogImplPointer spNewLogger; if (syncObject.getProperty("Logbook_Impl", spNewLogger)) { //there is something to sync for the logbook... if (spNewLogger.GetPointer() != _spLoggerImpl) { _syncedAsDedicated = true; swapImplementations(spNewLogger); } syncObject.getProperty("Logbook_Priority", _currentPriorityLevel); } }; void Logbook:: deSynchronize() { mapLogInfoStaticMacro( << "Attempt to desync logbook."); LogImplPointer spNewImpl = _spLoggerImpl->clone(Logbook::_defaultFilename); //if we reached this point without exception the implementation //with the new file is open and established, thus swap the implmentations, //store the new default file and print the header. swapImplementations(spNewImpl); _syncedAsDedicated = false; }; } // end namespace core -} // end namespace map \ No newline at end of file +} // end namespace map diff --git a/Code/Core/source/mapSDXMLFileReader.cpp b/Code/Core/source/mapSDXMLFileReader.cpp index 1d43548..3ba5fe9 100644 --- a/Code/Core/source/mapSDXMLFileReader.cpp +++ b/Code/Core/source/mapSDXMLFileReader.cpp @@ -1,143 +1,143 @@ // ----------------------------------------------------------------------- // MatchPoint - DKFZ translational registration framework // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See mapCopyright.txt or // http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html // // 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. // //------------------------------------------------------------------------ /*! // @file // @version $Revision$ (last changed revision) // @date $Date$ (last change date) // @author $Author$ (last changed by) // Subversion HeadURL: $HeadURL$ */ #include #include #include #include "itksys/SystemTools.hxx" #include "mapSDXMLStrReader.h" #include "mapSDXMLFileReader.h" #include "mapSDExceptions.h" #include "mapSDTags.h" namespace map { namespace structuredData { XMLFileReader::ElementPointer XMLFileReader:: read(const core::String& filePath) { - ElementPointer spResult = NULL; + ElementPointer spResult = nullptr; std::ifstream file; std::ios_base::openmode iOpenFlag = std::ios_base::in; file.open(filePath.c_str(), iOpenFlag); if (!file.is_open()) { mapDefaultExceptionMacro( << "Cannot open or create specified file to load. File path: " << filePath); } ::map::core::String data; bool hasError = false; std::streamsize filesize = itksys::SystemTools::FileLength(filePath.c_str()); char* buffer = new char [filesize]; try { file.read(buffer, filesize); std::streamsize gsize = file.gcount(); data.insert(0, buffer, gsize); } catch (...) { hasError = true; } delete[] buffer; file.close(); if (hasError) { mapDefaultExceptionMacro( << "Error while reading file content into buffer. File path:" << filePath); } XMLStrReader::Pointer spStrReader = XMLStrReader::New(); spResult = spStrReader->read(data); spResult->setAttribute(tags::SDInternalSourceReader, tags::SDInternalSourceReader_file, true); spResult->setAttribute(tags::SDInternalSourceURI, filePath, true); _spRoot = spResult; return spResult; }; void XMLFileReader:: read(const core::String& filePath, StreamingInterface* pInterface) { if (!pInterface) { mapDefaultExceptionMacro( << "Error, cannot read passed object from xml file. Passed interface is NULL."); } read(filePath); pInterface->streamFromStructuredData(getXMLContent()); }; XMLFileReader::ElementPointer XMLFileReader:: getXMLContent() { - ElementPointer spResult = NULL; + ElementPointer spResult = nullptr; if (_spRoot.IsNotNull()) { if (_spRoot->getSubElementsCount() > 0) { spResult = _spRoot->getSubElement(0); } } return spResult; }; XMLFileReader:: XMLFileReader() { _spRoot = NULL; }; XMLFileReader:: ~XMLFileReader() { }; } //end of namespace structuredData } //end of namespace map diff --git a/Code/Core/source/mapSDXMLStrReader.cpp b/Code/Core/source/mapSDXMLStrReader.cpp index e2f5e5d..ed89d25 100644 --- a/Code/Core/source/mapSDXMLStrReader.cpp +++ b/Code/Core/source/mapSDXMLStrReader.cpp @@ -1,415 +1,415 @@ // ----------------------------------------------------------------------- // MatchPoint - DKFZ translational registration framework // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See mapCopyright.txt or // http://www.dkfz.de/en/sidt/projects/MatchPoint/copyright.html // // 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. // //------------------------------------------------------------------------ /*! // @file // @version $Revision$ (last changed revision) // @date $Date$ (last change date) // @author $Author$ (last changed by) // Subversion HeadURL: $HeadURL$ */ #include "expat.h" #include #include #include #include #include "mapSDXMLStrReader.h" #include "mapSDExceptions.h" #include "mapSDTags.h" namespace map { namespace structuredData { ::map::core::String decodeForXmlChar(const core::String& sSrc, const core::String& searchStr, const core::String& newStr) { ::map::core::String sRet = sSrc; ::map::core::String::size_type pos = sRet.find(searchStr); while (pos != core::String::npos) { sRet.erase(pos, searchStr.size()); sRet.insert(pos, newStr); } return sRet; } ::map::core::String decodeForXml(const core::String& sSrc) { ::map::core::String sRet = decodeForXmlChar(sSrc, "'", "\'"); sRet = decodeForXmlChar(sRet, """, "\""); sRet = decodeForXmlChar(sRet, ">", ">"); sRet = decodeForXmlChar(sRet, "<", "<'"); sRet = decodeForXmlChar(sRet, "&", "&"); return sRet; } //////////////////////////////////////////////////////////////////////// /// Implementation of map::XMLStrReaderImpl /////////////////////////// //////////////////////////////////////////////////////////////////////// /** @class XMLStrReaderImpl * @brief Private implementation of the XMLStrReader. * * This class does the real work of XMLStrReader as non public implementation * to cover the internals like the use of expat. * The concept of the class has been designed for the requirements in free * and has been motivated by the wish using present resources of itk and introduce as * less as possible third-party libraries. * * @ingroup XML */ class XMLStrReaderImpl { public: virtual const char* GetNameOfClass() const { return "XMLStrReaderImpl"; }; typedef std::pair< ::map::core::String, core::String> AttributeType; typedef std::map< ::map::core::String, core::String> AttributesType; //uses vector for saving, to avoid automatic sort feature of stl::map typedef std::vector AttributesSaveListType; typedef Element::Pointer ElementPointer; /** Function to load a structure from a xml string. The function creates * an expat parser, manages the callbacks, calls Reset() and ResetRequirements(). * To control the loading process, the function SubElementLoadProcessing() should be * overridden. When the loading is finished, it will be checked, if the requirements * are meet, the expat resources will be freed. * @param [in] rsData Reference to the whole data of the xml element (with start and end tag and attributes)*/ ElementPointer LoadFromString(const core::String& rsData); /** Resets the object to default/initial state*/ void Reset(); /** Default constructor */ XMLStrReaderImpl(); /** destructor */ ~XMLStrReaderImpl(); protected: /** Function is called by LoadFromXMLString() to handle the Attributes contained by the xml string * for the passed SD element. * @param [in] pElement Pointer to the element that should get the attributes set. * @param [in] rAttributes Reference to a stl map with the attributes of the element.*/ static void AttributesLoadProcessing(Element* pElement, const AttributesType& rAttributes); static void CB_Static_StartElement(void* parser, const char* name, const char** pAttributes); static void CB_Static_EndElement(void* parser, const char* name); static void CB_Static_CharacterDataHandler(void* parser, const char* data, int length); /** Callback function -- called from XML parser when starting tag * encountered */ void CB_StartElement(const char* name, const char** pAttributes); /** Callback function -- called from XML parser when ending tag * encountered */ void CB_EndElement(const char* name); /** Callback function -- called from XML parser with the character data * for a XML element */ void CB_CharacterDataHandler(const char* inData, int inLength); /** Function adds the content of m_currentElementText to the Value of the passed element. * @param [in] pElement Pointer to the element that should get the content of m_currentElementText.*/ void TransferCurrentText(Element* pElement); /** Converts the attribute structure passed by expat to a stl string map.*/ static AttributesType ConvertExpatAttrToMap(const char** pAttributes); /** pointer to the data string passed with ReadString*/ const core::String* m_pLoadData; ElementPointer m_spRootElement; typedef std::deque ElementStackType; /**Stack of all structured data element that are open right now. Therefor had * an start tag but no stop tag yet. An element is added to the stack when its * xml start tag occures and is removed if the proper end tag is found.*/ ElementStackType m_stack; /**String containing all data received by CB_CharacterDataHandler * it will used to set the current element's value.*/ ::map::core::String m_currentElementText; /** Pointer to the expat parser*/ XML_Parser m_Parser; }; void XMLStrReaderImpl:: CB_Static_StartElement(void* parser, const char* name, const char** pAttributes) { // Begin element handler that is registered with the XML_Parser. // This just casts the user data to an XMLStrReaderImpl and calls // StartElement. static_cast(parser)->CB_StartElement(name, pAttributes); } void XMLStrReaderImpl:: CB_Static_EndElement(void* parser, const char* name) { // End element handler that is registered with the XML_Parser. This // just casts the user data to an XMLStrReaderImpl and calls EndElement. static_cast(parser)->CB_EndElement(name); } void XMLStrReaderImpl:: CB_Static_CharacterDataHandler(void* parser, const char* data, int length) { // Character data handler that is registered with the XML_Parser. // This just casts the user data to an XMLStrReaderImpl and calls // CharacterDataHandler. static_cast(parser)->CB_CharacterDataHandler(data, length); } XMLStrReaderImpl::ElementPointer XMLStrReaderImpl:: LoadFromString(const core::String& rsRawData) { Reset(); m_Parser = XML_ParserCreate(0); XML_SetElementHandler(m_Parser, &CB_Static_StartElement, &CB_Static_EndElement); XML_SetCharacterDataHandler(m_Parser, &CB_Static_CharacterDataHandler); XML_SetUserData(m_Parser, this); m_pLoadData = &rsRawData; m_spRootElement = Element::createElement("ROOT", ""); m_stack.push_back(m_spRootElement); bool result = XML_Parse(m_Parser, m_pLoadData->c_str(), m_pLoadData->size(), true); if (!result) { ::map::core::String errorMsg(XML_ErrorString(XML_GetErrorCode(m_Parser))); mapDefaultExceptionMacro( << "Expat error while parsing raw string. Error: " << errorMsg << "; Error position: " << XML_GetCurrentLineNumber(m_Parser) << ":" << XML_GetCurrentColumnNumber( m_Parser)); } ElementPointer spResult = m_spRootElement; Reset(); return spResult; }; void XMLStrReaderImpl:: CB_StartElement(const char* name, const char** pAttributes) { ElementPointer spNewElement = Element::createElement(::map::core::String(name), ""); m_stack.back()->addSubElement(spNewElement); //any data yet stored in m_CurrentElementText should now be stored to //the current last element in stack, befor pushing the new one. TransferCurrentText(m_stack.back()); m_stack.push_back(spNewElement); //set attributes AttributesLoadProcessing(spNewElement, ConvertExpatAttrToMap(pAttributes)); }; void XMLStrReaderImpl:: CB_EndElement(const char* name) { if (::map::core::String(name) != m_stack.back()->getTag()) { mapDefaultExceptionMacro( << "Error. XML structure seems not to be correct. XML tags seem to be mingeld end tag does not fit the last start tag. Start tag: " << m_stack.back()->getTag() << "; end tag: " << name); } if (m_stack.size() < 2) { mapDefaultExceptionMacro( << "Error. XML structure seems not to be correct. End tag found, but no top level element was started. End tag: " << name); } //any data yet stored in m_CurrentElementText should now be stored to //the current last element in stack, befor element is "popped". TransferCurrentText(m_stack.back()); m_stack.pop_back(); }; void XMLStrReaderImpl:: CB_CharacterDataHandler(const char* inData, int inLength) { m_currentElementText.append(inData, inLength); }; void XMLStrReaderImpl:: TransferCurrentText(Element* pElement) { assert(pElement); pElement->setValue(pElement->getValue() + decodeForXml(m_currentElementText)); m_currentElementText.clear(); }; XMLStrReaderImpl:: XMLStrReaderImpl() { m_Parser = NULL; Reset(); }; XMLStrReaderImpl:: ~XMLStrReaderImpl() { Reset(); }; void XMLStrReaderImpl:: AttributesLoadProcessing(Element* pElement, const AttributesType& attributes) { for (AttributesType::const_iterator pos = attributes.begin(); pos != attributes.end(); ++pos) { pElement->setAttribute(pos->first, pos->second); } }; void XMLStrReaderImpl:: Reset() { m_stack.clear(); m_spRootElement = NULL; m_pLoadData = NULL; m_currentElementText.clear(); if (m_Parser) { XML_ParserFree(m_Parser); m_Parser = NULL; } }; XMLStrReaderImpl::AttributesType XMLStrReaderImpl:: ConvertExpatAttrToMap(const char** pAttributes) { AttributesType attrs; const char** pActAttr = pAttributes; while (*pActAttr) { ::map::core::String sKey = *pActAttr; pActAttr++; ::map::core::String sValue = *pActAttr; pActAttr++; attrs.insert(AttributeType(sKey, sValue)); }; return attrs; }; //////////////////////////////////////////////////////////////////////// /// Implementation of FREE::XMLStrReader /////////////////////////////// //////////////////////////////////////////////////////////////////////// XMLStrReader::ElementPointer XMLStrReader:: read(const XMLRawDataType& data) { XMLStrReaderImpl implementation; - ElementPointer spResult = NULL; + ElementPointer spResult = nullptr; spResult = implementation.LoadFromString(data); if (spResult) { spResult->setAttribute(tags::SDInternalSourceReader, tags::SDInternalSourceReader_string, true); spResult->setAttribute(tags::SDInternalSourceFormat, tags::SDInternalSourceFormat_xml, true); } return spResult; }; XMLStrReader::ElementPointer XMLStrReader:: readXMLContent(const XMLRawDataType& data) { XMLStrReaderImpl implementation; - ElementPointer spResult = NULL; + ElementPointer spResult = nullptr; spResult = implementation.LoadFromString(data); if (spResult->getSubElementsCount() < 1) { mapDefaultExceptionMacro( << "Error. String does not contain any xml elements. String: " << data); } spResult = spResult->getSubElement(0); spResult->setAttribute(tags::SDInternalSourceReader, tags::SDInternalSourceReader_string, true); spResult->setAttribute(tags::SDInternalSourceFormat, tags::SDInternalSourceFormat_xml, true); return spResult; }; XMLStrReader:: XMLStrReader() { }; XMLStrReader:: ~XMLStrReader() { }; } //end of namespace structuredData } //end of namespace free