diff --git a/Core/Code/Common/mitkCoreObjectFactory.cpp b/Core/Code/Common/mitkCoreObjectFactory.cpp index 61e9cbb735..50d524f2f9 100644 --- a/Core/Code/Common/mitkCoreObjectFactory.cpp +++ b/Core/Code/Common/mitkCoreObjectFactory.cpp @@ -1,501 +1,430 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkConfig.h" #include "mitkCoreObjectFactory.h" #include "mitkAffineInteractor.h" #include "mitkColorProperty.h" #include "mitkDataNode.h" #include "mitkEnumerationProperty.h" #include "mitkGeometry2DData.h" #include "mitkGeometry2DDataMapper2D.h" #include "mitkGeometry2DDataVtkMapper3D.h" #include "mitkGeometry3D.h" #include "mitkGeometryData.h" #include "mitkImage.h" #include #include "mitkLevelWindowProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkPlaneGeometry.h" #include "mitkPointSet.h" #include "mitkPointSetVtkMapper2D.h" #include "mitkPointSetVtkMapper3D.h" #include "mitkPolyDataGLMapper2D.h" #include "mitkProperties.h" #include "mitkPropertyList.h" #include "mitkSlicedGeometry3D.h" #include "mitkSmartPointerProperty.h" #include "mitkStringProperty.h" #include "mitkSurface.h" #include "mitkSurface.h" #include "mitkSurfaceGLMapper2D.h" #include "mitkSurfaceVtkMapper3D.h" #include "mitkTimeSlicedGeometry.h" #include "mitkTransferFunctionProperty.h" #include "mitkVolumeDataVtkMapper3D.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkResliceInterpolationProperty.h" -//#include "mitkPicFileIOFactory.h" -#include "mitkPointSetIOFactory.h" -#include "mitkItkImageFileIOFactory.h" -#include "mitkSTLFileIOFactory.h" -#include "mitkVtkSurfaceIOFactory.h" -#include "mitkVtkImageIOFactory.h" -#include "mitkVtiFileIOFactory.h" -//#include "mitkPicVolumeTimeSeriesIOFactory.h" - -#include "mitkImageWriterFactory.h" -#include "mitkImageWriter.h" -#include "mitkPointSetWriterFactory.h" -#include "mitkSurfaceVtkWriterFactory.h" - // Legacy Support: #include #include +#include #include -#include -#include -#include - -mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::m_FileWriters; -std::list< mitk::LegacyFileReaderService* > mitk::CoreObjectFactory::m_LegacyReaders; -std::list< mitk::LegacyFileWriterService* > mitk::CoreObjectFactory::m_LegacyWriters; -std::list< mitk::LegacyImageWriterService* > mitk::CoreObjectFactory::m_LegacyImageWriters; void mitk::CoreObjectFactory::RegisterExtraFactory(CoreObjectFactoryBase* factory) { MITK_DEBUG << "CoreObjectFactory: registering extra factory of type " << factory->GetNameOfClass(); m_ExtraFactories.insert(CoreObjectFactoryBase::Pointer(factory)); // Register Legacy Reader and Writer - this->RegisterLegacyReaders(this); - this->RegisterLegacyWriters(); + this->RegisterLegacyReaders(factory); + this->RegisterLegacyWriters(factory); } void mitk::CoreObjectFactory::UnRegisterExtraFactory(CoreObjectFactoryBase *factory) { MITK_DEBUG << "CoreObjectFactory: un-registering extra factory of type " << factory->GetNameOfClass(); try { m_ExtraFactories.erase(factory); } catch( std::exception const& e) { MITK_ERROR << "Caugt exception while unregistering: " << e.what(); } } mitk::CoreObjectFactory::Pointer mitk::CoreObjectFactory::GetInstance() { static mitk::CoreObjectFactory::Pointer instance; if (instance.IsNull()) { instance = mitk::CoreObjectFactory::New(); } return instance; } -#include +mitk::CoreObjectFactory::~CoreObjectFactory() +{ + for (std::list< mitk::LegacyFileReaderService* >::iterator it = m_LegacyReaders.begin(); + it != m_LegacyReaders.end(); ++it) + { + delete *it; + } + + for (std::list< mitk::LegacyFileWriterService* >::iterator it = m_LegacyWriters.begin(); + it != m_LegacyWriters.end(); ++it) + { + delete *it; + } +} void mitk::CoreObjectFactory::SetDefaultProperties(mitk::DataNode* node) { if(node==NULL) return; mitk::DataNode::Pointer nodePointer = node; mitk::Image::Pointer image = dynamic_cast(node->GetData()); if(image.IsNotNull() && image->IsInitialized()) { mitk::ImageVtkMapper2D::SetDefaultProperties(node); mitk::VolumeDataVtkMapper3D::SetDefaultProperties(node); } mitk::Surface::Pointer surface = dynamic_cast(node->GetData()); if(surface.IsNotNull()) { mitk::SurfaceGLMapper2D::SetDefaultProperties(node); mitk::SurfaceVtkMapper3D::SetDefaultProperties(node); } mitk::PointSet::Pointer pointSet = dynamic_cast(node->GetData()); if(pointSet.IsNotNull()) { mitk::PointSetVtkMapper2D::SetDefaultProperties(node); mitk::PointSetVtkMapper3D::SetDefaultProperties(node); } for (ExtraFactoriesContainer::iterator it = m_ExtraFactories.begin(); it != m_ExtraFactories.end() ; it++ ) { (*it)->SetDefaultProperties(node); } } mitk::CoreObjectFactory::CoreObjectFactory() { static bool alreadyDone = false; if (!alreadyDone) { - MITK_DEBUG << "CoreObjectFactory c'tor" << std::endl; - - // FIXME itk::ObjectFactoryBase::RegisterFactory( PicFileIOFactory::New() ); - itk::ObjectFactoryBase::RegisterFactory( PointSetIOFactory::New() ); - itk::ObjectFactoryBase::RegisterFactory( STLFileIOFactory::New() ); - itk::ObjectFactoryBase::RegisterFactory( VtkSurfaceIOFactory::New() ); - itk::ObjectFactoryBase::RegisterFactory( VtkImageIOFactory::New() ); - itk::ObjectFactoryBase::RegisterFactory( VtiFileIOFactory::New() ); - itk::ObjectFactoryBase::RegisterFactory( ItkImageFileIOFactory::New() ); - // FIXME itk::ObjectFactoryBase::RegisterFactory( PicVolumeTimeSeriesIOFactory::New() ); - - mitk::SurfaceVtkWriterFactory::RegisterOneFactory(); - mitk::PointSetWriterFactory::RegisterOneFactory(); - mitk::ImageWriterFactory::RegisterOneFactory(); - m_FileWriters.push_back(mitk::ImageWriter::New().GetPointer()); - CreateFileExtensionsMap(); + RegisterLegacyReaders(this); + RegisterLegacyWriters(this); + alreadyDone = true; } } mitk::Mapper::Pointer mitk::CoreObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper = NULL; mitk::Mapper::Pointer tmpMapper = NULL; // check whether extra factories provide mapper for (ExtraFactoriesContainer::iterator it = m_ExtraFactories.begin(); it != m_ExtraFactories.end() ; it++ ) { tmpMapper = (*it)->CreateMapper(node,id); if(tmpMapper.IsNotNull()) newMapper = tmpMapper; } if (newMapper.IsNull()) { mitk::BaseData *data = node->GetData(); if ( id == mitk::BaseRenderer::Standard2D ) { if((dynamic_cast(data)!=NULL)) { newMapper = mitk::ImageVtkMapper2D::New(); newMapper->SetDataNode(node); } else if((dynamic_cast(data)!=NULL)) { newMapper = mitk::Geometry2DDataMapper2D::New(); newMapper->SetDataNode(node); } else if((dynamic_cast(data)!=NULL)) { newMapper = mitk::SurfaceGLMapper2D::New(); // cast because SetDataNode is not virtual mitk::SurfaceGLMapper2D *castedMapper = dynamic_cast(newMapper.GetPointer()); castedMapper->SetDataNode(node); } else if((dynamic_cast(data)!=NULL)) { newMapper = mitk::PointSetVtkMapper2D::New(); newMapper->SetDataNode(node); } } else if ( id == mitk::BaseRenderer::Standard3D ) { if((dynamic_cast(data) != NULL)) { newMapper = mitk::VolumeDataVtkMapper3D::New(); newMapper->SetDataNode(node); } else if((dynamic_cast(data)!=NULL)) { newMapper = mitk::Geometry2DDataVtkMapper3D::New(); newMapper->SetDataNode(node); } else if((dynamic_cast(data)!=NULL)) { newMapper = mitk::SurfaceVtkMapper3D::New(); newMapper->SetDataNode(node); } else if((dynamic_cast(data)!=NULL)) { newMapper = mitk::PointSetVtkMapper3D::New(); newMapper->SetDataNode(node); } } } return newMapper; } -/* -// @deprecated -// -#define EXTERNAL_FILE_EXTENSIONS \ -"All known formats(*.dcm *.DCM *.dc3 *.DC3 *.gdcm *.ima *.mhd *.mps *.nii *.pic *.pic.gz *.bmp *.png *.jpg *.tiff *.pvtk *.stl *.vtk *.vtp *.vtu *.obj *.vti *.hdr *.nrrd *.nhdr );;" \ -"DICOM files(*.dcm *.DCM *.dc3 *.DC3 *.gdcm);;" \ -"DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \ -"NRRD Vector Images (*.nrrd *.nhdr);;" \ -"Point sets (*.mps);;" \ -"Sets of 2D slices (*.pic *.pic.gz *.bmp *.png *.dcm *.gdcm *.ima *.tiff);;" \ -"Surface files (*.stl *.vtk *.vtp *.obj);;" \ -"NIfTI format (*.nii)" - -#define SAVE_FILE_EXTENSIONS "all (*.pic *.mhd *.vtk *.vti *.hdr *.png *.tiff *.jpg *.hdr *.bmp *.dcm *.gipl *.nii *.nrrd *.nhdr *.spr *.lsm *.dwi *.hdwi *.qbi *.hqbi)" -*/ - -/** -* @brief This method gets the supported (open) file extensions as string. This string is can then used by the QT QFileDialog widget. -* @return The c-string that contains the file extensions -* -*/ const char* mitk::CoreObjectFactory::GetFileExtensions() { MultimapType aMap; for (ExtraFactoriesContainer::iterator it = m_ExtraFactories.begin(); it != m_ExtraFactories.end() ; it++ ) { aMap = (*it)->GetFileExtensionsMap(); this->MergeFileExtensions(m_FileExtensionsMap, aMap); } this->CreateFileExtensions(m_FileExtensionsMap, m_FileExtensions); return m_FileExtensions.c_str(); } -/** -* @brief Merge the input map into the fileExtensionsMap. Duplicate entries are removed -* @param fileExtensionsMap the existing map, it contains value pairs like ("*.dcm", "DICOM files"),("*.dc3", "DICOM files"). -* This map is extented/merged with the values from the input map. -* @param inputMap the input map, it contains value pairs like ("*.dcm", "DICOM files"),("*.dc3", "DICOM files") returned by -* the extra factories. -* -*/ void mitk::CoreObjectFactory::MergeFileExtensions(MultimapType& fileExtensionsMap, MultimapType inputMap) { bool duplicateFound = false; std::pair pairOfIter; for (MultimapType::iterator it = inputMap.begin(); it != inputMap.end(); ++it) { duplicateFound = false; pairOfIter = fileExtensionsMap.equal_range((*it).first); for (MultimapType::iterator it2 = pairOfIter.first; it2 != pairOfIter.second; ++it2) { //cout << " [" << (*it).first << ", " << (*it).second << "]" << endl; std::string aString = (*it2).second; if (aString.compare((*it).second) == 0) { //cout << " DUP!! [" << (*it).first << ", " << (*it).second << "]" << endl; duplicateFound = true; break; } } if (!duplicateFound) { fileExtensionsMap.insert(std::pair((*it).first, (*it).second)); } } } -/** -* @brief get the defined (open) file extension map -* @return the defined (open) file extension map -*/ mitk::CoreObjectFactoryBase::MultimapType mitk::CoreObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } -/** -* @brief initialize the file extension entries for open and save -*/ void mitk::CoreObjectFactory::CreateFileExtensionsMap() { m_FileExtensionsMap.insert(std::pair("*.dcm", "DICOM files")); m_FileExtensionsMap.insert(std::pair("*.DCM", "DICOM files")); m_FileExtensionsMap.insert(std::pair("*.dc3", "DICOM files")); m_FileExtensionsMap.insert(std::pair("*.DC3", "DICOM files")); m_FileExtensionsMap.insert(std::pair("*.gdcm", "DICOM files")); m_FileExtensionsMap.insert(std::pair("*.seq", "DKFZ Pic")); m_FileExtensionsMap.insert(std::pair("*.pic", "DKFZ Pic")); m_FileExtensionsMap.insert(std::pair("*.pic.gz", "DKFZ Pic")); m_FileExtensionsMap.insert(std::pair("*.mhd", "MetaImage")); m_FileExtensionsMap.insert(std::pair("*.seq.gz", "DKFZ Pic")); m_FileExtensionsMap.insert(std::pair("*.hdr", "Analyze Format")); m_FileExtensionsMap.insert(std::pair("*.img", "Analyze Format")); m_FileExtensionsMap.insert(std::pair("*.img.gz", "Analyze Format")); m_FileExtensionsMap.insert(std::pair("*.nrrd", "Nearly Raw Raster Data")); m_FileExtensionsMap.insert(std::pair("*.nhdr", "NRRD with detached header")); m_FileExtensionsMap.insert(std::pair("*.mps", "Point sets")); m_FileExtensionsMap.insert(std::pair("*.pic", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.pic.gz", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.bmp", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.png", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.jpg", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.jpeg", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.dcm", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.gdcm", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.ima", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.tiff", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.tif", "Sets of 2D slices")); m_FileExtensionsMap.insert(std::pair("*.stl", "Surface files")); m_FileExtensionsMap.insert(std::pair("*.vtk", "Surface files")); m_FileExtensionsMap.insert(std::pair("*.vtp", "Surface files")); m_FileExtensionsMap.insert(std::pair("*.obj", "Surface files")); m_FileExtensionsMap.insert(std::pair("*.nii", "NIfTI format")); m_FileExtensionsMap.insert(std::pair("*.nii.gz", "NIfTI format")); //m_SaveFileExtensionsMap.insert(std::pair("*.pic", "DKFZ Pic")); m_SaveFileExtensionsMap.insert(std::pair("*.mhd", "MetaImage")); m_SaveFileExtensionsMap.insert(std::pair("*.vtk", "Surface Files")); m_SaveFileExtensionsMap.insert(std::pair("*.vti", "VTK Image Data Files")); m_SaveFileExtensionsMap.insert(std::pair("*.hdr", "Analyze Format")); m_SaveFileExtensionsMap.insert(std::pair("*.png", "Sets of 2D slices")); m_SaveFileExtensionsMap.insert(std::pair("*.tiff", "Sets of 2D slices")); m_SaveFileExtensionsMap.insert(std::pair("*.tif", "Sets of 2D slices")); m_SaveFileExtensionsMap.insert(std::pair("*.jpg", "Sets of 2D slices")); m_SaveFileExtensionsMap.insert(std::pair("*.jpeg", "Sets of 2D slices")); m_SaveFileExtensionsMap.insert(std::pair("*.bmp", "Sets of 2D slices")); m_SaveFileExtensionsMap.insert(std::pair("*.dcm", "Sets of 2D slices")); m_SaveFileExtensionsMap.insert(std::pair("*.gipl", "UMDS GIPL Format Files")); m_SaveFileExtensionsMap.insert(std::pair("*.nii", "NIfTI format")); m_SaveFileExtensionsMap.insert(std::pair("*.nrrd", "Nearly Raw Raster Data")); m_SaveFileExtensionsMap.insert(std::pair("*.nhdr", "NRRD with detached header")); m_SaveFileExtensionsMap.insert(std::pair("*.lsm", "Microscope Images")); m_SaveFileExtensionsMap.insert(std::pair("*.dwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair("*.hdwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair("*.qbi", "Q-Ball Images")); m_SaveFileExtensionsMap.insert(std::pair("*.hqbi", "Q-Ball Images")); - - RegisterLegacyReaders(this); - RegisterLegacyWriters(); } -/** -* @brief This method gets the supported (save) file extensions as string. This string is can then used by the QT QFileDialog widget. -* @return The c-string that contains the (save) file extensions -* -*/ const char* mitk::CoreObjectFactory::GetSaveFileExtensions() { MultimapType aMap; for (ExtraFactoriesContainer::iterator it = m_ExtraFactories.begin(); it != m_ExtraFactories.end() ; it++ ) { aMap = (*it)->GetSaveFileExtensionsMap(); this->MergeFileExtensions(m_SaveFileExtensionsMap, aMap); } this->CreateFileExtensions(m_SaveFileExtensionsMap, m_SaveFileExtensions); return m_SaveFileExtensions.c_str(); -}; -/** -* @brief get the defined (save) file extension map -* @return the defined (save) file extension map -*/ + return m_SaveFileExtensions.c_str(); +} + mitk::CoreObjectFactoryBase::MultimapType mitk::CoreObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::GetFileWriters() { FileWriterList allWriters = m_FileWriters; for (ExtraFactoriesContainer::iterator it = m_ExtraFactories.begin(); it != m_ExtraFactories.end() ; it++ ) { - FileWriterList list2 = (*it)->GetFileWriters(); - allWriters.merge(list2); + allWriters.merge((*it)->m_FileWriters); } return allWriters; } void mitk::CoreObjectFactory::MapEvent(const mitk::Event*, const int) { } -void mitk::CoreObjectFactory::RegisterLegacyReaders(mitk::CoreObjectFactoryBase::Pointer factory) +std::string mitk::CoreObjectFactory::GetDescriptionForExtension(const std::string& extension) +{ + std::multimap fileExtensionMap = GetSaveFileExtensionsMap(); + for(std::multimap::iterator it = fileExtensionMap.begin(); it != fileExtensionMap.end(); it++) + if (it->first == extension) return it->second; + return ""; // If no matching extension was found, return emtpy string +} + +void mitk::CoreObjectFactory::RegisterLegacyReaders(mitk::CoreObjectFactoryBase* factory) { - // We are not really interested in the string, but this function will make sure to merge - // all extensions of all registered Factories into the map that we will work with. + // We are not really interested in the string, just call the method since + // many readers initialize the map the first time when this method is called factory->GetFileExtensions(); + std::multimap fileExtensionMap = factory->GetFileExtensionsMap(); for(std::multimap::iterator it = fileExtensionMap.begin(); it != fileExtensionMap.end(); it++) { //only add if no reader already registered under that extension std::string extension = it->first; extension = extension.erase(0,1); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); mitk::FileReaderRegistry readerRegistry; if(readerRegistry.GetReader(it->first) == 0) { mitk::LegacyFileReaderService* lfrs = new mitk::LegacyFileReaderService(extension, it->second); m_LegacyReaders.push_back(lfrs); } } } -std::string mitk::CoreObjectFactory::GetDescriptionForExtension(const std::string& extension) -{ - std::multimap fileExtensionMap = GetSaveFileExtensionsMap(); - for(std::multimap::iterator it = fileExtensionMap.begin(); it != fileExtensionMap.end(); it++) - if (it->first.compare(extension) == 0) return it->second; - return ""; // If no matching extension was found, return emtpy string -} - -void mitk::CoreObjectFactory::RegisterLegacyWriters(/*mitk::CoreObjectFactoryBase::Pointer factory*/) +void mitk::CoreObjectFactory::RegisterLegacyWriters(mitk::CoreObjectFactoryBase* factory) { // Get all external Writers - mitk::CoreObjectFactory::FileWriterList informedWriters = GetFileWriters(); - std::list writers; - - // Upcast List - for(mitk::CoreObjectFactory::FileWriterList::iterator it = informedWriters.begin(); it != informedWriters.end(); it++) - writers.push_back(it->GetPointer()); - - // Add All ImageWriterTypes - mitk::ImageWriter::Pointer dummyWriter = mitk::ImageWriter::New(); - mitk::Image::Pointer dummyImage = mitk::Image::New(); - std::vector extensions = dummyWriter->GetPossibleFileExtensions(); - mitk::FileWriterRegistry writerRegistry; - for(std::vector::iterator ext = extensions.begin(); ext != extensions.end(); ext++) - { - std::string extension = *ext; - if (extension.compare("") == 0) continue; - std::string description = GetDescriptionForExtension("*" + extension); - std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); - if(writerRegistry.GetWriter(extension) == 0) - { - MITK_INFO << extension << "/" << description; - mitk::LegacyImageWriterService* liws = new mitk::LegacyImageWriterService(dummyImage->GetNameOfClass(), extension, description); - m_LegacyImageWriters.push_back(liws); - } - } + mitk::CoreObjectFactory::FileWriterList writers = factory->GetFileWriters(); + + // We are not really interested in the string, just call the method since + // many writers initialize the map the first time when this method is called + factory->GetSaveFileExtensions(); - // Add Aall external Writers - writers.push_back(mitk::PointSetWriter::New().GetPointer()); + MultimapType fileExtensionMap = factory->GetSaveFileExtensionsMap(); - for(std::list::iterator it = writers.begin(); it != writers.end(); it++) + for(mitk::CoreObjectFactory::FileWriterList::iterator it = writers.begin(); it != writers.end(); it++) { - std::vector extensions = it->GetPointer()->GetPossibleFileExtensions(); + std::vector extensions = (*it)->GetPossibleFileExtensions(); for(std::vector::iterator ext = extensions.begin(); ext != extensions.end(); ext++) { + if (ext->empty()) continue; + std::string extension = *ext; - if (extension.compare("") == 0) continue; - std::string description = GetDescriptionForExtension("*" + extension); - //extension = extension.erase(0,1); - std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); - if(writerRegistry.GetWriter(extension) == 0) + std::string extensionWithStar = extension; + if (extension.find_first_of('*') == 0) { - MITK_INFO << extension << "/" << description; - mitk::LegacyFileWriterService* lfws = new mitk::LegacyFileWriterService(it->GetPointer(), "LegacyDataType", extension, description); - m_LegacyWriters.push_back(lfws); + extension.erase(0, 1); } + else + { + extensionWithStar.insert(extensionWithStar.begin(), '*'); + } + + std::string description; + for(MultimapType::iterator fileExtensionIter = fileExtensionMap.begin(); + fileExtensionIter != fileExtensionMap.end(); fileExtensionIter++) + { + if (fileExtensionIter->first == extensionWithStar) + { + description = fileExtensionIter->second; + break; + } + } + + //extension = extension.erase(0,1); + std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); + mitk::LegacyFileWriterService* lfws = new mitk::LegacyFileWriterService(*it, "LegacyDataType", extension, description); + m_LegacyWriters.push_back(lfws); } } } diff --git a/Core/Code/Common/mitkCoreObjectFactory.h b/Core/Code/Common/mitkCoreObjectFactory.h index 5702185953..259db367b2 100644 --- a/Core/Code/Common/mitkCoreObjectFactory.h +++ b/Core/Code/Common/mitkCoreObjectFactory.h @@ -1,71 +1,147 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef COREOBJECTFACTORY_H_INCLUDED #define COREOBJECTFACTORY_H_INCLUDED #include #include #include "mitkCoreObjectFactoryBase.h" #include "mitkFileWriterWithInformation.h" -#include -#include -#include namespace mitk { class Event; +class LegacyFileReaderService; +class LegacyFileWriterService; +class LegacyImageWriterService; class MITK_CORE_EXPORT CoreObjectFactory : public CoreObjectFactoryBase { - public: - mitkClassMacro(CoreObjectFactory,CoreObjectFactoryBase); - itkFactorylessNewMacro(CoreObjectFactory); - virtual Mapper::Pointer CreateMapper(mitk::DataNode* node, MapperSlotId slotId); - virtual void SetDefaultProperties(mitk::DataNode* node); - virtual const char* GetFileExtensions(); - virtual MultimapType GetFileExtensionsMap(); - virtual const char* GetSaveFileExtensions(); - virtual MultimapType GetSaveFileExtensionsMap(); - virtual FileWriterList GetFileWriters(); - virtual void MapEvent(const mitk::Event* event, const int eventID); - virtual void RegisterExtraFactory(CoreObjectFactoryBase* factory); - virtual void UnRegisterExtraFactory(CoreObjectFactoryBase* factory); - static Pointer GetInstance(); - void RegisterLegacyReaders(mitk::CoreObjectFactoryBase::Pointer factory); - void RegisterLegacyWriters(/*mitk::CoreObjectFactoryBase::Pointer factory*/); - std::string GetDescriptionForExtension(const std::string& extension); - protected: - CoreObjectFactory(); - void MergeFileExtensions(MultimapType& fileExtensionsMap, MultimapType inputMap); - void CreateFileExtensionsMap(); - void CreateSaveFileExtensions(); - typedef std::set ExtraFactoriesContainer; - ExtraFactoriesContainer m_ExtraFactories; - static FileWriterList m_FileWriters; - std::string m_FileExtensions; - MultimapType m_FileExtensionsMap; - std::string m_SaveFileExtensions; - MultimapType m_SaveFileExtensionsMap; - static std::list< mitk::LegacyFileReaderService* > m_LegacyReaders; - static std::list< mitk::LegacyFileWriterService* > m_LegacyWriters; - static std::list< mitk::LegacyImageWriterService* > m_LegacyImageWriters; + +public: + + mitkClassMacro(CoreObjectFactory,CoreObjectFactoryBase) + itkFactorylessNewMacro(CoreObjectFactory) + + virtual Mapper::Pointer CreateMapper(mitk::DataNode* node, MapperSlotId slotId); + virtual void SetDefaultProperties(mitk::DataNode* node); + + virtual void MapEvent(const mitk::Event* event, const int eventID); + + virtual void RegisterExtraFactory(CoreObjectFactoryBase* factory); + virtual void UnRegisterExtraFactory(CoreObjectFactoryBase* factory); + + static Pointer GetInstance(); + + ~CoreObjectFactory(); + + /** + * @brief This method gets the supported (open) file extensions as string. + * + * This string can then used by the Qt QFileDialog widget. + * + * @return The c-string that contains the file extensions + * @deprecatedSince{2013_09} See mitk::FileReaderRegistry and QmitkIOUtil + */ + DEPRECATED(virtual const char* GetFileExtensions()); + + /** + * @brief get the defined (open) file extension map + * + * @return the defined (open) file extension map + * @deprecatedSince{2013_09} See mitk::FileReaderRegistry and QmitkIOUtil + */ + DEPRECATED(virtual MultimapType GetFileExtensionsMap()); + + /** + * @brief This method gets the supported (save) file extensions as string. + * + * This string can then used by the Qt QFileDialog widget. + * + * @return The c-string that contains the (save) file extensions + * @deprecatedSince{2013_09} See mitk::FileWriterRegistry and QmitkIOUtil + */ + DEPRECATED(virtual const char* GetSaveFileExtensions()); + + /** + * @brief get the defined (save) file extension map + * + * @return the defined (save) file extension map + * @deprecatedSince{2013_09} See mitk::FileWriterRegistry and QmitkIOUtil + */ + virtual MultimapType GetSaveFileExtensionsMap(); + + /** + * @deprecatedSince{2013_09} See mitk::FileWriterRegistry + */ + DEPRECATED(virtual FileWriterList GetFileWriters()); + + /** + * @deprecatedSince{2013_09} See mitk::FileWriterRegistry and QmitkIOUtil + */ + DEPRECATED(std::string GetDescriptionForExtension(const std::string& extension)); + +protected: + + CoreObjectFactory(); + + /** + * @brief Merge the input map into the fileExtensionsMap. Duplicate entries are removed + * + * @param fileExtensionsMap the existing map, it contains value pairs like + * ("*.dcm", "DICOM files"),("*.dc3", "DICOM files"). + * This map is extented/merged with the values from the input map. + * @param inputMap the input map, it contains value pairs like ("*.dcm", + * "DICOM files"),("*.dc3", "DICOM files") returned by the extra factories. + * @deprecatedSince{2013_09} + */ + void MergeFileExtensions(MultimapType& fileExtensionsMap, MultimapType inputMap); + + /** + * @brief initialize the file extension entries for open and save + * @deprecatedSince{2013_09} + */ + void CreateFileExtensionsMap(); + + /** + * @deprecatedSince{2013_09} + */ + DEPRECATED(void CreateSaveFileExtensions()); + + typedef std::set ExtraFactoriesContainer; + + ExtraFactoriesContainer m_ExtraFactories; + FileWriterList m_FileWriters; + std::string m_FileExtensions; + MultimapType m_FileExtensionsMap; + std::string m_SaveFileExtensions; + MultimapType m_SaveFileExtensionsMap; + +private: + + void RegisterLegacyReaders(mitk::CoreObjectFactoryBase* factory); + void RegisterLegacyWriters(mitk::CoreObjectFactoryBase* factory); + + std::list< mitk::LegacyFileReaderService* > m_LegacyReaders; + std::list< mitk::LegacyFileWriterService* > m_LegacyWriters; + }; } // namespace mitk #endif diff --git a/Core/Code/Common/mitkCoreObjectFactoryBase.h b/Core/Code/Common/mitkCoreObjectFactoryBase.h index ee5a4f4bae..9452d605e1 100644 --- a/Core/Code/Common/mitkCoreObjectFactoryBase.h +++ b/Core/Code/Common/mitkCoreObjectFactoryBase.h @@ -1,78 +1,107 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef COREOBJECTFACTORYBASE_H_INCLUDED #define COREOBJECTFACTORYBASE_H_INCLUDED // the mbilog header is necessary for CMake test drivers. // Since the EXTRA_INCLUDE parameter of CREATE_TEST_SOURCELIST only // allows one extra include file, we specify mitkLog.h here so it will // be available to all classes implementing this interface. #include "mitkLog.h" #include #include "mitkMapper.h" #include #include #include "mitkFileWriterWithInformation.h" namespace mitk { class DataNode; //## @brief base-class for factories of certain mitk objects. //## @ingroup Algorithms //## This interface can be implemented by factories which add new mapper classes or extend the //## data tree deserialization mechanism. class MITK_CORE_EXPORT CoreObjectFactoryBase : public itk::Object { public: + typedef std::list FileWriterList; typedef std::multimap MultimapType; - mitkClassMacro(CoreObjectFactoryBase,itk::Object); + + mitkClassMacro(CoreObjectFactoryBase,itk::Object) + virtual Mapper::Pointer CreateMapper(mitk::DataNode* node, MapperSlotId slotId) = 0; virtual void SetDefaultProperties(mitk::DataNode* node) = 0; + + /** + * @deprecatedSince{2013_09} See mitk::FileReaderRegistry and QmitkIOUtil + */ virtual const char* GetFileExtensions() = 0; + + /** + * @deprecatedSince{2013_09} See mitk::FileReaderRegistry and QmitkIOUtil + */ virtual MultimapType GetFileExtensionsMap() = 0; + + /** + * @deprecatedSince{2013_09} See mitk::FileWriterRegistry and QmitkIOUtil + */ virtual const char* GetSaveFileExtensions() = 0; + + /** + * @deprecatedSince{2013_09} See mitk::FileWriterRegistry and QmitkIOUtil + */ virtual MultimapType GetSaveFileExtensionsMap() = 0; + virtual const char* GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } virtual const char* GetDescription() const { return "Core Object Factory"; } - FileWriterList GetFileWriters() { + + /** + * @deprecatedSince{2013_09} See mitk::FileWriterRegistry + */ + FileWriterList GetFileWriters() + { return m_FileWriters; } protected: /** * @brief create a string from a map that contains the file extensions * @param fileExtensionsMap input map with the file extensions, e.g. ("*.dcm", "DICOM files")("*.dc3", "DICOM files") * @param fileExtensions the converted output string, suitable for the QT QFileDialog widget * e.g. "all (*.dcm *.DCM *.dc3 ... *.vti *.hdr *.nrrd *.nhdr );;Q-Ball Images (*.hqbi *qbi)" + * + * @deprecatedSince{2013_09} */ static void CreateFileExtensions(MultimapType fileExtensionsMap, std::string& fileExtensions); FileWriterList m_FileWriters; + + friend class CoreObjectFactory; }; } #endif diff --git a/Core/Code/Controllers/mitkCoreActivator.cpp b/Core/Code/Controllers/mitkCoreActivator.cpp index 4eebfc0bd9..dba8dae899 100644 --- a/Core/Code/Controllers/mitkCoreActivator.cpp +++ b/Core/Code/Controllers/mitkCoreActivator.cpp @@ -1,222 +1,217 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Rendering #include "mitkRenderingManager.h" #include "mitkPlanePositionManager.h" -#include #include #include #include #include #include #include // File IO #include #include #include #include // Microservices #include #include #include #include #include #include #include void HandleMicroServicesMessages(us::MsgType type, const char* msg) { switch (type) { case us::DebugMsg: MITK_DEBUG << msg; break; case us::InfoMsg: MITK_INFO << msg; break; case us::WarningMsg: MITK_WARN << msg; break; case us::ErrorMsg: MITK_ERROR << msg; break; } } void AddMitkAutoLoadPaths(const std::string& programPath) { us::ModuleSettings::AddAutoLoadPath(programPath); #ifdef __APPLE__ // Walk up three directories since that is where the .dylib files are located // for build trees. std::string additionalPath = programPath; bool addPath = true; for(int i = 0; i < 3; ++i) { std::size_t index = additionalPath.find_last_of('/'); if (index != std::string::npos) { additionalPath = additionalPath.substr(0, index); } else { addPath = false; break; } } if (addPath) { us::ModuleSettings::AddAutoLoadPath(additionalPath); } #endif } /* * This is the module activator for the "Mitk" module. It registers core services * like ... */ class MitkCoreActivator : public us::ModuleActivator { public: void Load(us::ModuleContext* context) { // Handle messages from CppMicroServices us::installMsgHandler(HandleMicroServicesMessages); // Add the current application directory to the auto-load paths. // This is useful for third-party executables. std::string programPath = mitk::IOUtil::GetProgramPath(); if (programPath.empty()) { MITK_WARN << "Could not get the program path."; } else { AddMitkAutoLoadPaths(programPath); } //m_RenderingManager = mitk::RenderingManager::New(); //context->RegisterService(renderingManager.GetPointer()); m_PlanePositionManager.reset(new mitk::PlanePositionManagerService); context->RegisterService(m_PlanePositionManager.get()); - m_CoreDataNodeReader.reset(new mitk::CoreDataNodeReader); - context->RegisterService(m_CoreDataNodeReader.get()); - m_ShaderRepository.reset(new mitk::ShaderRepository); context->RegisterService(m_ShaderRepository.get()); m_PropertyAliases.reset(new mitk::PropertyAliases); context->RegisterService(m_PropertyAliases.get()); m_PropertyDescriptions.reset(new mitk::PropertyDescriptions); context->RegisterService(m_PropertyDescriptions.get()); m_PropertyExtensions.reset(new mitk::PropertyExtensions); context->RegisterService(m_PropertyExtensions.get()); m_PropertyFilters.reset(new mitk::PropertyFilters); context->RegisterService(m_PropertyFilters.get()); context->AddModuleListener(this, &MitkCoreActivator::HandleModuleEvent); // Add Reader / Writer Services mitk::IFileReader* reader; // mitk::IFileWriter* writer; reader = new mitk::PointSetReaderService(); m_FileReaders.push_back(reader); /* There IS an option to exchange ALL vtkTexture instances against vtkNeverTranslucentTextureFactory. This code is left here as a reminder, just in case we might need to do that some time. vtkNeverTranslucentTextureFactory* textureFactory = vtkNeverTranslucentTextureFactory::New(); vtkObjectFactory::RegisterFactory( textureFactory ); textureFactory->Delete(); */ } void Unload(us::ModuleContext* ) { // The mitk::ModuleContext* argument of the Unload() method // will always be 0 for the Mitk library. It makes no sense // to use it at this stage anyway, since all libraries which // know about the module system have already been unloaded. } private: void HandleModuleEvent(const us::ModuleEvent moduleEvent); std::map > moduleIdToShaderIds; //mitk::RenderingManager::Pointer m_RenderingManager; std::auto_ptr m_PlanePositionManager; - std::auto_ptr m_CoreDataNodeReader; std::auto_ptr m_ShaderRepository; std::auto_ptr m_PropertyAliases; std::auto_ptr m_PropertyDescriptions; std::auto_ptr m_PropertyExtensions; std::auto_ptr m_PropertyFilters; // File IO std::vector m_FileReaders; std::vector m_FileWriters; }; void MitkCoreActivator::HandleModuleEvent(const us::ModuleEvent moduleEvent) { if (moduleEvent.GetType() == us::ModuleEvent::LOADED) { // search and load shader files std::vector shaderResoruces = moduleEvent.GetModule()->FindResources("Shaders", "*.xml", true); for (std::vector::iterator i = shaderResoruces.begin(); i != shaderResoruces.end(); ++i) { if (*i) { us::ModuleResourceStream rs(*i); int id = m_ShaderRepository->LoadShader(rs, i->GetBaseName()); if (id >= 0) { moduleIdToShaderIds[moduleEvent.GetModule()->GetModuleId()].push_back(id); } } } } else if (moduleEvent.GetType() == us::ModuleEvent::UNLOADED) { std::map >::iterator shaderIdsIter = moduleIdToShaderIds.find(moduleEvent.GetModule()->GetModuleId()); if (shaderIdsIter != moduleIdToShaderIds.end()) { for (std::vector::iterator idIter = shaderIdsIter->second.begin(); idIter != shaderIdsIter->second.end(); ++idIter) { m_ShaderRepository->UnloadShader(*idIter); } moduleIdToShaderIds.erase(shaderIdsIter); } } } US_EXPORT_MODULE_ACTIVATOR(Mitk, MitkCoreActivator) diff --git a/Core/Code/IO/mitkAbstractFileReader.cpp b/Core/Code/IO/mitkAbstractFileReader.cpp index 671ed33a8a..bb8e043c1b 100644 --- a/Core/Code/IO/mitkAbstractFileReader.cpp +++ b/Core/Code/IO/mitkAbstractFileReader.cpp @@ -1,179 +1,178 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include mitk::AbstractFileReader::AbstractFileReader() : m_Priority (0) , m_PrototypeFactory(NULL) { } mitk::AbstractFileReader::~AbstractFileReader() { delete m_PrototypeFactory; } mitk::AbstractFileReader::AbstractFileReader(const mitk::AbstractFileReader& other) : m_Extension(other.m_Extension) , m_Description(other.m_Description) , m_Priority(other.m_Priority) , m_Options(other.m_Options) , m_PrototypeFactory(NULL) { } mitk::AbstractFileReader::AbstractFileReader(const std::string& extension, const std::string& description) : m_Extension (extension) , m_Description (description) , m_Priority (0) , m_PrototypeFactory(NULL) { } ////////////////////// Reading ///////////////////////// std::vector< itk::SmartPointer > mitk::AbstractFileReader::Read(const std::string& path, mitk::DataStorage* /*ds*/) { if (! itksys::SystemTools::FileExists(path.c_str())) mitkThrow() << "File '" + path + "' not found."; std::ifstream stream; stream.open(path.c_str()); return this->Read(stream); } std::vector< itk::SmartPointer > mitk::AbstractFileReader::Read(const std::istream& stream, mitk::DataStorage* ds) { // Create a temporary file and copy the data to it std::ofstream tmpOutputStream; std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpOutputStream); tmpOutputStream << stream.rdbuf(); tmpOutputStream.close(); // Now read from the temporary file std::vector< itk::SmartPointer > result = this->Read(tmpFilePath, ds); std::remove(tmpFilePath.c_str()); return result; } //////////// µS Registration & Properties ////////////// us::ServiceRegistration mitk::AbstractFileReader::RegisterService(us::ModuleContext* context) { if (m_PrototypeFactory) return us::ServiceRegistration(); struct PrototypeFactory : public us::PrototypeServiceFactory { mitk::AbstractFileReader* const m_Prototype; PrototypeFactory(mitk::AbstractFileReader* prototype) : m_Prototype(prototype) {} us::InterfaceMap GetService(us::Module* /*module*/, const us::ServiceRegistrationBase& /*registration*/) { return us::MakeInterfaceMap(m_Prototype->Clone()); } void UngetService(us::Module* /*module*/, const us::ServiceRegistrationBase& /*registration*/, const us::InterfaceMap& service) { delete us::ExtractInterface(service); } }; m_PrototypeFactory = new PrototypeFactory(this); us::ServiceProperties props = this->GetServiceProperties(); return context->RegisterService(m_PrototypeFactory, props); } -us::ServiceProperties mitk::AbstractFileReader::GetServiceProperties() +us::ServiceProperties mitk::AbstractFileReader::GetServiceProperties() const { if ( m_Extension.empty() ) MITK_WARN << "Registered a Reader with no extension defined (m_Extension is empty). Reader will not be found by calls from ReaderManager.)"; if ( m_Description.empty() ) MITK_WARN << "Registered a Reader with no description defined (m_Description is empty). Reader will have no human readable extension information in FileDialogs.)"; - std::transform(m_Extension.begin(), m_Extension.end(), m_Extension.begin(), ::tolower); us::ServiceProperties result; - result[mitk::IFileReader::PROP_EXTENSION] = m_Extension; - result[mitk::IFileReader::PROP_DESCRIPTION] = m_Description; + result[mitk::IFileReader::PROP_EXTENSION()] = m_Extension; + result[mitk::IFileReader::PROP_DESCRIPTION()] = m_Description; result[us::ServiceConstants::SERVICE_RANKING()] = m_Priority; for (mitk::IFileReader::OptionList::const_iterator it = m_Options.begin(); it != m_Options.end(); ++it) { if (it->second) result[it->first] = std::string("true"); else result[it->first] = std::string("false"); } return result; } //////////////////////// Options /////////////////////// mitk::IFileReader::OptionList mitk::AbstractFileReader::GetOptions() const { return m_Options; } void mitk::AbstractFileReader::SetOptions(const mitk::IFileReader::OptionList& options) { if (options.size() != m_Options.size()) MITK_WARN << "Number of set Options differs from Number of available Options, which is a sign of false usage. Please consult documentation"; m_Options = options; } ////////////////// MISC ////////////////// bool mitk::AbstractFileReader::CanRead(const std::string& path) const { // Default implementation only checks if extension is correct std::string pathEnd = path.substr( path.length() - m_Extension.length(), m_Extension.length() ); return (m_Extension == pathEnd); } void mitk::AbstractFileReader::AddProgressCallback(const mitk::MessageAbstractDelegate& callback) { } void mitk::AbstractFileReader::RemoveProgressCallback(const mitk::MessageAbstractDelegate& callback) { } ////////////////// µS related Getters ////////////////// int mitk::AbstractFileReader::GetPriority() const { return m_Priority; } std::string mitk::AbstractFileReader::GetExtension() const { return m_Extension; } std::string mitk::AbstractFileReader::GetDescription() const { return m_Description; } diff --git a/Core/Code/IO/mitkAbstractFileReader.h b/Core/Code/IO/mitkAbstractFileReader.h index 92c6623307..68166501c1 100644 --- a/Core/Code/IO/mitkAbstractFileReader.h +++ b/Core/Code/IO/mitkAbstractFileReader.h @@ -1,99 +1,101 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 #define AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 // Macro #include // MITK #include #include // Microservices #include #include #include namespace us { struct PrototypeServiceFactory; } namespace mitk { - //##Documentation - //## @brief Interface class of readers that read from files - //## @ingroup Process - class MITK_CORE_EXPORT AbstractFileReader : public mitk::IFileReader - { - public: - virtual std::vector< itk::SmartPointer > Read(const std::string& path, mitk::DataStorage *ds = 0 ); +/** + * @brief Interface class of readers that read from files + * @ingroup Process + */ +class MITK_CORE_EXPORT AbstractFileReader : public mitk::IFileReader +{ - virtual std::vector< itk::SmartPointer > Read(const std::istream& stream, mitk::DataStorage *ds = 0 ) = 0; +public: - virtual int GetPriority() const; + virtual std::vector< itk::SmartPointer > Read(const std::string& path, mitk::DataStorage *ds = 0 ); - virtual std::string GetExtension() const; + virtual std::vector< itk::SmartPointer > Read(const std::istream& stream, mitk::DataStorage *ds = 0 ) = 0; - virtual std::string GetDescription() const; + virtual int GetPriority() const; - virtual mitk::IFileReader::OptionList GetOptions() const; + virtual std::string GetExtension() const; - virtual void SetOptions(const mitk::IFileReader::OptionList& options); + virtual std::string GetDescription() const; - virtual bool CanRead(const std::string& path) const; + virtual mitk::IFileReader::OptionList GetOptions() const; - virtual void AddProgressCallback(const mitk::MessageAbstractDelegate& callback); + virtual void SetOptions(const mitk::IFileReader::OptionList& options); - virtual void RemoveProgressCallback(const mitk::MessageAbstractDelegate& callback); + virtual bool CanRead(const std::string& path) const; - us::ServiceRegistration RegisterService(us::ModuleContext* context = us::GetModuleContext()); + virtual void AddProgressCallback(const mitk::MessageAbstractDelegate& callback); - protected: - AbstractFileReader(); - ~AbstractFileReader(); + virtual void RemoveProgressCallback(const mitk::MessageAbstractDelegate& callback); - AbstractFileReader(const AbstractFileReader& other); + us::ServiceRegistration RegisterService(us::ModuleContext* context = us::GetModuleContext()); - AbstractFileReader(const std::string& extension, const std::string& description); +protected: - // Minimal Service Properties: ALWAYS SET THESE IN CONSTRUCTOR OF DERIVED CLASSES! - std::string m_Extension; - std::string m_Description; - int m_Priority; + AbstractFileReader(); + ~AbstractFileReader(); - /** - * \brief Options supported by this reader. Set sensible default values! - * - * Can be left emtpy if no special options are required. - */ - mitk::IFileReader::OptionList m_Options; + AbstractFileReader(const AbstractFileReader& other); - virtual us::ServiceProperties GetServiceProperties(); + AbstractFileReader(const std::string& extension, const std::string& description); - private: + // Minimal Service Properties: ALWAYS SET THESE IN CONSTRUCTOR OF DERIVED CLASSES! + std::string m_Extension; + std::string m_Description; + int m_Priority; - us::PrototypeServiceFactory* m_PrototypeFactory; + /** + * \brief Options supported by this reader. Set sensible default values! + * + * Can be left emtpy if no special options are required. + */ + mitk::IFileReader::OptionList m_Options; - virtual mitk::IFileReader* Clone() const = 0; - }; -} // namespace mitk + virtual us::ServiceProperties GetServiceProperties() const; + +private: + + us::PrototypeServiceFactory* m_PrototypeFactory; -// This is the microservice declaration. Do not meddle! -US_DECLARE_SERVICE_INTERFACE(mitk::AbstractFileReader, "org.mitk.services.FileReader") + virtual mitk::IFileReader* Clone() const = 0; +}; + +} // namespace mitk #endif /* AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/IO/mitkAbstractFileWriter.cpp b/Core/Code/IO/mitkAbstractFileWriter.cpp index 54fcc9d00a..fa3eac51ff 100644 --- a/Core/Code/IO/mitkAbstractFileWriter.cpp +++ b/Core/Code/IO/mitkAbstractFileWriter.cpp @@ -1,185 +1,185 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include #include #include #include mitk::AbstractFileWriter::AbstractFileWriter() : m_Priority (0) , m_PrototypeFactory(NULL) { } mitk::AbstractFileWriter::~AbstractFileWriter() { delete m_PrototypeFactory; } mitk::AbstractFileWriter::AbstractFileWriter(const mitk::AbstractFileWriter& other) : m_Extension(other.m_Extension) , m_BasedataType(other.m_BasedataType) , m_Description(other.m_Description) , m_Priority(other.m_Priority) , m_Options(other.m_Options) , m_PrototypeFactory(NULL) { } mitk::AbstractFileWriter::AbstractFileWriter(const std::string& basedataType, const std::string& extension, const std::string& description) : m_Extension (extension) , m_BasedataType(basedataType) , m_Description (description) , m_Priority (0) , m_PrototypeFactory(NULL) { } ////////////////////// Writing ///////////////////////// void mitk::AbstractFileWriter::Write(const BaseData* data, const std::string& path) { std::ofstream stream; stream.open(path.c_str()); this->Write(data, stream); } void mitk::AbstractFileWriter::Write(const mitk::BaseData* data, std::ostream& stream) { // Create a temporary file and write the data to it std::ofstream tmpOutputStream; std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpOutputStream); this->Write(data, tmpFilePath); tmpOutputStream.close(); // Now copy the contents std::ifstream tmpInputStream(tmpFilePath.c_str(), std::ios_base::binary); stream << tmpInputStream.rdbuf(); tmpInputStream.close(); std::remove(tmpFilePath.c_str()); } //////////// µS Registration & Properties ////////////// us::ServiceRegistration mitk::AbstractFileWriter::RegisterService(us::ModuleContext* context) { if (m_PrototypeFactory) return us::ServiceRegistration(); struct PrototypeFactory : public us::PrototypeServiceFactory { mitk::AbstractFileWriter* const m_Prototype; PrototypeFactory(mitk::AbstractFileWriter* prototype) : m_Prototype(prototype) {} us::InterfaceMap GetService(us::Module* /*module*/, const us::ServiceRegistrationBase& /*registration*/) { return us::MakeInterfaceMap(m_Prototype->Clone()); } void UngetService(us::Module* /*module*/, const us::ServiceRegistrationBase& /*registration*/, const us::InterfaceMap& service) { delete us::ExtractInterface(service); } }; m_PrototypeFactory = new PrototypeFactory(this); us::ServiceProperties props = this->GetServiceProperties(); return context->RegisterService(m_PrototypeFactory, props); } -us::ServiceProperties mitk::AbstractFileWriter::GetServiceProperties() +us::ServiceProperties mitk::AbstractFileWriter::GetServiceProperties() const { if ( m_Extension.empty() ) MITK_WARN << "Registered a Writer with no extension defined (m_Extension is empty). Writer will not be found by calls from WriterManager.)"; if ( m_BasedataType.empty() ) MITK_WARN << "Registered a Writer with no BasedataType defined (m_BasedataType is empty). Writer will not be found by calls from WriterManager.)"; if ( m_Description.empty() ) MITK_WARN << "Registered a Writer with no description defined (m_Description is empty). Writer will have no human readable extension information in FileDialogs.)"; us::ServiceProperties result; - result[mitk::IFileWriter::PROP_EXTENSION] = m_Extension; - result[mitk::IFileWriter::PROP_DESCRIPTION] = m_Description; - result[mitk::IFileWriter::PROP_BASEDATA_TYPE] = m_BasedataType; + result[mitk::IFileWriter::PROP_EXTENSION()] = m_Extension; + result[mitk::IFileWriter::PROP_DESCRIPTION()] = m_Description; + result[mitk::IFileWriter::PROP_BASEDATA_TYPE()] = m_BasedataType; result[us::ServiceConstants::SERVICE_RANKING()] = m_Priority; for (mitk::IFileWriter::OptionList::const_iterator it = m_Options.begin(); it != m_Options.end(); ++it) { result[it->first] = std::string("true"); } return result; } //////////////////////// Options /////////////////////// mitk::IFileWriter::OptionList mitk::AbstractFileWriter::GetOptions() const { return m_Options; } void mitk::AbstractFileWriter::SetOptions(const OptionList& options) { if (options.size() != m_Options.size()) MITK_WARN << "Number of set Options differs from Number of available Options, which is a sign of false usage. Please consult documentation"; m_Options = options; } ////////////////// MISC ////////////////// bool mitk::AbstractFileWriter::CanWrite(const BaseData* data) const { // Default implementation only checks if basedatatype is correct std::string externalDataType = data->GetNameOfClass(); return (externalDataType == m_BasedataType); } float mitk::AbstractFileWriter::GetProgress() const { // Default implementation always returns 1 (finished) return 1; } ////////////////// µS related Getters ////////////////// int mitk::AbstractFileWriter::GetPriority() const { return m_Priority; } std::string mitk::AbstractFileWriter::GetExtension() const { return m_Extension; } std::string mitk::AbstractFileWriter::GetDescription() const { return m_Description; } std::string mitk::AbstractFileWriter::GetSupportedBasedataType() const { return m_BasedataType; } diff --git a/Core/Code/IO/mitkAbstractFileWriter.h b/Core/Code/IO/mitkAbstractFileWriter.h index 9951cf9ca3..b045ccbe7d 100644 --- a/Core/Code/IO/mitkAbstractFileWriter.h +++ b/Core/Code/IO/mitkAbstractFileWriter.h @@ -1,160 +1,160 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef AbstractFileWriter_H_HEADER_INCLUDED_C1E7E521 #define AbstractFileWriter_H_HEADER_INCLUDED_C1E7E521 // Macro #include // MITK #include // Microservices #include #include #include namespace us { struct PrototypeServiceFactory; } namespace mitk { /** * @brief This abstract class gives a meaningful default implementations to most methods of mitkIFileWriter.h. * * In general, all FileWriters should derive from this class, this way it is made sure that the new implementation is * exposed to the Microservice-Framework and that is automatically available troughout MITK. * The default implementation only requires the two write * methods and the Clone() method to be implemented. Be sure to set all important members in the constructor. These are: *
    *
  • m_Extension: To define which file extension can be written. *
  • m_Description: To give a human readable name for this writer to be displayed in FileDialogs. *
  • m_BasedataType: To define which type of Basedata this fileWriter can handle. *
  • (Optional) m_Priority: To make this writer rank higher when choosing writers automatically *
  • (Optional) m_SupportedOptions: To define which options this writer can handle. Options can modify writing behaviour (e.g. set a compression) *
* You can also use the protected constructor for this. * * @ingroup Process */ class MITK_CORE_EXPORT AbstractFileWriter : public mitk::IFileWriter { public: /** * \brief Write the data in data to the the location specified in path */ virtual void Write(const BaseData* data, const std::string& path); /** * \brief Write the data in data to the the stream specified in stream */ virtual void Write(const BaseData* data, std::ostream& stream ) = 0; /** * \brief Returns the priority which defined how 'good' the FileWriter can handle it's file format. * * Default is zero and should only be chosen differently for a reason. * The priority is intended to be used by the MicroserviceFramework to determine * which reader to use if several equivalent readers have been found. * It may be used to replace a default reader from MITK in your own project. * E.g. if you want to use your own reader for *.nrrd files instead of the default, * implement it and give it a higher priority than zero. * * This method has a default implementation and need not be reimplemented, simply set m_Priority in the constructor. */ virtual int GetPriority() const; /** * \brief returns the file extension that this FileWriter is able to handle. * * Please enter only the characters after the fullstop, e.g "nrrd" is correct * while "*.nrrd" and ".nrrd" are incorrect. * * This method has a default implementation and need not be reimplemented, simply set m_Extension in the constructor. */ virtual std::string GetExtension() const; /** * \brief returns the name of the itk Basedata that this FileWriter is able to handle. * * The correct value is the one given as the first parameter in the ItkNewMacro of that Basedata derivate. * You can also retrieve it by calling GetNameOfClass() on an instance of said data. * * This method has a default implementation and need not be reimplemented, simply set m_BaseDataType in the constructor. */ virtual std::string GetSupportedBasedataType() const; /** * \brief Returns a human readable description of the file format. * * This will be used in FileDialogs for example. * This method has a default implementation and need not be reimplemented, simply set m_BaseDataType in the constructor. */ virtual std::string GetDescription() const; /** * \brief returns a list of the supported Options * * Options are strings that are treated as flags when passed to the read method. */ virtual OptionList GetOptions() const; virtual void SetOptions(const OptionList& options); /** * \brief Return true if this writer can confirm that it can read this file and false otherwise. * * The default implementation of AbstractFileWriter checks if the supplied filename is of the same extension as m_extension. * Overwrite this method if you require more specific behaviour */ virtual bool CanWrite(const BaseData* data) const; /** * \brief Returns a value between 0 and 1 depending on the progress of the writing process. * This method need not necessarily be implemented, always returning zero is accepted. */ virtual float GetProgress() const; us::ServiceRegistration RegisterService(us::ModuleContext* context = us::GetModuleContext()); protected: AbstractFileWriter(); ~AbstractFileWriter(); AbstractFileWriter(const AbstractFileWriter& other); AbstractFileWriter(const std::string& basedataType, const std::string& extension, const std::string& description); // Minimal Service Properties: ALWAYS SET THESE IN CONSTRUCTOR OF DERIVED CLASSES! std::string m_Extension; std::string m_BasedataType; std::string m_Description; int m_Priority; OptionList m_Options; // Options supported by this Writer. Can be left emtpy if no special options are required - virtual us::ServiceProperties GetServiceProperties(); + virtual us::ServiceProperties GetServiceProperties() const; private: us::PrototypeServiceFactory* m_PrototypeFactory; virtual mitk::IFileWriter* Clone() const = 0; }; } // namespace mitk #endif /* AbstractFileWriter_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/IO/mitkCoreDataNodeReader.cpp b/Core/Code/IO/mitkCoreDataNodeReader.cpp deleted file mode 100644 index 2664e37207..0000000000 --- a/Core/Code/IO/mitkCoreDataNodeReader.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#include "mitkCoreDataNodeReader.h" - -#include -#include - -namespace mitk { - -int CoreDataNodeReader::Read(const std::string &fileName, DataStorage &storage) -{ - mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); - - // the ITK Nrrd file reader cannot handle '/' in file path on Win 64bit - std::string name(fileName); - std::replace(name.begin(), name.end(), '\\', '/'); - nodeReader->SetFileName(name); - nodeReader->Update(); - int n = 0; - for ( unsigned int i = 0 ; i < nodeReader->GetNumberOfOutputs( ); ++i ) - { - mitk::DataNode::Pointer node; - node = nodeReader->GetOutput(i); - if ( node->GetData() != NULL ) - { - storage.Add(node); - ++n; - } - } - return n; -} - -} diff --git a/Core/Code/IO/mitkCoreDataNodeReader.h b/Core/Code/IO/mitkCoreDataNodeReader.h deleted file mode 100644 index a396f45d8e..0000000000 --- a/Core/Code/IO/mitkCoreDataNodeReader.h +++ /dev/null @@ -1,34 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef MITKCOREDATANODEREADER_H -#define MITKCOREDATANODEREADER_H - -#include - -namespace mitk { - -class CoreDataNodeReader : public mitk::IDataNodeReader -{ -public: - - int Read(const std::string& fileName, mitk::DataStorage& storage); -}; - -} - -#endif // MITKCOREDATANODEREADER_H diff --git a/Core/Code/IO/mitkFileReader.h b/Core/Code/IO/mitkFileReader.h index 3a9f2afc28..ec6ccf7f88 100644 --- a/Core/Code/IO/mitkFileReader.h +++ b/Core/Code/IO/mitkFileReader.h @@ -1,106 +1,107 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef FILEREADER_H_HEADER_INCLUDED_C1E7E521 #define FILEREADER_H_HEADER_INCLUDED_C1E7E521 #include namespace mitk { //##Documentation //## @brief Interface class of readers that read from files //## @ingroup Process +//## @deprecatedSince{2013_09} Use mitk::IFileReader instead. class MITK_CORE_EXPORT FileReader { public: //##Documentation //## @brief Get the specified the file to load. //## //## Either the FileName or FilePrefix plus FilePattern are used to read. virtual const char* GetFileName() const = 0; //##Documentation //## @brief Specify the file to load. //## //## Either the FileName or FilePrefix plus FilePattern are used to read. virtual void SetFileName(const char* aFileName) = 0; //##Documentation //## @brief Get the specified file prefix for the file(s) to load. //## //## You should specify either a FileName or FilePrefix. Use FilePrefix if //## the data is stored in multiple files. virtual const char* GetFilePrefix() const = 0; //##Documentation //## @brief Specify file prefix for the file(s) to load. //## //## You should specify either a FileName or FilePrefix. Use FilePrefix if //## the data is stored in multiple files. virtual void SetFilePrefix(const char* aFilePrefix) = 0; //##Documentation //## @brief Get the specified file pattern for the file(s) to load. The //## sprintf format used to build filename from FilePrefix and number. //## //## You should specify either a FileName or FilePrefix. Use FilePrefix if //## the data is stored in multiple files. virtual const char* GetFilePattern() const = 0; /** @brief Specified file pattern for the file(s) to load. The sprintf format used to build filename from FilePrefix and number. You should specify either a FileName or FilePrefix. Use FilePrefix if the data is stored in multiple files. */ virtual void SetFilePattern(const char* aFilePattern) = 0; /** @brief Specifies, whether the file reader also can read a file from a memory buffer */ virtual bool CanReadFromMemory( ); // TODO Eliminieren, stattdessen abstrakte Klasse welche nach unten StrStream bereitstellt /** @brief Set/Get functions to advise the file reader to use a memory array for reading a file*/ virtual void SetReadFromMemory( bool read ); virtual bool GetReadFromMemory( ); /** @brief To be used along with a call of SetReadFromMemory(true). This sets the memory buffer and the size from which the reader will read.*/ virtual void SetMemoryBuffer(const char* dataArray, unsigned int size); protected: FileReader(); virtual ~FileReader(); bool m_CanReadFromMemory; bool m_ReadFromMemory; const char* m_MemoryBuffer; unsigned int m_MemorySize; public: protected: }; } // namespace mitk #endif /* FILEREADER_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/IO/mitkFileReaderRegistry.cpp b/Core/Code/IO/mitkFileReaderRegistry.cpp index 24d48be55d..9ab2d58855 100644 --- a/Core/Code/IO/mitkFileReaderRegistry.cpp +++ b/Core/Code/IO/mitkFileReaderRegistry.cpp @@ -1,228 +1,231 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFileReaderRegistry.h" // Microservices #include #include #include #include -// Legacy Support -#include - -//const std::string mitk::IFileWriter::PROP_EXTENSION = "org.mitk.services.FileWriter.Extension"; +#include "itksys/SystemTools.hxx" mitk::FileReaderRegistry::FileReaderRegistry() { } mitk::FileReaderRegistry::~FileReaderRegistry() { for (std::map >::iterator iter = m_ServiceObjects.begin(), end = m_ServiceObjects.end(); iter != end; ++iter) { iter->second.UngetService(iter->first); } } //////////////////// READING DIRECTLY //////////////////// std::vector< mitk::BaseData::Pointer > mitk::FileReaderRegistry::Read(const std::string& path, us::ModuleContext* context) { // Find extension - std::string extension = path; - extension.erase(0, path.find_last_of('.')); + const std::string extension = itksys::SystemTools::GetFilenameExtension(path); // Get best Reader - mitk::IFileReader* reader = GetReader(extension, context); + FileReaderRegistry readerRegistry; + mitk::IFileReader* reader = readerRegistry.GetReader(extension, context); // Throw exception if no compatible reader was found if (reader == NULL) mitkThrow() << "Tried to directly read a file of type '" + extension + "' via FileReaderRegistry, but no reader supporting this filetype was found."; return reader->Read(path); } std::vector< mitk::BaseData::Pointer > mitk::FileReaderRegistry::ReadAll( const std::vector& paths, std::vector* unreadableFiles, - us::ModuleContext* context) + us::ModuleContext* context) { + FileReaderRegistry readerRegistry; std::vector< mitk::BaseData::Pointer > result; for (std::vector::const_iterator iterator = paths.begin(), end = paths.end(); iterator != end; ++iterator) { try { - std::vector baseDataList = Read( *iterator, context ); + const std::string extension = itksys::SystemTools::GetFilenameExtension(*iterator); + mitk::IFileReader* reader = readerRegistry.GetReader(extension, context); + // Throw exception if no compatible reader was found + if (reader == NULL) throw; + + std::vector baseDataList = reader->Read( *iterator ); result.insert(result.end(), baseDataList.begin(), baseDataList.end()); } catch (...) { if (unreadableFiles) unreadableFiles->push_back( *iterator ); } } return result; } //////////////////// GETTING READERS //////////////////// mitk::IFileReader* mitk::FileReaderRegistry::GetReader(const std::string& extension, us::ModuleContext* context ) { std::vector results = GetReaders(extension, context); if (results.empty()) return NULL; return results.front(); } std::vector mitk::FileReaderRegistry::GetReaders(const std::string& extension, us::ModuleContext* context ) { std::vector result; const std::vector > refs = GetReaderList(extension, context); result.reserve(refs.size()); // Translate List of ServiceRefs to List of Pointers for (std::vector >::const_iterator iter = refs.begin(), end = refs.end(); iter != end; ++iter) { us::ServiceObjects serviceObjects = context->GetServiceObjects(*iter); mitk::IFileReader* reader = serviceObjects.GetService(); m_ServiceObjects.insert(std::make_pair(reader, serviceObjects)); result.push_back(reader); } return result; } mitk::IFileReader* mitk::FileReaderRegistry::GetReader( - const std::string& extension, const mitk::IFileReader::OptionNames& options, - us::ModuleContext* context ) + const std::string& extension, const mitk::IFileReader::OptionNames& options, + us::ModuleContext* context ) { std::vector matching = mitk::FileReaderRegistry::GetReaders(extension, options, context); if (matching.empty()) return NULL; return matching.front(); } std::vector mitk::FileReaderRegistry::GetReaders( - const std::string& extension, const mitk::IFileReader::OptionNames& options, - us::ModuleContext* context ) + const std::string& extension, const mitk::IFileReader::OptionNames& options, + us::ModuleContext* context ) { const std::vector allReaders = mitk::FileReaderRegistry::GetReaders(extension, context); std::vector result; result.reserve(allReaders.size()); // the list is already sorted by priority. Now find reader that supports all options for (std::vector ::const_iterator iter = allReaders.begin(), end = allReaders.end(); iter != end; ++iter) { mitk::IFileReader * currentReader = *iter; // Now see if this reader supports all options. If yes, push to results if ( mitk::FileReaderRegistry::ReaderSupportsOptions(currentReader, options) ) { result.push_back(currentReader); } } return result; } void mitk::FileReaderRegistry::UngetReader(mitk::IFileReader* reader) { std::map >::iterator readerIter = m_ServiceObjects.find(reader); if (readerIter != m_ServiceObjects.end()) { readerIter->second.UngetService(reader); m_ServiceObjects.erase(readerIter); } } void mitk::FileReaderRegistry::UngetReaders(const std::vector& readers) { for (std::vector::const_iterator iter = readers.begin(), end = readers.end(); iter != end; ++iter) { this->UngetReader(*iter); } } //////////////////// GENERIC INFORMATION //////////////////// std::string mitk::FileReaderRegistry::GetSupportedExtensions(const std::string& extension) { us::ModuleContext* context = us::GetModuleContext(); const std::vector > refs = GetReaderList(extension, context); std::vector entries; // Will contain Description + Extension (Human readable) entries.reserve(refs.size()); std::string knownExtensions; // Will contain plain list of all known extensions (for the QFileDialog entry "All Known Extensions") for (std::vector >::const_iterator iterator = refs.begin(), end = refs.end(); iterator != end; ++iterator) { // Generate List of Extensions if (iterator == refs.begin()) // First entry without semicolon - knownExtensions += "*" + iterator->GetProperty(mitk::IFileReader::PROP_EXTENSION).ToString(); + knownExtensions += "*" + iterator->GetProperty(mitk::IFileReader::PROP_EXTENSION()).ToString(); else // Ad semicolon for each following entry - knownExtensions += "; *" + iterator->GetProperty(mitk::IFileReader::PROP_EXTENSION).ToString(); + knownExtensions += "; *" + iterator->GetProperty(mitk::IFileReader::PROP_EXTENSION()).ToString(); // Generate List of human readable entries composed of Description + Extension - std::string entry = iterator->GetProperty(mitk::IFileReader::PROP_DESCRIPTION).ToString() + "(*" + iterator->GetProperty(mitk::IFileReader::PROP_EXTENSION).ToString() + ");;"; + std::string entry = iterator->GetProperty(mitk::IFileReader::PROP_DESCRIPTION()).ToString() + "(*" + iterator->GetProperty(mitk::IFileReader::PROP_EXTENSION()).ToString() + ");;"; entries.push_back(entry); } std::sort(entries.begin(), entries.end()); std::string result = "Known Extensions (" + knownExtensions + ");;All (*)"; for (std::vector::const_iterator iterator = entries.begin(), end = entries.end(); iterator != end; ++iterator) { result += ";;" + *iterator; } return result; } //////////////////// INTERNAL CODE //////////////////// bool mitk::FileReaderRegistry::ReaderSupportsOptions(mitk::IFileReader* reader, const mitk::IFileReader::OptionNames& options ) { const mitk::IFileReader::OptionList readerOptions = reader->GetOptions(); if (options.empty()) return true; // if no options were requested, return true unconditionally if (readerOptions.empty()) return false; // if options were requested and reader supports no options, return false // For each of the strings in requested options, check if option is available in reader for(mitk::IFileReader::OptionNames::const_iterator options_i = options.begin(), i_end = options.end(); options_i != i_end; ++options_i) { { bool optionFound = false; // Iterate over each available option from reader to check if one of them matches the current option for(mitk::IFileReader::OptionList::const_iterator options_j = readerOptions.begin(), j_end = readerOptions.end(); options_j != j_end; ++options_j) { if ( *options_i == options_j->first ) optionFound = true; } if (optionFound == false) return false; // If one option was not found, leave method and return false } } return true; // if all options have been found, return true } //////////////////// uS-INTERACTION //////////////////// std::vector< us::ServiceReference > mitk::FileReaderRegistry::GetReaderList(const std::string& extension, us::ModuleContext* context ) { // filter for class and extension std::string filter; if (!extension.empty()) { - filter = us::LDAPProp(mitk::IFileReader::PROP_EXTENSION) == extension; + filter = us::LDAPProp(mitk::IFileReader::PROP_EXTENSION()) == extension; } std::vector > result = context->GetServiceReferences(filter); std::sort(result.begin(), result.end()); std::reverse(result.begin(), result.end()); return result; } diff --git a/Core/Code/IO/mitkFileReaderRegistry.h b/Core/Code/IO/mitkFileReaderRegistry.h index 980e3b95da..d390a5cbf2 100644 --- a/Core/Code/IO/mitkFileReaderRegistry.h +++ b/Core/Code/IO/mitkFileReaderRegistry.h @@ -1,107 +1,108 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef FileReaderRegistry_H_HEADER_INCLUDED_C1E7E521 #define FileReaderRegistry_H_HEADER_INCLUDED_C1E7E521 #include #include #include // Microservices #include #include #include namespace mitk { /** * @ingroup Process * * Provides convenient access to mitk::IFileReader instances and reading * files into mitk::BaseData types. * * \note The life-time of all mitk::IFileReader objects returned by an * instance of this class ends with the destruction of that instance. */ class MITK_CORE_EXPORT FileReaderRegistry { public: FileReaderRegistry(); ~FileReaderRegistry(); /** * Reads the file located at path and returns the * contents as a DataNode. * * This method will select the best available reader in the service * registry for the task. * * UnsupportedFileException: If no compatible reader was found * FileNotFoundException: If no file was found at path * FileReadException: If the selected reader failed to read the file **/ - std::vector< itk::SmartPointer > Read(const std::string& path, us::ModuleContext* context = us::GetModuleContext()); + static std::vector< itk::SmartPointer > Read(const std::string& path, us::ModuleContext* context = us::GetModuleContext()); - std::vector< mitk::BaseData::Pointer > ReadAll(const std::vector& paths, std::vector* unreadableFiles = 0, - us::ModuleContext* context = us::GetModuleContext()); + static std::vector< mitk::BaseData::Pointer > ReadAll(const std::vector& paths, std::vector* unreadableFiles = 0, + us::ModuleContext* context = us::GetModuleContext()); template - itk::SmartPointer Read(const std::string& path, us::ModuleContext* context = us::GetModuleContext()) + static itk::SmartPointer Read(const std::string& path, us::ModuleContext* context = us::GetModuleContext()) { std::vector basedatas = Read(path, context); + if (basedatas.empty()) return NULL; T* result = dynamic_cast (basedatas.front().GetPointer()); return result; } /** * Returns a compatible Reader to the given file extension **/ mitk::IFileReader* GetReader(const std::string& extension, us::ModuleContext* context = us::GetModuleContext() ); mitk::IFileReader* GetReader(const std::string& extension, const mitk::IFileReader::OptionNames& options, us::ModuleContext* context = us::GetModuleContext() ); std::vector GetReaders(const std::string& extension, us::ModuleContext* context = us::GetModuleContext() ); std::vector GetReaders(const std::string& extension, const mitk::IFileReader::OptionNames& options, us::ModuleContext* context = us::GetModuleContext() ); void UngetReader(mitk::IFileReader* reader); void UngetReaders(const std::vector& readers); std::string GetSupportedExtensions(const std::string& extension = ""); protected: std::vector< us::ServiceReference > GetReaderList(const std::string& extension, us::ModuleContext* context); bool ReaderSupportsOptions(mitk::IFileReader* reader, const mitk::IFileReader::OptionNames& options); private: // purposely not implemented FileReaderRegistry(const FileReaderRegistry&); FileReaderRegistry& operator=(const FileReaderRegistry&); std::map > m_ServiceObjects; }; } // namespace mitk #endif /* FileReaderRegistry_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/IO/mitkFileWriter.h b/Core/Code/IO/mitkFileWriter.h index d07733769d..e8d7267bc1 100644 --- a/Core/Code/IO/mitkFileWriter.h +++ b/Core/Code/IO/mitkFileWriter.h @@ -1,166 +1,167 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef FILEWRITER_H_HEADER_INCLUDED #define FILEWRITER_H_HEADER_INCLUDED #include #include #include namespace mitk { //##Documentation //## @brief Interface class of writers that write data to files //## @ingroup Process +//## @deprecatedSince{2013_09} Use mitk::IFileWriter instead. class MITK_CORE_EXPORT FileWriter : public itk::ProcessObject { public: mitkClassMacro(FileWriter,itk::ProcessObject); //##Documentation //## @brief Get the specified the file to write //## //## Either the FileName or FilePrefix plus FilePattern are used to write. virtual const char* GetFileName() const = 0; //##Documentation //## @brief Specify the file to write. //## //## Either the FileName or FilePrefix plus FilePattern are used to write. virtual void SetFileName(const char* aFileName) = 0; //##Documentation //## @brief Get the specified file prefix for the file(s) to write. //## //## You should specify either a FileName or FilePrefix. Use FilePrefix if //## the data is stored in multiple files. virtual const char* GetFilePrefix() const = 0; //##Documentation //## @brief Specify file prefix for the file(s) to write. //## //## You should specify either a FileName or FilePrefix. Use FilePrefix if //## the data is stored in multiple files. virtual void SetFilePrefix(const char* aFilePrefix) = 0; //##Documentation //## @brief Get the specified file pattern for the file(s) to write. The //## sprintf format used to build filename from FilePrefix and number. //## //## You should specify either a FileName or FilePrefix. Use FilePrefix if //## the data is stored in multiple files. virtual const char* GetFilePattern() const = 0; //##Documentation //## @brief Specified file pattern for the file(s) to write. The sprintf //## format used to build filename from FilePrefix and number. //## //## You should specify either a FileName or FilePrefix. Use FilePrefix if //## the data is stored in multiple files. virtual void SetFilePattern(const char* aFilePattern) = 0; //##Documentation //## @brief Return the extension to be added to the filename. virtual std::string GetFileExtension(); //##Documentation //## @brief Checks if given extension is valid for file writer bool IsExtensionValid(std::string extension); //##Documentation //## @brief Return the possible file extensions for the data type associated with the writer virtual std::vector GetPossibleFileExtensions() = 0; //##Documentation //## @brief possible file extensions for the data type associated with the writer as string virtual std::string GetPossibleFileExtensionsAsString(); //##Documentation //## @brief Check if the Writer can write this type of data of the //## DataTreenode. virtual bool CanWriteDataType( DataNode* ); //##Documentation //## @brief Return the MimeType of the saved File. virtual std::string GetWritenMIMEType(); //##Documentation //## @brief Set the DataTreenode as Input. Important: The Writer //## always have a SetInput-Function. using itk::ProcessObject::SetInput; virtual void SetInput( DataNode* ); virtual void Write() = 0; /** @brief Specifies, whether the file writer also can write a file to a memory buffer */ virtual bool CanWriteToMemory( ); /** @brief Set/Get functions to advise the file writer to use tis internal memory array as file writing destination*/ virtual void SetWriteToMemory( bool write ); virtual bool GetWriteToMemory( ); /** @brief To be used along with a call of SetWriteToMemory(true). This returns the memory buffer where the file was written.*/ virtual const char* GetMemoryPointer(); /** @brief To be used along with a call of SetWriteToMemory(true). This returns the size of the memory buffer where the file was written.*/ virtual unsigned int GetMemorySize(); /** @brief CAUTION: It's up to the user to call this function to release the memory buffer after use in case the file writer has written to its memory array.*/ virtual void ReleaseMemory(); protected: FileWriter(); virtual ~FileWriter(); bool m_CanWriteToMemory; bool m_WriteToMemory; char * m_MemoryBuffer; unsigned int m_MemoryBufferSize; }; #define mitkWriterMacro \ virtual void Write() \ { \ if ( this->GetInput() == NULL ) \ { \ itkExceptionMacro(<<"Write:Please specify an input!"); \ return; \ } \ /* Fill in image information.*/ \ this->UpdateOutputInformation(); \ (*(this->GetInputs().begin()))->SetRequestedRegionToLargestPossibleRegion();\ this->PropagateRequestedRegion(NULL); \ this->UpdateOutputData(NULL); \ } \ \ virtual void Update() \ { \ Write(); \ } } // namespace mitk #endif /* FILEWRITER_H_HEADER_INCLUDED */ diff --git a/Core/Code/IO/mitkFileWriterRegistry.cpp b/Core/Code/IO/mitkFileWriterRegistry.cpp index 58a43818df..38e8698d14 100644 --- a/Core/Code/IO/mitkFileWriterRegistry.cpp +++ b/Core/Code/IO/mitkFileWriterRegistry.cpp @@ -1,206 +1,208 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFileWriterRegistry.h" // MITK #include // ITK #include // Microservices #include #include #include #include mitk::FileWriterRegistry::FileWriterRegistry() { } mitk::FileWriterRegistry::~FileWriterRegistry() { for (std::map >::iterator iter = m_ServiceObjects.begin(), end = m_ServiceObjects.end(); iter != end; ++iter) { iter->second.UngetService(iter->first); } } //////////////////// WRITING DIRECTLY //////////////////// void mitk::FileWriterRegistry::Write(const mitk::BaseData* data, const std::string& path, us::ModuleContext* context) { // Find extension std::string extension = itksys::SystemTools::GetFilenameExtension(path); // Get best Writer - mitk::IFileWriter* writer = GetWriter(data, extension, mitk::IFileWriter::OptionNames(), context); + FileWriterRegistry writerRegistry; + mitk::IFileWriter* writer = writerRegistry.GetWriter(data, extension, mitk::IFileWriter::OptionNames(), context); // Throw exception if no compatible Writer was found if (writer == NULL) { mitkThrow() << "Tried to directly write a file of type '" << data->GetNameOfClass() << "' and extension '" << extension << "' via FileWriterRegistry, but no writer supporting this filetype was found."; } writer->Write(data, path); } void mitk::FileWriterRegistry::Write(const mitk::BaseData* data, std::ostream& os, us::ModuleContext* context) { // Get best Writer - mitk::IFileWriter* writer = GetWriter(data, std::string(), mitk::IFileWriter::OptionNames(), context); + FileWriterRegistry writerRegistry; + mitk::IFileWriter* writer = writerRegistry.GetWriter(data, std::string(), mitk::IFileWriter::OptionNames(), context); // Throw exception if no compatible Writer was found if (writer == NULL) { mitkThrow() << "Tried to directly write a file of type '" << data->GetNameOfClass() << "' to a std::ostream via FileWriterRegistry, but no writer supporting this BaseData type was found."; } writer->Write(data, os); } //////////////////// GETTING WRITERS //////////////////// mitk::IFileWriter* mitk::FileWriterRegistry::GetWriter( const mitk::BaseData* baseData, const std::string& extension, const mitk::IFileWriter::OptionNames& options, us::ModuleContext* context) { return GetWriter(baseData->GetNameOfClass(), extension, options, context); } mitk::IFileWriter* mitk::FileWriterRegistry::GetWriter( const std::string& baseDataType, const std::string& extension, const mitk::IFileWriter::OptionNames& options, us::ModuleContext* context) { std::vector results = GetWriters(baseDataType, extension, options, context); if (results.empty()) return NULL; return results.front(); } std::vector mitk::FileWriterRegistry::GetWriters( const mitk::BaseData* baseData, const std::string& extension, const mitk::IFileWriter::OptionNames& options, us::ModuleContext* context) { return GetWriters(baseData->GetNameOfClass(), extension, options, context); } std::vector mitk::FileWriterRegistry::GetWriters( const std::string& baseDataType, const std::string& extension, const mitk::IFileWriter::OptionNames& options, us::ModuleContext* context) { // filter for class and extension - std::string filter = us::LDAPProp(mitk::IFileWriter::PROP_BASEDATA_TYPE) == baseDataType && - us::LDAPProp(mitk::IFileWriter::PROP_EXTENSION) == extension; + std::string filter = us::LDAPProp(mitk::IFileWriter::PROP_BASEDATA_TYPE()) == baseDataType && + us::LDAPProp(mitk::IFileWriter::PROP_EXTENSION()) == extension; std::vector > refs = context->GetServiceReferences(filter); std::sort(refs.begin(), refs.end()); std::reverse(refs.begin(), refs.end()); std::vector result; result.reserve(refs.size()); // Translate List of ServiceRefs to List of Pointers for (std::vector >::const_iterator iter = refs.begin(), end = refs.end(); iter != end; ++iter) { us::ServiceObjects serviceObjects = context->GetServiceObjects(*iter); mitk::IFileWriter* writer = serviceObjects.GetService(); // Now see if this Writer supports all options. If yes, push to results if (mitk::FileWriterRegistry::WriterSupportsOptions(writer, options)) { m_ServiceObjects.insert(std::make_pair(writer, serviceObjects)); result.push_back(writer); } } return result; } //////////////////// GENERIC INFORMATION //////////////////// std::string mitk::FileWriterRegistry::GetSupportedExtensions(const std::string& extension, us::ModuleContext* context) { - std::string filter = us::LDAPProp(mitk::IFileWriter::PROP_EXTENSION) == extension; + std::string filter = us::LDAPProp(mitk::IFileWriter::PROP_EXTENSION()) == extension; const std::vector > refs = context->GetServiceReferences(filter); return CreateFileDialogString(refs); } std::string mitk::FileWriterRegistry::GetSupportedWriters(const std::string& baseDataType, us::ModuleContext* context) { - std::string filter = us::LDAPProp(mitk::IFileWriter::PROP_BASEDATA_TYPE) == baseDataType; + std::string filter = us::LDAPProp(mitk::IFileWriter::PROP_BASEDATA_TYPE()) == baseDataType; const std::vector > refs = context->GetServiceReferences(filter); return CreateFileDialogString(refs); } //////////////////// INTERNAL CODE //////////////////// bool mitk::FileWriterRegistry::WriterSupportsOptions(mitk::IFileWriter* writer, const mitk::IFileWriter::OptionNames& options ) { const mitk::IFileWriter::OptionList writerOptions = writer->GetOptions(); if (options.empty()) return true; // if no options were requested, return true unconditionally if (writerOptions.empty()) return false; // if options were requested and reader supports no options, return false // For each of the strings in requested options, check if option is available in reader for(mitk::IFileWriter::OptionNames::const_iterator options_i = options.begin(), i_end = options.end(); options_i != i_end; ++options_i) { { bool optionFound = false; // Iterate over each available option from reader to check if one of them matches the current option for(mitk::IFileWriter::OptionList::const_iterator options_j = writerOptions.begin(), j_end = writerOptions.end(); options_j != j_end; ++options_j) { if ( *options_i == options_j->first ) optionFound = true; } if (optionFound == false) return false; // If one option was not found, leave method and return false } } return true; // if all options have been found, return true } std::string mitk::FileWriterRegistry::CreateFileDialogString(const std::vector >& refs) { std::vector entries; // Will contain Description + Extension (Human readable) entries.reserve(refs.size()); std::string knownExtensions; // Will contain plain list of all known extensions (for the QFileDialog entry "All Known Extensions") for (std::vector >::const_iterator iterator = refs.begin(), end = refs.end(); iterator != end; ++iterator) { // Generate List of Extensions if (iterator == refs.begin()) // First entry without semicolon - knownExtensions += "*" + iterator->GetProperty(mitk::IFileWriter::PROP_EXTENSION).ToString(); + knownExtensions += "*" + iterator->GetProperty(mitk::IFileWriter::PROP_EXTENSION()).ToString(); else // Ad semicolon for each following entry - knownExtensions += "; *" + iterator->GetProperty(mitk::IFileWriter::PROP_EXTENSION).ToString(); + knownExtensions += "; *" + iterator->GetProperty(mitk::IFileWriter::PROP_EXTENSION()).ToString(); // Generate List of human readable entries composed of Description + Extension - std::string entry = iterator->GetProperty(mitk::IFileWriter::PROP_DESCRIPTION).ToString() + "(*" + iterator->GetProperty(mitk::IFileWriter::PROP_EXTENSION).ToString() + ");;"; + std::string entry = iterator->GetProperty(mitk::IFileWriter::PROP_DESCRIPTION()).ToString() + "(*" + iterator->GetProperty(mitk::IFileWriter::PROP_EXTENSION()).ToString() + ");;"; entries.push_back(entry); } std::sort(entries.begin(), entries.end()); std::string result = "Known Extensions (" + knownExtensions + ");;All (*)"; for (std::vector::const_iterator iterator = entries.begin(), end = entries.end(); iterator != end; ++iterator) { result += ";;" + *iterator; } return result; } diff --git a/Core/Code/IO/mitkFileWriterRegistry.h b/Core/Code/IO/mitkFileWriterRegistry.h index ddcc78a231..84ac536cb9 100644 --- a/Core/Code/IO/mitkFileWriterRegistry.h +++ b/Core/Code/IO/mitkFileWriterRegistry.h @@ -1,108 +1,108 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef FileWriterRegistry_H_HEADER_INCLUDED_C1E7E521 #define FileWriterRegistry_H_HEADER_INCLUDED_C1E7E521 #include // Microservices #include #include #include #include "mitkIFileWriter.h" // Temporarily disable warning until PIMPL pattern is implemented here #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4251) #endif namespace mitk { class BaseData; } namespace mitk { /** * @ingroup Process * * Provides convenient access to mitk::IFileWriter instances and writing * files from mitk::BaseData types. * * \note The life-time of all mitk::IFileWriter objects returned by an * instance of this class ends with the destruction of that instance. */ class MITK_CORE_EXPORT FileWriterRegistry { public: FileWriterRegistry(); ~FileWriterRegistry(); - void Write(const mitk::BaseData* data, const std::string& path, us::ModuleContext* context = us::GetModuleContext()); + static void Write(const mitk::BaseData* data, const std::string& path, us::ModuleContext* context = us::GetModuleContext()); - void Write(const mitk::BaseData* data, std::ostream& os, us::ModuleContext* context = us::GetModuleContext()); + static void Write(const mitk::BaseData* data, std::ostream& os, us::ModuleContext* context = us::GetModuleContext()); /** * Returns a compatible Writer to the given file extension */ mitk::IFileWriter* GetWriter(const std::string& baseDataType, const std::string& extension = std::string(), const mitk::IFileWriter::OptionNames& options = mitk::IFileWriter::OptionNames(), us::ModuleContext* context = us::GetModuleContext() ); mitk::IFileWriter* GetWriter(const mitk::BaseData* baseData, const std::string& extension = std::string(), const mitk::IFileWriter::OptionNames& options = mitk::IFileWriter::OptionNames(), us::ModuleContext* context = us::GetModuleContext() ); std::vector GetWriters(const std::string& baseDataType, const std::string& extension = std::string(), const mitk::IFileWriter::OptionNames& options = mitk::IFileWriter::OptionNames(), us::ModuleContext* context = us::GetModuleContext() ); std::vector GetWriters(const mitk::BaseData* baseData, const std::string& extension = std::string(), const mitk::IFileWriter::OptionNames& options = mitk::IFileWriter::OptionNames(), us::ModuleContext* context = us::GetModuleContext() ); void UngetWriter(mitk::IFileWriter* writer); void UngetWriters(const std::vector& writers); // TODO: We should not generate GUI dependent strings here. Maybe just return a pair of extensions // and descriptions. std::string GetSupportedExtensions(const std::string& extension = std::string(), us::ModuleContext* context = us::GetModuleContext()); std::string GetSupportedWriters(const std::string& basedataType, us::ModuleContext* context = us::GetModuleContext()); protected: std::string CreateFileDialogString(const std::vector >& refs); bool WriterSupportsOptions(mitk::IFileWriter* writer, const mitk::IFileWriter::OptionNames& options); private: // purposely not implemented FileWriterRegistry(const FileWriterRegistry&); FileWriterRegistry& operator=(const FileWriterRegistry&); std::map > m_ServiceObjects; }; } // namespace mitk #ifdef _MSC_VER # pragma warning(pop) #endif #endif /* FileWriterRegistry_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/IO/mitkFileWriterWithInformation.h b/Core/Code/IO/mitkFileWriterWithInformation.h index 707b342f24..319921e26a 100644 --- a/Core/Code/IO/mitkFileWriterWithInformation.h +++ b/Core/Code/IO/mitkFileWriterWithInformation.h @@ -1,41 +1,41 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef FILEWRITERWITHINFORMATION_H_INCLUDED #define FILEWRITERWITHINFORMATION_H_INCLUDED #include "mitkFileWriter.h" #include "mitkBaseData.h" namespace mitk { /** * \brief Interface for FileWriters with extra information. * Should be merged into FileWriter. + * + * \deprecatedSince{2013_09} Use mitk::IFileWriter instead. */ -class MITK_CORE_EXPORT FileWriterWithInformation : public FileWriter { +class FileWriterWithInformation : public FileWriter { public: mitkClassMacro(FileWriterWithInformation,FileWriter); virtual const char *GetDefaultFilename() = 0; virtual const char *GetFileDialogPattern() = 0; virtual const char *GetDefaultExtension() = 0; virtual bool CanWriteBaseDataType(BaseData::Pointer data) = 0; virtual void DoWrite(BaseData::Pointer data) = 0; }; } #endif - - diff --git a/Core/Code/IO/mitkIOUtil.cpp b/Core/Code/IO/mitkIOUtil.cpp index a6e4154417..d2c2ad6529 100644 --- a/Core/Code/IO/mitkIOUtil.cpp +++ b/Core/Code/IO/mitkIOUtil.cpp @@ -1,696 +1,697 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkIOUtil.h" -#include "mitkDataNodeFactory.h" -#include "mitkImageWriter.h" -#include "mitkPointSetWriter.h" -#include "mitkSurfaceVtkWriter.h" #include #include #include #include #include #include #include +#include +#include //ITK #include //VTK #include #include #include #include #include static std::string GetLastErrorStr() { #ifdef US_PLATFORM_POSIX return std::string(strerror(errno)); #else // Retrieve the system error message for the last-error code LPVOID lpMsgBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); std::string errMsg((LPCTSTR)lpMsgBuf); LocalFree(lpMsgBuf); return errMsg; #endif } #ifdef US_PLATFORM_WINDOWS #include #include #include #include static const char validLetters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // A Windows version of the POSIX mkstemp function static int mkstemp(char* tmpl) { static unsigned long long value = 0; unsigned long long randomTimeBits = 0; int savedErrno = errno; // Lower bound on the number of temporary files to attempt to generate. #define ATTEMPTS_MIN (62 * 62 * 62) /* The number of times to attempt to generate a temporary file. To conform to POSIX, this must be no smaller than TMP_MAX. */ #if ATTEMPTS_MIN < TMP_MAX const unsigned int attempts = TMP_MAX; #else const unsigned int attempts = ATTEMPTS_MIN; #endif const int len = strlen(tmpl); if (len < 6 || strcmp(&tmpl[len - 6], "XXXXXX")) { errno = EINVAL; return -1; } /* This is where the Xs start. */ char* XXXXXX = &tmpl[len - 6]; /* Get some more or less random data. */ { SYSTEMTIME stNow; FILETIME ftNow; // get system time GetSystemTime(&stNow); stNow.wMilliseconds = 500; if (!SystemTimeToFileTime(&stNow, &ftNow)) { errno = -1; return -1; } randomTimeBits = ((static_cast(ftNow.dwHighDateTime) << 32) | static_cast(ftNow.dwLowDateTime)); } value += randomTimeBits ^ static_cast(GetCurrentThreadId()); for (unsigned int count = 0; count < attempts; value += 7777, ++count) { unsigned long long v = value; /* Fill in the random bits. */ XXXXXX[0] = validLetters[v % 62]; v /= 62; XXXXXX[1] = validLetters[v % 62]; v /= 62; XXXXXX[2] = validLetters[v % 62]; v /= 62; XXXXXX[3] = validLetters[v % 62]; v /= 62; XXXXXX[4] = validLetters[v % 62]; v /= 62; XXXXXX[5] = validLetters[v % 62]; int fd = _open (tmpl, _O_RDWR | _O_CREAT | _O_EXCL, _S_IREAD | _S_IWRITE); if (fd >= 0) { errno = savedErrno; return fd; } else if (errno != EEXIST) { return -1; } } /* We got out of the loop because we ran out of combinations to try. */ errno = EEXIST; return -1; } // A Windows version of the POSIX mkdtemp function static char* mkdtemp(char* tmpl) { static unsigned long long value = 0; unsigned long long randomTimeBits = 0; int savedErrno = errno; // Lower bound on the number of temporary dirs to attempt to generate. #define ATTEMPTS_MIN (62 * 62 * 62) /* The number of times to attempt to generate a temporary dir. To conform to POSIX, this must be no smaller than TMP_MAX. */ #if ATTEMPTS_MIN < TMP_MAX const unsigned int attempts = TMP_MAX; #else const unsigned int attempts = ATTEMPTS_MIN; #endif const int len = strlen(tmpl); if (len < 6 || strcmp(&tmpl[len - 6], "XXXXXX")) { errno = EINVAL; return NULL; } /* This is where the Xs start. */ char* XXXXXX = &tmpl[len - 6]; /* Get some more or less random data. */ { SYSTEMTIME stNow; FILETIME ftNow; // get system time GetSystemTime(&stNow); stNow.wMilliseconds = 500; if (!SystemTimeToFileTime(&stNow, &ftNow)) { errno = -1; return NULL; } randomTimeBits = ((static_cast(ftNow.dwHighDateTime) << 32) | static_cast(ftNow.dwLowDateTime)); } value += randomTimeBits ^ static_cast(GetCurrentThreadId()); unsigned int count = 0; for (; count < attempts; value += 7777, ++count) { unsigned long long v = value; /* Fill in the random bits. */ XXXXXX[0] = validLetters[v % 62]; v /= 62; XXXXXX[1] = validLetters[v % 62]; v /= 62; XXXXXX[2] = validLetters[v % 62]; v /= 62; XXXXXX[3] = validLetters[v % 62]; v /= 62; XXXXXX[4] = validLetters[v % 62]; v /= 62; XXXXXX[5] = validLetters[v % 62]; int fd = _mkdir (tmpl); //, _S_IREAD | _S_IWRITE | _S_IEXEC); if (fd >= 0) { errno = savedErrno; return tmpl; } else if (errno != EEXIST) { return NULL; } } /* We got out of the loop because we ran out of combinations to try. */ errno = EEXIST; return NULL; } #endif namespace mitk { const std::string IOUtil::DEFAULTIMAGEEXTENSION = ".nrrd"; const std::string IOUtil::DEFAULTSURFACEEXTENSION = ".stl"; const std::string IOUtil::DEFAULTPOINTSETEXTENSION = ".mps"; #ifdef US_PLATFORM_WINDOWS std::string IOUtil::GetProgramPath() { char path[512]; std::size_t index = std::string(path, GetModuleFileName(NULL, path, 512)).find_last_of('\\'); return std::string(path, index); } #elif defined(US_PLATFORM_APPLE) #include std::string IOUtil::GetProgramPath() { char path[512]; uint32_t size = sizeof(path); if (_NSGetExecutablePath(path, &size) == 0) { std::size_t index = std::string(path).find_last_of('/'); std::string strPath = std::string(path, index); const char* execPath = strPath.c_str(); //mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch(execPath,false); return strPath; } return std::string(); } #else #include #include #include std::string IOUtil::GetProgramPath() { std::stringstream ss; ss << "/proc/" << getpid() << "/exe"; char proc[512] = {0}; ssize_t ch = readlink(ss.str().c_str(), proc, 512); if (ch == -1) return std::string(); std::size_t index = std::string(proc).find_last_of('/'); return std::string(proc, index); } #endif std::string IOUtil::GetTempPath() { static std::string result; if (result.empty()) { #ifdef US_PLATFORM_WINDOWS char tempPathTestBuffer[1]; DWORD bufferLength = ::GetTempPath(1, tempPathTestBuffer); if (bufferLength == 0) { mitkThrow() << GetLastErrorStr(); } std::vector tempPath(bufferLength); bufferLength = ::GetTempPath(bufferLength, &tempPath[0]); if (bufferLength == 0) { mitkThrow() << GetLastErrorStr(); } result.assign(tempPath.begin(), tempPath.begin() + static_cast(bufferLength)); #else result = "/tmp/"; #endif } return result; } std::string IOUtil::CreateTemporaryFile(std::ofstream& f, const std::string& templateName, std::string path) { if (path.empty()) { path = GetTempPath(); } path += "/" + templateName; std::vector dst_path(path.begin(), path.end()); dst_path.push_back('\0'); int fd = mkstemp(&dst_path[0]); if(fd != -1) { path.assign(dst_path.begin(), dst_path.end() - 1); f.open(path.c_str(), std::ios_base::trunc | std::ios_base::out); close(fd); } else { mitkThrow() << "Creating temporary file " << &dst_path[0] << " failed: " << GetLastErrorStr(); } return path; } std::string IOUtil::CreateTemporaryDirectory(const std::string& templateName, std::string path) { if (path.empty()) { path = GetTempPath(); } path += "/" + templateName; std::vector dst_path(path.begin(), path.end()); dst_path.push_back('\0'); if(mkdtemp(&dst_path[0]) == NULL) { mitkThrow() << "Creating temporary directory " << &dst_path[0] << " failed: " << GetLastErrorStr(); } path.assign(dst_path.begin(), dst_path.end() - 1); return path; } int IOUtil::LoadFiles(const std::vector &fileNames, DataStorage &ds) { // Get the set of registered mitk::IDataNodeReader services us::ModuleContext* context = us::GetModuleContext(); const std::vector > refs = context->GetServiceReferences(); std::vector services; services.reserve(refs.size()); for (std::vector >::const_iterator i = refs.begin(); i != refs.end(); ++i) { IDataNodeReader* s = context->GetService(*i); if (s != 0) { services.push_back(s); } } mitk::ProgressBar::GetInstance()->AddStepsToDo(2*fileNames.size()); // Iterate over all file names and use the IDataNodeReader services // to load them. int nodesRead = 0; for (std::vector::const_iterator i = fileNames.begin(); i != fileNames.end(); ++i) { for (std::vector::const_iterator readerIt = services.begin(); readerIt != services.end(); ++readerIt) { try { int n = (*readerIt)->Read(*i, ds); nodesRead += n; if (n > 0) break; } catch (const std::exception& e) { MITK_WARN << e.what(); } } mitk::ProgressBar::GetInstance()->Progress(2); } for (std::vector >::const_iterator i = refs.begin(); i != refs.end(); ++i) { context->UngetService(*i); } return nodesRead; } DataStorage::Pointer IOUtil::LoadFiles(const std::vector& fileNames) { mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); LoadFiles(fileNames, *ds); return ds.GetPointer(); } DataNode::Pointer IOUtil::LoadDataNode(const std::string path) { - mitk::DataNodeFactory::Pointer reader = mitk::DataNodeFactory::New(); - try - { - reader->SetFileName( path ); - reader->Update(); - - if((reader->GetNumberOfOutputs()<1)) - { - MITK_ERROR << "Could not find data '" << path << "'"; - mitkThrow() << "An exception occured during loading the file " << path << ". Exception says could not find data."; - } + try + { + mitk::FileReaderRegistry readerRegistry; + std::vector baseDataList = readerRegistry.Read(path); - mitk::DataNode::Pointer node = reader->GetOutput(); + BaseData::Pointer baseData; + if (!baseDataList.empty()) baseData = baseDataList.front(); - if(node.IsNull()) - { - MITK_ERROR << "Could not find path: '" << path << "'" << " datanode is NULL" ; - mitkThrow() << "An exception occured during loading the file " << path << ". Exception says datanode is NULL."; - } - - return reader->GetOutput( 0 ); - } - catch ( itk::ExceptionObject & e ) + if(baseData.IsNull()) { - MITK_ERROR << "Exception occured during load data of '" << path << "': Exception: " << e.what(); - mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: " << e.what(); + MITK_ERROR << "Could not find data '" << path << "'"; + mitkThrow() << "An exception occured during loading the file " << path << ". Exception says could not find data."; } + + mitk::DataNode::Pointer node = mitk::DataNode::New(); + node->SetData(baseData); + SetDefaultDataNodeProperties(node, path); + + return node; + } + catch (const std::exception& e) + { + MITK_ERROR << "Exception occured during load data of '" << path << "': Exception: " << e.what(); + mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: " << e.what(); + } } Image::Pointer IOUtil::LoadImage(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::Image::Pointer image = dynamic_cast(node->GetData()); if(image.IsNull()) { MITK_ERROR << "Image is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the image " << path << ". Exception says: Image is NULL."; } return image; } Surface::Pointer IOUtil::LoadSurface(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::Surface::Pointer surface = dynamic_cast(node->GetData()); if(surface.IsNull()) { MITK_ERROR << "Surface is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: Surface is NULL."; } return surface; } PointSet::Pointer IOUtil::LoadPointSet(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::PointSet::Pointer pointset = dynamic_cast(node->GetData()); if(pointset.IsNull()) { MITK_ERROR << "PointSet is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: Pointset is NULL."; } return pointset; } bool IOUtil::SaveImage(mitk::Image::Pointer image, const std::string path) { + return SaveBaseData(image, path); + /* std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutExtension( path ); std::string extension = itksys::SystemTools::GetFilenameExtension( path ); if (dir == "") dir = "."; std::string finalFileName = dir + "/" + baseFilename; mitk::ImageWriter::Pointer imageWriter = mitk::ImageWriter::New(); //check if an extension is given, else use the defaul extension if( extension == "" ) { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTIMAGEEXTENSION; extension = DEFAULTIMAGEEXTENSION; } // check if extension is suitable for writing image data if (!imageWriter->IsExtensionValid(extension)) { MITK_WARN << extension << " extension is unknown. Extension set to default: " << finalFileName << DEFAULTIMAGEEXTENSION; extension = DEFAULTIMAGEEXTENSION; } try { //write the data imageWriter->SetInput(image); imageWriter->SetFileName(finalFileName.c_str()); imageWriter->SetExtension(extension.c_str()); imageWriter->Write(); } catch ( std::exception& e ) { MITK_ERROR << " during attempt to write '" << finalFileName + extension << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; + */ } bool IOUtil::SaveSurface(Surface::Pointer surface, const std::string path) { + return SaveBaseData(surface, path); + /* std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( path ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( path ); if (dir == "") dir = "."; std::string finalFileName = dir + "/" + baseFilename; if (extension == "") // if no extension has been set we use the default extension { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTSURFACEEXTENSION; extension = DEFAULTSURFACEEXTENSION; } try { finalFileName += extension; if(extension == ".stl" ) { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); // check if surface actually consists of triangles; if not, the writer will not do anything; so, convert to triangles... vtkPolyData* polys = surface->GetVtkPolyData(); if( polys->GetNumberOfStrips() > 0 ) { vtkSmartPointer triangleFilter = vtkSmartPointer::New(); triangleFilter->SetInput(polys); triangleFilter->Update(); polys = triangleFilter->GetOutput(); polys->Register(NULL); surface->SetVtkPolyData(polys); } surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->GetVtkWriter()->SetFileTypeToBinary(); surfaceWriter->Write(); } else if(extension == ".vtp") { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->GetVtkWriter()->SetDataModeToBinary(); surfaceWriter->Write(); } else if(extension == ".vtk") { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->Write(); } else { // file extension not suitable for writing specified data type MITK_ERROR << "File extension is not suitable for writing'" << finalFileName; mitkThrow() << "An exception occured during writing the file " << finalFileName << ". File extension " << extension << " is not suitable for writing."; } } catch(std::exception& e) { MITK_ERROR << " during attempt to write '" << finalFileName << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; + */ } bool IOUtil::SavePointSet(PointSet::Pointer pointset, const std::string path) { + return SaveBaseData(pointset, path); + /* mitk::PointSetWriter::Pointer pointSetWriter = mitk::PointSetWriter::New(); std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( path ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( path ); if (dir == "") dir = "."; std::string finalFileName = dir + "/" + baseFilename; if (extension == "") // if no extension has been entered manually into the filename { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTPOINTSETEXTENSION; extension = DEFAULTPOINTSETEXTENSION; } // check if extension is valid if (!pointSetWriter->IsExtensionValid(extension)) { MITK_WARN << extension << " extension is unknown. Extension set to default: " << finalFileName << DEFAULTPOINTSETEXTENSION; extension = DEFAULTPOINTSETEXTENSION; } try { pointSetWriter->SetInput( pointset ); finalFileName += extension; pointSetWriter->SetFileName( finalFileName.c_str() ); pointSetWriter->Update(); } catch( std::exception& e ) { MITK_ERROR << " during attempt to write '" << finalFileName << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; + */ } bool IOUtil::SaveBaseData( mitk::BaseData* data, const std::string& path ) { if (data == NULL || path.empty()) return false; - std::string dir = itksys::SystemTools::GetFilenamePath( path ); - std::string baseFilename = itksys::SystemTools::GetFilenameWithoutExtension( path ); - std::string extension = itksys::SystemTools::GetFilenameExtension( path ); - if (dir == "") - dir = "."; - std::string fileNameWithoutExtension = dir + "/" + baseFilename; + try + { + mitk::FileWriterRegistry::Write(data, path); + } + catch(const std::exception& e) + { + MITK_ERROR << " Writing a " << data->GetNameOfClass() << " to " << path << " failed: " + << e.what(); + throw e; + } + + return true; +} - mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); +void IOUtil::SetDefaultDataNodeProperties(DataNode* node, const std::string& filePath) +{ + // path + mitk::StringProperty::Pointer pathProp = mitk::StringProperty::New( itksys::SystemTools::GetFilenamePath(filePath) ); + node->SetProperty(StringProperty::PATH, pathProp); - for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) + // name already defined? + mitk::StringProperty::Pointer nameProp = dynamic_cast(node->GetProperty("name")); + if(nameProp.IsNull() || (strcmp(nameProp->GetValue(),"No Name!")==0)) { - if ( (*it)->CanWriteBaseDataType(data) ) + // name already defined in BaseData + mitk::StringProperty::Pointer baseDataNameProp = dynamic_cast(node->GetData()->GetProperty("name").GetPointer() ); + if(baseDataNameProp.IsNull() || (strcmp(baseDataNameProp->GetValue(),"No Name!")==0)) { - // Ensure a valid filename - if(baseFilename=="") - { - baseFilename = (*it)->GetDefaultFilename(); - } - // Check if an extension exists already and if not, append the default extension - if (extension=="" ) - { - extension=(*it)->GetDefaultExtension(); - } - else - { - if (!(*it)->IsExtensionValid(extension)) - { - MITK_WARN << extension << " extension is unknown"; - continue; - } - } - - std::string finalFileName = fileNameWithoutExtension + extension; - try - { - (*it)->SetFileName( finalFileName.c_str() ); - (*it)->DoWrite( data ); - return true; - } - catch( const std::exception& e ) - { - MITK_ERROR << " during attempt to write '" << finalFileName << "' Exception says:"; - MITK_ERROR << e.what(); - mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); - } + // name neither defined in node, nor in BaseData -> name = filename + nameProp = mitk::StringProperty::New( itksys::SystemTools::GetFilenameWithoutExtension(filePath)); + node->SetProperty("name", nameProp); + } + else + { + // name defined in BaseData! + nameProp = mitk::StringProperty::New(baseDataNameProp->GetValue()); + node->SetProperty("name", nameProp); } } - return false; + // visibility + if(!node->GetProperty("visible")) + { + node->SetVisibility(true); + } } } diff --git a/Core/Code/IO/mitkIOUtil.h b/Core/Code/IO/mitkIOUtil.h index d474573247..d2893a71ec 100644 --- a/Core/Code/IO/mitkIOUtil.h +++ b/Core/Code/IO/mitkIOUtil.h @@ -1,208 +1,212 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKIOUTIL_H #define MITKIOUTIL_H #include #include #include #include #include namespace mitk { /** * \ingroup IO * * \brief A utility class to load and save data from/to the local file system. * * This method LoadFiles queries the MITK Micro Services registry for registered mitk::IDataNodeReader service * instances. The service instance with the highest ranking will be asked first to load the * given file. On error (exception thrown) or if no mitk::DataNode was constructed, the next * service instance is used. * * The methods LoadImage, LoadSurface, and LoadPointSet are convenience methods for general loading of * the three main data types in MITK. They all use the more generic method LoadDataNode. * * The methods SaveImage, SaveSurface, and SurfacePointSet are also meant for convenience (e.g. during testing). * Currently, there is no generic way to save a generic DataNode with an appropriate format. Thus, every method * initializes the corresponding instance of the special writer for the data type. * * \see mitk::IDataNodeReader */ class MITK_CORE_EXPORT IOUtil { public: /** * Get the file system path where the running executable is located. * * @return The location of the currently running executable, without the filename. */ static std::string GetProgramPath(); /** * Get the default temporary path. * * @return The default path for temporary data. */ static std::string GetTempPath(); /** * Create and open a temporary file. * * This method generates a unique temporary filename from \c templateName, creates * and opens the file using the output stream \c tmpStream and returns the name of * the newly create file. * * The last six characters of \c templateName must be "XXXXXX" and these are replaced * with a string that makes the filename unique. * * The file is created with read and write permissions for owner only. * * @param tmpStream The output stream for writing to the temporary file. * @param templateName An optional template for the filename. * @param path An optional path where the temporary file should be created. Defaults * to the default temp path as returned by GetTempPath(). * @return The filename of the created temporary file. * * @throw mitk::Exception if the temporary file could not be created. */ static std::string CreateTemporaryFile(std::ofstream& tmpStream, const std::string& templateName = "XXXXXX", std::string path = std::string()); /** * Create a temporary directory. * * This method generates a uniquely named temporary directory from \c templateName. * The last six characters of \c templateName must be "XXXXXX" and these are replaced * with a string that makes the directory name unique. * * The directory is created with read, write and executable permissions for owner only. * * @param templateName An optional template for the directory name. * @param path An optional path where the temporary directory should be created. Defaults * to the default temp path as returned by GetTempPath(). * @return The filename of the created temporary file. * * @throw mitk::Exception if the temporary directory could not be created. */ static std::string CreateTemporaryDirectory(const std::string& templateName = "XXXXXX", std::string path = std::string()); /** * Load a files in fileNames and add the constructed mitk::DataNode instances * to the mitk::DataStorage storage * * \param fileNames A list (vector) of absolute file name paths. * \param storage The data storage to which the constructed data nodes are added. * \return The number of added mitk::DataNode instances. */ static int LoadFiles(const std::vector&fileNames, DataStorage& storage); /** * This method will create a new mitk::DataStorage instance and pass it to * LoadFiles(std::vector,DataStorage). * * \param fileNames A list (vector) of absolute file name paths. * \return The new mitk::DataStorage containing the constructed data nodes. * * \see LoadFiles(std::vector,DataStorage) */ static DataStorage::Pointer LoadFiles(const std::vector& fileNames); /** * @brief LoadDataNode Method to load an arbitrary DataNode. * @param path The path to the file including file name and file extension. * @throws mitk::Exception This exception is thrown when the DataNodeFactory is not able to read/find the file * or the DataNode is NULL. * @return Returns the DataNode. */ static mitk::DataNode::Pointer LoadDataNode(const std::string path); /** * @brief LoadImage Convenience method to load an arbitrary mitkImage. * @param path The path to the image including file name and file extension. * @throws mitk::Exception This exception is thrown when the Image is NULL. * @return Returns the mitkImage. */ static mitk::Image::Pointer LoadImage(const std::string path); /** * @brief LoadSurface Convenience method to load an arbitrary mitkSurface. * @param path The path to the surface including file name and file extension. * @throws mitk::Exception This exception is thrown when the Surface is NULL. * @return Returns the mitkSurface. */ static mitk::Surface::Pointer LoadSurface(const std::string path); /** * @brief LoadPointSet Convenience method to load an arbitrary mitkPointSet. * @param path The path to the pointset including file name and file extension (currently, only .mps is supported). * @throws mitk::Exception This exception is thrown when the PointSet is NULL. * @return Returns the mitkPointSet. */ static mitk::PointSet::Pointer LoadPointSet(const std::string path); /** * @brief SaveImage Convenience method to save an arbitrary mitkImage. * @param path The path to the image including file name and file extension. * If not extention is set, the default value (defined in DEFAULTIMAGEEXTENSION) is used. * @param image The image to save. * @throws mitk::Exception This exception is thrown when the writer is not able to write the image. * @return Returns true for success else false. */ static bool SaveImage(mitk::Image::Pointer image, const std::string path); /** * @brief SaveBaseData Convenience method to save arbitrary baseData. * @param path The path to the image including file name and file extension. * If not extention is set, the default value (defined in DEFAULTIMAGEEXTENSION) is used. * @param data The data to save. * @throws mitk::Exception This exception is thrown when the writer is not able to write the image. * @return Returns true for success else false. */ static bool SaveBaseData(mitk::BaseData* data, const std::string& path); /** * @brief SaveSurface Convenience method to save an arbitrary mitkSurface. * @param path The path to the surface including file name and file extension. * If not extention is set, the default value (defined in DEFAULTSURFACEEXTENSION) is used. * @throws mitk::Exception This exception is thrown when the writer is not able to write the surface. * or if the fileextension is not suitable for writing. * @return Returns true for success else false. */ static bool SaveSurface(mitk::Surface::Pointer surface, const std::string path); /** * @brief SavePointSet Convenience method to save an mitkPointSet. * @param path The path to the pointset including file name and file extension (currently, only .mps is supported). * If not extention is set, the default value (defined in DEFAULTPOINTSETEXTENSION) is used. * @throws mitk::Exception This exception is thrown when the writer is not able to write the pointset. * @return Returns true for success else false. */ static bool SavePointSet(mitk::PointSet::Pointer pointset, const std::string path); static const std::string DEFAULTIMAGEEXTENSION; static const std::string DEFAULTSURFACEEXTENSION; static const std::string DEFAULTPOINTSETEXTENSION; +private: + + static void SetDefaultDataNodeProperties(mitk::DataNode* node, const std::string& filePath = std::string()); + }; } #endif // MITKIOUTIL_H diff --git a/Core/Code/IO/mitkLegacyFileWriterService.cpp b/Core/Code/IO/mitkLegacyFileWriterService.cpp index 892331e659..d44ff4c8be 100644 --- a/Core/Code/IO/mitkLegacyFileWriterService.cpp +++ b/Core/Code/IO/mitkLegacyFileWriterService.cpp @@ -1,58 +1,61 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include -mitk::LegacyFileWriterService::LegacyFileWriterService(mitk::FileWriter::Pointer legacyWriter, +mitk::LegacyFileWriterService::LegacyFileWriterService(mitk::FileWriterWithInformation::Pointer legacyWriter, const std::string& basedataType, const std::string& extension, const std::string& description) : AbstractFileWriter(basedataType, extension, description) , m_LegacyWriter(legacyWriter) { if (extension.empty()) mitkThrow() << "LegacyFileWriterWrapper cannot be initialized without FileExtension." ; RegisterService(); } ////////////////////// Writing ///////////////////////// void mitk::LegacyFileWriterService::Write(const BaseData* data, const std::string& path) { if (m_LegacyWriter.IsNull()) mitkThrow() << "LegacyFileWriterService was incorrectly initialized: Has no LegacyFileWriter."; m_LegacyWriter->SetFileName(path.c_str()); - mitk::DataNode::Pointer node = mitk::DataNode::New(); - node->SetData(const_cast(data)); - m_LegacyWriter->SetInput(node); - m_LegacyWriter->Write(); + m_LegacyWriter->DoWrite(mitk::BaseData::Pointer(const_cast(data))); } void mitk::LegacyFileWriterService::Write(const BaseData* data, std::ostream& stream) { mitk::AbstractFileWriter::Write(data, stream); } +bool mitk::LegacyFileWriterService::CanWrite(const mitk::BaseData* data) const +{ + return mitk::AbstractFileWriter::CanWrite(data) && + m_LegacyWriter->CanWriteBaseDataType(mitk::BaseData::Pointer(const_cast(data))); +} + mitk::LegacyFileWriterService* mitk::LegacyFileWriterService::Clone() const { return new LegacyFileWriterService(*this); } diff --git a/Core/Code/IO/mitkLegacyFileWriterService.h b/Core/Code/IO/mitkLegacyFileWriterService.h index 077163dd18..4a58a364ab 100644 --- a/Core/Code/IO/mitkLegacyFileWriterService.h +++ b/Core/Code/IO/mitkLegacyFileWriterService.h @@ -1,58 +1,60 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef LegacyFileWriterService_H_HEADER_INCLUDED_C1E7E521 #define LegacyFileWriterService_H_HEADER_INCLUDED_C1E7E521 // Macro #include // MITK #include -#include +#include namespace mitk { //##Documentation //## @brief //## @ingroup Process class LegacyFileWriterService : public mitk::AbstractFileWriter { public: - LegacyFileWriterService(mitk::FileWriter::Pointer legacyWriter, const std::string& basedataType, + LegacyFileWriterService(mitk::FileWriterWithInformation::Pointer legacyWriter, const std::string& basedataType, const std::string& extension, const std::string& description); using AbstractFileWriter::Write; virtual void Write(const BaseData* data, const std::string& path); virtual void Write(const BaseData* data, std::ostream& stream ); + virtual bool CanWrite(const BaseData *data) const; + protected: - mitk::FileWriter::Pointer m_LegacyWriter; + mitk::FileWriterWithInformation::Pointer m_LegacyWriter; private: LegacyFileWriterService* Clone() const; }; } // namespace mitk #endif /* LegacyFileWriterService_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/IO/mitkLegacyImageWriterService.cpp b/Core/Code/IO/mitkLegacyImageWriterService.cpp deleted file mode 100644 index efe4b2970e..0000000000 --- a/Core/Code/IO/mitkLegacyImageWriterService.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#include - -#include - -mitk::LegacyImageWriterService::LegacyImageWriterService(const std::string& basedataType, const std::string& extension, - const std::string& description) - : LegacyFileWriterService(mitk::ImageWriter::New().GetPointer(), basedataType, extension, description) -{ -} - -mitk::LegacyImageWriterService* mitk::LegacyImageWriterService::Clone() const -{ - return new LegacyImageWriterService(*this); -} diff --git a/Core/Code/IO/mitkLegacyImageWriterService.h b/Core/Code/IO/mitkLegacyImageWriterService.h deleted file mode 100644 index d05ee10a19..0000000000 --- a/Core/Code/IO/mitkLegacyImageWriterService.h +++ /dev/null @@ -1,46 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef LegacyImageWriterService_H_HEADER_INCLUDED_C1E7E521 -#define LegacyImageWriterService_H_HEADER_INCLUDED_C1E7E521 - -// Macro -#include - -// MITK -#include - -namespace mitk { - -//##Documentation -//## @brief -//## @ingroup Process -class LegacyImageWriterService : public mitk::LegacyFileWriterService -{ -public: - - LegacyImageWriterService(const std::string& basedataType, const std::string& extension, const std::string& description); - -private: - - LegacyImageWriterService* Clone() const; -}; - -} // namespace mitk - - -#endif /* LegacyImageWriterService_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/IO/mitkPointSetReaderService.cpp b/Core/Code/IO/mitkPointSetReaderService.cpp index 70eff35446..33b987f812 100644 --- a/Core/Code/IO/mitkPointSetReaderService.cpp +++ b/Core/Code/IO/mitkPointSetReaderService.cpp @@ -1,144 +1,149 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // MITK #include "mitkPointSetReaderService.h" #include // STL #include #include #include mitk::PointSetReaderService::PointSetReaderService() : AbstractFileReader("mps", "Great Reader of Point Sets") { RegisterService(); } mitk::PointSetReaderService::~PointSetReaderService() {} std::vector< itk::SmartPointer > mitk::PointSetReaderService::Read(const std::istream& stream, mitk::DataStorage *ds ) { - std::vector< itk::SmartPointer> emptySet; + std::vector< itk::SmartPointer > emptySet; return emptySet; } std::vector< itk::SmartPointer > mitk::PointSetReaderService::Read(const std::string& path, mitk::DataStorage* /*ds*/) { std::locale::global(std::locale("C")); - std::vector< itk::SmartPointer> result; + std::vector< itk::SmartPointer > result; if ( ! this->CanRead( path ) ) { MITK_WARN << "Sorry, can't read file " << path << "! Returning empty set..."; - std::vector< itk::SmartPointer> emptySet; + std::vector< itk::SmartPointer > emptySet; return emptySet; } try{ TiXmlDocument doc(path.c_str()); bool loadOkay = doc.LoadFile(); if (loadOkay) { TiXmlHandle docHandle( &doc ); - unsigned int pointSetCounter(0); + //unsigned int pointSetCounter(0); for( TiXmlElement* currentPointSetElement = docHandle.FirstChildElement("point_set_file").FirstChildElement("point_set").ToElement(); currentPointSetElement != NULL; currentPointSetElement = currentPointSetElement->NextSiblingElement()) { mitk::PointSet::Pointer newPointSet = mitk::PointSet::New(); if(currentPointSetElement->FirstChildElement("time_series") != NULL) { for( TiXmlElement* currentTimeSeries = currentPointSetElement->FirstChildElement("time_series")->ToElement(); currentTimeSeries != NULL; currentTimeSeries = currentTimeSeries->NextSiblingElement()) { unsigned int currentTimeStep(0); TiXmlElement* currentTimeSeriesID = currentTimeSeries->FirstChildElement("time_series_id"); currentTimeStep = atoi(currentTimeSeriesID->GetText()); newPointSet = this->ReadPoint(newPointSet, currentTimeSeries, currentTimeStep); } } else { newPointSet = this->ReadPoint(newPointSet, currentPointSetElement, 0); } result.push_back( newPointSet.GetPointer() ); } } else { MITK_WARN << "XML parser error in mitkPointSetReaderService! Aborting..."; } }catch(...) { MITK_ERROR << "Error while reading point set. Aborting..."; } return result; } mitk::PointSet::Pointer mitk::PointSetReaderService::ReadPoint(mitk::PointSet::Pointer newPointSet, TiXmlElement* currentTimeSeries, unsigned int currentTimeStep) { if(currentTimeSeries->FirstChildElement("point") != NULL) { for( TiXmlElement* currentPoint = currentTimeSeries->FirstChildElement("point")->ToElement(); currentPoint != NULL; currentPoint = currentPoint->NextSiblingElement()) { unsigned int id(0); mitk::PointSpecificationType spec((mitk::PointSpecificationType) 0); double x(0.0); double y(0.0); double z(0.0); id = atoi(currentPoint->FirstChildElement("id")->GetText()); if(currentPoint->FirstChildElement("specification") != NULL) { spec = (mitk::PointSpecificationType) atoi(currentPoint->FirstChildElement("specification")->GetText()); } x = atof(currentPoint->FirstChildElement("x")->GetText()); y = atof(currentPoint->FirstChildElement("y")->GetText()); z = atof(currentPoint->FirstChildElement("z")->GetText()); mitk::Point3D point; mitk::FillVector3D(point, x, y, z); newPointSet->SetPoint(id, point, spec, currentTimeStep); } } else { if(currentTimeStep != newPointSet->GetTimeSteps()+1) { newPointSet->Expand(currentTimeStep+1); // expand time step series with empty time step } } return newPointSet; } bool mitk::PointSetReaderService::CanRead(const std::string& path) const { - std::ifstream in( path ); + std::ifstream in( path.c_str() ); bool isGood = in.good(); in.close(); return isGood; } +mitk::PointSetReaderService::PointSetReaderService(const mitk::PointSetReaderService& other) + : mitk::AbstractFileReader(other) +{ +} + mitk::IFileReader* mitk::PointSetReaderService::Clone() const { - return new mitk::PointSetReaderService(); -} \ No newline at end of file + return new mitk::PointSetReaderService(*this); +} diff --git a/Core/Code/IO/mitkPointSetReaderService.h b/Core/Code/IO/mitkPointSetReaderService.h index d05e1fe3ec..851edb4dcb 100644 --- a/Core/Code/IO/mitkPointSetReaderService.h +++ b/Core/Code/IO/mitkPointSetReaderService.h @@ -1,80 +1,82 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_POINT_SET_READER__H_ #define _MITK_POINT_SET_READER__H_ // ITK #include #include // MITK #include // Old, delete if necessary #include #include #include #include #include #include namespace mitk { /** * @brief reads xml representations of mitk::PointSets from a file * * Reader for xml files containing one or multiple xml represenations of * mitk::PointSets. If multiple mitk::PointSets are stored in one file, * these are assigned to multiple outputs of the filter. The number of point * sets which have be read can be retrieven by a call to GetNumberOfOutputs() * after the pipeline update(). * The reader is able to read the old 3D Pointsets without the "specification" and "timeseries" tags and the new 4D Pointsets. * @note loading point sets from multiple files according to a given file pattern * is not yet supported! * @ingroup PSIO * @ingroup IO */ - class MITK_CORE_EXPORT PointSetReaderService: public AbstractFileReader + class PointSetReaderService: public AbstractFileReader { public: /** * Constructor */ PointSetReaderService(); /** * Virtual destructor */ virtual ~PointSetReaderService(); virtual std::vector< itk::SmartPointer > Read(const std::string& path, mitk::DataStorage* /*ds*/); virtual std::vector< itk::SmartPointer > Read(const std::istream& stream, mitk::DataStorage *ds = 0 ); virtual bool CanRead(const std::string& path) const; protected: + PointSetReaderService(const PointSetReaderService& other); + virtual mitk::PointSet::Pointer ReadPoint(mitk::PointSet::Pointer newPointSet, TiXmlElement* currentTimeSeries, unsigned int currentTimeStep); virtual mitk::IFileReader* Clone() const; }; } #endif diff --git a/Core/Code/Interfaces/mitkIDataNodeReader.h b/Core/Code/Interfaces/mitkIDataNodeReader.h index f9b198674c..8040ba5679 100644 --- a/Core/Code/Interfaces/mitkIDataNodeReader.h +++ b/Core/Code/Interfaces/mitkIDataNodeReader.h @@ -1,58 +1,60 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKIDATANODEREADER_H #define MITKIDATANODEREADER_H #include #include namespace mitk { class DataStorage; /** * \ingroup MicroServices_Interfaces * * This interface provides methods to load data from the local filesystem * into a given mitk::DataStorage. + * + * \deprecatedSince{2013_09} Use mitk::IFileReader instead */ struct IDataNodeReader { virtual ~IDataNodeReader() {} /** * Reads the local file given by fileName and constructs one or more * mitk::DataNode instances which are added to the given mitk::DataStorage storage. * * \param fileName The absolute path to a local file. * \param storage The mitk::DataStorage which will contain the constructed data nodes. * \return The number of constructed mitk::DataNode instances. * * \note Errors during reading the file or constructing the data node should be expressed by * throwing appropriate exceptions. * * \see mitk::DataNodeFactory */ virtual int Read(const std::string& fileName, mitk::DataStorage& storage) = 0; }; } US_DECLARE_SERVICE_INTERFACE(mitk::IDataNodeReader, "org.mitk.IDataNodeReader") #endif // MITKIDATANODEREADER_H diff --git a/Core/Code/Interfaces/mitkIFileReader.cpp b/Core/Code/Interfaces/mitkIFileReader.cpp index 62743a6720..29c7eb8e6c 100644 --- a/Core/Code/Interfaces/mitkIFileReader.cpp +++ b/Core/Code/Interfaces/mitkIFileReader.cpp @@ -1,33 +1,56 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkIFileReader.h" mitk::IFileReader::~IFileReader() { } -const std::string mitk::IFileReader::PROP_EXTENSION = "org.mitk.services.FileReader.Extension"; -const std::string mitk::IFileReader::PROP_DESCRIPTION = "org.mitk.services.FileReader.Description"; -const std::string mitk::IFileReader::PROP_IS_LEGACY = "org.mitk.services.FileReader.IsLegacy"; +std::string mitk::IFileReader::PROP_EXTENSION() +{ + static std::string s = "org.mitk.services.FileReader.Extension"; + return s; +} + +std::string mitk::IFileReader::PROP_DESCRIPTION() +{ + static std::string s = "org.mitk.services.FileReader.Description"; + return s; +} + +std::string mitk::IFileReader::PROP_IS_LEGACY() +{ + static std::string s = "org.mitk.services.FileReader.IsLegacy"; + return s; +} /** * @brief Used to indicate that an image should be read as an binary image. */ -const std::string mitk::IFileReader::OPTION_READ_AS_BINARY = "org.mitk.services.FileReader.Option.ReadAsBinary"; -const std::string mitk::IFileReader::OPTION_READ_MULTIPLE_FILES = "org.mitk.services.FileReader.Option.ReadMultipleFiles"; +std::string mitk::IFileReader::OPTION_READ_AS_BINARY() +{ + static std::string s = "org.mitk.services.FileReader.Option.ReadAsBinary"; + return s; +} + +std::string mitk::IFileReader::OPTION_READ_MULTIPLE_FILES() +{ + static std::string s = "org.mitk.services.FileReader.Option.ReadMultipleFiles"; + return s; +} diff --git a/Core/Code/Interfaces/mitkIFileReader.h b/Core/Code/Interfaces/mitkIFileReader.h index 0630591272..54958a0f8d 100644 --- a/Core/Code/Interfaces/mitkIFileReader.h +++ b/Core/Code/Interfaces/mitkIFileReader.h @@ -1,142 +1,142 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef IFileReader_H_HEADER_INCLUDED_C1E7E521 #define IFileReader_H_HEADER_INCLUDED_C1E7E521 // Macro #include #include // Microservices #include // MITK #include // STL #include namespace mitk { class BaseData; class DataStorage; } namespace itk { template class SmartPointer; } namespace mitk { /** * \brief The common interface of all FileReader. * * This interface defines the Methods necessary for the FileReaderManager * to interact with its FileReaders. To implement a new Filereader, it is * recommended to derive from FileReaderAbstract instead of from the Interface, * as the abstract class already implements most of the functions and also makes sure * that your reader will be managed by the FileReaderManager. */ struct MITK_CORE_EXPORT IFileReader { virtual ~IFileReader(); typedef std::pair FileServiceOption; typedef std::vector OptionNames; typedef std::vector OptionList; /** * \brief Reads the specified file and returns its contents. */ virtual std::vector< itk::SmartPointer > Read(const std::string& path, mitk::DataStorage* ds = 0) = 0; /** * \brief Reads the specified input stream and returns its contents. */ virtual std::vector< itk::SmartPointer > Read(const std::istream& stream, mitk::DataStorage* ds = 0) = 0; /** * \brief Returns the priority which defined how 'good' the FileReader can handle it's file format. * * Default is zero and should only be chosen differently for a reason. * The priority is intended to be used by the MicroserviceFramework to determine * which reader to use if several equivalent readers have been found. * It may be used to replace a default reader from MITK in your own project. * E.g. if you want to use your own reader for *.nrrd files instead of the default, * implement it and give it a higher priority than zero. */ virtual int GetPriority() const = 0 ; /** * \brief returns the file extension that this FileReader is able to handle. * * Please enter only the characters after the fullstop, e.g "nrrd" is correct * while "*.nrrd" and ".nrrd" are incorrect. */ virtual std::string GetExtension() const = 0; /** * \brief Returns a human readable description of the file format. * * This will be used in FileDialogs for example. */ virtual std::string GetDescription() const = 0; /** * \brief returns a list of the supported Options * - * Inititally, the reader contains a set of standard options. These can be retrieved, + * Initially, the reader contains a set of standard options. These can be retrieved, * manipulated and set again. To activate or deactivate an option, just set it's bool * value accordingly. All supported options are in the default set, it does not * make sense to add strings artificially after retrieving a reader - the specific * implementation decides which options it wants to support. * If no options are supported, an empty list is returned. */ virtual OptionList GetOptions() const = 0; /** * \brief Sets the options for this reader * * The best way to use this method is to retireve the options via GetOptions, manipulate the bool values, * and then set the options again. */ virtual void SetOptions(const OptionList& options) = 0; /** * \brief Returns true if this writer can confirm that it can read this file and false otherwise. */ virtual bool CanRead(const std::string& path) const = 0; virtual void AddProgressCallback(const mitk::MessageAbstractDelegate& callback) = 0; virtual void RemoveProgressCallback(const mitk::MessageAbstractDelegate& callback) = 0; // Microservice properties - static const std::string PROP_EXTENSION; - static const std::string PROP_DESCRIPTION; - static const std::string PROP_IS_LEGACY; + static std::string PROP_EXTENSION(); + static std::string PROP_DESCRIPTION(); + static std::string PROP_IS_LEGACY(); // Microservice names for defined properties - static const std::string OPTION_READ_AS_BINARY; - static const std::string OPTION_READ_MULTIPLE_FILES; + static std::string OPTION_READ_AS_BINARY(); + static std::string OPTION_READ_MULTIPLE_FILES(); protected: }; } // namespace mitk // This is the microservice declaration. Do not meddle! US_DECLARE_SERVICE_INTERFACE(mitk::IFileReader, "org.mitk.IFileReader") #endif /* IFileReader_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/Interfaces/mitkIFileWriter.cpp b/Core/Code/Interfaces/mitkIFileWriter.cpp index e57de1611f..fd538daede 100644 --- a/Core/Code/Interfaces/mitkIFileWriter.cpp +++ b/Core/Code/Interfaces/mitkIFileWriter.cpp @@ -1,28 +1,47 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkIFileWriter.h" mitk::IFileWriter::~IFileWriter() { } -const std::string mitk::IFileWriter::PROP_EXTENSION = "org.mitk.services.FileWriter.Extension"; -const std::string mitk::IFileWriter::PROP_BASEDATA_TYPE = "org.mitk.services.FileWriter.BasedataType"; -const std::string mitk::IFileWriter::PROP_DESCRIPTION = "org.mitk.services.FileWriter.Description"; -const std::string mitk::IFileWriter::PROP_IS_LEGACY = "org.mitk.services.FileWriter.IsLegacy"; +std::string mitk::IFileWriter::PROP_EXTENSION() +{ + static std::string s = "org.mitk.services.FileWriter.Extension"; + return s; +} + +std::string mitk::IFileWriter::PROP_BASEDATA_TYPE() +{ + static std::string s = "org.mitk.services.FileWriter.BasedataType"; + return s; +} + +std::string mitk::IFileWriter::PROP_DESCRIPTION() +{ + static std::string s = "org.mitk.services.FileWriter.Description"; + return s; +} + +std::string mitk::IFileWriter::PROP_IS_LEGACY() +{ + static std::string s = "org.mitk.services.FileWriter.IsLegacy"; + return s; +} diff --git a/Core/Code/Interfaces/mitkIFileWriter.h b/Core/Code/Interfaces/mitkIFileWriter.h index 004fc9bbef..8696972629 100644 --- a/Core/Code/Interfaces/mitkIFileWriter.h +++ b/Core/Code/Interfaces/mitkIFileWriter.h @@ -1,105 +1,105 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef IFileWriter_H_HEADER_INCLUDED_C1E7E521 #define IFileWriter_H_HEADER_INCLUDED_C1E7E521 // Macro #include #include // Microservices #include // MITK #include // STL #include namespace mitk { class BaseData; } namespace mitk { /** * \brief The common interface of all FileWriters. * * This interface defines the methods necessary for the FileWriterManager * to interact with its FileWriters. To implement a new FileWriter, it is * recommended to derive from FileWriterAbstract instead of directly from this Interface, * as the abstract class already implements most of the methods and also makes sure that your writer * will be managed by the FileWriterManager. */ struct MITK_CORE_EXPORT IFileWriter { virtual ~IFileWriter(); typedef std::pair FileServiceOption; typedef std::vector OptionList; typedef std::vector OptionNames; virtual void Write(const BaseData* data, const std::string& path ) = 0; virtual void Write(const BaseData* data, std::ostream& stream ) = 0; /** * \brief returns the file extension that this FileWriter is able to handle. * * Please return only the characters after the fullstop, e.g "nrrd" is correct * while "*.nrrd" and ".nrrd" are incorrect. */ virtual std::string GetExtension() const = 0; /** * \brief returns the itk classname that this FileWriter is able to handle. */ virtual std::string GetSupportedBasedataType() const = 0; /** * \brief returns a list of the supported Options * * Options are strings that are treated as flags when passed to the write method. */ virtual OptionList GetOptions() const = 0; virtual void SetOptions(const OptionList& options) = 0; /** * \brief Returns true if this reader can confirm that it can write \c data and false otherwise. */ virtual bool CanWrite(const BaseData* data) const = 0; /** * \brief Returns a value between 0 and 1 depending on the progress of the writing process. * This method need not necessarily be implemented meaningfully, always returning zero is accepted. */ virtual float GetProgress() const = 0; // Microservice properties - static const std::string PROP_EXTENSION; - static const std::string PROP_BASEDATA_TYPE; - static const std::string PROP_DESCRIPTION; - static const std::string PROP_IS_LEGACY; + static std::string PROP_EXTENSION(); + static std::string PROP_BASEDATA_TYPE(); + static std::string PROP_DESCRIPTION(); + static std::string PROP_IS_LEGACY(); protected: }; } // namespace mitk // This is the microservice declaration. Do not meddle! US_DECLARE_SERVICE_INTERFACE(mitk::IFileWriter, "org.mitk.IFileWriter") #endif /* IFileWriter_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/Rendering/mitkImageVtkMapper2D.cpp b/Core/Code/Rendering/mitkImageVtkMapper2D.cpp index 7d6a88dfef..f1badce607 100644 --- a/Core/Code/Rendering/mitkImageVtkMapper2D.cpp +++ b/Core/Code/Rendering/mitkImageVtkMapper2D.cpp @@ -1,1077 +1,1076 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //MITK #include #include -#include #include #include #include #include #include #include #include #include #include //#include #include #include "mitkImageStatisticsHolder.h" #include "mitkPlaneClipping.h" //MITK Rendering #include "mitkImageVtkMapper2D.h" #include "vtkMitkThickSlicesFilter.h" #include "vtkMitkLevelWindowFilter.h" #include "vtkNeverTranslucentTexture.h" //VTK #include #include #include #include #include #include #include #include #include #include #include #include #include #include //ITK #include #include mitk::ImageVtkMapper2D::ImageVtkMapper2D() { } mitk::ImageVtkMapper2D::~ImageVtkMapper2D() { //The 3D RW Mapper (Geometry2DDataVtkMapper3D) is listening to this event, //in order to delete the images from the 3D RW. this->InvokeEvent( itk::DeleteEvent() ); } //set the two points defining the textured plane according to the dimension and spacing void mitk::ImageVtkMapper2D::GeneratePlane(mitk::BaseRenderer* renderer, vtkFloatingPointType planeBounds[6]) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); float depth = this->CalculateLayerDepth(renderer); //Set the origin to (xMin; yMin; depth) of the plane. This is necessary for obtaining the correct //plane size in crosshair rotation and swivel mode. localStorage->m_Plane->SetOrigin(planeBounds[0], planeBounds[2], depth); //These two points define the axes of the plane in combination with the origin. //Point 1 is the x-axis and point 2 the y-axis. //Each plane is transformed according to the view (axial, coronal and saggital) afterwards. localStorage->m_Plane->SetPoint1(planeBounds[1] , planeBounds[2], depth); //P1: (xMax, yMin, depth) localStorage->m_Plane->SetPoint2(planeBounds[0], planeBounds[3], depth); //P2: (xMin, yMax, depth) } float mitk::ImageVtkMapper2D::CalculateLayerDepth(mitk::BaseRenderer* renderer) { //get the clipping range to check how deep into z direction we can render images double maxRange = renderer->GetVtkRenderer()->GetActiveCamera()->GetClippingRange()[1]; //Due to a VTK bug, we cannot use the whole clipping range. /100 is empirically determined float depth = -maxRange*0.01; // divide by 100 int layer = 0; GetDataNode()->GetIntProperty( "layer", layer, renderer); //add the layer property for each image to render images with a higher layer on top of the others depth += layer*10; //*10: keep some room for each image (e.g. for QBalls in between) if(depth > 0.0f) { depth = 0.0f; MITK_WARN << "Layer value exceeds clipping range. Set to minimum instead."; } return depth; } const mitk::Image* mitk::ImageVtkMapper2D::GetInput( void ) { return static_cast< const mitk::Image * >( GetDataNode()->GetData() ); } vtkProp* mitk::ImageVtkMapper2D::GetVtkProp(mitk::BaseRenderer* renderer) { //return the actor corresponding to the renderer return m_LSH.GetLocalStorage(renderer)->m_Actors; } void mitk::ImageVtkMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); mitk::Image *input = const_cast< mitk::Image * >( this->GetInput() ); mitk::DataNode* datanode = this->GetDataNode(); if ( input == NULL || input->IsInitialized() == false ) { return; } //check if there is a valid worldGeometry const Geometry2D *worldGeometry = renderer->GetCurrentWorldGeometry2D(); if( ( worldGeometry == NULL ) || ( !worldGeometry->IsValid() ) || ( !worldGeometry->HasReferenceGeometry() )) { return; } input->Update(); // early out if there is no intersection of the current rendering geometry // and the geometry of the image that is to be rendered. if ( !RenderingGeometryIntersectsImage( worldGeometry, input->GetSlicedGeometry() ) ) { // set image to NULL, to clear the texture in 3D, because // the latest image is used there if the plane is out of the geometry // see bug-13275 localStorage->m_ReslicedImage = NULL; localStorage->m_Mapper->SetInput( localStorage->m_EmptyPolyData ); return; } //set main input for ExtractSliceFilter localStorage->m_Reslicer->SetInput(input); localStorage->m_Reslicer->SetWorldGeometry(worldGeometry); localStorage->m_Reslicer->SetTimeStep( this->GetTimestep() ); //set the transformation of the image to adapt reslice axis localStorage->m_Reslicer->SetResliceTransformByGeometry( input->GetTimeSlicedGeometry()->GetGeometry3D( this->GetTimestep() ) ); //is the geometry of the slice based on the input image or the worldgeometry? bool inPlaneResampleExtentByGeometry = false; datanode->GetBoolProperty("in plane resample extent by geometry", inPlaneResampleExtentByGeometry, renderer); localStorage->m_Reslicer->SetInPlaneResampleExtentByGeometry(inPlaneResampleExtentByGeometry); // Initialize the interpolation mode for resampling; switch to nearest // neighbor if the input image is too small. if ( (input->GetDimension() >= 3) && (input->GetDimension(2) > 1) ) { VtkResliceInterpolationProperty *resliceInterpolationProperty; datanode->GetProperty( resliceInterpolationProperty, "reslice interpolation" ); int interpolationMode = VTK_RESLICE_NEAREST; if ( resliceInterpolationProperty != NULL ) { interpolationMode = resliceInterpolationProperty->GetInterpolation(); } switch ( interpolationMode ) { case VTK_RESLICE_NEAREST: localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST); break; case VTK_RESLICE_LINEAR: localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_LINEAR); break; case VTK_RESLICE_CUBIC: localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_CUBIC); break; } } else { localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST); } //set the vtk output property to true, makes sure that no unneeded mitk image convertion //is done. localStorage->m_Reslicer->SetVtkOutputRequest(true); //Thickslicing int thickSlicesMode = 0; int thickSlicesNum = 1; // Thick slices parameters if( input->GetPixelType().GetNumberOfComponents() == 1 ) // for now only single component are allowed { DataNode *dn=renderer->GetCurrentWorldGeometry2DNode(); if(dn) { ResliceMethodProperty *resliceMethodEnumProperty=0; if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices" ) && resliceMethodEnumProperty ) thickSlicesMode = resliceMethodEnumProperty->GetValueAsId(); IntProperty *intProperty=0; if( dn->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty ) { thickSlicesNum = intProperty->GetValue(); if(thickSlicesNum < 1) thickSlicesNum=1; if(thickSlicesNum > 10) thickSlicesNum=10; } } else { MITK_WARN << "no associated widget plane data tree node found"; } } const PlaneGeometry *planeGeometry = dynamic_cast< const PlaneGeometry * >( worldGeometry ); if(thickSlicesMode > 0) { double dataZSpacing = 1.0; Vector3D normInIndex, normal; if ( planeGeometry != NULL ){ normal = planeGeometry->GetNormal(); }else{ const mitk::AbstractTransformGeometry* abstractGeometry = dynamic_cast< const AbstractTransformGeometry * >(worldGeometry); if(abstractGeometry != NULL) normal = abstractGeometry->GetPlane()->GetNormal(); else return; //no fitting geometry set } normal.Normalize(); input->GetTimeSlicedGeometry()->GetGeometry3D( this->GetTimestep() )->WorldToIndex( normal, normInIndex ); dataZSpacing = 1.0 / normInIndex.GetNorm(); localStorage->m_Reslicer->SetOutputDimensionality( 3 ); localStorage->m_Reslicer->SetOutputSpacingZDirection(dataZSpacing); localStorage->m_Reslicer->SetOutputExtentZDirection( -thickSlicesNum, 0+thickSlicesNum ); // Do the reslicing. Modified() is called to make sure that the reslicer is // executed even though the input geometry information did not change; this // is necessary when the input /em data, but not the /em geometry changes. localStorage->m_TSFilter->SetThickSliceMode( thickSlicesMode-1 ); localStorage->m_TSFilter->SetInput( localStorage->m_Reslicer->GetVtkOutput() ); //vtkFilter=>mitkFilter=>vtkFilter update mechanism will fail without calling manually localStorage->m_Reslicer->Modified(); localStorage->m_Reslicer->Update(); localStorage->m_TSFilter->Modified(); localStorage->m_TSFilter->Update(); localStorage->m_ReslicedImage = localStorage->m_TSFilter->GetOutput(); } else { //this is needed when thick mode was enable bevore. These variable have to be reset to default values localStorage->m_Reslicer->SetOutputDimensionality( 2 ); localStorage->m_Reslicer->SetOutputSpacingZDirection(1.0); localStorage->m_Reslicer->SetOutputExtentZDirection( 0, 0 ); localStorage->m_Reslicer->Modified(); //start the pipeline with updating the largest possible, needed if the geometry of the input has changed localStorage->m_Reslicer->UpdateLargestPossibleRegion(); localStorage->m_ReslicedImage = localStorage->m_Reslicer->GetVtkOutput(); } // Bounds information for reslicing (only reuqired if reference geometry // is present) //this used for generating a vtkPLaneSource with the right size vtkFloatingPointType sliceBounds[6]; for ( int i = 0; i < 6; ++i ) { sliceBounds[i] = 0.0; } localStorage->m_Reslicer->GetClippedPlaneBounds(sliceBounds); //get the spacing of the slice localStorage->m_mmPerPixel = localStorage->m_Reslicer->GetOutputSpacing(); // calculate minimum bounding rect of IMAGE in texture { vtkFloatingPointType textureClippingBounds[6]; for ( int i = 0; i < 6; ++i ) { textureClippingBounds[i] = 0.0; } // Calculate the actual bounds of the transformed plane clipped by the // dataset bounding box; this is required for drawing the texture at the // correct position during 3D mapping. mitk::PlaneClipping::CalculateClippedPlaneBounds( input->GetGeometry(), planeGeometry, textureClippingBounds ); textureClippingBounds[0] = static_cast< int >( textureClippingBounds[0] / localStorage->m_mmPerPixel[0] + 0.5 ); textureClippingBounds[1] = static_cast< int >( textureClippingBounds[1] / localStorage->m_mmPerPixel[0] + 0.5 ); textureClippingBounds[2] = static_cast< int >( textureClippingBounds[2] / localStorage->m_mmPerPixel[1] + 0.5 ); textureClippingBounds[3] = static_cast< int >( textureClippingBounds[3] / localStorage->m_mmPerPixel[1] + 0.5 ); //clipping bounds for cutting the image localStorage->m_LevelWindowFilter->SetClippingBounds(textureClippingBounds); } //get the number of scalar components to distinguish between different image types int numberOfComponents = localStorage->m_ReslicedImage->GetNumberOfScalarComponents(); //get the binary property bool binary = false; bool binaryOutline = false; datanode->GetBoolProperty( "binary", binary, renderer ); if(binary) //binary image { datanode->GetBoolProperty( "outline binary", binaryOutline, renderer ); if(binaryOutline) //contour rendering { if ( input->GetPixelType().GetBpe() <= 8 ) { //generate contours/outlines localStorage->m_OutlinePolyData = CreateOutlinePolyData(renderer); float binaryOutlineWidth(1.0); if ( datanode->GetFloatProperty( "outline width", binaryOutlineWidth, renderer ) ) { if ( localStorage->m_Actors->GetNumberOfPaths() > 1 ) { float binaryOutlineShadowWidth(1.5); datanode->GetFloatProperty( "outline shadow width", binaryOutlineShadowWidth, renderer ); dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0)) ->GetProperty()->SetLineWidth( binaryOutlineWidth * binaryOutlineShadowWidth ); } localStorage->m_Actor->GetProperty()->SetLineWidth( binaryOutlineWidth ); } } else { binaryOutline = false; this->ApplyLookuptable(renderer); MITK_WARN << "Type of all binary images should be (un)signed char. Outline does not work on other pixel types!"; } } else //standard binary image { if(numberOfComponents != 1) { MITK_ERROR << "Rendering Error: Binary Images with more then 1 component are not supported!"; } } } if (!(numberOfComponents == 1 || numberOfComponents == 3 || numberOfComponents == 4)) { MITK_WARN << "Unknown number of components!"; } this->ApplyOpacity( renderer ); this->ApplyRenderingMode(renderer); // do not use a VTK lookup table (we do that ourselves in m_LevelWindowFilter) localStorage->m_Texture->MapColorScalarsThroughLookupTableOff(); //connect the input with the levelwindow filter localStorage->m_LevelWindowFilter->SetInput(localStorage->m_ReslicedImage); //connect the texture with the output of the levelwindow filter // check for texture interpolation property bool textureInterpolation = false; GetDataNode()->GetBoolProperty( "texture interpolation", textureInterpolation, renderer ); //set the interpolation modus according to the property localStorage->m_Texture->SetInterpolate(textureInterpolation); localStorage->m_Texture->SetInputConnection(localStorage->m_LevelWindowFilter->GetOutputPort()); this->TransformActor( renderer ); vtkActor* contourShadowActor = dynamic_cast (localStorage->m_Actors->GetParts()->GetItemAsObject(0)); if(binary && binaryOutline) //connect the mapper with the polyData which contains the lines { //We need the contour for the binary outline property as actor localStorage->m_Mapper->SetInput(localStorage->m_OutlinePolyData); localStorage->m_Actor->SetTexture(NULL); //no texture for contours bool binaryOutlineShadow( false ); datanode->GetBoolProperty( "outline binary shadow", binaryOutlineShadow, renderer ); if ( binaryOutlineShadow ) contourShadowActor->SetVisibility( true ); else contourShadowActor->SetVisibility( false ); } else { //Connect the mapper with the input texture. This is the standard case. //setup the textured plane this->GeneratePlane( renderer, sliceBounds ); //set the plane as input for the mapper localStorage->m_Mapper->SetInputConnection(localStorage->m_Plane->GetOutputPort()); //set the texture for the actor localStorage->m_Actor->SetTexture(localStorage->m_Texture); contourShadowActor->SetVisibility( false ); } // We have been modified => save this for next Update() localStorage->m_LastUpdateTime.Modified(); } void mitk::ImageVtkMapper2D::ApplyLevelWindow(mitk::BaseRenderer *renderer) { LocalStorage *localStorage = this->GetLocalStorage( renderer ); LevelWindow levelWindow; this->GetDataNode()->GetLevelWindow( levelWindow, renderer, "levelwindow" ); localStorage->m_LevelWindowFilter->GetLookupTable()->SetRange( levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound() ); mitk::LevelWindow opacLevelWindow; if( this->GetDataNode()->GetLevelWindow( opacLevelWindow, renderer, "opaclevelwindow" ) ) { //pass the opaque level window to the filter localStorage->m_LevelWindowFilter->SetMinOpacity(opacLevelWindow.GetLowerWindowBound()); localStorage->m_LevelWindowFilter->SetMaxOpacity(opacLevelWindow.GetUpperWindowBound()); } else { //no opaque level window localStorage->m_LevelWindowFilter->SetMinOpacity(0.0); localStorage->m_LevelWindowFilter->SetMaxOpacity(255.0); } } void mitk::ImageVtkMapper2D::ApplyColor( mitk::BaseRenderer* renderer ) { LocalStorage *localStorage = this->GetLocalStorage( renderer ); float rgb[3]= { 1.0f, 1.0f, 1.0f }; // check for color prop and use it for rendering if it exists // binary image hovering & binary image selection bool hover = false; bool selected = false; GetDataNode()->GetBoolProperty("binaryimage.ishovering", hover, renderer); GetDataNode()->GetBoolProperty("selected", selected, renderer); if(hover && !selected) { mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty ("binaryimage.hoveringcolor", renderer)); if(colorprop.IsNotNull()) { memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); } else { GetDataNode()->GetColor( rgb, renderer, "color" ); } } if(selected) { mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty ("binaryimage.selectedcolor", renderer)); if(colorprop.IsNotNull()) { memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); } else { GetDataNode()->GetColor(rgb, renderer, "color"); } } if(!hover && !selected) { GetDataNode()->GetColor( rgb, renderer, "color" ); } double rgbConv[3] = {(double)rgb[0], (double)rgb[1], (double)rgb[2]}; //conversion to double for VTK dynamic_cast (localStorage->m_Actors->GetParts()->GetItemAsObject(0))->GetProperty()->SetColor(rgbConv); localStorage->m_Actor->GetProperty()->SetColor(rgbConv); if ( localStorage->m_Actors->GetParts()->GetNumberOfItems() > 1 ) { float rgb[3]= { 1.0f, 1.0f, 1.0f }; mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty ("outline binary shadow color", renderer)); if(colorprop.IsNotNull()) { memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); } double rgbConv[3] = {(double)rgb[0], (double)rgb[1], (double)rgb[2]}; //conversion to double for VTK dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) )->GetProperty()->SetColor(rgbConv); } } void mitk::ImageVtkMapper2D::ApplyOpacity( mitk::BaseRenderer* renderer ) { LocalStorage* localStorage = this->GetLocalStorage( renderer ); float opacity = 1.0f; // check for opacity prop and use it for rendering if it exists GetDataNode()->GetOpacity( opacity, renderer, "opacity" ); //set the opacity according to the properties localStorage->m_Actor->GetProperty()->SetOpacity(opacity); if ( localStorage->m_Actors->GetParts()->GetNumberOfItems() > 1 ) { dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) )->GetProperty()->SetOpacity(opacity); } } void mitk::ImageVtkMapper2D::ApplyRenderingMode( mitk::BaseRenderer* renderer ) { LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); bool binary = false; this->GetDataNode()->GetBoolProperty( "binary", binary, renderer ); if(binary) // is it a binary image? { //for binary images, we always use our default LuT and map every value to (0,1) //the opacity of 0 will always be 0.0. We never a apply a LuT/TfF nor a level window. localStorage->m_LevelWindowFilter->SetLookupTable(localStorage->m_BinaryLookupTable); } else { //all other image types can make use of the rendering mode int renderingMode = mitk::RenderingModeProperty::LEVELWINDOW_COLOR; mitk::RenderingModeProperty::Pointer mode = dynamic_cast(this->GetDataNode()->GetProperty( "Image Rendering.Mode", renderer )); if(mode.IsNotNull()) { renderingMode = mode->GetRenderingMode(); } switch(renderingMode) { case mitk::RenderingModeProperty::LEVELWINDOW_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_Color"; localStorage->m_LevelWindowFilter->SetLookupTable( localStorage->m_DefaultLookupTable ); this->ApplyLevelWindow( renderer ); break; case mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_LookupTable_Color"; this->ApplyLookuptable( renderer ); this->ApplyLevelWindow( renderer ); break; case mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_ColorTransferFunction_Color"; this->ApplyColorTransferFunction( renderer ); this->ApplyLevelWindow( renderer ); break; case mitk::RenderingModeProperty::LOOKUPTABLE_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = LookupTable_Color"; this->ApplyLookuptable( renderer ); break; case mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = ColorTransferFunction_Color"; this->ApplyColorTransferFunction( renderer ); break; default: MITK_ERROR << "No valid 'Image Rendering.Mode' set"; break; } } //we apply color for all images (including binaries). this->ApplyColor( renderer ); } void mitk::ImageVtkMapper2D::ApplyLookuptable( mitk::BaseRenderer* renderer ) { LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); vtkLookupTable* usedLookupTable = localStorage->m_ColorLookupTable; // If lookup table or transferfunction use is requested... mitk::LookupTableProperty::Pointer lookupTableProp = dynamic_cast(this->GetDataNode()->GetProperty("LookupTable")); if( lookupTableProp.IsNotNull() ) // is a lookuptable set? { usedLookupTable = lookupTableProp->GetLookupTable()->GetVtkLookupTable(); } else { MITK_WARN << "Image Rendering.Mode was set to use a lookup table but there is no property 'LookupTable'. A default (rainbow) lookup table will be used."; } localStorage->m_LevelWindowFilter->SetLookupTable(usedLookupTable); } void mitk::ImageVtkMapper2D::ApplyColorTransferFunction(mitk::BaseRenderer *renderer) { mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(this->GetDataNode()->GetProperty("Image Rendering.Transfer Function",renderer )); if( transferFunctionProp.IsNull() ) { MITK_ERROR << "'Image Rendering.Mode'' was set to use a color transfer function but there is no property 'Image Rendering.Transfer Function'. Nothing will be done."; return; } LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); //pass the transfer function to our level window filter localStorage->m_LevelWindowFilter->SetLookupTable(transferFunctionProp->GetValue()->GetColorTransferFunction()); } void mitk::ImageVtkMapper2D::Update(mitk::BaseRenderer* renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if ( !visible ) { return; } mitk::Image* data = const_cast( this->GetInput() ); if ( data == NULL ) { return; } // Calculate time step of the input data for the specified renderer (integer value) this->CalculateTimeStep( renderer ); // Check if time step is valid const TimeSlicedGeometry *dataTimeGeometry = data->GetTimeSlicedGeometry(); if ( ( dataTimeGeometry == NULL ) || ( dataTimeGeometry->GetTimeSteps() == 0 ) || ( !dataTimeGeometry->IsValidTime( this->GetTimestep() ) ) ) { return; } const DataNode *node = this->GetDataNode(); data->UpdateOutputInformation(); LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //check if something important has changed and we need to rerender if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified? || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2DUpdateTime()) //was the geometry modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldGeometry2D()->GetMTime()) || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) { this->GenerateDataForRenderer( renderer ); } // since we have checked that nothing important has changed, we can set // m_LastUpdateTime to the current time localStorage->m_LastUpdateTime.Modified(); } void mitk::ImageVtkMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { mitk::Image::Pointer image = dynamic_cast(node->GetData()); // Properties common for both images and segmentations node->AddProperty( "depthOffset", mitk::FloatProperty::New( 0.0 ), renderer, overwrite ); node->AddProperty( "outline binary", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "outline width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite ); node->AddProperty( "outline binary shadow", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "outline binary shadow color", ColorProperty::New(0.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "outline shadow width", mitk::FloatProperty::New( 1.5 ), renderer, overwrite ); if(image->IsRotated()) node->AddProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New(VTK_RESLICE_CUBIC) ); else node->AddProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ); - node->AddProperty( "texture interpolation", mitk::BoolProperty::New( mitk::DataNodeFactory::m_TextureInterpolationActive ) ); // set to user configurable default value (see global options) + node->AddProperty( "texture interpolation", mitk::BoolProperty::New( false ) ); node->AddProperty( "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ); node->AddProperty( "bounding box", mitk::BoolProperty::New( false ) ); mitk::RenderingModeProperty::Pointer renderingModeProperty = mitk::RenderingModeProperty::New(); node->AddProperty( "Image Rendering.Mode", renderingModeProperty); std::string photometricInterpretation; // DICOM tag telling us how pixel values should be displayed if ( node->GetStringProperty( "dicom.pixel.PhotometricInterpretation", photometricInterpretation ) ) { // modality provided by DICOM or other reader if ( photometricInterpretation.find("MONOCHROME1") != std::string::npos ) // meaning: display MINIMUM pixels as WHITE { // generate LUT (white to black) mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); vtkLookupTable* bwLut = mitkLut->GetVtkLookupTable(); bwLut->SetTableRange (0, 1); bwLut->SetSaturationRange (0, 0); bwLut->SetHueRange (0, 0); bwLut->SetValueRange (1, 0); bwLut->SetAlphaRange (1, 1); bwLut->SetRampToLinear(); bwLut->Build(); mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); mitkLutProp->SetLookupTable(mitkLut); node->SetProperty( "LookupTable", mitkLutProp ); } else if ( photometricInterpretation.find("MONOCHROME2") != std::string::npos ) // meaning: display MINIMUM pixels as BLACK { // apply default LUT (black to white) node->SetProperty( "color", mitk::ColorProperty::New( 1,1,1 ), renderer ); } // PALETTE interpretation should be handled ok by RGB loading } bool isBinaryImage(false); if ( ! node->GetBoolProperty("binary", isBinaryImage) ) { // ok, property is not set, use heuristic to determine if this // is a binary image mitk::Image::Pointer centralSliceImage; ScalarType minValue = 0.0; ScalarType maxValue = 0.0; ScalarType min2ndValue = 0.0; ScalarType max2ndValue = 0.0; mitk::ImageSliceSelector::Pointer sliceSelector = mitk::ImageSliceSelector::New(); sliceSelector->SetInput(image); sliceSelector->SetSliceNr(image->GetDimension(2)/2); sliceSelector->SetTimeNr(image->GetDimension(3)/2); sliceSelector->SetChannelNr(image->GetDimension(4)/2); sliceSelector->Update(); centralSliceImage = sliceSelector->GetOutput(); if ( centralSliceImage.IsNotNull() && centralSliceImage->IsInitialized() ) { minValue = centralSliceImage->GetStatistics()->GetScalarValueMin(); maxValue = centralSliceImage->GetStatistics()->GetScalarValueMax(); min2ndValue = centralSliceImage->GetStatistics()->GetScalarValue2ndMin(); max2ndValue = centralSliceImage->GetStatistics()->GetScalarValue2ndMax(); } if ((maxValue == min2ndValue && minValue == max2ndValue) || minValue == maxValue) { // centralSlice is strange, lets look at all data minValue = image->GetStatistics()->GetScalarValueMin(); maxValue = image->GetStatistics()->GetScalarValueMaxNoRecompute(); min2ndValue = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(); max2ndValue = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(); } isBinaryImage = ( maxValue == min2ndValue && minValue == max2ndValue ); } // some more properties specific for a binary... if (isBinaryImage) { node->AddProperty( "opacity", mitk::FloatProperty::New(0.3f), renderer, overwrite ); node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binaryimage.selectedcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binaryimage.selectedannotationcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binaryimage.hoveringcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binaryimage.hoveringannotationcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binary", mitk::BoolProperty::New( true ), renderer, overwrite ); node->AddProperty("layer", mitk::IntProperty::New(10), renderer, overwrite); } else //...or image type object { node->AddProperty( "opacity", mitk::FloatProperty::New(1.0f), renderer, overwrite ); node->AddProperty( "color", ColorProperty::New(1.0,1.0,1.0), renderer, overwrite ); node->AddProperty( "binary", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty("layer", mitk::IntProperty::New(0), renderer, overwrite); } if(image.IsNotNull() && image->IsInitialized()) { if((overwrite) || (node->GetProperty("levelwindow", renderer)==NULL)) { /* initialize level/window from DICOM tags */ std::string sLevel; std::string sWindow; if ( image->GetPropertyList()->GetStringProperty( "dicom.voilut.WindowCenter", sLevel ) && image->GetPropertyList()->GetStringProperty( "dicom.voilut.WindowWidth", sWindow ) ) { float level = atof( sLevel.c_str() ); float window = atof( sWindow.c_str() ); mitk::LevelWindow contrast; std::string sSmallestPixelValueInSeries; std::string sLargestPixelValueInSeries; if ( image->GetPropertyList()->GetStringProperty( "dicom.series.SmallestPixelValueInSeries", sSmallestPixelValueInSeries ) && image->GetPropertyList()->GetStringProperty( "dicom.series.LargestPixelValueInSeries", sLargestPixelValueInSeries ) ) { float smallestPixelValueInSeries = atof( sSmallestPixelValueInSeries.c_str() ); float largestPixelValueInSeries = atof( sLargestPixelValueInSeries.c_str() ); contrast.SetRangeMinMax( smallestPixelValueInSeries-1, largestPixelValueInSeries+1 ); // why not a little buffer? // might remedy some l/w widget challenges } else { contrast.SetAuto( static_cast(node->GetData()), false, true ); // we need this as a fallback } contrast.SetLevelWindow( level, window, true ); node->SetProperty( "levelwindow", LevelWindowProperty::New( contrast ), renderer ); } } if(((overwrite) || (node->GetProperty("opaclevelwindow", renderer)==NULL)) && (image->GetPixelType().GetPixelType() == itk::ImageIOBase::RGBA) && (image->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR) ) { mitk::LevelWindow opaclevwin; opaclevwin.SetRangeMinMax(0,255); opaclevwin.SetWindowBounds(0,255); mitk::LevelWindowProperty::Pointer prop = mitk::LevelWindowProperty::New(opaclevwin); node->SetProperty( "opaclevelwindow", prop, renderer ); } } Superclass::SetDefaultProperties(node, renderer, overwrite); } mitk::ImageVtkMapper2D::LocalStorage* mitk::ImageVtkMapper2D::GetLocalStorage(mitk::BaseRenderer* renderer) { return m_LSH.GetLocalStorage(renderer); } vtkSmartPointer mitk::ImageVtkMapper2D::CreateOutlinePolyData(mitk::BaseRenderer* renderer ){ LocalStorage* localStorage = this->GetLocalStorage(renderer); //get the min and max index values of each direction int* extent = localStorage->m_ReslicedImage->GetExtent(); int xMin = extent[0]; int xMax = extent[1]; int yMin = extent[2]; int yMax = extent[3]; int* dims = localStorage->m_ReslicedImage->GetDimensions(); //dimensions of the image int line = dims[0]; //how many pixels per line? int x = xMin; //pixel index x int y = yMin; //pixel index y char* currentPixel; //get the depth for each contour float depth = CalculateLayerDepth(renderer); vtkSmartPointer points = vtkSmartPointer::New(); //the points to draw vtkSmartPointer lines = vtkSmartPointer::New(); //the lines to connect the points // We take the pointer to the first pixel of the image currentPixel = static_cast(localStorage->m_ReslicedImage->GetScalarPointer() ); while (y <= yMax) { //if the current pixel value is set to something if ((currentPixel) && (*currentPixel != 0)) { //check in which direction a line is necessary //a line is added if the neighbor of the current pixel has the value 0 //and if the pixel is located at the edge of the image //if vvvvv not the first line vvvvv if (y > yMin && *(currentPixel-line) == 0) { //x direction - bottom edge of the pixel //add the 2 points vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); //add the line between both points lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv not the last line vvvvv if (y < yMax && *(currentPixel+line) == 0) { //x direction - top edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv not the first pixel vvvvv if ( (x > xMin || y > yMin) && *(currentPixel-1) == 0) { //y direction - left edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv not the last pixel vvvvv if ( (y < yMax || (x < xMax) ) && *(currentPixel+1) == 0) { //y direction - right edge of the pixel vtkIdType p1 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } /* now consider pixels at the edge of the image */ //if vvvvv left edge of image vvvvv if (x == xMin) { //draw left edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv right edge of image vvvvv if (x == xMax) { //draw right edge of the pixel vtkIdType p1 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv bottom edge of image vvvvv if (y == yMin) { //draw bottom edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv top edge of image vvvvv if (y == yMax) { //draw top edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } }//end if currentpixel is set x++; if (x > xMax) { //reached end of line x = xMin; y++; } // Increase the pointer-position to the next pixel. // This is safe, as the while-loop and the x-reset logic above makes // sure we do not exceed the bounds of the image currentPixel++; }//end of while // Create a polydata to store everything in vtkSmartPointer polyData = vtkSmartPointer::New(); // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(lines); return polyData; } void mitk::ImageVtkMapper2D::TransformActor(mitk::BaseRenderer* renderer) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //get the transformation matrix of the reslicer in order to render the slice as axial, coronal or saggital vtkSmartPointer trans = vtkSmartPointer::New(); vtkSmartPointer matrix = localStorage->m_Reslicer->GetResliceAxes(); trans->SetMatrix(matrix); //transform the plane/contour (the actual actor) to the corresponding view (axial, coronal or saggital) localStorage->m_Actor->SetUserTransform(trans); //transform the origin to center based coordinates, because MITK is center based. localStorage->m_Actor->SetPosition( -0.5*localStorage->m_mmPerPixel[0], -0.5*localStorage->m_mmPerPixel[1], 0.0); if ( localStorage->m_Actors->GetNumberOfPaths() > 1 ) { vtkActor* secondaryActor = dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) ); secondaryActor->SetUserTransform(trans); secondaryActor->SetPosition( -0.5*localStorage->m_mmPerPixel[0], -0.5*localStorage->m_mmPerPixel[1], 0.0); } } bool mitk::ImageVtkMapper2D::RenderingGeometryIntersectsImage( const Geometry2D* renderingGeometry, SlicedGeometry3D* imageGeometry ) { // if either one of the two geometries is NULL we return true // for safety reasons if ( renderingGeometry == NULL || imageGeometry == NULL ) return true; // get the distance for the first cornerpoint ScalarType initialDistance = renderingGeometry->SignedDistance( imageGeometry->GetCornerPoint( 0 ) ); for( int i=1; i<8; i++ ) { mitk::Point3D cornerPoint = imageGeometry->GetCornerPoint( i ); // get the distance to the other cornerpoints ScalarType distance = renderingGeometry->SignedDistance( cornerPoint ); // if it has not the same signing as the distance of the first point if ( initialDistance * distance < 0 ) { // we have an intersection and return true return true; } } // all distances have the same sign, no intersection and we return false return false; } mitk::ImageVtkMapper2D::LocalStorage::~LocalStorage() { } mitk::ImageVtkMapper2D::LocalStorage::LocalStorage() { m_LevelWindowFilter = vtkSmartPointer::New(); //Do as much actions as possible in here to avoid double executions. m_Plane = vtkSmartPointer::New(); m_Texture = vtkSmartPointer::New().GetPointer(); m_DefaultLookupTable = vtkSmartPointer::New(); m_BinaryLookupTable = vtkSmartPointer::New(); m_ColorLookupTable = vtkSmartPointer::New(); m_Mapper = vtkSmartPointer::New(); m_Actor = vtkSmartPointer::New(); m_Actors = vtkSmartPointer::New(); m_Reslicer = mitk::ExtractSliceFilter::New(); m_TSFilter = vtkSmartPointer::New(); m_OutlinePolyData = vtkSmartPointer::New(); m_ReslicedImage = vtkSmartPointer::New(); m_EmptyPolyData = vtkSmartPointer::New(); //the following actions are always the same and thus can be performed //in the constructor for each image (i.e. the image-corresponding local storage) m_TSFilter->ReleaseDataFlagOn(); //built a default lookuptable m_DefaultLookupTable->SetRampToLinear(); m_DefaultLookupTable->SetSaturationRange( 0.0, 0.0 ); m_DefaultLookupTable->SetHueRange( 0.0, 0.0 ); m_DefaultLookupTable->SetValueRange( 0.0, 1.0 ); m_DefaultLookupTable->Build(); m_BinaryLookupTable->SetRampToLinear(); m_BinaryLookupTable->SetSaturationRange( 0.0, 0.0 ); m_BinaryLookupTable->SetHueRange( 0.0, 0.0 ); m_BinaryLookupTable->SetValueRange( 0.0, 1.0 ); m_BinaryLookupTable->SetRange(0.0, 1.0); m_BinaryLookupTable->Build(); // add a default rainbow lookup table for color mapping m_ColorLookupTable->SetRampToLinear(); m_ColorLookupTable->SetHueRange(0.6667, 0.0); m_ColorLookupTable->SetTableRange(0.0, 20.0); m_ColorLookupTable->Build(); // make first value transparent { double rgba[4]; m_BinaryLookupTable->GetTableValue(0, rgba); m_BinaryLookupTable->SetTableValue(0, rgba[0], rgba[1], rgba[2], 0.0); // background to 0 } //do not repeat the texture (the image) m_Texture->RepeatOff(); //set the mapper for the actor m_Actor->SetMapper( m_Mapper ); vtkSmartPointer outlineShadowActor = vtkSmartPointer::New(); outlineShadowActor->SetMapper( m_Mapper ); m_Actors->AddPart( outlineShadowActor ); m_Actors->AddPart( m_Actor ); } diff --git a/Core/Code/Rendering/mitkRenderingTestHelper.h b/Core/Code/Rendering/mitkRenderingTestHelper.h index 22f0a69d50..1b51b87a14 100644 --- a/Core/Code/Rendering/mitkRenderingTestHelper.h +++ b/Core/Code/Rendering/mitkRenderingTestHelper.h @@ -1,171 +1,170 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkRenderingTestHelper_h #define mitkRenderingTestHelper_h #include #include -#include #include #include class vtkRenderWindow; class vtkRenderer; namespace mitk { class MITK_CORE_EXPORT RenderingTestHelper { public: /** @brief Generate a rendering test helper object including a render window of the size width * height (in pixel). @param argc Number of parameters. (here: Images) "Usage: [filename1 filenam2 -V referenceScreenshot (optional -T /directory/to/save/differenceImage)] @param argv Given parameters. If no data is inserted via commandline, you can add data later via AddNodeToDataStorage(). **/ RenderingTestHelper(int width, int height, int argc, char *argv[]); /** @brief Generate a rendering test helper object including a render window of the size width * height (in pixel).*/ RenderingTestHelper(int width, int height); /** Default destructor */ ~RenderingTestHelper(); /** @brief Getter for the vtkRenderer. **/ vtkRenderer* GetVtkRenderer(); /** @brief Getter for the vtkRenderWindow which should be used to call vtkRegressionTestImage. **/ vtkRenderWindow* GetVtkRenderWindow(); /** @brief Method can be used to save a screenshot (e.g. reference screenshot as a .png file. @param fileName The filename of the new screenshot (including path). **/ void SaveAsPNG(std::string fileName); /** * @brief SetStopRenderWindow Convenience method to make the renderwindow hold after rendering. Usefull for debugging. * @param flag Flag indicating whether the renderwindow should automatically close (false, default) or stay open (true). Usefull for debugging. */ void SetAutomaticallyCloseRenderWindow(bool automaticallyCloseRenderWindow); /** @brief This method set the property of the member datastorage @param property Set a property for each image in the datastorage m_DataStorage. If you want to set the property for a single data node, use GetDataStorage() and set the property yourself for the destinct node. **/ void SetImageProperty(const char *propertyKey, mitk::BaseProperty *property); /** @brief Set the view direction of the renderwindow (e.g. sagittal, coronal, axial) **/ void SetViewDirection(mitk::SliceNavigationController::ViewDirection viewDirection); /** @brief Reorient the slice (e.g. rotation and translation like the swivel mode). **/ void ReorientSlices(mitk::Point3D origin, mitk::Vector3D rotation); /** @brief Render everything into an mitkRenderWindow. Call SetViewDirection() and SetProperty() before this method. **/ void Render(); /** @brief Returns the datastorage, in order to modify the data inside a rendering test. **/ mitk::DataStorage::Pointer GetDataStorage(); /** * @brief SetMapperID Change between Standard2D and 3D mappers. * @param id Enum mitk::BaseRenderer::StandardMapperSlot which defines the mapper. */ void SetMapperID(mitk::BaseRenderer::StandardMapperSlot id); /** * @brief AddNodeToStorage Add a node to the datastorage and perform a reinit which is necessary for rendering. * @param node The data you want to add. */ void AddNodeToStorage(mitk::DataNode::Pointer node); /** * @brief SetMapperIDToRender3D Convenience method to render in a 3D renderwindow. * @warning Does not add helper objects like the image planes to render images in 3D. */ void SetMapperIDToRender3D(); /** * @brief SetMapperIDToRender2D Convenience method to render in a 2D renderwindow. */ void SetMapperIDToRender2D(); /** * @brief SaveReferenceScreenShot Convenience method to save a reference screen shot. * @param fileName Path/to/save/the/png/file. */ void SaveReferenceScreenShot(std::string fileName); /** * @brief CompareRenderWindowAgainstReference Convenience method to compare the image rendered in the internal renderwindow against a reference screen shot. * Usage of vtkTesting::Test: vtkTesting::Test( argc, argv, vtkRenderWindow, threshold ) Set a vtkRenderWindow containing the desired scene. This is automatically rendered. vtkTesting::Test() automatically searches in argc and argv[] for a path a valid image with -V. If the test failed with the first image (foo.png) it checks if there are images of the form foo_N.png (where N=1,2,3...) and compare against them. This allows for multiple valid images. * @param argc Number of arguments. * @param argv Arguments must(!) contain the term "-V Path/To/Valid/Image.png" * @param threshold Allowed difference between two images. Default = 10.0 and was taken from VTK. * @return True if the images are equal regarding the threshold. False in all other cases. */ bool CompareRenderWindowAgainstReference(int argc, char *argv[], double threshold = 10.0); protected: /** * @brief Initialize Internal method to initialize the renderwindow and set the datastorage. * @param width Height of renderwindow. * @param height Width of renderwindow. */ void Initialize(int width, int height); /** @brief Prints the opengl information, e.g. version, vendor and extensions, * This function can only be called after an opengl context is active. * It only prints the context after the vtkRenderwindow is fully initialized. **/ void PrintGLInfo(); /** @brief This method tries to load the given file into a member datastorage, in order to render it. @param fileName The filename of the file to be loaded (including path). **/ void AddToStorage(const std::string& filename); /** @brief This method tries to parse the given argv for files (e.g. images) and load them into a member datastorage, in order to render it. @param argc Number of parameters. @param argv Given parameters. **/ void SetInputFileNames(int argc, char *argv[]); mitk::RenderWindow::Pointer m_RenderWindow; //<< Contains the mitkRenderWindow into which the test renders the data mitk::DataStorage::Pointer m_DataStorage; //<< Contains the mitkDataStorage which contains the data to be rendered bool m_AutomaticallyCloseRenderWindow; //<< Flag indicating whether the renderwindow should automatically close (true, default) or stay open (false). Usefull for debugging. }; }//namespace mitk #endif diff --git a/Core/Code/Testing/files.cmake b/Core/Code/Testing/files.cmake index a6ad4d636d..6e6452e04b 100644 --- a/Core/Code/Testing/files.cmake +++ b/Core/Code/Testing/files.cmake @@ -1,158 +1,156 @@ # tests with no extra command line parameter set(MODULE_TESTS mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkDispatcherTest.cpp mitkEnumerationPropertyTest.cpp mitkEventTest.cpp mitkFileReaderRegistryTest.cpp mitkFileWriterRegistryTest.cpp mitkFocusManagerTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkGlobalInteractionTest.cpp mitkImageDataItemTest.cpp #mitkImageMapper2DTest.cpp mitkImageGeneratorTest.cpp mitkBaseDataTest.cpp #mitkImageToItkTest.cpp mitkImportItkImageTest.cpp mitkGrabItkImageMemoryTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkInteractorTest.cpp #mitkITKThreadingTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp #mitkPipelineSmartPointerCorrectnessTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetTest.cpp mitkPointSetWriterTest.cpp mitkPointSetReaderTest.cpp mitkPointSetInteractorTest.cpp mitkPropertyTest.cpp mitkPropertyListTest.cpp #mitkRegistrationBaseTest.cpp #mitkSegmentationInterpolationTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkStateMachineTest.cpp ##mitkStateMachineContainerTest.cpp ## rewrite test, indirect since no longer exported Bug 14529 mitkStateTest.cpp mitkSurfaceTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeSlicedGeometryTest.cpp mitkTransitionTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp #mitkAbstractTransformGeometryTest.cpp mitkStepperTest.cpp itkTotalVariationDenoisingImageFilterTest.cpp mitkRenderingManagerTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp mitkExceptionTest.cpp mitkExtractSliceFilterTest.cpp mitkLogTest.cpp mitkImageDimensionConverterTest.cpp mitkLoggingAdapterTest.cpp mitkUIDGeneratorTest.cpp mitkShaderRepositoryTest.cpp mitkPlanePositionManagerTest.cpp mitkAffineTransformBaseTest.cpp mitkPropertyAliasesTest.cpp mitkPropertyDescriptionsTest.cpp mitkPropertyExtensionsTest.cpp mitkPropertyFiltersTest.cpp ) # test with image filename as an extra command line parameter set(MODULE_IMAGE_TESTS mitkImageTimeSelectorTest.cpp #only runs on images mitkImageAccessorTest.cpp #only runs on images - mitkDataNodeFactoryTest.cpp #runs on all types of data ) set(MODULE_SURFACE_TESTS mitkSurfaceVtkWriterTest.cpp #only runs on surfaces - mitkDataNodeFactoryTest.cpp #runs on all types of data ) # list of images for which the tests are run set(MODULE_TESTIMAGES US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd Png2D-bw.png ) set(MODULE_TESTSURFACES binary.stl ball.stl ) set(MODULE_CUSTOM_TESTS #mitkLabeledImageToSurfaceFilterTest.cpp #mitkExternalToolsTest.cpp mitkDataStorageTest.cpp mitkDataNodeTest.cpp mitkDicomSeriesReaderTest.cpp mitkDICOMLocaleTest.cpp mitkEventMapperTest.cpp mitkEventConfigTest.cpp mitkNodeDependentPointSetInteractorTest.cpp mitkStateMachineFactoryTest.cpp mitkPointSetLocaleTest.cpp mitkImageTest.cpp mitkImageWriterTest.cpp mitkImageVtkMapper2DTest.cpp mitkImageVtkMapper2DLevelWindowTest.cpp mitkImageVtkMapper2DOpacityTest.cpp mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp mitkImageVtkMapper2DColorTest.cpp mitkImageVtkMapper2DSwivelTest.cpp mitkImageVtkMapper2DTransferFunctionTest.cpp mitkIOUtilTest.cpp mitkSurfaceVtkMapper3DTest mitkSurfaceVtkMapper3DTexturedSphereTest.cpp mitkSurfaceGLMapper2DColorTest.cpp mitkSurfaceGLMapper2DOpacityTest.cpp mitkVolumeCalculatorTest.cpp mitkLevelWindowManagerTest.cpp mitkPointSetVtkMapper2DTest.cpp mitkPointSetVtkMapper2DImageTest.cpp mitkPointSetVtkMapper2DGlyphTypeTest.cpp ) set(MODULE_RESOURCE_FILES Interactions/AddAndRemovePoints.xml Interactions/globalConfig.xml Interactions/StatemachineTest.xml Interactions/StatemachineConfigTest.xml ) # Create an artificial module initializing class for # the usServiceListenerTest.cpp usFunctionGenerateExecutableInit(testdriver_init_file IDENTIFIER ${MODULE_NAME}TestDriver ) # Embed the resources set(testdriver_resources ) usFunctionEmbedResources(testdriver_resources EXECUTABLE_NAME ${MODULE_NAME}TestDriver ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Resources FILES ${MODULE_RESOURCE_FILES} ) set(TEST_CPP_FILES ${testdriver_init_file} ${testdriver_resources}) diff --git a/Core/Code/Testing/mitkDICOMLocaleTest.cpp b/Core/Code/Testing/mitkDICOMLocaleTest.cpp index 1ed7789357..5936f9ef91 100644 --- a/Core/Code/Testing/mitkDICOMLocaleTest.cpp +++ b/Core/Code/Testing/mitkDICOMLocaleTest.cpp @@ -1,131 +1,125 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /* This test is meant to reproduce the following error: - The machine or current user has a German locale. - This esp. means that stream IO expects the decimal separator as a comma: "," - DICOM files use a point "." as the decimal separator to be locale independent - The parser used by MITK (ITK's GDCM) seems to use the current locale instead of the "C" or "POSIX" locale - This leads to spacings (and probably other numbers) being trimmed/rounded, e.g. the correct spacing of 0.314 is read as 1.0 etc. */ -#include "mitkDataNodeFactory.h" #include "mitkStandardFileLocations.h" #include "mitkDicomSeriesReader.h" +#include "mitkIOUtil.h" #include "mitkTestingMacros.h" #include #include #include bool mitkDICOMLocaleTestChangeLocale(const std::string& locale) { try { MITK_TEST_OUTPUT(<< " ** Changing locale from " << setlocale(LC_ALL, NULL) << " to '" << locale << "'"); setlocale(LC_ALL, locale.c_str()); std::locale l( locale.c_str() ); std::cin.imbue(l); return true; } catch(...) { MITK_TEST_OUTPUT(<< "Could not activate locale " << locale); return false; } } void mitkDICOMLocaleTestWithReferenceImage(std::string filename) { - mitk::Image::Pointer image; - mitk::DataNodeFactory::Pointer factory = mitk::DataNodeFactory::New(); - factory->SetFileName( filename ); - factory->Update(); - MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file " << filename << " loaded"); - - mitk::DataNode::Pointer node = factory->GetOutput( 0 ); - image = dynamic_cast(node->GetData()); + mitk::DataNode::Pointer node = mitk::IOUtil::LoadDataNode(filename); + mitk::Image::Pointer image = dynamic_cast(node->GetData()); if(image.IsNull()) { MITK_TEST_FAILED_MSG(<< "File "<< filename << " is not an image - test will not be applied." ); return; } // note importance of minor differences in spacings: // DICOM has order y-spacing, x-spacing, while in MITK we assume x-spacing, y-spacing (both meant for 0 and 1 index in array) MITK_TEST_CONDITION_REQUIRED(mitk::Equal(image->GetGeometry()->GetSpacing()[0], 0.3141592), "correct x spacing? found " << image->GetGeometry()->GetSpacing()[0]); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(image->GetGeometry()->GetSpacing()[1], 0.3411592), "correct y spacing? found " << image->GetGeometry()->GetSpacing()[1]); } int mitkDICOMLocaleTest(int argc, char* argv[]) { MITK_TEST_BEGIN("DICOMLocaleTest"); MITK_TEST_CONDITION_REQUIRED(argc >= 2, "File to load has been specified on commandline"); MITK_TEST_OUTPUT(<< "Configuration: \n" << mitk::DicomSeriesReader::GetConfigurationString() ); std::string filename = argv[1]; // load a reference DICOM file with the "C" locale being set mitkDICOMLocaleTestChangeLocale("C"); mitkDICOMLocaleTestWithReferenceImage(filename); // load a reference DICOM file with German locales being set typedef std::list StringList; StringList alllocales; alllocales.push_back("de_DE"); alllocales.push_back("de_DE.utf8"); alllocales.push_back("de_DE.UTF8"); alllocales.push_back("de_DE@euro"); alllocales.push_back("German_Germany"); // supressing this test to be run on MacOS X // See bug #3894 #if defined (__APPLE__) || defined(MACOSX) alllocales.push_back("C"); #endif unsigned int numberOfTestedGermanLocales(0); for (StringList::iterator iter = alllocales.begin(); iter != alllocales.end(); ++iter) { if ( mitkDICOMLocaleTestChangeLocale(*iter) ) { ++numberOfTestedGermanLocales; mitkDICOMLocaleTestWithReferenceImage(filename); } } if(numberOfTestedGermanLocales == 0) { MITK_TEST_OUTPUT(<< "Warning: No German locale was found on the system."); } //MITK_TEST_CONDITION_REQUIRED( numberOfTestedGermanLocales > 0, "Verify that at least one German locale has been tested."); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkDataStorageTest.cpp b/Core/Code/Testing/mitkDataStorageTest.cpp index c3b9e9a14f..a9fc0c6644 100644 --- a/Core/Code/Testing/mitkDataStorageTest.cpp +++ b/Core/Code/Testing/mitkDataStorageTest.cpp @@ -1,875 +1,872 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include "mitkImage.h" #include "mitkSurface.h" #include "mitkStringProperty.h" #include "mitkColorProperty.h" #include "mitkGroupTagProperty.h" #include "mitkDataNode.h" #include "mitkReferenceCountWatcher.h" #include "mitkDataStorage.h" +#include "mitkFileReaderRegistry.h" #include "mitkStandaloneDataStorage.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateDimension.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateOr.h" #include "mitkNodePredicateSource.h" #include "mitkMessage.h" //#include "mitkPicFileReader.h" #include "mitkTestingMacros.h" -#include "mitkItkImageFileReader.h" void TestDataStorage(mitk::DataStorage* ds, std::string filename); namespace mitk { class TestStandaloneDataStorage: public StandaloneDataStorage { public: mitkClassMacro(TestStandaloneDataStorage, mitk::DataStorage); itkNewMacro(Self); std::map GetModifiedObserverTags() const {return m_NodeModifiedObserverTags;} std::map GetDeletedObserverTags() const { return m_NodeDeleteObserverTags; } protected: TestStandaloneDataStorage() {} }; } class DSEventReceiver // Helper class for event testing { public: const mitk::DataNode* m_NodeAdded; const mitk::DataNode* m_NodeRemoved; DSEventReceiver() : m_NodeAdded(NULL), m_NodeRemoved(NULL) { } void OnAdd(const mitk::DataNode* node) { m_NodeAdded = node; } void OnRemove(const mitk::DataNode* node) { m_NodeRemoved = node; } }; /// /// \brief a class for checking if the datastorage is really thread safe /// /// Therefore it listens to a node contained in the datastorage. when this node /// gets removed and deleted, this class gets informed by calling OnObjectDelete(). /// in OnObjectDelete() an empty node gets added. this must not cause a deadlock /// struct ItkDeleteEventListener { ItkDeleteEventListener( mitk::DataStorage* ds ) : m_Node(0), m_DataStorage(ds), m_DeleteObserverTag(0) { } void SetNode( mitk::DataNode* _Node ) { if(m_Node) return; m_Node = _Node; itk::MemberCommand::Pointer onObjectDelete = itk::MemberCommand::New(); onObjectDelete->SetCallbackFunction(this, &ItkDeleteEventListener::OnObjectDelete); m_DeleteObserverTag = m_Node->AddObserver(itk::DeleteEvent(), onObjectDelete); } void OnObjectDelete( const itk::Object* /*caller*/, const itk::EventObject & ) { mitk::DataNode::Pointer node = mitk::DataNode::New(); m_DataStorage->Add( node ); // SHOULD NOT CAUSE A DEADLOCK! m_DataStorage->Remove( node ); // tidy up: remove the empty node again m_Node = 0; } protected: mitk::DataNode* m_Node; mitk::DataStorage::Pointer m_DataStorage; unsigned int m_DeleteObserverTag; }; //## Documentation //## main testing method //## NOTE: the current Singleton implementation of DataTreeStorage will lead to crashes if a testcase fails //## and therefore mitk::DataStorage::ShutdownSingleton() is not called. int mitkDataStorageTest(int argc, char* argv[]) { MITK_TEST_BEGIN("DataStorageTest"); // muellerm: test observer tag remove mitk::TestStandaloneDataStorage::Pointer testDS = mitk::TestStandaloneDataStorage::New(); mitk::DataNode::Pointer n1 = mitk::DataNode::New(); testDS->Add(n1); MITK_TEST_CONDITION_REQUIRED( testDS->GetModifiedObserverTags().size()==1, "Testing if modified" " observer was added."); MITK_TEST_CONDITION_REQUIRED( testDS->GetDeletedObserverTags().size()==1, "Testing if delete" " observer was added."); testDS->Remove(n1); MITK_TEST_CONDITION_REQUIRED( testDS->GetModifiedObserverTags().size()==0, "Testing if modified" " observer was removed."); MITK_TEST_CONDITION_REQUIRED( testDS->GetDeletedObserverTags().size()==0, "Testing if delete" " observer was removed."); /* Create StandaloneDataStorage */ MITK_TEST_OUTPUT( << "Create StandaloneDataStorage : "); mitk::StandaloneDataStorage::Pointer sds; try { sds = mitk::StandaloneDataStorage::New(); MITK_TEST_CONDITION_REQUIRED(sds.IsNotNull(), "Testing Instatiation"); } catch (...) { MITK_TEST_FAILED_MSG( << "Exception during creation of StandaloneDataStorage"); } MITK_TEST_OUTPUT( << "Testing StandaloneDataStorage: "); MITK_TEST_CONDITION_REQUIRED(argc>1, "Testing correct test invocation"); TestDataStorage(sds,argv[1]); // TODO: Add specific StandaloneDataStorage Tests here sds = NULL; MITK_TEST_END(); } //##Documentation //## @brief Test for the DataStorage class and its associated classes (e.g. the predicate classes) //## This method will be called once for each subclass of DataStorage void TestDataStorage( mitk::DataStorage* ds, std::string filename ) { /* DataStorage valid? */ MITK_TEST_CONDITION_REQUIRED(ds != NULL, "DataStorage valid?"); // Take the ItkImageFile Reader for the .nrrd data format. // (was previously pic which is now deprecated format) - mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); - reader -> SetFileName(filename.c_str()); - reader -> Update(); - mitk::Image::Pointer image = reader->GetOutput(); + mitk::Image::Pointer image = mitk::FileReaderRegistry::Read(filename.c_str()); // create some DataNodes to fill the ds mitk::DataNode::Pointer n1 = mitk::DataNode::New(); // node with image and name property // mitk::Image::Pointer image = mitk::Image::New(); // unsigned int imageDimensions[] = { 10, 10, 10, 10 }; // mitk::PixelType pt(typeid(int)); // image->Initialize( pt, 4, imageDimensions ); n1->SetData(image); n1->SetProperty("name", mitk::StringProperty::New("Node 1 - Image Node")); mitk::DataStorage::SetOfObjects::Pointer parents1 = mitk::DataStorage::SetOfObjects::New(); mitk::DataNode::Pointer n2 = mitk::DataNode::New(); // node with surface and name and color properties mitk::Surface::Pointer surface = mitk::Surface::New(); n2->SetData(surface); n2->SetProperty("name", mitk::StringProperty::New("Node 2 - Surface Node")); mitk::Color color; color.Set(1.0f, 1.0f, 0.0f); n2->SetColor(color); n2->SetProperty("Resection Proposal 1", mitk::GroupTagProperty::New()); mitk::DataStorage::SetOfObjects::Pointer parents2 = mitk::DataStorage::SetOfObjects::New(); parents2->InsertElement(0, n1); // n1 (image node) is source of n2 (surface node) mitk::DataNode::Pointer n3 = mitk::DataNode::New(); // node without data but with name property n3->SetProperty("name", mitk::StringProperty::New("Node 3 - Empty Node")); n3->SetProperty("Resection Proposal 1", mitk::GroupTagProperty::New()); n3->SetProperty("Resection Proposal 2", mitk::GroupTagProperty::New()); mitk::DataStorage::SetOfObjects::Pointer parents3 = mitk::DataStorage::SetOfObjects::New(); parents3->InsertElement(0, n2); // n2 is source of n3 mitk::DataNode::Pointer n4 = mitk::DataNode::New(); // node without data but with color property n4->SetColor(color); n4->SetProperty("Resection Proposal 2", mitk::GroupTagProperty::New()); mitk::DataStorage::SetOfObjects::Pointer parents4 = mitk::DataStorage::SetOfObjects::New(); parents4->InsertElement(0, n2); parents4->InsertElement(1, n3); // n2 and n3 are sources of n4 mitk::DataNode::Pointer n5 = mitk::DataNode::New(); // extra node n5->SetProperty("name", mitk::StringProperty::New("Node 5")); try /* adding objects */ { /* Add an object */ ds->Add(n1, parents1); MITK_TEST_CONDITION_REQUIRED((ds->GetAll()->Size() == 1) && (ds->GetAll()->GetElement(0) == n1), "Testing Adding a new object"); /* Check exception on adding the same object again */ MITK_TEST_OUTPUT( << "Check exception on adding the same object again: "); MITK_TEST_FOR_EXCEPTION(..., ds->Add(n1, parents1)); MITK_TEST_CONDITION(ds->GetAll()->Size() == 1, "Test if object count is correct after exception"); /* Add an object that has a source object */ ds->Add(n2, parents2); MITK_TEST_CONDITION_REQUIRED(ds->GetAll()->Size() == 2, "Testing Adding an object that has a source object"); /* Add some more objects needed for further tests */ ds->Add(n3, parents3); // n3 object that has name property and one parent ds->Add(n4, parents4); // n4 object that has color property ds->Add(n5); // n5 has no parents MITK_TEST_CONDITION_REQUIRED(ds->GetAll()->Size() == 5, "Adding some more objects needed for further tests"); } catch(...) { MITK_TEST_FAILED_MSG( << "Exeption during object creation"); } try /* object retrieval methods */ { /* Requesting all Objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetAll(); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (stlAll.size() == 5) // check if all tree nodes are in resultset && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n5) != stlAll.end()), "Testing GetAll()" ); } /* Requesting a named object */ { mitk::NodePredicateProperty::Pointer predicate(mitk::NodePredicateProperty::New("name", mitk::StringProperty::New("Node 2 - Surface Node"))); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n2), "Requesting a named object"); } /* Requesting objects of specific data type */ { mitk::NodePredicateDataType::Pointer predicate(mitk::NodePredicateDataType::New("Image")); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n1), "Requesting objects of specific data type") } /* Requesting objects of specific dimension */ { mitk::NodePredicateDimension::Pointer predicate(mitk::NodePredicateDimension::New( 4 )); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n1), "Requesting objects of specific dimension") } /* Requesting objects with specific data object */ { mitk::NodePredicateData::Pointer predicate(mitk::NodePredicateData::New(image)); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n1), "Requesting objects with specific data object") } /* Requesting objects with NULL data */ { mitk::NodePredicateData::Pointer predicate(mitk::NodePredicateData::New(NULL)); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION( (all->Size() == 3) && (std::find(all->begin(), all->end(), n3) != all->end()) && (std::find(all->begin(), all->end(), n4) != all->end()) && (std::find(all->begin(), all->end(), n5) != all->end()) , "Requesting objects with NULL data"); } /* Requesting objects that meet a conjunction criteria */ { mitk::NodePredicateDataType::Pointer p1 = mitk::NodePredicateDataType::New("Surface"); mitk::NodePredicateProperty::Pointer p2 = mitk::NodePredicateProperty::New("color", mitk::ColorProperty::New(color)); mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New(); predicate->AddPredicate(p1); predicate->AddPredicate(p2); // objects must be of datatype "Surface" and have red color (= n2) const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n2), "Requesting objects that meet a conjunction criteria"); } /* Requesting objects that meet a disjunction criteria */ { mitk::NodePredicateDataType::Pointer p1(mitk::NodePredicateDataType::New("Image")); mitk::NodePredicateProperty::Pointer p2(mitk::NodePredicateProperty::New("color", mitk::ColorProperty::New(color))); mitk::NodePredicateOr::Pointer predicate = mitk::NodePredicateOr::New(); predicate->AddPredicate(p1); predicate->AddPredicate(p2); // objects must be of datatype "Surface" or have red color (= n1, n2, n4) const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION( (all->Size() == 3) && (std::find(all->begin(), all->end(), n1) != all->end()) && (std::find(all->begin(), all->end(), n2) != all->end()) && (std::find(all->begin(), all->end(), n4) != all->end()), "Requesting objects that meet a disjunction criteria"); } /* Requesting objects that do not meet a criteria */ { mitk::ColorProperty::Pointer cp = mitk::ColorProperty::New(color); mitk::NodePredicateProperty::Pointer proppred(mitk::NodePredicateProperty::New("color", cp)); mitk::NodePredicateNot::Pointer predicate(mitk::NodePredicateNot::New(proppred)); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 3) // check if correct objects are in resultset && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n5) != stlAll.end()), "Requesting objects that do not meet a criteria"); } /* Requesting *direct* source objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n3, NULL, true); // Get direct parents of n3 (=n2) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 1) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()), "Requesting *direct* source objects"); } /* Requesting *all* source objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n3, NULL, false); // Get all parents of n3 (= n1 + n2) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 2) && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()), "Requesting *all* source objects"); // check if n1 and n2 are the resultset } /* Requesting *all* sources of object with multiple parents */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, NULL, false); // Get all parents of n4 (= n1 + n2 + n3) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 3) && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) // check if n1 and n2 and n3 are the resultset , "Requesting *all* sources of object with multiple parents"); } /* Requesting *direct* derived objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n1, NULL, true); // Get direct childs of n1 (=n2) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 1) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end())// check if n1 is the resultset , "Requesting *direct* derived objects"); } ///* Requesting *direct* derived objects with multiple parents/derivations */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n2, NULL, true); // Get direct childs of n2 (=n3 + n4) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 2) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) // check if n3 is the resultset && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()) // check if n4 is the resultset , "Requesting *direct* derived objects with multiple parents/derivations"); } //* Requesting *all* derived objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n1, NULL, false); // Get all childs of n1 (=n2, n3, n4) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 3) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()) , "Requesting *all* derived objects"); } /* Checking for circular source relationships */ { parents1->InsertElement(0, n4); // make n1 derived from n4 (which is derived from n2, which is derived from n1) const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, NULL, false); // Get all parents of n4 (= n1 + n2 + n3, not n4 itself and not multiple versions of the nodes!) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 3) && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) // check if n1 and n2 and n3 are the resultset , "Checking for circular source relationships"); } ///* Checking for circular derivation relationships can not be performed, because the internal derivations datastructure // can not be accessed from the outside. (Therefore it should not be possible to create these circular relations */ //* Checking GroupTagProperty */ { mitk::GroupTagProperty::Pointer tp = mitk::GroupTagProperty::New(); mitk::NodePredicateProperty::Pointer pred(mitk::NodePredicateProperty::New("Resection Proposal 1", tp)); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(pred); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 2) // check if n2 and n3 are in resultset && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) , "Checking GroupTagProperty"); } /* Checking GroupTagProperty 2 */ { mitk::GroupTagProperty::Pointer tp = mitk::GroupTagProperty::New(); mitk::NodePredicateProperty::Pointer pred(mitk::NodePredicateProperty::New("Resection Proposal 2", tp)); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(pred); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 2) // check if n3 and n4 are in resultset && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()) , "Checking GroupTagProperty 2"); } /* Checking direct sources with condition */ { mitk::NodePredicateDataType::Pointer pred = mitk::NodePredicateDataType::New("Surface"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, pred, true); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 1) // check if n2 is in resultset && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) , "checking direct sources with condition"); } /* Checking all sources with condition */ { mitk::NodePredicateDataType::Pointer pred = mitk::NodePredicateDataType::New("Image"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, pred, false); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 1) // check if n1 is in resultset && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) , "Checking all sources with condition"); } /* Checking all sources with condition with empty resultset */ { mitk::NodePredicateDataType::Pointer pred = mitk::NodePredicateDataType::New("VesselTree"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, pred, false); MITK_TEST_CONDITION(all->Size() == 0 , "Checking all sources with condition with empty resultset"); // check if resultset is empty } /* Checking direct derivations with condition */ { mitk::NodePredicateProperty::Pointer pred = mitk::NodePredicateProperty::New("color"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n1, pred, true); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 1) // check if n2 is in resultset && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) , "Checking direct derivations with condition"); } /* Checking all derivations with condition */ { mitk::NodePredicateProperty::Pointer pred = mitk::NodePredicateProperty::New("color"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n1, pred, false); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 2) // check if n2 and n4 are in resultset && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()) , "Checking direct derivations with condition"); } /* Checking named node method */ MITK_TEST_CONDITION(ds->GetNamedNode("Node 2 - Surface Node") == n2, "Checking named node method"); MITK_TEST_CONDITION(ds->GetNamedNode(std::string("Node 2 - Surface Node")) == n2, "Checking named node(std::string) method"); /* Checking named node method with wrong name */ MITK_TEST_CONDITION(ds->GetNamedNode("This name does not exist") == NULL, "Checking named node method with wrong name"); /* Checking named object method */ MITK_TEST_CONDITION(ds->GetNamedObject("Node 1 - Image Node") == image, "Checking named object method"); MITK_TEST_CONDITION(ds->GetNamedObject(std::string("Node 1 - Image Node")) == image, "Checking named object(std::string) method"); /* Checking named object method with wrong DataType */ MITK_TEST_CONDITION(ds->GetNamedObject("Node 1 - Image Node") == NULL, "Checking named object method with wrong DataType"); /* Checking named object method with wrong name */ MITK_TEST_CONDITION(ds->GetNamedObject("This name does not exist") == NULL, "Checking named object method with wrong name"); /* Checking GetNamedDerivedNode with valid name and direct derivation only */ MITK_TEST_CONDITION(ds->GetNamedDerivedNode("Node 2 - Surface Node", n1, true) == n2, "Checking GetNamedDerivedNode with valid name & direct derivation only"); /* Checking GetNamedDerivedNode with invalid Name and direct derivation only */ MITK_TEST_CONDITION(ds->GetNamedDerivedNode("wrong name", n1, true) == NULL, "Checking GetNamedDerivedNode with invalid name & direct derivation only"); /* Checking GetNamedDerivedNode with invalid Name and direct derivation only */ MITK_TEST_CONDITION(ds->GetNamedDerivedNode("Node 3 - Empty Node", n1, false) == n3, "Checking GetNamedDerivedNode with invalid name & direct derivation only"); /* Checking GetNamedDerivedNode with valid Name but direct derivation only */ MITK_TEST_CONDITION(ds->GetNamedDerivedNode("Node 3 - Empty Node", n1, true) == NULL, "Checking GetNamedDerivedNode with valid Name but direct derivation only"); /* Checking GetNode with valid predicate */ { mitk::NodePredicateDataType::Pointer p(mitk::NodePredicateDataType::New("Image")); MITK_TEST_CONDITION(ds->GetNode(p) == n1, "Checking GetNode with valid predicate"); } /* Checking GetNode with invalid predicate */ { mitk::NodePredicateDataType::Pointer p(mitk::NodePredicateDataType::New("PointSet")); MITK_TEST_CONDITION(ds->GetNode(p) == NULL, "Checking GetNode with invalid predicate"); } } // object retrieval methods catch(...) { MITK_TEST_FAILED_MSG( << "Exeption during object retrieval (GetXXX() Methods)"); } try /* object removal methods */ { /* Checking removal of a node without relations */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); int refCountbeforeDS = watcher->GetReferenceCount(); ds->Add(extra); MITK_TEST_CONDITION(ds->GetNamedNode("extra") == extra, "Adding extra node"); ds->Remove(extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == NULL) && (refCountbeforeDS == watcher->GetReferenceCount()) , "Checking removal of a node without relations"); extra = NULL; } /* Checking removal of a node with a parent */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); int refCountbeforeDS = watcher->GetReferenceCount(); ds->Add(extra, n1); // n1 is parent of extra MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == extra) && (ds->GetDerivations(n1)->Size() == 2) // n2 and extra should be derived from n1 , "Adding extra node"); ds->Remove(extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == NULL) && (refCountbeforeDS == watcher->GetReferenceCount()) && (ds->GetDerivations(n1)->Size() == 1) , "Checking removal of a node with a parent"); extra = NULL; } /* Checking removal of a node with two parents */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); int refCountbeforeDS = watcher->GetReferenceCount(); mitk::DataStorage::SetOfObjects::Pointer p = mitk::DataStorage::SetOfObjects::New(); p->push_back(n1); p->push_back(n2); ds->Add(extra, p); // n1 and n2 are parents of extra MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == extra) && (ds->GetDerivations(n1)->Size() == 2) // n2 and extra should be derived from n1 && (ds->GetDerivations(n2)->Size() == 3) , "add extra node"); ds->Remove(extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == NULL) && (refCountbeforeDS == watcher->GetReferenceCount()) && (ds->GetDerivations(n1)->Size() == 1) // after remove, only n2 should be derived from n1 && (ds->GetDerivations(n2)->Size() == 2) // after remove, only n3 and n4 should be derived from n2 , "Checking removal of a node with two parents"); extra = NULL; } /* Checking removal of a node with two derived nodes */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); int refCountbeforeDS = watcher->GetReferenceCount(); ds->Add(extra); mitk::DataNode::Pointer d1 = mitk::DataNode::New(); d1->SetProperty("name", mitk::StringProperty::New("d1")); ds->Add(d1, extra); mitk::DataNode::Pointer d2 = mitk::DataNode::New(); d2->SetProperty("name", mitk::StringProperty::New("d2")); ds->Add(d2, extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == extra) && (ds->GetNamedNode("d1") == d1) && (ds->GetNamedNode("d2") == d2) && (ds->GetSources(d1)->Size() == 1) // extra should be source of d1 && (ds->GetSources(d2)->Size() == 1) // extra should be source of d2 && (ds->GetDerivations(extra)->Size() == 2) // d1 and d2 should be derived from extra , "add extra node"); ds->Remove(extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == NULL) && (ds->GetNamedNode("d1") == d1) && (ds->GetNamedNode("d2") == d2) && (refCountbeforeDS == watcher->GetReferenceCount()) && (ds->GetSources(d1)->Size() == 0) // after remove, d1 should not have a source anymore && (ds->GetSources(d2)->Size() == 0) // after remove, d2 should not have a source anymore , "Checking removal of a node with two derived nodes"); extra = NULL; } /* Checking removal of a node with two parents and two derived nodes */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); mitk::ReferenceCountWatcher::Pointer n1watcher = new mitk::ReferenceCountWatcher(n1); int refCountbeforeDS = watcher->GetReferenceCount(); mitk::DataStorage::SetOfObjects::Pointer p = mitk::DataStorage::SetOfObjects::New(); p->push_back(n1); p->push_back(n2); ds->Add(extra, p); // n1 and n2 are parents of extra mitk::DataNode::Pointer d1 = mitk::DataNode::New(); d1->SetProperty("name", mitk::StringProperty::New("d1x")); ds->Add(d1, extra); mitk::DataNode::Pointer d2 = mitk::DataNode::New(); d2->SetProperty("name", mitk::StringProperty::New("d2x")); ds->Add(d2, extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == extra) && (ds->GetNamedNode("d1x") == d1) && (ds->GetNamedNode("d2x") == d2) && (ds->GetSources(d1)->Size() == 1) // extra should be source of d1 && (ds->GetSources(d2)->Size() == 1) // extra should be source of d2 && (ds->GetDerivations(n1)->Size() == 2) // n2 and extra should be derived from n1 && (ds->GetDerivations(n2)->Size() == 3) // n3, n4 and extra should be derived from n2 && (ds->GetDerivations(extra)->Size() == 2) // d1 and d2 should be derived from extra , "add extra node"); ds->Remove(extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == NULL) && (ds->GetNamedNode("d1x") == d1) && (ds->GetNamedNode("d2x") == d2) && (refCountbeforeDS == watcher->GetReferenceCount()) && (ds->GetDerivations(n1)->Size() == 1) // after remove, only n2 should be derived from n1 && (ds->GetDerivations(n2)->Size() == 2) // after remove, only n3 and n4 should be derived from n2 && (ds->GetSources(d1)->Size() == 0) // after remove, d1 should not have a source anymore && (ds->GetSources(d2)->Size() == 0) // after remove, d2 should not have a source anymore , "Checking removal of a node with two parents and two derived nodes"); extra = NULL; } } catch(...) { MITK_TEST_FAILED_MSG( << "Exeption during object removal methods"); } /* Checking for node is it's own parent exception */ { MITK_TEST_FOR_EXCEPTION_BEGIN(...); mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::DataStorage::SetOfObjects::Pointer p = mitk::DataStorage::SetOfObjects::New(); p->push_back(n1); p->push_back(extra); // extra is parent of extra!!! ds->Add(extra, p); MITK_TEST_FOR_EXCEPTION_END(...); } /* Checking reference count of node after add and remove */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::DataStorage::SetOfObjects::Pointer p = mitk::DataStorage::SetOfObjects::New(); p->push_back(n1); p->push_back(n3); ds->Add(extra, p); extra = NULL; ds->Remove(ds->GetNamedNode("extra")); MITK_TEST_CONDITION(watcher->GetReferenceCount() == 0, "Checking reference count of node after add and remove"); } /* Checking removal of a node with two derived nodes [ dataStorage->GetDerivations( rootNode )] see bug #3426 */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); ds->Add(extra); mitk::DataNode::Pointer d1y = mitk::DataNode::New(); d1y->SetProperty("name", mitk::StringProperty::New("d1y")); mitk::ReferenceCountWatcher::Pointer watcherD1y = new mitk::ReferenceCountWatcher(d1y); int refCountbeforeDS = watcherD1y->GetReferenceCount(); ds->Add(d1y, extra); mitk::DataNode::Pointer d2y = mitk::DataNode::New(); d2y->SetProperty("name", mitk::StringProperty::New("d2y")); ds->Add(d2y, extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == extra) && (ds->GetNamedNode("d1y") == d1y) && (ds->GetNamedNode("d2y") == d2y) && (ds->GetSources(d1y)->Size() == 1) // extra should be source of d1y && (ds->GetSources(d2y)->Size() == 1) // extra should be source of d2y && (ds->GetDerivations(extra)->Size() == 2) // d1y and d2y should be derived from extra , "add extra node"); ds->Remove(ds->GetDerivations( extra)); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == extra) && (ds->GetNamedNode("d1y") == NULL) // d1y should be NULL now && (ds->GetNamedNode("d2y") == NULL) // d2y should be NULL now && (refCountbeforeDS == watcherD1y->GetReferenceCount()) , "Checking removal of subset of two derived nodes from one parent node"); ds->Remove(extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == NULL) , "Checking removal of a parent node"); extra = NULL; } /* Checking GetGrouptags() */ { const std::set groupTags = ds->GetGroupTags(); MITK_TEST_CONDITION( (groupTags.size() == 2) && (std::find(groupTags.begin(), groupTags.end(), "Resection Proposal 1") != groupTags.end()) && (std::find(groupTags.begin(), groupTags.end(), "Resection Proposal 2") != groupTags.end()) , "Checking GetGrouptags()"); } /* Checking Event handling */ DSEventReceiver listener; try { ds->AddNodeEvent += mitk::MessageDelegate1(&listener, &DSEventReceiver::OnAdd); ds->RemoveNodeEvent += mitk::MessageDelegate1(&listener, &DSEventReceiver::OnRemove); mitk::DataNode::Pointer extra = mitk::DataNode::New(); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); ds->Add(extra); MITK_TEST_CONDITION(listener.m_NodeAdded == extra.GetPointer(), "Checking AddEvent"); ds->Remove(extra); MITK_TEST_CONDITION(listener.m_NodeRemoved == extra.GetPointer(), "Checking RemoveEvent"); /* RemoveListener */ ds->AddNodeEvent -= mitk::MessageDelegate1(&listener, &DSEventReceiver::OnAdd); ds->RemoveNodeEvent -= mitk::MessageDelegate1(&listener, &DSEventReceiver::OnRemove); listener.m_NodeAdded = NULL; listener.m_NodeRemoved = NULL; ds->Add(extra); ds->Remove(extra); MITK_TEST_CONDITION((listener.m_NodeRemoved == NULL) && (listener.m_NodeAdded == NULL), "Checking RemoveListener"); std::cout << "Pointer handling after event handling: " << std::flush; extra = NULL; // delete reference to the node. its memory should be freed now MITK_TEST_CONDITION(watcher->GetReferenceCount() == 0, "Pointer handling after event handling"); } catch(...) { /* cleanup */ ds->AddNodeEvent -= mitk::MessageDelegate1(&listener, &DSEventReceiver::OnAdd); ds->RemoveNodeEvent -= mitk::MessageDelegate1(&listener, &DSEventReceiver::OnRemove); MITK_TEST_FAILED_MSG( << "Exception during object removal methods"); } //Checking ComputeBoundingGeometry3D method*/ const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetAll(); mitk::TimeSlicedGeometry::Pointer geometry = ds->ComputeBoundingGeometry3D(); MITK_TEST_CONDITION(geometry->GetTimeSteps()==4, "Test for number or time steps with ComputeBoundingGeometry()"); mitk::TimeBounds timebounds = geometry->GetTimeBounds(); MITK_TEST_CONDITION((timebounds[0]==0)&&(timebounds[1]==4),"Test for timebounds with ComputeBoundingGeometry()"); for (unsigned int i=0; iGetTimeSteps(); i++) { mitk::Geometry3D::Pointer subGeometry = geometry->GetGeometry3D(i); mitk::TimeBounds bounds = subGeometry->GetTimeBounds(); MITK_TEST_CONDITION((bounds[0]==i)&&(bounds[1]==i+1),"Test for timebounds of geometry at different time steps with ComputeBoundingGeometry()"); } geometry = ds->ComputeBoundingGeometry3D(all); MITK_TEST_CONDITION(geometry->GetTimeSteps()==4, "Test for number or time steps with ComputeBoundingGeometry(allNodes)"); timebounds = geometry->GetTimeBounds(); MITK_TEST_CONDITION((timebounds[0]==0)&&(timebounds[1]==4),"Test for timebounds with ComputeBoundingGeometry(allNodes)"); for (unsigned int i=0; iGetTimeSteps(); i++) { mitk::Geometry3D::Pointer subGeometry = geometry->GetGeometry3D(i); mitk::TimeBounds bounds = subGeometry->GetTimeBounds(); MITK_TEST_CONDITION((bounds[0]==i)&&(bounds[1]==i+1),"Test for timebounds of geometry at different time steps with ComputeBoundingGeometry()"); } // test for thread safety of DataStorage try { mitk::StandaloneDataStorage::Pointer standaloneDataStorage = mitk::StandaloneDataStorage::New(); ItkDeleteEventListener listener( standaloneDataStorage ); { mitk::DataNode::Pointer emptyNode = mitk::DataNode::New(); mitk::DataNode* pEmptyNode = emptyNode; listener.SetNode( emptyNode ); standaloneDataStorage->Add( emptyNode ); emptyNode = 0; // emptyNode is still alive because standaloneDataStorage // owns it standaloneDataStorage->Remove( pEmptyNode ); // this should not freeze the whole thing } } catch(...) { MITK_TEST_FAILED_MSG( << "Exception during testing DataStorage thread safe"); } /* Clear DataStorage */ ds->Remove(ds->GetAll()); MITK_TEST_CONDITION(ds->GetAll()->Size() == 0, "Checking Clear DataStorage"); } diff --git a/Core/Code/Testing/mitkExtractSliceFilterTest.cpp b/Core/Code/Testing/mitkExtractSliceFilterTest.cpp index a2f5084a2e..3f1aa08ca3 100644 --- a/Core/Code/Testing/mitkExtractSliceFilterTest.cpp +++ b/Core/Code/Testing/mitkExtractSliceFilterTest.cpp @@ -1,1162 +1,1151 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include -#include +#include #include #include #include #include #include -#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //use this to create the test volume on the fly #define CREATE_VOLUME //use this to save the created volume //#define SAVE_VOLUME //use this to calculate the error from the sphere mathematical model to our pixel based one //#define CALC_TESTFAILURE_DEVIATION //use this to render an oblique slice through a specified image //#define SHOW_SLICE_IN_RENDER_WINDOW //use this to have infos printed in mbilog //#define EXTRACTOR_DEBUG /*these are the deviations calculated by the function CalcTestFailureDeviation (see for details)*/ #define Testfailure_Deviation_Mean_128 0.853842 #define Testfailure_Deviation_Volume_128 0.145184 #define Testfailure_Deviation_Diameter_128 1.5625 #define Testfailure_Deviation_Mean_256 0.397693 #define Testfailure_Deviation_Volume_256 0.0141357 #define Testfailure_Deviation_Diameter_256 0.78125 #define Testfailure_Deviation_Mean_512 0.205277 #define Testfailure_Deviation_Volume_512 0.01993 #define Testfailure_Deviation_Diameter_512 0.390625 class mitkExtractSliceFilterTestClass{ public: static void TestSlice(mitk::PlaneGeometry* planeGeometry, std::string testname) { TestPlane = planeGeometry; TestName = testname; float centerCoordValue = TestvolumeSize / 2.0; float center[3] = {centerCoordValue, centerCoordValue, centerCoordValue}; mitk::Point3D centerIndex(center); double radius = TestvolumeSize / 4.0; if(TestPlane->Distance(centerIndex) >= radius ) return;//outside sphere //feed ExtractSliceFilter mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(); slicer->SetInput(TestVolume); slicer->SetWorldGeometry(TestPlane); slicer->Update(); MITK_TEST_CONDITION_REQUIRED(slicer->GetOutput() != NULL, "Extractor returned a slice"); mitk::Image::Pointer reslicedImage = slicer->GetOutput(); AccessFixedDimensionByItk(reslicedImage, TestSphereRadiusByItk, 2); AccessFixedDimensionByItk(reslicedImage, TestSphereAreaByItk, 2); /* double devArea, devDiameter; if(TestvolumeSize == 128.0){ devArea = Testfailure_Deviation_Volume_128; devDiameter = Testfailure_Deviation_Diameter_128; } else if(TestvolumeSize == 256.0){devArea = Testfailure_Deviation_Volume_256; devDiameter = Testfailure_Deviation_Diameter_256;} else if (TestvolumeSize == 512.0){devArea = Testfailure_Deviation_Volume_512; devDiameter = Testfailure_Deviation_Diameter_512;} else{devArea = Testfailure_Deviation_Volume_128; devDiameter = Testfailure_Deviation_Diameter_128;} */ std::string areatestName = TestName.append(" area"); std::string diametertestName = TestName.append(" testing diameter"); //TODO think about the deviation, 1% makes no sense at all MITK_TEST_CONDITION(std::abs(100 - testResults.percentageAreaCalcToPixel) < 1, areatestName ); MITK_TEST_CONDITION(std::abs(100 - testResults.percentageRadiusToPixel) < 1, diametertestName ); #ifdef EXTRACTOR_DEBUG MITK_INFO << TestName << " >>> " << "planeDistanceToSphereCenter: " << testResults.planeDistanceToSphereCenter; MITK_INFO << "area in pixels: " << testResults.areaInPixel << " <-> area in mm: " << testResults.areaCalculated << " = " << testResults.percentageAreaCalcToPixel << "%"; MITK_INFO << "calculated diameter: " << testResults.diameterCalculated << " <-> diameter in mm: " << testResults.diameterInMM << " <-> diameter in pixel: " << testResults.diameterInPixel << " = " << testResults.percentageRadiusToPixel << "%"; #endif } /* * get the radius of the slice of a sphere based on pixel distance from edge to edge of the circle. */ template static void TestSphereRadiusByItk (itk::Image* inputImage) { typedef itk::Image InputImageType; //set the index to the middle of the image's edge at x and y axis typename InputImageType::IndexType currentIndexX; currentIndexX[0] = (int)(TestvolumeSize / 2.0); currentIndexX[1] = 0; typename InputImageType::IndexType currentIndexY; currentIndexY[0] = 0; currentIndexY[1] = (int)(TestvolumeSize / 2.0); //remember the last pixel value double lastValueX = inputImage->GetPixel(currentIndexX); double lastValueY = inputImage->GetPixel(currentIndexY); //storage for the index marks std::vector indicesX; std::vector indicesY; /*Get four indices on the edge of the circle*/ while(currentIndexX[1] < TestvolumeSize && currentIndexX[0] < TestvolumeSize) { //move x direction currentIndexX[1] += 1; //move y direction currentIndexY[0] += 1; if(inputImage->GetPixel(currentIndexX) > lastValueX) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexX[0]; markIndex[1] = currentIndexX[1]; indicesX.push_back(markIndex); } else if( inputImage->GetPixel(currentIndexX) < lastValueX) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexX[0]; markIndex[1] = currentIndexX[1] - 1;//value inside the sphere indicesX.push_back(markIndex); } if(inputImage->GetPixel(currentIndexY) > lastValueY) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexY[0]; markIndex[1] = currentIndexY[1]; indicesY.push_back(markIndex); } else if( inputImage->GetPixel(currentIndexY) < lastValueY) { //mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexY[0]; markIndex[1] = currentIndexY[1] - 1;//value inside the sphere indicesY.push_back(markIndex); } //found both marks? if(indicesX.size() == 2 && indicesY.size() == 2) break; //the new 'last' values lastValueX = inputImage->GetPixel(currentIndexX); lastValueY = inputImage->GetPixel(currentIndexY); } /* *If we are here we found the four marks on the edge of the circle. *For the case our plane is rotated and shifted, we have to calculate the center of the circle, *else the center is the intersection of both straight lines between the marks. *When we have the center, the diameter of the circle will be checked to the reference value(math!). */ //each distance from the first mark of each direction to the center of the straight line between the marks double distanceToCenterX = std::abs(indicesX[0][1] - indicesX[1][1]) / 2.0; //double distanceToCenterY = std::abs(indicesY[0][0] - indicesY[1][0]) / 2.0; //the center of the straight lines typename InputImageType::IndexType centerX; //typename InputImageType::IndexType centerY; centerX[0] = indicesX[0][0]; centerX[1] = indicesX[0][1] + distanceToCenterX; //TODO think about implicit cast to int. this is not the real center of the image, which could be between two pixels //centerY[0] = indicesY[0][0] + distanceToCenterY; //centerY[1] = inidcesY[0][1]; typename InputImageType::IndexType currentIndex(centerX); lastValueX = inputImage->GetPixel(currentIndex); long sumpixels = 0; std::vector diameterIndices; //move up while(currentIndex[1] < TestvolumeSize) { currentIndex[1] += 1; if( inputImage->GetPixel(currentIndex) != lastValueX) { typename InputImageType::IndexType markIndex; markIndex[0] = currentIndex[0]; markIndex[1] = currentIndex[1] - 1; diameterIndices.push_back(markIndex); break; } sumpixels++; lastValueX = inputImage->GetPixel(currentIndex); } currentIndex[1] -= sumpixels; //move back to center to go in the other direction lastValueX = inputImage->GetPixel(currentIndex); //move down while(currentIndex[1] >= 0) { currentIndex[1] -= 1; if( inputImage->GetPixel(currentIndex) != lastValueX) { typename InputImageType::IndexType markIndex; markIndex[0] = currentIndex[0]; markIndex[1] = currentIndex[1];//outside sphere because we want to calculate the distance from edge to edge diameterIndices.push_back(markIndex); break; } sumpixels++; lastValueX = inputImage->GetPixel(currentIndex); } /* *Now sumpixels should be the apromximate diameter of the circle. This is checked with the calculated diameter from the plane transformation(math). */ mitk::Point3D volumeCenter; volumeCenter[0] = volumeCenter[1] = volumeCenter[2] = TestvolumeSize / 2.0; double planeDistanceToSphereCenter = TestPlane->Distance(volumeCenter); double sphereRadius = TestvolumeSize/4.0; //calculate the radius of the circle cut from the sphere by the plane double diameter = 2.0 * std::sqrt(std::pow(sphereRadius, 2) - std::pow( planeDistanceToSphereCenter , 2)); double percentageRadiusToPixel = 100 / diameter * sumpixels; /* *calculate the radius in mm by the both marks of the center line by using the world coordinates */ //get the points as 3D coordinates mitk::Vector3D diameterPointRight, diameterPointLeft; diameterPointRight[2] = diameterPointLeft[2] = 0.0; diameterPointLeft[0] = diameterIndices[0][0]; diameterPointLeft[1] = diameterIndices[0][1]; diameterPointRight[0] = diameterIndices[1][0]; diameterPointRight[1] = diameterIndices[1][1]; //transform to worldcoordinates TestVolume->GetGeometry()->IndexToWorld(diameterPointLeft, diameterPointLeft); TestVolume->GetGeometry()->IndexToWorld(diameterPointRight, diameterPointRight); //euklidian distance double diameterInMM = ( (diameterPointLeft * -1.0) + diameterPointRight).GetNorm(); testResults.diameterInMM = diameterInMM; testResults.diameterCalculated = diameter; testResults.diameterInPixel = sumpixels; testResults.percentageRadiusToPixel = percentageRadiusToPixel; testResults.planeDistanceToSphereCenter = planeDistanceToSphereCenter; } /*brute force the area pixel by pixel*/ template static void TestSphereAreaByItk (itk::Image* inputImage) { typedef itk::Image InputImageType; typedef itk::ImageRegionConstIterator< InputImageType > ImageIterator; ImageIterator imageIterator( inputImage, inputImage->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); int sumPixelsInArea = 0; while( !imageIterator.IsAtEnd() ) { if(inputImage->GetPixel(imageIterator.GetIndex()) == pixelValueSet) sumPixelsInArea++; ++imageIterator; } mitk::Point3D volumeCenter; volumeCenter[0] = volumeCenter[1] = volumeCenter[2] = TestvolumeSize / 2.0; double planeDistanceToSphereCenter = TestPlane->Distance(volumeCenter); double sphereRadius = TestvolumeSize/4.0; //calculate the radius of the circle cut from the sphere by the plane double radius = std::sqrt(std::pow(sphereRadius, 2) - std::pow( planeDistanceToSphereCenter , 2)); double areaInMM = 3.14159265358979 * std::pow(radius, 2); testResults.areaCalculated = areaInMM; testResults.areaInPixel = sumPixelsInArea; testResults.percentageAreaCalcToPixel = 100 / areaInMM * sumPixelsInArea; } /* * random a voxel. define plane through this voxel. reslice at the plane. compare the pixel vaues of the voxel * in the volume with the pixel value in the resliced image. * there are some indice shifting problems which causes the test to fail for oblique planes. seems like the chosen * worldcoordinate is not corrresponding to the index in the 2D image. and so the pixel values are not the same as * expected. */ static void PixelvalueBasedTest() { /* setup itk image */ typedef itk::Image ImageType; typedef itk::ImageRegionConstIterator< ImageType > ImageIterator; ImageType::Pointer image = ImageType::New(); ImageType::IndexType start; start[0] = start[1] = start[2] = 0; ImageType::SizeType size; size[0] = size[1] = size[2] = 32; ImageType::RegionType imgRegion; imgRegion.SetSize(size); imgRegion.SetIndex(start); image->SetRegions(imgRegion); image->SetSpacing(1.0); image->Allocate(); ImageIterator imageIterator( image, image->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); unsigned short pixelValue = 0; //fill the image with distinct values while ( !imageIterator.IsAtEnd() ) { image->SetPixel(imageIterator.GetIndex(), pixelValue); ++imageIterator; ++pixelValue; } /* end setup itk image */ mitk::Image::Pointer imageInMitk; CastToMitkImage(image, imageInMitk); /*mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New(); writer->SetInput(imageInMitk); std::string file = "C:\\Users\\schroedt\\Desktop\\cube.nrrd"; writer->SetFileName(file); writer->Update();*/ PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Frontal); PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Sagittal); PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Axial); } static void PixelvalueBasedTestByPlane(mitk::Image* imageInMitk, mitk::PlaneGeometry::PlaneOrientation orientation){ typedef itk::Image ImageType; //set the seed of the rand function srand((unsigned)time(0)); /* setup a random orthogonal plane */ int sliceindex = 17;//rand() % 32; bool isFrontside = true; bool isRotated = false; if( orientation == mitk::PlaneGeometry::Axial) { /*isFrontside = false; isRotated = true;*/ } mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); plane->InitializeStandardPlane(imageInMitk->GetGeometry(), orientation, sliceindex, isFrontside, isRotated); mitk::Point3D origin = plane->GetOrigin(); mitk::Vector3D normal; normal = plane->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 plane->SetOrigin(origin); //we dont need this any more, because we are only testing orthogonal planes /*mitk::Vector3D rotationVector; rotationVector[0] = randFloat(); rotationVector[1] = randFloat(); rotationVector[2] = randFloat(); float degree = randFloat() * 180.0; mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, plane->GetCenter(), rotationVector, degree); plane->ExecuteOperation(op); delete op;*/ /* end setup plane */ /* define a point in the 3D volume. * add the two axis vectors of the plane (each multiplied with a * random number) to the origin. now the two random numbers * become our index coordinates in the 2D image, because the * length of the axis vectors is 1. */ mitk::Point3D planeOrigin = plane->GetOrigin(); mitk::Vector3D axis0, axis1; axis0 = plane->GetAxisVector(0); axis1 = plane->GetAxisVector(1); axis0.Normalize(); axis1.Normalize(); unsigned char n1 = 7;// rand() % 32; unsigned char n2 = 13;// rand() % 32; mitk::Point3D testPoint3DInWorld; testPoint3DInWorld = planeOrigin + (axis0 * n1) + (axis1 * n2); //get the index of the point in the 3D volume ImageType::IndexType testPoint3DInIndex; imageInMitk->GetGeometry()->WorldToIndex(testPoint3DInWorld, testPoint3DInIndex); mitk::Index3D testPoint2DInIndex; /* end define a point in the 3D volume.*/ //do reslicing at the plane mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(); slicer->SetInput(imageInMitk); slicer->SetWorldGeometry(plane); slicer->Update(); mitk::Image::Pointer slice = slicer->GetOutput(); // Get TestPoiont3D as Index in Slice slice->GetGeometry()->WorldToIndex(testPoint3DInWorld,testPoint2DInIndex); mitk::Point3D p, sliceIndexToWorld, imageIndexToWorld; p[0] = testPoint2DInIndex[0]; p[1] = testPoint2DInIndex[1]; p[2] = testPoint2DInIndex[2]; slice->GetGeometry()->IndexToWorld(p, sliceIndexToWorld); p[0] = testPoint3DInIndex[0]; p[1] = testPoint3DInIndex[1]; p[2] = testPoint3DInIndex[2]; imageInMitk->GetGeometry()->IndexToWorld(p, imageIndexToWorld); //compare the pixelvalues of the defined point in the 3D volume with the value of the resliced image unsigned short valueAt3DVolume = imageInMitk->GetPixelValueByIndex(testPoint3DInIndex);//image->GetPixel(testPoint3DInIndex); //unsigned short valueAt3DVolumeByWorld = imageInMitk->GetPixelValueByWorldCoordinate(testPoint3DInWorld); unsigned short valueAtSlice = slice->GetPixelValueByIndex(testPoint2DInIndex); //valueAt3DVolume == valueAtSlice is not always working. because of rounding errors //indices are shifted MITK_TEST_CONDITION(valueAt3DVolume == valueAtSlice, "comparing pixelvalues for orthogonal plane"); vtkSmartPointer imageInVtk = vtkSmartPointer::New(); imageInVtk = imageInMitk->GetVtkImageData(); vtkSmartPointer sliceInVtk = vtkSmartPointer::New(); sliceInVtk = slice->GetVtkImageData(); double PixelvalueByMitkOutput = sliceInVtk->GetScalarComponentAsDouble(n1, n2, 0, 0); //double valueVTKinImage = imageInVtk->GetScalarComponentAsDouble(testPoint3DInIndex[0], testPoint3DInIndex[1], testPoint3DInIndex[2], 0); /* Test that everything is working equally if vtkoutput is used instead of the default output * from mitk ImageToImageFilter */ mitk::ExtractSliceFilter::Pointer slicerWithVtkOutput = mitk::ExtractSliceFilter::New(); slicerWithVtkOutput->SetInput(imageInMitk); slicerWithVtkOutput->SetWorldGeometry(plane); slicerWithVtkOutput->SetVtkOutputRequest(true); slicerWithVtkOutput->Update(); vtkSmartPointer vtkImageByVtkOutput = vtkSmartPointer::New(); vtkImageByVtkOutput = slicerWithVtkOutput->GetVtkOutput(); double PixelvalueByVtkOutput = vtkImageByVtkOutput->GetScalarComponentAsDouble(n1, n2, 0, 0); MITK_TEST_CONDITION(PixelvalueByMitkOutput == PixelvalueByVtkOutput, "testing convertion of image output vtk->mitk by reslicer"); /*================ mbilog outputs ===========================*/ #ifdef EXTRACTOR_DEBUG MITK_INFO << "\n" << "TESTINFO index: " << sliceindex << " orientation: " << orientation << " frontside: " << isFrontside << " rotated: " << isRotated; MITK_INFO << "\n" << "slice index to world: " << sliceIndexToWorld; MITK_INFO << "\n" << "image index to world: " << imageIndexToWorld; MITK_INFO << "\n" << "vtk: slice: " << PixelvalueByMitkOutput << ", image: "<< valueVTKinImage; MITK_INFO << "\n" << "testPoint3D InWorld" << testPoint3DInWorld << " is " << testPoint2DInIndex << " in 2D"; MITK_INFO << "\n" << "randoms: " << ((int)n1) << ", " << ((int)n2); MITK_INFO << "\n" << "point is inside plane: " << plane->IsInside(testPoint3DInWorld) << " and volume: " << imageInMitk->GetGeometry()->IsInside(testPoint3DInWorld); MITK_INFO << "\n" << "volume idx: " << testPoint3DInIndex << " = " << valueAt3DVolume ; MITK_INFO << "\n" << "volume world: " << testPoint3DInWorld << " = " << valueAt3DVolumeByWorld ; MITK_INFO << "\n" << "slice idx: " << testPoint2DInIndex << " = " << valueAtSlice ; mitk::Index3D curr; curr[0] = curr[1] = curr[2] = 0; for( int i = 0; i < 32 ; ++i){ for( int j = 0; j < 32; ++j){ ++curr[1]; if(slice->GetPixelValueByIndex(curr) == valueAt3DVolume){ MITK_INFO << "\n" << valueAt3DVolume << " MATCHED mitk " << curr; } } curr[1] = 0; ++curr[0]; } typedef itk::Image Image2DType; Image2DType::Pointer img = Image2DType::New(); CastToItkImage(slice, img); typedef itk::ImageRegionConstIterator< Image2DType > Iterator2D; Iterator2D iter(img, img->GetLargestPossibleRegion()); iter.GoToBegin(); while( !iter.IsAtEnd() ){ if(img->GetPixel(iter.GetIndex()) == valueAt3DVolume) MITK_INFO << "\n" << valueAt3DVolume << " MATCHED itk " << iter.GetIndex(); ++iter; } #endif //EXTRACTOR_DEBUG } /* random a float value */ static float randFloat(){ return (((float)rand()+1.0) / ((float)RAND_MAX + 1.0)) + (((float)rand()+1.0) / ((float)RAND_MAX + 1.0)) / ((float)RAND_MAX + 1.0);} /* create a sphere with the size of the given testVolumeSize*/ static void InitializeTestVolume() { #ifdef CREATE_VOLUME //do sphere creation ItkVolumeGeneration(); #ifdef SAVE_VOLUME //save in file mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New(); writer->SetInput(TestVolume); std::string file; std::ostringstream filename; filename << "C:\\home\\schroedt\\MITK\\Modules\\ImageExtraction\\Testing\\Data\\sphere_"; filename << TestvolumeSize; filename << ".nrrd"; file = filename.str(); writer->SetFileName(file); writer->Update(); #endif//SAVE_VOLUME #endif #ifndef CREATE_VOLUME //read from file mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance(); std::string filename = locator->FindFile("sphere_512.nrrd.mhd", "Modules/ImageExtraction/Testing/Data"); - mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); - reader->SetFileName(filename); - - reader->Update(); - TestVolume = reader->GetOutput(); + TestVolume = mitk::FileReaderRegistry::Read(filename); #endif #ifdef CALC_TESTFAILURE_DEVIATION //get the TestFailureDeviation in % AccessFixedDimensionByItk(TestVolume, CalcTestFailureDeviation, 3); #endif } //the test result of the sphere reslice struct SliceProperties{ double planeDistanceToSphereCenter; double diameterInMM; double diameterInPixel; double diameterCalculated; double percentageRadiusToPixel; double areaCalculated; double areaInPixel; double percentageAreaCalcToPixel; }; static mitk::Image::Pointer TestVolume; static double TestvolumeSize; static mitk::PlaneGeometry::Pointer TestPlane; static std::string TestName; static unsigned char pixelValueSet; static SliceProperties testResults; static double TestFailureDeviation; private: /* * Generate a sphere with a radius of TestvolumeSize / 4.0 */ static void ItkVolumeGeneration () { typedef itk::Image TestVolumeType; typedef itk::ImageRegionConstIterator< TestVolumeType > ImageIterator; TestVolumeType::Pointer sphereImage = TestVolumeType::New(); TestVolumeType::IndexType start; start[0] = start[1] = start[2] = 0; TestVolumeType::SizeType size; size[0] = size[1] = size[2] = TestvolumeSize; TestVolumeType::RegionType imgRegion; imgRegion.SetSize(size); imgRegion.SetIndex(start); sphereImage->SetRegions(imgRegion); sphereImage->SetSpacing(1.0); sphereImage->Allocate(); sphereImage->FillBuffer(0); mitk::Vector3D center; center[0] = center[1] = center[2] = TestvolumeSize / 2.0; double radius = TestvolumeSize / 4.0; double pixelValue = pixelValueSet; double distanceToCenter = 0.0; ImageIterator imageIterator( sphereImage, sphereImage->GetLargestPossibleRegion() ); imageIterator.GoToBegin(); mitk::Vector3D currentVoxelInIndex; while ( !imageIterator.IsAtEnd() ) { currentVoxelInIndex[0] = imageIterator.GetIndex()[0]; currentVoxelInIndex[1] = imageIterator.GetIndex()[1]; currentVoxelInIndex[2] = imageIterator.GetIndex()[2]; distanceToCenter = (center + ( currentVoxelInIndex * -1.0 )).GetNorm(); //if distance to center is smaller then the radius of the sphere if( distanceToCenter < radius) { sphereImage->SetPixel(imageIterator.GetIndex(), pixelValue); } ++imageIterator; } CastToMitkImage(sphereImage, TestVolume); } /* calculate the devation of the voxel object to the mathematical sphere object. * this is use to make a statement about the accuracy of the resliced image, eg. the circle's diameter or area. */ template static void CalcTestFailureDeviation (itk::Image* inputImage) { typedef itk::Image InputImageType; typedef itk::ImageRegionConstIterator< InputImageType > ImageIterator; ImageIterator iterator(inputImage, inputImage->GetLargestPossibleRegion()); iterator.GoToBegin(); int volumeInPixel = 0; while( !iterator.IsAtEnd() ) { if(inputImage->GetPixel(iterator.GetIndex()) == pixelValueSet) volumeInPixel++; ++iterator; } double diameter = TestvolumeSize / 2.0; double volumeCalculated = (1.0 / 6.0) * 3.14159265358979 * std::pow(diameter, 3); double volumeDeviation = std::abs( 100 - (100 / volumeCalculated * volumeInPixel) ); typename InputImageType::IndexType index; index[0] = index[1] = TestvolumeSize / 2.0; index[2] = 0; int sumpixels = 0; while (index[2] < TestvolumeSize ) { if(inputImage->GetPixel(index) == pixelValueSet) sumpixels++; index[2] += 1; } double diameterDeviation = std::abs( 100 - (100 / diameter * sumpixels) ); #ifdef DEBUG MITK_INFO << "volume deviation: " << volumeDeviation << " diameter deviation:" << diameterDeviation; #endif mitkExtractSliceFilterTestClass::TestFailureDeviation = (volumeDeviation + diameterDeviation) / 2.0; } }; /*================ #END class ================*/ /*================#BEGIN Instanciation of members ================*/ mitk::Image::Pointer mitkExtractSliceFilterTestClass::TestVolume = mitk::Image::New(); double mitkExtractSliceFilterTestClass::TestvolumeSize = 256.0; mitk::PlaneGeometry::Pointer mitkExtractSliceFilterTestClass::TestPlane = mitk::PlaneGeometry::New(); std::string mitkExtractSliceFilterTestClass::TestName = ""; unsigned char mitkExtractSliceFilterTestClass::pixelValueSet = 255; mitkExtractSliceFilterTestClass::SliceProperties mitkExtractSliceFilterTestClass::testResults = {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}; double mitkExtractSliceFilterTestClass::TestFailureDeviation = 0.0; /*================ #END Instanciation of members ================*/ /*================ #BEGIN test main ================*/ int mitkExtractSliceFilterTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkExtractSliceFilterTest") //pixelvalue based testing mitkExtractSliceFilterTestClass::PixelvalueBasedTest(); //initialize sphere test volume mitkExtractSliceFilterTestClass::InitializeTestVolume(); mitk::Vector3D spacing = mitkExtractSliceFilterTestClass::TestVolume->GetGeometry()->GetSpacing(); //the center of the sphere = center of image double sphereCenter = mitkExtractSliceFilterTestClass::TestvolumeSize / 2.0; double planeSize = mitkExtractSliceFilterTestClass::TestvolumeSize; /* axial plane */ mitk::PlaneGeometry::Pointer geometryAxial = mitk::PlaneGeometry::New(); geometryAxial->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Axial, sphereCenter, false, true); geometryAxial->ChangeImageGeometryConsideringOriginOffset(true); mitk::Point3D origin = geometryAxial->GetOrigin(); mitk::Vector3D normal; normal = geometryAxial->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometryAxial->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometryAxial, "Testing axial plane"); /* end axial plane */ /* sagittal plane */ mitk::PlaneGeometry::Pointer geometrySagital = mitk::PlaneGeometry::New(); geometrySagital->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, sphereCenter, true, false); geometrySagital->ChangeImageGeometryConsideringOriginOffset(true); origin = geometrySagital->GetOrigin(); normal = geometrySagital->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometrySagital->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometrySagital, "Testing sagittal plane"); /* sagittal plane */ /* sagittal shifted plane */ mitk::PlaneGeometry::Pointer geometrySagitalShifted = mitk::PlaneGeometry::New(); geometrySagitalShifted->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, (sphereCenter - 14), true, false); geometrySagitalShifted->ChangeImageGeometryConsideringOriginOffset(true); origin = geometrySagitalShifted->GetOrigin(); normal = geometrySagitalShifted->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometrySagitalShifted->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometrySagitalShifted, "Testing sagittal plane shifted"); /* end sagittal shifted plane */ /* coronal plane */ mitk::PlaneGeometry::Pointer geometryCoronal = mitk::PlaneGeometry::New(); geometryCoronal->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Frontal, sphereCenter, true, false); geometryCoronal->ChangeImageGeometryConsideringOriginOffset(true); origin = geometryCoronal->GetOrigin(); normal = geometryCoronal->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //geometryCoronal->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometryCoronal, "Testing coronal plane"); /* end coronal plane */ /* oblique plane */ mitk::PlaneGeometry::Pointer obliquePlane = mitk::PlaneGeometry::New(); obliquePlane->InitializeStandardPlane(planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, sphereCenter, true, false); obliquePlane->ChangeImageGeometryConsideringOriginOffset(true); origin = obliquePlane->GetOrigin(); normal = obliquePlane->GetNormal(); normal.Normalize(); origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5 //obliquePlane->SetOrigin(origin); mitk::Vector3D rotationVector; rotationVector[0] = 0.2; rotationVector[1] = 0.4; rotationVector[2] = 0.62; float degree = 37.0; mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, obliquePlane->GetCenter(), rotationVector, degree); obliquePlane->ExecuteOperation(op); delete op; mitkExtractSliceFilterTestClass::TestSlice(obliquePlane, "Testing oblique plane"); /* end oblique plane */ #ifdef SHOW_SLICE_IN_RENDER_WINDOW /*================ #BEGIN vtk render code ================*/ //set reslicer for renderwindow - mitk::ItkImageFileReader::Pointer reader = mitk::ItkImageFileReader::New(); - - std::string filename = "C:\\home\\Pics\\Pic3D.nrrd"; - reader->SetFileName(filename); - - reader->Update(); - mitk::Image::Pointer pic = reader->GetOutput(); + mitk::Image::Pointer pic = mitk::FileReaderRegistry::Read(filename); vtkSmartPointer slicer = vtkSmartPointer::New(); slicer->SetInput(pic->GetVtkImageData()); mitk::PlaneGeometry::Pointer obliquePl = mitk::PlaneGeometry::New(); obliquePl->InitializeStandardPlane(pic->GetGeometry(), mitk::PlaneGeometry::Sagittal, pic->GetGeometry()->GetCenter()[0], true, false); obliquePl->ChangeImageGeometryConsideringOriginOffset(true); mitk::Point3D origin2 = obliquePl->GetOrigin(); mitk::Vector3D n; n = obliquePl->GetNormal(); n.Normalize(); origin2 += n * 0.5;//pixelspacing is 1, so half the spacing is 0.5 obliquePl->SetOrigin(origin2); mitk::Vector3D rotation; rotation[0] = 0.534307; rotation[1] = 0.000439605; rotation[2] = 0.423017; MITK_INFO << rotation; float rotateDegree = 70; mitk::RotationOperation* operation = new mitk::RotationOperation(mitk::OpROTATE, obliquePl->GetCenter(), rotationVector, degree); obliquePl->ExecuteOperation(operation); delete operation; double origin[3]; origin[0] = obliquePl->GetOrigin()[0]; origin[1] = obliquePl->GetOrigin()[1]; origin[2] = obliquePl->GetOrigin()[2]; slicer->SetResliceAxesOrigin(origin); mitk::Vector3D right, bottom, normal; right = obliquePl->GetAxisVector( 0 ); bottom = obliquePl->GetAxisVector( 1 ); normal = obliquePl->GetNormal(); right.Normalize(); bottom.Normalize(); normal.Normalize(); double cosines[9]; mitk::vnl2vtk(right.GetVnlVector(), cosines);//x mitk::vnl2vtk(bottom.GetVnlVector(), cosines + 3);//y mitk::vnl2vtk(normal.GetVnlVector(), cosines + 6);//n slicer->SetResliceAxesDirectionCosines(cosines); slicer->SetOutputDimensionality(2); slicer->Update(); //set vtk renderwindow vtkSmartPointer vtkPlane = vtkSmartPointer::New(); vtkPlane->SetOrigin(0.0, 0.0, 0.0); //These two points define the axes of the plane in combination with the origin. //Point 1 is the x-axis and point 2 the y-axis. //Each plane is transformed according to the view (axial, coronal and saggital) afterwards. vtkPlane->SetPoint1(1.0, 0.0, 0.0); //P1: (xMax, yMin, depth) vtkPlane->SetPoint2(0.0, 1.0, 0.0); //P2: (xMin, yMax, depth) //these are not the correct values for all slices, only a square plane by now vtkSmartPointer imageMapper = vtkSmartPointer::New(); imageMapper->SetInputConnection(vtkPlane->GetOutputPort()); vtkSmartPointer lookupTable = vtkSmartPointer::New(); //built a default lookuptable lookupTable->SetRampToLinear(); lookupTable->SetSaturationRange( 0.0, 0.0 ); lookupTable->SetHueRange( 0.0, 0.0 ); lookupTable->SetValueRange( 0.0, 1.0 ); lookupTable->Build(); //map all black values to transparent lookupTable->SetTableValue(0, 0.0, 0.0, 0.0, 0.0); lookupTable->SetRange(-255.0, 255.0); //lookupTable->SetRange(-1022.0, 1184.0);//pic3D range vtkSmartPointer texture = vtkSmartPointer::New(); texture->SetInput(slicer->GetOutput()); texture->SetLookupTable(lookupTable); texture->SetMapColorScalarsThroughLookupTable(true); vtkSmartPointer imageActor = vtkSmartPointer::New(); imageActor->SetMapper(imageMapper); imageActor->SetTexture(texture); // Setup renderers vtkSmartPointer renderer = vtkSmartPointer::New(); renderer->AddActor(imageActor); // Setup render window vtkSmartPointer renderWindow = vtkSmartPointer::New(); renderWindow->AddRenderer(renderer); // Setup render window interactor vtkSmartPointer renderWindowInteractor = vtkSmartPointer::New(); vtkSmartPointer style = vtkSmartPointer::New(); renderWindowInteractor->SetInteractorStyle(style); // Render and start interaction renderWindowInteractor->SetRenderWindow(renderWindow); //renderer->AddViewProp(imageActor); renderWindow->Render(); renderWindowInteractor->Start(); // always end with this! /*================ #END vtk render code ================*/ #endif //SHOW_SLICE_IN_RENDER_WINDOW MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkFileReaderRegistryTest.cpp b/Core/Code/Testing/mitkFileReaderRegistryTest.cpp index 75683f1d73..7935ee784d 100644 --- a/Core/Code/Testing/mitkFileReaderRegistryTest.cpp +++ b/Core/Code/Testing/mitkFileReaderRegistryTest.cpp @@ -1,218 +1,209 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkAbstractFileReader.h" #include "mitkIFileReader.h" #include "mitkFileReaderRegistry.h" #include -#include -#include #include -#include -#include -#include - class DummyReader : public mitk::AbstractFileReader { public: DummyReader(const DummyReader& other) : mitk::AbstractFileReader(other) { } DummyReader(const std::string& extension, int priority) : mitk::AbstractFileReader(extension, "This is a dummy description") { m_Priority = priority; m_ServiceReg = this->RegisterService(); } ~DummyReader() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using mitk::AbstractFileReader::Read; virtual std::vector< itk::SmartPointer > Read(const std::istream& /*stream*/, mitk::DataStorage* /*ds*/ = 0) { std::vector result; return result; } private: DummyReader* Clone() const { return new DummyReader(*this); } us::ServiceRegistration m_ServiceReg; }; // End of internal dummy reader class DummyReader2 : public mitk::AbstractFileReader { public: DummyReader2(const DummyReader2& other) : mitk::AbstractFileReader(other) { } DummyReader2(const std::string& extension, int priority) : mitk::AbstractFileReader(extension, "This is a second dummy description") { m_Priority = priority; m_ServiceReg = this->RegisterService(); } ~DummyReader2() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using mitk::AbstractFileReader::Read; virtual std::vector< itk::SmartPointer > Read(const std::istream& /*stream*/, mitk::DataStorage* /*ds*/ = 0) { std::vector result; return result; } private: DummyReader2* Clone() const { return new DummyReader2(*this); } us::ServiceRegistration m_ServiceReg; }; // End of internal dummy reader 2 /** * TODO */ int mitkFileReaderRegistryTest(int /*argc*/ , char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("FileReaderRegistry"); // mitk::FileReaderRegistry::Pointer frm = mitk::FileReaderRegistry::New(); // MITK_TEST_CONDITION_REQUIRED(argc == 2,"Testing FileReaderRegistry instantiation"); DummyReader testDR("test",1); DummyReader otherDR("other",1); MITK_TEST_CONDITION_REQUIRED(testDR.CanRead("/this/is/a/folder/file.test"),"Positive test of default CanRead() implementation"); MITK_TEST_CONDITION_REQUIRED(!testDR.CanRead("/this/is/a/folder/file.tes"),"Negative test of default CanRead() implementation"); - mitk::FileReaderRegistry* ReaderRegistry = new mitk::FileReaderRegistry; - mitk::IFileReader* returned = ReaderRegistry->GetReader("test"); + mitk::FileReaderRegistry* readerRegistry = new mitk::FileReaderRegistry; + mitk::IFileReader* returned = readerRegistry->GetReader("test"); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(testDR) != returned,"Testing correct retrieval of FileReader 1/2"); - returned = ReaderRegistry->GetReader("other"); + returned = readerRegistry->GetReader("other"); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(otherDR) != returned,"Testing correct retrieval of FileReader 2/2"); DummyReader mediocreTestDR("test", 20); DummyReader prettyFlyTestDR("test", 50); DummyReader2 awesomeTestDR("test", 100); - returned = ReaderRegistry->GetReader("test"); + returned = readerRegistry->GetReader("test"); MITK_TEST_CONDITION_REQUIRED(dynamic_cast(returned), "Testing correct priorized retrieval of FileReader: Best reader"); // Now to give those readers some options, then we will try again mitk::IFileReader::OptionList options; options.push_back(std::make_pair("isANiceGuy", true)); mediocreTestDR.SetOptions(options); options.clear(); options.push_back(std::make_pair("canFly", true)); prettyFlyTestDR.SetOptions(options); options.push_back(std::make_pair("isAwesome", true)); awesomeTestDR.SetOptions(options); //note: awesomeReader canFly and isAwesome // Reset Options, use to define what we want the reader to do options.clear(); mitk::IFileReader::OptionNames optionsFilter; optionsFilter.push_back("canFly"); - returned = ReaderRegistry->GetReader("test", optionsFilter); + returned = readerRegistry->GetReader("test", optionsFilter); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(awesomeTestDR) != returned, "Testing correct retrieval of FileReader with Options: Best reader with options"); optionsFilter.push_back("isAwesome"); - returned = ReaderRegistry->GetReader("test", optionsFilter); + returned = readerRegistry->GetReader("test", optionsFilter); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(awesomeTestDR) != returned, "Testing correct retrieval of FileReader with multiple Options: Best reader with options"); optionsFilter.clear(); optionsFilter.push_back("isANiceGuy"); - returned = ReaderRegistry->GetReader("test", optionsFilter); + returned = readerRegistry->GetReader("test", optionsFilter); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(mediocreTestDR) != returned, "Testing correct retrieval of specific FileReader with Options: Low priority reader with specific option"); optionsFilter.push_back("canFly"); - returned = ReaderRegistry->GetReader("test", optionsFilter); + returned = readerRegistry->GetReader("test", optionsFilter); MITK_TEST_CONDITION_REQUIRED(returned == NULL, "Testing correct return of 0 value when no matching reader was found"); // Onward to test the retrieval of multiple readers std::vector< mitk::IFileReader* > returnedList; - returnedList = ReaderRegistry->GetReaders("test", optionsFilter); + returnedList = readerRegistry->GetReaders("test", optionsFilter); MITK_TEST_CONDITION_REQUIRED(returnedList.empty(), "Testing correct return of zero readers when no matching reader was found, asking for all compatibles"); optionsFilter.clear(); optionsFilter.push_back("canFly"); - returnedList = ReaderRegistry->GetReaders("test", optionsFilter); + returnedList = readerRegistry->GetReaders("test", optionsFilter); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 2, "Testing correct return of two readers when two matching reader was found, asking for all compatibles"); MITK_TEST_CONDITION_REQUIRED(dynamic_cast(returnedList.front()), "Testing correct priorization of returned Readers with options 1/2"); optionsFilter.clear(); optionsFilter.push_back("isAwesome"); - returnedList = ReaderRegistry->GetReaders("test", optionsFilter); + returnedList = readerRegistry->GetReaders("test", optionsFilter); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 1, "Testing correct return of one readers when one matching reader was found, asking for all compatibles"); MITK_TEST_CONDITION_REQUIRED(dynamic_cast(returnedList.front()), "Testing correctness of result from former query"); // And now to verify a working read chain for a mps file: //mitk::PointSetReader::Pointer psr = mitk::PointSetReader::New(); //std::vector basedata; //basedata = mitk::FileReaderRegistry::Read("F://Build//MITK-Data//pointSet.mps"); //MITK_TEST_CONDITION_REQUIRED(basedata.size() > 0, "Testing correct read of PointSet"); - // Need to instanciate the CoreObjectFactory, so legacy Readers are available - mitk::CoreObjectFactory::GetInstance(); - // Testing templated call to ReaderRegistry //mitk::PointSet::Pointer pointset = mitk::FileReaderRegistry::Read< mitk::PointSet >("F://Build//MITK-Data//pointSet.mps"); //MITK_TEST_CONDITION_REQUIRED(pointset.IsNotNull(), "Testing templated call of Read()"); // And now for something completely different... (Debug) // mitk::LegacyFileReaderService::Pointer lfr = mitk::LegacyFileReaderService::New(".nrrd", "Nearly Raw Raster Data"); //returned = mitk::FileReaderRegistry::GetReader(".nrrd"); //MITK_TEST_CONDITION_REQUIRED(lfr == returned, "Testing correct retrieval of specific FileReader with Options: Low priority reader with specific option"); //std::vector image = mitk::FileReaderRegistry::Read("F://Build//MITK-Data//Pic2DplusT.nrrd"); //MITK_TEST_CONDITION_REQUIRED(image.size() > 0, "Testing whether image was returned or not"); //mitk::Image::Pointer image2 = dynamic_cast (image.front().GetPointer()); //MITK_TEST_CONDITION_REQUIRED(image2.IsNotNull(), "Testing if BaseData is an image"); // Delete this here because it will call the PrototypeServiceFactory::Unget() method // of the dummy readers. - delete ReaderRegistry; + delete readerRegistry; // always end with this! MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkFileWriterRegistryTest.cpp b/Core/Code/Testing/mitkFileWriterRegistryTest.cpp index 5905cbcd64..2eff6b00fa 100644 --- a/Core/Code/Testing/mitkFileWriterRegistryTest.cpp +++ b/Core/Code/Testing/mitkFileWriterRegistryTest.cpp @@ -1,312 +1,307 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include +#include #include -#include -#include -#include -#include -#include -#include #include class DummyBaseData : public mitk::BaseData { public: mitkClassMacro(DummyBaseData, mitk::BaseData) itkNewMacro(Self) void SetRequestedRegion(const itk::DataObject * /*data*/) {} void SetRequestedRegionToLargestPossibleRegion() {} bool RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool VerifyRequestedRegion() { return true; } }; class DummyWriter : public mitk::AbstractFileWriter { public: DummyWriter(const DummyWriter& other) : mitk::AbstractFileWriter(other) , m_Content("Hi there stream") { } DummyWriter(const std::string& basedataType, const std::string& extension, int priority) : mitk::AbstractFileWriter(basedataType, extension, "This is a dummy description") , m_Content("Hi there stream") { m_Priority = priority; m_ServiceReg = this->RegisterService(); } ~DummyWriter() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using AbstractFileWriter::Write; virtual void Write(const mitk::BaseData* data, std::ostream& stream) { MITK_TEST_CONDITION_REQUIRED(dynamic_cast(data), "Correct data type") stream << m_Content; } std::string m_Content; private: DummyWriter* Clone() const { return new DummyWriter(*this); } us::ServiceRegistration m_ServiceReg; }; // End of internal dummy Writer class DummyWriter2 : public mitk::AbstractFileWriter { public: DummyWriter2(const DummyWriter2& other) : mitk::AbstractFileWriter(other) , m_Content("hi there file path") { } DummyWriter2(const std::string& basedataType, const std::string& extension, int priority) : mitk::AbstractFileWriter(basedataType, extension, "This is a dummy description") , m_Content("hi there file path") { m_Priority = priority; m_ServiceReg = this->RegisterService(); } ~DummyWriter2() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using AbstractFileWriter::Write; virtual void Write(const mitk::BaseData* data, const std::string& filePath ) { MITK_TEST_CONDITION_REQUIRED(dynamic_cast(data), "Correct data type") std::ofstream fileStream(filePath.c_str()); fileStream << m_Content; } virtual void Write(const mitk::BaseData* data, std::ostream& stream ) { mitk::AbstractFileWriter::Write(data, stream); } virtual bool CanWrite(const mitk::BaseData *data) const { return dynamic_cast(data); } std::string m_Content; private: DummyWriter2* Clone() const { return new DummyWriter2(*this); } us::ServiceRegistration m_ServiceReg; }; // End of internal dummy Writer 2 void TestStreamMethods() { DummyWriter dummyWriter(DummyBaseData::GetStaticNameOfClass(), ".stream", 100); DummyWriter2 dummyWriter2(DummyBaseData::GetStaticNameOfClass(), ".file", 50); mitk::FileWriterRegistry writerRegistry; // Test DummyWriter, which always uses a ostream for writing, even // when a file path is used DummyBaseData dummyData; std::stringstream oss; writerRegistry.Write(&dummyData, oss); MITK_TEST_CONDITION_REQUIRED(dummyWriter.m_Content == oss.str(), "Dummy stream writer") std::string content; { std::ofstream tmpStream; std::string tmpFileName = mitk::IOUtil::CreateTemporaryFile(tmpStream); writerRegistry.Write(&dummyData, tmpFileName); std::ifstream tmpInput(tmpFileName.c_str()); std::getline(tmpInput, content); tmpInput.close(); tmpStream.close(); std::remove(tmpFileName.c_str()); } MITK_TEST_CONDITION_REQUIRED(dummyWriter.m_Content == content, "Dummy stream writer") // Test DummyWriter2, which always uses a real file for writing, even // when a std::ostream object is given std::stringstream oss2; dummyWriter2.Write(&dummyData, oss2); MITK_TEST_CONDITION_REQUIRED(dummyWriter2.m_Content == oss2.str(), "Dummy 2 stream writer") std::string content2; { std::ofstream tmpStream; std::string tmpFileName = mitk::IOUtil::CreateTemporaryFile(tmpStream); tmpStream.close(); std::remove(tmpFileName.c_str()); // This is a work-around to get a temporary file name ending with ".file" tmpFileName += ".file"; writerRegistry.Write(&dummyData, tmpFileName); std::ifstream tmpInput(tmpFileName.c_str()); std::getline(tmpInput, content2); tmpInput.close(); std::remove(tmpFileName.c_str()); } MITK_TEST_CONDITION_REQUIRED(dummyWriter2.m_Content == content2, "Dummy 2 stream writer") } /** * TODO */ int mitkFileWriterRegistryTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("FileWriterRegistry"); TestStreamMethods(); // mitk::FileWriterRegistry::Pointer frm = mitk::FileWriterRegistry::New(); // MITK_TEST_CONDITION_REQUIRED(argc == 2,"Testing FileWriterRegistry instantiation"); DummyWriter testDR("testdata", "test", 1); DummyWriter otherDR("testdata", "other", 1); // MITK_TEST_CONDITION_REQUIRED(testDR->CanWrite("/this/is/a/folder/file.test"),"Positive test of default CanRead() implementation"); // MITK_TEST_CONDITION_REQUIRED(!testDR->CanWrite("/this/is/a/folder/file.tes"),"Negative test of default CanRead() implementation"); - mitk::FileWriterRegistry* WriterRegistry = new mitk::FileWriterRegistry; - mitk::IFileWriter* returned = WriterRegistry->GetWriter("", "test"); + mitk::FileWriterRegistry* writerRegistry = new mitk::FileWriterRegistry; + mitk::IFileWriter* returned = writerRegistry->GetWriter("", "test"); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(testDR) != returned,"Testing correct retrieval of FileWriter 1/2"); - returned = WriterRegistry->GetWriter("", "other"); + returned = writerRegistry->GetWriter("", "other"); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(otherDR) != returned,"Testing correct retrieval of FileWriter 2/2"); DummyWriter mediocreTestDR("testdata", "test", 20); DummyWriter prettyFlyTestDR("testdata", "test", 50); DummyWriter2 awesomeTestDR("testdata", "test", 100); - returned = WriterRegistry->GetWriter("test"); + returned = writerRegistry->GetWriter("test"); MITK_TEST_CONDITION_REQUIRED(dynamic_cast(&awesomeTestDR), "Testing correct priorized retrieval of FileWriter: Best Writer"); // Now to give those Writers some options, then we will try again mitk::IFileWriter::OptionList options; options.push_back(std::make_pair("isANiceGuy", true)); mediocreTestDR.SetOptions(options); options.clear(); options.push_back(std::make_pair("canFly", true)); prettyFlyTestDR.SetOptions(options); options.push_back(std::make_pair("isAwesome", true)); awesomeTestDR.SetOptions(options); //note: awesomeWriter canFly and isAwesome // Reset Options, use to define what we want the Writer to do mitk::IFileWriter::OptionNames optionFilter; optionFilter.push_back("canFly"); - returned = WriterRegistry->GetWriter("", "test", optionFilter); + returned = writerRegistry->GetWriter("", "test", optionFilter); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(awesomeTestDR) != returned, "Testing correct retrieval of FileWriter with Options: Best Writer with options"); optionFilter.push_back("isAwesome"); - returned = WriterRegistry->GetWriter("", "test", optionFilter); + returned = writerRegistry->GetWriter("", "test", optionFilter); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(awesomeTestDR) != returned, "Testing correct retrieval of FileWriter with multiple Options: Best Writer with options"); optionFilter.clear(); optionFilter.push_back("isANiceGuy"); - returned = WriterRegistry->GetWriter("", "test", optionFilter); + returned = writerRegistry->GetWriter("", "test", optionFilter); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(mediocreTestDR) != returned, "Testing correct retrieval of specific FileWriter with Options: Low priority Writer with specific option"); optionFilter.push_back("canFly"); - returned = WriterRegistry->GetWriter("", "test", optionFilter); + returned = writerRegistry->GetWriter("", "test", optionFilter); MITK_TEST_CONDITION_REQUIRED(returned == NULL, "Testing correct return of 0 value when no matching Writer was found"); // Onward to test the retrieval of multiple Writers std::vector< mitk::IFileWriter* > returnedList; - returnedList = WriterRegistry->GetWriters("", "test", optionFilter); + returnedList = writerRegistry->GetWriters("", "test", optionFilter); MITK_TEST_CONDITION_REQUIRED(returnedList.empty(), "Testing correct return of zero Writers when no matching Writer was found, asking for all compatibles"); optionFilter.clear(); optionFilter.push_back("canFly"); - returnedList = WriterRegistry->GetWriters("", "test", optionFilter); + returnedList = writerRegistry->GetWriters("", "test", optionFilter); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 2, "Testing correct return of two Writers when two matching Writer was found, asking for all compatibles"); MITK_TEST_CONDITION_REQUIRED(dynamic_cast(returnedList.front()), "Testing correct priorization of returned Writers with options 1/2"); optionFilter.clear(); optionFilter.push_back("isAwesome"); - returnedList = WriterRegistry->GetWriters("", "test", optionFilter); + returnedList = writerRegistry->GetWriters("", "test", optionFilter); MITK_TEST_CONDITION_REQUIRED(returnedList.size() == 1, "Testing correct return of one Writers when one matching Writer was found, asking for all compatibles"); MITK_TEST_CONDITION_REQUIRED(dynamic_cast(returnedList.front()), "Testing correctness of result from former query"); - mitk::CoreObjectFactory::GetInstance(); - //mitk::FileReaderRegistry ReaderRegistry; - //mitk::Image::Pointer image = ReaderRegistry.Read("F://Build//MITK-Data//Pic2DplusT.nrrd"); + //mitk::CoreObjectFactory::GetInstance(); + //mitk::FileReaderRegistry readerRegistry; + //mitk::Image::Pointer image = readerRegistry.Read("F://Build//MITK-Data//Pic2DplusT.nrrd"); - //WriterRegistry->Write(image.GetPointer(), "F://Build//MITK-Data//Pic2DplusTcopy.nrrd"); + //writerRegistry->Write(image.GetPointer(), "F://Build//MITK-Data//Pic2DplusTcopy.nrrd"); //// And now to verify a working read chain for a mps file: //mitk::PointSetWriter::Pointer psr = mitk::PointSetWriter::New(); //mitk::BaseData::Pointer basedata; //basedata = mitk::FileWriterRegistry::Read("F://Build//MITK-Data//pointSet.mps"); //MITK_TEST_CONDITION_REQUIRED(basedata.IsNotNull(), "Testing correct read of PointSet"); //// Testing templated call to WriterRegistry //mitk::PointSet::Pointer pointset = mitk::FileWriterRegistry::Read< mitk::PointSet >("F://Build//MITK-Data//pointSet.mps"); //MITK_TEST_CONDITION_REQUIRED(pointset.IsNotNull(), "Testing templated call of Read()"); //// And now for something completely different... (Debug) //mitk::LegacyFileWriterService::Pointer lfr = mitk::LegacyFileWriterService::New(".nrrd", "Nearly Raw Raster Data"); //returned = mitk::FileWriterRegistry::GetWriter(".nrrd"); //MITK_TEST_CONDITION_REQUIRED(lfr == returned, "Testing correct retrieval of specific FileWriter with Options: Low priority Writer with specific option"); //mitk::BaseData::Pointer image = mitk::FileWriterRegistry::Read("F://Build//MITK-Data//Pic2DplusT.nrrd"); //MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(), "Testing whether BaseData is empty or not"); //mitk::Image::Pointer image2 = dynamic_cast (image.GetPointer()); //MITK_TEST_CONDITION_REQUIRED(image2.IsNotNull(), "Testing if BaseData is an image"); // Delete this here because it will call the PrototypeServiceFactory::Unget() method // of the dummy writers. - delete WriterRegistry; + delete writerRegistry; //// always end with this! MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkImageAccessorTest.cpp b/Core/Code/Testing/mitkImageAccessorTest.cpp index d38476d840..1e684389ac 100644 --- a/Core/Code/Testing/mitkImageAccessorTest.cpp +++ b/Core/Code/Testing/mitkImageAccessorTest.cpp @@ -1,261 +1,249 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkImage.h" #include "mitkImageReadAccessor.h" #include "mitkImagePixelReadAccessor.h" #include "mitkImagePixelWriteAccessor.h" #include "mitkImageWriteAccessor.h" -#include "mitkDataNodeFactory.h" #include "mitkImageTimeSelector.h" +#include "mitkFileReaderRegistry.h" #include #include "itkBarrier.h" #include #include #include #include #include struct ThreadData { itk::Barrier::Pointer m_Barrier; // holds a pointer to the used barrier mitk::Image::Pointer data; // some random data int m_NoOfThreads; // holds the number of generated threads bool m_Successful; // to check if everything worked }; itk::SimpleFastMutexLock testMutex; ITK_THREAD_RETURN_TYPE ThreadMethod(void* data) { /* extract data pointer from Thread Info structure */ struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)data; // some data validity checking if (pInfo == NULL) { return ITK_THREAD_RETURN_VALUE; } if (pInfo->UserData == NULL) { return ITK_THREAD_RETURN_VALUE; } // obtain user data for processing ThreadData* threadData = (ThreadData*) pInfo->UserData; srand( pInfo->ThreadID ); mitk::Image::Pointer im = threadData->data; int nrSlices = im->GetDimension(2); // Create randomly a PixelRead- or PixelWriteAccessor for a slice and access all pixels in it. try { if(rand() % 2) { testMutex.Lock(); mitk::ImageDataItem* iDi = im->GetSliceData(rand() % nrSlices); testMutex.Unlock(); while(!iDi->IsComplete()) {} //MITK_INFO << "pixeltype: " << im->GetPixelType().GetComponentTypeAsString(); if ((im->GetPixelType().GetComponentTypeAsString() == "short") && (im->GetDimension() == 3) ) { // Use pixeltype&dimension specific read accessor int xlength = im->GetDimension(0); int ylength = im->GetDimension(1); mitk::ImagePixelReadAccessor readAccessor(im, iDi); itk::Index<2> idx; for(int i=0; iGetSliceData(rand() % nrSlices); testMutex.Unlock(); while(!iDi->IsComplete()) {} if ((im->GetPixelType().GetComponentTypeAsString() == "short") && (im->GetDimension() == 3) ) { // Use pixeltype&dimension specific read accessor int xlength = im->GetDimension(0); int ylength = im->GetDimension(1); mitk::ImagePixelWriteAccessor writeAccessor(im, iDi); itk::Index<2> idx; for(int i=0; im_Successful = false; } } } } else { // use general accessor mitk::ImageWriteAccessor iB(im,iDi); void* pointer = iB.GetData(); *((char*) pointer) = 0; } } } catch(mitk::MemoryIsLockedException e) { threadData->m_Successful = false; e.Print(std::cout); } catch(mitk::Exception e) { threadData->m_Successful = false; e.Print(std::cout); } // data processing end! threadData->m_Barrier->Wait(); return ITK_THREAD_RETURN_VALUE; } int mitkImageAccessorTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkImageAccessorTest"); std::cout << "Loading file: "; if(argc==0) { std::cout<<"no file specified [FAILED]"<SetFileName( argv[1] ); - factory->Update(); + image = mitk::FileReaderRegistry::Read(std::string(argv[1])); - if(factory->GetNumberOfOutputs()<1) - { - std::cout<<"file could not be loaded [FAILED]"<GetOutput( 0 ); - image = dynamic_cast(node->GetData()); if(image.IsNull()) { - std::cout<<"file not an image - test will not be applied [PASSED]"<GetGeometry()->Initialize(); itk::MultiThreader::Pointer threader = itk::MultiThreader::New(); unsigned int noOfThreads = 100; // initialize barrier itk::Barrier::Pointer barrier = itk::Barrier::New(); barrier->Initialize( noOfThreads + 1); // add one for we stop the base thread when the worker threads are processing ThreadData* threadData = new ThreadData; threadData->m_Barrier = barrier; threadData->m_NoOfThreads = noOfThreads; threadData->data = image; threadData->m_Successful = true; // spawn threads for(unsigned int i=0; i < noOfThreads; ++i) { threader->SpawnThread(ThreadMethod, threadData); } // stop the base thread during worker thread execution barrier->Wait(); // terminate threads for(unsigned int j=0; j < noOfThreads; ++j) { threader->TerminateThread(j); } bool TestSuccessful = threadData->m_Successful ; delete threadData; MITK_TEST_CONDITION_REQUIRED( TestSuccessful, "Testing image access from multiple threads"); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkImageDimensionConverterTest.cpp b/Core/Code/Testing/mitkImageDimensionConverterTest.cpp index ff084a8523..40adc9126e 100644 --- a/Core/Code/Testing/mitkImageDimensionConverterTest.cpp +++ b/Core/Code/Testing/mitkImageDimensionConverterTest.cpp @@ -1,292 +1,277 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // mitk includes #include #include #include -#include "mitkItkImageFileReader.h" #include #include #include #include #include -#include #include +#include +#include #include "mitkTestingConfig.h" -#include "mitkItkImageFileReader.h" // itk includes #include #include // stl includes #include // vtk includes #include int mitkImageDimensionConverterTest(int argc, char* argv[]) { MITK_TEST_BEGIN(mitkImageDimensionConverterTest); // Define an epsilon which is the allowed error float eps = 0.00001; // Define helper variables float error = 0; bool matrixIsEqual = true; std::stringstream sstream; - mitk::ImageWriter::Pointer imageWriter = mitk::ImageWriter::New(); - mitk::ItkImageFileReader::Pointer imageReader = mitk::ItkImageFileReader::New(); mitk::Convert2Dto3DImageFilter::Pointer convertFilter = mitk::Convert2Dto3DImageFilter::New(); /////////////////////////////////////// // Create 2D Image with a 3D rotation from scratch. typedef itk::Image ImageType; ImageType::Pointer itkImage = ImageType::New(); ImageType::RegionType myRegion; ImageType::SizeType mySize; ImageType::IndexType myIndex; ImageType::SpacingType mySpacing; mySpacing[0] = 1; mySpacing[1] = 1; myIndex[0] = 0; myIndex[1] = 0; mySize[0] = 50; mySize[1] = 50; myRegion.SetSize( mySize); myRegion.SetIndex( myIndex ); itkImage->SetSpacing(mySpacing); itkImage->SetRegions( myRegion); itkImage->Allocate(); itkImage->FillBuffer(50); mitk::Image::Pointer mitkImage2D; mitk::CastToMitkImage(itkImage,mitkImage2D); // rotate mitk::Point3D p; p[0] = 1; p[1] = 3; p[2] = 5; mitk::Vector3D v; v[0] = 0.3; v[1] = 1; v[2] = 0.1; mitk::RotationOperation op(mitk::OpROTATE, p, v, 35); mitkImage2D->GetGeometry()->ExecuteOperation(&op); // Save original Geometry infos mitk::Vector3D Original_col0, Original_col1, Original_col2; Original_col0.SetVnlVector(mitkImage2D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(0)); Original_col1.SetVnlVector(mitkImage2D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(1)); Original_col2.SetVnlVector(mitkImage2D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)); MITK_INFO << "Rotated Matrix: " << Original_col0 << " " << Original_col1 << " " << Original_col2; mitk::Point3D Original_Origin = mitkImage2D->GetGeometry()->GetOrigin(); mitk::Vector3D Original_Spacing = mitkImage2D->GetGeometry()->GetSpacing(); MITK_TEST_CONDITION_REQUIRED( mitkImage2D->GetDimension() == 2 , "Created Image is Dimension 2"); /////////////////////////////////////// // mitkImage2D is now a 2D image with 3D Geometry information. // Save it without conversion and load it again. It should have an identitiy matrix sstream.clear(); - sstream << MITK_TEST_OUTPUT_DIR << "" << "/rotatedImage2D"; - imageWriter->SetInput(mitkImage2D); - imageWriter->SetFileName(sstream.str().c_str()); - imageWriter->SetExtension(".nrrd"); - imageWriter->Write(); - sstream << ".nrrd"; + sstream << MITK_TEST_OUTPUT_DIR << "" << "/rotatedImage2D.nrrd"; + mitk::FileWriterRegistry::Write(mitkImage2D, sstream.str()); - imageReader->SetFileName(sstream.str().c_str()); - imageReader->Update(); - mitk::Image::Pointer imageLoaded2D = imageReader->GetOutput(); + mitk::Image::Pointer imageLoaded2D = mitk::FileReaderRegistry::Read(sstream.str()); // check if image can be loaded MITK_TEST_CONDITION_REQUIRED( imageLoaded2D.IsNotNull() , "Loading saved 2D Image"); MITK_TEST_CONDITION_REQUIRED( imageLoaded2D->GetDimension() == 2 , "Loaded Image is Dimension 2"); // check if spacing is ok mitk::Vector3D Loaded2D_Spacing = imageLoaded2D->GetGeometry()->GetSpacing(); error = abs(Loaded2D_Spacing[0] - Original_Spacing[0]) + abs(Loaded2D_Spacing[1] - Original_Spacing[1]) + abs(Loaded2D_Spacing[2] - 1) ; MITK_TEST_CONDITION_REQUIRED( error < eps , "Compare Geometry: Spacing"); // Check origin mitk::Point3D Loaded2D_Origin = imageLoaded2D->GetGeometry()->GetOrigin(); error = abs(Loaded2D_Origin[0] - Original_Origin[0]) + abs(Loaded2D_Origin[1] - Original_Origin[1]) + abs(Loaded2D_Origin[2] - 0) ; MITK_TEST_CONDITION_REQUIRED( error < eps, "Compare Geometry: Origin"); // Check matrix mitk::Vector3D Loaded2D_col0, Loaded2D_col1, Loaded2D_col2; Loaded2D_col0.SetVnlVector(imageLoaded2D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(0)); Loaded2D_col1.SetVnlVector(imageLoaded2D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(1)); Loaded2D_col2.SetVnlVector(imageLoaded2D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)); if ( (abs(1 - Loaded2D_col0[0]) > eps) || (abs(0 - Loaded2D_col0[1]) > eps) || (abs(0 - Loaded2D_col0[2]) > eps) || (abs(0 - Loaded2D_col1[0]) > eps) || (abs(1 - Loaded2D_col1[1]) > eps) || (abs(0 - Loaded2D_col1[2]) > eps) || (abs(0 - Loaded2D_col2[0]) > eps) || (abs(0 - Loaded2D_col2[1]) > eps) || (abs(1 - Loaded2D_col2[2]) > eps) ) { matrixIsEqual = false; } else matrixIsEqual = true; MITK_TEST_CONDITION_REQUIRED( matrixIsEqual , "Compare Geometry: Matrix"); /////////////////////////////////////// // mitkImage2D is a 2D image with 3D Geometry information. // Convert it with filter to a 3D image and check if everything went well convertFilter->SetInput(mitkImage2D); convertFilter->Update(); mitk::Image::Pointer mitkImage3D = convertFilter->GetOutput(); MITK_TEST_CONDITION_REQUIRED( mitkImage3D->GetDimension() == 3 , "Converted Image is Dimension 3"); // check if geometry is still same mitk::Vector3D Converted_Spacing = mitkImage3D->GetGeometry()->GetSpacing(); error = abs(Converted_Spacing[0] - Original_Spacing[0]) + abs(Converted_Spacing[1] - Original_Spacing[1]) + abs(Converted_Spacing[2] - Original_Spacing[2]) ; MITK_TEST_CONDITION_REQUIRED( error < eps , "Compare Geometry: Spacing"); mitk::Point3D Converted_Origin = mitkImage3D->GetGeometry()->GetOrigin(); error = abs(Converted_Origin[0] - Original_Origin[0]) + abs(Converted_Origin[1] - Original_Origin[1]) + abs(Converted_Origin[2] - Original_Origin[2]) ; MITK_INFO << Converted_Origin << " and " << Original_Origin; MITK_TEST_CONDITION_REQUIRED( error < eps , "Compare Geometry: Origin"); mitk::Vector3D Converted_col0, Converted_col1, Converted_col2; Converted_col0.SetVnlVector(mitkImage3D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(0)); Converted_col1.SetVnlVector(mitkImage3D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(1)); Converted_col2.SetVnlVector(mitkImage3D->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)); if ( (abs(Original_col0[0] - Converted_col0[0]) > eps) || (abs(Original_col0[1] - Converted_col0[1]) > eps) || (abs(Original_col0[2] - Converted_col0[2]) > eps) || (abs(Original_col1[0] - Converted_col1[0]) > eps) || (abs(Original_col1[1] - Converted_col1[1]) > eps) || (abs(Original_col1[2] - Converted_col1[2]) > eps) || (abs(Original_col2[0] - Converted_col2[0]) > eps) || (abs(Original_col2[1] - Converted_col2[1]) > eps) || (abs(Original_col2[2] - Converted_col2[2]) > eps) ) { MITK_INFO << "Oh No! Original Image Matrix and Converted Image Matrix are different!"; MITK_INFO << "original Image:" << Original_col0 << " " << Original_col1 << " " << Original_col2; MITK_INFO << "converted Image:" << Converted_col0 << " " << Converted_col1 << " " << Converted_col2; matrixIsEqual = false; } else matrixIsEqual = true; MITK_TEST_CONDITION_REQUIRED( matrixIsEqual , "Compare Geometry: Matrix"); /////////////////////////////////////// // So far it seems good! now try to save and load the file std::stringstream sstream2; - sstream2 << MITK_TEST_OUTPUT_DIR << "" << "/rotatedImage"; - imageWriter->SetInput(mitkImage3D); - imageWriter->SetFileName(sstream2.str().c_str()); - imageWriter->SetExtension(".nrrd"); - imageWriter->Write(); - sstream2 << ".nrrd"; - imageReader->SetFileName(sstream2.str().c_str()); - imageReader->Update(); - mitk::Image::Pointer imageLoaded = imageReader->GetOutput(); + sstream2 << MITK_TEST_OUTPUT_DIR << "" << "/rotatedImage.nrrd"; + mitk::FileWriterRegistry::Write(mitkImage3D, sstream2.str()); + mitk::Image::Pointer imageLoaded = mitk::FileReaderRegistry::Read(sstream2.str()); // check if image can be loaded MITK_TEST_CONDITION_REQUIRED( imageLoaded.IsNotNull() , "Loading saved Image"); // check if loaded image is still what it should be: MITK_TEST_CONDITION_REQUIRED( imageLoaded->GetDimension() == 3 , "Loaded Image is Dimension 3"); // check if geometry is still same mitk::Vector3D Loaded_Spacing = imageLoaded->GetGeometry()->GetSpacing(); error = abs(Loaded_Spacing[0] - Original_Spacing[0]) + abs(Loaded_Spacing[1] - Original_Spacing[1]) + abs(Loaded_Spacing[2] - Original_Spacing[2]) ; MITK_TEST_CONDITION_REQUIRED( error < eps , "Compare Geometry: Spacing"); mitk::Point3D Loaded_Origin = imageLoaded->GetGeometry()->GetOrigin(); error = abs(Loaded_Origin[0] - Original_Origin[0]) + abs(Loaded_Origin[1] - Original_Origin[1]) + abs(Loaded_Origin[2] - Original_Origin[2]) ; MITK_TEST_CONDITION_REQUIRED( error < eps , "Compare Geometry: Origin"); mitk::Vector3D Loaded_col0, Loaded_col1, Loaded_col2; Loaded_col0.SetVnlVector(imageLoaded->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(0)); Loaded_col1.SetVnlVector(imageLoaded->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(1)); Loaded_col2.SetVnlVector(imageLoaded->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)); if ( (abs(Original_col0[0] - Loaded_col0[0]) > eps) || (abs(Original_col0[1] - Loaded_col0[1]) > eps) || (abs(Original_col0[2] - Loaded_col0[2]) > eps) || (abs(Original_col1[0] - Loaded_col1[0]) > eps) || (abs(Original_col1[1] - Loaded_col1[1]) > eps) || (abs(Original_col1[2] - Loaded_col1[2]) > eps) || (abs(Original_col2[0] - Loaded_col2[0]) > eps) || (abs(Original_col2[1] - Loaded_col2[1]) > eps) || (abs(Original_col2[2] - Loaded_col2[2]) > eps) ) { MITK_INFO << "Oh No! Original Image Matrix and Converted Image Matrix are different!"; MITK_INFO << "original Image:" << Original_col0 << " " << Original_col1 << " " << Original_col2; MITK_INFO << "converted Image:" << Loaded_col0 << " " << Loaded_col1 << " " << Loaded_col2; matrixIsEqual = false; } else matrixIsEqual = true; MITK_TEST_CONDITION_REQUIRED( matrixIsEqual , "Compare Geometry: Matrix"); return 0; MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkImageTest.cpp b/Core/Code/Testing/mitkImageTest.cpp index 5e6f003e50..50bcf1f6a9 100644 --- a/Core/Code/Testing/mitkImageTest.cpp +++ b/Core/Code/Testing/mitkImageTest.cpp @@ -1,497 +1,493 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // mitk includes #include #include #include -#include "mitkItkImageFileReader.h" #include #include #include "mitkImageGenerator.h" #include "mitkImageReadAccessor.h" #include "mitkException.h" +#include "mitkFileReaderRegistry.h" // itk includes #include #include // stl includes #include // vtk includes #include // Checks if reference count is correct after using GetVtkImageData() bool ImageVtkDataReferenceCheck(const char* fname) { const std::string filename = std::string(fname); - mitk::ItkImageFileReader::Pointer imageReader = mitk::ItkImageFileReader::New(); + try { - imageReader->SetFileName(filename); - imageReader->Update(); - } - catch(...) { - MITK_TEST_FAILED_MSG(<< "Could not read file for testing: " << filename); - return false; - } + mitk::Image::Pointer image = mitk::FileReaderRegistry::Read(filename); + MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(), "Non-NULL image") - { - mitk::Image::Pointer image = imageReader->GetOutput(); vtkImageData* vtk = image->GetVtkImageData(); if(vtk == NULL) return false; } + catch(...) + { + MITK_TEST_FAILED_MSG(<< "Could not read file for testing: " << filename); + return false; + } return true; } class mitkImageTestClass { public: void SetClonedGeometry_None_ClonedEqualInput() { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(100, 100, 100, 1, 0.2, 0.3, 0.4); //----------------- // geometry information for image mitk::Point3D origin; mitk::Vector3D right, bottom; mitk::Vector3D spacing; mitk::FillVector3D(origin, 17.0, 19.92, 7.83); mitk::FillVector3D(right, 1.0, 2.0, 3.0); mitk::FillVector3D(bottom, 0.0, -3.0, 2.0); mitk::FillVector3D(spacing, 0.78, 0.91, 2.23); //InitializeStandardPlane(rightVector, downVector, spacing) mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); planegeometry->InitializeStandardPlane(100, 100, right, bottom, &spacing); planegeometry->SetOrigin(origin); planegeometry->ChangeImageGeometryConsideringOriginOffset(true); image->SetClonedGeometry(planegeometry); mitk::Geometry3D::Pointer imageGeometry = image->GetGeometry(); itk::ScalableAffineTransform* frameNew = imageGeometry->GetIndexToWorldTransform(); itk::ScalableAffineTransform* frameOld = planegeometry->GetIndexToWorldTransform(); bool matrixEqual = true; for (int i = 0; i < 16; ++i) { double valueNew = *(frameNew->GetMatrix()[i]); double valueOld = *(frameOld->GetMatrix()[i]); //MITK_INFO << "Index: " << i << " Old: " << valueOld << " New: " << valueNew << " Difference:" << valueOld-valueNew<< std::endl; matrixEqual = matrixEqual && mitk::Equal(valueNew, valueOld, mitk::eps); } // Disabled because this test fails on the dashboard. Does not fail on my machine. // See Bug 6505 // MITK_TEST_CONDITION(matrixEqual, "Matrix elements of cloned matrix equal original matrix"); } }; int mitkImageTest(int argc, char* argv[]) { MITK_TEST_BEGIN(mitkImageTest); mitkImageTestClass tester; tester.SetClonedGeometry_None_ClonedEqualInput(); //Create Image out of nowhere mitk::Image::Pointer imgMem = mitk::Image::New(); mitk::PixelType pt = mitk::MakeScalarPixelType(); unsigned int dim[]={100,100,20}; MITK_TEST_CONDITION_REQUIRED( imgMem.IsNotNull(), "An image was created. "); // Initialize image imgMem->Initialize( pt, 3, dim); MITK_TEST_CONDITION_REQUIRED( imgMem->IsInitialized(), "Image::IsInitialized() ?"); MITK_TEST_CONDITION_REQUIRED( imgMem->GetPixelType() == pt, "PixelType was set correctly."); int *p; int *p2; try { mitk::ImageReadAccessor imgMemAcc(imgMem); p = (int*)imgMemAcc.GetData(); } catch (mitk::Exception& e) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION( p != NULL, "GetData() returned not-NULL pointer."); // filling image const unsigned int size = dim[0]*dim[1]*dim[2]; for(unsigned int i=0; iGetSliceData(dim[2]/2)); p2 = (int*)imgMemAcc.GetData(); } catch (mitk::Exception& e) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION_REQUIRED( p2 != NULL, "Valid slice data returned"); unsigned int xy_size = dim[0]*dim[1]; unsigned int start_mid_slice = (dim[2]/2)*xy_size; isEqual = true; for(unsigned int i=0; i(); imgMem->Initialize( pType , 3, dim); MITK_TEST_CONDITION_REQUIRED(imgMem->GetDimension()== 3, "Testing initialization parameter dimension!"); MITK_TEST_CONDITION_REQUIRED(imgMem->GetPixelType() == pType, "Testing initialization parameter pixeltype!"); MITK_TEST_CONDITION_REQUIRED(imgMem->GetDimension(0) == dim[0] && imgMem->GetDimension(1)== dim[1] && imgMem->GetDimension(2)== dim[2], "Testing initialization of dimensions!"); MITK_TEST_CONDITION( imgMem->IsInitialized(), "Image is initialized."); // Setting volume again: try { mitk::ImageReadAccessor imgMemAcc(imgMem); imgMem->SetVolume(imgMemAcc.GetData()); } catch (mitk::Exception& e) { MITK_ERROR << e.what(); } //----------------- // geometry information for image mitk::Point3D origin; mitk::Vector3D right, bottom; mitk::Vector3D spacing; mitk::FillVector3D(origin, 17.0, 19.92, 7.83); mitk::FillVector3D(right, 1.0, 2.0, 3.0); mitk::FillVector3D(bottom, 0.0, -3.0, 2.0); mitk::FillVector3D(spacing, 0.78, 0.91, 2.23); //InitializeStandardPlane(rightVector, downVector, spacing) mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); planegeometry->InitializeStandardPlane(100, 100, right, bottom, &spacing); planegeometry->SetOrigin(origin); // Testing Initialize(const mitk::PixelType& type, const mitk::Geometry3D& geometry, unsigned int slices) with PlaneGeometry and GetData(): "; imgMem->Initialize( mitk::MakePixelType(), *planegeometry); MITK_TEST_CONDITION_REQUIRED( imgMem->GetGeometry()->GetOrigin() == static_cast(planegeometry)->GetOrigin(), "Testing correct setting of geometry via initialize!"); try { mitk::ImageReadAccessor imgMemAcc(imgMem); p = (int*)imgMemAcc.GetData(); } catch (mitk::Exception& e) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION_REQUIRED( p!=NULL, "GetData() returned valid pointer."); // Testing Initialize(const mitk::PixelType& type, int sDim, const mitk::PlaneGeometry& geometry) and GetData(): "; imgMem->Initialize( mitk::MakePixelType() , 40, *planegeometry); try { mitk::ImageReadAccessor imgMemAcc(imgMem); p = (int*)imgMemAcc.GetData(); } catch (mitk::Exception& e) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION_REQUIRED( p != NULL, "GetData() returned valid pointer."); //----------------- // testing origin information and methods MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetGeometry()->GetOrigin(), origin), "Testing correctness of origin via GetGeometry()->GetOrigin(): "); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetTimeSlicedGeometry()->GetOrigin(), origin), "Testing correctness of origin via GetTimeSlicedGeometry()->GetOrigin(): "); // Setting origin via SetOrigin(origin): "; mitk::FillVector3D(origin, 37.0, 17.92, 27.83); imgMem->SetOrigin(origin); // Test origin MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetGeometry()->GetOrigin(), origin), "Testing correctness of changed origin via GetGeometry()->GetOrigin(): "); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetTimeSlicedGeometry()->GetOrigin(), origin), "Testing correctness of changed origin via GetTimeSlicedGeometry()->GetOrigin(): "); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetSlicedGeometry()->GetGeometry2D(0)->GetOrigin(), origin), "Testing correctness of changed origin via GetSlicedGeometry()->GetGeometry2D(0)->GetOrigin(): "); //----------------- // testing spacing information and methods MITK_TEST_CONDITION_REQUIRED(mitk::Equal(imgMem->GetGeometry()->GetSpacing(), spacing), "Testing correct spacing from Geometry3D!"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(imgMem->GetTimeSlicedGeometry()->GetSpacing(), spacing), "Testing correctspacing from TimeSlicedGeometry!"); mitk::FillVector3D(spacing, 7.0, 0.92, 1.83); imgMem->SetSpacing(spacing); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetGeometry()->GetSpacing(), spacing), "Testing correctness of changed spacing via GetGeometry()->GetSpacing(): "); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetTimeSlicedGeometry()->GetSpacing(), spacing), "Testing correctness of changed spacing via GetTimeSlicedGeometry()->GetSpacing(): "); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetSlicedGeometry()->GetGeometry2D(0)->GetSpacing(), spacing), "Testing correctness of changed spacing via GetSlicedGeometry()->GetGeometry2D(0)->GetSpacing(): "); mitk::Image::Pointer vecImg = mitk::Image::New(); try { mitk::ImageReadAccessor imgMemAcc(imgMem); vecImg->Initialize( imgMem->GetPixelType(), *imgMem->GetGeometry(), 2 /* #channels */, 0 /*tDim*/ ); vecImg->SetImportChannel(const_cast(imgMemAcc.GetData()), 0, mitk::Image::CopyMemory ); vecImg->SetImportChannel(const_cast(imgMemAcc.GetData()), 1, mitk::Image::CopyMemory ); mitk::ImageReadAccessor vecImgAcc(vecImg); mitk::ImageReadAccessor vecImgAcc0(vecImg, vecImg->GetChannelData(0)); mitk::ImageReadAccessor vecImgAcc1(vecImg, vecImg->GetChannelData(1)); MITK_TEST_CONDITION_REQUIRED(vecImgAcc0.GetData() != NULL && vecImgAcc1.GetData() != NULL, "Testing set and return of channel data!"); MITK_TEST_CONDITION_REQUIRED( vecImg->IsValidSlice(0,0,1) , ""); MITK_TEST_OUTPUT(<< " Testing whether CopyMemory worked"); MITK_TEST_CONDITION_REQUIRED(imgMemAcc.GetData() != vecImgAcc.GetData(), ""); MITK_TEST_OUTPUT(<< " Testing destruction after SetImportChannel"); vecImg = NULL; MITK_TEST_CONDITION_REQUIRED(vecImg.IsNull() , "testing destruction!"); } catch (mitk::Exception& e) { MITK_ERROR << e.what(); } //----------------- MITK_TEST_OUTPUT(<< "Testing initialization via vtkImageData"); MITK_TEST_OUTPUT(<< " Setting up vtkImageData"); vtkImageData* vtkimage = vtkImageData::New(); vtkimage->Initialize(); vtkimage->SetDimensions( 2, 3, 4); double vtkorigin[] = {-350,-358.203, -1363.5}; vtkimage->SetOrigin(vtkorigin); mitk::Point3D vtkoriginAsMitkPoint; mitk::vtk2itk(vtkorigin, vtkoriginAsMitkPoint); double vtkspacing[] = {1.367, 1.367, 2}; vtkimage->SetSpacing(vtkspacing); vtkimage->SetScalarType( VTK_SHORT ); vtkimage->AllocateScalars(); std::cout<<"[PASSED]"<Initialize(vtkimage); MITK_TEST_CONDITION_REQUIRED(mitkByVtkImage->IsInitialized(), ""); vtkimage->Delete(); MITK_TEST_OUTPUT(<< " Testing whether spacing has been correctly initialized from vtkImageData"); mitk::Vector3D spacing2 = mitkByVtkImage->GetGeometry()->GetSpacing(); mitk::Vector3D vtkspacingAsMitkVector; mitk::vtk2itk(vtkspacing, vtkspacingAsMitkVector); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(spacing2,vtkspacingAsMitkVector), ""); MITK_TEST_OUTPUT(<< " Testing whether GetSlicedGeometry(0)->GetOrigin() has been correctly initialized from vtkImageData"); mitk::Point3D origin2 = mitkByVtkImage->GetSlicedGeometry(0)->GetOrigin(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(origin2,vtkoriginAsMitkPoint), ""); MITK_TEST_OUTPUT(<< " Testing whether GetGeometry()->GetOrigin() has been correctly initialized from vtkImageData"); origin2 = mitkByVtkImage->GetGeometry()->GetOrigin(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(origin2,vtkoriginAsMitkPoint), ""); MITK_TEST_OUTPUT(<< " Testing whether GetTimeSlicedGeometry()->GetOrigin() has been correctly initialized from vtkImageData"); origin2 = mitkByVtkImage->GetTimeSlicedGeometry()->GetOrigin(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(origin2,vtkoriginAsMitkPoint), ""); // TODO test the following initializers on channel-incorporation // void mitk::Image::Initialize(const mitk::PixelType& type, unsigned int dimension, unsigned int *dimensions, unsigned int channels) // void mitk::Image::Initialize(const mitk::PixelType& type, int sDim, const mitk::Geometry2D& geometry2d, bool flipped, unsigned int channels, int tDim ) // void mitk::Image::Initialize(const mitk::Image* image) // void mitk::Image::Initialize(const mitkIpPicDescriptor* pic, int channels, int tDim, int sDim) //mitk::Image::Pointer vecImg = mitk::Image::New(); //vecImg->Initialize(PixelType(typeid(float), 6, itk::ImageIOBase::SYMMETRICSECONDRANKTENSOR), *imgMem->GetGeometry(), 2 /* #channels */, 0 /*tDim*/, false /*shiftBoundingBoxMinimumToZero*/ ); //vecImg->Initialize(PixelType(typeid(itk::Vector)), *imgMem->GetGeometry(), 2 /* #channels */, 0 /*tDim*/, false /*shiftBoundingBoxMinimumToZero*/ ); // testing access by index coordinates and by world coordinates MITK_TEST_CONDITION_REQUIRED(argc == 2, "Check if test image is accessible!"); const std::string filename = std::string(argv[1]); - mitk::ItkImageFileReader::Pointer imageReader = mitk::ItkImageFileReader::New(); + mitk::Image::Pointer image; try { - imageReader->SetFileName(filename); - imageReader->Update(); + mitk::Image::Pointer image = mitk::FileReaderRegistry::Read(filename); + MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(), "Non-NULL image") } catch(...) { MITK_TEST_FAILED_MSG(<< "Could not read file for testing: " << filename); return 0; } - mitk::Image::Pointer image = imageReader->GetOutput(); - // generate a random point in world coordinates mitk::Point3D xMax, yMax, zMax, xMaxIndex, yMaxIndex, zMaxIndex; xMaxIndex.Fill(0.0f); yMaxIndex.Fill(0.0f); zMaxIndex.Fill(0.0f); xMaxIndex[0] = image->GetLargestPossibleRegion().GetSize()[0]; yMaxIndex[1] = image->GetLargestPossibleRegion().GetSize()[1]; zMaxIndex[2] = image->GetLargestPossibleRegion().GetSize()[2]; image->GetGeometry()->IndexToWorld(xMaxIndex, xMax); image->GetGeometry()->IndexToWorld(yMaxIndex, yMax); image->GetGeometry()->IndexToWorld(zMaxIndex, zMax); MITK_INFO << "Origin " << image->GetGeometry()->GetOrigin()[0] << " "<< image->GetGeometry()->GetOrigin()[1] << " "<< image->GetGeometry()->GetOrigin()[2] << ""; MITK_INFO << "MaxExtend " << xMax[0] << " "<< yMax[1] << " "<< zMax[2] << ""; mitk::Point3D point; itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randomGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New(); randomGenerator->Initialize( std::rand() ); // initialize with random value, to get sensible random points for the image point[0] = randomGenerator->GetUniformVariate( image->GetGeometry()->GetOrigin()[0], xMax[0]); point[1] = randomGenerator->GetUniformVariate( image->GetGeometry()->GetOrigin()[1], yMax[1]); point[2] = randomGenerator->GetUniformVariate( image->GetGeometry()->GetOrigin()[2], zMax[2]); MITK_INFO << "RandomPoint " << point[0] << " "<< point[1] << " "<< point[2] << ""; // test values and max/min mitk::ScalarType imageMin = image->GetStatistics()->GetScalarValueMin(); mitk::ScalarType imageMax = image->GetStatistics()->GetScalarValueMax(); mitk::ScalarType value = image->GetPixelValueByWorldCoordinate(point); MITK_INFO << imageMin << " "<< imageMax << " "<< value << ""; MITK_TEST_CONDITION( (value >= imageMin && value <= imageMax), "Value returned is between max/min"); // test accessing PixelValue with coordinate leading to a negative index const mitk::Point3D geom_origin = image->GetGeometry()->GetOrigin(); const mitk::Point3D geom_center = image->GetGeometry()->GetCenter(); const unsigned int timestep = 0; // shift position from origin outside of the image ( in the opposite direction to [center-origin] vector which points in the inside) mitk::Point3D position = geom_origin + (geom_origin - geom_center); MITK_TEST_CONDITION_REQUIRED( image->GetPixelValueByWorldCoordinate(position, timestep) == 0, "Test access to the outside of the image") // testing the clone method of mitk::Image mitk::Image::Pointer cloneImage = image->Clone(); MITK_TEST_CONDITION_REQUIRED(cloneImage->GetDimension() == image->GetDimension(), "Clone (testing dimension)"); MITK_TEST_CONDITION_REQUIRED(cloneImage->GetPixelType() == image->GetPixelType(), "Clone (testing pixel type)"); // After cloning an image the geometry of both images should be equal too MITK_TEST_CONDITION_REQUIRED(cloneImage->GetGeometry()->GetOrigin() == image->GetGeometry()->GetOrigin(), "Clone (testing origin)"); MITK_TEST_CONDITION_REQUIRED(cloneImage->GetGeometry()->GetSpacing() == image->GetGeometry()->GetSpacing(), "Clone (testing spacing)"); MITK_TEST_CONDITION_REQUIRED(mitk::MatrixEqualElementWise(cloneImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(), image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix()), "Clone (testing transformation matrix)"); MITK_TEST_CONDITION_REQUIRED(mitk::MatrixEqualElementWise(cloneImage->GetTimeSlicedGeometry()->GetGeometry3D(cloneImage->GetDimension(3)-1)->GetIndexToWorldTransform()->GetMatrix(), cloneImage->GetTimeSlicedGeometry()->GetGeometry3D(image->GetDimension(3)-1)->GetIndexToWorldTransform()->GetMatrix()), "Clone(testing time sliced geometry)"); for (unsigned int i = 0u; i < cloneImage->GetDimension(); ++i) { MITK_TEST_CONDITION_REQUIRED(cloneImage->GetDimension(i) == image->GetDimension(i), "Clone (testing dimension " << i << ")"); } //access via itk if(image->GetDimension()> 3) // CastToItk only works with 3d images so we need to check for 4d images { mitk::ImageTimeSelector::Pointer selector = mitk::ImageTimeSelector::New(); selector->SetTimeNr(0); selector->SetInput(image); selector->Update(); image = selector->GetOutput(); } if(image->GetDimension()==3) { typedef itk::Image ItkFloatImage3D; ItkFloatImage3D::Pointer itkimage; mitk::CastToItkImage(image, itkimage); MITK_TEST_CONDITION_REQUIRED(itkimage.IsNotNull(), "Test conversion to itk::Image!"); mitk::Point3D itkPhysicalPoint; image->GetGeometry()->WorldToItkPhysicalPoint(point, itkPhysicalPoint); MITK_INFO << "ITKPoint " << itkPhysicalPoint[0] << " "<< itkPhysicalPoint[1] << " "<< itkPhysicalPoint[2] << ""; mitk::Point3D backTransformedPoint; image->GetGeometry()->ItkPhysicalPointToWorld(itkPhysicalPoint, backTransformedPoint); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(point,backTransformedPoint), "Testing world->itk-physical->world consistency"); itk::Index<3> idx; bool status = itkimage->TransformPhysicalPointToIndex(itkPhysicalPoint, idx); MITK_INFO << "ITK Index " << idx[0] << " "<< idx[1] << " "<< idx[2] << ""; if(status) { float valByItk = itkimage->GetPixel(idx); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(valByItk, value), "Compare value of pixel returned by mitk in comparison to itk"); } else { MITK_WARN<< "Index is out buffered region!"; } } else { MITK_INFO << "Image does not contain three dimensions, some test cases are skipped!"; } // clone generated 3D image with one slice in z direction (cf. bug 11058) unsigned int* threeDdim = new unsigned int[3]; threeDdim[0] = 100; threeDdim[1] = 200; threeDdim[2] = 1; mitk::Image::Pointer threeDImage = mitk::Image::New(); threeDImage->Initialize(mitk::MakeScalarPixelType(), 3, threeDdim); mitk::Image::Pointer cloneThreeDImage = threeDImage->Clone(); // check that the clone image has the same dimensionality as the source image MITK_TEST_CONDITION_REQUIRED( cloneThreeDImage->GetDimension() == 3, "Testing if the clone image initializes with 3D!"); MITK_TEST_CONDITION_REQUIRED( ImageVtkDataReferenceCheck(argv[1]), "Checking reference count of Image after using GetVtkImageData()"); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkImageTimeSelectorTest.cpp b/Core/Code/Testing/mitkImageTimeSelectorTest.cpp index 55bbdefde8..2f14572a54 100644 --- a/Core/Code/Testing/mitkImageTimeSelectorTest.cpp +++ b/Core/Code/Testing/mitkImageTimeSelectorTest.cpp @@ -1,90 +1,61 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkImage.h" -#include "mitkDataNodeFactory.h" #include "mitkImageTimeSelector.h" +#include "mitkIOUtil.h" +#include "mitkTestingMacros.h" + +#include + #include -#include + int mitkImageTimeSelectorTest(int argc, char* argv[]) { + MITK_TEST_BEGIN(ImageTimeSelector) - std::cout << "Loading file: "; if(argc==0) { - std::cout<<"no file specified [FAILED]"<SetFileName( argv[1] ); - factory->Update(); - - if(factory->GetNumberOfOutputs()<1) - { - std::cout<<"file could not be loaded [FAILED]"<GetOutput( 0 ); + mitk::DataNode::Pointer node = mitk::IOUtil::LoadDataNode(argv[1]); image = dynamic_cast(node->GetData()); - if(image.IsNull()) - { - std::cout<<"file not an image - test will not be applied [PASSED]"<SetInput(image); timeSelector->SetTimeNr( 0 ); timeSelector->UpdateLargestPossibleRegion(); mitk::Image::Pointer result = timeSelector->GetOutput(); - std::cout << "Testing IsInitialized(): "; - if(result->IsInitialized()==false) - { - std::cout<<"[FAILED]"<DisconnectPipeline(); - //timeSelector = NULL; - - if( result->IsVolumeSet(0) == false) - { - std::cout<<"[FAILED]"<IsInitialized(), "Testin IsInitialized()") + MITK_TEST_CONDITION(result->IsVolumeSet(0), "Test IsVolumeSet(0)") - std::cout<<"[TEST DONE]"< #include "mitkIOUtil.h" +#include "mitkFileWriterRegistry.h" + +#include "itksys/SystemTools.hxx" #include #include #ifdef WIN32 #include "process.h" #else #include #endif std::string AppendExtension(const std::string &filename, const char *extension) { std::string new_filename = filename; new_filename += extension; return new_filename; } bool CompareImageMetaData( mitk::Image::Pointer image, mitk::Image::Pointer reference, bool checkPixelType = true ) { // switch to AreIdentical() methods as soon as Bug 11925 (Basic comparison operators) is fixed if( image->GetDimension() != reference->GetDimension() ) { MITK_ERROR << "The image dimension differs: IN (" << image->GetDimension() << ") REF(" << reference->GetDimension() << ")"; return false; } // pixel type if( checkPixelType && ( image->GetPixelType() != reference->GetPixelType() && image->GetPixelType().GetBitsPerComponent() != reference->GetPixelType().GetBitsPerComponent() ) ) { MITK_ERROR << "Pixeltype differs ( image=" << image->GetPixelType().GetPixelTypeAsString() << "[" << image->GetPixelType().GetBitsPerComponent() << "]" << " reference=" << reference->GetPixelType().GetPixelTypeAsString() << "[" << reference->GetPixelType().GetBitsPerComponent() << "]" << " )"; return false; } return true; } /* Test writing picture formats like *.bmp, *.png, *.tiff or *.jpg NOTE: Saving as picture format must ignore PixelType comparison - not all bits per components are supported (see specification of the format) */ void TestPictureWriting(mitk::Image* image, const std::string& filename, const std::string& extension) { - mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New(); - myImageWriter->SetFileName(AppendExtension(filename, extension.c_str()) ); - myImageWriter->SetFilePrefix("pref"); - myImageWriter->SetFilePattern("pattern"); - myImageWriter->SetInput(image); - + const std::string fullFileName = AppendExtension(filename, extension.c_str()); - mitk::Image::Pointer singleSliceImage = NULL; + mitk::Image::Pointer singleSliceImage = NULL; if( image->GetDimension() == 3 ) { mitk::ExtractSliceFilter::Pointer extractFilter = mitk::ExtractSliceFilter::New(); extractFilter->SetInput( image ); extractFilter->SetWorldGeometry( image->GetSlicedGeometry()->GetGeometry2D(0) ); extractFilter->Update(); singleSliceImage = extractFilter->GetOutput(); // test 3D writing in format supporting only 2D - myImageWriter->Update(); + mitk::FileWriterRegistry::Write(image, fullFileName); // test images unsigned int foundImagesCount = 0; //if the image only contains one sinlge slice the itkImageSeriesWriter won't add a number like filename.XX.extension if(image->GetDimension(2) == 1) { std::stringstream series_filenames; series_filenames << filename << extension; mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage( series_filenames.str() ); if( compareImage.IsNotNull() ) { foundImagesCount++; MITK_TEST_CONDITION(CompareImageMetaData( singleSliceImage, compareImage, false ), "Image meta data unchanged after writing and loading again. "); //ignore bits per component } remove( series_filenames.str().c_str() ); } else //test the whole slice stack { for( unsigned int i=0; i< image->GetDimension(2); i++) { std::stringstream series_filenames; series_filenames << filename << "." << i+1 << extension; mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage( series_filenames.str() ); if( compareImage.IsNotNull() ) { foundImagesCount++; MITK_TEST_CONDITION(CompareImageMetaData( singleSliceImage, compareImage, false ), "Image meta data unchanged after writing and loading again. "); //ignore bits per component } remove( series_filenames.str().c_str() ); } } MITK_TEST_CONDITION( foundImagesCount == image->GetDimension(2), "All 2D-Slices of a 3D image were stored correctly."); } else if( image->GetDimension() == 2 ) { singleSliceImage = image; } // test 2D writing if( singleSliceImage.IsNotNull() ) { try { - myImageWriter->SetInput( singleSliceImage ); - myImageWriter->Update(); + mitk::FileWriterRegistry::Write(singleSliceImage, fullFileName); - mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage( AppendExtension(filename, extension.c_str()).c_str()); + mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(fullFileName.c_str()); MITK_TEST_CONDITION_REQUIRED( compareImage.IsNotNull(), "Image stored was succesfully loaded again"); MITK_TEST_CONDITION_REQUIRED( CompareImageMetaData(singleSliceImage, compareImage, false ), "Image meta data unchanged after writing and loading again. ");//ignore bits per component remove(AppendExtension(filename, extension.c_str()).c_str()); } catch(itk::ExceptionObject &e) { MITK_TEST_FAILED_MSG(<< "Exception during file writing for ." << extension << ": " << e.what() ); } } } /** * test for "ImageWriter". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkImageWriterTest(int argc , char* argv[]) { // always start with this! MITK_TEST_BEGIN("ImageWriter") - // let's create an object of our class - mitk::ImageWriter::Pointer myImageWriter = mitk::ImageWriter::New(); - - // first test: did this work? - // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since - // it makes no sense to continue without an object. - MITK_TEST_CONDITION_REQUIRED(myImageWriter.IsNotNull(),"Testing instantiation") - // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! // load image MITK_TEST_CONDITION_REQUIRED(argc > 1, "File to load has been specified"); mitk::Image::Pointer image = NULL; try { MITK_TEST_OUTPUT(<< "Loading file: " << argv[1]); image = mitk::IOUtil::LoadImage( argv[1] ); } catch (itk::ExceptionObject & ex) { MITK_TEST_FAILED_MSG(<< "Exception during file loading: " << ex.GetDescription()); } MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"loaded image not NULL") - std::stringstream filename_stream; - -#ifdef WIN32 - filename_stream << "test" << _getpid(); -#else - filename_stream << "test" << getpid(); -#endif + mitk::FileWriterRegistry writerRegistry; - std::string filename = filename_stream.str(); - std::cout << filename << std::endl; - - // test set/get methods - myImageWriter->SetInput(image); - MITK_TEST_CONDITION_REQUIRED(myImageWriter->GetInput()==image,"test Set/GetInput()"); - myImageWriter->SetFileName(filename); - MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFileName(),filename.c_str()),"test Set/GetFileName()"); - myImageWriter->SetFilePrefix("pref"); - MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFilePrefix(),"pref"),"test Set/GetFilePrefix()"); - myImageWriter->SetFilePattern("pattern"); - MITK_TEST_CONDITION_REQUIRED(!strcmp(myImageWriter->GetFilePattern(),"pattern"),"test Set/GetFilePattern()"); + std::ofstream tmpStream; + std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream); + tmpStream.close(); // write ITK .mhd image (2D and 3D only) if( image->GetDimension() <= 3 ) { try { - myImageWriter->SetExtension(".mhd"); - myImageWriter->Update(); + mitk::IFileWriter* writer = writerRegistry.GetWriter(mitk::Image::GetStaticNameOfClass(), ".mhd"); + writer->Write(image, tmpFilePath); - mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage( AppendExtension(filename, ".mhd").c_str() ); + mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(tmpFilePath); MITK_TEST_CONDITION_REQUIRED( compareImage.IsNotNull(), "Image stored in MHD format was succesfully loaded again! "); - std::string rawExtension = ".raw"; - std::fstream rawPartIn; - rawPartIn.open(AppendExtension(filename, ".raw").c_str()); - if( !rawPartIn.is_open() ) - { - rawExtension = ".zraw"; - rawPartIn.open(AppendExtension(filename, ".zraw").c_str()); - } - - MITK_TEST_CONDITION_REQUIRED(rawPartIn.is_open(),"Write .raw file"); - rawPartIn.close(); + MITK_TEST_CONDITION(itksys::SystemTools::FileExists((tmpFilePath + ".mhd").c_str()), ".mhd file exists") + MITK_TEST_CONDITION(itksys::SystemTools::FileExists((tmpFilePath + ".raw").c_str()) || + itksys::SystemTools::FileExists((tmpFilePath + ".zraw").c_str()), ".raw or .zraw exists") // delete - remove(AppendExtension(filename, ".mhd").c_str()); - remove(AppendExtension(filename, rawExtension.c_str()).c_str()); + remove((tmpFilePath + ".mhd").c_str()); + remove((tmpFilePath + ".raw").c_str()); + remove((tmpFilePath + ".zraw").c_str()); } catch (...) { MITK_TEST_FAILED_MSG(<< "Exception during .mhd file writing"); } } //testing more component image writing as nrrd files try { - myImageWriter->SetExtension(".nrrd"); - myImageWriter->Update(); + mitk::IFileWriter* writer = writerRegistry.GetWriter(mitk::Image::GetStaticNameOfClass(), ".nrrd"); + writer->Write(image, tmpFilePath); + std::fstream fin; - mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(AppendExtension(filename, ".nrrd").c_str()); + mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(AppendExtension(tmpFilePath, ".nrrd").c_str()); MITK_TEST_CONDITION_REQUIRED(compareImage.IsNotNull(), "Image stored in NRRD format was succesfully loaded again"); fin.close(); - remove(AppendExtension(filename, ".nrrd").c_str()); + remove(AppendExtension(tmpFilePath, ".nrrd").c_str()); } catch(...) { MITK_TEST_FAILED_MSG(<< "Exception during .nrrd file writing"); } - TestPictureWriting(image, filename, ".png"); - TestPictureWriting(image, filename, ".jpg"); - TestPictureWriting(image, filename, ".tiff"); - TestPictureWriting(image, filename, ".bmp"); + TestPictureWriting(image, tmpFilePath, ".png"); + TestPictureWriting(image, tmpFilePath, ".jpg"); + TestPictureWriting(image, tmpFilePath, ".tiff"); + TestPictureWriting(image, tmpFilePath, ".bmp"); // test for exception handling - try + std::vector writers = writerRegistry.GetWriters(mitk::Image::GetStaticNameOfClass()); + for (std::vector::const_iterator iter = writers.begin(), + end = writers.end(); iter != end; ++iter) { - MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject) - myImageWriter->SetInput(image); - myImageWriter->SetFileName("/usr/bin"); - myImageWriter->Update(); - MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject) - } - catch(...) { - //this means that a wrong exception (i.e. no itk:Exception) has been thrown - MITK_TEST_FAILED_MSG(<< "Wrong exception (i.e. no itk:Exception) caught during write"); + try + { + (*iter)->Write(image, "/usr/bin"); + MITK_TEST_FAILED_MSG( << "itk::ExceptionObject expected") + } + catch (const itk::ExceptionObject&) { /* this is expected */ } + catch(...) + { + //this means that a wrong exception (i.e. no itk:Exception) has been thrown + MITK_TEST_FAILED_MSG(<< "Wrong exception (i.e. no itk:Exception) caught during write"); + } } // always end with this! MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkNodeDependentPointSetInteractorTest.cpp b/Core/Code/Testing/mitkNodeDependentPointSetInteractorTest.cpp index abeb765d5d..afbd6b5c21 100644 --- a/Core/Code/Testing/mitkNodeDependentPointSetInteractorTest.cpp +++ b/Core/Code/Testing/mitkNodeDependentPointSetInteractorTest.cpp @@ -1,203 +1,198 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNodeDepententPointSetInteractor.h" #include "mitkPointSet.h" #include "mitkPositionEvent.h" #include "mitkVtkPropRenderer.h" #include "mitkStateEvent.h" #include "mitkInteractionConst.h" #include "mitkGlobalInteraction.h" #include "mitkPointOperation.h" #include "mitkTestingMacros.h" #include "mitkStandaloneDataStorage.h" -#include "mitkDataNodeFactory.h" #include "mitkStandardFileLocations.h" #include "mitkNodePredicateDataType.h" +#include "mitkIOUtil.h" void SendPositionEvent(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition, const mitk::Point3D& worldPosition) { mitk::Event *posEvent = new mitk::PositionEvent(sender, type, button, buttonState, key, displPosition, worldPosition); mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(posEvent); delete posEvent; } //test related to tutorial Step5.cpp int mitkNodeDependentPointSetInteractorTest(int argc, char* argv[]) { MITK_TEST_BEGIN("NodeDependentPointSetInteractor"); // Global interaction must(!) be initialized if used mitk::GlobalInteraction::GetInstance()->Initialize("global"); // Create a DataStorage mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); MITK_TEST_CONDITION_REQUIRED(ds.IsNotNull(),"Instantiating DataStorage"); //read two images and store to datastorage //these two images are used as node the interactors depend on. If the visibility property of one node if false, the //associated interactor may not change the data mitk::DataNode::Pointer node1, node2; - mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); MITK_TEST_CONDITION_REQUIRED(argc >= 3, "Test if a files to load has been specified"); try { //file 1 const std::string filename1 = argv[1]; - nodeReader->SetFileName(filename1); - nodeReader->Update(); - node1 = nodeReader->GetOutput(); + node1 = mitk::IOUtil::LoadDataNode(filename1); ds->Add(node1); //file 2 const std::string filename2 = argv[2]; - nodeReader->SetFileName(filename2); - nodeReader->Update(); - node2 = nodeReader->GetOutput(); + node2 = mitk::IOUtil::LoadDataNode(filename2); ds->Add(node2); } catch(...) { MITK_TEST_FAILED_MSG(<< "Could not read file for testing"); return EXIT_FAILURE; } //check for the two images mitk::NodePredicateDataType::Pointer predicate(mitk::NodePredicateDataType::New("Image")); mitk::DataStorage::SetOfObjects::ConstPointer allImagesInDS = ds->GetSubset(predicate); MITK_TEST_CONDITION_REQUIRED(allImagesInDS->Size()==2,"load images to data storage"); // Create PointSet and a node for it mitk::PointSet::Pointer pointSet1 = mitk::PointSet::New(); mitk::DataNode::Pointer pointSetNode1 = mitk::DataNode::New(); pointSetNode1->AddProperty( "unselectedcolor", mitk::ColorProperty::New(0.0f, 1.0f, 0.0f)); pointSetNode1->SetData(pointSet1); mitk::NodeDepententPointSetInteractor::Pointer interactor1 = mitk::NodeDepententPointSetInteractor::New("pointsetinteractor", pointSetNode1, node1); MITK_TEST_CONDITION_REQUIRED(interactor1.IsNotNull(),"Instanciating NodeDependentPointSetInteractor"); // Add the node to the tree ds->Add(pointSetNode1); mitk::GlobalInteraction::GetInstance()->AddInteractor(interactor1); mitk::PointSet::Pointer pointSet2 = mitk::PointSet::New(); mitk::DataNode::Pointer pointSetNode2 = mitk::DataNode::New(); pointSetNode2->AddProperty( "unselectedcolor", mitk::ColorProperty::New(0.0f, 0.0f, 1.0f)); pointSetNode2->SetData(pointSet2); mitk::NodeDepententPointSetInteractor::Pointer interactor2 = mitk::NodeDepententPointSetInteractor::New("pointsetinteractor", pointSetNode2, node2); MITK_TEST_CONDITION_REQUIRED(interactor2.IsNotNull(),"Instanciating NodeDependentPointSetInteractor"); // Add the node to the tree ds->Add(pointSetNode2); mitk::GlobalInteraction::GetInstance()->AddInteractor(interactor2); //check for the two pointsets mitk::NodePredicateDataType::Pointer predicatePS(mitk::NodePredicateDataType::New("PointSet")); mitk::DataStorage::SetOfObjects::ConstPointer allImagesInDSPS = ds->GetSubset(predicatePS); MITK_TEST_CONDITION_REQUIRED(allImagesInDSPS->Size()==2,"create associated pointsets to data storage"); //create two RenderWindows mitk::RenderingManager::Pointer myRenderingManager = mitk::RenderingManager::New(); vtkRenderWindow* vtkRenWin1 = vtkRenderWindow::New(); mitk::VtkPropRenderer::Pointer br1 = mitk::VtkPropRenderer::New("testingBR", vtkRenWin1, myRenderingManager); mitk::BaseRenderer::AddInstance(vtkRenWin1,br1); myRenderingManager->AddRenderWindow(vtkRenWin1); mitk::BaseRenderer::Pointer renderer1 = mitk::BaseRenderer::GetInstance(vtkRenWin1); vtkRenderWindow* vtkRenWin2 = vtkRenderWindow::New(); mitk::VtkPropRenderer::Pointer br2 = mitk::VtkPropRenderer::New("testingBR", vtkRenWin2, myRenderingManager); mitk::BaseRenderer::AddInstance(vtkRenWin2,br2); myRenderingManager->AddRenderWindow(vtkRenWin2); mitk::BaseRenderer::Pointer renderer2 = mitk::BaseRenderer::GetInstance(vtkRenWin2); //set properties for renderWindow 1 and 2 //1: node1->SetBoolProperty("visible", true, renderer1); node2->SetBoolProperty("visible", false, renderer1); //2: node1->SetBoolProperty("visible", false, renderer2); node2->SetBoolProperty("visible", true, renderer2); //*************************************************** //now start to test if only an event send from renderwindow 1 can interact with interactor 1 and vice versa MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==0,"Checking empty pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==0,"Checking empty pointset 2."); //sending an event to interactor1 mitk::Point3D pos3D; mitk::Point2D pos2D; pos3D[0]= 10.0; pos3D[1]= 20.0; pos3D[2]= 30.0; pos2D[0]= 100; pos2D[0]= 200; //add to pointset 1 SendPositionEvent(renderer1, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D); MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"1 Checking addition of point to pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==0,"2 Checking empty pointset 2"); //add to pointset 2 SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D); MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"3 Checking untouched state of pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==1,"4 Checking addition of point to pointset 2"); //add to pointset 2 SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D); MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"5 Checking untouched state of pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"6 Checking addition of point to pointset 2"); //add to pointset 2 SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D); MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"7 Checking untouched state of pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==3,"8 Checking addition of point to pointset 2"); //add to pointset 1 SendPositionEvent(renderer1, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D); MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==2,"9 Checking addition of point to pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==3,"10 Checking untouched state of pointset 2"); //trying to delete points mitk::Event* delEvent1 = new mitk::Event(renderer1, mitk::Type_KeyPress, mitk::BS_NoButton, mitk::BS_NoButton, mitk::Key_Delete); mitk::Event* delEvent2 = new mitk::Event(renderer2, mitk::Type_KeyPress, mitk::BS_NoButton, mitk::BS_NoButton, mitk::Key_Delete); mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent2); MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==2,"11 Checking untouched state of pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"12 Checking detected point in pointset 2"); mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent1); MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"11 Checking deleted point in pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"12 Checking untouched state of pointset 2"); mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent2); MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"13 Checking untouched state of pointset 1"); MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==1,"14 Checking detected point in pointset 2"); mitk::GlobalInteraction::GetInstance()->RemoveInteractor(interactor1); mitk::GlobalInteraction::GetInstance()->RemoveInteractor(interactor2); delete delEvent1; delete delEvent2; myRenderingManager->RemoveRenderWindow(vtkRenWin1); myRenderingManager->RemoveRenderWindow(vtkRenWin2); vtkRenWin1->Delete(); vtkRenWin2->Delete(); //destroy RenderingManager myRenderingManager = NULL; MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkPointSetFileIOTest.cpp b/Core/Code/Testing/mitkPointSetFileIOTest.cpp index 45b36258fe..e059d36493 100644 --- a/Core/Code/Testing/mitkPointSetFileIOTest.cpp +++ b/Core/Code/Testing/mitkPointSetFileIOTest.cpp @@ -1,162 +1,157 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPointSet.h" -#include "mitkPointSetWriter.h" -#include "mitkPointSetReader.h" #include "mitkTestingMacros.h" +#include "mitkFileReaderRegistry.h" +#include "mitkFileWriterRegistry.h" +#include "mitkIOUtil.h" + #include #include #include //unsigned int numberOfTestPointSets = 1; unsigned int numberOfTimeSeries = 5; // create one test PointSet class mitkPointSetFileIOTestClass { public: - std::vector m_SavedPointSet; + mitk::PointSet::Pointer m_SavedPointSet; + std::string m_FilePath; mitkPointSetFileIOTestClass() { } + ~mitkPointSetFileIOTestClass() + { + if (!m_FilePath.empty()) + { + std::remove(m_FilePath.c_str()); + } + } + mitk::PointSet::Pointer CreateTestPointSet() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); for (unsigned int t = 0; t < numberOfTimeSeries; t++) { unsigned int position(0); mitk::Point3D point; mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); pointSet->SetPoint(position, point, t); mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); ++position; pointSet->SetPoint(position, point, t); mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); ++position; pointSet->SetPoint(position, point, t); } - m_SavedPointSet.push_back(pointSet); + m_SavedPointSet = pointSet; return pointSet; } void PointSetCompare(mitk::PointSet::Pointer pointSet2, mitk::PointSet::Pointer pointSet1, bool& /*identical*/) { MITK_TEST_CONDITION(pointSet1->GetSize() == pointSet2->GetSize(), "Testing if PointSet size is correct" ); for (unsigned int t = 0; t < numberOfTimeSeries; t++) { for (unsigned int i = 0; i < (unsigned int) pointSet1->GetSize(t); ++i) { mitk::Point3D p1 = pointSet1->GetPoint(i); mitk::Point3D p2 = pointSet2->GetPoint(i); //test std::cout << "r point: " << p2 << std::endl; std::cout << "w point: " << p1 << std::endl; //test end MITK_TEST_CONDITION((p1[0] - p2[0]) <= 0.0001, "Testing if X coordinates of the Point are at the same Position" ); MITK_TEST_CONDITION((p1[1] - p2[1]) <= 0.0001, "Testing if Y coordinates of the Point are at the same Position" ); MITK_TEST_CONDITION((p1[2] - p2[2]) <= 0.0001, "Testing if Z coordinates of the Point are at the same Position" ); } } } - bool PointSetWrite(unsigned int numberOfPointSets) + bool PointSetWrite() { try { - m_SavedPointSet.clear(); - - mitk::PointSetWriter::Pointer pointSetWriter = mitk::PointSetWriter::New(); - pointSetWriter->SetFileName("test_pointset_new.mps"); + m_SavedPointSet = NULL; - for (unsigned int i = 0; i < numberOfPointSets; i++) - { - pointSetWriter->SetInput(i, CreateTestPointSet()); - } - - pointSetWriter->Write(); + std::ofstream tmpStream; + m_FilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream); + mitk::FileWriterRegistry::Write(CreateTestPointSet(), tmpStream); } catch (std::exception& /*e*/) { return false; } return true; } - void PointSetLoadAndCompareTest(unsigned int numberOfPointSets) + void PointSetLoadAndCompareTest() { try { - mitk::PointSetReader::Pointer pointSetReader = - mitk::PointSetReader::New(); - mitk::PointSet::Pointer pointSet; + mitk::PointSet::Pointer pointSet = mitk::FileReaderRegistry::Read(m_FilePath); + MITK_TEST_CONDITION(pointSet.IsNotNull(), "Testing if the loaded Data are NULL" ); - pointSetReader->SetFileName("test_pointset_new.mps"); - for (unsigned int i = 0; i < numberOfPointSets; i++) - { - pointSetReader->Update(); - pointSet = pointSetReader->GetOutput(i); - MITK_TEST_CONDITION(pointSet.IsNotNull(), "Testing if the loaded Data are NULL" ); - - bool identical(true); - PointSetCompare(pointSet.GetPointer(), m_SavedPointSet.at(i).GetPointer(), - identical); - } + bool identical(true); + PointSetCompare(pointSet.GetPointer(), m_SavedPointSet.GetPointer(), + identical); } catch (std::exception& /*e*/) { } } }; //mitkPointSetFileIOTestClass int mitkPointSetFileIOTest(int, char*[]) { MITK_TEST_BEGIN("PointSet"); - unsigned int numberOfPointSets(5); mitkPointSetFileIOTestClass* test = new mitkPointSetFileIOTestClass(); // write - MITK_TEST_CONDITION(test->PointSetWrite(numberOfPointSets), "Testing if the PointSetWriter writes Data" ); + MITK_TEST_CONDITION(test->PointSetWrite(), "Testing if the PointSetWriter writes Data" ); // load - compare - test->PointSetLoadAndCompareTest(numberOfPointSets); + test->PointSetLoadAndCompareTest(); //Delete correctly delete test; MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkPointSetLocaleTest.cpp b/Core/Code/Testing/mitkPointSetLocaleTest.cpp index 7396e70655..bd06e34464 100644 --- a/Core/Code/Testing/mitkPointSetLocaleTest.cpp +++ b/Core/Code/Testing/mitkPointSetLocaleTest.cpp @@ -1,177 +1,172 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ -#include "mitkPointSetReader.h" -#include "mitkPointSetWriter.h" +#include "mitkPointSet.h" +#include "mitkFileReaderRegistry.h" +#include "mitkFileWriterRegistry.h" #include "mitkStandardFileLocations.h" +#include "mitkIOUtil.h" #include "mitkTestingMacros.h" #include #include #include #include bool ChangeLocale(const std::string& locale) { try { MITK_TEST_OUTPUT(<< "\n** Changing locale from " << setlocale(LC_ALL, NULL) << " to '" << locale << "'"); setlocale(LC_ALL, locale.c_str()); std::locale l( locale.c_str() ); std::cin.imbue(l); std::cout.imbue(l); return true; } catch(...) { MITK_TEST_OUTPUT(<< "Could not activate locale" << locale << "\n"); return false; } } void ReaderLocaleTest(mitk::Point3D & refPoint, std::string filename) { MITK_TEST_OUTPUT(<< "---- Reader Test ---- "); - mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New(); - reader -> SetFileName(filename.c_str()); - reader -> Update(); - mitk::PointSet::Pointer pointSet = reader -> GetOutput(); + mitk::PointSet::Pointer pointSet = mitk::FileReaderRegistry::Read(filename); mitk::Point3D point; if (pointSet->GetPointIfExists(0, &point)) { MITK_TEST_CONDITION_REQUIRED(fabs(refPoint[0] - point[0]) < 0.00001, "read x correct"); MITK_TEST_CONDITION_REQUIRED(fabs(refPoint[1] - point[1]) < 0.00001, "read y correct"); MITK_TEST_CONDITION_REQUIRED(fabs(refPoint[2] - point[2]) < 0.00001, "read z correct"); }else { MITK_TEST_FAILED_MSG(<< "File "<< filename << " can not be read - test will not applied." ); return; } } void WriterLocaleTest(mitk::Point3D & refPoint, std::string filename) { MITK_TEST_OUTPUT(<< "---- Writer Test---- "); //create pointset mitk::PointSet::Pointer refPointSet = mitk::PointSet::New(); refPointSet->InsertPoint(0,refPoint); //SetPoint(0, refPoint); - std::string testFileName = "testPointSet.mps"; + std::ofstream tmpStream; + std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream); // write point set - mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New(); - writer -> SetFileName(testFileName.c_str()); - writer -> SetInput(refPointSet); - writer -> Write(); + mitk::FileWriterRegistry::Write(refPointSet, tmpStream); + tmpStream.close(); + + std::ifstream stream(tmpFilePath.c_str()); //compare two .mps files std::ifstream refStream (filename.c_str()); - std::ifstream stream (testFileName.c_str()); MITK_TEST_CONDITION_REQUIRED(refStream,"Read reference point set"); MITK_TEST_CONDITION_REQUIRED(stream,"Read point set"); - - std::string streamLine; - std::string refStreamLine; - bool differ = false; if (stream.is_open() && refStream.is_open()) { std::string streamLine; std::string refStreamLine; while(!stream.eof() && ! refStream.eof()) { getline(stream, streamLine); getline(refStream, refStreamLine); if(streamLine.compare(refStreamLine) != 0) { differ = true; break; } } stream.close(); refStream.close(); } MITK_TEST_CONDITION_REQUIRED(!differ, "Write point set correct"); } int mitkPointSetLocaleTest(int argc, char* argv[]) { MITK_TEST_BEGIN("PointSetLocaleTest"); if (argc<2) {MITK_TEST_FAILED_MSG(<<"Error: test file name is needed as second argument.");} std::string filename = argv[1]; MITK_INFO << filename; //create reference point set mitk::PointSet::Pointer refPointSet = mitk::PointSet::New(); mitk::Point3D refPoint; refPoint[0] = 32.2946; refPoint[1] = -17.7359; refPoint[2] = 29.6502; refPointSet->SetPoint(0, refPoint); //create locale list std::ofstream stream; std::locale previousLocale(stream.getloc()); typedef std::list StringList; StringList alllocales; alllocales.push_back("de_DE"); alllocales.push_back("de_DE.utf8"); alllocales.push_back("de_DE.UTF-8"); alllocales.push_back("de_DE@euro"); alllocales.push_back("German_Germany"); // QuickFix for MAC OS X // See for more the Bug #3894 comments #if defined (__APPLE__) || defined(MACOSX) alllocales.push_back("C"); #endif unsigned int numberOfTestedGermanLocales(0); for (StringList::iterator iter = alllocales.begin(); iter != alllocales.end(); ++iter) { if ( ChangeLocale(*iter) ) { ++numberOfTestedGermanLocales; WriterLocaleTest(refPoint,filename); ReaderLocaleTest(refPoint,filename); } } if(numberOfTestedGermanLocales == 0) { MITK_TEST_OUTPUT(<< "Warning: No German locale was found on the system."); } //MITK_TEST_CONDITION_REQUIRED( numberOfTestedGermanLocales > 0, "Verify that at least one German locale has been tested."); MITK_TEST_END(); } diff --git a/Core/Code/Testing/mitkPointSetReaderTest.cpp b/Core/Code/Testing/mitkPointSetReaderTest.cpp index 888fa87654..5361801e47 100644 --- a/Core/Code/Testing/mitkPointSetReaderTest.cpp +++ b/Core/Code/Testing/mitkPointSetReaderTest.cpp @@ -1,65 +1,66 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPointSet.h" -#include "mitkPointSetReader.h" #include "mitkTestingMacros.h" +#include "mitkFileReaderRegistry.h" /** * Test for the class "mitkPointSetReader". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test data set for the tests (see CMakeLists.txt). */ int mitkPointSetReaderTest(int argc , char* argv[]) { // always start with this! // MITK_TEST_BEGIN("PointSetReader") //MITK_TEST_CONDITION_REQUIRED(argc == 2,"Testing invocation") - // let's create an object of our class - mitk::PointSetReader::Pointer myPointSetReader = mitk::PointSetReader::New(); - MITK_TEST_CONDITION_REQUIRED(myPointSetReader.IsNotNull(),"Testing instantiation") + mitk::FileReaderRegistry readerRegistry; - // testing set / get name with invalid data - std::string testName = "test1"; - myPointSetReader->SetFileName( testName ); - MITK_TEST_CONDITION_REQUIRED( myPointSetReader->GetFileName()== testName, "Testing set / get file name methods!"); + // Get PointSet reader(s) + std::vector readers = readerRegistry.GetReaders(".mps"); + MITK_TEST_CONDITION_REQUIRED(!readers.empty(), "Testing for registered readers") - // testing file reading with invalid data - MITK_TEST_CONDITION_REQUIRED( !myPointSetReader->CanReadFile(testName,"",""), "Testing CanReadFile() method with invalid input file name!"); - myPointSetReader->Update(); - MITK_TEST_CONDITION_REQUIRED( !myPointSetReader->GetSuccess(), "Testing GetSuccess() with invalid input file name!"); + for (std::vector::const_iterator iter = readers.begin(), end = readers.end(); + iter != end; ++iter) + { + std::string testName = "test1"; + mitk::IFileReader* reader = *iter; + // testing file reading with invalid data + MITK_TEST_CONDITION_REQUIRED( !reader->CanRead(testName), "Testing CanRead() method with invalid input file name!"); + std::vector data = reader->Read(testName); + MITK_TEST_CONDITION_REQUIRED(data.empty(), "Testing GetSuccess() with invalid input file name!"); - // testing file reading with invalid data - myPointSetReader->SetFileName("F://Build//MITK-Data//PointSetReaderTestData.mps"); - MITK_TEST_CONDITION_REQUIRED( myPointSetReader->CanReadFile("F://Build//MITK-Data//PointSetReaderTestData.mps", "", ""), "Testing CanReadFile() method with valid input file name!"); - myPointSetReader->Modified(); - myPointSetReader->Update(); - MITK_TEST_CONDITION_REQUIRED( myPointSetReader->GetSuccess(), "Testing GetSuccess() with valid input file name!"); + // testing file reading with valid data + std::string filePath = argv[1]; + MITK_TEST_CONDITION_REQUIRED( reader->CanRead(filePath), "Testing CanReadFile() method with valid input file name!"); + data = reader->Read(filePath); + MITK_TEST_CONDITION_REQUIRED( !data.empty(), "Testing non-empty data with valid input file name!"); - // evaluate if the read point set is correct - mitk::PointSet::Pointer resultPS = myPointSetReader->GetOutput(); - MITK_TEST_CONDITION_REQUIRED( resultPS.IsNotNull(), "Testing output generation!"); - MITK_TEST_CONDITION_REQUIRED( resultPS->GetTimeSteps() == 14, "Testing output time step generation!"); // CAVE: Only valid with the specified test data! - MITK_TEST_CONDITION_REQUIRED( resultPS->GetPointSet(resultPS->GetTimeSteps()-1)->GetNumberOfPoints() == 0, "Testing output time step generation with empty time step!"); // CAVE: Only valid with the specified test data! + // evaluate if the read point set is correct + mitk::PointSet::Pointer resultPS = dynamic_cast(data.front().GetPointer()); + MITK_TEST_CONDITION_REQUIRED( resultPS.IsNotNull(), "Testing correct BaseData type"); + MITK_TEST_CONDITION_REQUIRED( resultPS->GetTimeSteps() == 14, "Testing output time step generation!"); // CAVE: Only valid with the specified test data! + MITK_TEST_CONDITION_REQUIRED( resultPS->GetPointSet(resultPS->GetTimeSteps()-1)->GetNumberOfPoints() == 0, "Testing output time step generation with empty time step!"); // CAVE: Only valid with the specified test data! + } // always end with this! //MITK_TEST_END() } - diff --git a/Core/Code/Testing/mitkPointSetWriterTest.cpp b/Core/Code/Testing/mitkPointSetWriterTest.cpp index ae005e2446..fc5196caaa 100644 --- a/Core/Code/Testing/mitkPointSetWriterTest.cpp +++ b/Core/Code/Testing/mitkPointSetWriterTest.cpp @@ -1,114 +1,80 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPointSet.h" -#include "mitkPointSetWriter.h" #include "mitkTestingMacros.h" +#include "mitkFileWriterRegistry.h" #include #include /** * Test for the class "mitkPointSetFileWriter". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkPointSetWriterTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("PointSetWriter") - // let's create an object of our class - mitk::PointSetWriter::Pointer myPointSetWriter = mitk::PointSetWriter::New(); + mitk::FileWriterRegistry writerRegistry; - // first test: did this work? - // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since - // it makes no sense to continue without an object. - MITK_TEST_CONDITION_REQUIRED(myPointSetWriter.IsNotNull(),"Testing instantiation") - - // write your own tests here and use the macros from mitkTestingMacros.h !!! - // do not write to std::cout and do not return from this function yourself! + // Get PointSet writer(s) + std::vector writers = writerRegistry.GetWriters(mitk::PointSet::GetStaticNameOfClass()); + MITK_TEST_CONDITION_REQUIRED(!writers.empty(), "Testing for registered writers") // create pointSet srand(time(NULL)); mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); int numberOfPoints = rand()%100; for (int i=0; i<=numberOfPoints+1;i++) { mitk::Point3D point; point[0] = rand()%1000; point[1] = rand()%1000; point[2] = rand()%1000; pointSet->SetPoint(i,point); } MITK_TEST_CONDITION_REQUIRED(pointSet.IsNotNull(),"PointSet creation") - try{ - // test for exception handling - MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject) - myPointSetWriter->SetInput(pointSet); - myPointSetWriter->SetFileName("/usr/bin"); - myPointSetWriter->Update(); - MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject) - } - catch(...) { - //this means that a wrong exception (i.e. no itk:Exception) has been thrown - std::cout << "Wrong exception (i.e. no itk:Exception) caught during write [FAILED]" << std::endl; - return EXIT_FAILURE; - } - - /* - MITK_TEST_OUTPUT( << "Check if filename can be set correctly: "); - myPointSetWriter->SetFileName("filename"); - const char * filename = myPointSetWriter->GetFileName(); - MITK_TEST_CONDITION_REQUIRED(std::string("filename") == "filename", "Filename set correctly?"); - - MITK_TEST_OUTPUT( << "Check if prefix can be set correctly: "); - myPointSetWriter->SetFilePrefix("pre"); - const char * prefix = myPointSetWriter->GetFilePrefix(); - MITK_TEST_CONDITION_REQUIRED(std::string("pre") == prefix, "Prefix set correctly?"); - - MITK_TEST_OUTPUT( << "Check if pattern can be set correctly: "); - myPointSetWriter->SetFilePattern("pattern"); - const char * pattern = myPointSetWriter->GetFilePattern(); - MITK_TEST_CONDITION_REQUIRED(std::string("pattern") == prefix, "Pattern set correctly?"); - */ - - MITK_TEST_OUTPUT( << "Check if input can be set correctly: "); - myPointSetWriter->SetInput(pointSet); - mitk::PointSet::Pointer pointSet2 = mitk::PointSet::New(); - pointSet2 = myPointSetWriter->GetInput(); - - MITK_TEST_CONDITION_REQUIRED( pointSet->GetSize() == pointSet2->GetSize(), "Pointsets have unequal size" ); - - for(int i=0; iGetSize(); i++) + for (std::vector::const_iterator iter = writers.begin(), + end = writers.end(); iter != end; ++iter) { - mitk::Point3D p1 = pointSet->GetPoint(i); - mitk::Point3D p2 = pointSet2->GetPoint(i); - MITK_TEST_CONDITION_REQUIRED( p1[0] == p2[0] && p1[0] == p2[0] && p1[0] == p2[0], "Pointsets aren't equal" ); + // test for exception handling + try + { + (*iter)->Write(pointSet, "/usr/bin"); + MITK_TEST_FAILED_MSG( << "itk::ExceptionObject expected" ) + } + catch (const itk::ExceptionObject&) + { /* this is expected */ } + catch(...) + { + //this means that a wrong exception (i.e. no itk:Exception) has been thrown + MITK_TEST_FAILED_MSG( << "Wrong exception (i.e. no itk:Exception) caught during write [FAILED]") + } } - std::vector< std::string > extensions = myPointSetWriter->GetPossibleFileExtensions(); - // always end with this! MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkSurfaceVtkWriterTest.cpp b/Core/Code/Testing/mitkSurfaceVtkWriterTest.cpp index 3d9ecbb3d1..180e7b148d 100644 --- a/Core/Code/Testing/mitkSurfaceVtkWriterTest.cpp +++ b/Core/Code/Testing/mitkSurfaceVtkWriterTest.cpp @@ -1,85 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ -#include "mitkSurfaceVtkWriter.h" - #include "mitkTestingMacros.h" +#include "mitkFileWriterRegistry.h" +#include "mitkSurface.h" #include #include #include /** * Simple example for a test for the (non-existent) class "ClassName". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkSurfaceVtkWriterTest(int /*argc*/ , char* argv[]) { // always start with this! MITK_TEST_BEGIN("SurfaceVtkWriter") - // let's create an object of our class - mitk::SurfaceVtkWriter::Pointer mySurfaceVtkWriter = mitk::SurfaceVtkWriter::New(); - - // first test: did this work? - // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since - // it makes no sense to continue without an object. - MITK_TEST_CONDITION_REQUIRED(mySurfaceVtkWriter.IsNotNull(),"Testing instantiation") - // create contour vtkPolyDataReader* reader = vtkPolyDataReader::New(); reader->SetFileName(argv[1]); reader->Update(); if (reader->GetOutput()) { mitk::Surface::Pointer surface = mitk::Surface::New(); surface->SetVtkPolyData(reader->GetOutput()); surface->Update(); MITK_TEST_CONDITION_REQUIRED(surface.IsNotNull(),"Surface creation") - try{ - // test for exception handling - MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ExceptionObject) - mySurfaceVtkWriter->SetInput(surface); - mySurfaceVtkWriter->SetFileName("/usr/bin"); - mySurfaceVtkWriter->Update(); - MITK_TEST_FOR_EXCEPTION_END(itk::ExceptionObject) + try + { + // test for exception handling + mitk::FileWriterRegistry::Write(surface, "/usr/bin"); + MITK_TEST_FAILED_MSG( << "itk::ExceptionObject expected" ) } - catch(...) { + catch (const itk::ExceptionObject&) { /* this is expected */ } + catch(...) + { //this means that a wrong exception (i.e. no itk:Exception) has been thrown - std::cout << "Wrong exception (i.e. no itk:Exception) caught during write [FAILED]" << std::endl; - return EXIT_FAILURE; + MITK_TEST_FAILED_MSG( << "Wrong exception (i.e. no itk:Exception) caught during write [FAILED]" ) } // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! - - // always end with this! } //Delete reader correctly reader->Delete(); + // always end with this! MITK_TEST_END() - } diff --git a/Core/Code/Testing/mitkVolumeCalculatorTest.cpp b/Core/Code/Testing/mitkVolumeCalculatorTest.cpp index b79d3c8626..0d4927fbc3 100644 --- a/Core/Code/Testing/mitkVolumeCalculatorTest.cpp +++ b/Core/Code/Testing/mitkVolumeCalculatorTest.cpp @@ -1,81 +1,73 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkVolumeCalculator.h" #include "mitkImage.h" #include "mitkTestingMacros.h" -#include #include - +#include "mitkIOUtil.h" int mitkVolumeCalculatorTest(int /*argc*/, char* argv[]) { MITK_TEST_BEGIN("VolumeCalculator") const char * filename = argv[1]; const char * filename3D = argv[2]; mitk::VolumeCalculator::Pointer volumeCalculator = mitk::VolumeCalculator::New(); - mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); //********************************************************************* // Part I: Testing calculated volume. // The correct values have been manually calculated using external software. //********************************************************************* - nodeReader->SetFileName(filename); - nodeReader->Update(); - - mitk::DataNode::Pointer node = nodeReader->GetOutput(); + mitk::DataNode::Pointer node = mitk::IOUtil::LoadDataNode(filename); mitk::Image::Pointer image = dynamic_cast(node->GetData()); MITK_TEST_CONDITION_REQUIRED( image.IsNotNull() , "01 Check if test image could be loaded"); volumeCalculator->SetImage(image); volumeCalculator->SetThreshold(0); volumeCalculator->ComputeVolume(); float volume = volumeCalculator->GetVolume(); MITK_TEST_CONDITION_REQUIRED( volume == 1600 , "02 Test Volume Result. Expected 1600 actual value " << volume); volumeCalculator->SetThreshold(255); volumeCalculator->ComputeVolume(); volume = volumeCalculator->GetVolume(); MITK_TEST_CONDITION_REQUIRED( volume == 1272.50 , "03 Test Volume Result. Expected 1272.50 actual value " << volume); - nodeReader->SetFileName(filename3D); - nodeReader->Update(); - - node = nodeReader->GetOutput(); + node = mitk::IOUtil::LoadDataNode(filename3D); image = dynamic_cast(node->GetData()); volumeCalculator->SetImage(image); volumeCalculator->SetThreshold(-1023); volumeCalculator->ComputeVolume(); std::vector volumes = volumeCalculator->GetVolumes(); for (std::vector::iterator it = volumes.begin(); it != volumes.end(); it++) { MITK_TEST_CONDITION_REQUIRED( (*it) == 24.576f , "04 Test Volume Result."); } MITK_TEST_END() } diff --git a/Core/Code/files.cmake b/Core/Code/files.cmake index 0e1261adbf..a9b7117e20 100644 --- a/Core/Code/files.cmake +++ b/Core/Code/files.cmake @@ -1,391 +1,365 @@ set(H_FILES Algorithms/itkImportMitkImageContainer.h Algorithms/itkImportMitkImageContainer.txx Algorithms/itkLocalVariationImageFilter.h Algorithms/itkLocalVariationImageFilter.txx Algorithms/itkMITKScalarImageToHistogramGenerator.h Algorithms/itkMITKScalarImageToHistogramGenerator.txx Algorithms/itkTotalVariationDenoisingImageFilter.h Algorithms/itkTotalVariationDenoisingImageFilter.txx Algorithms/itkTotalVariationSingleIterationImageFilter.h Algorithms/itkTotalVariationSingleIterationImageFilter.txx Algorithms/mitkBilateralFilter.h Algorithms/mitkBilateralFilter.cpp Algorithms/mitkInstantiateAccessFunctions.h Algorithms/mitkPixelTypeList.h # Preprocessor macros taken from Boost Algorithms/mitkPPArithmeticDec.h Algorithms/mitkPPArgCount.h Algorithms/mitkPPCat.h Algorithms/mitkPPConfig.h Algorithms/mitkPPControlExprIIf.h Algorithms/mitkPPControlIf.h Algorithms/mitkPPControlIIf.h Algorithms/mitkPPDebugError.h Algorithms/mitkPPDetailAutoRec.h Algorithms/mitkPPDetailDMCAutoRec.h Algorithms/mitkPPExpand.h Algorithms/mitkPPFacilitiesEmpty.h Algorithms/mitkPPFacilitiesExpand.h Algorithms/mitkPPLogicalBool.h Algorithms/mitkPPRepetitionDetailDMCFor.h Algorithms/mitkPPRepetitionDetailEDGFor.h Algorithms/mitkPPRepetitionDetailFor.h Algorithms/mitkPPRepetitionDetailMSVCFor.h Algorithms/mitkPPRepetitionFor.h Algorithms/mitkPPSeqElem.h Algorithms/mitkPPSeqForEach.h Algorithms/mitkPPSeqForEachProduct.h Algorithms/mitkPPSeq.h Algorithms/mitkPPSeqEnum.h Algorithms/mitkPPSeqSize.h Algorithms/mitkPPSeqToTuple.h Algorithms/mitkPPStringize.h Algorithms/mitkPPTupleEat.h Algorithms/mitkPPTupleElem.h Algorithms/mitkPPTupleRem.h Algorithms/mitkClippedSurfaceBoundsCalculator.h Algorithms/mitkExtractSliceFilter.h Algorithms/mitkConvert2Dto3DImageFilter.h Algorithms/mitkPlaneClipping.h Common/mitkExceptionMacro.h Common/mitkServiceBaseObject.h Common/mitkTestingMacros.h DataManagement/mitkImageAccessByItk.h DataManagement/mitkImageCast.h DataManagement/mitkImagePixelAccessor.h DataManagement/mitkImagePixelReadAccessor.h DataManagement/mitkImagePixelWriteAccessor.h DataManagement/mitkImageReadAccessor.h DataManagement/mitkImageWriteAccessor.h DataManagement/mitkITKImageImport.h DataManagement/mitkITKImageImport.txx DataManagement/mitkImageToItk.h DataManagement/mitkImageToItk.txx Interactions/mitkEventMapperAddOn.h Interfaces/mitkIDataNodeReader.h Interfaces/mitkIFileWriter.h Interfaces/mitkIFileWriter.cpp Interfaces/mitkIFileReader.h Interfaces/mitkIFileReader.cpp Rendering/mitkLocalStorageHandler.h IO/mitkPixelTypeTraits.h ) set(CPP_FILES Algorithms/mitkBaseDataSource.cpp Algorithms/mitkDataNodeSource.cpp Algorithms/mitkGeometry2DDataToSurfaceFilter.cpp Algorithms/mitkHistogramGenerator.cpp Algorithms/mitkImageChannelSelector.cpp Algorithms/mitkImageSliceSelector.cpp Algorithms/mitkImageSource.cpp Algorithms/mitkImageTimeSelector.cpp Algorithms/mitkImageToImageFilter.cpp Algorithms/mitkImageToSurfaceFilter.cpp Algorithms/mitkPointSetSource.cpp Algorithms/mitkPointSetToPointSetFilter.cpp Algorithms/mitkRGBToRGBACastImageFilter.cpp Algorithms/mitkSubImageSelector.cpp Algorithms/mitkSurfaceSource.cpp Algorithms/mitkSurfaceToImageFilter.cpp Algorithms/mitkSurfaceToSurfaceFilter.cpp Algorithms/mitkUIDGenerator.cpp Algorithms/mitkVolumeCalculator.cpp Algorithms/mitkClippedSurfaceBoundsCalculator.cpp Algorithms/mitkExtractSliceFilter.cpp Algorithms/mitkConvert2Dto3DImageFilter.cpp Controllers/mitkBaseController.cpp Controllers/mitkCallbackFromGUIThread.cpp Controllers/mitkCameraController.cpp Controllers/mitkCameraRotationController.cpp Controllers/mitkCoreActivator.cpp Controllers/mitkFocusManager.cpp Controllers/mitkLimitedLinearUndo.cpp Controllers/mitkOperationEvent.cpp Controllers/mitkPlanePositionManager.cpp Controllers/mitkProgressBar.cpp Controllers/mitkRenderingManager.cpp Controllers/mitkSliceNavigationController.cpp Controllers/mitkSlicesCoordinator.cpp Controllers/mitkSlicesRotator.cpp Controllers/mitkSlicesSwiveller.cpp Controllers/mitkStatusBar.cpp Controllers/mitkStepper.cpp Controllers/mitkTestManager.cpp Controllers/mitkUndoController.cpp Controllers/mitkVerboseLimitedLinearUndo.cpp Controllers/mitkVtkInteractorCameraController.cpp Controllers/mitkVtkLayerController.cpp DataManagement/mitkAbstractTransformGeometry.cpp DataManagement/mitkAnnotationProperty.cpp DataManagement/mitkApplicationCursor.cpp DataManagement/mitkBaseData.cpp DataManagement/mitkBaseProperty.cpp DataManagement/mitkClippingProperty.cpp DataManagement/mitkChannelDescriptor.cpp DataManagement/mitkColorProperty.cpp DataManagement/mitkDataStorage.cpp #DataManagement/mitkDataTree.cpp DataManagement/mitkDataNode.cpp - DataManagement/mitkDataNodeFactory.cpp #DataManagement/mitkDataTreeStorage.cpp DataManagement/mitkDisplayGeometry.cpp DataManagement/mitkEnumerationProperty.cpp DataManagement/mitkGeometry2D.cpp DataManagement/mitkGeometry2DData.cpp DataManagement/mitkGeometry3D.cpp DataManagement/mitkGeometryData.cpp DataManagement/mitkGroupTagProperty.cpp DataManagement/mitkImage.cpp DataManagement/mitkImageAccessorBase.cpp DataManagement/mitkImageCaster.cpp DataManagement/mitkImageCastPart1.cpp DataManagement/mitkImageCastPart2.cpp DataManagement/mitkImageCastPart3.cpp DataManagement/mitkImageCastPart4.cpp DataManagement/mitkImageDataItem.cpp DataManagement/mitkImageDescriptor.cpp DataManagement/mitkImageVtkAccessor.cpp DataManagement/mitkImageStatisticsHolder.cpp DataManagement/mitkLandmarkBasedCurvedGeometry.cpp DataManagement/mitkLandmarkProjectorBasedCurvedGeometry.cpp DataManagement/mitkLandmarkProjector.cpp DataManagement/mitkLevelWindow.cpp DataManagement/mitkLevelWindowManager.cpp DataManagement/mitkLevelWindowPreset.cpp DataManagement/mitkLevelWindowProperty.cpp DataManagement/mitkLookupTable.cpp DataManagement/mitkLookupTables.cpp # specializations of GenericLookupTable DataManagement/mitkMemoryUtilities.cpp DataManagement/mitkModalityProperty.cpp DataManagement/mitkModeOperation.cpp DataManagement/mitkNodePredicateAnd.cpp DataManagement/mitkNodePredicateBase.cpp DataManagement/mitkNodePredicateCompositeBase.cpp DataManagement/mitkNodePredicateData.cpp DataManagement/mitkNodePredicateDataType.cpp DataManagement/mitkNodePredicateDimension.cpp DataManagement/mitkNodePredicateFirstLevel.cpp DataManagement/mitkNodePredicateNot.cpp DataManagement/mitkNodePredicateOr.cpp DataManagement/mitkNodePredicateProperty.cpp DataManagement/mitkNodePredicateSource.cpp DataManagement/mitkPlaneOrientationProperty.cpp DataManagement/mitkPlaneGeometry.cpp DataManagement/mitkPlaneOperation.cpp DataManagement/mitkPointOperation.cpp DataManagement/mitkPointSet.cpp DataManagement/mitkProperties.cpp DataManagement/mitkPropertyList.cpp DataManagement/mitkRestorePlanePositionOperation.cpp DataManagement/mitkRotationOperation.cpp DataManagement/mitkSlicedData.cpp DataManagement/mitkSlicedGeometry3D.cpp DataManagement/mitkSmartPointerProperty.cpp DataManagement/mitkStandaloneDataStorage.cpp DataManagement/mitkStateTransitionOperation.cpp DataManagement/mitkStringProperty.cpp DataManagement/mitkSurface.cpp DataManagement/mitkSurfaceOperation.cpp DataManagement/mitkThinPlateSplineCurvedGeometry.cpp DataManagement/mitkTimeSlicedGeometry.cpp DataManagement/mitkTransferFunction.cpp DataManagement/mitkTransferFunctionProperty.cpp DataManagement/mitkTransferFunctionInitializer.cpp DataManagement/mitkVector.cpp DataManagement/mitkVtkInterpolationProperty.cpp DataManagement/mitkVtkRepresentationProperty.cpp DataManagement/mitkVtkResliceInterpolationProperty.cpp DataManagement/mitkVtkScalarModeProperty.cpp DataManagement/mitkVtkVolumeRenderingProperty.cpp DataManagement/mitkWeakPointerProperty.cpp DataManagement/mitkRenderingModeProperty.cpp DataManagement/mitkShaderProperty.cpp DataManagement/mitkResliceMethodProperty.cpp DataManagement/mitkMaterial.cpp DataManagement/mitkPointSetShapeProperty.cpp DataManagement/mitkFloatPropertyExtension.cpp DataManagement/mitkIntPropertyExtension.cpp DataManagement/mitkPropertyExtension.cpp DataManagement/mitkPropertyFilter.cpp DataManagement/mitkPropertyAliases.cpp DataManagement/mitkPropertyDescriptions.cpp DataManagement/mitkPropertyExtensions.cpp DataManagement/mitkPropertyFilters.cpp Interactions/mitkAction.cpp Interactions/mitkAffineInteractor.cpp Interactions/mitkBindDispatcherInteractor.cpp Interactions/mitkCoordinateSupplier.cpp Interactions/mitkDataInteractor.cpp Interactions/mitkDispatcher.cpp Interactions/mitkDisplayCoordinateOperation.cpp Interactions/mitkDisplayInteractor.cpp Interactions/mitkDisplayPositionEvent.cpp # Interactions/mitkDisplayVectorInteractorLevelWindow.cpp # legacy, prob even now unneeded # Interactions/mitkDisplayVectorInteractorScroll.cpp Interactions/mitkEvent.cpp Interactions/mitkEventConfig.cpp Interactions/mitkEventDescription.cpp Interactions/mitkEventFactory.cpp Interactions/mitkInteractionEventHandler.cpp Interactions/mitkEventMapper.cpp Interactions/mitkEventStateMachine.cpp Interactions/mitkGlobalInteraction.cpp Interactions/mitkInteractor.cpp Interactions/mitkInternalEvent.cpp Interactions/mitkInteractionEvent.cpp Interactions/mitkInteractionEventConst.cpp Interactions/mitkInteractionPositionEvent.cpp Interactions/mitkInteractionKeyEvent.cpp Interactions/mitkMousePressEvent.cpp Interactions/mitkMouseMoveEvent.cpp Interactions/mitkMouseReleaseEvent.cpp Interactions/mitkMouseWheelEvent.cpp Interactions/mitkMouseDoubleClickEvent.cpp Interactions/mitkMouseModeSwitcher.cpp Interactions/mitkMouseMovePointSetInteractor.cpp Interactions/mitkMoveBaseDataInteractor.cpp Interactions/mitkNodeDepententPointSetInteractor.cpp Interactions/mitkPointSetDataInteractor.cpp Interactions/mitkPointSetInteractor.cpp Interactions/mitkPositionEvent.cpp Interactions/mitkPositionTracker.cpp Interactions/mitkStateMachineAction.cpp Interactions/mitkStateMachineCondition.cpp Interactions/mitkStateMachineState.cpp Interactions/mitkStateMachineTransition.cpp Interactions/mitkState.cpp Interactions/mitkStateMachineContainer.cpp Interactions/mitkStateEvent.cpp Interactions/mitkStateMachine.cpp Interactions/mitkStateMachineFactory.cpp Interactions/mitkTransition.cpp Interactions/mitkWheelEvent.cpp Interactions/mitkKeyEvent.cpp Interactions/mitkVtkEventAdapter.cpp Interactions/mitkVtkInteractorStyle.cxx Interactions/mitkCrosshairPositionEvent.cpp Interfaces/mitkInteractionEventObserver.cpp Interfaces/mitkIShaderRepository.cpp Interfaces/mitkIPropertyAliases.cpp Interfaces/mitkIPropertyDescriptions.cpp Interfaces/mitkIPropertyExtensions.cpp Interfaces/mitkIPropertyFilters.cpp IO/mitkAbstractFileReader.cpp IO/mitkAbstractFileWriter.cpp - IO/mitkLegacyImageWriterService.cpp IO/mitkLegacyFileReaderService.cpp IO/mitkLegacyFileWriterService.cpp - IO/mitkBaseDataIOFactory.cpp - IO/mitkCoreDataNodeReader.cpp IO/mitkDicomSeriesReader.cpp IO/mitkFileReader.cpp - IO/mitkFileReaderRegistry.cpp - IO/mitkFileSeriesReader.cpp IO/mitkFileWriter.cpp + IO/mitkFileReaderRegistry.cpp IO/mitkFileWriterRegistry.cpp #IO/mitkIpPicGet.c IO/mitkImageGenerator.cpp - IO/mitkImageWriter.cpp - IO/mitkImageWriterFactory.cpp - IO/mitkItkImageFileIOFactory.cpp - IO/mitkItkImageFileReader.cpp IO/mitkItkLoggingAdapter.cpp - IO/mitkItkPictureWrite.cpp IO/mitkIOUtil.cpp IO/mitkLookupTableProperty.cpp IO/mitkOperation.cpp #IO/mitkPicFileIOFactory.cpp #IO/mitkPicFileReader.cpp #IO/mitkPicFileWriter.cpp #IO/mitkPicHelper.cpp #IO/mitkPicVolumeTimeSeriesIOFactory.cpp #IO/mitkPicVolumeTimeSeriesReader.cpp IO/mitkPixelType.cpp - IO/mitkPointSetIOFactory.cpp - IO/mitkPointSetReader.cpp IO/mitkPointSetReaderService.cpp - IO/mitkPointSetWriter.cpp IO/mitkPointSetWriterService.cpp - IO/mitkPointSetWriterFactory.cpp - IO/mitkRawImageFileReader.cpp IO/mitkStandardFileLocations.cpp - IO/mitkSTLFileIOFactory.cpp - IO/mitkSTLFileReader.cpp - IO/mitkSurfaceVtkWriter.cpp - IO/mitkSurfaceVtkWriterFactory.cpp IO/mitkVtkLoggingAdapter.cpp - IO/mitkVtiFileIOFactory.cpp - IO/mitkVtiFileReader.cpp - IO/mitkVtkImageIOFactory.cpp - IO/mitkVtkImageReader.cpp - IO/mitkVtkSurfaceIOFactory.cpp - IO/mitkVtkSurfaceReader.cpp - IO/vtkPointSetXMLParser.cpp IO/mitkLog.cpp Rendering/mitkBaseRenderer.cpp Rendering/mitkVtkMapper.cpp Rendering/mitkRenderWindowFrame.cpp Rendering/mitkGeometry2DDataMapper2D.cpp Rendering/mitkGeometry2DDataVtkMapper3D.cpp Rendering/mitkGLMapper.cpp Rendering/mitkGradientBackground.cpp Rendering/mitkManufacturerLogo.cpp Rendering/mitkMapper.cpp Rendering/mitkPointSetGLMapper2D.cpp Rendering/mitkPointSetVtkMapper2D.cpp Rendering/mitkPointSetVtkMapper3D.cpp Rendering/mitkPolyDataGLMapper2D.cpp Rendering/mitkSurfaceGLMapper2D.cpp Rendering/mitkSurfaceVtkMapper3D.cpp Rendering/mitkVolumeDataVtkMapper3D.cpp Rendering/mitkVtkPropRenderer.cpp Rendering/mitkVtkWidgetRendering.cpp Rendering/vtkMitkRectangleProp.cpp Rendering/vtkMitkRenderProp.cpp Rendering/mitkVtkEventProvider.cpp Rendering/mitkRenderWindow.cpp Rendering/mitkRenderWindowBase.cpp Rendering/mitkShaderRepository.cpp Rendering/mitkImageVtkMapper2D.cpp Rendering/vtkMitkThickSlicesFilter.cpp Rendering/vtkMitkLevelWindowFilter.cpp Rendering/vtkNeverTranslucentTexture.cpp Rendering/mitkRenderingTestHelper.cpp Common/mitkException.cpp Common/mitkCommon.h Common/mitkCoreObjectFactoryBase.cpp Common/mitkCoreObjectFactory.cpp Common/mitkCoreServices.cpp ) list(APPEND CPP_FILES ${CppMicroServices_SOURCES}) set(RESOURCE_FILES Interactions/globalConfig.xml Interactions/DisplayInteraction.xml Interactions/DisplayConfig.xml Interactions/DisplayConfigPACS.xml Interactions/DisplayConfigPACSPan.xml Interactions/DisplayConfigPACSScroll.xml Interactions/DisplayConfigPACSZoom.xml Interactions/DisplayConfigPACSLevelWindow.xml Interactions/DisplayConfigMITK.xml Interactions/PointSet.xml Interactions/Legacy/StateMachine.xml Interactions/Legacy/DisplayConfigMITKTools.xml Interactions/PointSetConfig.xml Shaders/mitkShaderLighting.xml mitkLevelWindowPresets.xml ) diff --git a/Modules/CMakeLists.txt b/Modules/CMakeLists.txt index a1b7eab5e7..a999b2049d 100644 --- a/Modules/CMakeLists.txt +++ b/Modules/CMakeLists.txt @@ -1,63 +1,64 @@ set(LIBPOSTFIX "Ext") # Modules must be listed according to their dependencies set(module_dirs + LegacyIO SceneSerializationBase PlanarFigure ImageExtraction ImageStatistics LegacyAdaptors IpPicSupport MitkExt SceneSerialization GraphAlgorithms SurfaceInterpolation Segmentation PlanarFigureSegmentation Qmitk QmitkExt SegmentationUI DiffusionImaging GPGPU IGT CameraCalibration IGTUI RigidRegistration RigidRegistrationUI DeformableRegistration DeformableRegistrationUI OpenCL OpenCVVideoSupport Overlays InputDevices ToFHardware ToFProcessing ToFUI US ClippingTools USUI DicomUI Simulation Remeshing Python ) set(MITK_DEFAULT_SUBPROJECTS MITK-Modules) foreach(module_dir ${module_dirs}) add_subdirectory(${module_dir}) endforeach() if(MITK_PRIVATE_MODULES) file(GLOB all_subdirs RELATIVE ${MITK_PRIVATE_MODULES} ${MITK_PRIVATE_MODULES}/*) foreach(subdir ${all_subdirs}) string(FIND ${subdir} "." _result) if(_result EQUAL -1) if(EXISTS ${MITK_PRIVATE_MODULES}/${subdir}/CMakeLists.txt) message(STATUS "Found private module ${subdir}") add_subdirectory(${MITK_PRIVATE_MODULES}/${subdir} private_modules/${subdir}) endif() endif() endforeach() endif(MITK_PRIVATE_MODULES) diff --git a/Modules/IpPicSupport/CMakeLists.txt b/Modules/IpPicSupport/CMakeLists.txt index 63900a7b73..54bc38cb31 100644 --- a/Modules/IpPicSupport/CMakeLists.txt +++ b/Modules/IpPicSupport/CMakeLists.txt @@ -1,7 +1,7 @@ mitkFunctionCheckCompilerFlags("-Wno-deprecated-declarations" CMAKE_CXX_FLAGS) MITK_CREATE_MODULE( IpPicSupport - DEPENDS Mitk LegacyAdaptors mitkIpPic + DEPENDS Mitk LegacyAdaptors LegacyIO mitkIpPic ) add_subdirectory(Testing) diff --git a/Modules/LegacyIO/CMakeLists.txt b/Modules/LegacyIO/CMakeLists.txt new file mode 100644 index 0000000000..7920316be4 --- /dev/null +++ b/Modules/LegacyIO/CMakeLists.txt @@ -0,0 +1,4 @@ + +MITK_CREATE_MODULE( LegacyIO + DEPENDS Mitk +) diff --git a/Modules/LegacyIO/Testing/files.cmake b/Modules/LegacyIO/Testing/files.cmake new file mode 100644 index 0000000000..0e81f8005f --- /dev/null +++ b/Modules/LegacyIO/Testing/files.cmake @@ -0,0 +1,8 @@ +# test with image filename as an extra command line parameter +set(MODULE_IMAGE_TESTS + mitkDataNodeFactoryTest.cpp #runs on all types of data +) + +set(MODULE_SURFACE_TESTS + mitkDataNodeFactoryTest.cpp #runs on all types of data +) diff --git a/Core/Code/Testing/mitkDataNodeFactoryTest.cpp b/Modules/LegacyIO/Testing/mitkDataNodeFactoryTest.cpp similarity index 100% rename from Core/Code/Testing/mitkDataNodeFactoryTest.cpp rename to Modules/LegacyIO/Testing/mitkDataNodeFactoryTest.cpp diff --git a/Modules/LegacyIO/files.cmake b/Modules/LegacyIO/files.cmake new file mode 100644 index 0000000000..5790303f08 --- /dev/null +++ b/Modules/LegacyIO/files.cmake @@ -0,0 +1,30 @@ +set(H_FILES + +) + +set(CPP_FILES + mitkBaseDataIOFactory.cpp + mitkDataNodeFactory.cpp + mitkFileSeriesReader.cpp + mitkImageWriter.cpp + mitkImageWriterFactory.cpp + mitkItkImageFileIOFactory.cpp + mitkItkImageFileReader.cpp + mitkItkPictureWrite.cpp + mitkPointSetIOFactory.cpp + mitkPointSetReader.cpp + mitkPointSetWriter.cpp + mitkPointSetWriterFactory.cpp + mitkRawImageFileReader.cpp + mitkSTLFileIOFactory.cpp + mitkSTLFileReader.cpp + mitkSurfaceVtkWriter.cpp + mitkSurfaceVtkWriterFactory.cpp + mitkVtiFileIOFactory.cpp + mitkVtiFileReader.cpp + mitkVtkImageIOFactory.cpp + mitkVtkImageReader.cpp + mitkVtkSurfaceIOFactory.cpp + mitkVtkSurfaceReader.cpp + vtkPointSetXMLParser.cpp +) diff --git a/Modules/LegacyIO/mitkActivator.cpp b/Modules/LegacyIO/mitkActivator.cpp new file mode 100644 index 0000000000..096c2b320e --- /dev/null +++ b/Modules/LegacyIO/mitkActivator.cpp @@ -0,0 +1,70 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include + +#include + +#include "mitkSurfaceVtkWriterFactory.h" +#include "mitkPointSetWriterFactory.h" +#include "mitkImageWriterFactory.h" + +class US_ABI_LOCAL Activator : public us::ModuleActivator +{ +public: + + void Load(us::ModuleContext* context) + { + m_CoreDataNodeReader.reset(new mitk::CoreDataNodeReader); + context->RegisterService(m_CoreDataNodeReader.get()); + + m_ObjectFactories.push_back(PointSetIOFactory::New()); + m_ObjectFactories.push_back(STLFileIOFactory::New()); + m_ObjectFactories.push_back(VtkSurfaceIOFactory::New()); + m_ObjectFactories.push_back(VtkImageIOFactory::New()); + m_ObjectFactories.push_back(VtiFileIOFactory::New()); + m_ObjectFactories.push_back(ItkImageFileIOFactory::New()); + + for(std::vector::const_iterator iter = m_ObjectFactories.begin(), + end = m_ObjectFactories.end(); iter != end; ++iter) + { + itk::ObjectFactoryBase::RegisterFactory(*iter); + } + + mitk::SurfaceVtkWriterFactory::RegisterOneFactory(); + mitk::PointSetWriterFactory::RegisterOneFactory(); + mitk::ImageWriterFactory::RegisterOneFactory(); + } + + void Unload(us::ModuleContext* ) + { + for(std::vector::const_iterator iter = m_ObjectFactories.begin(), + end = m_ObjectFactories.end(); iter != end; ++iter) + { + itk::ObjectFactoryBase::UnRegisterFactory(*iter); + } + + // FIXME: There is no "UnRegisterOneFactory" method + } + +private: + + std::auto_ptr m_CoreDataNodeReader; + + std::vector m_ObjectFactories; +}; + +US_EXPORT_MODULE_ACTIVATOR(LegacyIO, Activator) diff --git a/Core/Code/IO/mitkBaseDataIOFactory.cpp b/Modules/LegacyIO/mitkBaseDataIOFactory.cpp similarity index 100% rename from Core/Code/IO/mitkBaseDataIOFactory.cpp rename to Modules/LegacyIO/mitkBaseDataIOFactory.cpp diff --git a/Core/Code/IO/mitkBaseDataIOFactory.h b/Modules/LegacyIO/mitkBaseDataIOFactory.h similarity index 90% rename from Core/Code/IO/mitkBaseDataIOFactory.h rename to Modules/LegacyIO/mitkBaseDataIOFactory.h index 856711816c..e00015a7a9 100644 --- a/Core/Code/IO/mitkBaseDataIOFactory.h +++ b/Modules/LegacyIO/mitkBaseDataIOFactory.h @@ -1,66 +1,67 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkBaseDataIO_h #define __mitkBaseDataIO_h +#include + #include "mitkBaseData.h" #include "itkObject.h" namespace mitk { /*! @brief BaseDataIO creates instances of BaseData objects using an object factory. @todo Add file writing method, move writers into a similar factory scheme @ingroup IO + @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ -class MITK_CORE_EXPORT BaseDataIO : public itk::Object +class DEPRECATED() LegacyIO_EXPORT BaseDataIO : public itk::Object { public: /** Standard class typedefs. */ typedef BaseDataIO Self; typedef itk::Object Superclass; typedef itk::SmartPointer Pointer; typedef itk::SmartPointer ConstPointer; /** Class Methods used to interface with the registered factories */ /** Run-time type information (and related methods). */ itkTypeMacro(BaseDataIO, Object); /** Create the appropriate BaseData depending on the particulars of the file. */ static std::vector LoadBaseDataFromFile(const std::string path, const std::string filePrefix, const std::string filePattern, bool series); protected: BaseDataIO(); ~BaseDataIO(); private: BaseDataIO(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif - - diff --git a/Core/Code/DataManagement/mitkDataNodeFactory.cpp b/Modules/LegacyIO/mitkDataNodeFactory.cpp similarity index 99% rename from Core/Code/DataManagement/mitkDataNodeFactory.cpp rename to Modules/LegacyIO/mitkDataNodeFactory.cpp index 6665197e52..47bd8a1c7b 100644 --- a/Core/Code/DataManagement/mitkDataNodeFactory.cpp +++ b/Modules/LegacyIO/mitkDataNodeFactory.cpp @@ -1,489 +1,488 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include #include #include // C-Standard library includes #include #include // STL-related includes #include #include #include #include #include // VTK-related includes #include #include #include #include #include #include #include #include #include #include #include // ITK-related includes #include #include #include #include #include #include #include #include #include #ifdef NOMINMAX # define DEF_NOMINMAX # undef NOMINMAX #endif #include #ifdef DEF_NOMINMAX # ifndef NOMINMAX # define NOMINMAX # endif # undef DEF_NOMINMAX #endif #include #include // MITK-related includes #include "mitkSurface.h" #include "mitkPointSet.h" #include "mitkStringProperty.h" #include "mitkProperties.h" //#include "mitkMaterialProperty.h" #include "mitkLevelWindowProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkScalarModeProperty.h" #include "mitkImage.h" #include "mitkLookupTableProperty.h" #include "mitkLookupTable.h" #include "mitkImageChannelSelector.h" #include "mitkImageSliceSelector.h" #include "mitkCoreObjectFactory.h" #include "mitkTransferFunctionProperty.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkProgressBar.h" #include bool mitk::DataNodeFactory::m_TextureInterpolationActive = false; // default value for texture interpolation if nothing is defined in global options (see QmitkMainTemplate.ui.h) mitk::DataNodeFactory::DataNodeFactory() { m_Serie = false; m_OldProgress = 0; this->Modified(); //ensure that a CoreObjectFactory has been instantiated mitk::CoreObjectFactory::GetInstance(); } mitk::DataNodeFactory::~DataNodeFactory() {} void mitk::DataNodeFactory::SetImageSerie(bool serie) { m_Serie = serie; } void mitk::DataNodeFactory::GenerateData() { // IF filename is something.pic, and something.pic does not exist, try to read something.pic.gz // if there are both, something.pic and something.pic.gz, only the requested file is read // not only for images, but for all formats std::ifstream exists(m_FileName.c_str()); if (!exists) { std::string testfilename = m_FileName + ".gz"; std::ifstream exists(testfilename.c_str()); if (exists.good()) { m_FileName += ".gz"; } else { testfilename = m_FileName + ".GZ"; std::ifstream exists(testfilename.c_str()); if (exists.good()) { m_FileName += ".GZ"; } else { std::string message("File does not exist, or cannot be read. Filename = "); message += m_FileName; MITK_ERROR << message; itkExceptionMacro( << message ); } } } // part for DICOM // const char *numbers = "0123456789."; // std::string::size_type first_non_number; // first_non_number = itksys::SystemTools::GetFilenameName(m_FileName).find_first_not_of ( numbers ); if (DicomSeriesReader::IsDicom(this->m_FileName) /*|| first_non_number == std::string::npos*/) { this->ReadFileSeriesTypeDCM(); } else { bool usedNewDTNF = false; // the mitkBaseDataIO class returns a pointer of a vector of BaseData objects std::vector baseDataVector = mitk::BaseDataIO::LoadBaseDataFromFile( m_FileName, m_FilePrefix, m_FilePattern, m_Serie ); if( !baseDataVector.empty() ) this->ResizeOutputs((unsigned int)baseDataVector.size()); for(int i=0; i<(int)baseDataVector.size(); i++) { mitk::BaseData::Pointer baseData = baseDataVector.at(i); if( baseData.IsNotNull() ) { usedNewDTNF = true; mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(baseData); this->SetDefaultCommonProperties( node ); this->SetOutput(this->MakeNameFromOutputIndex(i), node); } } if(!usedNewDTNF && ( m_FileName != "" ) && !(m_Serie == false)) ReadFileSeriesTypeITKImageSeriesReader(); } } void mitk::DataNodeFactory::ResizeOutputs( const unsigned int& num ) { unsigned int prevNum = this->GetNumberOfOutputs(); this->SetNumberOfIndexedOutputs( num ); for ( unsigned int i = prevNum; i < num; ++i ) { this->SetNthOutput( i, this->MakeOutput( i ).GetPointer() ); } } bool mitk::DataNodeFactory::FileNameEndsWith( const std::string& name ) { if (m_FileName.size() < name.size()) return false; return m_FileName.substr(m_FileName.size() - name.size()) == name; } bool mitk::DataNodeFactory::FilePatternEndsWith( const std::string& name ) { return m_FilePattern.find( name ) != std::string::npos; } std::string mitk::DataNodeFactory::GetBaseFileName() { return itksys::SystemTools::GetFilenameName( m_FileName ); } std::string mitk::DataNodeFactory::GetBaseFilePrefix() { return itksys::SystemTools::GetFilenameName( m_FilePrefix ); } std::string mitk::DataNodeFactory::GetDirectory() { if ( !m_FileName.empty() ) return itksys::SystemTools::GetFilenamePath( m_FileName ); if ( !m_FilePrefix.empty() ) return itksys::SystemTools::GetFilenamePath( m_FilePrefix ); return std::string(); } void mitk::DataNodeFactory::ReadFileSeriesTypeDCM() { const char* previousCLocale = setlocale(LC_NUMERIC, NULL); setlocale(LC_NUMERIC, "C"); std::locale previousCppLocale( std::cin.getloc() ); std::locale l( "C" ); std::cin.imbue(l); if ( DicomSeriesReader::IsPhilips3DDicom(this->GetFileName()) ) { MITK_INFO << "it is a Philips3D US Dicom file" << std::endl; this->ResizeOutputs(1); DataNode::Pointer node = this->GetOutput(); mitk::DicomSeriesReader::StringContainer stringvec; stringvec.push_back(this->GetFileName()); if (DicomSeriesReader::LoadDicomSeries(stringvec, *node)) { node->SetName(this->GetBaseFileName()); } setlocale(LC_NUMERIC, previousCLocale); std::cin.imbue(previousCppLocale); return; } DicomSeriesReader::FileNamesGrouping imageBlocks = DicomSeriesReader::GetSeries(this->GetDirectory(), true, this->m_SeriesRestrictions); // true = group gantry tilt images const unsigned int size = imageBlocks.size(); this->ResizeOutputs(size); ProgressBar::GetInstance()->AddStepsToDo(size); ProgressBar::GetInstance()->Progress(); unsigned int outputIndex = 0u; const DicomSeriesReader::FileNamesGrouping::const_iterator n_end = imageBlocks.end(); for (DicomSeriesReader::FileNamesGrouping::const_iterator n_it = imageBlocks.begin(); n_it != n_end; ++n_it) { const std::string &uid = n_it->first; DataNode::Pointer node = this->GetOutput(outputIndex); const DicomSeriesReader::ImageBlockDescriptor& imageBlockDescriptor( n_it->second ); MITK_INFO << "--------------------------------------------------------------------------------"; MITK_INFO << "DataNodeFactory: Loading DICOM series " << outputIndex << ": Series UID " << imageBlockDescriptor.GetSeriesInstanceUID() << std::endl; MITK_INFO << " " << imageBlockDescriptor.GetFilenames().size() << " '" << imageBlockDescriptor.GetModality() << "' files (" << imageBlockDescriptor.GetSOPClassUIDAsString() << ") loaded into 1 mitk::Image"; MITK_INFO << " multi-frame: " << (imageBlockDescriptor.IsMultiFrameImage()?"Yes":"No"); MITK_INFO << " reader support: " << DicomSeriesReader::ReaderImplementationLevelToString(imageBlockDescriptor.GetReaderImplementationLevel()); MITK_INFO << " pixel spacing type: " << DicomSeriesReader::PixelSpacingInterpretationToString( imageBlockDescriptor.GetPixelSpacingType() ); MITK_INFO << " gantry tilt corrected: " << (imageBlockDescriptor.HasGantryTiltCorrected()?"Yes":"No"); MITK_INFO << " 3D+t: " << (imageBlockDescriptor.HasMultipleTimePoints()?"Yes":"No"); MITK_INFO << "--------------------------------------------------------------------------------"; if (DicomSeriesReader::LoadDicomSeries(n_it->second.GetFilenames(), *node, true, true, true)) { std::string nodeName(uid); std::string studyDescription; if ( node->GetStringProperty( "dicom.study.StudyDescription", studyDescription ) ) { nodeName = studyDescription; std::string seriesDescription; if ( node->GetStringProperty( "dicom.series.SeriesDescription", seriesDescription ) ) { nodeName += "/" + seriesDescription; } } node->SetName(nodeName); ++outputIndex; } else { MITK_ERROR << "DataNodeFactory: Skipping series " << outputIndex << " due to some unspecified error..." << std::endl; } ProgressBar::GetInstance()->Progress(); } setlocale(LC_NUMERIC, previousCLocale); std::cin.imbue(previousCppLocale); } void mitk::DataNodeFactory::ReadFileSeriesTypeITKImageSeriesReader() { typedef itk::Image ImageType; typedef itk::ImageSeriesReader< ImageType > ReaderType; if ( ! this->GenerateFileList() ) { itkWarningMacro( "Sorry, file list could not be generated!" ); return ; } if ( m_MatchedFileNames.size() == 0 ) { itkWarningMacro( "Sorry, no files matched the given filename ("<< m_FileName <<")!" ); return ; } // // Finally, initialize the ITK-reader and load the files! // ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( m_MatchedFileNames ); try { reader->Update(); ResizeOutputs( reader->GetNumberOfOutputs() ); for ( unsigned int i = 0; i < reader->GetNumberOfOutputs(); ++i ) { //Initialize mitk image from itk mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk( reader->GetOutput( i ) ); image->SetVolume( reader->GetOutput( i )->GetBufferPointer() ); //add the mitk image to the node mitk::DataNode::Pointer node = this->GetOutput( i ); node->SetData( image ); mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New( m_FileName ); node->SetProperty( "name", nameProp ); } } catch ( const std::exception & e ) { itkWarningMacro( << e.what() ); return ; } } mitk::ColorProperty::Pointer mitk::DataNodeFactory::DefaultColorForOrgan( const std::string& organ ) { static bool initialized = false; static std::map< std::string, std::string > s_ColorMap; if (!initialized) { // all lowercase here, please! s_ColorMap.insert( std::make_pair( "ankle", "0xe38686") ); s_ColorMap.insert( std::make_pair( "appendix", "0xe38686") ); s_ColorMap.insert( std::make_pair( "blood vessels", "0xff3131") ); s_ColorMap.insert( std::make_pair( "bronchial tree", "0x3168ff") ); s_ColorMap.insert( std::make_pair( "bone", "0xd5d5d5") ); s_ColorMap.insert( std::make_pair( "brain", "0xff9cca") ); s_ColorMap.insert( std::make_pair( "coccyx", "0xe38686") ); s_ColorMap.insert( std::make_pair( "colon", "0xe38686") ); s_ColorMap.insert( std::make_pair( "cyst", "0xe38686") ); s_ColorMap.insert( std::make_pair( "elbow", "0xe38686") ); s_ColorMap.insert( std::make_pair( "eye", "0xe38686") ); s_ColorMap.insert( std::make_pair( "fallopian tube", "0xe38686") ); s_ColorMap.insert( std::make_pair( "fat", "0xff2bee") ); s_ColorMap.insert( std::make_pair( "hand", "0xe38686") ); s_ColorMap.insert( std::make_pair( "gall bladder", "0x567f18") ); s_ColorMap.insert( std::make_pair( "heart", "0xeb1d32") ); s_ColorMap.insert( std::make_pair( "hip", "0xe38686") ); s_ColorMap.insert( std::make_pair( "kidney", "0xd33f00") ); s_ColorMap.insert( std::make_pair( "knee", "0xe38686") ); s_ColorMap.insert( std::make_pair( "larynx", "0xe38686") ); s_ColorMap.insert( std::make_pair( "liver", "0xffcc3d") ); s_ColorMap.insert( std::make_pair( "lung", "0x6bdcff") ); s_ColorMap.insert( std::make_pair( "lymph node", "0xff0000") ); s_ColorMap.insert( std::make_pair( "muscle", "0xff456a") ); s_ColorMap.insert( std::make_pair( "nerve", "0xffea4f") ); s_ColorMap.insert( std::make_pair( "nose", "0xe38686") ); s_ColorMap.insert( std::make_pair( "oesophagus", "0xe38686") ); s_ColorMap.insert( std::make_pair( "ovaries", "0xe38686") ); s_ColorMap.insert( std::make_pair( "pancreas", "0xf9ab3d") ); s_ColorMap.insert( std::make_pair( "pelvis", "0xe38686") ); s_ColorMap.insert( std::make_pair( "penis", "0xe38686") ); s_ColorMap.insert( std::make_pair( "pharynx", "0xe38686") ); s_ColorMap.insert( std::make_pair( "prostate", "0xe38686") ); s_ColorMap.insert( std::make_pair( "rectum", "0xe38686") ); s_ColorMap.insert( std::make_pair( "sacrum", "0xe38686") ); s_ColorMap.insert( std::make_pair( "seminal vesicle", "0xe38686") ); s_ColorMap.insert( std::make_pair( "shoulder", "0xe38686") ); s_ColorMap.insert( std::make_pair( "spinal cord", "0xf5f93d") ); s_ColorMap.insert( std::make_pair( "spleen", "0xf96c3d") ); s_ColorMap.insert( std::make_pair( "stomach", "0xf96c3d") ); s_ColorMap.insert( std::make_pair( "teeth", "0xfffcd8") ); s_ColorMap.insert( std::make_pair( "testicles", "0xe38686") ); s_ColorMap.insert( std::make_pair( "thyroid", "0xfff694") ); s_ColorMap.insert( std::make_pair( "tongue", "0xe38686") ); s_ColorMap.insert( std::make_pair( "tumor", "0x937011") ); s_ColorMap.insert( std::make_pair( "urethra", "0xf8ff32") ); s_ColorMap.insert( std::make_pair( "urinary bladder", "0xf8ff32") ); s_ColorMap.insert( std::make_pair( "uterus", "0xe38686") ); s_ColorMap.insert( std::make_pair( "vagina", "0xe38686") ); s_ColorMap.insert( std::make_pair( "vertebra", "0xe38686") ); s_ColorMap.insert( std::make_pair( "wrist", "0xe38686") ); initialized = true; } std::string lowercaseOrgan(organ); for(unsigned int i = 0; i < organ.length(); i++) { lowercaseOrgan[i] = tolower(lowercaseOrgan[i]); } std::map< std::string, std::string >::iterator iter = s_ColorMap.find( lowercaseOrgan ); if ( iter != s_ColorMap.end() ) { std::string hexColor = iter->second; std::string hexRed = std::string("0x") + hexColor.substr( 2, 2 ); std::string hexGreen = std::string("0x") + hexColor.substr( 4, 2 ); std::string hexBlue = std::string("0x") + hexColor.substr( 6, 2 ); long int red = strtol( hexRed.c_str(), NULL, 16 ); long int green = strtol( hexGreen.c_str(), NULL, 16 ); long int blue = strtol( hexBlue.c_str(), NULL, 16 ); return ColorProperty::New( (float)red/ 255.0, (float)green/ 255.0, (float)blue/ 255.0 ); } else { // a default color (green) return ColorProperty::New( 0.0, 1.0, 0.0 ); } } void mitk::DataNodeFactory::SetDefaultCommonProperties(mitk::DataNode::Pointer &node) { // path mitk::StringProperty::Pointer pathProp = mitk::StringProperty::New( itksys::SystemTools::GetFilenamePath( m_FileName ) ); node->SetProperty( StringProperty::PATH, pathProp ); // name already defined? mitk::StringProperty::Pointer nameProp = dynamic_cast(node->GetProperty("name")); if(nameProp.IsNull() || (strcmp(nameProp->GetValue(),"No Name!")==0)) { // name already defined in BaseData mitk::StringProperty::Pointer baseDataNameProp = dynamic_cast(node->GetData()->GetProperty("name").GetPointer() ); if(baseDataNameProp.IsNull() || (strcmp(baseDataNameProp->GetValue(),"No Name!")==0)) { // name neither defined in node, nor in BaseData -> name = filename if (FileNameEndsWith( ".gz" )) m_FileName = m_FileName.substr( 0, m_FileName.length()-3 ); nameProp = mitk::StringProperty::New( itksys::SystemTools::GetFilenameWithoutLastExtension( m_FileName ) ); node->SetProperty( "name", nameProp ); } else { // name defined in BaseData! nameProp = mitk::StringProperty::New( baseDataNameProp->GetValue() ); node->SetProperty( "name", nameProp ); } } // visibility if(!node->GetProperty("visible")) node->SetVisibility(true); } - diff --git a/Core/Code/DataManagement/mitkDataNodeFactory.h b/Modules/LegacyIO/mitkDataNodeFactory.h similarity index 95% rename from Core/Code/DataManagement/mitkDataNodeFactory.h rename to Modules/LegacyIO/mitkDataNodeFactory.h index 81869f4262..76e516eb01 100644 --- a/Core/Code/DataManagement/mitkDataNodeFactory.h +++ b/Modules/LegacyIO/mitkDataNodeFactory.h @@ -1,182 +1,183 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _DATA_TREE_NODE_FACTORY_H_ #define _DATA_TREE_NODE_FACTORY_H_ #include "mitkDataNodeSource.h" #include "mitkFileSeriesReader.h" #include "mitkColorProperty.h" #include #include namespace mitk { /** * @brief Factory, which creates instances of mitk::DataNodes filled with * data read from a given file * * This class reads files, creates an appropriate mitk::BaseData and adds the * BaseData to a mitk::DataNode. This filter may produce one or more outputs * (i.e. mitk::DataNodes). The number of generated nodes can be retrieved by a * call of GetNumberOfOutputs(). * * If you want to add a new file type, you have to register the factory * of the file reader in the class mitk::BaseDataIOFactory. * @ingroup IO +* @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ -class MITK_CORE_EXPORT DataNodeFactory : public DataNodeSource, public FileSeriesReader +class DEPRECATED() LegacyIO_EXPORT DataNodeFactory : public DataNodeSource, public FileSeriesReader { public: mitkClassMacro( DataNodeFactory, DataNodeSource ); itkNewMacro( Self ); /** * Sets the filename of the file to read. * @param FileName the name of the file to read. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be read from disk. */ itkGetStringMacro( FileName ); /** * \brief Set prefix for multiple load */ itkSetStringMacro( FilePrefix ); /** * \brief Get prefix for multiple load */ itkGetStringMacro( FilePrefix ); /** * \brief Set pattern for multiple load */ itkSetStringMacro( FilePattern ); /** * \brief Get pattern for multiple load */ itkGetStringMacro( FilePattern ); /** * Nice default colors for segmentations of some "normal" organs. */ static ColorProperty::Pointer DefaultColorForOrgan( const std::string& ); void SetDefaultCommonProperties(mitk::DataNode::Pointer &node); /** * if true -> loaded image is part of a serie */ void SetImageSerie(bool serie); void AddSeriesRestriction(const std::string &tag) {m_SeriesRestrictions.push_back(tag);} static bool m_TextureInterpolationActive; protected: /** * Constructor. */ DataNodeFactory(); /** * Virtual destructor. */ virtual ~DataNodeFactory(); bool m_Serie; /** * Determines of which file type a given file is and calls the * appropriate reader function. */ virtual void GenerateData(); /** * Resizes the number of outputs of the factory. * The outputs are initialized by empty DataNodes * @param num the new number of outputs */ virtual void ResizeOutputs( const unsigned int& num ); /** * Checks if the file name m_FileName ends with the given name. * Currently, this check is done by a dumb search for name in * the filename. * @param name the extension of the file * @returns true, if the filename contains name. */ virtual bool FileNameEndsWith(const std::string& name); /** * Checks if the file pattern m_FilePattern ends with the given name. * Currently, this check is done by a dumb search for name in * the filename. * @param name the extension of the file * @returns true, if the filepattern contains name. */ virtual bool FilePatternEndsWith(const std::string& name); /** * @returns the plain filename, that is, without any directory. */ virtual std::string GetBaseFileName(); /** * @returns the plain file prefix, that is, without any directory. */ virtual std::string GetBaseFilePrefix(); /** * @returns the directory of the file name m_FileName. */ virtual std::string GetDirectory(); #ifdef MBI_INTERNAL virtual void ReadFileTypeHPSONOS(); #ifdef HAVE_IPDICOM virtual void ReadFileTypeIPDCM(); #endif /* HAVE_IPDICOM */ #ifdef USE_TUS_READER virtual void ReadFileTypeTUS(); #endif #endif /* MBI_INTERNAL */ virtual void ReadFileSeriesTypeDCM(); virtual void ReadFileSeriesTypeITKImageSeriesReader(); std::vector m_SeriesRestrictions; int m_OldProgress; }; } #endif //#ifndef __DATA_TREE_NODE_FACTORY_H diff --git a/Core/Code/IO/mitkFileSeriesReader.cpp b/Modules/LegacyIO/mitkFileSeriesReader.cpp similarity index 100% rename from Core/Code/IO/mitkFileSeriesReader.cpp rename to Modules/LegacyIO/mitkFileSeriesReader.cpp diff --git a/Core/Code/IO/mitkFileSeriesReader.h b/Modules/LegacyIO/mitkFileSeriesReader.h similarity index 90% rename from Core/Code/IO/mitkFileSeriesReader.h rename to Modules/LegacyIO/mitkFileSeriesReader.h index dc0dd67373..c545750e9d 100644 --- a/Core/Code/IO/mitkFileSeriesReader.h +++ b/Modules/LegacyIO/mitkFileSeriesReader.h @@ -1,65 +1,65 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __MITK_FILE_SERIES_READER__H_ #define __MITK_FILE_SERIES_READER__H_ -#include +#include #include #include #include #include namespace mitk { /** * Provides a function which generates a list of files from * a given prefix and pattern. * Subclasses may use this function to load a series of files. + * + * @deprecatedSince{2013_09} */ -class MITK_CORE_EXPORT FileSeriesReader : public FileReader +class DEPRECATED() LegacyIO_EXPORT FileSeriesReader : public FileReader { public: mitkClassMacro( FileSeriesReader, FileReader ); typedef std::vector< std::string > MatchedFileNames; virtual MatchedFileNames GetMatchedFileNames( ); protected: FileSeriesReader(); virtual ~FileSeriesReader(); virtual bool GenerateFileList(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; MatchedFileNames m_MatchedFileNames; }; } #endif - - diff --git a/Core/Code/IO/mitkIOAdapter.h b/Modules/LegacyIO/mitkIOAdapter.h similarity index 97% rename from Core/Code/IO/mitkIOAdapter.h rename to Modules/LegacyIO/mitkIOAdapter.h index 3f38cbede2..9ba9c6a00f 100644 --- a/Core/Code/IO/mitkIOAdapter.h +++ b/Modules/LegacyIO/mitkIOAdapter.h @@ -1,93 +1,94 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkIOAdapter_h #define __mitkIOAdapter_h +#include #include "mitkBaseProcess.h" #include "itkObject.h" namespace mitk { //##Documentation //## @brief IOAdapterBase class is an abstract adapter class for IO process objects. //## //## @ingroup IO -class MITK_CORE_EXPORT IOAdapterBase: public itk::Object +class LegacyIO_EXPORT IOAdapterBase: public itk::Object { public: /** Standard typedefs. */ typedef IOAdapterBase Self; typedef itk::Object Superclass; typedef itk::SmartPointerPointer; typedef itk::SmartPointerConstPointer; /// Create an object and return a pointer to it as a mitk::BaseProcess. virtual itk::SmartPointer CreateIOProcessObject(const std::string filename, const std::string filePrefix, const std::string filePattern) = 0; virtual bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern) = 0; protected: IOAdapterBase() {} ~IOAdapterBase() {} private: IOAdapterBase(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; //##Documentation //## @brief IOAdapter class is an adapter class for instantiation of IO process objects. //## Additional this interface defines the function CanReadFile(). //## This interface allows the target (object) the access to the adaptee (IO process object). //## @ingroup IO template class IOAdapter : public IOAdapterBase { public: /** Standard class typedefs. */ typedef IOAdapter Self; typedef itk::SmartPointer Pointer; /** Methods from mitk::BaseProcess. */ itkFactorylessNewMacro(Self); mitk::BaseProcess::Pointer CreateIOProcessObject(const std::string filename, const std::string filePrefix, const std::string filePattern) { typename T::Pointer ioProcessObject = T::New(); ioProcessObject->SetFileName(filename.c_str()); ioProcessObject->SetFilePrefix(filePrefix.c_str()); ioProcessObject->SetFilePattern(filePattern.c_str()); return ioProcessObject.GetPointer(); } virtual bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern) { return T::CanReadFile(filename, filePrefix, filePattern); } protected: IOAdapter() {} ~IOAdapter() {} private: IOAdapter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkImageWriter.cpp b/Modules/LegacyIO/mitkImageWriter.cpp similarity index 100% rename from Core/Code/IO/mitkImageWriter.cpp rename to Modules/LegacyIO/mitkImageWriter.cpp diff --git a/Core/Code/IO/mitkImageWriter.h b/Modules/LegacyIO/mitkImageWriter.h similarity index 95% rename from Core/Code/IO/mitkImageWriter.h rename to Modules/LegacyIO/mitkImageWriter.h index b8bd51241f..c31cd2ba6e 100644 --- a/Core/Code/IO/mitkImageWriter.h +++ b/Modules/LegacyIO/mitkImageWriter.h @@ -1,170 +1,172 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_IMAGE_WRITER__H_ #define _MITK_IMAGE_WRITER__H_ +#include #include namespace mitk { class Image; /** * @brief Writer for mitk::Image * * Uses the given extension (SetExtension) to decide the format to write * (.mhd is default, .pic, .tif, .png, .jpg supported yet). * @ingroup IO + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ -class MITK_CORE_EXPORT ImageWriter : public mitk::FileWriterWithInformation +class DEPRECATED() LegacyIO_EXPORT ImageWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( ImageWriter, mitk::FileWriter ); itkNewMacro( Self ); mitkWriterMacro; /** * Sets the filename of the file to write. * @param _arg the name of the file to write. */ virtual void SetFileName (const char* fileName); virtual void SetFileName (const std::string& fileName); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * \brief Explicitly set the extension to be added to the filename. * @param _arg to be added to the filename, including a "." * (e.g., ".mhd"). */ virtual void SetExtension (const char* extension); virtual void SetExtension (const std::string& extension); /** * \brief Get the extension to be added to the filename. * @returns the extension to be added to the filename (e.g., * ".mhd"). */ itkGetStringMacro( Extension ); /** * \brief Set the extension to be added to the filename to the default */ void SetDefaultExtension(); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the 0'th input object for the filter. * @param input the first input for the filter. */ void SetInput( mitk::Image* input ); //##Documentation //## @brief Return the possible file extensions for the data type associated with the writer virtual std::vector GetPossibleFileExtensions(); /** * @brief Return the extension to be added to the filename. */ virtual std::string GetFileExtension(); /** * @brief Check if the Writer can write the Content of the */ virtual bool CanWriteDataType( DataNode* ); /** * @brief Return the MimeType of the saved File. */ virtual std::string GetWritenMIMEType(); using Superclass::SetInput; /** * @brief Set the DataTreenode as Input. Important: The Writer always have a SetInput-Function. */ virtual void SetInput( DataNode* ); /** * @returns the 0'th input object of the filter. */ const mitk::Image* GetInput(); // FileWriterWithInformation methods virtual const char* GetDefaultFilename(); virtual const char *GetFileDialogPattern(); virtual const char *GetDefaultExtension(); virtual bool CanWriteBaseDataType(BaseData::Pointer data); virtual void DoWrite(BaseData::Pointer data); protected: /** * Constructor. */ ImageWriter(); /** * Virtual destructor. */ virtual ~ImageWriter(); virtual void GenerateData(); virtual void WriteByITK(mitk::Image* image, const std::string& fileName); std::string m_FileName; std::string m_FileNameWithoutExtension; std::string m_FilePrefix; std::string m_FilePattern; std::string m_Extension; std::string m_MimeType; }; } #endif //_MITK_IMAGE_WRITER__H_ diff --git a/Core/Code/IO/mitkImageWriterFactory.cpp b/Modules/LegacyIO/mitkImageWriterFactory.cpp similarity index 99% rename from Core/Code/IO/mitkImageWriterFactory.cpp rename to Modules/LegacyIO/mitkImageWriterFactory.cpp index 1f23b90ff4..85deb68f5c 100644 --- a/Core/Code/IO/mitkImageWriterFactory.cpp +++ b/Modules/LegacyIO/mitkImageWriterFactory.cpp @@ -1,76 +1,75 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkImageWriterFactory.h" #include "itkCreateObjectFunction.h" #include "itkVersion.h" #include "mitkImageWriter.h" namespace mitk { template class CreateImageWriter : public itk::CreateObjectFunctionBase { public: /** Standard class typedefs. */ typedef CreateImageWriter Self; typedef itk::SmartPointer Pointer; /** Methods from itk:LightObject. */ itkFactorylessNewMacro(Self); LightObject::Pointer CreateObject() { typename T::Pointer p = T::New(); p->Register(); return p.GetPointer(); } protected: CreateImageWriter() {} ~CreateImageWriter() {} private: CreateImageWriter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; ImageWriterFactory::ImageWriterFactory() { this->RegisterOverride("IOWriter", "ImageWriter", "Image Writer", 1, mitk::CreateImageWriter::New()); } ImageWriterFactory::~ImageWriterFactory() { } const char* ImageWriterFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; } const char* ImageWriterFactory::GetDescription() const { return "ImageWriterFactory"; } } // end namespace mitk - diff --git a/Core/Code/IO/mitkImageWriterFactory.h b/Modules/LegacyIO/mitkImageWriterFactory.h similarity index 88% rename from Core/Code/IO/mitkImageWriterFactory.h rename to Modules/LegacyIO/mitkImageWriterFactory.h index 6be37feb28..a23912e1cf 100644 --- a/Core/Code/IO/mitkImageWriterFactory.h +++ b/Modules/LegacyIO/mitkImageWriterFactory.h @@ -1,63 +1,68 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef IMAGEWRITERFACTORY_H_HEADER_INCLUDED #define IMAGEWRITERFACTORY_H_HEADER_INCLUDED +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { -class MITK_CORE_EXPORT ImageWriterFactory : public itk::ObjectFactoryBase +/** + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ +class DEPRECATED() LegacyIO_EXPORT ImageWriterFactory : public itk::ObjectFactoryBase { public: mitkClassMacro( mitk::ImageWriterFactory, itk::ObjectFactoryBase ) /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); /** Register one factory of this type */ static void RegisterOneFactory(void) { static bool IsRegistered = false; if ( !IsRegistered ) { ImageWriterFactory::Pointer imageWriterFactory = ImageWriterFactory::New(); ObjectFactoryBase::RegisterFactory( imageWriterFactory ); IsRegistered = true; } } protected: ImageWriterFactory(); ~ImageWriterFactory(); private: ImageWriterFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkItkImageFileIOFactory.cpp b/Modules/LegacyIO/mitkItkImageFileIOFactory.cpp similarity index 100% rename from Core/Code/IO/mitkItkImageFileIOFactory.cpp rename to Modules/LegacyIO/mitkItkImageFileIOFactory.cpp diff --git a/Core/Code/IO/mitkItkImageFileIOFactory.h b/Modules/LegacyIO/mitkItkImageFileIOFactory.h similarity index 90% rename from Core/Code/IO/mitkItkImageFileIOFactory.h rename to Modules/LegacyIO/mitkItkImageFileIOFactory.h index 991c9e25a0..1c1e94a7c4 100644 --- a/Core/Code/IO/mitkItkImageFileIOFactory.h +++ b/Modules/LegacyIO/mitkItkImageFileIOFactory.h @@ -1,71 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkItkImageFileIOFactory_h #define __mitkItkImageFileIOFactory_h #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { //##Documentation //## @brief Create instances of ItkImageFileReader objects using an object factory. //## //## @ingroup IO -class MITK_CORE_EXPORT ItkImageFileIOFactory : public itk::ObjectFactoryBase +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT ItkImageFileIOFactory : public itk::ObjectFactoryBase { public: /** Standard class typedefs. */ typedef ItkImageFileIOFactory Self; typedef itk::ObjectFactoryBase Superclass; typedef itk::SmartPointer Pointer; typedef itk::SmartPointer ConstPointer; /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); static ItkImageFileIOFactory* FactoryNew() { return new ItkImageFileIOFactory;} /** Run-time type information (and related methods). */ itkTypeMacro(ItkImageFileIOFactory, ObjectFactoryBase); /** Register one factory of this type */ static void RegisterOneFactory(void) { ItkImageFileIOFactory::Pointer ItkImageFileIOFactory = ItkImageFileIOFactory::New(); ObjectFactoryBase::RegisterFactory(ItkImageFileIOFactory); } protected: ItkImageFileIOFactory(); ~ItkImageFileIOFactory(); private: ItkImageFileIOFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkItkImageFileReader.cpp b/Modules/LegacyIO/mitkItkImageFileReader.cpp similarity index 100% rename from Core/Code/IO/mitkItkImageFileReader.cpp rename to Modules/LegacyIO/mitkItkImageFileReader.cpp diff --git a/Core/Code/IO/mitkItkImageFileReader.h b/Modules/LegacyIO/mitkItkImageFileReader.h similarity index 87% rename from Core/Code/IO/mitkItkImageFileReader.h rename to Modules/LegacyIO/mitkItkImageFileReader.h index 459679b4d0..09f122af44 100644 --- a/Core/Code/IO/mitkItkImageFileReader.h +++ b/Modules/LegacyIO/mitkItkImageFileReader.h @@ -1,66 +1,67 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef ItkImageFileReader_H_HEADER_INCLUDED #define ItkImageFileReader_H_HEADER_INCLUDED -#include +#include #include "mitkFileReader.h" #include "mitkImageSource.h" namespace mitk { //##Documentation //## @brief Reader to read file formats supported by itk //## @ingroup IO -class MITK_CORE_EXPORT ItkImageFileReader : public ImageSource, public FileReader +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT ItkImageFileReader : public ImageSource, public FileReader { public: mitkClassMacro(ItkImageFileReader, FileReader); /** Method for creation through the object factory. */ itkNewMacro(Self); itkSetStringMacro(FileName); itkGetStringMacro(FileName); itkSetStringMacro(FilePrefix); itkGetStringMacro(FilePrefix); itkSetStringMacro(FilePattern); itkGetStringMacro(FilePattern); static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); protected: virtual void GenerateData(); ItkImageFileReader(); ~ItkImageFileReader(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; }; } // namespace mitk #endif /* ItkImageFileReader_H_HEADER_INCLUDED */ diff --git a/Core/Code/IO/mitkItkPictureWrite.cpp b/Modules/LegacyIO/mitkItkPictureWrite.cpp similarity index 95% rename from Core/Code/IO/mitkItkPictureWrite.cpp rename to Modules/LegacyIO/mitkItkPictureWrite.cpp index a796fc5c21..381bc40da1 100644 --- a/Core/Code/IO/mitkItkPictureWrite.cpp +++ b/Modules/LegacyIO/mitkItkPictureWrite.cpp @@ -1,164 +1,163 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ +#include #include "mitkItkPictureWrite.h" #include #include #include #include #include /** Set the filenames to the specified writer in dependace on the number of images passed in */ template< class WriterType > void SetOutputNames( typename WriterType::Pointer writer, const std::string& baseFileName, unsigned int numberOfImages ) { if( numberOfImages > 1 ) { itk::NumericSeriesFileNames::Pointer numericFileNameWriter = itk::NumericSeriesFileNames::New(); std::string finalFileName = baseFileName; std::string::size_type pos = baseFileName.find_last_of(".",baseFileName.length()-1); if(pos==std::string::npos) finalFileName.append(".%d.png"); else finalFileName.insert(pos,".%d"); std::cout << "Filename: " << finalFileName << std::endl; numericFileNameWriter->SetEndIndex(numberOfImages); numericFileNameWriter->SetSeriesFormat(finalFileName.c_str()); numericFileNameWriter->Modified(); writer->SetFileNames(numericFileNameWriter->GetFileNames()); } // if the given image is an 2D-png image, do not use the numericFileNameWriter // to generate the name, since it alters the fileName given as parameter else { writer->SetFileName( baseFileName.c_str() ); } } template < typename TPixel, unsigned int VImageDimension > void _mitkItkPictureWrite(itk::Image< TPixel, VImageDimension >* itkImage, const std::string& fileName) { typedef itk::Image< TPixel, VImageDimension > TImageType; typedef itk::Image UCharOutputImage3DType; typedef itk::Image ShortOutputImage3DType; typedef itk::Image OutputImage2D_8bitType; typedef itk::Image OutputImage2D_16bitType; typedef itk::ImageSeriesWriter UCharWriterType; typedef itk::ImageSeriesWriter ShortWriterType; typedef itk::RescaleIntensityImageFilter UCharRescalerFilterType; typedef itk::RescaleIntensityImageFilter ShortRescalerFilterType; // get the size info size_t inputTypeSize = sizeof(TPixel); size_t supportedOutputMaxSize = 1; // default value 8bit // the PNG and TIFF formats can handle up-to 16-bit images if( fileName.find(".png") != std::string::npos || fileName.find(".tif") != std::string::npos ) { supportedOutputMaxSize = 2; } // get the dimension info unsigned int numberOfImages = 1; if( itkImage->GetImageDimension() > 2) numberOfImages = itkImage->GetLargestPossibleRegion().GetSize()[2]; typename ShortRescalerFilterType::Pointer sh_rescaler = ShortRescalerFilterType::New(); sh_rescaler->SetInput( itkImage ); sh_rescaler->SetOutputMinimum( 0 ); sh_rescaler->SetOutputMaximum( 65535 ); typename UCharRescalerFilterType::Pointer rescaler = UCharRescalerFilterType::New(); rescaler->SetInput( itkImage ); rescaler->SetOutputMinimum( 0 ); rescaler->SetOutputMaximum( 255 ); // if( inputTypeSize == 1) { UCharWriterType::Pointer writer = UCharWriterType::New(); SetOutputNames( writer, fileName, numberOfImages ); writer->SetInput( rescaler->GetOutput() ); writer->Update(); } // 16bit 16bit possible else if ( inputTypeSize == supportedOutputMaxSize && supportedOutputMaxSize == 2 ) { ShortWriterType::Pointer writer = ShortWriterType::New(); SetOutputNames( writer, fileName, numberOfImages ); writer->SetInput( sh_rescaler->GetOutput() ); writer->Update(); } // rescaling to maximum of supported format else { if( supportedOutputMaxSize == 2) { typename ShortWriterType::Pointer writer = ShortWriterType::New(); SetOutputNames( writer, fileName, numberOfImages ); writer->SetInput(sh_rescaler->GetOutput() ); writer->Update(); } else { typename UCharWriterType::Pointer writer = UCharWriterType::New(); SetOutputNames( writer, fileName, numberOfImages ); writer->SetInput( rescaler->GetOutput() ); writer->Update(); } } } template < typename TPixel, unsigned int VImageDimension > void _mitkItkPictureWriteComposite(itk::Image< TPixel, VImageDimension >* itkImage, const std::string& fileName) { typedef itk::Image< TPixel, VImageDimension > TImageType; typedef itk::ImageFileWriter< TImageType > WriterType; typename WriterType::Pointer simpleWriter = WriterType::New(); simpleWriter->SetFileName( fileName ); simpleWriter->SetInput( itkImage ); try { simpleWriter->Update(); } catch( itk::ExceptionObject &e) { std::cerr << "Caught exception while writing image with composite type: \n" << e.what(); } } #define InstantiateAccessFunction__mitkItkPictureWrite(pixelType, dim) \ - template MITK_CORE_EXPORT void _mitkItkPictureWrite(itk::Image*, const std::string&); + template LegacyIO_EXPORT void _mitkItkPictureWrite(itk::Image*, const std::string&); #define InstantiateAccessFunction__mitkItkPictureWriteComposite(pixelType, dim) \ - template MITK_CORE_EXPORT void _mitkItkPictureWriteComposite(itk::Image*, const std::string&); + template LegacyIO_EXPORT void _mitkItkPictureWriteComposite(itk::Image*, const std::string&); InstantiateAccessFunction(_mitkItkPictureWrite) InstantiateAccessFunctionForFixedPixelType( _mitkItkPictureWriteComposite, MITK_ACCESSBYITK_PIXEL_TYPES_SEQ MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES_SEQ) - - diff --git a/Core/Code/IO/mitkItkPictureWrite.h b/Modules/LegacyIO/mitkItkPictureWrite.h similarity index 71% rename from Core/Code/IO/mitkItkPictureWrite.h rename to Modules/LegacyIO/mitkItkPictureWrite.h index 57754c3ac0..7af773672a 100644 --- a/Core/Code/IO/mitkItkPictureWrite.h +++ b/Modules/LegacyIO/mitkItkPictureWrite.h @@ -1,40 +1,45 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /** @file mitkItkPictureWrite.h */ #ifndef MITKITKPICTUREWRITE_H #define MITKITKPICTUREWRITE_H +#include #include /** * @brief ITK-Like method to be called for writing an single-component image using the AccessByItk Macros * * @param itkImage an image with single-component pixel type + * + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ -template < typename TPixel, unsigned int VImageDimension > -void _mitkItkPictureWrite(itk::Image< TPixel, VImageDimension >* itkImage, const std::string& fileName); +DEPRECATED( template < typename TPixel, unsigned int VImageDimension > +void _mitkItkPictureWrite(itk::Image< TPixel, VImageDimension >* itkImage, const std::string& fileName) ); /** * @brief ITK-Like method to be called for writing an image * * @param itkImage an Image with single-component or composite pixel type + * + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ -template < typename TPixel, unsigned int VImageDimension > -void _mitkItkPictureWriteComposite(itk::Image< TPixel, VImageDimension >* itkImage, const std::string& fileName); +DEPRECATED( template < typename TPixel, unsigned int VImageDimension > +void _mitkItkPictureWriteComposite(itk::Image< TPixel, VImageDimension >* itkImage, const std::string& fileName) ); #endif /* MITKITKPICTUREWRITE_H */ diff --git a/Core/Code/IO/mitkPointSetIOFactory.cpp b/Modules/LegacyIO/mitkPointSetIOFactory.cpp similarity index 100% rename from Core/Code/IO/mitkPointSetIOFactory.cpp rename to Modules/LegacyIO/mitkPointSetIOFactory.cpp diff --git a/Core/Code/IO/mitkPointSetIOFactory.h b/Modules/LegacyIO/mitkPointSetIOFactory.h similarity index 90% rename from Core/Code/IO/mitkPointSetIOFactory.h rename to Modules/LegacyIO/mitkPointSetIOFactory.h index b739392faa..502b4abeb9 100644 --- a/Core/Code/IO/mitkPointSetIOFactory.h +++ b/Modules/LegacyIO/mitkPointSetIOFactory.h @@ -1,71 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkPointSetIOFactory_h #define __mitkPointSetIOFactory_h #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { //##Documentation //## @brief Create instances of PointSetReader objects using an object factory. //## //## @ingroup IO -class MITK_CORE_EXPORT PointSetIOFactory : public itk::ObjectFactoryBase +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT PointSetIOFactory : public itk::ObjectFactoryBase { public: /** Standard class typedefs. */ typedef PointSetIOFactory Self; typedef itk::ObjectFactoryBase Superclass; typedef itk::SmartPointer Pointer; typedef itk::SmartPointer ConstPointer; /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); static PointSetIOFactory* FactoryNew() { return new PointSetIOFactory;} /** Run-time type information (and related methods). */ itkTypeMacro(PointSetIOFactory, ObjectFactoryBase); /** Register one factory of this type */ static void RegisterOneFactory(void) { PointSetIOFactory::Pointer PointSetIOFactory = PointSetIOFactory::New(); ObjectFactoryBase::RegisterFactory(PointSetIOFactory); } protected: PointSetIOFactory(); ~PointSetIOFactory(); private: PointSetIOFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkPointSetReader.cpp b/Modules/LegacyIO/mitkPointSetReader.cpp similarity index 100% rename from Core/Code/IO/mitkPointSetReader.cpp rename to Modules/LegacyIO/mitkPointSetReader.cpp diff --git a/Core/Code/IO/mitkPointSetReader.h b/Modules/LegacyIO/mitkPointSetReader.h similarity index 94% rename from Core/Code/IO/mitkPointSetReader.h rename to Modules/LegacyIO/mitkPointSetReader.h index d384d11a0a..7e0041fe5f 100644 --- a/Core/Code/IO/mitkPointSetReader.h +++ b/Modules/LegacyIO/mitkPointSetReader.h @@ -1,144 +1,148 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_POINT_SET_READER__H_ #define _MITK_POINT_SET_READER__H_ +#include + #include #include #include #include #include #include namespace mitk { /** * @brief reads xml representations of mitk::PointSets from a file * * Reader for xml files containing one or multiple xml represenations of * mitk::PointSets. If multiple mitk::PointSets are stored in one file, * these are assigned to multiple outputs of the filter. The number of point * sets which have be read can be retrieven by a call to GetNumberOfOutputs() * after the pipeline update(). * The reader is able to read the old 3D Pointsets without the "specification" and "timeseries" tags and the new 4D Pointsets. * @note loading point sets from multiple files according to a given file pattern * is not yet supported! * @ingroup PSIO * @ingroup IO + * + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ -class MITK_CORE_EXPORT PointSetReader: public PointSetSource, public FileReader +class DEPRECATED() LegacyIO_EXPORT PointSetReader: public PointSetSource, public FileReader { public: mitkClassMacro( PointSetReader, FileReader ); itkNewMacro( Self ); /** * @brief Sets the filename of the file to be read * @param _arg the filename of the point set xml-file */ itkSetStringMacro( FileName ); /** * @brief Returns the filename of the point set xml-file. * @returns the filename of the point set xml-file. */ itkGetStringMacro( FileName ); /** * @warning multiple load not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple load not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple load not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple load not (yet) supported */ itkGetStringMacro( FilePattern ); static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); /** * @returns whether the last read attempt was successful or not. */ bool GetSuccess() const; protected: /** * Constructor */ PointSetReader(); /** * Virtual destructor */ virtual ~PointSetReader(); /** * Actually reads the point sets from the given file */ virtual void GenerateData(); virtual mitk::PointSet::Pointer ReadPoint(mitk::PointSet::Pointer newPointSet, TiXmlElement* currentTimeSeries, unsigned int currentTimeStep); /** * Does nothing in the current implementation */ virtual void GenerateOutputInformation(); /** * Resizes the output-objects according to the given number. * @param num the new number of output objects. */ virtual void ResizeOutputs( const unsigned int& num ); /** * Checks if the given file has appropriate * read access. * @returns true if the file exists and may be read * or false otherwise. */ virtual int CanReadFile (const char *name); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } #endif diff --git a/Core/Code/IO/mitkPointSetWriter.cpp b/Modules/LegacyIO/mitkPointSetWriter.cpp similarity index 100% rename from Core/Code/IO/mitkPointSetWriter.cpp rename to Modules/LegacyIO/mitkPointSetWriter.cpp diff --git a/Core/Code/IO/mitkPointSetWriter.h b/Modules/LegacyIO/mitkPointSetWriter.h similarity index 97% rename from Core/Code/IO/mitkPointSetWriter.h rename to Modules/LegacyIO/mitkPointSetWriter.h index 9ba6a7e216..91d3514b68 100644 --- a/Core/Code/IO/mitkPointSetWriter.h +++ b/Modules/LegacyIO/mitkPointSetWriter.h @@ -1,266 +1,270 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_POINT_SET_WRITER__H_ #define _MITK_POINT_SET_WRITER__H_ +#include + #include #include #include namespace mitk { /** * @brief XML-based writer for mitk::PointSets * * XML-based writer for mitk::PointSets. Multiple PointSets can be written in * a single XML file by simply setting multiple inputs to the filter. * Writing of multiple XML files according to a given filename pattern is not * yet supported. * @ingroup PSIO * @ingroup Process + * + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ -class MITK_CORE_EXPORT PointSetWriter : public mitk::FileWriter +class DEPRECATED() LegacyIO_EXPORT PointSetWriter : public mitk::FileWriter { public: mitkClassMacro( PointSetWriter, mitk::FileWriter ); mitkWriterMacro; itkNewMacro( Self ); typedef mitk::PointSet InputType; typedef InputType::Pointer InputTypePointer; /** * Sets the filename of the file to write. * @param FileName the name of the file to write. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the 0'th input object for the filter. * @param input the first input for the filter. */ void SetInput( InputType* input ); /** * Sets the n'th input object for the filter. If num is * larger than GetNumberOfInputs() the number of inputs is * resized appropriately. * @param input the n'th input for the filter. */ void SetInput( const unsigned int& num, InputType* input); /** * @returns the 0'th input object of the filter. */ PointSet* GetInput(); /** * @param num the index of the desired output object. * @returns the n'th input object of the filter. */ PointSet* GetInput( const unsigned int& num ); /** * @brief Return the possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); /** * @brief Return the extension to be added to the filename. */ virtual std::string GetFileExtension(); /** * @brief Check if the Writer can write the Content of the */ virtual bool CanWriteDataType( DataNode* ); /** * @brief Return the MimeType of the saved File. */ virtual std::string GetWritenMIMEType(); using mitk::FileWriter::SetInput; /** * @brief Set the DataTreenode as Input. Important: The Writer always have a SetInput-Function. */ virtual void SetInput( DataNode* ); /** * @returns whether the last write attempt was successful or not. */ bool GetSuccess() const; protected: /** * Constructor. */ PointSetWriter(); /** * Virtual destructor. */ virtual ~PointSetWriter(); /** * Writes the XML file */ virtual void GenerateData(); /** * Resizes the number of inputs of the writer. * The inputs are initialized by empty PointSets * @param num the new number of inputs */ virtual void ResizeInputs( const unsigned int& num ); /** * Converts an arbitrary type to a string. The type has to * support the << operator. This works fine at least for integral * data types as float, int, long etc. * @param value the value to convert * @returns the string representation of value */ template < typename T> std::string ConvertToString( T value ); /** * Writes an XML representation of the given point set to * an outstream. The XML-Header an root node is not included! * @param pointSet the point set to be converted to xml * @param out the stream to write to. */ void WriteXML( mitk::PointSet* pointSet, std::ofstream& out ); /** * Writes an standard xml header to the given stream. * @param file the stream in which the header is written. */ void WriteXMLHeader( std::ofstream &file ); /** Write a start element tag */ void WriteStartElement( const char *const tag, std::ofstream &file ); /** * Write an end element tag * End-Elements following character data should pass indent = false. */ void WriteEndElement( const char *const tag, std::ofstream &file, const bool& indent = true ); /** Write character data inside a tag. */ void WriteCharacterData( const char *const data, std::ofstream &file ); /** Write a start element tag */ void WriteStartElement( std::string &tag, std::ofstream &file ); /** Write an end element tag */ void WriteEndElement( std::string &tag, std::ofstream &file, const bool& indent = true ); /** Write character data inside a tag. */ void WriteCharacterData( std::string &data, std::ofstream &file ); /** Writes empty spaces to the stream according to m_IndentDepth and m_Indent */ void WriteIndent( std::ofstream& file ); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; std::string m_Extension; std::string m_MimeType; unsigned int m_IndentDepth; unsigned int m_Indent; bool m_Success; public: static const char* XML_POINT_SET; static const char* XML_TIME_SERIES; static const char* XML_TIME_SERIES_ID; static const char* XML_POINT_SET_FILE; static const char* XML_FILE_VERSION; static const char* XML_POINT; static const char* XML_SPEC; static const char* XML_ID; static const char* XML_X; static const char* XML_Y; static const char* XML_Z; static const char* VERSION_STRING; }; } #endif diff --git a/Core/Code/IO/mitkPointSetWriterFactory.cpp b/Modules/LegacyIO/mitkPointSetWriterFactory.cpp similarity index 100% rename from Core/Code/IO/mitkPointSetWriterFactory.cpp rename to Modules/LegacyIO/mitkPointSetWriterFactory.cpp diff --git a/Core/Code/IO/mitkPointSetWriterFactory.h b/Modules/LegacyIO/mitkPointSetWriterFactory.h similarity index 88% rename from Core/Code/IO/mitkPointSetWriterFactory.h rename to Modules/LegacyIO/mitkPointSetWriterFactory.h index bb63c3f17a..a3e1276938 100644 --- a/Core/Code/IO/mitkPointSetWriterFactory.h +++ b/Modules/LegacyIO/mitkPointSetWriterFactory.h @@ -1,63 +1,68 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef POINTSETWRITERFACTORY_H_HEADER_INCLUDED #define POINTSETWRITERFACTORY_H_HEADER_INCLUDED +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { -class MITK_CORE_EXPORT PointSetWriterFactory : public itk::ObjectFactoryBase +/** + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ +class DEPRECATED() LegacyIO_EXPORT PointSetWriterFactory : public itk::ObjectFactoryBase { public: mitkClassMacro( mitk::PointSetWriterFactory, itk::ObjectFactoryBase ) /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); /** Register one factory of this type */ static void RegisterOneFactory(void) { static bool IsRegistered = false; if ( !IsRegistered ) { PointSetWriterFactory::Pointer pointSetWriterFactory = PointSetWriterFactory::New(); ObjectFactoryBase::RegisterFactory( pointSetWriterFactory ); IsRegistered = true; } } protected: PointSetWriterFactory(); ~PointSetWriterFactory(); private: PointSetWriterFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkRawImageFileReader.cpp b/Modules/LegacyIO/mitkRawImageFileReader.cpp similarity index 99% rename from Core/Code/IO/mitkRawImageFileReader.cpp rename to Modules/LegacyIO/mitkRawImageFileReader.cpp index c9cc40e61c..1740fae240 100644 --- a/Core/Code/IO/mitkRawImageFileReader.cpp +++ b/Modules/LegacyIO/mitkRawImageFileReader.cpp @@ -1,186 +1,185 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkRawImageFileReader.h" #include "mitkITKImageImport.h" #include #include #include mitk::RawImageFileReader::RawImageFileReader() : m_FileName(""), m_FilePrefix(""), m_FilePattern("") { } mitk::RawImageFileReader::~RawImageFileReader() { } void mitk::RawImageFileReader::SetDimensions(unsigned int i, unsigned int dim) { if ( i > 2 ) return; this->Modified(); // TODO: this order (first modified, then set the variable) is intended?? m_Dimensions[i] = dim; } unsigned int mitk::RawImageFileReader::GetDimensions(unsigned int i) const { if ( i > 2 ) return 0; return m_Dimensions[i]; } bool mitk::RawImageFileReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern) { // First check the extension if( filename == "" ) return false; // check if image is serie if( filePattern != "" && filePrefix != "" ) return false; return true; } void mitk::RawImageFileReader::GenerateData() { mitk::Image::Pointer output = this->GetOutput(); if (this->GetOutput()==NULL) { MITK_INFO << "Error" << std::endl; } // Check to see if we can read the file given the name or prefix if ( m_FileName == "" ) { itkWarningMacro( << "File Type not supported!" ); return ; } // check file dimensionality and pixel type and perform reading according to it if (m_Dimensionality == 2) { if (m_PixelType == SCHAR) TypedGenerateData(); else if (m_PixelType == UCHAR) TypedGenerateData(); else if (m_PixelType == SSHORT) TypedGenerateData(); else if (m_PixelType == USHORT) TypedGenerateData(); else if (m_PixelType == UINT) TypedGenerateData(); else if (m_PixelType == SINT) TypedGenerateData(); else if (m_PixelType == FLOAT) TypedGenerateData(); else if (m_PixelType == DOUBLE) TypedGenerateData(); else { MITK_INFO << "Error while reading raw file: Dimensionality or pixel type not supported or not properly set" << std::endl; return; } } else if (m_Dimensionality==3) { if (m_PixelType == SCHAR) TypedGenerateData(); else if (m_PixelType == UCHAR) TypedGenerateData(); else if (m_PixelType == SSHORT) TypedGenerateData(); else if (m_PixelType == USHORT) TypedGenerateData(); else if (m_PixelType == UINT) TypedGenerateData(); else if (m_PixelType == SINT) TypedGenerateData(); else if (m_PixelType == FLOAT) TypedGenerateData(); else if (m_PixelType == DOUBLE) TypedGenerateData(); else { MITK_INFO << "Error while reading raw file: Dimensionality or pixel type not supported or not properly set" << std::endl; return; } } else { MITK_INFO << "Error while reading raw file: Dimensionality not supported" << std::endl; return; } MITK_INFO << "...reading raw finished!" << std::endl; } template < typename TPixel, unsigned int VImageDimensions > void mitk::RawImageFileReader::TypedGenerateData() { mitk::Image::Pointer output = this->GetOutput(); if (this->GetOutput()==NULL) { MITK_INFO << "Error" << std::endl; } MITK_INFO << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl; // Check to see if we can read the file given the name or prefix if ( m_FileName == "" ) { itkWarningMacro( << "File Type not supported!" ); return ; } typedef itk::Image< TPixel, VImageDimensions > ImageType; typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::RawImageIO< TPixel, VImageDimensions > IOType; typename ReaderType::Pointer reader = ReaderType::New(); typename IOType::Pointer io = IOType::New(); io->SetFileDimensionality(VImageDimensions); for (unsigned short int dim = 0; dim < VImageDimensions; ++dim) { io->SetDimensions(dim, m_Dimensions[dim] ); } if (m_Endianity == LITTLE) { io->SetByteOrderToLittleEndian(); } else if (m_Endianity == BIG) { io->SetByteOrderToBigEndian(); } else { MITK_INFO << "Warning: endianity not properly set. Resulting image might be incorrect"; } reader->SetImageIO( io ); reader->SetFileName(m_FileName.c_str()); try { reader->Update(); } catch( itk::ExceptionObject & err ) { MITK_ERROR <<"An error occurred during the raw image reading process: "; MITK_INFO << err << std::endl; } mitk::Image::Pointer image = mitk::Image::New(); mitk::CastToMitkImage(reader->GetOutput(), image); output->Initialize( image ); output->SetVolume( reader->GetOutput()->GetBufferPointer()); } - diff --git a/Core/Code/IO/mitkRawImageFileReader.h b/Modules/LegacyIO/mitkRawImageFileReader.h similarity index 93% rename from Core/Code/IO/mitkRawImageFileReader.h rename to Modules/LegacyIO/mitkRawImageFileReader.h index 7c73fd1f83..55528ca997 100644 --- a/Core/Code/IO/mitkRawImageFileReader.h +++ b/Modules/LegacyIO/mitkRawImageFileReader.h @@ -1,110 +1,109 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef RawImageFileReader_H_HEADER_INCLUDED #define RawImageFileReader_H_HEADER_INCLUDED #include "itkVector.h" -#include +#include #include "mitkFileReader.h" #include "mitkImageSource.h" namespace mitk { //##Documentation //## @brief Reader to read raw image files /** The user must set the dimensionality, the dimensions and the pixel type. If they are incorrect, the image will not be opened or the visualization will be incorrect. */ //## @ingroup IO -class MITK_CORE_EXPORT RawImageFileReader : public ImageSource, public FileReader +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT RawImageFileReader : public ImageSource, public FileReader { public: mitkClassMacro(RawImageFileReader, FileReader); /** Method for creation through the object factory. */ itkNewMacro(Self); itkSetMacro(FileName, std::string); itkSetStringMacro(FileName); itkGetMacro(FileName, std::string); itkGetStringMacro(FileName); itkSetMacro(FilePrefix, std::string); itkSetStringMacro(FilePrefix); itkGetMacro(FilePrefix, std::string); itkGetStringMacro(FilePrefix); itkSetMacro(FilePattern, std::string); itkSetStringMacro(FilePattern); itkGetMacro(FilePattern, std::string); itkGetStringMacro(FilePattern); /** Supported pixel types. */ typedef enum {UCHAR,SCHAR,USHORT,SSHORT, UINT, SINT, FLOAT, DOUBLE} IOPixelType; itkSetMacro(PixelType, IOPixelType); /** Endianity of bits. */ typedef enum {LITTLE, BIG} EndianityType; itkSetMacro(Endianity, EndianityType); itkSetMacro(Dimensionality, int); itkGetMacro(Dimensionality, int); /** Image dimensions must be set one by one, starting from dimension 0. */ void SetDimensions(unsigned int i, unsigned int dim); unsigned int GetDimensions(unsigned int i) const; static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); protected: RawImageFileReader(); ~RawImageFileReader(); virtual void GenerateData(); template < typename TPixel, unsigned int VImageDimensions > void TypedGenerateData(); /** Name of file to be read.*/ std::string m_FileName; /** File prefix. */ std::string m_FilePrefix; /** File pattern. */ std::string m_FilePattern; /** Pixel type of image to be read. Must be of type IOPixelType. */ IOPixelType m_PixelType; /** Dimensionality of file to be read. Can be 2 or 3. */ int m_Dimensionality; /** Endianity. Must be set to LITTLE or BIG. Default is BIG. */ EndianityType m_Endianity; /** Vector containing dimensions of image to be read. */ itk::Vector m_Dimensions; }; } // namespace mitk #endif /* RawImageFileReader_H_HEADER_INCLUDED */ - - diff --git a/Core/Code/IO/mitkSTLFileIOFactory.cpp b/Modules/LegacyIO/mitkSTLFileIOFactory.cpp similarity index 100% rename from Core/Code/IO/mitkSTLFileIOFactory.cpp rename to Modules/LegacyIO/mitkSTLFileIOFactory.cpp diff --git a/Core/Code/IO/mitkSTLFileIOFactory.h b/Modules/LegacyIO/mitkSTLFileIOFactory.h similarity index 90% rename from Core/Code/IO/mitkSTLFileIOFactory.h rename to Modules/LegacyIO/mitkSTLFileIOFactory.h index eee06b2694..9cc493c758 100644 --- a/Core/Code/IO/mitkSTLFileIOFactory.h +++ b/Modules/LegacyIO/mitkSTLFileIOFactory.h @@ -1,71 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkSTLFileIOFactory_h #define __mitkSTLFileIOFactory_h #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { //##Documentation //## @brief Create instances of STLFileReader objects using an object factory. //## //## @ingroup IO -class MITK_CORE_EXPORT STLFileIOFactory : public itk::ObjectFactoryBase +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT STLFileIOFactory : public itk::ObjectFactoryBase { public: /** Standard class typedefs. */ typedef STLFileIOFactory Self; typedef itk::ObjectFactoryBase Superclass; typedef itk::SmartPointer Pointer; typedef itk::SmartPointer ConstPointer; /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); static STLFileIOFactory* FactoryNew() { return new STLFileIOFactory;} /** Run-time type information (and related methods). */ itkTypeMacro(STLFileIOFactory, ObjectFactoryBase); /** Register one factory of this type */ static void RegisterOneFactory(void) { STLFileIOFactory::Pointer STLFileIOFactory = STLFileIOFactory::New(); ObjectFactoryBase::RegisterFactory(STLFileIOFactory); } protected: STLFileIOFactory(); ~STLFileIOFactory(); private: STLFileIOFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkSTLFileReader.cpp b/Modules/LegacyIO/mitkSTLFileReader.cpp similarity index 100% rename from Core/Code/IO/mitkSTLFileReader.cpp rename to Modules/LegacyIO/mitkSTLFileReader.cpp diff --git a/Core/Code/IO/mitkSTLFileReader.h b/Modules/LegacyIO/mitkSTLFileReader.h similarity index 88% rename from Core/Code/IO/mitkSTLFileReader.h rename to Modules/LegacyIO/mitkSTLFileReader.h index 834106457a..a938c6ffe4 100644 --- a/Core/Code/IO/mitkSTLFileReader.h +++ b/Modules/LegacyIO/mitkSTLFileReader.h @@ -1,58 +1,59 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef STLFileReader_H_HEADER_INCLUDED #define STLFileReader_H_HEADER_INCLUDED -#include +#include #include "mitkSurfaceSource.h" namespace mitk { //##Documentation //## @brief Reader to read files in stl-format //## @ingroup IO -class MITK_CORE_EXPORT STLFileReader : public SurfaceSource +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT STLFileReader : public SurfaceSource { public: mitkClassMacro(STLFileReader, SurfaceSource); /** Method for creation through the object factory. */ itkNewMacro(Self); itkSetStringMacro(FileName); itkGetStringMacro(FileName); itkSetStringMacro(FilePrefix); itkGetStringMacro(FilePrefix); itkSetStringMacro(FilePattern); itkGetStringMacro(FilePattern); static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); protected: virtual void GenerateData(); STLFileReader(); ~STLFileReader(); std::string m_FileName, m_FilePrefix, m_FilePattern; }; } // namespace mitk #endif /* STLFileReader_H_HEADER_INCLUDED */ diff --git a/Core/Code/IO/mitkSurfaceVtkWriter.cpp b/Modules/LegacyIO/mitkSurfaceVtkWriter.cpp similarity index 99% rename from Core/Code/IO/mitkSurfaceVtkWriter.cpp rename to Modules/LegacyIO/mitkSurfaceVtkWriter.cpp index b728067b93..15627385c6 100644 --- a/Core/Code/IO/mitkSurfaceVtkWriter.cpp +++ b/Modules/LegacyIO/mitkSurfaceVtkWriter.cpp @@ -1,88 +1,86 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "mitkSurfaceVtkWriter.h" #include "mitkSurfaceVtkWriter.txx" namespace mitk { template<> void SurfaceVtkWriter::SetDefaultExtension() { m_Extension = ".stl"; m_WriterWriteHasReturnValue = false; } template<> void SurfaceVtkWriter::SetDefaultExtension() { m_Extension = ".vtk"; m_WriterWriteHasReturnValue = false; } template<> void SurfaceVtkWriter::SetDefaultExtension() { m_Extension = ".vtp"; m_WriterWriteHasReturnValue = true; } template<> void SurfaceVtkWriter::ExecuteWrite( VtkWriterType* vtkWriter ) { if ( vtkWriter->Write() == 0 || vtkWriter->GetErrorCode() != 0 ) { itkExceptionMacro(<<"Error during surface writing: " << vtkErrorCode::GetStringFromErrorCode(vtkWriter->GetErrorCode()) ); } } template<> std::vector SurfaceVtkWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".stl"); possibleFileExtensions.push_back(".obj"); return possibleFileExtensions; } template<> std::vector SurfaceVtkWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".vtk"); possibleFileExtensions.push_back(".obj"); return possibleFileExtensions; } template<> std::vector SurfaceVtkWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".vtp"); possibleFileExtensions.push_back(".obj"); return possibleFileExtensions; } template class SurfaceVtkWriter; template class SurfaceVtkWriter; template class SurfaceVtkWriter; } - - diff --git a/Core/Code/IO/mitkSurfaceVtkWriter.h b/Modules/LegacyIO/mitkSurfaceVtkWriter.h similarity index 95% rename from Core/Code/IO/mitkSurfaceVtkWriter.h rename to Modules/LegacyIO/mitkSurfaceVtkWriter.h index 5761555988..ae4310ef73 100644 --- a/Core/Code/IO/mitkSurfaceVtkWriter.h +++ b/Modules/LegacyIO/mitkSurfaceVtkWriter.h @@ -1,203 +1,206 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_SURFACE_VTK_WRITER__H_ #define _MITK_SURFACE_VTK_WRITER__H_ #include #include #include #include +#include #include #include #include #include #include class vtkTransformPolyDataFilter; namespace mitk { /** * @brief VTK-based writer for mitk::Surface * * The mitk::Surface is written using the VTK-writer-type provided as the * template argument. If the mitk::Surface contains multiple points of * time, multiple files are written. The life-span (time-bounds) of each * each point of time is included in the filename according to the * following scheme: * <filename>_S<timebounds[0]>E<timebounds[1]>_T<framenumber> * (S=start, E=end, T=time). * Writing of multiple files according to a given filename pattern is not * yet supported. * @ingroup Process + * + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ template -class MITK_CORE_EXPORT SurfaceVtkWriter : public mitk::FileWriter +class DEPRECATED() LegacyIO_EXPORT SurfaceVtkWriter : public mitk::FileWriter { public: mitkClassMacro( SurfaceVtkWriter, mitk::FileWriter ); itkNewMacro( Self ); mitkWriterMacro; typedef VTKWRITER VtkWriterType; /** * Sets the filename of the file to write. * @param _arg the name of the file to write. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * \brief Explicitly set the extension to be added to the filename. * @param _arg to be added to the filename, including a "." * (e.g., ".vtk"). * * Partial template specialization is used for some vtk-writer types * to set a default extension. */ itkSetStringMacro( Extension ); /** * \brief Get the extension to be added to the filename. * @returns the extension to be added to the filename (e.g., * ".vtk"). */ itkGetStringMacro( Extension ); /** * \brief Set the extension to be added to the filename to the default * * Partial template specialization is used for some vtk-writer types * to define the default extension. */ void SetDefaultExtension(); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the 0'th input object for the filter. * @param input the first input for the filter. */ void SetInput( mitk::Surface* input ); /** * @returns the 0'th input object of the filter. */ const mitk::Surface* GetInput(); /** * @brief Return the extension to be added to the filename. */ virtual std::string GetFileExtension(); /** * @brief Check if the Writer can write the Content of the DataTreenode. */ virtual bool CanWriteDataType( DataNode* ); /** * @brief Return the MimeType of the saved File. */ virtual std::string GetWritenMIMEType(); using Superclass::SetInput; /** * @brief Set the DataTreenode as Input. Important: The Writer always have a SetInput-Function. */ virtual void SetInput( DataNode* ); VtkWriterType* GetVtkWriter() { return m_VtkWriter; } /** * @brief Return the possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); protected: /** * Constructor. */ SurfaceVtkWriter(); /** * Virtual destructor. */ virtual ~SurfaceVtkWriter(); virtual void GenerateData(); void ExecuteWrite( VtkWriterType* vtkWriter ); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; std::string m_Extension; std::string m_MimeType; vtkSmartPointer m_VtkWriter; bool m_WriterWriteHasReturnValue; }; -#ifndef Mitk_EXPORTS +#ifndef LegacyIO_EXPORTS extern template class SurfaceVtkWriter; extern template class SurfaceVtkWriter; extern template class SurfaceVtkWriter; #endif } #endif //_MITK_SURFACE_VTK_WRITER__H_ diff --git a/Core/Code/IO/mitkSurfaceVtkWriter.txx b/Modules/LegacyIO/mitkSurfaceVtkWriter.txx similarity index 100% rename from Core/Code/IO/mitkSurfaceVtkWriter.txx rename to Modules/LegacyIO/mitkSurfaceVtkWriter.txx diff --git a/Core/Code/IO/mitkSurfaceVtkWriterFactory.cpp b/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.cpp similarity index 100% rename from Core/Code/IO/mitkSurfaceVtkWriterFactory.cpp rename to Modules/LegacyIO/mitkSurfaceVtkWriterFactory.cpp diff --git a/Core/Code/IO/mitkSurfaceVtkWriterFactory.h b/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.h similarity index 88% rename from Core/Code/IO/mitkSurfaceVtkWriterFactory.h rename to Modules/LegacyIO/mitkSurfaceVtkWriterFactory.h index 00f5522024..7654a3a3ac 100644 --- a/Core/Code/IO/mitkSurfaceVtkWriterFactory.h +++ b/Modules/LegacyIO/mitkSurfaceVtkWriterFactory.h @@ -1,66 +1,68 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef SURFACEWRITERFACTORY_H_HEADER_INCLUDED #define SURFACEWRITERFACTORY_H_HEADER_INCLUDED +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { -class MITK_CORE_EXPORT SurfaceVtkWriterFactory : public itk::ObjectFactoryBase +/** + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + */ +class DEPRECATED() LegacyIO_EXPORT SurfaceVtkWriterFactory : public itk::ObjectFactoryBase { public: mitkClassMacro( mitk::SurfaceVtkWriterFactory, itk::ObjectFactoryBase ) /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); /** Register one factory of this type */ static void RegisterOneFactory(void) { static bool IsRegistered = false; if ( !IsRegistered ) { SurfaceVtkWriterFactory::Pointer surfaceVtkWriterFactory = SurfaceVtkWriterFactory::New(); ObjectFactoryBase::RegisterFactory( surfaceVtkWriterFactory ); IsRegistered = true; } } protected: SurfaceVtkWriterFactory(); ~SurfaceVtkWriterFactory(); private: SurfaceVtkWriterFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif - - - diff --git a/Core/Code/IO/mitkVtiFileIOFactory.cpp b/Modules/LegacyIO/mitkVtiFileIOFactory.cpp similarity index 100% rename from Core/Code/IO/mitkVtiFileIOFactory.cpp rename to Modules/LegacyIO/mitkVtiFileIOFactory.cpp diff --git a/Core/Code/IO/mitkVtiFileIOFactory.h b/Modules/LegacyIO/mitkVtiFileIOFactory.h similarity index 90% rename from Core/Code/IO/mitkVtiFileIOFactory.h rename to Modules/LegacyIO/mitkVtiFileIOFactory.h index 1e77fa0b81..c2f67ed976 100644 --- a/Core/Code/IO/mitkVtiFileIOFactory.h +++ b/Modules/LegacyIO/mitkVtiFileIOFactory.h @@ -1,71 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkVtiFileIOFactory_h #define __mitkVtiFileIOFactory_h #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { //##Documentation //## @brief Create instances of VtiFileReader objects using an object factory. //## //## @ingroup IO -class MITK_CORE_EXPORT VtiFileIOFactory : public itk::ObjectFactoryBase +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT VtiFileIOFactory : public itk::ObjectFactoryBase { public: /** Standard class typedefs. */ typedef VtiFileIOFactory Self; typedef itk::ObjectFactoryBase Superclass; typedef itk::SmartPointer Pointer; typedef itk::SmartPointer ConstPointer; /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); static VtiFileIOFactory* FactoryNew() { return new VtiFileIOFactory;} /** Run-time type information (and related methods). */ itkTypeMacro(VtiFileIOFactory, ObjectFactoryBase); /** Register one factory of this type */ static void RegisterOneFactory(void) { VtiFileIOFactory::Pointer VtiFileIOFactory = VtiFileIOFactory::New(); ObjectFactoryBase::RegisterFactory(VtiFileIOFactory); } protected: VtiFileIOFactory(); ~VtiFileIOFactory(); private: VtiFileIOFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkVtiFileReader.cpp b/Modules/LegacyIO/mitkVtiFileReader.cpp similarity index 100% rename from Core/Code/IO/mitkVtiFileReader.cpp rename to Modules/LegacyIO/mitkVtiFileReader.cpp diff --git a/Core/Code/IO/mitkVtiFileReader.h b/Modules/LegacyIO/mitkVtiFileReader.h similarity index 88% rename from Core/Code/IO/mitkVtiFileReader.h rename to Modules/LegacyIO/mitkVtiFileReader.h index f5411c4cb7..e61f2b2eb4 100644 --- a/Core/Code/IO/mitkVtiFileReader.h +++ b/Modules/LegacyIO/mitkVtiFileReader.h @@ -1,70 +1,71 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef VtiFileReader_H_HEADER_INCLUDED #define VtiFileReader_H_HEADER_INCLUDED -#include +#include #include "mitkFileReader.h" #include "mitkImageSource.h" namespace mitk { //##Documentation //## @brief Reader to read image files in vtk file format //## @ingroup IO -class MITK_CORE_EXPORT VtiFileReader : public ImageSource, public FileReader +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT VtiFileReader : public ImageSource, public FileReader { public: mitkClassMacro(VtiFileReader, FileReader); /** Method for creation through the object factory. */ itkNewMacro(Self); itkSetStringMacro(FileName); itkGetStringMacro(FileName); itkSetStringMacro(FilePrefix); itkGetStringMacro(FilePrefix); itkSetStringMacro(FilePattern); itkGetStringMacro(FilePattern); static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); protected: VtiFileReader(); ~VtiFileReader(); virtual void GenerateData(); //##Description //## @brief Time when Header was last read //itk::TimeStamp m_ReadHeaderTime; protected: std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; }; } // namespace mitk #endif /* VtiFileReader_H_HEADER_INCLUDED */ diff --git a/Core/Code/IO/mitkVtkImageIOFactory.cpp b/Modules/LegacyIO/mitkVtkImageIOFactory.cpp similarity index 100% rename from Core/Code/IO/mitkVtkImageIOFactory.cpp rename to Modules/LegacyIO/mitkVtkImageIOFactory.cpp diff --git a/Core/Code/IO/mitkVtkImageIOFactory.h b/Modules/LegacyIO/mitkVtkImageIOFactory.h similarity index 90% rename from Core/Code/IO/mitkVtkImageIOFactory.h rename to Modules/LegacyIO/mitkVtkImageIOFactory.h index b05e8ebede..06fdf564c6 100644 --- a/Core/Code/IO/mitkVtkImageIOFactory.h +++ b/Modules/LegacyIO/mitkVtkImageIOFactory.h @@ -1,71 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkVtkImageIOFactory_h #define __mitkVtkImageIOFactory_h #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { //##Documentation //## @brief Create instances of VtkImageReader objects using an object factory. //## //## @ingroup IO -class MITK_CORE_EXPORT VtkImageIOFactory : public itk::ObjectFactoryBase +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT VtkImageIOFactory : public itk::ObjectFactoryBase { public: /** Standard class typedefs. */ typedef VtkImageIOFactory Self; typedef itk::ObjectFactoryBase Superclass; typedef itk::SmartPointer Pointer; typedef itk::SmartPointer ConstPointer; /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); static VtkImageIOFactory* FactoryNew() { return new VtkImageIOFactory;} /** Run-time type information (and related methods). */ itkTypeMacro(VtkImageIOFactory, ObjectFactoryBase); /** Register one factory of this type */ static void RegisterOneFactory(void) { VtkImageIOFactory::Pointer VtkImageIOFactory = VtkImageIOFactory::New(); ObjectFactoryBase::RegisterFactory(VtkImageIOFactory); } protected: VtkImageIOFactory(); ~VtkImageIOFactory(); private: VtkImageIOFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkVtkImageReader.cpp b/Modules/LegacyIO/mitkVtkImageReader.cpp similarity index 100% rename from Core/Code/IO/mitkVtkImageReader.cpp rename to Modules/LegacyIO/mitkVtkImageReader.cpp diff --git a/Core/Code/IO/mitkVtkImageReader.h b/Modules/LegacyIO/mitkVtkImageReader.h similarity index 88% rename from Core/Code/IO/mitkVtkImageReader.h rename to Modules/LegacyIO/mitkVtkImageReader.h index 06f7ba0f48..71a7f24804 100644 --- a/Core/Code/IO/mitkVtkImageReader.h +++ b/Modules/LegacyIO/mitkVtkImageReader.h @@ -1,70 +1,71 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef VtkImageReader_H_HEADER_INCLUDED #define VtkImageReader_H_HEADER_INCLUDED -#include +#include #include "mitkFileReader.h" #include "mitkImageSource.h" namespace mitk { //##Documentation //## @brief Reader to read image files in vtk file format //## @ingroup IO -class MITK_CORE_EXPORT VtkImageReader : public ImageSource, public FileReader +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT VtkImageReader : public ImageSource, public FileReader { public: mitkClassMacro(VtkImageReader, FileReader); /** Method for creation through the object factory. */ itkNewMacro(Self); itkSetStringMacro(FileName); itkGetStringMacro(FileName); itkSetStringMacro(FilePrefix); itkGetStringMacro(FilePrefix); itkSetStringMacro(FilePattern); itkGetStringMacro(FilePattern); static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); protected: VtkImageReader(); ~VtkImageReader(); virtual void GenerateData(); //##Description //## @brief Time when Header was last read //itk::TimeStamp m_ReadHeaderTime; protected: std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; }; } // namespace mitk #endif /* VtkImageReader_H_HEADER_INCLUDED */ diff --git a/Core/Code/IO/mitkVtkSurfaceIOFactory.cpp b/Modules/LegacyIO/mitkVtkSurfaceIOFactory.cpp similarity index 100% rename from Core/Code/IO/mitkVtkSurfaceIOFactory.cpp rename to Modules/LegacyIO/mitkVtkSurfaceIOFactory.cpp diff --git a/Core/Code/IO/mitkVtkSurfaceIOFactory.h b/Modules/LegacyIO/mitkVtkSurfaceIOFactory.h similarity index 90% rename from Core/Code/IO/mitkVtkSurfaceIOFactory.h rename to Modules/LegacyIO/mitkVtkSurfaceIOFactory.h index 427a0228ed..31079913d3 100644 --- a/Core/Code/IO/mitkVtkSurfaceIOFactory.h +++ b/Modules/LegacyIO/mitkVtkSurfaceIOFactory.h @@ -1,71 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkVtkSurfaceIOFactory_h #define __mitkVtkSurfaceIOFactory_h #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif +#include + #include "itkObjectFactoryBase.h" #include "mitkBaseData.h" namespace mitk { //##Documentation //## @brief Create instances of VtkSurfaceReader objects using an object factory. //## //## @ingroup IO -class MITK_CORE_EXPORT VtkSurfaceIOFactory : public itk::ObjectFactoryBase +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT VtkSurfaceIOFactory : public itk::ObjectFactoryBase { public: /** Standard class typedefs. */ typedef VtkSurfaceIOFactory Self; typedef itk::ObjectFactoryBase Superclass; typedef itk::SmartPointer Pointer; typedef itk::SmartPointer ConstPointer; /** Class methods used to interface with the registered factories. */ virtual const char* GetITKSourceVersion(void) const; virtual const char* GetDescription(void) const; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); static VtkSurfaceIOFactory* FactoryNew() { return new VtkSurfaceIOFactory;} /** Run-time type information (and related methods). */ itkTypeMacro(VtkSurfaceIOFactory, ObjectFactoryBase); /** Register one factory of this type */ static void RegisterOneFactory(void) { VtkSurfaceIOFactory::Pointer VtkSurfaceIOFactory = VtkSurfaceIOFactory::New(); ObjectFactoryBase::RegisterFactory(VtkSurfaceIOFactory); } protected: VtkSurfaceIOFactory(); ~VtkSurfaceIOFactory(); private: VtkSurfaceIOFactory(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; } // end namespace mitk #endif diff --git a/Core/Code/IO/mitkVtkSurfaceReader.cpp b/Modules/LegacyIO/mitkVtkSurfaceReader.cpp similarity index 100% rename from Core/Code/IO/mitkVtkSurfaceReader.cpp rename to Modules/LegacyIO/mitkVtkSurfaceReader.cpp diff --git a/Core/Code/IO/mitkVtkSurfaceReader.h b/Modules/LegacyIO/mitkVtkSurfaceReader.h similarity index 88% rename from Core/Code/IO/mitkVtkSurfaceReader.h rename to Modules/LegacyIO/mitkVtkSurfaceReader.h index 51c6e0592d..7f07f0e8e0 100644 --- a/Core/Code/IO/mitkVtkSurfaceReader.h +++ b/Modules/LegacyIO/mitkVtkSurfaceReader.h @@ -1,58 +1,59 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef VtkSurfaceReader_H_HEADER_INCLUDED #define VtkSurfaceReader_H_HEADER_INCLUDED -#include +#include #include "mitkSurfaceSource.h" namespace mitk { //##Documentation //## @brief Reader to read surface files in vtk-format //## @ingroup IO -class MITK_CORE_EXPORT VtkSurfaceReader : public SurfaceSource +//## @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. +class DEPRECATED() LegacyIO_EXPORT VtkSurfaceReader : public SurfaceSource { public: mitkClassMacro(VtkSurfaceReader, SurfaceSource); /** Method for creation through the object factory. */ itkNewMacro(Self); itkSetStringMacro(FileName); itkGetStringMacro(FileName); itkSetStringMacro(FilePrefix); itkGetStringMacro(FilePrefix); itkSetStringMacro(FilePattern); itkGetStringMacro(FilePattern); static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); protected: virtual void GenerateData(); VtkSurfaceReader(); ~VtkSurfaceReader(); std::string m_FileName, m_FilePrefix, m_FilePattern; }; } // namespace mitk #endif /* VtkSurfaceReader_H_HEADER_INCLUDED */ diff --git a/Core/Code/IO/vtkPointSetXMLParser.cpp b/Modules/LegacyIO/vtkPointSetXMLParser.cpp similarity index 99% rename from Core/Code/IO/vtkPointSetXMLParser.cpp rename to Modules/LegacyIO/vtkPointSetXMLParser.cpp index ab4f81c94d..e61eaf830b 100644 --- a/Core/Code/IO/vtkPointSetXMLParser.cpp +++ b/Modules/LegacyIO/vtkPointSetXMLParser.cpp @@ -1,205 +1,202 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "vtkPointSetXMLParser.h" #include "vtkObjectFactory.h" #include "mitkPointSetWriter.h" #include "mitkOperation.h" #include "mitkInteractionConst.h" #include "mitkPointOperation.h" namespace mitk { vtkStandardNewMacro(vtkPointSetXMLParser); } mitk::vtkPointSetXMLParser::vtkPointSetXMLParser() { } mitk::vtkPointSetXMLParser::~vtkPointSetXMLParser() { } int mitk::vtkPointSetXMLParser::InitializeParser() { vtkXMLParser::InitializeParser(); std::istream* stream = this -> GetStream(); if (!stream) { vtkErrorMacro("no stream available in XML file reader"); this->ParseError = 1; return 0; } m_PreviousLocale = stream->getloc(); std::locale I("C"); stream->imbue(I); return 1; } int mitk::vtkPointSetXMLParser::CleanupParser() { std::istream* stream = this -> GetStream(); if (!stream) { vtkErrorMacro("no stream available in XML file reader"); this->ParseError = 1; return 0; } stream->imbue( m_PreviousLocale ); vtkXMLParser::CleanupParser(); return 1; } void mitk::vtkPointSetXMLParser::StartElement ( const char *name, const char ** /*atts */) { std::string currentElement = name; // // when a new point set begins in the file, create a new // mitk::point set and store it in m_PointSetList // if ( currentElement == mitk::PointSetWriter::XML_POINT_SET ) { m_CurrentPointSet = PointSetType::New(); } // // when a new point begins, initialize it to zero. // else if ( currentElement == mitk::PointSetWriter::XML_POINT ) { m_CurrentPoint[ 0 ] = 0.0f; m_CurrentPoint[ 1 ] = 0.0f; m_CurrentPoint[ 2 ] = 0.0f; m_CurId.clear(); m_CurXString.clear(); m_CurYString.clear(); m_CurZString.clear(); } // // the current element is pushed on to the stack // to be able to detect some errors in the xml file // m_ParseStack.push( currentElement ); } void mitk::vtkPointSetXMLParser::EndElement ( const char *name ) { std::string currentElement = name; // // make sure, that the current end element matches with the // last start tag // if ( m_ParseStack.top() != currentElement ) { MITK_ERROR << "Top of parse stack ( " << m_ParseStack.top() << " ) is != currentEndElement ( " << currentElement << " )!" << std::endl; } m_ParseStack.pop(); // // After a complete point set has been parsed, its // output information is updated and it is inserted into the list // of parsed point sets. // if (currentElement == mitk::PointSetWriter::XML_POINT_SET) { m_CurrentPointSet->UpdateOutputInformation(); m_PointSetList.push_back( m_CurrentPointSet ); } // // if we have finished parsing a point, insert it to the current // point set. // else if ( currentElement == mitk::PointSetWriter::XML_POINT ) { m_CurrentPointId = ParsePointIdentifier( m_CurId ); m_CurrentPoint[ 0 ] = ParseScalarType( m_CurXString ); m_CurrentPoint[ 1 ] = ParseScalarType( m_CurYString ); m_CurrentPoint[ 2 ] = ParseScalarType( m_CurZString ); mitk::PointOperation popInsert( mitk::OpINSERT, m_CurrentPoint, m_CurrentPointId ); mitk::PointOperation popDeactivate( mitk::OpDESELECTPOINT, m_CurrentPoint, m_CurrentPointId ); assert( m_CurrentPointSet.IsNotNull() ); m_CurrentPointSet->ExecuteOperation( &popInsert ); m_CurrentPointSet->ExecuteOperation( &popDeactivate ); } } void mitk::vtkPointSetXMLParser::CharacterDataHandler ( const char *inData, int inLength ) { std::string currentElement = m_ParseStack.top(); if ( currentElement == mitk::PointSetWriter::XML_ID ) { m_CurId.append( inData, inLength ); } else if ( currentElement == mitk::PointSetWriter::XML_X ) { m_CurXString.append(inData, inLength); } else if ( currentElement == mitk::PointSetWriter::XML_Y ) { m_CurYString.append(inData, inLength); } else if ( currentElement == mitk::PointSetWriter::XML_Z ) { m_CurZString.append(inData, inLength); } } mitk::ScalarType mitk::vtkPointSetXMLParser::ParseScalarType( const std::string &data ) { std::istringstream stm; stm.str(data); ScalarType number; stm >>number; return number; } mitk::vtkPointSetXMLParser::PointIdentifier mitk::vtkPointSetXMLParser::ParsePointIdentifier( const std::string &data ) { std::istringstream stm; stm.str(data); PointIdentifier pointID; stm >>pointID; return pointID; } mitk::vtkPointSetXMLParser::PointSetList mitk::vtkPointSetXMLParser::GetParsedPointSets() { return m_PointSetList; } - - - diff --git a/Core/Code/IO/vtkPointSetXMLParser.h b/Modules/LegacyIO/vtkPointSetXMLParser.h similarity index 94% rename from Core/Code/IO/vtkPointSetXMLParser.h rename to Modules/LegacyIO/vtkPointSetXMLParser.h index 244e6595bc..34e4dbe376 100644 --- a/Core/Code/IO/vtkPointSetXMLParser.h +++ b/Modules/LegacyIO/vtkPointSetXMLParser.h @@ -1,136 +1,139 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _VTK_POINT_SET_XML_READER__H_ #define _VTK_POINT_SET_XML_READER__H_ +#include #include #include #include #include #include namespace mitk { /** * @brief Implementation of the vtkXMLParser interface for reading mitk::PointSets. * * This class implements the XMLParser interface of the vtkXMLParser which is based * on expat. It is used by the mitk::PointSetReader and is NOT INTENDED TO BE USED * FROM THE END-USER. If you want to read point sets, use the mitk::PointSetReader. * @ingroup Process + * + * @deprecatedSince{2013_09} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ -class MITK_CORE_EXPORT vtkPointSetXMLParser : public vtkXMLParser +class DEPRECATED() LegacyIO_EXPORT vtkPointSetXMLParser : public vtkXMLParser { public: vtkTypeMacro(vtkPointSetXMLParser,vtkXMLParser); static vtkPointSetXMLParser* New(); typedef mitk::PointSet PointSetType; typedef std::stack< std::string > ParseStack; typedef std::list< PointSetType::Pointer > PointSetList; typedef PointSetType::DataType::PointIdentifier PointIdentifier; typedef PointSetType::PointType PointType; virtual int InitializeParser(); virtual int CleanupParser(); /** * Handler function which is called, when a new xml start-tag * has been parsed. */ virtual void StartElement (const char *name, const char **atts); /** * Handler function which is called, when a xml end-tag * has been parsed. */ virtual void EndElement (const char *name); /** * Handler function which is called, if characted data has been * parsed by expat. * @param inData a char array containing the parsed string data * @param inLength the length of the parsed data string. */ virtual void CharacterDataHandler (const char *inData, int inLength); /** * Converts the given data to mitk::ScalarType. */ virtual mitk::ScalarType ParseScalarType(const std::string &data); /** * Converts the given data to an PointIdentifier */ virtual PointIdentifier ParsePointIdentifier(const std::string &data); /** * @returns the list of point sets which have been read from file. * NOTE: your have to call the Parse() function, before this function. */ virtual PointSetList GetParsedPointSets(); protected: vtkPointSetXMLParser(); virtual ~vtkPointSetXMLParser(); /** * A stack containing the parsed start-tags. * If an end tag is encountered, it is matched with the * top element of the stack. */ ParseStack m_ParseStack; /** * Contains the parsed point sets. */ PointSetList m_PointSetList; /** * The current point set which is processed * by the parser. */ PointSetType::Pointer m_CurrentPointSet; /** * The current point which is processed * by the parser. */ PointType m_CurrentPoint; std::string m_CurId; std::string m_CurXString; std::string m_CurYString; std::string m_CurZString; /** * The current point id which is processed * by the parser. */ PointIdentifier m_CurrentPointId; std::locale m_PreviousLocale; }; } #endif // _VTK_POINT_SET_XML_READER__H_ diff --git a/Modules/PlanarFigure/CMakeLists.txt b/Modules/PlanarFigure/CMakeLists.txt index cc9d50b89e..e03080c617 100644 --- a/Modules/PlanarFigure/CMakeLists.txt +++ b/Modules/PlanarFigure/CMakeLists.txt @@ -1,8 +1,8 @@ MITK_CREATE_MODULE( PlanarFigure INCLUDE_DIRS Algorithms DataManagement Interactions IO Rendering - DEPENDS Mitk SceneSerializationBase + DEPENDS Mitk LegacyIO SceneSerializationBase ) IF( BUILD_TESTING ) add_subdirectory(Testing) ENDIF() diff --git a/Modules/Qmitk/QmitkFileDialog.cpp b/Modules/Qmitk/QmitkFileDialog.cpp index be3034d532..c6fc22beeb 100644 --- a/Modules/Qmitk/QmitkFileDialog.cpp +++ b/Modules/Qmitk/QmitkFileDialog.cpp @@ -1,195 +1,198 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define _USE_MATH_DEFINES #include // MITK #include // STL Headers #include //microservices #include #include #include //QT #include #include #include // Test imports, delete later #include class DummyReader : public mitk::AbstractFileReader { public: DummyReader(const DummyReader& other) : mitk::AbstractFileReader(other) { } DummyReader(const std::string& extension, int priority) : mitk::AbstractFileReader(extension, "This is a dummy description") { m_Priority = priority; //std::vector options; m_Options.push_back(std::make_pair("isANiceGuy", true)); m_Options.push_back(std::make_pair("canFly", false)); m_Options.push_back(std::make_pair("isAwesome", true)); m_Options.push_back(std::make_pair("hasOptions", true)); m_Options.push_back(std::make_pair("has more Options", true)); m_Options.push_back(std::make_pair("has maaaaaaaany Options", true)); m_ServiceReg = this->RegisterService(); } ~DummyReader() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using mitk::AbstractFileReader::Read; virtual std::vector< itk::SmartPointer > Read(const std::istream& /*stream*/, mitk::DataStorage* /*ds*/ = 0) { std::vector result; return result; } - virtual void SetOptions(const std::vector< mitk::IFileReader::FileServiceOption >& options ) + virtual void SetOptions(const mitk::IFileReader::OptionList& options ) { m_Options = options; //m_Registration.SetProperties(GetServiceProperties()); } private: DummyReader* Clone() const { return new DummyReader(*this); } us::ServiceRegistration m_ServiceReg; }; // End of internal dummy reader const std::string QmitkFileDialog::VIEW_ID = "org.mitk.views.QmitkFileDialog"; // // // // // // // // // QmitkFileDialog::QmitkFileDialog(QWidget* parent, Qt::WindowFlags f): QFileDialog(parent, f) { this->setOption(QFileDialog::DontUseNativeDialog); DummyReader* dr = new DummyReader(".xsfd", 1000); CreateQtPartControl(this); } QmitkFileDialog::~QmitkFileDialog() { } //////////////////// INITIALIZATION ///////////////////// void QmitkFileDialog::CreateQtPartControl(QWidget *parent) { // cast own layout to gridLayout QGridLayout *layout = (QGridLayout*)this->layout(); // creat groupbox for options QGroupBox *box = new QGroupBox(this); box->setTitle("Options:"); box->setVisible(true); m_BoxLayout = new QGridLayout(box); box->setLayout(m_BoxLayout); layout->addWidget(box,4,0,1,3); this->CreateConnections(); // m_context = us::getmodulecontext(); } void QmitkFileDialog::CreateConnections() { connect( this, SIGNAL(currentChanged( const QString &)), this, SLOT(DisplayOptions( QString)) ); connect( this, SIGNAL(fileSelected( const QString &)), this, SLOT(ProcessSelectedFile()) ); } /////////////////////////// OPTIONS /////////////////////////////// void QmitkFileDialog::DisplayOptions(QString path) { ClearOptionsBox(); - std::vector< mitk::IFileReader::FileServiceOption > options = QueryAvailableOptions(path.toStdString()); - for (int i = 0; i < options.size(); i++) + mitk::IFileReader::OptionList options = QueryAvailableOptions(path.toStdString()); + int i = 0; + for (mitk::IFileReader::OptionList::const_iterator iter = options.begin(), + end = options.end(); iter != end; ++iter) { QCheckBox *checker = new QCheckBox(this); - checker->setText( options[i].first.c_str() ); - checker->setChecked( options[i].second ); + checker->setText( QString::fromStdString(iter->first) ); + checker->setChecked( iter->second ); m_BoxLayout->addWidget(checker, i / 4, i % 4); + ++i; } } void QmitkFileDialog::ClearOptionsBox() { if ( m_BoxLayout != NULL ) { QLayoutItem* item; while ( ( item = m_BoxLayout->takeAt( 0 ) ) != NULL ) { delete item->widget(); delete item; } } } -std::vector< mitk::IFileReader::FileServiceOption > QmitkFileDialog::GetSelectedOptions() +mitk::IFileReader::OptionList QmitkFileDialog::GetSelectedOptions() { - std::vector result; + mitk::IFileReader::OptionList result; if ( m_BoxLayout != NULL ) { QLayoutItem* item; while ( ( item = m_BoxLayout->takeAt( 0 ) ) != NULL ) { QCheckBox* checker = dynamic_cast (item->widget()); if (checker) { - mitk::IFileReader::FileServiceOption option = std::make_pair( checker->text().toStdString() , checker->isChecked() ); + mitk::IFileReader::FileServiceOption option( checker->text().toStdString() , checker->isChecked() ); result.push_back(option); } delete item->widget(); delete item; } } return result; } diff --git a/Modules/Qmitk/QmitkFileDialog.h b/Modules/Qmitk/QmitkFileDialog.h index 4ae8cde38d..b205bddc6d 100644 --- a/Modules/Qmitk/QmitkFileDialog.h +++ b/Modules/Qmitk/QmitkFileDialog.h @@ -1,97 +1,97 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QmitkFileDialog_H_INCLUDED #define _QmitkFileDialog_H_INCLUDED #include "QmitkExports.h" #include //QT headers #include #include #include //Microservices #include "usServiceReference.h" // MITK #include /** * \ingroup QmitkModule * * \brief This is the abstract base class for QmitkFileOpenDialog and QmitkFileSaveDialog. * * It contains common functionality and logic, but is not really useful on it's own. Use the subclasses! */ class QMITK_EXPORT QmitkFileDialog :public QFileDialog { //this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkFileDialog(QWidget* p = 0, Qt::WindowFlags f1 = 0); virtual ~QmitkFileDialog(); /** \brief This method is part of the widget and needs not to be called separately. */ virtual void CreateQtPartControl(QWidget *parent); /** \brief This method is part of the widget and needs not to be called separately. (Creation of the connections of main and control widget.)*/ virtual void CreateConnections(); /** * \brief Returns the Options that are currently / have been selected in the widget. */ - virtual std::vector< mitk::IFileReader::FileServiceOption > GetSelectedOptions(); + virtual mitk::IFileReader::OptionList GetSelectedOptions(); signals: public slots: /** * \brief Called when the file selection has changed and the options need to be adapted. */ virtual void DisplayOptions(QString path); protected slots: /** * \brief When the Dialog is closed, the subclass must execute the logic to process the selected files. */ virtual void ProcessSelectedFile() = 0; protected: /** \brief Contains the checkboxes for the options*/ QGridLayout* m_BoxLayout; /** \brief The Options the user has set for the reader / writer*/ - std::vector m_Options; + mitk::IFileReader::OptionList m_Options; /** * \brief This is kind of a workaround. Getting the Options is differen whether using a reader or a writer, * so the subclasses of this dialog must implement this logic. */ - virtual std::vector QueryAvailableOptions(std::string path) = 0; + virtual mitk::IFileReader::OptionList QueryAvailableOptions(std::string path) = 0; /** \brief Remove all checkboxes from the options box.*/ virtual void ClearOptionsBox(); }; #endif // _QmitkFileDialog_H_INCLUDED diff --git a/Modules/Qmitk/QmitkFileOpenDialog.cpp b/Modules/Qmitk/QmitkFileOpenDialog.cpp index 62360e68bb..018b620412 100644 --- a/Modules/Qmitk/QmitkFileOpenDialog.cpp +++ b/Modules/Qmitk/QmitkFileOpenDialog.cpp @@ -1,110 +1,109 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define _USE_MATH_DEFINES #include // MITK #include #include // STL Headers #include //microservices #include #include #include //QT #include // Test imports, delete later #include const std::string QmitkFileOpenDialog::VIEW_ID = "org.mitk.views.QmitkFileOpenDialog"; QmitkFileOpenDialog::QmitkFileOpenDialog(QWidget* parent, Qt::WindowFlags f): QmitkFileDialog(parent, f) { this->setFileMode(QFileDialog::ExistingFiles); } QmitkFileOpenDialog::~QmitkFileOpenDialog() { } void QmitkFileOpenDialog::ProcessSelectedFile() { QStringList files = this->selectedFiles(); while( files.size() > 0) { std::string file = files.front().toStdString(); files.pop_front(); std::string extension = file; extension.erase(0, extension.find_last_of('.')); m_Options = GetSelectedOptions(); // We are not looking for specific options here, which is okay, since the dialog currently only shows the // reader with the highest priority. Better behaviour required, if we want selectable readers. mitk::IFileReader* fileReader = m_FileReaderRegistry.GetReader(extension); fileReader->SetOptions(m_Options); m_FileReaders.push_back(fileReader); } } -std::vector QmitkFileOpenDialog::QueryAvailableOptions(std::string path) +mitk::IFileReader::OptionList QmitkFileOpenDialog::QueryAvailableOptions(std::string path) { std::string extension = path; extension.erase(0, extension.find_last_of('.')); us::ModuleContext* context = us::GetModuleContext(); mitk::IFileReader* reader = m_FileReaderRegistry.GetReader(extension); if (reader == NULL) { // MITK_WARN << "Did not find ReaderService for registered Extension. This should be looked into by a developer."; - std::vector emptyList; - return emptyList; + return mitk::IFileReader::OptionList(); } return reader->GetOptions(); } std::vector QmitkFileOpenDialog::GetReaders() { return this->m_FileReaders; } std::vector< mitk::BaseData::Pointer > QmitkFileOpenDialog::GetBaseDatas() { //if (m_FileReaders.size() == 0 ) //{ // MITK_WARN << "Tried go get BaseData while no FileReader was selected in Dialog. Returning empty list."; // std::vector< mitk::BaseData::Pointer > emptyList; // return emptyList; //} //std::vector result; //for(std::vector< mitk::IFileReader* >::iterator reader = m_FileReaders.begin(); reader != m_FileReaders.end; reader++) //{ // result.splice(result.end(), m_FileReaders.) // result.pu //} //return m_FileReader->Read(this->selectedFiles().front().toStdString()); std::vector< mitk::BaseData::Pointer > emptyList; return emptyList; } diff --git a/Modules/Qmitk/QmitkFileOpenDialog.h b/Modules/Qmitk/QmitkFileOpenDialog.h index 9724e636b1..b8741b0137 100644 --- a/Modules/Qmitk/QmitkFileOpenDialog.h +++ b/Modules/Qmitk/QmitkFileOpenDialog.h @@ -1,88 +1,88 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QmitkFileOpenDialog_H_INCLUDED #define _QmitkFileOpenDialog_H_INCLUDED #include "QmitkExports.h" #include //QT headers #include #include //Microservices #include "usServiceReference.h" #include "usModuleContext.h" #include "usServiceEvent.h" #include "usServiceInterface.h" // MITK #include #include #include /** * \ingroup QmitkModule * * \brief */ class QMITK_EXPORT QmitkFileOpenDialog :public QmitkFileDialog { //this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT private: //us::ModuleContext* m_Context; ///** \brief a filter to further narrow down the list of results*/ //std::string m_Filter; ///** \brief The name of the ServiceInterface that this class should list */ //std::string m_Interface; ///** \brief The name of the ServiceProperty that will be displayed in the list to represent the service */ //std::string m_NamingProperty; public: static const std::string VIEW_ID; QmitkFileOpenDialog(QWidget* p = 0, Qt::WindowFlags f1 = 0); virtual ~QmitkFileOpenDialog(); virtual std::vector GetReaders(); virtual std::vector< mitk::BaseData::Pointer > GetBaseDatas(); signals: public slots: protected slots: virtual void ProcessSelectedFile(); protected: std::vector m_FileReaders; - std::vector m_Options; + mitk::IFileReader::OptionList m_Options; mitk::FileReaderRegistry m_FileReaderRegistry; - virtual std::vector QueryAvailableOptions(std::string path) ; + virtual mitk::IFileReader::OptionList QueryAvailableOptions(std::string path); //Ui::QmitkFileOpenDialogControls* m_Controls; ///< member holding the UI elements of this widget }; #endif // _QmitkFileOpenDialog_H_INCLUDED diff --git a/Modules/Qmitk/QmitkFileSaveDialog.cpp b/Modules/Qmitk/QmitkFileSaveDialog.cpp index 33b35eadee..ea5c7dffca 100644 --- a/Modules/Qmitk/QmitkFileSaveDialog.cpp +++ b/Modules/Qmitk/QmitkFileSaveDialog.cpp @@ -1,160 +1,159 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define _USE_MATH_DEFINES #include // MITK #include #include // STL Headers #include //microservices #include #include #include //QT #include #include #include #include // Test imports, delete later #include class DummyReader : public mitk::AbstractFileReader { public: DummyReader(const DummyReader& other) : mitk::AbstractFileReader(other) { } DummyReader(const std::string& extension, int priority) : mitk::AbstractFileReader(extension, "This is a dummy description") { m_Priority = priority; //std::vector options; m_Options.push_back(std::make_pair("isANiceGuy", true)); m_Options.push_back(std::make_pair("canFly", false)); m_Options.push_back(std::make_pair("isAwesome", true)); m_Options.push_back(std::make_pair("hasOptions", true)); m_Options.push_back(std::make_pair("has more Options", true)); m_Options.push_back(std::make_pair("has maaaaaaaany Options", true)); m_ServiceReg = this->RegisterService(); } ~DummyReader() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using mitk::AbstractFileReader::Read; virtual std::vector< itk::SmartPointer > Read(const std::istream& /*stream*/, mitk::DataStorage* /*ds*/ = 0) { std::vector result; return result; } - virtual void SetOptions(const std::vector< mitk::IFileWriter::FileServiceOption >& options ) + virtual void SetOptions(const mitk::IFileWriter::OptionList& options ) { m_Options = options; //m_Registration.SetProperties(GetServiceProperties()); } private: DummyReader* Clone() const { return new DummyReader(*this); } us::ServiceRegistration m_ServiceReg; }; // End of internal dummy reader const std::string QmitkFileSaveDialog::VIEW_ID = "org.mitk.views.QmitkFileSaveDialog"; // // // // // // // // // QmitkFileSaveDialog::QmitkFileSaveDialog(mitk::BaseData::Pointer baseData, QWidget* parent, Qt::WindowFlags f): QmitkFileDialog(parent, f) { m_BaseData = baseData; this->setFileMode(QFileDialog::AnyFile); } QmitkFileSaveDialog::~QmitkFileSaveDialog() { } void QmitkFileSaveDialog::ProcessSelectedFile() { std::string file = this->selectedFiles().front().toStdString(); std::string extension = file; extension.erase(0, extension.find_last_of('.')); m_Options = GetSelectedOptions(); // We are not looking for specific Options here, which is okay, since the dialog currently only shows the // reader with the highest priority. Better behaviour required, if we want selectable readers. m_FileWriter = m_FileWriterRegistry.GetWriter(extension); m_FileWriter->SetOptions(m_Options); } -std::vector QmitkFileSaveDialog::QueryAvailableOptions(std::string path) +mitk::IFileWriter::OptionList QmitkFileSaveDialog::QueryAvailableOptions(std::string path) { us::ModuleContext* context = us::GetModuleContext(); mitk::IFileWriter* writer = m_FileWriterRegistry.GetWriter(m_BaseData->GetNameOfClass()); if (writer == NULL) { // MITK_WARN << "Did not find WriterService for registered Extension. This should be looked into by a developer."; - std::vector emptyList; - return emptyList; + return mitk::IFileWriter::OptionList(); } return writer->GetOptions(); } mitk::IFileWriter* QmitkFileSaveDialog::GetWriter() { return this->m_FileWriter; } void QmitkFileSaveDialog::WriteBaseData() { if (m_FileWriter == NULL ) { MITK_WARN << "Tried go write BaseData while no FileWriter was selected in Dialog. Aborting."; return; } m_FileWriter->Write(m_BaseData, this->selectedFiles().front().toStdString()); } diff --git a/Modules/Qmitk/QmitkFileSaveDialog.h b/Modules/Qmitk/QmitkFileSaveDialog.h index b7f83c0ea1..9fda899211 100644 --- a/Modules/Qmitk/QmitkFileSaveDialog.h +++ b/Modules/Qmitk/QmitkFileSaveDialog.h @@ -1,82 +1,82 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QmitkFileSaveDialog_H_INCLUDED #define _QmitkFileSaveDialog_H_INCLUDED #include "QmitkExports.h" #include //QT headers #include #include #include //Microservices #include "usServiceReference.h" // MITK #include #include #include #include /** * \ingroup QmitkModule * * \brief */ class QMITK_EXPORT QmitkFileSaveDialog :public QmitkFileDialog { //this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT private: public: static const std::string VIEW_ID; QmitkFileSaveDialog(mitk::BaseData::Pointer baseData, QWidget* p = 0, Qt::WindowFlags f1 = 0); virtual ~QmitkFileSaveDialog(); virtual mitk::IFileWriter* GetWriter(); /** * \brief Writes the Basedata that the WIdget was constructed with into the file selected by the user. * */ virtual void WriteBaseData(); signals: protected slots: virtual void ProcessSelectedFile(); protected: mitk::IFileWriter* m_FileWriter; - std::vector m_Options; + mitk::IFileWriter::OptionList m_Options; mitk::FileWriterRegistry m_FileWriterRegistry; mitk::BaseData::Pointer m_BaseData; - std::vector QueryAvailableOptions(std::string path); + mitk::IFileWriter::OptionList QueryAvailableOptions(std::string path); //Ui::QmitkFileSaveDialogControls* m_Controls; ///< member holding the UI elements of this widget }; #endif // _QmitkFileSaveDialog_H_INCLUDED diff --git a/Modules/SceneSerializationBase/Testing/mitkPropertySerializationTest.cpp b/Modules/SceneSerializationBase/Testing/mitkPropertySerializationTest.cpp index 937b3e8e57..9776f4a6d5 100644 --- a/Modules/SceneSerializationBase/Testing/mitkPropertySerializationTest.cpp +++ b/Modules/SceneSerializationBase/Testing/mitkPropertySerializationTest.cpp @@ -1,266 +1,265 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" -#include "mitkDataNodeFactory.h" #include "mitkCoreObjectFactory.h" #include "mitkBaseProperty.h" #include "mitkProperties.h" #include #include #include #include /* #include #include #include */ #include //#include //#include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkPropertyList.h" #include "mitkPropertyListSerializer.h" #include "mitkBasePropertySerializer.h" #include #include #include #include /* #include #include #include #include #include #include #include #include #include #include */ void TestAllProperties(const mitk::PropertyList* propList); /**Documentation * \brief Test for all PropertySerializer classes. * */ int mitkPropertySerializationTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("PropertySerializationTest"); mitk::PropertyListSerializer::Pointer serializer = mitk::PropertyListSerializer::New(); // make sure something from the lib is actually used (registration of serializers) /* build list of properties that will be serialized and deserialized */ mitk::PropertyList::Pointer propList = mitk::PropertyList::New(); propList->SetProperty("booltrue", mitk::BoolProperty::New(true)); propList->SetProperty("boolfalse", mitk::BoolProperty::New(false)); propList->SetProperty("int", mitk::IntProperty::New(-32)); propList->SetProperty("float", mitk::FloatProperty::New(-31.337)); propList->SetProperty("double", mitk::DoubleProperty::New(-31.337)); propList->SetProperty("string", mitk::StringProperty::New("Hello MITK")); mitk::Point3D p3d; mitk::FillVector3D(p3d, 1.0, 2.2, -3.3); propList->SetProperty("p3d", mitk::Point3dProperty::New(p3d)); mitk::Point3I p3i; mitk::FillVector3D(p3i, 1, 2, -3); propList->SetProperty("p3i", mitk::Point3iProperty::New(p3i)); mitk::Point4D p4d; mitk::FillVector4D(p4d, 1.5, 2.6, -3.7, 4.44); propList->SetProperty("p4d", mitk::Point4dProperty::New(p4d)); mitk::Vector3D v3d; mitk::FillVector3D(v3d, 1.0, 2.2, -3.3); propList->SetProperty("v3d", mitk::Vector3DProperty::New(v3d)); propList->SetProperty("annotation", mitk::AnnotationProperty::New("My Annotation", p3d)); propList->SetProperty("clipping", mitk::ClippingProperty::New(p3d, v3d)); propList->SetProperty("color", mitk::ColorProperty::New(1.0, 0.2, 0.2)); //mitk::EnumerationProperty::Pointer en = mitk::EnumerationProperty::New(); //en->AddEnum("PC", 1); en->AddEnum("Playstation", 2); en->AddEnum("Wii", 111); en->AddEnum("XBox", 7); //en->SetValue("XBox"); //propList->SetProperty("enum", en); /* propList->SetProperty("gridrep", mitk::GridRepresentationProperty::New(2)); propList->SetProperty("gridvol", mitk::GridVolumeMapperProperty::New(0)); propList->SetProperty("OrganTypeProperty", mitk::OrganTypeProperty::New("Larynx")); */ propList->SetProperty("modality", mitk::ModalityProperty::New("Color Doppler")); //propList->SetProperty("OdfNormalizationMethodProperty", mitk::OdfNormalizationMethodProperty::New("Global Maximum")); //propList->SetProperty("OdfScaleByProperty", mitk::OdfScaleByProperty::New("Principal Curvature")); propList->SetProperty("PlaneOrientationProperty", mitk::PlaneOrientationProperty::New("Arrows in positive direction")); propList->SetProperty("ShaderProperty", mitk::ShaderProperty::New("fixed")); propList->SetProperty("VtkInterpolationProperty", mitk::VtkInterpolationProperty::New("Gouraud")); propList->SetProperty("VtkRepresentationProperty", mitk::VtkRepresentationProperty::New("Surface")); propList->SetProperty("VtkResliceInterpolationProperty", mitk::VtkResliceInterpolationProperty::New("Cubic")); propList->SetProperty("VtkScalarModeProperty", mitk::VtkScalarModeProperty::New("PointFieldData")); propList->SetProperty("VtkVolumeRenderingProperty", mitk::VtkVolumeRenderingProperty::New("COMPOSITE")); mitk::BoolLookupTable blt; blt.SetTableValue(0, true); blt.SetTableValue(1, false); blt.SetTableValue(2, true); propList->SetProperty("BoolLookupTableProperty", mitk::BoolLookupTableProperty::New(blt)); mitk::FloatLookupTable flt; flt.SetTableValue(0, 3.1); flt.SetTableValue(1, 3.3); flt.SetTableValue(2, 7.0); propList->SetProperty("FloatLookupTableProperty", mitk::FloatLookupTableProperty::New(flt)); mitk::IntLookupTable ilt; ilt.SetTableValue(0, 3); ilt.SetTableValue(1, 2); ilt.SetTableValue(2, 11); propList->SetProperty("IntLookupTableProperty", mitk::IntLookupTableProperty::New(ilt)); mitk::StringLookupTable slt; slt.SetTableValue(0, "Hello"); slt.SetTableValue(1, "MITK"); slt.SetTableValue(2, "world"); propList->SetProperty("StringLookupTableProperty", mitk::StringLookupTableProperty::New(slt)); propList->SetProperty("GroupTagProperty", mitk::GroupTagProperty::New()); propList->SetProperty("LevelWindowProperty", mitk::LevelWindowProperty::New(mitk::LevelWindow(100.0, 50.0))); mitk::LookupTable::Pointer lt = mitk::LookupTable::New(); lt->ChangeOpacityForAll(0.25); lt->ChangeOpacity(17, 0.88); propList->SetProperty("LookupTableProperty", mitk::LookupTableProperty::New(lt)); propList->SetProperty("StringProperty", mitk::StringProperty::New("Oh why, gruel world")); //mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); //tf->SetTransferFunctionMode(1); //propList->SetProperty("TransferFunctionProperty", mitk::TransferFunctionProperty::New(tf)); MITK_TEST_CONDITION_REQUIRED(propList->GetMap()->size() > 0, "Initialize PropertyList"); TestAllProperties(propList); /* test default property lists of basedata objects */ // activate the following tests after MaterialProperty is deleted mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(mitk::PointSet::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Image::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Surface::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::VtkWidgetRendering::New()); TestAllProperties(node->GetPropertyList()); /* node->SetData(mitk::Contour::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::ContourSet::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Mesh::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Cone::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Cuboid::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Cylinder::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Ellipsoid::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::ExtrudedContour::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Plane::New()); TestAllProperties(node->GetPropertyList()); //node->SetData(mitk::TrackingVolume::New()); // TrackingVolume is in IGT Module, it does not have special properties, therefore we skip it here //TestAllProperties(node->GetPropertyList()); node->SetData(mitk::UnstructuredGrid::New()); TestAllProperties(node->GetPropertyList()); */ /* untested base data types: BaseDataTestImplementation RenderWindowFrame mitk::DiffusionImage< TPixelType > GeometryData mitk::Geometry2DData GradientBackground ItkBaseDataAdapter ManufacturerLogo SlicedData QBallImage SeedsImage TensorImage BoundingObject BoundingObjectGroup */ MITK_TEST_END(); } void TestAllProperties(const mitk::PropertyList* propList) { assert(propList); /* try to serialize each property in the list, then deserialize again and check for equality */ for (mitk::PropertyList::PropertyMap::const_iterator it = propList->GetMap()->begin(); it != propList->GetMap()->end(); ++it) { const mitk::BaseProperty* prop = it->second; // construct name of serializer class std::string serializername = std::string(prop->GetNameOfClass()) + "Serializer"; std::list allSerializers = itk::ObjectFactoryBase::CreateAllInstance(serializername.c_str()); MITK_TEST_CONDITION(allSerializers.size() > 0, std::string("Creating serializers for ") + serializername); if (allSerializers.size() == 0) { MITK_TEST_OUTPUT( << "serialization not possible, skipping " << prop->GetNameOfClass()); continue; } if (allSerializers.size() > 1) { MITK_TEST_OUTPUT (<< "Warning: " << allSerializers.size() << " serializers found for " << prop->GetNameOfClass() << "testing only the first one."); } mitk::BasePropertySerializer* serializer = dynamic_cast( allSerializers.begin()->GetPointer()); MITK_TEST_CONDITION(serializer != NULL, serializername + std::string(" is valid")); if (serializer != NULL) { serializer->SetProperty(prop); TiXmlElement* valueelement = NULL; try { valueelement = serializer->Serialize(); } catch (...) { } MITK_TEST_CONDITION(valueelement != NULL, std::string("Serialize property with ") + serializername); if (valueelement == NULL) { MITK_TEST_OUTPUT( << "serialization failed, skipping deserialization"); continue; } mitk::BaseProperty::Pointer deserializedProp = serializer->Deserialize( valueelement ); MITK_TEST_CONDITION(deserializedProp.IsNotNull(), "serializer created valid property"); if (deserializedProp.IsNotNull()) { MITK_TEST_CONDITION(*(deserializedProp.GetPointer()) == *prop, "deserialized property equals initial property for type " << prop->GetNameOfClass()); } } else { MITK_TEST_OUTPUT( << "created serializer object is of class " << allSerializers.begin()->GetPointer()->GetNameOfClass()) } } // for all properties } diff --git a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp index 2ef550c4c0..956788b312 100644 --- a/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkWorkbenchUtil.cpp @@ -1,348 +1,347 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkWorkbenchUtil.h" #include #include #include #include -#include #include "mitkIDataStorageService.h" #include "mitkDataStorageEditorInput.h" #include "mitkRenderingManager.h" #include "mitkIRenderWindowPart.h" #include "mitkIRenderingManager.h" #include "mitkProperties.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" #include "mitkIOUtil.h" #include "mitkWorkbenchUtil.h" #include #include #include #include #include "internal/org_mitk_gui_common_Activator.h" namespace mitk { struct WorkbenchUtilPrivate { /** * Get the editor descriptor for a given name using the editorDescriptor * passed in as a default as a starting point. * * @param name * The name of the element to open. * @param editorReg * The editor registry to do the lookups from. * @param defaultDescriptor * IEditorDescriptor or null * @return IEditorDescriptor * @throws PartInitException * if no valid editor can be found */ static berry::IEditorDescriptor::Pointer GetEditorDescriptor(const QString& name, berry::IEditorRegistry* editorReg, berry::IEditorDescriptor::Pointer defaultDescriptor) { if (defaultDescriptor.IsNotNull()) { return defaultDescriptor; } berry::IEditorDescriptor::Pointer editorDesc = defaultDescriptor; // next check the OS for in-place editor (OLE on Win32) if (editorReg->IsSystemInPlaceEditorAvailable(name.toStdString())) { editorDesc = editorReg->FindEditor(berry::IEditorRegistry::SYSTEM_INPLACE_EDITOR_ID); } // next check with the OS for an external editor if (editorDesc.IsNull() && editorReg->IsSystemExternalEditorAvailable(name.toStdString())) { editorDesc = editorReg->FindEditor(berry::IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); } // if no valid editor found, bail out if (editorDesc.IsNull()) { throw berry::PartInitException("No editor found"); } return editorDesc; } }; // //! [UtilLoadFiles] void WorkbenchUtil::LoadFiles(const QStringList &fileNames, berry::IWorkbenchWindow::Pointer window, bool openEditor) // //! [UtilLoadFiles] { if (fileNames.empty()) return; mitk::IDataStorageReference::Pointer dataStorageRef; { ctkPluginContext* context = mitk::PluginActivator::GetContext(); mitk::IDataStorageService* dss = 0; ctkServiceReference dsRef = context->getServiceReference(); if (dsRef) { dss = context->getService(dsRef); } if (!dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return; } // Get the active data storage (or the default one, if none is active) dataStorageRef = dss->GetDataStorage(); context->ungetService(dsRef); } mitk::DataStorage::Pointer dataStorage = dataStorageRef->GetDataStorage(); // Do the actual work of loading the data into the data storage std::vector fileNames2; // Correct conversion for File names.(BUG 12252) fileNames2.resize(fileNames.size()); for (int i = 0; i< fileNames.size(); i++) fileNames2[i] = std::string(QFile::encodeName(fileNames[i]).data()); // Old conversion which returns wrong encoded Non-Latin-Characters. //ctk::qListToSTLVector(fileNames, fileNames2); // Turn off ASSERT #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) int lastCrtReportType = _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_DEBUG ); #endif const bool dsmodified = mitk::IOUtil::LoadFiles(fileNames2, *dataStorage); // Set ASSERT status back to previous status. #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) if (lastCrtReportType) _CrtSetReportMode( _CRT_ASSERT, lastCrtReportType ); #endif // Check if there is an open perspective. If not, open the default perspective. if (window->GetActivePage().IsNull()) { std::string defaultPerspId = window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective(); window->GetWorkbench()->ShowPerspective(defaultPerspId, window); } if (openEditor) { try { // Activate the editor using the same data storage or open the default editor mitk::DataStorageEditorInput::Pointer input(new mitk::DataStorageEditorInput(dataStorageRef)); berry::IEditorPart::Pointer editor = mitk::WorkbenchUtil::OpenEditor(window->GetActivePage(), input, true); mitk::IRenderWindowPart* renderEditor = dynamic_cast(editor.GetPointer()); mitk::IRenderingManager* renderingManager = renderEditor == 0 ? 0 : renderEditor->GetRenderingManager(); if(dsmodified && renderingManager) { // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" , mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = dataStorage->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = dataStorage->ComputeBoundingGeometry3D(rs); // initialize the views to the bounding geometry renderingManager->InitializeViews(bounds); } } catch (const berry::PartInitException& e) { QString msg = "An error occurred when displaying the file(s): %1"; QMessageBox::warning(QApplication::activeWindow(), "Error displaying file", msg.arg(QString::fromStdString(e.message()))); } } } berry::IEditorPart::Pointer WorkbenchUtil::OpenEditor(berry::IWorkbenchPage::Pointer page, berry::IEditorInput::Pointer input, const QString &editorId, bool activate) { // sanity checks if (page.IsNull()) { throw std::invalid_argument("page argument must not be NULL"); } // open the editor on the input return page->OpenEditor(input, editorId.toStdString(), activate); } berry::IEditorPart::Pointer WorkbenchUtil::OpenEditor(berry::IWorkbenchPage::Pointer page, mitk::DataStorageEditorInput::Pointer input, bool activate, bool determineContentType) { // sanity checks if (page.IsNull()) { throw std::invalid_argument("page argument must not be NULL"); } // open the editor on the data storage QString name = QString::fromStdString(input->GetName()) + ".mitk"; berry::IEditorDescriptor::Pointer editorDesc = WorkbenchUtilPrivate::GetEditorDescriptor(name, berry::PlatformUI::GetWorkbench()->GetEditorRegistry(), GetDefaultEditor(name, determineContentType)); return page->OpenEditor(input, editorDesc->GetId(), activate); } berry::IEditorDescriptor::Pointer WorkbenchUtil::GetEditorDescriptor( const QString& name, bool /*inferContentType*/) { if (name.isEmpty()) { throw std::invalid_argument("name argument must not be empty"); } // no used for now //IContentType contentType = inferContentType ? Platform // .getContentTypeManager().findContentTypeFor(name) : null; berry::IEditorRegistry* editorReg = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); return WorkbenchUtilPrivate::GetEditorDescriptor(name, editorReg, editorReg->GetDefaultEditor(name.toStdString() /*, contentType*/)); } berry::IEditorDescriptor::Pointer WorkbenchUtil::GetDefaultEditor(const QString& name, bool /*determineContentType*/) { // Try file specific editor. berry::IEditorRegistry* editorReg = berry::PlatformUI::GetWorkbench()->GetEditorRegistry(); try { QString editorID; // = file.getPersistentProperty(EDITOR_KEY); if (!editorID.isEmpty()) { berry::IEditorDescriptor::Pointer desc = editorReg->FindEditor(editorID.toStdString()); if (desc.IsNotNull()) { return desc; } } } catch (const berry::CoreException&) { // do nothing } // IContentType contentType = null; // if (determineContentType) // { // contentType = getContentType(file); // } // Try lookup with filename return editorReg->GetDefaultEditor(name.toStdString()); //, contentType); } bool WorkbenchUtil::SetDepartmentLogoPreference(const QString &logoResource, ctkPluginContext *context) { // The logo must be available in the local filesystem. We check if we have not already extracted the // logo from the plug-in or if this plug-ins timestamp is newer then the already extracted logo timestamp. // If one of the conditions is true, extract it and write it to the plug-in specific storage location. const QString logoFileName = logoResource.mid(logoResource.lastIndexOf('/')+1); const QString logoPath = context->getDataFile("").absoluteFilePath(); bool extractLogo = true; QFileInfo logoFileInfo(logoPath + "/" + logoFileName); if (logoFileInfo.exists()) { // The logo has been extracted previously. Check if the plugin timestamp is newer, which // means it might contain an updated logo. QString pluginLocation = QUrl(context->getPlugin()->getLocation()).toLocalFile(); if (!pluginLocation.isEmpty()) { QFileInfo pluginFileInfo(pluginLocation); if (logoFileInfo.lastModified() > pluginFileInfo.lastModified()) { extractLogo = false; } } } if (extractLogo) { // Extract the logo from the shared library and write it to disk. QFile logo(logoResource); if (logo.open(QIODevice::ReadOnly)) { QFile localLogo(logoPath + "/" + logoFileName); if (localLogo.open(QIODevice::WriteOnly)) { localLogo.write(logo.readAll()); } } } logoFileInfo.refresh(); if (logoFileInfo.exists()) { // Get the preferences service ctkServiceReference prefServiceRef = context->getServiceReference(); berry::IPreferencesService* prefService = NULL; if (prefServiceRef) { prefService = context->getService(prefServiceRef); } if (prefService) { prefService->GetSystemPreferences()->Put("DepartmentLogo", qPrintable(logoFileInfo.absoluteFilePath())); } else { BERRY_WARN << "Preferences service not available, unable to set custom logo."; return false; } } else { BERRY_WARN << "Custom logo at " << logoFileInfo.absoluteFilePath().toStdString() << " does not exist"; return false; } return true; } } // namespace mitk diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.cpp index 92c968ae4f..491b5e1e02 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileExitAction.cpp @@ -1,43 +1,35 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkFileExitAction.h" -#include -#include - -#include -#include -#include -#include - #include QmitkFileExitAction::QmitkFileExitAction(berry::IWorkbenchWindow::Pointer window) : QAction(0) { m_Window = window.GetPointer(); this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&Exit"); this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkFileExitAction::Run() { berry::PlatformUI::GetWorkbench()->Close(); }