diff --git a/CMake/mitkFunctionCheckCompilerFlags.cmake b/CMake/mitkFunctionCheckCompilerFlags.cmake index 3df3f41ad5..abf3d13f88 100644 --- a/CMake/mitkFunctionCheckCompilerFlags.cmake +++ b/CMake/mitkFunctionCheckCompilerFlags.cmake @@ -1,80 +1,98 @@ # # Helper macro allowing to check if the given flags are supported # by the underlying build tool # # If the flag(s) is/are supported, they will be appended to the string identified by RESULT_VAR # # Usage: # mitkFunctionCheckCompilerFlags(FLAGS_TO_CHECK VALID_FLAGS_VAR) # # The above example uses the C++ compiler to check the flags. To individually check with # the C and C++ compiler, use: # # mitkFunctionCheckCompilerFlags2(FLAGS_TO_CHECK VALID_C_FLAGS_VAR VALID_CXX_FLAGS_VAR) # # Example: # # set(myflags) # mitkFunctionCheckCompilerFlags("-fprofile-arcs" myflags) # message(1-myflags:${myflags}) # mitkFunctionCheckCompilerFlags("-fauto-bugfix" myflags) # message(2-myflags:${myflags}) # mitkFunctionCheckCompilerFlags("-Wall" myflags) # message(1-myflags:${myflags}) # # The output will be: # 1-myflags: -fprofile-arcs # 2-myflags: -fprofile-arcs # 3-myflags: -fprofile-arcs -Wall include(TestCXXAcceptsFlag) include(CheckCXXCompilerFlag) include(CheckCCompilerFlag) function(mitkFunctionCheckCompilerFlags CXX_FLAG_TO_TEST RESULT_VAR) if(CXX_FLAG_TO_TEST STREQUAL "") message(FATAL_ERROR "CXX_FLAG_TO_TEST shouldn't be empty") endif() # Internally, the macro CMAKE_CXX_ACCEPTS_FLAG calls TRY_COMPILE. To avoid # the cost of compiling the test each time the project is configured, the variable set by # the macro is added to the cache so that following invocation of the macro with # the same variable name skip the compilation step. - # For that same reason, ctkFunctionCheckCompilerFlags function appends a unique suffix to + # For that same reason, the mitkFunctionCheckCompilerFlags function appends a unique suffix to # the HAS_FLAG variable. This suffix is created using a 'clean version' of the flag to test. string(REGEX REPLACE "[, \\$\\+\\*\\{\\}\\(\\)\\#]" "" suffix ${CXX_FLAG_TO_TEST}) CHECK_CXX_ACCEPTS_FLAG(${CXX_FLAG_TO_TEST} HAS_FLAG_${suffix}) if(HAS_FLAG_${suffix}) set(${RESULT_VAR} "${${RESULT_VAR}} ${CXX_FLAG_TO_TEST}" PARENT_SCOPE) endif() endfunction() function(mitkFunctionCheckCompilerFlags2 FLAG_TO_TEST C_RESULT_VAR CXX_RESULT_VAR) if(FLAG_TO_TEST STREQUAL "") message(FATAL_ERROR "FLAG_TO_TEST shouldn't be empty") endif() - # Internally, the macro CMAKE_CXX_ACCEPTS_FLAG calls TRY_COMPILE. To avoid + # Clear all flags. If not, existing flags triggering warnings might lead to + # false-negatives when checking for certain compiler flags. + set(CMAKE_C_FLAGS ) + set(CMAKE_C_FLAGS_DEBUG ) + set(CMAKE_C_FLAGS_MINSIZEREL ) + set(CMAKE_C_FLAGS_RELEASE ) + set(CMAKE_C_FLAGS_RELWITHDEBINFO ) + set(CMAKE_CXX_FLAGS ) + set(CMAKE_CXX_FLAGS_DEBUG ) + set(CMAKE_CXX_FLAGS_MINSIZEREL ) + set(CMAKE_CXX_FLAGS_RELEASE ) + set(CMAKE_CXX_FLAGS_RELWITHDEBINFO ) + + # Internally, the macro CMAKE_CXX_COMPILER_FLAG calls TRY_COMPILE. To avoid # the cost of compiling the test each time the project is configured, the variable set by # the macro is added to the cache so that following invocation of the macro with # the same variable name skip the compilation step. - # For that same reason, ctkFunctionCheckCompilerFlags function appends a unique suffix to - # the HAS_FLAG variable. This suffix is created using a 'clean version' of the flag to test. - string(REGEX REPLACE "[, \\$\\+\\*\\{\\}\\(\\)\\#]" "" suffix ${FLAG_TO_TEST}) + # For that same reason, the mitkFunctionCheckCompilerFlags2 function appends a unique suffix to + # the HAS_CXX_FLAG and HAS_C_FLAG variable. This suffix is created using a 'clean version' of the + # flag to test. The value of HAS_C(XX)_FLAG_${suffix} additonally needs to be a valid + # pre-processor token because CHECK_CXX_COMPILER_FLAG adds it as a definition to the compiler + # arguments. An invalid token triggers compiler warnings, which in case of the "-Werror" flag + # leads to false-negative checks. + string(REGEX REPLACE "[/-]" "_" suffix ${FLAG_TO_TEST}) + string(REGEX REPLACE "[, \\$\\+\\*\\{\\}\\(\\)\\#]" "" suffix ${suffix}) CHECK_CXX_COMPILER_FLAG(${FLAG_TO_TEST} HAS_CXX_FLAG_${suffix}) if(HAS_CXX_FLAG_${suffix}) set(${CXX_RESULT_VAR} "${${CXX_RESULT_VAR}} ${FLAG_TO_TEST}" PARENT_SCOPE) endif() CHECK_C_COMPILER_FLAG(${FLAG_TO_TEST} HAS_C_FLAG_${suffix}) if(HAS_C_FLAG_${suffix}) set(${C_RESULT_VAR} "${${C_RESULT_VAR}} ${FLAG_TO_TEST}" PARENT_SCOPE) endif() endfunction() diff --git a/CMake/mitkSetupVariables.cmake b/CMake/mitkSetupVariables.cmake index d233b8b0b2..84555e5e77 100644 --- a/CMake/mitkSetupVariables.cmake +++ b/CMake/mitkSetupVariables.cmake @@ -1,169 +1,169 @@ if(MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS_OPTION "FORCE_BUILD_ALL") endif() set(LIBPOSTFIX "") # MITK_VERSION -set(MITK_VERSION_MAJOR "2012") -set(MITK_VERSION_MINOR "12") -set(MITK_VERSION_PATCH "99") +set(MITK_VERSION_MAJOR "2013") +set(MITK_VERSION_MINOR "03") +set(MITK_VERSION_PATCH "00") set(MITK_VERSION_STRING "${MITK_VERSION_MAJOR}.${MITK_VERSION_MINOR}.${MITK_VERSION_PATCH}") if(MITK_VERSION_PATCH STREQUAL "99") set(MITK_VERSION_STRING "${MITK_VERSION_STRING}-${MITK_REVISION_SHORTID}") endif() # Needed early on for redirecting the BlueBerry documentation output dir set(MITK_DOXYGEN_OUTPUT_DIR ${PROJECT_BINARY_DIR}/Documentation/Doxygen CACHE PATH "Output directory for doxygen generated documentation." ) #----------------------------------- # Configuration of module system #----------------------------------- set(MODULES_CONF_DIRNAME modulesConf) set(MODULES_CONF_DIRS ${MITK_BINARY_DIR}/${MODULES_CONF_DIRNAME}) if(NOT UNIX AND NOT MINGW) set(MITK_WIN32_FORCE_STATIC "STATIC" CACHE INTERNAL "Use this variable to always build static libraries on non-unix platforms") endif() # build the MITK_INCLUDE_DIRS variable set(MITK_INCLUDE_DIRS ${ITK_INCLUDE_DIRS} ${VTK_INCLUDE_DIRS} ${PROJECT_BINARY_DIR} # contains mitkConfig.h and similar files ${MODULES_CONF_DIRS} # contains module *Exports.h files ) set(CORE_DIRECTORIES Common DataManagement Algorithms IO Rendering Interactions Controllers Service) foreach(d ${CORE_DIRECTORIES}) list(APPEND MITK_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/Core/Code/${d}) endforeach() #list(APPEND MITK_INCLUDE_DIRS #${ITK_INCLUDE_DIRS} #${VTK_INCLUDE_DIRS} # ) foreach(d Utilities Utilities/ipPic Utilities/pic2vtk Utilities/tinyxml Utilities/mbilog) list(APPEND MITK_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/${d}) endforeach() list(APPEND MITK_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/Utilities/mbilog) if(WIN32) list(APPEND MITK_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/ipPic/win32) endif() # additional include dirs variables set(ANN_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/ann/include) set(IPSEGMENTATION_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/ipSegmentation) # variables containing librariy names set(MITK_CORE_LIBRARIES Mitk) set(VTK_FOR_MITK_LIBRARIES vtkGraphics vtkCommon vtkFiltering vtkGraphics vtkHybrid vtkImaging vtkIO vtkParallel vtkRendering vtkVolumeRendering vtkWidgets ${VTK_JPEG_LIBRARIES} ${VTK_PNG_LIBRARIES} ${VTK_ZLIB_LIBRARIES} ${VTK_EXPAT_LIBRARIES} ${VTK_FREETYPE_LIBRARIES} ) # TODO: maybe solve this with lib depends mechanism of CMake set(UTIL_FOR_MITK_LIBRARIES mitkIpPic mitkIpFunc mbilog) set(LIBRARIES_FOR_MITK_CORE ${UTIL_FOR_MITK_LIBRARIES} ${VTK_FOR_MITK_LIBRARIES} ${ITK_LIBRARIES} ) set(MITK_LIBRARIES ${MITK_CORE_LIBRARIES} ${LIBRARIES_FOR_MITK_CORE} pic2vtk ipSegmentation ann ) # variables used in CMake macros which are called from external projects set(MITK_VTK_LIBRARY_DIRS ${VTK_LIBRARY_DIRS}) set(MITK_ITK_LIBRARY_DIRS ${ITK_LIBRARY_DIRS}) # variables containing link directories set(MITK_LIBRARY_DIRS ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}) set(MITK_LINK_DIRECTORIES ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} ${ITK_LIBRARY_DIRS} ${VTK_LIBRARY_DIRS} ${GDCM_LIBRARY_DIRS}) # Qt support if(MITK_USE_QT) find_package(Qt4 REQUIRED) set(QMITK_INCLUDE_DIRS ${MITK_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR}/Modules/Qmitk ${PROJECT_BINARY_DIR}/Modules/Qmitk ) set(QMITK_LIBRARIES Qmitk ${MITK_LIBRARIES}) set(QMITK_LINK_DIRECTORIES ${MITK_LINK_DIRECTORIES}) endif() if(MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS_OPTION "FORCE_BUILD_ALL") endif() # create a list of types for template instantiations of itk image access functions function(_create_type_seq TYPES seq_var seqdim_var) set(_seq ) set(_seq_dim ) string(REPLACE "," ";" _pixeltypes "${TYPES}") foreach(_pixeltype ${_pixeltypes}) set(_seq "${_seq}(${_pixeltype})") set(_seq_dim "${_seq_dim}((${_pixeltype},dim))") endforeach() set(${seq_var} "${_seq}" PARENT_SCOPE) set(${seqdim_var} "${_seq_dim}" PARENT_SCOPE) endfunction() set(MITK_ACCESSBYITK_PIXEL_TYPES ) set(MITK_ACCESSBYITK_PIXEL_TYPES_SEQ ) set(MITK_ACCESSBYITK_TYPES_DIMN_SEQ ) # concatenate only the simple pixel types to the MITK_ACCESSBYITK_PIXEL_TYPE_SEQ list # see Bug 12682 for detailed information foreach(_type INTEGRAL FLOATING) set(_typelist "${MITK_ACCESSBYITK_${_type}_PIXEL_TYPES}") if(_typelist) if(MITK_ACCESSBYITK_PIXEL_TYPES) set(MITK_ACCESSBYITK_PIXEL_TYPES "${MITK_ACCESSBYITK_PIXEL_TYPES},${_typelist}") else() set(MITK_ACCESSBYITK_PIXEL_TYPES "${_typelist}") endif() endif() _create_type_seq("${_typelist}" MITK_ACCESSBYITK_${_type}_PIXEL_TYPES_SEQ MITK_ACCESSBYITK_${_type}_TYPES_DIMN_SEQ) set(MITK_ACCESSBYITK_PIXEL_TYPES_SEQ "${MITK_ACCESSBYITK_PIXEL_TYPES_SEQ}${MITK_ACCESSBYITK_${_type}_PIXEL_TYPES_SEQ}") set(MITK_ACCESSBYITK_TYPES_DIMN_SEQ "${MITK_ACCESSBYITK_TYPES_DIMN_SEQ}${MITK_ACCESSBYITK_${_type}_TYPES_DIMN_SEQ}") endforeach() # separate processing of the COMPOSITE list to avoid its concatenation to to global list _create_type_seq(${MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES} MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES_SEQ MITK_ACCESSBYITK_COMPOSITE_TYPES_DIMN_SEQ) set(MITK_ACCESSBYITK_DIMENSIONS_SEQ ) string(REPLACE "," ";" _dimensions "${MITK_ACCESSBYITK_DIMENSIONS}") foreach(_dimension ${_dimensions}) set(MITK_ACCESSBYITK_DIMENSIONS_SEQ "${MITK_ACCESSBYITK_DIMENSIONS_SEQ}(${_dimension})") endforeach() diff --git a/Core/Code/Controllers/mitkCameraController.h b/Core/Code/Controllers/mitkCameraController.h index 9d30735e01..3327adfa92 100644 --- a/Core/Code/Controllers/mitkCameraController.h +++ b/Core/Code/Controllers/mitkCameraController.h @@ -1,92 +1,93 @@ /*=================================================================== 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 CAMERACONTROLLER_H_HEADER_INCLUDED_C1C53722 #define CAMERACONTROLLER_H_HEADER_INCLUDED_C1C53722 #include #include "mitkBaseController.h" #include "mitkDisplayPositionEvent.h" -#include "mitkKeyEvent.h" namespace mitk { +class KeyEvent; + //##Documentation //## @brief controls the camera used by the associated BaseRenderer //## //## Subclass of BaseController. Controls the camera used by the associated //## BaseRenderer. //## @ingroup NavigationControl class MITK_CORE_EXPORT CameraController : public BaseController { public: enum StandardView { ANTERIOR,POSTERIOR,SINISTER,DEXTER,CRANIAL,CAUDAL }; mitkClassMacro(CameraController, BaseController); mitkNewMacro1Param(Self, const char*); itkSetMacro(Renderer,BaseRenderer*); itkSetMacro(ZoomFactor,double); itkGetConstMacro(Renderer,const BaseRenderer*); itkGetConstMacro(ZoomFactor,double); //##Documentation //## @brief Implemented in sub-classes. virtual void Resize(int w, int h); //##Documentation //## @brief Implemented in sub-classes. virtual void MousePressEvent(mitk::MouseEvent*); //##Documentation //## @brief Implemented in sub-classes. virtual void MouseReleaseEvent(mitk::MouseEvent*); //##Documentation //## @brief Implemented in sub-classes. virtual void MouseMoveEvent(mitk::MouseEvent*); //##Documentation //## @brief Implemented in sub-classes. virtual void KeyPressEvent(mitk::KeyEvent*); virtual void SetViewToAnterior(); virtual void SetViewToPosterior(); virtual void SetViewToSinister(); virtual void SetViewToDexter(); virtual void SetViewToCranial(); virtual void SetViewToCaudal(); virtual void SetStandardView(StandardView view); protected: /** * @brief Default Constructor **/ CameraController(const char * type = NULL); /** * @brief Default Destructor **/ virtual ~CameraController(); const BaseRenderer* m_Renderer; double m_ZoomFactor; ///< zoom factor used for the standard view camera }; } // namespace mitk #endif /* CAMERACONTROLLER_H_HEADER_INCLUDED_C1C53722 */ diff --git a/Core/Code/Controllers/mitkVtkInteractorCameraController.cpp b/Core/Code/Controllers/mitkVtkInteractorCameraController.cpp index 56eafaa330..4c3107b63e 100644 --- a/Core/Code/Controllers/mitkVtkInteractorCameraController.cpp +++ b/Core/Code/Controllers/mitkVtkInteractorCameraController.cpp @@ -1,195 +1,196 @@ /*=================================================================== 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 "mitkVtkInteractorCameraController.h" #include "mitkInteractionConst.h" #include #include #include #include "mitkAction.h" #include "mitkVtkPropRenderer.h" +#include "mitkKeyEvent.h" mitk::VtkInteractorCameraController::VtkInteractorCameraController(const char* type) : CameraController(type), m_VtkInteractor(NULL) { //m_VtkInteractor = vtkRenderWindowInteractor::New(); } mitk::VtkInteractorCameraController::~VtkInteractorCameraController() { if(m_VtkInteractor!=NULL) { m_VtkInteractor->SetRenderWindow(NULL); m_VtkInteractor->Delete(); m_VtkInteractor = NULL; } } void mitk::VtkInteractorCameraController::Resize(int w, int h) { if(m_VtkInteractor) m_VtkInteractor->SetSize(w, h); } void mitk::VtkInteractorCameraController::MousePressEvent(mitk::MouseEvent *me) { MITK_INFO<<"Called MousePressEvent() in VtkInteractorCameraController. Seems to be obsolete after QVTK restructuring (bug #1503, bug #954)"<GetEnabled()) { return; } int ctrl = me->GetButtonState() & BS_ControlButton; int shift = me->GetButtonState() & BS_ShiftButton; int xp = (int)me->GetDisplayPosition()[0]; int yp = (int)me->GetDisplayPosition()[1]; m_VtkInteractor->SetEventInformationFlipY(xp, yp, ctrl, shift); switch (me->GetButton()) { case BS_LeftButton: m_VtkInteractor->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL); break; case BS_MidButton: m_VtkInteractor->InvokeEvent(vtkCommand::MiddleButtonPressEvent,NULL); break; case BS_RightButton: m_VtkInteractor->InvokeEvent(vtkCommand::RightButtonPressEvent,NULL); break; default: return; } } } void mitk::VtkInteractorCameraController::MouseReleaseEvent(mitk::MouseEvent *me) { MITK_INFO<<"Called MouseReleaseEvent() in VtkInteractorCameraController. Seems to be obsolete after QVTK restructuring (bug #1503, bug #954)"<GetEnabled()) { return; } int ctrl = me->GetButtonState() & BS_ControlButton; int shift = me->GetButtonState() & BS_ShiftButton; int xp = (int)me->GetDisplayPosition()[0]; int yp = (int)me->GetDisplayPosition()[1]; m_VtkInteractor->SetEventInformationFlipY(xp, yp, ctrl, shift); switch (me->GetButton()) { case BS_LeftButton: m_VtkInteractor->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); break; case BS_MidButton: m_VtkInteractor->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent,NULL); break; case BS_RightButton: m_VtkInteractor->InvokeEvent(vtkCommand::RightButtonReleaseEvent,NULL); break; default: return; } } } void mitk::VtkInteractorCameraController::MouseMoveEvent(mitk::MouseEvent *me) { MITK_INFO<<"Called MouseMoveEvent() in VtkInteractorCameraController. Seems to be obsolete after QVTK restructuring (bug #1503, bug #954)"<GetEnabled()) { return; } int ctrl = me->GetButtonState() & BS_ControlButton; int shift = me->GetButtonState() & BS_ShiftButton; int xp = (int)me->GetDisplayPosition()[0]; int yp = (int)me->GetDisplayPosition()[1]; m_VtkInteractor->SetEventInformationFlipY(xp, yp, ctrl, shift); m_VtkInteractor->InvokeEvent(vtkCommand::MouseMoveEvent, NULL); } } void mitk::VtkInteractorCameraController::KeyPressEvent(mitk::KeyEvent *ke) { MITK_INFO<<"Called KeyPressEvent() in VtkInteractorCameraController. Seems to be obsolete after QVTK restructuring (bug #1503, bug #954)"<GetEnabled()) { return; } int ctrl = ke->GetButtonState() & BS_ControlButton; int shift = ke->GetButtonState() & BS_ShiftButton; Point2D p(ke->GetDisplayPosition()); m_VtkInteractor->SetEventInformationFlipY(static_cast(p[0]), static_cast(p[1]), ctrl, shift, tolower(ke->GetText()[0]), 1, ke->GetText()); m_VtkInteractor->InvokeEvent(vtkCommand::KeyPressEvent, NULL); m_VtkInteractor->InvokeEvent(vtkCommand::CharEvent, NULL); } } void mitk::VtkInteractorCameraController::SetRenderer(const mitk::BaseRenderer* renderer) { Superclass::SetRenderer(renderer); if (renderer) { // CHG 11-07: QVTK-Widget comes along with vtkRenderWindow and vtkRenWinInteractor, therefore do not // generate a new one any more m_VtkInteractor = renderer->GetVtkRenderer()->GetRenderWindow()->GetInteractor(); m_VtkInteractor->SetRenderWindow(renderer->GetVtkRenderer()->GetRenderWindow()); // Enable possibility to (mouse-)interact with the renderer m_VtkInteractor->Enable(); m_VtkInteractor->Register(NULL); } /* VtkRenderWindowInteractor* windowInteractor = dynamic_cast(m_VtkInteractor); if (windowInteractor == NULL) { itkWarningMacro(<< "renderwindow is not an mitk::VtkRenderWindow"); } else { windowInteractor->SetMitkRenderer(const_cast(this->GetRenderer())); } m_VtkInteractor->Initialize(); m_VtkInteractor->SetRenderWindow(renderer->GetVtkRenderWindow()); } else { m_VtkInteractor->SetRenderWindow(NULL); m_VtkInteractor->Delete(); m_VtkInteractor = NULL; }*/ } vtkRenderWindowInteractor* mitk::VtkInteractorCameraController::GetVtkInteractor() { return m_VtkInteractor; } ///* //bool mitk::VtkInteractorCameraController::ExecuteAction(Action*, mitk::StateEvent const * /*stateEvent*/ //{ // return false; //} //*/ diff --git a/Core/Code/DataManagement/mitkAnnotationProperty.cpp b/Core/Code/DataManagement/mitkAnnotationProperty.cpp index 9ac73e5d9f..0ce2f6eb60 100644 --- a/Core/Code/DataManagement/mitkAnnotationProperty.cpp +++ b/Core/Code/DataManagement/mitkAnnotationProperty.cpp @@ -1,106 +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 "mitkAnnotationProperty.h" mitk::AnnotationProperty::AnnotationProperty() { } mitk::AnnotationProperty::AnnotationProperty( const char *label, const Point3D &position ) : m_Label( "" ), m_Position( position ) { if ( label != NULL ) { m_Label = label; } } mitk::AnnotationProperty::AnnotationProperty( const std::string &label, const Point3D &position ) : m_Label( label ), m_Position( position ) { } mitk::AnnotationProperty::AnnotationProperty( const char *label, ScalarType x, ScalarType y, ScalarType z ) : m_Label( "" ) { if ( label != NULL ) { m_Label = label; } m_Position[0] = x; m_Position[1] = y; m_Position[2] = z; } mitk::AnnotationProperty::AnnotationProperty( const std::string &label, ScalarType x, ScalarType y, ScalarType z ) : m_Label( label ) { m_Position[0] = x; m_Position[1] = y; m_Position[2] = z; } +mitk::AnnotationProperty::AnnotationProperty(const mitk::AnnotationProperty& other) + : BaseProperty(other) + , m_Label(other.m_Label) + , m_Position(other.m_Position) +{ +} const mitk::Point3D &mitk::AnnotationProperty::GetPosition() const { return m_Position; } void mitk::AnnotationProperty::SetPosition( const mitk::Point3D &position ) { if (m_Position != position) { m_Position = position; this->Modified(); } } bool mitk::AnnotationProperty::IsEqual( const BaseProperty &property ) const { return ( (this->m_Label == static_cast(property).m_Label ) && (this->m_Position == static_cast(property).m_Position ) ); } bool mitk::AnnotationProperty::Assign( const BaseProperty &property ) { this->m_Label = static_cast(property).m_Label; this->m_Position = static_cast(property).m_Position; return true; } std::string mitk::AnnotationProperty::GetValueAsString() const { std::stringstream myStr; myStr << this->GetLabel() << this->GetPosition(); return myStr.str(); } + +mitk::AnnotationProperty::Pointer mitk::AnnotationProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::AnnotationProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkAnnotationProperty.h b/Core/Code/DataManagement/mitkAnnotationProperty.h index b3f14b332f..73ecab4daa 100644 --- a/Core/Code/DataManagement/mitkAnnotationProperty.h +++ b/Core/Code/DataManagement/mitkAnnotationProperty.h @@ -1,86 +1,93 @@ /*=================================================================== 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 MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED #define MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED #include #include "mitkBaseProperty.h" #include "mitkVector.h" #include #include namespace mitk { /** * \brief Property for annotations * \ingroup DataManagement */ class MITK_CORE_EXPORT AnnotationProperty : public BaseProperty { public: - mitkClassMacro(AnnotationProperty, BaseProperty); + mitkClassMacro(AnnotationProperty, BaseProperty) + typedef std::string ValueType; itkNewMacro( AnnotationProperty ); mitkNewMacro2Param( AnnotationProperty, const char *, const Point3D & ); mitkNewMacro2Param( AnnotationProperty, const std::string &, const Point3D & ); mitkNewMacro4Param( AnnotationProperty, const char *, ScalarType, ScalarType, ScalarType ); mitkNewMacro4Param( AnnotationProperty, const std::string &, ScalarType, ScalarType, ScalarType ); + Pointer Clone() const; + itkGetStringMacro( Label ); itkSetStringMacro( Label ); const Point3D &GetPosition() const; void SetPosition( const Point3D &position ); virtual std::string GetValueAsString() const; virtual BaseProperty& operator=(const BaseProperty& other) { return Superclass::operator=(other); } \ + using BaseProperty::operator =; protected: std::string m_Label; Point3D m_Position; AnnotationProperty(); AnnotationProperty( const char *label, const Point3D &position ); AnnotationProperty( const std::string &label, const Point3D &position ); AnnotationProperty( const char *label, ScalarType x, ScalarType y, ScalarType z ); AnnotationProperty( const std::string &label, ScalarType x, ScalarType y, ScalarType z ); + AnnotationProperty(const AnnotationProperty& other); + private: // purposely not implemented - AnnotationProperty(const AnnotationProperty&); AnnotationProperty& operator=(const AnnotationProperty&); + itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty & property); }; } // namespace mitk #endif /* MITKANNOTATIONPROPERTY_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkBaseProperty.cpp b/Core/Code/DataManagement/mitkBaseProperty.cpp index c135493c57..abc07dc500 100644 --- a/Core/Code/DataManagement/mitkBaseProperty.cpp +++ b/Core/Code/DataManagement/mitkBaseProperty.cpp @@ -1,61 +1,66 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBaseProperty.h" mitk::BaseProperty::BaseProperty() { } +mitk::BaseProperty::BaseProperty(const mitk::BaseProperty&) + : itk::Object() +{ +} + mitk::BaseProperty::~BaseProperty() { } std::string mitk::BaseProperty::GetValueAsString() const { return std::string("n/a"); } mitk::BaseProperty& mitk::BaseProperty::operator=(const BaseProperty& rhs) { AssignProperty(rhs); return *this; } bool mitk::BaseProperty::AssignProperty(const BaseProperty& rhs) { if (this == &rhs) return true; // no self assignment - const char* t1 = typeid(this).name(); - const char* t2 = typeid(&rhs).name(); - - std::string s1(t1); - std::string s2(t2); - if (typeid(*this) == typeid(rhs) && Assign(rhs)) { this->Modified(); return true; } return false; } +mitk::BaseProperty::Pointer mitk::BaseProperty::Clone() const +{ + Pointer result = dynamic_cast(this->InternalClone().GetPointer()); + return result; +} + bool mitk::BaseProperty::operator==(const BaseProperty& property) const { return (typeid(*this) == typeid(property) && IsEqual(property)); } diff --git a/Core/Code/DataManagement/mitkBaseProperty.h b/Core/Code/DataManagement/mitkBaseProperty.h index d42ced312a..f88ca0e912 100644 --- a/Core/Code/DataManagement/mitkBaseProperty.h +++ b/Core/Code/DataManagement/mitkBaseProperty.h @@ -1,101 +1,106 @@ /*=================================================================== 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 BASEPROPERTY_H_HEADER_INCLUDED_C1F4DF54 #define BASEPROPERTY_H_HEADER_INCLUDED_C1F4DF54 #include #include #include #include namespace mitk { /*! \brief Abstract base class for properties \ingroup DataManagement Base class for properties. Properties are arbitrary additional information (to define a new type of information you have to define a subclass of BaseProperty) that can be added to a PropertyList. Concrete subclasses of BaseProperty should define Set-/Get-methods to assess the property value, which should be stored by value (not by reference). Subclasses must implement an operator==(const BaseProperty& property), which is used by PropertyList to check whether a property has been changed. */ class MITK_CORE_EXPORT BaseProperty : public itk::Object { public: - mitkClassMacro(BaseProperty,itk::Object); + mitkClassMacro(BaseProperty,itk::Object) + + Pointer Clone() const; /*! @brief Subclasses must implement IsEqual(const BaseProperty&) to support comparison. operator== which is used by PropertyList to check whether a property has been changed. */ bool operator==(const BaseProperty& property) const; /*! @brief Assigns property to this BaseProperty instance. Subclasses must implement Assign(const BaseProperty&) and call the superclass Assign method for proper handling of polymorphic assignments. The assignment operator of the subclass should be disabled and the baseclass operator should be made visible using "using" statements. */ BaseProperty& operator=(const BaseProperty& property); /*! @brief Assigns property to this BaseProperty instance. This method is identical to the assignment operator, except for the return type. It allows to directly check if the assignemnt was successfull. */ bool AssignProperty(const BaseProperty & property); virtual std::string GetValueAsString() const; protected: BaseProperty(); + BaseProperty(const BaseProperty& other); virtual ~BaseProperty(); private: /*! Override this method in subclasses to implement a meaningful comparison. The property argument is guaranteed to be castable to the type of the implementing subclass. */ virtual bool IsEqual(const BaseProperty& property) const = 0; /*! Override this method in subclasses to implement a meaningful assignment. The property argument is guaranteed to be castable to the type of the implementing subclass. @warning This is not yet exception aware/safe and if this method returns false, this property's state might be undefined. @return True if the argument could be assigned to this property. */ virtual bool Assign(const BaseProperty& ) = 0; + + virtual itk::LightObject::Pointer InternalClone() const = 0; }; } // namespace mitk #endif /* BASEPROPERTY_H_HEADER_INCLUDED_C1F4DF54 */ diff --git a/Core/Code/DataManagement/mitkClippingProperty.cpp b/Core/Code/DataManagement/mitkClippingProperty.cpp index 56c7168a22..74d6c22c5b 100644 --- a/Core/Code/DataManagement/mitkClippingProperty.cpp +++ b/Core/Code/DataManagement/mitkClippingProperty.cpp @@ -1,111 +1,131 @@ /*=================================================================== 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 "mitkClippingProperty.h" namespace mitk { ClippingProperty::ClippingProperty() : m_ClippingEnabled( false ) { } +ClippingProperty::ClippingProperty(const ClippingProperty& other) + : BaseProperty(other) + , m_ClippingEnabled(other.m_ClippingEnabled) + , m_Origin(other.m_Origin) + , m_Normal(other.m_Normal) +{ +} ClippingProperty::ClippingProperty( const Point3D &origin, const Vector3D &normal ) : m_ClippingEnabled( true ), m_Origin( origin ), m_Normal( normal ) { } bool ClippingProperty::GetClippingEnabled() const { return m_ClippingEnabled; } void ClippingProperty::SetClippingEnabled( bool enabled ) { if (m_ClippingEnabled != enabled) { m_ClippingEnabled = enabled; this->Modified(); } } const Point3D &ClippingProperty::GetOrigin() const { return m_Origin; } void ClippingProperty::SetOrigin( const Point3D &origin ) { if (m_Origin != origin) { m_Origin = origin; this->Modified(); } } const Vector3D &ClippingProperty::GetNormal() const { return m_Normal; } void ClippingProperty::SetNormal( const Vector3D &normal ) { if (m_Normal != normal) { m_Normal = normal; this->Modified(); } } bool ClippingProperty::IsEqual( const BaseProperty &property ) const { return ((this->m_ClippingEnabled == static_cast(property).m_ClippingEnabled) && (this->m_Origin == static_cast(property).m_Origin ) && (this->m_Normal == static_cast(property).m_Normal ) ); } bool ClippingProperty::Assign( const BaseProperty &property ) { this->m_ClippingEnabled = static_cast(property).m_ClippingEnabled; this->m_Origin = static_cast(property).m_Origin; this->m_Normal = static_cast(property).m_Normal; return true; } - std::string ClippingProperty::GetValueAsString() const { std::stringstream myStr; myStr << this->GetClippingEnabled() << this->GetOrigin() << this->GetNormal(); return myStr.str(); } + +ClippingProperty::Pointer ClippingProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer ClippingProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} + + } // namespace diff --git a/Core/Code/DataManagement/mitkClippingProperty.h b/Core/Code/DataManagement/mitkClippingProperty.h index 6486131a33..29a848117f 100644 --- a/Core/Code/DataManagement/mitkClippingProperty.h +++ b/Core/Code/DataManagement/mitkClippingProperty.h @@ -1,93 +1,97 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED #define MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED #include #include "mitkBaseProperty.h" #include "mitkVector.h" #include #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * \brief Property for clipping datasets; currently only * clipping planes are possible * \ingroup DataManagement */ class MITK_CORE_EXPORT ClippingProperty : public BaseProperty { public: - mitkClassMacro(ClippingProperty, BaseProperty); + mitkClassMacro(ClippingProperty, BaseProperty) typedef std::string ValueType; itkNewMacro( ClippingProperty ); mitkNewMacro2Param( ClippingProperty, const Point3D &, const Vector3D & ); + Pointer Clone() const; + bool GetClippingEnabled() const; void SetClippingEnabled( bool enabled ); const Point3D &GetOrigin() const; void SetOrigin( const Point3D &origin ); const Vector3D &GetNormal() const; void SetNormal( const Vector3D &normal ); virtual std::string GetValueAsString() const; using BaseProperty::operator =; protected: bool m_ClippingEnabled; Point3D m_Origin; Vector3D m_Normal; ClippingProperty(); + ClippingProperty(const ClippingProperty& other); ClippingProperty( const Point3D &origin, const Vector3D &normal ); private: // purposely not implemented - ClippingProperty(const ClippingProperty&); ClippingProperty& operator=(const ClippingProperty&); virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); + virtual itk::LightObject::Pointer InternalClone() const; + }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKCLIPPINGPROPERTY_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkColorProperty.cpp b/Core/Code/DataManagement/mitkColorProperty.cpp index 62ee0b7a6c..ca48514c96 100644 --- a/Core/Code/DataManagement/mitkColorProperty.cpp +++ b/Core/Code/DataManagement/mitkColorProperty.cpp @@ -1,87 +1,105 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "mitkColorProperty.h" mitk::ColorProperty::ColorProperty() : m_Color() { } +mitk::ColorProperty::ColorProperty(const mitk::ColorProperty& other) + : BaseProperty(other) + , m_Color(other.m_Color) +{ +} + mitk::ColorProperty::ColorProperty(const float color[3]) : m_Color(color) { } mitk::ColorProperty::ColorProperty(const float red, const float green, const float blue) { m_Color.Set(red, green, blue); } mitk::ColorProperty::ColorProperty(const mitk::Color & color) : m_Color(color) { } bool mitk::ColorProperty::IsEqual(const BaseProperty& property) const { return this->m_Color == static_cast(property).m_Color; } bool mitk::ColorProperty::Assign(const BaseProperty& property) { this->m_Color = static_cast(property).m_Color; return true; } const mitk::Color & mitk::ColorProperty::GetColor() const { return m_Color; } void mitk::ColorProperty::SetColor(const mitk::Color & color ) { if(m_Color!=color) { m_Color = color; Modified(); } } void mitk::ColorProperty::SetValue(const mitk::Color & color ) { SetColor(color); } void mitk::ColorProperty::SetColor( float red, float green, float blue ) { float tmp[3] = { red, green, blue }; SetColor(mitk::Color(tmp)); } std::string mitk::ColorProperty::GetValueAsString() const { std::stringstream myStr; myStr.imbue(std::locale::classic()); myStr << GetValue() ; return myStr.str(); } const mitk::Color & mitk::ColorProperty::GetValue() const { return GetColor(); } + +mitk::ColorProperty::Pointer mitk::ColorProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::ColorProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkColorProperty.h b/Core/Code/DataManagement/mitkColorProperty.h index 2d8501f18d..2b89db9844 100644 --- a/Core/Code/DataManagement/mitkColorProperty.h +++ b/Core/Code/DataManagement/mitkColorProperty.h @@ -1,93 +1,98 @@ /*=================================================================== 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 MITKCOLORPROPERTY_H_HEADER_INCLUDED_C17953D1 #define MITKCOLORPROPERTY_H_HEADER_INCLUDED_C17953D1 #include #include "mitkBaseProperty.h" #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif //##Documentation //## @brief Standard RGB color typedef (float) //## //## Standard RGB color typedef to get rid of template argument (float). //## @ingroup Property typedef itk::RGBPixel< float > Color; //##Documentation //## @brief RGB color property //## //## @ingroup DataManagement class MITK_CORE_EXPORT ColorProperty : public BaseProperty { protected: mitk::Color m_Color; ColorProperty(); + ColorProperty(const ColorProperty& other); + ColorProperty(const float red, const float green, const float blue); ColorProperty(const float color[3]); ColorProperty(const mitk::Color & color); public: - mitkClassMacro(ColorProperty, BaseProperty); + mitkClassMacro(ColorProperty, BaseProperty) itkNewMacro(ColorProperty); mitkNewMacro1Param(ColorProperty, const float*); mitkNewMacro1Param(ColorProperty, const mitk::Color&); mitkNewMacro3Param(ColorProperty, const float, const float, const float); + Pointer Clone() const; + typedef mitk::Color ValueType; const mitk::Color & GetColor() const; const mitk::Color & GetValue() const; std::string GetValueAsString() const; void SetColor(const mitk::Color & color ); void SetValue(const mitk::Color & color ); void SetColor( float red, float green, float blue ); using BaseProperty::operator=; private: // purposely not implemented - ColorProperty(const ColorProperty&); ColorProperty& operator=(const ColorProperty&); + virtual itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty & property); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKCOLORPROPERTY_H_HEADER_INCLUDED_C17953D1 */ diff --git a/Core/Code/DataManagement/mitkDataNode.cpp b/Core/Code/DataManagement/mitkDataNode.cpp index 4d8d099619..30b0ab3a5f 100644 --- a/Core/Code/DataManagement/mitkDataNode.cpp +++ b/Core/Code/DataManagement/mitkDataNode.cpp @@ -1,564 +1,564 @@ /*=================================================================== 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 "mitkDataNode.h" #include "mitkCoreObjectFactory.h" #include #include "mitkProperties.h" #include "mitkStringProperty.h" #include "mitkGroupTagProperty.h" #include "mitkSmartPointerProperty.h" //#include "mitkMaterialProperty.h" #include "mitkColorProperty.h" #include "mitkLevelWindowProperty.h" #include "mitkGeometry3D.h" #include "mitkRenderingManager.h" #include "mitkGlobalInteraction.h" #include "mitkEventMapper.h" #include "mitkGenericProperty.h" #include "mitkCoreObjectFactory.h" mitk::Mapper* mitk::DataNode::GetMapper(MapperSlotId id) const { if( (id >= m_Mappers.size()) || (m_Mappers[id].IsNull()) ) { if(id >= m_Mappers.capacity()) { // int i, size=id-m_Mappers.capacity()+10; m_Mappers.resize(id+10); } m_Mappers[id] = CoreObjectFactory::GetInstance()->CreateMapper(const_cast(this),id); } return m_Mappers[id]; } mitk::BaseData* mitk::DataNode::GetData() const { return m_Data; } mitk::Interactor* mitk::DataNode::GetInteractor() const { return m_Interactor; } void mitk::DataNode::SetData(mitk::BaseData* baseData) { if(m_Data!=baseData) { m_Data=baseData; m_Mappers.clear(); m_Mappers.resize(10); mitk::CoreObjectFactory::GetInstance()->SetDefaultProperties(this); m_DataReferenceChangedTime.Modified(); Modified(); //inform the interactor about the change if (m_Interactor.IsNotNull()) m_Interactor->DataChanged(); } } void mitk::DataNode::SetInteractor(mitk::Interactor* interactor) { m_Interactor = interactor; if(m_Interactor.IsNotNull()) m_Interactor->SetDataNode(this); } mitk::DataNode::DataNode() : m_Data(NULL), m_PropertyListModifiedObserverTag(0) { m_Mappers.resize(10); m_PropertyList = PropertyList::New(); // subscribe for modified event itk::MemberCommand::Pointer _PropertyListModifiedCommand = itk::MemberCommand::New(); _PropertyListModifiedCommand->SetCallbackFunction(this, &mitk::DataNode::PropertyListModified); m_PropertyListModifiedObserverTag = m_PropertyList->AddObserver(itk::ModifiedEvent(), _PropertyListModifiedCommand); } mitk::DataNode::~DataNode() { if(m_PropertyList.IsNotNull()) // remove modified event listener m_PropertyList->RemoveObserver(m_PropertyListModifiedObserverTag); Interactor* interactor = this->GetInteractor(); if ( interactor ) { mitk::GlobalInteraction::GetInstance()->RemoveInteractor( interactor ); } m_Mappers.clear(); m_Data = NULL; } mitk::DataNode& mitk::DataNode::operator=(const DataNode& right) { mitk::DataNode* node=mitk::DataNode::New(); node->SetData(right.GetData()); return *node; } mitk::DataNode& mitk::DataNode::operator=(mitk::BaseData* right) { mitk::DataNode* node=mitk::DataNode::New(); node->SetData(right); return *node; } #if (_MSC_VER > 1200) || !defined(_MSC_VER) MBI_STD::istream& mitk::operator>>( MBI_STD::istream& i, mitk::DataNode::Pointer& dtn ) #endif #if ((defined(_MSC_VER)) && (_MSC_VER <= 1200)) MBI_STD::istream& operator>>( MBI_STD::istream& i, mitk::DataNode::Pointer& dtn ) #endif { dtn = mitk::DataNode::New(); //i >> av.get(); return i; } #if (_MSC_VER > 1200) || !defined(_MSC_VER) MBI_STD::ostream& mitk::operator<<( MBI_STD::ostream& o, mitk::DataNode::Pointer& dtn) #endif #if ((defined(_MSC_VER)) && (_MSC_VER <= 1200)) MBI_STD::ostream& operator<<( MBI_STD::ostream& o, mitk::DataNode::Pointer& dtn) #endif { if(dtn->GetData()!=NULL) o<GetData()->GetNameOfClass(); else o<<"empty data"; return o; } void mitk::DataNode::SetMapper(MapperSlotId id, mitk::Mapper* mapper) { m_Mappers[id] = mapper; if (mapper!=NULL) mapper->SetDataNode(this); } void mitk::DataNode::UpdateOutputInformation() { if (this->GetSource()) { this->GetSource()->UpdateOutputInformation(); } } void mitk::DataNode::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::DataNode::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::DataNode::VerifyRequestedRegion() { return true; } void mitk::DataNode::SetRequestedRegion(itk::DataObject * /*data*/) { } void mitk::DataNode::CopyInformation(const itk::DataObject * /*data*/) { } mitk::PropertyList* mitk::DataNode::GetPropertyList(const mitk::BaseRenderer* renderer) const { if(renderer==NULL) return m_PropertyList; mitk::PropertyList::Pointer & propertyList = m_MapOfPropertyLists[renderer]; if(propertyList.IsNull()) propertyList = mitk::PropertyList::New(); assert(m_MapOfPropertyLists[renderer].IsNotNull()); return propertyList; } void mitk::DataNode::ConcatenatePropertyList(PropertyList *pList, bool replace) { m_PropertyList->ConcatenatePropertyList(pList, replace); } mitk::BaseProperty* mitk::DataNode::GetProperty(const char *propertyKey, const mitk::BaseRenderer* renderer) const { if(propertyKey==NULL) return NULL; //renderer specified? if (renderer) { std::map::const_iterator it; //check for the renderer specific property it=m_MapOfPropertyLists.find(renderer); if(it!=m_MapOfPropertyLists.end()) //found { mitk::BaseProperty::Pointer property; property=it->second->GetProperty(propertyKey); if(property.IsNotNull())//found an enabled property in the render specific list return property; else //found a renderer specific list, but not the desired property return m_PropertyList->GetProperty(propertyKey); //return renderer unspecific property } else //didn't find the property list of the given renderer { //return the renderer unspecific property if there is one return m_PropertyList->GetProperty(propertyKey); } } else //no specific renderer given; use the renderer independent one { mitk::BaseProperty::Pointer property; property=m_PropertyList->GetProperty(propertyKey); if(property.IsNotNull()) return property; } //only to satisfy compiler! return NULL; } mitk::DataNode::GroupTagList mitk::DataNode::GetGroupTags() const { GroupTagList groups; const PropertyList::PropertyMap* propertyMap = m_PropertyList->GetMap(); for ( PropertyList::PropertyMap::const_iterator groupIter = propertyMap->begin(); // m_PropertyList is created in the constructor, so we don't check it here groupIter != propertyMap->end(); ++groupIter ) { const BaseProperty* bp = groupIter->second; if ( dynamic_cast(bp) ) { groups.insert( groupIter->first ); } } return groups; } bool mitk::DataNode::GetBoolProperty(const char* propertyKey, bool& boolValue, mitk::BaseRenderer* renderer) const { mitk::BoolProperty::Pointer boolprop = dynamic_cast(GetProperty(propertyKey, renderer)); if(boolprop.IsNull()) return false; boolValue = boolprop->GetValue(); return true; } bool mitk::DataNode::GetIntProperty(const char* propertyKey, int &intValue, mitk::BaseRenderer* renderer) const { mitk::IntProperty::Pointer intprop = dynamic_cast(GetProperty(propertyKey, renderer)); if(intprop.IsNull()) return false; intValue = intprop->GetValue(); return true; } bool mitk::DataNode::GetFloatProperty(const char* propertyKey, float &floatValue, mitk::BaseRenderer* renderer) const { mitk::FloatProperty::Pointer floatprop = dynamic_cast(GetProperty(propertyKey, renderer)); if(floatprop.IsNull()) return false; floatValue = floatprop->GetValue(); return true; } bool mitk::DataNode::GetStringProperty(const char* propertyKey, std::string& string, mitk::BaseRenderer* renderer) const { mitk::StringProperty::Pointer stringProp = dynamic_cast(GetProperty(propertyKey, renderer)); if(stringProp.IsNull()) { return false; } else { //memcpy((void*)string, stringProp->GetValue(), strlen(stringProp->GetValue()) + 1 ); // looks dangerous string = stringProp->GetValue(); return true; } } bool mitk::DataNode::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* propertyKey) const { mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetProperty(propertyKey, renderer)); if(colorprop.IsNull()) return false; memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); return true; } bool mitk::DataNode::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* propertyKey) const { mitk::FloatProperty::Pointer opacityprop = dynamic_cast(GetProperty(propertyKey, renderer)); if(opacityprop.IsNull()) return false; opacity=opacityprop->GetValue(); return true; } bool mitk::DataNode::GetLevelWindow(mitk::LevelWindow &levelWindow, mitk::BaseRenderer* renderer, const char* propertyKey) const { mitk::LevelWindowProperty::Pointer levWinProp = dynamic_cast(GetProperty(propertyKey, renderer)); if(levWinProp.IsNull()) return false; levelWindow=levWinProp->GetLevelWindow(); return true; } void mitk::DataNode::SetColor(const mitk::Color &color, mitk::BaseRenderer* renderer, const char* propertyKey) { mitk::ColorProperty::Pointer prop; prop = mitk::ColorProperty::New(color); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } void mitk::DataNode::SetColor(float red, float green, float blue, mitk::BaseRenderer* renderer, const char* propertyKey) { float color[3]; color[0]=red; color[1]=green; color[2]=blue; SetColor(color, renderer, propertyKey); } void mitk::DataNode::SetColor(const float rgb[3], mitk::BaseRenderer* renderer, const char* propertyKey) { mitk::ColorProperty::Pointer prop; prop = mitk::ColorProperty::New(rgb); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } void mitk::DataNode::SetVisibility(bool visible, mitk::BaseRenderer* renderer, const char* propertyKey) { mitk::BoolProperty::Pointer prop; prop = mitk::BoolProperty::New(visible); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } void mitk::DataNode::SetOpacity(float opacity, mitk::BaseRenderer* renderer, const char* propertyKey) { mitk::FloatProperty::Pointer prop; prop = mitk::FloatProperty::New(opacity); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } void mitk::DataNode::SetLevelWindow(mitk::LevelWindow levelWindow, mitk::BaseRenderer* renderer, const char* propertyKey) { mitk::LevelWindowProperty::Pointer prop; prop = mitk::LevelWindowProperty::New(levelWindow); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } void mitk::DataNode::SetIntProperty(const char* propertyKey, int intValue, mitk::BaseRenderer* renderer) { GetPropertyList(renderer)->SetProperty(propertyKey, mitk::IntProperty::New(intValue)); } void mitk::DataNode::SetBoolProperty( const char* propertyKey, bool boolValue, mitk::BaseRenderer* renderer/*=NULL*/ ) { GetPropertyList(renderer)->SetProperty(propertyKey, mitk::BoolProperty::New(boolValue)); } void mitk::DataNode::SetFloatProperty( const char* propertyKey, float floatValue, mitk::BaseRenderer* renderer/*=NULL*/ ) { GetPropertyList(renderer)->SetProperty(propertyKey, mitk::FloatProperty::New(floatValue)); } void mitk::DataNode::SetStringProperty( const char* propertyKey, const char* stringValue, mitk::BaseRenderer* renderer/*=NULL*/ ) { GetPropertyList(renderer)->SetProperty(propertyKey, mitk::StringProperty::New(stringValue)); } void mitk::DataNode::SetProperty(const char *propertyKey, BaseProperty* propertyValue, const mitk::BaseRenderer* renderer) { GetPropertyList(renderer)->SetProperty(propertyKey, propertyValue); } void mitk::DataNode::ReplaceProperty(const char *propertyKey, BaseProperty* propertyValue, const mitk::BaseRenderer* renderer) { GetPropertyList(renderer)->ReplaceProperty(propertyKey, propertyValue); } void mitk::DataNode::AddProperty(const char *propertyKey, BaseProperty* propertyValue, const mitk::BaseRenderer* renderer, bool overwrite) { if((overwrite) || (GetProperty(propertyKey, renderer) == NULL)) { SetProperty(propertyKey, propertyValue, renderer); } } vtkLinearTransform* mitk::DataNode::GetVtkTransform(int t) const { assert(m_Data.IsNotNull()); mitk::Geometry3D* geometry = m_Data->GetGeometry(t); if(geometry == NULL) return NULL; return geometry->GetVtkTransform(); } unsigned long mitk::DataNode::GetMTime() const { unsigned long time = Superclass::GetMTime(); if(m_Data.IsNotNull()) { if((time < m_Data->GetMTime()) || ((m_Data->GetSource().IsNotNull()) && (time < m_Data->GetSource()->GetMTime())) ) { Modified(); return Superclass::GetMTime(); } } return time; } void mitk::DataNode::SetSelected(bool selected, mitk::BaseRenderer* renderer) { mitk::BoolProperty::Pointer selectedProperty = dynamic_cast(GetProperty("selected")); if ( selectedProperty.IsNull() ) { selectedProperty = mitk::BoolProperty::New(); selectedProperty->SetValue(false); SetProperty("selected", selectedProperty, renderer); } if( selectedProperty->GetValue() != selected ) { selectedProperty->SetValue(selected); itk::ModifiedEvent event; InvokeEvent( event ); } } /* class SelectedEvent : public itk::ModifiedEvent { public: typedef SelectedEvent Self; typedef itk::ModifiedEvent Superclass; SelectedEvent(DataNode* dataNode) { m_DataNode = dataNode; }; DataNode* GetDataNode() { return m_DataNode; }; virtual const char * GetEventName() const { return "SelectedEvent"; } virtual bool CheckEvent(const ::itk::EventObject* e) const { return dynamic_cast(e); } virtual ::itk::EventObject* MakeObject() const { return new Self(m_DataNode); } private: DataNode* m_DataNode; SelectedEvent(const Self& event) { m_DataNode = event.m_DataNode; }; void operator=(const Self& event) { m_DataNode = event.m_DataNode; } }; */ bool mitk::DataNode::IsSelected(mitk::BaseRenderer* renderer) { bool selected; if ( !GetBoolProperty("selected", selected, renderer) ) return false; return selected; } void mitk::DataNode::SetInteractorEnabled( const bool& enabled ) { if ( m_Interactor.IsNull() ) { itkWarningMacro("Interactor is NULL. Couldn't enable or disable interaction."); return; } if ( enabled ) mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor.GetPointer() ); else mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor.GetPointer() ); } void mitk::DataNode::EnableInteractor() { SetInteractorEnabled( true ); } void mitk::DataNode::DisableInteractor() { SetInteractorEnabled( false ); } bool mitk::DataNode::IsInteractorEnabled() const { return mitk::GlobalInteraction::GetInstance()->InteractorRegistered( m_Interactor.GetPointer() ); } -void mitk::DataNode::SetDataInteractor(DataInteractor::Pointer interactor) +void mitk::DataNode::SetDataInteractor(const DataInteractor::Pointer& interactor) { m_DataInteractor = interactor; Modified(); } mitk::DataInteractor::Pointer mitk::DataNode::GetDataInteractor() const { return m_DataInteractor; } void mitk::DataNode::PropertyListModified( const itk::Object* /*caller*/, const itk::EventObject& ) { Modified(); } diff --git a/Core/Code/DataManagement/mitkDataNode.h b/Core/Code/DataManagement/mitkDataNode.h index f9050c0aff..921d4cad6c 100644 --- a/Core/Code/DataManagement/mitkDataNode.h +++ b/Core/Code/DataManagement/mitkDataNode.h @@ -1,531 +1,533 @@ /*=================================================================== 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 DATATREENODE_H_HEADER_INCLUDED_C1E14338 #define DATATREENODE_H_HEADER_INCLUDED_C1E14338 #include "mitkImageSource.h" #include "mitkBaseData.h" //#include "mitkMapper.h" #include "mitkInteractor.h" #include "mitkDataInteractor.h" #ifdef MBI_NO_STD_NAMESPACE #define MBI_STD #include #include #else #define MBI_STD std #include #include #endif #include "mitkStringProperty.h" #include "mitkColorProperty.h" #include "mitkPropertyList.h" //#include "mitkMapper.h" #include #include #include "mitkLevelWindow.h" class vtkLinearTransform; namespace mitk { class BaseRenderer; class Mapper; //##Documentation //## @brief Class for nodes of the DataTree //## //## Contains the data (instance of BaseData), a list of mappers, which can //## draw the data, a transform (vtkTransform) and a list of properties //## (PropertyList). //## @ingroup DataManagement //## //## @todo clean up all the GetProperty methods. There are too many different flavours... Can most probably be reduced to bool GetProperty(type&) //## //## @warning Change in semantics of SetProperty() since Aug 25th 2006. Check your usage of this method if you do //## more with properties than just call SetProperty( "key", new SomeProperty("value") ). class MITK_CORE_EXPORT DataNode : public itk::DataObject { public: typedef mitk::Geometry3D::Pointer Geometry3DPointer; typedef std::vector< itk::SmartPointer< Mapper > > MapperVector; typedef std::map MapOfPropertyLists; typedef std::set GroupTagList; mitkClassMacro(DataNode, itk::DataObject); itkNewMacro(Self); mitk::Mapper* GetMapper(MapperSlotId id) const; //##Documentation //## @brief Get the data object (instance of BaseData, e.g., an Image) //## managed by this DataNode BaseData* GetData() const; //##Documentation //## @brief Get the transformation applied prior to displaying the data as //## a vtkTransform //## \deprecated use GetData()->GetGeometry()->GetVtkTransform() instead vtkLinearTransform* GetVtkTransform(int t=0) const; //##Documentation - //## @brief Get the Interactor + //## @brief Get the Interactor. + //## @deprecatedSince{2013_03} Use DataInteractor and GetDataInteractor instead. Interactor* GetInteractor() const; //##Documentation //## @brief Set the data object (instance of BaseData, e.g., an Image) //## managed by this DataNode //## @warning the actor-mode of the vtkInteractor does not work any more, if the transform of the //## data-tree-node is connected to the transform of the basedata via vtkTransform->SetInput. virtual void SetData(mitk::BaseData* baseData); //##Documentation - //## @brief Set the Interactor + //## @brief Set the Interactor. + //## @deprecatedSince{2013_03} Use DataInteractor and SetDataInteractor instead. virtual void SetInteractor(Interactor* interactor); - virtual void SetDataInteractor(DataInteractor::Pointer interactor); + virtual void SetDataInteractor(const DataInteractor::Pointer& interactor); virtual DataInteractor::Pointer GetDataInteractor() const; mitk::DataNode& operator=(const DataNode& right); mitk::DataNode& operator=(BaseData* right); virtual void SetMapper(MapperSlotId id, mitk::Mapper* mapper); virtual void UpdateOutputInformation(); virtual void SetRequestedRegionToLargestPossibleRegion(); virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); virtual bool VerifyRequestedRegion(); virtual void SetRequestedRegion(itk::DataObject *data); virtual void CopyInformation(const itk::DataObject *data); //##Documentation //## @brief Set the property (instance of BaseProperty) with key @a propertyKey in the PropertyList //## of the @a renderer (if NULL, use BaseRenderer-independent PropertyList). This is set-by-value. //## //## @warning Change in semantics since Aug 25th 2006. Check your usage of this method if you do //## more with properties than just call SetProperty( "key", new SomeProperty("value") ). //## //## @sa GetProperty //## @sa m_PropertyList //## @sa m_MapOfPropertyLists void SetProperty(const char *propertyKey, BaseProperty* property, const mitk::BaseRenderer* renderer = NULL); //##Documentation //## @brief Replace the property (instance of BaseProperty) with key @a propertyKey in the PropertyList //## of the @a renderer (if NULL, use BaseRenderer-independent PropertyList). This is set-by-reference. //## //## If @a renderer is @a NULL the property is set in the BaseRenderer-independent //## PropertyList of this DataNode. //## @sa GetProperty //## @sa m_PropertyList //## @sa m_MapOfPropertyLists void ReplaceProperty(const char *propertyKey, BaseProperty* property, const mitk::BaseRenderer* renderer = NULL); //##Documentation //## @brief Add the property (instance of BaseProperty) if it does //## not exist (or always if \a overwrite is \a true) //## with key @a propertyKey in the PropertyList //## of the @a renderer (if NULL, use BaseRenderer-independent //## PropertyList). This is set-by-value. //## //## For \a overwrite == \a false the property is \em not changed //## if it already exists. For \a overwrite == \a true the method //## is identical to SetProperty. //## //## @sa SetProperty //## @sa GetProperty //## @sa m_PropertyList //## @sa m_MapOfPropertyLists void AddProperty(const char *propertyKey, BaseProperty* property, const mitk::BaseRenderer* renderer = NULL, bool overwrite = false); //##Documentation //## @brief Get the PropertyList of the @a renderer. If @a renderer is @a //## NULL, the BaseRenderer-independent PropertyList of this DataNode //## is returned. //## @sa GetProperty //## @sa m_PropertyList //## @sa m_MapOfPropertyLists mitk::PropertyList* GetPropertyList(const mitk::BaseRenderer* renderer = NULL) const; //##Documentation //## @brief Add values from another PropertyList. //## //## Overwrites values in m_PropertyList only when possible (i.e. when types are compatible). //## If you want to allow for object type changes (replacing a "visible":BoolProperty with "visible":IntProperty, //## set the @param replace. //## //## @param replace true: if @param pList contains a property "visible" of type ColorProperty and our m_PropertyList also has a "visible" property of a different type (e.g. BoolProperty), change the type, i.e. replace the objects behind the pointer. //## //## @sa SetProperty //## @sa ReplaceProperty //## @sa m_PropertyList void ConcatenatePropertyList(PropertyList* pList, bool replace = false); //##Documentation //## @brief Get the property (instance of BaseProperty) with key @a propertyKey from the PropertyList //## of the @a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. //## //## If @a renderer is @a NULL or the @a propertyKey cannot be found //## in the PropertyList specific to @a renderer or is disabled there, the BaseRenderer-independent //## PropertyList of this DataNode is queried. //## @sa GetPropertyList //## @sa m_PropertyList //## @sa m_MapOfPropertyLists mitk::BaseProperty* GetProperty(const char *propertyKey, const mitk::BaseRenderer* renderer = NULL) const; //##Documentation //## @brief Get the property of type T with key @a propertyKey from the PropertyList //## of the @a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. //## //## If @a renderer is @a NULL or the @a propertyKey cannot be found //## in the PropertyList specific to @a renderer or is disabled there, the BaseRenderer-independent //## PropertyList of this DataNode is queried. //## @sa GetPropertyList //## @sa m_PropertyList //## @sa m_MapOfPropertyLists template bool GetProperty(itk::SmartPointer &property, const char *propertyKey, const mitk::BaseRenderer* renderer = NULL) const { property = dynamic_cast(GetProperty(propertyKey, renderer)); return property.IsNotNull(); } //##Documentation //## @brief Get the property of type T with key @a propertyKey from the PropertyList //## of the @a renderer, if available there, otherwise use the BaseRenderer-independent PropertyList. //## //## If @a renderer is @a NULL or the @a propertyKey cannot be found //## in the PropertyList specific to @a renderer or is disabled there, the BaseRenderer-independent //## PropertyList of this DataNode is queried. //## @sa GetPropertyList //## @sa m_PropertyList //## @sa m_MapOfPropertyLists template bool GetProperty(T* &property, const char *propertyKey, const mitk::BaseRenderer* renderer = NULL) const { property = dynamic_cast(GetProperty(propertyKey, renderer)); return property!=NULL; } //##Documentation //## @brief Convenience access method for GenericProperty properties //## (T being the type of the second parameter) //## @return @a true property was found template bool GetPropertyValue(const char* propertyKey, T & value, mitk::BaseRenderer* renderer=NULL) const { GenericProperty* gp= dynamic_cast*>(GetProperty(propertyKey, renderer)); if ( gp != NULL ) { value = gp->GetValue(); return true; } return false; } // @brief Get a set of all group tags from this node's property list GroupTagList GetGroupTags() const; //##Documentation //## @brief Convenience access method for bool properties (instances of //## BoolProperty) //## @return @a true property was found bool GetBoolProperty(const char* propertyKey, bool &boolValue, mitk::BaseRenderer* renderer = NULL) const; //##Documentation //## @brief Convenience access method for int properties (instances of //## IntProperty) //## @return @a true property was found bool GetIntProperty(const char* propertyKey, int &intValue, mitk::BaseRenderer* renderer=NULL) const; //##Documentation //## @brief Convenience access method for float properties (instances of //## FloatProperty) //## @return @a true property was found bool GetFloatProperty(const char* propertyKey, float &floatValue, mitk::BaseRenderer* renderer = NULL) const; //##Documentation //## @brief Convenience access method for string properties (instances of //## StringProperty) //## @return @a true property was found bool GetStringProperty(const char* propertyKey, std::string& string, mitk::BaseRenderer* renderer = NULL) const; //##Documentation //## @brief Convenience access method for color properties (instances of //## ColorProperty) //## @return @a true property was found bool GetColor(float rgb[3], mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "color") const; //##Documentation //## @brief Convenience access method for level-window properties (instances of //## LevelWindowProperty) //## @return @a true property was found bool GetLevelWindow(mitk::LevelWindow &levelWindow, mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "levelwindow") const; //## //##Documentation //## @brief set the node as selected void SetSelected(bool selected, mitk::BaseRenderer* renderer=NULL); //## //##Documentation //## @brief set the node as selected //## @return @a true node is selected bool IsSelected(mitk::BaseRenderer* renderer=NULL); //##Documentation //## @brief Convenience access method for accessing the name of an object (instance of //## StringProperty with property-key "name") //## @return @a true property was found bool GetName(std::string& nodeName, mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "name") const { return GetStringProperty(propertyKey, nodeName, renderer); } //##Documentation //## @brief Extra convenience access method for accessing the name of an object (instance of //## StringProperty with property-key "name"). //## //## This method does not take the renderer specific //## propertylists into account, because the name of an object should never be renderer specific. //## @returns a std::string with the name of the object (content of "name" Property). //## If there is no "name" Property, an empty string will be returned. virtual std::string GetName() const { mitk::StringProperty* sp = dynamic_cast(this->GetProperty("name")); if (sp == NULL) return ""; return sp->GetValue(); } //##Documentation //## @brief Extra convenience access method to set the name of an object. //## //## The name will be stored in the non-renderer-specific PropertyList in a StringProperty named "name". virtual void SetName( const char* name) { if (name == NULL) return; this->SetProperty("name", StringProperty::New(name)); } //##Documentation //## @brief Extra convenience access method to set the name of an object. //## //## The name will be stored in the non-renderer-specific PropertyList in a StringProperty named "name". virtual void SetName( const std::string name) { this->SetName(name.c_str()); } //##Documentation //## @brief Convenience access method for visibility properties (instances //## of BoolProperty with property-key "visible") //## @return @a true property was found //## @sa IsVisible bool GetVisibility(bool &visible, mitk::BaseRenderer* renderer, const char* propertyKey = "visible") const { return GetBoolProperty(propertyKey, visible, renderer); } //##Documentation //## @brief Convenience access method for opacity properties (instances of //## FloatProperty) //## @return @a true property was found bool GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* propertyKey = "opacity") const; //##Documentation //## @brief Convenience access method for boolean properties (instances //## of BoolProperty). Return value is the value of the property. If the property is //## not found, the value of @a defaultIsOn is returned. //## //## Thus, the return value has a different meaning than in the //## GetBoolProperty method! //## @sa GetBoolProperty bool IsOn(const char* propertyKey, mitk::BaseRenderer* renderer, bool defaultIsOn = true) const { if(propertyKey==NULL) return defaultIsOn; GetBoolProperty(propertyKey, defaultIsOn, renderer); return defaultIsOn; } //##Documentation //## @brief Convenience access method for visibility properties (instances //## of BoolProperty). Return value is the visibility. Default is //## visible==true, i.e., true is returned even if the property (@a //## propertyKey) is not found. //## //## Thus, the return value has a different meaning than in the //## GetVisibility method! //## @sa GetVisibility //## @sa IsOn bool IsVisible(mitk::BaseRenderer* renderer, const char* propertyKey = "visible", bool defaultIsOn = true) const { return IsOn(propertyKey, renderer, defaultIsOn); } //##Documentation //## @brief Convenience method for setting color properties (instances of //## ColorProperty) void SetColor(const mitk::Color &color, mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "color"); //##Documentation //## @brief Convenience method for setting color properties (instances of //## ColorProperty) void SetColor(float red, float green, float blue, mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "color"); //##Documentation //## @brief Convenience method for setting color properties (instances of //## ColorProperty) void SetColor(const float rgb[3], mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "color"); //##Documentation //## @brief Convenience method for setting visibility properties (instances //## of BoolProperty) //## @param visible If set to true, the data will be rendered. If false, the render will skip this data. //## @param renderer Specify a renderer if the visibility shall be specific to a renderer //## @param propertykey Can be used to specify a user defined name of the visibility propery. void SetVisibility(bool visible, mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "visible"); //##Documentation //## @brief Convenience method for setting opacity properties (instances of //## FloatProperty) void SetOpacity(float opacity, mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "opacity"); //##Documentation //## @brief Convenience method for setting level-window properties //## (instances of LevelWindowProperty) void SetLevelWindow(mitk::LevelWindow levelWindow, mitk::BaseRenderer* renderer = NULL, const char* propertyKey = "levelwindow"); //##Documentation //## @brief Convenience method for setting int properties (instances of //## IntProperty) void SetIntProperty(const char* propertyKey, int intValue, mitk::BaseRenderer* renderer=NULL); //##Documentation //## @brief Convenience method for setting int properties (instances of //## IntProperty) void SetBoolProperty(const char* propertyKey, bool boolValue, mitk::BaseRenderer* renderer=NULL); //##Documentation //## @brief Convenience method for setting int properties (instances of //## IntProperty) void SetFloatProperty(const char* propertyKey, float floatValue, mitk::BaseRenderer* renderer=NULL); //##Documentation //## @brief Convenience method for setting int properties (instances of //## IntProperty) void SetStringProperty(const char* propertyKey, const char* string, mitk::BaseRenderer* renderer=NULL); //##Documentation //## @brief Get the timestamp of the last change of the contents of this node or //## the referenced BaseData. virtual unsigned long GetMTime() const; //##Documentation //## @brief Get the timestamp of the last change of the reference to the //## BaseData. unsigned long GetDataReferenceChangedTime() const { return m_DataReferenceChangedTime.GetMTime(); } //##Documentation //## @brief Adds or removes the associated interactor to mitk::GLobalInteraction. //## virtual void SetInteractorEnabled( const bool& enabled ); //##Documentation //## @brief Adds the interactor to mitk::GlobalInteraction //## virtual void EnableInteractor(); //##Documentation //## @brief Removes the Interactor from mitk::GlobalInteraction //## virtual void DisableInteractor(); //##Documentation //## @brief Tests, if the interactor is already added to mitk::GlobalInteraction //## virtual bool IsInteractorEnabled() const; protected: DataNode(); virtual ~DataNode(); //## //## Invoked when the property list was modified. Calls Modified() of the DataNode virtual void PropertyListModified(const itk::Object *caller, const itk::EventObject &event); //##Documentation //## @brief Mapper-slots mutable MapperVector m_Mappers; //##Documentation //## @brief The data object (instance of BaseData, e.g., an Image) managed //## by this DataNode BaseData::Pointer m_Data; //##Documentation //## @brief BaseRenderer-independent PropertyList //## //## Properties herein can be overwritten specifically for each BaseRenderer //## by the BaseRenderer-specific properties defined in m_MapOfPropertyLists. PropertyList::Pointer m_PropertyList; //##Documentation //## @brief Map associating each BaseRenderer with its own PropertyList mutable MapOfPropertyLists m_MapOfPropertyLists; //##Documentation //## @brief Interactor, that handles the Interaction Interactor::Pointer m_Interactor; // TODO: INTERACTION_LEGACY DataInteractor::Pointer m_DataInteractor; //##Documentation //## @brief Timestamp of the last change of m_Data itk::TimeStamp m_DataReferenceChangedTime; unsigned long m_PropertyListModifiedObserverTag; }; #if (_MSC_VER > 1200) || !defined(_MSC_VER) MITK_CORE_EXPORT MBI_STD::istream& operator>>( MBI_STD::istream& i, DataNode::Pointer& dtn ); MITK_CORE_EXPORT MBI_STD::ostream& operator<<( MBI_STD::ostream& o, DataNode::Pointer& dtn); #endif } // namespace mitk #if ((defined(_MSC_VER)) && (_MSC_VER <= 1200)) MITK_CORE_EXPORT MBI_STD::istream& operator>>( MBI_STD::istream& i, mitk::DataNode::Pointer& dtn ); MITK_CORE_EXPORT MBI_STD::ostream& operator<<( MBI_STD::ostream& o, mitk::DataNode::Pointer& dtn); #endif #endif /* DATATREENODE_H_HEADER_INCLUDED_C1E14338 */ diff --git a/Core/Code/DataManagement/mitkEnumerationProperty.cpp b/Core/Code/DataManagement/mitkEnumerationProperty.cpp index 413b1ae05e..7abecbdb2f 100644 --- a/Core/Code/DataManagement/mitkEnumerationProperty.cpp +++ b/Core/Code/DataManagement/mitkEnumerationProperty.cpp @@ -1,195 +1,211 @@ /*=================================================================== 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 "mitkEnumerationProperty.h" #include // static map members of EnumerationProperty. These Maps point to per-classname-maps of ID <-> String. Accessed by GetEnumIds() and GetEnumString(). mitk::EnumerationProperty::IdMapForClassNameContainerType mitk::EnumerationProperty::s_IdMapForClassName; mitk::EnumerationProperty::StringMapForClassNameContainerType mitk::EnumerationProperty::s_StringMapForClassName; mitk::EnumerationProperty::EnumerationProperty() { m_CurrentValue = 0; } +mitk::EnumerationProperty::EnumerationProperty(const EnumerationProperty& other) + : BaseProperty(other) + , m_CurrentValue(other.m_CurrentValue) +{ +} bool mitk::EnumerationProperty::AddEnum( const std::string& name, const IdType& id ) { if ( ( ! IsValidEnumerationValue( name ) ) && ( ! IsValidEnumerationValue( id ) ) ) { GetEnumIds().insert( std::make_pair( id, name ) ); GetEnumStrings().insert( std::make_pair( name, id ) ); return true; } else { return false; } } bool mitk::EnumerationProperty::SetValue( const std::string& name ) { if ( IsValidEnumerationValue( name ) ) { m_CurrentValue = GetEnumId( name ); Modified(); return true; } else { return false; } } bool mitk::EnumerationProperty::SetValue( const IdType& id ) { if ( IsValidEnumerationValue( id ) ) { m_CurrentValue = id; Modified(); return true; } else { return false; } } mitk::EnumerationProperty::IdType mitk::EnumerationProperty::GetValueAsId() const { return m_CurrentValue; } std::string mitk::EnumerationProperty::GetValueAsString() const { return GetEnumString( m_CurrentValue ); } void mitk::EnumerationProperty::Clear() { GetEnumIds().clear(); GetEnumStrings().clear(); m_CurrentValue = 0; } mitk::EnumerationProperty::EnumIdsContainerType::size_type mitk::EnumerationProperty::Size() const { return GetEnumIds().size(); } mitk::EnumerationProperty::EnumConstIterator mitk::EnumerationProperty::Begin() const { return GetEnumIds().begin(); } mitk::EnumerationProperty::EnumConstIterator mitk::EnumerationProperty::End() const { return GetEnumIds().end(); } std::string mitk::EnumerationProperty::GetEnumString( const IdType& id ) const { if ( IsValidEnumerationValue( id ) ) { return GetEnumIds().find( id )->second; } else { return "invalid enum id or enums empty"; } } mitk::EnumerationProperty::IdType mitk::EnumerationProperty::GetEnumId( const std::string& name ) const { if ( IsValidEnumerationValue( name ) ) { return GetEnumStrings().find( name )->second; } else { return 0; } } bool mitk::EnumerationProperty::IsEqual( const BaseProperty& property ) const { const Self& other = static_cast(property); return this->Size() == other.Size() && this->GetValueAsId() == other.GetValueAsId() && std::equal( this->Begin(), this->End(), other.Begin() ); } bool mitk::EnumerationProperty::Assign( const BaseProperty& property ) { const Self& other = static_cast(property); this->GetEnumIds() = other.GetEnumIds(); this->GetEnumStrings() = other.GetEnumStrings(); this->m_CurrentValue = other.m_CurrentValue; this->Size() == other.Size() && this->GetValueAsId() == other.GetValueAsId() && std::equal( this->Begin(), this->End(), other.Begin() ); return true; } bool mitk::EnumerationProperty::IsValidEnumerationValue( const IdType& val ) const { return ( GetEnumIds().find( val ) != GetEnumIds().end() ); } bool mitk::EnumerationProperty::IsValidEnumerationValue( const std::string& val ) const { return ( GetEnumStrings().find( val ) != GetEnumStrings().end() ); } mitk::EnumerationProperty::EnumIdsContainerType& mitk::EnumerationProperty::GetEnumIds() { std::string className = this->GetNameOfClass(); // virtual! return s_IdMapForClassName[ className ]; } const mitk::EnumerationProperty::EnumIdsContainerType& mitk::EnumerationProperty::GetEnumIds() const { std::string className = this->GetNameOfClass(); // virtual! return s_IdMapForClassName[ className ]; } mitk::EnumerationProperty::EnumStringsContainerType& mitk::EnumerationProperty::GetEnumStrings() { std::string className = this->GetNameOfClass(); // virtual! return s_StringMapForClassName[ className ]; } const mitk::EnumerationProperty::EnumStringsContainerType& mitk::EnumerationProperty::GetEnumStrings() const { std::string className = this->GetNameOfClass(); // virtual! return s_StringMapForClassName[ className ]; } +mitk::EnumerationProperty::Pointer mitk::EnumerationProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::EnumerationProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkEnumerationProperty.h b/Core/Code/DataManagement/mitkEnumerationProperty.h index 3300983bf9..f5b1dfa974 100644 --- a/Core/Code/DataManagement/mitkEnumerationProperty.h +++ b/Core/Code/DataManagement/mitkEnumerationProperty.h @@ -1,225 +1,230 @@ /*=================================================================== 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_ENUMERATION_PROPERTY__H_ #define _MITK_ENUMERATION_PROPERTY__H_ #include "mitkBaseProperty.h" #include #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * This class may be used to store properties similar to enumeration values. * Each enumeration value is identified via a string representation and a * id. Note, that both string representation and id MUST be unique. This is checked * when inserting a new enumeration value. Please note that you have to add valid * enumeration values before you may use the Get/SetValue methods. * * To use the class enumeration property you have 2 choices: * * 1. Directly use the class and add your possible enumeration values via * AddEnum(name, id). NOte that the ids do not have to be in any order, they * just have to be unique. The current value is set via SetValue(...) and * retrieved via GetValueAsId() or GetValueAsString(). * 2. Create a subclass, which adds the possible enumeration values in its * constructor and maybe adds some additional convenience functions to * set/get the value. NOte that you should override AddEnum(...) as protected * so that the user may not add additional invalid enumeration values. * As example see mitk::VtkRepresentationProperty or mitk::VtkInterpolationProperty * * @ingroup DataManagement */ class MITK_CORE_EXPORT EnumerationProperty : public BaseProperty { public: mitkClassMacro( EnumerationProperty, BaseProperty ); itkNewMacro(EnumerationProperty); /** * Represents the unique id which is asigned to each enumeration value */ typedef unsigned int IdType; /** * Type used to store a mapping from enumeration id to enumeration string/ * description */ typedef std::map EnumIdsContainerType; /** * Type used to store a mapping from enumeration string/description to * enumeration id */ typedef std::map EnumStringsContainerType; /** * Type used for iterators over all defined enumeration values. */ typedef EnumIdsContainerType::const_iterator EnumConstIterator; + Pointer Clone() const; + /** * Adds an enumeration value into the enumeration. The name and id provided * must be unique. This is checked while adding the new enumeration value. * If it is not unique, false is returned. If addition was successful, true * is returned. * @param name the unique string representation of the enumeration value * @param id the unique integer representation of the enumeration value * @returns true, if the name/id combination was successfully added to the * enumeration values or true otherwise */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Sets the current value of the enumeration * @param name the string representation of the enumeration value to set * @returns true if the value was successfully set (i.e. it was valid), or * false, if the name provided is incalid. */ virtual bool SetValue( const std::string& name ); /** * Sets the current value of the enumeration * @param id the integer representation of the enumeration value to set * @returns true if the value was successfully set (i.e. it was valid), or * false, if the id provided is invalid. */ virtual bool SetValue( const IdType& id ); /** * Returns the id of the current enumeration value. If it was not yet set, * the return value is unspecified */ virtual IdType GetValueAsId() const; /** * Returns the string representation of the current enumeration value. If it * was not yet set, the return value is unspecified */ virtual std::string GetValueAsString() const; /** * Clears all possible enumeration values and the current enumeration value. */ virtual void Clear(); /** * Determines the number of enumeration values which have been added via * AddEnum(...). * @returns the number of enumeration values associated with this Enumeration * Property */ virtual EnumIdsContainerType::size_type Size() const; /** * Provides access to the set of known enumeration values. The string representation * may be accessed via iterator->second, the id may be access via iterator->first * @returns an iterator over all enumeration values. */ virtual EnumConstIterator Begin() const; /** * Specifies the end of the range of the known enumeration values. * @returns an iterator pointing past the last known element of the possible * enumeration values. */ virtual EnumConstIterator End() const; /** * Returns the string representation for the given id. * @param id the id for which the string representation should be determined * if id is invalid, the return value is unspecified. * @returns the string representation of the given enumeration value */ virtual std::string GetEnumString( const IdType& id ) const; /** * Returns the integer representation for the given string. * @param name the enumeration name for which the integer representation should be determined * if the name is invalid, the return value is unspecified. * @returns the integer representation of the given enumeration value */ virtual IdType GetEnumId( const std::string& name ) const; /** * Determines if a given integer representation of an enumeration value * is valid or not * @param val the integer value to check * @returns true if the given value is valid or false otherwise */ virtual bool IsValidEnumerationValue( const IdType& val ) const; /** * Determines if a given string representation of an enumeration value * is valid or not * @param val the string to check * @returns true if the given value is valid or false otherwise */ virtual bool IsValidEnumerationValue( const std::string& val ) const; const EnumIdsContainerType& GetEnumIds() const; const EnumStringsContainerType& GetEnumStrings() const; EnumIdsContainerType& GetEnumIds(); EnumStringsContainerType& GetEnumStrings(); using BaseProperty::operator=; protected: /** * Default constructor. The current value of the enumeration is undefined. */ EnumerationProperty(); + EnumerationProperty(const EnumerationProperty&); + virtual bool IsEqual( const BaseProperty& property ) const; virtual bool Assign( const BaseProperty& property ); private: // purposely not implemented - EnumerationProperty(const EnumerationProperty&); EnumerationProperty& operator=(const EnumerationProperty&); + itk::LightObject::Pointer InternalClone() const; + IdType m_CurrentValue; typedef std::map IdMapForClassNameContainerType; typedef std::map StringMapForClassNameContainerType; static IdMapForClassNameContainerType s_IdMapForClassName; static StringMapForClassNameContainerType s_StringMapForClassName; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace #endif diff --git a/Core/Code/DataManagement/mitkGenericProperty.h b/Core/Code/DataManagement/mitkGenericProperty.h index d1afe3b5fd..4f867e0880 100644 --- a/Core/Code/DataManagement/mitkGenericProperty.h +++ b/Core/Code/DataManagement/mitkGenericProperty.h @@ -1,127 +1,156 @@ /*=================================================================== 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 MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE #define MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE #include #include #include #include "mitkVector.h" #include #include "mitkBaseProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /*! @ brief Template class for generating properties for int, float, bool, etc. This class template can be instantiated for all classes/internal types that fulfills these requirements: - an operator<< so that the properties value can be put into a std::stringstream - an operator== so that two properties can be checked for equality Note: you must use the macro mitkSpecializeGenericProperty to provide specializations for concrete types (e.g. BoolProperty). Please see mitkProperties.h for examples. If you don't use the mitkSpecializeGenericProperty Macro, GetNameOfClass() returns a wrong name. */ template class MITK_EXPORT GenericProperty : public BaseProperty { public: mitkClassMacro(GenericProperty, BaseProperty); mitkNewMacro1Param(GenericProperty, T); typedef T ValueType; + Pointer Clone() const + { + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; + } + itkSetMacro(Value,T); itkGetConstMacro(Value,T); virtual std::string GetValueAsString() const { std::stringstream myStr; myStr << GetValue() ; return myStr.str(); } using BaseProperty::operator=; protected: GenericProperty() {} GenericProperty(T x) : m_Value(x) {} + GenericProperty(const GenericProperty& other) + : BaseProperty(other) + , m_Value(other.m_Value) + {} + T m_Value; private: // purposely not implemented - GenericProperty(const GenericProperty&); GenericProperty& operator=(const GenericProperty&); + virtual itk::LightObject::Pointer InternalClone() const + { + itk::LightObject::Pointer result(new Self(*this)); + return result; + } + virtual bool IsEqual(const BaseProperty& other) const { return (this->m_Value == static_cast(other).m_Value); } virtual bool Assign(const BaseProperty& other) { this->m_Value = static_cast(other).m_Value; return true; } }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk /** * Generates a specialized subclass of mitk::GenericProperty. * This way, GetNameOfClass() returns the value provided by PropertyName. * Please see mitkProperties.h for examples. * @param PropertyName the name of the subclass of GenericProperty * @param Type the value type of the GenericProperty * @param Export the export macro for DLL usage */ #define mitkDeclareGenericProperty(PropertyName,Type,Export) \ class Export PropertyName: public GenericProperty< Type > \ { \ public: \ mitkClassMacro(PropertyName, GenericProperty< Type >); \ itkNewMacro(PropertyName); \ mitkNewMacro1Param(PropertyName, Type); \ + Pointer Clone() const; \ using BaseProperty::operator=; \ protected: \ PropertyName(); \ + PropertyName(const PropertyName&); \ PropertyName(Type x); \ +private: \ + itk::LightObject::Pointer InternalClone() const; \ }; -#define mitkDefineGenericProperty(PropertyName,Type,DefaultValue) \ - mitk::PropertyName::PropertyName() : Superclass(DefaultValue) { } \ - mitk::PropertyName::PropertyName(Type x) : Superclass(x) {} +#define mitkDefineGenericProperty(PropertyName,Type,DefaultValue) \ + mitk::PropertyName::PropertyName() : Superclass(DefaultValue) { } \ + mitk::PropertyName::PropertyName(const PropertyName& other) : GenericProperty< Type >(other) {} \ + mitk::PropertyName::PropertyName(Type x) : Superclass(x) {} \ + mitk::PropertyName::Pointer mitk::PropertyName::Clone() const { \ + Pointer result = static_cast(this->InternalClone().GetPointer()); \ + return result; \ + } \ + itk::LightObject::Pointer mitk::PropertyName::InternalClone() const { \ + itk::LightObject::Pointer result(new Self(*this)); \ + return result; \ + } \ #endif /* MITKGENERICPROPERTY_H_HEADER_INCLUDED_C1061CEE */ diff --git a/Core/Code/DataManagement/mitkGroupTagProperty.cpp b/Core/Code/DataManagement/mitkGroupTagProperty.cpp index a6e6dd9f5a..6b78c083fb 100644 --- a/Core/Code/DataManagement/mitkGroupTagProperty.cpp +++ b/Core/Code/DataManagement/mitkGroupTagProperty.cpp @@ -1,35 +1,52 @@ /*=================================================================== 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 "mitkGroupTagProperty.h" mitk::GroupTagProperty::GroupTagProperty() : mitk::BaseProperty() { } +mitk::GroupTagProperty::GroupTagProperty(const GroupTagProperty& other) + : mitk::BaseProperty(other) +{ +} + bool mitk::GroupTagProperty::IsEqual(const BaseProperty& /*property*/) const { // if other property is also a GroupTagProperty, then it is equal to us, because tags have no value themselves return true; } bool mitk::GroupTagProperty::Assign(const BaseProperty& /*property*/) { return true; } + +mitk::GroupTagProperty::Pointer mitk::GroupTagProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::GroupTagProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkGroupTagProperty.h b/Core/Code/DataManagement/mitkGroupTagProperty.h index e97229e76b..2bb258642e 100644 --- a/Core/Code/DataManagement/mitkGroupTagProperty.h +++ b/Core/Code/DataManagement/mitkGroupTagProperty.h @@ -1,67 +1,71 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef GROUPTAGPROPERTY_H_HEADER_INCLUDED_C1F4DF54 #define GROUPTAGPROPERTY_H_HEADER_INCLUDED_C1F4DF54 #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /*! @brief Property class that has no value. @ingroup DataManagement The GroupTag property is used to tag a datatree node to show, that it is member of a group of datatree nodes. This can be used to build groups of datatreenodes without the need to contain them in a specific hiearchic order in the datatree */ class MITK_CORE_EXPORT GroupTagProperty : public BaseProperty { public: mitkClassMacro(GroupTagProperty, BaseProperty); itkNewMacro(GroupTagProperty); + Pointer Clone() const; + using BaseProperty::operator=; protected: GroupTagProperty(); + GroupTagProperty(const GroupTagProperty&); private: // purposely not implemented - GroupTagProperty(const GroupTagProperty&); GroupTagProperty& operator=(const GroupTagProperty&); + itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* GROUPTAGPROPERTY_H_HEADER_INCLUDED_C1F4DF54 */ diff --git a/Core/Code/DataManagement/mitkLevelWindowProperty.cpp b/Core/Code/DataManagement/mitkLevelWindowProperty.cpp index 74d686d470..63d687bc71 100755 --- a/Core/Code/DataManagement/mitkLevelWindowProperty.cpp +++ b/Core/Code/DataManagement/mitkLevelWindowProperty.cpp @@ -1,74 +1,92 @@ /*=================================================================== 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 "mitkLevelWindowProperty.h" mitk::LevelWindowProperty::LevelWindowProperty() { } +mitk::LevelWindowProperty::LevelWindowProperty(const mitk::LevelWindowProperty& other) + : BaseProperty(other) + , m_LevWin(other.m_LevWin) +{ +} + mitk::LevelWindowProperty::LevelWindowProperty(const mitk::LevelWindow &levWin) { SetLevelWindow(levWin); } mitk::LevelWindowProperty::~LevelWindowProperty() { } bool mitk::LevelWindowProperty::IsEqual(const BaseProperty& property) const { return this->m_LevWin == static_cast(property).m_LevWin; } bool mitk::LevelWindowProperty::Assign(const BaseProperty& property) { this->m_LevWin = static_cast(property).m_LevWin; return true; } const mitk::LevelWindow & mitk::LevelWindowProperty::GetLevelWindow() const { return m_LevWin; } const mitk::LevelWindow & mitk::LevelWindowProperty::GetValue() const { return GetLevelWindow(); } void mitk::LevelWindowProperty::SetLevelWindow(const mitk::LevelWindow &levWin) { if(m_LevWin != levWin) { m_LevWin = levWin; Modified(); } } void mitk::LevelWindowProperty::SetValue(const ValueType& levWin) { SetLevelWindow(levWin); } std::string mitk::LevelWindowProperty::GetValueAsString() const { std::stringstream myStr; myStr << "L:" << m_LevWin.GetLevel() << " W:" << m_LevWin.GetWindow(); return myStr.str(); } + +mitk::LevelWindowProperty::Pointer mitk::LevelWindowProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::LevelWindowProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkLevelWindowProperty.h b/Core/Code/DataManagement/mitkLevelWindowProperty.h index 28e5e97237..00d665e8b5 100755 --- a/Core/Code/DataManagement/mitkLevelWindowProperty.h +++ b/Core/Code/DataManagement/mitkLevelWindowProperty.h @@ -1,84 +1,89 @@ /*=================================================================== 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 MITKLEVELWINDOWPROPERTY_H_HEADER_INCLUDED_C10EEAA8 #define MITKLEVELWINDOWPROPERTY_H_HEADER_INCLUDED_C10EEAA8 #include "mitkBaseProperty.h" #include "mitkLevelWindow.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif //##Documentation //## @brief Property for level/window data //## //## @ingroup DataManagement class MITK_CORE_EXPORT LevelWindowProperty : public BaseProperty { protected: LevelWindow m_LevWin; LevelWindowProperty(); + LevelWindowProperty(const LevelWindowProperty& other); + LevelWindowProperty(const mitk::LevelWindow &levWin); public: mitkClassMacro(LevelWindowProperty, BaseProperty); itkNewMacro(LevelWindowProperty); mitkNewMacro1Param(LevelWindowProperty, const mitk::LevelWindow&); typedef LevelWindow ValueType; + Pointer Clone() const; + virtual ~LevelWindowProperty(); const mitk::LevelWindow & GetLevelWindow() const; const mitk::LevelWindow & GetValue() const; void SetLevelWindow(const LevelWindow &levWin); void SetValue(const ValueType& levWin); virtual std::string GetValueAsString() const; using BaseProperty::operator=; private: // purposely not implemented - LevelWindowProperty(const LevelWindowProperty&); LevelWindowProperty& operator=(const LevelWindowProperty&); + itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKLEVELWINDOWPROPERTY_H_HEADER_INCLUDED_C10EEAA8 */ diff --git a/Core/Code/DataManagement/mitkLookupTable.cpp b/Core/Code/DataManagement/mitkLookupTable.cpp index 48131e65ba..3e08d0f8ec 100644 --- a/Core/Code/DataManagement/mitkLookupTable.cpp +++ b/Core/Code/DataManagement/mitkLookupTable.cpp @@ -1,297 +1,315 @@ /*=================================================================== 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 "mitkLookupTable.h" #include #include #include mitk::LookupTable::LookupTable() { m_LookupTable = vtkLookupTable::New(); this->SetRequestedRegionToLargestPossibleRegion(); } +mitk::LookupTable::LookupTable(const LookupTable& other) + : itk::DataObject() + , m_LookupTable(vtkLookupTable::New()) +{ + m_LookupTable->DeepCopy(other.m_LookupTable); +} mitk::LookupTable::~LookupTable() { if ( m_LookupTable ) { m_LookupTable->Delete(); m_LookupTable = NULL; } } void mitk::LookupTable::SetVtkLookupTable( vtkLookupTable* lut ) { if(m_LookupTable == lut) { return; } if(m_LookupTable) { m_LookupTable->UnRegister(NULL); m_LookupTable = NULL; } if(lut) { lut->Register(NULL); } m_LookupTable = lut; this->Modified(); } void mitk::LookupTable::ChangeOpacityForAll( float opacity ) { int noValues = m_LookupTable->GetNumberOfTableValues (); vtkFloatingPointType rgba[ 4 ]; for ( int i = 0;i < noValues;i++ ) { m_LookupTable->GetTableValue ( i, rgba ); rgba[ 3 ] = opacity; m_LookupTable->SetTableValue ( i, rgba ); } this->Modified(); // need to call modiefied, since LookupTableProperty seems to be unchanged so no widget-updat is executed } void mitk::LookupTable::ChangeOpacity(int index, float opacity ) { int noValues = m_LookupTable->GetNumberOfTableValues (); if (index>noValues) { MITK_INFO << "could not change opacity. index exceed size of lut ... " << std::endl; return; } vtkFloatingPointType rgba[ 4 ]; m_LookupTable->GetTableValue ( index, rgba ); rgba[ 3 ] = opacity; m_LookupTable->SetTableValue ( index, rgba ); this->Modified(); // need to call modiefied, since LookupTableProperty seems to be unchanged so no widget-updat is executed } vtkLookupTable* mitk::LookupTable::GetVtkLookupTable() const { return m_LookupTable; }; mitk::LookupTable::RawLookupTableType * mitk::LookupTable::GetRawLookupTable() const { if (m_LookupTable==NULL) MITK_INFO << "uuups..." << std::endl; return m_LookupTable->GetPointer( 0 ); }; /*! * \brief equality operator inplementation */ bool mitk::LookupTable::operator==( const mitk::LookupTable& other ) const { if ( m_LookupTable == other.GetVtkLookupTable()) return true; vtkLookupTable* olut = other.GetVtkLookupTable(); if (olut == NULL) return false; bool equal = (m_LookupTable->GetNumberOfColors() == olut->GetNumberOfColors()) && (m_LookupTable->GetTableRange()[0] == olut->GetTableRange()[0]) && (m_LookupTable->GetTableRange()[1] == olut->GetTableRange()[1]) && (m_LookupTable->GetHueRange()[0] == olut->GetHueRange()[0]) && (m_LookupTable->GetHueRange()[1] == olut->GetHueRange()[1]) && (m_LookupTable->GetSaturationRange()[0] == olut->GetSaturationRange()[0]) && (m_LookupTable->GetSaturationRange()[1] == olut->GetSaturationRange()[1]) && (m_LookupTable->GetValueRange()[0] == olut->GetValueRange()[0]) && (m_LookupTable->GetValueRange()[1] == olut->GetValueRange()[1]) && (m_LookupTable->GetAlphaRange()[0] == olut->GetAlphaRange()[0]) && (m_LookupTable->GetAlphaRange()[1] == olut->GetAlphaRange()[1]) && (m_LookupTable->GetRamp() == olut->GetRamp()) && (m_LookupTable->GetScale() == olut->GetScale()) && (m_LookupTable->GetAlpha() == olut->GetAlpha()) && (m_LookupTable->GetTable()->GetNumberOfTuples() == olut->GetTable()->GetNumberOfTuples()); if (equal == false) return false; //for (vtkIdType i=0; i < m_LookupTable->GetTable()->GetNumberOfTuples(); i++) //{ // if (m_LookupTable->GetTable()->GetTuple(i) != olut->GetTable()->GetTuple(i)) // return false; //} for (vtkIdType i=0; i < m_LookupTable->GetNumberOfTableValues(); i++) { //double v0_1 = m_LookupTable->GetTableValue(i)[0]; double v0_2 = olut->GetTableValue(i)[0]; //double v1_1 = m_LookupTable->GetTableValue(i)[1]; double v1_2 = olut->GetTableValue(i)[1]; //double v2_1 = m_LookupTable->GetTableValue(i)[2]; double v2_2 = olut->GetTableValue(i)[2]; //double v3_1 = m_LookupTable->GetTableValue(i)[3]; double v3_2 = olut->GetTableValue(i)[3]; bool tvequal = (m_LookupTable->GetTableValue(i)[0] == olut->GetTableValue(i)[0]) && (m_LookupTable->GetTableValue(i)[1] == olut->GetTableValue(i)[1]) && (m_LookupTable->GetTableValue(i)[2] == olut->GetTableValue(i)[2]) && (m_LookupTable->GetTableValue(i)[3] == olut->GetTableValue(i)[3]); if (tvequal == false) return false; } return true; } /*! * \brief un-equality operator implementation */ bool mitk::LookupTable::operator!=( const mitk::LookupTable& other ) const { return !(*this == other); } /*! * \brief assignment operator implementation */ mitk::LookupTable& mitk::LookupTable::operator=( const mitk::LookupTable& LookupTable ) { if ( this == &LookupTable ) { return * this; } else { m_LookupTable = LookupTable.GetVtkLookupTable(); return *this; } } void mitk::LookupTable::UpdateOutputInformation( ) { if ( this->GetSource( ) ) { this->GetSource( ) ->UpdateOutputInformation( ); } } void mitk::LookupTable::SetRequestedRegionToLargestPossibleRegion( ) {} bool mitk::LookupTable::RequestedRegionIsOutsideOfTheBufferedRegion( ) { return false; } bool mitk::LookupTable::VerifyRequestedRegion( ) { //normally we should check if the requested region lies within the //largest possible region. Since for lookup-tables we assume, that the //requested region is always the largest possible region, we can always //return true! return true; } void mitk::LookupTable::SetRequestedRegion( itk::DataObject *) { //not implemented, since we always want to have the RequestedRegion //to be set to LargestPossibleRegion } void mitk::LookupTable::CreateColorTransferFunction(vtkColorTransferFunction*& colorFunction) { if(colorFunction==NULL) colorFunction = vtkColorTransferFunction::New(); mitk::LookupTable::RawLookupTableType *rgba = GetRawLookupTable(); int i, num_of_values=m_LookupTable->GetNumberOfTableValues(); vtkFloatingPointType *cols; vtkFloatingPointType *colsHead; colsHead=cols=(vtkFloatingPointType *)malloc(sizeof(vtkFloatingPointType)*num_of_values*3); for(i=0;iBuildFunctionFromTable(m_LookupTable->GetTableRange()[0], m_LookupTable->GetTableRange()[1], num_of_values-1, colsHead); free(colsHead); } void mitk::LookupTable::CreateOpacityTransferFunction(vtkPiecewiseFunction*& opacityFunction) { if(opacityFunction==NULL) opacityFunction = vtkPiecewiseFunction::New(); mitk::LookupTable::RawLookupTableType *rgba = GetRawLookupTable(); int i, num_of_values=m_LookupTable->GetNumberOfTableValues(); vtkFloatingPointType *alphas; vtkFloatingPointType *alphasHead; alphasHead=alphas=(vtkFloatingPointType*)malloc(sizeof(vtkFloatingPointType)*num_of_values); rgba+=3; for(i=0;iBuildFunctionFromTable(m_LookupTable->GetTableRange()[0], m_LookupTable->GetTableRange()[1], num_of_values-1, alphasHead); free(alphasHead); } void mitk::LookupTable::CreateGradientTransferFunction(vtkPiecewiseFunction*& gradientFunction) { if(gradientFunction==NULL) gradientFunction = vtkPiecewiseFunction::New(); mitk::LookupTable::RawLookupTableType *rgba = GetRawLookupTable(); int i, num_of_values=m_LookupTable->GetNumberOfTableValues(); vtkFloatingPointType *alphas; vtkFloatingPointType *alphasHead; alphasHead=alphas=(vtkFloatingPointType*)malloc(sizeof(vtkFloatingPointType)*num_of_values); rgba+=3; for(i=0;iBuildFunctionFromTable(m_LookupTable->GetTableRange()[0], m_LookupTable->GetTableRange()[1], num_of_values-1, alphasHead); free(alphasHead); } void mitk::LookupTable::PrintSelf(std::ostream &os, itk::Indent indent) const { os << indent; m_LookupTable->PrintHeader(os, vtkIndent()); } + +mitk::LookupTable::Pointer mitk::LookupTable::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::LookupTable::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkLookupTable.h b/Core/Code/DataManagement/mitkLookupTable.h index 02124bd09d..d489310eb6 100644 --- a/Core/Code/DataManagement/mitkLookupTable.h +++ b/Core/Code/DataManagement/mitkLookupTable.h @@ -1,134 +1,139 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKLookupTable_H_HEADER_INCLUDED_C1EBD53D #define MITKLookupTable_H_HEADER_INCLUDED_C1EBD53D #include #include #include "vtkLookupTable.h" #include #include class vtkColorTransferFunction; class vtkPiecewiseFunction; namespace mitk { //## //##Documentation //## @brief LookupTable containing a vtkLookupTable //## @ingroup Data //## class MITK_CORE_EXPORT LookupTable : public itk::DataObject { public: /** *@brief Some convenient typedefs. */ typedef unsigned char RawLookupTableType; mitkClassMacro( LookupTable, itk::DataObject ); itkNewMacro( Self ); + Pointer Clone() const; + /** * @returns the associated vtkLookupTable */ virtual vtkLookupTable* GetVtkLookupTable() const; virtual RawLookupTableType * GetRawLookupTable() const; virtual void SetVtkLookupTable( vtkLookupTable* lut ); virtual void ChangeOpacityForAll( float opacity ); virtual void ChangeOpacity(int index, float opacity ); /*! * \brief equality operator implementation */ virtual bool operator==( const mitk::LookupTable& LookupTable ) const; /*! * \brief non equality operator implementation */ virtual bool operator!=( const LookupTable& LookupTable ) const; /*! * \brief implementation necessary because operator made * private in itk::Object */ virtual LookupTable& operator=( const LookupTable& LookupTable ); /** * Updates the output information of the current object by calling * updateOutputInformation of the data objects source object. */ virtual void UpdateOutputInformation( ); /** * Sets the requested Region to the largest possible region. * This method is not implemented, since this is the default * behaviour of the itk pipeline and we do not support the * requested-region mechanism for lookup-tables */ virtual void SetRequestedRegionToLargestPossibleRegion( ); /** * Checks, if the requested region lies outside of the buffered region by * calling verifyRequestedRegion(). */ virtual bool RequestedRegionIsOutsideOfTheBufferedRegion( ); /** * Checks if the requested region is completely contained in * the buffered region. Since we always want to process the lookup * table as a whole, this method always returns true */ virtual bool VerifyRequestedRegion( ); /** * This method has no effect for lookup tables, since we do * not support the region-mechanism */ virtual void SetRequestedRegion( itk::DataObject *data ); LookupTable(); virtual ~LookupTable(); void CreateColorTransferFunction(vtkColorTransferFunction*& colorFunction); void CreateOpacityTransferFunction(vtkPiecewiseFunction*& opacityFunction); void CreateGradientTransferFunction(vtkPiecewiseFunction*& gradientFunction); protected: void PrintSelf(std::ostream &os, itk::Indent indent) const; + LookupTable(const LookupTable& other); + vtkLookupTable* m_LookupTable; private: + virtual itk::LightObject::Pointer InternalClone() const; }; } // namespace mitk #endif /* LookupTable_H_HEADER_INCLUDED_C1EBD53D */ diff --git a/Core/Code/DataManagement/mitkModalityProperty.cpp b/Core/Code/DataManagement/mitkModalityProperty.cpp index a7387d5992..b5047d0027 100644 --- a/Core/Code/DataManagement/mitkModalityProperty.cpp +++ b/Core/Code/DataManagement/mitkModalityProperty.cpp @@ -1,70 +1,80 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkModalityProperty.h" mitk::ModalityProperty::ModalityProperty() { AddEnumerationTypes(); } mitk::ModalityProperty::ModalityProperty( const IdType& value ) { AddEnumerationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ) ; } else { SetValue( 0 ); } } mitk::ModalityProperty::ModalityProperty( const std::string& value ) { AddEnumerationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( "undefined" ); } } mitk::ModalityProperty::~ModalityProperty() { } void mitk::ModalityProperty::AddEnumerationTypes() { IdType newId = static_cast(EnumerationProperty::Size()); AddEnum( "undefined", newId++ ); AddEnum( "CR", newId++ ); // computer radiography AddEnum( "CT", newId++ ); // computed tomography AddEnum( "MR", newId++ ); // magnetic resonance AddEnum( "NM", newId++ ); // nuclear medicine AddEnum( "US", newId++ ); // ultrasound AddEnum( "Color Doppler", newId++ ); // ultrasound AddEnum( "Power Doppler", newId++ ); // ultrasound } +mitk::ModalityProperty::Pointer mitk::ModalityProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} +itk::LightObject::Pointer mitk::ModalityProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkModalityProperty.h b/Core/Code/DataManagement/mitkModalityProperty.h index b2d4f2cda3..df2d5f01b4 100644 --- a/Core/Code/DataManagement/mitkModalityProperty.h +++ b/Core/Code/DataManagement/mitkModalityProperty.h @@ -1,71 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkModalityProperty_h_Included #define mitkModalityProperty_h_Included #include #include "mitkEnumerationProperty.h" #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** \brief Enumerates all known modalities \ingroup DataManagement */ class MITK_CORE_EXPORT ModalityProperty : public EnumerationProperty { public: mitkClassMacro(ModalityProperty, EnumerationProperty); itkNewMacro(ModalityProperty); mitkNewMacro1Param(ModalityProperty, const IdType&); mitkNewMacro1Param(ModalityProperty, const std::string&); + Pointer Clone() const; + using BaseProperty::operator=; protected: ModalityProperty(); ModalityProperty( const IdType& value ); ModalityProperty( const std::string& value ); virtual ~ModalityProperty(); virtual void AddEnumerationTypes(); private: // purposely not implemented - ModalityProperty(const ModalityProperty&); const ModalityProperty& operator=(const ModalityProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace #endif diff --git a/Core/Code/DataManagement/mitkPlaneOrientationProperty.cpp b/Core/Code/DataManagement/mitkPlaneOrientationProperty.cpp index dd5b1436c6..80f39ecec6 100644 --- a/Core/Code/DataManagement/mitkPlaneOrientationProperty.cpp +++ b/Core/Code/DataManagement/mitkPlaneOrientationProperty.cpp @@ -1,96 +1,107 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPlaneOrientationProperty.h" namespace mitk { PlaneOrientationProperty::PlaneOrientationProperty( ) { this->AddDecorationTypes(); this->SetValue( static_cast( PLANE_DECORATION_NONE ) ); } PlaneOrientationProperty::PlaneOrientationProperty( const IdType& value ) { this->AddDecorationTypes(); if ( this->IsValidEnumerationValue( value ) ) { this->SetValue( value ) ; } else { this->SetValue( static_cast( PLANE_DECORATION_NONE ) ); } } PlaneOrientationProperty::PlaneOrientationProperty( const std::string& value ) { this->AddDecorationTypes(); if ( this->IsValidEnumerationValue( value ) ) { this->SetValue( value ); } else { this->SetValue( static_cast( PLANE_DECORATION_NONE ) ); } } int PlaneOrientationProperty::GetPlaneDecoration() { return static_cast( this->GetValueAsId() ); } void PlaneOrientationProperty::SetPlaneDecorationToNone() { this->SetValue( static_cast( PLANE_DECORATION_NONE ) ); } void PlaneOrientationProperty::SetPlaneDecorationToPositiveOrientation() { this->SetValue( static_cast( PLANE_DECORATION_POSITIVE_ORIENTATION ) ); } void PlaneOrientationProperty::SetPlaneDecorationToNegativeOrientation() { this->SetValue( static_cast( PLANE_DECORATION_NEGATIVE_ORIENTATION ) ); } void PlaneOrientationProperty::AddDecorationTypes() { this->AddEnum( "No plane decoration", static_cast( PLANE_DECORATION_NONE ) ); this->AddEnum( "Arrows in positive direction", static_cast( PLANE_DECORATION_POSITIVE_ORIENTATION ) ); this->AddEnum( "Arrows in negative direction", static_cast( PLANE_DECORATION_NEGATIVE_ORIENTATION ) ); } bool PlaneOrientationProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } +PlaneOrientationProperty::Pointer PlaneOrientationProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer PlaneOrientationProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} } // namespace diff --git a/Core/Code/DataManagement/mitkPlaneOrientationProperty.h b/Core/Code/DataManagement/mitkPlaneOrientationProperty.h index 8a9453a63f..3c13cc4782 100644 --- a/Core/Code/DataManagement/mitkPlaneOrientationProperty.h +++ b/Core/Code/DataManagement/mitkPlaneOrientationProperty.h @@ -1,129 +1,132 @@ /*=================================================================== 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_PLANE_DECORATION_PROPERTY__H #define MITK_PLANE_DECORATION_PROPERTY__H #include "mitkEnumerationProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Property which controls whether 2D line representation of a PlaneGeometry * should have small arrows at both ends to indicate the orientation of * the plane, and whether the arrows should be oriented in the direction of * the plane's normal or against it. * * Valid values of the enumeration property are * - PLANE_DECORATION_NONE (no arrows) * - PLANE_DECORATION_POSITIVE_ORIENTATION (arrows pointing upwards) * - PLANE_DECORATION_NEGATIVE_ORIENTATION (arrows pointing downwards) * * See also mitk::Geometry2DDataMapper2D::DrawOrientationArrow() */ class MITK_CORE_EXPORT PlaneOrientationProperty : public EnumerationProperty { public: mitkClassMacro( PlaneOrientationProperty, EnumerationProperty ); itkNewMacro(PlaneOrientationProperty); mitkNewMacro1Param(PlaneOrientationProperty, const IdType&); mitkNewMacro1Param(PlaneOrientationProperty, const std::string&); + Pointer Clone() const; + enum { PLANE_DECORATION_NONE, PLANE_DECORATION_POSITIVE_ORIENTATION, PLANE_DECORATION_NEGATIVE_ORIENTATION }; /** * Returns the state of plane decoration. */ virtual int GetPlaneDecoration(); /** * Sets the decoration type to no decoration. */ virtual void SetPlaneDecorationToNone(); /** * Sets the decoration type to arrows in positive plane direction. */ virtual void SetPlaneDecorationToPositiveOrientation(); /** * Sets the decoration type to arrows in negative plane direction. */ virtual void SetPlaneDecorationToNegativeOrientation(); using BaseProperty::operator=; protected: /** * Constructor. Sets the decoration type to none. */ PlaneOrientationProperty( ); /** * Constructor. Sets the decoration type to the given value. If it is not * valid, the interpolation is set to none */ PlaneOrientationProperty( const IdType &value ); /** * Constructor. Sets the decoration type to the given value. If it is not * valid, the representation is set to none */ PlaneOrientationProperty( const std::string &value ); /** * this function is overridden as protected, so that the user may not add * additional invalid types. */ virtual bool AddEnum( const std::string &name, const IdType &id ); /** * Adds the standard enumeration types with corresponding strings. */ virtual void AddDecorationTypes(); private: // purposely not implemented - PlaneOrientationProperty(const PlaneOrientationProperty&); PlaneOrientationProperty& operator=(const PlaneOrientationProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkPropertyList.cpp b/Core/Code/DataManagement/mitkPropertyList.cpp index b980cdaced..0bad64951d 100644 --- a/Core/Code/DataManagement/mitkPropertyList.cpp +++ b/Core/Code/DataManagement/mitkPropertyList.cpp @@ -1,280 +1,291 @@ /*=================================================================== 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 "mitkPropertyList.h" #include "mitkProperties.h" #include "mitkStringProperty.h" #include "mitkVector.h" mitk::BaseProperty* mitk::PropertyList::GetProperty(const std::string& propertyKey) const { PropertyMap::const_iterator it; it=m_Properties.find( propertyKey ); if(it!=m_Properties.end()) return it->second; else return NULL; } void mitk::PropertyList::SetProperty(const std::string& propertyKey, BaseProperty* property) { if (!property) return; //make sure that BaseProperty*, which may have just been created and never been //assigned to a SmartPointer, is registered/unregistered properly. If we do not //do that, it will a) not deleted in case it is identical to the old one or //b) possibly deleted when temporarily added to a smartpointer somewhere below. BaseProperty::Pointer tmpSmartPointerToProperty = property; PropertyMap::iterator it( m_Properties.find( propertyKey ) ); // Is a property with key @a propertyKey contained in the list? if( it != m_Properties.end() ) { // yes //is the property contained in the list identical to the new one? if( it->second->operator==(*property) ) { // yes? do nothing and return. return; } if (it->second->AssignProperty(*property)) { // The assignment was successfull this->Modified(); } else { MITK_ERROR << "In " __FILE__ ", l." << __LINE__ << ": Trying to set existing property " << it->first << " of type " << it->second->GetNameOfClass() << " to a property with different type " << property->GetNameOfClass() << "." << " Use ReplaceProperty() instead." << std::endl; } return; } //no? add it. PropertyMapElementType newProp; newProp.first = propertyKey; newProp.second = property; m_Properties.insert ( newProp ); this->Modified(); } void mitk::PropertyList::ReplaceProperty(const std::string& propertyKey, BaseProperty* property) { if (!property) return; PropertyMap::iterator it( m_Properties.find( propertyKey ) ); // Is a property with key @a propertyKey contained in the list? if( it != m_Properties.end() ) { it->second=NULL; m_Properties.erase(it); } //no? add/replace it. PropertyMapElementType newProp; newProp.first = propertyKey; newProp.second = property; m_Properties.insert ( newProp ); Modified(); } mitk::PropertyList::PropertyList() { } +mitk::PropertyList::PropertyList(const mitk::PropertyList& other) + : itk::Object() +{ + for (PropertyMap::const_iterator i = other.m_Properties.begin(); + i != other.m_Properties.end(); ++i) + { + m_Properties.insert(std::make_pair(i->first, i->second->Clone())); + } +} + mitk::PropertyList::~PropertyList() { Clear(); } /** * Consider the list as changed when any of the properties has changed recently. */ unsigned long mitk::PropertyList::GetMTime() const { for ( PropertyMap::const_iterator it = m_Properties.begin() ; it != m_Properties.end(); ++it ) { if( it->second.IsNull() ) { itkWarningMacro(<< "Property '" << it->first <<"' contains nothing (NULL)."); continue; } if( Superclass::GetMTime() < it->second->GetMTime() ) { Modified(); break; } } return Superclass::GetMTime(); } bool mitk::PropertyList::DeleteProperty(const std::string& propertyKey) { PropertyMap::iterator it; it=m_Properties.find( propertyKey ); if(it!=m_Properties.end()) { it->second=NULL; m_Properties.erase(it); Modified(); return true; } return false; } -mitk::PropertyList::Pointer mitk::PropertyList::Clone() +mitk::PropertyList::Pointer mitk::PropertyList::Clone() const { - mitk::PropertyList::Pointer newPropertyList = PropertyList::New(); - - // copy the map - newPropertyList->m_Properties = m_Properties; - - return newPropertyList.GetPointer(); + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; } void mitk::PropertyList::Clear() { PropertyMap::iterator it = m_Properties.begin(), end = m_Properties.end(); while(it!=end) { it->second = NULL; ++it; } m_Properties.clear(); } +itk::LightObject::Pointer mitk::PropertyList::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} void mitk::PropertyList::ConcatenatePropertyList(PropertyList *pList, bool replace) { if (pList) { const PropertyMap* propertyMap = pList->GetMap(); for ( PropertyMap::const_iterator iter = propertyMap->begin(); // m_PropertyList is created in the constructor, so we don't check it here iter != propertyMap->end(); ++iter ) { const std::string key = iter->first; BaseProperty* value = iter->second; if (replace) { ReplaceProperty( key.c_str(), value ); } else { SetProperty( key.c_str(), value ); } } } } bool mitk::PropertyList::GetBoolProperty(const char* propertyKey, bool& boolValue) const { BoolProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { boolValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, boolValue); } bool mitk::PropertyList::GetIntProperty(const char* propertyKey, int &intValue) const { IntProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { intValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, intValue); } bool mitk::PropertyList::GetFloatProperty(const char* propertyKey, float &floatValue) const { FloatProperty *gp = dynamic_cast( GetProperty(propertyKey) ); if ( gp != NULL ) { floatValue = gp->GetValue(); return true; } return false; // Templated Method does not work on Macs //return GetPropertyValue(propertyKey, floatValue); } bool mitk::PropertyList::GetStringProperty(const char* propertyKey, std::string& stringValue) const { StringProperty* sp= dynamic_cast(GetProperty(propertyKey)); if ( sp != NULL ) { stringValue = sp->GetValue(); return true; } return false; } void mitk::PropertyList::SetIntProperty(const char* propertyKey, int intValue) { SetProperty(propertyKey, mitk::IntProperty::New(intValue)); } void mitk::PropertyList::SetBoolProperty( const char* propertyKey, bool boolValue) { SetProperty(propertyKey, mitk::BoolProperty::New(boolValue)); } void mitk::PropertyList::SetFloatProperty( const char* propertyKey, float floatValue) { SetProperty(propertyKey, mitk::FloatProperty::New(floatValue)); } void mitk::PropertyList::SetStringProperty( const char* propertyKey, const char* stringValue) { SetProperty(propertyKey, mitk::StringProperty::New(stringValue)); } diff --git a/Core/Code/DataManagement/mitkPropertyList.h b/Core/Code/DataManagement/mitkPropertyList.h index add2dd6763..40a2a1029f 100644 --- a/Core/Code/DataManagement/mitkPropertyList.h +++ b/Core/Code/DataManagement/mitkPropertyList.h @@ -1,207 +1,212 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef PROPERTYLIST_H_HEADER_INCLUDED_C1C77D8D #define PROPERTYLIST_H_HEADER_INCLUDED_C1C77D8D #include #include "mitkBaseProperty.h" #include "mitkGenericProperty.h" #include "mitkUIDGenerator.h" #include #include #include namespace mitk { class XMLWriter; /** * @brief Key-value list holding instances of BaseProperty * * This list is meant to hold an arbitrary list of "properties", * which should describe the object associated with this list. * * Usually you will use PropertyList as part of a DataNode * object - in this context the properties describe the data object * held by the DataNode (e.g. whether the object is rendered at * all, which color is used for rendering, what name should be * displayed for the object, etc.) * * The values in the list are not fixed, you may introduce any kind * of property that seems useful - all you have to do is inherit * from BaseProperty. * * The list is organized as a key-value pairs, i.e. * * \li "name" : pointer to a StringProperty * \li "visible" : pointer to a BoolProperty * \li "color" : pointer to a ColorProperty * \li "volume" : pointer to a FloatProperty * * Please see the documentation of SetProperty and ReplaceProperty for two * quite different semantics. Normally SetProperty is what you want - this * method will try to change the value of an existing property and will * not allow you to replace e.g. a ColorProperty with an IntProperty. * * @ingroup DataManagement */ class MITK_CORE_EXPORT PropertyList : public itk::Object { public: - mitkClassMacro(PropertyList, itk::Object); + mitkClassMacro(PropertyList, itk::Object) /** * Method for creation through the object factory. */ - itkNewMacro(Self); + itkNewMacro(Self) + + Pointer Clone() const; /** * Map structure to hold the properties: the map key is a string, * the value consists of the actual property object (BaseProperty). */ typedef std::map< std::string, BaseProperty::Pointer> PropertyMap; typedef std::pair< std::string, BaseProperty::Pointer> PropertyMapElementType; /** * @brief Get a property by its name. */ mitk::BaseProperty* GetProperty(const std::string& propertyKey) const; /** * @brief Set a property in the list/map by value. * * The actual OBJECT holding the value of the property is not replaced, but its value * is modified to match that of @a property. To really replace the object holding the * property - which would make sense if you want to change the type (bool, string) of the property * - call ReplaceProperty. */ void SetProperty(const std::string& propertyKey, BaseProperty* property); /** * @brief Set a property object in the list/map by reference. * * The actual OBJECT holding the value of the property is replaced by this function. * This is useful if you want to change the type of the property, like from BoolProperty to StringProperty. * Another use is to share one and the same property object among several ProperyList/DataNode objects, which * makes them appear synchronized. */ void ReplaceProperty(const std::string& propertyKey, BaseProperty* property); /** * @brief Set a property object in the list/map by reference. */ void ConcatenatePropertyList(PropertyList *pList, bool replace = false); //##Documentation //## @brief Convenience access method for GenericProperty properties //## (T being the type of the second parameter) //## @return @a true property was found template bool GetPropertyValue(const char* propertyKey, T & value) const { GenericProperty* gp= dynamic_cast*>(GetProperty(propertyKey)); if ( gp != NULL ) { value = gp->GetValue(); return true; } return false; } /** * @brief Convenience method to access the value of a BoolProperty */ bool GetBoolProperty(const char* propertyKey, bool& boolValue) const; /** * @brief Convenience method to set the value of a BoolProperty */ void SetBoolProperty( const char* propertyKey, bool boolValue); /** * @brief Convenience method to access the value of an IntProperty */ bool GetIntProperty(const char* propertyKey, int &intValue) const; /** * @brief Convenience method to set the value of an IntProperty */ void SetIntProperty(const char* propertyKey, int intValue); /** * @brief Convenience method to access the value of a FloatProperty */ bool GetFloatProperty(const char* propertyKey, float &floatValue) const; /** * @brief Convenience method to set the value of a FloatProperty */ void SetFloatProperty( const char* propertyKey, float floatValue); /** * @brief Convenience method to access the value of a StringProperty */ bool GetStringProperty(const char* propertyKey, std::string& stringValue) const; /** * @brief Convenience method to set the value of a StringProperty */ void SetStringProperty( const char* propertyKey, const char* stringValue); /** * @brief Get the timestamp of the last change of the map or the last change of one of * the properties store in the list (whichever is later). */ virtual unsigned long GetMTime() const; /** * @brief Remove a property from the list/map. */ bool DeleteProperty(const std::string& propertyKey); const PropertyMap* GetMap() const { return &m_Properties; } bool IsEmpty() const { return m_Properties.empty(); } - virtual Pointer Clone(); - virtual void Clear(); protected: PropertyList(); + PropertyList(const PropertyList& other); virtual ~PropertyList(); /** * @brief Map of properties. */ PropertyMap m_Properties; + private: + + virtual itk::LightObject::Pointer InternalClone() const; + }; } // namespace mitk #endif /* PROPERTYLIST_H_HEADER_INCLUDED_C1C77D8D */ diff --git a/Core/Code/DataManagement/mitkRenderingModeProperty.cpp b/Core/Code/DataManagement/mitkRenderingModeProperty.cpp index 6766fedde9..99377a60d0 100644 --- a/Core/Code/DataManagement/mitkRenderingModeProperty.cpp +++ b/Core/Code/DataManagement/mitkRenderingModeProperty.cpp @@ -1,65 +1,77 @@ /*=================================================================== 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 "mitkRenderingModeProperty.h" mitk::RenderingModeProperty::RenderingModeProperty( ) { this->AddRenderingModes(); this->SetValue( LEVELWINDOW_COLOR ); } mitk::RenderingModeProperty::RenderingModeProperty( const IdType& value ) { this->AddRenderingModes(); if ( IsValidEnumerationValue( value ) ) { this->SetValue( value ) ; } else MITK_WARN << "Warning: invalid image rendering mode"; } mitk::RenderingModeProperty::RenderingModeProperty( const std::string& value ) { this->AddRenderingModes(); if ( IsValidEnumerationValue( value ) ) { this->SetValue( value ); } else MITK_WARN << "Invalid image rendering mode"; } int mitk::RenderingModeProperty::GetRenderingMode() { return static_cast( this->GetValueAsId() ); } void mitk::RenderingModeProperty::AddRenderingModes() { AddEnum( "LevelWindow_Color", LEVELWINDOW_COLOR ); AddEnum( "LookupTable_LevelWindow_Color", LOOKUPTABLE_LEVELWINDOW_COLOR ); AddEnum( "ColorTransferFunction_LevelWindow_Color", COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR ); AddEnum( "LookupTable_Color", LOOKUPTABLE_COLOR ); AddEnum( "ColorTransferFunction_Color", COLORTRANSFERFUNCTION_COLOR ); } bool mitk::RenderingModeProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } + +mitk::RenderingModeProperty::Pointer mitk::RenderingModeProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::RenderingModeProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkRenderingModeProperty.h b/Core/Code/DataManagement/mitkRenderingModeProperty.h index ac11f0ab16..50f7dda154 100644 --- a/Core/Code/DataManagement/mitkRenderingModeProperty.h +++ b/Core/Code/DataManagement/mitkRenderingModeProperty.h @@ -1,114 +1,117 @@ /*=================================================================== 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_RENDERING_MODE_PROPERTY__H_ #define _MITK_RENDERING_MODE_PROPERTY__H_ #include "mitkEnumerationProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Encapsulates the enumeration for rendering modes. Valid values are: * \li LEVELWINDOW_COLOR: Level window and color will be applied to the image. * \li LOOKUPTABLE_LEVELWINDOW_COLOR: A lookup table, level window and color will be applied to the image. * \li COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR: A colortransferfunction, level window and color will be applied to the image. * \li LOOKUPTABLE_COLOR: A lookup table and color will be applied to the image. * \li COLORTRANSFERFUNCTION_COLOR: A colortransferfunction and color will be applied to the image. * * The order is given by the names (e.g. LOOKUPTABLE_COLOR applies first a lookup table and next a color). * Currently, there is no GUI (in mitkWorkbench) support for controlling lookup tables or transfer functions. * This has to be done by the programmer. Color and level window are controled by color widget and level window slider. * Currently, the color is always applied. We do not set the color to white, if the user changes the mode. We assume * that users who change the mode know that a previously set color will still be applied (on top of the mode). */ class MITK_CORE_EXPORT RenderingModeProperty : public EnumerationProperty { public: mitkClassMacro( RenderingModeProperty, EnumerationProperty ); itkNewMacro(RenderingModeProperty); mitkNewMacro1Param(RenderingModeProperty, const IdType&); mitkNewMacro1Param(RenderingModeProperty, const std::string&); + Pointer Clone() const; + enum ImageRenderingMode { LEVELWINDOW_COLOR = 0, LOOKUPTABLE_LEVELWINDOW_COLOR = 1, COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR = 2, LOOKUPTABLE_COLOR = 3, COLORTRANSFERFUNCTION_COLOR = 4 // Default = LEVELWINDOW_COLOR; }; /** * Returns the current rendering mode */ virtual int GetRenderingMode(); using BaseProperty::operator=; protected: /** Sets rendering type to default (VTK_RAY_CAST_COMPOSITE_FUNCTION). */ RenderingModeProperty( ); /** * Constructor. Sets rendering type to the given value. */ RenderingModeProperty( const IdType& value ); /** * Constructor. Sets rendering type to the given value. */ RenderingModeProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid rendering types. */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Adds the default enumeration types. */ virtual void AddRenderingModes(); private: // purposely not implemented - RenderingModeProperty(const RenderingModeProperty&); RenderingModeProperty& operator=(const RenderingModeProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkResliceMethodProperty.cpp b/Core/Code/DataManagement/mitkResliceMethodProperty.cpp index 6493c044ac..052683cce0 100644 --- a/Core/Code/DataManagement/mitkResliceMethodProperty.cpp +++ b/Core/Code/DataManagement/mitkResliceMethodProperty.cpp @@ -1,46 +1,57 @@ /*=================================================================== 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 "mitkResliceMethodProperty.h" mitk::ResliceMethodProperty::ResliceMethodProperty( ) { AddThickSlicesTypes(); SetValue( (IdType)0 ); } mitk::ResliceMethodProperty::ResliceMethodProperty( const IdType& value ) { AddThickSlicesTypes(); if ( IsValidEnumerationValue( value ) ) SetValue( value ); } mitk::ResliceMethodProperty::ResliceMethodProperty( const std::string& value ) { AddThickSlicesTypes(); if ( IsValidEnumerationValue( value ) ) SetValue( value ); } void mitk::ResliceMethodProperty::AddThickSlicesTypes() { AddEnum( "disabled", (IdType) 0 ); AddEnum( "mip", (IdType) 1 ); AddEnum( "sum", (IdType) 2 ); AddEnum( "weighted", (IdType) 3 ); } +mitk::ResliceMethodProperty::Pointer mitk::ResliceMethodProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::ResliceMethodProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkResliceMethodProperty.h b/Core/Code/DataManagement/mitkResliceMethodProperty.h index e711489b78..eb7ea26b78 100644 --- a/Core/Code/DataManagement/mitkResliceMethodProperty.h +++ b/Core/Code/DataManagement/mitkResliceMethodProperty.h @@ -1,67 +1,70 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __MITKRESLICEMETHODENUMPROPERTY_H #define __MITKRESLICEMETHODENUMPROPERTY_H #include "mitkEnumerationProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Encapsulates the thick slices method enumeration */ class MITK_CORE_EXPORT ResliceMethodProperty : public EnumerationProperty { public: mitkClassMacro( ResliceMethodProperty, EnumerationProperty ); itkNewMacro(ResliceMethodProperty); mitkNewMacro1Param(ResliceMethodProperty, const IdType&); mitkNewMacro1Param(ResliceMethodProperty, const std::string&); + Pointer Clone() const; + using BaseProperty::operator=; protected: ResliceMethodProperty( ); ResliceMethodProperty( const IdType& value ); ResliceMethodProperty( const std::string& value ); void AddThickSlicesTypes(); private: // purposely not implemented - ResliceMethodProperty(const ResliceMethodProperty&); ResliceMethodProperty& operator=(const ResliceMethodProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif //_MITK_VTK_SCALARMODE_PROPERTY__H_ diff --git a/Core/Code/DataManagement/mitkShaderProperty.cpp b/Core/Code/DataManagement/mitkShaderProperty.cpp index e1d00c44e3..6e042c910b 100644 --- a/Core/Code/DataManagement/mitkShaderProperty.cpp +++ b/Core/Code/DataManagement/mitkShaderProperty.cpp @@ -1,110 +1,126 @@ /*=================================================================== 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 "mitkShaderProperty.h" #include "mitkCoreServices.h" #include "mitkIShaderRepository.h" #include #include mitk::ShaderProperty::ShaderProperty( ) { AddShaderTypes(); SetShader( (IdType)0 ); } +mitk::ShaderProperty::ShaderProperty(const ShaderProperty& other) + : mitk::EnumerationProperty(other) + , shaderList(other.shaderList) +{ +} + mitk::ShaderProperty::ShaderProperty( const IdType& value ) { AddShaderTypes(); SetShader(value); } mitk::ShaderProperty::ShaderProperty( const std::string& value ) { AddShaderTypes(); SetShader(value); } void mitk::ShaderProperty::SetShader( const IdType& value ) { if ( IsValidEnumerationValue( value ) ) SetValue( value ); else SetValue( (IdType)0 ); } void mitk::ShaderProperty::SetShader( const std::string& value ) { if ( IsValidEnumerationValue( value ) ) SetValue( value ); else SetValue( (IdType)0 ); } mitk::EnumerationProperty::IdType mitk::ShaderProperty::GetShaderId() { return GetValueAsId(); } std::string mitk::ShaderProperty::GetShaderName() { return GetValueAsString(); } void mitk::ShaderProperty::AddShaderTypes() { AddEnum( "fixed" ); IShaderRepository* shaderRepo = CoreServices::GetShaderRepository(); if (shaderRepo == NULL) return; std::list l = shaderRepo->GetShaders(); std::list::const_iterator i = l.begin(); while( i != l.end() ) { AddEnum( (*i)->GetName() ); i++; } } bool mitk::ShaderProperty::AddEnum( const std::string& name ,const IdType& /*id*/) { Element e; e.name=name; bool success=Superclass::AddEnum( e.name, (IdType)shaderList.size() ); shaderList.push_back(e); return success; } bool mitk::ShaderProperty::Assign(const BaseProperty &property) { Superclass::Assign(property); this->shaderList = static_cast(property).shaderList; return true; } +mitk::ShaderProperty::Pointer mitk::ShaderProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} +itk::LightObject::Pointer mitk::ShaderProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkShaderProperty.h b/Core/Code/DataManagement/mitkShaderProperty.h index c56fba7d24..eadc0a6874 100644 --- a/Core/Code/DataManagement/mitkShaderProperty.h +++ b/Core/Code/DataManagement/mitkShaderProperty.h @@ -1,115 +1,120 @@ /*=================================================================== 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 __MITKSHADERENUMPROPERTY_H #define __MITKSHADERENUMPROPERTY_H #include "mitkEnumerationProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Encapsulates the shader enumeration */ class MITK_CORE_EXPORT ShaderProperty : public EnumerationProperty { public: class Element { public: std::string name; }; mitkClassMacro( ShaderProperty, EnumerationProperty ); itkNewMacro(ShaderProperty); mitkNewMacro1Param(ShaderProperty, const IdType&); mitkNewMacro1Param(ShaderProperty, const std::string&); + Pointer Clone() const; + /** * Returns the current scalar mode value as defined by VTK constants. * @returns the current scalar mode as VTK constant. */ IdType GetShaderId(); std::string GetShaderName(); void SetShader(const IdType& i); void SetShader(const std::string& i); using BaseProperty::operator=; protected: std::list shaderList; /** * Constructor. Sets the representation to a default value of surface(2) */ ShaderProperty( ); + ShaderProperty(const ShaderProperty& other); + /** * \brief Sets the scalar mode to the given value. If it is not * valid, the scalar mode is set to default (0). * @param value the integer representation of the scalar mode */ ShaderProperty( const IdType& value ); /** * \brief Sets the scalar mode to the given value. If it is not * valid, the representation is set to default (0). * @param value the string representation of the scalar mode */ ShaderProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid scalar mode types. */ bool AddEnum( const std::string& name, const IdType& id = 0); /** * Adds the enumeration types as defined by vtk to the list of known * enumeration values. */ void AddShaderTypes(); private: // purposely not implemented - ShaderProperty(const ShaderProperty&); ShaderProperty& operator=(const ShaderProperty&); + virtual itk::LightObject::Pointer InternalClone() const; + virtual bool Assign(const BaseProperty &property); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif //_MITK_VTK_SCALARMODE_PROPERTY__H_ diff --git a/Core/Code/DataManagement/mitkSmartPointerProperty.cpp b/Core/Code/DataManagement/mitkSmartPointerProperty.cpp index d2a8dfb68f..d666cb4667 100644 --- a/Core/Code/DataManagement/mitkSmartPointerProperty.cpp +++ b/Core/Code/DataManagement/mitkSmartPointerProperty.cpp @@ -1,130 +1,148 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSmartPointerProperty.h" mitk::SmartPointerProperty::ReferenceCountMapType mitk::SmartPointerProperty::m_ReferenceCount; mitk::SmartPointerProperty::ReferencesUIDMapType mitk::SmartPointerProperty::m_ReferencesUID; mitk::SmartPointerProperty::ReadInSmartPointersMapType mitk::SmartPointerProperty::m_ReadInInstances; mitk::SmartPointerProperty::ReadInTargetsMapType mitk::SmartPointerProperty::m_ReadInTargets; mitk::UIDGenerator mitk::SmartPointerProperty::m_UIDGenerator("POINTER_"); void mitk::SmartPointerProperty::PostProcessXMLReading() { for (ReadInSmartPointersMapType::iterator iter = m_ReadInInstances.begin(); iter != m_ReadInInstances.end(); ++iter) { if ( m_ReadInTargets.find(iter->second) != m_ReadInTargets.end() ) { iter->first->SetSmartPointer( m_ReadInTargets[ iter->second ] ); } } m_ReadInInstances.clear(); } /// \return The number of SmartPointerProperties that point to @param object unsigned int mitk::SmartPointerProperty::GetReferenceCountFor(itk::Object* object) { if ( m_ReferenceCount.find(object) != m_ReferenceCount.end() ) { return m_ReferenceCount[object]; } else { return 0; } } void mitk::SmartPointerProperty::RegisterPointerTarget(itk::Object* object, const std::string uid) { m_ReadInTargets[uid] = object; } std::string mitk::SmartPointerProperty::GetReferenceUIDFor(itk::Object* object) { if ( m_ReferencesUID.find(object) != m_ReferencesUID.end() ) { return m_ReferencesUID[object]; } else { return std::string("invalid"); } } bool mitk::SmartPointerProperty::IsEqual(const BaseProperty& property) const { return this->m_SmartPointer == static_cast(property).m_SmartPointer; } bool mitk::SmartPointerProperty::Assign(const BaseProperty& property) { this->m_SmartPointer = static_cast(property).m_SmartPointer; return true; } mitk::SmartPointerProperty::SmartPointerProperty(itk::Object* pointer) { SetSmartPointer( pointer ); } +mitk::SmartPointerProperty::SmartPointerProperty(const SmartPointerProperty& other) + : BaseProperty(other) + , m_SmartPointer(other.m_SmartPointer) +{ +} + itk::Object::Pointer mitk::SmartPointerProperty::GetSmartPointer() const { return m_SmartPointer; } itk::Object::Pointer mitk::SmartPointerProperty::GetValue() const { return this->GetSmartPointer(); } void mitk::SmartPointerProperty::SetSmartPointer(itk::Object* pointer) { if(m_SmartPointer.GetPointer() != pointer) { // keep track of referenced objects if ( m_SmartPointer.GetPointer() && --m_ReferenceCount[m_SmartPointer.GetPointer()] == 0 ) // if there is no reference left, delete entry { m_ReferenceCount.erase( m_SmartPointer.GetPointer() ); m_ReferencesUID.erase( m_SmartPointer.GetPointer() ); } if ( pointer && ++m_ReferenceCount[pointer] == 1 ) // first reference --> generate UID { m_ReferencesUID[pointer] = m_UIDGenerator.GetUID(); } // change pointer m_SmartPointer = pointer; Modified(); } } void mitk::SmartPointerProperty::SetValue(const ValueType & value) { this->SetSmartPointer(value.GetPointer()); } std::string mitk::SmartPointerProperty::GetValueAsString() const { if ( m_SmartPointer.IsNotNull() ) return m_ReferencesUID[ m_SmartPointer.GetPointer() ]; else return std::string("NULL"); } + +mitk::SmartPointerProperty::Pointer mitk::SmartPointerProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::SmartPointerProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkSmartPointerProperty.h b/Core/Code/DataManagement/mitkSmartPointerProperty.h index 4ace39ae7f..20ac955bd7 100644 --- a/Core/Code/DataManagement/mitkSmartPointerProperty.h +++ b/Core/Code/DataManagement/mitkSmartPointerProperty.h @@ -1,105 +1,109 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKSMARTPOINTERPROPERTY_H_HEADER_INCLUDED_C126B791 #define MITKSMARTPOINTERPROPERTY_H_HEADER_INCLUDED_C126B791 #include #include "mitkBaseProperty.h" #include "mitkUIDGenerator.h" #include #include #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif //##Documentation //## @brief Property containing a smart-pointer //## @ingroup DataManagement class MITK_CORE_EXPORT SmartPointerProperty : public BaseProperty { public: mitkClassMacro(SmartPointerProperty, BaseProperty); itkNewMacro(SmartPointerProperty); mitkNewMacro1Param(SmartPointerProperty, itk::Object*); typedef itk::Object::Pointer ValueType; + Pointer Clone() const; + itk::Object::Pointer GetSmartPointer() const; ValueType GetValue() const; void SetSmartPointer(itk::Object*); void SetValue(const ValueType&); /// mainly for XML output virtual std::string GetValueAsString() const; static void PostProcessXMLReading(); /// Return the number of SmartPointerProperties that reference the object given as parameter static unsigned int GetReferenceCountFor(itk::Object*); static std::string GetReferenceUIDFor(itk::Object*); static void RegisterPointerTarget(itk::Object*, const std::string uid); using BaseProperty::operator=; protected: SmartPointerProperty(itk::Object* = NULL); + SmartPointerProperty(const SmartPointerProperty&); itk::Object::Pointer m_SmartPointer; private: // purposely not implemented - SmartPointerProperty(const SmartPointerProperty&); SmartPointerProperty& operator=(const SmartPointerProperty&); + itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty&) const; virtual bool Assign(const BaseProperty&); typedef std::map ReferenceCountMapType; typedef std::map ReferencesUIDMapType; typedef std::map ReadInSmartPointersMapType; typedef std::map ReadInTargetsMapType; /// for each itk::Object* count how many SmartPointerProperties point to it static ReferenceCountMapType m_ReferenceCount; static ReferencesUIDMapType m_ReferencesUID; static ReadInSmartPointersMapType m_ReadInInstances; static ReadInTargetsMapType m_ReadInTargets; /// to generate unique IDs for the objects pointed at (during XML writing) static UIDGenerator m_UIDGenerator; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKSMARTPOINTERPROPERTY_H_HEADER_INCLUDED_C126B791 */ diff --git a/Core/Code/DataManagement/mitkStringProperty.cpp b/Core/Code/DataManagement/mitkStringProperty.cpp index c1f12b9c47..d1fea19b12 100644 --- a/Core/Code/DataManagement/mitkStringProperty.cpp +++ b/Core/Code/DataManagement/mitkStringProperty.cpp @@ -1,48 +1,65 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStringProperty.h" const char* mitk::StringProperty::PATH = "path"; mitk::StringProperty::StringProperty( const char* string ) : m_Value() { if ( string ) m_Value = string; } mitk::StringProperty::StringProperty( const std::string& s ) : m_Value( s ) { +} +mitk::StringProperty::StringProperty(const StringProperty& other) + : BaseProperty(other) + , m_Value(other.m_Value) +{ } bool mitk::StringProperty::IsEqual(const BaseProperty& property ) const { return this->m_Value == static_cast(property).m_Value; } bool mitk::StringProperty::Assign(const BaseProperty& property ) { this->m_Value = static_cast(property).m_Value; return true; } std::string mitk::StringProperty::GetValueAsString() const { return m_Value; } + +mitk::StringProperty::Pointer mitk::StringProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::StringProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkStringProperty.h b/Core/Code/DataManagement/mitkStringProperty.h index 0941014ed1..13586216c1 100644 --- a/Core/Code/DataManagement/mitkStringProperty.h +++ b/Core/Code/DataManagement/mitkStringProperty.h @@ -1,80 +1,85 @@ /*=================================================================== 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 MITKSTRINGPROPERTY_H_HEADER_INCLUDED_C1C02491 #define MITKSTRINGPROPERTY_H_HEADER_INCLUDED_C1C02491 #include #include #include "mitkBaseProperty.h" #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * @brief Property for strings * @ingroup DataManagement */ class MITK_CORE_EXPORT StringProperty : public BaseProperty { protected: std::string m_Value; StringProperty( const char* string = 0 ); StringProperty( const std::string& s ); + StringProperty(const StringProperty&); + public: mitkClassMacro(StringProperty, BaseProperty); typedef std::string ValueType; itkNewMacro(StringProperty); mitkNewMacro1Param(StringProperty, const char*); mitkNewMacro1Param(StringProperty, const std::string&) + Pointer Clone() const; + itkGetStringMacro(Value); itkSetStringMacro(Value); virtual std::string GetValueAsString() const; static const char* PATH; using BaseProperty::operator=; private: // purposely not implemented - StringProperty(const StringProperty&); StringProperty& operator=(const StringProperty&); + itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property ) const; virtual bool Assign(const BaseProperty& property ); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkTransferFunction.cpp b/Core/Code/DataManagement/mitkTransferFunction.cpp index d125847124..c0d5324523 100644 --- a/Core/Code/DataManagement/mitkTransferFunction.cpp +++ b/Core/Code/DataManagement/mitkTransferFunction.cpp @@ -1,309 +1,338 @@ /*=================================================================== 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 "mitkTransferFunction.h" #include "mitkImageToItk.h" #include "mitkHistogramGenerator.h" #include #include namespace mitk { TransferFunction::TransferFunction() { m_ScalarOpacityFunction = vtkSmartPointer::New(); m_ColorTransferFunction = vtkSmartPointer::New(); m_GradientOpacityFunction = vtkSmartPointer::New(); m_ScalarOpacityFunction->Initialize(); m_ScalarOpacityFunction->AddPoint(0,1); m_GradientOpacityFunction->Initialize(); m_GradientOpacityFunction->AddPoint(0,1); m_ColorTransferFunction->RemoveAllPoints(); m_ColorTransferFunction->SetColorSpaceToHSV(); m_ColorTransferFunction->AddRGBPoint(0,1,1,1); } +TransferFunction::TransferFunction(const TransferFunction& other) + : itk::Object() + , m_ScalarOpacityFunction(other.m_ScalarOpacityFunction.New()) + , m_GradientOpacityFunction(other.m_GradientOpacityFunction.New()) + , m_ColorTransferFunction(other.m_ColorTransferFunction.New()) + , m_Min(other.m_Min) + , m_Max(other.m_Max) + , m_Histogram(other.m_Histogram) + , m_ScalarOpacityPoints(other.m_ScalarOpacityPoints) + , m_GradientOpacityPoints(other.m_GradientOpacityPoints) + , m_RGBPoints(other.m_RGBPoints) +{ + m_ScalarOpacityFunction->DeepCopy(other.m_ScalarOpacityFunction); + m_GradientOpacityFunction->DeepCopy(other.m_GradientOpacityFunction); + m_ColorTransferFunction->DeepCopy(other.m_ColorTransferFunction); +} + TransferFunction::~TransferFunction() { } bool TransferFunction::operator==(Self& other) { if ((m_Min != other.m_Min) || (m_Max != other.m_Max)) return false; bool sizes = (m_ScalarOpacityFunction->GetSize() == other.m_ScalarOpacityFunction->GetSize()) && (m_GradientOpacityFunction->GetSize() == other.m_GradientOpacityFunction->GetSize()) && (m_ColorTransferFunction->GetSize() == other.m_ColorTransferFunction->GetSize()); if (sizes == false) return false; for (int i = 0; i < m_ScalarOpacityFunction->GetSize(); i++ ) { double myVal[4]; double otherVal[4]; m_ScalarOpacityFunction->GetNodeValue(i, myVal); other.m_ScalarOpacityFunction->GetNodeValue(i, otherVal); bool equal = (myVal[0] == otherVal[0]) && (myVal[1] == otherVal[1]) && (myVal[2] == otherVal[2]) && (myVal[3] == otherVal[3]); if (equal == false) return false; } for (int i = 0; i < m_GradientOpacityFunction->GetSize(); i++ ) { double myVal[4]; double otherVal[4]; m_GradientOpacityFunction->GetNodeValue(i, myVal); other.m_GradientOpacityFunction->GetNodeValue(i, otherVal); bool equal = (myVal[0] == otherVal[0]) && (myVal[1] == otherVal[1]) && (myVal[2] == otherVal[2]) && (myVal[3] == otherVal[3]); if (equal == false) return false; } for (int i = 0; i < m_ColorTransferFunction->GetSize(); i++ ) { double myVal[6]; double otherVal[6]; m_ColorTransferFunction->GetNodeValue(i, myVal); other.m_ColorTransferFunction->GetNodeValue(i, otherVal); bool equal = (myVal[0] == otherVal[0]) // X && (myVal[1] == otherVal[1]) // R && (myVal[2] == otherVal[2]) // G && (myVal[3] == otherVal[3]) // B && (myVal[4] == otherVal[4]) // midpoint && (myVal[5] == otherVal[5]); // sharpness if (equal == false) return false; } return true; } void TransferFunction::SetScalarOpacityPoints(TransferFunction::ControlPoints points) { m_ScalarOpacityFunction->RemoveAllPoints(); for(unsigned int i=0; i<=points.size()-1;i++) { this->AddScalarOpacityPoint(points[i].first, points[i].second); } } void TransferFunction::SetGradientOpacityPoints(TransferFunction::ControlPoints points) { m_GradientOpacityFunction->RemoveAllPoints(); for(unsigned int i=0; i<=points.size()-1;i++) { this->AddGradientOpacityPoint(points[i].first, points[i].second); } } void TransferFunction::SetRGBPoints(TransferFunction::RGBControlPoints rgbpoints) { m_ColorTransferFunction->RemoveAllPoints(); for(unsigned int i=0; i<=rgbpoints.size()-1;i++) { this->AddRGBPoint(rgbpoints[i].first, rgbpoints[i].second[0], rgbpoints[i].second[1], rgbpoints[i].second[2]); } } void TransferFunction::AddScalarOpacityPoint(double x, double value) { m_ScalarOpacityFunction->AddPoint(x, value); } void TransferFunction::AddGradientOpacityPoint(double x, double value) { m_GradientOpacityFunction->AddPoint(x, value); } void TransferFunction::AddRGBPoint(double x, double r, double g, double b) { m_ColorTransferFunction->AddRGBPoint(x, r, g, b); } TransferFunction::ControlPoints &TransferFunction::GetScalarOpacityPoints() { // Retrieve data points from VTK transfer function and store them in a vector m_ScalarOpacityPoints.clear(); vtkFloatingPointType *data = m_ScalarOpacityFunction->GetDataPointer(); for ( int i = 0; i < m_ScalarOpacityFunction->GetSize(); ++i ) { m_ScalarOpacityPoints.push_back( std::make_pair( data[i*2], data[i*2+1] )); } return m_ScalarOpacityPoints; } TransferFunction::ControlPoints &TransferFunction::GetGradientOpacityPoints() { // Retrieve data points from VTK transfer function and store them in a vector m_GradientOpacityPoints.clear(); vtkFloatingPointType *data = m_GradientOpacityFunction->GetDataPointer(); for ( int i = 0; i < m_GradientOpacityFunction->GetSize(); ++i ) { m_GradientOpacityPoints.push_back( std::make_pair( data[i*2], data[i*2+1] )); } return m_GradientOpacityPoints; } TransferFunction::RGBControlPoints &TransferFunction::GetRGBPoints() { // Retrieve data points from VTK transfer function and store them in a vector m_RGBPoints.clear(); vtkFloatingPointType *data = m_ColorTransferFunction->GetDataPointer(); for ( int i = 0; i < m_ColorTransferFunction->GetSize(); ++i ) { double rgb[] = { data[i*4+1], data[i*4+2], data[i*4+3] }; m_RGBPoints.push_back( std::make_pair( data[i*4], rgb )); } return m_RGBPoints; } int TransferFunction::RemoveScalarOpacityPoint(double x) { return m_ScalarOpacityFunction->RemovePoint(x); } int TransferFunction::RemoveGradientOpacityPoint(double x) { return m_GradientOpacityFunction->RemovePoint(x); } int TransferFunction::RemoveRGBPoint(double x) { return m_ColorTransferFunction->RemovePoint(x); } void TransferFunction::ClearScalarOpacityPoints() { m_ScalarOpacityFunction->RemoveAllPoints(); } void TransferFunction::ClearGradientOpacityPoints() { m_GradientOpacityFunction->RemoveAllPoints(); } void TransferFunction::ClearRGBPoints() { m_ColorTransferFunction->RemoveAllPoints(); } void TransferFunction::InitializeByItkHistogram( const itk::Statistics::Histogram* histogram) { m_Histogram = histogram; m_Min = (int)GetHistogram()->GetBinMin(0,0); m_Max = (int)GetHistogram()->GetBinMax(0, GetHistogram()->Size()-1); /* m_ScalarOpacityFunction->Initialize(); m_ScalarOpacityFunction->AddPoint(m_Min,0.0); m_ScalarOpacityFunction->AddPoint(0.0,0.0); m_ScalarOpacityFunction->AddPoint(m_Max,1.0); m_GradientOpacityFunction->Initialize(); m_GradientOpacityFunction->AddPoint(m_Min,0.0); m_GradientOpacityFunction->AddPoint(0.0,1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.125),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.2),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.25),1.0); m_GradientOpacityFunction->AddPoint(m_Max,1.0); m_ColorTransferFunction->RemoveAllPoints(); m_ColorTransferFunction->AddRGBPoint(m_Min,1,0,0); m_ColorTransferFunction->AddRGBPoint(m_Max,1,1,0); m_ColorTransferFunction->SetColorSpaceToHSV(); MITK_INFO << "min/max in tf-c'tor:" << m_Min << "/" << m_Max << std::endl; */ } void TransferFunction::InitializeByMitkImage( const Image * image ) { HistogramGenerator::Pointer histGen= HistogramGenerator::New(); histGen->SetImage(image); histGen->SetSize(256); histGen->ComputeHistogram(); m_Histogram = histGen->GetHistogram(); m_Min = (int)GetHistogram()->GetBinMin(0,0); m_Max = (int)GetHistogram()->GetBinMax(0, GetHistogram()->Size()-1); m_ScalarOpacityFunction->Initialize(); m_ScalarOpacityFunction->AddPoint(m_Min,0.0); m_ScalarOpacityFunction->AddPoint(0.0,0.0); m_ScalarOpacityFunction->AddPoint(m_Max,1.0); m_GradientOpacityFunction->Initialize(); m_GradientOpacityFunction->AddPoint(m_Min,0.0); m_GradientOpacityFunction->AddPoint(0.0,1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.125),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.2),1.0); m_GradientOpacityFunction->AddPoint((m_Max*0.25),1.0); m_GradientOpacityFunction->AddPoint(m_Max,1.0); m_ColorTransferFunction->RemoveAllPoints(); m_ColorTransferFunction->AddRGBPoint(m_Min,1,0,0); m_ColorTransferFunction->AddRGBPoint(m_Max,1,1,0); m_ColorTransferFunction->SetColorSpaceToHSV(); //MITK_INFO << "min/max in tf-c'tor:" << m_Min << "/" << m_Max << std::endl; } void TransferFunction::InitializeHistogram( const Image * image ) { HistogramGenerator::Pointer histGen= HistogramGenerator::New(); histGen->SetImage(image); histGen->SetSize(256); histGen->ComputeHistogram(); m_Histogram = histGen->GetHistogram(); m_Min = (int)GetHistogram()->GetBinMin(0,0); m_Max = (int)GetHistogram()->GetBinMax(0, GetHistogram()->Size()-1); } void TransferFunction::PrintSelf(std::ostream &os, itk::Indent indent) const { os << indent << "ScalarOpacity: "; m_ScalarOpacityFunction->PrintHeader(os, vtkIndent()); os << indent << "GradientOpacity: "; m_GradientOpacityFunction->PrintHeader(os, vtkIndent()); os << indent << "ColorTransfer: "; m_ColorTransferFunction->PrintHeader(os, vtkIndent()); os << indent << "Min: " << m_Min << ", Max: " << m_Max << std::endl; } +mitk::TransferFunction::Pointer mitk::TransferFunction::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::TransferFunction::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} + }// namespace diff --git a/Core/Code/DataManagement/mitkTransferFunction.h b/Core/Code/DataManagement/mitkTransferFunction.h index 7b34a4b385..37b1682809 100644 --- a/Core/Code/DataManagement/mitkTransferFunction.h +++ b/Core/Code/DataManagement/mitkTransferFunction.h @@ -1,195 +1,201 @@ /*=================================================================== 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_TRANSFER_FUNCTION_H_HEADER_INCLUDED #define MITK_TRANSFER_FUNCTION_H_HEADER_INCLUDED #include "mitkHistogramGenerator.h" #include #include "mitkImage.h" #include #include #include #include #include #include #include #include #include namespace mitk { /** * \brief Wrapper class for VTK scalar opacity, gradient opacity, and color * transfer functions. * * Holds a copy of each of the three standard VTK transfer functions (scalar * opacity, gradient opacity, color) and provides an interface for manipulating * their control points. Each original function can be retrieved by a Get() * method. * * NOTE: Currently, transfer function initialization based on histograms or * computed-tomography-presets is also provided by this class, but will likely * be separated into a specific initializer class. */ class MITK_CORE_EXPORT TransferFunction : public itk::Object { public: typedef std::vector > ControlPoints; typedef std::vector > > RGBControlPoints; mitkClassMacro(TransferFunction, itk::DataObject); itkNewMacro(Self); + Pointer Clone() const; + /** \brief Get/Set min/max of transfer function range for initialization. */ itkSetMacro(Min,int); /** \brief Get/Set min/max of transfer function range for initialization. */ itkSetMacro(Max,int); /** \brief Get/Set min/max of transfer function range for initialization. */ itkGetMacro(Min,int); /** \brief Get/Set min/max of transfer function range for initialization. */ itkGetMacro(Max,int); /** \brief Get/Set wrapped vtk transfer function. */ itkGetMacro(ScalarOpacityFunction,vtkPiecewiseFunction*); /** \brief Get/Set wrapped vtk transfer function. */ itkGetMacro(GradientOpacityFunction,vtkPiecewiseFunction*); /** \brief Get/Set wrapped vtk transfer function. */ itkGetMacro(ColorTransferFunction,vtkColorTransferFunction*); itkSetMacro(ColorTransferFunction,vtkSmartPointer); /** \brief Get histogram used for transfer function initialization. */ itkGetConstObjectMacro(Histogram,HistogramGenerator::HistogramType); /** \brief Initialize transfer function based on the histogram of an mitk::Image. */ void InitializeByMitkImage(const mitk::Image* image); /** \brief Initialize transfer function based on the specified histogram. */ void InitializeByItkHistogram(const itk::Statistics::Histogram* histogram); /** \brief Initialize the internal histogram and min/max range based on the * specified mitk::Image. */ void InitializeHistogram( const mitk::Image* image ); /** \brief Insert control points and values into the scalar opacity transfer * function. */ void SetScalarOpacityPoints(TransferFunction::ControlPoints points); /** \brief Insert control points and values into the gradient opacity transfer * function. */ void SetGradientOpacityPoints(TransferFunction::ControlPoints points); /** \brief Insert control points and RGB values into the color transfer * function. */ void SetRGBPoints(TransferFunction::RGBControlPoints rgbpoints); /** \brief Add a single control point to the scalar opacity transfer function. */ void AddScalarOpacityPoint(double x, double value); /** \brief Add a single control point to the gradient opacity transfer function. */ void AddGradientOpacityPoint(double x, double value); /** \brief Add a single control point to the color opacity transfer function. */ void AddRGBPoint(double x, double r, double g, double b); /** \brief Get a copy of the scalar opacity transfer function control-points. */ TransferFunction::ControlPoints &GetScalarOpacityPoints(); /** \brief Get a copy of the gradient opacity transfer function control-points. */ TransferFunction::ControlPoints &GetGradientOpacityPoints(); /** \brief Get a copy of the color transfer function control-points. */ TransferFunction::RGBControlPoints &GetRGBPoints(); /** \brief Remove the specified control point from the scalar opacity transfer * function. */ int RemoveScalarOpacityPoint(double x); /** \brief Remove the specified control point from the gradient opacity transfer * function. */ int RemoveGradientOpacityPoint(double x); /** \brief Remove the specified control point from the color transfer function. */ int RemoveRGBPoint(double x); /** \brief Removes all control points from the scalar opacity transfer function. */ void ClearScalarOpacityPoints(); /** \brief Removes all control points from the gradient opacity transfer * function. */ void ClearGradientOpacityPoints(); /** \brief Removes all control points from the color transfer function. */ void ClearRGBPoints(); bool operator==(Self& other); protected: TransferFunction(); virtual ~TransferFunction(); + TransferFunction(const TransferFunction& other); + + virtual itk::LightObject::Pointer InternalClone() const; + void PrintSelf(std::ostream &os, itk::Indent indent) const; /** Wrapped VTK scalar opacity transfer function */ vtkSmartPointer m_ScalarOpacityFunction; /** Wrapped VTK gradient opacity transfer function */ vtkSmartPointer m_GradientOpacityFunction; /** Wrapped VTK color transfer function */ vtkSmartPointer m_ColorTransferFunction; /** Current range of transfer function (used for initialization) */ int m_Min; /** Current range of transfer function (used for initialization) */ int m_Max; /** Specified or calculated histogram (used for initialization) */ mitk::HistogramGenerator::HistogramType::ConstPointer m_Histogram; private: /** Temporary STL style copy of VTK internal control points */ TransferFunction::ControlPoints m_ScalarOpacityPoints; /** Temporary STL style copy of VTK internal control points */ TransferFunction::ControlPoints m_GradientOpacityPoints; /** Temporary STL style copy of VTK internal control points */ TransferFunction::RGBControlPoints m_RGBPoints; }; } #endif /* MITK_TRANSFER_FUNCTION_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkTransferFunctionProperty.cpp b/Core/Code/DataManagement/mitkTransferFunctionProperty.cpp index fe7328c2c9..f600f319f5 100644 --- a/Core/Code/DataManagement/mitkTransferFunctionProperty.cpp +++ b/Core/Code/DataManagement/mitkTransferFunctionProperty.cpp @@ -1,49 +1,67 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTransferFunctionProperty.h" namespace mitk { bool TransferFunctionProperty::IsEqual(const BaseProperty& property) const { return *(this->m_Value) == *(static_cast(property).m_Value); } bool TransferFunctionProperty::Assign(const BaseProperty& property) { this->m_Value = static_cast(property).m_Value; return true; } std::string TransferFunctionProperty::GetValueAsString() const { std::stringstream myStr; myStr << GetValue(); return myStr.str(); } TransferFunctionProperty::TransferFunctionProperty() : BaseProperty() {} +TransferFunctionProperty::TransferFunctionProperty(const TransferFunctionProperty& other) + : BaseProperty(other) + , m_Value(other.m_Value->Clone()) +{ +} + TransferFunctionProperty::TransferFunctionProperty( mitk::TransferFunction::Pointer value ) : BaseProperty(), m_Value( value ) {} +TransferFunctionProperty::Pointer TransferFunctionProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer TransferFunctionProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} + } // namespace mitk diff --git a/Core/Code/DataManagement/mitkTransferFunctionProperty.h b/Core/Code/DataManagement/mitkTransferFunctionProperty.h index 59a613942e..982ee6cf63 100644 --- a/Core/Code/DataManagement/mitkTransferFunctionProperty.h +++ b/Core/Code/DataManagement/mitkTransferFunctionProperty.h @@ -1,73 +1,77 @@ /*=================================================================== 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 MITKTRANFERFUNCTIONPROPERTY_H_HEADER_INCLUDED #define MITKTRANFERFUNCTIONPROPERTY_H_HEADER_INCLUDED #include "mitkBaseProperty.h" #include "mitkTransferFunction.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif class MITK_CORE_EXPORT TransferFunctionProperty : public BaseProperty { public: typedef mitk::TransferFunction::Pointer ValueType; mitkClassMacro(TransferFunctionProperty, BaseProperty); itkNewMacro(TransferFunctionProperty); mitkNewMacro1Param(TransferFunctionProperty, mitk::TransferFunction::Pointer); + Pointer Clone() const; + itkSetMacro(Value, mitk::TransferFunction::Pointer ); itkGetConstMacro(Value, mitk::TransferFunction::Pointer ); std::string GetValueAsString() const; using BaseProperty::operator=; protected: mitk::TransferFunction::Pointer m_Value; TransferFunctionProperty(); + TransferFunctionProperty(const TransferFunctionProperty& other); TransferFunctionProperty( mitk::TransferFunction::Pointer value ); private: // purposely not implemented - TransferFunctionProperty(const TransferFunctionProperty&); TransferFunctionProperty& operator=(const TransferFunctionProperty&); + itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKTRANFERFUNCTIONPROPERTY_H_HEADER_INCLUDED */ diff --git a/Core/Code/DataManagement/mitkVtkInterpolationProperty.cpp b/Core/Code/DataManagement/mitkVtkInterpolationProperty.cpp index 70d23493d2..660a054b6a 100644 --- a/Core/Code/DataManagement/mitkVtkInterpolationProperty.cpp +++ b/Core/Code/DataManagement/mitkVtkInterpolationProperty.cpp @@ -1,91 +1,103 @@ /*=================================================================== 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 "mitkVtkInterpolationProperty.h" mitk::VtkInterpolationProperty::VtkInterpolationProperty( ) { AddInterpolationTypes(); SetValue( static_cast( VTK_GOURAUD ) ); } mitk::VtkInterpolationProperty::VtkInterpolationProperty( const IdType& value ) { AddInterpolationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ) ; } else { SetValue( static_cast( VTK_GOURAUD ) ); } } mitk::VtkInterpolationProperty::VtkInterpolationProperty( const std::string& value ) { AddInterpolationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( static_cast( VTK_GOURAUD ) ); } } int mitk::VtkInterpolationProperty::GetVtkInterpolation() { return static_cast( GetValueAsId() ); } void mitk::VtkInterpolationProperty::SetInterpolationToFlat() { SetValue( static_cast( VTK_FLAT ) ); } void mitk::VtkInterpolationProperty::SetInterpolationToGouraud() { SetValue( static_cast( VTK_GOURAUD ) ); } void mitk::VtkInterpolationProperty::SetInterpolationToPhong() { SetValue( static_cast( VTK_PHONG ) ); } void mitk::VtkInterpolationProperty::AddInterpolationTypes() { AddEnum( "Flat", static_cast( VTK_FLAT ) ); AddEnum( "Gouraud", static_cast( VTK_GOURAUD ) ); AddEnum( "Phong", static_cast( VTK_PHONG ) ); } bool mitk::VtkInterpolationProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } + +mitk::VtkInterpolationProperty::Pointer mitk::VtkInterpolationProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::VtkInterpolationProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkVtkInterpolationProperty.h b/Core/Code/DataManagement/mitkVtkInterpolationProperty.h index a474fff29e..acd1d0db44 100644 --- a/Core/Code/DataManagement/mitkVtkInterpolationProperty.h +++ b/Core/Code/DataManagement/mitkVtkInterpolationProperty.h @@ -1,119 +1,122 @@ /*=================================================================== 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_VTK_INTERPOLATION_PROPERTY__H_ #define _MITK_VTK_INTERPOLATION_PROPERTY__H_ #include "mitkEnumerationProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Encapsulates the enumeration vtkInterpolation. Valid values are * (VTK constant/Id/string representation): * VTK_FLAT/0/Flat, VTK_GOURAUD/1/Gouraud, VTK_PHONG/2/Phong * Default is the Gouraud interpolation */ class MITK_CORE_EXPORT VtkInterpolationProperty : public EnumerationProperty { public: mitkClassMacro( VtkInterpolationProperty, EnumerationProperty ); itkNewMacro(VtkInterpolationProperty); mitkNewMacro1Param(VtkInterpolationProperty, const IdType&); mitkNewMacro1Param(VtkInterpolationProperty, const std::string&); + Pointer Clone() const; + /** * Returns the current interpolation value as defined by VTK constants. * @returns the current interpolation as VTK constant. */ virtual int GetVtkInterpolation(); /** * Sets the interpolation type to VTK_FLAT. */ virtual void SetInterpolationToFlat(); /** * Sets the interpolation type to VTK_WIREFRAME. */ virtual void SetInterpolationToGouraud(); /** * Sets the interpolation type to VTK_SURFACE. */ virtual void SetInterpolationToPhong(); using BaseProperty::operator=; protected: /** * Constructor. Sets the representation to a default value of surface(2) */ VtkInterpolationProperty( ); /** * Constructor. Sets the interpolation to the given value. If it is not * valid, the interpolation is set to gouraud(1) * @param value the integer representation of the interpolation */ VtkInterpolationProperty( const IdType& value ); /** * Constructor. Sets the interpolation to the given value. If it is not * valid, the representation is set to gouraud(1) * @param value the string representation of the interpolation */ VtkInterpolationProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid interpolation types. */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Adds the enumeration types as defined by vtk to the list of known * enumeration values. */ virtual void AddInterpolationTypes(); private: // purposely not implemented - VtkInterpolationProperty(const VtkInterpolationProperty&); VtkInterpolationProperty& operator=(const VtkInterpolationProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkVtkRepresentationProperty.cpp b/Core/Code/DataManagement/mitkVtkRepresentationProperty.cpp index 038bdc943a..637a5d00c3 100644 --- a/Core/Code/DataManagement/mitkVtkRepresentationProperty.cpp +++ b/Core/Code/DataManagement/mitkVtkRepresentationProperty.cpp @@ -1,90 +1,102 @@ /*=================================================================== 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 "mitkVtkRepresentationProperty.h" mitk::VtkRepresentationProperty::VtkRepresentationProperty( ) { AddRepresentationTypes(); SetValue( static_cast( VTK_SURFACE ) ); } mitk::VtkRepresentationProperty::VtkRepresentationProperty( const IdType& value ) { AddRepresentationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( static_cast( VTK_SURFACE ) ); } } mitk::VtkRepresentationProperty::VtkRepresentationProperty( const std::string& value ) { AddRepresentationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( static_cast( VTK_SURFACE ) ); } } int mitk::VtkRepresentationProperty::GetVtkRepresentation() { return static_cast( GetValueAsId() ); } void mitk::VtkRepresentationProperty::SetRepresentationToPoints() { SetValue( static_cast( VTK_POINTS ) ); } void mitk::VtkRepresentationProperty::SetRepresentationToWireframe() { SetValue( static_cast( VTK_WIREFRAME ) ); } void mitk::VtkRepresentationProperty::SetRepresentationToSurface() { SetValue( static_cast( VTK_SURFACE ) ); } void mitk::VtkRepresentationProperty::AddRepresentationTypes() { AddEnum( "Points", static_cast( VTK_POINTS ) ); AddEnum( "Wireframe", static_cast( VTK_WIREFRAME ) ); AddEnum( "Surface", static_cast( VTK_SURFACE ) ); } bool mitk::VtkRepresentationProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } + +mitk::VtkRepresentationProperty::Pointer mitk::VtkRepresentationProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::VtkRepresentationProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkVtkRepresentationProperty.h b/Core/Code/DataManagement/mitkVtkRepresentationProperty.h index 08e835d0f4..9b5ef1fda6 100644 --- a/Core/Code/DataManagement/mitkVtkRepresentationProperty.h +++ b/Core/Code/DataManagement/mitkVtkRepresentationProperty.h @@ -1,118 +1,121 @@ /*=================================================================== 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_VTK_REPRESENTATION_PROPERTY__H_ #define _MITK_VTK_REPRESENTATION_PROPERTY__H_ #include "mitkEnumerationProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Encapsulates the enumeration vtkRepresentation. Valid values are * (VTK constant/Id/string representation): * VTK_POINTS/0/Points, VTK_WIREFRAME/1/Wireframe, VTK_SURFACE/2/Surface * Default is the Surface representation */ class MITK_CORE_EXPORT VtkRepresentationProperty : public EnumerationProperty { public: mitkClassMacro( VtkRepresentationProperty, EnumerationProperty ); itkNewMacro(VtkRepresentationProperty); mitkNewMacro1Param(VtkRepresentationProperty, const IdType&); mitkNewMacro1Param(VtkRepresentationProperty, const std::string&); + Pointer Clone() const; + /** * Returns the current representation value as defined by VTK constants. * @returns the current representation as VTK constant. */ virtual int GetVtkRepresentation(); /** * Sets the representation type to VTK_POINTS. */ virtual void SetRepresentationToPoints(); /** * Sets the representation type to VTK_WIREFRAME. */ virtual void SetRepresentationToWireframe(); /** * Sets the representation type to VTK_SURFACE. */ virtual void SetRepresentationToSurface(); using BaseProperty::operator=; protected: /** * Constructor. Sets the representation to a default value of Surface(2) */ VtkRepresentationProperty( ); /** * Constructor. Sets the representation to the given value. If it is not * valid, the representation is set to Surface(2) * @param value the integer representation of the representation */ VtkRepresentationProperty( const IdType& value ); /** * Constructor. Sets the representation to the given value. If it is not * valid, the representation is set to Surface(2) * @param value the string representation of the representation */ VtkRepresentationProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid representation types. */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Adds the enumeration types as defined by vtk to the list of known * enumeration values. */ virtual void AddRepresentationTypes(); private: // purposely not implemented - VtkRepresentationProperty(const VtkRepresentationProperty&); VtkRepresentationProperty& operator=(const VtkRepresentationProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkVtkResliceInterpolationProperty.cpp b/Core/Code/DataManagement/mitkVtkResliceInterpolationProperty.cpp index 36aa9d2bcb..d13b914500 100644 --- a/Core/Code/DataManagement/mitkVtkResliceInterpolationProperty.cpp +++ b/Core/Code/DataManagement/mitkVtkResliceInterpolationProperty.cpp @@ -1,91 +1,103 @@ /*=================================================================== 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 "mitkVtkResliceInterpolationProperty.h" mitk::VtkResliceInterpolationProperty::VtkResliceInterpolationProperty( ) { this->AddInterpolationTypes(); this->SetValue( static_cast( VTK_RESLICE_NEAREST ) ); } mitk::VtkResliceInterpolationProperty::VtkResliceInterpolationProperty( const IdType& value ) { this->AddInterpolationTypes(); if ( IsValidEnumerationValue( value ) ) { this->SetValue( value ) ; } else { this->SetValue( static_cast( VTK_RESLICE_NEAREST ) ); } } mitk::VtkResliceInterpolationProperty::VtkResliceInterpolationProperty( const std::string& value ) { this->AddInterpolationTypes(); if ( IsValidEnumerationValue( value ) ) { this->SetValue( value ); } else { this->SetValue( static_cast( VTK_RESLICE_NEAREST ) ); } } int mitk::VtkResliceInterpolationProperty::GetInterpolation() { return static_cast( this->GetValueAsId() ); } void mitk::VtkResliceInterpolationProperty::SetInterpolationToNearest() { this->SetValue( static_cast( VTK_RESLICE_NEAREST ) ); } void mitk::VtkResliceInterpolationProperty::SetInterpolationToLinear() { this->SetValue( static_cast( VTK_RESLICE_LINEAR ) ); } void mitk::VtkResliceInterpolationProperty::SetInterpolationToCubic() { this->SetValue( static_cast( VTK_RESLICE_CUBIC ) ); } void mitk::VtkResliceInterpolationProperty::AddInterpolationTypes() { AddEnum( "Nearest", static_cast( VTK_RESLICE_NEAREST ) ); AddEnum( "Linear", static_cast( VTK_RESLICE_LINEAR ) ); AddEnum( "Cubic", static_cast( VTK_RESLICE_CUBIC ) ); } bool mitk::VtkResliceInterpolationProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } + +mitk::VtkResliceInterpolationProperty::Pointer mitk::VtkResliceInterpolationProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::VtkResliceInterpolationProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkVtkResliceInterpolationProperty.h b/Core/Code/DataManagement/mitkVtkResliceInterpolationProperty.h index d11003fdff..7f6b678653 100644 --- a/Core/Code/DataManagement/mitkVtkResliceInterpolationProperty.h +++ b/Core/Code/DataManagement/mitkVtkResliceInterpolationProperty.h @@ -1,115 +1,118 @@ /*=================================================================== 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_VTK_RESLICE_INTERPOLATION_PROPERTY__H_ #define _MITK_VTK_RESLICE_INTERPOLATION_PROPERTY__H_ #include "mitkEnumerationProperty.h" #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Encapsulates the enumeration for reslice interpolation. Valid values are * (VTK constant/Id/string representation): * VTK_RESLICE_NEAREST, VTK_RESLICE_LINEAR, VTK_RESLICE_CUBIC * Default is VTK_RESLICE_NEAREST */ class MITK_CORE_EXPORT VtkResliceInterpolationProperty : public EnumerationProperty { public: mitkClassMacro( VtkResliceInterpolationProperty, EnumerationProperty ); itkNewMacro(VtkResliceInterpolationProperty); mitkNewMacro1Param(VtkResliceInterpolationProperty, const IdType&); mitkNewMacro1Param(VtkResliceInterpolationProperty, const std::string&); + Pointer Clone() const; + /** * Returns the current interpolation value as defined by VTK constants. */ virtual int GetInterpolation(); /** * Sets the interpolation type to VTK_RESLICE_NEAREST. */ virtual void SetInterpolationToNearest(); /** * Sets the interpolation type to VTK_RESLICE_LINEAR. */ virtual void SetInterpolationToLinear(); /** * Sets the interpolation type to VTK_RESLICE_CUBIC. */ virtual void SetInterpolationToCubic(); using BaseProperty::operator=; protected: /** Sets reslice interpolation mode to default (VTK_RESLICE_NEAREST). */ VtkResliceInterpolationProperty( ); /** * Constructor. Sets reslice interpolation to the given value. */ VtkResliceInterpolationProperty( const IdType& value ); /** * Constructor. Sets reslice interpolation to the given value. */ VtkResliceInterpolationProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid interpolation types. */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Adds the enumeration types as defined by vtk to the list of known * enumeration values. */ virtual void AddInterpolationTypes(); private: // purposely not implemented - VtkResliceInterpolationProperty(const VtkResliceInterpolationProperty&); VtkResliceInterpolationProperty& operator=(const VtkResliceInterpolationProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkVtkScalarModeProperty.cpp b/Core/Code/DataManagement/mitkVtkScalarModeProperty.cpp index 5842164d42..8fe199efc5 100644 --- a/Core/Code/DataManagement/mitkVtkScalarModeProperty.cpp +++ b/Core/Code/DataManagement/mitkVtkScalarModeProperty.cpp @@ -1,94 +1,106 @@ /*=================================================================== 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 "mitkVtkScalarModeProperty.h" mitk::VtkScalarModeProperty::VtkScalarModeProperty( ) { AddInterpolationTypes(); SetScalarModeToDefault(); } mitk::VtkScalarModeProperty::VtkScalarModeProperty( const IdType& value ) { AddInterpolationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ) ; } else { SetScalarModeToDefault(); } } mitk::VtkScalarModeProperty::VtkScalarModeProperty( const std::string& value ) { AddInterpolationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetScalarModeToDefault(); } } int mitk::VtkScalarModeProperty::GetVtkScalarMode() { return static_cast( GetValueAsId() ); } void mitk::VtkScalarModeProperty::SetScalarModeToDefault() { SetValue( static_cast( VTK_SCALAR_MODE_DEFAULT ) ); } void mitk::VtkScalarModeProperty::SetScalarModeToPointData() { SetValue( static_cast( VTK_SCALAR_MODE_USE_POINT_DATA ) ); } void mitk::VtkScalarModeProperty::SetScalarModeToCellData() { SetValue( static_cast( VTK_SCALAR_MODE_USE_CELL_DATA ) ); } void mitk::VtkScalarModeProperty::SetScalarModeToPointFieldData() { SetValue( static_cast( VTK_SCALAR_MODE_USE_POINT_FIELD_DATA ) ); } void mitk::VtkScalarModeProperty::SetScalarModeToCellFieldData() { SetValue( static_cast( VTK_SCALAR_MODE_USE_CELL_FIELD_DATA ) ); } void mitk::VtkScalarModeProperty::AddInterpolationTypes() { AddEnum( "Default", static_cast( VTK_SCALAR_MODE_DEFAULT ) ); AddEnum( "PointData", static_cast( VTK_SCALAR_MODE_USE_POINT_DATA ) ); AddEnum( "CellData", static_cast( VTK_SCALAR_MODE_USE_CELL_DATA ) ); AddEnum( "PointFieldData", static_cast( VTK_SCALAR_MODE_USE_POINT_FIELD_DATA ) ); AddEnum( "CellFieldData", static_cast( VTK_SCALAR_MODE_USE_CELL_FIELD_DATA ) ); } bool mitk::VtkScalarModeProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } + +mitk::VtkScalarModeProperty::Pointer mitk::VtkScalarModeProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::VtkScalarModeProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkVtkScalarModeProperty.h b/Core/Code/DataManagement/mitkVtkScalarModeProperty.h index 54b3a570d7..983eda1082 100644 --- a/Core/Code/DataManagement/mitkVtkScalarModeProperty.h +++ b/Core/Code/DataManagement/mitkVtkScalarModeProperty.h @@ -1,117 +1,120 @@ /*=================================================================== 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_VTK_SCALARMODE_PROPERTY__H_ #define _MITK_VTK_SCALARMODE_PROPERTY__H_ #include "mitkEnumerationProperty.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Encapsulates the enumeration vtkInterpolation. Valid values are * (VTK constant/Id/string representation): * \li VTK_SCALAR_MODE_DEFAULT/0/Default, * \li VTK_SCALAR_MODE_USE_POINT_DATA/1/PointData, * \li VTK_SCALAR_MODE_USE_CELL_DATA/2/CellData * \li VTK_SCALAR_MODE_USE_POINT_FIELD_DATA/3/PointFieldData * \li VTK_SCALAR_MODE_USE_CELL_FIELD_DATA/4/CellFieldData */ class MITK_CORE_EXPORT VtkScalarModeProperty : public EnumerationProperty { public: mitkClassMacro( VtkScalarModeProperty, EnumerationProperty ); itkNewMacro(VtkScalarModeProperty); mitkNewMacro1Param(VtkScalarModeProperty, const IdType&); mitkNewMacro1Param(VtkScalarModeProperty, const std::string&); + Pointer Clone() const; + /** * Returns the current scalar mode value as defined by VTK constants. * @returns the current scalar mode as VTK constant. */ virtual int GetVtkScalarMode(); virtual void SetScalarModeToDefault(); virtual void SetScalarModeToPointData(); virtual void SetScalarModeToCellData(); virtual void SetScalarModeToPointFieldData(); virtual void SetScalarModeToCellFieldData(); using BaseProperty::operator=; protected: /** * Constructor. Sets the representation to a default value of surface(2) */ VtkScalarModeProperty( ); /** * \brief Sets the scalar mode to the given value. If it is not * valid, the scalar mode is set to default (0). * @param value the integer representation of the scalar mode */ VtkScalarModeProperty( const IdType& value ); /** * \brief Sets the scalar mode to the given value. If it is not * valid, the representation is set to default (0). * @param value the string representation of the scalar mode */ VtkScalarModeProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid scalar mode types. */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Adds the enumeration types as defined by vtk to the list of known * enumeration values. */ virtual void AddInterpolationTypes(); private: // purposely not implemented - VtkScalarModeProperty(const VtkScalarModeProperty&); VtkScalarModeProperty& operator=(const VtkScalarModeProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif //_MITK_VTK_SCALARMODE_PROPERTY__H_ diff --git a/Core/Code/DataManagement/mitkVtkVolumeRenderingProperty.cpp b/Core/Code/DataManagement/mitkVtkVolumeRenderingProperty.cpp index fc2e1abeb2..2abfcf8d6b 100644 --- a/Core/Code/DataManagement/mitkVtkVolumeRenderingProperty.cpp +++ b/Core/Code/DataManagement/mitkVtkVolumeRenderingProperty.cpp @@ -1,78 +1,90 @@ /*=================================================================== 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 "mitkVtkVolumeRenderingProperty.h" mitk::VtkVolumeRenderingProperty::VtkVolumeRenderingProperty( ) { this->AddRenderingTypes(); this->SetValue( static_cast( VTK_RAY_CAST_COMPOSITE_FUNCTION ) ); } mitk::VtkVolumeRenderingProperty::VtkVolumeRenderingProperty( const IdType& value ) { this->AddRenderingTypes(); if ( IsValidEnumerationValue( value ) ) { this->SetValue( value ) ; } else MITK_INFO << "Warning: invalid rendering configuration" << std::endl; } mitk::VtkVolumeRenderingProperty::VtkVolumeRenderingProperty( const std::string& value ) { this->AddRenderingTypes(); if ( IsValidEnumerationValue( value ) ) { this->SetValue( value ); } else MITK_INFO << "Warning: invalid rendering configuration" << std::endl; } int mitk::VtkVolumeRenderingProperty::GetRenderingType() { return static_cast( this->GetValueAsId() ); } void mitk::VtkVolumeRenderingProperty::SetRenderingTypeToMIP() { this->SetValue( static_cast( VTK_VOLUME_RAY_CAST_MIP_FUNCTION ) ); } void mitk::VtkVolumeRenderingProperty::SetRenderingTypeToComposite() { this->SetValue( static_cast( VTK_RAY_CAST_COMPOSITE_FUNCTION ) ); } void mitk::VtkVolumeRenderingProperty::AddRenderingTypes() { AddEnum( "MIP", static_cast( VTK_VOLUME_RAY_CAST_MIP_FUNCTION ) ); AddEnum( "COMPOSITE", static_cast (VTK_RAY_CAST_COMPOSITE_FUNCTION)); } bool mitk::VtkVolumeRenderingProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } + +mitk::VtkVolumeRenderingProperty::Pointer mitk::VtkVolumeRenderingProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::VtkVolumeRenderingProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkVtkVolumeRenderingProperty.h b/Core/Code/DataManagement/mitkVtkVolumeRenderingProperty.h index 4afb9ec1e1..debf2787d6 100644 --- a/Core/Code/DataManagement/mitkVtkVolumeRenderingProperty.h +++ b/Core/Code/DataManagement/mitkVtkVolumeRenderingProperty.h @@ -1,111 +1,114 @@ /*=================================================================== 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_VTK_VOLUME_RENDERING_PROPERTY__H_ #define _MITK_VTK_VOLUME_RENDERING_PROPERTY__H_ #include "mitkEnumerationProperty.h" #define VTK_RAY_CAST_COMPOSITE_FUNCTION 1 #define VTK_VOLUME_RAY_CAST_MIP_FUNCTION 2 namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** * Encapsulates the enumeration for volume rendering. Valid values are * (VTK constant/Id/string representation): * VTK_VOLUME_RAY_CAST_MIP_FUNCTION * VTK_RAY_CAST_COMPOSITE_FUNCTION * Default is NULL */ class MITK_CORE_EXPORT VtkVolumeRenderingProperty : public EnumerationProperty { public: mitkClassMacro( VtkVolumeRenderingProperty, EnumerationProperty ); itkNewMacro(VtkVolumeRenderingProperty); mitkNewMacro1Param(VtkVolumeRenderingProperty, const IdType&); mitkNewMacro1Param(VtkVolumeRenderingProperty, const std::string&); + Pointer Clone() const; + /** * Returns the current volume rendering type */ virtual int GetRenderingType(); /** * Sets the rendering type to VTK_VOLUME_RAY_CAST_MIP_FUNCTION */ virtual void SetRenderingTypeToMIP(); /** * Sets the rendering type to VTK_RAY_CAST_COMPOSITE_FUNCTION */ virtual void SetRenderingTypeToComposite(); using BaseProperty::operator=; protected: /** Sets rendering type to default (VTK_RAY_CAST_COMPOSITE_FUNCTION). */ VtkVolumeRenderingProperty( ); /** * Constructor. Sets rendering type to the given value. */ VtkVolumeRenderingProperty( const IdType& value ); /** * Constructor. Sets rendering type to the given value. */ VtkVolumeRenderingProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid rendering types. */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Adds the enumeration types as defined by vtk to the list of known * enumeration values. */ virtual void AddRenderingTypes(); private: // purposely not implemented - VtkVolumeRenderingProperty(const VtkVolumeRenderingProperty&); VtkVolumeRenderingProperty& operator=(const VtkVolumeRenderingProperty&); + + itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // end of namespace mitk #endif diff --git a/Core/Code/DataManagement/mitkWeakPointerProperty.cpp b/Core/Code/DataManagement/mitkWeakPointerProperty.cpp index 77b487ccd4..d505bb129e 100644 --- a/Core/Code/DataManagement/mitkWeakPointerProperty.cpp +++ b/Core/Code/DataManagement/mitkWeakPointerProperty.cpp @@ -1,68 +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 "mitkWeakPointerProperty.h" bool mitk::WeakPointerProperty::IsEqual(const BaseProperty& property) const { return this->m_WeakPointer == static_cast(property).m_WeakPointer; } bool mitk::WeakPointerProperty::Assign(const BaseProperty& property) { this->m_WeakPointer = static_cast(property).m_WeakPointer; return true; } mitk::WeakPointerProperty::WeakPointerProperty(itk::Object* pointer) : m_WeakPointer(pointer) { } +mitk::WeakPointerProperty::WeakPointerProperty(const WeakPointerProperty& other) + : mitk::BaseProperty(other) + , m_WeakPointer(other.m_WeakPointer) +{ +} + mitk::WeakPointerProperty::~WeakPointerProperty() { } std::string mitk::WeakPointerProperty::GetValueAsString() const { std::stringstream ss; ss << m_WeakPointer.GetPointer(); return ss.str(); } mitk::WeakPointerProperty::ValueType mitk::WeakPointerProperty::GetWeakPointer() const { return m_WeakPointer.GetPointer(); } mitk::WeakPointerProperty::ValueType mitk::WeakPointerProperty::GetValue() const { return GetWeakPointer(); } void mitk::WeakPointerProperty::SetWeakPointer(itk::Object* pointer) { if(m_WeakPointer.GetPointer() != pointer) { m_WeakPointer = pointer; Modified(); } } void mitk::WeakPointerProperty::SetValue(const ValueType &value) { SetWeakPointer(value.GetPointer()); } + +mitk::WeakPointerProperty::Pointer mitk::WeakPointerProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::WeakPointerProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/DataManagement/mitkWeakPointerProperty.h b/Core/Code/DataManagement/mitkWeakPointerProperty.h index c06e66e393..1b5e222800 100644 --- a/Core/Code/DataManagement/mitkWeakPointerProperty.h +++ b/Core/Code/DataManagement/mitkWeakPointerProperty.h @@ -1,80 +1,85 @@ /*=================================================================== 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 MITKWEAKPOINTERPROPERTY_H_HEADER_INCLUDED_C126B791 #define MITKWEAKPOINTERPROPERTY_H_HEADER_INCLUDED_C126B791 #include #include "mitkBaseProperty.h" #include "itkWeakPointer.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif //##Documentation //## @brief Property containing a smart-pointer //## //## @ingroup DataManagement class MITK_CORE_EXPORT WeakPointerProperty : public BaseProperty { public: mitkClassMacro(WeakPointerProperty, BaseProperty); itkNewMacro(WeakPointerProperty); mitkNewMacro1Param(WeakPointerProperty, itk::Object*); + Pointer Clone() const; + virtual ~WeakPointerProperty(); typedef itk::WeakPointer ValueType; ValueType GetWeakPointer() const; ValueType GetValue() const; void SetWeakPointer(itk::Object* pointer); void SetValue(const ValueType& value); virtual std::string GetValueAsString() const; using BaseProperty::operator=; protected: itk::WeakPointer m_WeakPointer; + WeakPointerProperty(const WeakPointerProperty&); + WeakPointerProperty(itk::Object* pointer = 0); private: // purposely not implemented - WeakPointerProperty(const WeakPointerProperty&); WeakPointerProperty& operator=(const WeakPointerProperty&); + itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKWEAKPOINTERPROPERTY_H_HEADER_INCLUDED_C126B791 */ diff --git a/Core/Code/IO/mitkLookupTableProperty.cpp b/Core/Code/IO/mitkLookupTableProperty.cpp index 12da81ee75..e3dbd846c8 100755 --- a/Core/Code/IO/mitkLookupTableProperty.cpp +++ b/Core/Code/IO/mitkLookupTableProperty.cpp @@ -1,68 +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 "mitkLookupTableProperty.h" mitk::LookupTableProperty::LookupTableProperty() { } +mitk::LookupTableProperty::LookupTableProperty(const LookupTableProperty& other) + : mitk::BaseProperty(other) + , m_LookupTable(other.m_LookupTable) +{ +} + mitk::LookupTableProperty::LookupTableProperty(const mitk::LookupTable::Pointer lut) { this->SetLookupTable(lut); } bool mitk::LookupTableProperty::IsEqual(const BaseProperty& property) const { return *(this->m_LookupTable) == *(static_cast(property).m_LookupTable); } bool mitk::LookupTableProperty::Assign(const BaseProperty& property) { this->m_LookupTable = static_cast(property).m_LookupTable; return true; } std::string mitk::LookupTableProperty::GetValueAsString() const { std::stringstream ss; ss << m_LookupTable; return ss.str(); } mitk::LookupTableProperty::ValueType mitk::LookupTableProperty::GetValue() const { return m_LookupTable; } void mitk::LookupTableProperty::SetLookupTable(const mitk::LookupTable::Pointer aLookupTable) { // MITK_INFO << "setting LUT property ... " << std::endl; if((m_LookupTable != aLookupTable) || (*m_LookupTable != *aLookupTable)) { m_LookupTable = aLookupTable; Modified(); } // MITK_INFO << "setting LUT property OK! " << std::endl; } void mitk::LookupTableProperty::SetValue(const ValueType & value) { SetLookupTable(value); } + +mitk::LookupTableProperty::Pointer mitk::LookupTableProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::LookupTableProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Core/Code/IO/mitkLookupTableProperty.h b/Core/Code/IO/mitkLookupTableProperty.h index 5301c19240..73ed35ac0f 100755 --- a/Core/Code/IO/mitkLookupTableProperty.h +++ b/Core/Code/IO/mitkLookupTableProperty.h @@ -1,84 +1,89 @@ /*=================================================================== 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 MITKLookupTablePROPERTY_H_HEADER_INCLUDED_C10EEAA8 #define MITKLookupTablePROPERTY_H_HEADER_INCLUDED_C10EEAA8 #include #include "mitkBaseProperty.h" #include "mitkLookupTable.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif //##Documentation //## @brief Property for LookupTable data //## //## @ingroup DataManagement class MITK_CORE_EXPORT LookupTableProperty : public BaseProperty { protected: LookupTable::Pointer m_LookupTable; LookupTableProperty(); + LookupTableProperty(const LookupTableProperty&); + LookupTableProperty(const mitk::LookupTable::Pointer lut); public: typedef LookupTable::Pointer ValueType; mitkClassMacro(LookupTableProperty, BaseProperty); itkNewMacro(LookupTableProperty); mitkNewMacro1Param(LookupTableProperty, const mitk::LookupTable::Pointer); + Pointer Clone() const; + itkGetObjectMacro(LookupTable, LookupTable ); ValueType GetValue() const; void SetLookupTable(const mitk::LookupTable::Pointer aLookupTable); void SetValue(const ValueType&); virtual std::string GetValueAsString() const; using BaseProperty::operator=; private: // purposely not implemented - LookupTableProperty(const LookupTableProperty&); LookupTableProperty& operator=(const LookupTableProperty&); + itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif /* MITKLookupTablePROPERTY_H_HEADER_INCLUDED_C10EEAA8 */ diff --git a/Core/Code/Interactions/mitkBindDispatcherInteractor.cpp b/Core/Code/Interactions/mitkBindDispatcherInteractor.cpp index 8ac1a5453c..6a90d6ed25 100644 --- a/Core/Code/Interactions/mitkBindDispatcherInteractor.cpp +++ b/Core/Code/Interactions/mitkBindDispatcherInteractor.cpp @@ -1,110 +1,110 @@ /*=================================================================== 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 "mitkBindDispatcherInteractor.h" #include "mitkMessage.h" #include // us #include "mitkGetModuleContext.h" #include "mitkModule.h" #include "mitkModuleRegistry.h" mitk::BindDispatcherInteractor::BindDispatcherInteractor() : m_DataStorage(NULL) { ModuleContext* context = ModuleRegistry::GetModule(1)->GetModuleContext(); if (context == NULL) { MITK_ERROR<< "BindDispatcherInteractor() - Context could not be obtained."; return; } m_Dispatcher = Dispatcher::New(); } void mitk::BindDispatcherInteractor::SetDataStorage(mitk::DataStorage::Pointer dataStorage) { // Set/Change Datastorage. This registers BDI to listen for events of DataStorage, to be informed when // a DataNode with a Interactor is added/modified/removed. // clean up events from previous datastorage UnRegisterDataStorageEvents(); m_DataStorage = dataStorage; RegisterDataStorageEvents(); } mitk::BindDispatcherInteractor::~BindDispatcherInteractor() { if (m_DataStorage.IsNotNull()) { UnRegisterDataStorageEvents(); } } void mitk::BindDispatcherInteractor::RegisterInteractor(const mitk::DataNode* dataNode) { if (m_Dispatcher.IsNotNull()) { m_Dispatcher->AddDataInteractor(dataNode); } } void mitk::BindDispatcherInteractor::RegisterDataStorageEvents() { if (m_DataStorage.IsNotNull()) { m_DataStorage->AddNodeEvent.AddListener( MessageDelegate1(this, &BindDispatcherInteractor::RegisterInteractor)); m_DataStorage->RemoveNodeEvent.AddListener( MessageDelegate1(this, &BindDispatcherInteractor::UnRegisterInteractor)); m_DataStorage->ChangedNodeEvent.AddListener( MessageDelegate1(this, &BindDispatcherInteractor::RegisterInteractor)); } } void mitk::BindDispatcherInteractor::UnRegisterInteractor(const DataNode* dataNode) { if (m_Dispatcher.IsNotNull()) { m_Dispatcher->RemoveDataInteractor(dataNode); } } -const mitk::Dispatcher::Pointer mitk::BindDispatcherInteractor::GetDispatcher() +mitk::Dispatcher::Pointer mitk::BindDispatcherInteractor::GetDispatcher() const { return m_Dispatcher; } void mitk::BindDispatcherInteractor::SetDispatcher(Dispatcher::Pointer dispatcher) { m_Dispatcher = dispatcher; } void mitk::BindDispatcherInteractor::UnRegisterDataStorageEvents() { if (m_DataStorage.IsNotNull()) { m_DataStorage->AddNodeEvent.RemoveListener( MessageDelegate1(this, &BindDispatcherInteractor::RegisterInteractor)); m_DataStorage->RemoveNodeEvent.RemoveListener( MessageDelegate1(this, &BindDispatcherInteractor::UnRegisterInteractor)); m_DataStorage->ChangedNodeEvent.RemoveListener( MessageDelegate1(this, &BindDispatcherInteractor::RegisterInteractor)); } } diff --git a/Core/Code/Interactions/mitkBindDispatcherInteractor.h b/Core/Code/Interactions/mitkBindDispatcherInteractor.h index b3dc084895..8909b20d90 100644 --- a/Core/Code/Interactions/mitkBindDispatcherInteractor.h +++ b/Core/Code/Interactions/mitkBindDispatcherInteractor.h @@ -1,80 +1,80 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkBindDispatcherInteractor_h #define mitkBindDispatcherInteractor_h #include "mitkCommon.h" #include #include "mitkDataStorage.h" #include "mitkDataNode.h" #include "mitkDispatcher.h" namespace mitk { /** * \class BindDispatcherInteractor * \brief This Class is used to connect a DataStorage with the Dispatcher. * * This is done by registering for DataStorage Events and sending the Events to the registered Dispatcher. * When a DataInteractor is registered with a DataNode the Dispatcher will be notified. * Also this class registers the MicroService at which InteractionEventObservers can register to receive events. * * \ingroup Interaction */ class MITK_CORE_EXPORT BindDispatcherInteractor { public: BindDispatcherInteractor(); ~BindDispatcherInteractor(); /** * Sets the DataStorage to which Events the class subscribes. */ void SetDataStorage(DataStorage::Pointer dataStorage); /** * Sets Dispatcher which will be notified. By default each RenderWindow gets its own Dispatcher, * this function can be used to override this behavior. */ void SetDispatcher(Dispatcher::Pointer dispatcher); /** * Return currently active Dispatcher. */ - const Dispatcher::Pointer GetDispatcher(); + Dispatcher::Pointer GetDispatcher() const; private: /** @brief Registers for events from DataStorage. * * This way whenever a DataNode is added the Dispatcher is notified about this change, and checks whether a DataInteractor * is set for this DataNode */ void RegisterInteractor(const DataNode* dataNode); void UnRegisterInteractor(const DataNode* dataNode); void RegisterDataStorageEvents(); void UnRegisterDataStorageEvents(); Dispatcher::Pointer m_Dispatcher; DataStorage::Pointer m_DataStorage; }; } #endif /* mitkBindDispatcherInteractor_h */ diff --git a/Core/Code/Interactions/mitkDataInteractor.cpp b/Core/Code/Interactions/mitkDataInteractor.cpp index c99f9e01d8..e1a28190f4 100644 --- a/Core/Code/Interactions/mitkDataInteractor.cpp +++ b/Core/Code/Interactions/mitkDataInteractor.cpp @@ -1,93 +1,98 @@ /*=================================================================== 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 "mitkDataInteractor.h" #include "mitkInteractor.h" #include "mitkPointSet.h" #include "mitkDataNode.h" #include "mitkStateMachineState.h" +// Predefined internal events/signals +const std::string mitk::DataInteractor::IntDeactivateMe = "DeactivateMe"; +const std::string mitk::DataInteractor::IntLeaveWidget = "LeaveWidget"; +const std::string mitk::DataInteractor::IntEnterWidget = "EnterWidget"; + mitk::DataInteractor::DataInteractor() { } mitk::DataInteractor::NodeType mitk::DataInteractor::GetDataNode() const { return m_DataNode; } void mitk::DataInteractor::SetDataNode(DataNode::Pointer dataNode) { if (dataNode == m_DataNode) return; if (m_DataNode.IsNotNull()) { // if DataInteractors' DataNode is set to null, the "old" DataNode has to be notified (else the Dispatcher won't be notified either) m_DataNode->SetDataInteractor(NULL); } m_DataNode = dataNode; if (m_DataNode.IsNotNull()) { m_DataNode->SetDataInteractor(this); } // notify implementations ... DataNodeChanged(); } int mitk::DataInteractor::GetLayer() const { int layer = -1; if (m_DataNode.IsNotNull()) { m_DataNode->GetIntProperty("layer", layer); } return layer; } mitk::DataInteractor::~DataInteractor() { if (m_DataNode.IsNotNull()) { - m_DataNode->SetInteractor(NULL); + m_DataNode->SetDataInteractor(NULL); } } void mitk::DataInteractor::ConnectActionsAndFunctions() { MITK_WARN<< "ConnectActionsAndFunctions in DataInteractor not implemented.\n DataInteractor will not be able to process any events."; } -mitk::ProcessEventMode mitk::DataInteractor::GetMode() +mitk::ProcessEventMode mitk::DataInteractor::GetMode() const { if (GetCurrentState()->GetMode() == "PREFER_INPUT") { return PREFERINPUT; } if (GetCurrentState()->GetMode() == "GRAB_INPUT") { return GRABINPUT; } return REGULAR; } void mitk::DataInteractor::DataNodeChanged() { } diff --git a/Core/Code/Interactions/mitkDataInteractor.h b/Core/Code/Interactions/mitkDataInteractor.h index 94cd3b5d58..9fc9e8435e 100644 --- a/Core/Code/Interactions/mitkDataInteractor.h +++ b/Core/Code/Interactions/mitkDataInteractor.h @@ -1,100 +1,105 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKEVENTINTERACTOR_H_ #define MITKEVENTINTERACTOR_H_ #include "itkSmartPointer.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include #include "mitkEventStateMachine.h" #include namespace mitk { /** * \class DataInteractor * * \brief Base class from with interactors that handle DataNodes are to be derived. * * Base class from with interactors that handle DataNodes are to be derived. * Provides an interface that is relevant for the interactor to work together with the dispatcher. * To implement a new interactor overwrite the ConnectActionsAndFunctions to connect the actions. */ // Public 'cause it's also used by the mitk::Dispatcher enum ProcessEventMode { REGULAR = 0, GRABINPUT = 1, PREFERINPUT = 2, CONNECTEDMOUSEACTION = 3 // only used by mitk::Dispatcher }; class DataNode; class MITK_CORE_EXPORT DataInteractor: public EventStateMachine { public: typedef itk::SmartPointer NodeType; mitkClassMacro(DataInteractor, EventStateMachine) itkNewMacro(Self) /** * Set/Change the DataNode of the DataInteractor */ void SetDataNode(NodeType); /** * @brief Returns the mode the DataInteractor currently is in. See in mitkDispatcher the description of m_ProcessingMode for further details. */ - ProcessEventMode GetMode(); + ProcessEventMode GetMode() const; NodeType GetDataNode() const; int GetLayer() const; + // Predefined internal events/signals + static const std::string IntDeactivateMe; // = "DeactivateMe"; + static const std::string IntLeaveWidget; // = "LeaveWidget"; + static const std::string IntEnterWidget; // = "EnterWidget"; + protected: DataInteractor(); virtual ~DataInteractor(); /** * @brief Overwrite this function to connect actions from StateMachine description with functions. * * Following example shows how to connect the 'addpoint' action from the StateMachine XML description using the CONNECT_FUNCTION macro * with the AddPoint() function in the TestInteractor. * @code * void mitk::TestInteractor::ConnectActionsAndFunctions() { CONNECT_FUNCTION("addpoint", AddPoint); } * @endcode */ virtual void ConnectActionsAndFunctions(); /** \brief Is called when a DataNode is initially set or changed * To be implemented by sub-classes for initialization code which require a DataNode. * \note New DataInteractors usually are expected to have the focus, but this only works if they have the highest Layer, * since empty DataNodes have a layer of -1, the DataNode must be filled here in order to get a layer assigned. * \note Is also called when the DataNode is set to NULL. */ virtual void DataNodeChanged(); private: NodeType m_DataNode; }; } /* namespace mitk */ #endif /* MITKEVENTINTERACTOR_H_ */ diff --git a/Core/Code/Interactions/mitkDispatcher.cpp b/Core/Code/Interactions/mitkDispatcher.cpp index a90637e3d8..ba928ba780 100644 --- a/Core/Code/Interactions/mitkDispatcher.cpp +++ b/Core/Code/Interactions/mitkDispatcher.cpp @@ -1,230 +1,231 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkDispatcher.h" #include "mitkInteractionEvent.h" #include "mitkInternalEvent.h" // MicroServices #include "mitkGetModuleContext.h" #include "mitkModule.h" #include "mitkModuleRegistry.h" #include "mitkInteractionEventObserver.h" mitk::Dispatcher::Dispatcher() : m_ProcessingMode(REGULAR) { m_EventObserverTracker = new mitk::ServiceTracker(GetModuleContext()); m_EventObserverTracker->Open(); } void mitk::Dispatcher::AddDataInteractor(const DataNode* dataNode) { RemoveDataInteractor(dataNode); RemoveOrphanedInteractors(); DataInteractor::Pointer dataInteractor = dataNode->GetDataInteractor(); if (dataInteractor.IsNotNull()) { m_Interactors.push_back(dataInteractor); } } /* * Note: One DataInteractor can only have one DataNode and vice versa, * BUT the m_Interactors list may contain another DataInteractor that is still connected to this DataNode, * in this case we have to remove >1 DataInteractor. (Some special case of switching DataNodes between DataInteractors and registering a * DataNode to a DataStorage after assigning it to an DataInteractor) */ void mitk::Dispatcher::RemoveDataInteractor(const DataNode* dataNode) { for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();) { if ((*it)->GetDataNode() == dataNode) { it = m_Interactors.erase(it); } else { ++it; } } } size_t mitk::Dispatcher::GetNumberOfInteractors() { return m_Interactors.size(); } mitk::Dispatcher::~Dispatcher() { m_EventObserverTracker->Close(); delete m_EventObserverTracker; } bool mitk::Dispatcher::ProcessEvent(InteractionEvent* event) { InteractionEvent::Pointer p = event; //MITK_INFO << event->GetEventClass(); bool eventIsHandled = false; /* Filter out and handle Internal Events separately */ InternalEvent* internalEvent = dynamic_cast(event); if (internalEvent != NULL) { eventIsHandled = HandleInternalEvent(internalEvent); // InternalEvents that are handled are not sent to the listeners if (eventIsHandled) { return true; } } switch (m_ProcessingMode) { case CONNECTEDMOUSEACTION: // finished connected mouse action - if (p->GetEventClass() == "MouseReleaseEvent") + if (std::strcmp(p->GetNameOfClass(), "MouseReleaseEvent") == 0) { m_ProcessingMode = REGULAR; eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()); } // give event to selected interactor if (eventIsHandled == false) { eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()); } break; case GRABINPUT: eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()); SetEventProcessingMode(m_SelectedInteractor); break; case PREFERINPUT: if (m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()) == true) { SetEventProcessingMode(m_SelectedInteractor); eventIsHandled = true; } break; case REGULAR: break; } // Standard behavior. Is executed in STANDARD mode and PREFERINPUT mode, if preferred interactor rejects event. if (m_ProcessingMode == REGULAR || (m_ProcessingMode == PREFERINPUT && eventIsHandled == false)) { m_Interactors.sort(cmp()); // sorts interactors by layer (descending); for (std::list::iterator it = m_Interactors.begin(); it != m_Interactors.end(); ++it) { // explicit copy of pointer because HandleEvent function causes the m_Interactors list to be updated, // which in turn invalidates the iterator. DataInteractor::Pointer dataInteractor = *it; if (dataInteractor->HandleEvent(event, dataInteractor->GetDataNode())) { // if an event is handled several properties are checked, in order to determine the processing mode of the dispatcher SetEventProcessingMode(dataInteractor); - if (p->GetEventClass() == "MousePressEvent" && m_ProcessingMode == REGULAR) + if (std::strcmp(p->GetNameOfClass(), "MousePressEvent") == 0 && m_ProcessingMode == REGULAR) { m_SelectedInteractor = dataInteractor; m_ProcessingMode = CONNECTEDMOUSEACTION; } eventIsHandled = true; break; } } } /* Notify InteractionEventObserver */ std::list listEventObserver; m_EventObserverTracker->GetServiceReferences(listEventObserver); for (std::list::iterator it = listEventObserver.begin(); it != listEventObserver.end(); ++it) { InteractionEventObserver* interactionEventObserver = m_EventObserverTracker->GetService(*it); if (interactionEventObserver != NULL) { if (interactionEventObserver->IsEnabled()) { interactionEventObserver->Notify(event, eventIsHandled); } } } // Process event queue if (!m_QueuedEvents.empty()) { InteractionEvent::Pointer e = m_QueuedEvents.front(); m_QueuedEvents.pop_front(); ProcessEvent(e); } return eventIsHandled; } /* * Checks if DataNodes associated with DataInteractors point back to them. * If not remove the DataInteractors. (This can happen when s.o. tries to set DataNodes to multiple DataInteractors) */ void mitk::Dispatcher::RemoveOrphanedInteractors() { for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();) { DataNode::Pointer dn = (*it)->GetDataNode(); if (dn.IsNull()) { it = m_Interactors.erase(it); } else { DataInteractor::Pointer interactor = dn->GetDataInteractor(); if (interactor != it->GetPointer()) { it = m_Interactors.erase(it); } else { ++it; } } } } void mitk::Dispatcher::QueueEvent(InteractionEvent* event) { m_QueuedEvents.push_back(event); } void mitk::Dispatcher::SetEventProcessingMode(DataInteractor::Pointer dataInteractor) { m_ProcessingMode = dataInteractor->GetMode(); if (dataInteractor->GetMode() != REGULAR) { m_SelectedInteractor = dataInteractor; } } bool mitk::Dispatcher::HandleInternalEvent(InternalEvent* internalEvent) { - if (internalEvent->GetSignalName() == IntDeactivateMe && internalEvent->GetTargetInteractor() != NULL) + if (internalEvent->GetSignalName() == DataInteractor::IntDeactivateMe && + internalEvent->GetTargetInteractor() != NULL) { internalEvent->GetTargetInteractor()->GetDataNode()->SetDataInteractor(NULL); internalEvent->GetTargetInteractor()->SetDataNode(NULL); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } return false; } diff --git a/Core/Code/Interactions/mitkDisplayInteractor.cpp b/Core/Code/Interactions/mitkDisplayInteractor.cpp index dc0a4fb335..540731cd53 100644 --- a/Core/Code/Interactions/mitkDisplayInteractor.cpp +++ b/Core/Code/Interactions/mitkDisplayInteractor.cpp @@ -1,346 +1,346 @@ /*=================================================================== 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 "mitkDisplayInteractor.h" #include "mitkBaseRenderer.h" #include "mitkInteractionPositionEvent.h" #include "mitkPropertyList.h" #include // level window #include "mitkStandaloneDataStorage.h" #include "mitkNodePredicateDataType.h" #include "mitkLevelWindowProperty.h" #include "mitkLevelWindow.h" void mitk::DisplayInteractor::Notify(InteractionEvent* interactionEvent, bool isHandled) { // to use the state machine pattern, // the event is passed to the state machine interface to be handled if (!isHandled || m_AlwaysReact) { this->HandleEvent(interactionEvent, NULL); } } void mitk::DisplayInteractor::ConnectActionsAndFunctions() { CONNECT_FUNCTION("init", Init); CONNECT_FUNCTION("move", Move); CONNECT_FUNCTION("zoom", Zoom); CONNECT_FUNCTION("scroll", Scroll); CONNECT_FUNCTION("ScrollOneDown", ScrollOneDown); CONNECT_FUNCTION("ScrollOneUp", ScrollOneUp); CONNECT_FUNCTION("levelWindow", AdjustLevelWindow); } mitk::DisplayInteractor::DisplayInteractor() : m_IndexToSliceModifier(4),m_AutoRepeat(false), m_AlwaysReact(false), m_ZoomFactor(2) { m_StartDisplayCoordinate.Fill(0); m_LastDisplayCoordinate.Fill(0); m_CurrentDisplayCoordinate.Fill(0); } mitk::DisplayInteractor::~DisplayInteractor() { } bool mitk::DisplayInteractor::Init(StateMachineAction*, InteractionEvent* interactionEvent) { BaseRenderer* sender = interactionEvent->GetSender(); InteractionPositionEvent* positionEvent = dynamic_cast(interactionEvent); if (positionEvent == NULL) { - MITK_WARN<< "DisplayVectorInteractor cannot process the event: " << interactionEvent->GetEventClass(); + MITK_WARN<< "DisplayVectorInteractor cannot process the event: " << interactionEvent->GetNameOfClass(); return false; } Vector2D origin = sender->GetDisplayGeometry()->GetOriginInMM(); double scaleFactorMMPerDisplayUnit = sender->GetDisplayGeometry()->GetScaleFactorMMPerDisplayUnit(); m_StartDisplayCoordinate = positionEvent->GetPointerPositionOnScreen(); m_LastDisplayCoordinate = positionEvent->GetPointerPositionOnScreen(); m_CurrentDisplayCoordinate = positionEvent->GetPointerPositionOnScreen(); m_StartCoordinateInMM = mitk::Point2D( (origin + m_StartDisplayCoordinate.GetVectorFromOrigin() * scaleFactorMMPerDisplayUnit).GetDataPointer()); return true; } bool mitk::DisplayInteractor::Move(StateMachineAction*, InteractionEvent* interactionEvent) { BaseRenderer* sender = interactionEvent->GetSender(); InteractionPositionEvent* positionEvent = dynamic_cast(interactionEvent); if (positionEvent == NULL) { - MITK_WARN<< "DisplayVectorInteractor: cannot process the event in Move action: " << interactionEvent->GetEventClass(); + MITK_WARN<< "DisplayVectorInteractor: cannot process the event in Move action: " << interactionEvent->GetNameOfClass(); return false; } // perform translation sender->GetDisplayGeometry()->MoveBy((positionEvent->GetPointerPositionOnScreen() - m_LastDisplayCoordinate) * (-1.0)); sender->GetRenderingManager()->RequestUpdate(sender->GetRenderWindow()); m_LastDisplayCoordinate = positionEvent->GetPointerPositionOnScreen(); return true; } bool mitk::DisplayInteractor::Zoom(StateMachineAction*, InteractionEvent* interactionEvent) { const BaseRenderer::Pointer sender = interactionEvent->GetSender(); InteractionPositionEvent* positionEvent = dynamic_cast(interactionEvent); if (positionEvent == NULL) { - MITK_WARN<< "DisplayVectorInteractor cannot process the event: " << interactionEvent->GetEventClass(); + MITK_WARN<< "DisplayVectorInteractor cannot process the event: " << interactionEvent->GetNameOfClass(); return false; } float factor = 1.0; float distance = 0; if (m_ZoomDirection == "leftright") { distance = m_CurrentDisplayCoordinate[1] - m_LastDisplayCoordinate[1]; } else { distance = m_CurrentDisplayCoordinate[0] - m_LastDisplayCoordinate[0]; } // set zooming speed if (distance < 0.0) { factor = 1.0 / m_ZoomFactor; } else if (distance > 0.0) { factor = 1.0 * m_ZoomFactor; } sender->GetDisplayGeometry()->ZoomWithFixedWorldCoordinates(factor, m_StartDisplayCoordinate, m_StartCoordinateInMM); sender->GetRenderingManager()->RequestUpdate(sender->GetRenderWindow()); m_LastDisplayCoordinate = m_CurrentDisplayCoordinate; m_CurrentDisplayCoordinate = positionEvent->GetPointerPositionOnScreen(); return true; } bool mitk::DisplayInteractor::Scroll(StateMachineAction*, InteractionEvent* interactionEvent) { InteractionPositionEvent* positionEvent = dynamic_cast(interactionEvent); if (positionEvent == NULL) { - MITK_WARN<< "DisplayVectorInteractor::Scroll cannot process the event: " << interactionEvent->GetEventClass(); + MITK_WARN<< "DisplayVectorInteractor::Scroll cannot process the event: " << interactionEvent->GetNameOfClass(); return false; } mitk::SliceNavigationController::Pointer sliceNaviController = interactionEvent->GetSender()->GetSliceNavigationController(); if (sliceNaviController) { int delta = 0; // Scrolling direction if (m_ScrollDirection == "leftright") { delta = static_cast(m_LastDisplayCoordinate[1] - positionEvent->GetPointerPositionOnScreen()[1]); } else { delta = static_cast(m_LastDisplayCoordinate[0] - positionEvent->GetPointerPositionOnScreen()[0]); } // Set how many pixels the mouse has to be moved to scroll one slice // if we moved less than 'm_IndexToSliceModifier' pixels slice ONE slice only if (delta > 0 && delta < m_IndexToSliceModifier) { delta = m_IndexToSliceModifier; } else if (delta < 0 && delta > -m_IndexToSliceModifier) { delta = -m_IndexToSliceModifier; } delta /= m_IndexToSliceModifier; int newPos = sliceNaviController->GetSlice()->GetPos() + delta; // if auto repeat is on, start at first slice if you reach the last slice and vice versa int maxSlices = sliceNaviController->GetSlice()->GetSteps(); if (m_AutoRepeat) { while (newPos < 0) { newPos += maxSlices; } while (newPos >= maxSlices) { newPos -= maxSlices; } } else { // if the new slice is below 0 we still show slice 0 // due to the stepper using unsigned int we have to do this ourselves if (newPos < 1) { newPos = 0; } } // set the new position sliceNaviController->GetSlice()->SetPos(newPos); m_LastDisplayCoordinate = m_CurrentDisplayCoordinate; m_CurrentDisplayCoordinate = positionEvent->GetPointerPositionOnScreen(); } return true; } bool mitk::DisplayInteractor::ScrollOneDown(StateMachineAction*, InteractionEvent* interactionEvent) { mitk::SliceNavigationController::Pointer sliceNaviController = interactionEvent->GetSender()->GetSliceNavigationController(); if (!sliceNaviController->GetSliceLocked()) { mitk::Stepper* stepper = sliceNaviController->GetSlice(); if (stepper->GetSteps() <= 1) { stepper = sliceNaviController->GetTime(); } stepper->Next(); } return true; } bool mitk::DisplayInteractor::ScrollOneUp(StateMachineAction*, InteractionEvent* interactionEvent) { mitk::SliceNavigationController::Pointer sliceNaviController = interactionEvent->GetSender()->GetSliceNavigationController(); if (!sliceNaviController->GetSliceLocked()) { mitk::Stepper* stepper = sliceNaviController->GetSlice(); if (stepper->GetSteps() <= 1) { stepper = sliceNaviController->GetTime(); } stepper->Previous(); return true; } return false; } bool mitk::DisplayInteractor::AdjustLevelWindow(StateMachineAction*, InteractionEvent* interactionEvent) { BaseRenderer::Pointer sender = interactionEvent->GetSender(); InteractionPositionEvent* positionEvent = dynamic_cast(interactionEvent); if (positionEvent == NULL) { - MITK_WARN<< "DisplayVectorInteractor::Scroll cannot process the event: " << interactionEvent->GetEventClass(); + MITK_WARN<< "DisplayVectorInteractor::Scroll cannot process the event: " << interactionEvent->GetNameOfClass(); return false; } m_LastDisplayCoordinate = m_CurrentDisplayCoordinate; m_CurrentDisplayCoordinate = positionEvent->GetPointerPositionOnScreen(); // search for active image mitk::DataStorage::Pointer storage = sender->GetDataStorage(); mitk::DataNode::Pointer node = NULL; mitk::DataStorage::SetOfObjects::ConstPointer allImageNodes = storage->GetSubset(mitk::NodePredicateDataType::New("Image")); for (unsigned int i = 0; i < allImageNodes->size(); i++) { bool isActiveImage = false; bool propFound = allImageNodes->at(i)->GetBoolProperty("imageForLevelWindow", isActiveImage); if (propFound && isActiveImage) { node = allImageNodes->at(i); continue; } } if (node.IsNull()) { node = storage->GetNode(mitk::NodePredicateDataType::New("Image")); } if (node.IsNull()) { return false; } mitk::LevelWindow lv = mitk::LevelWindow(); node->GetLevelWindow(lv); ScalarType level = lv.GetLevel(); ScalarType window = lv.GetWindow(); // calculate adjustments from mouse movements level += (m_CurrentDisplayCoordinate[0] - m_LastDisplayCoordinate[0]) * static_cast(2); window += (m_CurrentDisplayCoordinate[1] - m_LastDisplayCoordinate[1]) * static_cast(2); lv.SetLevelWindow(level, window); dynamic_cast(node->GetProperty("levelwindow"))->SetLevelWindow(lv); sender->GetRenderingManager()->RequestUpdateAll(); return true; } void mitk::DisplayInteractor::ConfigurationChanged() { mitk::PropertyList::Pointer properties = GetAttributes(); // auto repeat std::string strAutoRepeat = ""; if (properties->GetStringProperty("autoRepeat", strAutoRepeat)) { if (strAutoRepeat == "true") { m_AutoRepeat = true; } else { m_AutoRepeat = false; } } // pixel movement for scrolling one slice std::string strPixelPerSlice = ""; if (properties->GetStringProperty("pixelPerSlice", strPixelPerSlice)) { m_IndexToSliceModifier = atoi(strPixelPerSlice.c_str()); } else { m_IndexToSliceModifier = 4; } // scroll direction if (!properties->GetStringProperty("zoomDirection", m_ScrollDirection)) { m_ScrollDirection = "updown"; } // zoom direction if (!properties->GetStringProperty("zoomDirection", m_ZoomDirection)) { m_ZoomDirection = "updown"; } // zoom factor std::string strZoomFactor = ""; properties->GetStringProperty("zoomFactor", strZoomFactor); m_ZoomFactor = .05; if (atoi(strZoomFactor.c_str()) > 0) { m_ZoomFactor = 1.0 + (atoi(strZoomFactor.c_str()) / 100.0); } // allwaysReact std::string strAlwaysReact = ""; if (properties->GetStringProperty("alwaysReact", strAlwaysReact)) { if (strAlwaysReact == "true") { m_AlwaysReact = true; } else { m_AlwaysReact = false; } } else { m_AlwaysReact = false; } } bool mitk::DisplayInteractor::FilterEvents(InteractionEvent* /*interactionEvent*/, DataNode* /*dataNode*/) { return true; } diff --git a/Core/Code/Interactions/mitkEventConfig.cpp b/Core/Code/Interactions/mitkEventConfig.cpp index 19c869a8c5..a7d87e81ee 100755 --- a/Core/Code/Interactions/mitkEventConfig.cpp +++ b/Core/Code/Interactions/mitkEventConfig.cpp @@ -1,196 +1,358 @@ /*=================================================================== 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 "mitkEventConfig.h" -#include -#include -#include -#include -#include + #include "mitkEventFactory.h" #include "mitkInteractionEvent.h" #include "mitkInternalEvent.h" #include "mitkInteractionKeyEvent.h" #include "mitkInteractionEventConst.h" + +// VTK +#include +#include + // us +#include "mitkGetModuleContext.h" #include "mitkModule.h" #include "mitkModuleResource.h" #include "mitkModuleResourceStream.h" -#include "mitkModuleRegistry.h" -namespace mitk +namespace mitk { + +class EventConfigXMLParser : public vtkXMLParser { - vtkStandardNewMacro(EventConfig); -} -mitk::EventConfig::EventConfig() : - m_Errors(false) +public: + + EventConfigXMLParser(EventConfigPrivate* d); + +protected: + + /** + * @brief Derived from XMLReader + **/ + void StartElement(const char* elementName, const char **atts); + + /** + * @brief Derived from XMLReader + **/ + void EndElement(const char* elementName); + + std::string ReadXMLStringAttribute(const std::string& name, const char** atts); + bool ReadXMLBooleanAttribute(const std::string& name, const char** atts); + +private: + + EventConfigPrivate* const d; + +}; + +struct EventConfigPrivate : public SharedData { - if (m_PropertyList.IsNull()) + + EventConfigPrivate(); + EventConfigPrivate(const EventConfigPrivate& other); + + struct EventMapping { - m_PropertyList = PropertyList::New(); - } + std::string variantName; + InteractionEvent::ConstPointer interactionEvent; + }; + + /** + * Checks if mapping with the same parameters already exists, if so, it is replaced, + * else the new mapping added + */ + void InsertMapping(const EventMapping& mapping); + + /** + * @brief List of all global properties of the config object. + */ + PropertyList::Pointer m_PropertyList; + + /** + * @brief Temporal list of all properties of a Event. Used to parse an Input-Event and collect all parameters between the two + * and tags. + */ + PropertyList::Pointer m_EventPropertyList; + + EventMapping m_CurrEventMapping; + + typedef std::list EventListType; + + /** + * Stores InteractionEvents and their corresponding VariantName + */ + EventListType m_EventList; + + bool m_Errors; // use member, because of inheritance from vtkXMLParser we can't return a success value for parsing the file. + + EventConfigXMLParser m_XmlParser; +}; + } -mitk::EventConfig::~EventConfig() + +mitk::EventConfigPrivate::EventConfigPrivate() + : m_PropertyList(PropertyList::New()) + , m_Errors(false) + , m_XmlParser(this) { + // Avoid VTK warning: Trying to delete object with non-zero reference count. + m_XmlParser.SetReferenceCount(0); } -void mitk::EventConfig::InsertMapping(EventMapping mapping) +mitk::EventConfigPrivate::EventConfigPrivate(const EventConfigPrivate& other) + : SharedData(other) + , m_PropertyList(other.m_PropertyList->Clone()) + , m_EventPropertyList(other.m_EventPropertyList->Clone()) + , m_CurrEventMapping(other.m_CurrEventMapping) + , m_EventList(other.m_EventList) + , m_Errors(other.m_Errors) + , m_XmlParser(this) +{ + // Avoid VTK warning: Trying to delete object with non-zero reference count. + m_XmlParser.SetReferenceCount(0); +} + +void mitk::EventConfigPrivate::InsertMapping(const EventMapping& mapping) { for (EventListType::iterator it = m_EventList.begin(); it != m_EventList.end(); ++it) { - if ((*it).interactionEvent->MatchesTemplate(mapping.interactionEvent)) + if (*(it->interactionEvent) == *mapping.interactionEvent) { //MITK_INFO<< "Configuration overwritten:" << (*it).variantName; m_EventList.erase(it); break; } } m_EventList.push_back(mapping); } -/** - * @brief Loads the xml file filename and generates the necessary instances. - **/ -bool mitk::EventConfig::LoadConfig(std::string fileName, std::string moduleName) +mitk::EventConfigXMLParser::EventConfigXMLParser(EventConfigPrivate *d) + : d(d) { - mitk::Module* module = mitk::ModuleRegistry::GetModule(moduleName); - mitk::ModuleResource resource = module->GetResource("Interactions/" + fileName); - if (!resource.IsValid()) - { - mitkThrow()<< ("Resource not valid. State machine pattern not found:" + fileName); - } - mitk::ModuleResourceStream stream(resource); - this->SetStream(&stream); - return this->Parse() && !m_Errors; } -void mitk::EventConfig::StartElement(const char* elementName, const char **atts) +void mitk::EventConfigXMLParser::StartElement(const char* elementName, const char **atts) { std::string name(elementName); - if (name == xmlTagConfigRoot) + if (name == InteractionEventConst::xmlTagConfigRoot) { // } - else if (name == xmlTagParam) + else if (name == InteractionEventConst::xmlTagParam) { - std::string name = ReadXMLStringAttribut(xmlParameterName, atts); - std::string value = ReadXMLStringAttribut(xmlParameterValue, atts); - m_PropertyList->SetStringProperty(name.c_str(), value.c_str()); + std::string name = ReadXMLStringAttribute(InteractionEventConst::xmlParameterName, atts); + std::string value = ReadXMLStringAttribute(InteractionEventConst::xmlParameterValue, atts); + d->m_PropertyList->SetStringProperty(name.c_str(), value.c_str()); } - else if (name == xmlTagEventVariant) + else if (name == InteractionEventConst::xmlTagEventVariant) { - std::string eventClass = ReadXMLStringAttribut(xmlParameterEventClass, atts); - std::string eventVariant = ReadXMLStringAttribut(xmlParameterName, atts); + std::string eventClass = ReadXMLStringAttribute(InteractionEventConst::xmlParameterEventClass, atts); + std::string eventVariant = ReadXMLStringAttribute(InteractionEventConst::xmlParameterName, atts); // New list in which all parameters are stored that are given within the tag - m_EventPropertyList = PropertyList::New(); - m_EventPropertyList->SetStringProperty(xmlParameterEventClass.c_str(), eventClass.c_str()); - m_EventPropertyList->SetStringProperty(xmlParameterEventVariant.c_str(), eventVariant.c_str()); - m_CurrEventMapping.variantName = eventVariant; + d->m_EventPropertyList = PropertyList::New(); + d->m_EventPropertyList->SetStringProperty(InteractionEventConst::xmlParameterEventClass.c_str(), eventClass.c_str()); + d->m_EventPropertyList->SetStringProperty(InteractionEventConst::xmlParameterEventVariant.c_str(), eventVariant.c_str()); + d->m_CurrEventMapping.variantName = eventVariant; } - else if (name == xmlTagAttribute) + else if (name == InteractionEventConst::xmlTagAttribute) { // Attributes that describe an Input Event, such as which MouseButton triggered the event,or which modifier keys are pressed - std::string name = ReadXMLStringAttribut(xmlParameterName, atts); - std::string value = ReadXMLStringAttribut(xmlParameterValue, atts); - m_EventPropertyList->SetStringProperty(name.c_str(), value.c_str()); + std::string name = ReadXMLStringAttribute(InteractionEventConst::xmlParameterName, atts); + std::string value = ReadXMLStringAttribute(InteractionEventConst::xmlParameterValue, atts); + d->m_EventPropertyList->SetStringProperty(name.c_str(), value.c_str()); } } -void mitk::EventConfig::EndElement(const char* elementName) +void mitk::EventConfigXMLParser::EndElement(const char* elementName) { std::string name(elementName); // At end of input section, all necessary infos are collected to created an interaction event. - if (name == xmlTagEventVariant) + if (name == InteractionEventConst::xmlTagEventVariant) { - InteractionEvent::Pointer event = EventFactory::CreateEvent(m_EventPropertyList); + InteractionEvent::Pointer event = EventFactory::CreateEvent(d->m_EventPropertyList); if (event.IsNotNull()) { - m_CurrEventMapping.interactionEvent = event; - InsertMapping(m_CurrEventMapping); + d->m_CurrEventMapping.interactionEvent = event; + d->InsertMapping(d->m_CurrEventMapping); } else { MITK_WARN<< "EventConfig: Unknown Event-Type in config. Entry skipped: " << name; } } } -std::string mitk::EventConfig::ReadXMLStringAttribut(std::string name, const char** atts) +std::string mitk::EventConfigXMLParser::ReadXMLStringAttribute(const std::string& name, const char** atts) { if (atts) { const char** attsIter = atts; while (*attsIter) { if (name == *attsIter) { attsIter++; return *attsIter; } attsIter += 2; } } return std::string(); } +bool mitk::EventConfigXMLParser::ReadXMLBooleanAttribute(const std::string& name, const char** atts) +{ + std::string s = ReadXMLStringAttribute(name, atts); + std::transform(s.begin(), s.end(), s.begin(), ::toupper); + + return s == "TRUE"; +} + +mitk::EventConfig::EventConfig() + : d(new EventConfigPrivate) +{ +} + +mitk::EventConfig::EventConfig(const EventConfig &other) + : d(other.d) +{ +} + +mitk::EventConfig::EventConfig(const std::string& filename, const Module* module) + : d(new EventConfigPrivate) +{ + if (module == NULL) + { + module = GetModuleContext()->GetModule(); + } + mitk::ModuleResource resource = module->GetResource("Interactions/" + filename); + if (!resource.IsValid()) + { + MITK_ERROR << "Resource not valid. State machine pattern in module " << module->GetName() + << " not found: /Interactions/" << filename; + return; + } + + EventConfig newConfig; + mitk::ModuleResourceStream stream(resource); + newConfig.d->m_XmlParser.SetStream(&stream); + bool success = newConfig.d->m_XmlParser.Parse() && !newConfig.d->m_Errors; + if (success) + { + *this = newConfig; + } +} + +mitk::EventConfig& mitk::EventConfig::operator =(const mitk::EventConfig& other) +{ + d = other.d; + return *this; +} + +mitk::EventConfig::~EventConfig() +{ +} + +bool mitk::EventConfig::IsValid() const +{ + return !d->m_EventList.empty(); +} + +bool mitk::EventConfig::AddConfig(const std::string& fileName, const Module* module) +{ + if (module == NULL) + { + module = GetModuleContext()->GetModule(); + } + mitk::ModuleResource resource = module->GetResource("Interactions/" + fileName); + if (!resource.IsValid()) + { + MITK_ERROR << "Resource not valid. State machine pattern in module " << module->GetName() + << " not found: /Interactions/" << fileName; + return false; + } + + EventConfig newConfig(*this); + mitk::ModuleResourceStream stream(resource); + newConfig.d->m_XmlParser.SetStream(&stream); + bool success = newConfig.d->m_XmlParser.Parse() && !newConfig.d->m_Errors; + if (success) + { + *this = newConfig; + } + return success; +} + +bool mitk::EventConfig::AddConfig(const EventConfig& config) +{ + if (!config.IsValid()) return false; + + d->m_PropertyList->ConcatenatePropertyList(config.d->m_PropertyList->Clone(), true); + d->m_EventPropertyList = config.d->m_EventPropertyList->Clone(); + d->m_CurrEventMapping = config.d->m_CurrEventMapping; + d->InsertMapping(config.d->m_CurrEventMapping); + return true; +} + mitk::PropertyList::Pointer mitk::EventConfig::GetAttributes() const { - return m_PropertyList; + return d->m_PropertyList; } -std::string mitk::EventConfig::GetMappedEvent(InteractionEvent::Pointer interactionEvent) +std::string mitk::EventConfig::GetMappedEvent(const EventType& interactionEvent) const { // internal events are excluded from mapping - if (interactionEvent->GetEventClass() == "InternalEvent") + if (std::strcmp(interactionEvent->GetNameOfClass(), "InternalEvent") == 0) { InternalEvent* internalEvent = dynamic_cast(interactionEvent.GetPointer()); return internalEvent->GetSignalName(); } - for (EventListType::iterator it = m_EventList.begin(); it != m_EventList.end(); ++it) + for (EventConfigPrivate::EventListType::const_iterator it = d->m_EventList.begin(); + it != d->m_EventList.end(); ++it) { - if ((*it).interactionEvent->MatchesTemplate(interactionEvent)) + if (*(it->interactionEvent) == *interactionEvent) { return (*it).variantName; } } // if this part is reached, no mapping has been found, // so here we handle key events and map a key event to the string "Std" + letter/code // so "A" will be returned as "StdA" - if (interactionEvent->GetEventClass() == "KeyEvent") + if (std::strcmp(interactionEvent->GetNameOfClass(), "InteractionKeyEvent") == 0) { InteractionKeyEvent* keyEvent = dynamic_cast(interactionEvent.GetPointer()); return ("Std" + keyEvent->GetKey()); } return ""; } void mitk::EventConfig::ClearConfig() { - m_EventList.clear(); -} - -bool mitk::EventConfig::ReadXMLBooleanAttribut(std::string name, const char** atts) -{ - std::string s = ReadXMLStringAttribut(name, atts); - std::transform(s.begin(), s.end(), s.begin(), ::toupper); - - return s == "TRUE"; + d->m_PropertyList->Clear(); + d->m_EventPropertyList->Clear(); + d->m_CurrEventMapping.variantName.clear(); + d->m_CurrEventMapping.interactionEvent = NULL; + d->m_EventList.clear(); + d->m_Errors = false; } diff --git a/Core/Code/Interactions/mitkEventConfig.h b/Core/Code/Interactions/mitkEventConfig.h index 2f41a6640d..a6d8339c79 100755 --- a/Core/Code/Interactions/mitkEventConfig.h +++ b/Core/Code/Interactions/mitkEventConfig.h @@ -1,144 +1,138 @@ /*=================================================================== 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 mitkStateMachineConfig_h #define mitkStateMachineConfig_h -#include -#include -#include "mitkCommon.h" #include -#include -#include + +#include "mitkSharedData.h" +#include "mitkPropertyList.h" + +#include "itkSmartPointer.h" namespace mitk { class InteractionEvent; - - class EventConfigReader: public vtkXMLParser - { - public: - - private: - }; + class Module; + struct EventConfigPrivate; /** * \class EventConfig * \brief Configuration Object for Statemachines. * * Reads given config file, which translates specific user inputs (InteractionEvents) into EventVariants that can be processed * by the StateMachine. * Refer to \ref ConfigFileDescriptionSection . * * @ingroup Interaction **/ - - class EventConfig: public vtkXMLParser + class MITK_CORE_EXPORT EventConfig { - public: - - static EventConfig *New(); - vtkTypeMacro(EventConfig,vtkXMLParser) + public: typedef itk::SmartPointer EventType; /** - * @brief Loads XML resource + * @brief Constructs an invalid EventConfig object. * - * Loads a XML resource file in the given module context. - * The files have to be placed in the Resources/Interaction folder of their respective module. - **/ - bool LoadConfig(std::string fileName, std::string moduleName = "Mitk"); - - void ClearConfig(); - /** - * Returns a PropertyList that contains the properties set in the configuration file. - * All properties are stored as strings. + * Call LoadConfig to create a valid configuration object. */ - PropertyList::Pointer GetAttributes() const; + EventConfig(); + EventConfig(const EventConfig& other); /** - * Checks if the config object has a definition for the given event. If it has, the corresponding variant name is returned, else - * an empty string is returned. - * \note mitk::InternalEvents are handled differently. Their signal name is returned as event variant. So there is no need - * to configure them in a config file. - * \note mitk::InteractionKeys may have a defined event variant, if this is the case, this function returns it. If no - * such definition is found key events are mapped to Std + Key , so an 'A' will be return as 'StdA' . + * @brief Construct an EventConfig object based on a XML configuration file. + * + * Uses the specified resource file containing an XML event configuration to + * construct a EventConfig object. If the resource is invalid, the created + * EventConfig object will also be invalid. + * + * @param filename The resource name relative to the Interactions resource folder. + * @param module */ - std::string GetMappedEvent(EventType interactionEvent); + EventConfig(const std::string& filename, const Module* module = NULL); - protected: + EventConfig& operator=(const EventConfig& other); - EventConfig(); - virtual ~EventConfig(); + ~EventConfig(); /** - * @brief Derived from XMLReader - **/ - void StartElement(const char* elementName, const char **atts); - /** - * @brief Derived from XMLReader - **/ - void EndElement(const char* elementName); + * @brief Checks wether this EventConfig object is valid. + * @return Returns \c true if a configuration was successfully loaded, \c false otherwise. + */ + bool IsValid() const; - private: /** - * @brief Derived from XMLReader - **/ - std::string ReadXMLStringAttribut(std::string name, const char** atts); - /** - * @brief Derived from XMLReader - **/ - bool ReadXMLBooleanAttribut(std::string name, const char** atts); + * @brief This method \e extends this configuration. + * + * The configuration from the resource provided is loaded and only the ones conflicting are replaced by the new one. + * This way several configuration files can be combined. + * + * @see AddConfig(const EventConfig&) + * @see InteractionEventHandler::AddEventConfig(const std::string&, const Module*) + * + * @param filename The resource name relative to the Interactions resource folder. + * @param module The module containing the resource. Defaults to the Mitk module. + * @return \c true if the configuration was successfully added, \c false otherwise. + */ + bool AddConfig(const std::string& filename, const Module* module = NULL); /** - * @brief List of all global properties of the config object. + * @brief This method \e extends this configuration. + * The configuration from the EventConfig object is loaded and only the ones conflicting are replaced by the new one. + * This way several configurations can be combined. + * + * @see AddConfig(const std::string&, const Module*) + * @see InteractionEventHandler::AddEventConfig(const EventConfig&) + * + * @param config The EventConfig object whose configuration should be added. + * @return \c true if the configuration was successfully added, \c false otherwise. */ - PropertyList::Pointer m_PropertyList; + bool AddConfig(const EventConfig& config); /** - * @brief Temporal list of all properties of a Event. Used to parse an Input-Event and collect all parameters between the two - * and tags. + * @brief Reset this EventConfig object, rendering it invalid. */ - PropertyList::Pointer m_EventPropertyList; - - struct EventMapping - { - std::string variantName; - EventType interactionEvent; - }; + void ClearConfig(); /** - * Checks if mapping with the same parameters already exists, if so, it is replaced, - * else the new mapping added + * Returns a PropertyList that contains the properties set in the configuration file. + * All properties are stored as strings. */ - void InsertMapping(EventMapping mapping); - - typedef std::list EventListType; - EventMapping m_CurrEventMapping; + PropertyList::Pointer GetAttributes() const; /** - * Stores InteractionEvents and their corresponding VariantName + * Checks if the config object has a definition for the given event. If it has, the corresponding variant name is returned, else + * an empty string is returned. + * \note mitk::InternalEvent is handled differently. Their signal name is returned as event variant. So there is no need + * to configure them in a config file. + * \note mitk::InteractionKeyEvent may have a defined event variant, if this is the case, this function returns it. If no + * such definition is found key events are mapped to Std + Key , so an 'A' will be return as 'StdA' . */ - EventListType m_EventList; - bool m_Errors; // use member, because of inheritance from vtkXMLParser we can't return a success value for parsing the file. + std::string GetMappedEvent(const EventType& interactionEvent) const; + + private: + + SharedDataPointer d; + }; } // namespace mitk #endif /* mitkStateMachineConfig_h */ diff --git a/Core/Code/Interactions/mitkEventFactory.cpp b/Core/Code/Interactions/mitkEventFactory.cpp index 9fcc7d3078..ad26f7e4dc 100755 --- a/Core/Code/Interactions/mitkEventFactory.cpp +++ b/Core/Code/Interactions/mitkEventFactory.cpp @@ -1,224 +1,224 @@ /*=================================================================== 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 "mitkEventFactory.h" #include #include #include #include #include #include #include #include #include #include #include namespace { std::vector &split(const std::string &s, char delim, std::vector &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector split(const std::string &s, char delim) { std::vector < std::string > elems; return split(s, delim, elems); } } mitk::InteractionEvent::Pointer mitk::EventFactory::CreateEvent(PropertyList::Pointer list) { // std::string eventClass, eventVariant; - list->GetStringProperty(xmlParameterEventClass.c_str(), eventClass); - list->GetStringProperty(xmlParameterEventVariant.c_str(), eventVariant); + list->GetStringProperty(InteractionEventConst::xmlParameterEventClass.c_str(), eventClass); + list->GetStringProperty(InteractionEventConst::xmlParameterEventVariant.c_str(), eventVariant); // Query all possible attributes, if they are not present, set their default values. // Position Events & Key Events std::string strModifiers; - ModifierKeys modifiers = NoKey; + InteractionEvent::ModifierKeys modifiers = InteractionEvent::NoKey; std::string strEventButton; - MouseButtons eventButton = NoButton; + InteractionEvent::MouseButtons eventButton = InteractionEvent::NoButton; std::string strButtonState; - MouseButtons buttonState = NoButton; + InteractionEvent::MouseButtons buttonState = InteractionEvent::NoButton; std::string strKey; std::string key; std::string strWheelDelta; int wheelDelta; std::string strSignalName = ""; Point2D pos; pos.Fill(0); // Parse modifier information - if (list->GetStringProperty(xmlEventPropertyModifier.c_str(), strModifiers)) + if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyModifier.c_str(), strModifiers)) { std::vector mods = split(strModifiers, ','); for (std::vector::iterator it = mods.begin(); it != mods.end(); ++it) { std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper); if (*it == "CTRL") { - modifiers = modifiers | ControlKey; + modifiers = modifiers | InteractionEvent::ControlKey; } else if (*it == "ALT") { - modifiers = modifiers | AltKey; + modifiers = modifiers | InteractionEvent::AltKey; } else if (*it == "SHIFT") { - modifiers = modifiers | ShiftKey; + modifiers = modifiers | InteractionEvent::ShiftKey; } else { MITK_WARN<< "mitkEventFactory: Invalid event modifier in config file :" << (*it); } } } // Set EventButton - if (list->GetStringProperty(xmlEventPropertyEventButton.c_str(), strEventButton)) + if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyEventButton.c_str(), strEventButton)) { std::transform(strEventButton.begin(), strEventButton.end(), strEventButton.begin(), ::toupper); if (strEventButton == "MIDDLEMOUSEBUTTON") { - eventButton = MiddleMouseButton; + eventButton = InteractionEvent::MiddleMouseButton; } else if (strEventButton == "LEFTMOUSEBUTTON") { - eventButton = LeftMouseButton; + eventButton = InteractionEvent::LeftMouseButton; } else if (strEventButton == "RIGHTMOUSEBUTTON") { - eventButton = RightMouseButton; + eventButton = InteractionEvent::RightMouseButton; } else { MITK_WARN<< "mitkEventFactory: Invalid event button in config file: " << strEventButton; } } // Parse ButtonStates - if (list->GetStringProperty(xmlEventPropertyButtonState.c_str(), strButtonState)) + if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyButtonState.c_str(), strButtonState)) { std::vector mods = split(strButtonState, ','); for (std::vector::iterator it = mods.begin(); it != mods.end(); ++it) { std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper); if (*it == "MIDDLEMOUSEBUTTON") { - buttonState = buttonState | MiddleMouseButton; + buttonState = buttonState | InteractionEvent::MiddleMouseButton; } else if (*it == "LEFTMOUSEBUTTON") { - buttonState = buttonState | LeftMouseButton; + buttonState = buttonState | InteractionEvent::LeftMouseButton; } else if (*it == "RIGHTMOUSEBUTTON") { - buttonState = buttonState | RightMouseButton; + buttonState = buttonState | InteractionEvent::RightMouseButton; } else { MITK_WARN<< "mitkEventFactory: Invalid event buttonstate in config file:" << (*it); } } } // Key - if (!list->GetStringProperty(xmlEventPropertyKey.c_str(), strKey)) + if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyKey.c_str(), strKey)) { key = ""; } else { key = strKey; } // WheelDelta - if (!list->GetStringProperty(xmlEventPropertyScrollDirection.c_str(), strWheelDelta)) + if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyScrollDirection.c_str(), strWheelDelta)) { wheelDelta = 0; } else { std::transform(strWheelDelta.begin(), strWheelDelta.end(), strWheelDelta.begin(), ::toupper); if (strWheelDelta == "DOWN") { wheelDelta = -1; } else { wheelDelta = 1; } } // Internal Signals Name - list->GetStringProperty(xmlEventPropertySignalName.c_str(), strSignalName); + list->GetStringProperty(InteractionEventConst::xmlEventPropertySignalName.c_str(), strSignalName); /* * Here the objects are created */ mitk::InteractionEvent::Pointer event; std::transform(eventClass.begin(), eventClass.end(), eventClass.begin(), ::toupper); if (eventClass == "MOUSEPRESSEVENT") { // buttonstates incorporate the event button (as in Qt) buttonState = buttonState | eventButton; event = MousePressEvent::New(NULL, pos, buttonState, modifiers, eventButton); } else if (eventClass == "MOUSEMOVEEVENT") { event = MouseMoveEvent::New(NULL, pos, buttonState, modifiers); } else if (eventClass == "MOUSERELEASEEVENT") { event = MouseReleaseEvent::New(NULL, pos, buttonState, modifiers, eventButton); } - else if (eventClass == "KEYEVENT") + else if (eventClass == "INTERACTIONKEYEVENT") { event = InteractionKeyEvent::New(NULL, key, modifiers); } else if (eventClass == "MOUSEWHEELEVENT") { event = MouseWheelEvent::New(NULL, pos, buttonState, modifiers, wheelDelta); } - else if (eventClass == "POSITIONEVENT") + else if (eventClass == "INTERACTIONPOSITIONEVENT") { - event = InteractionPositionEvent::New(NULL, pos, "PositionEvent"); + event = InteractionPositionEvent::New(NULL, pos); } else if (eventClass == "INTERNALEVENT") { event = InternalEvent::New(NULL, NULL, strSignalName); } else if (eventClass == "INTERACTIONEVENT") { - event = InteractionEvent::New(NULL, strSignalName); + event = InteractionEvent::New(NULL); } if (event.IsNull()) { MITK_WARN<< "Event couldn't be constructed. Please check your StateMachine patterns and config files\n for the following event class, which is not valid: " << eventClass; return NULL; } return event; } diff --git a/Core/Code/Interactions/mitkEventMapper.cpp b/Core/Code/Interactions/mitkEventMapper.cpp index 82db98a890..bc3ff68433 100644 --- a/Core/Code/Interactions/mitkEventMapper.cpp +++ b/Core/Code/Interactions/mitkEventMapper.cpp @@ -1,706 +1,706 @@ /*=================================================================== 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. ===================================================================*/ /** * EventMapping: * This class maps the Events, usually given by the OS or here by QT, to a MITK internal EventId. * It loads all information from the xml-file (possible, understandable Events with the mitkEventID). * If an event appears, the method MapEvent is called with the event params. * This Method looks up the event params, and tries to find an mitkEventId to it. * If yes, then sends the event and the found ID to the globalStateMachine, which handles all * further operations of that event. * */ #include "mitkEventMapper.h" #include "mitkInteractionConst.h" #include "mitkStateEvent.h" #include "mitkOperationEvent.h" #include "mitkGlobalInteraction.h" #include #include "mitkStandardFileLocations.h" //#include #include "mitkConfig.h" #include "mitkCoreObjectFactory.h" #include #include #include #include // us #include "mitkModule.h" #include "mitkModuleResource.h" #include "mitkModuleResourceStream.h" #include "mitkModuleRegistry.h" #include #include namespace mitk { vtkStandardNewMacro(EventMapper); } #ifdef MBI_INTERNAL_CONFERENCE #include #include #include #include #include #endif //MBI_INTERNAL_CONFERENCE //XML Event const std::string mitk::EventMapper::STYLE = "STYLE"; const std::string mitk::EventMapper::NAME = "NAME"; const std::string mitk::EventMapper::ID = "ID"; const std::string mitk::EventMapper::TYPE = "TYPE"; const std::string mitk::EventMapper::BUTTON = "BUTTON"; const std::string mitk::EventMapper::BUTTONSTATE = "BUTTONSTATE"; const std::string mitk::EventMapper::KEY = "KEY"; const std::string mitk::EventMapper::EVENTS = "events"; const std::string mitk::EventMapper::EVENT = "event"; mitk::EventMapper::EventDescriptionVec mitk::EventMapper::m_EventDescriptions; std::string mitk::EventMapper::m_XmlFileName; mitk::StateEvent mitk::EventMapper::m_StateEvent; std::string mitk::EventMapper::m_StyleName; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; mitk::EventMapper::EventMapper() { //map with string to key for mapping string from xml-file to int m_EventConstMap["Type_None"] = mitk::Type_None; // invalid event m_EventConstMap["Type_Timer"] = mitk::Type_Timer; // timer event m_EventConstMap["Type_MouseButtonPress"] = mitk::Type_MouseButtonPress; // mouse button pressed m_EventConstMap["Type_MouseButtonRelease"] = mitk::Type_MouseButtonRelease; // mouse button released m_EventConstMap["Type_MouseButtonDblClick"] = mitk::Type_MouseButtonDblClick; // mouse button double click m_EventConstMap["Type_MouseMove"] = mitk::Type_MouseMove; // mouse move m_EventConstMap["Type_KeyPress"] = mitk::Type_KeyPress; // key pressed m_EventConstMap["Type_KeyRelease"] = mitk::Type_KeyRelease; // key released m_EventConstMap["Type_FocusIn"] = 8; // keyboard focus received m_EventConstMap["Type_FocusOut"] = 9; // keyboard focus lost m_EventConstMap["Type_Enter"] = 10; // mouse enters widget m_EventConstMap["Type_Leave"] = 11; // mouse leaves widget m_EventConstMap["Type_Paint"] = 12; // paint widget m_EventConstMap["Type_Move"] = 13; // move widget m_EventConstMap["Type_Resize"] = 14; // resize widget m_EventConstMap["Type_Create"] = 15; // after object creation m_EventConstMap["Type_Destroy"] = 16; // during object destruction m_EventConstMap["Type_Show"] = 17; // widget is shown m_EventConstMap["Type_Hide"] = 18; // widget is hidden m_EventConstMap["Type_Close"] = 19; // request to close widget m_EventConstMap["Type_Quit"] = 20; // request to quit application m_EventConstMap["Type_Reparent"] = 21; // widget has been reparented m_EventConstMap["Type_ShowMinimized"] = 22; // widget is shown minimized m_EventConstMap["Type_ShowNormal"] = 23; // widget is shown normal m_EventConstMap["Type_WindowActivate"] = 24; // window was activated m_EventConstMap["Type_WindowDeactivate"] = 25; // window was deactivated m_EventConstMap["Type_ShowToParent"] = 26; // widget is shown to parent m_EventConstMap["Type_HideToParent"] = 27; // widget is hidden to parent m_EventConstMap["Type_ShowMaximized"] = 28; // widget is shown maximized m_EventConstMap["Type_ShowFullScreen"] = 29; // widget is shown full-screen m_EventConstMap["Type_Accel"] = 30; // accelerator event m_EventConstMap["Type_Wheel"] = 31; // wheel event m_EventConstMap["Type_AccelAvailable"] = 32; // accelerator available event m_EventConstMap["Type_CaptionChange"] = 33; // caption changed m_EventConstMap["Type_IconChange"] = 34; // icon changed m_EventConstMap["Type_ParentFontChange"] = 35; // parent font changed m_EventConstMap["Type_ApplicationFontChange"] = 36;// application font changed m_EventConstMap["Type_ParentPaletteChange"] = 37; // parent palette changed m_EventConstMap["Type_ApplicationPaletteChange"] = 38;// application palette changed m_EventConstMap["Type_PaletteChange"] = 39; // widget palette changed m_EventConstMap["Type_Clipboard"] = 40; // internal clipboard event m_EventConstMap["Type_Speech"] = 42; // reserved for speech input m_EventConstMap["Type_SockAct"] = 50; // socket activation m_EventConstMap["Type_AccelOverride"] = 51; // accelerator override event m_EventConstMap["Type_DeferredDelete"] = 52; // deferred delete event m_EventConstMap["Type_DragEnter"] = 60; // drag moves into widget m_EventConstMap["Type_DragMove"] = 61; // drag moves in widget m_EventConstMap["Type_DragLeave"] = 62; // drag leaves or is cancelled m_EventConstMap["Type_Drop"] = 63; // actual drop m_EventConstMap["Type_DragResponse"] = 64; // drag accepted/rejected m_EventConstMap["Type_ChildInserted"] = 70; // new child widget m_EventConstMap["Type_ChildRemoved"] = 71; // deleted child widget m_EventConstMap["Type_LayoutHint"] = 72; // child min/max size changed m_EventConstMap["Type_ShowWindowRequest"] = 73; // widget's window should be mapped m_EventConstMap["Type_ActivateControl"] = 80; // ActiveX activation m_EventConstMap["Type_DeactivateControl"] = 81; // ActiveX deactivation m_EventConstMap["Type_ContextMenu"] = 82; // context popup menu m_EventConstMap["Type_IMStart"] = 83; // input method composition start m_EventConstMap["Type_IMCompose"] = 84; // input method composition m_EventConstMap["Type_IMEnd"] = 85; // input method composition end m_EventConstMap["Type_Accessibility"] = 86; // accessibility information is requested m_EventConstMap["Type_TabletMove"] = 87; // Wacom tablet event m_EventConstMap["Type_LocaleChange"] = 88; // the system locale changed m_EventConstMap["Type_LanguageChange"] = 89; // the application language changed m_EventConstMap["Type_LayoutDirectionChange"] = 90; // the layout direction changed m_EventConstMap["Type_Style"] = 91; // internal style event m_EventConstMap["Type_TabletPress"] = 92; // tablet press m_EventConstMap["Type_TabletRelease"] = 93; // tablet release // apparently not necessary, since the IDs can be assigned earlier (in the AddOns after they are generated in the driver) //m_EventConstMap["Type_TDMouseInput"] = mitk::Type_TDMouseInput; // 3D mouse input occured m_EventConstMap["Type_User"] = 1000; // first user event id m_EventConstMap["Type_MaxUser"] = 65535; // last user event id //ButtonState m_EventConstMap["BS_NoButton"] = mitk::BS_NoButton;//0x0000 m_EventConstMap["BS_LeftButton"] = mitk::BS_LeftButton;//0x0001 m_EventConstMap["BS_RightButton"] = mitk::BS_RightButton;//0x0002 m_EventConstMap["BS_MidButton"] = mitk::BS_MidButton;//0x0004 m_EventConstMap["BS_MouseButtonMask"] = mitk::BS_MouseButtonMask;//0x0007 m_EventConstMap["BS_ShiftButton"] = mitk::BS_ShiftButton;//0x0008 m_EventConstMap["BS_ControlButton"] = mitk::BS_ControlButton;//0x0010 m_EventConstMap["BS_AltButton"] = mitk::BS_AltButton;//0x0020 m_EventConstMap["BS_KeyButtonMask"] = mitk::BS_KeyButtonMask;//0x0038 m_EventConstMap["BS_Keypad"] = mitk::BS_Keypad;//0x4000 //Modifier m_EventConstMap["Mod_SHIFT"] = 0x00200000; m_EventConstMap["Mod_CTRL"] = 0x00400000; m_EventConstMap["Mod_ALT"] = 0x00800000; m_EventConstMap["Mod_MODIFIER_MASK"] = 0x00e00000; m_EventConstMap["Mod_UNICODE_ACCEL"] = 0x10000000; m_EventConstMap["Mod_ASCII_ACCEL"] = 0x10000000; //Key m_EventConstMap["Key_Escape"] = 0x1000; m_EventConstMap["Key_Tab"] = 0x1001; m_EventConstMap["Key_Backtab"] = 0x1002; m_EventConstMap["Key_BackTab"] = 0x1002; m_EventConstMap["Key_Backspace"] = 0x1003; m_EventConstMap["Key_BackSpace"] = 0x1003; m_EventConstMap["Key_Return"] = 0x1004; m_EventConstMap["Key_Enter"] = 0x1005; m_EventConstMap["Key_Insert"] = 0x1006; m_EventConstMap["Key_Delete"] = 0x1007; m_EventConstMap["Key_Pause"] = 0x1008; m_EventConstMap["Key_Print"] = 0x1009; m_EventConstMap["Key_SysReq"] = 0x100a; m_EventConstMap["Key_Home"] = 0x1010; m_EventConstMap["Key_End"] = 0x1011; m_EventConstMap["Key_Left"] = 0x1012; m_EventConstMap["Key_Up"] = 0x1013; m_EventConstMap["Key_Right"] = 0x1014; m_EventConstMap["Key_Down"] = 0x1015; m_EventConstMap["Key_Prior"] = 0x1016; m_EventConstMap["Key_PageUp"] = 0x1016; m_EventConstMap["Key_Next"] = 0x1017; m_EventConstMap["Key_PageDown"] = 0x1017; m_EventConstMap["Key_Shift"] = 0x1020; m_EventConstMap["Key_Control"] = 0x1021; m_EventConstMap["Key_Meta"] = 0x1022; m_EventConstMap["Key_Alt"] = 0x1023; m_EventConstMap["Key_CapsLock"] = 0x1024; m_EventConstMap["Key_NumLock"] = 0x1025; m_EventConstMap["Key_ScrollLock"] = 0x1026; m_EventConstMap["Key_F1"] = 0x1030; m_EventConstMap["Key_F2"] = 0x1031; m_EventConstMap["Key_F3"] = 0x1032; m_EventConstMap["Key_F4"] = 0x1033; m_EventConstMap["Key_F5"] = 0x1034; m_EventConstMap["Key_F6"] = 0x1035; m_EventConstMap["Key_F7"] = 0x1036; m_EventConstMap["Key_F8"] = 0x1037; m_EventConstMap["Key_F9"] = 0x1038; m_EventConstMap["Key_F10"] = 0x1039; m_EventConstMap["Key_F11"] = 0x103a; m_EventConstMap["Key_F12"] = 0x103b; m_EventConstMap["Key_F13"] = 0x103c; m_EventConstMap["Key_F14"] = 0x103d; m_EventConstMap["Key_F15"] = 0x103e; m_EventConstMap["Key_F16"] = 0x103f; m_EventConstMap["Key_F17"] = 0x1040; m_EventConstMap["Key_F18"] = 0x1041; m_EventConstMap["Key_F19"] = 0x1042; m_EventConstMap["Key_F20"] = 0x1043; m_EventConstMap["Key_F21"] = 0x1044; m_EventConstMap["Key_F22"] = 0x1045; m_EventConstMap["Key_F23"] = 0x1046; m_EventConstMap["Key_F24"] = 0x1047; m_EventConstMap["Key_F25"] = 0x1048; m_EventConstMap["Key_F26"] = 0x1049; m_EventConstMap["Key_F27"] = 0x104a; m_EventConstMap["Key_F28"] = 0x104b; m_EventConstMap["Key_F29"] = 0x104c; m_EventConstMap["Key_F30"] = 0x104d; m_EventConstMap["Key_F31"] = 0x104e; m_EventConstMap["Key_F32"] = 0x104f; m_EventConstMap["Key_F33"] = 0x1050; m_EventConstMap["Key_F34"] = 0x1051; m_EventConstMap["Key_F35"] = 0x1052; m_EventConstMap["Key_Super_L"] = 0x1053; m_EventConstMap["Key_Super_R"] = 0x1054; m_EventConstMap["Key_Menu"] = 0x1055; m_EventConstMap["Key_Hyper_L"] = 0x1056; m_EventConstMap["Key_Hyper_R"] = 0x1057; m_EventConstMap["Key_Help"] = 0x1058; m_EventConstMap["Key_Muhenkan"] = 0x1122; m_EventConstMap["Key_Henkan"] = 0x1123; m_EventConstMap["Key_Hiragana_Katakana"] = 0x1127; m_EventConstMap["Key_Zenkaku_Hankaku"] = 0x112A; m_EventConstMap["Key_Space"] = 0x20; m_EventConstMap["Key_Any"] = 0x20; m_EventConstMap["Key_Exclam"] = 0x21; m_EventConstMap["Key_QuoteDbl"] = 0x22; m_EventConstMap["Key_NumberSign"] = 0x23; m_EventConstMap["Key_Dollar"] = 0x24; m_EventConstMap["Key_Percent"] = 0x25; m_EventConstMap["Key_Ampersand"] = 0x26; m_EventConstMap["Key_Apostrophe"] = 0x27; m_EventConstMap["Key_ParenLeft"] = 0x28; m_EventConstMap["Key_ParenRight"] = 0x29; m_EventConstMap["Key_Asterisk"] = 0x2a; m_EventConstMap["Key_Plus"] = 0x2b; m_EventConstMap["Key_Comma"] = 0x2c; m_EventConstMap["Key_Minus"] = 0x2d; m_EventConstMap["Key_Period"] = 0x2e; m_EventConstMap["Key_Slash"] = 0x2f; m_EventConstMap["Key_0"] = 0x30; m_EventConstMap["Key_1"] = 0x31; m_EventConstMap["Key_2"] = 0x32; m_EventConstMap["Key_3"] = 0x33; m_EventConstMap["Key_4"] = 0x34; m_EventConstMap["Key_5"] = 0x35; m_EventConstMap["Key_6"] = 0x36; m_EventConstMap["Key_7"] = 0x37; m_EventConstMap["Key_8"] = 0x38; m_EventConstMap["Key_9"] = 0x39; m_EventConstMap["Key_Colon"] = 0x3a; m_EventConstMap["Key_Semicolon"] = 0x3b; m_EventConstMap["Key_Less"] = 0x3c; m_EventConstMap["Key_Equal"] = 0x3d; m_EventConstMap["Key_Greater"] = 0x3e; m_EventConstMap["Key_Question"] = 0x3f; m_EventConstMap["Key_At"] = 0x40; m_EventConstMap["Key_A"] = 0x41; m_EventConstMap["Key_B"] = 0x42; m_EventConstMap["Key_C"] = 0x43; m_EventConstMap["Key_D"] = 0x44; m_EventConstMap["Key_E"] = 0x45; m_EventConstMap["Key_F"] = 0x46; m_EventConstMap["Key_G"] = 0x47; m_EventConstMap["Key_H"] = 0x48; m_EventConstMap["Key_I"] = 0x49; m_EventConstMap["Key_J"] = 0x4a; m_EventConstMap["Key_K"] = 0x4b; m_EventConstMap["Key_L"] = 0x4c; m_EventConstMap["Key_M"] = 0x4d; m_EventConstMap["Key_N"] = 0x4e; m_EventConstMap["Key_O"] = 0x4f; m_EventConstMap["Key_P"] = 0x50; m_EventConstMap["Key_Q"] = 0x51; m_EventConstMap["Key_R"] = 0x52; m_EventConstMap["Key_S"] = 0x53; m_EventConstMap["Key_T"] = 0x54; m_EventConstMap["Key_U"] = 0x55; m_EventConstMap["Key_V"] = 0x56; m_EventConstMap["Key_W"] = 0x57; m_EventConstMap["Key_X"] = 0x58; m_EventConstMap["Key_Y"] = 0x59; m_EventConstMap["Key_Z"] = 0x5a; m_EventConstMap["Key_BracketLeft"] = 0x5b; m_EventConstMap["Key_Backslash"] = 0x5c; m_EventConstMap["Key_BracketRight"] = 0x5d; m_EventConstMap["Key_AsciiCircum"] = 0x5e; m_EventConstMap["Key_Underscore"] = 0x5f; m_EventConstMap["Key_QuoteLeft"] = 0x60; m_EventConstMap["Key_BraceLeft"] = 0x7b; m_EventConstMap["Key_Bar"] = 0x7c; m_EventConstMap["Key_BraceRight"] = 0x7d; m_EventConstMap["Key_AsciiTilde"] = 0x7e; m_EventConstMap["Key_nobreakspace"] = 0x0a0; m_EventConstMap["Key_exclamdown"] = 0x0a1; m_EventConstMap["Key_cent"] = 0x0a2; m_EventConstMap["Key_sterling"] = 0x0a3; m_EventConstMap["Key_currency"] = 0x0a4; m_EventConstMap["Key_yen"] = 0x0a5; m_EventConstMap["Key_brokenbar"] = 0x0a6; m_EventConstMap["Key_section"] = 0x0a7; m_EventConstMap["Key_diaeresis"] = 0x0a8; m_EventConstMap["Key_copyright"] = 0x0a9; m_EventConstMap["Key_ordfeminine"] = 0x0aa; m_EventConstMap["Key_guillemotleft"] = 0x0ab; m_EventConstMap["Key_notsign"] = 0x0ac; m_EventConstMap["Key_hyphen"] = 0x0ad; m_EventConstMap["Key_registered"] = 0x0ae; m_EventConstMap["Key_macron"] = 0x0af; m_EventConstMap["Key_degree"] = 0x0b0; m_EventConstMap["Key_plusminus"] = 0x0b1; m_EventConstMap["Key_twosuperior"] = 0x0b2; m_EventConstMap["Key_threesuperior"] = 0x0b3; m_EventConstMap["Key_acute"] = 0x0b4; m_EventConstMap["Key_mu"] = 0x0b5; m_EventConstMap["Key_paragraph"] = 0x0b6; m_EventConstMap["Key_periodcentered"] = 0x0b7; m_EventConstMap["Key_cedilla"] = 0x0b8; m_EventConstMap["Key_onesuperior"] = 0x0b9; m_EventConstMap["Key_masculine"] = 0x0ba; m_EventConstMap["Key_guillemotright"] = 0x0bb; m_EventConstMap["Key_onequarter"] = 0x0bc; m_EventConstMap["Key_onehalf"] = 0x0bd; m_EventConstMap["Key_threequarters"] = 0x0be; m_EventConstMap["Key_questiondown"] = 0x0bf; m_EventConstMap["Key_Agrave"] = 0x0c0; m_EventConstMap["Key_Aacute"] = 0x0c1; m_EventConstMap["Key_Acircumflex"] = 0x0c2; m_EventConstMap["Key_Atilde"] = 0x0c3; m_EventConstMap["Key_Adiaeresis"] = 0x0c4; m_EventConstMap["Key_Aring"] = 0x0c5; m_EventConstMap["Key_AE"] = 0x0c6; m_EventConstMap["Key_Ccedilla"] = 0x0c7; m_EventConstMap["Key_Egrave"] = 0x0c8; m_EventConstMap["Key_Eacute"] = 0x0c9; m_EventConstMap["Key_Ecircumflex"] = 0x0ca; m_EventConstMap["Key_Ediaeresis"] = 0x0cb; m_EventConstMap["Key_Igrave"] = 0x0cc; m_EventConstMap["Key_Iacute"] = 0x0cd; m_EventConstMap["Key_Icircumflex"] = 0x0ce; m_EventConstMap["Key_Idiaeresis"] = 0x0cf; m_EventConstMap["Key_ETH"] = 0x0d0; m_EventConstMap["Key_Ntilde"] = 0x0d1; m_EventConstMap["Key_Ograve"] = 0x0d2; m_EventConstMap["Key_Oacute"] = 0x0d3; m_EventConstMap["Key_Ocircumflex"] = 0x0d4; m_EventConstMap["Key_Otilde"] = 0x0d5; m_EventConstMap["Key_Odiaeresis"] = 0x0d6; m_EventConstMap["Key_multiply"] = 0x0d7; m_EventConstMap["Key_Ooblique"] = 0x0d8; m_EventConstMap["Key_Ugrave"] = 0x0d9; m_EventConstMap["Key_Uacute"] = 0x0da; m_EventConstMap["Key_Ucircumflex"] = 0x0db; m_EventConstMap["Key_Udiaeresis"] = 0x0dc; m_EventConstMap["Key_Yacute"] = 0x0dd; m_EventConstMap["Key_THORN"] = 0x0de; m_EventConstMap["Key_ssharp"] = 0x0df; m_EventConstMap["Key_agrave"] = 0x0e0; m_EventConstMap["Key_aacute"] = 0x0e1; m_EventConstMap["Key_acircumflex"] = 0x0e2; m_EventConstMap["Key_atilde"] = 0x0e3; m_EventConstMap["Key_adiaeresis"] = 0x0e4; m_EventConstMap["Key_aring"] = 0x0e5; m_EventConstMap["Key_ae"] = 0x0e6; m_EventConstMap["Key_ccedilla"] = 0x0e7; m_EventConstMap["Key_egrave"] = 0x0e8; m_EventConstMap["Key_eacute"] = 0x0e9; m_EventConstMap["Key_ecircumflex"] = 0x0ea; m_EventConstMap["Key_ediaeresis"] = 0x0eb; m_EventConstMap["Key_igrave"] = 0x0ec; m_EventConstMap["Key_iacute"] = 0x0ed; m_EventConstMap["Key_icircumflex"] = 0x0ee; m_EventConstMap["Key_idiaeresis"] = 0x0ef; m_EventConstMap["Key_eth"] = 0x0f0; m_EventConstMap["Key_ntilde"] = 0x0f1; m_EventConstMap["Key_ograve"] = 0x0f2; m_EventConstMap["Key_oacute"] = 0x0f3; m_EventConstMap["Key_ocircumflex"] = 0x0f4; m_EventConstMap["Key_otilde"] = 0x0f5; m_EventConstMap["Key_odiaeresis"] = 0x0f6; m_EventConstMap["Key_division"] = 0x0f7; m_EventConstMap["Key_oslash"] = 0x0f8; m_EventConstMap["Key_ugrave"] = 0x0f9; m_EventConstMap["Key_uacute"] = 0x0fa; m_EventConstMap["Key_ucircumflex"] = 0x0fb; m_EventConstMap["Key_udiaeresis"] = 0x0fc; m_EventConstMap["Key_yacute"] = 0x0fd; m_EventConstMap["Key_thorn"] = 0x0fe; m_EventConstMap["Key_ydiaeresis"] = 0x0ff; m_EventConstMap["Key_unknown"] = 0xffff; m_EventConstMap["Key_none"] = 0xffff; } mitk::EventMapper::~EventMapper() { } //##Documentation //## searches for the event in m_EventDescription and adds the corresponding eventID //## bool mitk::EventMapper::MapEvent(Event* event, GlobalInteraction* globalInteraction, int mitkPostedEventID ) { int eventID = mitkPostedEventID; if( mitkPostedEventID == 0 ) { //search the event in the list of event descriptions, if found, then take the number and produce a stateevent EventDescriptionVecIter iter; for (iter = m_EventDescriptions.begin(); iter!=m_EventDescriptions.end();iter++) { if (*iter == *event) break; } if (iter == m_EventDescriptions.end())//not found return false; eventID = (*iter).GetId(); } //set the Menger_Var m_StateEvent and send to StateMachine, which does everything further! m_StateEvent.Set( eventID, event ); /* Group and Object EventId: then EventMapper has the power to decide which operations hang together; each event causes n (n e N) operations (e.g. StateChanges, data-operations...). Undo must recall all these coherent operations, so all of the same objectId. But Undo has also the power to recall more operationsets, for example a set for building up a new object, so that a newly build up object is deleted after a Undo and not only the latest set point. The StateMachines::ExecuteAction have the power to descide weather a new GroupID has to be calculated (by example after the editing of a new object) A user interaction with the mouse is started by a mousePressEvent, continues with a MouseMove and finishes with a MouseReleaseEvent */ switch (event->GetType()) { case mitk::Type_MouseButtonPress://Increase mitk::OperationEvent::IncCurrObjectEventId(); break; case mitk::Type_MouseMove://same break; case mitk::Type_MouseButtonRelease://same break; case mitk::Type_User://same break; case mitk::Type_KeyPress://Increase mitk::OperationEvent::IncCurrObjectEventId(); break; default://increase mitk::OperationEvent::IncCurrObjectEventId(); } #ifdef MBI_INTERNAL_CONFERENCE //Conference - pass local events through if ( mitkPostedEventID == 0 ) { mitk::CoreObjectFactory::GetInstance()->MapEvent(event,eventID); } #endif //MBI_INTERNAL_CONFERENCE mitk::OperationEvent::ExecuteIncrement(); if ( globalInteraction != NULL ) { return globalInteraction->HandleEvent( &m_StateEvent ); } else { return mitk::GlobalInteraction::GetInstance()->HandleEvent(&m_StateEvent); } } bool mitk::EventMapper::LoadBehavior(std::string fileName) { if ( fileName.empty() ) return false; if (m_XmlFileName.length() > 0) { if (fileName.compare(m_XmlFileName) == 0) return true; // this is nothing bad, we already loaded this file. } this->SetFileName( fileName.c_str() ); m_XmlFileName = fileName.c_str(); return ( this->Parse() ); } bool mitk::EventMapper::LoadBehaviorString(std::string xmlString) { if ( xmlString.empty() ) return false; return ( this->Parse(xmlString.c_str(), xmlString.length()) ); } bool mitk::EventMapper::LoadStandardBehavior() { - Module* module = ModuleRegistry::GetModule("Mitk"); + Module* module = GetModuleContext()->GetModule(); ModuleResource resource = module->GetResource("Interactions/Legacy/StateMachine.xml"); if (!resource.IsValid()) { mitkThrow()<< ("Resource not valid. State machine pattern not found:Interactions/Legacy/StateMachine.xml" ); } mitk::ModuleResourceStream stream(resource); std::string patternString((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); return this->LoadBehaviorString(patternString); } //##Documentation //## @brief converts the given const String declared in the xml-file //## to the defined const int inline int mitk::EventMapper::convertConstString2ConstInt(std::string input) { ConstMapIter tempIt = m_EventConstMap.find(input.c_str()); if (tempIt != m_EventConstMap.end()) { return (tempIt)->second; } //mitk::StatusBar::GetInstance()->DisplayText("Warning! from mitkEventMapper.cpp: Couldn't find matching Event Int from Event String in XML-File"); return -1;//for didn't find anything } void mitk::EventMapper::StartElement (const char *elementName, const char **atts) { if ( elementName == EVENT ) { // EventDescription(int type, int button, int buttonState,int key, std::string name, int id) EventDescription eventDescr( convertConstString2ConstInt( ReadXMLStringAttribut( TYPE, atts )), convertConstString2ConstInt( ReadXMLStringAttribut( BUTTON, atts )), ReadXMLIntegerAttribut( BUTTONSTATE, atts ), convertConstString2ConstInt( ReadXMLStringAttribut( KEY, atts )), ReadXMLStringAttribut( NAME, atts ), ReadXMLIntegerAttribut( ID, atts )); //check for a double entry unless it is an event for internal usage if (eventDescr.GetType()!= mitk::Type_User) { for (EventDescriptionVecIter iter = m_EventDescriptions.begin(); iter!=m_EventDescriptions.end(); iter++) { if (*iter == eventDescr) { MITK_DEBUG << "Event description " << eventDescr.GetName() << " already present! Skipping event description"; return; } } } m_EventDescriptions.push_back(eventDescr); } else if ( elementName == EVENTS ) m_StyleName = ReadXMLStringAttribut( STYLE, atts ); } std::string mitk::EventMapper::GetStyleName() const { return m_StyleName; } std::string mitk::EventMapper::ReadXMLStringAttribut( std::string name, const char** atts ) { if(atts) { const char** attsIter = atts; while(*attsIter) { if ( name == *attsIter ) { attsIter++; return *attsIter; } attsIter++; attsIter++; } } return std::string(); } int mitk::EventMapper::ReadXMLIntegerAttribut( std::string name, const char** atts ) { std::string s = ReadXMLStringAttribut( name, atts ); static const std::string hex = "0x"; int result; if ( s[0] == hex[0] && s[1] == hex[1] ) result = strtol( s.c_str(), NULL, 16 ); else result = atoi( s.c_str() ); return result; } void mitk::EventMapper::SetStateEvent(mitk::Event* event) { m_StateEvent.Set( m_StateEvent.GetId(), event ); } bool mitk::EventMapper::RefreshStateEvent(mitk::StateEvent* stateEvent) { //search the event within stateEvent in the list of event descriptions, if found adapt stateEvent ID EventDescriptionVecIter iter; for (iter = m_EventDescriptions.begin(); iter!=m_EventDescriptions.end(); iter++) { if (*iter == *(stateEvent->GetEvent())) break; } if (iter != m_EventDescriptions.end())//found { stateEvent->Set((*iter).GetId(), stateEvent->GetEvent()); return true; } else return false; return false; } void mitk::EventMapper::AddEventMapperAddOn(mitk::EventMapperAddOn* newAddOn) { bool addOnAlreadyAdded = false; for(AddOnVectorType::const_iterator it = this->m_AddOnVector.begin();it != m_AddOnVector.end();it++) { if(*it == newAddOn) { addOnAlreadyAdded = true; break; } } if(!addOnAlreadyAdded) { m_AddOnVector.push_back(newAddOn); MITK_INFO << "AddOn Count: " << m_AddOnVector.size(); } } void mitk::EventMapper::RemoveEventMapperAddOn(mitk::EventMapperAddOn* unusedAddOn) { for(AddOnVectorType::iterator it = this->m_AddOnVector.begin();it != m_AddOnVector.end();it++) { if(*it == unusedAddOn) { m_AddOnVector.erase(it); break; } } } diff --git a/Core/Code/Interactions/mitkEventStateMachine.cpp b/Core/Code/Interactions/mitkEventStateMachine.cpp index 233f19ddd7..530433bb8b 100644 --- a/Core/Code/Interactions/mitkEventStateMachine.cpp +++ b/Core/Code/Interactions/mitkEventStateMachine.cpp @@ -1,148 +1,189 @@ /*=================================================================== 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 "mitkEventStateMachine.h" #include "mitkStateMachineContainer.h" #include "mitkInteractionEvent.h" #include "mitkStateMachineAction.h" #include "mitkStateMachineTransition.h" #include "mitkStateMachineState.h" // us #include "mitkModule.h" #include "mitkModuleResource.h" #include "mitkModuleResourceStream.h" #include "mitkModuleRegistry.h" mitk::EventStateMachine::EventStateMachine() : m_StateMachineContainer(NULL), m_CurrentState(NULL) { } -bool mitk::EventStateMachine::LoadStateMachine(const std::string filename, const std::string moduleName) +bool mitk::EventStateMachine::LoadStateMachine(const std::string& filename, const Module* module) { if (m_StateMachineContainer != NULL) { m_StateMachineContainer->Delete(); } m_StateMachineContainer = StateMachineContainer::New(); - if (m_StateMachineContainer->LoadBehavior(filename, moduleName)) + if (m_StateMachineContainer->LoadBehavior(filename, module)) { m_CurrentState = m_StateMachineContainer->GetStartState(); // clear actions map ,and connect all actions as declared in sub-class + for(std::map::iterator i = m_ActionFunctionsMap.begin(); + i != m_ActionFunctionsMap.end(); ++i) + { + delete i->second; + } m_ActionFunctionsMap.clear(); + for(ActionDelegatesMapType::iterator i = m_ActionDelegatesMap.begin(); + i != m_ActionDelegatesMap.end(); ++i) + { + delete i->second; + } + m_ActionDelegatesMap.clear(); + ConnectActionsAndFunctions(); return true; } else { MITK_WARN<< "Unable to load StateMachine from file: " << filename; return false; } } mitk::EventStateMachine::~EventStateMachine() { if (m_StateMachineContainer != NULL) { m_StateMachineContainer->Delete(); } } -void mitk::EventStateMachine::AddActionFunction(const std::string action, mitk::TActionFunctor* functor) +void mitk::EventStateMachine::AddActionFunction(const std::string& action, mitk::TActionFunctor* functor) { if (!functor) return; // make sure double calls for same action won't cause memory leaks delete m_ActionFunctionsMap[action]; + ActionDelegatesMapType::iterator i = m_ActionDelegatesMap.find(action); + if (i != m_ActionDelegatesMap.end()) + { + delete i->second; + m_ActionDelegatesMap.erase(i); + } m_ActionFunctionsMap[action] = functor; } +void mitk::EventStateMachine::AddActionFunction(const std::string& action, const ActionFunctionDelegate& delegate) +{ + std::map::iterator i = m_ActionFunctionsMap.find(action); + if (i != m_ActionFunctionsMap.end()) + { + delete i->second; + m_ActionFunctionsMap.erase(i); + } + + delete m_ActionDelegatesMap[action]; + m_ActionDelegatesMap[action] = delegate.Clone(); +} + bool mitk::EventStateMachine::HandleEvent(InteractionEvent* event, DataNode* dataNode) { if (!FilterEvents(event, dataNode)) { return false; } // check if the current state holds a transition that works with the given event. - StateMachineTransition::Pointer transition = m_CurrentState->GetTransition(event->GetEventClass(), MapToEventVariant(event)); + StateMachineTransition::Pointer transition = m_CurrentState->GetTransition(event->GetNameOfClass(), MapToEventVariant(event)); if (transition.IsNotNull()) { // iterate over all actions in this transition and execute them ActionVectorType actions = transition->GetActions(); bool success = false; for (ActionVectorType::iterator it = actions.begin(); it != actions.end(); ++it) { success |= ExecuteAction(*it, event); // treat an event as handled if at least one of the actions is executed successfully } if (success || actions.empty()) // an empty action list is always successful { // perform state change m_CurrentState = transition->GetNextState(); //MITK_INFO<< "StateChange: " << m_CurrentState->GetName(); } return success; } else { return false; // no transition found that matches event } } void mitk::EventStateMachine::ConnectActionsAndFunctions() { MITK_WARN<< "ConnectActionsAndFunctions in DataInteractor not implemented.\n DataInteractor will not be able to process any events."; } bool mitk::EventStateMachine::ExecuteAction(StateMachineAction* action, InteractionEvent* event) { if (action == NULL) { return false; } - // Maps Action-Name to Functor and executes DoAction on Functor. - TActionFunctor* actionFunction = m_ActionFunctionsMap[action->GetActionName()]; - if (actionFunction == NULL) + + bool retVal = false; + // Maps Action-Name to Functor and executes the Functor. + ActionDelegatesMapType::iterator delegateIter = m_ActionDelegatesMap.find(action->GetActionName()); + if (delegateIter != m_ActionDelegatesMap.end()) { - return false; + retVal = delegateIter->second->Execute(action, event); + } + else + { + // try the legacy system + std::map::iterator functionIter = m_ActionFunctionsMap.find(action->GetActionName()); + if (functionIter != m_ActionFunctionsMap.end()) + { + retVal = functionIter->second->DoAction(action, event); + } } - bool retVal = actionFunction->DoAction(action, event); return retVal; } -mitk::StateMachineState* mitk::EventStateMachine::GetCurrentState() +mitk::StateMachineState* mitk::EventStateMachine::GetCurrentState() const { return m_CurrentState.GetPointer(); } bool mitk::EventStateMachine::FilterEvents(InteractionEvent* interactionEvent, DataNode* dataNode) { if (dataNode == NULL) { MITK_WARN<< "EventStateMachine: Empty DataNode received along with this Event " << interactionEvent; return false; } bool visible = false; if (dataNode->GetPropertyList()->GetBoolProperty("visible", visible) == false) { //property doesn't exist return false; } return visible; } diff --git a/Core/Code/Interactions/mitkEventStateMachine.h b/Core/Code/Interactions/mitkEventStateMachine.h index f4152a0a50..480a414e61 100644 --- a/Core/Code/Interactions/mitkEventStateMachine.h +++ b/Core/Code/Interactions/mitkEventStateMachine.h @@ -1,176 +1,190 @@ /*=================================================================== 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 MITKEVENTSTATEMACHINE_H_ #define MITKEVENTSTATEMACHINE_H_ #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" +#include "mitkMessage.h" #include "mitkInteractionEventHandler.h" #include #include namespace mitk { class StateMachineContainer; class StateMachineAction; class InteractionEvent; class StateMachineState; class DataNode; + class Module; /** * \class TActionFunctor * \brief Base class of ActionFunctors, to provide an easy to connect actions with functions. + * + * \deprecatedSince{2013_03} Use mitk::Message classes instead. */ - - class MITK_CORE_EXPORT TActionFunctor + class TActionFunctor { public: virtual bool DoAction(StateMachineAction*, InteractionEvent*)=0; virtual ~TActionFunctor() { } }; /** * \class TSpecificActionFunctor * Specific implementation of ActionFunctor class, implements a reference to the function which is to be executed. It takes two arguments: * StateMachineAction - the action by which the function call is invoked, InteractionEvent - the event that caused the transition. */ template - class TSpecificActionFunctor: public TActionFunctor + class DEPRECATED() TSpecificActionFunctor : public TActionFunctor { public: TSpecificActionFunctor(T* object, bool (T::*memberFunctionPointer)(StateMachineAction*, InteractionEvent*)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~TSpecificActionFunctor() { } virtual bool DoAction(StateMachineAction* action, InteractionEvent* event) { return (*m_Object.*m_MemberFunctionPointer)(action, event);// executes member function } private: T* m_Object; bool (T::*m_MemberFunctionPointer)(StateMachineAction*, InteractionEvent*); }; /** Macro that can be used to connect a StateMachineAction with a function. * It assumes that there is a typedef Classname Self in classes that use this macro, as is provided by e.g. mitkClassMacro */ #define CONNECT_FUNCTION(a, f) \ - EventStateMachine::AddActionFunction(a, new TSpecificActionFunctor(this, &Self::f)); + EventStateMachine::AddActionFunction(a, MessageDelegate2(this, &Self::f)); /** * \class EventStateMachine * * \brief Super-class that provides the functionality of a StateMachine to DataInteractors. * * A state machine is created by loading a state machine pattern. It consists of states, transitions and action. * The state represent the current status of the interaction, transitions are means to switch between states. Each transition * is triggered by an event and it is associated with actions that are to be executed when the state change is performed. * */ class MITK_CORE_EXPORT EventStateMachine : public mitk::InteractionEventHandler { public: mitkClassMacro(EventStateMachine, InteractionEventHandler) itkNewMacro(Self) - typedef std::map ActionFunctionsMapType; + + typedef std::map DEPRECATED(ActionFunctionsMapType); + typedef itk::SmartPointer StateMachineStateType; /** * @brief Loads XML resource * - * Loads a XML resource file in the given module context. + * Loads a XML resource file from the given module. * Default is the Mitk module (core). * The files have to be placed in the Resources/Interaction folder of their respective module. **/ - bool LoadStateMachine(const std::string filename, const std::string moduleName="Mitk"); + bool LoadStateMachine(const std::string& filename, const Module* module = NULL); /** * Receives Event from Dispatcher. * Event is mapped using the EventConfig Object to a variant, then it is checked if the StateMachine is listening for * such an Event. If this is the case, the transition to the next state it performed and all actions associated with the transition executed, * and true is returned to the caller. * If the StateMachine can't handle this event false is returned. * Attention: * If a transition is associated with multiple actions - "true" is returned if one action returns true, * and the event is treated as HANDLED even though some actions might not have been executed! So be sure that all actions that occur within * one transitions have the same conditions. */ bool HandleEvent(InteractionEvent* event, DataNode* dataNode); protected: EventStateMachine(); virtual ~EventStateMachine(); + + typedef MessageAbstractDelegate2 ActionFunctionDelegate; + /** * Connects action from StateMachine (String in XML file) with a function that is called when this action is to be executed. */ - void AddActionFunction(const std::string action, TActionFunctor* functor); + DEPRECATED(void AddActionFunction(const std::string& action, TActionFunctor* functor)); + + void AddActionFunction(const std::string& action, const ActionFunctionDelegate& delegate); - StateMachineState* GetCurrentState(); + StateMachineState* GetCurrentState() const; /** * Is called after loading a statemachine. * Overwrite this function in specific interactor implementations. * Connect actions and functions using the CONNECT_FUNCTION macro within this function. */ virtual void ConnectActionsAndFunctions(); /** * Looks up function that is associated with action and executes it. * To implement your own execution scheme overwrite this in your DataInteractor. */ virtual bool ExecuteAction(StateMachineAction* action, InteractionEvent* interactionEvent); /** * Implements filter scheme for events. * Standard implementation accepts events from 2d and 3d windows, * and rejects events if DataNode is not visible. * \return true if event is accepted, else false * * Overwrite this function to adapt for your own needs, for example to filter out events from * 3d windows like this: \code bool mitk::EventStateMachine::FilterEvents(InteractionEvent* interactionEvent, DataNode*dataNode) { return interactionEvent->GetSender()->GetMapperID() == BaseRenderer::Standard2D; // only 2D mappers } \endcode * or to enforce that the interactor only reacts when the corresponding DataNode is selected in the DataManager view.. */ virtual bool FilterEvents(InteractionEvent* interactionEvent, DataNode* dataNode); private: + + typedef std::map ActionDelegatesMapType; + StateMachineContainer* m_StateMachineContainer; // storage of all states, action, transitions on which the statemachine operates. - ActionFunctionsMapType m_ActionFunctionsMap; // stores association between action string + std::map m_ActionFunctionsMap; // stores association between action string + ActionDelegatesMapType m_ActionDelegatesMap; StateMachineStateType m_CurrentState; }; } /* namespace mitk */ #endif /* MITKEVENTSTATEMACHINE_H_ */ diff --git a/Core/Code/Interactions/mitkInteractionEvent.cpp b/Core/Code/Interactions/mitkInteractionEvent.cpp index 195e0f0c76..4ccd4c0210 100644 --- a/Core/Code/Interactions/mitkInteractionEvent.cpp +++ b/Core/Code/Interactions/mitkInteractionEvent.cpp @@ -1,53 +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 "mitkException.h" #include "mitkInteractionEvent.h" -mitk::InteractionEvent::InteractionEvent(BaseRenderer* baseRenderer, std::string eventClass) +const std::string mitk::InteractionEvent::KeyEsc = "Escape"; +const std::string mitk::InteractionEvent::KeyEnter = "Enter"; +const std::string mitk::InteractionEvent::KeyReturn = "Return"; +const std::string mitk::InteractionEvent::KeyDelete = "Delete"; +const std::string mitk::InteractionEvent::KeyArrowUp = "ArrowUp"; +const std::string mitk::InteractionEvent::KeyArrowDown = "ArrowDown"; +const std::string mitk::InteractionEvent::KeyArrowLeft = "ArrowLeft"; +const std::string mitk::InteractionEvent::KeyArrowRight = "ArrowRight"; + +const std::string mitk::InteractionEvent::KeyF1 = "F1"; +const std::string mitk::InteractionEvent::KeyF2 = "F2"; +const std::string mitk::InteractionEvent::KeyF3 = "F3"; +const std::string mitk::InteractionEvent::KeyF4 = "F4"; +const std::string mitk::InteractionEvent::KeyF5 = "F5"; +const std::string mitk::InteractionEvent::KeyF6 = "F6"; +const std::string mitk::InteractionEvent::KeyF7 = "F7"; +const std::string mitk::InteractionEvent::KeyF8 = "F8"; +const std::string mitk::InteractionEvent::KeyF9 = "F9"; +const std::string mitk::InteractionEvent::KeyF10 = "F10"; +const std::string mitk::InteractionEvent::KeyF11 = "F11"; +const std::string mitk::InteractionEvent::KeyF12 = "F12"; + +const std::string mitk::InteractionEvent::KeyPos1 = "Pos1"; +const std::string mitk::InteractionEvent::KeyEnd = "End"; +const std::string mitk::InteractionEvent::KeyInsert = "Insert"; +const std::string mitk::InteractionEvent::KeyPageUp = "PageUp"; +const std::string mitk::InteractionEvent::KeyPageDown = "PageDown"; +const std::string mitk::InteractionEvent::KeySpace = "Space"; + +mitk::InteractionEvent::InteractionEvent(BaseRenderer* baseRenderer) : m_Sender(baseRenderer) -, m_EventClass(eventClass) { } void mitk::InteractionEvent::SetSender(mitk::BaseRenderer* sender) { m_Sender = sender; } -mitk::BaseRenderer* mitk::InteractionEvent::GetSender() +mitk::BaseRenderer* mitk::InteractionEvent::GetSender() const { return m_Sender; } -bool mitk::InteractionEvent::MatchesTemplate(InteractionEvent::Pointer) +bool mitk::InteractionEvent::IsEqual(const InteractionEvent&) const { - return false; + return true; } mitk::InteractionEvent::~InteractionEvent() { } -bool mitk::InteractionEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) +bool mitk::InteractionEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const { return (dynamic_cast(baseClass.GetPointer()) != NULL) ; } -std::string mitk::InteractionEvent::GetEventClass() const +bool mitk::operator==(const InteractionEvent& a, const InteractionEvent& b) +{ + return (typeid(a) == typeid(b) && a.IsEqual(b)); +} + +bool mitk::operator!=(const InteractionEvent& a, const InteractionEvent& b) { - return m_EventClass; + return !(a == b); } diff --git a/Core/Code/Interactions/mitkInteractionEvent.h b/Core/Code/Interactions/mitkInteractionEvent.h index 64ac405415..5e35f1e54e 100644 --- a/Core/Code/Interactions/mitkInteractionEvent.h +++ b/Core/Code/Interactions/mitkInteractionEvent.h @@ -1,75 +1,150 @@ /*=================================================================== 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 MITKINTERACTIONEVENT_H_ #define MITKINTERACTIONEVENT_H_ #include "itkLightObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkBaseRenderer.h" #include #include namespace mitk { class MITK_CORE_EXPORT InteractionEvent: public itk::LightObject { public: mitkClassMacro(InteractionEvent,itk::LightObject) - mitkNewMacro2Param(Self,BaseRenderer*, std::string) + mitkNewMacro1Param(Self,BaseRenderer*) void SetSender(BaseRenderer* sender); - BaseRenderer* GetSender(); + BaseRenderer* GetSender() const; /** - * Implementation of equality for each event class. - * Equality does \b not mean an exact copy or pointer equality. - * - * A match is determined by agreement in all attributes that are necessary to describe - * the event for a state machine transition. - * E.g. for a mouse event press event, it is important which modifiers are used, - * which mouse button was used to triggered the event, but the mouse position is irrelevant. + * This class implements an up cast to check if the provided baseClass object is derived from this class. + * This function is used to support polymorphism on state machine pattern (XML) level. */ - virtual bool MatchesTemplate(InteractionEvent::Pointer); + virtual bool IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const; /** - * Return unique string identifier that gives the event class of this object, as it can be used in a state machine pattern. - * --- itk + * Mouse/keyboard state values */ - std::string GetEventClass() const; + enum MouseButtons + { + NoButton = 0x0000, + LeftMouseButton = 0x0001, + RightMouseButton = 0x0002, + MiddleMouseButton = 0x0004 + }; + + enum ModifierKeys + { + NoKey = 0x0000, + ShiftKey = 0x0100, + ControlKey = 0x0200, + AltKey = 0x0400 + }; /** - * This class implements an up cast to check if the provided baseClass object is derived from this class. - * This function is used to support polymorphism on state machine pattern (XML) level. + * KeyConstants Constants for special keys */ - virtual bool IsSuperClassOf(InteractionEvent::Pointer baseClass); + // Special Keys + static const std::string KeyEsc; // = "Escape"; + static const std::string KeyEnter; // = "Enter"; + static const std::string KeyReturn; // = "Return"; + static const std::string KeyDelete; // = "Delete"; + static const std::string KeyArrowUp; // = "ArrowUp"; + static const std::string KeyArrowDown; // = "ArrowDown"; + static const std::string KeyArrowLeft; // = "ArrowLeft"; + static const std::string KeyArrowRight; // = "ArrowRight"; + + static const std::string KeyF1; // = "F1"; + static const std::string KeyF2; // = "F2"; + static const std::string KeyF3; // = "F3"; + static const std::string KeyF4; // = "F4"; + static const std::string KeyF5; // = "F5"; + static const std::string KeyF6; // = "F6"; + static const std::string KeyF7; // = "F7"; + static const std::string KeyF8; // = "F8"; + static const std::string KeyF9; // = "F9"; + static const std::string KeyF10; // = "F10"; + static const std::string KeyF11; // = "F11"; + static const std::string KeyF12; // = "F12"; + + static const std::string KeyPos1; // = "Pos1"; + static const std::string KeyEnd; // = "End"; + static const std::string KeyInsert; // = "Insert"; + static const std::string KeyPageUp; // = "PageUp"; + static const std::string KeyPageDown; // = "PageDown"; + static const std::string KeySpace; // = "Space"; + // End special keys protected: - InteractionEvent(BaseRenderer*, std::string); + InteractionEvent(BaseRenderer*); virtual ~InteractionEvent(); + friend MITK_CORE_EXPORT bool operator==(const InteractionEvent&, const InteractionEvent&); + virtual bool IsEqual(const InteractionEvent& other) const; + private: BaseRenderer* m_Sender; - std::string m_EventClass; }; + /** + * Implementation of equality for event classes. + * Equality does \b not mean an exact copy or pointer equality. + * + * A match is determined by agreement in all attributes that are necessary to describe + * the event for a state machine transition. + * E.g. for a mouse event press event, it is important which modifiers are used, + * which mouse button was used to triggered the event, but the mouse position is irrelevant. + */ + MITK_CORE_EXPORT bool operator==(const InteractionEvent& a, const InteractionEvent& b); + MITK_CORE_EXPORT bool operator!=(const InteractionEvent& a, const InteractionEvent& b); + + /* + * Allow bitwise OR operation on enums. + */ + inline InteractionEvent::MouseButtons operator|(InteractionEvent::MouseButtons a, InteractionEvent::MouseButtons b) + { + return static_cast(static_cast(a) | static_cast(b)); + } + + inline InteractionEvent::MouseButtons& operator|=(InteractionEvent::MouseButtons& a, InteractionEvent::MouseButtons& b) + { + a = static_cast(static_cast(a) | static_cast(b)); + return a; + } + + inline InteractionEvent::ModifierKeys operator|(InteractionEvent::ModifierKeys a, InteractionEvent::ModifierKeys b) + { + return static_cast(static_cast(a) | static_cast(b)); + } + + inline InteractionEvent::ModifierKeys& operator|=(InteractionEvent::ModifierKeys& a, InteractionEvent::ModifierKeys& b) + { + a = static_cast(static_cast(a) | static_cast(b)); + return a; + } + } /* namespace mitk */ #endif /* MITKINTERACTIONEVENT_H_ */ diff --git a/Core/Code/Interactions/mitkInteractionEventConst.cpp b/Core/Code/Interactions/mitkInteractionEventConst.cpp new file mode 100644 index 0000000000..35fb858ed3 --- /dev/null +++ b/Core/Code/Interactions/mitkInteractionEventConst.cpp @@ -0,0 +1,41 @@ +/*=================================================================== + + The Medical Imaging Interaction Toolkit (MITK) + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics. + All rights reserved. + + This software is distributed WITHOUT ANY WARRANTY; without + even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. + + See LICENSE.txt or http://www.mitk.org for details. + + ===================================================================*/ + +#include "mitkInteractionEventConst.h" + +namespace mitk { + +// XML Tags +const std::string InteractionEventConst::xmlTagConfigRoot = "config"; +const std::string InteractionEventConst::xmlTagParam = "param"; +const std::string InteractionEventConst::xmlTagEventVariant = "event_variant"; +const std::string InteractionEventConst::xmlTagAttribute = "attribute"; + +// XML Param +const std::string InteractionEventConst::xmlParameterName = "name"; +const std::string InteractionEventConst::xmlParameterValue = "value"; +const std::string InteractionEventConst::xmlParameterEventVariant = "event_variant"; +const std::string InteractionEventConst::xmlParameterEventClass = "class"; + +// Event Description +const std::string InteractionEventConst::xmlEventPropertyModifier = "Modifiers"; +const std::string InteractionEventConst::xmlEventPropertyEventButton = "EventButton"; +const std::string InteractionEventConst::xmlEventPropertyButtonState = "ButtonState"; +const std::string InteractionEventConst::xmlEventPropertyKey = "Key"; +const std::string InteractionEventConst::xmlEventPropertyScrollDirection = "ScrollDirection"; +const std::string InteractionEventConst::xmlEventPropertySignalName = "SignalName"; + +} diff --git a/Core/Code/Interactions/mitkInteractionEventConst.h b/Core/Code/Interactions/mitkInteractionEventConst.h index cc06f391fd..754ed83c23 100644 --- a/Core/Code/Interactions/mitkInteractionEventConst.h +++ b/Core/Code/Interactions/mitkInteractionEventConst.h @@ -1,132 +1,53 @@ /*=================================================================== 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 MITKINTERACTEVENTCONST_H #define MITKINTERACTEVENTCONST_H -//##Documentation -//## @file mitkInteractionEventConst.h -//## @brief Constants to describe Mouse Events and special Key Events. - #include namespace mitk { -//##ButtonState -// Mouse/keyboard state values - enum MouseButtons - { - NoButton = 0x0000, - LeftMouseButton = 0x0001, - RightMouseButton = 0x0002, - MiddleMouseButton = 0x0004, - }; - - enum ModifierKeys - { - NoKey = 0x0000, - ShiftKey = 0x0100, - ControlKey = 0x0200, - AltKey = 0x0400 - }; - - /* - * Allow bitwise OR operation on enums. - */ - inline MouseButtons operator|(MouseButtons a, MouseButtons b) - { - return static_cast(static_cast(a) | static_cast(b)); - } - - inline MouseButtons& operator|=(MouseButtons& a, MouseButtons& b) - { - a = static_cast(static_cast(a) | static_cast(b)); - return a; - } - - inline ModifierKeys operator|(ModifierKeys a, ModifierKeys b) - { - return static_cast(static_cast(a) | static_cast(b)); - } - - inline ModifierKeys& operator|=(ModifierKeys& a, ModifierKeys& b) - { - a = static_cast(static_cast(a) | static_cast(b)); - return a; - } - - /** - * KeyConstants Constants for special keys - */ - // Special Keys - const std::string KeyEsc = "Escape"; - const std::string KeyEnter = "Enter"; - const std::string KeyReturn = "Return"; - const std::string KeyDelete = "Delete"; - const std::string KeyArrowUp = "ArrowUp"; - const std::string KeyArrowDown = "ArrowDown"; - const std::string KeyArrowLeft = "ArrowLeft"; - const std::string KeyArrowRight = "ArrowRight"; - - const std::string KeyF1 = "F1"; - const std::string KeyF2 = "F2"; - const std::string KeyF3 = "F3"; - const std::string KeyF4 = "F4"; - const std::string KeyF5 = "F5"; - const std::string KeyF6 = "F6"; - const std::string KeyF7 = "F7"; - const std::string KeyF8 = "F8"; - const std::string KeyF9 = "F9"; - const std::string KeyF10 = "F10"; - const std::string KeyF11 = "F11"; - const std::string KeyF12 = "F12"; - - const std::string KeyPos1 = "Pos1"; - const std::string KeyEnd = "End"; - const std::string KeyInsert = "Insert"; - const std::string KeyPageUp = "PageUp"; - const std::string KeyPageDown = "PageDown"; - const std::string KeySpace = "Space"; - // End special keys - +/** + * @brief Constants to describe Mouse Events and special Key Events. + */ +struct InteractionEventConst +{ // XML Tags - const std::string xmlTagConfigRoot = "config"; - const std::string xmlTagParam = "param"; - const std::string xmlTagEventVariant = "event_variant"; - const std::string xmlTagAttribute = "attribute"; + static const std::string xmlTagConfigRoot; // = "config"; + static const std::string xmlTagParam; // = "param"; + static const std::string xmlTagEventVariant; // = "event_variant"; + static const std::string xmlTagAttribute; // = "attribute"; // XML Param - const std::string xmlParameterName = "name"; - const std::string xmlParameterValue = "value"; - const std::string xmlParameterEventVariant = "event_variant"; - const std::string xmlParameterEventClass = "class"; + static const std::string xmlParameterName; // = "name"; + static const std::string xmlParameterValue; // = "value"; + static const std::string xmlParameterEventVariant; // = "event_variant"; + static const std::string xmlParameterEventClass; // = "class"; // Event Description - const std::string xmlEventPropertyModifier = "Modifiers"; - const std::string xmlEventPropertyEventButton = "EventButton"; - const std::string xmlEventPropertyButtonState = "ButtonState"; - const std::string xmlEventPropertyKey = "Key"; - const std::string xmlEventPropertyScrollDirection = "ScrollDirection"; - const std::string xmlEventPropertySignalName = "SignalName"; - - // Predefined internal events/signals - const std::string IntDeactivateMe = "DeactivateMe"; - const std::string IntLeaveWidget = "LeaveWidget"; - const std::string IntEnterWidget = "EnterWidget"; + static const std::string xmlEventPropertyModifier; // = "Modifiers"; + static const std::string xmlEventPropertyEventButton; // = "EventButton"; + static const std::string xmlEventPropertyButtonState; // = "ButtonState"; + static const std::string xmlEventPropertyKey; // = "Key"; + static const std::string xmlEventPropertyScrollDirection; // = "ScrollDirection"; + static const std::string xmlEventPropertySignalName; // = "SignalName"; + +}; } //namespace mitk #endif //ifndef MITKINTERACTEVENTCONST_H diff --git a/Core/Code/Interactions/mitkInteractionEventHandler.cpp b/Core/Code/Interactions/mitkInteractionEventHandler.cpp index 2157bf592e..6d28d8da60 100644 --- a/Core/Code/Interactions/mitkInteractionEventHandler.cpp +++ b/Core/Code/Interactions/mitkInteractionEventHandler.cpp @@ -1,75 +1,118 @@ /*=================================================================== 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 "mitkInteractionEventHandler.h" #include "mitkInteractionEvent.h" -mitk::InteractionEventHandler::InteractionEventHandler(): - m_EventConfig(NULL) +mitk::InteractionEventHandler::InteractionEventHandler() + : m_EventConfig() { } mitk::InteractionEventHandler::~InteractionEventHandler() { } -bool mitk::InteractionEventHandler::LoadEventConfig(std::string filename, std::string moduleName) +bool mitk::InteractionEventHandler::SetEventConfig(const std::string& filename, const Module* module) { - m_EventConfig = vtkSmartPointer::New(); + EventConfig newConfig(filename, module); + if (newConfig.IsValid()) + { + m_EventConfig = newConfig; + // notify sub-classes that new config is set + ConfigurationChanged(); + return true; + } + return false; +} + +bool mitk::InteractionEventHandler::SetEventConfig(const EventConfig& config) +{ + if (config.IsValid()) + { + m_EventConfig = config; + // notify sub-classes that new config is set + ConfigurationChanged(); + return true; + } + return false; +} + +mitk::EventConfig mitk::InteractionEventHandler::GetEventConfig() const +{ + return m_EventConfig; +} + +bool mitk::InteractionEventHandler::AddEventConfig(const std::string& filename, const Module* module) +{ + if (!m_EventConfig.IsValid()) + { + MITK_ERROR<< "SetEventConfig has to be called before AddEventConfig can be used."; + return false; + } // notify sub-classes that new config is set - bool success = m_EventConfig->LoadConfig(filename, moduleName); - ConfigurationChanged(); + bool success = m_EventConfig.AddConfig(filename, module); + if (success) + { + ConfigurationChanged(); + } return success; } -bool mitk::InteractionEventHandler::AddEventConfig(std::string filename, std::string moduleName) +bool mitk::InteractionEventHandler::AddEventConfig(const EventConfig& config) { - if (m_EventConfig == NULL) + if (!m_EventConfig.IsValid()) { - MITK_ERROR<< "LoadEventConfig has to be called before AddEventConfig can be used."; + MITK_ERROR<< "SetEventConfig has to be called before AddEventConfig can be used."; return false; } // notify sub-classes that new config is set - bool success = m_EventConfig->LoadConfig(filename, moduleName); - ConfigurationChanged(); + bool success = m_EventConfig.AddConfig(config); + if (success) + { + ConfigurationChanged(); + } return success; } -mitk::PropertyList::Pointer mitk::InteractionEventHandler::GetAttributes() +mitk::PropertyList::Pointer mitk::InteractionEventHandler::GetAttributes() const { - if (m_EventConfig != NULL) { - return m_EventConfig->GetAttributes(); - } else { + if (m_EventConfig.IsValid()) + { + return m_EventConfig.GetAttributes(); + } + else + { MITK_ERROR << "InteractionEventHandler::GetAttributes() requested, but not configuration loaded."; return NULL; } } std::string mitk::InteractionEventHandler::MapToEventVariant(InteractionEvent* interactionEvent) { - if (m_EventConfig != NULL) + if (m_EventConfig.IsValid()) { - return m_EventConfig->GetMappedEvent(interactionEvent); + return m_EventConfig.GetMappedEvent(interactionEvent); } else { return ""; } } void mitk::InteractionEventHandler::ConfigurationChanged() { } diff --git a/Core/Code/Interactions/mitkInteractionEventHandler.h b/Core/Code/Interactions/mitkInteractionEventHandler.h index 8b45862464..e2cc0e7273 100644 --- a/Core/Code/Interactions/mitkInteractionEventHandler.h +++ b/Core/Code/Interactions/mitkInteractionEventHandler.h @@ -1,84 +1,133 @@ /*=================================================================== 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 MITKEVENTHANDLER_H_ #define MITKEVENTHANDLER_H_ #include "itkLightObject.h" #include "itkObjectFactory.h" -#include "mitkEvent.h" + #include "mitkCommon.h" #include #include "mitkEventConfig.h" #include "mitkPropertyList.h" -#include + #include namespace mitk { + class Module; + /** * \class EventHandler * Serves as a base class for all objects and classes that handle mitk::InteractionEvents. * * It provides an interface to load configuration objects map of events to variant names. */ class InteractionEvent; class MITK_CORE_EXPORT InteractionEventHandler : public itk::LightObject { public: mitkClassMacro(InteractionEventHandler, itk::LightObject) itkNewMacro(Self) + + /** + * @brief Loads a configuration from an XML resource. + * + * Loads an event configuration from an XML resource file contained in the given module. + * Default is the Mitk module (core). + * The files have to be placed in the Resources/Interactions folder of their respective module. + * This method will remove all existing configuration and replaces it with the new one. + * + * @see SetEventConfig(const EventConfig&) + * + * @param filename The resource name relative to the Interactions resource folder. + * @param module The module containing the resource. Defaults to the Mitk module. + * @return \c true if the resource was successfully loaded, \c false otherwise. + */ + bool SetEventConfig(const std::string& filename, const Module* module = NULL); + + /** + * @brief Loads a configuration from an EventConfig object. + * + * Loads an event configuration from the given EventConfig object. This method will remove + * all existing configuration and replaces it with the new one. + * + * @see SetEventConfig(const std::string&, const Module*) + * + * @param config The EventConfig object containing the new configuration. + * @return \c true if the configuration was successfully loaded, \c false otherwise. + */ + bool SetEventConfig(const EventConfig& config); + /** - * @brief Loads XML resource - * - * Loads a XML resource file in the given module context. - * Default is the Mitk module (core). - * The files have to be placed in the Resources/Interaction folder of their respective module. - * This method will remove all existing configuration and replaces it with the new one. - */ - virtual bool LoadEventConfig(std::string filename, std::string moduleName = "Mitk"); + * @brief Returns the current configuration. + * @return A EventConfig object representing the current event configuration. + */ + EventConfig GetEventConfig() const; + /** - * This method EXTENDs the configuration. + * @brief This method \e extends the configuration. + * * The configuration from the resource provided is loaded and only the ones conflicting are replaced by the new one. - * This way several configuration files can be combined + * This way several configuration files can be combined. + * + * @see AddEventConfig(const EventConfig&) + * + * @param filename The resource name relative to the Interactions resource folder. + * @param module The module containing the resource. Defaults to the Mitk module. + * @return \c true if the configuration was successfully added, \c false otherwise. */ - virtual bool AddEventConfig(std::string filename, std::string moduleName = "Mitk"); + bool AddEventConfig(const std::string& filename, const Module* module = NULL); + + /** + * @brief This method \e extends the configuration. + * The configuration from the EventConfig object is loaded and only the ones conflicting are replaced by the new one. + * This way several configurations can be combined. + * + * @see AddEventConfig(const std::string&, const Module*) + * + * @param config The EventConfig object whose configuration should be added. + * @return \c true if the configuration was successfully added, \c false otherwise. + */ + bool AddEventConfig(const EventConfig& config); protected: InteractionEventHandler(); virtual ~InteractionEventHandler(); + /** * Returns a PropertyList in which the parameters defined in the config file are listed. */ - PropertyList::Pointer GetAttributes(); + PropertyList::Pointer GetAttributes() const; std::string MapToEventVariant(InteractionEvent* interactionEvent); /** * Is called whenever a new config object ist set. * Overwrite this method e.g. to initialize EventHandler with parameters in configuration file. */ virtual void ConfigurationChanged(); private: - vtkSmartPointer m_EventConfig; + EventConfig m_EventConfig; }; } /* namespace mitk */ #endif /* MITKEVENTHANDLER_H_ */ diff --git a/Core/Code/Interactions/mitkInteractionKeyEvent.cpp b/Core/Code/Interactions/mitkInteractionKeyEvent.cpp index feb979df3f..4e80ee89c8 100644 --- a/Core/Code/Interactions/mitkInteractionKeyEvent.cpp +++ b/Core/Code/Interactions/mitkInteractionKeyEvent.cpp @@ -1,52 +1,49 @@ /*=================================================================== 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 "mitkInteractionKeyEvent.h" -mitk::InteractionKeyEvent::InteractionKeyEvent(mitk::BaseRenderer* baseRenderer, const std::string key, mitk::ModifierKeys modifiers = ControlKey) : - InteractionEvent(baseRenderer, "KeyEvent"), m_Key(key), m_Modifiers(modifiers) +mitk::InteractionKeyEvent::InteractionKeyEvent(mitk::BaseRenderer* baseRenderer, const std::string& key, ModifierKeys modifiers = ControlKey) : + InteractionEvent(baseRenderer), m_Key(key), m_Modifiers(modifiers) { } -mitk::ModifierKeys mitk::InteractionKeyEvent::GetModifiers() const +mitk::InteractionEvent::ModifierKeys mitk::InteractionKeyEvent::GetModifiers() const { return m_Modifiers; } std::string mitk::InteractionKeyEvent::GetKey() const { return m_Key; } mitk::InteractionKeyEvent::~InteractionKeyEvent() { } -bool mitk::InteractionKeyEvent::MatchesTemplate(mitk::InteractionEvent::Pointer interactionEvent) +bool mitk::InteractionKeyEvent::IsEqual(const mitk::InteractionEvent& interactionEvent) const { - mitk::InteractionKeyEvent* keyEvent = dynamic_cast(interactionEvent.GetPointer()); - if (keyEvent == NULL) - { - return false; - } - return (this->GetModifiers() == keyEvent->GetModifiers() && this->GetKey() == keyEvent->GetKey()); + const mitk::InteractionKeyEvent& keyEvent = static_cast(interactionEvent); + return (this->GetModifiers() == keyEvent.GetModifiers() && this->GetKey() == keyEvent.GetKey() && + Superclass::IsEqual(interactionEvent)); } -bool mitk::InteractionKeyEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) +bool mitk::InteractionKeyEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const { return (dynamic_cast(baseClass.GetPointer()) != NULL) ; } diff --git a/Core/Code/Interactions/mitkInteractionKeyEvent.h b/Core/Code/Interactions/mitkInteractionKeyEvent.h index 7dea3c994c..18da7fa95e 100644 --- a/Core/Code/Interactions/mitkInteractionKeyEvent.h +++ b/Core/Code/Interactions/mitkInteractionKeyEvent.h @@ -1,65 +1,66 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKINTERACTIONKEYEVENT_H_ #define MITKINTERACTIONKEYEVENT_H_ #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkInteractionEventConst.h" #include "mitkInteractionPositionEvent.h" #include "mitkBaseRenderer.h" #include "mitkInteractionEvent.h" #include #include /* * Note: A Click with the MiddleButton is to be handled with MousePressEvents */ namespace mitk { /** * \class InteractionKeyEvent * \brief Handles key events. * \input std::string for pressed key or special key description , mitk::ModifierKeys for modifiers * \ingroup Interaction. */ class MITK_CORE_EXPORT InteractionKeyEvent : public InteractionEvent { public: mitkClassMacro(InteractionKeyEvent,InteractionEvent) - mitkNewMacro3Param(Self, BaseRenderer*, const std::string , ModifierKeys) + mitkNewMacro3Param(Self, BaseRenderer*, const std::string& , ModifierKeys) - virtual bool MatchesTemplate(InteractionEvent::Pointer); - bool IsSuperClassOf(InteractionEvent::Pointer baseClass); + bool IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const; ModifierKeys GetModifiers() const; std::string GetKey() const; protected: - InteractionKeyEvent(BaseRenderer*, const std::string key, ModifierKeys modifiers); + InteractionKeyEvent(BaseRenderer*, const std::string& key, ModifierKeys modifiers); virtual ~InteractionKeyEvent(); + virtual bool IsEqual(const InteractionEvent&) const; + private: std::string m_Key; ModifierKeys m_Modifiers; }; } /* namespace mitk */ #endif /* MITKINTERACTIONKEYEVENT_H_ */ diff --git a/Core/Code/Interactions/mitkInteractionPositionEvent.cpp b/Core/Code/Interactions/mitkInteractionPositionEvent.cpp index 155f6c80a0..74f963600e 100644 --- a/Core/Code/Interactions/mitkInteractionPositionEvent.cpp +++ b/Core/Code/Interactions/mitkInteractionPositionEvent.cpp @@ -1,58 +1,57 @@ /*=================================================================== 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 "mitkInteractionPositionEvent.h" #include mitk::InteractionPositionEvent::InteractionPositionEvent(mitk::BaseRenderer* baseRenderer, - const mitk::Point2D mousePosition, - const std::string eventClass) -: InteractionEvent(baseRenderer, eventClass) + const mitk::Point2D& mousePosition) +: InteractionEvent(baseRenderer) , m_PointerPosition(mousePosition) { if (GetSender() != NULL) { m_WorldPosition = GetSender()->Map2DRendererPositionTo3DWorldPosition(&m_PointerPosition); } else { m_WorldPosition.Fill(0); } } -const mitk::Point2D mitk::InteractionPositionEvent::GetPointerPositionOnScreen() +const mitk::Point2D mitk::InteractionPositionEvent::GetPointerPositionOnScreen() const { return m_PointerPosition; } -const mitk::Point3D mitk::InteractionPositionEvent::GetPositionInWorld() +const mitk::Point3D mitk::InteractionPositionEvent::GetPositionInWorld() const { return m_WorldPosition; } -bool mitk::InteractionPositionEvent::MatchesTemplate(InteractionEvent::Pointer) +bool mitk::InteractionPositionEvent::IsEqual(const InteractionEvent& other) const { - return true; + return Superclass::IsEqual(other); } mitk::InteractionPositionEvent::~InteractionPositionEvent() { } -bool mitk::InteractionPositionEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) +bool mitk::InteractionPositionEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const { return (dynamic_cast(baseClass.GetPointer()) != NULL) ; } diff --git a/Core/Code/Interactions/mitkInteractionPositionEvent.h b/Core/Code/Interactions/mitkInteractionPositionEvent.h index 5f7960cd9a..74ad60a5f1 100644 --- a/Core/Code/Interactions/mitkInteractionPositionEvent.h +++ b/Core/Code/Interactions/mitkInteractionPositionEvent.h @@ -1,65 +1,65 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKINTERACTIONPOSITIONEVENT_H_ #define MITKINTERACTIONPOSITIONEVENT_H_ #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkInteractionEvent.h" #include "mitkInteractionEventConst.h" #include #include namespace mitk { /** * \class InteractionPositionEvent * * \brief Super class for all position events. * * This class is instantiated with a BaseRenderer and the 2D pointer position relative to the renderer, * the object then queries the Renderer for 3D world coordinates and supplies them to deriving classes. * */ class MITK_CORE_EXPORT InteractionPositionEvent : public InteractionEvent { public: mitkClassMacro(InteractionPositionEvent,InteractionEvent); - mitkNewMacro3Param(Self, BaseRenderer*, const Point2D , const std::string); + mitkNewMacro2Param(Self, BaseRenderer*, const Point2D&); - const Point2D GetPointerPositionOnScreen(); - const Point3D GetPositionInWorld(); + const Point2D GetPointerPositionOnScreen() const; + const Point3D GetPositionInWorld() const; - virtual bool MatchesTemplate(InteractionEvent::Pointer); - virtual bool IsSuperClassOf(InteractionEvent::Pointer baseClass); + virtual bool IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const; protected: - InteractionPositionEvent(BaseRenderer* baseRenderer, const Point2D mousePosition, const std::string eventClass); + InteractionPositionEvent(BaseRenderer* baseRenderer, const Point2D& mousePosition); virtual ~InteractionPositionEvent(); + virtual bool IsEqual(const InteractionEvent&) const; private: Point2D m_PointerPosition; Point3D m_WorldPosition; }; } /* namespace mitk */ #endif /* MITKINTERACTIONPOSITIONEVENT_H_ */ diff --git a/Core/Code/Interactions/mitkInternalEvent.cpp b/Core/Code/Interactions/mitkInternalEvent.cpp index 15622e6bc1..171cd49f3a 100644 --- a/Core/Code/Interactions/mitkInternalEvent.cpp +++ b/Core/Code/Interactions/mitkInternalEvent.cpp @@ -1,55 +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. ===================================================================*/ #include "mitkInternalEvent.h" #include "mitkDataInteractor.h" -mitk::InternalEvent::InternalEvent(mitk::BaseRenderer* baseRenderer, DataInteractor* sourceInteractor, const std::string signalName) -: InteractionEvent(baseRenderer, "InternalEvent") +mitk::InternalEvent::InternalEvent(mitk::BaseRenderer* baseRenderer, DataInteractor* sourceInteractor, const std::string& signalName) +: InteractionEvent(baseRenderer) , m_DataInteractor(sourceInteractor) , m_SignalName(signalName) { } -bool mitk::InternalEvent::MatchesTemplate(mitk::InteractionEvent::Pointer interactionEvent) +bool mitk::InternalEvent::IsEqual(const mitk::InteractionEvent& interactionEvent) const { - mitk::InternalEvent* internalEvent = dynamic_cast(interactionEvent.GetPointer()); - if (internalEvent == NULL) - { - return false; - } - return (m_SignalName == internalEvent->GetSignalName()); + const mitk::InternalEvent& internalEvent = static_cast(interactionEvent); + return (m_SignalName == internalEvent.GetSignalName() && Superclass::IsEqual(interactionEvent)); } mitk::InternalEvent::~InternalEvent() { } -const std::string mitk::InternalEvent::GetSignalName() +std::string mitk::InternalEvent::GetSignalName() const { return m_SignalName; } -mitk::DataInteractor* mitk::InternalEvent::GetTargetInteractor() +mitk::DataInteractor* mitk::InternalEvent::GetTargetInteractor() const { return m_DataInteractor.GetPointer(); } -bool mitk::InternalEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) +bool mitk::InternalEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const { return (NULL != dynamic_cast(baseClass.GetPointer()) ); } diff --git a/Core/Code/Interactions/mitkInternalEvent.h b/Core/Code/Interactions/mitkInternalEvent.h index 4d511084e2..dd6b984938 100644 --- a/Core/Code/Interactions/mitkInternalEvent.h +++ b/Core/Code/Interactions/mitkInternalEvent.h @@ -1,63 +1,62 @@ /*=================================================================== 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 mitkInternalEvent_h #define mitkInternalEvent_h #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkInteractionEventConst.h" #include "mitkInteractionEvent.h" #include "mitkBaseRenderer.h" #include #include namespace mitk { /** *\brief Class to create events from within the application to signal about internal events. * * These events can target a specific DataInteractor, if this DataInteractor is specified in the constructor; * else this parameter is set to NULL and the event is treated as a regular event. */ - - class DataInteracor; class MITK_CORE_EXPORT InternalEvent: public InteractionEvent { public: mitkClassMacro(InternalEvent,InteractionEvent); - mitkNewMacro3Param(Self, BaseRenderer*, DataInteractor*, const std::string); + mitkNewMacro3Param(Self, BaseRenderer*, DataInteractor*, const std::string&); - const std::string GetSignalName(); - DataInteractor* GetTargetInteractor(); + std::string GetSignalName() const; + DataInteractor* GetTargetInteractor() const; - virtual bool MatchesTemplate(InteractionEvent::Pointer); - virtual bool IsSuperClassOf(InteractionEvent::Pointer baseClass); + virtual bool IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const; protected: - InternalEvent(BaseRenderer*, DataInteractor* destInteractor, const std::string signalName); + InternalEvent(BaseRenderer*, DataInteractor* destInteractor, const std::string& signalName); virtual ~InternalEvent(); + virtual bool IsEqual(const InteractionEvent&) const; + private: DataInteractor::Pointer m_DataInteractor; std::string m_SignalName; }; } #endif /* mitkInternalEvent_h */ diff --git a/Core/Code/Interactions/mitkMouseModeSwitcher.cpp b/Core/Code/Interactions/mitkMouseModeSwitcher.cpp index f7a5f24a4b..5abf241d42 100644 --- a/Core/Code/Interactions/mitkMouseModeSwitcher.cpp +++ b/Core/Code/Interactions/mitkMouseModeSwitcher.cpp @@ -1,113 +1,113 @@ /*=================================================================== 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 "mitkMouseModeSwitcher.h" // us #include "mitkGetModuleContext.h" #include "mitkModule.h" #include "mitkModuleRegistry.h" #include "mitkInteractionEventObserver.h" mitk::MouseModeSwitcher::MouseModeSwitcher() : m_ActiveInteractionScheme(MITK), m_ActiveMouseMode(MousePointer), m_CurrentObserver(NULL) { this->InitializeListeners(); this->SetInteractionScheme(m_ActiveInteractionScheme); } mitk::MouseModeSwitcher::~MouseModeSwitcher() { m_ServiceRegistration.Unregister(); } void mitk::MouseModeSwitcher::InitializeListeners() { if (m_CurrentObserver.IsNull()) { m_CurrentObserver = mitk::DisplayInteractor::New(); m_CurrentObserver->LoadStateMachine("DisplayInteraction.xml"); - m_CurrentObserver->LoadEventConfig("DisplayConfigMITK.xml"); + m_CurrentObserver->SetEventConfig("DisplayConfigMITK.xml"); // Register as listener via micro services ServiceProperties props; props["name"] = std::string("DisplayInteractor"); m_ServiceRegistration = GetModuleContext()->RegisterService( m_CurrentObserver.GetPointer(),props); } } void mitk::MouseModeSwitcher::SetInteractionScheme(InteractionScheme scheme) { switch (scheme) { case MITK: { - m_CurrentObserver->LoadEventConfig("DisplayConfigMITK.xml"); + m_CurrentObserver->SetEventConfig("DisplayConfigMITK.xml"); } break; case PACS: { - m_CurrentObserver->LoadEventConfig("DisplayConfigPACS.xml"); + m_CurrentObserver->SetEventConfig("DisplayConfigPACS.xml"); } break; } m_ActiveInteractionScheme = scheme; this->InvokeEvent(MouseModeChangedEvent()); } void mitk::MouseModeSwitcher::SelectMouseMode(MouseMode mode) { if (m_ActiveInteractionScheme != PACS) return; switch (mode) { case MousePointer: { - m_CurrentObserver->LoadEventConfig("DisplayConfigPACS.xml"); + m_CurrentObserver->SetEventConfig("DisplayConfigPACS.xml"); break; } // case 0 case Scroll: { m_CurrentObserver->AddEventConfig("DisplayConfigPACSScroll.xml"); break; } case LevelWindow: { m_CurrentObserver->AddEventConfig("DisplayConfigPACSLevelWindow.xml"); break; } case Zoom: { m_CurrentObserver->AddEventConfig("DisplayConfigPACSZoom.xml"); break; } case Pan: { m_CurrentObserver->AddEventConfig("DisplayConfigPACSPan.xml"); break; } } // end switch (mode) m_ActiveMouseMode = mode; this->InvokeEvent(MouseModeChangedEvent()); } mitk::MouseModeSwitcher::MouseMode mitk::MouseModeSwitcher::GetCurrentMouseMode() const { return m_ActiveMouseMode; } diff --git a/Core/Code/Interactions/mitkMouseMoveEvent.cpp b/Core/Code/Interactions/mitkMouseMoveEvent.cpp index 31492997e0..d58ce5c563 100644 --- a/Core/Code/Interactions/mitkMouseMoveEvent.cpp +++ b/Core/Code/Interactions/mitkMouseMoveEvent.cpp @@ -1,64 +1,61 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkException.h" #include "mitkMouseMoveEvent.h" -mitk::MouseMoveEvent::MouseMoveEvent(mitk::BaseRenderer* baseRenderer, mitk::Point2D mousePosition , mitk::MouseButtons buttonStates, mitk::ModifierKeys modifiers) -: InteractionPositionEvent(baseRenderer, mousePosition, "MouseMoveEvent") +mitk::MouseMoveEvent::MouseMoveEvent(mitk::BaseRenderer* baseRenderer, const mitk::Point2D& mousePosition , MouseButtons buttonStates, ModifierKeys modifiers) +: InteractionPositionEvent(baseRenderer, mousePosition) , m_ButtonStates(buttonStates) , m_Modifiers(modifiers) { } -mitk::ModifierKeys mitk::MouseMoveEvent::GetModifiers() const +mitk::InteractionEvent::ModifierKeys mitk::MouseMoveEvent::GetModifiers() const { return m_Modifiers; } -mitk::MouseButtons mitk::MouseMoveEvent::GetButtonStates() const +mitk::InteractionEvent::MouseButtons mitk::MouseMoveEvent::GetButtonStates() const { return m_ButtonStates; } void mitk::MouseMoveEvent::SetModifiers(ModifierKeys modifiers) { m_Modifiers = modifiers; } void mitk::MouseMoveEvent::SetButtonStates(MouseButtons buttons) { m_ButtonStates = buttons; } mitk::MouseMoveEvent::~MouseMoveEvent() { } -bool mitk::MouseMoveEvent::MatchesTemplate(mitk::InteractionEvent::Pointer interactionEvent) +bool mitk::MouseMoveEvent::IsEqual(const mitk::InteractionEvent& interactionEvent) const { - mitk::MouseMoveEvent* mpe = dynamic_cast(interactionEvent.GetPointer()); - if (mpe == NULL) - { - return false; - } - return (this->GetModifiers() == mpe->GetModifiers() && this->GetButtonStates() == mpe->GetButtonStates()); + const mitk::MouseMoveEvent& mpe = static_cast(interactionEvent); + return (this->GetModifiers() == mpe.GetModifiers() && this->GetButtonStates() == mpe.GetButtonStates() && + Superclass::IsEqual(interactionEvent)); } -bool mitk::MouseMoveEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) +bool mitk::MouseMoveEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const { return (dynamic_cast(baseClass.GetPointer()) != NULL) ; } diff --git a/Core/Code/Interactions/mitkMouseMoveEvent.h b/Core/Code/Interactions/mitkMouseMoveEvent.h index dc7dd8a5cf..074e508ac3 100644 --- a/Core/Code/Interactions/mitkMouseMoveEvent.h +++ b/Core/Code/Interactions/mitkMouseMoveEvent.h @@ -1,57 +1,59 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKMOUSEMOVEEVENT_H_ #define MITKMOUSEMOVEEVENT_H_ #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkInteractionEventConst.h" #include "mitkInteractionPositionEvent.h" #include "mitkBaseRenderer.h" #include "mitkInteractionEvent.h" #include namespace mitk { class MITK_CORE_EXPORT MouseMoveEvent : public InteractionPositionEvent { public: mitkClassMacro(MouseMoveEvent,InteractionPositionEvent); - mitkNewMacro4Param(Self, BaseRenderer*, Point2D , MouseButtons , ModifierKeys); + mitkNewMacro4Param(Self, BaseRenderer*, const Point2D& , MouseButtons , ModifierKeys); ModifierKeys GetModifiers() const; MouseButtons GetButtonStates() const; void SetModifiers(ModifierKeys modifiers); void SetButtonStates(MouseButtons buttons); - virtual bool MatchesTemplate(InteractionEvent::Pointer); - virtual bool IsSuperClassOf(InteractionEvent::Pointer baseClass); + virtual bool IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const; protected: - MouseMoveEvent(BaseRenderer*, Point2D = Point2D(), MouseButtons buttonStates = NoButton, mitk::ModifierKeys modifiers = NoKey); + MouseMoveEvent(BaseRenderer*, const Point2D& = Point2D(), MouseButtons buttonStates = NoButton, + ModifierKeys modifiers = NoKey); virtual ~MouseMoveEvent(); + virtual bool IsEqual(const InteractionEvent&) const; + private: MouseButtons m_ButtonStates; ModifierKeys m_Modifiers; }; } /* namespace mitk */ #endif /* MITKMOUSEMOVEEVENT_H_ */ diff --git a/Core/Code/Interactions/mitkMousePressEvent.cpp b/Core/Code/Interactions/mitkMousePressEvent.cpp index 6026811db7..12af1bfe82 100644 --- a/Core/Code/Interactions/mitkMousePressEvent.cpp +++ b/Core/Code/Interactions/mitkMousePressEvent.cpp @@ -1,80 +1,77 @@ /*=================================================================== 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 "mitkException.h" #include "mitkMousePressEvent.h" mitk::MousePressEvent::MousePressEvent(mitk::BaseRenderer* baseRenderer, - const mitk::Point2D mousePosition, - mitk::MouseButtons buttonStates, - mitk::ModifierKeys modifiers, - mitk::MouseButtons eventButton) -: InteractionPositionEvent(baseRenderer, mousePosition, "MousePressEvent") + const mitk::Point2D& mousePosition, + MouseButtons buttonStates, + ModifierKeys modifiers, + MouseButtons eventButton) +: InteractionPositionEvent(baseRenderer, mousePosition) , m_EventButton(eventButton) , m_ButtonStates(buttonStates) , m_Modifiers( modifiers) { } -mitk::MouseButtons mitk::MousePressEvent::GetEventButton() const +mitk::InteractionEvent::MouseButtons mitk::MousePressEvent::GetEventButton() const { return m_EventButton; } void mitk::MousePressEvent::SetEventButton(MouseButtons buttons) { m_EventButton = buttons; } -mitk::ModifierKeys mitk::MousePressEvent::GetModifiers() const +mitk::InteractionEvent::ModifierKeys mitk::MousePressEvent::GetModifiers() const { return m_Modifiers; } -mitk::MouseButtons mitk::MousePressEvent::GetButtonStates() const +mitk::InteractionEvent::MouseButtons mitk::MousePressEvent::GetButtonStates() const { return m_ButtonStates; } void mitk::MousePressEvent::SetModifiers(ModifierKeys modifiers) { m_Modifiers = modifiers; } void mitk::MousePressEvent::SetButtonStates(MouseButtons buttons) { m_ButtonStates = buttons; } mitk::MousePressEvent::~MousePressEvent() { } -bool mitk::MousePressEvent::MatchesTemplate(mitk::InteractionEvent::Pointer interactionEvent) +bool mitk::MousePressEvent::IsEqual(const mitk::InteractionEvent& interactionEvent) const { - mitk::MousePressEvent* mpe = dynamic_cast(interactionEvent.GetPointer()); - if (mpe == NULL) - { - return false; - } - return (this->GetEventButton() == mpe->GetEventButton() && this->GetModifiers() == mpe->GetModifiers() - && this->GetButtonStates() == mpe->GetButtonStates()); + const mitk::MousePressEvent& mpe = static_cast(interactionEvent); + return (this->GetEventButton() == mpe.GetEventButton() && this->GetModifiers() == mpe.GetModifiers() + && this->GetButtonStates() == mpe.GetButtonStates() && + Superclass::IsEqual(interactionEvent)); } -bool mitk::MousePressEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) +bool mitk::MousePressEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const { return (dynamic_cast(baseClass.GetPointer()) != NULL) ; } diff --git a/Core/Code/Interactions/mitkMousePressEvent.h b/Core/Code/Interactions/mitkMousePressEvent.h index f15f3f15b4..6b931236a2 100644 --- a/Core/Code/Interactions/mitkMousePressEvent.h +++ b/Core/Code/Interactions/mitkMousePressEvent.h @@ -1,62 +1,63 @@ /*=================================================================== 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 MITKMOUSEPRESSEVENT_H_ #define MITKMOUSEPRESSEVENT_H_ #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkInteractionEventConst.h" #include "mitkInteractionPositionEvent.h" #include "mitkBaseRenderer.h" #include "mitkInteractionEvent.h" #include namespace mitk { class MITK_CORE_EXPORT MousePressEvent: public InteractionPositionEvent { public: mitkClassMacro(MousePressEvent,InteractionPositionEvent) - mitkNewMacro5Param(Self, BaseRenderer*, const Point2D , MouseButtons , ModifierKeys, MouseButtons) + mitkNewMacro5Param(Self, BaseRenderer*, const Point2D& , MouseButtons , ModifierKeys, MouseButtons) ModifierKeys GetModifiers() const; MouseButtons GetButtonStates() const; void SetModifiers(ModifierKeys modifiers); void SetButtonStates(MouseButtons buttons); MouseButtons GetEventButton() const; void SetEventButton(MouseButtons buttons); - virtual bool MatchesTemplate(InteractionEvent::Pointer); - virtual bool IsSuperClassOf(InteractionEvent::Pointer baseClass); + virtual bool IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const; protected: - MousePressEvent(BaseRenderer*, const Point2D = Point2D(), mitk::MouseButtons buttonStates = NoButton, mitk::ModifierKeys modifiers = - NoKey, mitk::MouseButtons eventButton = NoButton); + MousePressEvent(BaseRenderer*, const Point2D& = Point2D(), MouseButtons buttonStates = NoButton, + ModifierKeys modifiers = NoKey, MouseButtons eventButton = NoButton); virtual ~MousePressEvent(); + virtual bool IsEqual(const InteractionEvent&) const; + private: MouseButtons m_EventButton; MouseButtons m_ButtonStates; ModifierKeys m_Modifiers; }; } /* namespace mitk */ #endif /* MITKMOUSEPRESSEVENT_H_ */ diff --git a/Core/Code/Interactions/mitkMouseReleaseEvent.cpp b/Core/Code/Interactions/mitkMouseReleaseEvent.cpp index 1a8a6d5354..00162b9f49 100644 --- a/Core/Code/Interactions/mitkMouseReleaseEvent.cpp +++ b/Core/Code/Interactions/mitkMouseReleaseEvent.cpp @@ -1,83 +1,78 @@ /*=================================================================== 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 "mitkException.h" #include "mitkMouseReleaseEvent.h" mitk::MouseReleaseEvent::MouseReleaseEvent(mitk::BaseRenderer* baseRenderer, - mitk::Point2D mousePosition, - mitk::MouseButtons buttonStates, - mitk::ModifierKeys modifiers, - mitk::MouseButtons eventButton) -: InteractionPositionEvent(baseRenderer, mousePosition, "MouseReleaseEvent") + const mitk::Point2D& mousePosition, + MouseButtons buttonStates, + ModifierKeys modifiers, + MouseButtons eventButton) +: InteractionPositionEvent(baseRenderer, mousePosition) , m_EventButton(eventButton) -,m_ButtonStates(buttonStates) +, m_ButtonStates(buttonStates) , m_Modifiers(modifiers) { } -mitk::MouseButtons mitk::MouseReleaseEvent::GetEventButton() const +mitk::InteractionEvent::MouseButtons mitk::MouseReleaseEvent::GetEventButton() const { return m_EventButton; } void mitk::MouseReleaseEvent::SetEventButton(MouseButtons buttons) { m_EventButton = buttons; } -mitk::ModifierKeys mitk::MouseReleaseEvent::GetModifiers() const +mitk::InteractionEvent::ModifierKeys mitk::MouseReleaseEvent::GetModifiers() const { return m_Modifiers; } -mitk::MouseButtons mitk::MouseReleaseEvent::GetButtonStates() const +mitk::InteractionEvent::MouseButtons mitk::MouseReleaseEvent::GetButtonStates() const { return m_ButtonStates; } void mitk::MouseReleaseEvent::SetModifiers(ModifierKeys modifiers) { m_Modifiers = modifiers; } void mitk::MouseReleaseEvent::SetButtonStates(MouseButtons buttons) { m_ButtonStates = buttons; } mitk::MouseReleaseEvent::~MouseReleaseEvent() { } -bool mitk::MouseReleaseEvent::MatchesTemplate(mitk::InteractionEvent::Pointer interactionEvent) +bool mitk::MouseReleaseEvent::IsEqual(const mitk::InteractionEvent& interactionEvent) const { - mitk::MouseReleaseEvent* mre = dynamic_cast(interactionEvent.GetPointer()); - if (mre == NULL) - { - return false; - } - return (this->GetEventButton() == mre->GetEventButton() && this->GetModifiers() == mre->GetModifiers() - && this->GetButtonStates() == mre->GetButtonStates() - - ); + const mitk::MouseReleaseEvent& mre = static_cast(interactionEvent); + return (this->GetEventButton() == mre.GetEventButton() && this->GetModifiers() == mre.GetModifiers() + && this->GetButtonStates() == mre.GetButtonStates() && + Superclass::IsEqual(interactionEvent)); } -bool mitk::MouseReleaseEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) +bool mitk::MouseReleaseEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const { return (dynamic_cast(baseClass.GetPointer()) != NULL) ; } diff --git a/Core/Code/Interactions/mitkMouseReleaseEvent.h b/Core/Code/Interactions/mitkMouseReleaseEvent.h index 966c4d70da..b2699544a5 100644 --- a/Core/Code/Interactions/mitkMouseReleaseEvent.h +++ b/Core/Code/Interactions/mitkMouseReleaseEvent.h @@ -1,65 +1,66 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKMOUSERELEASEEVENT_H_ #define MITKMOUSERELEASEEVENT_H_ #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkInteractionPositionEvent.h" #include "mitkInteractionEventConst.h" #include "mitkBaseRenderer.h" #include "mitkInteractionEvent.h" #include namespace mitk { class MITK_CORE_EXPORT MouseReleaseEvent: public InteractionPositionEvent { public: mitkClassMacro(MouseReleaseEvent,InteractionPositionEvent) - mitkNewMacro5Param(Self, BaseRenderer*, const Point2D ,MouseButtons , ModifierKeys, MouseButtons) + mitkNewMacro5Param(Self, BaseRenderer*, const Point2D& ,MouseButtons , ModifierKeys, MouseButtons) ModifierKeys GetModifiers() const; MouseButtons GetButtonStates() const; void SetModifiers(ModifierKeys modifiers); void SetButtonStates(MouseButtons buttons); MouseButtons GetEventButton() const; void SetEventButton(MouseButtons buttons); - virtual bool MatchesTemplate(InteractionEvent::Pointer); - virtual bool IsSuperClassOf(InteractionEvent::Pointer baseClass); + virtual bool IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const; protected: MouseReleaseEvent(BaseRenderer*, - mitk::Point2D mousePosition = Point2D(), - mitk::MouseButtons buttonStates = NoButton, - mitk::ModifierKeys modifiers = NoKey, - mitk::MouseButtons eventButton = NoButton); + const mitk::Point2D& mousePosition = Point2D(), + MouseButtons buttonStates = NoButton, + ModifierKeys modifiers = NoKey, + MouseButtons eventButton = NoButton); virtual ~MouseReleaseEvent(); + virtual bool IsEqual(const InteractionEvent&) const; + private: MouseButtons m_EventButton; MouseButtons m_ButtonStates; ModifierKeys m_Modifiers; }; } /* namespace mitk */ #endif /* MITKMOUSERELEASEEVENT_H_ */ diff --git a/Core/Code/Interactions/mitkMouseWheelEvent.cpp b/Core/Code/Interactions/mitkMouseWheelEvent.cpp index d81b1800e3..b6c05a4355 100644 --- a/Core/Code/Interactions/mitkMouseWheelEvent.cpp +++ b/Core/Code/Interactions/mitkMouseWheelEvent.cpp @@ -1,79 +1,76 @@ /*=================================================================== 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 "mitkMouseWheelEvent.h" mitk::MouseWheelEvent::MouseWheelEvent(BaseRenderer* baseRenderer, - Point2D mousePosition, + const Point2D& mousePosition, MouseButtons buttonStates, ModifierKeys modifiers, int wheelDelta) -: InteractionPositionEvent(baseRenderer, mousePosition, "MouseWheelEvent") +: InteractionPositionEvent(baseRenderer, mousePosition) , m_WheelDelta(wheelDelta) , m_ButtonStates(buttonStates) , m_Modifiers(modifiers) { } int mitk::MouseWheelEvent::GetWheelDelta() const { return m_WheelDelta; } void mitk::MouseWheelEvent::SetWheelDelta(int delta) { m_WheelDelta = delta; } -mitk::ModifierKeys mitk::MouseWheelEvent::GetModifiers() const +mitk::InteractionEvent::ModifierKeys mitk::MouseWheelEvent::GetModifiers() const { return m_Modifiers; } -mitk::MouseButtons mitk::MouseWheelEvent::GetButtonStates() const +mitk::InteractionEvent::MouseButtons mitk::MouseWheelEvent::GetButtonStates() const { return m_ButtonStates; } void mitk::MouseWheelEvent::SetModifiers(ModifierKeys modifiers) { m_Modifiers = modifiers; } void mitk::MouseWheelEvent::SetButtonStates(MouseButtons buttons) { m_ButtonStates = buttons; } mitk::MouseWheelEvent::~MouseWheelEvent() { } -bool mitk::MouseWheelEvent::MatchesTemplate(mitk::InteractionEvent::Pointer interactionEvent) +bool mitk::MouseWheelEvent::IsEqual(const mitk::InteractionEvent& interactionEvent) const { - const mitk::MouseWheelEvent* mwe = dynamic_cast(interactionEvent.GetPointer()); - if (mwe == NULL) - { - return false; - } - return ((this->GetWheelDelta() * mwe->GetWheelDelta() > 0) // Consider WheelEvents to be equal if the scrolling is done in the same direction. - && this->GetModifiers() == mwe->GetModifiers() && this->GetButtonStates() == mwe->GetButtonStates()); + const mitk::MouseWheelEvent& mwe = static_cast(interactionEvent); + return ((this->GetWheelDelta() * mwe.GetWheelDelta() > 0) // Consider WheelEvents to be equal if the scrolling is done in the same direction. + && this->GetModifiers() == mwe.GetModifiers() && this->GetButtonStates() == mwe.GetButtonStates() && + Superclass::IsEqual(interactionEvent)); } -bool mitk::MouseWheelEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) +bool mitk::MouseWheelEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const { return (dynamic_cast(baseClass.GetPointer()) != NULL) ; } diff --git a/Core/Code/Interactions/mitkMouseWheelEvent.h b/Core/Code/Interactions/mitkMouseWheelEvent.h index deac97bb56..25caf1c7c0 100644 --- a/Core/Code/Interactions/mitkMouseWheelEvent.h +++ b/Core/Code/Interactions/mitkMouseWheelEvent.h @@ -1,68 +1,69 @@ /*=================================================================== 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 MITKMOUSEWHEELEVENT_H_ #define MITKMOUSEWHEELEVENT_H_ #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkInteractionEventConst.h" #include "mitkInteractionPositionEvent.h" #include "mitkBaseRenderer.h" #include "mitkInteractionEvent.h" #include /** * Note: A Click with the MiddleButton is to be handled with MousePressEvents */ namespace mitk { class MITK_CORE_EXPORT MouseWheelEvent: public InteractionPositionEvent { public: mitkClassMacro(MouseWheelEvent,InteractionPositionEvent) - mitkNewMacro5Param(Self, BaseRenderer*, const Point2D , MouseButtons , ModifierKeys, int) + mitkNewMacro5Param(Self, BaseRenderer*, const Point2D&, MouseButtons , ModifierKeys, int) ModifierKeys GetModifiers() const; MouseButtons GetButtonStates() const; void SetModifiers(ModifierKeys modifiers); void SetButtonStates(MouseButtons buttons); int GetWheelDelta() const; void SetWheelDelta(int delta); - virtual bool MatchesTemplate(InteractionEvent::Pointer); - virtual bool IsSuperClassOf(InteractionEvent::Pointer baseClass); + virtual bool IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const; protected: MouseWheelEvent(BaseRenderer* = NULL, - const Point2D mousePosition = Point2D(), + const Point2D& mousePosition = Point2D(), MouseButtons buttonStates = NoButton, ModifierKeys modifiers = NoKey, int wheelDelta = 0); virtual ~MouseWheelEvent(); + virtual bool IsEqual(const InteractionEvent&) const; + private: int m_WheelDelta; MouseButtons m_ButtonStates; ModifierKeys m_Modifiers; }; } /* namespace mitk */ #endif /* MITKMOUSEPRESSEVENT_H_ */ diff --git a/Core/Code/Interactions/mitkStateMachineAction.cpp b/Core/Code/Interactions/mitkStateMachineAction.cpp index c916a4268e..ecd55a83bb 100644 --- a/Core/Code/Interactions/mitkStateMachineAction.cpp +++ b/Core/Code/Interactions/mitkStateMachineAction.cpp @@ -1,30 +1,30 @@ /*=================================================================== 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 "mitkStateMachineAction.h" -mitk::StateMachineAction::StateMachineAction(std::string actionName) : m_ActionName(actionName) +mitk::StateMachineAction::StateMachineAction(const std::string& actionName) : m_ActionName(actionName) { } std::string mitk::StateMachineAction::GetActionName() const { return m_ActionName; } mitk::StateMachineAction::~StateMachineAction() { } diff --git a/Core/Code/Interactions/mitkStateMachineAction.h b/Core/Code/Interactions/mitkStateMachineAction.h index d054ba7d2d..902f234733 100644 --- a/Core/Code/Interactions/mitkStateMachineAction.h +++ b/Core/Code/Interactions/mitkStateMachineAction.h @@ -1,57 +1,57 @@ /*=================================================================== 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 SMACTION_H_HEADER_INCLUDED_C19AE06B #define SMACTION_H_HEADER_INCLUDED_C19AE06B #include #include "mitkCommon.h" -#include +#include #include #include namespace mitk { //##Documentation //## @brief Represents an action, that is executed after a certain event (in statemachine-mechanism) //## TODO: implement: Is used to connect the Action-Id in an XML Statemachine description with a functor in the StateMachine //## implementation //## @ingroup Interaction - class MITK_CORE_EXPORT StateMachineAction: public itk::Object + class MITK_CORE_EXPORT StateMachineAction: public itk::LightObject { public: - mitkClassMacro(StateMachineAction, itk::Object); - mitkNewMacro1Param(Self, std::string); + mitkClassMacro(StateMachineAction, itk::Object) + mitkNewMacro1Param(Self, const std::string&) /** * @brief Returns the String-Id of this action. **/ std::string GetActionName() const; protected: - StateMachineAction(std::string); + StateMachineAction(const std::string&); ~StateMachineAction(); private: /** * @brief The Id-Name of this action. **/ std::string m_ActionName; }; } // namespace mitk #endif /* SMACTION_H_HEADER_INCLUDED_C19AE06B */ diff --git a/Core/Code/Interactions/mitkStateMachineContainer.cpp b/Core/Code/Interactions/mitkStateMachineContainer.cpp index 3e276ef6f3..3b224851d8 100755 --- a/Core/Code/Interactions/mitkStateMachineContainer.cpp +++ b/Core/Code/Interactions/mitkStateMachineContainer.cpp @@ -1,218 +1,221 @@ /*=================================================================== 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 "mitkStateMachineContainer.h" #include #include #include #include // us +#include "mitkGetModuleContext.h" #include "mitkModule.h" #include "mitkModuleResource.h" #include "mitkModuleResourceStream.h" -#include "mitkModuleRegistry.h" /** * @brief This class builds up all the necessary structures for a statemachine. * and stores one start-state for all built statemachines. **/ //XML StateMachine Tags const std::string NAME = "name"; const std::string CONFIG = "statemachine"; const std::string STATE = "state"; const std::string STATEMODE = "state_mode"; const std::string TRANSITION = "transition"; const std::string EVENTCLASS = "event_class"; const std::string EVENTVARIANT = "event_variant"; const std::string STARTSTATE = "startstate"; const std::string TARGET = "target"; const std::string ACTION = "action"; namespace mitk { vtkStandardNewMacro(StateMachineContainer); } mitk::StateMachineContainer::StateMachineContainer() : m_StartStateFound(false), m_errors(false) { } mitk::StateMachineContainer::~StateMachineContainer() { } /** * @brief Loads the xml file filename and generates the necessary instances. **/ -bool mitk::StateMachineContainer::LoadBehavior(std::string fileName, std::string moduleName) +bool mitk::StateMachineContainer::LoadBehavior(const std::string& fileName, const Module* module) { - mitk::Module* module = mitk::ModuleRegistry::GetModule(moduleName); + if (module == NULL) + { + module = GetModuleContext()->GetModule(); + } mitk::ModuleResource resource = module->GetResource("Interactions/" + fileName); if (!resource.IsValid() ) { mitkThrow() << ("Resource not valid. State machine pattern not found:" + fileName); } mitk::ModuleResourceStream stream(resource); this->SetStream(&stream); m_Filename = fileName; return this->Parse() && !m_errors; } -mitk::StateMachineState::Pointer mitk::StateMachineContainer::GetStartState() +mitk::StateMachineState::Pointer mitk::StateMachineContainer::GetStartState() const { return m_StartState; } /** * @brief sets the pointers in Transition (setNextState(..)) according to the extracted xml-file content **/ void mitk::StateMachineContainer::ConnectStates() { for (StateMachineCollectionType::iterator it = m_States.begin(); it != m_States.end(); ++it) { if ((*it)->ConnectTransitions(&m_States) == false) m_errors = true; } } void mitk::StateMachineContainer::StartElement(const char* elementName, const char **atts) { std::string name(elementName); if (name == CONFIG) { // } else if (name == STATE) { std::string stateName = ReadXMLStringAttribut(NAME, atts); std::transform(stateName.begin(), stateName.end(), stateName.begin(), ::toupper); std::string stateMode = ReadXMLStringAttribut(STATEMODE, atts); std::transform(stateMode.begin(), stateMode.end(), stateMode.begin(), ::toupper); bool isStartState = ReadXMLBooleanAttribut(STARTSTATE, atts); if (isStartState) { m_StartStateFound = true; } // sanitize state modes if (stateMode == "" || stateMode == "REGULAR") { stateMode = "REGULAR"; } else if (stateMode != "GRAB_INPUT" && stateMode != "PREFER_INPUT") { MITK_WARN<< "Invalid State Modus " << stateMode << ". Mode assumed to be REGULAR"; stateMode = "REGULAR"; } m_CurrState = mitk::StateMachineState::New(stateName, stateMode); if (isStartState) m_StartState = m_CurrState; } else if (name == TRANSITION) { std::string eventClass = ReadXMLStringAttribut(EVENTCLASS, atts); std::string eventVariant = ReadXMLStringAttribut(EVENTVARIANT, atts); std::string target = ReadXMLStringAttribut(TARGET, atts); std::transform(target.begin(), target.end(), target.begin(), ::toupper); mitk::StateMachineTransition::Pointer transition = mitk::StateMachineTransition::New(target, eventClass, eventVariant); if (m_CurrState) { m_CurrState->AddTransition(transition); } else { MITK_WARN<< "Malformed Statemachine Pattern. Transition has no origin. \n Will be ignored."; MITK_WARN<< "Malformed Transition details: target="<< target << ", event class:" << eventClass << ", event variant:"<< eventVariant ; } m_CurrTransition = transition; } else if (name == ACTION) { std::string actionName = ReadXMLStringAttribut(NAME, atts); mitk::StateMachineAction::Pointer action = mitk::StateMachineAction::New(actionName); if (m_CurrTransition) m_CurrTransition->AddAction(action); else MITK_WARN<< "Malformed state machine Pattern. Action without transition. \n Will be ignored."; } } void mitk::StateMachineContainer::EndElement(const char* elementName) { std::string name(elementName); if (name == CONFIG) { if (m_StartState.IsNull()) { MITK_ERROR << "State machine pattern has no start state and cannot be used: " << m_Filename; } ConnectStates(); } else if (name == TRANSITION) { m_CurrTransition = NULL; } else if (name == ACTION) { // } else if (name == STATE) { m_States.push_back(m_CurrState); m_CurrState = NULL; } } std::string mitk::StateMachineContainer::ReadXMLStringAttribut(std::string name, const char** atts) { if (atts) { const char** attsIter = atts; while (*attsIter) { if (name == *attsIter) { attsIter++; return *attsIter; } attsIter++; attsIter++; } } return std::string(); } bool mitk::StateMachineContainer::ReadXMLBooleanAttribut(std::string name, const char** atts) { std::string s = ReadXMLStringAttribut(name, atts); std::transform(s.begin(), s.end(), s.begin(), ::toupper); if (s == "TRUE") return true; else return false; } diff --git a/Core/Code/Interactions/mitkStateMachineContainer.h b/Core/Code/Interactions/mitkStateMachineContainer.h index 8f90dfcf8c..5c3c9fc28a 100755 --- a/Core/Code/Interactions/mitkStateMachineContainer.h +++ b/Core/Code/Interactions/mitkStateMachineContainer.h @@ -1,120 +1,121 @@ /*=================================================================== 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 STATEMACHINECONTAINER_H_HEADER_INCLUDED_C19AEDDD #define STATEMACHINECONTAINER_H_HEADER_INCLUDED_C19AEDDD #include #include #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include #include "mitkStateMachineState.h" #include "mitkStateMachineTransition.h" #include "mitkStateMachineAction.h" namespace mitk { - /** - *@brief - * - * @ingroup Interaction - **/ + class Module; - class MITK_CORE_EXPORT StateMachineContainer : public vtkXMLParser + /** + *@brief + * + * @ingroup Interaction + **/ + class StateMachineContainer : public vtkXMLParser { public: static StateMachineContainer *New(); vtkTypeMacro(StateMachineContainer,vtkXMLParser); /** * @brief This type holds all states of one statemachine. **/ typedef std::vector StateMachineCollectionType; /** * @brief Returns the StartState of the StateMachine. **/ - StateMachineState::Pointer GetStartState(); + StateMachineState::Pointer GetStartState() const; /** * @brief Loads XML resource * * Loads a XML resource file in the given module context. * The files have to be placed in the Resources/Interaction folder of their respective module. **/ - bool LoadBehavior(std::string fileName , std::string moduleName = "Mitk"); + bool LoadBehavior(const std::string& fileName , const Module* module); /** * brief To enable StateMachine to access states **/ friend class InteractionStateMachine; protected: StateMachineContainer(); virtual ~StateMachineContainer(); /** * @brief Derived from XMLReader **/ void StartElement (const char* elementName, const char **atts); /** * @brief Derived from XMLReader **/ void EndElement (const char* elementName); private: /** * @brief Derived from XMLReader **/ std::string ReadXMLStringAttribut( std::string name, const char** atts); /** * @brief Derived from XMLReader **/ bool ReadXMLBooleanAttribut( std::string name, const char** atts ); /** * @brief Sets the pointers in Transition (setNextState(..)) according to the extracted xml-file content **/ void ConnectStates(); StateMachineState::Pointer m_StartState; StateMachineState::Pointer m_CurrState; StateMachineTransition::Pointer m_CurrTransition; StateMachineCollectionType m_States; bool m_StartStateFound; bool m_errors; // use member, because of inheritance from vtkXMLParser we can't return a success value for parsing the file. std::string m_Filename; // store file name for debug purposes. }; } // namespace mitk #endif /* STATEMACHINECONTAINER_H_HEADER_INCLUDED_C19AEDDD */ diff --git a/Core/Code/Interactions/mitkStateMachineState.cpp b/Core/Code/Interactions/mitkStateMachineState.cpp index 155b41cb57..d41f01c519 100755 --- a/Core/Code/Interactions/mitkStateMachineState.cpp +++ b/Core/Code/Interactions/mitkStateMachineState.cpp @@ -1,86 +1,88 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStateMachineState.h" -mitk::StateMachineState::StateMachineState(std::string stateName, std::string stateMode) : - m_Name(stateName), m_StateMode(stateMode) +mitk::StateMachineState::StateMachineState(const std::string& stateName, const std::string& stateMode) + : m_Name(stateName) + , m_StateMode(stateMode) { } std::string mitk::StateMachineState::GetMode() const { return m_StateMode; } mitk::StateMachineState::~StateMachineState() { m_Transitions.clear(); } bool mitk::StateMachineState::AddTransition(StateMachineTransition::Pointer transition) { for (TransitionVector::iterator it = m_Transitions.begin(); it != m_Transitions.end(); ++it) { if (transition.GetPointer() == (*it).GetPointer()) return false; } m_Transitions.push_back(transition); return true; } -mitk::StateMachineTransition::Pointer mitk::StateMachineState::GetTransition(const std::string eventClass, const std::string eventVariant) +mitk::StateMachineTransition::Pointer mitk::StateMachineState::GetTransition(const std::string& eventClass, + const std::string& eventVariant) { mitk::StateMachineTransition::Pointer t = mitk::StateMachineTransition::New("", eventClass, eventVariant); for (TransitionVector::iterator it = m_Transitions.begin(); it != m_Transitions.end(); ++it) { if (**it == *t) // do not switch it and t, order matters, see mitk::StateMachineTransition == operator return *it; } return NULL; } std::string mitk::StateMachineState::GetName() const { return m_Name; } //##Documentation //## Post-processing step, when builing StateMachine from XML. //## Parse all transitions and find the State that matches the String-Name. bool mitk::StateMachineState::ConnectTransitions(StateMap *allStates) { for (TransitionVector::iterator transIt = m_Transitions.begin(); transIt != m_Transitions.end(); ++transIt) { bool found = false; for (StateMap::iterator stateIt = allStates->begin(); stateIt != allStates->end(); ++stateIt) { if ((*stateIt)->GetName() == (*transIt)->GetNextStateName()) { (*transIt)->SetNextState(*stateIt); found = true; break; } } if (!found) { MITK_WARN<< "Target State not found in StateMachine."; return false; // only reached if no state matching the string is found } } return true; } diff --git a/Core/Code/Interactions/mitkStateMachineState.h b/Core/Code/Interactions/mitkStateMachineState.h index b83c100ec1..16847f9159 100755 --- a/Core/Code/Interactions/mitkStateMachineState.h +++ b/Core/Code/Interactions/mitkStateMachineState.h @@ -1,90 +1,89 @@ /*=================================================================== 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 SMSTATE_H_HEADER_INCLUDED_C19A8A5D #define SMSTATE_H_HEADER_INCLUDED_C19A8A5D #include #include -#include -#include +#include #include #include "mitkStateMachineTransition.h" namespace mitk { /** * \class StateMachineState * Represents a state of a state machine pattern. * It holds transitions to other states (mitk::StateMachineTransition) and the mode of the current state, see * m_StateMode . */ - class MITK_CORE_EXPORT StateMachineState : public itk::Object + class MITK_CORE_EXPORT StateMachineState : public itk::LightObject { public: - mitkClassMacro(StateMachineState, itk::Object); - mitkNewMacro2Param(Self, std::string, std::string); + mitkClassMacro(StateMachineState, itk::LightObject); + mitkNewMacro2Param(Self, const std::string&, const std::string&); typedef std::vector StateMap; typedef std::vector TransitionVector; bool AddTransition( StateMachineTransition::Pointer transition ); /** * @brief Return Transition which matches given event description. **/ - StateMachineTransition::Pointer GetTransition(const std::string eventClass,const std::string eventVariant); + StateMachineTransition::Pointer GetTransition(const std::string& eventClass,const std::string& eventVariant); /** * @brief Returns the name. **/ std::string GetName() const; std::string GetMode() const; /** * @brief Searches dedicated States of all Transitions and sets *nextState of these Transitions. * Required for this is a List of all build States of that StateMachine (allStates). This way the StateMachine can be build up. **/ bool ConnectTransitions(StateMap* allStates); protected: - StateMachineState(std::string name, std::string stateMode); + StateMachineState(const std::string& name, const std::string& stateMode); ~StateMachineState(); private: /** * @brief Name of this State. **/ std::string m_Name; /** * State Modus, which determines the behavior of the dispatcher. A State can be in three different modes: * REGULAR - standard dispatcher behavior * GRAB_INPUT - all events are given to the statemachine in this modus, if they are not processed by this statemachine the events are dropped. * PREFER_INPUT - events are first given to this statemachine, and if not processed, offered to the other statemachines. */ std::string m_StateMode; /** * @brief map of transitions that lead from this state to the next state **/ TransitionVector m_Transitions; }; } // namespace mitk #endif /* SMSTATE_H_HEADER_INCLUDED_C19A8A5D */ diff --git a/Core/Code/Interactions/mitkStateMachineTransition.cpp b/Core/Code/Interactions/mitkStateMachineTransition.cpp index fcce659d99..d5b629df0e 100755 --- a/Core/Code/Interactions/mitkStateMachineTransition.cpp +++ b/Core/Code/Interactions/mitkStateMachineTransition.cpp @@ -1,96 +1,99 @@ /*=================================================================== 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 "mitkStateMachineTransition.h" #include "mitkStateMachineAction.h" #include "mitkStateMachineState.h" #include "mitkEventFactory.h" #include "mitkInteractionEventConst.h" -mitk::StateMachineTransition::StateMachineTransition(std::string nextStateName, std::string eventClass, std::string eventVariant) : - m_EventClass(eventClass), m_EventVariant(eventVariant), m_NextStateName(nextStateName) +mitk::StateMachineTransition::StateMachineTransition(const std::string& nextStateName, const std::string& eventClass, + const std::string& eventVariant) + : m_EventClass(eventClass) + , m_EventVariant(eventVariant) + , m_NextStateName(nextStateName) { PropertyList::Pointer propertyList = PropertyList::New(); - propertyList->SetStringProperty(xmlParameterEventClass.c_str(), eventClass.c_str()); + propertyList->SetStringProperty(InteractionEventConst::xmlParameterEventClass.c_str(), eventClass.c_str()); m_TransitionEvent = EventFactory::CreateEvent(propertyList); } bool mitk::StateMachineTransition::operator ==(const StateMachineTransition& transition) const { // Create event based on incoming event type, // then try to cast it to the type of event that this transition holds, // if this is possible, the variant is checked // check for NULL since a corrupted state machine might cause an empty event if (m_TransitionEvent.IsNull()) { return false; } PropertyList::Pointer propertyList = PropertyList::New(); - propertyList->SetStringProperty(xmlParameterEventClass.c_str(), transition.m_EventClass.c_str()); + propertyList->SetStringProperty(InteractionEventConst::xmlParameterEventClass.c_str(), transition.m_EventClass.c_str()); InteractionEvent::Pointer tmpEvent = EventFactory::CreateEvent(propertyList); if (tmpEvent.IsNull()) { return false; } if (m_TransitionEvent->IsSuperClassOf(tmpEvent.GetPointer())) { return (this->m_EventVariant == transition.m_EventVariant); } else { // if event variants match, but super class condition is violated // this means that the configuration file, implements a class that does not // support the type in the state machine. if (this->m_EventVariant == transition.m_EventVariant) { MITK_WARN<< "Event type in Statemachine " << m_EventClass << " is not compatible to configuration class " << transition.m_EventClass; } return false; } } mitk::StateMachineTransition::~StateMachineTransition() { //needed for correct reference counting of mitkState//, for real??? m_NextState = NULL; m_Actions.clear(); } -void mitk::StateMachineTransition::AddAction(StateMachineAction::Pointer action) +void mitk::StateMachineTransition::AddAction(const StateMachineAction::Pointer& action) { m_Actions.push_back(action); } mitk::StateMachineState::Pointer mitk::StateMachineTransition::GetNextState() const { return m_NextState; } std::string mitk::StateMachineTransition::GetNextStateName() const { return m_NextStateName; } std::vector mitk::StateMachineTransition::GetActions() const { return m_Actions; } -void mitk::StateMachineTransition::SetNextState(SpStateMachineState nextState) +void mitk::StateMachineTransition::SetNextState(const SpStateMachineState& nextState) { m_NextState = nextState; } diff --git a/Core/Code/Interactions/mitkStateMachineTransition.h b/Core/Code/Interactions/mitkStateMachineTransition.h index fdc94e2802..8e06ba5da6 100755 --- a/Core/Code/Interactions/mitkStateMachineTransition.h +++ b/Core/Code/Interactions/mitkStateMachineTransition.h @@ -1,94 +1,94 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef SMTRANSITION_H_HEADER_INCLUDED #define SMTRANSITION_H_HEADER_INCLUDED #include #include "mitkCommon.h" -#include +#include #include #include #include "mitkStateMachineAction.h" #include "mitkInteractionEvent.h" namespace mitk { class StateMachineState; typedef std::vector ActionVectorType; typedef itk::SmartPointer SpStateMachineState; /** * \class StateMachineTransition * @brief Connects two states, and holds references to actions that are executed on transition. * * @ingroup Interaction **/ - class MITK_CORE_EXPORT StateMachineTransition: public itk::Object + class MITK_CORE_EXPORT StateMachineTransition: public itk::LightObject { public: - mitkClassMacro(StateMachineTransition, itk::Object); - mitkNewMacro3Param(Self, std::string,std::string,std::string); + mitkClassMacro(StateMachineTransition, itk::LightObject); + mitkNewMacro3Param(Self, const std::string&, const std::string&, const std::string&); - void AddAction(StateMachineAction::Pointer action); + void AddAction(const StateMachineAction::Pointer& action); SpStateMachineState GetNextState() const; std::string GetNextStateName() const; /** * Check for equality. Equality is given if event variant is the same and * classes are the same or the first argument is a superclass of the second. * \warn Here the order of arguments matters. ! */ bool operator==(const StateMachineTransition& transition) const; /** * @brief Get an iterator on the first action in list. **/ ActionVectorType GetActions() const; /** * @brief Set the next state of this object. **/ - void SetNextState(SpStateMachineState nextState); + void SetNextState(const SpStateMachineState& nextState); protected: - StateMachineTransition(std::string nextStateName, std::string eventClass, std::string eventVariant); + StateMachineTransition(const std::string& nextStateName, const std::string& eventClass, const std::string& eventVariant); virtual ~StateMachineTransition(); // Triggering Event std::string m_EventClass; std::string m_EventVariant; private: SpStateMachineState m_NextState; std::string m_NextStateName; InteractionEvent::Pointer m_TransitionEvent; /** * @brief The list of actions, that are executed if this transition is done. **/ std::vector m_Actions; }; } // namespace mitk #endif /* SMTRANSITION_H_HEADER_INCLUDED */ diff --git a/Core/Code/Interactions/mitkVtkEventAdapter.cpp b/Core/Code/Interactions/mitkVtkEventAdapter.cpp index 21612021f1..2b5b907da3 100644 --- a/Core/Code/Interactions/mitkVtkEventAdapter.cpp +++ b/Core/Code/Interactions/mitkVtkEventAdapter.cpp @@ -1,453 +1,463 @@ /*=================================================================== 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 "mitkVtkEventAdapter.h" #include // INTERACTION LEGACY #include // INTERACTION LEGACY #include "mitkInteractionEventConst.h" #include #include "vtkCommand.h" namespace mitk { std::map VtkEventAdapter::buttonStateMap; } mitk::MouseEvent mitk::VtkEventAdapter::AdaptMouseEvent(mitk::BaseRenderer* sender, unsigned long vtkCommandEventId, vtkRenderWindowInteractor* rwi) { mitk::Point2D p; p[0] = rwi->GetEventPosition()[0]; p[1] = rwi->GetEventPosition()[1]; p[1] = rwi->GetSize()[1] - p[1]; // flip y axis // http://doc.trolltech.com/4.6/qt.html#MouseButton-enum int button = 0; int type = 0; int state = 0; // vtkRenderWindowInteractor does not provide information about mouse buttons during // mouse move events... // some button action might be going on during mouse move events // that needs to be temp. saved in our buttonStateMap int tmpstate = 0; if (buttonStateMap.find(sender) != buttonStateMap.end()) tmpstate = buttonStateMap.find(sender)->second; if (tmpstate != 0 && vtkCommandEventId != vtkCommand::MouseMoveEvent) buttonStateMap.erase(buttonStateMap.find(sender)); //press or release event with active map caching switch (vtkCommandEventId) { case vtkCommand::MouseMoveEvent: type = 5; button = mitk::BS_NoButton; if (tmpstate != 0) { state = tmpstate; /* // debug output static char tmp; sprintf(&tmp,"%d",tmpstate); std::cout << tmp << std::endl; */ } break; case vtkCommand::LeftButtonReleaseEvent: type = 3; button = mitk::BS_LeftButton; state = tmpstate; buttonStateMap[sender] = (tmpstate - button); break; case vtkCommand::MiddleButtonReleaseEvent: type = 3; button = mitk::BS_MidButton; state = tmpstate; buttonStateMap[sender] = (tmpstate - button); break; case vtkCommand::RightButtonReleaseEvent: type = 3; button = mitk::BS_RightButton; state = tmpstate; buttonStateMap[sender] = (tmpstate - button); break; case vtkCommand::LeftButtonPressEvent: type = 2; button = mitk::BS_LeftButton; tmpstate |= button; buttonStateMap[sender] = tmpstate; break; case vtkCommand::MiddleButtonPressEvent: type = 2; button = mitk::BS_MidButton; tmpstate |= button; buttonStateMap[sender] = tmpstate; break; case vtkCommand::RightButtonPressEvent: type = 2; button = mitk::BS_RightButton; tmpstate |= button; buttonStateMap[sender] = tmpstate; break; } if (rwi->GetShiftKey()) { state |= mitk::BS_ShiftButton; } if (rwi->GetControlKey()) { state |= mitk::BS_ControlButton; } if (rwi->GetAltKey()) { state |= mitk::BS_AltButton; } mitk::MouseEvent mitkEvent(sender, type, button, state, mitk::Key_none, p); return mitkEvent; } mitk::WheelEvent //mitk::VtkEventAdapter::AdaptWheelEvent(mitk::BaseRenderer* sender, QWheelEvent* wheelEvent) mitk::VtkEventAdapter::AdaptWheelEvent(mitk::BaseRenderer* sender, unsigned long vtkCommandEventId, vtkRenderWindowInteractor* rwi) { mitk::Point2D p; p[0] = rwi->GetEventPosition()[0]; p[1] = rwi->GetEventPosition()[1]; // http://doc.trolltech.com/4.6/qt.html#MouseButton-enum int button = 0; int type = 0; int state = 0; int delta = 0; switch (vtkCommandEventId) { case vtkCommand::MouseWheelForwardEvent: type = 31; // wheel event, // see qcoreevent enum "type" button = 0x00000000; delta = +120; //http://doc.trolltech.com/3.3/qwheelevent.html#delta break; case vtkCommand::MouseWheelBackwardEvent: type = 31; // wheel event, // see qcoreevent enum "type" button = 0x00000000; delta = -120; //http://doc.trolltech.com/3.3/qwheelevent.html#delta break; } if (rwi->GetShiftKey()) state |= mitk::BS_ShiftButton; if (rwi->GetControlKey()) state |= mitk::BS_ControlButton; if (rwi->GetAltKey()) state |= mitk::BS_AltButton; mitk::WheelEvent mitkEvent(sender, type, button, state, mitk::Key_none, p, delta); return mitkEvent; } mitk::KeyEvent //mitk::VtkEventAdapter::AdaptKeyEvent(mitk::BaseRenderer* sender, QKeyEvent* keyEvent, const QPoint& cp) mitk::VtkEventAdapter::AdaptKeyEvent(mitk::BaseRenderer* sender, unsigned long vtkCommandEventId, vtkRenderWindowInteractor* rwi) { // TODO: is this viable? int key = (int) rwi->GetKeyCode(); // Those keycodes changed in Qt 4 if (key >= 0x01000000 && key <= 0x01000060) key -= (0x01000000 - 0x1000); else if (key >= 0x01001120 && key <= 0x01001262) key -= 0x01000000; mitk::Point2D p; p[0] = rwi->GetEventPosition()[0]; p[1] = rwi->GetEventPosition()[1]; int type = 0; if (vtkCommandEventId == vtkCommand::KeyPressEvent) type = 6; // http://doc.trolltech.com/4.6/qevent.html#Type-enum int state = 0; if (rwi->GetShiftKey()) state |= mitk::BS_ShiftButton; if (rwi->GetControlKey()) state |= mitk::BS_ControlButton; if (rwi->GetAltKey()) state |= mitk::BS_AltButton; mitk::KeyEvent mke(sender, type, mitk::BS_NoButton, state, key, std::string(rwi->GetKeySym()), p); return mke; } mitk::MousePressEvent::Pointer mitk::VtkEventAdapter::AdaptMousePressEvent(mitk::BaseRenderer* sender, unsigned long vtkCommandEventId, vtkRenderWindowInteractor* rwi) { mitk::Point2D point; point[0] = rwi->GetEventPosition()[0]; point[1] = rwi->GetEventPosition()[1]; point[1] = rwi->GetSize()[1] - point[1]; // flip y axis int button = 0; int modifiers = 0; int buttonState = 0; // vtkRenderWindowInteractor does not provide information about mouse buttons during // mouse move events therefore the Press/Release functions update the button state in the buttonStateMap // this button state is then provided for mouse move events if (buttonStateMap.find(sender) != buttonStateMap.end()) buttonState = buttonStateMap.find(sender)->second; if (buttonState != 0 && vtkCommandEventId != vtkCommand::MouseMoveEvent) buttonStateMap.erase(buttonStateMap.find(sender)); //press or release event with active map caching switch (vtkCommandEventId) { case vtkCommand::LeftButtonPressEvent: - button = mitk::LeftMouseButton; + button = InteractionEvent::LeftMouseButton; buttonState |= button; buttonStateMap[sender] = buttonState; break; case vtkCommand::MiddleButtonPressEvent: - button = mitk::MiddleMouseButton; + button = InteractionEvent::MiddleMouseButton; buttonState |= button; buttonStateMap[sender] = buttonState; break; case vtkCommand::RightButtonPressEvent: - button = mitk::RightMouseButton; + button = InteractionEvent::RightMouseButton; buttonState |= button; buttonStateMap[sender] = buttonState; break; } if (rwi->GetShiftKey()) { - modifiers |= mitk::ShiftKey; + modifiers |= InteractionEvent::ShiftKey; } if (rwi->GetControlKey()) { - modifiers |= mitk::ControlKey; + modifiers |= InteractionEvent::ControlKey; } if (rwi->GetAltKey()) { - modifiers |= mitk::AltKey; + modifiers |= InteractionEvent::AltKey; } - MousePressEvent::Pointer mpe = MousePressEvent::New(sender, point, (MouseButtons) buttonState, (ModifierKeys) modifiers, - (MouseButtons) button); + MousePressEvent::Pointer mpe = MousePressEvent::New(sender, point, + static_cast(buttonState), + static_cast(modifiers), + static_cast(button)); return mpe; } mitk::MouseMoveEvent::Pointer mitk::VtkEventAdapter::AdaptMouseMoveEvent(mitk::BaseRenderer* sender, unsigned long vtkCommandEventId, vtkRenderWindowInteractor* rwi) { mitk::Point2D point; point[0] = rwi->GetEventPosition()[0]; point[1] = rwi->GetEventPosition()[1]; point[1] = rwi->GetSize()[1] - point[1]; // flip y axis int modifiers = 0; // vtkRenderWindowInteractor does not provide information about mouse buttons during // mouse move events therefore the Press/Release functions update the button state in the buttonStateMap // this button state is then provided for mouse move events int buttonState = 0; if (buttonStateMap.find(sender) != buttonStateMap.end()) { // set stored button state buttonState = buttonStateMap.find(sender)->second; } if (vtkCommandEventId == vtkCommand::MouseMoveEvent) { if (buttonState != 0) { modifiers = buttonState; } } else { MITK_WARN<< "Wrong usage of function AdaptMouseMoveEvent. Wrong input type."; } if (rwi->GetShiftKey()) { - modifiers |= mitk::ShiftKey; + modifiers |= InteractionEvent::ShiftKey; } if (rwi->GetControlKey()) { - modifiers |= mitk::ControlKey; + modifiers |= InteractionEvent::ControlKey; } if (rwi->GetAltKey()) { - modifiers |= mitk::AltKey; + modifiers |= InteractionEvent::AltKey; } - MouseMoveEvent::Pointer mme = MouseMoveEvent::New(sender, point, (MouseButtons) buttonState, (ModifierKeys) modifiers); + MouseMoveEvent::Pointer mme = MouseMoveEvent::New(sender, point, + static_cast(buttonState), + static_cast(modifiers)); return mme; } mitk::MouseReleaseEvent::Pointer mitk::VtkEventAdapter::AdaptMouseReleaseEvent(mitk::BaseRenderer* sender, unsigned long vtkCommandEventId, vtkRenderWindowInteractor* rwi) { mitk::Point2D point; point[0] = rwi->GetEventPosition()[0]; point[1] = rwi->GetEventPosition()[1]; point[1] = rwi->GetSize()[1] - point[1]; // flip y axis int button = 0; int modifiers = 0; int buttonState = 0; // vtkRenderWindowInteractor does not provide information about mouse buttons during // mouse move events therefore the Press/Release functions update the button state in the buttonStateMap // this button state is then provided for mouse move events if (buttonStateMap.find(sender) != buttonStateMap.end()) buttonState = buttonStateMap.find(sender)->second; if (buttonState != 0 && vtkCommandEventId != vtkCommand::MouseMoveEvent) buttonStateMap.erase(buttonStateMap.find(sender)); //press or release event with active map caching switch (vtkCommandEventId) { case vtkCommand::LeftButtonReleaseEvent: - button = mitk::LeftMouseButton; + button = InteractionEvent::LeftMouseButton; // remove left mouse button from button state buttonStateMap[sender] = (buttonState - button); break; case vtkCommand::MiddleButtonReleaseEvent: - button = mitk::MiddleMouseButton; + button = InteractionEvent::MiddleMouseButton; // remove middle button from button state buttonStateMap[sender] = (buttonState - button); break; case vtkCommand::RightButtonReleaseEvent: - button = mitk::RightMouseButton; + button = InteractionEvent::RightMouseButton; // remove right mouse button from button state buttonStateMap[sender] = (buttonState - button); break; } if (rwi->GetShiftKey()) { - modifiers |= mitk::ShiftKey; + modifiers |= InteractionEvent::ShiftKey; } if (rwi->GetControlKey()) { - modifiers |= mitk::ControlKey; + modifiers |= InteractionEvent::ControlKey; } if (rwi->GetAltKey()) { - modifiers |= mitk::AltKey; + modifiers |= InteractionEvent::AltKey; } // after releasing button is no longer pressed, to update it if (buttonStateMap.find(sender) != buttonStateMap.end()) { buttonState = buttonStateMap.find(sender)->second; } - MouseReleaseEvent::Pointer mre = MouseReleaseEvent::New(sender, point, (MouseButtons) buttonState, (ModifierKeys) modifiers, - (MouseButtons) button); + MouseReleaseEvent::Pointer mre = MouseReleaseEvent::New(sender, point, + static_cast(buttonState), + static_cast(modifiers), + static_cast(button)); return mre; } mitk::MouseWheelEvent::Pointer mitk::VtkEventAdapter::AdaptMouseWheelEvent(mitk::BaseRenderer* sender, unsigned long vtkCommandEventId, vtkRenderWindowInteractor* rwi) { mitk::Point2D p; p[0] = rwi->GetEventPosition()[0]; p[1] = rwi->GetEventPosition()[1]; int delta = 0; switch (vtkCommandEventId) { case vtkCommand::MouseWheelForwardEvent: delta = +120; //http://doc.trolltech.com/3.3/qwheelevent.html#delta break; case vtkCommand::MouseWheelBackwardEvent: delta = -120; //http://doc.trolltech.com/3.3/qwheelevent.html#delta break; } int modifiers = 0; if (rwi->GetShiftKey()) { modifiers |= mitk::BS_ShiftButton; } if (rwi->GetControlKey()) { modifiers |= mitk::BS_ControlButton; } if (rwi->GetAltKey()) { modifiers |= mitk::BS_AltButton; } mitk::Point2D point; point[0] = rwi->GetEventPosition()[0]; point[1] = rwi->GetEventPosition()[1]; point[1] = rwi->GetSize()[1] - point[1]; // flip y axis // vtkWheelEvent does not have a buttonState or event button int buttonState = 0; - MouseWheelEvent::Pointer mpe = MouseWheelEvent::New(sender, point, (MouseButtons) buttonState, (ModifierKeys) modifiers, delta); + MouseWheelEvent::Pointer mpe = MouseWheelEvent::New(sender, point, + static_cast(buttonState), + static_cast(modifiers), + delta); return mpe; } mitk::InteractionKeyEvent::Pointer mitk::VtkEventAdapter::AdaptInteractionKeyEvent(mitk::BaseRenderer* sender, unsigned long vtkCommandEventId, vtkRenderWindowInteractor* rwi) { if (vtkCommandEventId != vtkCommand::KeyPressEvent) { MITK_WARN<< "mitk::VtkEventAdapter::AdaptInteractionKeyEvent() called with wrong argument"; return NULL; } int modifiers = 0; if (rwi->GetShiftKey()) { modifiers |= mitk::BS_ShiftButton;} if (rwi->GetControlKey()) { modifiers |= mitk::BS_ControlButton;} if (rwi->GetAltKey()) { modifiers |= mitk::BS_AltButton; } - InteractionKeyEvent::Pointer ike = InteractionKeyEvent::New(sender, std::string(rwi->GetKeySym()), (ModifierKeys)modifiers ); + InteractionKeyEvent::Pointer ike = InteractionKeyEvent::New(sender, std::string(rwi->GetKeySym()), + static_cast(modifiers)); return ike; } diff --git a/Core/Code/Interfaces/mitkInteractionEventObserver.cpp b/Core/Code/Interfaces/mitkInteractionEventObserver.cpp index cb98786e3f..1d6f89e772 100644 --- a/Core/Code/Interfaces/mitkInteractionEventObserver.cpp +++ b/Core/Code/Interfaces/mitkInteractionEventObserver.cpp @@ -1,41 +1,41 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkInteractionEventObserver.h" mitk::InteractionEventObserver::InteractionEventObserver() : m_IsEnabled(true) { } mitk::InteractionEventObserver::~InteractionEventObserver() { } void mitk::InteractionEventObserver::Disable() { m_IsEnabled = false; } void mitk::InteractionEventObserver::Enable() { m_IsEnabled = true; } -bool mitk::InteractionEventObserver::IsEnabled() +bool mitk::InteractionEventObserver::IsEnabled() const { return m_IsEnabled; } diff --git a/Core/Code/Interfaces/mitkInteractionEventObserver.h b/Core/Code/Interfaces/mitkInteractionEventObserver.h index de1cee1fe0..fc22d9567a 100644 --- a/Core/Code/Interfaces/mitkInteractionEventObserver.h +++ b/Core/Code/Interfaces/mitkInteractionEventObserver.h @@ -1,69 +1,69 @@ /*=================================================================== 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 InteractionEventObserver_h #define InteractionEventObserver_h #include #include "mitkServiceInterface.h" #include "mitkInteractionEvent.h" namespace mitk { /** * \class InteractionEventObserver * \brief Base class to implement InteractionEventObservers. * * This class also provides state machine infrastructure, * but usage thereof is optional. See the Notify method for more information. */ struct MITK_CORE_EXPORT InteractionEventObserver { InteractionEventObserver(); virtual ~InteractionEventObserver(); /** * By this method all registered EventObersers are notified about every InteractionEvent, * the isHandled flag indicates if a DataInteractor has already handled that event. * InteractionEventObserver that trigger an action when observing an event may consider * this in order to not confuse the user by, triggering several independent action with one * single user event (such as a mouse click) * * If you want to use the InteractionEventObserver as a state machine give the event to the state machine by implementing, e.g. \code void mitk::InteractionEventObserver::Notify(InteractionEvent::Pointer interactionEvent, bool isHandled) { if (!isHandled) { this->HandleEvent(interactionEvent, NULL); } } \endcode * This overwrites the FilterEvents function of the EventStateMachine to ignore the DataNode, since InteractionEventObservers are not associated with one. virtual bool FilterEvents(InteractionEvent* interactionEvent, DataNode* dataNode); */ virtual void Notify(InteractionEvent* interactionEvent,bool isHandled) = 0; void Disable(); void Enable(); - bool IsEnabled(); + bool IsEnabled() const; private: bool m_IsEnabled; }; } /* namespace mitk */ US_DECLARE_SERVICE_INTERFACE(mitk::InteractionEventObserver, "org.mitk.InteractionEventObserver") #endif /* InteractionEventObserver_h */ diff --git a/Core/Code/Rendering/mitkBaseRenderer.cpp b/Core/Code/Rendering/mitkBaseRenderer.cpp index 0e1015498e..307c375223 100644 --- a/Core/Code/Rendering/mitkBaseRenderer.cpp +++ b/Core/Code/Rendering/mitkBaseRenderer.cpp @@ -1,835 +1,836 @@ /*=================================================================== 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 "mitkBaseRenderer.h" #include "mitkMapper.h" #include "mitkResliceMethodProperty.h" +#include "mitkKeyEvent.h" // Geometries #include "mitkPlaneGeometry.h" #include "mitkSlicedGeometry3D.h" // Controllers #include "mitkCameraController.h" #include "mitkSliceNavigationController.h" #include "mitkCameraRotationController.h" #include "mitkVtkInteractorCameraController.h" #ifdef MITK_USE_TD_MOUSE #include "mitkTDMouseVtkCameraController.h" #else #include "mitkCameraController.h" #endif #include "mitkVtkLayerController.h" // Events // TODO: INTERACTION_LEGACY #include "mitkEventMapper.h" #include "mitkGlobalInteraction.h" #include "mitkPositionEvent.h" #include "mitkDisplayPositionEvent.h" #include "mitkProperties.h" #include "mitkWeakPointerProperty.h" #include "mitkInteractionConst.h" // VTK #include #include #include #include #include #include #include mitk::BaseRenderer::BaseRendererMapType mitk::BaseRenderer::baseRendererMap; mitk::BaseRenderer* mitk::BaseRenderer::GetInstance(vtkRenderWindow * renWin) { for (BaseRendererMapType::iterator mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); mapit++) { if ((*mapit).first == renWin) return (*mapit).second; } return NULL; } void mitk::BaseRenderer::AddInstance(vtkRenderWindow* renWin, BaseRenderer* baseRenderer) { if (renWin == NULL || baseRenderer == NULL) return; // ensure that no BaseRenderer is managed twice mitk::BaseRenderer::RemoveInstance(renWin); baseRendererMap.insert(BaseRendererMapType::value_type(renWin, baseRenderer)); } void mitk::BaseRenderer::RemoveInstance(vtkRenderWindow* renWin) { BaseRendererMapType::iterator mapit = baseRendererMap.find(renWin); if (mapit != baseRendererMap.end()) baseRendererMap.erase(mapit); } mitk::BaseRenderer* mitk::BaseRenderer::GetByName(const std::string& name) { for (BaseRendererMapType::iterator mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); mapit++) { if ((*mapit).second->m_Name == name) return (*mapit).second; } return NULL; } vtkRenderWindow* mitk::BaseRenderer::GetRenderWindowByName(const std::string& name) { for (BaseRendererMapType::iterator mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); mapit++) { if ((*mapit).second->m_Name == name) return (*mapit).first; } return NULL; } mitk::BaseRenderer::BaseRenderer(const char* name, vtkRenderWindow * renWin, mitk::RenderingManager* rm) : m_RenderWindow(NULL), m_VtkRenderer(NULL), m_MapperID(defaultMapper), m_DataStorage(NULL), m_RenderingManager(rm), m_LastUpdateTime(0), m_CameraController( NULL), m_SliceNavigationController(NULL), m_CameraRotationController(NULL), /*m_Size(),*/ m_Focused(false), m_WorldGeometry(NULL), m_TimeSlicedWorldGeometry(NULL), m_CurrentWorldGeometry(NULL), m_CurrentWorldGeometry2D(NULL), m_DisplayGeometry( NULL), m_Slice(0), m_TimeStep(), m_CurrentWorldGeometry2DUpdateTime(), m_DisplayGeometryUpdateTime(), m_TimeStepUpdateTime(), m_WorldGeometryData( NULL), m_DisplayGeometryData(NULL), m_CurrentWorldGeometry2DData(NULL), m_WorldGeometryNode(NULL), m_DisplayGeometryNode(NULL), m_CurrentWorldGeometry2DNode( NULL), m_DisplayGeometryTransformTime(0), m_CurrentWorldGeometry2DTransformTime(0), m_Name(name), /*m_Bounds(),*/m_EmptyWorldGeometry( true), m_DepthPeelingEnabled(true), m_MaxNumberOfPeels(100), m_NumberOfVisibleLODEnabledMappers(0) { m_Bounds[0] = 0; m_Bounds[1] = 0; m_Bounds[2] = 0; m_Bounds[3] = 0; m_Bounds[4] = 0; m_Bounds[5] = 0; if (name != NULL) { m_Name = name; } else { m_Name = "unnamed renderer"; itkWarningMacro(<< "Created unnamed renderer. Bad for serialization. Please choose a name."); } if (renWin != NULL) { m_RenderWindow = renWin; m_RenderWindow->Register(NULL); } else { itkWarningMacro(<< "Created mitkBaseRenderer without vtkRenderWindow present."); } m_Size[0] = 0; m_Size[1] = 0; //instances.insert( this ); //adding this BaseRenderer to the List of all BaseRenderer // TODO: INTERACTION_LEGACY m_RenderingManager->GetGlobalInteraction()->AddFocusElement(this); m_BindDispatcherInteractor = new mitk::BindDispatcherInteractor(); WeakPointerProperty::Pointer rendererProp = WeakPointerProperty::New((itk::Object*) this); m_CurrentWorldGeometry2D = mitk::PlaneGeometry::New(); m_CurrentWorldGeometry2DData = mitk::Geometry2DData::New(); m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D); m_CurrentWorldGeometry2DNode = mitk::DataNode::New(); m_CurrentWorldGeometry2DNode->SetData(m_CurrentWorldGeometry2DData); m_CurrentWorldGeometry2DNode->GetPropertyList()->SetProperty("renderer", rendererProp); m_CurrentWorldGeometry2DNode->GetPropertyList()->SetProperty("layer", IntProperty::New(1000)); m_CurrentWorldGeometry2DNode->SetProperty("reslice.thickslices", mitk::ResliceMethodProperty::New()); m_CurrentWorldGeometry2DNode->SetProperty("reslice.thickslices.num", mitk::IntProperty::New(1)); m_CurrentWorldGeometry2DTransformTime = m_CurrentWorldGeometry2DNode->GetVtkTransform()->GetMTime(); m_DisplayGeometry = mitk::DisplayGeometry::New(); m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D); m_DisplayGeometryData = mitk::Geometry2DData::New(); m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry); m_DisplayGeometryNode = mitk::DataNode::New(); m_DisplayGeometryNode->SetData(m_DisplayGeometryData); m_DisplayGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp); m_DisplayGeometryTransformTime = m_DisplayGeometryNode->GetVtkTransform()->GetMTime(); mitk::SliceNavigationController::Pointer sliceNavigationController = mitk::SliceNavigationController::New("navigation"); sliceNavigationController->SetRenderer(this); sliceNavigationController->ConnectGeometrySliceEvent(this); sliceNavigationController->ConnectGeometryUpdateEvent(this); sliceNavigationController->ConnectGeometryTimeEvent(this, false); m_SliceNavigationController = sliceNavigationController; m_CameraRotationController = mitk::CameraRotationController::New(); m_CameraRotationController->SetRenderWindow(m_RenderWindow); m_CameraRotationController->AcquireCamera(); //if TD Mouse Interaction is activated, then call TDMouseVtkCameraController instead of VtkInteractorCameraController #ifdef MITK_USE_TD_MOUSE m_CameraController = mitk::TDMouseVtkCameraController::New(); #else m_CameraController = mitk::CameraController::New(NULL); #endif m_VtkRenderer = vtkRenderer::New(); if (mitk::VtkLayerController::GetInstance(m_RenderWindow) == NULL) { mitk::VtkLayerController::AddInstance(m_RenderWindow, m_VtkRenderer); mitk::VtkLayerController::GetInstance(m_RenderWindow)->InsertSceneRenderer(m_VtkRenderer); } else mitk::VtkLayerController::GetInstance(m_RenderWindow)->InsertSceneRenderer(m_VtkRenderer); } mitk::BaseRenderer::~BaseRenderer() { if (m_VtkRenderer != NULL) { m_VtkRenderer->Delete(); m_VtkRenderer = NULL; } if (m_CameraController.IsNotNull()) m_CameraController->SetRenderer(NULL); m_RenderingManager->GetGlobalInteraction()->RemoveFocusElement(this); mitk::VtkLayerController::RemoveInstance(m_RenderWindow); RemoveAllLocalStorages(); m_DataStorage = NULL; if (m_BindDispatcherInteractor != NULL) { delete m_BindDispatcherInteractor; } if (m_RenderWindow != NULL) { m_RenderWindow->Delete(); m_RenderWindow = NULL; } } void mitk::BaseRenderer::RemoveAllLocalStorages() { this->InvokeEvent(mitk::BaseRenderer::RendererResetEvent()); std::list::iterator it; for (it = m_RegisteredLocalStorageHandlers.begin(); it != m_RegisteredLocalStorageHandlers.end(); it++) (*it)->ClearLocalStorage(this, false); m_RegisteredLocalStorageHandlers.clear(); } void mitk::BaseRenderer::RegisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh) { m_RegisteredLocalStorageHandlers.push_back(lsh); } -mitk::Dispatcher::Pointer mitk::BaseRenderer::GetDispatcher() +mitk::Dispatcher::Pointer mitk::BaseRenderer::GetDispatcher() const { return m_BindDispatcherInteractor->GetDispatcher(); } mitk::Point3D mitk::BaseRenderer::Map2DRendererPositionTo3DWorldPosition(Point2D* mousePosition) const { Point2D p_mm; Point3D position; if (m_MapperID == 1) { GetDisplayGeometry()->ULDisplayToDisplay(*mousePosition, *mousePosition); GetDisplayGeometry()->DisplayToWorld(*mousePosition, p_mm); GetDisplayGeometry()->Map(p_mm, position); } else if (m_MapperID == 2) { GetDisplayGeometry()->ULDisplayToDisplay(*mousePosition, *mousePosition); PickWorldPoint(*mousePosition, position); } return position; } void mitk::BaseRenderer::UnregisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh) { m_RegisteredLocalStorageHandlers.remove(lsh); } void mitk::BaseRenderer::SetDataStorage(DataStorage* storage) { if (storage != NULL) { m_DataStorage = storage; m_BindDispatcherInteractor->SetDataStorage(m_DataStorage); this->Modified(); } } const mitk::BaseRenderer::MapperSlotId mitk::BaseRenderer::defaultMapper = 1; void mitk::BaseRenderer::Paint() { } void mitk::BaseRenderer::Initialize() { } void mitk::BaseRenderer::Resize(int w, int h) { m_Size[0] = w; m_Size[1] = h; if (m_CameraController) m_CameraController->Resize(w, h); //(formerly problematic on windows: vtkSizeBug) GetDisplayGeometry()->SetSizeInDisplayUnits(w, h); } void mitk::BaseRenderer::InitRenderer(vtkRenderWindow* renderwindow) { if (m_RenderWindow != NULL) { m_RenderWindow->Delete(); } m_RenderWindow = renderwindow; if (m_RenderWindow != NULL) { m_RenderWindow->Register(NULL); } RemoveAllLocalStorages(); if (m_CameraController.IsNotNull()) { m_CameraController->SetRenderer(this); } //BUG (#1551) added settings for depth peeling m_RenderWindow->SetAlphaBitPlanes(1); m_VtkRenderer->SetUseDepthPeeling(m_DepthPeelingEnabled); m_VtkRenderer->SetMaximumNumberOfPeels(m_MaxNumberOfPeels); m_VtkRenderer->SetOcclusionRatio(0.1); } void mitk::BaseRenderer::InitSize(int w, int h) { m_Size[0] = w; m_Size[1] = h; GetDisplayGeometry()->SetSizeInDisplayUnits(w, h, false); GetDisplayGeometry()->Fit(); } void mitk::BaseRenderer::SetSlice(unsigned int slice) { if (m_Slice != slice) { m_Slice = slice; if (m_TimeSlicedWorldGeometry.IsNotNull()) { SlicedGeometry3D* slicedWorldGeometry = dynamic_cast(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep)); if (slicedWorldGeometry != NULL) { if (m_Slice >= slicedWorldGeometry->GetSlices()) m_Slice = slicedWorldGeometry->GetSlices() - 1; SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice)); SetCurrentWorldGeometry(slicedWorldGeometry); } } else Modified(); } } void mitk::BaseRenderer::SetTimeStep(unsigned int timeStep) { if (m_TimeStep != timeStep) { m_TimeStep = timeStep; m_TimeStepUpdateTime.Modified(); if (m_TimeSlicedWorldGeometry.IsNotNull()) { if (m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps()) m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps() - 1; SlicedGeometry3D* slicedWorldGeometry = dynamic_cast(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep)); if (slicedWorldGeometry != NULL) { SetCurrentWorldGeometry2D(slicedWorldGeometry->GetGeometry2D(m_Slice)); SetCurrentWorldGeometry(slicedWorldGeometry); } } else Modified(); } } int mitk::BaseRenderer::GetTimeStep(const mitk::BaseData* data) const { if ((data == NULL) || (data->IsInitialized() == false)) { return -1; } return data->GetTimeSlicedGeometry()->MSToTimeStep(GetTime()); } mitk::ScalarType mitk::BaseRenderer::GetTime() const { if (m_TimeSlicedWorldGeometry.IsNull()) { return 0; } else { ScalarType timeInMS = m_TimeSlicedWorldGeometry->TimeStepToMS(GetTimeStep()); if (timeInMS == ScalarTypeNumericTraits::NonpositiveMin()) return 0; else return timeInMS; } } void mitk::BaseRenderer::SetWorldGeometry(mitk::Geometry3D* geometry) { itkDebugMacro("setting WorldGeometry to " << geometry); if (m_WorldGeometry != geometry) { if (geometry->GetBoundingBox()->GetDiagonalLength2() == 0) return; m_WorldGeometry = geometry; m_TimeSlicedWorldGeometry = dynamic_cast(geometry); SlicedGeometry3D* slicedWorldGeometry; if (m_TimeSlicedWorldGeometry.IsNotNull()) { itkDebugMacro("setting TimeSlicedWorldGeometry to " << m_TimeSlicedWorldGeometry); if (m_TimeStep >= m_TimeSlicedWorldGeometry->GetTimeSteps()) m_TimeStep = m_TimeSlicedWorldGeometry->GetTimeSteps() - 1; slicedWorldGeometry = dynamic_cast(m_TimeSlicedWorldGeometry->GetGeometry3D(m_TimeStep)); } else { slicedWorldGeometry = dynamic_cast(geometry); } Geometry2D::Pointer geometry2d; if (slicedWorldGeometry != NULL) { if (m_Slice >= slicedWorldGeometry->GetSlices() && (m_Slice != 0)) m_Slice = slicedWorldGeometry->GetSlices() - 1; geometry2d = slicedWorldGeometry->GetGeometry2D(m_Slice); if (geometry2d.IsNull()) { PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); plane->InitializeStandardPlane(slicedWorldGeometry); geometry2d = plane; } SetCurrentWorldGeometry(slicedWorldGeometry); } else { geometry2d = dynamic_cast(geometry); if (geometry2d.IsNull()) { PlaneGeometry::Pointer plane = PlaneGeometry::New(); plane->InitializeStandardPlane(geometry); geometry2d = plane; } SetCurrentWorldGeometry(geometry); } SetCurrentWorldGeometry2D(geometry2d); // calls Modified() } if (m_CurrentWorldGeometry2D.IsNull()) itkWarningMacro("m_CurrentWorldGeometry2D is NULL"); } void mitk::BaseRenderer::SetDisplayGeometry(mitk::DisplayGeometry* geometry2d) { itkDebugMacro("setting DisplayGeometry to " << geometry2d); if (m_DisplayGeometry != geometry2d) { m_DisplayGeometry = geometry2d; m_DisplayGeometryData->SetGeometry2D(m_DisplayGeometry); m_DisplayGeometryUpdateTime.Modified(); Modified(); } } void mitk::BaseRenderer::SetCurrentWorldGeometry2D(mitk::Geometry2D* geometry2d) { if (m_CurrentWorldGeometry2D != geometry2d) { m_CurrentWorldGeometry2D = geometry2d; m_CurrentWorldGeometry2DData->SetGeometry2D(m_CurrentWorldGeometry2D); m_DisplayGeometry->SetWorldGeometry(m_CurrentWorldGeometry2D); m_CurrentWorldGeometry2DUpdateTime.Modified(); Modified(); } } void mitk::BaseRenderer::SendUpdateSlice() { m_DisplayGeometryUpdateTime.Modified(); m_CurrentWorldGeometry2DUpdateTime.Modified(); } void mitk::BaseRenderer::SetCurrentWorldGeometry(mitk::Geometry3D* geometry) { m_CurrentWorldGeometry = geometry; if (geometry == NULL) { m_Bounds[0] = 0; m_Bounds[1] = 0; m_Bounds[2] = 0; m_Bounds[3] = 0; m_Bounds[4] = 0; m_Bounds[5] = 0; m_EmptyWorldGeometry = true; return; } BoundingBox::Pointer boundingBox = m_CurrentWorldGeometry->CalculateBoundingBoxRelativeToTransform(NULL); const BoundingBox::BoundsArrayType& worldBounds = boundingBox->GetBounds(); m_Bounds[0] = worldBounds[0]; m_Bounds[1] = worldBounds[1]; m_Bounds[2] = worldBounds[2]; m_Bounds[3] = worldBounds[3]; m_Bounds[4] = worldBounds[4]; m_Bounds[5] = worldBounds[5]; if (boundingBox->GetDiagonalLength2() <= mitk::eps) m_EmptyWorldGeometry = true; else m_EmptyWorldGeometry = false; } void mitk::BaseRenderer::SetGeometry(const itk::EventObject & geometrySendEvent) { const SliceNavigationController::GeometrySendEvent* sendEvent = dynamic_cast(&geometrySendEvent); assert(sendEvent!=NULL); SetWorldGeometry(sendEvent->GetTimeSlicedGeometry()); } void mitk::BaseRenderer::UpdateGeometry(const itk::EventObject & geometryUpdateEvent) { const SliceNavigationController::GeometryUpdateEvent* updateEvent = dynamic_cast(&geometryUpdateEvent); if (updateEvent == NULL) return; if (m_CurrentWorldGeometry.IsNotNull()) { SlicedGeometry3D* slicedWorldGeometry = dynamic_cast(m_CurrentWorldGeometry.GetPointer()); if (slicedWorldGeometry) { Geometry2D* geometry2D = slicedWorldGeometry->GetGeometry2D(m_Slice); SetCurrentWorldGeometry2D(geometry2D); // calls Modified() } } } void mitk::BaseRenderer::SetGeometrySlice(const itk::EventObject & geometrySliceEvent) { const SliceNavigationController::GeometrySliceEvent* sliceEvent = dynamic_cast(&geometrySliceEvent); assert(sliceEvent!=NULL); SetSlice(sliceEvent->GetPos()); } void mitk::BaseRenderer::SetGeometryTime(const itk::EventObject & geometryTimeEvent) { const SliceNavigationController::GeometryTimeEvent * timeEvent = dynamic_cast(&geometryTimeEvent); assert(timeEvent!=NULL); SetTimeStep(timeEvent->GetPos()); } const double* mitk::BaseRenderer::GetBounds() const { return m_Bounds; } void mitk::BaseRenderer::MousePressEvent(mitk::MouseEvent *me) { //set the Focus on the renderer /*bool success =*/m_RenderingManager->GetGlobalInteraction()->SetFocus(this); /* if (! success) mitk::StatusBar::GetInstance()->DisplayText("Warning! from mitkBaseRenderer.cpp: Couldn't focus this BaseRenderer!"); */ //if (m_CameraController) //{ // if(me->GetButtonState()!=512) // provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine // m_CameraController->MousePressEvent(me); //} if (m_MapperID == 1) { Point2D p(me->GetDisplayPosition()); Point2D p_mm; Point3D position; GetDisplayGeometry()->ULDisplayToDisplay(p, p); GetDisplayGeometry()->DisplayToWorld(p, p_mm); GetDisplayGeometry()->Map(p_mm, position); mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position); mitk::EventMapper::MapEvent(&event, m_RenderingManager->GetGlobalInteraction()); } else if (m_MapperID > 1) //==2 for 3D and ==5 for stencil { Point2D p(me->GetDisplayPosition()); GetDisplayGeometry()->ULDisplayToDisplay(p, p); me->SetDisplayPosition(p); mitk::EventMapper::MapEvent(me, m_RenderingManager->GetGlobalInteraction()); } } void mitk::BaseRenderer::MouseReleaseEvent(mitk::MouseEvent *me) { //if (m_CameraController) //{ // if(me->GetButtonState()!=512) // provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine // m_CameraController->MouseReleaseEvent(me); //} if (m_MapperID == 1) { Point2D p(me->GetDisplayPosition()); Point2D p_mm; Point3D position; GetDisplayGeometry()->ULDisplayToDisplay(p, p); GetDisplayGeometry()->DisplayToWorld(p, p_mm); GetDisplayGeometry()->Map(p_mm, position); mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position); mitk::EventMapper::MapEvent(&event, m_RenderingManager->GetGlobalInteraction()); } else if (m_MapperID == 2) { Point2D p(me->GetDisplayPosition()); GetDisplayGeometry()->ULDisplayToDisplay(p, p); me->SetDisplayPosition(p); mitk::EventMapper::MapEvent(me, m_RenderingManager->GetGlobalInteraction()); } } void mitk::BaseRenderer::MouseMoveEvent(mitk::MouseEvent *me) { //if (m_CameraController) //{ // if((me->GetButtonState()<=512) || (me->GetButtonState()>=516))// provisorisch: Ctrl nicht durchlassen. Bald wird aus m_CameraController eine StateMachine // m_CameraController->MouseMoveEvent(me); //} if (m_MapperID == 1) { Point2D p(me->GetDisplayPosition()); Point2D p_mm; Point3D position; GetDisplayGeometry()->ULDisplayToDisplay(p, p); GetDisplayGeometry()->DisplayToWorld(p, p_mm); GetDisplayGeometry()->Map(p_mm, position); mitk::PositionEvent event(this, me->GetType(), me->GetButton(), me->GetButtonState(), mitk::Key_unknown, p, position); mitk::EventMapper::MapEvent(&event, m_RenderingManager->GetGlobalInteraction()); } else if (m_MapperID == 2) { Point2D p(me->GetDisplayPosition()); GetDisplayGeometry()->ULDisplayToDisplay(p, p); me->SetDisplayPosition(p); mitk::EventMapper::MapEvent(me, m_RenderingManager->GetGlobalInteraction()); } } void mitk::BaseRenderer::PickWorldPoint(const mitk::Point2D& displayPoint, mitk::Point3D& worldPoint) const { mitk::Point2D worldPoint2D; GetDisplayGeometry()->DisplayToWorld(displayPoint, worldPoint2D); GetDisplayGeometry()->Map(worldPoint2D, worldPoint); } void mitk::BaseRenderer::WheelEvent(mitk::WheelEvent * we) { if (m_MapperID == 1) { Point2D p(we->GetDisplayPosition()); Point2D p_mm; Point3D position; GetDisplayGeometry()->ULDisplayToDisplay(p, p); GetDisplayGeometry()->DisplayToWorld(p, p_mm); GetDisplayGeometry()->Map(p_mm, position); mitk::PositionEvent event(this, we->GetType(), we->GetButton(), we->GetButtonState(), mitk::Key_unknown, p, position); mitk::EventMapper::MapEvent(we, m_RenderingManager->GetGlobalInteraction()); mitk::EventMapper::MapEvent(&event, m_RenderingManager->GetGlobalInteraction()); } else if (m_MapperID == 2) { Point2D p(we->GetDisplayPosition()); GetDisplayGeometry()->ULDisplayToDisplay(p, p); we->SetDisplayPosition(p); mitk::EventMapper::MapEvent(we, m_RenderingManager->GetGlobalInteraction()); } } void mitk::BaseRenderer::KeyPressEvent(mitk::KeyEvent *ke) { if (m_MapperID == 1) { Point2D p(ke->GetDisplayPosition()); Point2D p_mm; Point3D position; GetDisplayGeometry()->ULDisplayToDisplay(p, p); GetDisplayGeometry()->DisplayToWorld(p, p_mm); GetDisplayGeometry()->Map(p_mm, position); mitk::KeyEvent event(this, ke->GetType(), ke->GetButton(), ke->GetButtonState(), ke->GetKey(), ke->GetText(), p); mitk::EventMapper::MapEvent(&event, m_RenderingManager->GetGlobalInteraction()); } else if (m_MapperID == 2) { Point2D p(ke->GetDisplayPosition()); GetDisplayGeometry()->ULDisplayToDisplay(p, p); ke->SetDisplayPosition(p); mitk::EventMapper::MapEvent(ke, m_RenderingManager->GetGlobalInteraction()); } } void mitk::BaseRenderer::DrawOverlayMouse(mitk::Point2D& itkNotUsed(p2d)) { MITK_INFO<<"BaseRenderer::DrawOverlayMouse()- should be inconcret implementation OpenGLRenderer."<RequestUpdate(this->m_RenderWindow); } void mitk::BaseRenderer::ForceImmediateUpdate() { m_RenderingManager->ForceImmediateUpdate(this->m_RenderWindow); } unsigned int mitk::BaseRenderer::GetNumberOfVisibleLODEnabledMappers() const { return m_NumberOfVisibleLODEnabledMappers; } mitk::RenderingManager* mitk::BaseRenderer::GetRenderingManager() const { return m_RenderingManager.GetPointer(); } /*! Sets the new Navigation controller */ void mitk::BaseRenderer::SetSliceNavigationController(mitk::SliceNavigationController *SlicenavigationController) { if (SlicenavigationController == NULL) return; //disconnect old from globalinteraction m_RenderingManager->GetGlobalInteraction()->RemoveListener(SlicenavigationController); //copy worldgeometry SlicenavigationController->SetInputWorldGeometry(SlicenavigationController->GetCreatedWorldGeometry()); SlicenavigationController->Update(); //set new m_SliceNavigationController = SlicenavigationController; m_SliceNavigationController->SetRenderer(this); if (m_SliceNavigationController.IsNotNull()) { m_SliceNavigationController->ConnectGeometrySliceEvent(this); m_SliceNavigationController->ConnectGeometryUpdateEvent(this); m_SliceNavigationController->ConnectGeometryTimeEvent(this, false); } } /*! Sets the new camera controller and deletes the vtkRenderWindowInteractor in case of the VTKInteractorCameraController */ void mitk::BaseRenderer::SetCameraController(CameraController* cameraController) { mitk::VtkInteractorCameraController::Pointer vtkInteractorCameraController = dynamic_cast(cameraController); if (vtkInteractorCameraController.IsNotNull()) MITK_INFO<<"!!!WARNING!!!: RenderWindow interaction events are no longer handled via CameraController (See Bug #954)."<SetRenderer(NULL); m_CameraController = NULL; m_CameraController = cameraController; m_CameraController->SetRenderer(this); } void mitk::BaseRenderer::PrintSelf(std::ostream& os, itk::Indent indent) const { os << indent << " MapperID: " << m_MapperID << std::endl; os << indent << " Slice: " << m_Slice << std::endl; os << indent << " TimeStep: " << m_TimeStep << std::endl; os << indent << " WorldGeometry: "; if (m_WorldGeometry.IsNull()) os << "NULL" << std::endl; else m_WorldGeometry->Print(os, indent); os << indent << " CurrentWorldGeometry2D: "; if (m_CurrentWorldGeometry2D.IsNull()) os << "NULL" << std::endl; else m_CurrentWorldGeometry2D->Print(os, indent); os << indent << " CurrentWorldGeometry2DUpdateTime: " << m_CurrentWorldGeometry2DUpdateTime << std::endl; os << indent << " CurrentWorldGeometry2DTransformTime: " << m_CurrentWorldGeometry2DTransformTime << std::endl; os << indent << " DisplayGeometry: "; if (m_DisplayGeometry.IsNull()) os << "NULL" << std::endl; else m_DisplayGeometry->Print(os, indent); os << indent << " DisplayGeometryTransformTime: " << m_DisplayGeometryTransformTime << std::endl; Superclass::PrintSelf(os, indent); } void mitk::BaseRenderer::SetDepthPeelingEnabled(bool enabled) { m_DepthPeelingEnabled = enabled; m_VtkRenderer->SetUseDepthPeeling(enabled); } void mitk::BaseRenderer::SetMaxNumberOfPeels(int maxNumber) { m_MaxNumberOfPeels = maxNumber; m_VtkRenderer->SetMaximumNumberOfPeels(maxNumber); } diff --git a/Core/Code/Rendering/mitkBaseRenderer.h b/Core/Code/Rendering/mitkBaseRenderer.h index db2f18f4ba..be2274f90e 100644 --- a/Core/Code/Rendering/mitkBaseRenderer.h +++ b/Core/Code/Rendering/mitkBaseRenderer.h @@ -1,611 +1,611 @@ /*=================================================================== 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 BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 #define BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 #include "mitkDataStorage.h" #include "mitkGeometry2D.h" #include "mitkTimeSlicedGeometry.h" #include "mitkDisplayGeometry.h" #include "mitkGeometry2DData.h" #include "mitkCameraController.h" #include "mitkDisplayPositionEvent.h" #include "mitkWheelEvent.h" //#include "mitkMapper.h" #include "mitkSliceNavigationController.h" #include "mitkCameraController.h" #include "mitkCameraRotationController.h" #include "mitkBindDispatcherInteractor.h" #include "mitkDispatcher.h" #include #include #include #include namespace mitk { class NavigationController; class SliceNavigationController; class CameraRotationController; class CameraController; class DataStorage; class Mapper; class BaseLocalStorageHandler; //##Documentation //## @brief Organizes the rendering process //## //## Organizes the rendering process. A Renderer contains a reference to a //## DataStorage and asks the mappers of the data objects to render //## the data into the renderwindow it is associated to. //## //## \#Render() checks if rendering is currently allowed by calling //## RenderWindow::PrepareRendering(). Initialization of a rendering context //## can also be performed in this method. //## //## The actual rendering code has been moved to \#Repaint() //## Both \#Repaint() and \#Update() are declared protected now. //## //## Note: Separation of the Repaint and Update processes (rendering vs //## creating a vtk prop tree) still needs to be worked on. The whole //## rendering process also should be reworked to use VTK based classes for //## both 2D and 3D rendering. //## @ingroup Renderer class MITK_CORE_EXPORT BaseRenderer: public itk::Object { public: typedef std::map BaseRendererMapType; static BaseRendererMapType baseRendererMap; static BaseRenderer* GetInstance(vtkRenderWindow * renWin); static void AddInstance(vtkRenderWindow* renWin, BaseRenderer* baseRenderer); static void RemoveInstance(vtkRenderWindow* renWin); static BaseRenderer* GetByName(const std::string& name); static vtkRenderWindow* GetRenderWindowByName(const std::string& name); #pragma GCC visibility push(default) itkEventMacro( RendererResetEvent, itk::AnyEvent ); #pragma GCC visibility pop /** Standard class typedefs. */ mitkClassMacro(BaseRenderer, itk::Object); BaseRenderer(const char* name = NULL, vtkRenderWindow * renWin = NULL, mitk::RenderingManager* rm = NULL); //##Documentation //## @brief MapperSlotId defines which kind of mapper (e.g., 2D or 3D) shoud be used. typedef int MapperSlotId; enum StandardMapperSlot { Standard2D = 1, Standard3D = 2 }; virtual void SetDataStorage(DataStorage* storage); ///< set the datastorage that will be used for rendering //##Documentation //## return the DataStorage that is used for rendering virtual DataStorage::Pointer GetDataStorage() const { return m_DataStorage.GetPointer(); } //##Documentation //## @brief Access the RenderWindow into which this renderer renders. vtkRenderWindow* GetRenderWindow() const { return m_RenderWindow; } vtkRenderer* GetVtkRenderer() const { return m_VtkRenderer; } //##Documentation //## @brief Returns the Dispatcher which handles Events for this BaseRenderer - Dispatcher::Pointer GetDispatcher(); + Dispatcher::Pointer GetDispatcher() const; //##Documentation //## @brief Default mapper id to use. static const MapperSlotId defaultMapper; //##Documentation //## @brief Do the rendering and flush the result. virtual void Paint(); //##Documentation //## @brief Initialize the RenderWindow. Should only be called from RenderWindow. virtual void Initialize(); //##Documentation //## @brief Called to inform the renderer that the RenderWindow has been resized. virtual void Resize(int w, int h); //##Documentation //## @brief Initialize the renderer with a RenderWindow (@a renderwindow). virtual void InitRenderer(vtkRenderWindow* renderwindow); //##Documentation //## @brief Set the initial size. Called by RenderWindow after it has become //## visible for the first time. virtual void InitSize(int w, int h); //##Documentation //## @brief Draws a point on the widget. //## Should be used during conferences to show the position of the remote mouse virtual void DrawOverlayMouse(Point2D& p2d); //##Documentation //## @brief Set/Get the WorldGeometry (m_WorldGeometry) for 3D and 2D rendering, that describing the //## (maximal) area to be rendered. //## //## Depending of the type of the passed Geometry3D more or less information can be extracted: //## \li if it is a Geometry2D (which is a sub-class of Geometry3D), m_CurrentWorldGeometry2D is //## also set to point to it. m_TimeSlicedWorldGeometry is set to NULL. //## \li if it is a TimeSlicedGeometry, m_TimeSlicedWorldGeometry is also set to point to it. //## If m_TimeSlicedWorldGeometry contains instances of SlicedGeometry3D, m_CurrentWorldGeometry2D is set to //## one of geometries stored in the SlicedGeometry3D according to the value of m_Slice; otherwise //## a PlaneGeometry describing the top of the bounding-box of the Geometry3D is set as the //## m_CurrentWorldGeometry2D. //## \li otherwise a PlaneGeometry describing the top of the bounding-box of the Geometry3D //## is set as the m_CurrentWorldGeometry2D. m_TimeSlicedWorldGeometry is set to NULL. //## @todo add calculation of PlaneGeometry describing the top of the bounding-box of the Geometry3D //## when the passed Geometry3D is not sliced. //## \sa m_WorldGeometry //## \sa m_TimeSlicedWorldGeometry //## \sa m_CurrentWorldGeometry2D virtual void SetWorldGeometry(Geometry3D* geometry); itkGetConstObjectMacro(WorldGeometry, Geometry3D) //##Documentation //## @brief Get the current 3D-worldgeometry (m_CurrentWorldGeometry) used for 3D-rendering itkGetConstObjectMacro(CurrentWorldGeometry, Geometry3D) //##Documentation //## @brief Get the current 2D-worldgeometry (m_CurrentWorldGeometry2D) used for 2D-rendering itkGetConstObjectMacro(CurrentWorldGeometry2D, Geometry2D) //##Documentation //## Calculates the bounds of the DataStorage (if it contains any valid data), //## creates a geometry from these bounds and sets it as world geometry of the renderer. //## //## Call this method to re-initialize the renderer to the current DataStorage //## (e.g. after loading an additional dataset), to ensure that the view is //## aligned correctly. //## \warn This is not implemented yet. virtual bool SetWorldGeometryToDataStorageBounds() { return false; } //##Documentation //## @brief Set/Get the DisplayGeometry (for 2D rendering) //## //## The DisplayGeometry describes which part of the Geometry2D m_CurrentWorldGeometry2D //## is displayed. virtual void SetDisplayGeometry(DisplayGeometry* geometry2d); itkGetConstObjectMacro(DisplayGeometry, DisplayGeometry) itkGetObjectMacro(DisplayGeometry, DisplayGeometry) //##Documentation //## @brief Set/Get m_Slice which defines together with m_TimeStep the 2D geometry //## stored in m_TimeSlicedWorldGeometry used as m_CurrentWorldGeometry2D //## //## \sa m_Slice virtual void SetSlice(unsigned int slice); itkGetConstMacro(Slice, unsigned int) //##Documentation //## @brief Set/Get m_TimeStep which defines together with m_Slice the 2D geometry //## stored in m_TimeSlicedWorldGeometry used as m_CurrentWorldGeometry2D //## //## \sa m_TimeStep virtual void SetTimeStep(unsigned int timeStep); itkGetConstMacro(TimeStep, unsigned int) //##Documentation //## @brief Get the time-step of a BaseData object which //## exists at the time of the currently displayed content //## //## Returns -1 or mitk::BaseData::m_TimeSteps if there //## is no data at the current time. //## \sa GetTimeStep, m_TimeStep int GetTimeStep(const BaseData* data) const; //##Documentation //## @brief Get the time in ms of the currently displayed content //## //## \sa GetTimeStep, m_TimeStep ScalarType GetTime() const; //##Documentation //## @brief SetWorldGeometry is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometrySendEvent virtual void SetGeometry(const itk::EventObject & geometrySliceEvent); //##Documentation //## @brief UpdateWorldGeometry is called to re-read the 2D geometry from the //## slice navigation controller virtual void UpdateGeometry(const itk::EventObject & geometrySliceEvent); //##Documentation //## @brief SetSlice is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometrySliceEvent virtual void SetGeometrySlice(const itk::EventObject & geometrySliceEvent); //##Documentation //## @brief SetTimeStep is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometryTimeEvent virtual void SetGeometryTime(const itk::EventObject & geometryTimeEvent); //##Documentation //## @brief Get a data object containing the DisplayGeometry (for 2D rendering) itkGetObjectMacro(DisplayGeometryData, Geometry2DData) //##Documentation //## @brief Get a data object containing the WorldGeometry (for 2D rendering) itkGetObjectMacro(WorldGeometryData, Geometry2DData) //##Documentation //## @brief Get a DataNode pointing to a data object containing the WorldGeometry (3D and 2D rendering) itkGetObjectMacro(WorldGeometryNode, DataNode) //##Documentation //## @brief Get a DataNode pointing to a data object containing the DisplayGeometry (for 2D rendering) itkGetObjectMacro(DisplayGeometryNode, DataNode) //##Documentation //## @brief Get a DataNode pointing to a data object containing the current 2D-worldgeometry m_CurrentWorldGeometry2D (for 2D rendering) itkGetObjectMacro(CurrentWorldGeometry2DNode, DataNode) //##Documentation //## @brief Sets timestamp of CurrentWorldGeometry2D and DisplayGeometry and forces so reslicing in that renderwindow void SendUpdateSlice(); //##Documentation //## @brief Get timestamp of last call of SetCurrentWorldGeometry2D unsigned long GetCurrentWorldGeometry2DUpdateTime() { return m_CurrentWorldGeometry2DUpdateTime; } //##Documentation //## @brief Get timestamp of last call of SetDisplayGeometry unsigned long GetDisplayGeometryUpdateTime() { return m_CurrentWorldGeometry2DUpdateTime; } //##Documentation //## @brief Get timestamp of last change of current TimeStep unsigned long GetTimeStepUpdateTime() { return m_TimeStepUpdateTime; } //##Documentation //## @brief Perform a picking: find the x,y,z world coordinate of a //## display x,y coordinate. //## @warning Has to be overwritten in subclasses for the 3D-case. //## //## Implemented here only for 2D-rendering by using //## m_DisplayGeometry virtual void PickWorldPoint(const Point2D& diplayPosition, Point3D& worldPosition) const; /** \brief Determines the object (mitk::DataNode) closest to the current * position by means of picking * * \warning Implementation currently empty for 2D rendering; intended to be * implemented for 3D renderers */ virtual DataNode* PickObject(const Point2D& /*displayPosition*/, Point3D& /*worldPosition*/) const { return NULL; } //##Documentation //## @brief Get the MapperSlotId to use. itkGetMacro(MapperID, MapperSlotId) itkGetConstMacro(MapperID, MapperSlotId) //##Documentation //## @brief Set the MapperSlotId to use. itkSetMacro(MapperID, MapperSlotId) //##Documentation //## @brief Has the renderer the focus? itkGetMacro(Focused, bool) //##Documentation //## @brief Tell the renderer that it is focused. The caller is responsible for focus management, //## not the renderer itself. itkSetMacro(Focused, bool) //##Documentation //## @brief Sets whether depth peeling is enabled or not void SetDepthPeelingEnabled(bool enabled); //##Documentation //## @brief Sets maximal number of peels void SetMaxNumberOfPeels(int maxNumber); itkGetMacro(Size, int*) void SetSliceNavigationController(SliceNavigationController* SlicenavigationController); void SetCameraController(CameraController* cameraController); itkGetObjectMacro(CameraController, CameraController) itkGetObjectMacro(SliceNavigationController, SliceNavigationController) itkGetObjectMacro(CameraRotationController, CameraRotationController) itkGetMacro(EmptyWorldGeometry, bool) //##Documentation //## @brief Mouse event dispatchers //## @note for internal use only. preliminary. virtual void MousePressEvent(MouseEvent*); //##Documentation //## @brief Mouse event dispatchers //## @note for internal use only. preliminary. virtual void MouseReleaseEvent(MouseEvent*); //##Documentation //## @brief Mouse event dispatchers //## @note for internal use only. preliminary. virtual void MouseMoveEvent(MouseEvent*); //##Documentation //## @brief Wheel event dispatcher //## @note for internal use only. preliminary. virtual void WheelEvent(mitk::WheelEvent* we); //##Documentation //## @brief Key event dispatcher //## @note for internal use only. preliminary. virtual void KeyPressEvent(KeyEvent*); //##Documentation //## @brief get the name of the Renderer //## @note const char * GetName() const { return m_Name.c_str(); } //##Documentation //## @brief get the x_size of the RendererWindow //## @note int GetSizeX() const { return m_Size[0]; } //##Documentation //## @brief get the y_size of the RendererWindow //## @note int GetSizeY() const { return m_Size[1]; } const double* GetBounds() const; void RequestUpdate(); void ForceImmediateUpdate(); /** Returns number of mappers which are visible and have level-of-detail * rendering enabled */ unsigned int GetNumberOfVisibleLODEnabledMappers() const; ///** //* \brief Setter for the RenderingManager that handles this instance of BaseRenderer //*/ //void SetRenderingManager( mitk::RenderingManager* ); /** * \brief Getter for the RenderingManager that handles this instance of BaseRenderer */ virtual mitk::RenderingManager* GetRenderingManager() const; /** * \brief Provides (1) world coordinates for a given mouse position and (2) * translates mousePosition to Display coordinates */ virtual Point3D Map2DRendererPositionTo3DWorldPosition(Point2D* mousePosition) const; protected: virtual ~BaseRenderer(); //##Documentation //## @brief Call update of all mappers. To be implemented in subclasses. virtual void Update() = 0; vtkRenderWindow* m_RenderWindow; vtkRenderer* m_VtkRenderer; //##Documentation //## @brief MapperSlotId to use. Defines which kind of mapper (e.g., 2D or 3D) shoud be used. MapperSlotId m_MapperID; //##Documentation //## @brief The DataStorage that is used for rendering. DataStorage::Pointer m_DataStorage; //##Documentation //## @brief The RenderingManager that manages this instance RenderingManager::Pointer m_RenderingManager; //##Documentation //## @brief Timestamp of last call of Update(). unsigned long m_LastUpdateTime; //##Documentation //## @brief CameraController for 3D rendering //## @note preliminary. CameraController::Pointer m_CameraController; SliceNavigationController::Pointer m_SliceNavigationController; CameraRotationController::Pointer m_CameraRotationController; //##Documentation //## @brief Size of the RenderWindow. int m_Size[2]; //##Documentation //## @brief Contains whether the renderer that it is focused. The caller of //## SetFocused is responsible for focus management, not the renderer itself. //## is doubled because of mitk::FocusManager in GlobalInteraction!!! (ingmar) bool m_Focused; //##Documentation //## @brief Sets m_CurrentWorldGeometry2D virtual void SetCurrentWorldGeometry2D(Geometry2D* geometry2d); //##Documentation //## @brief Sets m_CurrentWorldGeometry virtual void SetCurrentWorldGeometry(Geometry3D* geometry); private: //##Documentation //## Pointer to the worldgeometry, describing the maximal area to be rendered //## (3D as well as 2D). //## It is const, since we are not allowed to change it (it may be taken //## directly from the geometry of an image-slice and thus it would be //## very strange when suddenly the image-slice changes its geometry). //## \sa SetWorldGeometry Geometry3D::Pointer m_WorldGeometry; //##Documentation //## m_TimeSlicedWorldGeometry is set by SetWorldGeometry if the passed Geometry3D is a //## TimeSlicedGeometry (or a sub-class of it). If it contains instances of SlicedGeometry3D, //## m_Slice and m_TimeStep (set via SetSlice and SetTimeStep, respectively) define //## which 2D geometry stored in m_TimeSlicedWorldGeometry (if available) //## is used as m_CurrentWorldGeometry2D. //## \sa m_CurrentWorldGeometry2D TimeSlicedGeometry::Pointer m_TimeSlicedWorldGeometry; //##Documentation //## Pointer to the current 3D-worldgeometry. Geometry3D::Pointer m_CurrentWorldGeometry; //##Documentation //## Pointer to the current 2D-worldgeometry. The 2D-worldgeometry //## describes the maximal area (2D manifold) to be rendered in case we //## are doing 2D-rendering. More precisely, a subpart of this according //## to m_DisplayGeometry is displayed. //## It is const, since we are not allowed to change it (it may be taken //## directly from the geometry of an image-slice and thus it would be //## very strange when suddenly the image-slice changes its geometry). Geometry2D::Pointer m_CurrentWorldGeometry2D; //##Documentation //## Pointer to the displaygeometry. The displaygeometry describes the //## geometry of the \em visible area in the window controlled by the renderer //## in case we are doing 2D-rendering. //## It is const, since we are not allowed to change it. DisplayGeometry::Pointer m_DisplayGeometry; //##Documentation //## Defines together with m_Slice which 2D geometry stored in m_TimeSlicedWorldGeometry //## is used as m_CurrentWorldGeometry2D: m_TimeSlicedWorldGeometry->GetGeometry2D(m_Slice, m_TimeStep). //## \sa m_TimeSlicedWorldGeometry unsigned int m_Slice; //##Documentation //## Defines together with m_TimeStep which 2D geometry stored in m_TimeSlicedWorldGeometry //## is used as m_CurrentWorldGeometry2D: m_TimeSlicedWorldGeometry->GetGeometry2D(m_Slice, m_TimeStep). //## \sa m_TimeSlicedWorldGeometry unsigned int m_TimeStep; //##Documentation //## @brief timestamp of last call of SetWorldGeometry itk::TimeStamp m_CurrentWorldGeometry2DUpdateTime; //##Documentation //## @brief timestamp of last call of SetDisplayGeometry itk::TimeStamp m_DisplayGeometryUpdateTime; //##Documentation //## @brief timestamp of last change of the current time step itk::TimeStamp m_TimeStepUpdateTime; //##Documentation //## @brief Helper class which establishes connection between Interactors and Dispatcher via a common DataStorage. BindDispatcherInteractor* m_BindDispatcherInteractor; protected: virtual void PrintSelf(std::ostream& os, itk::Indent indent) const; //##Documentation //## Data object containing the m_WorldGeometry defined above. Geometry2DData::Pointer m_WorldGeometryData; //##Documentation //## Data object containing the m_DisplayGeometry defined above. Geometry2DData::Pointer m_DisplayGeometryData; //##Documentation //## Data object containing the m_CurrentWorldGeometry2D defined above. Geometry2DData::Pointer m_CurrentWorldGeometry2DData; //##Documentation //## DataNode objects containing the m_WorldGeometryData defined above. DataNode::Pointer m_WorldGeometryNode; //##Documentation //## DataNode objects containing the m_DisplayGeometryData defined above. DataNode::Pointer m_DisplayGeometryNode; //##Documentation //## DataNode objects containing the m_CurrentWorldGeometry2DData defined above. DataNode::Pointer m_CurrentWorldGeometry2DNode; //##Documentation //## @brief test only unsigned long m_DisplayGeometryTransformTime; //##Documentation //## @brief test only unsigned long m_CurrentWorldGeometry2DTransformTime; std::string m_Name; double m_Bounds[6]; bool m_EmptyWorldGeometry; bool m_DepthPeelingEnabled; int m_MaxNumberOfPeels; typedef std::set LODEnabledMappersType; /** Number of mappers which are visible and have level-of-detail * rendering enabled */ unsigned int m_NumberOfVisibleLODEnabledMappers; // Local Storage Handling for mappers protected: std::list m_RegisteredLocalStorageHandlers; public: void RemoveAllLocalStorages(); void RegisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh); void UnregisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh); }; } // namespace mitk #endif /* BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 */ diff --git a/Core/Code/Rendering/mitkMapper.h b/Core/Code/Rendering/mitkMapper.h index 09d72df6d7..6bab8fae42 100644 --- a/Core/Code/Rendering/mitkMapper.h +++ b/Core/Code/Rendering/mitkMapper.h @@ -1,298 +1,298 @@ /*=================================================================== 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 MAPPER_H_HEADER_INCLUDED_C1E6EA08 #define MAPPER_H_HEADER_INCLUDED_C1E6EA08 #include #include "mitkBaseRenderer.h" #include "mitkVtkPropRenderer.h" #include "mitkLevelWindow.h" #include "mitkCommon.h" #include #include //Just included to get VTK version #include class vtkWindow; class vtkProp; namespace mitk { class BaseRenderer; class BaseData; class DataNode; /** \brief Interface for accessing (templated) LocalStorageHandler instances. */ class BaseLocalStorageHandler { public: virtual ~BaseLocalStorageHandler() {} virtual void ClearLocalStorage(mitk::BaseRenderer *renderer,bool unregisterFromBaseRenderer=true )=0; }; /** \brief Base class of all mappers, Vtk as well as OpenGL mappers * * By the help of mappers, the input data is transformed to tangible primitives, * such as surfaces, points, lines, etc. * This is the base class of all mappers, Vtk as well as OpenGL mappers. * Subclasses of mitk::Mapper control the creation of rendering primitives * that interface to the graphics library (e.g., OpenGL, vtk). * * \todo Should Mapper be a subclass of ImageSource? * \ingroup Mapper */ class MITK_CORE_EXPORT Mapper : public itk::Object { public: mitkClassMacro(Mapper, itk::Object); /** \brief Set the DataNode containing the data to map */ itkSetObjectMacro(DataNode, DataNode); /** \brief Get the DataNode containing the data to map */ virtual DataNode* GetDataNode() const; /**\brief Get the data to map * * Returns the mitk::BaseData object associated with this mapper. * \return the mitk::BaseData associated with this mapper. * \deprecatedSince{2013_03} Use GetDataNode()->GetData() instead to access the data */ DEPRECATED(BaseData* GetData() const); /** \brief Convenience access method for color properties (instances of * ColorProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode()->GetColor(...) instead to get the color */ DEPRECATED(virtual bool GetColor(float rgb[3], BaseRenderer* renderer, const char* name = "color") const); /** \brief Convenience access method for visibility properties (instances * of BoolProperty) * \return \a true property was found * \sa IsVisible * \deprecatedSince{2013_03} Use GetDataNode()->GetVisibility(...) instead to get the visibility */ DEPRECATED(virtual bool GetVisibility(bool &visible, BaseRenderer* renderer, const char* name = "visible") const); /** \brief Convenience access method for opacity properties (instances of * FloatProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode()->GetOpacity(...) instead to get the opacity */ DEPRECATED(virtual bool GetOpacity(float &opacity, BaseRenderer* renderer, const char* name = "opacity") const); /** \brief Convenience access method for color properties (instances of * LevelWindoProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode->GetLevelWindow(...) instead to get the levelwindow */ DEPRECATED(virtual bool GetLevelWindow(LevelWindow &levelWindow, BaseRenderer* renderer, const char* name = "levelwindow") const); /** \brief Convenience access method for visibility properties (instances * of BoolProperty). Return value is the visibility. Default is * visible==true, i.e., true is returned even if the property (\a * propertyKey) is not found. * * Thus, the return value has a different meaning than in the * GetVisibility method! * \sa GetVisibility * \deprecatedSince{2013_03} Use GetDataNode()->GetVisibility(...) instead */ DEPRECATED(virtual bool IsVisible(BaseRenderer* renderer, const char* name = "visible") const); /** \brief Returns whether this is an vtk-based mapper * \deprecatedSince{2013_03} All mappers of superclass VTKMapper are vtk based, use a dynamic_cast instead */ virtual bool IsVtkBased() const = 0; /** \brief Calls the time step of the input data for the specified renderer and checks * whether the time step is valid and calls method GenerateDataForRenderer() */ virtual void Update(BaseRenderer* renderer); /** \brief Responsible for calling the appropriate render functions. * To be implemented in sub-classes. */ virtual void MitkRender(mitk::BaseRenderer* renderer, mitk::VtkPropRenderer::RenderType type) = 0; /** * \brief Apply specific color and opacity properties read from the PropertyList. * Reimplemented in GLmapper (does not use the actor) and the VtkMapper class. * The function is called by the individual mapper (mostly in the ApplyProperties() or ApplyAllProperties() * method). */ virtual void ApplyColorAndOpacityProperties(mitk::BaseRenderer* renderer, vtkActor* actor = NULL) = 0; /** \brief Set default values of properties used by this mapper * to \a node * * \param node The node for which the properties are set * \param overwrite overwrite existing properties (default: \a false) * \param renderer defines which property list of node is used * (default: \a NULL, i.e. default property list) */ static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = NULL, bool overwrite = false); /** \brief Returns the current time step as calculated from the renderer */ - int GetTimestep() const { return m_TimeStep; }; + int GetTimestep() const { return m_TimeStep; } /** Returns true if this Mapper currently allows for Level-of-Detail rendering. * This reflects whether this Mapper currently invokes StartEvent, EndEvent, and * ProgressEvent on BaseRenderer. */ virtual bool IsLODEnabled( BaseRenderer * /*renderer*/ ) const { return false; } protected: /** \brief explicit constructor which disallows implicit conversions */ explicit Mapper(); /** \brief virtual destructor in order to derive from this class */ virtual ~Mapper(); /** \brief Generate the data needed for rendering (independent of a specific renderer) * \deprecatedSince{2013_03} Use GenerateDataForRenderer(BaseRenderer* renderer) instead. */ - DEPRECATED( virtual void GenerateData() { }); + DEPRECATED( virtual void GenerateData() ) { } /** \brief Generate the data needed for rendering into \a renderer */ virtual void GenerateDataForRenderer(BaseRenderer* /* renderer */) { } /** \brief Updates the time step, which is sometimes needed in subclasses */ virtual void CalculateTimeStep( BaseRenderer* renderer ); /** \brief Reset the mapper (i.e., make sure that nothing is displayed) if no * valid data is present. In most cases the reimplemented function * disables the according actors (toggling visibility off) * * To be implemented in sub-classes. */ - virtual void ResetMapper( BaseRenderer* /*renderer*/ ) { }; + virtual void ResetMapper( BaseRenderer* /*renderer*/ ) { } //\brief not thread-safe itk::WeakPointer m_DataNode; /** \brief timestamp of last update of stored data */ itk::TimeStamp m_LastUpdateTime; private: /** \brief The current time step of the dataset to be rendered, * for use in subclasses. * The current timestep can be accessed via the GetTimestep() method. */ int m_TimeStep; /** \brief copy constructor */ Mapper( const Mapper &); /** \brief assignment operator */ Mapper &operator=(const Mapper &); public: /** \brief Base class for mapper specific rendering ressources. */ class BaseLocalStorage { }; /** \brief Templated class for management of LocalStorage implementations in Mappers. * * The LocalStorageHandler is responsible for providing a LocalStorage to a * concrete mitk::Mapper subclass. Each RenderWindow / mitk::BaseRenderer is * assigned its own LocalStorage instance so that all contained ressources * (actors, shaders, textures, ...) are provided individually per window. * */ template class LocalStorageHandler : public mitk::BaseLocalStorageHandler { protected: std::map m_BaseRenderer2LS; public: /** \brief deallocates a local storage for a specifc BaseRenderer (if the * BaseRenderer is itself deallocating it in its destructor, it has to set * unregisterFromBaseRenderer=false) */ virtual void ClearLocalStorage(mitk::BaseRenderer *renderer,bool unregisterFromBaseRenderer=true ) { //MITK_INFO << "deleting a localstorage on a mapper request"; if(unregisterFromBaseRenderer) renderer->UnregisterLocalStorageHandler( this ); L *l = m_BaseRenderer2LS[renderer]; m_BaseRenderer2LS.erase( renderer ); delete l; } /** \brief Retrieves a LocalStorage for a specific BaseRenderer. * * Should be used by mappers in GenerateDataForRenderer() */ L *GetLocalStorage(mitk::BaseRenderer *forRenderer) { L *l = m_BaseRenderer2LS[ forRenderer ]; if(!l) { //MITK_INFO << "creating new localstorage"; l = new L; m_BaseRenderer2LS[ forRenderer ] = l; forRenderer->RegisterLocalStorageHandler( this ); } return l; } ~LocalStorageHandler() { typename std::map::iterator it; for ( it=m_BaseRenderer2LS.begin() ; it != m_BaseRenderer2LS.end(); it++ ) { (*it).first->UnregisterLocalStorageHandler(this); delete (*it).second; } m_BaseRenderer2LS.clear(); } }; }; } // namespace mitk #endif /* MAPPER_H_HEADER_INCLUDED_C1E6EA08 */ diff --git a/Core/Code/Rendering/mitkRenderWindowBase.h b/Core/Code/Rendering/mitkRenderWindowBase.h index c8eb14a2fd..6fd19f770f 100644 --- a/Core/Code/Rendering/mitkRenderWindowBase.h +++ b/Core/Code/Rendering/mitkRenderWindowBase.h @@ -1,111 +1,111 @@ /*=================================================================== 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 MITKRENDERWINDOWBASE_H_HEADER_INCLUDED_C1C40D66ASDF #define MITKRENDERWINDOWBASE_H_HEADER_INCLUDED_C1C40D66ASDF #include #include "mitkVtkPropRenderer.h" #include "vtkMitkRenderProp.h" #include "mitkSliceNavigationController.h" #include "mitkCameraRotationController.h" #include "mitkInteractionEvent.h" namespace mitk { /** * \brief Base class of MITK RenderWindows * * This class sets up the MITK rendering mechanism and it's integration into VTK. * * Currently, there are two specific implementations of this abstract class: * QmitkRenderWindow, inerhits from the QVTKWidget and is the matured way for MITK rendering * mitkRenderWindow is a new, QT-independent RenderWindow implementation * * \ingroup Renderer */ class MITK_CORE_EXPORT RenderWindowBase { public: //mitkClassMacro(RenderWindowBase,itk::Object); //itkNewMacro(Self); virtual ~RenderWindowBase(); void InitRenderer(); virtual mitk::SliceNavigationController * GetSliceNavigationController(); virtual mitk::CameraRotationController * GetCameraRotationController(); virtual mitk::BaseController * GetController(); virtual mitk::VtkPropRenderer* GetRenderer(); virtual vtkRenderWindow* GetVtkRenderWindow() = 0; virtual vtkRenderWindowInteractor* GetVtkRenderWindowInteractor() = 0; void SetProcessWheelEvents( bool state ); bool GetProcessWheelEvents(); void SetInvertScrollingDirection( bool ); - /** \deprecated{Use InteractionEvents instead and pass them to HandleEvent()} */ - virtual void mousePressMitkEvent(mitk::MouseEvent *me); - /** \deprecated{Use InteractionEvents instead and pass them to HandleEvent()} */ - virtual void mouseReleaseMitkEvent(mitk::MouseEvent *me); - /** \deprecated{Use InteractionEvents instead and pass them to HandleEvent()} */ - virtual void mouseMoveMitkEvent(mitk::MouseEvent *me); - /** \deprecated{Use InteractionEvents instead and pass them to HandleEvent()} */ - virtual void wheelMitkEvent(mitk::WheelEvent *we); - /** \deprecated{Use InteractionEvents instead and pass them to HandleEvent()} */ - virtual void keyPressMitkEvent(mitk::KeyEvent* mke); - /** \deprecated{Use InteractionEvents instead and pass them to HandleEvent()} */ + /** \deprecatedSince{2013_03} Use InteractionEvent instead and pass them to HandleEvent() */ + DEPRECATED(virtual void mousePressMitkEvent(mitk::MouseEvent *me)); + /** \deprecatedSince{2013_03} Use InteractionEvent instead and pass them to HandleEvent() */ + DEPRECATED(virtual void mouseReleaseMitkEvent(mitk::MouseEvent *me)); + /** \deprecatedSince{2013_03} Use InteractionEvent instead and pass them to HandleEvent() */ + DEPRECATED(virtual void mouseMoveMitkEvent(mitk::MouseEvent *me)); + /** \deprecatedSince{2013_03} Use InteractionEvent instead and pass them to HandleEvent() */ + DEPRECATED(virtual void wheelMitkEvent(mitk::WheelEvent *we)); + /** \deprecatedSince{2013_03} Use InteractionEvent instead and pass them to HandleEvent() */ + DEPRECATED(virtual void keyPressMitkEvent(mitk::KeyEvent* mke)); + /** \deprecatedSince{2013_03} Use InteractionEvent instead and pass them to HandleEvent() */ virtual void resizeMitkEvent(int width, int height); virtual bool HandleEvent(InteractionEvent* interactionEvent); protected: RenderWindowBase(); // helper functions: within constructors and destructors classes are not polymorph. void Initialize( mitk::RenderingManager* renderingManager = NULL, const char* name = "unnamed renderer" ); void Destroy(); mitk::VtkPropRenderer::Pointer m_Renderer; vtkMitkRenderProp* m_RenderProp; bool m_InResize; bool m_ProcessWheelEvents; bool m_InvertScrollingDirection; private: }; } #endif /* MITKRENDERWINDOWBASE_H_HEADER_INCLUDED_C1C40D66ASDF */ diff --git a/Core/Code/Resources/Interactions/DisplayConfig.xml b/Core/Code/Resources/Interactions/DisplayConfig.xml index 5e76716816..55c6f6b6d1 100644 --- a/Core/Code/Resources/Interactions/DisplayConfig.xml +++ b/Core/Code/Resources/Interactions/DisplayConfig.xml @@ -1,73 +1,73 @@ - + - + diff --git a/Core/Code/Resources/Interactions/DisplayInteraction.xml b/Core/Code/Resources/Interactions/DisplayInteraction.xml index f891ca261f..b6505dc89a 100644 --- a/Core/Code/Resources/Interactions/DisplayInteraction.xml +++ b/Core/Code/Resources/Interactions/DisplayInteraction.xml @@ -1,65 +1,65 @@ - + - + - + - + - + - + - + - - + + - + - + diff --git a/Core/Code/Resources/Interactions/PointSet.xml b/Core/Code/Resources/Interactions/PointSet.xml index 8451ccb211..bc35dcedd5 100644 --- a/Core/Code/Resources/Interactions/PointSet.xml +++ b/Core/Code/Resources/Interactions/PointSet.xml @@ -1,49 +1,49 @@ - + - + diff --git a/Core/Code/Resources/Interactions/PointSetConfig.xml b/Core/Code/Resources/Interactions/PointSetConfig.xml index f38f80b075..96743379bf 100644 --- a/Core/Code/Resources/Interactions/PointSetConfig.xml +++ b/Core/Code/Resources/Interactions/PointSetConfig.xml @@ -1,40 +1,40 @@ - + diff --git a/Core/Code/Resources/Interactions/globalConfig.xml b/Core/Code/Resources/Interactions/globalConfig.xml index 34d543270c..0915aa1fcf 100644 --- a/Core/Code/Resources/Interactions/globalConfig.xml +++ b/Core/Code/Resources/Interactions/globalConfig.xml @@ -1,70 +1,70 @@ - + - + diff --git a/Core/Code/Resources/Interactions/Tests/AddAndRemovePoints.xml b/Core/Code/Testing/Resources/Interactions/AddAndRemovePoints.xml similarity index 87% rename from Core/Code/Resources/Interactions/Tests/AddAndRemovePoints.xml rename to Core/Code/Testing/Resources/Interactions/AddAndRemovePoints.xml index 28e50b86fa..6ee546e0f5 100644 --- a/Core/Code/Resources/Interactions/Tests/AddAndRemovePoints.xml +++ b/Core/Code/Testing/Resources/Interactions/AddAndRemovePoints.xml @@ -1,31 +1,31 @@ - + - + diff --git a/Core/Code/Resources/Interactions/Tests/StatemachineConfigTest.xml b/Core/Code/Testing/Resources/Interactions/StatemachineConfigTest.xml similarity index 92% rename from Core/Code/Resources/Interactions/Tests/StatemachineConfigTest.xml rename to Core/Code/Testing/Resources/Interactions/StatemachineConfigTest.xml index b0e0095457..ab95481f68 100644 --- a/Core/Code/Resources/Interactions/Tests/StatemachineConfigTest.xml +++ b/Core/Code/Testing/Resources/Interactions/StatemachineConfigTest.xml @@ -1,19 +1,19 @@ - + diff --git a/Core/Code/Resources/Interactions/Tests/StatemachineTest.xml b/Core/Code/Testing/Resources/Interactions/StatemachineTest.xml similarity index 100% rename from Core/Code/Resources/Interactions/Tests/StatemachineTest.xml rename to Core/Code/Testing/Resources/Interactions/StatemachineTest.xml diff --git a/Core/Code/Resources/Interactions/Tests/globalConfig.xml b/Core/Code/Testing/Resources/Interactions/globalConfig.xml similarity index 96% rename from Core/Code/Resources/Interactions/Tests/globalConfig.xml rename to Core/Code/Testing/Resources/Interactions/globalConfig.xml index 34d543270c..0915aa1fcf 100644 --- a/Core/Code/Resources/Interactions/Tests/globalConfig.xml +++ b/Core/Code/Testing/Resources/Interactions/globalConfig.xml @@ -1,70 +1,70 @@ - + - + diff --git a/Core/Code/Testing/files.cmake b/Core/Code/Testing/files.cmake index 6e25a83a43..6ce2f66ba9 100644 --- a/Core/Code/Testing/files.cmake +++ b/Core/Code/Testing/files.cmake @@ -1,130 +1,145 @@ # tests with no extra command line parameter set(MODULE_TESTS mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkDispatcherTest.cpp mitkEnumerationPropertyTest.cpp mitkEventTest.cpp #mitkEventConfigTest.cpp ## needs to be re-written, test indirect since EventConfig is no longer exported as interface Bug 14529 mitkFocusManagerTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkGlobalInteractionTest.cpp mitkImageDataItemTest.cpp #mitkImageMapper2DTest.cpp mitkImageGeneratorTest.cpp mitkBaseDataTest.cpp #mitkImageToItkTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkInteractorTest.cpp mitkInteractionEventTest.cpp mitkITKThreadingTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp #mitkPipelineSmartPointerCorrectnessTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetTest.cpp mitkPointSetWriterTest.cpp mitkPointSetReaderTest.cpp mitkPointSetInteractorTest.cpp mitkPropertyTest.cpp mitkPropertyListTest.cpp #mitkRegistrationBaseTest.cpp #mitkSegmentationInterpolationTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkStateMachineTest.cpp ##mitkStateMachineContainerTest.cpp ## rewrite test, indirect since no longer exported Bug 14529 mitkStateTest.cpp mitkSurfaceTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeSlicedGeometryTest.cpp mitkTransitionTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp #mitkAbstractTransformGeometryTest.cpp mitkStepperTest.cpp itkTotalVariationDenoisingImageFilterTest.cpp mitkRenderingManagerTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp #QmitkRenderingTestHelper.cpp mitkExceptionTest.cpp mitkExtractSliceFilterTest.cpp mitkLogTest.cpp mitkImageDimensionConverterTest.cpp mitkLoggingAdapterTest.cpp mitkUIDGeneratorTest.cpp mitkShaderRepositoryTest.cpp ) # test with image filename as an extra command line parameter set(MODULE_IMAGE_TESTS mitkPlanePositionManagerTest.cpp mitkSurfaceVtkWriterTest.cpp #mitkImageSliceSelectorTest.cpp mitkImageTimeSelectorTest.cpp # mitkVtkPropRendererTest.cpp mitkDataNodeFactoryTest.cpp #mitkSTLFileReaderTest.cpp mitkImageAccessorTest.cpp ) # list of images for which the tests are run set(MODULE_TESTIMAGES # Pic-Factory no more available in Core, test images now in .nrrd format US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd binary.stl ball.stl ) set(MODULE_CUSTOM_TESTS #mitkLabeledImageToSurfaceFilterTest.cpp #mitkExternalToolsTest.cpp mitkDataStorageTest.cpp mitkDataNodeTest.cpp mitkDicomSeriesReaderTest.cpp mitkDICOMLocaleTest.cpp mitkEventMapperTest.cpp mitkNodeDependentPointSetInteractorTest.cpp mitkStateMachineFactoryTest.cpp mitkPointSetLocaleTest.cpp mitkImageTest.cpp mitkImageWriterTest.cpp mitkImageVtkMapper2DTest.cpp mitkImageVtkMapper2DLevelWindowTest.cpp mitkImageVtkMapper2DOpacityTest.cpp mitkImageVtkMapper2DColorTest.cpp mitkImageVtkMapper2DSwivelTest.cpp mitkImageVtkMapper2DTransferFunctionTest.cpp mitkIOUtilTest.cpp mitkSurfaceVtkMapper3DTest mitkSurfaceVtkMapper3DTexturedSphereTest.cpp mitkVolumeCalculatorTest.cpp mitkLevelWindowManagerTest.cpp ) +set(MODULE_RESOURCE_FILES + Interactions/AddAndRemovePoints.xml + Interactions/globalConfig.xml + Interactions/StatemachineTest.xml + Interactions/StatemachineConfigTest.xml +) + # Create an artificial module initializing class for # the usServiceListenerTest.cpp usFunctionGenerateModuleInit(testdriver_init_file NAME ${MODULE_NAME}TestDriver DEPENDS "Mitk" VERSION "0.1.0" EXECUTABLE ) -set(TEST_CPP_FILES ${testdriver_init_file}) +# Embed the resources +set(testdriver_resources ) +usFunctionEmbedResources(testdriver_resources + EXECUTABLE_NAME ${MODULE_NAME}TestDriver + ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Resources + FILES ${MODULE_RESOURCE_FILES} + ) + +set(TEST_CPP_FILES ${testdriver_init_file} ${testdriver_resources}) diff --git a/Core/Code/Testing/mitkInteractionEventTest.cpp b/Core/Code/Testing/mitkInteractionEventTest.cpp index c3496e37ba..6017b66343 100644 --- a/Core/Code/Testing/mitkInteractionEventTest.cpp +++ b/Core/Code/Testing/mitkInteractionEventTest.cpp @@ -1,96 +1,96 @@ /*=================================================================== 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 "mitkMousePressEvent.h" #include "mitkMouseReleaseEvent.h" #include "mitkMouseMoveEvent.h" #include "mitkVtkPropRenderer.h" #include "mitkInteractionEventConst.h" #include "mitkTestingMacros.h" int mitkInteractionEventTest(int /*argc*/, char* /*argv*/[]) { /* * Create different Events, fill them with data. * And check if isEqual method is implemented properly. */ MITK_TEST_BEGIN("InteractionEvent") mitk::VtkPropRenderer::Pointer renderer = NULL; - mitk::MouseButtons buttonStates = mitk::LeftMouseButton | mitk::RightMouseButton; - mitk::MouseButtons eventButton = mitk::LeftMouseButton; - mitk::ModifierKeys modifiers = mitk::ControlKey | mitk::AltKey; + mitk::InteractionEvent::MouseButtons buttonStates = mitk::InteractionEvent::LeftMouseButton | mitk::InteractionEvent::RightMouseButton; + mitk::InteractionEvent::MouseButtons eventButton = mitk::InteractionEvent::LeftMouseButton; + mitk::InteractionEvent::ModifierKeys modifiers = mitk::InteractionEvent::ControlKey | mitk::InteractionEvent::AltKey; mitk::Point2D point; point[0] = 17; point[1] = 170; // MousePress Events mitk::MousePressEvent::Pointer me1 = mitk::MousePressEvent::New(renderer,point, buttonStates, modifiers, eventButton); mitk::MousePressEvent::Pointer me2 = mitk::MousePressEvent::New(renderer,point, buttonStates, modifiers, eventButton); point[0] = 178; point[1] = 170; mitk::MousePressEvent::Pointer me3 = mitk::MousePressEvent::New(renderer,point, buttonStates, modifiers, eventButton); - modifiers = mitk::ControlKey; + modifiers = mitk::InteractionEvent::ControlKey; mitk::MousePressEvent::Pointer me4 = mitk::MousePressEvent::New(renderer,point, buttonStates, modifiers, eventButton); MITK_TEST_CONDITION_REQUIRED( - me1->MatchesTemplate(me2.GetPointer()) && - me1->MatchesTemplate(me3.GetPointer()) && - (me2->MatchesTemplate(me3.GetPointer())) && - !(me3->MatchesTemplate(me4.GetPointer())) + *me1 == *me2 && + *me1 == *me3 && + *me2 == *me3 && + *me3 != *me4 , "Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MousePressEvent"); // MouseReleaseEvents mitk::MouseReleaseEvent::Pointer mr1 = mitk::MouseReleaseEvent::New(renderer,point, buttonStates, modifiers, eventButton); mitk::MouseReleaseEvent::Pointer mr2 = mitk::MouseReleaseEvent::New(renderer,point, buttonStates, modifiers, eventButton); point[0] = 178; point[1] = 170; mitk::MouseReleaseEvent::Pointer mr3 = mitk::MouseReleaseEvent::New(renderer,point, buttonStates, modifiers, eventButton); - eventButton = mitk::RightMouseButton; + eventButton = mitk::InteractionEvent::RightMouseButton; mitk::MouseReleaseEvent::Pointer mr4 = mitk::MouseReleaseEvent::New(renderer,point, buttonStates, modifiers, eventButton); MITK_TEST_CONDITION_REQUIRED( - mr1->MatchesTemplate(mr2.GetPointer()) && - mr1->MatchesTemplate(mr3.GetPointer()) && - (mr2->MatchesTemplate(mr3.GetPointer())) && - !(mr3->MatchesTemplate(mr4.GetPointer())) + *mr1 == *mr2 && + *mr1 == *mr3 && + *mr2 == *mr3 && + *mr3 != *mr4 , "Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MouseReleaseEvent"); // MouseMoveEvents mitk::MouseMoveEvent::Pointer mm1 = mitk::MouseMoveEvent::New(renderer,point, buttonStates, modifiers); point[0] = 178; point[1] = 170; mitk::MouseMoveEvent::Pointer mm3 = mitk::MouseMoveEvent::New(renderer,point, buttonStates, modifiers); - modifiers = mitk::AltKey; + modifiers = mitk::InteractionEvent::AltKey; mitk::MouseMoveEvent::Pointer mm4 = mitk::MouseMoveEvent::New(renderer,point, buttonStates, modifiers); MITK_TEST_CONDITION_REQUIRED( - mm1->MatchesTemplate(mm3.GetPointer()) && - !(mm3->MatchesTemplate(mm4.GetPointer())) + *mm1 == *mm3 && + *mm3 != *mm4 , "Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MouseMoveEvent"); // always end with this! MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkPropertyTest.cpp b/Core/Code/Testing/mitkPropertyTest.cpp index d72da3c11a..409dfc78e2 100644 --- a/Core/Code/Testing/mitkPropertyTest.cpp +++ b/Core/Code/Testing/mitkPropertyTest.cpp @@ -1,375 +1,385 @@ /*=================================================================== 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 #include #include #include #include #include #include #include #include #include #include #include struct PropertyModifiedListener { typedef itk::SimpleMemberCommand CmdType; PropertyModifiedListener() : m_Modified(false), m_Cmd(CmdType::New()) { m_Cmd->SetCallbackFunction(this, &PropertyModifiedListener::Modified); } void Modified() { m_Modified = true; } bool Pop() { bool b = m_Modified; m_Modified = false; return b; } bool m_Modified; CmdType::Pointer m_Cmd; }; template void TestPropInequality(T prop, T prop2) { mitk::BaseProperty::Pointer baseProp2(prop2.GetPointer()); MITK_TEST_CONDITION_REQUIRED(!(*prop == *prop2), "Test inequality 1"); MITK_TEST_CONDITION_REQUIRED(!(*prop == *baseProp2), "Test polymorphic inequality 1"); MITK_TEST_CONDITION_REQUIRED(!(*baseProp2 == *prop), "Test polymorphic inequality 2"); } template void TestPropAssignment(T prop, T prop2, const std::string& strProp) { PropertyModifiedListener l; unsigned long tag = prop->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); mitk::BaseProperty::Pointer baseProp2(prop2.GetPointer()); *prop = *baseProp2; MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified event"); std::string msg = std::string("Test assignment [") + prop->GetValueAsString() + " == " + strProp + "]"; MITK_TEST_CONDITION_REQUIRED(prop->GetValueAsString() == strProp, msg); MITK_TEST_CONDITION_REQUIRED(*prop == *prop2, "Test equality"); MITK_TEST_CONDITION_REQUIRED(*prop == *baseProp2, "Test equality"); MITK_TEST_CONDITION_REQUIRED(*baseProp2 == *prop, "Test polymorphic equality"); prop->RemoveObserver(tag); } template void TestPropPolymorphicAssignment(T prop, T prop2, const std::string& strProp) { mitk::BaseProperty::Pointer baseProp(prop.GetPointer()); PropertyModifiedListener l; unsigned long tag = baseProp->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); *baseProp = *prop2; MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified event"); std::string msg = std::string("Test polymorphic assignment [") + baseProp->GetValueAsString() + " == " + strProp + "]"; MITK_TEST_CONDITION_REQUIRED(baseProp->GetValueAsString() == strProp, msg); MITK_TEST_CONDITION_REQUIRED(*prop == *prop2, "Test equality"); MITK_TEST_CONDITION_REQUIRED(*prop2 == *baseProp, "Test equality"); MITK_TEST_CONDITION_REQUIRED(*baseProp == *prop2, "Test polymorphic equality"); baseProp->RemoveObserver(tag); } +template +void TestPropCloning(T prop) +{ + T prop2 = prop->Clone(); + MITK_TEST_CONDITION_REQUIRED(prop.GetPointer() != prop2.GetPointer(), "Test clone pointer") + MITK_TEST_CONDITION_REQUIRED(*prop == *prop2, "Test equality of the clone") +} + template void TestProperty(const typename T::ValueType& v1, const typename T::ValueType& v2, const std::string& strV1, const std::string& strV2) { PropertyModifiedListener l; typename T::Pointer prop = T::New(v1); MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); MITK_TEST_CONDITION_REQUIRED(prop->GetValue() == v1, "Test constructor"); std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + strV1 + "]"; MITK_TEST_CONDITION_REQUIRED(prop->GetValueAsString() == strV1, msg); + TestPropCloning(prop); + typename T::Pointer prop2 = T::New(); prop2->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); MITK_TEST_CONDITION_REQUIRED(!l.m_Modified, "Test modified"); prop2->SetValue(v2); MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); MITK_TEST_CONDITION_REQUIRED(prop2->GetValue() == v2, "Test SetValue()"); prop2->SetValue(v2); MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); TestPropInequality(prop, prop2); TestPropAssignment(prop, prop2, strV2); prop->SetValue(v1); TestPropPolymorphicAssignment(prop2, prop, strV1); } void TestGenericProperties() { TestProperty(false, true, "0", "1"); TestProperty(3, 5, "3", "5"); TestProperty(0.3f, -23.5f, "0.3", "-23.5"); TestProperty(64.1f, 2.34f, "64.1", "2.34"); { mitk::Vector3D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; mitk::Vector3D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; TestProperty(p1, p2, "[2, 3, 4]", "[-1, 2, 3]"); } { mitk::Point3D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; mitk::Point3D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; TestProperty( p1, p2, "[2, 3, 4]", "[-1, 2, 3]"); } { mitk::Point4D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; p1[3] =-2.0; mitk::Point4D p2; p2[0] =-1.0; p2[1] = 2.0; p2[2] = 3.0; p2[3] = 5.0; TestProperty(p1, p2, "[2, 3, 4, -2]", "[-1, 2, 3, 5]"); } { mitk::Point3I p1; p1[0] = 2; p1[1] = 3; p1[2] = 4; mitk::Point3I p2; p2[0] = 8; p2[1] = 7; p2[2] = 6; TestProperty(p1, p2, "[2, 3, 4]", "[8, 7, 6]"); } { mitk::FloatLookupTable lut1; lut1.SetTableValue(1, 0.3f); lut1.SetTableValue(4, 323.7f); mitk::FloatLookupTable lut2; lut2.SetTableValue(6, -0.3f); lut2.SetTableValue(2, 25.7f); TestProperty(lut1, lut2, "[1 -> 0.3, 4 -> 323.7]", "[2 -> 25.7, 6 -> -0.3]"); } { mitk::BoolLookupTable lut1; lut1.SetTableValue(3, false); lut1.SetTableValue(5, true); mitk::BoolLookupTable lut2; lut2.SetTableValue(1, false); lut2.SetTableValue(2, false); TestProperty(lut1, lut2, "[3 -> 0, 5 -> 1]", "[1 -> 0, 2 -> 0]"); } { mitk::IntLookupTable lut1; lut1.SetTableValue(5, -12); lut1.SetTableValue(7, 3); mitk::IntLookupTable lut2; lut2.SetTableValue(4, -6); lut2.SetTableValue(8, -45); TestProperty(lut1, lut2, "[5 -> -12, 7 -> 3]", "[4 -> -6, 8 -> -45]"); } { mitk::StringLookupTable lut1; lut1.SetTableValue(0, "a"); lut1.SetTableValue(2, "b"); mitk::StringLookupTable lut2; lut2.SetTableValue(0, "a"); lut2.SetTableValue(2, "c"); TestProperty(lut1, lut2, "[0 -> a, 2 -> b]", "[0 -> a, 2 -> c]"); } } void TestAnnotationProperty() { PropertyModifiedListener l; std::string label1("Label1"); mitk::Point3D point1; point1[0] = 3; point1[1] = 5; point1[2] = -4; std::string str1 = "Label1[3, 5, -4]"; std::string label2("Label2"); mitk::Point3D point2; point2[0] = -2; point2[1] = 8; point2[2] = -4; std::string str2 = "Label2[-2, 8, -4]"; mitk::AnnotationProperty::Pointer prop = mitk::AnnotationProperty::New(label1, point1); MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); MITK_TEST_CONDITION_REQUIRED(prop->GetLabel() == label1 && prop->GetPosition() == point1, "Test constructor"); std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + str1 + "]"; MITK_TEST_CONDITION_REQUIRED(prop->GetValueAsString() == str1, msg); mitk::AnnotationProperty::Pointer prop2 = mitk::AnnotationProperty::New(); prop2->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); MITK_TEST_CONDITION_REQUIRED(!l.m_Modified, "Test not modified"); prop2->SetLabel(label2); MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); prop2->SetPosition(point2); MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); MITK_TEST_CONDITION_REQUIRED(prop2->GetLabel() == label2 && prop2->GetPosition() == point2, "Test Setter"); prop2->SetLabel(label2); MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); prop2->SetPosition(point2); MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); TestPropInequality(prop, prop2); TestPropAssignment(prop, prop2, str2); prop->SetLabel(label1); prop->SetPosition(point1); TestPropPolymorphicAssignment(prop2, prop, str1); } void TestClippingProperty() { PropertyModifiedListener l; bool enabled1 = true; mitk::Point3D point1; point1[0] = 3; point1[1] = 5; point1[2] = -4; mitk::Vector3D vec1; vec1[0] = 0; vec1[1] = 2; vec1[2] = -1; std::string str1 = "1[3, 5, -4][0, 2, -1]"; bool enabled2 = false; mitk::Point3D point2; point2[0] = -2; point2[1] = 8; point2[2] = -4; mitk::Vector3D vec2; vec2[0] = 0; vec2[1] = 2; vec2[2] = 4; std::string str2 = "0[-2, 8, -4][0, 2, 4]"; mitk::ClippingProperty::Pointer prop = mitk::ClippingProperty::New(point1, vec1); MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); MITK_TEST_CONDITION_REQUIRED(prop->GetClippingEnabled() == enabled1 && prop->GetOrigin() == point1 && prop->GetNormal() == vec1, "Test constructor"); std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + str1 + "]"; MITK_TEST_CONDITION_REQUIRED(prop->GetValueAsString() == str1, msg); mitk::ClippingProperty::Pointer prop2 = mitk::ClippingProperty::New(); prop2->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); MITK_TEST_CONDITION_REQUIRED(!l.m_Modified, "Test not modified"); prop2->SetClippingEnabled(enabled2); MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test not modified"); prop2->SetOrigin(point2); MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); prop2->SetNormal(vec2); MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); MITK_TEST_CONDITION_REQUIRED(prop2->GetClippingEnabled() == enabled2 && prop2->GetOrigin() == point2 && prop2->GetNormal() == vec2, "Test Setter"); prop2->SetClippingEnabled(enabled2); MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); prop2->SetOrigin(point2); MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); prop2->SetNormal(vec2); MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); TestPropInequality(prop, prop2); TestPropAssignment(prop, prop2, str2); prop->SetClippingEnabled(enabled1); prop->SetOrigin(point1); prop->SetNormal(vec1); TestPropPolymorphicAssignment(prop2, prop, str1); } int mitkPropertyTest(int /* argc */, char* /*argv*/[]) { MITK_TEST_BEGIN("Testing MITK Properties") TestGenericProperties(); TestAnnotationProperty(); TestClippingProperty(); mitk::Color c1; c1[0] = 0.2; c1[1] = 0.6; c1[2] = 0.8; mitk::Color c2; c2[0] = 0.2; c2[1] = 0.4; c2[2] = 0.1; TestProperty(c1, c2, "0.2 0.6 0.8", "0.2 0.4 0.1"); mitk::LevelWindow lw1(50, 100); mitk::LevelWindow lw2(120, 30); TestProperty(lw1, lw2, "L:50 W:100", "L:120 W:30"); { itk::Object::Pointer sp1 = itk::Object::New(); itk::Object::Pointer sp2 = itk::Object::New(); // to generate the UIDs, we set the smartpointers mitk::SmartPointerProperty::Pointer spp1 = mitk::SmartPointerProperty::New(sp1.GetPointer()); mitk::SmartPointerProperty::Pointer spp2 = mitk::SmartPointerProperty::New(sp2.GetPointer()); TestProperty(sp1, sp2, spp1->GetReferenceUIDFor(sp1), spp2->GetReferenceUIDFor(sp2)); } TestProperty("1", "2", "1", "2"); { mitk::TransferFunction::Pointer tf1 = mitk::TransferFunction::New(); mitk::TransferFunction::Pointer tf2 = mitk::TransferFunction::New(); tf2->AddScalarOpacityPoint(0.4, 0.8); std::stringstream ss; ss << tf1; std::string strTF1 = ss.str(); ss.str(""); ss << tf2; std::string strTF2 = ss.str(); TestProperty(tf1, tf2, strTF1, strTF2); } { itk::Object::Pointer sp1 = itk::Object::New(); itk::Object::Pointer sp2 = itk::Object::New(); mitk::WeakPointerProperty::ValueType wp1 = sp1.GetPointer(); mitk::WeakPointerProperty::ValueType wp2 = sp2.GetPointer(); std::stringstream ss; ss << sp1.GetPointer(); std::string str1 = ss.str(); ss.str(""); ss << sp2.GetPointer(); std::string str2 = ss.str(); TestProperty(wp1, wp2, str1, str2); } { mitk::LookupTable::Pointer lut1 = mitk::LookupTable::New(); lut1->GetVtkLookupTable()->SetTableValue(0, 0.2, 0.3, 0.4); mitk::LookupTable::Pointer lut2 = mitk::LookupTable::New(); lut2->GetVtkLookupTable()->SetTableValue(0, 0.2, 0.4, 0.4); std::stringstream ss; ss << lut1; std::string strLUT1 = ss.str(); ss.str(""); ss << lut2; std::string strLUT2 = ss.str(); TestProperty(lut1, lut2, strLUT1, strLUT2); } MITK_TEST_END() } diff --git a/Core/Code/files.cmake b/Core/Code/files.cmake index 5ac0ab1c8c..a962092fd6 100644 --- a/Core/Code/files.cmake +++ b/Core/Code/files.cmake @@ -1,363 +1,360 @@ set(H_FILES Algorithms/itkImportMitkImageContainer.h Algorithms/itkImportMitkImageContainer.txx Algorithms/itkLocalVariationImageFilter.h Algorithms/itkLocalVariationImageFilter.txx Algorithms/itkMITKScalarImageToHistogramGenerator.h Algorithms/itkMITKScalarImageToHistogramGenerator.txx Algorithms/itkTotalVariationDenoisingImageFilter.h Algorithms/itkTotalVariationDenoisingImageFilter.txx Algorithms/itkTotalVariationSingleIterationImageFilter.h Algorithms/itkTotalVariationSingleIterationImageFilter.txx Algorithms/mitkBilateralFilter.h Algorithms/mitkBilateralFilter.cpp Algorithms/mitkInstantiateAccessFunctions.h Algorithms/mitkPixelTypeList.h # Preprocessor macros taken from Boost Algorithms/mitkPPArithmeticDec.h Algorithms/mitkPPArgCount.h Algorithms/mitkPPCat.h Algorithms/mitkPPConfig.h Algorithms/mitkPPControlExprIIf.h Algorithms/mitkPPControlIf.h Algorithms/mitkPPControlIIf.h Algorithms/mitkPPDebugError.h Algorithms/mitkPPDetailAutoRec.h Algorithms/mitkPPDetailDMCAutoRec.h Algorithms/mitkPPExpand.h Algorithms/mitkPPFacilitiesEmpty.h Algorithms/mitkPPFacilitiesExpand.h Algorithms/mitkPPLogicalBool.h Algorithms/mitkPPRepetitionDetailDMCFor.h Algorithms/mitkPPRepetitionDetailEDGFor.h Algorithms/mitkPPRepetitionDetailFor.h Algorithms/mitkPPRepetitionDetailMSVCFor.h Algorithms/mitkPPRepetitionFor.h Algorithms/mitkPPSeqElem.h Algorithms/mitkPPSeqForEach.h Algorithms/mitkPPSeqForEachProduct.h Algorithms/mitkPPSeq.h Algorithms/mitkPPSeqEnum.h Algorithms/mitkPPSeqSize.h Algorithms/mitkPPSeqToTuple.h Algorithms/mitkPPStringize.h Algorithms/mitkPPTupleEat.h Algorithms/mitkPPTupleElem.h Algorithms/mitkPPTupleRem.h Algorithms/mitkClippedSurfaceBoundsCalculator.h Algorithms/mitkExtractSliceFilter.h Algorithms/mitkConvert2Dto3DImageFilter.h Algorithms/mitkPlaneClipping.h Common/mitkExceptionMacro.h Common/mitkServiceBaseObject.h Common/mitkTestingMacros.h DataManagement/mitkImageAccessByItk.h DataManagement/mitkImageCast.h DataManagement/mitkImagePixelAccessor.h DataManagement/mitkImagePixelReadAccessor.h DataManagement/mitkImagePixelWriteAccessor.h DataManagement/mitkImageReadAccessor.h DataManagement/mitkImageWriteAccessor.h DataManagement/mitkITKImageImport.h DataManagement/mitkITKImageImport.txx DataManagement/mitkImageToItk.h DataManagement/mitkImageToItk.txx Interactions/mitkEventMapperAddOn.h Interfaces/mitkIDataNodeReader.h IO/mitkPixelTypeTraits.h ) set(CPP_FILES Algorithms/mitkBaseDataSource.cpp Algorithms/mitkBaseProcess.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/mitkPointSetSource.cpp Algorithms/mitkPointSetToPointSetFilter.cpp Algorithms/mitkRGBToRGBACastImageFilter.cpp Algorithms/mitkSubImageSelector.cpp Algorithms/mitkSurfaceSource.cpp Algorithms/mitkSurfaceToSurfaceFilter.cpp Algorithms/mitkUIDGenerator.cpp Algorithms/mitkVolumeCalculator.cpp Algorithms/mitkClippedSurfaceBoundsCalculator.cpp Algorithms/mitkExtractSliceFilter.cpp Algorithms/mitkConvert2Dto3DImageFilter.cpp Controllers/mitkBaseController.cpp Controllers/mitkCallbackFromGUIThread.cpp Controllers/mitkCameraController.cpp Controllers/mitkCameraRotationController.cpp Controllers/mitkCoreActivator.cpp Controllers/mitkFocusManager.cpp Controllers/mitkLimitedLinearUndo.cpp Controllers/mitkOperationEvent.cpp Controllers/mitkPlanePositionManager.cpp Controllers/mitkProgressBar.cpp Controllers/mitkRenderingManager.cpp Controllers/mitkSliceNavigationController.cpp Controllers/mitkSlicesCoordinator.cpp Controllers/mitkSlicesRotator.cpp Controllers/mitkSlicesSwiveller.cpp Controllers/mitkStatusBar.cpp Controllers/mitkStepper.cpp Controllers/mitkTestManager.cpp Controllers/mitkUndoController.cpp Controllers/mitkVerboseLimitedLinearUndo.cpp Controllers/mitkVtkInteractorCameraController.cpp Controllers/mitkVtkLayerController.cpp DataManagement/mitkAbstractTransformGeometry.cpp DataManagement/mitkAnnotationProperty.cpp DataManagement/mitkApplicationCursor.cpp DataManagement/mitkBaseData.cpp DataManagement/mitkBaseProperty.cpp DataManagement/mitkClippingProperty.cpp DataManagement/mitkChannelDescriptor.cpp DataManagement/mitkColorProperty.cpp DataManagement/mitkDataStorage.cpp #DataManagement/mitkDataTree.cpp DataManagement/mitkDataNode.cpp DataManagement/mitkDataNodeFactory.cpp #DataManagement/mitkDataTreeStorage.cpp DataManagement/mitkDisplayGeometry.cpp DataManagement/mitkEnumerationProperty.cpp DataManagement/mitkGeometry2D.cpp DataManagement/mitkGeometry2DData.cpp DataManagement/mitkGeometry3D.cpp DataManagement/mitkGeometryData.cpp DataManagement/mitkGroupTagProperty.cpp DataManagement/mitkImage.cpp DataManagement/mitkImageAccessorBase.cpp DataManagement/mitkImageCaster.cpp DataManagement/mitkImageCastPart1.cpp DataManagement/mitkImageCastPart2.cpp DataManagement/mitkImageCastPart3.cpp DataManagement/mitkImageCastPart4.cpp DataManagement/mitkImageDataItem.cpp DataManagement/mitkImageDescriptor.cpp DataManagement/mitkImageVtkAccessor.cpp DataManagement/mitkImageStatisticsHolder.cpp DataManagement/mitkLandmarkBasedCurvedGeometry.cpp DataManagement/mitkLandmarkProjectorBasedCurvedGeometry.cpp DataManagement/mitkLandmarkProjector.cpp DataManagement/mitkLevelWindow.cpp DataManagement/mitkLevelWindowManager.cpp DataManagement/mitkLevelWindowPreset.cpp DataManagement/mitkLevelWindowProperty.cpp DataManagement/mitkLookupTable.cpp DataManagement/mitkLookupTables.cpp # specializations of GenericLookupTable DataManagement/mitkMemoryUtilities.cpp DataManagement/mitkModalityProperty.cpp DataManagement/mitkModeOperation.cpp DataManagement/mitkNodePredicateAnd.cpp DataManagement/mitkNodePredicateBase.cpp DataManagement/mitkNodePredicateCompositeBase.cpp DataManagement/mitkNodePredicateData.cpp DataManagement/mitkNodePredicateDataType.cpp DataManagement/mitkNodePredicateDimension.cpp DataManagement/mitkNodePredicateFirstLevel.cpp DataManagement/mitkNodePredicateNot.cpp DataManagement/mitkNodePredicateOr.cpp DataManagement/mitkNodePredicateProperty.cpp DataManagement/mitkNodePredicateSource.cpp DataManagement/mitkPlaneOrientationProperty.cpp DataManagement/mitkPlaneGeometry.cpp DataManagement/mitkPlaneOperation.cpp DataManagement/mitkPointOperation.cpp DataManagement/mitkPointSet.cpp DataManagement/mitkProperties.cpp DataManagement/mitkPropertyList.cpp DataManagement/mitkRestorePlanePositionOperation.cpp DataManagement/mitkRotationOperation.cpp DataManagement/mitkSlicedData.cpp DataManagement/mitkSlicedGeometry3D.cpp DataManagement/mitkSmartPointerProperty.cpp DataManagement/mitkStandaloneDataStorage.cpp DataManagement/mitkStateTransitionOperation.cpp DataManagement/mitkStringProperty.cpp DataManagement/mitkSurface.cpp DataManagement/mitkSurfaceOperation.cpp DataManagement/mitkThinPlateSplineCurvedGeometry.cpp DataManagement/mitkTimeSlicedGeometry.cpp DataManagement/mitkTransferFunction.cpp DataManagement/mitkTransferFunctionProperty.cpp DataManagement/mitkTransferFunctionInitializer.cpp DataManagement/mitkVector.cpp DataManagement/mitkVtkInterpolationProperty.cpp DataManagement/mitkVtkRepresentationProperty.cpp DataManagement/mitkVtkResliceInterpolationProperty.cpp DataManagement/mitkVtkScalarModeProperty.cpp DataManagement/mitkVtkVolumeRenderingProperty.cpp DataManagement/mitkWeakPointerProperty.cpp DataManagement/mitkRenderingModeProperty.cpp DataManagement/mitkShaderProperty.cpp DataManagement/mitkResliceMethodProperty.cpp DataManagement/mitkMaterial.cpp 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/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/mitkStateMachineState.cpp Interactions/mitkStateMachineTransition.cpp Interactions/mitkState.cpp Interactions/mitkStateMachineContainer.cpp Interactions/mitkStateEvent.cpp Interactions/mitkStateMachine.cpp Interactions/mitkStateMachineFactory.cpp Interactions/mitkTransition.cpp Interactions/mitkWheelEvent.cpp Interactions/mitkKeyEvent.cpp Interactions/mitkVtkEventAdapter.cpp Interactions/mitkVtkInteractorStyle.cxx Interactions/mitkCrosshairPositionEvent.cpp Interfaces/mitkInteractionEventObserver.cpp Interfaces/mitkIShaderRepository.cpp IO/mitkBaseDataIOFactory.cpp IO/mitkCoreDataNodeReader.cpp IO/mitkDicomSeriesReader.cpp IO/mitkFileReader.cpp IO/mitkFileSeriesReader.cpp IO/mitkFileWriter.cpp #IO/mitkIpPicGet.c IO/mitkImageGenerator.cpp IO/mitkImageWriter.cpp IO/mitkImageWriterFactory.cpp IO/mitkItkImageFileIOFactory.cpp IO/mitkItkImageFileReader.cpp IO/mitkItkLoggingAdapter.cpp IO/mitkItkPictureWrite.cpp IO/mitkIOUtil.cpp IO/mitkLookupTableProperty.cpp IO/mitkOperation.cpp #IO/mitkPicFileIOFactory.cpp #IO/mitkPicFileReader.cpp #IO/mitkPicFileWriter.cpp #IO/mitkPicHelper.cpp #IO/mitkPicVolumeTimeSeriesIOFactory.cpp #IO/mitkPicVolumeTimeSeriesReader.cpp IO/mitkPixelType.cpp IO/mitkPointSetIOFactory.cpp IO/mitkPointSetReader.cpp IO/mitkPointSetWriter.cpp IO/mitkPointSetWriterFactory.cpp IO/mitkRawImageFileReader.cpp IO/mitkStandardFileLocations.cpp IO/mitkSTLFileIOFactory.cpp IO/mitkSTLFileReader.cpp IO/mitkSurfaceVtkWriter.cpp IO/mitkSurfaceVtkWriterFactory.cpp IO/mitkVtkLoggingAdapter.cpp IO/mitkVtiFileIOFactory.cpp IO/mitkVtiFileReader.cpp IO/mitkVtkImageIOFactory.cpp IO/mitkVtkImageReader.cpp IO/mitkVtkSurfaceIOFactory.cpp IO/mitkVtkSurfaceReader.cpp IO/vtkPointSetXMLParser.cpp IO/mitkLog.cpp Rendering/mitkBaseRenderer.cpp Rendering/mitkVtkMapper.cpp Rendering/mitkRenderWindowFrame.cpp Rendering/mitkGeometry2DDataMapper2D.cpp Rendering/mitkGeometry2DDataVtkMapper3D.cpp Rendering/mitkGLMapper.cpp Rendering/mitkGradientBackground.cpp Rendering/mitkManufacturerLogo.cpp Rendering/mitkMapper.cpp Rendering/mitkPointSetGLMapper2D.cpp Rendering/mitkPointSetVtkMapper3D.cpp Rendering/mitkPolyDataGLMapper2D.cpp Rendering/mitkSurfaceGLMapper2D.cpp Rendering/mitkSurfaceVtkMapper3D.cpp Rendering/mitkVolumeDataVtkMapper3D.cpp Rendering/mitkVtkPropRenderer.cpp Rendering/mitkVtkWidgetRendering.cpp Rendering/vtkMitkRectangleProp.cpp Rendering/vtkMitkRenderProp.cpp Rendering/mitkVtkEventProvider.cpp Rendering/mitkRenderWindow.cpp Rendering/mitkRenderWindowBase.cpp Rendering/mitkShaderRepository.cpp Rendering/mitkImageVtkMapper2D.cpp Rendering/vtkMitkThickSlicesFilter.cpp Rendering/vtkMitkLevelWindowFilter.cpp Rendering/vtkNeverTranslucentTexture.cpp Rendering/mitkRenderingTestHelper.cpp Common/mitkException.cpp Common/mitkCommon.h Common/mitkCoreObjectFactoryBase.cpp Common/mitkCoreObjectFactory.cpp Common/mitkCoreServices.cpp ) list(APPEND CPP_FILES ${CppMicroServices_SOURCES}) set(RESOURCE_FILES Interactions/globalConfig.xml Interactions/DisplayInteraction.xml Interactions/DisplayConfig.xml Interactions/DisplayConfigPACS.xml Interactions/DisplayConfigPACSPan.xml Interactions/DisplayConfigPACSScroll.xml Interactions/DisplayConfigPACSZoom.xml Interactions/DisplayConfigPACSLevelWindow.xml Interactions/DisplayConfigMITK.xml Interactions/PointSet.xml Interactions/Legacy/StateMachine.xml Interactions/Legacy/DisplayConfigMITKTools.xml Interactions/PointSetConfig.xml -Interactions/Tests/AddAndRemovePoints.xml -Interactions/Tests/globalConfig.xml -Interactions/Tests/StatemachineTest.xml -Interactions/Tests/StatemachineConfigTest.xml Shaders/mitkShaderLighting.xml mitkLevelWindowPresets.xml ) diff --git a/Core/Documentation/Doxygen/Concepts/NewEvents.dox b/Core/Documentation/Doxygen/Concepts/NewEvents.dox index cb42cb550a..9a3545d9cf 100644 --- a/Core/Documentation/Doxygen/Concepts/NewEvents.dox +++ b/Core/Documentation/Doxygen/Concepts/NewEvents.dox @@ -1,72 +1,67 @@ /** \page ImplementNewEventsPage What needs to be done to implement a new event? \tableofcontents \section WhenUseEvents When to use this guide In general there are no restriction about how events are created and processed. The intention of this page is to provide how to contruct Events in order to use them with the MITK Interaction Concept. \section OriginEvents Origin and processing of Events \ref DataInteractionPage gives a brief description of how events are generated and proccessed. After events are created they need to be send via mitk::RenderWindowBase::HandleEvent() so that they are relayed to a Dispatcher which handles the event distribution to the DataInteractors. \section EventImplementation Event Implementation The only prerequisite for a new event to be accepted is that it is derived from the mitk::InteractionEvent class. -Further it is neccessary to provide a unique string identifier for this event class -(this string will identify this class/super-class in a state machine pattern by the event_class tag), and it needs to implement at least two functions, -as shown at the example of the MousePressEvent. +The new event must implement at least two functions, +as shown in the example of the MousePressEvent. -Implementation of equality for each event class by implementing isEqual. +Implementation of equality for each event class by implementing IsEqual. Equality does \b not mean an exact copy or pointer equality. Equality is determined by agreement in all attributes that are necessary to describe the event for a state machine transition. Here, for example, for the a mouse event press event, it is important which modifiers are used, which mouse button was used to triggered the event, but the mouse position is irrelevant. \code -bool mitk::MousePressEvent::MatchesTemplate(mitk::InteractionEvent::Pointer interactionEvent) +bool mitk::MousePressEvent::IsEqual(const mitk::InteractionEvent& interactionEvent) { - // cast to your event class here - mitk::MousePressEvent* mpe = dynamic_cast(interactionEvent.GetPointer()); - if (mpe == NULL) - { - return false; - } + // cast to your event class here (this is guaranteed to work + const mitk::MousePressEvent& mpe = static_cast(interactionEvent); // Checking relevant attributes, such as EventButton and Modifiers, but omitting the mouse coordinates // Replace this to check for your event class' attributes - return (this->GetEventButton() == mpe->GetEventButton() && this->GetModifiers() == mpe->GetModifiers() - && this->GetButtonStates() == mpe->GetButtonStates()); + return (this->GetEventButton() == mpe.GetEventButton() && this->GetModifiers() == mpe.GetModifiers() + && this->GetButtonStates() == mpe.GetButtonStates()) && Superclass::IsEqual(interactionEvent); } \endcode The function IsSuperClassOf() implements an up cast to check if the provided baseClass object is derived from this class. This function is used to support polymorphism on state machine pattern (XML) level. \code bool mitk::MousePressEvent::IsSuperClassOf(InteractionEvent::Pointer baseClass) { // Replace with your class, or implement some rules which classes are accepted. MousePressEvent* event = dynamic_cast(baseClass.GetPointer()); if (event != NULL) { return true; } return false; } \endcode \section EventConstruction Configuration File & Event Factory Regarding the state machine and the state machine pattern parser there are no changes necessary. To be able to parse the new event, changes have to be made in the mitk::EventConfig and mitk::EventFactory classes. The mitk::EventConfig class has to be adapted in a way such that the parameters that describe the event are parsed. The parsing can be easily extended, and should provide a mitk::PropertyList for each event parsed. Lastly the mitk::EventFactory has to be extended to use this mitk::PropertyList and construct an event based on it. */ diff --git a/Documentation/Doxygen/DeveloperManual/Starting/GettingToKnow/Tutorial/Step10.dox b/Documentation/Doxygen/DeveloperManual/Starting/GettingToKnow/Tutorial/Step10.dox index 493da74bde..542dd477c9 100644 --- a/Documentation/Doxygen/DeveloperManual/Starting/GettingToKnow/Tutorial/Step10.dox +++ b/Documentation/Doxygen/DeveloperManual/Starting/GettingToKnow/Tutorial/Step10.dox @@ -1,432 +1,432 @@ /** \page Step10Page MITK Tutorial - Step 10: Adding new Interaction \tableofcontents \section HowToUseDataInteractor How to use an existing DataInteractor MITK provides finished DataInteractors for a variety of tasks, they can be found in Code/Core/Interactors. They can be used with state machine patterns and config files located under Resources/Interaction. A DataInteractor consists of four parts. The class describing the functionality and two XML files; one describes the state machine pattern, that is the workflow of an interaction and the second describes the user events which trigger an action. Lastly every DataInteractor works on a DataNode in which it stores and manipulates data. To use a DataInteractor these parts have to be brought together. This code demonstrates the use of an existing DataInteractor exemplary for the PointSetDataInteractor: First we need a DataNode that is added to the DataStorage. \code mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); GetDataStorage()->Add(dataNode.GetPointer()); \endcode Then we create an instance of to PointSetDataInteractor and load a statemachine pattern as well as a configuration for it: \code m_CurrentInteractor = mitk::PointSetDataInteractor::New(); m_CurrentInteractor->LoadStateMachine("PointSet.xml"); m_CurrentInteractor->LoadEventConfig("PointSetConfig.xml"); \endcode Lastly the DataNode is added to the DataInteractor \code m_CurrentInteractor->SetDataNode(dataNode); \endcode now the DataInteractor is ready for usage. \section SectionImplementationDataInteractor How to implement a new DataInteractor This second part of the tutorial step goes beyond the activation of an interactor, that modifies data by user interaction) as shown above. It shows what needs to be implemented to add a new way of interaction within your MITK application. Please see \ref DataInteractionPage as an introduction to the MITK interaction mechanism, you may also want to read \ref DataInteractionTechnicalPage. This tutorial is structured as follows: The first section deals with config files, describing all the parameters of events and how to use them in a configuration file. In the second section the basics are described that are needed to write a state machine pattern. The last section deals with brining configuration, state machine pattern and code together and gives an examplary implementation of a DataInteractor. \section ConfigFileDescriptionSection How to create a Config-File \subsection EventDescriptionSection Event Description Events are described by their parameters. Each event type has its own set of parameters that can be set in the configuration file. If a parameter is ommitted it is set to its default value. Following all possible parameters are listed and described, to which parameters events have is decribed in their respective documentation. Mandatory for each event description is the event class and the event variant. The parameters of an event are set by attribute tags. \note Refer to \ref EventClassSection for the meaning of event class. \b Mouse \b Buttons \n mitk::MouseButtons represent the buttons. They can be used for two attributes. First the EventButton which describes the button that triggered the event, this allways is a single button. Secondly the ButtonState attribute that describes which buttons were pressed at the moment the event has been generated. For example assume the right mouse button and the middle mouse button are already pressed, now also the left mouse button is pressed too and generates a second event, this would be described as follows: \code \endcode Note: Technically the LeftMouseButton is also pressed and should be listed in the ButtonState, but this is taken care of by the mitk:EventFactory . Key Events \n mitk::InteractionKeyEvent represents a pressed key, which key is pressed is provided with the Key attribute like this \code \endcode or \code \endcode \note Key Events do not require an explicit configuration all, for all key events there exists a predefined event variant with the name 'Std' + value, that is key a is named 'StdA'. The names for special keys are listed here: \dontinclude mitkInteractionEventConst.h \skipline // Special Keys \until // End special keys Modifier Keys \n mitk::ModifierKeys represent the combination of pressed modifier keys, several modifier keys pressed at the same time are denoted by listing them all separated by commas. \code \endcode \b ScrollDirection \n This attribute is unique to the mitk::MouseWheelEvent and describes the direction in which the mouse wheel is rotated. In the event description actual only the direction is provided, but the event is generated with the actual value, and this value can be retrieved from the object. \code \endcode \subsection ExamplesSection Examples Examples for key events: \code - + - + \endcode Examples for MousePress events: \code \endcode There exists a standard configuration file for the most common events called GlobalConfig.xml that can be used to as a default and can be extended by a specific definition. \subsection ParameterDescriptionSection Parameter Description It is also possible to store parameters in the config file. Those are stored using the param-tag, like this: \code \endcode Within the application these properties can then be access via a mitk::PropertyList like this: \code // sm - state machine loaded with config file example2 mitk::PropertyList::Pointer properties = GetAttributes(); std::string prop1; properties->GetStringProperty("property1",prop1); \endcode \section HowToStateMachine HowTo Write a State Machine A state machine pattern is described in a XML file. \subsection StateSection States States are described using the state-tag. Each state has to have a name. Exactly one state has to be as start state in each state machine to indicate the state in which the state machine is set when it is constructed. So a valid, but rather useless state machine would like like this: \code \endcode Optionally a state can be assigned a special mode that influences the event distribution. These modes are GRAB_INPUT , PREFER_INPUT and REGULAR (where REGULAR is default and does not need to be indicated). See \ref DispatcherEventDistSection for a description of these modes. Use the special modes only when necessary as they prevent other DataInteractors to receive events. \code \endcode \subsection TransitionSection Transitions Transitions are part of a state and describe all possible state switches, and are therefore important for modelling an interaction scheme. Transitions consist a part that describes the event which triggers the transition (event class and event variant) and a target which is state to which the state machine switches after executing a transition. An event class describes the event type (see mitk::InteractionEvent for the different classes) and the event variant is a specification thereof and the exact description is taken from a config file. Together they determine which event can trigger this transition. For example this state machine will switch from state A to state B when the StdMousePressPrimaryButton event (left mouse button is pressed) occurs. \subsubsection EventClassSection Event Class The event class description supports the polymorphism of the event classes. Therefore state machine patters should be written in the most general ways possible. So for a given class hierarchy like this: \dot digraph { node [shape=record, fontname=Helvetica, fontsize=10]; a [ label="{PositionEvent}"]; b [ label="{MousePressEvent}" ]; c [ label="MouseReleaseEvent" ]; d [ label="TouchEvent", style=dotted ]; a -> b; a -> c; a -> d; } \enddot in the state machine pattern the PositionEvent can be declared as event class to restrict to the events which hold a position information. The actual implementation is then given in the configuration file. In this case it allows to define event of the classes PositionEvent itself, or MousePressEvent,MouseReleaseEvent,TouchEvent. This has the advantage that the patterns remain the same no matter what input devices are used, and the state machine patterns can be configured for newly added event classes as long as they match the class hierachy (this ensures they hold the neccessary properties). \code \endcode \subsection ActionSection Actions Actions can be added to transitions and represent functions in the DataInteractor that are executed on taking a transition. The following simple state machine will listen for left mouse clicks and execute two actions (and actually never stop). \code \endcode In order to tell the DataInteractor which function to execute these actions are made known to the DataInteractor using the CONNECT_FUNCTION macro. This example assumes that there exists an ExampleInteractor which inherits from DataInteractor. This class implements the functions AddPoint and CountClicks. The actions are introduced by implementing the virtual method ConnectActionsAndFunctions(): \code void mitk::ExampleInteractor::ConnectActionsAndFunctions() { CONNECT_FUNCTION("addPoint", AddPoint); CONNECT_FUNCTION("countClicks", CountClicks); } \endcode \section HowToDataInteractor Implementation a new DataInteractor DataInteractors are to inherit from mitk::DataInteractor. Their functionality is implemented in functions that follow this interface: \code bool SomeFunctionality(StateMachineAction* , InteractionEvent*); \endcode Your functions are connected with actions by implementing the function ConnectActionsAndFunctions(), e.g. \code void mitk::ExampleInteractor::ConnectActionsAndFunctions() { CONNECT_FUNCTION("addPoint", AddPoint); CONNECT_FUNCTION("enoughPoints", EnoughPoints); } \endcode Now all that is left it to write a state machine pattern and a config file as is described in the tutorials. \subsection ExampleInternalEvent PointSetDataInteractor To provide a useful example the mitk::PointSetDataInteractor is annotated with comments that describe the important parts for an implementation of a DataInteractor. This step assumes knowlege of the Interaction concept described in \ref DataInteractionPage and some background of the implementation which is described in \ref DataInteractionPageTechnical. Please refer to these pages before proceeding. DataInteractor are to inherit from mitk::DataInteractor. Their functionality is implemented in functions that follow this interface: \code bool SomeFunctionality(StateMachineAction* , InteractionEvent*); \endcode Your functions are connected with actions by implementing the function ConnectActionsAndFunctions(), e.g. \code void mitk::ExampleInteractor::ConnectActionsAndFunctions() { CONNECT_FUNCTION("addPoint", AddPoint); CONNECT_FUNCTION("enoughPoints", EnoughPoints); } \endcode Now all that is left it to write a state machine pattern and a config file as is described in the tutorials. \subsection ExampleInternalEvent Example Interactor using InternalEvent A useful tool in creating DataInteractors are mitk::InternalEvents which allow to the DataInteractor send signals on its own. The following will describe how to build a DataInteractor that allows to add points until a certain number of points is reached. The number of accepted points is provided in the config file as a parameter. So we start by writing a state machine pattern that add points until it receives an InternalEvent telling it, that enough points have been added. \code <--! dead state, nothing happens any more, once we reached this --> \endcode In our config file we set the number of maximal points to 10, and define AddPointClick as a right mouse click with the ctrl button pressed. \code \endcode The implementation is desribed in the following. \see Step10.h \see Step10.cpp \dontinclude Step10.h Implementation of protected functions: \skipline protected: \until virtual void ConfigurationChanged(); ConnectActionsAndFunctions - Is inherited from mitk::InteractionStateMachine, here action strings from the xml are connected with functions in the Interactor (as seen above). In our example this looks like this: \dontinclude Step10.cpp \skipline void mitk::ExampleInteractor::ConnectActionsAndFunctions() \until } ConfigurationChanged - Is called whenever a new configuration file is loaded (by the mitk::InteractionEventHandler super class), this function allows to implement initialization code that depends on configuration values. In our example we want to set the limit of allowed points: \dontinclude Step10.cpp \skipline void mitk::ExampleInteractor::ConfigurationChang \until } Next the actual functionality of the DataInteractor is implemented, by providing one function per action, following this prototype: \code bool FUNCTION_NAME (StateMachineAction* , InteractionEvent*); \endcode \dontinclude Step10.h \skipline private: \until bool EnoughPoints(StateMac Each function has to return a boolean value. True if the action has been executed, and false if the action has not been executed. \dontinclude Step10.cpp \skipline bool mitk::ExampleInteractor::AddPoint(StateM \until //- Here we see an internal event used to signal that the point set reached the maximal number of allowed points. The event is created and added to the Dispatchers event queue. \dontinclude Step10.cpp \skipline // create internal \until positionEvent->GetSender( \note That internal events do not need any mapping to event variants. Their signal same is equivalent with the event variant. There are also two documented classes implementing a DataInteractor and an InteractionEventObserver which can be looked at for further understanding: \see mitk::PointSetDataInteractor \see mitk::DisplayInteractor Have fun with creating your own interaction and please think about contributing it to MITK! If you meet any difficulties during this step, don't hesitate to ask on the MITK mailing list mitk-users@lists.sourceforge.net! People there are kind and will try to help you. \ref Step09Page "[Previous step]" \ref TutorialPage "[Main tutorial page]" -*/ \ No newline at end of file +*/ diff --git a/Examples/QtFreeRender/QtFreeRender.cpp b/Examples/QtFreeRender/QtFreeRender.cpp index 3149c7cbb4..cc3e897051 100644 --- a/Examples/QtFreeRender/QtFreeRender.cpp +++ b/Examples/QtFreeRender/QtFreeRender.cpp @@ -1,373 +1,373 @@ /*=================================================================== 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 "mitkRenderWindow.h" #include #include #include #include #include #include #include #include "mitkProperties.h" #include "mitkGeometry2DDataMapper2D.h" #include "mitkGlobalInteraction.h" #include "mitkDisplayInteractor.h" #include "mitkPositionEvent.h" #include "mitkStateEvent.h" #include "mitkLine.h" #include "mitkInteractionConst.h" #include "mitkVtkLayerController.h" #include "mitkPositionTracker.h" #include "mitkDisplayInteractor.h" #include "mitkSlicesRotator.h" #include "mitkSlicesSwiveller.h" #include "mitkRenderWindowFrame.h" #include "mitkGradientBackground.h" #include "mitkCoordinateSupplier.h" #include "mitkDataStorage.h" #include "vtkTextProperty.h" #include "vtkCornerAnnotation.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkAnnotatedCubeActor.h" #include "vtkOrientationMarkerWidget.h" #include "vtkProperty.h" // us #include "mitkGetModuleContext.h" #include "mitkModule.h" #include "mitkModuleRegistry.h" #include "mitkInteractionEventObserver.h" //##Documentation //## @brief Example of a NON QT DEPENDENT MITK RENDERING APPLICATION. mitk::RenderWindow::Pointer mitkWidget1; mitk::RenderWindow::Pointer mitkWidget2; mitk::RenderWindow::Pointer mitkWidget3; mitk::RenderWindow::Pointer mitkWidget4; mitk::DisplayInteractor::Pointer m_DisplayInteractor; mitk::CoordinateSupplier::Pointer m_LastLeftClickPositionSupplier; mitk::GradientBackground::Pointer m_GradientBackground4; mitk::RenderWindowFrame::Pointer m_RectangleRendering1; mitk::RenderWindowFrame::Pointer m_RectangleRendering2; mitk::RenderWindowFrame::Pointer m_RectangleRendering3; mitk::RenderWindowFrame::Pointer m_RectangleRendering4; mitk::SliceNavigationController* m_TimeNavigationController = NULL; mitk::DataStorage::Pointer m_DataStorage; mitk::DataNode::Pointer m_PlaneNode1; mitk::DataNode::Pointer m_PlaneNode2; mitk::DataNode::Pointer m_PlaneNode3; mitk::DataNode::Pointer m_Node; void InitializeWindows() { // Set default view directions for SNCs mitkWidget1->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Axial); mitkWidget2->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Sagittal); mitkWidget3->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Frontal); mitkWidget4->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Original); //initialize m_TimeNavigationController: send time via sliceNavigationControllers m_TimeNavigationController = mitk::RenderingManager::GetInstance()->GetTimeNavigationController(); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget1->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget2->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget3->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget4->GetSliceNavigationController(), false); mitkWidget1->GetSliceNavigationController()->ConnectGeometrySendEvent(mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); //reverse connection between sliceNavigationControllers and m_TimeNavigationController mitkWidget1->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget2->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget3->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget4->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); // Let NavigationControllers listen to GlobalInteraction mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); gi->AddListener(m_TimeNavigationController); m_LastLeftClickPositionSupplier = mitk::CoordinateSupplier::New("navigation", NULL); mitk::GlobalInteraction::GetInstance()->AddListener(m_LastLeftClickPositionSupplier); m_GradientBackground4 = mitk::GradientBackground::New(); m_GradientBackground4->SetRenderWindow(mitkWidget4->GetVtkRenderWindow()); m_GradientBackground4->SetGradientColors(0.1, 0.1, 0.1, 0.5, 0.5, 0.5); m_GradientBackground4->Enable(); m_RectangleRendering1 = mitk::RenderWindowFrame::New(); m_RectangleRendering1->SetRenderWindow(mitkWidget1->GetVtkRenderWindow()); m_RectangleRendering1->Enable(1.0, 0.0, 0.0); m_RectangleRendering2 = mitk::RenderWindowFrame::New(); m_RectangleRendering2->SetRenderWindow(mitkWidget2->GetVtkRenderWindow()); m_RectangleRendering2->Enable(0.0, 1.0, 0.0); m_RectangleRendering3 = mitk::RenderWindowFrame::New(); m_RectangleRendering3->SetRenderWindow(mitkWidget3->GetVtkRenderWindow()); m_RectangleRendering3->Enable(0.0, 0.0, 1.0); m_RectangleRendering4 = mitk::RenderWindowFrame::New(); m_RectangleRendering4->SetRenderWindow(mitkWidget4->GetVtkRenderWindow()); m_RectangleRendering4->Enable(1.0, 1.0, 0.0); } void AddDisplayPlaneSubTree() { // add the displayed planes of the multiwidget to a node to which the subtree // @a planesSubTree points ... float white[3] = { 1.0f, 1.0f, 1.0f }; mitk::Geometry2DDataMapper2D::Pointer mapper; mitk::IntProperty::Pointer layer = mitk::IntProperty::New(1000); // ... of widget 1 m_PlaneNode1 = (mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow()))->GetCurrentWorldGeometry2DNode(); m_PlaneNode1->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode1->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode1->SetProperty("name", mitk::StringProperty::New("widget1Plane")); m_PlaneNode1->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode1->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode1->SetProperty("layer", layer); m_PlaneNode1->SetColor(1.0, 0.0, 0.0); mapper = mitk::Geometry2DDataMapper2D::New(); m_PlaneNode1->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 2 m_PlaneNode2 = (mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow()))->GetCurrentWorldGeometry2DNode(); m_PlaneNode2->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode2->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode2->SetProperty("name", mitk::StringProperty::New("widget2Plane")); m_PlaneNode2->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode2->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode2->SetProperty("layer", layer); m_PlaneNode2->SetColor(0.0, 1.0, 0.0); mapper = mitk::Geometry2DDataMapper2D::New(); m_PlaneNode2->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 3 m_PlaneNode3 = (mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow()))->GetCurrentWorldGeometry2DNode(); m_PlaneNode3->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode3->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode3->SetProperty("name", mitk::StringProperty::New("widget3Plane")); m_PlaneNode3->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode3->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode3->SetProperty("layer", layer); m_PlaneNode3->SetColor(0.0, 0.0, 1.0); mapper = mitk::Geometry2DDataMapper2D::New(); m_PlaneNode3->SetMapper(mitk::BaseRenderer::Standard2D, mapper); m_Node = mitk::DataNode::New(); m_Node->SetProperty("name", mitk::StringProperty::New("Widgets")); m_Node->SetProperty("helper object", mitk::BoolProperty::New(true)); //AddPlanesToDataStorage if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_Node.IsNotNull()) { if (m_DataStorage.IsNotNull()) { m_DataStorage->Add(m_Node); m_DataStorage->Add(m_PlaneNode1, m_Node); m_DataStorage->Add(m_PlaneNode2, m_Node); m_DataStorage->Add(m_PlaneNode3, m_Node); static_cast(m_PlaneNode1->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); static_cast(m_PlaneNode2->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); static_cast(m_PlaneNode3->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); } } } void Fit() { vtkRenderer * vtkrenderer; mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); int w = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkObject::SetGlobalWarningDisplay(w); } int main(int argc, char* argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s [filename1] [filename2] ...\n\n", ""); return 1; } // Create a DataStorage m_DataStorage = mitk::StandaloneDataStorage::New(); //************************************************************************* // Part II: Create some data by reading files //************************************************************************* int i; for (i = 1; i < argc; ++i) { // For testing if (strcmp(argv[i], "-testing") == 0) continue; // Create a DataNodeFactory to read a data format supported // by the DataNodeFactory (many image formats, surface formats, etc.) mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); const char * filename = argv[i]; try { nodeReader->SetFileName(filename); nodeReader->Update(); // Since the DataNodeFactory directly creates a node, // use the datastorage to add the read node mitk::DataNode::Pointer node = nodeReader->GetOutput(); m_DataStorage->Add(node); mitk::Image::Pointer image = dynamic_cast(node->GetData()); if (image.IsNotNull()) { // Set the property "volumerendering" to the Boolean value "true" node->SetProperty("volumerendering", mitk::BoolProperty::New(false)); node->SetProperty("name", mitk::StringProperty::New("testimage")); node->SetProperty("layer", mitk::IntProperty::New(1)); } } catch (...) { fprintf(stderr, "Could not open file %s \n\n", filename); exit(2); } } //************************************************************************* // Part V: Create window and pass the tree to it //************************************************************************* // Global Interaction initialize // legacy because window manager relies still on existence if global interaction mitk::GlobalInteraction::GetInstance()->Initialize("global"); //mitk::GlobalInteraction::GetInstance()->AddListener(m_DisplayInteractor); // Create renderwindows mitkWidget1 = mitk::RenderWindow::New(); mitkWidget2 = mitk::RenderWindow::New(); mitkWidget3 = mitk::RenderWindow::New(); mitkWidget4 = mitk::RenderWindow::New(); // Tell the renderwindow which (part of) the datastorage to render mitkWidget1->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget2->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget3->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget4->GetRenderer()->SetDataStorage(m_DataStorage); // Let NavigationControllers listen to GlobalInteraction mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); gi->AddListener(mitkWidget1->GetSliceNavigationController()); gi->AddListener(mitkWidget2->GetSliceNavigationController()); gi->AddListener(mitkWidget3->GetSliceNavigationController()); gi->AddListener(mitkWidget4->GetSliceNavigationController()); // instantiate display interactor if (m_DisplayInteractor.IsNull()) { m_DisplayInteractor = mitk::DisplayInteractor::New(); m_DisplayInteractor->LoadStateMachine("DisplayInteraction.xml"); - m_DisplayInteractor->LoadEventConfig("DisplayConfigMITK.xml"); + m_DisplayInteractor->SetEventConfig("DisplayConfigMITK.xml"); // Register as listener via micro services mitk::ModuleContext* context = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); context->RegisterService( m_DisplayInteractor.GetPointer()); } // Use it as a 2D View mitkWidget1->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget2->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget3->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget4->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D); mitkWidget1->SetSize(400, 400); mitkWidget2->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0] + 420, mitkWidget1->GetVtkRenderWindow()->GetPosition()[1]); mitkWidget2->SetSize(400, 400); mitkWidget3->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0], mitkWidget1->GetVtkRenderWindow()->GetPosition()[1] + 450); mitkWidget3->SetSize(400, 400); mitkWidget4->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0] + 420, mitkWidget1->GetVtkRenderWindow()->GetPosition()[1] + 450); mitkWidget4->SetSize(400, 400); InitializeWindows(); AddDisplayPlaneSubTree(); Fit(); // Initialize the RenderWindows mitk::TimeSlicedGeometry::Pointer geo = m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); m_DataStorage->Print(std::cout); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // reinit the mitkVTKEventProvider; // this is only necessary once after calling // ForceImmediateUpdateAll() for the first time mitkWidget1->ReinitEventProvider(); mitkWidget2->ReinitEventProvider(); mitkWidget3->ReinitEventProvider(); mitkWidget1->GetVtkRenderWindow()->Render(); mitkWidget2->GetVtkRenderWindow()->Render(); mitkWidget3->GetVtkRenderWindow()->Render(); mitkWidget4->GetVtkRenderWindow()->Render(); mitkWidget4->GetVtkRenderWindowInteractor()->Start(); return 0; } diff --git a/Modules/CameraCalibration/mitkCameraIntrinsics.cpp b/Modules/CameraCalibration/mitkCameraIntrinsics.cpp index ea4a8491d8..d08e191844 100644 --- a/Modules/CameraCalibration/mitkCameraIntrinsics.cpp +++ b/Modules/CameraCalibration/mitkCameraIntrinsics.cpp @@ -1,503 +1,516 @@ /*=================================================================== 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 "mitkCameraIntrinsics.h" #include #include #include mitk::CameraIntrinsics::CameraIntrinsics() : m_Valid(false), m_Mutex(itk::FastMutexLock::New()) { m_CameraMatrix = cv::Mat::zeros(3, 3, cv::DataType::type); m_CameraMatrix.at(2,2) = 1.0; m_DistorsionCoeffs = cv::Mat::zeros(1, 5, cv::DataType::type); } +mitk::CameraIntrinsics::CameraIntrinsics(const CameraIntrinsics& other) + : itk::Object() + , mitk::XMLSerializable() + , m_Valid(false) + , m_Mutex(itk::FastMutexLock::New()) +{ + this->Copy(&other); +} + mitk::CameraIntrinsics::~CameraIntrinsics() { } bool mitk::CameraIntrinsics::Equals( const CameraIntrinsics* other ) const { return other->GetDistorsionCoeffsAsPoint4D()== this->GetDistorsionCoeffsAsPoint4D() && other->GetFocalPoint()== this->GetFocalPoint() && other->GetPrincipalPoint() == this->GetPrincipalPoint(); } void mitk::CameraIntrinsics::Copy(const CameraIntrinsics* other) { this->SetIntrinsics( other->GetCameraMatrix().clone() , other->GetDistorsionCoeffs().clone() ); this->SetValid(other->m_Valid); } bool mitk::CameraIntrinsics::IsValid() const { itk::MutexLockHolder lock(*m_Mutex); return m_Valid; } -mitk::CameraIntrinsics::Pointer mitk::CameraIntrinsics::Clone() const -{ - mitk::CameraIntrinsics::Pointer copy = mitk::CameraIntrinsics::New(); - copy->SetIntrinsics( this->GetCameraMatrix(), this->GetDistorsionCoeffs() ); - copy->SetValid(this->IsValid()); - return copy; -} - vnl_matrix_fixed mitk::CameraIntrinsics::GetVnlCameraMatrix() const { vnl_matrix_fixed mat; mat.set_identity(); { itk::MutexLockHolder lock(*m_Mutex); mat(0,0) = m_CameraMatrix.at(0,0); mat(1,1) = m_CameraMatrix.at(1,1); mat(0,2) = m_CameraMatrix.at(0,2); mat(1,2) = m_CameraMatrix.at(1,2); } return mat; } void mitk::CameraIntrinsics::SetCameraMatrix( const vnl_matrix_fixed& _CameraMatrix ) { itk::MutexLockHolder lock(*m_Mutex); m_CameraMatrix.at(0,0) = _CameraMatrix(0,0); m_CameraMatrix.at(1,1) = _CameraMatrix(1,1); m_CameraMatrix.at(0,2) = _CameraMatrix(0,2); m_CameraMatrix.at(1,2) = _CameraMatrix(1,2); } vnl_matrix_fixed mitk::CameraIntrinsics::GetVnlCameraMatrix3x4() const { vnl_matrix_fixed mat; mat.fill(0); mat.update( this->GetVnlCameraMatrix().as_matrix() ); return mat; } void mitk::CameraIntrinsics::SetIntrinsics( const cv::Mat& _CameraMatrix , const cv::Mat& _DistorsionCoeffs) { { itk::MutexLockHolder lock(*m_Mutex); if( _CameraMatrix.cols != 3 || _CameraMatrix.rows != 3) throw std::invalid_argument("Wrong format of camera matrix. Should be 3x3" " double."); endoAssertMsg( (_DistorsionCoeffs.cols == 5) && _DistorsionCoeffs.rows == 1, "Wrong format of distorsion coefficients" " vector. Should be 5x1 double."); m_CameraMatrix = _CameraMatrix.clone(); m_DistorsionCoeffs = _DistorsionCoeffs.clone(); m_Valid = true; } this->Modified(); } void mitk::CameraIntrinsics::SetIntrinsics( const mitk::Point3D& focalPoint, const mitk::Point3D& principalPoint, const mitk::Point4D& distortionCoefficients) { { itk::MutexLockHolder lock(*m_Mutex); m_CameraMatrix.at(0,0) = focalPoint[0]; m_CameraMatrix.at(1,1) = focalPoint[1]; m_CameraMatrix.at(0,2) = principalPoint[0]; m_CameraMatrix.at(1,2) = principalPoint[1]; m_DistorsionCoeffs.at(0,0) = distortionCoefficients[0]; m_DistorsionCoeffs.at(0,1) = distortionCoefficients[1]; m_DistorsionCoeffs.at(0,2) = distortionCoefficients[2]; m_DistorsionCoeffs.at(0,3) = distortionCoefficients[3]; } this->Modified(); } void mitk::CameraIntrinsics::SetFocalLength( double x, double y ) { { itk::MutexLockHolder lock(*m_Mutex); m_CameraMatrix.at(0,0) = x; m_CameraMatrix.at(1,1) = y; } this->Modified(); } void mitk::CameraIntrinsics::SetPrincipalPoint( double x, double y ) { { itk::MutexLockHolder lock(*m_Mutex); m_CameraMatrix.at(0,2) = x; m_CameraMatrix.at(1,2) = y; } this->Modified(); } void mitk::CameraIntrinsics::SetDistorsionCoeffs( double k1, double k2, double p1, double p2 ) { { itk::MutexLockHolder lock(*m_Mutex); m_DistorsionCoeffs.at(0,0) = k1; m_DistorsionCoeffs.at(0,1) = k2; m_DistorsionCoeffs.at(0,2) = p1; m_DistorsionCoeffs.at(0,3) = p2; } this->Modified(); } cv::Mat mitk::CameraIntrinsics::GetCameraMatrix() const { itk::MutexLockHolder lock(*m_Mutex); return m_CameraMatrix.clone(); // return a copy of this small matrix } cv::Mat mitk::CameraIntrinsics::GetDistorsionCoeffs() const { itk::MutexLockHolder lock(*m_Mutex); return m_DistorsionCoeffs.clone(); // return a copy of this small matrix } cv::Mat mitk::CameraIntrinsics::GetDistorsionCoeffs() { const CameraIntrinsics* intrinsics = this; return intrinsics->GetDistorsionCoeffs(); } std::string mitk::CameraIntrinsics::ToString() const { itk::MutexLockHolder lock(*m_Mutex); std::ostringstream s; s.precision(12); const cv::Mat& CameraMatrix = m_CameraMatrix; const cv::Mat& DistorsionCoeffs = m_DistorsionCoeffs; s.str(""); s << this->GetNameOfClass() << ": "; s << "fx = " << CameraMatrix.at(0,0); s << ", fy = " << CameraMatrix.at(1,1); s << ", cx = " << CameraMatrix.at(0,2); s << ", cy = " << CameraMatrix.at(1,2); s << ", k1 = " << DistorsionCoeffs.at(0,0); s << ", k2 = " << DistorsionCoeffs.at(0,1); s << ", p1 = " << DistorsionCoeffs.at(0,2); s << ", p2 = " << DistorsionCoeffs.at(0,3); //s << ", k3 = " << DistorsionCoeffs.at(0,4); return s.str(); } void mitk::CameraIntrinsics::ToXML(TiXmlElement* elem) const { itk::MutexLockHolder lock(*m_Mutex); elem->SetValue(this->GetNameOfClass()); std::ostringstream s; s.precision(12); const cv::Mat& CameraMatrix = m_CameraMatrix; s.str(""); s << CameraMatrix.at(0,0); elem->SetAttribute( "fx", s.str() ); s.str(""); s << CameraMatrix.at(1,1); elem->SetAttribute( "fy", s.str() ); s.str(""); s << CameraMatrix.at(0,2); elem->SetAttribute( "cx", s.str() ); s.str(""); s << CameraMatrix.at(1,2); elem->SetAttribute( "cy", s.str() ); const cv::Mat& DistorsionCoeffs = m_DistorsionCoeffs; s.str(""); s << DistorsionCoeffs.at(0,0); elem->SetAttribute( "k1", s.str() ); s.str(""); s << DistorsionCoeffs.at(0,1); elem->SetAttribute( "k2", s.str() ); s.str(""); s << DistorsionCoeffs.at(0,2); elem->SetAttribute( "p1", s.str() ); s.str(""); s << DistorsionCoeffs.at(0,3); elem->SetAttribute( "p2", s.str() ); elem->SetAttribute("Valid", m_Valid); //s.str(""); s << DistorsionCoeffs.at(4,0); //elem->SetAttribute( "k3", s.str() ); } void mitk::CameraIntrinsics::FromGMLCalibrationXML(TiXmlElement* elem) { assert( elem ); assert( elem->ValueStr() == "results" ); cv::Mat CameraMatrix = cv::Mat::zeros(3, 3, cv::DataType::type); CameraMatrix.at(2,2) = 1.0; cv::Mat DistorsionCoeffs = cv::Mat::zeros(1, 5, cv::DataType::type); TiXmlElement* focus_lenXElem = elem->FirstChildElement("focus_lenX"); endoAssert( focus_lenXElem != 0 ); CameraMatrix.at(0,0) = atof( focus_lenXElem->GetText() ); TiXmlElement* focus_lenYElem = elem->FirstChildElement("focus_lenY"); endoAssert( focus_lenYElem != 0 ); CameraMatrix.at(1,1) = atof( focus_lenYElem->GetText() ); TiXmlElement* PrincipalXElem = elem->FirstChildElement("PrincipalX"); endoAssert( PrincipalXElem != 0 ); CameraMatrix.at(0,2) = atof( PrincipalXElem->GetText() ); TiXmlElement* PrincipalYElem = elem->FirstChildElement("PrincipalY"); endoAssert( PrincipalYElem != 0 ); CameraMatrix.at(1,2) = atof( PrincipalYElem->GetText() ); // DISTORSION COEFFS TiXmlElement* Dist1Elem = elem->FirstChildElement("Dist1"); endoAssert( Dist1Elem != 0 ); DistorsionCoeffs.at(0,0) = atof( Dist1Elem->GetText() ); TiXmlElement* Dist2Elem = elem->FirstChildElement("Dist2"); endoAssert( Dist2Elem != 0 ); DistorsionCoeffs.at(0,1) = atof( Dist2Elem->GetText() ); TiXmlElement* Dist3Elem = elem->FirstChildElement("Dist3"); endoAssert( Dist3Elem != 0 ); DistorsionCoeffs.at(0,2) = atof( Dist3Elem->GetText() ); TiXmlElement* Dist4Elem = elem->FirstChildElement("Dist4"); endoAssert( Dist4Elem != 0 ); DistorsionCoeffs.at(0,3) = atof( Dist4Elem->GetText() ); int valid = 0; elem->QueryIntAttribute("Valid", &valid); { itk::MutexLockHolder lock(*m_Mutex); m_Valid = static_cast(valid); m_CameraMatrix = CameraMatrix; m_DistorsionCoeffs = DistorsionCoeffs; } this->Modified(); } void mitk::CameraIntrinsics::FromXML(TiXmlElement* elem) { endoAssert ( elem ); MITK_DEBUG << elem->Value(); std::string filename; if(elem->QueryStringAttribute("file", &filename) == TIXML_SUCCESS) { this->FromXMLFile(filename); return; } else if(strcmp(elem->Value(), "CalibrationProject") == 0) { this->FromGMLCalibrationXML(elem->FirstChildElement("results")); return; } assert ( elem ); if(strcmp(elem->Value(), this->GetNameOfClass()) != 0) elem = elem->FirstChildElement(this->GetNameOfClass()); std::ostringstream err; // CAMERA MATRIX cv::Mat CameraMatrix = cv::Mat::zeros(3, 3, cv::DataType::type); CameraMatrix.at(2,2) = 1.0; float val = 0.0f; if(elem->QueryFloatAttribute("fx", &val) == TIXML_SUCCESS) CameraMatrix.at(0,0) = val; else err << "fx, "; if(elem->QueryFloatAttribute("fy", &val) == TIXML_SUCCESS) CameraMatrix.at(1,1) = val; else err << "fy, "; if(elem->QueryFloatAttribute("cx", &val) == TIXML_SUCCESS) CameraMatrix.at(0,2) = val; else err << "cx, "; if(elem->QueryFloatAttribute("cy", &val) == TIXML_SUCCESS) CameraMatrix.at(1,2) = val; else err << "cy, "; // DISTORSION COEFFS endodebug( "creating DistorsionCoeffs from XML file") cv::Mat DistorsionCoeffs = cv::Mat::zeros(1, 5, cv::DataType::type); if(elem->QueryFloatAttribute("k1", &val) == TIXML_SUCCESS) DistorsionCoeffs.at(0,0) = val; else err << "k1, "; if(elem->QueryFloatAttribute("k2", &val) == TIXML_SUCCESS) DistorsionCoeffs.at(0,1) = val; else err << "k2, "; if(elem->QueryFloatAttribute("p1", &val) == TIXML_SUCCESS) DistorsionCoeffs.at(0,2) = val; else err << "p1, "; if(elem->QueryFloatAttribute("p2", &val) == TIXML_SUCCESS) DistorsionCoeffs.at(0,3) = val; else err << "p2, "; DistorsionCoeffs.at(0,4) = 0.0; /*if(elem->QueryFloatAttribute("k3", &val) == TIXML_SUCCESS) DistorsionCoeffs.at(4,0) = val; else err << "k3, ";*/ std::string errorStr = err.str(); int errLength = errorStr.length(); if(errLength > 0) { errorStr = errorStr.substr(0, errLength-2); errorStr.append(" not found"); throw std::invalid_argument(err.str()); } int valid = 0; elem->QueryIntAttribute("Valid", &valid); { itk::MutexLockHolder lock(*m_Mutex); m_Valid = static_cast(valid); m_CameraMatrix = CameraMatrix; m_DistorsionCoeffs = DistorsionCoeffs; } this->Modified(); } double mitk::CameraIntrinsics::GetFocalLengthX() const { itk::MutexLockHolder lock(*m_Mutex); double FocalLengthX = m_CameraMatrix.at(0,0); return FocalLengthX; } double mitk::CameraIntrinsics::GetFocalLengthY() const { itk::MutexLockHolder lock(*m_Mutex); double FocalLengthY = m_CameraMatrix.at(1,1);; return FocalLengthY; } double mitk::CameraIntrinsics::GetPrincipalPointX() const { itk::MutexLockHolder lock(*m_Mutex); double PrincipalPointX = m_CameraMatrix.at(0,2); return PrincipalPointX; } double mitk::CameraIntrinsics::GetPrincipalPointY() const { itk::MutexLockHolder lock(*m_Mutex); double PrincipalPointY = m_CameraMatrix.at(1,2); return PrincipalPointY; } mitk::Point4D mitk::CameraIntrinsics::GetDistorsionCoeffsAsPoint4D() const { itk::MutexLockHolder lock(*m_Mutex); mitk::Point4D coeffs; coeffs[0] = m_DistorsionCoeffs.at(0,0); coeffs[1] = m_DistorsionCoeffs.at(0,1); coeffs[2] = m_DistorsionCoeffs.at(0,2); coeffs[3] = m_DistorsionCoeffs.at(0,3); return coeffs; } mitk::Point3D mitk::CameraIntrinsics::GetFocalPoint() const { mitk::Point3D p; p[0] = this->GetFocalLengthX(); p[1] = this->GetFocalLengthY(); p[2] = 0; return p; } mitk::Point3D mitk::CameraIntrinsics::GetPrincipalPoint() const { mitk::Point3D p; p[0] = this->GetPrincipalPointX(); p[1] = this->GetPrincipalPointY(); p[2] = 0; return p; } vnl_vector_fixed mitk::CameraIntrinsics::GetFocalPointAsVnlVector() const { vnl_vector_fixed vec; vec[0] = this->GetFocalLengthX(); vec[1] = this->GetFocalLengthY(); return vec; } vnl_vector_fixed mitk::CameraIntrinsics::GetPrincipalPointAsVnlVector() const { vnl_vector_fixed vec; vec[0] = this->GetPrincipalPointX(); vec[1] = this->GetPrincipalPointY(); return vec; } std::ostream& operator<< (std::ostream& os, mitk::CameraIntrinsics::Pointer p) { os << p->ToString(); return os; } std::string mitk::CameraIntrinsics::GetString() { return this->ToString(); } std::string mitk::CameraIntrinsics::ToOctaveString( const std::string& varName) { std::ostringstream s; s << varName << " = [" << this->GetFocalLengthX() << " 0 " << this->GetPrincipalPointX() << "; 0 " << this->GetFocalLengthY() << " " << this->GetPrincipalPointY() << ";" << " 0 0 1 ];"; return s.str(); } void mitk::CameraIntrinsics::SetValid( bool valid ) { itk::MutexLockHolder lock(*m_Mutex); m_Valid = valid; } + +mitk::CameraIntrinsics::Pointer mitk::CameraIntrinsics::Clone() const +{ + Pointer result = dynamic_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::CameraIntrinsics::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Modules/CameraCalibration/mitkCameraIntrinsics.h b/Modules/CameraCalibration/mitkCameraIntrinsics.h index 83b59b442d..4c6e3acc5a 100644 --- a/Modules/CameraCalibration/mitkCameraIntrinsics.h +++ b/Modules/CameraCalibration/mitkCameraIntrinsics.h @@ -1,138 +1,144 @@ /*=================================================================== 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 mitkCameraIntrinsics_h #define mitkCameraIntrinsics_h #include #include #include #include #include #include #include "mitkXMLSerializable.h" #include int mitkCameraIntrinsicsTest(int argc, char* argv[]); namespace mitk { /// /// \brief class representing camera intrinsics and related functions /// class mitkCameraCalibration_EXPORT CameraIntrinsics: virtual public itk::Object, virtual public mitk::XMLSerializable { public: /// /// for testing purposes /// friend int mitkCameraIntrinsicsTest(int argc, char* argv[]); /// /// smartpointer typedefs /// mitkClassMacro(CameraIntrinsics, itk::Object); /// /// the static new function /// itkFactorylessNewMacro(Self); /// /// make a clone of this intrinsics /// Pointer Clone() const; /// /// copy information from other to this /// void Copy(const CameraIntrinsics* other); /// /// checks two intrinsics for equality /// bool Equals( const CameraIntrinsics* other ) const; /// /// \return the intrinsic parameter matrix as a 3x3 vnl matrix /// vnl_matrix_fixed GetVnlCameraMatrix() const; /// /// \return the intrinsic parameter matrix as a 3x4 vnl matrix /// (the last column only containing zeros) /// vnl_matrix_fixed GetVnlCameraMatrix3x4() const; /// /// \return true if the intrinsics are set (some plausibility checks /// may be done here) /// bool IsValid() const; void SetValid(bool valid); cv::Mat GetCameraMatrix() const; cv::Mat GetDistorsionCoeffs(); cv::Mat GetDistorsionCoeffs() const; void ToXML(TiXmlElement* elem) const; std::string ToString() const; std::string GetString(); double GetFocalLengthX() const; double GetFocalLengthY() const; double GetPrincipalPointX() const; double GetPrincipalPointY() const; mitk::Point4D GetDistorsionCoeffsAsPoint4D() const; mitk::Point3D GetFocalPoint() const; mitk::Point3D GetPrincipalPoint() const; vnl_vector_fixed GetFocalPointAsVnlVector() const; vnl_vector_fixed GetPrincipalPointAsVnlVector() const; /// /// set a new camera matrix utilizing a vnl matrix /// void SetCameraMatrix( const vnl_matrix_fixed& _CameraMatrix ); void SetIntrinsics( const cv::Mat& _CameraMatrix , const cv::Mat& _DistorsionCoeffs); void SetFocalLength( double x, double y ); void SetPrincipalPoint( double x, double y ); void SetDistorsionCoeffs( double k1, double k2, double p1, double p2 ); void SetIntrinsics( const mitk::Point3D& focalPoint, const mitk::Point3D& principalPoint, const mitk::Point4D& distortionCoefficients); void FromXML(TiXmlElement* elem); void FromGMLCalibrationXML(TiXmlElement* elem); std::string ToOctaveString(const std::string& varName="CameraIntrinsics"); virtual ~CameraIntrinsics(); protected: CameraIntrinsics(); + CameraIntrinsics(const CameraIntrinsics& other); + cv::Mat m_CameraMatrix; cv::Mat m_DistorsionCoeffs; bool m_Valid; itk::FastMutexLock::Pointer m_Mutex; + + private: + + virtual itk::LightObject::Pointer InternalClone() const; }; } // namespace mitk mitkCameraCalibration_EXPORT std::ostream& operator<< (std::ostream& os, mitk::CameraIntrinsics::Pointer p); #endif // mitkCameraIntrinsics_h diff --git a/Modules/CameraCalibration/mitkCameraIntrinsicsProperty.cpp b/Modules/CameraCalibration/mitkCameraIntrinsicsProperty.cpp index 262ec809c2..fb9aefcd13 100644 --- a/Modules/CameraCalibration/mitkCameraIntrinsicsProperty.cpp +++ b/Modules/CameraCalibration/mitkCameraIntrinsicsProperty.cpp @@ -1,50 +1,68 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCameraIntrinsicsProperty.h" namespace mitk { bool CameraIntrinsicsProperty::IsEqual(const BaseProperty& property) const { return this->m_Value->Equals(static_cast(property).m_Value.GetPointer()); } bool CameraIntrinsicsProperty::Assign(const BaseProperty& property) { this->m_Value = static_cast(property).m_Value; return true; } std::string CameraIntrinsicsProperty::GetValueAsString() const { std::stringstream myStr; myStr << GetValue(); return myStr.str(); } CameraIntrinsicsProperty::CameraIntrinsicsProperty() : BaseProperty() {} +CameraIntrinsicsProperty::CameraIntrinsicsProperty(const CameraIntrinsicsProperty& other) + : BaseProperty(other) +{ + +} + CameraIntrinsicsProperty::CameraIntrinsicsProperty( mitk::CameraIntrinsics::Pointer value ) : BaseProperty(), m_Value( value ) {} +CameraIntrinsicsProperty::Pointer CameraIntrinsicsProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer CameraIntrinsicsProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} + } // namespace mitk diff --git a/Modules/CameraCalibration/mitkCameraIntrinsicsProperty.h b/Modules/CameraCalibration/mitkCameraIntrinsicsProperty.h index ed795bd194..44baecdb4f 100644 --- a/Modules/CameraCalibration/mitkCameraIntrinsicsProperty.h +++ b/Modules/CameraCalibration/mitkCameraIntrinsicsProperty.h @@ -1,72 +1,77 @@ /*=================================================================== 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 MITKCAMERAINTRINSICSPROPERTY_H #define MITKCAMERAINTRINSICSPROPERTY_H #include "mitkBaseProperty.h" #include "mitkCameraIntrinsics.h" namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif class mitkCameraCalibration_EXPORT CameraIntrinsicsProperty : public BaseProperty { public: typedef mitk::CameraIntrinsics::Pointer ValueType; mitkClassMacro(CameraIntrinsicsProperty, BaseProperty); itkNewMacro(CameraIntrinsicsProperty); mitkNewMacro1Param(CameraIntrinsicsProperty, mitk::CameraIntrinsics::Pointer); + Pointer Clone() const; + itkSetMacro(Value, mitk::CameraIntrinsics::Pointer ); itkGetConstMacro(Value, mitk::CameraIntrinsics::Pointer ); std::string GetValueAsString() const; using BaseProperty::operator=; protected: mitk::CameraIntrinsics::Pointer m_Value; CameraIntrinsicsProperty(); + CameraIntrinsicsProperty(const CameraIntrinsicsProperty&); + CameraIntrinsicsProperty( mitk::CameraIntrinsics::Pointer value ); private: // purposely not implemented - CameraIntrinsicsProperty(const CameraIntrinsicsProperty&); CameraIntrinsicsProperty& operator=(const CameraIntrinsicsProperty&); + virtual itk::LightObject::Pointer InternalClone() const; + virtual bool IsEqual(const BaseProperty& property) const; virtual bool Assign(const BaseProperty& property); }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace mitk #endif // MITKCAMERAINTRINSICSPROPERTY_H diff --git a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkMergeDiffusionImagesFilter.txx b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkMergeDiffusionImagesFilter.txx index 0826cefd35..a67828ea84 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkMergeDiffusionImagesFilter.txx +++ b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkMergeDiffusionImagesFilter.txx @@ -1,175 +1,176 @@ /*=================================================================== 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. ===================================================================*/ /*========================================================================= 2 3 Program: Tensor ToolKit - TTK 4 Module: $URL: svn://scm.gforge.inria.fr/svn/ttk/trunk/Algorithms/itkMergeDiffusionImagesFilter.txx $ 5 Language: C++ 6 Date: $Date: 2010-06-07 13:39:13 +0200 (Mo, 07 Jun 2010) $ 7 Version: $Revision: 68 $ 8 9 Copyright (c) INRIA 2010. All rights reserved. 10 See LICENSE.txt for details. 11 12 This software is distributed WITHOUT ANY WARRANTY; without even 13 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 14 PURPOSE. See the above copyright notices for more information. 15 16 =========================================================================*/ #ifndef _itk_MergeDiffusionImagesFilter_txx_ #define _itk_MergeDiffusionImagesFilter_txx_ #endif #include "itkMergeDiffusionImagesFilter.h" #include "itkTensorToL2NormImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include #include #include namespace itk { template MergeDiffusionImagesFilter::MergeDiffusionImagesFilter() { } template MergeDiffusionImagesFilter::~MergeDiffusionImagesFilter() { } template void MergeDiffusionImagesFilter ::SetImageVolumes(DwiImageContainerType cont) { m_ImageVolumes=cont; } template void MergeDiffusionImagesFilter ::SetGradientLists(GradientListContainerType cont) { m_GradientLists=cont; } template void MergeDiffusionImagesFilter ::SetBValues(std::vector< double > bvals) { m_BValues=bvals; } template MergeDiffusionImagesFilter::GradientListType::Pointer MergeDiffusionImagesFilter ::GetOutputGradients() { return m_OutputGradients; } template double MergeDiffusionImagesFilter ::GetB_Value() { return m_BValue; } template void MergeDiffusionImagesFilter ::GenerateData () { if( m_ImageVolumes.size()<2 ) throw itk::ExceptionObject (__FILE__,__LINE__,"Error: cannot combine less than two DWIs."); if( m_GradientLists.size()!=m_ImageVolumes.size() || m_ImageVolumes.size()!=m_BValues.size() || m_BValues.size()!=m_GradientLists.size() ) throw itk::ExceptionObject (__FILE__,__LINE__,"Error: need same number of b-values, image volumes and gradient containers."); typename DwiImageType::Pointer img = m_ImageVolumes.at(0); m_NumGradients = 0; for (int i=0; iSize(); typename DwiImageType::Pointer tmp = m_ImageVolumes.at(i); if ( img->GetLargestPossibleRegion()!=tmp->GetLargestPossibleRegion() ) throw itk::ExceptionObject (__FILE__,__LINE__,"Error: images are not of same size."); } m_BValue = m_BValues.at(0); m_OutputGradients = GradientListType::New(); typename DwiImageType::Pointer outImage = DwiImageType::New(); outImage->SetSpacing( img->GetSpacing() ); // Set the image spacing outImage->SetOrigin( img->GetOrigin() ); // Set the image origin outImage->SetDirection( img->GetDirection() ); // Set the image direction outImage->SetLargestPossibleRegion( img->GetLargestPossibleRegion()); outImage->SetBufferedRegion( img->GetLargestPossibleRegion() ); outImage->SetRequestedRegion( img->GetLargestPossibleRegion() ); outImage->SetVectorLength(m_NumGradients); outImage->Allocate(); this->SetNumberOfRequiredOutputs(1); this->SetNthOutput (0, outImage); typedef ImageRegionIterator IteratorOutputType; IteratorOutputType itOut (this->GetOutput(0), this->GetOutput(0)->GetLargestPossibleRegion()); MITK_INFO << "MergeDiffusionImagesFilter: merging images"; GradientType zeroG; zeroG.fill(0.0); boost::progress_display disp(this->GetOutput(0)->GetLargestPossibleRegion().GetNumberOfPixels()); while(!itOut.IsAtEnd()) { ++disp; DwiPixelType out; out.SetSize(m_NumGradients); out.Fill(0); int c=0; for (int i=0; iSize(); j++) { GradientType g = gradients->GetElement(j); + double mag = g.two_norm(); - if (g.magnitude()>0.0001) + if (mag>0.0001) { + double frac = m_BValues.at(i)*mag*mag/m_BValue; g.normalize(); - g *= std::sqrt(bValue/m_BValue); + g *= sqrt(frac); } else g = zeroG; m_OutputGradients->InsertElement(c, g); out[c] = static_cast(img->GetPixel(itOut.GetIndex())[j]); c++; } } itOut.Set(out); ++itOut; } } } // end of namespace diff --git a/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkDiffusionSignalModel.h b/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkDiffusionSignalModel.h index e07c2c861f..f11b07d7c8 100644 --- a/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkDiffusionSignalModel.h +++ b/Modules/DiffusionImaging/FiberTracking/SignalModels/mitkDiffusionSignalModel.h @@ -1,89 +1,90 @@ /*=================================================================== 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_DiffusionSignalModel_H #define _MITK_DiffusionSignalModel_H #include #include #include #include namespace mitk { /** * \brief Abstract class for diffusion signal models * */ template< class ScalarType > class DiffusionSignalModel { public: DiffusionSignalModel() : m_T2(100) , m_Weight(1) {} ~DiffusionSignalModel(){} typedef itk::VariableLengthVector< ScalarType > PixelType; typedef itk::Vector GradientType; typedef std::vector GradientListType; /** Realizes actual signal generation. Has to be implemented in subclass. **/ virtual PixelType SimulateMeasurement() = 0; void SetFiberDirection(GradientType fiberDirection){ m_FiberDirection = fiberDirection; } void SetGradientList(GradientListType gradientList) { m_GradientList = gradientList; } void SetT2(double T2) { m_T2 = T2; } void SetWeight(double Weight) { m_Weight = Weight; } double GetWeight() { return m_Weight; } double GetT2() { return m_T2; } int GetNumGradients(){ return m_GradientList.size(); } std::vector< int > GetBaselineIndices() { std::vector< int > result; for( unsigned int i=0; im_GradientList.size(); i++) if (m_GradientList.at(i).GetNorm()<0.0001) result.push_back(i); return result; } int GetFirstBaselineIndex() { for( unsigned int i=0; im_GradientList.size(); i++) if (m_GradientList.at(i).GetNorm()<0.0001) return i; return -1; } bool IsBaselineIndex(int idx) { if (m_GradientList.size()>idx && m_GradientList.at(idx).GetNorm()<0.0001) return true; + return false; } protected: GradientType m_FiberDirection; ///< Needed to generate anisotropc signal to determin direction of anisotropy GradientListType m_GradientList; ///< Diffusion gradient direction container double m_T2; ///< Tissue specific relaxation time double m_Weight; }; } #endif diff --git a/Modules/MitkExt/Controllers/mitkToolManager.cpp b/Modules/MitkExt/Controllers/mitkToolManager.cpp index 02ba2ad59b..351c284264 100644 --- a/Modules/MitkExt/Controllers/mitkToolManager.cpp +++ b/Modules/MitkExt/Controllers/mitkToolManager.cpp @@ -1,576 +1,573 @@ /*=================================================================== 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 "mitkToolManager.h" #include "mitkGlobalInteraction.h" #include "mitkCoreObjectFactory.h" #include #include #include #include "mitkInteractionEventObserver.h" #include "mitkDisplayInteractor.h" // MicroServices #include "mitkGetModuleContext.h" #include "mitkModule.h" #include "mitkModuleRegistry.h" mitk::ToolManager::ToolManager(DataStorage* storage) :m_ActiveTool(NULL), m_ActiveToolID(-1), m_RegisteredClients(0), m_DataStorage(storage) { CoreObjectFactory::GetInstance(); // to make sure a CoreObjectFactory was instantiated (and in turn, possible tools are registered) - bug 1029 // get a list of all known mitk::Tools std::list thingsThatClaimToBeATool = itk::ObjectFactoryBase::CreateAllInstance("mitkTool"); // remember these tools for ( std::list::iterator iter = thingsThatClaimToBeATool.begin(); iter != thingsThatClaimToBeATool.end(); ++iter ) { if ( Tool* tool = dynamic_cast( iter->GetPointer() ) ) { tool->SetToolManager(this); // important to call right after instantiation tool->ErrorMessage += MessageDelegate1( this, &ToolManager::OnToolErrorMessage ); tool->GeneralMessage += MessageDelegate1( this, &ToolManager::OnGeneralToolMessage ); m_Tools.push_back( tool ); } } //ActivateTool(0); // first one is default } mitk::ToolManager::~ToolManager() { for (DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter) (*dataIter)->RemoveObserver(m_WorkingDataObserverTags[(*dataIter)]); if(this->GetDataStorage() != NULL) this->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &ToolManager::OnNodeRemoved )); if (m_ActiveTool) { m_ActiveTool->Deactivated(); GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool ); m_ActiveTool = NULL; m_ActiveToolID = -1; // no tool active ActiveToolChanged.Send(); } for ( NodeTagMapType::iterator observerTagMapIter = m_ReferenceDataObserverTags.begin(); observerTagMapIter != m_ReferenceDataObserverTags.end(); ++observerTagMapIter ) { observerTagMapIter->first->RemoveObserver( observerTagMapIter->second ); } } void mitk::ToolManager::OnToolErrorMessage(std::string s) { this->ToolErrorMessage(s); } void mitk::ToolManager::OnGeneralToolMessage(std::string s) { this->GeneralToolMessage(s); } const mitk::ToolManager::ToolVectorTypeConst mitk::ToolManager::GetTools() { ToolVectorTypeConst resultList; for ( ToolVectorType::iterator iter = m_Tools.begin(); iter != m_Tools.end(); ++iter ) { resultList.push_back( iter->GetPointer() ); } return resultList; } mitk::Tool* mitk::ToolManager::GetToolById(int id) { try { return m_Tools.at(id); } catch(std::exception&) { return NULL; } } bool mitk::ToolManager::ActivateTool(int id) { if(this->GetDataStorage()) { this->GetDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &ToolManager::OnNodeRemoved ) ); } //MITK_INFO << "ToolManager::ActivateTool("<SetEventNotificationPolicy(GlobalInteraction::INFORM_MULTIPLE); + // Re-enabling InteractionEventObservers that have been previously disabled for legacy handling of Tools // in new interaction framework - std::list listEventObserver; - ServiceTracker* eventObserverTracker= new ServiceTracker(GetModuleContext()); - eventObserverTracker->Open(); - eventObserverTracker->GetServiceReferences(listEventObserver); // query all registered interaction event observer - for (std::list::iterator it = listEventObserver.begin(); it != listEventObserver.end(); ++it) + for (std::map::iterator it = m_DisplayInteractorConfigs.begin(); + it != m_DisplayInteractorConfigs.end(); ++it) { - InteractionEventObserver* interactionEventObserver = eventObserverTracker->GetService(*it); - if (interactionEventObserver != NULL) { - DisplayInteractor* displayInteractor = dynamic_cast(interactionEventObserver); - if (displayInteractor != NULL) { + if (it->first) + { + DisplayInteractor* displayInteractor = static_cast( + GetModuleContext()->GetService(it->first)); + if (displayInteractor != NULL) + { // here the regular configuration is loaded again - displayInteractor->LoadEventConfig("DisplayConfigMITK.xml","Mitk"); + displayInteractor->SetEventConfig(it->second); } } } - eventObserverTracker->Close(); - delete eventObserverTracker; + m_DisplayInteractorConfigs.clear(); } if ( GetToolById( id ) == m_ActiveTool ) return true; // no change needed static int nextTool = -1; nextTool = id; //MITK_INFO << "ToolManager::ActivateTool("<Deactivated(); GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool ); } m_ActiveTool = GetToolById( nextTool ); m_ActiveToolID = m_ActiveTool ? nextTool : -1; // current ID if tool is valid, otherwise -1 ActiveToolChanged.Send(); if (m_ActiveTool) { if (m_RegisteredClients > 0) { m_ActiveTool->Activated(); GlobalInteraction::GetInstance()->AddListener( m_ActiveTool ); //If a tool is activated set event notification policy to one GlobalInteraction::GetInstance()->SetEventNotificationPolicy(GlobalInteraction::INFORM_ONE); + // As a legacy solution the display interaction of the new interaction framework is disabled here to avoid conflicts with tools // Note: this only affects InteractionEventObservers (formerly known as Listeners) all DataNode specific interaction will still be enabled - std::list listEventObserver; - ServiceTracker* eventObserverTracker= new ServiceTracker(GetModuleContext()); - eventObserverTracker->Open(); - eventObserverTracker->GetServiceReferences(listEventObserver); + m_DisplayInteractorConfigs.clear(); + std::list listEventObserver = GetModuleContext()->GetServiceReferences(); for (std::list::iterator it = listEventObserver.begin(); it != listEventObserver.end(); ++it) { - InteractionEventObserver* interactionEventObserver = eventObserverTracker->GetService(*it); - if (interactionEventObserver != NULL) { - DisplayInteractor* displayInteractor = dynamic_cast(interactionEventObserver); - if (displayInteractor != NULL) { - // here the regular configuration is loaded again - displayInteractor->LoadEventConfig("Legacy/DisplayConfigMITKTools.xml","Mitk"); - } + DisplayInteractor* displayInteractor = dynamic_cast( + GetModuleContext()->GetService(*it)); + if (displayInteractor != NULL) + { + // remember the original configuration + m_DisplayInteractorConfigs.insert(std::make_pair(*it, displayInteractor->GetEventConfig())); + // here the alternative configuration is loaded + displayInteractor->SetEventConfig("Legacy/DisplayConfigMITKTools.xml"); } } - eventObserverTracker->Close(); - delete eventObserverTracker; } } } inActivateTool = false; return (m_ActiveTool != NULL); } void mitk::ToolManager::SetReferenceData(DataVectorType data) { if (data != m_ReferenceData) { // remove observers from old nodes for ( DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter ) { NodeTagMapType::iterator searchIter = m_ReferenceDataObserverTags.find( *dataIter ); if ( searchIter != m_ReferenceDataObserverTags.end() ) { //MITK_INFO << "Stopping observation of " << (void*)(*dataIter) << std::endl; (*dataIter)->RemoveObserver( searchIter->second ); } } m_ReferenceData = data; // TODO tell active tool? // attach new observers m_ReferenceDataObserverTags.clear(); for ( DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter ) { //MITK_INFO << "Observing " << (void*)(*dataIter) << std::endl; itk::MemberCommand::Pointer command = itk::MemberCommand::New(); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheReferenceDataDeleted ); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheReferenceDataDeletedConst ); m_ReferenceDataObserverTags.insert( std::pair( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) ); } ReferenceDataChanged.Send(); } } void mitk::ToolManager::OnOneOfTheReferenceDataDeletedConst(const itk::Object* caller, const itk::EventObject& e) { OnOneOfTheReferenceDataDeleted( const_cast(caller), e ); } void mitk::ToolManager::OnOneOfTheReferenceDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e)) { //MITK_INFO << "Deleted: " << (void*)caller << " Removing from reference data list." << std::endl; DataVectorType v; for (DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter ) { //MITK_INFO << " In list: " << (void*)(*dataIter); if ( (void*)(*dataIter) != (void*)caller ) { v.push_back( *dataIter ); //MITK_INFO << " kept" << std::endl; } else { //MITK_INFO << " removed" << std::endl; m_ReferenceDataObserverTags.erase( *dataIter ); // no tag to remove anymore } } this->SetReferenceData( v ); } void mitk::ToolManager::SetReferenceData(DataNode* data) { //MITK_INFO << "ToolManager::SetReferenceData(" << (void*)data << ")" << std::endl; DataVectorType v; if (data) { v.push_back(data); } SetReferenceData(v); } void mitk::ToolManager::SetWorkingData(DataVectorType data) { if ( data != m_WorkingData ) { // remove observers from old nodes for ( DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter ) { NodeTagMapType::iterator searchIter = m_WorkingDataObserverTags.find( *dataIter ); if ( searchIter != m_WorkingDataObserverTags.end() ) { //MITK_INFO << "Stopping observation of " << (void*)(*dataIter) << std::endl; (*dataIter)->RemoveObserver( searchIter->second ); } } m_WorkingData = data; // TODO tell active tool? // attach new observers m_WorkingDataObserverTags.clear(); for ( DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter ) { //MITK_INFO << "Observing " << (void*)(*dataIter) << std::endl; itk::MemberCommand::Pointer command = itk::MemberCommand::New(); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheWorkingDataDeleted ); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheWorkingDataDeletedConst ); m_WorkingDataObserverTags.insert( std::pair( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) ); } WorkingDataChanged.Send(); } } void mitk::ToolManager::OnOneOfTheWorkingDataDeletedConst(const itk::Object* caller, const itk::EventObject& e) { OnOneOfTheWorkingDataDeleted( const_cast(caller), e ); } void mitk::ToolManager::OnOneOfTheWorkingDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e)) { //MITK_INFO << "Deleted: " << (void*)caller << " Removing from reference data list." << std::endl; DataVectorType v; for (DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter ) { //MITK_INFO << " In list: " << (void*)(*dataIter); if ( (void*)(*dataIter) != (void*)caller ) { v.push_back( *dataIter ); //MITK_INFO << " kept" << std::endl; } else { //MITK_INFO << " removed" << std::endl; m_WorkingDataObserverTags.erase( *dataIter ); // no tag to remove anymore } } this->SetWorkingData( v ); } void mitk::ToolManager::SetWorkingData(DataNode* data) { DataVectorType v; if (data) // don't allow for NULL nodes { v.push_back(data); } SetWorkingData(v); } void mitk::ToolManager::SetRoiData(DataVectorType data) { if (data != m_RoiData) { // remove observers from old nodes for ( DataVectorType::iterator dataIter = m_RoiData.begin(); dataIter != m_RoiData.end(); ++dataIter ) { NodeTagMapType::iterator searchIter = m_RoiDataObserverTags.find( *dataIter ); if ( searchIter != m_RoiDataObserverTags.end() ) { //MITK_INFO << "Stopping observation of " << (void*)(*dataIter) << std::endl; (*dataIter)->RemoveObserver( searchIter->second ); } } m_RoiData = data; // TODO tell active tool? // attach new observers m_RoiDataObserverTags.clear(); for ( DataVectorType::iterator dataIter = m_RoiData.begin(); dataIter != m_RoiData.end(); ++dataIter ) { //MITK_INFO << "Observing " << (void*)(*dataIter) << std::endl; itk::MemberCommand::Pointer command = itk::MemberCommand::New(); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheRoiDataDeleted ); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheRoiDataDeletedConst ); m_RoiDataObserverTags.insert( std::pair( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) ); } RoiDataChanged.Send(); } } void mitk::ToolManager::SetRoiData(DataNode* data) { DataVectorType v; if(data) { v.push_back(data); } this->SetRoiData(v); } void mitk::ToolManager::OnOneOfTheRoiDataDeletedConst(const itk::Object* caller, const itk::EventObject& e) { OnOneOfTheRoiDataDeleted( const_cast(caller), e ); } void mitk::ToolManager::OnOneOfTheRoiDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e)) { //MITK_INFO << "Deleted: " << (void*)caller << " Removing from roi data list." << std::endl; DataVectorType v; for (DataVectorType::iterator dataIter = m_RoiData.begin(); dataIter != m_RoiData.end(); ++dataIter ) { //MITK_INFO << " In list: " << (void*)(*dataIter); if ( (void*)(*dataIter) != (void*)caller ) { v.push_back( *dataIter ); //MITK_INFO << " kept" << std::endl; } else { //MITK_INFO << " removed" << std::endl; m_RoiDataObserverTags.erase( *dataIter ); // no tag to remove anymore } } this->SetRoiData( v ); } mitk::ToolManager::DataVectorType mitk::ToolManager::GetReferenceData() { return m_ReferenceData; } mitk::DataNode* mitk::ToolManager::GetReferenceData(int idx) { try { return m_ReferenceData.at(idx); } catch(std::exception&) { return NULL; } } mitk::ToolManager::DataVectorType mitk::ToolManager::GetWorkingData() { return m_WorkingData; } mitk::ToolManager::DataVectorType mitk::ToolManager::GetRoiData() { return m_RoiData; } mitk::DataNode* mitk::ToolManager::GetRoiData(int idx) { try { return m_RoiData.at(idx); } catch(std::exception&) { return NULL; } } mitk::DataStorage* mitk::ToolManager::GetDataStorage() { if ( m_DataStorage.IsNotNull() ) { return m_DataStorage; } else { return NULL; } } void mitk::ToolManager::SetDataStorage(DataStorage& storage) { m_DataStorage = &storage; } mitk::DataNode* mitk::ToolManager::GetWorkingData(int idx) { try { return m_WorkingData.at(idx); } catch(std::exception&) { return NULL; } } int mitk::ToolManager::GetActiveToolID() { return m_ActiveToolID; } mitk::Tool* mitk::ToolManager::GetActiveTool() { return m_ActiveTool; } void mitk::ToolManager::RegisterClient() { if ( m_RegisteredClients < 1 ) { if ( m_ActiveTool ) { m_ActiveTool->Activated(); GlobalInteraction::GetInstance()->AddListener( m_ActiveTool ); } } ++m_RegisteredClients; } void mitk::ToolManager::UnregisterClient() { if ( m_RegisteredClients < 1) return; --m_RegisteredClients; if ( m_RegisteredClients < 1 ) { if ( m_ActiveTool ) { m_ActiveTool->Deactivated(); GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool ); } } } int mitk::ToolManager::GetToolID( const Tool* tool ) { int id(0); for ( ToolVectorType::iterator iter = m_Tools.begin(); iter != m_Tools.end(); ++iter, ++id ) { if ( tool == iter->GetPointer() ) { return id; } } return -1; } void mitk::ToolManager::OnNodeRemoved(const mitk::DataNode* node) { //check if the data of the node is typeof Image /*if(dynamic_cast(node->GetData())) {*/ //check all storage vectors OnOneOfTheReferenceDataDeleted(const_cast(node), itk::DeleteEvent()); OnOneOfTheRoiDataDeleted(const_cast(node),itk::DeleteEvent()); OnOneOfTheWorkingDataDeleted(const_cast(node),itk::DeleteEvent()); //} } diff --git a/Modules/MitkExt/Controllers/mitkToolManager.h b/Modules/MitkExt/Controllers/mitkToolManager.h index c6786ff719..a8ee554b74 100644 --- a/Modules/MitkExt/Controllers/mitkToolManager.h +++ b/Modules/MitkExt/Controllers/mitkToolManager.h @@ -1,290 +1,295 @@ /*=================================================================== 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 mitkToolManager_h_Included #define mitkToolManager_h_Included #include "mitkTool.h" #include "MitkExtExports.h" #include "mitkDataNode.h" #include "mitkDataStorage.h" #include "mitkWeakPointer.h" +#include "mitkServiceReference.h" #pragma GCC visibility push(default) #include #pragma GCC visibility pop #include #include namespace mitk { class Image; class PlaneGeometry; /** \brief Manages and coordinates instances of mitk::Tool. \sa QmitkToolSelectionBox \sa QmitkToolReferenceDataSelectionBox \sa QmitkToolWorkingDataSelectionBox \sa Tool \sa QmitkSegmentationView \ingroup Interaction \ingroup ToolManagerEtAl There is a separate page describing the general design of QmitkSegmentationView: \ref QmitkSegmentationTechnicalPage This class creates and manages several instances of mitk::Tool. \li ToolManager creates instances of mitk::Tool by asking the itk::ObjectFactory to list all known implementations of mitk::Tool. As a result, one has to implement both a subclass of mitk::Tool and a matching subclass of itk::ObjectFactoryBase that is registered to the top-level itk::ObjectFactory. For an example, see mitkContourToolFactory.h. (this limitiation of one-class-one-factory is due to the implementation of itk::ObjectFactory). In MITK, the right place to register the factories to itk::ObjectFactory is the mitk::QMCoreObjectFactory or mitk::SBCoreObjectFactory. \li One (and only one - or none at all) of the registered tools can be activated using ActivateTool. This tool is registered to mitk::GlobalInteraction as a listener and will receive all mouse clicks and keyboard strokes that get into the MITK event mechanism. Tools are automatically unregistered from GlobalInteraction when no clients are registered to ToolManager (see RegisterClient()). \li ToolManager knows a set of "reference" DataNodes and a set of "working" DataNodes. The first application are segmentation tools, where the reference is the original image and the working data the (kind of) binary segmentation. However, ToolManager is implemented more generally, so that there could be other tools that work, e.g., with surfaces. \li Any "user/client" of ToolManager, i.e. every functionality that wants to use a tool, should call RegisterClient when the tools should be active. ToolManager keeps track of how many clients want it to be used, and when this count reaches zero, it unregistes the active Tool from GlobalInteraction. In "normal" settings, the functionality does not need to care about that if it uses a QmitkToolSelectionBox, which does exactly that when it is enabled/disabled. \li There is a set of events that are sent by ToolManager. At the moment these are TODO update documentation: - mitk::ToolReferenceDataChangedEvent whenever somebody calls SetReferenceData. Most of the time this actually means that the data has changed, but there might be cases where the same data is passed to SetReferenceData a second time, so don't rely on the assumption that something actually changed. - mitk::ToolSelectedEvent is sent when a (truly) different tool was activated. In reaction to this event you can ask for the active Tool using GetActiveTool or GetActiveToolID (where NULL or -1 indicate that NO tool is active at the moment). Design descisions: \li Not a singleton, because there could be two functionalities using tools, each one with different reference/working data. $Author$ */ class MitkExt_EXPORT ToolManager : public itk::Object { public: typedef std::vector ToolVectorType; typedef std::vector ToolVectorTypeConst; typedef std::vector DataVectorType; // has to be observed for delete events! typedef std::map NodeTagMapType; Message<> NodePropertiesChanged; Message<> NewNodesGenerated; Message1 NewNodeObjectsGenerated; Message<> ActiveToolChanged; Message<> ReferenceDataChanged; Message<> WorkingDataChanged; Message<> RoiDataChanged; Message1 ToolErrorMessage; Message1 GeneralToolMessage; mitkClassMacro(ToolManager, itk::Object); mitkNewMacro1Param(ToolManager, DataStorage*); /** \brief Gives you a list of all tools. This is const on purpose. */ const ToolVectorTypeConst GetTools(); int GetToolID( const Tool* tool ); /* \param id The tool of interest. Counting starts with 0. */ Tool* GetToolById(int id); /** \param id The tool to activate. Provide -1 for disabling any tools. Counting starts with 0. Registeres a listner for NodeRemoved event at DataStorage (see mitk::ToolManager::OnNodeRemoved). */ bool ActivateTool(int id); template int GetToolIdByToolType() { int id = 0; for ( ToolVectorType::iterator iter = m_Tools.begin(); iter != m_Tools.end(); ++iter, ++id ) { if ( dynamic_cast(iter->GetPointer()) ) { return id; } } return -1; } /** \return -1 for "No tool is active" */ int GetActiveToolID(); /** \return NULL for "No tool is active" */ Tool* GetActiveTool(); /* \brief Set a list of data/images as reference objects. */ void SetReferenceData(DataVectorType); /* \brief Set single data item/image as reference object. */ void SetReferenceData(DataNode*); /* \brief Set a list of data/images as working objects. */ void SetWorkingData(DataVectorType); /* \brief Set single data item/image as working object. */ void SetWorkingData(DataNode*); /* \brief Set a list of data/images as roi objects. */ void SetRoiData(DataVectorType); /* \brief Set a single data item/image as roi object. */ void SetRoiData(DataNode*); /* \brief Get the list of reference data. */ DataVectorType GetReferenceData(); /* \brief Get the current reference data. \warning If there is a list of items, this method will only return the first list item. */ DataNode* GetReferenceData(int); /* \brief Get the list of working data. */ DataVectorType GetWorkingData(); /* \brief Get the current working data. \warning If there is a list of items, this method will only return the first list item. */ DataNode* GetWorkingData(int); /* \brief Get the current roi data */ DataVectorType GetRoiData(); /* \brief Get the roi data at position idx */ DataNode* GetRoiData(int idx); DataStorage* GetDataStorage(); void SetDataStorage(DataStorage& storage); /* \brief Tell that someone is using tools. GUI elements should call this when they become active. This method increases an internal "client count". Tools are only registered to GlobalInteraction when this count is greater than 0. This is useful to automatically deactivate tools when you hide their GUI elements. */ void RegisterClient(); /* \brief Tell that someone is NOT using tools. GUI elements should call this when they become active. This method increases an internal "client count". Tools are only registered to GlobalInteraction when this count is greater than 0. This is useful to automatically deactivate tools when you hide their GUI elements. */ void UnregisterClient(); void OnOneOfTheReferenceDataDeletedConst(const itk::Object* caller, const itk::EventObject& e); void OnOneOfTheReferenceDataDeleted (itk::Object* caller, const itk::EventObject& e); void OnOneOfTheWorkingDataDeletedConst(const itk::Object* caller, const itk::EventObject& e); void OnOneOfTheWorkingDataDeleted (itk::Object* caller, const itk::EventObject& e); void OnOneOfTheRoiDataDeletedConst(const itk::Object* caller, const itk::EventObject& e); void OnOneOfTheRoiDataDeleted (itk::Object* caller, const itk::EventObject& e); /* \brief Connected to tool's messages This method just resends error messages coming from any of the tools. This way clients (GUIs) only have to observe one message. */ void OnToolErrorMessage(std::string s); void OnGeneralToolMessage(std::string s); protected: /** You may specify a list of tool "groups" that should be available for this ToolManager. Every Tool can report its group as a string. This constructor will try to find the tool's group inside the supplied string. If there is a match, the tool is accepted. Effectively, you can provide a human readable list like "default, lymphnodevolumetry, oldERISstuff". */ ToolManager(DataStorage* storage); // purposely hidden virtual ~ToolManager(); ToolVectorType m_Tools; Tool* m_ActiveTool; int m_ActiveToolID; DataVectorType m_ReferenceData; NodeTagMapType m_ReferenceDataObserverTags; DataVectorType m_WorkingData; NodeTagMapType m_WorkingDataObserverTags; DataVectorType m_RoiData; NodeTagMapType m_RoiDataObserverTags; int m_RegisteredClients; WeakPointer m_DataStorage; /// \brief Callback for NodeRemove events void OnNodeRemoved(const mitk::DataNode* node); + + private: + + std::map m_DisplayInteractorConfigs; }; } // namespace #endif diff --git a/Modules/MitkExt/DataManagement/mitkGridRepresentationProperty.cpp b/Modules/MitkExt/DataManagement/mitkGridRepresentationProperty.cpp index 9b75baa4da..f0018e2c22 100644 --- a/Modules/MitkExt/DataManagement/mitkGridRepresentationProperty.cpp +++ b/Modules/MitkExt/DataManagement/mitkGridRepresentationProperty.cpp @@ -1,91 +1,109 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "mitkGridRepresentationProperty.h" mitk::GridRepresentationProperty::GridRepresentationProperty( ) { AddRepresentationTypes(); SetValue( WIREFRAME ); } +mitk::GridRepresentationProperty::GridRepresentationProperty(const mitk::GridRepresentationProperty& other) + : mitk::EnumerationProperty(other) +{ +} + + mitk::GridRepresentationProperty::GridRepresentationProperty( const IdType& value ) { AddRepresentationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( WIREFRAME ); } } mitk::GridRepresentationProperty::GridRepresentationProperty( const std::string& value ) { AddRepresentationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( WIREFRAME ); } } void mitk::GridRepresentationProperty::SetRepresentationToPoints() { SetValue( POINTS ); } void mitk::GridRepresentationProperty::SetRepresentationToWireframe() { SetValue( WIREFRAME ); } void mitk::GridRepresentationProperty::SetRepresentationToSurface() { SetValue( SURFACE ); } void mitk::GridRepresentationProperty::SetRepresentationToWireframeSurface() { //SetValue( WIREFRAME_SURFACE ); } void mitk::GridRepresentationProperty::AddRepresentationTypes() { AddEnum( "Points", POINTS ); AddEnum( "Wireframe", WIREFRAME ); AddEnum( "Surface", SURFACE ); //AddEnum( "WireframeSurface", WIREFRAME_SURFACE ); } bool mitk::GridRepresentationProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } + +mitk::GridRepresentationProperty::Pointer mitk::GridRepresentationProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::GridRepresentationProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Modules/MitkExt/DataManagement/mitkGridRepresentationProperty.h b/Modules/MitkExt/DataManagement/mitkGridRepresentationProperty.h index 836bb9e181..bb89f68295 100644 --- a/Modules/MitkExt/DataManagement/mitkGridRepresentationProperty.h +++ b/Modules/MitkExt/DataManagement/mitkGridRepresentationProperty.h @@ -1,106 +1,114 @@ /*=================================================================== 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_GRID_REPRESENTATION_PROPERTY__H_ #define _MITK_GRID_REPRESENTATION_PROPERTY__H_ #include "mitkEnumerationProperty.h" #include "MitkExtExports.h" namespace mitk { /** * Extends the enumeration prop mitkEnumerationPropery. Adds the value * (constant / Id / string representation): *
    *
  • POINTS / 0 / Points
  • *
  • WIREFRAME / 1 / Wireframe
  • *
  • SURFACE / 2 / Surface
  • *
  • WIREFRAME_SURFACE / 3 / WireframeSurface
  • *
* Default is the Wireframe representation */ class MitkExt_EXPORT GridRepresentationProperty : public EnumerationProperty { public: enum RepresentationType {POINTS = 0, WIREFRAME = 1, SURFACE = 2}; //, WIREFRAME_SURFACE = 3}; mitkClassMacro( GridRepresentationProperty, EnumerationProperty ); itkNewMacro(GridRepresentationProperty); mitkNewMacro1Param(GridRepresentationProperty, const IdType& ); mitkNewMacro1Param(GridRepresentationProperty, const std::string& ); + Pointer Clone() const; + /** * Sets the representation type to POINTS. */ virtual void SetRepresentationToPoints(); /** * Sets the representation type to WIREFRAME. */ virtual void SetRepresentationToWireframe(); /** * Sets the representation type to SURFACE. */ virtual void SetRepresentationToSurface(); /** * Sets the representation type to WIREFRAME_SURFACE. */ virtual void SetRepresentationToWireframeSurface(); protected: /** * Constructor. Sets the representation to a default value of Wireframe(1) */ GridRepresentationProperty( ); + GridRepresentationProperty(const GridRepresentationProperty& other); + /** * Constructor. Sets the representation to the given value. If it is not * valid, the representation is set to Wireframe(1) * @param value the integer representation of the representation */ GridRepresentationProperty( const IdType& value ); /** * Constructor. Sets the representation to the given value. If it is not * valid, the representation is set to Wireframe(1) * @param value the string representation of the representation */ GridRepresentationProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid representation types. */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Adds the enumeration types as defined by vtk to the list of known * enumeration values. */ virtual void AddRepresentationTypes(); + +private: + + virtual itk::LightObject::Pointer InternalClone() const; }; } // end of namespace mitk #endif // _MITK_GRID_REPRESENTATION_PROPERTY__H_ diff --git a/Modules/MitkExt/DataManagement/mitkGridVolumeMapperProperty.cpp b/Modules/MitkExt/DataManagement/mitkGridVolumeMapperProperty.cpp index 902ae7c9ab..444acf833a 100644 --- a/Modules/MitkExt/DataManagement/mitkGridVolumeMapperProperty.cpp +++ b/Modules/MitkExt/DataManagement/mitkGridVolumeMapperProperty.cpp @@ -1,85 +1,97 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "mitkGridVolumeMapperProperty.h" mitk::GridVolumeMapperProperty::GridVolumeMapperProperty( ) { AddRepresentationTypes(); SetValue( PT ); } mitk::GridVolumeMapperProperty::GridVolumeMapperProperty( const IdType& value ) { AddRepresentationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( PT ); } } mitk::GridVolumeMapperProperty::GridVolumeMapperProperty( const std::string& value ) { AddRepresentationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( PT ); } } void mitk::GridVolumeMapperProperty::SetVolumeMapperToPT() { SetValue( PT ); } void mitk::GridVolumeMapperProperty::SetVolumeMapperToZSweep() { SetValue( ZSWEEP ); } void mitk::GridVolumeMapperProperty::SetVolumeMapperToRayCast() { SetValue( RAYCAST ); } void mitk::GridVolumeMapperProperty::AddRepresentationTypes() { AddEnum( "Ray Cast", RAYCAST ); AddEnum( "Projected Tetrahedra", PT ); AddEnum( "ZSweep", ZSWEEP ); } bool mitk::GridVolumeMapperProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } + +mitk::GridVolumeMapperProperty::Pointer mitk::GridVolumeMapperProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::GridVolumeMapperProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Modules/MitkExt/DataManagement/mitkGridVolumeMapperProperty.h b/Modules/MitkExt/DataManagement/mitkGridVolumeMapperProperty.h index 21819d4886..21a9884a51 100644 --- a/Modules/MitkExt/DataManagement/mitkGridVolumeMapperProperty.h +++ b/Modules/MitkExt/DataManagement/mitkGridVolumeMapperProperty.h @@ -1,101 +1,107 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_GRID_VOLUME_MAPPER_PROPERTY__H_ #define _MITK_GRID_VOLUME_MAPPER_PROPERTY__H_ #include "mitkEnumerationProperty.h" #include "MitkExtExports.h" namespace mitk { /** * Extends the enumeration prop mitkEnumerationPropery. Adds the value * (constant/Id/string representation): * PT/0/Projected Tetrahedra, ZSWEEP/1/ZSweep, RAYCAST/2/Ray Cast * Default is the Wireframe representation */ class MitkExt_EXPORT GridVolumeMapperProperty : public EnumerationProperty { public: enum MapperType { RAYCAST = 0, PT = 1, ZSWEEP = 2 }; mitkClassMacro( GridVolumeMapperProperty, EnumerationProperty ); itkNewMacro(GridVolumeMapperProperty); mitkNewMacro1Param(GridVolumeMapperProperty, const IdType&); mitkNewMacro1Param(GridVolumeMapperProperty, const std::string&); + Pointer Clone() const; + /** * Sets the mapper to projected tetrahedra. */ virtual void SetVolumeMapperToPT(); /** * Sets the mapper to zsweep. */ virtual void SetVolumeMapperToZSweep(); /** * Sets the mapper to ray casting. */ virtual void SetVolumeMapperToRayCast(); protected: /** * Constructor. Sets the representation to a default value of Wireframe(1) */ GridVolumeMapperProperty( ); /** * Constructor. Sets the representation to the given value. If it is not * valid, the representation is set to Wireframe(1) * @param value the integer representation of the representation */ GridVolumeMapperProperty( const IdType& value ); /** * Constructor. Sets the representation to the given value. If it is not * valid, the representation is set to Wireframe(1) * @param value the string representation of the representation */ GridVolumeMapperProperty( const std::string& value ); /** * this function is overridden as protected, so that the user may not add * additional invalid representation types. */ virtual bool AddEnum( const std::string& name, const IdType& id ); /** * Adds the enumeration types as defined by vtk to the list of known * enumeration values. */ virtual void AddRepresentationTypes(); + +private: + + virtual itk::LightObject::Pointer InternalClone() const; }; } // end of namespace mitk #endif // _MITK_GRID_VOLUME_MAPPER_PROPERTY__H_ diff --git a/Modules/MitkExt/DataManagement/mitkOrganTypeProperty.cpp b/Modules/MitkExt/DataManagement/mitkOrganTypeProperty.cpp index 9c76744b97..c291630c84 100644 --- a/Modules/MitkExt/DataManagement/mitkOrganTypeProperty.cpp +++ b/Modules/MitkExt/DataManagement/mitkOrganTypeProperty.cpp @@ -1,115 +1,127 @@ /*=================================================================== 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 "mitkOrganTypeProperty.h" mitk::OrganTypeProperty::OrganTypeProperty() { AddEnumerationTypes(); } mitk::OrganTypeProperty::OrganTypeProperty( const IdType& value ) { AddEnumerationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ) ; } else { SetValue( 0 ); } } mitk::OrganTypeProperty::OrganTypeProperty( const std::string& value ) { AddEnumerationTypes(); if ( IsValidEnumerationValue( value ) ) { SetValue( value ); } else { SetValue( "undefined" ); } } mitk::OrganTypeProperty::~OrganTypeProperty() { } void mitk::OrganTypeProperty::AddEnumerationTypes() { IdType newId = static_cast(EnumerationProperty::Size()); // On changes, please also change mitk::DataNodeFactory::DefaultColorForOrgan() AddEnum( "undefined", newId++ ); AddEnum( "Ankle", newId++ ); AddEnum( "Appendix", newId++ ); AddEnum( "Blood vessels", newId++ ); AddEnum( "Bone", newId++ ); AddEnum( "Brain", newId++ ); AddEnum( "Bronchial tree", newId++ ); AddEnum( "Coccyx", newId++ ); AddEnum( "Colon", newId++ ); AddEnum( "Cyst", newId++ ); AddEnum( "Elbow", newId++ ); AddEnum( "Eye", newId++ ); AddEnum( "Fallopian tube", newId++ ); AddEnum( "Fat", newId++ ); AddEnum( "Gall bladder", newId++ ); AddEnum( "Hand", newId++ ); AddEnum( "Heart", newId++ ); AddEnum( "Hip", newId++ ); AddEnum( "Hippocampus", newId++ ); AddEnum( "Kidney", newId++ ); AddEnum( "Knee", newId++ ); AddEnum( "Larynx", newId++ ); AddEnum( "Liver", newId++ ); AddEnum( "Lung", newId++ ); AddEnum( "Lymph node", newId++ ); AddEnum( "Muscle", newId++ ); AddEnum( "Nerve", newId++ ); AddEnum( "Nose", newId++ ); AddEnum( "Oesophagus", newId++ ); AddEnum( "Ovaries", newId++ ); AddEnum( "Pancreas", newId++ ); AddEnum( "Pelvis", newId++ ); AddEnum( "Penis", newId++ ); AddEnum( "Pharynx", newId++ ); AddEnum( "Prostate", newId++ ); AddEnum( "Rectum", newId++ ); AddEnum( "Sacrum", newId++ ); AddEnum( "Seminal vesicle", newId++ ); AddEnum( "Shoulder", newId++ ); AddEnum( "Spinal cord", newId++ ); AddEnum( "Spleen", newId++ ); AddEnum( "Stomach", newId++ ); AddEnum( "Teeth", newId++ ); AddEnum( "Testicles", newId++ ); AddEnum( "Thyroid", newId++ ); AddEnum( "Tongue", newId++ ); AddEnum( "Tumor", newId++ ); AddEnum( "Urethra", newId++ ); AddEnum( "Urinary bladder", newId++ ); AddEnum( "Uterus", newId++ ); AddEnum( "Vagina", newId++ ); AddEnum( "Vertebra", newId++ ); AddEnum( "Wrist", newId++ ); } + +mitk::OrganTypeProperty::Pointer mitk::OrganTypeProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} + +itk::LightObject::Pointer mitk::OrganTypeProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Modules/MitkExt/DataManagement/mitkOrganTypeProperty.h b/Modules/MitkExt/DataManagement/mitkOrganTypeProperty.h index 577f8d3e93..43f80890f2 100644 --- a/Modules/MitkExt/DataManagement/mitkOrganTypeProperty.h +++ b/Modules/MitkExt/DataManagement/mitkOrganTypeProperty.h @@ -1,76 +1,79 @@ /*=================================================================== 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 mitkOrganTypeProperty_h_Included #define mitkOrganTypeProperty_h_Included #include "mitkCommon.h" #include "MitkExtExports.h" #include "mitkEnumerationProperty.h" #include namespace mitk { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4522) #endif /** \brief Enumerates all known organs :-) \sa QmitkInteractiveSegmentation \ingroup ToolManagerEtAl \ingroup DataManagement Last contributor $Author$ */ class MitkExt_EXPORT OrganTypeProperty : public EnumerationProperty { public: mitkClassMacro(OrganTypeProperty, EnumerationProperty); itkNewMacro(OrganTypeProperty); mitkNewMacro1Param(OrganTypeProperty, const IdType&); mitkNewMacro1Param(OrganTypeProperty, const std::string&); + Pointer Clone() const; + using BaseProperty::operator=; protected: OrganTypeProperty(); OrganTypeProperty( const IdType& value ); OrganTypeProperty( const std::string& value ); virtual ~OrganTypeProperty(); virtual void AddEnumerationTypes(); private: // purposely not implemented - OrganTypeProperty(const OrganTypeProperty&); OrganTypeProperty& operator=(const OrganTypeProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace #endif diff --git a/Modules/PlanarFigure/DataManagement/mitkPlanarFigureControlPointStyleProperty.cpp b/Modules/PlanarFigure/DataManagement/mitkPlanarFigureControlPointStyleProperty.cpp index e844b808e5..e353c99895 100644 --- a/Modules/PlanarFigure/DataManagement/mitkPlanarFigureControlPointStyleProperty.cpp +++ b/Modules/PlanarFigure/DataManagement/mitkPlanarFigureControlPointStyleProperty.cpp @@ -1,75 +1,85 @@ /*=================================================================== 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 "mitkPlanarFigureControlPointStyleProperty.h" mitk::PlanarFigureControlPointStyleProperty::PlanarFigureControlPointStyleProperty( ) { this->AddEnumTypes(); this->SetValue( static_cast ( Square ) ); } mitk::PlanarFigureControlPointStyleProperty::PlanarFigureControlPointStyleProperty( const IdType &value ) { this->AddEnumTypes(); if ( this->IsValidEnumerationValue( value ) ) { this->SetValue( value ) ; } else { this->SetValue( static_cast ( Square ) ); } } mitk::PlanarFigureControlPointStyleProperty::PlanarFigureControlPointStyleProperty( const std::string &value ) { this->AddEnumTypes(); if ( this->IsValidEnumerationValue( value ) ) { this->SetValue( value ); } else { this->SetValue( static_cast( Square ) ); } } void mitk::PlanarFigureControlPointStyleProperty::AddEnumTypes() { this->AddEnum( "Square", static_cast( Square ) ); this->AddEnum( "Circle", static_cast( Circle ) ); } bool mitk::PlanarFigureControlPointStyleProperty::AddEnum( const std::string& name, const IdType& id ) { return Superclass::AddEnum( name, id ); } mitk::PlanarFigureControlPointStyleProperty::Shape mitk::PlanarFigureControlPointStyleProperty::GetShape() { return static_cast( this->GetValueAsId() ); } void mitk::PlanarFigureControlPointStyleProperty::SetShape(mitk::PlanarFigureControlPointStyleProperty::Shape shape) { this->SetValue( static_cast( shape ) ); } +mitk::PlanarFigureControlPointStyleProperty::Pointer mitk::PlanarFigureControlPointStyleProperty::Clone() const +{ + Pointer result = static_cast(this->InternalClone().GetPointer()); + return result; +} +itk::LightObject::Pointer mitk::PlanarFigureControlPointStyleProperty::InternalClone() const +{ + itk::LightObject::Pointer result(new Self(*this)); + return result; +} diff --git a/Modules/PlanarFigure/DataManagement/mitkPlanarFigureControlPointStyleProperty.h b/Modules/PlanarFigure/DataManagement/mitkPlanarFigureControlPointStyleProperty.h index bcbf8f1a98..320c57ec07 100644 --- a/Modules/PlanarFigure/DataManagement/mitkPlanarFigureControlPointStyleProperty.h +++ b/Modules/PlanarFigure/DataManagement/mitkPlanarFigureControlPointStyleProperty.h @@ -1,88 +1,97 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkPlanarFigureControlPointStyleProperty_h #define mitkPlanarFigureControlPointStyleProperty_h #include "mitkEnumerationProperty.h" #include "PlanarFigureExports.h" namespace mitk { /** * \brief Defines the rendering style of control points for PlanarFigure objects. * \sa mitk::PlanarFigureMapper2D * \ingroup DataManagement * * Used by PlanarFigureMapper2D to determine which of several control point shapes to use. * Currently this is basically the choice between squares and circles. If more options * are implemented, this class should be enhanced. * * After construction, the default shape is a square. * */ class PlanarFigure_EXPORT PlanarFigureControlPointStyleProperty : public EnumerationProperty { public: mitkClassMacro( PlanarFigureControlPointStyleProperty, EnumerationProperty ); itkNewMacro(PlanarFigureControlPointStyleProperty); mitkNewMacro1Param(PlanarFigureControlPointStyleProperty, const IdType&); mitkNewMacro1Param(PlanarFigureControlPointStyleProperty, const std::string&); + Pointer Clone() const; + typedef enum { Square, Circle } Shape; virtual Shape GetShape(); virtual void SetShape( Shape ); protected: PlanarFigureControlPointStyleProperty( ); PlanarFigureControlPointStyleProperty( const IdType &value ); /** * Constructor. Sets the decoration type to the given value. If it is not * valid, the representation is set to none */ PlanarFigureControlPointStyleProperty( const std::string &value ); /** * this function is overridden as protected, so that the user may not add * additional invalid types. */ virtual bool AddEnum( const std::string &name, const IdType &id ); /** * Adds the standard enumeration types with corresponding strings. */ virtual void AddEnumTypes(); + +private: + + // purposely not implemented + PlanarFigureControlPointStyleProperty& operator=(const PlanarFigureControlPointStyleProperty&); + + virtual itk::LightObject::Pointer InternalClone() const; }; } // end of namespace mitk #endif diff --git a/Modules/Qmitk/QmitkRenderWindow.cpp b/Modules/Qmitk/QmitkRenderWindow.cpp index f9cf89a97d..e86f813537 100644 --- a/Modules/Qmitk/QmitkRenderWindow.cpp +++ b/Modules/Qmitk/QmitkRenderWindow.cpp @@ -1,542 +1,542 @@ /*=================================================================== 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 "QmitkRenderWindow.h" #include #include #include #include #include #include #include #include #include "QmitkEventAdapter.h" // TODO: INTERACTION_LEGACY #include "mitkMousePressEvent.h" #include "mitkMouseMoveEvent.h" #include "mitkMouseReleaseEvent.h" #include "mitkInteractionKeyEvent.h" #include "mitkMouseWheelEvent.h" #include "mitkInternalEvent.h" #include "QmitkRenderWindowMenu.h" QmitkRenderWindow::QmitkRenderWindow(QWidget *parent, QString name, mitk::VtkPropRenderer* /*renderer*/, mitk::RenderingManager* renderingManager) : QVTKWidget(parent), m_ResendQtEvents(true), m_MenuWidget(NULL), m_MenuWidgetActivated(false), m_LayoutIndex(0) { Initialize(renderingManager, name.toStdString().c_str()); // Initialize mitkRenderWindowBase setFocusPolicy(Qt::StrongFocus); setMouseTracking(true); } QmitkRenderWindow::~QmitkRenderWindow() { Destroy(); // Destroy mitkRenderWindowBase } void QmitkRenderWindow::SetResendQtEvents(bool resend) { m_ResendQtEvents = resend; } void QmitkRenderWindow::SetLayoutIndex(unsigned int layoutIndex) { m_LayoutIndex = layoutIndex; if (m_MenuWidget) m_MenuWidget->SetLayoutIndex(layoutIndex); } unsigned int QmitkRenderWindow::GetLayoutIndex() { if (m_MenuWidget) return m_MenuWidget->GetLayoutIndex(); else return 0; } void QmitkRenderWindow::LayoutDesignListChanged(int layoutDesignIndex) { if (m_MenuWidget) m_MenuWidget->UpdateLayoutDesignList(layoutDesignIndex); } void QmitkRenderWindow::mousePressEvent(QMouseEvent *me) { mitk::MousePressEvent::Pointer mPressEvent = mitk::MousePressEvent::New(m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me)); if (!this->HandleEvent(mPressEvent.GetPointer())) { // TODO: INTERACTION_LEGACY mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me)); this->mousePressMitkEvent(&myevent); } QVTKWidget::mousePressEvent(me); if (m_ResendQtEvents) me->ignore(); } void QmitkRenderWindow::mouseReleaseEvent(QMouseEvent *me) { mitk::MouseReleaseEvent::Pointer mReleaseEvent = mitk::MouseReleaseEvent::New(m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me)); if (!this->HandleEvent(mReleaseEvent.GetPointer())) { // TODO: INTERACTION_LEGACY mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me)); this->mouseReleaseMitkEvent(&myevent); } QVTKWidget::mouseReleaseEvent(me); if (m_ResendQtEvents) me->ignore(); } void QmitkRenderWindow::mouseMoveEvent(QMouseEvent *me) { this->AdjustRenderWindowMenuVisibility(me->pos()); mitk::MouseMoveEvent::Pointer mMoveEvent = mitk::MouseMoveEvent::New(m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me)); if (!this->HandleEvent(mMoveEvent.GetPointer())) { // TODO: INTERACTION_LEGACY mitk::MouseEvent myevent(QmitkEventAdapter::AdaptMouseEvent(m_Renderer, me)); this->mouseMoveMitkEvent(&myevent); } QVTKWidget::mouseMoveEvent(me); } void QmitkRenderWindow::wheelEvent(QWheelEvent *we) { mitk::MouseWheelEvent::Pointer mWheelEvent = mitk::MouseWheelEvent::New(m_Renderer, GetMousePosition(we), GetButtonState(we), GetModifiers(we), GetDelta(we)); if (!this->HandleEvent(mWheelEvent.GetPointer())) { // TODO: INTERACTION_LEGACY mitk::WheelEvent myevent(QmitkEventAdapter::AdaptWheelEvent(m_Renderer, we)); this->wheelMitkEvent(&myevent); } QVTKWidget::wheelEvent(we); if (m_ResendQtEvents) we->ignore(); } void QmitkRenderWindow::keyPressEvent(QKeyEvent *ke) { - mitk::ModifierKeys modifiers = GetModifiers(ke); + mitk::InteractionEvent::ModifierKeys modifiers = GetModifiers(ke); std::string key = GetKeyLetter(ke); mitk::InteractionKeyEvent::Pointer keyEvent = mitk::InteractionKeyEvent::New(m_Renderer, key, modifiers); if (!this->HandleEvent(keyEvent.GetPointer())) { // TODO: INTERACTION_LEGACY QPoint cp = mapFromGlobal(QCursor::pos()); mitk::KeyEvent mke(QmitkEventAdapter::AdaptKeyEvent(m_Renderer, ke, cp)); this->keyPressMitkEvent(&mke); ke->accept(); } QVTKWidget::keyPressEvent(ke); if (m_ResendQtEvents) ke->ignore(); } void QmitkRenderWindow::enterEvent(QEvent *e) { // TODO implement new event QVTKWidget::enterEvent(e); } void QmitkRenderWindow::DeferredHideMenu() { MITK_DEBUG << "QmitkRenderWindow::DeferredHideMenu"; if (m_MenuWidget) m_MenuWidget->HideMenu(); } void QmitkRenderWindow::leaveEvent(QEvent *e) { mitk::InternalEvent::Pointer internalEvent = mitk::InternalEvent::New(this->m_Renderer, NULL, "LeaveRenderWindow"); if (!this->HandleEvent(internalEvent.GetPointer())) // TODO implement new event MITK_DEBUG << "QmitkRenderWindow::leaveEvent"; if (m_MenuWidget) m_MenuWidget->smoothHide(); QVTKWidget::leaveEvent(e); } void QmitkRenderWindow::paintEvent(QPaintEvent* /*event*/) { //We are using our own interaction and thus have to call the rendering manually. this->GetRenderer()->GetRenderingManager()->RequestUpdate(GetRenderWindow()); } void QmitkRenderWindow::resizeEvent(QResizeEvent* event) { this->resizeMitkEvent(event->size().width(), event->size().height()); QVTKWidget::resizeEvent(event); emit resized(); } void QmitkRenderWindow::moveEvent(QMoveEvent* event) { QVTKWidget::moveEvent(event); // after a move the overlays need to be positioned emit moved(); } void QmitkRenderWindow::showEvent(QShowEvent* event) { QVTKWidget::showEvent(event); // this singleshot is necessary to have the overlays positioned correctly after initial show // simple call of moved() is no use here!! QTimer::singleShot(0, this, SIGNAL( moved() )); } void QmitkRenderWindow::ActivateMenuWidget(bool state, QmitkStdMultiWidget* stdMultiWidget) { m_MenuWidgetActivated = state; if (!m_MenuWidgetActivated && m_MenuWidget) { //disconnect Signal/Slot Connection disconnect(m_MenuWidget, SIGNAL( SignalChangeLayoutDesign(int) ), this, SLOT(OnChangeLayoutDesign(int))); disconnect(m_MenuWidget, SIGNAL( ResetView() ), this, SIGNAL( ResetView())); disconnect(m_MenuWidget, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SIGNAL( ChangeCrosshairRotationMode(int))); delete m_MenuWidget; m_MenuWidget = 0; } else if (m_MenuWidgetActivated && !m_MenuWidget) { //create render window MenuBar for split, close Window or set new setting. m_MenuWidget = new QmitkRenderWindowMenu(this, 0, m_Renderer, stdMultiWidget); m_MenuWidget->SetLayoutIndex(m_LayoutIndex); //create Signal/Slot Connection connect(m_MenuWidget, SIGNAL( SignalChangeLayoutDesign(int) ), this, SLOT(OnChangeLayoutDesign(int))); connect(m_MenuWidget, SIGNAL( ResetView() ), this, SIGNAL( ResetView())); connect(m_MenuWidget, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SIGNAL( ChangeCrosshairRotationMode(int))); } } void QmitkRenderWindow::AdjustRenderWindowMenuVisibility(const QPoint& /*pos*/) { if (m_MenuWidget) { m_MenuWidget->ShowMenu(); m_MenuWidget->MoveWidgetToCorrectPos(1.0f); } } void QmitkRenderWindow::HideRenderWindowMenu() { // DEPRECATED METHOD } void QmitkRenderWindow::OnChangeLayoutDesign(int layoutDesignIndex) { emit SignalLayoutDesignChanged(layoutDesignIndex); } void QmitkRenderWindow::OnWidgetPlaneModeChanged(int mode) { if (m_MenuWidget) m_MenuWidget->NotifyNewWidgetPlanesMode(mode); } void QmitkRenderWindow::FullScreenMode(bool state) { if (m_MenuWidget) m_MenuWidget->ChangeFullScreenMode(state); } void QmitkRenderWindow::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("application/x-mitk-datanodes")) { event->accept(); } } void QmitkRenderWindow::dropEvent(QDropEvent * event) { if (event->mimeData()->hasFormat("application/x-mitk-datanodes")) { QString arg = QString(event->mimeData()->data("application/x-mitk-datanodes").data()); QStringList listOfDataNodes = arg.split(","); std::vector vectorOfDataNodePointers; for (int i = 0; i < listOfDataNodes.size(); i++) { long val = listOfDataNodes[i].toLong(); mitk::DataNode* node = static_cast((void*) val); vectorOfDataNodePointers.push_back(node); } emit NodesDropped(this, vectorOfDataNodePointers); } } -mitk::Point2D QmitkRenderWindow::GetMousePosition(QMouseEvent* me) +mitk::Point2D QmitkRenderWindow::GetMousePosition(QMouseEvent* me) const { mitk::Point2D point; point[0] = me->x(); point[1] = me->y(); return point; } -mitk::Point2D QmitkRenderWindow::GetMousePosition(QWheelEvent* we) +mitk::Point2D QmitkRenderWindow::GetMousePosition(QWheelEvent* we) const { mitk::Point2D point; point[0] = we->x(); point[1] = we->y(); return point; } -mitk::MouseButtons QmitkRenderWindow::GetEventButton(QMouseEvent* me) +mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetEventButton(QMouseEvent* me) const { - mitk::MouseButtons eventButton; + mitk::InteractionEvent::MouseButtons eventButton; switch (me->button()) { case Qt::LeftButton: - eventButton = mitk::LeftMouseButton; + eventButton = mitk::InteractionEvent::LeftMouseButton; break; case Qt::RightButton: - eventButton = mitk::RightMouseButton; + eventButton = mitk::InteractionEvent::RightMouseButton; break; case Qt::MidButton: - eventButton = mitk::MiddleMouseButton; + eventButton = mitk::InteractionEvent::MiddleMouseButton; break; default: - eventButton = mitk::NoButton; + eventButton = mitk::InteractionEvent::NoButton; break; } return eventButton; } -mitk::MouseButtons QmitkRenderWindow::GetButtonState(QMouseEvent* me) +mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetButtonState(QMouseEvent* me) const { - mitk::MouseButtons buttonState = mitk::NoButton; + mitk::InteractionEvent::MouseButtons buttonState = mitk::InteractionEvent::NoButton; if (me->buttons() & Qt::LeftButton) { - buttonState = buttonState | mitk::LeftMouseButton; + buttonState = buttonState | mitk::InteractionEvent::LeftMouseButton; } if (me->buttons() & Qt::RightButton) { - buttonState = buttonState | mitk::RightMouseButton; + buttonState = buttonState | mitk::InteractionEvent::RightMouseButton; } if (me->buttons() & Qt::MidButton) { - buttonState = buttonState | mitk::MiddleMouseButton; + buttonState = buttonState | mitk::InteractionEvent::MiddleMouseButton; } return buttonState; } -mitk::ModifierKeys QmitkRenderWindow::GetModifiers(QMouseEvent* me) +mitk::InteractionEvent::ModifierKeys QmitkRenderWindow::GetModifiers(QMouseEvent* me) const { - mitk::ModifierKeys modifiers = mitk::NoKey; + mitk::InteractionEvent::ModifierKeys modifiers = mitk::InteractionEvent::NoKey; if (me->modifiers() & Qt::ALT) { - modifiers = modifiers | mitk::AltKey; + modifiers = modifiers | mitk::InteractionEvent::AltKey; } if (me->modifiers() & Qt::CTRL) { - modifiers = modifiers | mitk::ControlKey; + modifiers = modifiers | mitk::InteractionEvent::ControlKey; } if (me->modifiers() & Qt::SHIFT) { - modifiers = modifiers | mitk::ShiftKey; + modifiers = modifiers | mitk::InteractionEvent::ShiftKey; } return modifiers; } -mitk::MouseButtons QmitkRenderWindow::GetButtonState(QWheelEvent* we) +mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetButtonState(QWheelEvent* we) const { - mitk::MouseButtons buttonState = mitk::NoButton; + mitk::InteractionEvent::MouseButtons buttonState = mitk::InteractionEvent::NoButton; if (we->buttons() & Qt::LeftButton) { - buttonState = buttonState | mitk::RightMouseButton; + buttonState = buttonState | mitk::InteractionEvent::RightMouseButton; } if (we->buttons() & Qt::RightButton) { - buttonState = buttonState | mitk::LeftMouseButton; + buttonState = buttonState | mitk::InteractionEvent::LeftMouseButton; } if (we->buttons() & Qt::MidButton) { - buttonState = buttonState | mitk::MiddleMouseButton; + buttonState = buttonState | mitk::InteractionEvent::MiddleMouseButton; } return buttonState; } -mitk::ModifierKeys QmitkRenderWindow::GetModifiers(QWheelEvent* we) +mitk::InteractionEvent::ModifierKeys QmitkRenderWindow::GetModifiers(QWheelEvent* we) const { - mitk::ModifierKeys modifiers = mitk::NoKey; + mitk::InteractionEvent::ModifierKeys modifiers = mitk::InteractionEvent::NoKey; if (we->modifiers() & Qt::ALT) { - modifiers = modifiers | mitk::AltKey; + modifiers = modifiers | mitk::InteractionEvent::AltKey; } if (we->modifiers() & Qt::CTRL) { - modifiers = modifiers | mitk::ControlKey; + modifiers = modifiers | mitk::InteractionEvent::ControlKey; } if (we->modifiers() & Qt::SHIFT) { - modifiers = modifiers | mitk::ShiftKey; + modifiers = modifiers | mitk::InteractionEvent::ShiftKey; } return modifiers; } -mitk::ModifierKeys QmitkRenderWindow::GetModifiers(QKeyEvent* ke) +mitk::InteractionEvent::ModifierKeys QmitkRenderWindow::GetModifiers(QKeyEvent* ke) const { - mitk::ModifierKeys modifiers = mitk::NoKey; + mitk::InteractionEvent::ModifierKeys modifiers = mitk::InteractionEvent::NoKey; if (ke->modifiers() & Qt::ShiftModifier) - modifiers = modifiers | mitk::ShiftKey; + modifiers = modifiers | mitk::InteractionEvent::ShiftKey; if (ke->modifiers() & Qt::CTRL) - modifiers = modifiers | mitk::ControlKey; + modifiers = modifiers | mitk::InteractionEvent::ControlKey; if (ke->modifiers() & Qt::ALT) - modifiers = modifiers | mitk::AltKey; + modifiers = modifiers | mitk::InteractionEvent::AltKey; return modifiers; } -std::string QmitkRenderWindow::GetKeyLetter(QKeyEvent *ke) +std::string QmitkRenderWindow::GetKeyLetter(QKeyEvent *ke) const { // Converting Qt Key Event to string element. std::string key = ""; int tkey = ke->key(); if (tkey < 128) { //standard ascii letter key = (char) toupper(tkey); } else { // special keys switch (tkey) { case Qt::Key_Return: - key = mitk::KeyReturn; + key = mitk::InteractionEvent::KeyReturn; break; case Qt::Key_Enter: - key = mitk::KeyEnter; + key = mitk::InteractionEvent::KeyEnter; break; case Qt::Key_Escape: - key = mitk::KeyEnter; + key = mitk::InteractionEvent::KeyEnter; break; case Qt::Key_Delete: - key = mitk::KeyDelete; + key = mitk::InteractionEvent::KeyDelete; break; case Qt::Key_Up: - key = mitk::KeyArrowUp; + key = mitk::InteractionEvent::KeyArrowUp; break; case Qt::Key_Down: - key = mitk::KeyArrowDown; + key = mitk::InteractionEvent::KeyArrowDown; break; case Qt::Key_Left: - key = mitk::KeyArrowLeft; + key = mitk::InteractionEvent::KeyArrowLeft; break; case Qt::Key_Right: - key = mitk::KeyArrowRight; + key = mitk::InteractionEvent::KeyArrowRight; break; case Qt::Key_F1: - key = mitk::KeyF1; + key = mitk::InteractionEvent::KeyF1; break; case Qt::Key_F2: - key = mitk::KeyF2; + key = mitk::InteractionEvent::KeyF2; break; case Qt::Key_F3: - key = mitk::KeyF3; + key = mitk::InteractionEvent::KeyF3; break; case Qt::Key_F4: - key = mitk::KeyF4; + key = mitk::InteractionEvent::KeyF4; break; case Qt::Key_F5: - key = mitk::KeyF5; + key = mitk::InteractionEvent::KeyF5; break; case Qt::Key_F6: - key = mitk::KeyF6; + key = mitk::InteractionEvent::KeyF6; break; case Qt::Key_F7: - key = mitk::KeyF7; + key = mitk::InteractionEvent::KeyF7; break; case Qt::Key_F8: - key = mitk::KeyF8; + key = mitk::InteractionEvent::KeyF8; break; case Qt::Key_F9: - key = mitk::KeyF9; + key = mitk::InteractionEvent::KeyF9; break; case Qt::Key_F10: - key = mitk::KeyF10; + key = mitk::InteractionEvent::KeyF10; break; case Qt::Key_F11: - key = mitk::KeyF11; + key = mitk::InteractionEvent::KeyF11; break; case Qt::Key_F12: - key = mitk::KeyF12; + key = mitk::InteractionEvent::KeyF12; break; case Qt::Key_End: - key = mitk::KeyEnd; + key = mitk::InteractionEvent::KeyEnd; break; case Qt::Key_Home: - key = mitk::KeyPos1; + key = mitk::InteractionEvent::KeyPos1; break; case Qt::Key_Insert: - key = mitk::KeyInsert; + key = mitk::InteractionEvent::KeyInsert; break; case Qt::Key_PageDown: - key = mitk::KeyPageDown; + key = mitk::InteractionEvent::KeyPageDown; break; case Qt::Key_PageUp: - key = mitk::KeyPageUp; + key = mitk::InteractionEvent::KeyPageUp; break; case Qt::Key_Space: - key = mitk::KeySpace; + key = mitk::InteractionEvent::KeySpace; break; } } return key; } -int QmitkRenderWindow::GetDelta(QWheelEvent* we) +int QmitkRenderWindow::GetDelta(QWheelEvent* we) const { return we->delta(); } diff --git a/Modules/Qmitk/QmitkRenderWindow.h b/Modules/Qmitk/QmitkRenderWindow.h index 0763cd2e1e..b41332a344 100644 --- a/Modules/Qmitk/QmitkRenderWindow.h +++ b/Modules/Qmitk/QmitkRenderWindow.h @@ -1,180 +1,180 @@ /*=================================================================== 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 QMITKRENDERWINDOW_H_HEADER_INCLUDED_C1C40D66 #define QMITKRENDERWINDOW_H_HEADER_INCLUDED_C1C40D66 #include "mitkRenderWindowBase.h" #include #include "QVTKWidget.h" #include "QmitkRenderWindowMenu.h" #include "mitkInteractionEventConst.h" class QmitkStdMultiWidget; class QDragEnterEvent; class QDropEvent; /** * \ingroup QmitkModule * \brief MITK implementation of the QVTKWidget */ class QMITK_EXPORT QmitkRenderWindow: public QVTKWidget, public mitk::RenderWindowBase { Q_OBJECT public: QmitkRenderWindow(QWidget *parent = 0, QString name = "unnamed renderwindow", mitk::VtkPropRenderer* renderer = NULL, mitk::RenderingManager* renderingManager = NULL); virtual ~QmitkRenderWindow(); /** * \brief Whether Qt events should be passed to parent (default: true) * * With introduction of the QVTKWidget the behaviour regarding Qt events changed. * QVTKWidget "accepts" Qt events like mouse clicks (i.e. set an "accepted" flag). * When this flag is set, Qt fininshed handling of this event -- otherwise it is * reached through to the widget's parent. * * This reaching through to the parent was implicitly required by QmitkMaterialWidget / QmitkMaterialShowCase. *QmitkStdMultiWidget * The default behaviour of QmitkRenderWindow is now to clear the "accepted" flag * of Qt events after they were handled by QVTKWidget. This way parents can also * handle events. * * If you don't want this behaviour, call SetResendQtEvents(true) on your render window. */ virtual void SetResendQtEvents(bool resend); // Set Layout Index to define the Layout Type void SetLayoutIndex(unsigned int layoutIndex); // Get Layout Index to define the Layout Type unsigned int GetLayoutIndex(); //MenuWidget need to update the Layout Design List when Layout had changed void LayoutDesignListChanged(int layoutDesignIndex); void HideRenderWindowMenu(); //Activate or Deactivate MenuWidget. void ActivateMenuWidget(bool state, QmitkStdMultiWidget* stdMultiWidget = 0); bool GetActivateMenuWidgetFlag() { return m_MenuWidgetActivated; } // Get it from the QVTKWidget parent virtual vtkRenderWindow* GetVtkRenderWindow() { return GetRenderWindow(); } virtual vtkRenderWindowInteractor* GetVtkRenderWindowInteractor() { return NULL; } void FullScreenMode(bool state); protected: // overloaded move handler virtual void moveEvent(QMoveEvent* event); // overloaded show handler void showEvent(QShowEvent* event); // overloaded resize handler virtual void resizeEvent(QResizeEvent* event); // overloaded paint handler virtual void paintEvent(QPaintEvent* event); // overloaded mouse press handler virtual void mousePressEvent(QMouseEvent* event); // overloaded mouse move handler virtual void mouseMoveEvent(QMouseEvent* event); // overloaded mouse release handler virtual void mouseReleaseEvent(QMouseEvent* event); // overloaded key press handler virtual void keyPressEvent(QKeyEvent* event); // overloaded enter handler virtual void enterEvent(QEvent*); // overloaded leave handler virtual void leaveEvent(QEvent*); /// \brief Simply says we accept the event type. virtual void dragEnterEvent(QDragEnterEvent *event); /// \brief If the dropped type is application/x-mitk-datanodes we process the request by converting to mitk::DataNode pointers and emitting the NodesDropped signal. virtual void dropEvent(QDropEvent * event); #ifndef QT_NO_WHEELEVENT // overload wheel mouse event virtual void wheelEvent(QWheelEvent*); #endif void AdjustRenderWindowMenuVisibility(const QPoint& pos); signals: void ResetView(); // \brief int parameters are enum from QmitkStdMultiWidget void ChangeCrosshairRotationMode(int); void SignalLayoutDesignChanged(int layoutDesignIndex); void moved(); void resized(); /// \brief Emits a signal to say that this window has had the following nodes dropped on it. void NodesDropped(QmitkRenderWindow *thisWindow, std::vector nodes); protected slots: void OnChangeLayoutDesign(int layoutDesignIndex); void OnWidgetPlaneModeChanged(int); void DeferredHideMenu(); private: // Helper Functions to Convert Qt-Events to Mitk-Events - mitk::Point2D GetMousePosition(QMouseEvent* me); - mitk::Point2D GetMousePosition(QWheelEvent* we); - mitk::MouseButtons GetEventButton(QMouseEvent* me); - mitk::MouseButtons GetButtonState(QMouseEvent* me); - mitk::ModifierKeys GetModifiers(QMouseEvent* me); - mitk::MouseButtons GetButtonState(QWheelEvent* we); - mitk::ModifierKeys GetModifiers(QWheelEvent* we); - mitk::ModifierKeys GetModifiers(QKeyEvent* ke); - std::string GetKeyLetter(QKeyEvent* ke); - int GetDelta(QWheelEvent* we); + mitk::Point2D GetMousePosition(QMouseEvent* me) const; + mitk::Point2D GetMousePosition(QWheelEvent* we) const; + mitk::InteractionEvent::MouseButtons GetEventButton(QMouseEvent* me) const; + mitk::InteractionEvent::MouseButtons GetButtonState(QMouseEvent* me) const; + mitk::InteractionEvent::ModifierKeys GetModifiers(QMouseEvent* me) const; + mitk::InteractionEvent::MouseButtons GetButtonState(QWheelEvent* we) const; + mitk::InteractionEvent::ModifierKeys GetModifiers(QWheelEvent* we) const; + mitk::InteractionEvent::ModifierKeys GetModifiers(QKeyEvent* ke) const; + std::string GetKeyLetter(QKeyEvent* ke) const; + int GetDelta(QWheelEvent* we) const; bool m_ResendQtEvents; QmitkRenderWindowMenu* m_MenuWidget; bool m_MenuWidgetActivated; unsigned int m_LayoutIndex; }; #endif diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp index 3c9d513986..87054f15a6 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPreprocessingView.cpp @@ -1,597 +1,595 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define MBILOG_ENABLE_DEBUG #include "QmitkPreprocessingView.h" #include "mitkDiffusionImagingConfigure.h" // qt includes #include // itk includes #include "itkTimeProbe.h" #include "itkB0ImageExtractionImageFilter.h" #include "itkB0ImageExtractionToSeparateImageFilter.h" #include "itkBrainMaskExtractionImageFilter.h" #include "itkCastImageFilter.h" #include "itkVectorContainer.h" #include #include // mitk includes #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkProgressBar.h" #include "mitkStatusBar.h" #include "mitkNodePredicateDataType.h" #include "mitkProperties.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include #include #include const std::string QmitkPreprocessingView::VIEW_ID = "org.mitk.views.preprocessing"; #define DI_INFO MITK_INFO("DiffusionImaging") typedef float TTensorPixelType; QmitkPreprocessingView::QmitkPreprocessingView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_DiffusionImage(NULL) { } QmitkPreprocessingView::QmitkPreprocessingView(const QmitkPreprocessingView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkPreprocessingView::~QmitkPreprocessingView() { } void QmitkPreprocessingView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkPreprocessingViewControls; m_Controls->setupUi(parent); this->CreateConnections(); m_Controls->m_MeasurementFrameTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); m_Controls->m_MeasurementFrameTable->verticalHeader()->setResizeMode(QHeaderView::Stretch); } } void QmitkPreprocessingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkPreprocessingView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkPreprocessingView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_ButtonAverageGradients), SIGNAL(clicked()), this, SLOT(AverageGradients()) ); connect( (QObject*)(m_Controls->m_ButtonExtractB0), SIGNAL(clicked()), this, SLOT(ExtractB0()) ); connect( (QObject*)(m_Controls->m_ModifyMeasurementFrame), SIGNAL(clicked()), this, SLOT(DoApplyMesurementFrame()) ); connect( (QObject*)(m_Controls->m_ReduceGradientsButton), SIGNAL(clicked()), this, SLOT(DoReduceGradientDirections()) ); connect( (QObject*)(m_Controls->m_ShowGradientsButton), SIGNAL(clicked()), this, SLOT(DoShowGradientDirections()) ); connect( (QObject*)(m_Controls->m_MirrorGradientToHalfSphereButton), SIGNAL(clicked()), this, SLOT(DoHalfSphereGradientDirections()) ); connect( (QObject*)(m_Controls->m_MergeDwisButton), SIGNAL(clicked()), this, SLOT(MergeDwis()) ); } } void QmitkPreprocessingView::OnSelectionChanged( std::vector nodes ) { bool foundDwiVolume = false; m_DiffusionImage = NULL; m_SelectedDiffusionNodes.clear(); // iterate selection for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast*>(node->GetData()) ) { foundDwiVolume = true; m_DiffusionImage = dynamic_cast*>(node->GetData()); m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); m_SelectedDiffusionNodes.push_back(node); } } m_Controls->m_ButtonAverageGradients->setEnabled(foundDwiVolume); m_Controls->m_ButtonExtractB0->setEnabled(foundDwiVolume); m_Controls->m_CheckExtractAll->setEnabled(foundDwiVolume); m_Controls->m_ModifyMeasurementFrame->setEnabled(foundDwiVolume); m_Controls->m_MeasurementFrameTable->setEnabled(foundDwiVolume); m_Controls->m_ReduceGradientsButton->setEnabled(foundDwiVolume); m_Controls->m_ShowGradientsButton->setEnabled(foundDwiVolume); m_Controls->m_MirrorGradientToHalfSphereButton->setEnabled(foundDwiVolume); m_Controls->m_MergeDwisButton->setEnabled(foundDwiVolume); foreach(QCheckBox * box, m_ReduceGradientCheckboxes) { m_Controls->m_ReductionFrame->layout()->removeWidget(box); delete box; } foreach(QSpinBox * box, m_ReduceGradientSpinboxes) { m_Controls->m_ReductionFrame->layout()->removeWidget(box); delete box; } m_ReduceGradientCheckboxes.clear(); m_ReduceGradientSpinboxes.clear(); if (foundDwiVolume) { m_Controls->m_InputData->setTitle("Input Data"); vnl_matrix_fixed< double, 3, 3 > mf = m_DiffusionImage->GetMeasurementFrame(); for (int r=0; r<3; r++) for (int c=0; c<3; c++) { QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); delete item; item = new QTableWidgetItem(); item->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter); item->setText(QString::number(mf.get(r,c))); m_Controls->m_MeasurementFrameTable->setItem(r,c,item); } typedef mitk::DiffusionImage::BValueMap BValueMap; typedef mitk::DiffusionImage::BValueMap::iterator BValueMapIterator; BValueMap bValMap = m_DiffusionImage->GetB_ValueMap(); BValueMapIterator it = bValMap.begin(); m_Controls->m_BvalueTable->clear(); m_Controls->m_BvalueTable->setRowCount(bValMap.size() ); QStringList headerList; headerList << "b-Value" << "Number of gradients"; m_Controls->m_BvalueTable->setHorizontalHeaderLabels(headerList); QCheckBox* checkBox; QSpinBox* spinBox; int i = 0 ; for(;it != bValMap.end(); it++) { m_Controls->m_BvalueTable->setItem(i,0,new QTableWidgetItem(QString::number(it->first))); m_Controls->m_BvalueTable->setItem(i,1,new QTableWidgetItem(QString::number(it->second.size()))); // Reduce Gradients GUI adaption if(it->first != 0 && bValMap.size() > 1){ checkBox = new QCheckBox(QString::number(it->first) + " with " + QString::number(it->second.size()) + " directions"); checkBox->setEnabled(true); checkBox->setChecked(true); checkBox->setCheckable(true); m_ReduceGradientCheckboxes.push_back(checkBox); m_Controls->m_ReductionFrame->layout()->addWidget(checkBox); spinBox = new QSpinBox(); spinBox->setValue(std::ceil((float)it->second.size()/2)); spinBox->setMaximum(it->second.size()); spinBox->setMinimum(0); m_ReduceGradientSpinboxes.push_back(spinBox); m_Controls->m_ReductionFrame->layout()->addWidget(spinBox); } i++; } } else { for (int r=0; r<3; r++) for (int c=0; c<3; c++) { QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); delete item; item = new QTableWidgetItem(); m_Controls->m_MeasurementFrameTable->setItem(r,c,item); } m_Controls->m_BvalueTable->clear(); m_Controls->m_BvalueTable->setRowCount(1); QStringList headerList; headerList << "b-Value" << "Number of gradients"; m_Controls->m_BvalueTable->setHorizontalHeaderLabels(headerList); m_Controls->m_BvalueTable->setItem(0,0,new QTableWidgetItem("-")); m_Controls->m_BvalueTable->setItem(0,1,new QTableWidgetItem("-")); m_Controls->m_DiffusionImageLabel->setText("mandatory"); m_Controls->m_InputData->setTitle("Please Select Input Data"); } } void QmitkPreprocessingView::Activated() { QmitkFunctionality::Activated(); } void QmitkPreprocessingView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkPreprocessingView::DoHalfSphereGradientDirections() { GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetDirections(); for (int j=0; jSize(); j++) if (gradientContainer->at(j)[0]<0) gradientContainer->at(j) = -gradientContainer->at(j); m_DiffusionImage->SetDirections(gradientContainer); } void QmitkPreprocessingView::DoApplyMesurementFrame() { if (m_DiffusionImage.IsNull()) return; vnl_matrix_fixed< double, 3, 3 > mf; for (int r=0; r<3; r++) for (int c=0; c<3; c++) { QTableWidgetItem* item = m_Controls->m_MeasurementFrameTable->item(r,c); if (!item) return; mf[r][c] = item->text().toDouble(); } m_DiffusionImage->SetMeasurementFrame(mf); } void QmitkPreprocessingView::DoShowGradientDirections() { if (m_DiffusionImage.IsNull()) return; int maxIndex = 0; int maxSize = m_DiffusionImage->GetDimension(0); if (maxSizeGetDimension(1)) { maxSize = m_DiffusionImage->GetDimension(1); maxIndex = 1; } if (maxSizeGetDimension(2)) { maxSize = m_DiffusionImage->GetDimension(2); maxIndex = 2; } mitk::Point3D origin = m_DiffusionImage->GetGeometry()->GetOrigin(); mitk::PointSet::Pointer originSet = mitk::PointSet::New(); typedef mitk::DiffusionImage::BValueMap BValueMap; typedef mitk::DiffusionImage::BValueMap::iterator BValueMapIterator; BValueMap bValMap = m_DiffusionImage->GetB_ValueMap(); GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetDirections(); mitk::Geometry3D::Pointer geometry = m_DiffusionImage->GetGeometry(); int shellCount = 1; for(BValueMapIterator it = bValMap.begin(); it!=bValMap.end(); ++it) { mitk::PointSet::Pointer pointset = mitk::PointSet::New(); for (int j=0; jsecond.size(); j++) { mitk::Point3D ip; vnl_vector_fixed< double, 3 > v = gradientContainer->at(it->second[j]); if (v.magnitude()>mitk::eps) { ip[0] = v[0]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[0]-0.5*geometry->GetSpacing()[0] + geometry->GetSpacing()[0]*m_DiffusionImage->GetDimension(0)/2; ip[1] = v[1]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[1]-0.5*geometry->GetSpacing()[1] + geometry->GetSpacing()[1]*m_DiffusionImage->GetDimension(1)/2; ip[2] = v[2]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[2]-0.5*geometry->GetSpacing()[2] + geometry->GetSpacing()[2]*m_DiffusionImage->GetDimension(2)/2; pointset->InsertPoint(j, ip); } else if (originSet->IsEmpty()) { ip[0] = v[0]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[0]-0.5*geometry->GetSpacing()[0] + geometry->GetSpacing()[0]*m_DiffusionImage->GetDimension(0)/2; ip[1] = v[1]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[1]-0.5*geometry->GetSpacing()[1] + geometry->GetSpacing()[1]*m_DiffusionImage->GetDimension(1)/2; ip[2] = v[2]*maxSize*geometry->GetSpacing()[maxIndex]/2 + origin[2]-0.5*geometry->GetSpacing()[2] + geometry->GetSpacing()[2]*m_DiffusionImage->GetDimension(2)/2; originSet->InsertPoint(j, ip); } } if (it->firstSetData(pointset); QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); name += "_Shell_"; name += QString::number(it->first); node->SetName(name.toStdString().c_str()); node->SetProperty("pointsize", mitk::FloatProperty::New((float)maxSize/50)); int b0 = shellCount%2; int b1 = 0; int b2 = 0; if (shellCount>4) b2 = 1; if (shellCount%4 >= 2) b1 = 1; node->SetProperty("color", mitk::ColorProperty::New(b2, b1, b0)); GetDefaultDataStorage()->Add(node, m_SelectedDiffusionNodes.front()); shellCount++; } // add origin to datastorage mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(originSet); QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); name += "_Origin"; node->SetName(name.toStdString().c_str()); node->SetProperty("pointsize", mitk::FloatProperty::New((float)maxSize/50)); node->SetProperty("color", mitk::ColorProperty::New(1,1,1)); GetDefaultDataStorage()->Add(node, m_SelectedDiffusionNodes.front()); } void QmitkPreprocessingView::DoReduceGradientDirections() { if (m_DiffusionImage.IsNull()) return; typedef mitk::DiffusionImage DiffusionImageType; typedef itk::ElectrostaticRepulsionDiffusionGradientReductionFilter FilterType; typedef DiffusionImageType::BValueMap BValueMap; // GetShellSelection from GUI BValueMap shellSlectionMap; BValueMap originalShellMap = m_DiffusionImage->GetB_ValueMap(); std::vector newNumGradientDirections; int shellCounter = 0; foreach(QCheckBox * box , m_ReduceGradientCheckboxes) { if(box->isChecked()) { double BValue = (box->text().split(' ')).at(0).toDouble(); shellSlectionMap[BValue] = originalShellMap[BValue]; newNumGradientDirections.push_back(m_ReduceGradientSpinboxes.at(shellCounter)->value()); } shellCounter++; } if (newNumGradientDirections.empty()) return; GradientDirectionContainerType::Pointer gradientContainer = m_DiffusionImage->GetDirections(); FilterType::Pointer filter = FilterType::New(); filter->SetInput(m_DiffusionImage->GetVectorImage()); filter->SetOriginalGradientDirections(gradientContainer); filter->SetNumGradientDirections(newNumGradientDirections); filter->SetOriginalBValueMap(originalShellMap); filter->SetShellSelectionBValueMap(shellSlectionMap); filter->Update(); DiffusionImageType::Pointer image = DiffusionImageType::New(); image->SetVectorImage( filter->GetOutput() ); image->SetB_Value(m_DiffusionImage->GetB_Value()); image->SetDirections(filter->GetGradientDirections()); image->SetMeasurementFrame(m_DiffusionImage->GetMeasurementFrame()); image->InitializeFromVectorImage(); mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); imageNode->SetData( image ); QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); foreach(QSpinBox* box, m_ReduceGradientSpinboxes) { name += "_"; name += QString::number(box->value()); } imageNode->SetName(name.toStdString().c_str()); GetDefaultDataStorage()->Add(imageNode); } void QmitkPreprocessingView::MergeDwis() { typedef mitk::DiffusionImage DiffusionImageType; typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; if (m_SelectedDiffusionNodes.size()<2) return; typedef itk::VectorImage DwiImageType; typedef DwiImageType::PixelType DwiPixelType; typedef DwiImageType::RegionType DwiRegionType; typedef std::vector< DwiImageType::Pointer > DwiImageContainerType; typedef std::vector< GradientContainerType::Pointer > GradientListContainerType; DwiImageContainerType imageContainer; GradientListContainerType gradientListContainer; std::vector< double > bValueContainer; + QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); for (int i=0; i* >( m_SelectedDiffusionNodes.at(i)->GetData() ); if ( dwi.IsNotNull() ) { imageContainer.push_back(dwi->GetVectorImage()); gradientListContainer.push_back(dwi->GetDirections()); bValueContainer.push_back(dwi->GetB_Value()); + if (i>0) + { + name += "+"; + name += m_SelectedDiffusionNodes.at(i)->GetName().c_str(); + } } } typedef itk::MergeDiffusionImagesFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetImageVolumes(imageContainer); filter->SetGradientLists(gradientListContainer); filter->SetBValues(bValueContainer); filter->Update(); vnl_matrix_fixed< double, 3, 3 > mf; mf.set_identity(); DiffusionImageType::Pointer image = DiffusionImageType::New(); image->SetVectorImage( filter->GetOutput() ); image->SetB_Value(filter->GetB_Value()); image->SetDirections(filter->GetOutputGradients()); image->SetMeasurementFrame(mf); image->InitializeFromVectorImage(); mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); imageNode->SetData( image ); - QString name = m_SelectedDiffusionNodes.front()->GetName().c_str(); - - for (int i=0; iSetName(name.toStdString().c_str()); GetDefaultDataStorage()->Add(imageNode); } void QmitkPreprocessingView::ExtractB0() { typedef mitk::DiffusionImage DiffusionImageType; typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; int nrFiles = m_SelectedDiffusionNodes.size(); if (!nrFiles) return; // call the extraction withou averaging if the check-box is checked if( this->m_Controls->m_CheckExtractAll->isChecked() ) { DoExtractBOWithoutAveraging(); return; } mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { DiffusionImageType* vols = static_cast( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // Extract image using found index typedef itk::B0ImageExtractionImageFilter FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput(vols->GetVectorImage()); filter->SetDirections(vols->GetDirections()); filter->Update(); mitk::Image::Pointer mitkImage = mitk::Image::New(); mitkImage->InitializeByItk( filter->GetOutput() ); mitkImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( mitkImage ); node->SetProperty( "name", mitk::StringProperty::New(nodename + "_B0")); GetDefaultDataStorage()->Add(node); ++itemiter; } } void QmitkPreprocessingView::DoExtractBOWithoutAveraging() { // typedefs typedef mitk::DiffusionImage DiffusionImageType; typedef DiffusionImageType::GradientDirectionContainerType GradientContainerType; typedef itk::B0ImageExtractionToSeparateImageFilter< short, short> FilterType; // check number of selected objects, return if empty int nrFiles = m_SelectedDiffusionNodes.size(); if (!nrFiles) return; mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); while ( itemiter != itemiterend ) // for all items { DiffusionImageType* vols = static_cast( (*itemiter)->GetData()); std::string nodename; (*itemiter)->GetStringProperty("name", nodename); // Extract image using found index FilterType::Pointer filter = FilterType::New(); filter->SetInput(vols->GetVectorImage()); filter->SetDirections(vols->GetDirections()); filter->Update(); mitk::Image::Pointer mitkImage = mitk::Image::New(); mitkImage->InitializeByItk( filter->GetOutput() ); mitkImage->SetImportChannel( filter->GetOutput()->GetBufferPointer() ); mitk::DataNode::Pointer node=mitk::DataNode::New(); node->SetData( mitkImage ); node->SetProperty( "name", mitk::StringProperty::New(nodename + "_B0_ALL")); GetDefaultDataStorage()->Add(node); ++itemiter; } } void QmitkPreprocessingView::AverageGradients() { int nrFiles = m_SelectedDiffusionNodes.size(); if (!nrFiles) return; mitk::DataStorage::SetOfObjects::const_iterator itemiter( m_SelectedDiffusionNodes.begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( m_SelectedDiffusionNodes.end() ); std::vector nodes; while ( itemiter != itemiterend ) // for all items { mitk::DiffusionImage* vols = static_cast*>( (*itemiter)->GetData()); vols->AverageRedundantGradients(m_Controls->m_Blur->value()); ++itemiter; } }