diff --git a/Core/Code/Common/mitkCoreObjectFactory.cpp b/Core/Code/Common/mitkCoreObjectFactory.cpp index 7bbcca41c7..fb973680ac 100644 --- a/Core/Code/Common/mitkCoreObjectFactory.cpp +++ b/Core/Code/Common/mitkCoreObjectFactory.cpp @@ -1,466 +1,458 @@ /*=================================================================== 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 "mitkTimeGeometry.h" #include "mitkTransferFunctionProperty.h" #include "mitkVolumeDataVtkMapper3D.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkResliceInterpolationProperty.h" // Legacy Support: #include #include #include #include #include #include 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(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; } 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) { 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; } 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(); } 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)); } } } mitk::CoreObjectFactoryBase::MultimapType mitk::CoreObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } 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_FileExtensionsMap.insert(std::pair("*.gipl", "UMDS GIPL Format Files")); m_FileExtensionsMap.insert(std::pair("*.gipl.gz", "UMDS GIPL Format Files")); //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("*.gipl.gz", "UMDS compressed GIPL Format Files")); m_SaveFileExtensionsMap.insert(std::pair("*.nii", "NIfTI format")); m_SaveFileExtensionsMap.insert(std::pair("*.nii.gz", "NIfTI compressed 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")); } 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(); } mitk::CoreObjectFactoryBase::MultimapType mitk::CoreObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::GetFileWriters() { FileWriterList allWriters = m_FileWriters; //sort to merge lists later on typedef std::set FileWriterSet; FileWriterSet fileWritersSet; fileWritersSet.insert(allWriters.begin(), allWriters.end()); //collect all extra factories for (ExtraFactoriesContainer::iterator it = m_ExtraFactories.begin(); it != m_ExtraFactories.end(); it++ ) { FileWriterList list2 = (*it)->GetFileWriters(); //add them to the sorted set fileWritersSet.insert(list2.begin(), list2.end()); } //write back to allWriters to return a list allWriters.clear(); allWriters.insert(allWriters.end(), fileWritersSet.begin(), fileWritersSet.end()); return allWriters; } void mitk::CoreObjectFactory::MapEvent(const mitk::Event*, const int) { } 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, just call the method since // many readers initialize the map the first time when this method is called factory->GetFileExtensions(); - CoreServicePointer mimeTypeProvider(CoreServices::GetMimeTypeProvider()); - + std::map > extensionsByCategories; std::multimap fileExtensionMap = factory->GetFileExtensionsMap(); for(std::multimap::iterator it = fileExtensionMap.begin(); it != fileExtensionMap.end(); it++) { std::string extension = it->first; // remove "*." extension = extension.erase(0,2); - std::string mimeType; - std::vector mimeTypes = mimeTypeProvider->GetMimeTypesForExtension(extension); - for(std::vector::iterator mimeType = mimeTypes.begin(); - mimeType != mimeTypes.end(); ++mimeType) - { - try - { - mitk::LegacyFileReaderService* lfrs = new mitk::LegacyFileReaderService(*mimeType, extension, it->second); - m_LegacyReaders.push_back(lfrs); - } - catch (const std::exception& e) - { - MITK_WARN << e.what(); - } - } + + extensionsByCategories[it->second].push_back(extension); + } + + for(std::map >::iterator iter = extensionsByCategories.begin(), + endIter = extensionsByCategories.end(); iter != endIter; ++iter) + { + m_LegacyReaders.push_back(new mitk::LegacyFileReaderService(iter->second, iter->first)); } } void mitk::CoreObjectFactory::RegisterLegacyWriters(mitk::CoreObjectFactoryBase* factory) { // Get all external Writers 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(); MultimapType fileExtensionMap = factory->GetSaveFileExtensionsMap(); - for(mitk::CoreObjectFactory::FileWriterList::iterator it = writers.begin(); it != writers.end(); it++) - { - std::vector extensions = (*it)->GetPossibleFileExtensions(); - for(std::vector::iterator ext = extensions.begin(); ext != extensions.end(); ext++) - { - if (ext->empty()) continue; - - std::string extension = *ext; - std::string extensionWithStar = extension; - if (extension.find_first_of('*') == 0) - { - // remove "*." - extension = extension.substr(0, extension.size()-2); - } - 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); - } - } +// for(mitk::CoreObjectFactory::FileWriterList::iterator it = writers.begin(); it != writers.end(); it++) +// { +// std::vector extensions = (*it)->GetPossibleFileExtensions(); +// for(std::vector::iterator ext = extensions.begin(); ext != extensions.end(); ext++) +// { +// if (ext->empty()) continue; + +// std::string extension = *ext; +// std::string extensionWithStar = extension; +// if (extension.find_first_of('*') == 0) +// { +// // remove "*." +// extension = extension.substr(0, extension.size()-2); +// } +// 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/IO/mitkAbstractFileReader.cpp b/Core/Code/IO/mitkAbstractFileReader.cpp index 5bdb816e11..96cd0898a6 100644 --- a/Core/Code/IO/mitkAbstractFileReader.cpp +++ b/Core/Code/IO/mitkAbstractFileReader.cpp @@ -1,325 +1,411 @@ /*=================================================================== 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 namespace mitk { class AbstractFileReader::Impl { public: Impl() - : m_Priority(0) + : m_Ranking(0) , m_PrototypeFactory(NULL) {} Impl(const Impl& other) : m_MimeType(other.m_MimeType) , m_Category(other.m_Category) , m_Extensions(other.m_Extensions) , m_Description(other.m_Description) - , m_Priority(other.m_Priority) + , m_Ranking(other.m_Ranking) , m_Options(other.m_Options) , m_PrototypeFactory(NULL) {} // Minimal Service Properties: ALWAYS SET THESE IN CONSTRUCTOR OF DERIVED CLASSES! std::string m_MimeType; std::string m_Category; std::vector m_Extensions; std::string m_Description; - int m_Priority; + int m_Ranking; /** * \brief Options supported by this reader. Set sensible default values! * * Can be left emtpy if no special options are required. */ IFileReader::OptionList m_Options; us::PrototypeServiceFactory* m_PrototypeFactory; mitk::Message1 m_ProgressMessage; mitk::SimpleMimeType m_SimpleMimeType; us::ServiceRegistration m_MimeTypeReg; }; AbstractFileReader::AbstractFileReader() : d(new Impl) { } AbstractFileReader::~AbstractFileReader() { delete d->m_PrototypeFactory; if (d->m_MimeTypeReg) { d->m_MimeTypeReg.Unregister(); } } AbstractFileReader::AbstractFileReader(const AbstractFileReader& other) : d(new Impl(*other.d.get())) { } -AbstractFileReader::AbstractFileReader(const std::string& mimeType,const std::string& extension, - const std::string& description) +AbstractFileReader::AbstractFileReader(const MimeType& mimeType, const std::string& description) : d(new Impl) { d->m_MimeType = mimeType; - d->m_Extensions.push_back(extension); d->m_Description = description; } +AbstractFileReader::AbstractFileReader(const std::string& extension, const std::string& description) + : d(new Impl) +{ + d->m_Description = description; + + d->m_Extensions.push_back(extension); +} + ////////////////////// Reading ///////////////////////// std::vector > AbstractFileReader::Read(const std::string& path) { 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 > AbstractFileReader::Read(std::istream& stream) { // Create a temporary file and copy the data to it std::ofstream tmpOutputStream; std::string tmpFilePath = IOUtil::CreateTemporaryFile(tmpOutputStream); tmpOutputStream << stream.rdbuf(); tmpOutputStream.close(); // Now read from the temporary file std::vector > result = this->Read(tmpFilePath); std::remove(tmpFilePath.c_str()); return result; } std::vector,bool> > AbstractFileReader::Read(const std::string& path, DataStorage& /*ds*/) { std::vector > result; std::vector data = this->Read(path); for (std::vector::iterator iter = data.begin(); iter != data.end(); ++iter) { result.push_back(std::make_pair(*iter, false)); } return result; } std::vector,bool> > AbstractFileReader::Read(std::istream& stream, DataStorage& /*ds*/) { std::vector > result; std::vector data = this->Read(stream); for (std::vector::iterator iter = data.begin(); iter != data.end(); ++iter) { result.push_back(std::make_pair(*iter, false)); } return result; } //////////// µS Registration & Properties ////////////// us::ServiceRegistration AbstractFileReader::RegisterService(us::ModuleContext* context) { if (d->m_PrototypeFactory) return us::ServiceRegistration(); + if(context == NULL) + { + context = us::GetModuleContext(); + } + d->m_MimeTypeReg = this->RegisterMimeType(context); + if (this->GetMimeType().empty()) + { + MITK_WARN << "Not registering reader " << typeid(this).name() << " due to empty MIME type."; + return us::ServiceRegistration(); + } + struct PrototypeFactory : public us::PrototypeServiceFactory { AbstractFileReader* const m_Prototype; PrototypeFactory(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); } }; d->m_PrototypeFactory = new PrototypeFactory(this); us::ServiceProperties props = this->GetServiceProperties(); return context->RegisterService(d->m_PrototypeFactory, props); } us::ServiceProperties AbstractFileReader::GetServiceProperties() const { - if ( d->m_MimeType.empty() ) - MITK_WARN << "Registered a Reader with no mime type defined (m_MimeType is empty). Reader will not be found by calls from ReaderManager.)"; - if ( d->m_Extensions.empty() ) - MITK_WARN << "Registered a Reader with no extension defined (m_Extension is empty). Reader will not be found by calls from ReaderManager.)"; if ( d->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.)"; + MITK_WARN << "Registered a Reader with no description defined. Reader will have no human readable extension information.)"; us::ServiceProperties result; - result[IFileReader::PROP_DESCRIPTION()] = d->m_Description; - result[IFileReader::PROP_MIMETYPE()] = d->m_MimeType; - - result[us::ServiceConstants::SERVICE_RANKING()] = d->m_Priority; + result[IFileReader::PROP_DESCRIPTION()] = this->GetDescription(); + result[IFileReader::PROP_MIMETYPE()] = this->GetMimeType(); + result[us::ServiceConstants::SERVICE_RANKING()] = this->GetRanking(); for (IFileReader::OptionList::const_iterator it = d->m_Options.begin(); it != d->m_Options.end(); ++it) { if (it->second) result[it->first] = std::string("true"); else result[it->first] = std::string("false"); } return result; } -us::ServiceProperties AbstractFileReader::GetMimeTypeServiceProperties() const +us::ServiceRegistration AbstractFileReader::RegisterMimeType(us::ModuleContext* context) { - us::ServiceProperties result; + if (context == NULL) throw std::invalid_argument("The context argument must not be NULL."); - result[IMimeType::PROP_ID()] = d->m_MimeType; - result[IMimeType::PROP_CATEGORY()] = d->m_Category; - result[IMimeType::PROP_EXTENSIONS()] = d->m_Extensions; - result[IMimeType::PROP_DESCRIPTION()] = d->m_Description; + const std::string mimeType = this->GetMimeType(); + std::vector extensions = this->GetExtensions(); + const std::string primaryExtension = extensions.empty() ? "" : extensions.front(); + std::sort(extensions.begin(), extensions.end()); + extensions.erase(std::unique(extensions.begin(), extensions.end()), extensions.end()); - result[us::ServiceConstants::SERVICE_RANKING()] = d->m_Priority; + us::ServiceProperties props; - return result; -} + props[IMimeType::PROP_ID()] = mimeType; + props[IMimeType::PROP_CATEGORY()] = this->GetCategory(); + props[IMimeType::PROP_EXTENSIONS()] = extensions; + props[IMimeType::PROP_DESCRIPTION()] = std::string("Generated MIME type from mitk::AbstractFileReader"); + props[us::ServiceConstants::SERVICE_RANKING()] = this->GetRanking(); -us::ServiceRegistration AbstractFileReader::RegisterMimeType(us::ModuleContext* context) -{ - us::ServiceProperties mimeTypeProps = this->GetMimeTypeServiceProperties(); - return context->RegisterService(&d->m_SimpleMimeType, mimeTypeProps); + // If the mime type is set and the list of extensions is not empty, + // register a new IMimeType service + if (!mimeType.empty() && !extensions.empty()) + { + return context->RegisterService(&d->m_SimpleMimeType, props); + } + + // If the mime type is set and the list of extensions is empty, + // look up the mime type in the registry and print a warning if + // there is none + if (!mimeType.empty() && extensions.empty()) + { + if(us::GetModuleContext()->GetServiceReferences(us::LDAPProp(IMimeType::PROP_ID()) == mimeType).empty()) + { + MITK_WARN << "Registering a MITK reader with an unknown MIME type " << mimeType; + } + return us::ServiceRegistration(); + } + + // If the mime type is empty, get a mime type using the extensions list + assert(mimeType.empty()); + mitk::CoreServicePointer mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider()); + + if(extensions.empty()) + { + MITK_WARN << "Trying to register a MITK reader with an empty mime type and empty extension list."; + return us::ServiceRegistration(); + } + else if(extensions.size() == 1) + { + // If there is only one extension, try to look-up an existing mime tpye + std::vector mimeTypes = mimeTypeProvider->GetMimeTypesForExtension(extensions.front()); + if (!mimeTypes.empty()) + { + d->m_MimeType = mimeTypes.front(); + } + } + + if (d->m_MimeType.empty()) + { + // There is no registered mime type for the extension or the extensions + // list contains more than one entry. + // Register a new mime type by creating a synthetic mime type id from the + // first extension in the list + d->m_MimeType = "application/vnd.mitk." + primaryExtension; + props[IMimeType::PROP_ID()] = d->m_MimeType; + return context->RegisterService(&d->m_SimpleMimeType, props); + } + else + { + // A mime type for one of the listed extensions was found, do nothing. + return us::ServiceRegistration(); + } } void AbstractFileReader::SetMimeType(const std::string& mimeType) { d->m_MimeType = mimeType; } void AbstractFileReader::SetCategory(const std::string& category) { d->m_Category = category; } -void AbstractFileReader::SetExtensions(const std::vector& extensions) +void AbstractFileReader::AddExtension(const std::string& extension) { - d->m_Extensions = extensions; + d->m_Extensions.push_back(extension); } void AbstractFileReader::SetDescription(const std::string& description) { d->m_Description = description; } -void AbstractFileReader::SetPriority(int priority) +void AbstractFileReader::SetRanking(int ranking) { - d->m_Priority = priority; + d->m_Ranking = ranking; } +int AbstractFileReader::GetRanking() const +{ + return d->m_Ranking; +} //////////////////////// Options /////////////////////// IFileReader::OptionList AbstractFileReader::GetOptions() const { return d->m_Options; } void AbstractFileReader::SetOptions(const OptionList& options) { if (options.size() != d->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"; d->m_Options = options; } ////////////////// MISC ////////////////// bool AbstractFileReader::CanRead(const std::string& path) const { if (!itksys::SystemTools::FileExists(path.c_str(), true)) { return false; } // Default implementation only checks if extension is correct std::string extension = itksys::SystemTools::GetFilenameExtension(path); extension = extension.substr(1, extension.size()-1); if (std::find(d->m_Extensions.begin(), d->m_Extensions.end(), extension) == d->m_Extensions.end()) { return false; } std::ifstream stream(path.c_str()); return this->CanRead(stream); } bool AbstractFileReader::CanRead(std::istream& stream) const { return stream.good(); } void AbstractFileReader::AddProgressCallback(const ProgressCallback& callback) { d->m_ProgressMessage += callback; } void AbstractFileReader::RemoveProgressCallback(const ProgressCallback& callback) { d->m_ProgressMessage -= callback; } ////////////////// µS related Getters ////////////////// -int AbstractFileReader::GetPriority() const +std::string AbstractFileReader::GetCategory() const { - return d->m_Priority; + return d->m_Category; } std::string AbstractFileReader::GetMimeType() const { return d->m_MimeType; } std::vector AbstractFileReader::GetExtensions() const { return d->m_Extensions; } std::string AbstractFileReader::GetDescription() const { return d->m_Description; } +AbstractFileReader::MimeType::MimeType(const std::string& mimeType) + : std::string(mimeType) +{ + if (this->empty()) + { + throw std::invalid_argument("MIME type must not be empty."); + } +} + +AbstractFileReader::MimeType::MimeType() +{ +} + } diff --git a/Core/Code/IO/mitkAbstractFileReader.h b/Core/Code/IO/mitkAbstractFileReader.h index c2372b975e..0874c05ac0 100644 --- a/Core/Code/IO/mitkAbstractFileReader.h +++ b/Core/Code/IO/mitkAbstractFileReader.h @@ -1,152 +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. ===================================================================*/ #ifndef AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 #define AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 // Macro #include // MITK #include #include #include // Microservices #include #include #include namespace us { struct PrototypeServiceFactory; } namespace mitk { /** * @brief Interface class of readers that read from files * @ingroup Process */ class MITK_CORE_EXPORT AbstractFileReader : public mitk::IFileReader { public: virtual std::vector > Read(const std::string& path); virtual std::vector > Read(std::istream& stream) = 0; virtual std::vector,bool> > Read(const std::string& path, mitk::DataStorage& ds); virtual std::vector,bool> > Read(std::istream& stream, mitk::DataStorage& ds); - /** - * \brief Returns the service ranking for this file reader. - * - * Default is zero and should only be chosen differently for a reason. - * The priority is used 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; - - /** - * @brief Returns the mime-type this reader can handle. - * @return - */ - virtual std::string GetMimeType() const; - - /** - * \brief Returns the file extensions that this FileReader is able to handle. - * - * File extensions must not contain a leading period, e.g "nrrd" is correct - * while "*.nrrd" and ".nrrd" are incorrect. - */ - virtual std::vector GetExtensions() const; - - /** - * \brief Returns a human readable description of this file reader. - * - * This can be used in FileDialogs for example. - */ - virtual std::string GetDescription() const; - virtual OptionList GetOptions() const; virtual void SetOptions(const OptionList& options); /** * @brief Checks if the specified path can be read. * * The default implementation checks if the path exists and contains a * file extension associated with the mime-type of this reader. * It then creates a std::ifstream object for the given path and * calls CanRead(const std::istream&). * * @param path The absolute path to a file. * @return \c true if the file can be read, \c false otherwise. */ virtual bool CanRead(const std::string& path) const; /** * @brief Checks if the specified input stream can be read. * * @param stream The stream to be read. * @return \c true if the stream is good, \c false otherwise. */ virtual bool CanRead(std::istream& stream) const; virtual void AddProgressCallback(const ProgressCallback& callback); virtual void RemoveProgressCallback(const ProgressCallback& callback); + /** + * Associate this reader with the MIME type returned by the current IMimeTypeProvider + * service for the provided extension if the MIME type exists, otherwise registers + * a new MIME type when RegisterService() is called. + * + * If no MIME type for \c extension is already registered, a call to RegisterService() + * will register a new MIME type and associate this reader instance with it. The MIME + * type id can be set via SetMimeType() or it will be auto-generated using \c extension, + * having the form "application/vnd.mitk.". + * + * @param extension The file extension (without a leading period) for which a registered + * IMimeType object is looked up and associated with this reader instance. + * @param description A human readable description of this reader. + */ us::ServiceRegistration RegisterService(us::ModuleContext* context = us::GetModuleContext()); protected: + class MITK_CORE_EXPORT MimeType : public std::string + { + public: + MimeType(const std::string& mimeType); + + private: + MimeType(); + + friend class AbstractFileReader; + }; + AbstractFileReader(); ~AbstractFileReader(); AbstractFileReader(const AbstractFileReader& other); - AbstractFileReader(const std::string& mimeType, const std::string& extension, const std::string& description); + /** + * Associate this reader instance with the given MIME type. + * + * @param mimeType The mime type this reader can read. + * @param description A human readable description of this reader. + * + * @throws std::invalid_argument if \c mimeType is empty. + * + * @see RegisterService + */ + explicit AbstractFileReader(const MimeType& mimeType, const std::string& description); + + /** + * Associate this reader with the given file extension. + * + * Additonal file extensions can be added by sub-classes by calling AddExtension + * or SetExtensions. + * + * @param extension The file extension (without a leading period) for which a registered + * IMimeType object is looked up and associated with this reader instance. + * @param description A human readable description of this reader. + * + * @see RegisterService + */ + explicit AbstractFileReader(const std::string& extension, const std::string& description); virtual us::ServiceProperties GetServiceProperties() const; - virtual us::ServiceProperties GetMimeTypeServiceProperties() const; + /** + * @brief Returns the mime-type this reader can handle. + * @return + */ + std::string GetMimeType() const; + + /** + * Registers a new IMimeType service object. + * + * This method is called from RegisterService and the default implementation + * registers a new IMimeType service object if all of the following conditions + * are true: + * + * - The reader + * + * @param context + * @return + * @throws std::invalid_argument if \c context is NULL. + */ virtual us::ServiceRegistration RegisterMimeType(us::ModuleContext* context); void SetMimeType(const std::string& mimeType); void SetCategory(const std::string& category); - void SetExtensions(const std::vector& extensions); + void AddExtension(const std::string& extension); void SetDescription(const std::string& description); - void SetPriority(int priority); + + /** + * \brief Set the service ranking for this file reader. + * + * Default is zero and should only be chosen differently for a reason. + * The ranking is used 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 ranking than zero. + */ + void SetRanking(int ranking); + int GetRanking() const; + + std::string GetCategory() const; + std::vector GetExtensions() const; + std::string GetDescription() const; private: AbstractFileReader& operator=(const AbstractFileReader& other); virtual mitk::IFileReader* Clone() const = 0; class Impl; std::auto_ptr d; }; } // namespace mitk #endif /* AbstractFileReader_H_HEADER_INCLUDED_C1E7E521 */ diff --git a/Core/Code/Internal/mitkCoreActivator.cpp b/Core/Code/Internal/mitkCoreActivator.cpp index fc73f13de1..db8f113f40 100644 --- a/Core/Code/Internal/mitkCoreActivator.cpp +++ b/Core/Code/Internal/mitkCoreActivator.cpp @@ -1,245 +1,320 @@ /*=================================================================== 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 "mitkCoreActivator.h" // File IO #include -#include -#include +#include #include #include // Micro Services #include -#include #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 +void MitkCoreActivator::Load(us::ModuleContext* context) { -public: + // Handle messages from CppMicroServices + us::installMsgHandler(HandleMicroServicesMessages); - void Load(us::ModuleContext* context) + this->m_Context = context; + + // 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 { - // Handle messages from CppMicroServices - us::installMsgHandler(HandleMicroServicesMessages); + AddMitkAutoLoadPaths(programPath); + } - // 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_RenderingManager = mitk::RenderingManager::New(); - //context->RegisterService(renderingManager.GetPointer()); - m_PlanePositionManager.reset(new mitk::PlanePositionManagerService); - context->RegisterService(m_PlanePositionManager.get()); + m_ShaderRepository.reset(new mitk::ShaderRepository); + context->RegisterService(m_ShaderRepository.get()); - m_ShaderRepository.reset(new mitk::ShaderRepository); - context->RegisterService(m_ShaderRepository.get()); + m_PropertyAliases.reset(new mitk::PropertyAliases); + context->RegisterService(m_PropertyAliases.get()); - m_PropertyAliases.reset(new mitk::PropertyAliases); - context->RegisterService(m_PropertyAliases.get()); + m_PropertyDescriptions.reset(new mitk::PropertyDescriptions); + context->RegisterService(m_PropertyDescriptions.get()); - m_PropertyDescriptions.reset(new mitk::PropertyDescriptions); - context->RegisterService(m_PropertyDescriptions.get()); + m_PropertyExtensions.reset(new mitk::PropertyExtensions); + context->RegisterService(m_PropertyExtensions.get()); - m_PropertyExtensions.reset(new mitk::PropertyExtensions); - context->RegisterService(m_PropertyExtensions.get()); + m_PropertyFilters.reset(new mitk::PropertyFilters); + context->RegisterService(m_PropertyFilters.get()); - m_PropertyFilters.reset(new mitk::PropertyFilters); - context->RegisterService(m_PropertyFilters.get()); + m_MimeTypeProvider.reset(new mitk::MimeTypeProvider); + m_MimeTypeProvider->Start(); + m_MimeTypeProviderReg = context->RegisterService(m_MimeTypeProvider.get()); - m_MimeTypeProvider.reset(new mitk::MimeTypeProvider); - m_MimeTypeProvider->Start(); - m_MimeTypeProviderReg = context->RegisterService(m_MimeTypeProvider.get()); + context->AddModuleListener(this, &MitkCoreActivator::HandleModuleEvent); - context->AddModuleListener(this, &MitkCoreActivator::HandleModuleEvent); + this->RegisterMimeTypes(); + this->RegisterItkReaderWriter(); - // Explicitly load the LegacyIO module - us::SharedLibrary legacyIOLib(programPath, "LegacyIO"); - legacyIOLib.Load(); + // Explicitly load the LegacyIO module + us::SharedLibrary legacyIOLib(programPath, "LegacyIO"); + legacyIOLib.Load(); - // Add Reader / Writer Services + // Add Reader / Writer Services - mitk::IFileReader* reader; -// mitk::IFileWriter* writer; - reader = new mitk::PointSetReaderService(); - m_FileReaders.push_back(reader); + 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* ) +void MitkCoreActivator::Unload(us::ModuleContext* ) +{ + for(std::vector::iterator iter = m_FileReaders.begin(), + endIter = m_FileReaders.end(); iter != endIter; ++iter) { - // 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. - - // we need to close the internal service tracker of the - // MimeTypeProvider class here. Otherwise it - // would hold on to the ModuleContext longer than it is - // actually valid. - m_MimeTypeProviderReg.Unregister(); - m_MimeTypeProvider->Stop(); + delete *iter; } -private: - - void HandleModuleEvent(const us::ModuleEvent moduleEvent); - - std::map > moduleIdToShaderIds; - - //mitk::RenderingManager::Pointer m_RenderingManager; - std::auto_ptr m_PlanePositionManager; - 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; - std::auto_ptr m_MimeTypeProvider; - - // File IO - std::vector m_FileReaders; - std::vector m_FileWriters; - - us::ServiceRegistration m_MimeTypeProviderReg; -}; + // 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. + + // we need to close the internal service tracker of the + // MimeTypeProvider class here. Otherwise it + // would hold on to the ModuleContext longer than it is + // actually valid. + m_MimeTypeProviderReg.Unregister(); + m_MimeTypeProvider->Stop(); +} 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); } } } +void MitkCoreActivator::RegisterMimeTypes() +{ + // Register some default mime-types + + // 3D Images + std::vector mimeTypeExtensions; + mimeTypeExtensions.push_back("dc3"); + mimeTypeExtensions.push_back("dcm"); + RegisterMimeType("application/dicom", "Images", "Dicom Images", mimeTypeExtensions); + RegisterMimeType("application/vnd.mitk.pic", "Images", "DKFZ PIC Format", "pic"); + RegisterMimeType("application/vnd.mitk.pic+gz", "Images", "DKFZ Compressed PIC Format", "pic.gz"); + + // REMOVE: Test multiple mime types for same extension + RegisterMimeType("application/vnd.fancy", "Images", "Fancy Compressed PIC Format", "pic.gz"); + + // 2D Images + RegisterMimeType("image/bmp", "2D Images", "Bitmap Image", "bmp"); +} + +void MitkCoreActivator::RegisterItkReaderWriter() +{ + std::list possibleImageIO; + std::list allobjects = + itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); + for (std::list::iterator i = allobjects.begin(), + endIter = allobjects.end(); i != endIter; ++i) + { + itk::ImageIOBase* io = dynamic_cast(i->GetPointer()); + if (io) + { + if(!io->GetSupportedReadExtensions().empty()) + { + possibleImageIO.push_back(io); + } + else + { + MITK_INFO << "ImageIO factory " << io->GetNameOfClass() << " does not report its supported read extensions."; + } + } + else + { + MITK_WARN << "Error ImageIO factory did not return an ImageIOBase: " + << ( *i )->GetNameOfClass(); + } + } + for (std::list::iterator k = possibleImageIO.begin(), + endIter = possibleImageIO.end(); k != endIter; ++k) + { + m_FileReaders.push_back(new mitk::ItkFileReaderService((*k)->GetSupportedReadExtensions(), "ITK Image Reader")); + } + + // Some ITK ImageIOBase sub-classes do not report supported read extensions. + // Registering them manually here. + std::vector extensions; + + extensions.clear(); + extensions.push_back("gdcm"); + m_FileReaders.push_back(new mitk::ItkFileReaderService(extensions, "ITK Image Reader")); + + extensions.clear(); + extensions.push_back("png"); + extensions.push_back("PNG"); + m_FileReaders.push_back(new mitk::ItkFileReaderService(extensions, "ITK Image Reader")); + + extensions.clear(); + extensions.push_back("spr"); + m_FileReaders.push_back(new mitk::ItkFileReaderService(extensions, "ITK Image Reader")); + + extensions.clear(); + extensions.push_back("gipl"); + extensions.push_back("gipl.gz"); + m_FileReaders.push_back(new mitk::ItkFileReaderService(extensions, "ITK Image Reader")); + + extensions.clear(); + extensions.push_back("hdf"); + extensions.push_back("h4"); + extensions.push_back("hdf4"); + extensions.push_back("h5"); + extensions.push_back("hdf5"); + extensions.push_back("he4"); + extensions.push_back("he5"); + extensions.push_back("hd5"); + m_FileReaders.push_back(new mitk::ItkFileReaderService(extensions, "ITK Image Reader")); +} + +void MitkCoreActivator::RegisterMimeType(const std::string& id, const std::string& category, + const std::string& description, const std::string& extension) +{ + std::vector extensions; + extensions.push_back(extension); + this->RegisterMimeType(id, category, description, extensions); +} + +void MitkCoreActivator::RegisterMimeType(const std::string& id, const std::string& category, + const std::string& description, const std::vector& extensions) +{ + us::ServiceProperties mimeTypeProps; + mimeTypeProps[mitk::IMimeType::PROP_ID()] = id; + mimeTypeProps[mitk::IMimeType::PROP_CATEGORY()] = category; + mimeTypeProps[mitk::IMimeType::PROP_DESCRIPTION()] = description; + mimeTypeProps[mitk::IMimeType::PROP_EXTENSIONS()] = extensions; + mimeTypeProps[us::ServiceConstants::SERVICE_RANKING()] = -100; + m_Context->RegisterService(&m_MimeType, mimeTypeProps); +} + US_EXPORT_MODULE_ACTIVATOR(Mitk, MitkCoreActivator) // Call CppMicroservices initialization code at the end of the file. // This especially ensures that VTK object factories have already // been registered (VTK initialization code is injected by implicitly // include VTK header files at the top of this file). US_INITIALIZE_MODULE("Mitk", "Mitk") diff --git a/Core/Code/Internal/mitkCoreActivator.h b/Core/Code/Internal/mitkCoreActivator.h new file mode 100644 index 0000000000..de47b4447d --- /dev/null +++ b/Core/Code/Internal/mitkCoreActivator.h @@ -0,0 +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. + +===================================================================*/ + +#ifndef MITKCOREACTIVATOR_H_ +#define MITKCOREACTIVATOR_H_ + +// File IO +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +// Micro Services +#include +#include +#include + +#include + +/* + * 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); + void Unload(us::ModuleContext* ); + +private: + + void HandleModuleEvent(const us::ModuleEvent moduleEvent); + + void RegisterMimeTypes(); + void RegisterItkReaderWriter(); + + void RegisterMimeType(const std::string& id, const std::string& category, + const std::string& description, const std::string& extension); + + void RegisterMimeType(const std::string& id, const std::string& category, + const std::string& description, const std::vector& extensions); + + std::map > moduleIdToShaderIds; + + //mitk::RenderingManager::Pointer m_RenderingManager; + std::auto_ptr m_PlanePositionManager; + 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; + std::auto_ptr m_MimeTypeProvider; + + // File IO + std::vector m_FileReaders; + std::vector m_FileWriters; + + us::ServiceRegistration m_MimeTypeProviderReg; + + mitk::SimpleMimeType m_MimeType; + + us::ModuleContext* m_Context; +}; + +#endif // MITKCOREACTIVATOR_H_ diff --git a/Core/Code/Internal/mitkItkFileReaderService.cpp b/Core/Code/Internal/mitkItkFileReaderService.cpp new file mode 100644 index 0000000000..d71b6579af --- /dev/null +++ b/Core/Code/Internal/mitkItkFileReaderService.cpp @@ -0,0 +1,227 @@ +/*=================================================================== + +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 "mitkItkFileReaderService.h" + +#include +#include + +#include +#include +#include +#include + +mitk::ItkFileReaderService::ItkFileReaderService(const mitk::ItkFileReaderService& other) + : mitk::AbstractFileReader(other) +{ +} + +mitk::ItkFileReaderService::ItkFileReaderService(const std::vector& extensions, + const std::string& category) + : AbstractFileReader() +{ + for(std::vector::const_iterator iter = extensions.begin(), + endIter = extensions.end(); iter != endIter; ++iter) + { + std::string extension = *iter; + if (!extension.empty() && extension[0] == '.') + { + extension.assign(extension.begin()+1, extension.end()); + } + this->AddExtension(extension); + } + this->SetCategory(category); + this->SetDescription(category); + + m_ServiceReg = this->RegisterService(); +} + +mitk::ItkFileReaderService::~ItkFileReaderService() +{ + try + { + m_ServiceReg.Unregister(); + } + catch (const std::exception&) + {} +} + +////////////////////// Reading ///////////////////////// + +std::vector mitk::ItkFileReaderService::Read(std::istream& stream) +{ + return mitk::AbstractFileReader::Read(stream); +} + +std::vector mitk::ItkFileReaderService::Read(const std::string& path) +{ + std::vector result; + + const std::string& locale = "C"; + const std::string& currLocale = setlocale( LC_ALL, NULL ); + + if ( locale.compare(currLocale)!=0 ) + { + try + { + setlocale(LC_ALL, locale.c_str()); + } + catch(...) + { + MITK_INFO << "Could not set locale " << locale; + } + } + + mitk::Image::Pointer image = mitk::Image::New(); + + const unsigned int MINDIM = 2; + const unsigned int MAXDIM = 4; + + MITK_INFO << "loading " << path << " via itk::ImageIOFactory... " << std::endl; + + // Check to see if we can read the file given the name or prefix + if (path.empty()) + { + mitkThrow() << "Empty filename in mitk::ItkFileReaderService "; + } + + itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( path.c_str(), itk::ImageIOFactory::ReadMode ); + if ( imageIO.IsNull() ) + { + mitkThrow() << "Could not create itk::ImageIOBase object for filename " << path; + } + + // Got to allocate space for the image. Determine the characteristics of + // the image. + imageIO->SetFileName( path.c_str() ); + imageIO->ReadImageInformation(); + + unsigned int ndim = imageIO->GetNumberOfDimensions(); + if ( ndim < MINDIM || ndim > MAXDIM ) + { + MITK_WARN << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D."; + ndim = MAXDIM; + } + + itk::ImageIORegion ioRegion( ndim ); + itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize(); + itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); + + unsigned int dimensions[ MAXDIM ]; + dimensions[ 0 ] = 0; + dimensions[ 1 ] = 0; + dimensions[ 2 ] = 0; + dimensions[ 3 ] = 0; + + ScalarType spacing[ MAXDIM ]; + spacing[ 0 ] = 1.0f; + spacing[ 1 ] = 1.0f; + spacing[ 2 ] = 1.0f; + spacing[ 3 ] = 1.0f; + + Point3D origin; + origin.Fill(0); + + unsigned int i; + for ( i = 0; i < ndim ; ++i ) + { + ioStart[ i ] = 0; + ioSize[ i ] = imageIO->GetDimensions( i ); + if(iGetDimensions( i ); + spacing[ i ] = imageIO->GetSpacing( i ); + if(spacing[ i ] <= 0) + spacing[ i ] = 1.0f; + } + if(i<3) + { + origin[ i ] = imageIO->GetOrigin( i ); + } + } + + ioRegion.SetSize( ioSize ); + ioRegion.SetIndex( ioStart ); + + MITK_INFO << "ioRegion: " << ioRegion << std::endl; + imageIO->SetIORegion( ioRegion ); + void* buffer = new unsigned char[imageIO->GetImageSizeInBytes()]; + imageIO->Read( buffer ); + + image->Initialize( MakePixelType(imageIO), ndim, dimensions ); + image->SetImportChannel( buffer, 0, Image::ManageMemory ); + + // access direction of itk::Image and include spacing + mitk::Matrix3D matrix; + matrix.SetIdentity(); + unsigned int j, itkDimMax3 = (ndim >= 3? 3 : ndim); + for ( i=0; i < itkDimMax3; ++i) + for( j=0; j < itkDimMax3; ++j ) + matrix[i][j] = imageIO->GetDirection(j)[i]; + + // re-initialize PlaneGeometry with origin and direction + PlaneGeometry* planeGeometry = static_cast(image->GetSlicedGeometry(0)->GetGeometry2D(0)); + planeGeometry->SetOrigin(origin); + planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix); + + // re-initialize SlicedGeometry3D + SlicedGeometry3D* slicedGeometry = image->GetSlicedGeometry(0); + slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2)); + slicedGeometry->SetSpacing(spacing); + + MITK_INFO << slicedGeometry->GetCornerPoint(false,false,false); + MITK_INFO << slicedGeometry->GetCornerPoint(true,true,true); + + // re-initialize TimeGeometry + ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); + timeGeometry->Initialize(slicedGeometry, image->GetDimension(3)); + image->SetTimeGeometry(timeGeometry); + + buffer = NULL; + MITK_INFO << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl; + + MITK_INFO << "...finished!" << std::endl; + + try + { + setlocale(LC_ALL, currLocale.c_str()); + } + catch(...) + { + MITK_INFO << "Could not reset locale " << currLocale; + } + + result.push_back(image.GetPointer()); + return result; +} + + +bool mitk::ItkFileReaderService::CanRead(const std::string& path) const +{ + if (AbstractFileReader::CanRead(path) == false) return false; + + itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(path.c_str(), itk::ImageIOFactory::ReadMode); + if (imageIO.IsNull()) + return false; + + return imageIO->CanReadFile(path.c_str()); +} + +mitk::ItkFileReaderService* mitk::ItkFileReaderService::Clone() const +{ + return new ItkFileReaderService(*this); +} diff --git a/Core/Code/Internal/mitkItkFileReaderService.h b/Core/Code/Internal/mitkItkFileReaderService.h new file mode 100644 index 0000000000..1bcca01e47 --- /dev/null +++ b/Core/Code/Internal/mitkItkFileReaderService.h @@ -0,0 +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. + +===================================================================*/ + + +#ifndef MITKITKFILEREADERSERVICE_H +#define MITKITKFILEREADERSERVICE_H + +#include "mitkAbstractFileReader.h" + +namespace mitk { + +// This class represents ITK image file reader instances +// registerred via the ITK object factory system as a micro +// service. +class ItkFileReaderService : public AbstractFileReader +{ + +public: + + ItkFileReaderService(const ItkFileReaderService& other); + + ItkFileReaderService(const std::vector& extensions, const std::string& category); + virtual ~ItkFileReaderService(); + + using AbstractFileReader::Read; + virtual std::vector > Read(const std::string& path); + + virtual std::vector > Read(std::istream& stream); + + using AbstractFileReader::CanRead; + virtual bool CanRead(const std::string& path) const; + +private: + + ItkFileReaderService* Clone() const; + + us::ServiceRegistration m_ServiceReg; + +}; + +} // namespace mitk + +#endif /* MITKITKFILEREADERSERVICE_H */ diff --git a/Core/Code/Internal/mitkLegacyFileReaderService.cpp b/Core/Code/Internal/mitkLegacyFileReaderService.cpp index e547b23d13..79760e0f5a 100644 --- a/Core/Code/Internal/mitkLegacyFileReaderService.cpp +++ b/Core/Code/Internal/mitkLegacyFileReaderService.cpp @@ -1,242 +1,124 @@ /*=================================================================== 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 "mitkLegacyFileReaderService.h" #include #include #include -#include - mitk::LegacyFileReaderService::LegacyFileReaderService(const mitk::LegacyFileReaderService& other) : mitk::AbstractFileReader(other) { } -mitk::LegacyFileReaderService::LegacyFileReaderService(const std::string& mimeType, - const std::string& extension, - const std::string& description) - : AbstractFileReader(mimeType, extension, description) +mitk::LegacyFileReaderService::LegacyFileReaderService(const std::vector& extensions, + const std::string& category) + : AbstractFileReader() { - if (mimeType.empty()) mitkThrow() << "LegacyFileReaderService cannot be initialized without a mime type for extension " << extension << "."; - if (extension.empty()) mitkThrow() << "LegacyFileReaderService cannot be initialized without file extension for mime-type " << mimeType << "."; + for(std::vector::const_iterator iter = extensions.begin(), + endIter = extensions.end(); iter != endIter; ++iter) + { + std::string extension = *iter; + if (!extension.empty() && extension[0] == '.') + { + extension.assign(extension.begin()+1, extension.end()); + } + this->AddExtension(extension); + } + this->SetDescription(category); + this->SetCategory(category); - this->SetPriority(-100); m_ServiceReg = this->RegisterService(); } mitk::LegacyFileReaderService::~LegacyFileReaderService() { try { m_ServiceReg.Unregister(); } catch (const std::exception&) {} } ////////////////////// Reading ///////////////////////// -std::vector > mitk::LegacyFileReaderService::Read(const std::string& path) -{ - std::vector > result; - - // The following code is adapted legacy code copied from 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 - - // 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 (mitk::DicomSeriesReader::IsDicom(path) /*|| first_non_number == std::string::npos*/) - { - result = this->ReadFileSeriesTypeDCM(path); - } - else - { - // the mitkBaseDataIO class returns a pointer of a vector of BaseData objects - result = LoadBaseDataFromFile( path ); - } - - return result; -} - std::vector > mitk::LegacyFileReaderService::Read(std::istream& stream) { return mitk::AbstractFileReader::Read(stream); } -std::vector mitk::LegacyFileReaderService::ReadFileSeriesTypeDCM(const std::string& path) -{ - 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); - - std::vector result; - - if ( DicomSeriesReader::IsPhilips3DDicom(path) ) - { - MITK_INFO << "it is a Philips3D US Dicom file" << std::endl; - DataNode::Pointer node = DataNode::New(); - mitk::DicomSeriesReader::StringContainer stringvec; - stringvec.push_back(path); - if (DicomSeriesReader::LoadDicomSeries(stringvec, *node)) - { - //node->SetName(this->GetBaseFileName()); - } - setlocale(LC_NUMERIC, previousCLocale); - std::cin.imbue(previousCppLocale); - result.push_back(node->GetData()); - } - else - { - std::string dir = itksys::SystemTools::GetFilenamePath(path); - DicomSeriesReader::FileNamesGrouping imageBlocks = DicomSeriesReader::GetSeries(dir, true, std::vector()); // true = group gantry tilt images - const unsigned int size = imageBlocks.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 = DataNode::New(); - - const DicomSeriesReader::ImageBlockDescriptor& imageBlockDescriptor( n_it->second ); - - MITK_INFO << "--------------------------------------------------------------------------------"; - MITK_INFO << "LegayFileReaderService: 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); - result.push_back(node->GetData()); - - ++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); - - return result; -} - -std::vector mitk::LegacyFileReaderService::LoadBaseDataFromFile(const std::string& path) +std::vector > mitk::LegacyFileReaderService::Read(const std::string& path) { - - // factories are instantiated in mitk::CoreObjectFactory and other, potentially MITK external places - std::vector result; std::list possibleIOAdapter; std::list allobjects = itk::ObjectFactoryBase::CreateAllInstance("mitkIOAdapter"); for( std::list::iterator i = allobjects.begin(); i != allobjects.end(); ++i) { IOAdapterBase* io = dynamic_cast(i->GetPointer()); if(io) { possibleIOAdapter.push_back(io); } else { MITK_ERROR << "Error BaseDataIO factory did not return an IOAdapterBase: " << (*i)->GetNameOfClass() << std::endl; } } for( std::list::iterator k = possibleIOAdapter.begin(); k != possibleIOAdapter.end(); ++k ) { bool canReadFile = (*k)->CanReadFile(path, "", ""); // they could read the file if( canReadFile ) { BaseProcess::Pointer ioObject = (*k)->CreateIOProcessObject(path, "", ""); ioObject->Update(); int numberOfContents = static_cast(ioObject->GetNumberOfOutputs()); if (numberOfContents > 0) { BaseData::Pointer baseData; for(int i=0; i(ioObject->GetOutputs()[i].GetPointer()); if (baseData) // this is what's wanted, right? { result.push_back( baseData ); } } } break; } } return result; } -us::ServiceRegistration mitk::LegacyFileReaderService::RegisterMimeType(us::ModuleContext* /*context*/) -{ - // Do nothing. Mime types are registered explicitly in the LegacyIO module - return us::ServiceRegistration(); -} - mitk::LegacyFileReaderService* mitk::LegacyFileReaderService::Clone() const { return new LegacyFileReaderService(*this); } diff --git a/Core/Code/Internal/mitkLegacyFileReaderService.h b/Core/Code/Internal/mitkLegacyFileReaderService.h index e37c00c28b..7dad5335c3 100644 --- a/Core/Code/Internal/mitkLegacyFileReaderService.h +++ b/Core/Code/Internal/mitkLegacyFileReaderService.h @@ -1,67 +1,51 @@ /*=================================================================== 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 LegacyFileReaderService_H_HEADER_INCLUDED_C1E7E521 -#define LegacyFileReaderService_H_HEADER_INCLUDED_C1E7E521 +#ifndef MITKLEGACYFILEREADERSERVICE_H +#define MITKLEGACYFILEREADERSERVICE_H -// Macro -#include - -// MITK -#include #include - namespace mitk { -//##Documentation -//## @brief -//## @ingroup Process +// This class wraps mitk::FileReader instances registered as +// "mitkIOAdapter" via the ITK object factory system as a +// micro service. class LegacyFileReaderService : public mitk::AbstractFileReader { public: LegacyFileReaderService(const LegacyFileReaderService& other); - LegacyFileReaderService(const std::string& mimeType, const std::string& extension, const std::string& description); + LegacyFileReaderService(const std::vector& extensions, const std::string& category); virtual ~LegacyFileReaderService(); - using mitk::AbstractFileReader::Read; - + using AbstractFileReader::Read; virtual std::vector > Read(const std::string& path); - virtual std::vector > Read(std::istream& stream); -protected: - - us::ServiceRegistration RegisterMimeType(us::ModuleContext* context); - private: LegacyFileReaderService* Clone() const; - std::vector ReadFileSeriesTypeDCM(const std::string& path); - - std::vector LoadBaseDataFromFile(const std::string& path); - us::ServiceRegistration m_ServiceReg; }; } // namespace mitk -#endif /* LegacyFileReaderService_H_HEADER_INCLUDED_C1E7E521 */ +#endif /* MITKLEGACYFILEREADERSERVICE_H */ diff --git a/Core/Code/Internal/mitkPointSetReaderService.cpp b/Core/Code/Internal/mitkPointSetReaderService.cpp index 29c7c79ce1..7b195576a4 100644 --- a/Core/Code/Internal/mitkPointSetReaderService.cpp +++ b/Core/Code/Internal/mitkPointSetReaderService.cpp @@ -1,146 +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. ===================================================================*/ // MITK #include "mitkPointSetReaderService.h" #include // STL #include #include #include mitk::PointSetReaderService::PointSetReaderService() - : AbstractFileReader("application/vnd.mitk.pointset", "mps", "Great Reader of Point Sets") + : AbstractFileReader(MimeType("application/vnd.mitk.pointset"), "Great Reader of Point Sets") { + this->AddExtension("mps"); RegisterService(); } mitk::PointSetReaderService::~PointSetReaderService() {} std::vector< itk::SmartPointer > mitk::PointSetReaderService::Read(std::istream& stream) { std::locale::global(std::locale("C")); std::vector< itk::SmartPointer > result; stream.seekg(0, std::ios_base::end); long int length = stream.tellg(); stream.seekg(0, std::ios_base::beg); if (length <= 0) { MITK_WARN << "Could not read point set, no data."; return result; } char* data = new char[length+1]; stream.read(data, length); data[length] = 0; try{ TiXmlDocument doc("pointset.xml"); if (doc.Parse(data)) { TiXmlHandle docHandle( &doc ); //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..."; } delete data; 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; } mitk::PointSetReaderService::PointSetReaderService(const mitk::PointSetReaderService& other) : mitk::AbstractFileReader(other) { } mitk::IFileReader* mitk::PointSetReaderService::Clone() const { return new mitk::PointSetReaderService(*this); } diff --git a/Core/Code/Testing/mitkFileReaderRegistryTest.cpp b/Core/Code/Testing/mitkFileReaderRegistryTest.cpp index d324d86d4e..9c1c78504c 100644 --- a/Core/Code/Testing/mitkFileReaderRegistryTest.cpp +++ b/Core/Code/Testing/mitkFileReaderRegistryTest.cpp @@ -1,208 +1,210 @@ /*=================================================================== 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 class DummyReader : public mitk::AbstractFileReader { public: DummyReader(const DummyReader& other) : mitk::AbstractFileReader(other) { } DummyReader(const std::string& mimeType, const std::string& extension, int priority) - : mitk::AbstractFileReader(mimeType, extension, "This is a dummy description") + : mitk::AbstractFileReader(MimeType(mimeType), "This is a dummy description") { - this->SetPriority(priority); + this->AddExtension(extension); + this->SetRanking(priority); m_ServiceReg = this->RegisterService(); } ~DummyReader() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using mitk::AbstractFileReader::Read; virtual std::vector< itk::SmartPointer > Read(std::istream& /*stream*/) { 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& mimeType, const std::string& extension, int priority) - : mitk::AbstractFileReader(mimeType, extension, "This is a second dummy description") + : mitk::AbstractFileReader(MimeType(mimeType), "This is a second dummy description") { - this->SetPriority(priority); + this->AddExtension(extension); + this->SetRanking(priority); m_ServiceReg = this->RegisterService(); } ~DummyReader2() { if (m_ServiceReg) m_ServiceReg.Unregister(); } using mitk::AbstractFileReader::Read; virtual std::vector< itk::SmartPointer > Read(std::istream& /*stream*/) { 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("application/dummy", "test",1); DummyReader otherDR("application/dummy2", "other",1); 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_TEST_CONDITION_REQUIRED(returned && &static_cast(testDR) != returned,"Testing correct retrieval of FileReader 1/2"); returned = readerRegistry->GetReader("other"); MITK_TEST_CONDITION_REQUIRED(returned && &static_cast(otherDR) != returned,"Testing correct retrieval of FileReader 2/2"); DummyReader mediocreTestDR("application/dummy", "test", 20); DummyReader prettyFlyTestDR("application/dummy", "test", 50); DummyReader2 awesomeTestDR("application/dummy", "test", 100); 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); 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); 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); 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); 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); 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); 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); 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"); // 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; // always end with this! MITK_TEST_END(); } diff --git a/Core/Code/files.cmake b/Core/Code/files.cmake index fee5219d38..b8544a38f0 100644 --- a/Core/Code/files.cmake +++ b/Core/Code/files.cmake @@ -1,403 +1,404 @@ 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 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/mitkCommon.h Common/mitkExceptionMacro.h Common/mitkServiceBaseObject.h Common/mitkTestCaller.h Common/mitkTestFixture.h Common/mitkTesting.h Common/mitkTestingMacros.h DataManagement/mitkProportionalTimeGeometry.h DataManagement/mitkTimeGeometry.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 DataManagement/mitkTimeSlicedGeometry.h # Deprecated, empty for compatibilty reasons. 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/mitkCompareImageDataFilter.cpp Algorithms/mitkMultiComponentImageDataComparisonFilter.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/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/mitkProportionalTimeGeometry.cpp DataManagement/mitkTimeGeometry.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/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/mitkLookupTableProperty.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/mitkPropertyObserver.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/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/mitkIMimeType.cpp Interfaces/mitkIMimeTypeProvider.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/mitkDicomSeriesReader.cpp IO/mitkDicomSR_LoadDICOMScalar.cpp IO/mitkDicomSR_LoadDICOMScalar4D.cpp IO/mitkDicomSR_LoadDICOMRGBPixel.cpp IO/mitkDicomSR_LoadDICOMRGBPixel4D.cpp IO/mitkDicomSR_ImageBlockDescriptor.cpp IO/mitkDicomSR_GantryTiltInformation.cpp IO/mitkDicomSR_SliceGroupingResult.cpp IO/mitkFileReader.cpp IO/mitkFileWriter.cpp IO/mitkFileReaderRegistry.cpp IO/mitkFileWriterRegistry.cpp #IO/mitkIpPicGet.c IO/mitkImageGenerator.cpp IO/mitkItkLoggingAdapter.cpp IO/mitkIOUtil.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/mitkSimpleMimeType.cpp IO/mitkStandardFileLocations.cpp IO/mitkVtkLoggingAdapter.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 Rendering/mitkOverlay.cpp Rendering/mitkVtkOverlay.cpp Rendering/mitkVtkOverlay2D.cpp Rendering/mitkVtkOverlay3D.cpp Rendering/mitkOverlayManager.cpp Rendering/mitkAbstractOverlayLayouter.cpp Rendering/mitkTextOverlay2D.cpp Rendering/mitkTextOverlay3D.cpp Rendering/mitkLabelOverlay3D.cpp Rendering/mitkOverlay2DLayouter.cpp Common/mitkException.cpp Common/mitkCommon.h Common/mitkCoreObjectFactoryBase.cpp Common/mitkCoreObjectFactory.cpp Common/mitkCoreServices.cpp Internal/mitkCoreActivator.cpp + Internal/mitkItkFileReaderService.cpp Internal/mitkLegacyFileReaderService.cpp - Internal/mitkLegacyFileWriterService.cpp + #Internal/mitkLegacyFileWriterService.cpp Internal/mitkMimeTypeProvider.cpp Internal/mitkPointSetReaderService.cpp Internal/mitkPointSetWriterService.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/LegacyIO/mitkActivator.cpp b/Modules/LegacyIO/mitkActivator.cpp index 584dc6da3a..4eef583698 100644 --- a/Modules/LegacyIO/mitkActivator.cpp +++ b/Modules/LegacyIO/mitkActivator.cpp @@ -1,121 +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 #include "mitkSurfaceVtkWriterFactory.h" #include "mitkPointSetIOFactory.h" #include "mitkPointSetWriterFactory.h" #include "mitkSTLFileIOFactory.h" #include "mitkVtkSurfaceIOFactory.h" #include "mitkVtkImageIOFactory.h" #include "mitkVtiFileIOFactory.h" #include "mitkItkImageFileIOFactory.h" #include "mitkImageWriterFactory.h" #include "mitkSimpleMimeType.h" #include #include 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()); this->m_Context = context; - // Register some mime-types - // 3D Images - std::vector mimeTypeExtensions; - mimeTypeExtensions.push_back("dc3"); - mimeTypeExtensions.push_back("dcm"); - RegisterMimeType("application/dicom", "Images", "Dicom Images", mimeTypeExtensions); - RegisterMimeType("application/vnd.mitk.pic", "Images", "DKFZ PIC Format", "pic"); - RegisterMimeType("application/vnd.mitk.pic+gz", "Images", "DKFZ Compressed PIC Format", "pic.gz"); - - // REMOVE: Test multiple mime types for same extension - RegisterMimeType("application/vnd.fancy", "Images", "Fancy Compressed PIC Format", "pic.gz"); - - // 2D Images - RegisterMimeType("image/bmp", "2D Images", "Bitmap Image", "bmp"); m_ObjectFactories.push_back(mitk::PointSetIOFactory::New().GetPointer()); m_ObjectFactories.push_back(mitk::STLFileIOFactory::New().GetPointer()); m_ObjectFactories.push_back(mitk::VtkSurfaceIOFactory::New().GetPointer()); m_ObjectFactories.push_back(mitk::VtkImageIOFactory::New().GetPointer()); m_ObjectFactories.push_back(mitk::VtiFileIOFactory::New().GetPointer()); m_ObjectFactories.push_back(mitk::ItkImageFileIOFactory::New().GetPointer()); 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 } - void RegisterMimeType(const std::string& id, const std::string& category, const std::string& description, - const std::string& extension) - { - std::vector extensions; - extensions.push_back(extension); - this->RegisterMimeType(id, category, description, extensions); - } - - void RegisterMimeType(const std::string& id, const std::string& category, const std::string& description, - const std::vector& extensions) - { - us::ServiceProperties mimeTypeProps; - mimeTypeProps[mitk::IMimeType::PROP_ID()] = id; - mimeTypeProps[mitk::IMimeType::PROP_CATEGORY()] = category; - mimeTypeProps[mitk::IMimeType::PROP_DESCRIPTION()] = description; - mimeTypeProps[mitk::IMimeType::PROP_EXTENSIONS()] = extensions; - mimeTypeProps[us::ServiceConstants::SERVICE_RANKING()] = -100; - m_Context->RegisterService(&m_MimeType, mimeTypeProps); - } - private: //std::auto_ptr m_CoreDataNodeReader; us::ModuleContext* m_Context; std::vector m_ObjectFactories; - mitk::SimpleMimeType m_MimeType; }; US_EXPORT_MODULE_ACTIVATOR(LegacyIO, Activator) diff --git a/Modules/LegacyIO/mitkImageWriter.h b/Modules/LegacyIO/mitkImageWriter.h index 0eba546367..ad304e5b89 100644 --- a/Modules/LegacyIO/mitkImageWriter.h +++ b/Modules/LegacyIO/mitkImageWriter.h @@ -1,172 +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{2014_03} Use mitk::IOUtils or mitk::FileReaderRegistry instead. + * @deprecatedSince{2014_03} Use mitk::IOUtils or mitk::FileWriterRegistry instead. */ class 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_