diff --git a/CMake/PackageDepends/MITK_ITK_Config.cmake b/CMake/PackageDepends/MITK_ITK_Config.cmake index d70f9f42ec..5089845848 100644 --- a/CMake/PackageDepends/MITK_ITK_Config.cmake +++ b/CMake/PackageDepends/MITK_ITK_Config.cmake @@ -1,18 +1,19 @@ FIND_PACKAGE(ITK REQUIRED) # # for some reason this does not work on windows, probably an ITK bug # ITK_BUILD_SHARED is OFF even in shared library builds # #IF(ITK_FOUND AND NOT ITK_BUILD_SHARED) # MESSAGE(FATAL_ERROR "MITK only supports a ITK which was built with shared libraries. Turn on BUILD_SHARED_LIBS in your ITK config.") #ENDIF(ITK_FOUND AND NOT ITK_BUILD_SHARED) INCLUDE(${ITK_USE_FILE}) LIST(APPEND ALL_LIBRARIES ${ITK_LIBRARIES}) LIST(APPEND ALL_INCLUDE_DIRECTORIES ${ITK_INCLUDE_DIRS}) IF(ITK_USE_SYSTEM_GDCM) FIND_PACKAGE(GDCM PATHS ${ITK_GDCM_DIR} REQUIRED) + LIST(APPEND ALL_INCLUDE_DIRECTORIES ${GDCM_INCLUDE_DIRS}) LIST(APPEND ALL_LIBRARIES ${GDCM_LIBRARIES}) ENDIF(ITK_USE_SYSTEM_GDCM) diff --git a/CMake/mitkFunctionCheckC++0xHashSizeT.cmake b/CMake/mitkFunctionCheckC++0xHashSizeT.cmake new file mode 100644 index 0000000000..a93f8c7826 --- /dev/null +++ b/CMake/mitkFunctionCheckC++0xHashSizeT.cmake @@ -0,0 +1,13 @@ + +function(mitkFunctionCheckCxx0xHashSizeT var_has_feature) + + CHECK_CXX_SOURCE_COMPILES( + " + #include + int main() { std::hash h; return 0; } + " + ${var_has_feature} + ) + + set(${var_has_feature} "${${var_has_feature}}" PARENT_SCOPE) +endfunction() diff --git a/CMake/mitkFunctionCheckC++0xHashString.cmake b/CMake/mitkFunctionCheckC++0xHashString.cmake new file mode 100644 index 0000000000..09648943e3 --- /dev/null +++ b/CMake/mitkFunctionCheckC++0xHashString.cmake @@ -0,0 +1,14 @@ + +function(mitkFunctionCheckCxx0xHashString var_has_feature) + + CHECK_CXX_SOURCE_COMPILES( + " + #include + #include + int main() { std::hash h; return 0; } + " + ${var_has_feature} + ) + + set(${var_has_feature} "${${var_has_feature}}" PARENT_SCOPE) +endfunction() diff --git a/CMake/mitkFunctionCheckC++0xUnorderedMap.cmake b/CMake/mitkFunctionCheckC++0xUnorderedMap.cmake new file mode 100644 index 0000000000..04614d2578 --- /dev/null +++ b/CMake/mitkFunctionCheckC++0xUnorderedMap.cmake @@ -0,0 +1,13 @@ + +function(mitkFunctionCheckCxx0xUnorderedMap var_has_feature) + + CHECK_CXX_SOURCE_COMPILES( + " + #include + int main() { std::unordered_map um; return 0; } + " + ${var_has_feature} + ) + + set(${var_has_feature} "${${var_has_feature}}" PARENT_SCOPE) +endfunction() diff --git a/CMake/mitkFunctionCheckC++0xUnorderedSet.cmake b/CMake/mitkFunctionCheckC++0xUnorderedSet.cmake new file mode 100644 index 0000000000..678805136a --- /dev/null +++ b/CMake/mitkFunctionCheckC++0xUnorderedSet.cmake @@ -0,0 +1,13 @@ + +function(mitkFunctionCheckCxx0xUnorderedSet var_has_feature) + + CHECK_CXX_SOURCE_COMPILES( + " + #include + int main() { std::unordered_set us; return 0; } + " + ${var_has_feature} + ) + + set(${var_has_feature} "${${var_has_feature}}" PARENT_SCOPE) +endfunction() diff --git a/CMake/mitkFunctionCheckItkHashSizeT.cmake b/CMake/mitkFunctionCheckItkHashSizeT.cmake new file mode 100644 index 0000000000..ab7378d21f --- /dev/null +++ b/CMake/mitkFunctionCheckItkHashSizeT.cmake @@ -0,0 +1,13 @@ + +function(mitkFunctionCheckItkHashSizeT var_has_feature) + + CHECK_CXX_SOURCE_COMPILES( + " + #include + int main() { itk::hash h; return 0; } + " + ${var_has_feature} + ) + + set(${var_has_feature} "${${var_has_feature}}" PARENT_SCOPE) +endfunction() diff --git a/CMake/mitkFunctionCheckItkHashString.cmake b/CMake/mitkFunctionCheckItkHashString.cmake new file mode 100644 index 0000000000..9eb5bc813a --- /dev/null +++ b/CMake/mitkFunctionCheckItkHashString.cmake @@ -0,0 +1,14 @@ + +function(mitkFunctionCheckItkHashString var_has_feature) + + CHECK_CXX_SOURCE_COMPILES( + " + #include + #include + int main() { itk::hash h; return 0; } + " + ${var_has_feature} + ) + + set(${var_has_feature} "${${var_has_feature}}" PARENT_SCOPE) +endfunction() diff --git a/CMake/mitkFunctionCompileSnippets.cmake b/CMake/mitkFunctionCompileSnippets.cmake new file mode 100644 index 0000000000..e65d3036d9 --- /dev/null +++ b/CMake/mitkFunctionCompileSnippets.cmake @@ -0,0 +1,38 @@ +function(mitkFunctionCompileSnippets snippet_path) + + # get all files called "main.cpp" + file(GLOB_RECURSE main_cpp_list "${snippet_path}/main.cpp") + + foreach(main_cpp_file ${main_cpp_list}) + # get the directory containing the main.cpp file + get_filename_component(main_cpp_dir "${main_cpp_file}" PATH) + + set(snippet_src_files ) + + # If there exists a "files.cmake" file in the snippet directory, + # include it and assume it sets the variable "snippet_src_files" + # to a list of source files for the snippet. + if(EXISTS "${main_cpp_dir}/files.cmake") + include("${main_cpp_dir}/files.cmake") + else() + # glob all files in the directory and add them to the snippet src list + file(GLOB_RECURSE snippet_src_files "${main_cpp_dir}/*") + endif() + + # Uset the top-level directory name as the executable name + string(REPLACE "/" ";" main_cpp_dir_tokens "${main_cpp_dir}") + list(GET main_cpp_dir_tokens -1 snippet_exec_name) + set(snippet_target_name "Snippet/${snippet_exec_name}") + add_executable(${snippet_target_name} ${snippet_src_files}) + if(ARGN) + target_link_libraries(${snippet_target_name} ${ARGN}) + endif() + set_target_properties(${snippet_target_name} PROPERTIES + LABELS Documentation + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/snippets" + OUTPUT_NAME ${snippet_exec_name} + ) + + endforeach() + +endfunction() diff --git a/CMake/mitkMacroCreateModule.cmake b/CMake/mitkMacroCreateModule.cmake index 3d904551ed..d8d77972e9 100644 --- a/CMake/mitkMacroCreateModule.cmake +++ b/CMake/mitkMacroCreateModule.cmake @@ -1,238 +1,267 @@ ################################################################## # # MITK_CREATE_MODULE # #! Creates a module for the automatic module dependency system within MITK. #! Configurations are generated in the moduleConf directory. #! #! USAGE: #! #! \code #! MITK_CREATE_MODULE( #! [INCLUDE_DIRS ] #! [INTERNAL_INCLUDE_DIRS ] #! [DEPENDS ] #! [PACKAGE_DEPENDS ] #! [TARGET_DEPENDS #! [EXPORT_DEFINE ] #! [QT_MODULE] #! \endcode #! #! \param MODULE_NAME_IN The name for the new module # ################################################################## MACRO(MITK_CREATE_MODULE MODULE_NAME_IN) MACRO_PARSE_ARGUMENTS(MODULE - "SUBPROJECTS;INCLUDE_DIRS;INTERNAL_INCLUDE_DIRS;DEPENDS;DEPENDS_INTERNAL;PACKAGE_DEPENDS;TARGET_DEPENDS;EXPORT_DEFINE;ADDITIONAL_LIBS;GENERATED_CPP" - "QT_MODULE;FORCE_STATIC;HEADERS_ONLY;GCC_DEFAULT_VISIBILITY" + "SUBPROJECTS;VERSION;INCLUDE_DIRS;INTERNAL_INCLUDE_DIRS;DEPENDS;DEPENDS_INTERNAL;PACKAGE_DEPENDS;TARGET_DEPENDS;EXPORT_DEFINE;ADDITIONAL_LIBS;GENERATED_CPP" + "QT_MODULE;FORCE_STATIC;HEADERS_ONLY;GCC_DEFAULT_VISIBILITY;NO_INIT" ${ARGN}) SET(MODULE_NAME ${MODULE_NAME_IN}) IF(MODULE_HEADERS_ONLY) SET(MODULE_PROVIDES ) ELSE() SET(MODULE_PROVIDES ${MODULE_NAME}) ENDIF() IF(NOT MODULE_SUBPROJECTS) IF(MITK_DEFAULT_SUBPROJECTS) SET(MODULE_SUBPROJECTS ${MITK_DEFAULT_SUBPROJECTS}) ENDIF() ENDIF() # check if the subprojects exist as targets IF(MODULE_SUBPROJECTS) FOREACH(subproject ${MODULE_SUBPROJECTS}) IF(NOT TARGET ${subproject}) MESSAGE(SEND_ERROR "The subproject ${subproject} does not have a corresponding target") ENDIF() ENDFOREACH() ENDIF() # assume worst case SET(MODULE_IS_ENABLED 0) # first we check if we have an explicit module build list IF(MITK_MODULES_TO_BUILD) LIST(FIND MITK_MODULES_TO_BUILD ${MODULE_NAME} _MOD_INDEX) IF(_MOD_INDEX EQUAL -1) SET(MODULE_IS_EXCLUDED 1) ENDIF() ENDIF() IF(NOT MODULE_IS_EXCLUDED) # first of all we check for the dependencies MITK_CHECK_MODULE(_MISSING_DEP ${MODULE_DEPENDS}) IF(_MISSING_DEP) MESSAGE("Module ${MODULE_NAME} won't be built, missing dependency: ${_MISSING_DEP}") SET(MODULE_IS_ENABLED 0) ELSE(_MISSING_DEP) SET(MODULE_IS_ENABLED 1) # now check for every package if it is enabled. This overlaps a bit with # MITK_CHECK_MODULE ... FOREACH(_package ${MODULE_PACKAGE_DEPENDS}) - IF((DEFINED MITK_USE_${_package}) AND NOT (MITK_USE_${_package})) - MESSAGE("Module ${MODULE_NAME} won't be built. Turn on MITK_USE_${_package} if you want to use it.") - SET(MODULE_IS_ENABLED 0) - ENDIF() + IF((DEFINED MITK_USE_${_package}) AND NOT (MITK_USE_${_package})) + MESSAGE("Module ${MODULE_NAME} won't be built. Turn on MITK_USE_${_package} if you want to use it.") + SET(MODULE_IS_ENABLED 0) + ENDIF() ENDFOREACH() IF(MODULE_IS_ENABLED) - IF(NOT MODULE_QT_MODULE OR MITK_USE_QT) - SET(MODULE_IS_ENABLED 1) - _MITK_CREATE_MODULE_CONF() - IF(NOT MODULE_EXPORT_DEFINE) - SET(MODULE_EXPORT_DEFINE ${MODULE_NAME}_EXPORT) - ENDIF(NOT MODULE_EXPORT_DEFINE) - CONFIGURE_FILE(${MITK_SOURCE_DIR}/CMake/moduleExports.h.in ${MITK_MODULES_CONF_DIR}/${MODULE_NAME}Exports.h @ONLY) - IF(MITK_GENERATE_MODULE_DOT) - MESSAGE("MODULEDOTNAME ${MODULE_NAME}") - FOREACH(dep ${MODULE_DEPENDS}) - MESSAGE("MODULEDOT \"${MODULE_NAME}\" -> \"${dep}\" ; ") - ENDFOREACH(dep) - ENDIF(MITK_GENERATE_MODULE_DOT) - - SET(DEPENDS "${MODULE_DEPENDS}") - SET(DEPENDS_BEFORE "not initialized") - SET(PACKAGE_DEPENDS "${MODULE_PACKAGE_DEPENDS}") - MITK_USE_MODULE("${MODULE_DEPENDS}") - - # ok, now create the module itself - INCLUDE_DIRECTORIES(. ${ALL_INCLUDE_DIRECTORIES}) - INCLUDE(files.cmake) - - SET(module_compile_flags ) - # MinGW does not export all symbols automatically, so no need to set flags - IF(CMAKE_COMPILER_IS_GNUCXX AND NOT MINGW AND NOT MODULE_GCC_DEFAULT_VISIBILITY) - IF(${GCC_VERSION} VERSION_GREATER "4.5.0") - # With gcc < 4.5, type_info objects need special care. Especially exceptions - # and inline definitions of classes from 3rd party libraries would need - # to be wrapped with pragma GCC visibility statements if the library is not - # prepared to handle hidden visibility. This would need too many changes in - # MITK and would be too fragile. - SET(module_compile_flags "${module_compile_flags} -fvisibility=hidden -fvisibility-inlines-hidden") - ENDIF() - ENDIF() - - IF(NOT MODULE_QT_MODULE) - ORGANIZE_SOURCES(SOURCE ${CPP_FILES} - HEADER ${H_FILES} - TXX ${TXX_FILES} - DOC ${DOX_FILES} - ) - - IF(MODULE_FORCE_STATIC) + IF(NOT MODULE_QT_MODULE OR MITK_USE_QT) + SET(MODULE_IS_ENABLED 1) + _MITK_CREATE_MODULE_CONF() + IF(NOT MODULE_EXPORT_DEFINE) + SET(MODULE_EXPORT_DEFINE ${MODULE_NAME}_EXPORT) + ENDIF(NOT MODULE_EXPORT_DEFINE) + CONFIGURE_FILE(${MITK_SOURCE_DIR}/CMake/moduleExports.h.in ${MITK_MODULES_CONF_DIR}/${MODULE_NAME}Exports.h @ONLY) + + IF(MITK_GENERATE_MODULE_DOT) + MESSAGE("MODULEDOTNAME ${MODULE_NAME}") + FOREACH(dep ${MODULE_DEPENDS}) + MESSAGE("MODULEDOT \"${MODULE_NAME}\" -> \"${dep}\" ; ") + ENDFOREACH(dep) + ENDIF(MITK_GENERATE_MODULE_DOT) + + IF(NOT MODULE_NO_INIT) + # Create variables of the ModuleInfo object, created in CMake/mitkModuleInit.cpp + SET(MODULE_LIBNAME ${MODULE_PROVIDES}) + SET(MODULE_DEPENDS_STR "") + FOREACH(_dep ${MODULE_DEPENDS} ${MODULE_DEPENDS_INTERNAL}) + SET(MODULE_DEPENDS_STR "${MODULE_DEPENDS_STR} ${_dep}") + ENDFOREACH() + SET(MODULE_PACKAGE_DEPENDS_STR "") + FOREACH(_dep ${MODULE_PACKAGE_DEPENDS}) + SET(MODULE_PACKAGE_DEPENDS_STR "${MODULE_PACKAGE_DEPENDS_STR} ${_dep}") + ENDFOREACH() + IF(MODULE_QT_MODULE) + SET(MODULE_QT_BOOL "true") + ELSE() + SET(MODULE_QT_BOOL "false") + ENDIF() + SET(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_NAME}_init.cpp") + CONFIGURE_FILE(${MITK_SOURCE_DIR}/CMake/mitkModuleInit.cpp ${module_init_src_file} @ONLY) + ENDIF() + + SET(DEPENDS "${MODULE_DEPENDS}") + SET(DEPENDS_BEFORE "not initialized") + SET(PACKAGE_DEPENDS "${MODULE_PACKAGE_DEPENDS}") + MITK_USE_MODULE("${MODULE_DEPENDS}") + + # ok, now create the module itself + INCLUDE_DIRECTORIES(. ${ALL_INCLUDE_DIRECTORIES}) + INCLUDE(files.cmake) + + SET(module_compile_flags ) + # MinGW does not export all symbols automatically, so no need to set flags + IF(CMAKE_COMPILER_IS_GNUCXX AND NOT MINGW AND NOT MODULE_GCC_DEFAULT_VISIBILITY) + IF(${GCC_VERSION} VERSION_GREATER "4.5.0") + # With gcc < 4.5, type_info objects need special care. Especially exceptions + # and inline definitions of classes from 3rd party libraries would need + # to be wrapped with pragma GCC visibility statements if the library is not + # prepared to handle hidden visibility. This would need too many changes in + # MITK and would be too fragile. + SET(module_compile_flags "${module_compile_flags} -fvisibility=hidden -fvisibility-inlines-hidden") + ENDIF() + ENDIF() + + IF(NOT MODULE_NO_INIT) + LIST(APPEND CPP_FILES ${module_init_src_file}) + ENDIF() + + IF(NOT MODULE_QT_MODULE) + ORGANIZE_SOURCES(SOURCE ${CPP_FILES} + HEADER ${H_FILES} + TXX ${TXX_FILES} + DOC ${DOX_FILES} + ) + + IF(MODULE_FORCE_STATIC) SET(_STATIC STATIC) ELSE() SET(_STATIC ) - ENDIF(MODULE_FORCE_STATIC) - - SET(coverage_sources ${CPP_FILES} ${H_FILES} ${GLOBBED__H_FILES} ${CORRESPONDING__H_FILES} ${TXX_FILES} ${TOOL_CPPS}) - IF(MODULE_SUBPROJECTS) - SET_PROPERTY(SOURCE ${coverage_sources} APPEND PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) - ENDIF() - - IF(NOT MODULE_HEADERS_ONLY) - IF(ALL_LIBRARY_DIRS) - # LINK_DIRECTORIES applies only to targets which are added after the call to LINK_DIRECTORIES - LINK_DIRECTORIES(${ALL_LIBRARY_DIRS}) - ENDIF(ALL_LIBRARY_DIRS) + ENDIF(MODULE_FORCE_STATIC) + + SET(coverage_sources ${CPP_FILES} ${H_FILES} ${GLOBBED__H_FILES} ${CORRESPONDING__H_FILES} ${TXX_FILES} ${TOOL_CPPS}) + IF(MODULE_SUBPROJECTS) + SET_PROPERTY(SOURCE ${coverage_sources} APPEND PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) + ENDIF() + + IF(NOT MODULE_HEADERS_ONLY) + IF(ALL_LIBRARY_DIRS) + # LINK_DIRECTORIES applies only to targets which are added after the call to LINK_DIRECTORIES + LINK_DIRECTORIES(${ALL_LIBRARY_DIRS}) + ENDIF(ALL_LIBRARY_DIRS) ADD_LIBRARY(${MODULE_PROVIDES} ${_STATIC} ${coverage_sources} ${CPP_FILES_GENERATED} ${DOX_FILES} ${UI_FILES}) - IF(MODULE_TARGET_DEPENDS) - ADD_DEPENDENCIES(${MODULE_PROVIDES} ${MODULE_TARGET_DEPENDS}) - ENDIF() - IF(MODULE_SUBPROJECTS) - SET_PROPERTY(TARGET ${MODULE_PROVIDES} PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) - FOREACH(subproject ${MODULE_SUBPROJECTS}) - ADD_DEPENDENCIES(${subproject} ${MODULE_PROVIDES}) - ENDFOREACH() - ENDIF() - IF(ALL_LIBRARIES) - TARGET_LINK_LIBRARIES(${MODULE_PROVIDES} ${ALL_LIBRARIES}) - ENDIF(ALL_LIBRARIES) - - IF(MINGW) - TARGET_LINK_LIBRARIES(${MODULE_PROVIDES} ssp) # add stack smash protection lib - ENDIF() - ENDIF() - - ELSE(NOT MODULE_QT_MODULE) + IF(MODULE_TARGET_DEPENDS) + ADD_DEPENDENCIES(${MODULE_PROVIDES} ${MODULE_TARGET_DEPENDS}) + ENDIF() + IF(MODULE_SUBPROJECTS) + SET_PROPERTY(TARGET ${MODULE_PROVIDES} PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) + FOREACH(subproject ${MODULE_SUBPROJECTS}) + ADD_DEPENDENCIES(${subproject} ${MODULE_PROVIDES}) + ENDFOREACH() + ENDIF() + IF(ALL_LIBRARIES) + TARGET_LINK_LIBRARIES(${MODULE_PROVIDES} ${ALL_LIBRARIES}) + ENDIF(ALL_LIBRARIES) - INCLUDE(files.cmake) - - IF(UI_FILES) - QT4_WRAP_UI(Q${KITNAME}_GENERATED_UI_CPP ${UI_FILES}) - ENDIF(UI_FILES) - - IF(MOC_H_FILES) - QT4_WRAP_CPP(Q${KITNAME}_GENERATED_MOC_CPP ${MOC_H_FILES}) - ENDIF(MOC_H_FILES) - - IF(QRC_FILES) - QT4_ADD_RESOURCES(Q${KITNAME}_GENERATED_QRC_CPP ${QRC_FILES}) - ENDIF(QRC_FILES) - - SET(Q${KITNAME}_GENERATED_CPP ${Q${KITNAME}_GENERATED_CPP} ${Q${KITNAME}_GENERATED_UI_CPP} ${Q${KITNAME}_GENERATED_MOC_CPP} ${Q${KITNAME}_GENERATED_QRC_CPP}) - - ORGANIZE_SOURCES(SOURCE ${CPP_FILES} - HEADER ${H_FILES} - TXX ${TXX_FILES} - DOC ${DOX_FILES} - UI ${UI_FILES} - QRC ${QRC_FILES} - MOC ${Q${KITNAME}_GENERATED_MOC_CPP} - GEN_QRC ${Q${KITNAME}_GENERATED_QRC_CPP} - GEN_UI ${Q${KITNAME}_GENERATED_UI_CPP}) - - # MITK_GENERATE_TOOLS_LIBRARY(Qmitk${LIBPOSTFIX} "NO") - - SET(coverage_sources ${CPP_FILES} ${CORRESPONDING__H_FILES} ${GLOBBED__H_FILES} ${TXX_FILES} ${TOOL_GUI_CPPS}) - SET_PROPERTY(SOURCE ${coverage_sources} APPEND PROPERTY LABELS ${MODULE_SUBPROJECTS}) - - IF(NOT MODULE_HEADERS_ONLY) - IF(ALL_LIBRARY_DIRS) - # LINK_DIRECTORIES applies only to targets which are added after the call to LINK_DIRECTORIES - LINK_DIRECTORIES(${ALL_LIBRARY_DIRS}) - ENDIF(ALL_LIBRARY_DIRS) - ADD_LIBRARY(${MODULE_PROVIDES} ${coverage_sources} ${CPP_FILES_GENERATED} ${Q${KITNAME}_GENERATED_CPP} ${DOX_FILES} ${UI_FILES} ${QRC_FILES}) - TARGET_LINK_LIBRARIES(${MODULE_PROVIDES} ${QT_LIBRARIES} ${ALL_LIBRARIES} QVTK) - IF(MODULE_TARGET_DEPENDS) - ADD_DEPENDENCIES(${MODULE_PROVIDES} ${MODULE_TARGET_DEPENDS}) - ENDIF() - IF(MINGW) - TARGET_LINK_LIBRARIES(${MODULE_PROVIDES} ssp) # add stack smash protection lib - ENDIF() - IF(MODULE_SUBPROJECTS) - SET_PROPERTY(TARGET ${MODULE_PROVIDES} PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) - FOREACH(subproject ${MODULE_SUBPROJECTS}) - ADD_DEPENDENCIES(${subproject} ${MODULE_PROVIDES}) - ENDFOREACH() - ENDIF() - ENDIF() - - ENDIF(NOT MODULE_QT_MODULE) + IF(MINGW) + TARGET_LINK_LIBRARIES(${MODULE_PROVIDES} ssp) # add stack smash protection lib + ENDIF() + ENDIF() - IF(NOT MODULE_HEADERS_ONLY) - # Apply properties to the module target. - SET_TARGET_PROPERTIES(${MODULE_PROVIDES} PROPERTIES - COMPILE_FLAGS "${module_compile_flags}" - ) - ENDIF() + ELSE(NOT MODULE_QT_MODULE) + + INCLUDE(files.cmake) + IF(NOT MODULE_NO_INIT) + LIST(APPEND CPP_FILES ${module_init_src_file}) + ENDIF() + + IF(UI_FILES) + QT4_WRAP_UI(Q${KITNAME}_GENERATED_UI_CPP ${UI_FILES}) + ENDIF(UI_FILES) + + IF(MOC_H_FILES) + QT4_WRAP_CPP(Q${KITNAME}_GENERATED_MOC_CPP ${MOC_H_FILES}) + ENDIF(MOC_H_FILES) + + IF(QRC_FILES) + QT4_ADD_RESOURCES(Q${KITNAME}_GENERATED_QRC_CPP ${QRC_FILES}) + ENDIF(QRC_FILES) - # install only if shared lib (for now) - IF(NOT _STATIC OR MINGW) - IF(NOT MODULE_HEADERS_ONLY) - # # deprecated: MITK_INSTALL_TARGETS(${MODULE_PROVIDES}) - ENDIF() - ENDIF(NOT _STATIC OR MINGW) - - ENDIF(NOT MODULE_QT_MODULE OR MITK_USE_QT) + SET(Q${KITNAME}_GENERATED_CPP ${Q${KITNAME}_GENERATED_CPP} ${Q${KITNAME}_GENERATED_UI_CPP} ${Q${KITNAME}_GENERATED_MOC_CPP} ${Q${KITNAME}_GENERATED_QRC_CPP}) + + ORGANIZE_SOURCES(SOURCE ${CPP_FILES} + HEADER ${H_FILES} + TXX ${TXX_FILES} + DOC ${DOX_FILES} + UI ${UI_FILES} + QRC ${QRC_FILES} + MOC ${Q${KITNAME}_GENERATED_MOC_CPP} + GEN_QRC ${Q${KITNAME}_GENERATED_QRC_CPP} + GEN_UI ${Q${KITNAME}_GENERATED_UI_CPP}) + + # MITK_GENERATE_TOOLS_LIBRARY(Qmitk${LIBPOSTFIX} "NO") + + SET(coverage_sources ${CPP_FILES} ${CORRESPONDING__H_FILES} ${GLOBBED__H_FILES} ${TXX_FILES} ${TOOL_GUI_CPPS}) + SET_PROPERTY(SOURCE ${coverage_sources} APPEND PROPERTY LABELS ${MODULE_SUBPROJECTS}) + + IF(NOT MODULE_HEADERS_ONLY) + IF(ALL_LIBRARY_DIRS) + # LINK_DIRECTORIES applies only to targets which are added after the call to LINK_DIRECTORIES + LINK_DIRECTORIES(${ALL_LIBRARY_DIRS}) + ENDIF(ALL_LIBRARY_DIRS) + ADD_LIBRARY(${MODULE_PROVIDES} ${coverage_sources} ${CPP_FILES_GENERATED} ${Q${KITNAME}_GENERATED_CPP} ${DOX_FILES} ${UI_FILES} ${QRC_FILES}) + TARGET_LINK_LIBRARIES(${MODULE_PROVIDES} ${QT_LIBRARIES} ${ALL_LIBRARIES} QVTK) + IF(MODULE_TARGET_DEPENDS) + ADD_DEPENDENCIES(${MODULE_PROVIDES} ${MODULE_TARGET_DEPENDS}) + ENDIF() + IF(MINGW) + TARGET_LINK_LIBRARIES(${MODULE_PROVIDES} ssp) # add stack smash protection lib + ENDIF() + IF(MODULE_SUBPROJECTS) + SET_PROPERTY(TARGET ${MODULE_PROVIDES} PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) + FOREACH(subproject ${MODULE_SUBPROJECTS}) + ADD_DEPENDENCIES(${subproject} ${MODULE_PROVIDES}) + ENDFOREACH() + ENDIF() + ENDIF() + + ENDIF(NOT MODULE_QT_MODULE) + + IF(NOT MODULE_HEADERS_ONLY) + # Apply properties to the module target. + SET_TARGET_PROPERTIES(${MODULE_PROVIDES} PROPERTIES + COMPILE_FLAGS "${module_compile_flags}" + ) + ENDIF() + + # install only if shared lib (for now) + IF(NOT _STATIC OR MINGW) + IF(NOT MODULE_HEADERS_ONLY) + # # deprecated: MITK_INSTALL_TARGETS(${MODULE_PROVIDES}) + ENDIF() + ENDIF(NOT _STATIC OR MINGW) + + ENDIF(NOT MODULE_QT_MODULE OR MITK_USE_QT) ENDIF(MODULE_IS_ENABLED) ENDIF(_MISSING_DEP) ENDIF(NOT MODULE_IS_EXCLUDED) - IF(NOT MODULE_IS_ENABLED) + IF(NOT MODULE_IS_ENABLED) _MITK_CREATE_MODULE_CONF() - ENDIF(NOT MODULE_IS_ENABLED) + ENDIF(NOT MODULE_IS_ENABLED) + ENDMACRO(MITK_CREATE_MODULE) diff --git a/CMake/mitkMacroCreateModuleTests.cmake b/CMake/mitkMacroCreateModuleTests.cmake index 4f1f5f06f8..e7948abb0e 100644 --- a/CMake/mitkMacroCreateModuleTests.cmake +++ b/CMake/mitkMacroCreateModuleTests.cmake @@ -1,85 +1,85 @@ # # Create tests and testdriver for this module # # Usage: MITK_CREATE_MODULE_TESTS( [EXTRA_DRIVER_INIT init_code] ) # # EXTRA_DRIVER_INIT is inserted as c++ code in the testdriver and will be executed before each test # MACRO(MITK_CREATE_MODULE_TESTS) MACRO_PARSE_ARGUMENTS(MODULE_TEST "EXTRA_DRIVER_INIT;EXTRA_DRIVER_INCLUDE" "" ${ARGN}) IF(BUILD_TESTING AND MODULE_IS_ENABLED) SET(OLD_MOC_H_FILES ${MOC_H_FILES}) SET(MOC_H_FILES) INCLUDE(files.cmake) INCLUDE_DIRECTORIES(.) IF(DEFINED MOC_H_FILES) QT4_WRAP_CPP(MODULE_TEST_GENERATED_MOC_CPP ${MOC_H_FILES}) ENDIF(DEFINED MOC_H_FILES) SET(CMAKE_TESTDRIVER_BEFORE_TESTMAIN "mitk::LoggingBackend::Register(); ${MODULE_TEST_EXTRA_DRIVER_INIT};") SET(CMAKE_TESTDRIVER_AFTER_TESTMAIN "mitk::LoggingBackend::Unregister();") IF(NOT MODULE_TEST_EXTRA_DRIVER_INCLUDE) # this is necessary to make the LoggingBackend calls available if nothing else is included SET(MODULE_TEST_EXTRA_DRIVER_INCLUDE "mitkLog.h") ENDIF(NOT MODULE_TEST_EXTRA_DRIVER_INCLUDE) CREATE_TEST_SOURCELIST(MODULETEST_SOURCE ${MODULE_NAME}TestDriver.cpp ${MODULE_TESTS} ${MODULE_IMAGE_TESTS} ${MODULE_CUSTOM_TESTS} EXTRA_INCLUDE ${MODULE_TEST_EXTRA_DRIVER_INCLUDE} ) SET(TESTDRIVER ${MODULE_NAME}TestDriver) - ADD_EXECUTABLE(${TESTDRIVER} ${MODULETEST_SOURCE} ${MODULE_TEST_GENERATED_MOC_CPP}) + ADD_EXECUTABLE(${TESTDRIVER} ${MODULETEST_SOURCE} ${MODULE_TEST_GENERATED_MOC_CPP} ${TEST_CPP_FILES}) TARGET_LINK_LIBRARIES(${TESTDRIVER} ${MODULE_PROVIDES} ${ALL_LIBRARIES}) IF(MODULE_SUBPROJECTS) FOREACH(subproject ${MODULE_SUBPROJECTS}) ADD_DEPENDENCIES(${subproject} ${TESTDRIVER}) ENDFOREACH() ENDIF() # # Now tell CMake which tests should be run. This is done automatically # for all tests in ${KITNAME}_TESTS and ${KITNAME}_IMAGE_TESTS. The IMAGE_TESTS # are run for each image in the TESTIMAGES list. # FOREACH( test ${MODULE_TESTS} ) GET_FILENAME_COMPONENT(TName ${test} NAME_WE) ADD_TEST(${TName} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} ${TName}) # Add labels for CDash subproject support IF(MODULE_SUBPROJECTS) SET_PROPERTY(TEST ${TName} PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) ENDIF() ENDFOREACH( test ) FOREACH(image ${MODULE_TESTIMAGES} ${ADDITIONAL_TEST_IMAGES} ) IF(EXISTS ${image}) SET(IMAGE_FULL_PATH ${image}) ELSE(EXISTS ${image}) # todo: maybe search other paths as well # yes, please in mitk/Testing/Data, too SET(IMAGE_FULL_PATH ${MITK_DATA_DIR}/${image}) ENDIF(EXISTS ${image}) IF(EXISTS ${IMAGE_FULL_PATH}) FOREACH( test ${MODULE_IMAGE_TESTS} ) GET_FILENAME_COMPONENT(TName ${test} NAME_WE) GET_FILENAME_COMPONENT(ImageName ${IMAGE_FULL_PATH} NAME) ADD_TEST(${TName}_${ImageName} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} ${TName} ${IMAGE_FULL_PATH}) # Add labels for CDash subproject support IF(MODULE_SUBPROJECTS) SET_PROPERTY(TEST ${TName}_${ImageName} PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) ENDIF() ENDFOREACH( test ) ELSE(EXISTS ${IMAGE_FULL_PATH}) MESSAGE("!!!!! No such file: ${IMAGE_FULL_PATH} !!!!!") ENDIF(EXISTS ${IMAGE_FULL_PATH}) ENDFOREACH( image ) SET(MOC_H_FILES ${OLD_MOC_H_FILES}) ENDIF(BUILD_TESTING AND MODULE_IS_ENABLED) ENDMACRO(MITK_CREATE_MODULE_TESTS) diff --git a/CMake/mitkModuleInit.cpp b/CMake/mitkModuleInit.cpp new file mode 100644 index 0000000000..cab644a9e3 --- /dev/null +++ b/CMake/mitkModuleInit.cpp @@ -0,0 +1,82 @@ +/*============================================================================= + + Library: CTK + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + +#include "mitkStaticInit.h" + +#include "mitkModuleRegistry.h" +#include "mitkModuleContext.h" +#include "mitkModule.h" +#include "mitkModuleInfo.h" +#include "mitkModuleUtils.h" + +namespace mitk { + +MITK_GLOBAL_STATIC_WITH_ARGS(ModuleInfo, moduleInfo, ("@MODULE_NAME@", "@MODULE_LIBNAME@", "@MODULE_DEPENDS_STR@", "@MODULE_PACKAGE_DEPENDS_STR@", "@MODULE_VERSION@", @MODULE_QT_BOOL@)) + +#if defined(__GNUC__) +class __attribute__ ((visibility ("hidden"))) ModuleInitializer { +#else +class ModuleInitializer { +#endif + +public: + + ModuleInitializer() + { + std::string location = ModuleUtils::GetLibraryPath(moduleInfo()->libName, (void*)moduleInfo); + std::string activator_func = "_mitk_module_activator_instance_"; + activator_func.append(moduleInfo()->name); + + moduleInfo()->location = location; + moduleInfo()->activatorHook = (ModuleInfo::ModuleActivatorHook)ModuleUtils::GetSymbol(location, activator_func.c_str()); + + Register(); + } + + static void Register() + { + ModuleRegistry::Register(moduleInfo()); + } + + ~ModuleInitializer() + { + ModuleRegistry::UnRegister(moduleInfo()); + } + +}; + +ModuleContext* GetModuleContext() +{ + // make sure the module is registered + if (moduleInfo()->id == 0) + { + ModuleInitializer::Register(); + } + + return ModuleRegistry::GetModule(moduleInfo()->id)->GetModuleContext(); +} + +} + +static mitk::ModuleInitializer coreModule; + + + diff --git a/CMake/mitkSetupC++0xVariables.cmake b/CMake/mitkSetupC++0xVariables.cmake new file mode 100644 index 0000000000..6c60783f30 --- /dev/null +++ b/CMake/mitkSetupC++0xVariables.cmake @@ -0,0 +1,55 @@ +if(MSVC10) + set(MITK_USE_C++0x 1) +else() + option(MITK_USE_C++0x "Enable C++0x features in MITK. This is experimental." OFF) + mark_as_advanced(MITK_USE_C++0x) +endif() + +# Begin checking fo C++0x features +if(MITK_USE_C++0x) + if(CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_REQUIRED_FLAGS "-std=c++0x") + endif() + + include(mitkFunctionCheckC++0xHashString) + mitkFunctionCheckCxx0xHashString(MITK_HAS_HASH_STRING_0x) + + include(mitkFunctionCheckC++0xHashSizeT) + mitkFunctionCheckCxx0xHashSizeT(MITK_HAS_HASH_SIZE_T_0x) + + include(mitkFunctionCheckC++0xUnorderedMap) + mitkFunctionCheckCxx0xUnorderedMap(MITK_HAS_UNORDERED_MAP_H_0x) + + include(mitkFunctionCheckC++0xUnorderedSet) + mitkFunctionCheckCxx0xUnorderedMap(MITK_HAS_UNORDERED_SET_H_0x) + + set(MITK_HAS_VAR_SUFFIX "_0x") + set(CMAKE_REQUIRED_FLAGS "") + +else() + + set(CMAKE_REQUIRED_FLAGS "") + + include(mitkFunctionCheckItkHashString) + mitkFunctionCheckItkHashString(MITK_HAS_HASH_STRING_def) + + include(mitkFunctionCheckItkHashSizeT) + mitkFunctionCheckItkHashSizeT(MITK_HAS_HASH_SIZE_T_def) + + set(MITK_HAS_UNORDERED_MAP_H_def ) + set(MITK_HAS_UNORDERED_SET_H_def ) + + set(MITK_HAS_VAR_SUFFIX "_def") + +endif() + +foreach(var + MITK_HAS_HASH_STRING + MITK_HAS_HASH_SIZE_T + MITK_HAS_UNORDERED_MAP_H + MITK_HAS_UNORDERED_SET_H + ) + set(${var} ${${var}${MITK_HAS_VAR_SUFFIX}}) +endforeach() + +# End checking C++0x features diff --git a/CMake/mitkSetupVariables.cmake b/CMake/mitkSetupVariables.cmake index 7a573b0c17..412bd20206 100644 --- a/CMake/mitkSetupVariables.cmake +++ b/CMake/mitkSetupVariables.cmake @@ -1,146 +1,151 @@ if(MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS_OPTION "FORCE_BUILD_ALL") endif() set(LIBPOSTFIX "") # MITK_VERSION set(MITK_VERSION_MAJOR "0") set(MITK_VERSION_MINOR "15") set(MITK_VERSION_PATCH "1") set(MITK_VERSION_STRING "${MITK_VERSION_MAJOR}.${MITK_VERSION_MINOR}.${MITK_VERSION_PATCH}") 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 ${PROJECT_BINARY_DIR}) -set(CORE_DIRECTORIES DataManagement Algorithms IO Rendering Interactions Controllers) +set(CORE_DIRECTORIES 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/IIL4MITK Utilities/pic2vtk Utilities/tinyxml Utilities/mbilog) - list(APPEND MITK_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/${dir}) + 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 vtkftgl 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 IIL4MITK 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}) +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}/CoreUI/Qmitk ${PROJECT_BINARY_DIR}/CoreUI/Qmitk ) foreach(d QmitkApplicationBase QmitkModels QmitkPropertyObservers) list(APPEND QMITK_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/CoreUI/Qmitk/${d}) endforeach() list(APPEND QMITK_INCLUDE_DIRS ${QWT_INCLUDE_DIR}) set(QMITK_LIBRARIES Qmitk ${MITK_LIBRARIES} ${QT_LIBRARIES}) set(QMITK_LINK_DIRECTORIES ${MITK_LINK_DIRECTORIES} ${QT_LIBRARY_DIR}) 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 ) foreach(_type INTEGRAL FLOATING COMPOSITE) 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() 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/CMakeLists.txt b/CMakeLists.txt index 3998c96474..8751c20a98 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,663 +1,675 @@ cmake_minimum_required(VERSION 2.8.4) #----------------------------------------------------------------------------- # Set a default build type if none was specified #----------------------------------------------------------------------------- if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Debug' as none was specified.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() #----------------------------------------------------------------------------- # Superbuild Option - Enabled by default #----------------------------------------------------------------------------- option(MITK_USE_SUPERBUILD "Build MITK and the projects it depends on via SuperBuild.cmake." ON) if(MITK_USE_SUPERBUILD) project(MITK-superbuild) set(MITK_SOURCE_DIR ${PROJECT_SOURCE_DIR}) set(MITK_BINARY_DIR ${PROJECT_BINARY_DIR}) else() project(MITK) endif() #----------------------------------------------------------------------------- # See http://cmake.org/cmake/help/cmake-2-8-docs.html#section_Policies for details #----------------------------------------------------------------------------- set(project_policies CMP0001 # NEW: CMAKE_BACKWARDS_COMPATIBILITY should no longer be used. CMP0002 # NEW: Logical target names must be globally unique. CMP0003 # NEW: Libraries linked via full path no longer produce linker search paths. CMP0004 # NEW: Libraries linked may NOT have leading or trailing whitespace. CMP0005 # NEW: Preprocessor definition values are now escaped automatically. CMP0006 # NEW: Installing MACOSX_BUNDLE targets requires a BUNDLE DESTINATION. CMP0007 # NEW: List command no longer ignores empty elements. CMP0008 # NEW: Libraries linked by full-path must have a valid library file name. CMP0009 # NEW: FILE GLOB_RECURSE calls should not follow symlinks by default. CMP0010 # NEW: Bad variable reference syntax is an error. CMP0011 # NEW: Included scripts do automatic cmake_policy PUSH and POP. CMP0012 # NEW: if() recognizes numbers and boolean constants. CMP0013 # NEW: Duplicate binary directories are not allowed. CMP0014 # NEW: Input directories must have CMakeLists.txt ) foreach(policy ${project_policies}) if(POLICY ${policy}) cmake_policy(SET ${policy} NEW) endif() endforeach() #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(CMAKE_MODULE_PATH ${MITK_SOURCE_DIR}/CMake ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake Function(s) and Macro(s) #----------------------------------------------------------------------------- include(mitkMacroEmptyExternalProject) include(mitkFunctionGenerateProjectXml) #----------------------------------------------------------------------------- # Output directories. #----------------------------------------------------------------------------- foreach(type LIBRARY RUNTIME ARCHIVE) # Make sure the directory exists if(DEFINED MITK_CMAKE_${type}_OUTPUT_DIRECTORY AND NOT EXISTS ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) message("Creating directory MITK_CMAKE_${type}_OUTPUT_DIRECTORY: ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") file(MAKE_DIRECTORY "${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") endif() if(MITK_USE_SUPERBUILD) set(output_dir ${MITK_BINARY_DIR}/bin) if(NOT DEFINED MITK_CMAKE_${type}_OUTPUT_DIRECTORY) set(MITK_CMAKE_${type}_OUTPUT_DIRECTORY ${MITK_BINARY_DIR}/MITK-build/bin) endif() else() if(NOT DEFINED MITK_CMAKE_${type}_OUTPUT_DIRECTORY) SET(output_dir ${MITK_BINARY_DIR}/bin) else() SET(output_dir ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) endif() endif() set(CMAKE_${type}_OUTPUT_DIRECTORY ${output_dir} CACHE INTERNAL "Single output directory for building all libraries.") mark_as_advanced(CMAKE_${type}_OUTPUT_DIRECTORY) endforeach() #----------------------------------------------------------------------------- # Additional MITK Options (also shown during superbuild) #----------------------------------------------------------------------------- option(BUILD_SHARED_LIBS "Build MITK with shared libraries" ON) option(WITH_COVERAGE "Enable/Disable coverage" OFF) option(BUILD_TESTING "Test the project" ON) # some targets in Utilities also depend on Qt. Use this option # to decide if they should be build option(MITK_USE_QT "Use Trolltech's Qt library" ON) if(MITK_USE_QT) # find the package at the very beginning, so that QT4_FOUND is available find_package(Qt4 4.6.0 REQUIRED) endif() option(MITK_BUILD_ALL_PLUGINS "Build all MITK plugins" OFF) option(MITK_BUILD_TUTORIAL "Build the MITK tutorial" ON) option(MITK_USE_Boost "Use the Boost C++ library" OFF) option(MITK_USE_BLUEBERRY "Build the BlueBerry platform" ON) option(MITK_USE_CTK "Use CTK in MITK" ${MITK_USE_BLUEBERRY}) option(MITK_USE_DCMTK "EXEPERIMENTAL, superbuild only: Use DCMTK in MITK" OFF) option(MITK_USE_OpenCV "Use Intel's OpenCV library" OFF) mark_as_advanced(MITK_BUILD_ALL_PLUGINS MITK_USE_CTK MITK_USE_DCMTK ) set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") mark_as_advanced(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES MITK_ACCESSBYITK_DIMENSIONS ) # consistency checks if(MITK_USE_BLUEBERRY AND NOT MITK_USE_CTK) MESSAGE(FATAL_ERROR "BlueBerry depends on CTK. Please set MITK_USE_CTK to ON.") endif() if(NOT MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES) set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES) set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_DIMENSIONS) set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") endif() #----------------------------------------------------------------------------- # Additional CXX/C Flags #----------------------------------------------------------------------------- set(ADDITIONAL_C_FLAGS "" CACHE STRING "Additional C Flags") mark_as_advanced(ADDITIONAL_C_FLAGS) set(ADDITIONAL_CXX_FLAGS "" CACHE STRING "Additional CXX Flags") mark_as_advanced(ADDITIONAL_CXX_FLAGS) #----------------------------------------------------------------------------- # Project.xml #----------------------------------------------------------------------------- # A list of topologically ordered targets set(CTEST_PROJECT_SUBPROJECTS) if(MITK_USE_BLUEBERRY) list(APPEND CTEST_PROJECT_SUBPROJECTS BlueBerry) endif() list(APPEND CTEST_PROJECT_SUBPROJECTS MITK-Core MITK-CoreUI MITK-IGT MITK-ToF MITK-DTI MITK-Registration MITK-Modules # all modules not contained in a specific subproject MITK-Plugins # all plugins not contained in a specific subproject Unlabeled # special "subproject" catching all unlabeled targets and tests ) # Configure CTestConfigSubProject.cmake that could be used by CTest scripts configure_file(${MITK_SOURCE_DIR}/CTestConfigSubProject.cmake.in ${MITK_BINARY_DIR}/CTestConfigSubProject.cmake) if(CTEST_PROJECT_ADDITIONAL_TARGETS) # those targets will be executed at the end of the ctest driver script # and they also get their own subproject label set(subproject_list "${CTEST_PROJECT_SUBPROJECTS};${CTEST_PROJECT_ADDITIONAL_TARGETS}") else() set(subproject_list "${CTEST_PROJECT_SUBPROJECTS}") endif() # Generate Project.xml file expected by the CTest driver script mitkFunctionGenerateProjectXml(${MITK_BINARY_DIR} MITK "${subproject_list}" ${MITK_USE_SUPERBUILD}) #----------------------------------------------------------------------------- # Superbuild script #----------------------------------------------------------------------------- if(MITK_USE_SUPERBUILD) include("${CMAKE_CURRENT_SOURCE_DIR}/SuperBuild.cmake") return() endif() #***************************************************************************** #**************************** END OF SUPERBUILD **************************** #***************************************************************************** #----------------------------------------------------------------------------- # CMake Function(s) and Macro(s) #----------------------------------------------------------------------------- +include(CheckCXXSourceCompiles) include(mitkFunctionCheckCompilerFlags) include(mitkFunctionGetGccVersion) include(MacroParseArguments) include(mitkFunctionSuppressWarnings) # includes several functions include(mitkFunctionOrganizeSources) include(mitkFunctionGetVersion) include(mitkFunctionCreateWindowsBatchScript) include(mitkFunctionInstallProvisioningFiles) +include(mitkFunctionCompileSnippets) include(mitkMacroCreateModuleConf) include(mitkMacroCreateModule) include(mitkMacroCheckModule) include(mitkMacroCreateModuleTests) include(mitkFunctionAddCustomModuleTest) include(mitkMacroUseModule) include(mitkMacroMultiplexPicType) include(mitkMacroInstall) include(mitkMacroInstallHelperApp) include(mitkMacroInstallTargets) include(mitkMacroGenerateToolsLibrary) include(mitkMacroGetLinuxDistribution) #----------------------------------------------------------------------------- # Prerequesites #----------------------------------------------------------------------------- find_package(ITK REQUIRED) find_package(VTK REQUIRED) +if(ITK_USE_SYSTEM_GDCM) + find_package(GDCM PATHS ${ITK_GDCM_DIR} REQUIRED) +endif() + #----------------------------------------------------------------------------- # Set MITK specific options and variables (NOT available during superbuild) #----------------------------------------------------------------------------- # ASK THE USER TO SHOW THE CONSOLE WINDOW FOR CoreApp and ExtApp option(MITK_SHOW_CONSOLE_WINDOW "Use this to enable or disable the console window when starting MITK GUI Applications" ON) mark_as_advanced(MITK_SHOW_CONSOLE_WINDOW) # TODO: check if necessary option(USE_ITKZLIB "Use the ITK zlib for pic compression." ON) mark_as_advanced(USE_ITKZLIB) if(NOT MITK_FAST_TESTING) if(DEFINED MITK_CTEST_SCRIPT_MODE AND MITK_CTEST_SCRIPT_MODE STREQUAL "continuous") set(MITK_FAST_TESTING 1) endif() endif() #----------------------------------------------------------------------------- # Get MITK version info #----------------------------------------------------------------------------- mitkFunctionGetVersion(${MITK_SOURCE_DIR} MITK) #----------------------------------------------------------------------------- # Installation preparation # # These should be set before any MITK install macros are used #----------------------------------------------------------------------------- # on Mac OSX all BlueBerry plugins get copied into every # application bundle (.app directory) specified here if(APPLE) if(MITK_BUILD_org.mitk.gui.qt.extapplication) set(MACOSX_BUNDLE_NAMES ${MACOSX_BUNDLE_NAMES} ExtApp) endif() if(MITK_BUILD_org.mitk.gui.qt.application) set(MACOSX_BUNDLE_NAMES ${MACOSX_BUNDLE_NAMES} CoreApp) endif() endif(APPLE) #----------------------------------------------------------------------------- # Set symbol visibility Flags #----------------------------------------------------------------------------- # MinGW does not export all symbols automatically, so no need to set flags if(CMAKE_COMPILER_IS_GNUCXX AND NOT MINGW) set(VISIBILITY_CXX_FLAGS ) #"-fvisibility=hidden -fvisibility-inlines-hidden") endif() #----------------------------------------------------------------------------- # Set coverage Flags #----------------------------------------------------------------------------- if(WITH_COVERAGE) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") set(coverage_flags "-g -fprofile-arcs -ftest-coverage -O0 -DNDEBUG") set(COVERAGE_CXX_FLAGS ${coverage_flags}) set(COVERAGE_C_FLAGS ${coverage_flags}) endif() endif() #----------------------------------------------------------------------------- # MITK C/CXX Flags #----------------------------------------------------------------------------- set(MITK_C_FLAGS "${COVERAGE_C_FLAGS} ${ADDITIONAL_C_FLAGS}") set(MITK_CXX_FLAGS "${VISIBILITY_CXX_FLAGS} ${COVERAGE_CXX_FLAGS} ${ADDITIONAL_CXX_FLAGS}") +include(mitkSetupC++0xVariables) + if(CMAKE_COMPILER_IS_GNUCXX) set(cflags "-Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -D_FORTIFY_SOURCE=2") mitkFunctionCheckCompilerFlags("-fdiagnostics-show-option" cflags) mitkFunctionCheckCompilerFlags("-Wl,--no-undefined" cflags) + if(MITK_USE_C++0x) + mitkFunctionCheckCompilerFlags("-std=c++0x" MITK_CXX_FLAGS) + endif() + mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) # With older version of gcc supporting the flag -fstack-protector-all, an extra dependency to libssp.so # is introduced. If gcc is smaller than 4.4.0 and the build type is Release let's not include the flag. # Doing so should allow to build package made for distribution using older linux distro. if(${GCC_VERSION} VERSION_GREATER "4.4.0" OR (CMAKE_BUILD_TYPE STREQUAL "Debug" AND ${GCC_VERSION} VERSION_LESS "4.4.0")) mitkFunctionCheckCompilerFlags("-fstack-protector-all" cflags) endif() if(MINGW) # suppress warnings about auto imported symbols set(MITK_CXX_FLAGS "-Wl,--enable-auto-import ${MITK_CXX_FLAGS}") # we need to define a Windows version set(MITK_CXX_FLAGS "-D_WIN32_WINNT=0x0500 ${MITK_CXX_FLAGS}") endif() set(MITK_C_FLAGS "${cflags} ${MITK_C_FLAGS}") #set(MITK_CXX_FLAGS "${cflags} -Woverloaded-virtual -Wold-style-cast -Wstrict-null-sentinel -Wsign-promo ${MITK_CXX_FLAGS}") set(MITK_CXX_FLAGS "${cflags} -Woverloaded-virtual -Wstrict-null-sentinel ${MITK_CXX_FLAGS}") endif() #----------------------------------------------------------------------------- # MITK Modules #----------------------------------------------------------------------------- set(MITK_MODULES_CONF_DIR ${MITK_BINARY_DIR}/modulesConf CACHE INTERNAL "Modules Conf") set(MITK_MODULES_PACKAGE_DEPENDS_DIR ${MITK_SOURCE_DIR}/CMake/PackageDepends) set(MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR}) #----------------------------------------------------------------------------- # Testing #----------------------------------------------------------------------------- if(BUILD_TESTING) enable_testing() include(CTest) mark_as_advanced(TCL_TCLSH DART_ROOT) option(MITK_ENABLE_GUI_TESTING OFF "Enable the MITK GUI tests") # Setup file for setting custom ctest vars configure_file( CMake/CTestCustom.cmake.in ${MITK_BINARY_DIR}/CTestCustom.cmake @ONLY ) # Configuration for the CMake-generated test driver set(CMAKE_TESTDRIVER_EXTRA_INCLUDES "#include ") set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN " try {") set(CMAKE_TESTDRIVER_AFTER_TESTMAIN " } catch( std::exception & excp ) { fprintf(stderr,\"%s\\n\",excp.what()); return EXIT_FAILURE; } catch( ... ) { printf(\"Exception caught in the test driver\\n\"); return EXIT_FAILURE; } ") set(MITK_TEST_OUTPUT_DIR "${MITK_BINARY_DIR}/test_output") if(NOT EXISTS ${MITK_TEST_OUTPUT_DIR}) file(MAKE_DIRECTORY ${MITK_TEST_OUTPUT_DIR}) endif() # Test the external project template if(MITK_USE_BLUEBERRY) include(mitkTestProjectTemplate) endif() endif() configure_file(mitkTestingConfig.h.in ${MITK_BINARY_DIR}/mitkTestingConfig.h) #----------------------------------------------------------------------------- # MITK_SUPERBUILD_BINARY_DIR #----------------------------------------------------------------------------- # If MITK_SUPERBUILD_BINARY_DIR isn't defined, it means MITK is *NOT* build using Superbuild. # In that specific case, MITK_SUPERBUILD_BINARY_DIR should default to MITK_BINARY_DIR if(NOT DEFINED MITK_SUPERBUILD_BINARY_DIR) set(MITK_SUPERBUILD_BINARY_DIR ${MITK_BINARY_DIR}) endif() #----------------------------------------------------------------------------- # Compile Utilities and set-up MITK variables #----------------------------------------------------------------------------- add_subdirectory(Utilities) include(mitkSetupVariables) if(MITK_USE_BLUEBERRY) include(mitkSetupBlueBerry) endif() #----------------------------------------------------------------------------- # Set C/CXX Flags for MITK code #----------------------------------------------------------------------------- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MITK_CXX_FLAGS}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${MITK_C_FLAGS}") if(MITK_USE_QT) add_definitions(-DQWT_DLL) endif() #----------------------------------------------------------------------------- # Add custom targets representing CDash subprojects #----------------------------------------------------------------------------- foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) if(NOT TARGET ${subproject} AND NOT subproject MATCHES "Unlabeled") add_custom_target(${subproject}) endif() endforeach() #----------------------------------------------------------------------------- # Add subdirectories #----------------------------------------------------------------------------- link_directories(${MITK_LINK_DIRECTORIES}) add_subdirectory(Core) if(MITK_USE_QT AND QT4_FOUND) add_subdirectory(CoreUI/Qmitk) endif() add_subdirectory(Modules) if(MITK_USE_BLUEBERRY) set(MITK_DEFAULT_SUBPROJECTS MITK-Plugins) include("${CMAKE_CURRENT_SOURCE_DIR}/CoreUI/Bundles/PluginList.cmake") set(mitk_core_plugins_fullpath ) foreach(core_plugin ${MITK_CORE_PLUGINS}) list(APPEND mitk_core_plugins_fullpath CoreUI/Bundles/${core_plugin}) endforeach() if(BUILD_TESTING) include(berryTestingHelpers) include("${CMAKE_CURRENT_SOURCE_DIR}/CoreUI/BundleTesting/PluginList.cmake") set(mitk_core_test_plugins_fullpath ) foreach(core_test_plugin ${MITK_CORE_TEST_PLUGINS}) # list(APPEND mitk_core_test_plugins_fullpath CoreUI/BundleTesting/${core_test_plugin}) endforeach() set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp") get_target_property(_is_macosx_bundle CoreApp MACOSX_BUNDLE) if(APPLE AND _is_macosx_bundle) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp.app/Contents/MacOS/CoreApp") endif() set(BLUEBERRY_TEST_APP_ID "org.mitk.qt.application") endif() include("${CMAKE_CURRENT_SOURCE_DIR}/Modules/Bundles/PluginList.cmake") set(mitk_ext_plugins_fullpath ) foreach(ext_plugin ${MITK_EXT_PLUGINS}) list(APPEND mitk_ext_plugins_fullpath Modules/Bundles/${ext_plugin}) endforeach() ctkMacroSetupExternalPlugins(${mitk_core_plugins_fullpath} ${mitk_core_test_plugins_fullpath} ${mitk_ext_plugins_fullpath} BUILD_OPTION_PREFIX MITK_BUILD_ BUILD_ALL ${MITK_BUILD_ALL_PLUGINS} COMPACT_OPTIONS) ctkFunctionExtractPluginTargets("${mitk_core_plugins_fullpath}" ON MITK_CORE_ENABLED_PLUGINS) ctkFunctionExtractPluginTargets("${mitk_ext_plugins_fullpath}" ON MITK_EXT_ENABLED_PLUGINS) list(APPEND MITK_EXT_ENABLED_PLUGINS ${MITK_CORE_ENABLED_PLUGINS}) set(MITK_COREAPP_PROVISIONING_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp.provisioning") FunctionCreateProvisioningFile( FILE ${MITK_COREAPP_PROVISIONING_FILE} INCLUDE "${BLUEBERRY_PLUGIN_PROVISIONING_FILE}" PLUGIN_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/plugins" PLUGINS ${mitk_core_plugins_fullpath} ) set(MITK_EXTAPP_PROVISIONING_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/ExtApp.provisioning") FunctionCreateProvisioningFile( FILE ${MITK_EXTAPP_PROVISIONING_FILE} INCLUDE "${BLUEBERRY_PLUGIN_PROVISIONING_FILE}" PLUGIN_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/plugins" PLUGINS ${mitk_core_plugins_fullpath} ${mitk_ext_plugins_fullpath} ) set(MITK_PLUGIN_USE_FILE "${MITK_BINARY_DIR}/MitkPluginUseFile.cmake") ctkFunctionGeneratePluginUseFile(${MITK_PLUGIN_USE_FILE}) # Used in the export command further below GetMyTargetLibraries("${CTK_PLUGIN_LIBRARIES}" MITK_PLUGIN_TARGETS) # add legacy BlueBerry bundles add_subdirectory(Modules/Bundles) endif() # Construct a list of paths containing runtime directories # for MITK applications on Windows set(MITK_RUNTIME_PATH "${VTK_LIBRARY_DIRS}/@VS_BUILD_TYPE@;${ITK_LIBRARY_DIRS}/@VS_BUILD_TYPE@;${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/@VS_BUILD_TYPE@" ) if(QT4_FOUND) set(MITK_RUNTIME_PATH "${MITK_RUNTIME_PATH};${QT_LIBRARY_DIR}/../bin") endif() if(MITK_USE_BLUEBERRY) set(MITK_RUNTIME_PATH "${MITK_RUNTIME_PATH};${CTK_RUNTIME_LIBRARY_DIRS}/@VS_BUILD_TYPE@;${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/plugins/@VS_BUILD_TYPE@") endif() if(GDCM_DIR) set(MITK_RUNTIME_PATH "${MITK_RUNTIME_PATH};${GDCM_DIR}/bin/@VS_BUILD_TYPE@") endif() if(OpenCV_DIR) set(MITK_RUNTIME_PATH "${MITK_RUNTIME_PATH};${OpenCV_DIR}/bin/@VS_BUILD_TYPE@") endif() # DCMTK is statically build #if(DCMTK_DIR) # set(MITK_RUNTIME_PATH "${MITK_RUNTIME_PATH};${DCMTK_DIR}/bin/@VS_BUILD_TYPE@") #endif() # Add applications directory add_subdirectory(Applications) #----------------------------------------------------------------------------- # Python Wrapping #----------------------------------------------------------------------------- set(MITK_WRAPPING_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Wrapping) set(MITK_WRAPPING_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/Wrapping) option(MITK_USE_PYTHON "Build cswig Python wrapper support (requires CableSwig)." OFF) if(MITK_USE_PYTHON) add_subdirectory(Wrapping) endif() #----------------------------------------------------------------------------- # Documentation #----------------------------------------------------------------------------- add_subdirectory(Documentation) #----------------------------------------------------------------------------- # Installation #----------------------------------------------------------------------------- # set MITK cpack variables include(mitkSetupCPack) if(MITK_BUILD_org.mitk.gui.qt.application) list(APPEND CPACK_CREATE_DESKTOP_LINKS "CoreApp") endif() if(MITK_BUILD_org.mitk.gui.qt.extapplication) list(APPEND CPACK_CREATE_DESKTOP_LINKS "ExtApp") endif() configure_file(${MITK_SOURCE_DIR}/MITKCPackOptions.cmake.in ${MITK_BINARY_DIR}/MITKCPackOptions.cmake @ONLY) set(CPACK_PROJECT_CONFIG_FILE "${MITK_BINARY_DIR}/MITKCPackOptions.cmake") # include CPack model once all variables are set include(CPack) # Additional installation rules include(mitkInstallRules) #----------------------------------------------------------------------------- # Last configuration steps #----------------------------------------------------------------------------- set(MITK_EXPORTS_FILE "${MITK_BINARY_DIR}/MitkExports.cmake") file(REMOVE ${MITK_EXPORTS_FILE}) if(MITK_USE_BLUEBERRY) set(enabled_plugins ${BLUEBERRY_PLUGIN_TARGETS} ${MITK_PLUGIN_TARGETS} ${MITK_MODULES_ENABLED_PLUGINS} ) # This is for installation support of external projects depending on # MITK plugins. The export file should not be used for linking to MITK # libraries without using LINK_DIRECTORIES, since the exports are incomplete # yet(depending libraries are not exported). foreach(plugin ${enabled_plugins}) string(REPLACE "." "_" plugin_target ${plugin}) export(TARGETS ${plugin_target} APPEND FILE ${MITK_EXPORTS_FILE}) endforeach() endif() configure_file(${MITK_SOURCE_DIR}/CMake/ToolExtensionITKFactory.cpp.in ${MITK_BINARY_DIR}/ToolExtensionITKFactory.cpp.in COPYONLY) configure_file(${MITK_SOURCE_DIR}/CMake/ToolExtensionITKFactoryLoader.cpp.in ${MITK_BINARY_DIR}/ToolExtensionITKFactoryLoader.cpp.in COPYONLY) configure_file(${MITK_SOURCE_DIR}/CMake/ToolGUIExtensionITKFactory.cpp.in ${MITK_BINARY_DIR}/ToolGUIExtensionITKFactory.cpp.in COPYONLY) configure_file(mitkVersion.h.in ${MITK_BINARY_DIR}/mitkVersion.h) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) set(VECMATH_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/vecmath) set(IPFUNC_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/ipFunc) set(UTILITIES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) configure_file(MITKConfig.cmake.in ${MITK_BINARY_DIR}/MITKConfig.cmake @ONLY) # If we are under Windows, create two batch files which correctly # set up the environment for the application and for Visual Studio if(WIN32) include(mitkFunctionCreateWindowsBatchScript) set(VS_SOLUTION_FILE "${PROJECT_BINARY_DIR}/${PROJECT_NAME}.sln") foreach(VS_BUILD_TYPE debug release) mitkFunctionCreateWindowsBatchScript("${MITK_SOURCE_DIR}/CMake/StartVS.bat.in" ${PROJECT_BINARY_DIR}/StartVS_${VS_BUILD_TYPE}.bat ${VS_BUILD_TYPE}) endforeach() endif(WIN32) diff --git a/Core/Code/CMakeLists.txt b/Core/Code/CMakeLists.txt index b8097fa4b2..52435db386 100644 --- a/Core/Code/CMakeLists.txt +++ b/Core/Code/CMakeLists.txt @@ -1,53 +1,53 @@ FIND_PACKAGE(OpenGL) IF(NOT OPENGL_FOUND) MESSAGE("GL is required for MITK rendering") ENDIF(NOT OPENGL_FOUND ) SET(TOOL_CPPS "") MITK_CREATE_MODULE( Mitk - INCLUDE_DIRS Algorithms DataManagement Controllers Interactions IO Rendering ${MITK_BINARY_DIR} + INCLUDE_DIRS Algorithms DataManagement Controllers Interactions IO Rendering Service ${MITK_BINARY_DIR} INTERNAL_INCLUDE_DIRS ${OPENGL_INCLUDE_DIR} ${IPSEGMENTATION_INCLUDE_DIR} ${ANN_INCLUDE_DIR} DEPENDS mitkIpFunc mbilog tinyxml DEPENDS_INTERNAL IIL4MITK pic2vtk PACKAGE_DEPENDS ITK VTK EXPORT_DEFINE MITK_CORE_EXPORT ) # this is needed for libraries which link to Mitk and need # symbols from explicitly instantiated templates like # mitk::SurfaceVtkWriter which is referenced in # QmitkCommonFunctionality in the QmitkExt library. IF(MINGW) GET_TARGET_PROPERTY(_mitkCore_MINGW_linkflags Mitk LINK_FLAGS) IF(NOT _mitkCore_MINGW_linkflags) SET(_mitkCore_MINGW_linkflags "") ENDIF(NOT _mitkCore_MINGW_linkflags) SET_TARGET_PROPERTIES(Mitk PROPERTIES LINK_FLAGS "${_mitkCore_MINGW_linkflags} -Wl,--export-all-symbols") ENDIF(MINGW) # replacing Mitk by Mitk [due to removing the PROVIDES macro TARGET_LINK_LIBRARIES(Mitk ${LIBRARIES_FOR_${KITNAME}_CORE} ${IPFUNC_LIBRARY} ipSegmentation ann) TARGET_LINK_LIBRARIES(Mitk ${OPENGL_LIBRARIES} ) IF(MSVC_IDE OR MSVC_VERSION OR MINGW) TARGET_LINK_LIBRARIES(Mitk psapi.lib) ENDIF(MSVC_IDE OR MSVC_VERSION OR MINGW) # verify ITK has been built with GDCM >= 2.0.14 set(GDCM_FULL_VERSION "${GDCM_MAJOR_VERSION}.${GDCM_MINOR_VERSION}.${GDCM_BUILD_VERSION}") set(MITK_REQUIRED_GDCM_VERSION "2.0.14") if(GDCM_FULL_VERSION VERSION_LESS MITK_REQUIRED_GDCM_VERSION) message(SEND_ERROR "Mitk: MITK requires ITK with at least GDCM version ${MITK_REQUIRED_GDCM_VERSION}.\nFound version ${GDCM_FULL_VERSION} (GDCM NOT found if you don't see a version here)") else(GDCM_FULL_VERSION VERSION_LESS MITK_REQUIRED_GDCM_VERSION) message(STATUS "Mitk: Found GDCM version ${GDCM_FULL_VERSION}") endif(GDCM_FULL_VERSION VERSION_LESS MITK_REQUIRED_GDCM_VERSION) # build tests? OPTION(BUILD_TESTING "Build the MITK Core tests." ON) IF(BUILD_TESTING) ENABLE_TESTING() ADD_SUBDIRECTORY(Testing) ENDIF(BUILD_TESTING) diff --git a/Core/Code/DataManagement/mitkCommon.h b/Core/Code/DataManagement/mitkCommon.h index fa0d9ef3c8..b5063273e7 100644 --- a/Core/Code/DataManagement/mitkCommon.h +++ b/Core/Code/DataManagement/mitkCommon.h @@ -1,107 +1,124 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef MITK_COMMON_H_DEFINED #define MITK_COMMON_H_DEFINED #ifdef _MSC_VER // This warns about truncation to 255 characters in debug/browse info #pragma warning (disable : 4786) #pragma warning (disable : 4068 ) /* disable unknown pragma warnings */ #endif //add only those headers here that are really necessary for all classes! #include "itkObject.h" #include "mitkConfig.h" #include "mitkLogMacros.h" +#include "mitkExportMacros.h" #ifndef MITK_UNMANGLE_IPPIC #define mitkIpPicDescriptor mitkIpPicDescriptor #endif typedef unsigned int MapperSlotId; #define mitkClassMacro(className,SuperClassName) \ typedef className Self; \ typedef SuperClassName Superclass; \ typedef itk::SmartPointer Pointer; \ typedef itk::SmartPointer ConstPointer; \ itkTypeMacro(className,SuperClassName) /** * Macro for Constructors with one parameter for classes derived from itk::Lightobject **/ #define mitkNewMacro1Param(classname,type) \ static Pointer New(type _arg) \ { \ Pointer smartPtr = new classname ( _arg ); \ smartPtr->UnRegister(); \ return smartPtr; \ } \ /** * Macro for Constructors with two parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro2Param(classname,typea,typeb) \ static Pointer New(typea _arga, typeb _argb) \ { \ Pointer smartPtr = new classname ( _arga, _argb ); \ smartPtr->UnRegister(); \ return smartPtr; \ } \ /** * Macro for Constructors with three parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro3Param(classname,typea,typeb,typec) \ static Pointer New(typea _arga, typeb _argb, typec _argc) \ { \ Pointer smartPtr = new classname ( _arga, _argb, _argc ); \ smartPtr->UnRegister(); \ return smartPtr; \ } \ /** * Macro for Constructors with three parameters for classes derived from itk::Lightobject **/ #define mitkNewMacro4Param(classname,typea,typeb,typec,typed) \ static Pointer New(typea _arga, typeb _argb, typec _argc, typed _argd) \ { \ Pointer smartPtr = new classname ( _arga, _argb, _argc, _argd ); \ smartPtr->UnRegister(); \ return smartPtr; \ } \ /** Get a smart const pointer to an object. Creates the member * Get"name"() (e.g., GetPoints()). */ #define mitkGetObjectMacroConst(name,type) \ virtual type * Get##name () const \ { \ itkDebugMacro("returning " #name " address " << this->m_##name ); \ return this->m_##name.GetPointer(); \ } /** Creates a Clone() method for "Classname". Returns a smartPtr of a clone of the calling object*/ #define mitkCloneMacro(classname) \ virtual Pointer Clone() const \ { \ Pointer smartPtr = new classname(*this); \ return smartPtr; \ } + +#define MITK_EXPORT_MODULE_ACTIVATOR(moduleName, type) \ + extern "C" MITK_EXPORT mitk::ModuleActivator* _mitk_module_activator_instance_ ## moduleName () \ + { \ + struct ScopedPointer \ + { \ + ScopedPointer(mitk::ModuleActivator* activator = 0) : m_Activator(activator) {} \ + ~ScopedPointer() { delete m_Activator; } \ + mitk::ModuleActivator* m_Activator; \ + }; \ + \ + static ScopedPointer activatorPtr; \ + if (activatorPtr.m_Activator == 0) activatorPtr.m_Activator = new type; \ + return activatorPtr.m_Activator; \ + } + #endif // MITK_COMMON_H_DEFINED diff --git a/Core/Code/Interactions/mitkMessage.h b/Core/Code/Interactions/mitkMessage.h index e5ab84a236..2fa399ffae 100644 --- a/Core/Code/Interactions/mitkMessage.h +++ b/Core/Code/Interactions/mitkMessage.h @@ -1,1080 +1,802 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 14123 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef mitkMessageHIncluded #define mitkMessageHIncluded #include +#include #include /** * Adds a Message<> variable and methods to add/remove message delegates to/from * this variable. */ #define mitkNewMessageMacro(msgHandleObject) \ private: ::mitk::Message<> m_##msgHandleObject##Message; \ public: \ inline void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate<>& delegate) \ { m_##msgHandleObject##Message += delegate; } \ inline void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate<>& delegate) \ { m_##msgHandleObject##Message -= delegate; } \ #define mitkNewMessageWithReturnMacro(msgHandleObject, returnType) \ private: ::mitk::Message m_##msgHandleObject##Message; \ public: \ inline void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate& delegate) \ { m_##msgHandleObject##Message += delegate; } \ inline void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate& delegate) \ { m_##msgHandleObject##Message -= delegate; } \ #define mitkNewMessage1Macro(msgHandleObject, type1) \ private: ::mitk::Message1< type1 > m_##msgHandleObject##Message; \ public: \ void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate1< type1 >& delegate) \ { m_##msgHandleObject##Message += delegate; } \ void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate1< type1 >& delegate) \ { m_##msgHandleObject##Message -= delegate; } #define mitkNewMessage2Macro(msgHandleObject, type1, type2) \ private: ::mitk::Message2< type1, type2 > m_##msgHandleObject##Message; \ public: \ void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate2< type1, type2 >& delegate) \ { m_##msgHandleObject##Message += delegate; } \ void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate2< type1, type2 >& delegate) \ { m_##msgHandleObject##Message -= delegate; } namespace mitk { template class MessageAbstractDelegate { public: virtual ~MessageAbstractDelegate() { } - virtual A Execute() = 0; - virtual bool operator==(const MessageAbstractDelegate* cmd) = 0; + virtual A Execute() const = 0; + virtual bool operator==(const MessageAbstractDelegate* cmd) const = 0; virtual MessageAbstractDelegate* Clone() const = 0; }; - template class MessageAbstractDelegate1 { public: virtual ~MessageAbstractDelegate1() { } - virtual A Execute(T t) = 0; - virtual bool operator==(const MessageAbstractDelegate1* cmd) = 0; + virtual A Execute(T t) const = 0; + virtual bool operator==(const MessageAbstractDelegate1* cmd) const = 0; virtual MessageAbstractDelegate1* Clone() const = 0; }; template class MessageAbstractDelegate2 { public: virtual ~MessageAbstractDelegate2() { } virtual A Execute(T t, U u) const = 0; - virtual bool operator==(const MessageAbstractDelegate2* cmd) = 0; + virtual bool operator==(const MessageAbstractDelegate2* cmd) const = 0; virtual MessageAbstractDelegate2* Clone() const = 0; }; template class MessageAbstractDelegate3 { public: virtual ~MessageAbstractDelegate3() { } virtual A Execute(T t, U u, V v) const = 0; - virtual bool operator==(const MessageAbstractDelegate3* cmd) = 0; + virtual bool operator==(const MessageAbstractDelegate3* cmd) const = 0; virtual MessageAbstractDelegate3* Clone() const = 0; }; template class MessageAbstractDelegate4 { public: virtual ~MessageAbstractDelegate4() { } virtual A Execute(T t, U u, V v, W w) const = 0; - virtual bool operator==(const MessageAbstractDelegate4* cmd) = 0; + virtual bool operator==(const MessageAbstractDelegate4* cmd) const = 0; virtual MessageAbstractDelegate4* Clone() const = 0; }; /** * This class essentially wraps a function pointer with signature * A(R::*function)(). A is the return type of your callback function * and R the type of the class implementing the function. * * Use this class to add a callback function to * messages without parameters. */ template class MessageDelegate : public MessageAbstractDelegate { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate(R* object, A(R::*memberFunctionPointer)()) :m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate() { } // override function "Call" - virtual A Execute() + virtual A Execute() const { return (m_Object->*m_MemberFunctionPointer)(); // execute member function } - bool operator==(const MessageAbstractDelegate* c) + bool operator==(const MessageAbstractDelegate* c) const { const MessageDelegate* cmd = dynamic_cast* >(c); if (!cmd) return false; if ((void*)this->m_Object != (void*)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate* Clone() const { return new MessageDelegate(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(); // pointer to member function }; /** * This class essentially wraps a function pointer with signature * A(R::*function)(T). A is the return type of your callback function, * R the type of the class implementing the function and T the type * of the argument. * * Use this class to add a callback function to * messages with one parameter. * * If you need more parameters, use MessageDelegate2 etc. */ template class MessageDelegate1 : public MessageAbstractDelegate1 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate1(R* object, A(R::*memberFunctionPointer)(T)) :m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate1() { } // override function "Call" - virtual A Execute(T t) + virtual A Execute(T t) const { return (m_Object->*m_MemberFunctionPointer)(t); // execute member function } - bool operator==(const MessageAbstractDelegate1* c) + bool operator==(const MessageAbstractDelegate1* c) const { const MessageDelegate1* cmd = dynamic_cast* >(c); if (!cmd) return false; if ((void*)this->m_Object != (void*)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate1* Clone() const { return new MessageDelegate1(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T); // pointer to member function }; template class MessageDelegate2 : public MessageAbstractDelegate2 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate2(R* object, A(R::*memberFunctionPointer)(T, U)) :m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate2() { } // override function "Call" virtual A Execute(T t, U u) const { return (m_Object->*m_MemberFunctionPointer)(t,u); // execute member function } - bool operator==(const MessageAbstractDelegate2* c) + bool operator==(const MessageAbstractDelegate2* c) const { const MessageDelegate2* cmd = dynamic_cast* >(c); if (!cmd) return false; if ((void*)this->m_Object != (void*)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate2* Clone() const { return new MessageDelegate2(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U); // pointer to member function }; template class MessageDelegate3 : public MessageAbstractDelegate3 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate3(R* object, A(R::*memberFunctionPointer)(T, U, V)) :m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate3() { } // override function "Call" virtual A Execute(T t, U u, V v) const { return (m_Object->*m_MemberFunctionPointer)(t,u,v); // execute member function } - bool operator==(const MessageAbstractDelegate3* c) + bool operator==(const MessageAbstractDelegate3* c) const { const MessageDelegate3* cmd = dynamic_cast* >(c); if (!cmd) return false; if ((void*)this->m_Object != (void*)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate3* Clone() const { return new MessageDelegate3(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U, V); // pointer to member function }; template class MessageDelegate4 : public MessageAbstractDelegate4 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate4(R* object, A(R::*memberFunctionPointer)(T, U, V, W)) :m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate4() { } // override function "Call" virtual A Execute(T t, U u, V v, W w) const { return (m_Object->*m_MemberFunctionPointer)(t,u,v,w); // execute member function } - bool operator==(const MessageAbstractDelegate4* c) + bool operator==(const MessageAbstractDelegate4* c) const { const MessageDelegate4* cmd = dynamic_cast* >(c); if (!cmd) return false; if ((void*)this->m_Object != (void*)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate4* Clone() const { return new MessageDelegate4(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U, V, W); // pointer to member function }; + +template +class MessageBase +{ + public: + + typedef std::vector ListenerList; + + virtual ~MessageBase() { + for (typename ListenerList::iterator iter = m_Listeners.begin(); + iter != m_Listeners.end(); ++iter ) + { + delete *iter; + } + } + + MessageBase() {} + + MessageBase(const MessageBase& o) + { + for (typename ListenerList::iterator iter = o.m_Listeners.begin(); + iter != o.m_Listeners.end(); ++iter ) + { + m_Listeners.push_back((*iter)->Clone()); + } + } + + MessageBase& operator=(const MessageBase& o) + { + MessageBase tmp(o); + std::swap(tmp.m_Listeners, this->m_Listeners); + } + + void AddListener( const AbstractDelegate& delegate ) const + { + AbstractDelegate* msgCmd = delegate.Clone(); + + m_Mutex.Lock(); + for (typename ListenerList::iterator iter = m_Listeners.begin(); + iter != m_Listeners.end(); + ++iter ) + { + if ((*iter)->operator==(msgCmd)) { + delete msgCmd; + m_Mutex.Unlock(); + return; + } + } + m_Listeners.push_back(msgCmd); + m_Mutex.Unlock(); + } + + void operator += ( const AbstractDelegate& delegate ) const + { + this->AddListener(delegate); + } + + void RemoveListener( const AbstractDelegate& delegate ) const + { + m_Mutex.Lock(); + for (typename ListenerList::iterator iter = m_Listeners.begin(); + iter != m_Listeners.end(); + ++iter ) + { + if ((*iter)->operator==(&delegate)) + { + delete *iter; + m_Listeners.erase( iter ); + m_Mutex.Unlock(); + return; + } + } + m_Mutex.Unlock(); + } + + void operator -= ( const AbstractDelegate& delegate) const + { + this->RemoveListener(delegate); + } + + const ListenerList& GetListeners() const + { + return m_Listeners; + } + + bool HasListeners() const + { + return !m_Listeners.empty(); + } + + bool IsEmpty() const + { + return m_Listeners.empty(); + } + + protected: + + /** + * \brief List of listeners. + * + * This is declared mutable for a reason: Imagine an object that sends out notifications, e.g. + * + * \code +class Database { + public: + Message Modified; +}; + * \endcode + * + * Now imaginge someone gets a const Database object, because he/she should not write to the + * database. He/she should anyway be able to register for notifications about changes in the database + * -- this is why AddListener and RemoveListener are declared const. m_Listeners must be + * mutable so that AddListener and RemoveListener can modify it regardless of the object's constness. + */ + mutable ListenerList m_Listeners; + mutable itk::SimpleFastMutexLock m_Mutex; + +}; + /** * \brief Event/message/notification class. * * \sa mitk::BinaryThresholdTool * \sa QmitkBinaryThresholdToolGUI * * This totally ITK, Qt, VTK, whatever toolkit independent class * allows one class to send out messages and another class to * receive these message. This class is templated over the * return type (A) of the callback functions. * There are variations of this class * (Message1, Message2, etc.) for sending * one, two or more parameters along with the messages. * * This is an implementation of the Observer pattern. * * \li There is no guarantee about the order of which observer is notified first. At the moment the observers which register first will be notified first. * \li Notifications are synchronous, by direct method calls. There is no support for asynchronous messages. * * To conveniently add methods for registering/unregistering observers * to Message variables of your class, you can use the mitkNewMessageMacro * macros. * * Here is an example how to use the macros and templates: * * \code * * // An object to be send around * class Law * { * private: * std::string m_Description; * * public: * * Law(const std::string law) : m_Description(law) * { } * * std::string GetDescription() const * { * return m_Description; * } * }; * * // The NewtonMachine will issue specific events * class NewtonMachine * { * mitkNewMessageMacro(AnalysisStarted); * mitkNewMessage1Macro(AnalysisStopped, bool); * mitkNewMessage1Macro(LawDiscovered, const Law&); * * public: * * void StartAnalysis() * { * // send the "started" signal * m_AnalysisStartedMessage(); * * // we found a new law of nature by creating one :-) * Law massLaw("F=ma"); * m_LawDiscoveredMessage(massLaw); * } * * void StopAnalysis() * { * // send the "stop" message with false, indicating * // that no error occured * m_AnalysisStoppedMessage(false); * } * }; * * class Observer * { * private: * * NewtonMachine* m_Machine; * * public: * * Observer(NewtonMachine* machine) : m_Machine(machine) * { * // Add "observers", i.e. function pointers to the machine * m_Machine->AddAnalysisStartedListener( * ::mitk::MessageDelegate(this, &Observer::MachineStarted)); * m_Machine->AddAnalysisStoppedListener( * ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); * m_Machine->AddLawDiscoveredListener( * ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); * } * * ~Observer() * { * // Always remove your observers when finished * m_Machine->RemoveAnalysisStartedListener( * ::mitk::MessagDelegate(this, &Observer::MachineStarted)); * m_Machine->RemoveAnalysisStoppedListener( * ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); * m_Machine->RemoveLawDiscoveredListener( * ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); * } * * void MachineStarted() * { * std::cout << "Observed machine has started" << std::endl; * } * * void MachineStopped(bool error) * { * std::cout << "Observed machine stopped " << (error ? "with an error" : "") << std::endl; * } * * void LawDiscovered(const Law& law) * { * std::cout << "New law of nature discovered: " << law.GetDescription() << std::endl; * } * }; * * NewtonMachine newtonMachine; * Observer observer(&newtonMachine); * * // This will send two events to registered observers * newtonMachine.StartAnalysis(); * // This will send one event to registered observers * newtonMachine.StopAnalysis(); * * \endcode * * Another example of how to use these message classes can be * found in the directory Testing, file mitkMessageTest.cpp * */ template -class Message +class Message : public MessageBase< MessageAbstractDelegate > { - public: - - typedef Message Self; - typedef MessageAbstractDelegate AbstractDelegate; - typedef std::vector ListenerList; - ~Message() { - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); ++iter ) - { - delete *iter; - } - } +public: - void AddListener( const AbstractDelegate& delegate ) const - { - AbstractDelegate* msgCmd = delegate.Clone(); + typedef MessageBase< MessageAbstractDelegate > Super; + typedef typename Super::ListenerList ListenerList; - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(msgCmd)) { - delete msgCmd; - m_Mutex.Unlock(); - return; - } - } - m_Listeners.push_back(msgCmd); - m_Mutex.Unlock(); - } + void Send() + { + ListenerList listeners; - void operator += ( const AbstractDelegate& delegate ) const { - this->AddListener(delegate); + this->m_Mutex.Lock(); + listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); + this->m_Mutex.Unlock(); } - void RemoveListener( const AbstractDelegate& delegate ) const - { - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); + for (typename ListenerList::iterator iter = listeners.begin(); + iter != listeners.end(); ++iter ) { - if ((*iter)->operator==(&delegate)) - { - delete *iter; - m_Listeners.erase( iter ); - m_Mutex.Unlock(); - return; - } + // notify each listener + (*iter)->Execute(); } - m_Mutex.Unlock(); - } + } - void operator -= ( const AbstractDelegate& delegate) const - { - this->RemoveListener(delegate); - } + void operator()() + { + this->Send(); + } +}; - void Send() - { - ListenerList listeners; - { - m_Mutex.Lock(); - listeners.assign(m_Listeners.begin(), m_Listeners.end()); - m_Mutex.Unlock(); - } +// message with 1 parameter and return type +template +class Message1 : public MessageBase< MessageAbstractDelegate1 > +{ - for (typename ListenerList::iterator iter = listeners.begin(); - iter != listeners.end(); - ++iter ) - { - // notify each listener - (*iter)->Execute(); - } - } - void operator()() +public: + + typedef MessageBase< MessageAbstractDelegate1 > Super; + typedef typename Super::ListenerList ListenerList; + + void Send(T t) + { + ListenerList listeners; + { - this->Send(); + this->m_Mutex.Lock(); + listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); + this->m_Mutex.Unlock(); } - const ListenerList& GetListeners() const + for ( typename ListenerList::iterator iter = listeners.begin(); + iter != listeners.end(); + ++iter ) { - return m_Listeners; + // notify each listener + (*iter)->Execute(t); } + } + + void operator()(T t) + { + this->Send(t); + } +}; + + +// message with 2 parameters and return type +template +class Message2 : public MessageBase< MessageAbstractDelegate2 > +{ + +public: + + typedef MessageBase< MessageAbstractDelegate2 > Super; + typedef typename Super::ListenerList ListenerList; + + void Send(T t, U u) + { + ListenerList listeners; - bool HasListeners() const { - return !m_Listeners.empty(); + this->m_Mutex.Lock(); + listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); + this->m_Mutex.Unlock(); } - bool IsEmpty() const + for ( typename ListenerList::iterator iter = listeners.begin(); + iter != listeners.end(); + ++iter ) { - return m_Listeners.empty(); + // notify each listener + (*iter)->Execute(t,u); } + } - protected: - - /** - * \brief List of listeners. - * - * This is declared mutable for a reason: Imagine an object that sends out notifications, e.g. - * - * \code -class Database { - public: - Message Modified; + void operator()(T t, U u) + { + this->Send(t, u); + } }; - * \endcode - * - * Now imaginge someone gets a const Database object, because he/she should not write to the - * database. He/she should anyway be able to register for notifications about changes in the database - * -- this is why AddListener and RemoveListener are declared const. m_Listeners must be - * mutable so that AddListener and RemoveListener can modify it regardless of the object's constness. - */ - mutable ListenerList m_Listeners; - mutable itk::SimpleFastMutexLock m_Mutex; -}; +// message with 3 parameters and return type +template +class Message3 : public MessageBase< MessageAbstractDelegate3 > +{ +public: -// message with 1 parameter and return type -template -class Message1 -{ - public: + typedef MessageBase< MessageAbstractDelegate3 > Super; + typedef typename Super::ListenerList ListenerList; - typedef Message1 Self; - typedef MessageAbstractDelegate1 AbstractDelegate; - typedef std::vector ListenerList; + void Send(T t, U u, V v) + { + ListenerList listeners; - ~Message1() { - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); ++iter ) - { - delete *iter; - } + this->m_Mutex.Lock(); + listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); + this->m_Mutex.Unlock(); } - void AddListener( const AbstractDelegate& delegate ) const + for ( typename ListenerList::iterator iter = listeners.begin(); + iter != listeners.end(); + ++iter ) { - AbstractDelegate* msgCmd = delegate.Clone(); - - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(msgCmd)) { - delete msgCmd; - m_Mutex.Unlock(); - return; - } - } - m_Listeners.push_back(msgCmd); - m_Mutex.Unlock(); + // notify each listener + (*iter)->Execute(t,u,v); } + } + + void operator()(T t, U u, V v) + { + this->Send(t, u, v); + } +}; + +// message with 4 parameters and return type +template +class Message4 : public MessageBase< MessageAbstractDelegate4 > +{ + +public: + + typedef MessageBase< MessageAbstractDelegate4 > Super; + typedef typename Super::ListenerList ListenerList; + + void Send(T t, U u, V v, W w) + { + ListenerList listeners; - void operator += ( const AbstractDelegate& delegate ) const { - this->AddListener(delegate); + this->m_Mutex.Lock(); + listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); + this->m_Mutex.Unlock(); } - void RemoveListener( const AbstractDelegate& delegate ) const + for ( typename ListenerList::iterator iter = listeners.begin(); + iter != listeners.end(); + ++iter ) { - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(&delegate)) - { - delete *iter; - m_Listeners.erase( iter ); - m_Mutex.Unlock(); - return; - } - } - m_Mutex.Unlock(); - } - - void operator -= ( const AbstractDelegate& delegate) const - { - this->RemoveListener(delegate); - } - - void Send(T t) - { - ListenerList listeners; - - { - m_Mutex.Lock(); - listeners.assign(m_Listeners.begin(), m_Listeners.end()); - m_Mutex.Unlock(); - } - - for ( typename ListenerList::iterator iter = listeners.begin(); - iter != listeners.end(); - ++iter ) - { - // notify each listener - (*iter)->Execute(t); - } - } - - void operator()(T t) - { - this->Send(t); - } - - const ListenerList& GetListeners() const - { - return m_Listeners; - } - - bool HasListeners() const - { - return !m_Listeners.empty(); - } - - bool IsEmpty() const - { - return m_Listeners.empty(); - } - - protected: - - mutable ListenerList m_Listeners; - mutable itk::SimpleFastMutexLock m_Mutex; - -}; - - -// message with 2 parameters and return type -template -class Message2 -{ - public: - - typedef Message2 Self; - typedef MessageAbstractDelegate2 AbstractDelegate; - typedef std::vector ListenerList; - - ~Message2() { - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); ++iter ) - { - delete *iter; - } - } - - void AddListener( const AbstractDelegate& delegate ) const - { - AbstractDelegate* msgCmd = delegate.Clone(); - - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(msgCmd)) { - delete msgCmd; - m_Mutex.Unlock(); - return; - } - } - m_Listeners.push_back(msgCmd); - m_Mutex.Unlock(); - } - - void operator += ( const AbstractDelegate& delegate ) const - { - this->AddListener(delegate); - } - - void RemoveListener( const AbstractDelegate& delegate ) const - { - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(&delegate)) - { - delete *iter; - m_Listeners.erase( iter ); - m_Mutex.Unlock(); - return; - } - } - m_Mutex.Unlock(); - } - - void operator -= ( const AbstractDelegate& delegate) const - { - this->RemoveListener(delegate); - } - - void Send(T t, U u) - { - ListenerList listeners; - - { - m_Mutex.Lock(); - listeners.assign(m_Listeners.begin(), m_Listeners.end()); - m_Mutex.Unlock(); - } - - for ( typename ListenerList::iterator iter = listeners.begin(); - iter != listeners.end(); - ++iter ) - { - // notify each listener - (*iter)->Execute(t,u); - } - } - - void operator()(T t, U u) - { - this->Send(t, u); - } - - const ListenerList& GetListeners() const - { - return m_Listeners; - } - - bool HasListeners() const - { - return !m_Listeners.empty(); - } - - bool IsEmpty() const - { - return m_Listeners.empty(); - } - - protected: - - mutable ListenerList m_Listeners; - mutable itk::SimpleFastMutexLock m_Mutex; - -}; - -// message with 3 parameters and return type -template -class Message3 -{ - public: - - typedef Message3 Self; - typedef MessageAbstractDelegate3 AbstractDelegate; - typedef std::vector ListenerList; - - ~Message3() { - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); ++iter ) - { - delete *iter; - } - } - - void AddListener( const AbstractDelegate& delegate ) const - { - AbstractDelegate* msgCmd = delegate.Clone(); - - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(msgCmd)) { - delete msgCmd; - m_Mutex.Unlock(); - return; - } - } - m_Listeners.push_back(msgCmd); - m_Mutex.Unlock(); - } - - void operator += ( const AbstractDelegate& delegate ) const - { - this->AddListener(delegate); - } - - void RemoveListener(const AbstractDelegate& delegate ) const - { - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(&delegate)) - { - delete *iter; - m_Listeners.erase( iter ); - m_Mutex.Unlock(); - return; - } - } - m_Mutex.Unlock(); - } - - void operator -= ( const AbstractDelegate& delegate) const - { - this->RemoveListener(delegate); - } - - void Send(T t, U u, V v) - { - ListenerList listeners; - - { - m_Mutex.Lock(); - listeners.assign(m_Listeners.begin(), m_Listeners.end()); - m_Mutex.Unlock(); - } - - for ( typename ListenerList::iterator iter = listeners.begin(); - iter != listeners.end(); - ++iter ) - { - // notify each listener - (*iter)->Execute(t,u,v); - } - } - - void operator()(T t, U u, V v) - { - this->Send(t, u, v); - } - - const ListenerList& GetListeners() const - { - return m_Listeners; - } - - bool HasListeners() const - { - return !m_Listeners.empty(); - } - - bool IsEmpty() const - { - return m_Listeners.empty(); + // notify each listener + (*iter)->Execute(t,u,v,w); } + } - protected: - - mutable ListenerList m_Listeners; - mutable itk::SimpleFastMutexLock m_Mutex; - -}; - -// message with 4 parameters and return type -template -class Message4 -{ - public: - - typedef Message4 Self; - typedef MessageAbstractDelegate4 AbstractDelegate; - typedef std::vector ListenerList; - - ~Message4() { - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); ++iter ) - { - delete *iter; - } - } - - void AddListener( const AbstractDelegate& delegate ) const - { - AbstractDelegate* msgCmd = delegate.Clone(); - - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(msgCmd)) { - delete msgCmd; - m_Mutex.Unlock(); - return; - } - } - m_Listeners.push_back(msgCmd); - m_Mutex.Unlock(); - } - - void operator += ( const AbstractDelegate& delegate ) const - { - this->AddListener(delegate); - } - - void RemoveListener( const AbstractDelegate& delegate ) const - { - m_Mutex.Lock(); - for (typename ListenerList::iterator iter = m_Listeners.begin(); - iter != m_Listeners.end(); - ++iter ) - { - if ((*iter)->operator==(&delegate)) - { - delete *iter; - m_Listeners.erase( iter ); - m_Mutex.Unlock(); - return; - } - } - m_Mutex.Unlock(); - } - - void operator -= ( const AbstractDelegate& delegate) const - { - this->RemoveListener(delegate); - } - - void Send(T t, U u, V v, W w) - { - ListenerList listeners; - - { - m_Mutex.Lock(); - listeners.assign(m_Listeners.begin(), m_Listeners.end()); - m_Mutex.Unlock(); - } - - for ( typename ListenerList::iterator iter = listeners.begin(); - iter != listeners.end(); - ++iter ) - { - // notify each listener - (*iter)->Execute(t,u,v,w); - } - } - - void operator()(T t, U u, V v, W w) - { - this->Send(t, u, v, w); - } - - const ListenerList& GetListeners() const - { - return this->m_Listeners; - } - - bool HasListeners() const - { - return !m_Listeners.empty(); - } - - bool IsEmpty() const - { - return m_Listeners.empty(); - } - - protected: - - mutable ListenerList m_Listeners; - mutable itk::SimpleFastMutexLock m_Mutex; - + void operator()(T t, U u, V v, W w) + { + this->Send(t, u, v, w); + } }; } // namespace #endif diff --git a/Core/Code/Service/mitkAny.cpp b/Core/Code/Service/mitkAny.cpp new file mode 100644 index 0000000000..874c6e13cc --- /dev/null +++ b/Core/Code/Service/mitkAny.cpp @@ -0,0 +1,51 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkAny.h" + +namespace mitk { + +template +std::string container_to_string(Iterator i1, Iterator i2) +{ + std::stringstream ss; + ss << "("; + const Iterator begin = i1; + for ( ; i1 != i2; ++i1) + { + if (i1 == begin) ss << *i1; + else ss << "," << *i1; + } + return ss.str(); +} + +std::string any_value_to_string(const std::vector& val) +{ + return container_to_string(val.begin(), val.end()); +} + +std::string any_value_to_string(const std::list& val) +{ + return container_to_string(val.begin(), val.end()); +} + +std::string any_value_to_string(const std::vector& val) +{ + return container_to_string(val.begin(), val.end()); +} + +} diff --git a/Core/Code/Service/mitkAny.h b/Core/Code/Service/mitkAny.h new file mode 100644 index 0000000000..5fb6158f60 --- /dev/null +++ b/Core/Code/Service/mitkAny.h @@ -0,0 +1,401 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + + +Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. +Extracted from Boost 1.46.1 and adapted for MITK + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +=========================================================================*/ + +#ifndef MITK_ANY_H +#define MITK_ANY_H + +#include +#include +#include +#include +#include + +#include + +namespace mitk { + +template +std::string any_value_to_string(const T& val); + +MITK_CORE_EXPORT std::string any_value_to_string(const std::vector& val); +MITK_CORE_EXPORT std::string any_value_to_string(const std::list& val); + +/** + * An Any class represents a general type and is capable of storing any type, supporting type-safe extraction + * of the internally stored data. + * + * Code taken from the Boost 1.46.1 library. Original copyright by Kevlin Henney. Modified for MITK. + */ +class Any +{ +public: + + /** + * Creates an empty any type. + */ + Any(): _content(0) + { } + + /** + * Creates an Any which stores the init parameter inside. + * + * \param value The content of the Any + * + * Example: + * \code + * Any a(13); + * Any a(string("12345")); + * \endcode + */ + template + Any(const ValueType& value) + : _content(new Holder(value)) + { } + + /** + * Copy constructor, works with empty Anys and initialized Any values. + * + * \param other The Any to copy + */ + Any(const Any& other) + : _content(other._content ? other._content->Clone() : 0) + { } + + ~Any() + { + delete _content; + } + + /** + * Swaps the content of the two Anys. + * + * \param rhs The Any to swap this Any with. + */ + Any& Swap(Any& rhs) + { + std::swap(_content, rhs._content); + return *this; + } + + /** + * Assignment operator for all types != Any. + * + * \param rhs The value which should be assigned to this Any. + * + * Example: + * \code + * Any a = 13; + * Any a = string("12345"); + * \endcode + */ + template + Any& operator = (const ValueType& rhs) + { + Any(rhs).Swap(*this); + return *this; + } + + /** + * Assignment operator for Any. + * + * \param rhs The Any which should be assigned to this Any. + */ + Any& operator = (const Any& rhs) + { + Any(rhs).Swap(*this); + return *this; + } + + /** + * returns true if the Any is empty + */ + bool Empty() const + { + return !_content; + } + + /** + * Returns a string representation for the content. + * + * Custom types should either provide a std::ostream& operator<<(std::ostream& os, const CustomType& ct) + * function or specialize the any_value_to_string template function for meaningful output. + */ + std::string ToString() const + { + return _content->ToString(); + } + + /** + * Returns the type information of the stored content. + * If the Any is empty typeid(void) is returned. + * It is suggested to always query an Any for its type info before trying to extract + * data via an any_cast/ref_any_cast. + */ + const std::type_info& Type() const + { + return _content ? _content->Type() : typeid(void); + } + +private: + + class Placeholder + { + public: + virtual ~Placeholder() + { } + + virtual std::string ToString() const = 0; + + virtual const std::type_info& Type() const = 0; + virtual Placeholder* Clone() const = 0; + }; + + template + class Holder: public Placeholder + { + public: + Holder(const ValueType& value) + : _held(value) + { } + + virtual std::string ToString() const + { + return any_value_to_string(_held); + } + + virtual const std::type_info& Type() const + { + return typeid(ValueType); + } + + virtual Placeholder* Clone() const + { + return new Holder(_held); + } + + ValueType _held; + + private: // intentionally left unimplemented + Holder& operator=(const Holder &); + }; + +private: + template + friend ValueType* any_cast(Any*); + + template + friend ValueType* unsafe_any_cast(Any*); + + Placeholder* _content; +}; + +class BadAnyCastException : public std::bad_cast +{ +public: + + BadAnyCastException(const std::string& msg = "") + : std::bad_cast(), _msg(msg) + {} + + ~BadAnyCastException() throw() {} + + virtual const char * what() const throw() + { + if (_msg.empty()) + return "mitk::BadAnyCastException: " + "failed conversion using mitk::any_cast"; + else + return _msg.c_str(); + } + +private: + + std::string _msg; +}; + +/** + * any_cast operator used to extract the ValueType from an Any*. Will return a pointer + * to the stored value. + * + * Example Usage: + * \code + * MyType* pTmp = any_cast(pAny) + * \endcode + * Will return NULL if the cast fails, i.e. types don't match. + */ +template +ValueType* any_cast(Any* operand) +{ + return operand && operand->Type() == typeid(ValueType) + ? &static_cast*>(operand->_content)->_held + : 0; +} + +/** + * any_cast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer + * to the stored value. + * + * Example Usage: + * \code + * const MyType* pTmp = any_cast(pAny) + * \endcode + * Will return NULL if the cast fails, i.e. types don't match. + */ +template +const ValueType* any_cast(const Any* operand) +{ + return any_cast(const_cast(operand)); +} + +/** + * any_cast operator used to extract a copy of the ValueType from an const Any&. + * + * Example Usage: + * \code + * MyType tmp = any_cast(anAny) + * \endcode + * Will throw a BadCastException if the cast fails. + * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... + * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in + * these cases. + */ +template +ValueType any_cast(const Any& operand) +{ + ValueType* result = any_cast(const_cast(&operand)); + if (!result) throw BadAnyCastException("Failed to convert between const Any types"); + return *result; +} + +/** + * any_cast operator used to extract a copy of the ValueType from an Any&. + * + * Example Usage: + * \code + * MyType tmp = any_cast(anAny) + * \endcode + * Will throw a BadCastException if the cast fails. + * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... + * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in + * these cases. + */ +template +ValueType any_cast(Any& operand) +{ + ValueType* result = any_cast(&operand); + if (!result) throw BadAnyCastException("Failed to convert between Any types"); + return *result; +} + +/** + * ref_any_cast operator used to return a const reference to the internal data. + * + * Example Usage: + * \code + * const MyType& tmp = ref_any_cast(anAny); + * \endcode + */ +template +const ValueType& ref_any_cast(const Any & operand) +{ + ValueType* result = any_cast(const_cast(&operand)); + if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between const Any types"); + return *result; +} + +/** + * ref_any_cast operator used to return a reference to the internal data. + * + * Example Usage: + * \code + * MyType& tmp = ref_any_cast(anAny); + * \endcode + */ +template +ValueType& ref_any_cast(Any& operand) +{ + ValueType* result = any_cast(&operand); + if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between Any types"); + return *result; +} + +/** + * \internal + * + * The "unsafe" versions of any_cast are not part of the + * public interface and may be removed at any time. They are + * required where we know what type is stored in the any and can't + * use typeid() comparison, e.g., when our types may travel across + * different shared libraries. + */ +template +ValueType* unsafe_any_cast(Any* operand) +{ + return &static_cast*>(operand->_content)->_held; +} + +/** + * \internal + * + * The "unsafe" versions of any_cast are not part of the + * public interface and may be removed at any time. They are + * required where we know what type is stored in the any and can't + * use typeid() comparison, e.g., when our types may travel across + * different shared libraries. + */ +template +const ValueType* unsafe_any_cast(const Any* operand) +{ + return any_cast(const_cast(operand)); +} + +MITK_CORE_EXPORT std::string any_value_to_string(const std::vector& val); + +template +std::string any_value_to_string(const T& val) +{ + std::stringstream ss; + ss << val; + return ss.str(); +} + +} // namespace mitk + +inline std::ostream& operator<< (std::ostream& os, const mitk::Any& any) +{ + return os << any.ToString(); +} + +#endif // MITK_ANY_H diff --git a/Core/Code/Service/mitkAtomicInt.cpp b/Core/Code/Service/mitkAtomicInt.cpp new file mode 100644 index 0000000000..031e993bc3 --- /dev/null +++ b/Core/Code/Service/mitkAtomicInt.cpp @@ -0,0 +1,100 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkAtomicInt.h" + +#if defined(__APPLE__) + // OSAtomic.h optimizations only used in 10.5 and later + #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 + #include + #endif + +#elif defined(__GLIBCPP__) || defined(__GLIBCXX__) + #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) + # include + #else + # include + #endif + +#endif + + +namespace mitk +{ + +AtomicInt::AtomicInt(int value) + : m_ReferenceCount(value) +{ + +} + +bool AtomicInt::Ref() const +{ + // Windows optimization +#if (defined(WIN32) || defined(_WIN32)) + return InterlockedIncrement(&m_ReferenceCount); + + // Mac optimization +#elif defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) + #if defined (__LP64__) && __LP64__ + return OSAtomicIncrement64Barrier(&m_ReferenceCount); + #else + return OSAtomicIncrement32Barrier(&m_ReferenceCount); + #endif + + // gcc optimization +#elif defined(__GLIBCPP__) || defined(__GLIBCXX__) + return __sync_add_and_fetch(&m_ReferenceCount, 1); + + // General case +#else + m_ReferenceCountLock.Lock(); + InternalReferenceCountType ref = ++m_ReferenceCount; + m_ReferenceCountLock.Unlock(); + return ref; +#endif +} + +bool AtomicInt::Deref() const +{ + // Windows optimization +#if (defined(WIN32) || defined(_WIN32)) + return InterlockedDecrement(&m_ReferenceCount); + +// Mac optimization +#elif defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) + #if defined (__LP64__) && __LP64__ + return OSAtomicDecrement64Barrier(&m_ReferenceCount); + #else + return OSAtomicDecrement32Barrier(&m_ReferenceCount); + #endif + +// gcc optimization +#elif defined(__GLIBCPP__) || defined(__GLIBCXX__) + return __sync_add_and_fetch(&m_ReferenceCount, -1); + +// General case +#else + m_ReferenceCountLock.Lock(); + InternalReferenceCountType ref = --m_ReferenceCount; + m_ReferenceCountLock.Unlock(); + return ref; +#endif +} + + +} // end namespace itk diff --git a/Core/Code/Service/mitkAtomicInt.h b/Core/Code/Service/mitkAtomicInt.h new file mode 100644 index 0000000000..3f4c5d9255 --- /dev/null +++ b/Core/Code/Service/mitkAtomicInt.h @@ -0,0 +1,94 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKATOMICINT_H +#define MITKATOMICINT_H + +#include "itkFastMutexLock.h" + +#include + +namespace mitk { + +/** + * This class acts as an atomic integer. + * + * The integer value represented by this class can be incremented + * and decremented atomically. This is often useful in reference + * counting scenarios to minimize locking overhead in multi-threaded + * environments. + */ +class MITK_CORE_EXPORT AtomicInt { + +public: + + AtomicInt(int value = 0); + + /** + * Increase the reference count atomically by 1. + * + * \return true if the new value is unequal to zero, false + * otherwise. + */ + bool Ref() const; + + /** + * Decrease the reference count atomically by 1. + * + * \return true if the new value is unequal to zero, false + * otherwise. + */ + bool Deref() const; + + // Non-atomic API + + /** + * Returns the current value. + * + * This operator is not atomic. + */ + inline operator int() const + { + return m_ReferenceCount; + } + +private: + + /** Define the type of the reference count according to the + target. This allows the use of atomic operations */ +#if (defined(WIN32) || defined(_WIN32)) + typedef LONG InternalReferenceCountType; +#elif defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) + #if defined (__LP64__) && __LP64__ + typedef volatile int64_t InternalReferenceCountType; + #else + typedef volatile int32_t InternalReferenceCountType; + #endif +#elif defined(__GLIBCPP__) || defined(__GLIBCXX__) + typedef _Atomic_word InternalReferenceCountType; +#else + typedef int InternalReferenceCountType; + mutable itk::SimpleFastMutexLock m_ReferenceCountLock; +#endif + + mutable InternalReferenceCountType m_ReferenceCount; +}; + +} + +#endif // MITKATOMICINT_H diff --git a/Core/Code/Service/mitkCoreActivator.cpp b/Core/Code/Service/mitkCoreActivator.cpp new file mode 100644 index 0000000000..14c7a0c45c --- /dev/null +++ b/Core/Code/Service/mitkCoreActivator.cpp @@ -0,0 +1,47 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkRenderingManager.h" + +#include + +/* + * This is the module activator for the "Mitk" module. It registers core services + * like ... + */ +class MitkCoreActivator : public mitk::ModuleActivator +{ +public: + + void Load(mitk::ModuleContext* context) + { + //m_RenderingManager = mitk::RenderingManager::New(); + //context->RegisterService(renderingManager.GetPointer()); + } + + void Unload(mitk::ModuleContext* ) + { + + } + +private: + + mitk::RenderingManager::Pointer m_RenderingManager; +}; + +MITK_EXPORT_MODULE_ACTIVATOR(MitkCoreActivator) + diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Core/Code/Service/mitkCoreModuleContext.cpp similarity index 62% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Core/Code/Service/mitkCoreModuleContext.cpp index c09a6d26ee..7255248f2a 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Core/Code/Service/mitkCoreModuleContext.cpp @@ -1,33 +1,32 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +Date: $Date$ +Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#include "mitkCoreModuleContext_p.h" -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog -{ - Q_OBJECT +namespace mitk { - public: +CoreModuleContext::CoreModuleContext() + : services(this) +{ +} - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); +CoreModuleContext::~CoreModuleContext() +{ +} -}; +} diff --git a/Core/Code/Service/mitkCoreModuleContext_p.h b/Core/Code/Service/mitkCoreModuleContext_p.h new file mode 100644 index 0000000000..2c642c3b9a --- /dev/null +++ b/Core/Code/Service/mitkCoreModuleContext_p.h @@ -0,0 +1,59 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKCOREMODULECONTEXT_H +#define MITKCOREMODULECONTEXT_H + +#include "mitkServiceListeners_p.h" +#include "mitkServiceRegistry_p.h" + +namespace mitk { + +class ModuleRegistry; +class Module; + +/** + * This class is not part of the public API. + */ +class CoreModuleContext +{ +public: + + /** + * All listeners in this framework. + */ + ServiceListeners listeners; + + /** + * All registered services in this framework. + */ + ServiceRegistry services; + + /** + * Contruct a core context + * + */ + CoreModuleContext(); + + ~CoreModuleContext(); + +}; + +} + +#endif // MITKCOREMODULECONTEXT_H diff --git a/Core/Code/Service/mitkGetModuleContext.h b/Core/Code/Service/mitkGetModuleContext.h new file mode 100644 index 0000000000..95f46e567c --- /dev/null +++ b/Core/Code/Service/mitkGetModuleContext.h @@ -0,0 +1,48 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKGETMODULECONTEXT_H +#define MITKGETMODULECONTEXT_H + +namespace mitk { + +class ModuleContext; + +/** + * Returns the module context of the calling module. + * + * This function allows easy access to the own ModuleContext instance from + * inside a MITK module. + * + * \internal + * + * Note that the corresponding function definition is provided for each + * module by the mitkModuleInit.cpp file. This file is customized via CMake + * configure_file(...) and automatically compiled into each MITK module. + * Consequently, the GetModuleContext function is not exported, since each + * module gets its "own version". + */ +#if defined(__GNUC__) +__attribute__ ((visibility ("hidden"))) ModuleContext* GetModuleContext(); +#else +ModuleContext* GetModuleContext(); +#endif + +} + +#endif // MITKGETMODULECONTEXT_H diff --git a/Core/Code/Service/mitkItkHashMap.h b/Core/Code/Service/mitkItkHashMap.h new file mode 100644 index 0000000000..19b310fd81 --- /dev/null +++ b/Core/Code/Service/mitkItkHashMap.h @@ -0,0 +1,355 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +/** + * Copyright (c) 1996 + * Silicon Graphics Computer Systems, Inc. + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Silicon Graphics makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * + * Copyright (c) 1994 + * Hewlett-Packard Company + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Hewlett-Packard Company makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * Copyright (c) 1997 + * Moscow Center for SPARC Technology + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Moscow Center for SPARC Technology makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + */ + +#ifndef __itk_hash_map_h +#define __itk_hash_map_h + +#if defined(_MSC_VER) +#pragma warning ( disable : 4786 ) +#endif + +#if (defined(__GNUC__) && (((__GNUC__==3) && (__GNUC_MINOR__>=1) || (__GNUC__>3) ) || ( (__GNUC__==4) && defined(__INTEL_COMPILER) ) )) || (defined(__IBMCPP__) && __IBMCPP__ >= 600) +// Use this hash_map for GNU_C versions >= 3.1, IBMCPP >=600, or Intel compilers with GCCv4 + +// #if (defined(__GNUC__) && ((__GNUC__==4) && (__GNUC_MINOR__>=3) ) ) +// in gcc 4.3 the header was deprecated and replaced with . +// note that this is still experimental in gcc 4.3 +// #include +// #else +#include +// #endif + +namespace itk +{ + using __gnu_cxx::hash; + using __gnu_cxx::hash_map; + using __gnu_cxx::hash_multimap; +} + +#else + +#include "mitkItkHashTable.h" +#include "itk_alloc.h" + + +// The following is required for CodeWarrior +#if defined(__MWERKS__) +#include "vcl_functional.h" +#endif + +#include "vcl_compiler.h" + + +namespace itk +{ + +# define VCL_IMPORT_CONTAINER_TYPEDEFS(super) \ + typedef typename super::value_type value_type; \ + typedef typename super::reference reference; \ + typedef typename super::size_type size_type; \ + typedef typename super::const_reference const_reference; \ + typedef typename super::difference_type difference_type; + +# define VCL_IMPORT_ITERATORS(super) \ + typedef typename super::iterator iterator; \ + typedef typename super::const_iterator const_iterator; + +# define VCL_IMPORT_REVERSE_ITERATORS(super) \ + typedef typename super::const_reverse_iterator const_reverse_iterator; \ + typedef typename super::reverse_iterator reverse_iterator; + +template +class hash_map; +template +class hash_multimap; + +template +bool operator==(const hash_map&, + const hash_map&); +template +bool operator==(const hash_multimap&, + const hash_multimap&); + +/** \class hash_map + * \brief Replacement for STL hash map because some systems do not support it, + * or support it incorrectly. + */ +template ), + VCL_DFL_TMPL_PARAM_STLDECL(EqualKey,std::equal_to), + VCL_DFL_TYPE_PARAM_STLDECL(Alloc,std::allocator ) > +class hash_map +{ +private: + typedef std::select1st > sel1st; + typedef hashtable, Key, HashFcn, sel1st, EqualKey, Alloc> ht; + typedef hash_map self; +public: + VCL_IMPORT_CONTAINER_TYPEDEFS(ht) + VCL_IMPORT_ITERATORS(ht) + typedef typename ht::key_type key_type; + typedef typename ht::hasher hasher; + typedef typename ht::key_equal key_equal; + typedef T data_type; + typedef typename ht::pointer pointer; + typedef typename ht::const_pointer const_pointer; +private: + ht rep; + +public: + hasher hash_funct() const { return rep.hash_funct(); } + key_equal key_eq() const { return rep.key_eq(); } + +public: + hash_map() : rep(100, hasher(), key_equal()) {} + hash_map(size_type n) : rep(n, hasher(), key_equal()) {} + hash_map(size_type n, const hasher& hf) : rep(n, hf, key_equal()) {} + hash_map(size_type n, const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) {} + + hash_map(const value_type* f, const value_type* l) + : rep(100, hasher(), key_equal()) { rep.insert_unique(f, l); } + hash_map(const value_type* f, const value_type* l, size_type n) + : rep(n, hasher(), key_equal()) { rep.insert_unique(f, l); } + hash_map(const value_type* f, const value_type* l, size_type n, + const hasher& hf) + : rep(n, hf, key_equal()) { rep.insert_unique(f, l); } + hash_map(const value_type* f, const value_type* l, size_type n, + const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) { rep.insert_unique(f, l); } + + hash_map(const_iterator f, const_iterator l) + : rep(100, hasher(), key_equal()) { rep.insert_unique(f, l); } + hash_map(const_iterator f, const_iterator l, size_type n) + : rep(n, hasher(), key_equal()) { rep.insert_unique(f, l); } + hash_map(const_iterator f, const_iterator l, size_type n, + const hasher& hf) + : rep(n, hf, key_equal()) { rep.insert_unique(f, l); } + hash_map(const_iterator f, const_iterator l, size_type n, + const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) { rep.insert_unique(f, l); } + +public: + size_type size() const { return rep.size(); } + size_type max_size() const { return rep.max_size(); } + bool empty() const { return rep.empty(); } + void swap(self& hs) { rep.swap(hs.rep); } + + friend bool operator==ITK_FRIEND_TEMPLATE_FUNCTION_ARGUMENT(self)(const self &, const self &); + + iterator begin() { return rep.begin(); } + iterator end() { return rep.end(); } + const_iterator begin() const { return rep.begin(); } + const_iterator end() const { return rep.end(); } + +public: + std::pair insert(const value_type& obj) + { return rep.insert_unique(obj); } + void insert(const value_type* f, const value_type* l) { rep.insert_unique(f,l); } + void insert(const_iterator f, const_iterator l) { rep.insert_unique(f, l); } + std::pair insert_noresize(const value_type& obj) + { return rep.insert_unique_noresize(obj); } + + iterator find(const key_type& key) { return rep.find(key); } + const_iterator find(const key_type& key) const { return rep.find(key); } + + T& operator[](const key_type& key) + { + value_type val(key, T()); + return rep.find_or_insert(val).second; + } + + size_type count(const key_type& key) const { return rep.count(key); } + + std::pair equal_range(const key_type& key) + { return rep.equal_range(key); } + std::pair equal_range(const key_type& key) const + { return rep.equal_range(key); } + + size_type erase(const key_type& key) {return rep.erase(key); } + void erase(iterator it) { rep.erase(it); } + void erase(iterator f, iterator l) { rep.erase(f, l); } + void clear() { rep.clear(); } + +public: + void resize(size_type hint) { rep.resize(hint); } + size_type bucket_count() const { return rep.bucket_count(); } + size_type max_bucket_count() const { return rep.max_bucket_count(); } + size_type elems_in_bucket(size_type n) const + { return rep.elems_in_bucket(n); } +}; + + +template ), + VCL_DFL_TMPL_PARAM_STLDECL(EqualKey,std::equal_to), + VCL_DFL_TYPE_PARAM_STLDECL(Alloc,std::allocator ) > +class hash_multimap +{ +private: + typedef hashtable, Key, HashFcn, + std::select1st >, EqualKey, Alloc> ht; + typedef hash_multimap self; +public: + VCL_IMPORT_CONTAINER_TYPEDEFS(ht) + VCL_IMPORT_ITERATORS(ht) + typedef typename ht::key_type key_type; + typedef typename ht::hasher hasher; + typedef typename ht::key_equal key_equal; + typedef T data_type; + typedef typename ht::pointer pointer; + typedef typename ht::const_pointer const_pointer; + + hasher hash_funct() const { return rep.hash_funct(); } + key_equal key_eq() const { return rep.key_eq(); } +private: + ht rep; + +public: + hash_multimap() : rep(100, hasher(), key_equal()) {} + hash_multimap(size_type n) : rep(n, hasher(), key_equal()) {} + hash_multimap(size_type n, const hasher& hf) : rep(n, hf, key_equal()) {} + hash_multimap(size_type n, const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) {} + + hash_multimap(const value_type* f, const value_type* l) + : rep(100, hasher(), key_equal()) { rep.insert_equal(f, l); } + hash_multimap(const value_type* f, const value_type* l, size_type n) + : rep(n, hasher(), key_equal()) { rep.insert_equal(f, l); } + hash_multimap(const value_type* f, const value_type* l, size_type n, + const hasher& hf) + : rep(n, hf, key_equal()) { rep.insert_equal(f, l); } + hash_multimap(const value_type* f, const value_type* l, size_type n, + const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) { rep.insert_equal(f, l); } + + hash_multimap(const_iterator f, const_iterator l) + : rep(100, hasher(), key_equal()) { rep.insert_equal(f, l); } + hash_multimap(const_iterator f, const_iterator l, size_type n) + : rep(n, hasher(), key_equal()) { rep.insert_equal(f, l); } + hash_multimap(const_iterator f, const_iterator l, size_type n, + const hasher& hf) + : rep(n, hf, key_equal()) { rep.insert_equal(f, l); } + hash_multimap(const_iterator f, const_iterator l, size_type n, + const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) { rep.insert_equal(f, l); } + +public: + size_type size() const { return rep.size(); } + size_type max_size() const { return rep.max_size(); } + bool empty() const { return rep.empty(); } + void swap(self& hs) { rep.swap(hs.rep); } + + friend bool operator==ITK_FRIEND_TEMPLATE_FUNCTION_ARGUMENT(self)(const self &, const self &); + + iterator begin() { return rep.begin(); } + iterator end() { return rep.end(); } + const_iterator begin() const { return rep.begin(); } + const_iterator end() const { return rep.end(); } + +public: + iterator insert(const value_type& obj) { return rep.insert_equal(obj); } + void insert(const value_type* f, const value_type* l) { rep.insert_equal(f,l); } + void insert(const_iterator f, const_iterator l) { rep.insert_equal(f, l); } + iterator insert_noresize(const value_type& obj) + { return rep.insert_equal_noresize(obj); } + + iterator find(const key_type& key) { return rep.find(key); } + const_iterator find(const key_type& key) const { return rep.find(key); } + + size_type count(const key_type& key) const { return rep.count(key); } + + std::pair equal_range(const key_type& key) + { return rep.equal_range(key); } + std::pair equal_range(const key_type& key) const + { return rep.equal_range(key); } + + size_type erase(const key_type& key) {return rep.erase(key); } + void erase(iterator it) { rep.erase(it); } + void erase(iterator f, iterator l) { rep.erase(f, l); } + void clear() { rep.clear(); } + +public: + void resize(size_type hint) { rep.resize(hint); } + size_type bucket_count() const { return rep.bucket_count(); } + size_type max_bucket_count() const { return rep.max_bucket_count(); } + size_type elems_in_bucket(size_type n) const + { return rep.elems_in_bucket(n); } +}; + +/** This method MUST NOT be declared "inline" because it a specialization of its template is + declared as friend of a class. The hash_map class, in this case */ +template +bool operator==(const hash_map& hm1, + const hash_map& hm2) +{ + return hm1.rep == hm2.rep; +} + +/** This method MUST NOT be declared "inline" because it a specialization of its template is + declared as friend of a class. The hash_map class, in this case */ +template +bool operator==(const hash_multimap& hm1, + const hash_multimap& hm2) +{ + return hm1.rep == hm2.rep; +} + + +#define HASH_MAP_INSTANTIATE \ +extern "please include emulation/hash_map.txx instead" + +} // end namespace itk + +#endif + +#endif // itk_emulation_hash_map_h diff --git a/Core/Code/Service/mitkItkHashSet.h b/Core/Code/Service/mitkItkHashSet.h new file mode 100644 index 0000000000..b49aefe0f3 --- /dev/null +++ b/Core/Code/Service/mitkItkHashSet.h @@ -0,0 +1,377 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +/** + * Copyright (c) 1996 + * Silicon Graphics Computer Systems, Inc. + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Silicon Graphics makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * + * Copyright (c) 1994 + * Hewlett-Packard Company + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Hewlett-Packard Company makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * Copyright (c) 1997 + * Moscow Center for SPARC Technology + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Moscow Center for SPARC Technology makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + */ + +#ifndef __itk_hash_set_h +#define __itk_hash_set_h + +#if (defined(__GNUC__) && (((__GNUC__==3) && (__GNUC_MINOR__>=1) || (__GNUC__>3) ) || ( (__GNUC__==4) && defined(__INTEL_COMPILER) ) )) || (defined(__IBMCPP__) && __IBMCPP__ >= 600) +// Use this hash_map for GNU_C versions >= 3.1, IBMCPP >=600, or Intel compilers with GCCv4 +#include + +namespace itk +{ + using __gnu_cxx::hash; + using __gnu_cxx::hash_set; + using __gnu_cxx::hash_multiset; +} + +#else + +#include "mitkItkHashTable.h" +#include + +// --- + +namespace itk +{ + +/** \class hash_set + * \brief Replacement for STL hash set because some systems do not support it, + * or support it incorrectly. + */ +template ), + VCL_DFL_TMPL_PARAM_STLDECL(EqualKey,std::equal_to), + VCL_DFL_TYPE_PARAM_STLDECL(Alloc,std::allocator ) > +class hash_set +{ +private: + typedef hashtable, + EqualKey, Alloc> ht; + typedef hash_set self; +public: + typedef typename ht::key_type key_type; + typedef typename ht::value_type value_type; + typedef typename ht::hasher hasher; + typedef typename ht::key_equal key_equal; + + typedef typename ht::size_type size_type; + typedef typename ht::difference_type difference_type; + typedef typename ht::const_pointer pointer; + typedef typename ht::const_pointer const_pointer; + typedef typename ht::const_reference reference; + typedef typename ht::const_reference const_reference; + // SunPro bug + typedef typename ht::const_iterator const_iterator; + typedef const_iterator iterator; + + // vc6 addition + typedef typename ht::iterator ht_iterator; + + hasher hash_funct() const { return rep.hash_funct(); } + key_equal key_eq() const { return rep.key_eq(); } + +private: + ht rep; + +public: + hash_set() : rep(100, hasher(), key_equal()) {} + hash_set(size_type n) : rep(n, hasher(), key_equal()) {} + hash_set(size_type n, const hasher& hf) : rep(n, hf, key_equal()) {} + hash_set(size_type n, const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) {} + + hash_set(const value_type* f, const value_type* l) + : rep(100, hasher(), key_equal()) { rep.insert_unique(f, l); } + hash_set(const value_type* f, const value_type* l, size_type n) + : rep(n, hasher(), key_equal()) { rep.insert_unique(f, l); } + hash_set(const value_type* f, const value_type* l, size_type n, + const hasher& hf) + : rep(n, hf, key_equal()) { rep.insert_unique(f, l); } + hash_set(const value_type* f, const value_type* l, size_type n, + const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) { rep.insert_unique(f, l); } + + hash_set(const_iterator f, const_iterator l) + : rep(100, hasher(), key_equal()) { rep.insert_unique(f, l); } + hash_set(const_iterator f, const_iterator l, size_type n) + : rep(n, hasher(), key_equal()) { rep.insert_unique(f, l); } + hash_set(const_iterator f, const_iterator l, size_type n, + const hasher& hf) + : rep(n, hf, key_equal()) { rep.insert_unique(f, l); } + hash_set(const_iterator f, const_iterator l, size_type n, + const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) { rep.insert_unique(f, l); } + +public: + size_type size() const { return rep.size(); } + size_type max_size() const { return rep.max_size(); } + bool empty() const { return rep.empty(); } + void swap(self& hs) { rep.swap(hs.rep); } + + friend bool operator==ITK_FRIEND_TEMPLATE_FUNCTION_ARGUMENT(self)(const self &, const self &); + + iterator begin() const { return rep.begin(); } + iterator end() const { return rep.end(); } + +public: + std::pair insert(const value_type& obj) + { +#ifdef _MSC_VER + std::pair< ht::iterator, bool> p = rep.insert_unique(obj); +#else + std::pair p = rep.insert_unique(obj); +#endif + return std::pair(p.first, p.second); + } + void insert(const value_type* f, const value_type* l) { rep.insert_unique(f,l); } + void insert(const_iterator f, const_iterator l) { rep.insert_unique(f, l); } + std::pair insert_noresize(const value_type& obj) + { +#ifdef _MSC_VER + std::pair p = rep.insert_unique_noresize(obj); +#else + std::pair p = rep.insert_unique_noresize(obj); +#endif + return std::pair(p.first, p.second); + } + + iterator find(const key_type& key) const { return rep.find(key); } + + size_type count(const key_type& key) const { return rep.count(key); } + + std::pair equal_range(const key_type& key) const + { return rep.equal_range(key); } + + size_type erase(const key_type& key) {return rep.erase(key); } + void erase(iterator it) { rep.erase(it); } + void erase(iterator f, iterator l) { rep.erase(f, l); } + void clear() { rep.clear(); } + +public: + void resize(size_type hint) { rep.resize(hint); } + size_type bucket_count() const { return rep.bucket_count(); } + size_type max_bucket_count() const { return rep.max_bucket_count(); } + size_type elems_in_bucket(size_type n) const + { return rep.elems_in_bucket(n); } +}; + + +template ), + VCL_DFL_TMPL_PARAM_STLDECL(EqualKey,std::equal_to), + VCL_DFL_TYPE_PARAM_STLDECL(Alloc,std::allocator ) > +class hash_multiset +{ +private: + typedef hashtable, + EqualKey, Alloc> ht; + typedef hash_multiset self; +public: + typedef typename ht::key_type key_type; + typedef typename ht::value_type value_type; + typedef typename ht::hasher hasher; + typedef typename ht::key_equal key_equal; + + typedef typename ht::size_type size_type; + typedef typename ht::difference_type difference_type; + typedef typename ht::const_pointer pointer; + typedef typename ht::const_pointer const_pointer; + typedef typename ht::const_reference reference; + typedef typename ht::const_reference const_reference; + + typedef typename ht::const_iterator const_iterator; + // SunPro bug + typedef const_iterator iterator; + + hasher hash_funct() const { return rep.hash_funct(); } + key_equal key_eq() const { return rep.key_eq(); } +private: + ht rep; + +public: + hash_multiset() : rep(100, hasher(), key_equal()) {} + hash_multiset(size_type n) : rep(n, hasher(), key_equal()) {} + hash_multiset(size_type n, const hasher& hf) : rep(n, hf, key_equal()) {} + hash_multiset(size_type n, const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) {} + + hash_multiset(const value_type* f, const value_type* l) + : rep(100, hasher(), key_equal()) { rep.insert_equal(f, l); } + hash_multiset(const value_type* f, const value_type* l, size_type n) + : rep(n, hasher(), key_equal()) { rep.insert_equal(f, l); } + hash_multiset(const value_type* f, const value_type* l, size_type n, + const hasher& hf) + : rep(n, hf, key_equal()) { rep.insert_equal(f, l); } + hash_multiset(const value_type* f, const value_type* l, size_type n, + const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) { rep.insert_equal(f, l); } + + hash_multiset(const_iterator f, const_iterator l) + : rep(100, hasher(), key_equal()) { rep.insert_equal(f, l); } + hash_multiset(const_iterator f, const_iterator l, size_type n) + : rep(n, hasher(), key_equal()) { rep.insert_equal(f, l); } + hash_multiset(const_iterator f, const_iterator l, size_type n, + const hasher& hf) + : rep(n, hf, key_equal()) { rep.insert_equal(f, l); } + hash_multiset(const_iterator f, const_iterator l, size_type n, + const hasher& hf, const key_equal& eql) + : rep(n, hf, eql) { rep.insert_equal(f, l); } + +public: + size_type size() const { return rep.size(); } + size_type max_size() const { return rep.max_size(); } + bool empty() const { return rep.empty(); } + void swap(self& hs) { rep.swap(hs.rep); } + + friend bool operator==ITK_FRIEND_TEMPLATE_FUNCTION_ARGUMENT(self)(const self &, const self &); + + iterator begin() const { return rep.begin(); } + iterator end() const { return rep.end(); } + +public: + iterator insert(const value_type& obj) { return rep.insert_equal(obj); } + void insert(const value_type* f, const value_type* l) { rep.insert_equal(f,l); } + void insert(const_iterator f, const_iterator l) { rep.insert_equal(f, l); } + iterator insert_noresize(const value_type& obj) + { return rep.insert_equal_noresize(obj); } + + iterator find(const key_type& key) const { return rep.find(key); } + + size_type count(const key_type& key) const { return rep.count(key); } + + std::pair equal_range(const key_type& key) const + { return rep.equal_range(key); } + + size_type erase(const key_type& key) {return rep.erase(key); } + void erase(iterator it) { rep.erase(it); } + void erase(iterator f, iterator l) { rep.erase(f, l); } + void clear() { rep.clear(); } + +public: + void resize(size_type hint) { rep.resize(hint); } + size_type bucket_count() const { return rep.bucket_count(); } + size_type max_bucket_count() const { return rep.max_bucket_count(); } + size_type elems_in_bucket(size_type n) const + { return rep.elems_in_bucket(n); } +}; + + +/** This method MUST NOT be declared "inline" because it a specialization of its template is + declared as friend of a class. The hash_set class, in this case */ +template +bool operator==(const hash_set& hs1, + const hash_set& hs2) +{ + return hs1.rep == hs2.rep; +} + +/** This method MUST NOT be declared "inline" because it a specialization of its template is + declared as friend of a class. The hash_set class, in this case */ +template +bool operator==(const hash_multiset& hs1, + const hash_multiset& hs2) +{ + return hs1.rep == hs2.rep; +} + +# if defined (__STL_CLASS_PARTIAL_SPECIALIZATION ) +template +inline void swap(hash_multiset& a, + hash_multiset& b) { a.swap(b); } +template +inline void swap(hash_set& a, + hash_set& b) { a.swap(b); } +# endif + +} // end namespace itk + + +namespace std { + +// Specialization of insert_iterator so that it will work for hash_set +// and hash_multiset. +template +class insert_iterator > +{ +protected: + typedef itk::hash_set<_Value, _HashFcn, _EqualKey, _Alloc> _Container; + _Container* container; + +public: + typedef _Container container_type; + typedef output_iterator_tag iterator_category; + typedef void value_type; + typedef void difference_type; + typedef void pointer; + typedef void reference; + + insert_iterator(_Container& __x) + : container(&__x) {} + + insert_iterator(_Container& __x, typename _Container::iterator) + : container(&__x) {} + + insert_iterator<_Container>& + operator=(const typename _Container::value_type& value) + { + container->insert(value); + return *this; + } + + insert_iterator<_Container>& + operator*() + { return *this; } + + insert_iterator<_Container>& + operator++() + { return *this; } + + insert_iterator<_Container>& + operator++(int) + { return *this; } +}; + +} + +#endif +#endif // itk_emulation_hash_set_h diff --git a/Core/Code/Service/mitkItkHashTable.h b/Core/Code/Service/mitkItkHashTable.h new file mode 100644 index 0000000000..a7adfcbeb0 --- /dev/null +++ b/Core/Code/Service/mitkItkHashTable.h @@ -0,0 +1,1188 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ +/** + * Copyright (c) 1996 + * Silicon Graphics Computer Systems, Inc. + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Silicon Graphics makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * + * Copyright (c) 1994 + * Hewlett-Packard Company + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Hewlett-Packard Company makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * Exception Handling: + * Copyright (c) 1997 + * Mark of the Unicorn, Inc. + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Mark of the Unicorn makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * Adaptation: + * Copyright (c) 1997 + * Moscow Center for SPARC Technology + * + * Permission to use, copy, modify, distribute and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appear in all copies and + * that both that copyright notice and this permission notice appear + * in supporting documentation. Moscow Center for SPARC Technology makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + */ + + +#ifndef __itk_hashtable_h +#define __itk_hashtable_h + +#if defined(_MSC_VER) +// unreachable code +#pragma warning ( disable : 4702 ) +// assignment operator could not be generated +#pragma warning ( disable : 4512 ) +#endif + +#if (defined(__GNUC__) && (((__GNUC__==3) && (__GNUC_MINOR__>=1) || (__GNUC__>3) ) || ( (__GNUC__==4) && defined(__INTEL_COMPILER) ) )) || (defined(__IBMCPP__) && __IBMCPP__ >= 600) +// Use this hashtable that is already define for GNU_C versions >= 3.1, IBMCPP >=600, or Intel compilers with GCCv4 + +#else +/** \brief Hashtable class, used to implement the hashed associative containers + * itk_hash_set, itk_hash_map, itk_hash_multiset, and itk_hash_multimap. + */ +#include "itkMacro.h" +#include +#include "itk_alloc.h" +#include +#include +#include +#include "vcl_compiler.h" +#include +#include +#include + + +namespace itk +{ +template struct hash { }; + +inline size_t hash_string(const char* s) +{ + unsigned long h = 0; + for (; *s; ++s) + { + h = 5*h + *s; + } + return size_t(h); +} + +template<> +struct hash +{ + size_t operator()(const char* s) const { return hash_string(s); } +}; + +template<> +struct hash +{ + size_t operator()(const char* s) const { return hash_string(s); } +}; + +template<> +struct hash +{ + size_t operator()(char x) const { return x; } +}; + +template<> +struct hash +{ + size_t operator()(unsigned char x) const { return x; } +}; + +template<> +struct hash +{ + size_t operator()(unsigned char x) const { return x; } +}; + +template<> +struct hash +{ + size_t operator()(short x) const { return x; } +}; + +template<> +struct hash +{ + size_t operator()(unsigned short x) const { return x; } +}; + +template<> +struct hash +{ + size_t operator()(int x) const { return x; } +}; + +template<> +struct hash +{ + size_t operator()(unsigned int x) const { return x; } +}; + +template<> +struct hash +{ + size_t operator()(long x) const { return x; } +}; + +template<> +struct hash +{ + size_t operator()(unsigned long x) const { return x; } +}; + +#ifdef _WIN64 +template<> +struct hash +{ + size_t operator()(size_t x) const { return x; } +}; +#endif + +template +struct hashtable_node +{ + typedef hashtable_node self; + self* next; + Value val; +}; + +template )> +class hashtable; + +template +struct hashtable_iterator; + +template +struct hashtable_const_iterator; + +template +struct hashtable_iterator +{ + typedef hashtable hash_table; + typedef hashtable_iterator iterator; + typedef hashtable_const_iterator + const_iterator; + typedef hashtable_node node; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + typedef Value value_type; + typedef size_t size_type; + typedef Value& reference; + typedef Value* pointer; + typedef const Value& const_reference; + + node* cur; + hash_table* ht; + + hashtable_iterator(node* n, hash_table* tab) : cur(n), ht(tab) {} + hashtable_iterator() {} + reference operator*() const + { + return cur->val; + } + pointer operator->() const { return &(operator*()); } + + IUEi_STL_INLINE iterator& operator++(); + IUEi_STL_INLINE iterator operator++(int); + bool operator==(const iterator& it) const { return cur == it.cur; } + bool operator!=(const iterator& it) const { return cur != it.cur; } +}; + + +template +struct hashtable_const_iterator +{ + typedef hashtable + hash_table; + typedef hashtable_iterator iterator; + typedef hashtable_const_iterator const_iterator; + typedef hashtable_node node; + typedef std::forward_iterator_tag iterator_category; + typedef std::ptrdiff_t difference_type; + typedef Value value_type; + typedef size_t size_type; + typedef Value& reference; + typedef const Value& const_reference; + typedef const Value* pointer; + + const node* cur; + const hash_table* ht; + + hashtable_const_iterator(const node* n, const hash_table* tab) : cur(n), ht(tab) {} + hashtable_const_iterator() {} + hashtable_const_iterator(const iterator& it) : cur(it.cur), ht(it.ht) {} + + const_reference operator*() const { return cur->val; } + pointer operator->() const { return &(operator*()); } + IUEi_STL_INLINE const_iterator& operator++(); + IUEi_STL_INLINE const_iterator operator++(int); + bool operator==(const const_iterator& it) const { return cur == it.cur; } + bool operator!=(const const_iterator& it) const { return cur != it.cur; } +}; + +// Note: assumes long is at least 32 bits. +// fbp: try to avoid intances in every module +enum { num_primes = 28 }; + +#if ( __STL_STATIC_TEMPLATE_DATA > 0 ) && ! defined (WIN32) +# define prime_list prime::list_ +template +struct prime { +public: + static const unsigned long list_[]; +}; +static const unsigned long prime_list_dummy[num_primes] = +# else +# if ( __STL_WEAK_ATTRIBUTE > 0 ) + extern const unsigned long prime_list[num_primes] __attribute__((weak)) = +# else + // give up + static const unsigned long prime_list[num_primes] = +# endif /* __STL_WEAK_ATTRIBUTE */ +#endif /* __STL_STATIC_TEMPLATE_DATA */ +{ + 53, 97, 193, 389, 769, + 1543, 3079, 6151, 12289, 24593, + 49157, 98317, 196613, 393241, 786433, + 1572869, 3145739, 6291469, 12582917, 25165843, + 50331653, 100663319, 201326611, 402653189, 805306457, + 1610612741, 3221225473U, 4294967291U +}; + +inline unsigned long next_prime(unsigned long n) +{ + const unsigned long* first = prime_list; + const unsigned long* last = prime_list; + last += num_primes; + const unsigned long* pos = std::lower_bound(first, last, n); + return pos == last ? *(last - 1) : *pos; +} + +template +class hashtable_base +{ +private: + typedef Value value_type; + typedef size_t size_type; + typedef hashtable_node node; + typedef itk_simple_alloc node_allocator; +public: // These are public to get around restriction on protected access + typedef std::vector buckets_type; + buckets_type buckets; // awf killed optional allocator + size_type num_elements; +protected: + IUEi_STL_INLINE void clear(); + + node* new_node(const value_type& obj) + { + node* n = node_allocator::allocate(); + try + { + new (&(n->val)) value_type(obj); + } + catch (...) + { + node_allocator::deallocate(n); + throw ""; + } + n->next = 0; + return n; + } + + void delete_node(node* n) + { +#define vcli_destroy(T, p) ((T*)p)->~T() + vcli_destroy(Value, &(n->val)); +#undef vcli_destroy + node_allocator::deallocate(n); + } + + IUEi_STL_INLINE void copy_from(const hashtable_base& ht); + +public: // These are public to get around restriction on protected access + hashtable_base() : num_elements(0) { } +// hashtable_base(size_type n) : num_elements(0) {} + ~hashtable_base() { clear(); } +}; + + +// forward declarations +template class hashtable; +template + bool operator== (hashtableconst&,hashtableconst&); + +template +class hashtable : protected hashtable_base +{ + typedef hashtable_base super; + typedef hashtable self; +public: + typedef Key key_type; + typedef Value value_type; + typedef HashFcn hasher; + typedef EqualKey key_equal; + + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + + hasher hash_funct() const { return hashfun; } + key_equal key_eq() const { return equals; } + +private: + hasher hashfun; + key_equal equals; + ExtractKey get_key; + + typedef hashtable_node node; + typedef itk_simple_alloc node_allocator; + +public: + typedef hashtable_iterator iterator; + typedef hashtable_const_iterator const_iterator; + friend struct + hashtable_iterator; + friend struct + hashtable_const_iterator; + +public: + hashtable(size_type n, + const HashFcn& hf, + const EqualKey& eql, + const ExtractKey& ext) + : hashfun(hf), equals(eql), get_key(ext) + { + initialize_buckets(n); + } + + hashtable(size_type n, + const HashFcn& hf, + const EqualKey& eql) + : hashfun(hf), equals(eql), get_key(ExtractKey()) + { + initialize_buckets(n); + } + + hashtable(const self& ht) + : hashfun(ht.hashfun), equals(ht.equals), get_key(ht.get_key) + { + copy_from(ht); + } + + self& operator= (const self& ht) + { + if (&ht != this) + { + hashfun = ht.hashfun; + equals = ht.equals; + get_key = ht.get_key; + clear(); + this->buckets.clear(); + copy_from(ht); + } + return *this; + } + + ~hashtable() {} + + size_type size() const { return this->num_elements; } + size_type max_size() const { return size_type(-1); } + bool empty() const { return size() == 0; } + + void swap(self& ht) + { + std::swap(hashfun, ht.hashfun); + std::swap(equals, ht.equals); + std::swap(get_key, ht.get_key); + this->buckets.swap(ht.buckets); + std::swap(this->num_elements, ht.num_elements); + } + + iterator begin() + { + for (size_type n = 0; n < this->buckets.size(); ++n) + { + if (this->buckets[n]) + { + return iterator(this->buckets[n], this); + } + } + return end(); + } + + iterator end() { return iterator((node*)0, this); } + + const_iterator begin() const + { + for (size_type n = 0; n < this->buckets.size(); ++n) + { + if (this->buckets[n]) + { + return const_iterator(this->buckets[n], this); + } + } + return end(); + } + + const_iterator end() const { return const_iterator((node*)0, this); } + + friend bool operator==ITK_FRIEND_TEMPLATE_FUNCTION_ARGUMENT(self)(const self&,const self&); + +public: + + size_type bucket_count() const { return this->buckets.size(); } + + size_type max_bucket_count() const + { return prime_list[num_primes - 1]; } + + size_type elems_in_bucket(size_type bucket) const + { + size_type result = 0; + for (node* cur = this->buckets[bucket]; cur; cur = cur->next) + { + result += 1; + } + return result; + } + + std::pair insert_unique(const value_type& obj) + { + resize(this->num_elements + 1); + return insert_unique_noresize(obj); + } + + iterator insert_equal(const value_type& obj) + { + resize(this->num_elements + 1); + return insert_equal_noresize(obj); + } + + IUEi_STL_INLINE std::pair insert_unique_noresize(const value_type& obj); + IUEi_STL_INLINE iterator insert_equal_noresize(const value_type& obj); + + void insert_unique(const value_type* f, const value_type* l) + { + size_type n = l - f; + resize(this->num_elements + n); + for (; n > 0; --n) + { + insert_unique_noresize(*f++); + } + } + + void insert_equal(const value_type* f, const value_type* l) + { + size_type n = l - f; + resize(this->num_elements + n); + for (; n > 0; --n) + { + insert_equal_noresize(*f++); + } + } + + void insert_unique(const_iterator f, const_iterator l) + { + size_type n = std::distance(f, l); + resize(this->num_elements + n); + for (; n > 0; --n) + { + insert_unique_noresize(*f++); + } + } + + void insert_equal(const_iterator f, const_iterator l) + { + size_type n = std::distance(f, l); + resize(this->num_elements + n); + for (; n > 0; --n) + { + insert_equal_noresize(*f++); + } + } + + IUEi_STL_INLINE reference find_or_insert(const value_type& obj); + + iterator find(const key_type& key) + { + size_type n = bkt_num_key(key); + node* first; + for ( first = this->buckets[n]; + first && !equals(get_key(first->val), key); + first = first->next) + {} + return iterator(first, this); + } + + const_iterator find(const key_type& key) const + { + size_type n = bkt_num_key(key); + const node* first; + for ( first = this->buckets[n]; + first && !equals(get_key(first->val), key); + first = first->next) + {} + return const_iterator(first, this); + } + + size_type count(const key_type& key) const + { + const size_type n = bkt_num_key(key); + size_type result = 0; + + for (const node* cur = this->buckets[n]; cur; cur = cur->next) + { + if (equals(get_key(cur->val), key)) + { + ++result; + } + } + return result; + } + + IUEi_STL_INLINE std::pair equal_range(const key_type& key); + IUEi_STL_INLINE std::pair equal_range(const key_type& key) const; + + IUEi_STL_INLINE size_type erase(const key_type& key); + IUEi_STL_INLINE void erase(const iterator& it); + IUEi_STL_INLINE void erase(iterator first, iterator last); + + IUEi_STL_INLINE void erase(const const_iterator& it); + IUEi_STL_INLINE void erase(const_iterator first, const_iterator last); + + IUEi_STL_INLINE void resize(size_type num_elements_hint); + void clear() { super::clear(); } +private: + size_type next_size(size_type n) const + { + return static_cast( + next_prime( static_cast(n) ) ); + } + + void initialize_buckets(size_type n) + { + const size_type n_buckets = next_size(n); + this->buckets.reserve(n_buckets); + this->buckets.insert(this->buckets.end(), n_buckets, (node*) 0); + this->num_elements = 0; + } + size_type bkt_num_key(const key_type& key) const + { + return bkt_num_key(key, this->buckets.size()); + } + + size_type bkt_num(const value_type& obj) const + { + return bkt_num_key(get_key(obj)); + } + + size_type bkt_num_key(const key_type& key, size_t n) const + { + return hashfun(key) % n; + } + + size_type bkt_num(const value_type& obj, size_t n) const + { + return bkt_num_key(get_key(obj), n); + } + IUEi_STL_INLINE void erase_bucket(const size_type n, node* first, node* last); + IUEi_STL_INLINE void erase_bucket(const size_type n, node* last); +}; + +// fbp: these defines are for outline methods definitions. +// needed to definitions to be portable. Should not be used in method bodies. + +# if defined ( __STL_NESTED_TYPE_PARAM_BUG ) +# define __difference_type__ ptrdiff_t +# define __size_type__ size_t +# define __value_type__ Value +# define __key_type__ Key +# define __node__ hashtable_node +# define __reference__ Value& +# else +# define __difference_type__ typename hashtable::difference_type +# define __size_type__ typename hashtable::size_type +# define __value_type__ typename hashtable::value_type +# define __key_type__ typename hashtable::key_type +# define __node__ typename hashtable::node +# define __reference__ typename hashtable::reference +# endif + +template +inline hashtable_iterator& +hashtable_iterator::operator++() +{ + const node* old = cur; + cur = cur->next; + if (!cur) + { + size_type bucket = ht->bkt_num(old->val); + while (!cur && ++bucket < ht->buckets.size()) + { + cur = ht->buckets[bucket]; + } + } + return *this; +} + +template +inline hashtable_iterator +hashtable_iterator::operator++(int) +{ + iterator tmp = *this; + ++*this; + return tmp; +} + +template +inline hashtable_const_iterator& +hashtable_const_iterator::operator++() +{ + const node* old = cur; + cur = cur->next; + if (!cur) + { + size_type bucket = ht->bkt_num(old->val); + while (!cur && ++bucket < ht->buckets.size()) + { + cur = ht->buckets[bucket]; + } + } + return *this; +} + +template +inline hashtable_const_iterator +hashtable_const_iterator::operator++(int) +{ + const_iterator tmp = *this; + ++*this; + return tmp; +} + +template +inline std::forward_iterator_tag +iterator_category (const hashtable_iterator&) +{ + return std::forward_iterator_tag(); +} + +template +inline Value* +value_type(const hashtable_iterator&) +{ + return (Value*) 0; +} + +template +inline ptrdiff_t* +distance_type(const hashtable_iterator&) +{ + return (ptrdiff_t*) 0; +} + +template +inline std::forward_iterator_tag +iterator_category (const hashtable_const_iterator&) +{ + return std::forward_iterator_tag(); +} + +template +inline Value* +value_type(const hashtable_const_iterator&) +{ + return (Value*) 0; +} + +template +inline ptrdiff_t* +distance_type(const hashtable_const_iterator&) +{ + return (ptrdiff_t*) 0; +} + +/** This method MUST NOT be declared "inline" because it a specialization of its template is + declared as friend of a class. The hashtable class, in this case */ +template +bool operator==(const hashtable& ht1, + const hashtable& ht2) +{ + typedef typename hashtable::node node; + if (ht1.buckets.size() != ht2.buckets.size()) + { + return false; + } + for (int n = 0; n < ht1.buckets.size(); ++n) + { + node* cur1 = ht1.buckets[n]; + node* cur2 = ht2.buckets[n]; + for (; cur1 && cur2 && cur1->val == cur2->val; + cur1 = cur1->next, cur2 = cur2->next) + {} + if (cur1 || cur2) + { + return false; + } + } + return true; +} + +template +std::pair, bool> +hashtable::insert_unique_noresize(const __value_type__& obj) +{ + const size_type n = bkt_num(obj); + node* first = this->buckets[n]; + + for (node* cur = first; cur; cur = cur->next) + if (equals(get_key(cur->val), get_key(obj))) + return std::pair(iterator(cur, this), false); + + node* tmp = new_node(obj); + tmp->next = first; + this->buckets[n] = tmp; + ++this->num_elements; + return std::pair(iterator(tmp, this), true); +} + +template +hashtable_iterator +hashtable::insert_equal_noresize(const __value_type__& obj) +{ + const size_type n = bkt_num(obj); + node* first = this->buckets[n]; + + for (node* cur = first; cur; cur = cur->next) + { + if (equals(get_key(cur->val), get_key(obj))) + { + node* tmp = new_node(obj); + tmp->next = cur->next; + cur->next = tmp; + ++this->num_elements; + return iterator(tmp, this); + } + } + node* tmp = new_node(obj); + tmp->next = first; + this->buckets[n] = tmp; + ++this->num_elements; + return iterator(tmp, this); +} + +template +__reference__ +hashtable::find_or_insert(const __value_type__& obj) +{ + resize(this->num_elements + 1); + + size_type n = bkt_num(obj); + node* first = this->buckets[n]; + + for (node* cur = first; cur; cur = cur->next) + if (equals(get_key(cur->val), get_key(obj))) + return cur->val; + + node* tmp = new_node(obj); + tmp->next = first; + this->buckets[n] = tmp; + ++this->num_elements; + return tmp->val; +} + +template +std::pair, + hashtable_iterator > +hashtable::equal_range(const __key_type__& key) +{ + typedef std::pair pii; + const size_type n = bkt_num_key(key); + + for (node* first = this->buckets[n]; first; first = first->next) + { + if (equals(get_key(first->val), key)) + { + for (node* cur = first->next; cur; cur = cur->next) + { + if (!equals(get_key(cur->val), key)) + return pii(iterator(first, this), iterator(cur, this)); + } + for (size_type m = n + 1; m < this->buckets.size(); ++m) + { + if (this->buckets[m]) + { + return pii(iterator(first, this), + iterator(this->buckets[m], this)); + } + } + return pii(iterator(first, this), end()); + } + } + return pii(end(), end()); +} + +template +std::pair, + hashtable_const_iterator > +hashtable::equal_range(const __key_type__& key) const +{ + typedef std::pair pii; + const size_type n = bkt_num_key(key); + + for (const node* first = this->buckets[n]; first; first = first->next) + { + if (equals(get_key(first->val), key)) + { + for (const node* cur = first->next; cur; cur = cur->next) + { + if (!equals(get_key(cur->val), key)) + { + return pii(const_iterator(first, this), + const_iterator(cur, this)); + } + } + for (size_type m = n + 1; m < this->buckets.size(); ++m) + { + if (this->buckets[m]) + { + return pii(const_iterator(first, this), + const_iterator(this->buckets[m], this)); + } + } + return pii(const_iterator(first, this), end()); + } + } + return pii(end(), end()); +} + +template +__size_type__ +hashtable::erase(const __key_type__& key) +{ + const size_type n = bkt_num_key(key); + node* first = this->buckets[n]; + size_type erased = 0; + + if (first) + { + node* cur = first; + node* next = cur->next; + while (next) + { + if (equals(get_key(next->val), key)) + { + cur->next = next->next; + delete_node(next); + next = cur->next; + ++erased; + } + else + { + cur = next; + next = cur->next; + } + } + if (equals(get_key(first->val), key)) + { + this->buckets[n] = first->next; + delete_node(first); + ++erased; + } + } + this->num_elements -= erased; + return erased; +} + +template +void +hashtable::erase(const hashtable_iterator& it) +{ + node* const p = it.cur; + if (p) + { + const size_type n = bkt_num(p->val); + node* cur = this->buckets[n]; + + if (cur == p) + { + this->buckets[n] = cur->next; + delete_node(cur); + --this->num_elements; + } + else + { + node* next = cur->next; + while (next) + { + if (next == p) + { + cur->next = next->next; + delete_node(next); + --this->num_elements; + break; + } + else + { + cur = next; + next = cur->next; + } + } + } + } +} + +template +void +hashtable::erase(hashtable_iterator first, + hashtable_iterator last) +{ + size_type f_bucket = first.cur ? bkt_num(first.cur->val) : this->buckets.size(); + size_type l_bucket = last.cur ? bkt_num(last.cur->val) : this->buckets.size(); + if (first.cur == last.cur) + return; + else if (f_bucket == l_bucket) + erase_bucket(f_bucket, first.cur, last.cur); + else + { + erase_bucket(f_bucket, first.cur, 0); + for (size_type n = f_bucket + 1; n < l_bucket; ++n) + erase_bucket(n, 0); + if (l_bucket != this->buckets.size()) + erase_bucket(l_bucket, last.cur); + } +} + +template +inline void +hashtable::erase(hashtable_const_iterator first, + hashtable_const_iterator last) +{ + erase(iterator(const_cast(first.cur), + const_cast(first.ht)), + iterator(const_cast(last.cur), + const_cast(last.ht))); +} + +template +inline void +hashtable::erase(const hashtable_const_iterator& it) +{ + erase(iterator(const_cast(it.cur), + const_cast(it.ht))); +} + +template +void +hashtable::resize(__size_type__ num_elements_hint) +{ + const size_type old_n = this->buckets.size(); + if (num_elements_hint > old_n) + { + const size_type n = next_size(num_elements_hint); + if (n > old_n) + { + typename hashtable::buckets_type tmp(n, (node*)0); + for (size_type bucket = 0; bucket < old_n; ++bucket) + { + node* first = this->buckets[bucket]; + while (first) + { + size_type new_bucket = bkt_num(first->val, n); + this->buckets[bucket] = first->next; + first->next = tmp[new_bucket]; + tmp[new_bucket] = first; + first = this->buckets[bucket]; + } + } + this->buckets.clear(); + this->buckets.swap(tmp); + } + } +} + + +template +void +hashtable::erase_bucket(const size_t n, + hashtable_node* first, + hashtable_node* last) +{ + node* cur = this->buckets[n]; + if (cur == first) + erase_bucket(n, last); + else + { + node* next; + for (next = cur->next; next != first; cur = next, next = cur->next); + while (next) + { + cur->next = next->next; + delete_node(next); + next = cur->next; + --this->num_elements; + } + } +} + +template +void +hashtable::erase_bucket(const size_t n, + hashtable_node* last) +{ + node* cur = this->buckets[n]; + while (cur != last) + { + node* next = cur->next; + delete_node(cur); + cur = next; + this->buckets[n] = cur; + --this->num_elements; + } +} + +template +void hashtable_base::clear() +{ + for (size_type i = 0; i < buckets.size(); ++i) + { + node* cur = buckets[i]; + while (cur != 0) + { + node* next = cur->next; + delete_node(cur); + cur = next; + } + buckets[i] = 0; + } + num_elements = 0; +} + + +template +void hashtable_base::copy_from(const hashtable_base& ht) +{ + buckets.reserve(ht.buckets.size()); + buckets.insert(buckets.end(), ht.buckets.size(), (node*) 0); + for (size_type i = 0; i < ht.buckets.size(); ++i) + { + const node* cur = ht.buckets[i]; + if (cur) + { + node* copy = new_node(cur->val); + buckets[i] = copy; + ++num_elements; + + for (node* next = cur->next; next; cur = next, next = cur->next) + { + copy->next = new_node(next->val); + ++num_elements; + copy = copy->next; + } + } + } +} + +}// end namespace itk + + +# undef __difference_type__ +# undef __size_type__ +# undef __value_type__ +# undef __key_type__ +# undef __node__ + +// the following is added for itk compatability: + +// -- + +// A few compatability fixes. Placed here for automatic include in +// both the hash_set and the hash_map sources. +# if (defined (_MSC_VER)&&(_MSC_VER < 1600 )) || defined(__BORLANDC__) || ((defined(__ICC)||defined(__ECC)) && defined(linux)) +// This should be replaced with a try_compile that tests the availability of std::identity. FIXME +namespace std +{ +template +struct identity : public std::unary_function { +public: + const T& operator()(const T& x) const { return x; } +}; +} + +#endif + +# if defined (_MSC_VER) || defined(__BORLANDC__) || ((defined(__ICC)||defined(__ECC)) && defined(linux)) +// This should be replaced with a try_compile that tests the availability of std::select*. FIXME + +template +struct itk_Select1st : public std::unary_function<_Pair, typename _Pair::first_type> { + typename _Pair::first_type const & operator()(_Pair const & __x) const { return __x.first; } +}; + +template +struct itk_Select2nd : public std::unary_function<_Pair, typename _Pair::second_type> { + typename _Pair::second_type const & operator()(_Pair const & __x) const { return __x.second; } +}; + +// Add select* to std. +namespace std { +template +struct select1st : public itk_Select1st<_Pair> {}; +template struct select2nd : public itk_Select2nd<_Pair> {}; +} + +#endif + +#endif + +#endif // itk_emulation_hashtable_h diff --git a/Core/Code/Service/mitkLDAPExpr.cpp b/Core/Code/Service/mitkLDAPExpr.cpp new file mode 100644 index 0000000000..01f2fe8aff --- /dev/null +++ b/Core/Code/Service/mitkLDAPExpr.cpp @@ -0,0 +1,771 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include +#include +#include + +#include "mitkLDAPExpr_p.h" +#include "mitkServiceUtils.h" + +namespace mitk { + +const int LDAPExpr::AND = 0; +const int LDAPExpr::OR = 1; +const int LDAPExpr::NOT = 2; +const int LDAPExpr::EQ = 4; +const int LDAPExpr::LE = 8; +const int LDAPExpr::GE = 16; +const int LDAPExpr::APPROX = 32; +const int LDAPExpr::COMPLEX = LDAPExpr::AND | LDAPExpr::OR | LDAPExpr::NOT; +const int LDAPExpr::SIMPLE = LDAPExpr::EQ | LDAPExpr::LE | LDAPExpr::GE | LDAPExpr::APPROX; + +const LDAPExpr::Byte LDAPExpr::WILDCARD = std::numeric_limits::max(); +const std::string LDAPExpr::WILDCARD_STRING = std::string(1, LDAPExpr::WILDCARD ); +const std::string LDAPExpr::NULLQ = "Null query"; +const std::string LDAPExpr::GARBAGE = "Trailing garbage"; +const std::string LDAPExpr::EOS = "Unexpected end of query"; +const std::string LDAPExpr::MALFORMED = "Malformed query"; +const std::string LDAPExpr::OPERATOR = "Undefined operator"; + +bool stricomp(const std::string::value_type& v1, const std::string::value_type& v2) +{ + return ::tolower(v1) == ::tolower(v2); +} + +//! Contains the current parser position and parsing utility methods. +class LDAPExpr::ParseState +{ + +private: + + std::size_t m_pos; + std::string m_str; + +public: + + ParseState(const std::string &str) throw (std::invalid_argument); + + //! Move m_pos to remove the prefix \a pre + bool prefix(const std::string &pre); + + /** Peek a char at m_pos + \note If index out of bounds, throw exception + */ + LDAPExpr::Byte peek(); + + //! Increment m_pos by n + void skip(int n); + + //! return string from m_pos until the end + std::string rest() const; + + //! Move m_pos until there's no spaces + void skipWhite(); + + //! Get string until special chars. Move m_pos + std::string getAttributeName(); + + //! Get string and convert * to WILDCARD + std::string getAttributeValue(); + + //! Throw InvalidSyntaxException exception + void error(const std::string &m) const throw (std::invalid_argument); + +}; + + +class LDAPExprData : public SharedData +{ +public: + + LDAPExprData( int op, const std::vector& args ) + : m_operator(op), m_args(args) + { + } + + LDAPExprData( int op, std::string attrName, const std::string& attrValue ) + : m_operator(op), m_attrName(attrName), m_attrValue(attrValue) + { + } + + LDAPExprData( const LDAPExprData& other ) + : SharedData(other), m_operator(other.m_operator), + m_args(other.m_args), m_attrName(other.m_attrName), + m_attrValue(other.m_attrValue) + { + } + + int m_operator; + std::vector m_args; + std::string m_attrName; + std::string m_attrValue; +}; + +LDAPExpr::LDAPExpr() +{ +} + +LDAPExpr::LDAPExpr( const std::string &filter ) +{ + ParseState ps(filter); + try + { + LDAPExpr expr = ParseExpr(ps); + + if (!Trim(ps.rest()).empty()) + { + ps.error(GARBAGE + " '" + ps.rest() + "'"); + } + + d = expr.d; + } + catch (const std::out_of_range&) + { + ps.error(EOS); + } +} + +LDAPExpr::LDAPExpr( int op, const std::vector& args ) + : d(new LDAPExprData(op, args)) +{ +} + +LDAPExpr::LDAPExpr( int op, const std::string &attrName, const std::string &attrValue ) + : d(new LDAPExprData(op, attrName, attrValue)) +{ +} + +LDAPExpr::LDAPExpr( const LDAPExpr& other ) + : d(other.d) +{ +} + +LDAPExpr& LDAPExpr::operator=(const LDAPExpr& other) +{ + d = other.d; + return *this; +} + +LDAPExpr::~LDAPExpr() +{ +} + +std::string LDAPExpr::Trim(std::string str) +{ + str.erase(0, str.find_first_not_of(' ')); + str.erase(str.find_last_not_of(' ')+1); + return str; +} + +bool LDAPExpr::GetMatchedObjectClasses(ObjectClassSet& objClasses) const +{ + if (d->m_operator == EQ) + { + if (std::equal(d->m_attrName.begin(), d->m_attrName.end(), ServiceConstants::OBJECTCLASS().begin(), stricomp) && + d->m_attrValue.find(WILDCARD) == std::string::npos) + { + objClasses.insert( d->m_attrValue ); + return true; + } + return false; + } + else if (d->m_operator == AND) + { + bool result = false; + for (std::size_t i = 0; i < d->m_args.size( ); i++) + { + LDAPExpr::ObjectClassSet r; + if (d->m_args[i].GetMatchedObjectClasses(r)) + { + result = true; + if (objClasses.empty()) + { + objClasses = r; + } + else + { + // if AND op and classes in several operands, + // then only the intersection is possible. + LDAPExpr::ObjectClassSet::iterator it1 = objClasses.begin(); + LDAPExpr::ObjectClassSet::iterator it2 = r.begin(); + while ( (it1 != objClasses.end()) && (it2 != r.end()) ) + { + if (*it1 < *it2) + { + objClasses.erase(it1++); + } + else if (*it2 < *it1) + { + ++it2; + } + else + { // *it1 == *it2 + ++it1; + ++it2; + } + } + // Anything left in set_1 from here on did not appear in set_2, + // so we remove it. + objClasses.erase(it1, objClasses.end()); + } + } + } + return result; + } + else if (d->m_operator == OR) + { + for (std::size_t i = 0; i < d->m_args.size( ); i++) + { + LDAPExpr::ObjectClassSet r; + if (d->m_args[i].GetMatchedObjectClasses(r)) + { + std::copy(r.begin(), r.end(), std::inserter(objClasses, objClasses.begin())); + } + else + { + objClasses.clear(); + return false; + } + } + return true; + } + return false; +} + +std::string LDAPExpr::ToLower(const std::string& str) +{ + std::string lowerStr(str); + std::transform(str.begin(), str.end(), lowerStr.begin(), ::tolower); + return lowerStr; +} + +bool LDAPExpr::IsSimple(const StringList& keywords, LocalCache& cache, + bool matchCase ) const +{ + if (cache.empty()) + { + cache.resize(keywords.size()); + } + + if (d->m_operator == EQ) + { + StringList::const_iterator index; + if ((index = std::find(keywords.begin(), keywords.end(), matchCase ? d->m_attrName : ToLower(d->m_attrName))) != keywords.end() && + d->m_attrValue.find_first_of(WILDCARD) == std::string::npos) + { + cache[index - keywords.begin()] = StringList(1, d->m_attrValue); + return true; + } + } + else if (d->m_operator == OR) + { + for (std::size_t i = 0; i < d->m_args.size( ); i++) + { + if (!d->m_args[i].IsSimple(keywords, cache, matchCase)) + return false; + } + return true; + } + return false; +} + +bool LDAPExpr::IsNull() const +{ + return !d; +} + +bool LDAPExpr::Query( const std::string &filter, const ServiceProperties &pd ) +{ + return LDAPExpr(filter).Evaluate(pd, false); +} + +bool LDAPExpr::Evaluate( const ServiceProperties& p, bool matchCase ) const +{ + if ((d->m_operator & SIMPLE) != 0) + { + Any propVal; + ServiceProperties::const_iterator it = p.find(d->m_attrName); + if (it != p.end() && (matchCase ? d->m_attrName == (std::string)it->first : true)) + { + propVal = it->second; + } + return Compare(propVal, d->m_operator, d->m_attrValue); + } + else + { // (d->m_operator & COMPLEX) != 0 + switch (d->m_operator) + { + case AND: + for (std::size_t i = 0; i < d->m_args.size(); i++) + { + if (!d->m_args[i].Evaluate(p, matchCase)) + return false; + } + return true; + case OR: + for (std::size_t i = 0; i < d->m_args.size(); i++) + { + if (d->m_args[i].Evaluate(p, matchCase)) + return true; + } + return false; + case NOT: + return !d->m_args[0].Evaluate(p, matchCase); + default: + return false; // Cannot happen + } + } +} + +bool LDAPExpr::Compare( const Any& obj, int op, const std::string& s ) const +{ + if (obj.Empty()) + return false; + if (op == EQ && s == WILDCARD_STRING) + return true; + + try + { + const std::type_info& objType = obj.Type(); + if (objType == typeid(std::string)) + { + return CompareString(ref_any_cast(obj), op, s); + } + else if (objType == typeid(std::vector)) + { + const std::vector& list = ref_any_cast >(obj); + for (std::size_t it = 0; it != list.size(); it++) + { + if (CompareString(list[it], op, s)) + return true; + } + } + else if (objType == typeid(std::list)) + { + const std::list& list = ref_any_cast >(obj); + for (std::list::const_iterator it = list.begin(); + it != list.end(); ++it) + { + if (CompareString(*it, op, s)) + return true; + } + } + else if (objType == typeid(char)) + { + return CompareString(std::string(1, ref_any_cast(obj)), op, s); + } + else if (objType == typeid(bool)) + { + if (op==LE || op==GE) + return false; + + std::string boolVal = any_cast(obj) ? "true" : "false"; + return std::equal(s.begin(), s.end(), boolVal.begin(), stricomp); + } + else if (objType == typeid(Byte) || objType == typeid(int)) + { + int sInt; + std::stringstream ss(s); + ss >> sInt; + int intVal = any_cast(obj); + + switch(op) + { + case LE: + return intVal <= sInt; + case GE: + return intVal >= sInt; + default: /*APPROX and EQ*/ + return intVal == sInt; + } + } + else if (objType == typeid(float)) + { + float sFloat; + std::stringstream ss(s); + ss >> sFloat; + float floatVal = any_cast(obj); + + switch(op) + { + case LE: + return floatVal <= sFloat; + case GE: + return floatVal >= sFloat; + default: /*APPROX and EQ*/ + float diff = floatVal - sFloat; + return (diff < std::numeric_limits::epsilon()) && (diff > -std::numeric_limits::epsilon()); + } + } + else if (objType == typeid(double)) + { + double sDouble; + std::stringstream ss(s); + ss >> sDouble; + double doubleVal = any_cast(obj); + + switch(op) + { + case LE: + return doubleVal <= sDouble; + case GE: + return doubleVal >= sDouble; + default: /*APPROX and EQ*/ + double diff = doubleVal - sDouble; + return (diff < std::numeric_limits::epsilon()) && (diff > -std::numeric_limits::epsilon()); + } + } + else if (objType == typeid(long long int)) + { + long long int sLongInt; + std::stringstream ss(s); + ss >> sLongInt; + long long int longIntVal = any_cast(obj); + + switch(op) + { + case LE: + return longIntVal <= sLongInt; + case GE: + return longIntVal >= sLongInt; + default: /*APPROX and EQ*/ + return longIntVal == sLongInt; + } + } + else if (objType == typeid(std::vector)) + { + const std::vector& list = ref_any_cast >(obj); + for (std::size_t it = 0; it != list.size(); it++) + { + if (Compare(list[it], op, s)) + return true; + } + } + } + catch (...) + { + // This might happen if a std::string-to-datatype conversion fails + // Just consider it a false match and ignore the exception + } + return false; +} + +bool LDAPExpr::CompareString( const std::string& s1, int op, const std::string& s2 ) +{ + switch(op) + { + case LE: + return s1.compare(s2) <= 0; + case GE: + return s1.compare(s2) >= 0; + case EQ: + return PatSubstr(s1,s2); + case APPROX: + return FixupString(s2) == FixupString(s1); + default: + return false; + } +} + +std::string LDAPExpr::FixupString( const std::string& s ) +{ + std::string sb; + int len = s.length(); + for(int i=0; im_operator + + std::vector v; + do + { + v.push_back(ParseExpr(ps)); + ps.skipWhite(); + } while (ps.peek() == '('); + + int n = v.size(); + if (!ps.prefix(")") || n == 0 || (op == NOT && n > 1)) + ps.error(MALFORMED); + + return LDAPExpr(op, v); +} + +LDAPExpr LDAPExpr::ParseSimple( ParseState &ps ) +{ + std::string attrName = ps.getAttributeName(); + if (attrName.empty()) + ps.error(MALFORMED); + int op = 0; + if (ps.prefix("=")) + op = EQ; + else if (ps.prefix("<=")) + op = LE; + else if(ps.prefix(">=")) + op = GE; + else if(ps.prefix("~=")) + op = APPROX; + else + { + // System.out.println("undef op='" + ps.peek() + "'"); + ps.error(OPERATOR); // Does not return + } + std::string attrValue = ps.getAttributeValue(); + if (!ps.prefix(")")) + ps.error(MALFORMED); + return LDAPExpr(op, attrName, attrValue); +} + +const std::string LDAPExpr::ToString() const +{ + std::string res; + res.append("("); + if ((d->m_operator & SIMPLE) != 0) + { + res.append(d->m_attrName); + switch (d->m_operator) + { + case EQ: + res.append("="); + break; + case LE: + res.append("<="); + break; + case GE: + res.append(">="); + break; + case APPROX: + res.append("~="); + break; + } + + for (std::size_t i = 0; i < d->m_attrValue.length(); i++) + { + Byte c = d->m_attrValue.at(i); + if (c == '(' || c == ')' || c == '*' || c == '\\') + { + res.append(1, '\\'); + } + else if (c == WILDCARD) + { + c = '*'; + } + res.append(1, c); + } + } + else + { + switch (d->m_operator) + { + case AND: + res.append("&"); + break; + case OR: + res.append("|"); + break; + case NOT: + res.append("!"); + break; + } + for (std::size_t i = 0; i < d->m_args.size(); i++) + { + res.append(d->m_args[i].ToString()); + } + } + res.append(")"); + return res; +} + +LDAPExpr::ParseState::ParseState( const std::string& str ) throw (std::invalid_argument) +{ + if (str.empty()) + { + error(NULLQ); + } + + m_str = str; + m_pos = 0; +} + +bool LDAPExpr::ParseState::prefix( const std::string& pre ) +{ + std::string::iterator startIter = m_str.begin() + m_pos; + if (!std::equal(pre.begin(), pre.end(), startIter)) + return false; + m_pos += pre.size(); + return true; +} + +char LDAPExpr::ParseState::peek() +{ + if ( m_pos >= m_str.size() ) + { + throw std::out_of_range( "LDAPExpr" ); + } + return m_str.at(m_pos); +} + +void LDAPExpr::ParseState::skip( int n ) +{ + m_pos += n; +} + +std::string LDAPExpr::ParseState::rest() const +{ + return m_str.substr(m_pos); +} + +void LDAPExpr::ParseState::skipWhite() +{ + while (std::isspace(peek())) + { + m_pos++; + } +} + +std::string LDAPExpr::ParseState::getAttributeName() +{ + int start = m_pos; + int n = -1; + for(;; m_pos++) + { + Byte c = peek(); + if (c == '(' || c == ')' || + c == '<' || c == '>' || + c == '=' || c == '~') { + break; + } + else if (!std::isspace(c)) + { + n = m_pos - start + 1; + } + } + if (n == -1) + { + return std::string(); + } + return m_str.substr(start, n); +} + +std::string LDAPExpr::ParseState::getAttributeValue() +{ + std::string sb; + bool exit = false; + while( !exit ) { + Byte c = peek( ); + switch(c) + { + case '(': + case ')': + exit = true; + break; + case '*': + sb.append(1, WILDCARD); + break; + case '\\': + sb.append(1, m_str.at(++m_pos)); + break; + default: + sb.append(1, c); + break; + } + + if ( !exit ) + { + m_pos++; + } + } + return sb; +} + +void LDAPExpr::ParseState::error( const std::string &m ) const throw (std::invalid_argument) +{ + std::string error = m + ": " + (m_str.empty() ? "" : m_str.substr(m_pos)); + throw std::invalid_argument(error); +} + +} diff --git a/Core/Code/Service/mitkLDAPExpr_p.h b/Core/Code/Service/mitkLDAPExpr_p.h new file mode 100644 index 0000000000..2b2049f982 --- /dev/null +++ b/Core/Code/Service/mitkLDAPExpr_p.h @@ -0,0 +1,188 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKLDAPEXPR_H +#define MITKLDAPEXPR_H + +#include +#include + +#include + +#ifdef MITK_HAS_UNORDERED_SET_H +#include +#else +#include "mitkItkHashSet.h" +#endif + +#include "mitkSharedData.h" +#include "mitkServiceProperties.h" + +namespace mitk { + +class LDAPExprData; + +/** + * This class is not part of the public API. + */ +class LDAPExpr { + +public: + + const static int AND; // = 0; + const static int OR; // = 1; + const static int NOT; // = 2; + const static int EQ; // = 4; + const static int LE; // = 8; + const static int GE; // = 16; + const static int APPROX; // = 32; + const static int COMPLEX; // = AND | OR | NOT; + const static int SIMPLE; // = EQ | LE | GE | APPROX; + + typedef char Byte; + typedef std::vector StringList; + typedef std::vector LocalCache; +#ifdef MITK_HAS_UNORDERED_SET_H + typedef std::unordered_set ObjectClassSet; +#else + typedef itk::hash_set ObjectClassSet; +#endif + + /** + * Creates an invalid LDAPExpr object. Use with care. + * + * @see IsNull() + */ + LDAPExpr(); + + LDAPExpr(const std::string& filter); + + LDAPExpr(const LDAPExpr& other); + + LDAPExpr& operator=(const LDAPExpr& other); + + ~LDAPExpr(); + + /** + * Get object class set matched by this LDAP expression. This will not work + * with wildcards and NOT expressions. If a set can not be determined return false. + * + * \param objClasses The set of matched classes will be added to objClasses. + * \return If the set cannot be determined, false is returned, true otherwise. + */ + bool GetMatchedObjectClasses(ObjectClassSet& objClasses) const; + + /** + * Checks if this LDAP expression is "simple". The definition of + * a simple filter is: + *
    + *
  • (name=value) is simple if + * name is a member of the provided keywords, + * and value does not contain a wildcard character;
  • + *
  • (| EXPR+ ) is simple if all EXPR + * expressions are simple;
  • + *
  • No other expressions are simple.
  • + *
+ * If the filter is found to be simple, the cache is + * filled with mappings from the provided keywords to lists + * of attribute values. The keyword-value-pairs are the ones that + * satisfy this expression, for the given keywords. + * + * @param keywords The keywords to look for. + * @param cache An array (indexed by the keyword indexes) of lists to + * fill in with values saturating this expression. + * @return true if this expression is simple, + * false otherwise. + */ + bool IsSimple( + const StringList& keywords, + LocalCache& cache, + bool matchCase) const; + + /** + * Returns true if this instance is invalid, i.e. it was + * constructed using LDAPExpr(). + * + * @return true if the expression is invalid, + * false otherwise. + */ + bool IsNull() const; + + //! + static bool Query(const std::string& filter, const ServiceProperties& pd); + + //! Evaluate this LDAP filter. + bool Evaluate(const ServiceProperties& p, bool matchCase) const; + + //! + const std::string ToString() const; + + +private: + + class ParseState; + + //! + LDAPExpr(int op, const std::vector& args); + + //! + LDAPExpr(int op, const std::string& attrName, const std::string& attrValue); + + //! + static LDAPExpr ParseExpr(ParseState& ps); + + //! + static LDAPExpr ParseSimple(ParseState& ps); + + static std::string Trim(std::string str); + + static std::string ToLower(const std::string& str); + + //! + bool Compare(const Any& obj, int op, const std::string& s) const; + + //! + static bool CompareString(const std::string& s1, int op, const std::string& s2); + + //! + static std::string FixupString(const std::string &s); + + //! + static bool PatSubstr(const std::string& s, const std::string& pat); + + //! + static bool PatSubstr(const std::string& s, int si, const std::string& pat, int pi); + + + const static Byte WILDCARD; // = 65535; + const static std::string WILDCARD_STRING;// = std::string( WILDCARD ); + + const static std::string NULLQ; // = "Null query"; + const static std::string GARBAGE; // = "Trailing garbage"; + const static std::string EOS; // = "Unexpected end of query"; + const static std::string MALFORMED; // = "Malformed query"; + const static std::string OPERATOR; // = "Undefined m_operator"; + + //! Shared pointer + SharedDataPointer d; + +}; + +} + +#endif // MITKLDAPEXPR_H diff --git a/Core/Code/Service/mitkLDAPFilter.cpp b/Core/Code/Service/mitkLDAPFilter.cpp new file mode 100644 index 0000000000..9f099f42b1 --- /dev/null +++ b/Core/Code/Service/mitkLDAPFilter.cpp @@ -0,0 +1,112 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkLDAPFilter.h" + +#include "mitkLDAPExpr_p.h" +#include "mitkServiceReferencePrivate.h" + +namespace mitk { + +class LDAPFilterData : public SharedData +{ +public: + + LDAPFilterData() + {} + + LDAPFilterData(const std::string& filter) + : ldapExpr(filter) + {} + + LDAPFilterData(const LDAPFilterData& other) + : SharedData(other), ldapExpr(other.ldapExpr) + {} + + LDAPExpr ldapExpr; +}; + +LDAPFilter::LDAPFilter() + : d(0) +{ +} + +LDAPFilter::LDAPFilter(const std::string& filter) + : d(0) +{ + try + { + d = new LDAPFilterData(filter); + } + catch (const std::exception& e) + { + throw std::invalid_argument(e.what()); + } +} + +LDAPFilter::LDAPFilter(const LDAPFilter& other) + : d(other.d) +{ +} + +LDAPFilter::~LDAPFilter() +{ +} + +LDAPFilter::operator bool() const +{ + return d; +} + +bool LDAPFilter::Match(const ServiceReference& reference) const +{ + return d->ldapExpr.Evaluate(reference.d->GetProperties(), true); +} + +bool LDAPFilter::Match(const ServiceProperties& dictionary) const +{ + return d->ldapExpr.Evaluate(dictionary, false); +} + +bool LDAPFilter::MatchCase(const ServiceProperties& dictionary) const +{ + return d->ldapExpr.Evaluate(dictionary, true); +} + +std::string LDAPFilter::ToString() const +{ + return d->ldapExpr.ToString(); +} + +bool LDAPFilter::operator==(const LDAPFilter& other) const +{ + return d->ldapExpr.ToString() == other.d->ldapExpr.ToString(); +} + +LDAPFilter& LDAPFilter::operator=(const LDAPFilter& filter) +{ + d = filter.d; + + return *this; +} + +} + +std::ostream& operator<<(std::ostream& os, const mitk::LDAPFilter& filter) +{ + return os << filter.ToString(); +} diff --git a/Core/Code/Service/mitkLDAPFilter.h b/Core/Code/Service/mitkLDAPFilter.h new file mode 100644 index 0000000000..8f859b6a32 --- /dev/null +++ b/Core/Code/Service/mitkLDAPFilter.h @@ -0,0 +1,163 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKLDAPFILTER_H +#define MITKLDAPFILTER_H + +#include "mitkCommon.h" + +#include "mitkServiceReference.h" +#include "mitkServiceProperties.h" + +#include "mitkSharedData.h" + +namespace mitk { + +class LDAPFilterData; + +/** + * \ingroup MicroServices + * + * An
RFC 1960-based Filter. + * + *

+ * A LDAPFilter can be used numerous times to determine if the match + * argument matches the filter string that was used to create the LDAPFilter. + *

+ * Some examples of LDAP filters are: + * + * - "(cn=Babs Jensen)" + * - "(!(cn=Tim Howes))" + * - "(&(" + ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))" + * - "(o=univ*of*mich*)" + * + * \remarks This class is thread safe. + */ +class MITK_CORE_EXPORT LDAPFilter { + +public: + + /** + * Creates in invalid LDAPFilter object. + * Test the validity by using the boolean conversion operator. + * + *

+ * Calling methods on an invalid LDAPFilter + * will result in undefined behavior. + */ + LDAPFilter(); + + /** + * Creates a LDAPFilter object. This LDAPFilter + * object may be used to match a ServiceReference object or a + * ServiceProperties object. + * + *

+ * If the filter cannot be parsed, an std::invalid_argument will be + * thrown with a human readable message where the filter became unparsable. + * + * @param filter The filter string. + * @return A LDAPFilter object encapsulating the filter string. + * @throws std::invalid_argument If filter contains an invalid + * filter string that cannot be parsed. + * @see "Framework specification for a description of the filter string syntax." TODO! + */ + LDAPFilter(const std::string& filter); + + LDAPFilter(const LDAPFilter& other); + + ~LDAPFilter(); + + operator bool() const; + + /** + * Filter using a service's properties. + *

+ * This LDAPFilter is executed using the keys and values of the + * referenced service's properties. The keys are looked up in a case + * insensitive manner. + * + * @param reference The reference to the service whose properties are used + * in the match. + * @return true if the service's properties match this + * LDAPFilter false otherwise. + */ + bool Match(const ServiceReference& reference) const; + + /** + * Filter using a ServiceProperties object with case insensitive key lookup. This + * LDAPFilter is executed using the specified ServiceProperties's keys + * and values. The keys are looked up in a case insensitive manner. + * + * @param dictionary The ServiceProperties whose key/value pairs are used + * in the match. + * @return true if the ServiceProperties's values match this + * filter; false otherwise. + */ + bool Match(const ServiceProperties& dictionary) const; + + /** + * Filter using a ServiceProperties. This LDAPFilter is executed using + * the specified ServiceProperties's keys and values. The keys are looked + * up in a normal manner respecting case. + * + * @param dictionary The ServiceProperties whose key/value pairs are used + * in the match. + * @return true if the ServiceProperties's values match this + * filter; false otherwise. + */ + bool MatchCase(const ServiceProperties& dictionary) const; + + /** + * Returns this LDAPFilter's filter string. + *

+ * The filter string is normalized by removing whitespace which does not + * affect the meaning of the filter. + * + * @return This LDAPFilter's filter string. + */ + std::string ToString() const; + + /** + * Compares this LDAPFilter to another LDAPFilter. + * + *

+ * This implementation returns the result of calling + * this->ToString() == other.ToString(). + * + * @param other The object to compare against this LDAPFilter. + * @return Returns the result of calling + * this->ToString() == other.ToString(). + */ + bool operator==(const LDAPFilter& other) const; + + LDAPFilter& operator=(const LDAPFilter& filter); + +protected: + + SharedDataPointer d; + +}; + +} + +/** + * \ingroup MicroServices + */ +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, const mitk::LDAPFilter& filter); + +#endif // MITKLDAPFILTER_H diff --git a/Core/Code/Service/mitkModule.cpp b/Core/Code/Service/mitkModule.cpp new file mode 100644 index 0000000000..d7321ee6f4 --- /dev/null +++ b/Core/Code/Service/mitkModule.cpp @@ -0,0 +1,223 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "mitkModule.h" + +#include "mitkModuleContext.h" +#include "mitkModuleActivator.h" +#include "mitkModulePrivate.h" +#include "mitkCoreModuleContext_p.h" + +namespace mitk { + +const std::string& Module::PROP_ID() +{ + static const std::string s("module.id"); + return s; +} +const std::string& Module::PROP_NAME() +{ + static const std::string s("module.name"); + return s; +} +const std::string& Module::PROP_LOCATION() +{ + static const std::string s("module.location"); + return s; +} +const std::string& Module::PROP_MODULE_DEPENDS() +{ + static const std::string s("module.module_depends"); + return s; +} +const std::string& Module::PROP_LIB_DEPENDS() +{ + static const std::string s("module.lib_depends"); + return s; +} +const std::string& Module::PROP_PACKAGE_DEPENDS() +{ + static const std::string s("module.package_depends"); + return s; +} +const std::string& Module::PROP_VERSION() +{ + static const std::string s("module.version"); + return s; +} +const std::string& Module::PROP_QT() +{ + static const std::string s("module.qt"); + return s; +} + +Module::Module() +: d(0) +{ + +} + +Module::~Module() +{ + delete d; +} + +void Module::Init(CoreModuleContext* coreCtx, + ModuleInfo* info) +{ + ModulePrivate* mp = new ModulePrivate(this, coreCtx, info); + std::swap(mp, d); + delete mp; +} + +bool Module::IsLoaded() const +{ + return d->moduleContext != 0; +} + +void Module::Start() +{ + + if (d->moduleContext) + { + MITK_WARN << "Module " << d->info.name << " already started."; + return; + } + + d->moduleContext = new ModuleContext(this->d); + +// try +// { + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::LOADING, this)); + // try to get a ModuleActivator instance + if (d->info.activatorHook) + { + try + { + d->moduleActivator = d->info.activatorHook(); + } + catch (...) + { + MITK_ERROR << "Creating the module activator of " << d->info.name << " failed"; + throw; + } + + d->moduleActivator->Load(d->moduleContext); + } + + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::LOADED, this)); +// } +// catch (...) +// { +// d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADING, this)); +// d->RemoveModuleResources(); + +// delete d->moduleContext; +// d->moduleContext = 0; + +// d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); +// MITK_ERROR << "Calling the module activator Load() method of " << d->info.name << " failed!"; +// throw; +// } +} + +void Module::Stop() +{ + if (d->moduleContext == 0) + { + MITK_WARN << "Module " << d->info.name << " already stopped."; + return; + } + + try + { + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADING, this)); + if (d->moduleActivator) + { + d->moduleActivator->Unload(d->moduleContext); + } + } + catch (...) + { + MITK_ERROR << "Calling the module activator Unload() method of " << d->info.name << " failed!"; + + try + { + d->RemoveModuleResources(); + } + catch (...) {} + + delete d->moduleContext; + d->moduleContext = 0; + + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); + + throw; + } + + d->RemoveModuleResources(); + delete d->moduleContext; + d->moduleContext = 0; + d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); +} + +ModuleContext* Module::GetModuleContext() const +{ + return d->moduleContext; +} + +long Module::GetModuleId() const +{ + return d->info.id; +} + +std::string Module::GetLocation() const +{ + return d->info.location; +} + +std::string Module::GetName() const +{ + return d->info.name; +} + +ModuleVersion Module::GetVersion() const +{ + return d->version; +} + +std::string Module::GetProperty(const std::string& key) const +{ + if (d->properties.count(key) == 0) return ""; + return d->properties[key]; +} + +} // end namespace mitk + +std::ostream& operator<<(std::ostream& os, const mitk::Module& module) +{ + os << "Module[" << "id=" << module.GetModuleId() << + ", loc=" << module.GetLocation() << + ", name=" << module.GetName() << "]"; + return os; +} + +std::ostream& operator<<(std::ostream& os, mitk::Module const * module) +{ + return operator<<(os, *module); +} diff --git a/Core/Code/Service/mitkModule.h b/Core/Code/Service/mitkModule.h new file mode 100644 index 0000000000..59d580050d --- /dev/null +++ b/Core/Code/Service/mitkModule.h @@ -0,0 +1,243 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKMODULE_H +#define MITKMODULE_H + +#include + +#include "mitkModuleVersion.h" + +namespace mitk { + +class CoreModuleContext; +class ModuleInfo; +class ModuleContext; +class ModulePrivate; + +/** + * \ingroup MicroServices + * + * Represents a MITK module. + * + *

+ * A %Module object is the access point to a MITK module. + * Each MITK module has an associated %Module object. + * + *

+ * A module has unique identity, a long, chosen by the + * framework. This identity does not change during the lifecycle of a module. + * + *

+ * A module can be in one of two states: + *

    + *
  • LOADED + *
  • UNLOADED + *
+ *

+ * You can determine the current state by using IsLoaded(). + * + *

+ * A module can only execute code when its state is LOADED. + * An UNLOADED module is a + * zombie and can only be reached because it was loaded before. However, + * unloaded modules can be loaded again. + * + *

+ * The framework is the only entity that is allowed to create + * %Module objects. + * + * @remarks This class is thread safe. + */ +class MITK_CORE_EXPORT Module +{ + +public: + + static const std::string& PROP_ID(); + static const std::string& PROP_NAME(); + static const std::string& PROP_LOCATION(); + static const std::string& PROP_MODULE_DEPENDS(); + static const std::string& PROP_PACKAGE_DEPENDS(); + static const std::string& PROP_LIB_DEPENDS(); + static const std::string& PROP_VERSION(); + static const std::string& PROP_QT(); + + ~Module(); + + /** + * Returns this module's current state. + * + *

+ * A module can be in only one state at any time. + * + * @return true if the module is LOADED + * false if it is UNLOADED + */ + bool IsLoaded() const; + + /** + * Returns this module's {@link ModuleContext}. The returned + * ModuleContext can be used by the caller to act on behalf + * of this module. + * + *

+ * If this module is not in the LOADED state, then this + * module has no valid ModuleContext. This method will + * return 0 if this module has no valid + * ModuleContext. + * + * @return A ModuleContext for this module or + * 0 if this module has no valid + * ModuleContext. + */ + ModuleContext* GetModuleContext() const; + + /** + * Returns this module's unique identifier. This module is assigned a unique + * identifier by the framework when it was loaded. + * + *

+ * A module's unique identifier has the following attributes: + *

    + *
  • Is unique and persistent. + *
  • Is a long. + *
  • Its value is not reused for another module, even after a module is + * unloaded. + *
  • Does not change while a module remains loaded. + *
  • Does not change when a module is reloaded. + *
+ * + *

+ * This method continues to return this module's unique identifier while + * this module is in the UNLOADED state. + * + * @return The unique identifier of this module. + */ + long GetModuleId() const; + + /** + * Returns this module's location. + * + *

+ * The location is the full path to the module's shared library. + * This method continues to return this module's location + * while this module is in the UNLOADED state. + * + * @return The string representation of this module's location. + */ + std::string GetLocation() const; + + /** + * Returns the name of this module as specified by the + * MITK_CREATE_MODULE CMake macro. The module + * name together with a version must identify a unique module. + * + *

+ * This method continues to return this module's name while + * this module is in the UNLOADED state. + * + * @return The name of this module. + */ + std::string GetName() const; + + /** + * Returns the version of this module as specified by the + * MITK_CREATE_MODULE CMake macro. If this module does not have a + * specified version then {@link ModuleVersion#EmptyVersion} is returned. + * + *

+ * This method continues to return this module's version while + * this module is in the UNLOADED state. + * + * @return The version of this module. + */ + ModuleVersion GetVersion() const; + + /** + * Returns the value of the specified property for this module. The + * method returns an empty string if the property is not found. + * + * @param key The name of the requested property. + * @return The value of the requested property, or an empty string + * if the property is undefined. + */ + std::string GetProperty(const std::string& key) const; + +private: + + friend class ModuleRegistry; + friend class ServiceReferencePrivate; + + ModulePrivate* d; + + Module(); + Module(const Module&); + + void Init(CoreModuleContext* coreCtx, ModuleInfo* info); + + void Start(); + void Stop(); + +}; + +} + +#ifdef MITK_HAS_UNORDERED_MAP_H +namespace std { +#elif defined(__GNUC__) +namespace __gnu_cxx { +#else +namespace itk { +#endif + +template class hash; + +template<> class hash +{ +public: + std::size_t operator()(const mitk::Module* module) const + { +#ifdef MITK_HAS_HASH_SIZE_T + return hash()(reinterpret_cast(module)); +#else + std::size_t key = reinterpret_cast(module); + return std::size_t(key & (~0U)); +#endif + } +}; + +/** + * \ingroup MicroServices + */ +namespace ModuleConstants { + +} + +} + +/** + * \ingroup MicroServices + */ +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, const mitk::Module& module); +/** + * \ingroup MicroServices + */ +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, mitk::Module const * module); + +#endif // MITKMODULE_H diff --git a/Core/Code/Service/mitkModuleAbstractTracked.h b/Core/Code/Service/mitkModuleAbstractTracked.h new file mode 100644 index 0000000000..a838b22a51 --- /dev/null +++ b/Core/Code/Service/mitkModuleAbstractTracked.h @@ -0,0 +1,293 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKMODULEABSTRACTTRACKED_H +#define MITKMODULEABSTRACTTRACKED_H + +#include +#include + +#include + +#include "mitkAtomicInt.h" +#include "mitkAny.h" + +namespace mitk { + +/** + * This class is not intended to be used directly. It is exported to support + * the MITK module system. + * + * Abstract class to track items. If a Tracker is reused (closed then reopened), + * then a new ModuleAbstractTracked object is used. This class acts as a map of tracked + * item -> customized object. Subclasses of this class will act as the listener + * object for the tracker. This class is used to synchronize access to the + * tracked items. This is not a public class. It is only for use by the + * implementation of the Tracker class. + * + * @tparam S The tracked item. It is the key. + * @tparam T The value mapped to the tracked item. + * @tparam R The reason the tracked item is being tracked or untracked. + * @ThreadSafe + */ +template +class ModuleAbstractTracked : public itk::SimpleMutexLock +{ + +public: + + /* set this to true to compile in debug messages */ + static const bool DEBUG; // = false; + + typedef std::map TrackingMap; + + /** + * ModuleAbstractTracked constructor. + */ + ModuleAbstractTracked(); + + virtual ~ModuleAbstractTracked(); + + void Wait(); + void WakeAll(); + + /** + * Set initial list of items into tracker before events begin to be + * received. + * + * This method must be called from Tracker's open method while synchronized + * on this object in the same synchronized block as the add listener call. + * + * @param list The initial list of items to be tracked. null + * entries in the list are ignored. + * @GuardedBy this + */ + void SetInitial(const std::list& list); + + /** + * Track the initial list of items. This is called after events can begin to + * be received. + * + * This method must be called from Tracker's open method while not + * synchronized on this object after the add listener call. + * + */ + void TrackInitial(); + + /** + * Called by the owning Tracker object when it is closed. + */ + void Close(); + + /** + * Begin to track an item. + * + * @param item S to be tracked. + * @param related Action related object. + */ + void Track(S item, R related); + + /** + * Discontinue tracking the item. + * + * @param item S to be untracked. + * @param related Action related object. + */ + void Untrack(S item, R related); + + /** + * Returns the number of tracked items. + * + * @return The number of tracked items. + * + * @GuardedBy this + */ + std::size_t Size() const; + + /** + * Returns if the tracker is empty. + * + * @return Whether the tracker is empty. + * + * @GuardedBy this + */ + bool IsEmpty() const; + + /** + * Return the customized object for the specified item + * + * @param item The item to lookup in the map + * @return The customized object for the specified item. + * + * @GuardedBy this + */ + T GetCustomizedObject(S item) const; + + /** + * Return the list of tracked items. + * + * @return The tracked items. + * @GuardedBy this + */ + void GetTracked(std::list& items) const; + + /** + * Increment the modification count. If this method is overridden, the + * overriding method MUST call this method to increment the tracking count. + * + * @GuardedBy this + */ + virtual void Modified(); + + /** + * Returns the tracking count for this ServiceTracker object. + * + * The tracking count is initialized to 0 when this object is opened. Every + * time an item is added, modified or removed from this object the tracking + * count is incremented. + * + * @GuardedBy this + * @return The tracking count for this object. + */ + int GetTrackingCount() const; + + /** + * Copy the tracked items and associated values into the specified map. + * + * @param map The map into which to copy the tracked items and associated + * values. This map must not be a user provided map so that user code + * is not executed while synchronized on this. + * @return The specified map. + * @GuardedBy this + */ + void CopyEntries(TrackingMap& map) const; + + /** + * Call the specific customizer adding method. This method must not be + * called while synchronized on this object. + * + * @param item S to be tracked. + * @param related Action related object. + * @return Customized object for the tracked item or null if + * the item is not to be tracked. + */ + virtual T CustomizerAdding(S item, const R& related) = 0; + + /** + * Call the specific customizer modified method. This method must not be + * called while synchronized on this object. + * + * @param item Tracked item. + * @param related Action related object. + * @param object Customized object for the tracked item. + */ + virtual void CustomizerModified(S item, const R& related, + T object) = 0; + + /** + * Call the specific customizer removed method. This method must not be + * called while synchronized on this object. + * + * @param item Tracked item. + * @param related Action related object. + * @param object Customized object for the tracked item. + */ + virtual void CustomizerRemoved(S item, const R& related, + T object) = 0; + + /** + * List of items in the process of being added. This is used to deal with + * nesting of events. Since events may be synchronously delivered, events + * can be nested. For example, when processing the adding of a service and + * the customizer causes the service to be unregistered, notification to the + * nested call to untrack that the service was unregistered can be made to + * the track method. + * + * Since the std::vector implementation is not synchronized, all access to + * this list must be protected by the same synchronized object for + * thread-safety. + * + * @GuardedBy this + */ + std::list adding; + + /** + * true if the tracked object is closed. + * + * This field is volatile because it is set by one thread and read by + * another. + */ + volatile bool closed; + + /** + * Initial list of items for the tracker. This is used to correctly process + * the initial items which could be modified before they are tracked. This + * is necessary since the initial set of tracked items are not "announced" + * by events and therefore the event which makes the item untracked could be + * delivered before we track the item. + * + * An item must not be in both the initial and adding lists at the same + * time. An item must be moved from the initial list to the adding list + * "atomically" before we begin tracking it. + * + * Since the LinkedList implementation is not synchronized, all access to + * this list must be protected by the same synchronized object for + * thread-safety. + * + * @GuardedBy this + */ + std::list initial; + + /** + * Common logic to add an item to the tracker used by track and + * trackInitial. The specified item must have been placed in the adding list + * before calling this method. + * + * @param item S to be tracked. + * @param related Action related object. + */ + void TrackAdding(S item, R related); + +private: + + itk::ConditionVariable::Pointer waitCond; + + /** + * Map of tracked items to customized objects. + * + * @GuardedBy this + */ + TrackingMap tracked; + + /** + * Modification count. This field is initialized to zero and incremented by + * modified. + * + * @GuardedBy this + */ + AtomicInt trackingCount; + + bool CustomizerAddingFinal(S item, const T& custom); + +}; + +} + +#include "mitkModuleAbstractTracked.tpp" + +#endif // MITKMODULEABSTRACTTRACKED_H diff --git a/Core/Code/Service/mitkModuleAbstractTracked.tpp b/Core/Code/Service/mitkModuleAbstractTracked.tpp new file mode 100644 index 0000000000..9a79d0b3ec --- /dev/null +++ b/Core/Code/Service/mitkModuleAbstractTracked.tpp @@ -0,0 +1,325 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include + +namespace mitk { + +typedef itk::MutexLockHolder MutexLocker; + +template +const bool ModuleAbstractTracked::DEBUG = false; + +template +ModuleAbstractTracked::ModuleAbstractTracked() + : waitCond(itk::ConditionVariable::New()) +{ + closed = false; +} + +template +ModuleAbstractTracked::~ModuleAbstractTracked() +{ + +} + +template +void ModuleAbstractTracked::Wait() +{ + waitCond->Wait(this); +} + +template +void ModuleAbstractTracked::WakeAll() +{ + waitCond->Broadcast(); +} + +template +void ModuleAbstractTracked::SetInitial(const std::list& initiallist) +{ + initial = initiallist; + + if (DEBUG) + { + for(typename std::list::const_iterator item = initiallist.begin(); + item != initiallist.end(); ++item) + { + MITK_DEBUG(true) << "ModuleAbstractTracked::setInitial: " << (*item); + } + } +} + +template +void ModuleAbstractTracked::TrackInitial() +{ + while (true) + { + S item(0); + { + itk::MutexLockHolder lock(*this); + if (closed || (initial.size() == 0)) + { + /* + * if there are no more initial items + */ + return; /* we are done */ + } + /* + * move the first item from the initial list to the adding list + * within this synchronized block. + */ + item = initial.front(); + initial.pop_front(); + if (tracked[item]) + { + /* if we are already tracking this item */ + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::trackInitial[already tracked]: " << item; + continue; /* skip this item */ + } + if (std::find(adding.begin(), adding.end(), item) != adding.end()) + { + /* + * if this item is already in the process of being added. + */ + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::trackInitial[already adding]: " << item; + continue; /* skip this item */ + } + adding.push_back(item); + } + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::trackInitial: " << item; + TrackAdding(item, R()); + /* + * Begin tracking it. We call trackAdding + * since we have already put the item in the + * adding list. + */ + } +} + +template +void ModuleAbstractTracked::Close() +{ + closed = true; +} + +template +void ModuleAbstractTracked::Track(S item, R related) +{ + T object(0); + { + itk::MutexLockHolder lock(*this); + if (closed) + { + return; + } + object = tracked[item]; + if (!object) + { /* we are not tracking the item */ + if (std::find(adding.begin(), adding.end(),item) != adding.end()) + { + /* if this item is already in the process of being added. */ + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::track[already adding]: " << item; + return; + } + adding.push_back(item); /* mark this item is being added */ + } + else + { /* we are currently tracking this item */ + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::track[modified]: " << item; + Modified(); /* increment modification count */ + } + } + + if (!object) + { /* we are not tracking the item */ + TrackAdding(item, related); + } + else + { + /* Call customizer outside of synchronized region */ + CustomizerModified(item, related, object); + /* + * If the customizer throws an unchecked exception, it is safe to + * let it propagate + */ + } +} + +template +void ModuleAbstractTracked::Untrack(S item, R related) +{ + T object(0); + { + itk::MutexLockHolder lock(*this); + std::size_t initialSize = initial.size(); + initial.remove(item); + if (initialSize != initial.size()) + { /* if this item is already in the list + * of initial references to process + */ + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::untrack[removed from initial]: " << item; + return; /* we have removed it from the list and it will not be + * processed + */ + } + + std::size_t addingSize = adding.size(); + adding.remove(item); + if (addingSize != adding.size()) + { /* if the item is in the process of + * being added + */ + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::untrack[being added]: " << item; + return; /* + * in case the item is untracked while in the process of + * adding + */ + } + object = tracked[item]; + /* + * must remove from tracker before + * calling customizer callback + */ + tracked.erase(item); + if (!object) + { /* are we actually tracking the item */ + return; + } + Modified(); /* increment modification count */ + } + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::untrack[removed]: " << item; + /* Call customizer outside of synchronized region */ + CustomizerRemoved(item, related, object); + /* + * If the customizer throws an unchecked exception, it is safe to let it + * propagate + */ +} + +template +std::size_t ModuleAbstractTracked::Size() const +{ + return tracked.size(); +} + +template +bool ModuleAbstractTracked::IsEmpty() const +{ + return tracked.empty(); +} + +template +T ModuleAbstractTracked::GetCustomizedObject(S item) const +{ + typename TrackingMap::const_iterator i = tracked.find(item); + if (i != tracked.end()) return i->second; + return T(); +} + +template +void ModuleAbstractTracked::GetTracked(std::list& items) const +{ + for (typename TrackingMap::const_iterator i = tracked.begin(); + i != tracked.end(); ++i) + { + items.push_back(i->first); + } +} + +template +void ModuleAbstractTracked::Modified() +{ + trackingCount.Ref(); +} + +template +int ModuleAbstractTracked::GetTrackingCount() const +{ + return trackingCount; +} + +template +void ModuleAbstractTracked::CopyEntries(TrackingMap& map) const +{ + map.insert(tracked.begin(), tracked.end()); +} + +template +bool ModuleAbstractTracked::CustomizerAddingFinal(S item, const T& custom) +{ + itk::MutexLockHolder lock(*this); + std::size_t addingSize = adding.size(); + adding.remove(item); + if (addingSize != adding.size() && !closed) + { + /* + * if the item was not untracked during the customizer + * callback + */ + if (custom) + { + tracked[item] = custom; + Modified(); /* increment modification count */ + waitCond->Broadcast(); /* notify any waiters */ + } + return false; + } + else + { + return true; + } +} + +template +void ModuleAbstractTracked::TrackAdding(S item, R related) +{ + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::trackAdding:" << item; + T object(0); + bool becameUntracked = false; + /* Call customizer outside of synchronized region */ + try + { + object = CustomizerAdding(item, related); + becameUntracked = this->CustomizerAddingFinal(item, object); + } + catch (...) + { + /* + * If the customizer throws an exception, it will + * propagate after the cleanup code. + */ + this->CustomizerAddingFinal(item, object); + throw; + } + + /* + * The item became untracked during the customizer callback. + */ + if (becameUntracked && object) + { + MITK_DEBUG(DEBUG) << "ModuleAbstractTracked::trackAdding[removed]: " << item; + /* Call customizer outside of synchronized region */ + CustomizerRemoved(item, related, object); + /* + * If the customizer throws an unchecked exception, it is safe to + * let it propagate + */ + } +} + +} diff --git a/Core/Code/Service/mitkModuleActivator.h b/Core/Code/Service/mitkModuleActivator.h new file mode 100644 index 0000000000..589ffb50c8 --- /dev/null +++ b/Core/Code/Service/mitkModuleActivator.h @@ -0,0 +1,95 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKMODULEACTIVATOR_H_ +#define MITKMODULEACTIVATOR_H_ + +namespace mitk { + +class ModuleContext; + +/** + * \ingroup MicroServices + * + * Customizes the starting and stopping of a MITK module. + *

+ * %ModuleActivator is an interface that can be implemented by + * MITK modules. The MITK core can create instances of a + * module's %ModuleActivator as required. If an instance's + * moduleActivator::Load method executes successfully, it is + * guaranteed that the same instance's %ModuleActivator::Unload + * method will be called when the module is to be unloaded. The MITK core does + * not concurrently call a %ModuleActivator object. + * + *

+ * %ModuleActivator is an abstract class interface whose implementations + * must be exported via a special macro. Implementations are usually declared + * and defined directly in .cpp files. + * + *

+ * \snippet uServices-activator/main.cpp 0 + * + *

+ * The class implementing the %ModuleActivator interface must have a public + * default constructor so that a %ModuleActivator + * object can be created by the MITK core. + * + */ +struct ModuleActivator +{ +public: + + virtual ~ModuleActivator() {} + + /** + * Called when this module is loaded. This method + * can be used to register services or to allocate any resources that this + * module may need globally (during the whole module lifetime). + * + *

+ * This method must complete and return to its caller in a timely manner. + * + * @param context The execution context of the module being loaded. + * @throws std::exception If this method throws an exception, this + * module is marked as stopped and the framework will remove this + * module's listeners, unregister all services registered by this + * module, and release all services used by this module. + */ + virtual void Load(ModuleContext* context) = 0; + + /** + * Called when this module is unloaded. In general, this + * method should undo the work that the ModuleActivator::Load + * method started. There should be no active threads that were started by + * this module when this method returns. + * + *

+ * This method must complete and return to its caller in a timely manner. + * + * @param context The execution context of the module being unloaded. + * @throws std::exception If this method throws an exception, the + * module is still marked as unloaded, and the framework will remove + * the module's listeners, unregister all services registered by the + * module, and release all services used by the module. + */ + virtual void Unload(ModuleContext* context) = 0; + +}; + +} // end namespace mitk + +#endif /* MITKMODULEACTIVATOR_H_ */ diff --git a/Core/Code/Service/mitkModuleContext.cpp b/Core/Code/Service/mitkModuleContext.cpp new file mode 100644 index 0000000000..27fd22abce --- /dev/null +++ b/Core/Code/Service/mitkModuleContext.cpp @@ -0,0 +1,130 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkModuleContext.h" + +#include "mitkModuleRegistry.h" +#include "mitkModulePrivate.h" +#include "mitkCoreModuleContext_p.h" +#include "mitkServiceRegistry_p.h" +#include "mitkServiceReferencePrivate.h" + +namespace mitk { + +class ModuleContextPrivate { + +public: + + ModuleContextPrivate(ModulePrivate* module) + : module(module) + {} + + ModulePrivate* module; +}; + + +ModuleContext::ModuleContext(ModulePrivate* module) + : d(new ModuleContextPrivate(module)) +{} + +ModuleContext::~ModuleContext() +{ + delete d; +} + +Module* ModuleContext::GetModule() const +{ + return d->module->q; +} + +Module* ModuleContext::GetModule(long id) const +{ + return ModuleRegistry::GetModule(id); +} + +void ModuleContext::GetModules(std::vector& modules) const +{ + ModuleRegistry::GetModules(modules); +} + +ServiceRegistration ModuleContext::RegisterService(const std::list& clazzes, + itk::LightObject* service, + const ServiceProperties& properties) +{ + return d->module->coreCtx->services.RegisterService(d->module, clazzes, service, properties); +} + +ServiceRegistration ModuleContext::RegisterService(const char* clazz, itk::LightObject* service, + const ServiceProperties& properties) +{ + std::list clazzes; + clazzes.push_back(clazz); + return d->module->coreCtx->services.RegisterService(d->module, clazzes, service, properties); +} + +std::list ModuleContext::GetServiceReferences(const std::string& clazz, + const std::string& filter) +{ + std::list result; + d->module->coreCtx->services.Get(clazz, filter, 0, result); + return result; +} + +ServiceReference ModuleContext::GetServiceReference(const std::string& clazz) +{ + return d->module->coreCtx->services.Get(d->module, clazz); +} + +itk::LightObject* ModuleContext::GetService(const ServiceReference& reference) +{ + if (!reference) + { + throw std::invalid_argument("Default constructed mitk::ServiceReference is not a valid input to getService()"); + } + ServiceReference internalRef(reference); + return internalRef.d->GetService(d->module->q); +} + +bool ModuleContext::UngetService(const ServiceReference& reference) +{ + ServiceReference ref = reference; + return ref.d->UngetService(d->module->q, true); +} + +void ModuleContext::AddServiceListener(const ServiceListenerDelegate& delegate, + const std::string& filter) +{ + d->module->coreCtx->listeners.AddServiceListener(this, delegate, filter); +} + +void ModuleContext::RemoveServiceListener(const ServiceListenerDelegate& delegate) +{ + d->module->coreCtx->listeners.RemoveServiceListener(this, delegate); +} + +void ModuleContext::AddModuleListener(const ModuleListenerDelegate& delegate) +{ + d->module->coreCtx->listeners.AddModuleListener(this, delegate); +} + +void ModuleContext::RemoveModuleListener(const ModuleListenerDelegate& delegate) +{ + d->module->coreCtx->listeners.RemoveModuleListener(this, delegate); +} + +} + diff --git a/Core/Code/Service/mitkModuleContext.h b/Core/Code/Service/mitkModuleContext.h new file mode 100644 index 0000000000..d1388ee58e --- /dev/null +++ b/Core/Code/Service/mitkModuleContext.h @@ -0,0 +1,659 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKMODULECONTEXT_H_ +#define MITKMODULECONTEXT_H_ + +#include + +#include "mitkServiceInterface.h" +#include "mitkMessage.h" +#include "mitkServiceEvent.h" +#include "mitkServiceRegistration.h" +#include "mitkServiceException.h" +#include "mitkModuleEvent.h" + +namespace mitk { + +typedef MessageAbstractDelegate1 ServiceListenerDelegate; +typedef MessageAbstractDelegate1 ModuleListenerDelegate; + +class ModuleContextPrivate; + +/** + * \ingroup MicroServices + * + * A module's execution context within the framework. The context is used to + * grant access to other methods so that this module can interact with the + * Micro Services Framework. + * + *

+ * ModuleContext methods allow a module to: + *

    + *
  • Subscribe to events published by the framework. + *
  • Register service objects with the framework service registry. + *
  • Retrieve ServiceReferences from the framework service + * registry. + *
  • Get and release service objects for a referenced service. + *
  • Get the list of modules loaded in the framework. + *
  • Get the {@link Module} object for a module. + *
+ * + *

+ * A ModuleContext object will be created and provided to the + * module associated with this context when it is loaded using the + * {@link ModuleActivator::Load} method. The same ModuleContext + * object will be passed to the module associated with this context when it is + * unloaded using the {@link ModuleActivator::Unload} method. A + * ModuleContext object is generally for the private use of its + * associated module and is not meant to be shared with other modules in the + * module environment. + * + *

+ * The Module object associated with a ModuleContext + * object is called the context module. + * + *

+ * The ModuleContext object is only valid during the execution of + * its context module; that is, during the period when the context module + * is loaded. If the ModuleContext + * object is used subsequently, a std::logic_error is + * thrown. The ModuleContext object is never reused after + * its context module is unloaded. + * + *

+ * The framework is the only entity that can create ModuleContext + * objects. + * + * @remarks This class is thread safe. + */ +class MITK_CORE_EXPORT ModuleContext +{ + +public: + + ~ModuleContext(); + + /** + * Returns the Module object associated with this + * ModuleContext. This module is called the context module. + * + * @return The Module object associated with this + * ModuleContext. + * @throws std::logic_error If this ModuleContext is no + * longer valid. + */ + Module* GetModule() const; + + /** + * Returns the module with the specified identifier. + * + * @param id The identifier of the module to retrieve. + * @return A Module object or 0 if the + * identifier does not match any previously loaded module. + */ + Module* GetModule(long id) const; + + + /** + * Returns a list of all known modules. + *

+ * This method returns a list of all modules loaded in the module + * environment at the time of the call to this method. This list will + * also contain modules which might already have been unloaded. + * + * @param modules A std::vector of Module objects which + * will hold one object per known module. + */ + void GetModules(std::vector& modules) const; + + /** + * Registers the specified service object with the specified properties + * under the specified class names into the framework. A + * ServiceRegistration object is returned. The + * ServiceRegistration object is for the private use of the + * module registering the service and should not be shared with other + * modules. The registering module is defined to be the context module. + * Other modules can locate the service by using either the + * {@link #GetServiceReferences} or {@link #GetServiceReference} method. + * + *

+ * A module can register a service object that implements the + * {@link ServiceFactory} interface to have more flexibility in providing + * service objects to other modules. + * + *

+ * The following steps are taken when registering a service: + *

    + *
  1. The framework adds the following service properties to the service + * properties from the specified ServiceProperties (which may be + * omitted):
    + * A property named {@link ServiceConstants#SERVICE_ID} identifying the + * registration number of the service
    + * A property named {@link ServiceConstants#OBJECTCLASS} containing all the + * specified classes.
    + * Properties with these names in the specified ServiceProperties will + * be ignored. + *
  2. The service is added to the framework service registry and may now be + * used by other modules. + *
  3. A service event of type {@link ServiceEvent#REGISTERED} is fired. + *
  4. A ServiceRegistration object for this registration is + * returned. + *
+ * + * @param clazzes The class names under which the service can be located. + * The class names will be stored in the service's + * properties under the key {@link ServiceConstants#OBJECTCLASS}. + * @param service The service object or a ServiceFactory + * object. + * @param properties The properties for this service. The keys in the + * properties object must all be std::string objects. See + * {@link ServiceConstants} for a list of standard service property keys. + * Changes should not be made to this object after calling this + * method. To update the service's properties the + * {@link ServiceRegistration::SetProperties} method must be called. + * The set of properties may be omitted if the service has + * no properties. + * @return A ServiceRegistration object for use by the module + * registering the service to update the service's properties or to + * unregister the service. + * @throws std::invalid_argument If one of the following is true: + *
    + *
  • service is 0. + *
  • properties contains case variants of the same key name. + *
+ * @throws std::logic_error If this ModuleContext is no longer valid. + * @see ServiceRegistration + * @see ServiceFactory + */ + ServiceRegistration RegisterService(const std::list& clazzes, + itk::LightObject* service, + const ServiceProperties& properties = ServiceProperties()); + + /** + * Registers the specified service object with the specified properties + * under the specified class name with the framework. + * + *

+ * This method is otherwise identical to + * RegisterService(const std:vector&, itk::LighObject*, const ServiceProperties&) + * and is provided as a convenience when service will only be registered under a single + * class name. Note that even in this case the value of the service's + * ServiceConstants::OBJECTCLASS property will be a std::list, rather + * than just a single string. + * + * @param clazz The class name under which the service can be located. + * @param service The service object or a ServiceFactory object. + * @param properties The properties for this service. + * @return A ServiceRegistration object for use by the module + * registering the service to update the service's properties or to + * unregister the service. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @see RegisterService(const std:list&, itk::LighObject*, const ServiceProperties&) + */ + ServiceRegistration RegisterService(const char* clazz, itk::LightObject* service, + const ServiceProperties& properties = ServiceProperties()); + + /** + * Registers the specified service object with the specified properties + * using the specified template argument with the framework. + * + *

+ * This method is provided as a convenience when service will only be registered under + * a single class name whose type is available to the caller. It is otherwise identical to + * RegisterService(const char*, itk::LightObject*, const ServiceProperties&) but should be preferred + * since it avoids errors in the string literal identifying the class name or interface identifier. + * + * @tparam S The type under which the service can be located. + * @param service The service object or a ServiceFactory object. + * @param properties The properties for this service. + * @return A ServiceRegistration object for use by the module + * registering the service to update the service's properties or to + * unregister the service. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @see RegisterService(const char*, itk::LighObject*, const ServiceProperties&) + */ + template + ServiceRegistration RegisterService(itk::LightObject* service, const ServiceProperties& properties = ServiceProperties()) + { + const char* clazz = mitk_service_interface_iid(); + if (clazz == 0) + { + throw ServiceException(std::string("The interface class you are registering your service ") + + service->GetNameOfClass() + " against has no MITK_DECLARE_SERVICE_INTERFACE macro"); + } + return RegisterService(clazz, service, properties); + } + + /** + * Returns a list of ServiceReference objects. The returned + * list contains services that + * were registered under the specified class and match the specified filter + * expression. + * + *

+ * The list is valid at the time of the call to this method. However since + * the Micro Services framework is a very dynamic environment, services can be modified or + * unregistered at any time. + * + *

+ * The specified filter expression is used to select the + * registered services whose service properties contain keys and values + * which satisfy the filter expression. See {@link LDAPFilter} for a description + * of the filter syntax. If the specified filter is + * empty, all registered services are considered to match the + * filter. If the specified filter expression cannot be parsed, + * an std::invalid_argument will be thrown with a human readable + * message where the filter became unparsable. + * + *

+ * The result is a list of ServiceReference objects for all + * services that meet all of the following conditions: + *

    + *
  • If the specified class name, clazz, is not + * empty, the service must have been registered with the + * specified class name. The complete list of class names with which a + * service was registered is available from the service's + * {@link ServiceConstants::OBJECTCLASS objectClass} property. + *
  • If the specified filter is not empty, the + * filter expression must match the service. + *
+ * + * @param clazz The class name with which the service was registered or + * an empty string for all services. + * @param filter The filter expression or empty for all + * services. + * @return A list of ServiceReference objects or + * an empty list if no services are registered which satisfy the + * search. + * @throws std::invalid_argument If the specified filter + * contains an invalid filter expression that cannot be parsed. + * @throws std::logic_error If this ModuleContext is no longer valid. + */ + std::list GetServiceReferences(const std::string& clazz, + const std::string& filter = std::string()); + + /** + * Returns a list of ServiceReference objects. The returned + * list contains services that + * were registered under the interface id of the template argument S + * and match the specified filter expression. + * + *

+ * This method is identical to GetServiceReferences(const std::tring&, const std::string&) except that + * the class name for the service object is automatically deduced from the template argument. + * + * @tparam S The type under which the requested service objects must have been registered. + * @param filter The filter expression or empty for all + * services. + * @return A list of ServiceReference objects or + * an empty list if no services are registered which satisfy the + * search. + * @throws std::invalid_argument If the specified filter + * contains an invalid filter expression that cannot be parsed. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @see GetServiceReferences(const std::string&, const std::string&) + */ + template + std::list GetServiceReferences(const std::string& filter = std::string()) + { + const char* clazz = mitk_service_interface_iid(); + if (clazz == 0) throw ServiceException("The service interface class has no MITK_DECLARE_SERVICE_INTERFACE macro"); + return GetServiceReferences(std::string(clazz), filter); + } + + /** + * Returns a ServiceReference object for a service that + * implements and was registered under the specified class. + * + *

+ * The returned ServiceReference object is valid at the time of + * the call to this method. However as the Micro Services framework is a very dynamic + * environment, services can be modified or unregistered at any time. + * + *

+ * This method is the same as calling + * {@link ModuleContext::GetServiceReferences(const std::string&, const std::string&)} with an + * empty filter expression. It is provided as a convenience for + * when the caller is interested in any service that implements the + * specified class. + *

+ * If multiple such services exist, the service with the highest ranking (as + * specified in its {@link ServiceConstants::SERVICE_RANKING} property) is returned. + *

+ * If there is a tie in ranking, the service with the lowest service ID (as + * specified in its {@link ServiceConstants::SERVICE_ID} property); that is, the + * service that was registered first is returned. + * + * @param clazz The class name with which the service was registered. + * @return A ServiceReference object, or an invalid ServiceReference if + * no services are registered which implement the named class. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @throws ServiceException If no service was registered under the given class name. + * @see #GetServiceReferences(const std::string&, const std::string&) + */ + ServiceReference GetServiceReference(const std::string& clazz); + + /** + * Returns a ServiceReference object for a service that + * implements and was registered under the specified template class argument. + * + *

+ * This method is identical to GetServiceReference(const std::string&) except that + * the class name for the service object is automatically deduced from the template argument. + * + * @tparam S The type under which the requested service must have been registered. + * @return A ServiceReference object, or an invalid ServiceReference if + * no services are registered which implement the type S. + * @throws std::logic_error If this ModuleContext is no longer valid. + * @throws ServiceException It no service was registered under the given class name. + * @see #GetServiceReference(const std::string&) + * @see #GetServiceReferences(const std::string&) + */ + template + ServiceReference GetServiceReference() + { + const char* clazz = mitk_service_interface_iid(); + if (clazz == 0) throw ServiceException("The service interface class has no MITK_DECLARE_SERVICE_INTERFACE macro"); + return GetServiceReference(std::string(clazz)); + } + + /** + * Returns the service object referenced by the specified + * ServiceReference object. + *

+ * A module's use of a service is tracked by the module's use count of that + * service. Each time a service's service object is returned by + * {@link #GetService(const ServiceReference&)} the context module's use count for + * that service is incremented by one. Each time the service is released by + * {@link #UngetService(const ServiceReference&)} the context module's use count + * for that service is decremented by one. + *

+ * When a module's use count for a service drops to zero, the module should + * no longer use that service. + * + *

+ * This method will always return 0 when the service + * associated with this reference has been unregistered. + * + *

+ * The following steps are taken to get the service object: + *

    + *
  1. If the service has been unregistered, 0 is returned. + *
  2. The context module's use count for this service is incremented by + * one. + *
  3. If the context module's use count for the service is currently one + * and the service was registered with an object implementing the + * ServiceFactory interface, the + * {@link ServiceFactory::GetService} method is + * called to create a service object for the context module. This service + * object is cached by the framework. While the context module's use count + * for the service is greater than zero, subsequent calls to get the + * services's service object for the context module will return the cached + * service object.
    + * If the ServiceFactory object throws an + * exception, 0 is returned and a warning is logged. + *
  4. The service object for the service is returned. + *
+ * + * @param reference A reference to the service. + * @return A service object for the service associated with + * reference or 0 if the service is not + * registered or the ServiceFactory threw + * an exception. + * @throws std::logic_error If this ModuleContext is no + * longer valid. + * @throws std::invalid_argument If the specified + * ServiceReference is invalid (default constructed). + * @see #UngetService(const ServiceReference&) + * @see ServiceFactory + */ + itk::LightObject* GetService(const ServiceReference& reference); + + /** + * Returns the service object referenced by the specified + * ServiceReference object. + *

+ * This is a convenience method which is identical to itk::LightObject* GetService(const ServiceReference&) + * except that it casts the service object to the supplied template argument type + * + * @tparam S The type the service object will be cast to. + * @return A service object for the service associated with + * reference or 0 if the service is not + * registered, the ServiceFactory threw + * an exception or the service could not be casted to the desired type. + * @throws std::logic_error If this ModuleContext is no + * longer valid. + * @throws std::invalid_argument If the specified + * ServiceReference is invalid (default constructed). + * @see #GetService(const ServiceReference&) + * @see #UngetService(const ServiceReference&) + * @see ServiceFactory + */ + template + S* GetService(const ServiceReference& reference) + { + return dynamic_cast(GetService(reference)); + } + + /** + * Releases the service object referenced by the specified + * ServiceReference object. If the context module's use count + * for the service is zero, this method returns false. + * Otherwise, the context modules's use count for the service is decremented + * by one. + * + *

+ * The service's service object should no longer be used and all references + * to it should be destroyed when a module's use count for the service drops + * to zero. + * + *

+ * The following steps are taken to unget the service object: + *

    + *
  1. If the context module's use count for the service is zero or the + * service has been unregistered, false is returned. + *
  2. The context module's use count for this service is decremented by + * one. + *
  3. If the context module's use count for the service is currently zero + * and the service was registered with a ServiceFactory object, + * the ServiceFactory#UngetService + * method is called to release the service object for the context module. + *
  4. true is returned. + *
+ * + * @param reference A reference to the service to be released. + * @return false if the context module's use count for the + * service is zero or if the service has been unregistered; + * true otherwise. + * @throws std::logic_error If this ModuleContext is no + * longer valid. + * @see #GetService + * @see ServiceFactory + */ + bool UngetService(const ServiceReference& reference); + + /** + * Adds the specified callback with the + * specified filter to the context modules's list of listeners. + * See LDAPFilter for a description of the filter syntax. Listeners + * are notified when a service has a lifecycle state change. + * + *

+ * You must take care to remove registered listeners befor the receiver + * object is destroyed. However, the Micro Services framework takes care + * of removing all listeners registered by this context module's classes + * after the module is unloaded. + * + *

+ * If the context module's list of listeners already contains a pair (r,c) + * of receiver and callback such that + * (r == receiver && c == callback), then this + * method replaces that callback's filter (which may be empty) + * with the specified one (which may be empty). + * + *

+ * The callback is called if the filter criteria is met. To filter based + * upon the class of the service, the filter should reference the + * {@link ServiceConstants#OBJECTCLASS} property. If filter is + * empty, all services are considered to match the filter. + * + *

+ * When using a filter, it is possible that the + * ServiceEvents for the complete lifecycle of a service + * will not be delivered to the callback. For example, if the + * filter only matches when the property x has + * the value 1, the callback will not be called if the + * service is registered with the property x not set to the + * value 1. Subsequently, when the service is modified + * setting property x to the value 1, the + * filter will match and the callback will be called with a + * ServiceEvent of type MODIFIED. Thus, the + * callback will not be called with a ServiceEvent of type + * REGISTERED. + * + * @tparam The type of the receiver (containing the member function to be called) + * @param receiver The object to connect to. + * @param callback The member function pointer to call. + * @param filter The filter criteria. + * @throws std::invalid_argument If filter contains an + * invalid filter string that cannot be parsed. + * @throws std::logic_error If this ModuleContext is no + * longer valid. + * @see ServiceEvent + * @see RemoveServiceListener() + */ + template + void AddServiceListener(R* receiver, void(R::*callback)(const ServiceEvent&), + const std::string& filter = std::string()) + { + MessageDelegate1 delegate(receiver, callback); + AddServiceListener(delegate, filter); + } + + /** + * Removes the specified callback from the context module's + * list of listeners. + * + *

+ * If the (receiver,callback) pair is not contained in this + * context module's list of listeners, this method does nothing. + * + * @tparam The type of the receiver (containing the member function to be removed) + * @param receiver The object from which to disconnect. + * @param callback The member function pointer to remove. + * @throws std::logic_error If this ModuleContext is no + * longer valid. + * @see AddServiceListener() + */ + template + void RemoveServiceListener(R* receiver, void(R::*callback)(const ServiceEvent&)) + { + MessageDelegate1 delegate(receiver, callback); + RemoveServiceListener(delegate); + } + + /** + * Adds the specified callback to the context modules's list + * of listeners. Listeners are notified when a module has a lifecycle + * state change. + * + *

+ * If the context module's list of listeners already contains a pair (r,c) + * of receiver and callback such that + * (r == receiver && c == callback), then this method does nothing. + * + * @tparam The type of the receiver (containing the member function to be called) + * @param receiver The object to connect to. + * @param callback The member function pointer to call. + * @throws std::logic_error If this ModuleContext is no + * longer valid. + * @see ModuleEvent + */ + template + void AddModuleListener(R* receiver, void(R::*callback)(const ModuleEvent&)) + { + MessageDelegate1 delegate(receiver, callback); + AddModuleListener(delegate); + } + + /** + * Removes the specified callback from the context module's + * list of listeners. + * + *

+ * If the (receiver,callback) pair is not contained in this + * context module's list of listeners, this method does nothing. + * + * @tparam The type of the receiver (containing the member function to be removed) + * @param receiver The object from which to disconnect. + * @param callback The member function pointer to remove. + * @throws std::logic_error If this ModuleContext is no + * longer valid. + * @see AddModuleListener() + */ + template + void RemoveModuleListener(R* receiver, void(R::*callback)(const ModuleEvent&)) + { + MessageDelegate1 delegate(receiver, callback); + RemoveModuleListener(delegate); + } + + +private: + + friend class Module; + friend class ModulePrivate; + + ModuleContext(ModulePrivate* module); + + void AddServiceListener(const ServiceListenerDelegate& delegate, + const std::string& filter); + void RemoveServiceListener(const ServiceListenerDelegate& delegate); + + void AddModuleListener(const ModuleListenerDelegate& delegate); + void RemoveModuleListener(const ModuleListenerDelegate& delegate); + + ModuleContextPrivate * const d; +}; + +} + +#ifdef MITK_HAS_UNORDERED_MAP_H +namespace std { +#elif defined(__GNUC__) +namespace __gnu_cxx { +#else +namespace itk { +#endif + +template<> struct hash +{ + std::size_t operator()(const mitk::ModuleContext* context) const + { +#ifdef MITK_HAS_HASH_SIZE_T + return hash()(reinterpret_cast(context)); +#else + std::size_t key = reinterpret_cast(context); + return std::size_t(key & (~0U)); +#endif + } +}; + +} + +#endif /* MITKMODULECONTEXT_H_ */ diff --git a/Core/Code/Service/mitkModuleEvent.cpp b/Core/Code/Service/mitkModuleEvent.cpp new file mode 100644 index 0000000000..3a85833eda --- /dev/null +++ b/Core/Code/Service/mitkModuleEvent.cpp @@ -0,0 +1,110 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkModuleEvent.h" + +#include "mitkModule.h" + +namespace mitk { + +class ModuleEventData : public SharedData +{ +public: + + ModuleEventData(ModuleEvent::Type type, Module* module) + : type(type), module(module) + { + + } + + ModuleEventData(const ModuleEventData& other) + : SharedData(other), type(other.type), module(other.module) + { + + } + + const ModuleEvent::Type type; + Module* const module; +}; + +ModuleEvent::ModuleEvent() + : d(0) +{ + +} + +ModuleEvent::~ModuleEvent() +{ + +} + +bool ModuleEvent::IsNull() const +{ + return !d; +} + +ModuleEvent::ModuleEvent(Type type, Module* module) + : d(new ModuleEventData(type, module)) +{ + +} + +ModuleEvent::ModuleEvent(const ModuleEvent& other) + : d(other.d) +{ + +} + +ModuleEvent& ModuleEvent::operator=(const ModuleEvent& other) +{ + d = other.d; + return *this; +} + +Module* ModuleEvent::GetModule() const +{ + return d->module; +} + +ModuleEvent::Type ModuleEvent::GetType() const +{ + return d->type; +} + +} + +std::ostream& operator<<(std::ostream& os, mitk::ModuleEvent::Type eventType) +{ + switch (eventType) + { + case mitk::ModuleEvent::LOADED: return os << "LOADED"; + case mitk::ModuleEvent::UNLOADED: return os << "UNLOADED"; + case mitk::ModuleEvent::LOADING: return os << "LOADING"; + case mitk::ModuleEvent::UNLOADING: return os << "UNLOADING"; + + default: return os << "Unknown module event type (" << static_cast(eventType) << ")"; + } +} + +std::ostream& operator<<(std::ostream& os, const mitk::ModuleEvent& event) +{ + if (event.IsNull()) return os << "NONE"; + + mitk::Module* m = event.GetModule(); + os << event.GetType() << " #" << m->GetModuleId() << " (" << m->GetLocation() << ")"; + return os; +} diff --git a/Core/Code/Service/mitkModuleEvent.h b/Core/Code/Service/mitkModuleEvent.h new file mode 100644 index 0000000000..9da048ce1b --- /dev/null +++ b/Core/Code/Service/mitkModuleEvent.h @@ -0,0 +1,147 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKMODULEEVENT_H +#define MITKMODULEEVENT_H + +#include "mitkSharedData.h" + +namespace mitk { + +class Module; +class ModuleEventData; + +/** + * \ingroup MicroServices + * + * An event from the Micro Services framework describing a module lifecycle change. + *

+ * ModuleEvent objects are delivered to listeners connected + * via ModuleContext::AddModuleListener() when a change + * occurs in a modules's lifecycle. A type code is used to identify + * the event type for future extendability. + * + * @see ModuleContext#connectModuleListener + */ +class MITK_CORE_EXPORT ModuleEvent +{ + + SharedDataPointer d; + +public: + + enum Type { + + /** + * The module has been loaded. + *

+ * The module's + * \link ModuleActivator::Load(ModuleContext*) ModuleActivator Load\endlink method + * has been executed. + */ + LOADED, + + /** + * The module has been unloaded. + *

+ * The module's + * \link ModuleActivator::Unload(ModuleContext*) ModuleActivator Unload\endlink method + * has been executed. + */ + UNLOADED, + + /** + * The module is about to be loaded. + *

+ * The module's + * \link ModuleActivator::Load(ModuleContext*) ModuleActivator Load\endlink method + * is about to be called. + */ + LOADING, + + /** + * The module is about to be unloaded. + *

+ * The module's + * \link ModuleActivator::Unload(ModuleContext*) ModuleActivator Unload\endlink method + * is about to be called. + */ + UNLOADING + + }; + + /** + * Creates an invalid instance. + */ + ModuleEvent(); + + ~ModuleEvent(); + + /** + * Can be used to check if this ModuleEvent instance is valid, + * or if it has been constructed using the default constructor. + * + * @return true if this event object is valid, + * false otherwise. + */ + bool IsNull() const; + + /** + * Creates a module event of the specified type. + * + * @param type The event type. + * @param module The module which had a lifecycle change. + */ + ModuleEvent(Type type, Module* module); + + ModuleEvent(const ModuleEvent& other); + + ModuleEvent& operator=(const ModuleEvent& other); + + /** + * Returns the module which had a lifecycle change. + * + * @return The module that had a change occur in its lifecycle. + */ + Module* GetModule() const; + + /** + * Returns the type of lifecyle event. The type values are: + *

    + *
  • {@link #LOADING} + *
  • {@link #LOADED} + *
  • {@link #UNLOADING} + *
  • {@link #UNLOADED} + *
+ * + * @return The type of lifecycle event. + */ + Type GetType() const; + +}; + +} + +/** + * \ingroup MicroServices + * @{ + */ +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, mitk::ModuleEvent::Type eventType); +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, const mitk::ModuleEvent& event); +/** @}*/ + +#endif // MITKMODULEEVENT_H diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Core/Code/Service/mitkModuleInfo.cpp similarity index 57% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Core/Code/Service/mitkModuleInfo.cpp index c09a6d26ee..cec6f79e8c 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Core/Code/Service/mitkModuleInfo.cpp @@ -1,33 +1,30 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +Date: $Date$ +Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#include "mitkModuleInfo.h" -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog -{ - Q_OBJECT +namespace mitk { - public: +ModuleInfo::ModuleInfo(const std::string& name, const std::string& libName, const std::string& moduleDeps, + const std::string& packageDeps, const std::string& version, bool qtModule) + : name(name), libName(libName), moduleDeps(moduleDeps), packageDeps(packageDeps), + version(version), qtModule(qtModule), id(0), + activatorHook(0) +{} - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); - -}; +} diff --git a/Core/Code/Service/mitkModuleInfo.h b/Core/Code/Service/mitkModuleInfo.h new file mode 100644 index 0000000000..0fccc21a7a --- /dev/null +++ b/Core/Code/Service/mitkModuleInfo.h @@ -0,0 +1,58 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKMODULEINFO_H +#define MITKMODULEINFO_H + +#include + +#include + +namespace mitk { + +struct ModuleActivator; + +/** + * This class is not intended to be used directly. It is exported to support + * the MITK module system. + */ +struct MITK_CORE_EXPORT ModuleInfo +{ + ModuleInfo(const std::string& name, const std::string& libName, const std::string& moduleDeps, + const std::string& packageDeps, const std::string& version, bool qtModule); + + typedef ModuleActivator*(*ModuleActivatorHook)(void); + + std::string name; + std::string libName; + std::string moduleDeps; + std::string packageDeps; + std::string version; + + std::string location; + + bool qtModule; + + long id; + + ModuleActivatorHook activatorHook; +}; + +} + +#endif // MITKMODULEINFO_H diff --git a/Core/Code/Service/mitkModulePrivate.cpp b/Core/Code/Service/mitkModulePrivate.cpp new file mode 100644 index 0000000000..edc5ccbd7b --- /dev/null +++ b/Core/Code/Service/mitkModulePrivate.cpp @@ -0,0 +1,143 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkModulePrivate.h" + +#include "mitkModule.h" +#include "mitkCoreModuleContext_p.h" +#include "mitkServiceRegistration.h" +#include "mitkServiceReferencePrivate.h" + +namespace mitk { + +AtomicInt ModulePrivate::idCounter; + +ModulePrivate::ModulePrivate(Module* qq, CoreModuleContext* coreCtx, + ModuleInfo* info) + : coreCtx(coreCtx), info(*info), moduleContext(0), moduleActivator(0), q(qq) +{ + + std::stringstream propId; + propId << this->info.id; + properties[Module::PROP_ID()] = propId.str(); + + std::stringstream propModuleDepends; + std::stringstream propLibDepends; + std::stringstream propPackageDepends; + + int counter = 0; + int counter2 = 0; + std::stringstream ss(this->info.moduleDeps); + while (ss) + { + std::string moduleDep; + ss >> moduleDep; + if (!moduleDep.empty()) + { + Module* dep = ModuleRegistry::GetModule(moduleDep); + if (dep) + { + requiresIds.push_back(dep->GetModuleId()); + if (counter > 0) propModuleDepends << ", "; + propModuleDepends << moduleDep; + ++counter; + } + else + { + requiresLibs.push_back(moduleDep); + if (counter2 > 0) propLibDepends << ", "; + propLibDepends << moduleDep; + ++counter2; + } + } + } + + properties[Module::PROP_MODULE_DEPENDS()] = propModuleDepends.str(); + properties[Module::PROP_LIB_DEPENDS()] = propLibDepends.str(); + + counter = 0; + ss.clear(); + ss.str(this->info.packageDeps); + while (ss) + { + std::string packageDep; + ss >> packageDep; + if (!packageDep.empty()) + { + requiresPackages.push_back(packageDep); + if (counter > 0) propPackageDepends << ", "; + propPackageDepends << packageDep; + ++counter; + } + } + + properties[Module::PROP_PACKAGE_DEPENDS()] = propPackageDepends.str(); + + if (!this->info.version.empty()) + { + try + { + version = mitk::ModuleVersion(this->info.version); + properties[Module::PROP_VERSION()] = this->info.version; + } + catch (const std::exception& e) + { + throw std::invalid_argument(std::string("MITK module does not specify a valid version identifier. Got exception: ") + e.what()); + } + } + + properties[Module::PROP_LOCATION()] = this->info.location; + properties[Module::PROP_NAME()] = this->info.name; + properties[Module::PROP_QT()] = this->info.qtModule ? "true" : "false"; +} + +ModulePrivate::~ModulePrivate() +{ +} + +void ModulePrivate::RemoveModuleResources() +{ + coreCtx->listeners.RemoveAllListeners(moduleContext); + + std::list srs; + coreCtx->services.GetRegisteredByModule(this, srs); + for (std::list::iterator i = srs.begin(); + i != srs.end(); ++i) + { + try + { + i->Unregister(); + } + catch (const std::logic_error& /*ignore*/) + { + // Someone has unregistered the service after stop completed. + // This should not occur, but we don't want get stuck in + // an illegal state so we catch it. + } + } + + srs.clear(); + coreCtx->services.GetUsedByModule(q, srs); + for (std::list::const_iterator i = srs.begin(); + i != srs.end(); ++i) + { + i->GetReference().d->UngetService(q, false); + } +} + +} + diff --git a/Core/Code/Service/mitkModulePrivate.h b/Core/Code/Service/mitkModulePrivate.h new file mode 100644 index 0000000000..5dc6fc35fe --- /dev/null +++ b/Core/Code/Service/mitkModulePrivate.h @@ -0,0 +1,82 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKMODULEPRIVATE_H +#define MITKMODULEPRIVATE_H + +#include "mitkModuleRegistry.h" +#include "mitkModuleVersion.h" +#include "mitkModuleInfo.h" + +#include "mitkAtomicInt.h" + +namespace mitk { + +class CoreModuleContext; +class ModuleContext; +struct ModuleActivator; + +/** + * \ingroup MicroServices + */ +class ModulePrivate { + +public: + + /** + * Construct a new module based on a ModuleInfo object. + */ + ModulePrivate(Module* qq, CoreModuleContext* coreCtx, ModuleInfo* info); + + virtual ~ModulePrivate(); + + void RemoveModuleResources(); + + CoreModuleContext* const coreCtx; + + std::vector requiresIds; + + std::vector requiresLibs; + std::vector requiresPackages; + + /** + * Module version + */ + ModuleVersion version; + + ModuleInfo info; + + /** + * ModuleContext for the module + */ + ModuleContext* moduleContext; + + ModuleActivator* moduleActivator; + + std::map properties; + + Module* const q; + +private: + + static AtomicInt idCounter; + +}; + +} + +#endif // MITKMODULEPRIVATE_H diff --git a/Core/Code/Service/mitkModuleRegistry.cpp b/Core/Code/Service/mitkModuleRegistry.cpp new file mode 100644 index 0000000000..6d00646ed2 --- /dev/null +++ b/Core/Code/Service/mitkModuleRegistry.cpp @@ -0,0 +1,179 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkModuleRegistry.h" + +#include "mitkModule.h" +#include "mitkModuleInfo.h" +#include "mitkModuleContext.h" +#include "mitkCoreModuleContext_p.h" +#include "mitkStaticInit.h" + +#include +#include + +namespace mitk { + +#ifdef MITK_HAS_UNORDERED_MAP_H +typedef std::unordered_map ModuleMap; +#else +typedef itk::hash_map ModuleMap; +#endif + +MITK_GLOBAL_STATIC(CoreModuleContext, coreModuleContext) + +/** + * Table of all installed modules in this framework. + * Key is the module location. + */ +MITK_GLOBAL_STATIC(ModuleMap, modules) + + +typedef itk::SimpleFastMutexLock MutexType; +typedef itk::MutexLockHolder MutexLocker; + +/** + * Lock for protecting the modules object + */ +MITK_GLOBAL_STATIC(MutexType, modulesLock) + +/** + * Lock for protecting the register count + */ +MITK_GLOBAL_STATIC(MutexType, countLock) + + +void ModuleRegistry::Register(ModuleInfo* info) +{ + static long regCount = 0; + if (info->id > 0) + { + // The module was already registered + MutexLocker lock(*modulesLock()); + Module* module = modules()->operator[](info->id); + module->Start(); + } + else + { + Module* module = 0; + // check if the module is reloaded + { + MutexLocker lock(*modulesLock()); + ModuleMap* map = modules(); + for (ModuleMap::const_iterator i = map->begin(); + i != map->end(); ++i) + { + if (i->second->GetLocation() == info->location) + { + module = i->second; + info->id = module->GetModuleId(); + } + } + } + + if (!module) + { + module = new Module(); + countLock()->Lock(); + info->id = ++regCount; + countLock()->Unlock(); + + module->Init(coreModuleContext(), info); + + MutexLocker lock(*modulesLock()); + ModuleMap* map = modules(); + map->insert(std::make_pair(info->id, module)); + } + else + { + module->Init(coreModuleContext(), info); + } + + module->Start(); + } +} + +void ModuleRegistry::UnRegister(const ModuleInfo* info) +{ + // If we are unregistering the mitkCore module, there is + // nothing to do. + if (info->id == 1) return; + + MutexLocker lock(*modulesLock()); + Module* curr = modules()->operator[](info->id); + curr->Stop(); + delete curr->GetModuleContext(); +} + +Module* ModuleRegistry::GetModule(long id) +{ + MutexLocker lock(*modulesLock()); + + ModuleMap::const_iterator iter = modules()->find(id); + if (iter != modules()->end()) + { + return iter->second; + } + return 0; +} + +Module* ModuleRegistry::GetModule(const std::string& name) +{ + MutexLocker lock(*modulesLock()); + + ModuleMap::const_iterator iter = modules()->begin(); + ModuleMap::const_iterator iterEnd = modules()->end(); + for (; iter != iterEnd; ++iter) + { + if (iter->second->GetName() == name) + { + return iter->second; + } + } + + return 0; +} + +void ModuleRegistry::GetModules(std::vector& m) +{ + MutexLocker lock(*modulesLock()); + + ModuleMap* map = modules(); + ModuleMap::const_iterator iter = map->begin(); + ModuleMap::const_iterator iterEnd = map->end(); + for (; iter != iterEnd; ++iter) + { + m.push_back(iter->second); + } +} + +void ModuleRegistry::GetLoadedModules(std::vector& m) +{ + MutexLocker lock(*modulesLock()); + + ModuleMap::const_iterator iter = modules()->begin(); + ModuleMap::const_iterator iterEnd = modules()->end(); + for (; iter != iterEnd; ++iter) + { + if (iter->second->IsLoaded()) + { + m.push_back(iter->second); + } + } +} + +} diff --git a/Core/Code/Service/mitkModuleRegistry.h b/Core/Code/Service/mitkModuleRegistry.h new file mode 100644 index 0000000000..0159036bb5 --- /dev/null +++ b/Core/Code/Service/mitkModuleRegistry.h @@ -0,0 +1,87 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKMODULEREGISTRY_H +#define MITKMODULEREGISTRY_H + +#include +#include + +#include + +namespace mitk { + +class Module; +class ModuleInfo; + +/** + * \ingroup MicroServices + * + * Here we handle all the modules that are loaded in the framework. + */ +class MITK_CORE_EXPORT ModuleRegistry { + +public: + + /** + * Get the module that has the specified module identifier. + * + * @param id The identifier of the module to get. + * @return Module or null + * if the module was not found. + */ + static Module* GetModule(long id); + + /** + * Get the module that has specified module name. + * + * @param name The name of the module to get. + * @return Module or null. + */ + static Module* GetModule(const std::string& name); + + /** + * Get all known modules. + * + * @return A Module list with modules. + */ + static void GetModules(std::vector& modules); + + /** + * Get all modules currently in module state LOADED. + * + * @return A List of Modules. + */ + static void GetLoadedModules(std::vector& modules); + +private: + + friend class ModuleInitializer; + + // disabled + ModuleRegistry(); + + static void Register(ModuleInfo* info); + + static void UnRegister(const ModuleInfo* info); + +}; + +} + + +#endif // MITKMODULEREGISTRY_H diff --git a/Core/Code/Service/mitkModuleUtils.cpp b/Core/Code/Service/mitkModuleUtils.cpp new file mode 100644 index 0000000000..4cd893e881 --- /dev/null +++ b/Core/Code/Service/mitkModuleUtils.cpp @@ -0,0 +1,154 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "mitkModuleUtils.h" + +namespace mitk { + +#ifdef __GNUC__ + +#define _GNU_SOURCE +#include + +std::string GetLibraryPath_impl(const std::string& /*libName*/, const void* symbol) +{ + Dl_info info; + if (dladdr(symbol, &info)) + { + return info.dli_fname; + } + return ""; +} + +void* GetSymbol_impl(const std::string& libName, const char* symbol) +{ + void* selfHandle = dlopen(libName.c_str(), RTLD_LAZY); + if (selfHandle) + { + void* addr = dlsym(selfHandle, symbol); + dlclose(selfHandle); + return addr; + } + return 0; +} + +#elif _WIN32 + +#include + +void PrintLastError_impl(const std::string& context) +{ + // Retrieve the system error message for the last-error code + LPVOID lpMsgBuf; + LPVOID lpDisplayBuf; + DWORD dw = GetLastError(); + + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + dw, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &lpMsgBuf, + 0, NULL ); + + // Display the error message and exit the process + + lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, + (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)context.c_str()) + 50) * sizeof(TCHAR)); + StringCchPrintf((LPTSTR)lpDisplayBuf, + LocalSize(lpDisplayBuf) / sizeof(TCHAR), + TEXT("Error in context %s (%d): %s"), + context.c_str(), dw, lpMsgBuf); + + std::string errMsg((LPCTSTR)lpDisplayBuf); + + LocalFree(lpMsgBuf); + LocalFree(lpDisplayBuf); + + MITK_DEBUG(true) << errMsg; +} + +std::string GetLibraryPath_impl(const std::string& libName, const void *symbol) +{ + HMODULE handle = 0; + if (libName.empty()) + { + // get the handle for the executable + handle = GetModuleHandle(0); + } + else + { + handle = GetModuleHandle(libName.c_str()); + } + if (!handle) + { + PrintLastError_impl("GetLibraryPath_impl():GetModuleHandle()"); + return ""; + } + + char modulePath[512]; + if (GetModuleFileName(handle, modulePath, 512)) + { + return modulePath; + } + + PrintLastError_impl("GetLibraryPath_impl():GetModuleFileName()"); + return ""; +} + +void* GetSymbol_impl(const std::string& libName, const char* symbol) +{ + HMODULE handle = GetModuleHandle(libName.c_str()); + if (!handle) + { + PrintLastError_impl("GetSymbol_impl():GetModuleHandle()"); + return 0; + } + + void* addr = (void*)GetProcAddress(handle, symbol); + if (!addr) + { + PrintLastError_impl(std::string("GetSymbol_impl():GetProcAddress(handle,") + std::string(symbol) + ")"); + } + return addr; +} +#else +std::string GetLibraryPath_impl(const std::string& libName, const void* symbol) +{ + return ""; +} + +void* GetSymbol_impl(const std::string& libName, const char* symbol) +{ + return 0; +} +#endif + +std::string ModuleUtils::GetLibraryPath(const std::string& libName, const void* symbol) +{ + return GetLibraryPath_impl(libName, symbol); +} + +void* ModuleUtils::GetSymbol(const std::string& libName, const char* symbol) +{ + return GetSymbol_impl(libName, symbol); +} + +} diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Core/Code/Service/mitkModuleUtils.h similarity index 55% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Core/Code/Service/mitkModuleUtils.h index c09a6d26ee..9e54679790 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Core/Code/Service/mitkModuleUtils.h @@ -1,33 +1,41 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +Date: $Date$ +Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#ifndef MITKMODULEUTILS_H +#define MITKMODULEUTILS_H -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog -{ - Q_OBJECT +#include + +#include - public: +namespace mitk { - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); +/** + * This class is not intended to be used directly. It is exported to support + * the MITK module system. + */ +struct MITK_CORE_EXPORT ModuleUtils +{ + static std::string GetLibraryPath(const std::string& libName, const void* symbol); + static void* GetSymbol(const std::string& libName, const char* symbol); }; + +} + +#endif // MITKMODULEUTILS_H diff --git a/Core/Code/Service/mitkModuleVersion.cpp b/Core/Code/Service/mitkModuleVersion.cpp new file mode 100644 index 0000000000..4bf6a2fe00 --- /dev/null +++ b/Core/Code/Service/mitkModuleVersion.cpp @@ -0,0 +1,270 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkModuleVersion.h" + +#include +#include +#include +#include +#include + +namespace mitk { + +const char ModuleVersion::SEPARATOR = '.'; + +bool IsInvalidQualifier(char c) +{ + return !(std::isalnum(c) || c == '_' || c == '-'); +} + +ModuleVersion ModuleVersion::EmptyVersion() +{ + static ModuleVersion emptyV(false); + return emptyV; +} + +ModuleVersion ModuleVersion::UndefinedVersion() +{ + static ModuleVersion undefinedV(true); + return undefinedV; +} + +ModuleVersion& ModuleVersion::operator=(const ModuleVersion& v) +{ + majorVersion = v.majorVersion; + minorVersion = v.minorVersion; + microVersion = v.microVersion; + qualifier = v.qualifier; + undefined = v.undefined; + return *this; +} + +ModuleVersion::ModuleVersion(bool undefined) + : majorVersion(0), minorVersion(0), microVersion(0), qualifier(""), undefined(undefined) +{ + +} + +void ModuleVersion::Validate() +{ + if (std::find_if(qualifier.begin(), qualifier.end(), IsInvalidQualifier) != qualifier.end()) + throw std::invalid_argument(std::string("invalid qualifier: ") + qualifier); + + undefined = false; +} + +ModuleVersion::ModuleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion) + : majorVersion(majorVersion), minorVersion(minorVersion), microVersion(microVersion), qualifier(""), + undefined(false) +{ + +} + +ModuleVersion::ModuleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion, const std::string& qualifier) + : majorVersion(majorVersion), minorVersion(minorVersion), microVersion(microVersion), qualifier(qualifier), + undefined(true) +{ + this->Validate(); +} + +ModuleVersion::ModuleVersion(const std::string& version) + : majorVersion(0), minorVersion(0), microVersion(0), undefined(true) +{ + unsigned int maj = 0; + unsigned int min = 0; + unsigned int mic = 0; + std::string qual(""); + + std::vector st; + std::stringstream ss(version); + std::string token; + while(std::getline(ss, token, SEPARATOR)) + { + st.push_back(token); + } + + if (st.empty()) return; + + bool ok = true; + ss.clear(); + ss.str(st[0]); + ss >> maj; + ok = !ss.fail(); + + if (st.size() > 1) + { + ss.clear(); + ss.str(st[1]); + ss >> min; + ok = !ss.fail(); + if (st.size() > 2) + { + ss.clear(); + ss.str(st[2]); + ss >> mic; + ok = !ss.fail(); + if (st.size() > 3) + { + qual = st[3]; + if (st.size() > 4) + { + ok = false; + } + } + } + } + + if (!ok) throw std::invalid_argument("invalid format"); + + majorVersion = maj; + minorVersion = min; + microVersion = mic; + qualifier = qual; + this->Validate(); +} + +ModuleVersion::ModuleVersion(const ModuleVersion& version) +: majorVersion(version.majorVersion), minorVersion(version.minorVersion), + microVersion(version.microVersion), qualifier(version.qualifier), + undefined(version.undefined) +{ + +} + +ModuleVersion ModuleVersion::ParseVersion(const std::string& version) +{ + if (version.empty()) + { + return EmptyVersion(); + } + + std::string version2(version); + version2.erase(0, version2.find_first_not_of(' ')); + version2.erase(version2.find_last_not_of(' ')+1); + if (version2.empty()) + { + return EmptyVersion(); + } + + return ModuleVersion(version2); +} + +bool ModuleVersion::IsUndefined() const +{ + return undefined; +} + +unsigned int ModuleVersion::GetMajor() const +{ + if (undefined) throw std::logic_error("Version undefined"); + return majorVersion; +} + +unsigned int ModuleVersion::GetMinor() const +{ + if (undefined) throw std::logic_error("Version undefined"); + return minorVersion; +} + +unsigned int ModuleVersion::GetMicro() const +{ + if (undefined) throw std::logic_error("Version undefined"); + return microVersion; +} + +std::string ModuleVersion::GetQualifier() const +{ + if (undefined) throw std::logic_error("Version undefined"); + return qualifier; +} + +std::string ModuleVersion::ToString() const +{ + if (undefined) return "undefined"; + + std::string result; + std::stringstream ss(result); + ss << majorVersion << SEPARATOR << minorVersion << SEPARATOR << microVersion; + if (!qualifier.empty()) + { + ss << SEPARATOR << qualifier; + } + return result; +} + +bool ModuleVersion::operator==(const ModuleVersion& other) const +{ + if (&other == this) + { // quicktest + return true; + } + + if (other.undefined && this->undefined) return true; + if (this->undefined) throw std::logic_error("Version undefined"); + if (other.undefined) return false; + + return (majorVersion == other.majorVersion) && (minorVersion == other.minorVersion) && (microVersion + == other.microVersion) && qualifier == other.qualifier; +} + +int ModuleVersion::Compare(const ModuleVersion& other) const +{ + if (&other == this) + { // quicktest + return 0; + } + + if (this->undefined || other.undefined) + throw std::logic_error("Cannot compare undefined version"); + + if (majorVersion < other.majorVersion) + { + return -1; + } + + if (majorVersion == other.majorVersion) + { + + if (minorVersion < other.minorVersion) + { + return -1; + } + + if (minorVersion == other.minorVersion) + { + + if (microVersion < other.microVersion) + { + return -1; + } + + if (microVersion == other.microVersion) + { + return qualifier.compare(other.qualifier); + } + } + } + return 1; +} + +} + +std::ostream& operator<<(std::ostream& os, const mitk::ModuleVersion& v) +{ + return os << v.ToString(); +} diff --git a/Core/Code/Service/mitkModuleVersion.h b/Core/Code/Service/mitkModuleVersion.h new file mode 100644 index 0000000000..9594597cb4 --- /dev/null +++ b/Core/Code/Service/mitkModuleVersion.h @@ -0,0 +1,250 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKMODULEVERSION_H +#define MITKMODULEVERSION_H + +#include + +#include + +namespace mitk { + +/** + * \ingroup MicroServices + * + * Version identifier for MITK modules. + * + *

+ * Version identifiers have four components. + *

    + *
  1. Major version. A non-negative integer.
  2. + *
  3. Minor version. A non-negative integer.
  4. + *
  5. Micro version. A non-negative integer.
  6. + *
  7. Qualifier. A text string. See ModuleVersion(const std::string&) for the + * format of the qualifier string.
  8. + *
+ * + *

+ * ModuleVersion objects are immutable. + */ +class MITK_CORE_EXPORT ModuleVersion { + +private: + + friend class ModulePrivate; + + unsigned int majorVersion; + unsigned int minorVersion; + unsigned int microVersion; + std::string qualifier; + + static const char SEPARATOR; // = "." + + bool undefined; + + + /** + * Called by the ModuleVersion constructors to validate the version components. + * + * @return true if the validation was successfull, false otherwise. + */ + void Validate(); + + ModuleVersion& operator=(const ModuleVersion& v); + + explicit ModuleVersion(bool undefined = false); + +public: + + /** + * The empty version "0.0.0". + */ + static ModuleVersion EmptyVersion(); + + /** + * Creates an undefined version identifier, representing either + * infinity or minus infinity. + */ + static ModuleVersion UndefinedVersion(); + + /** + * Creates a version identifier from the specified numerical components. + * + *

+ * The qualifier is set to the empty string. + * + * @param majorVersion Major component of the version identifier. + * @param minorVersion Minor component of the version identifier. + * @param microVersion Micro component of the version identifier. + * + */ + ModuleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion); + + /** + * Creates a version identifier from the specified components. + * + * @param majorVersion Major component of the version identifier. + * @param minorVersion Minor component of the version identifier. + * @param microVersion Micro component of the version identifier. + * @param qualifier Qualifier component of the version identifier. + */ + ModuleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion, const std::string& qualifier); + + /** + * Created a version identifier from the specified string. + * + *

+ * Here is the grammar for version strings. + * + *

+   * version ::= majorVersion('.'minorVersion('.'microVersion('.'qualifier)?)?)?
+   * majorVersion ::= digit+
+   * minorVersion ::= digit+
+   * microVersion ::= digit+
+   * qualifier ::= (alpha|digit|'_'|'-')+
+   * digit ::= [0..9]
+   * alpha ::= [a..zA..Z]
+   * 
+ * + * There must be no whitespace in version. + * + * @param version string representation of the version identifier. + */ + ModuleVersion(const std::string& version); + + /** + * Create a version identifier from another. + * + * @param version Another version identifier + */ + ModuleVersion(const ModuleVersion& version); + + + /** + * Parses a version identifier from the specified string. + * + *

+ * See ModuleVersion(const std::string&) for the format of the version string. + * + * @param version string representation of the version identifier. Leading + * and trailing whitespace will be ignored. + * @return A ModuleVersion object representing the version + * identifier. If version is the empty string + * then EmptyVersion will be + * returned. + */ + static ModuleVersion ParseVersion(const std::string& version); + + /** + * Returns the undefined state of this version identifier. + * + * @return true if this version identifier is undefined, + * false otherwise. + */ + bool IsUndefined() const; + + /** + * Returns the majorVersion component of this version identifier. + * + * @return The majorVersion component. + */ + unsigned int GetMajor() const; + + /** + * Returns the minorVersion component of this version identifier. + * + * @return The minorVersion component. + */ + unsigned int GetMinor() const; + + /** + * Returns the microVersion component of this version identifier. + * + * @return The microVersion component. + */ + unsigned int GetMicro() const; + + /** + * Returns the qualifier component of this version identifier. + * + * @return The qualifier component. + */ + std::string GetQualifier() const; + + /** + * Returns the string representation of this version identifier. + * + *

+ * The format of the version string will be majorVersion.minorVersion.microVersion + * if qualifier is the empty string or + * majorVersion.minorVersion.microVersion.qualifier otherwise. + * + * @return The string representation of this version identifier. + */ + std::string ToString() const; + + /** + * Compares this ModuleVersion object to another object. + * + *

+ * A version is considered to be equal to another version if the + * majorVersion, minorVersion and microVersion components are equal and the qualifier component + * is equal. + * + * @param object The ModuleVersion object to be compared. + * @return true if object is a + * ModuleVersion and is equal to this object; + * false otherwise. + */ + bool operator==(const ModuleVersion& object) const; + + /** + * Compares this ModuleVersion object to another object. + * + *

+ * A version is considered to be less than another version if its + * majorVersion component is less than the other version's majorVersion component, or the + * majorVersion components are equal and its minorVersion component is less than the other + * version's minorVersion component, or the majorVersion and minorVersion components are equal + * and its microVersion component is less than the other version's microVersion component, + * or the majorVersion, minorVersion and microVersion components are equal and it's qualifier + * component is less than the other version's qualifier component (using + * std::string::operator<()). + * + *

+ * A version is considered to be equal to another version if the + * majorVersion, minorVersion and microVersion components are equal and the qualifier component + * is equal. + * + * @param object The ModuleVersion object to be compared. + * @return A negative integer, zero, or a positive integer if this object is + * less than, equal to, or greater than the specified + * ModuleVersion object. + */ + int Compare(const ModuleVersion& object) const; + +}; + +} + +/** + * \ingroup MicroServices + */ +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, const mitk::ModuleVersion& v); + +#endif // MITKMODULEVERSION_H diff --git a/Core/Code/Service/mitkServiceEvent.cpp b/Core/Code/Service/mitkServiceEvent.cpp new file mode 100644 index 0000000000..62dd2269c8 --- /dev/null +++ b/Core/Code/Service/mitkServiceEvent.cpp @@ -0,0 +1,121 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkServiceEvent.h" + +#include "mitkServiceProperties.h" + +namespace mitk { + +class ServiceEventData : public SharedData +{ +public: + + ServiceEventData(const ServiceEvent::Type& type, const ServiceReference& reference) + : type(type), reference(reference) + { + + } + + ServiceEventData(const ServiceEventData& other) + : SharedData(other), type(other.type), reference(other.reference) + { + + } + + const ServiceEvent::Type type; + const ServiceReference reference; +}; + +ServiceEvent::ServiceEvent() + : d(0) +{ + +} + +ServiceEvent::~ServiceEvent() +{ + +} + +bool ServiceEvent::IsNull() const +{ + return !d; +} + +ServiceEvent::ServiceEvent(Type type, const ServiceReference& reference) + : d(new ServiceEventData(type, reference)) +{ + +} + +ServiceEvent::ServiceEvent(const ServiceEvent& other) + : d(other.d) +{ + +} + +ServiceEvent& ServiceEvent::operator=(const ServiceEvent& other) +{ + d = other.d; + return *this; +} + +ServiceReference ServiceEvent::GetServiceReference() const +{ + return d->reference; +} + +ServiceEvent::Type ServiceEvent::GetType() const +{ + return d->type; +} + +} + +std::ostream& operator<<(std::ostream& os, const mitk::ServiceEvent::Type& type) +{ + switch(type) + { + case mitk::ServiceEvent::MODIFIED: return os << "MODIFIED"; + case mitk::ServiceEvent::MODIFIED_ENDMATCH: return os << "MODIFIED_ENDMATCH"; + case mitk::ServiceEvent::REGISTERED: return os << "REGISTERED"; + case mitk::ServiceEvent::UNREGISTERING: return os << "UNREGISTERING"; + + default: return os << "unknown service event type (" << static_cast(type) << ")"; + } +} + +std::ostream& operator<<(std::ostream& os, const mitk::ServiceEvent& event) +{ + if (event.IsNull()) return os << "NONE"; + + os << event.GetType(); + + mitk::ServiceReference sr = event.GetServiceReference(); + if (sr) + { + // Some events will not have a service reference + long int sid = mitk::any_cast(sr.GetProperty(mitk::ServiceConstants::SERVICE_ID())); + os << " " << sid; + + mitk::Any classes = sr.GetProperty(mitk::ServiceConstants::OBJECTCLASS()); + os << " objectClass=" << classes << ")"; + } + + return os; +} diff --git a/Core/Code/Service/mitkServiceEvent.h b/Core/Code/Service/mitkServiceEvent.h new file mode 100644 index 0000000000..620c79cef1 --- /dev/null +++ b/Core/Code/Service/mitkServiceEvent.h @@ -0,0 +1,166 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKSERVICEEVENT_H +#define MITKSERVICEEVENT_H + +#include "mitkSharedData.h" + +#include "mitkServiceReference.h" + +namespace mitk { + +class ServiceEventData; + +/** + * \ingroup MicroServices + * + * An event from the Micro Services framework describing a service lifecycle change. + *

+ * ServiceEvent objects are delivered to + * listeners connected via ModuleContext::AddServiceListener() when a + * change occurs in this service's lifecycle. A type code is used to identify + * the event type for future extendability. + */ +class MITK_CORE_EXPORT ServiceEvent +{ + + SharedDataPointer d; + +public: + + enum Type { + + /** + * This service has been registered. + *

+ * This event is delivered after the service + * has been registered with the framework. + * + * @see ModuleContext#RegisterService() + */ + REGISTERED = 0x00000001, + + /** + * The properties of a registered service have been modified. + *

+ * This event is delivered after the service + * properties have been modified. + * + * @see ServiceRegistration#SetProperties + */ + MODIFIED = 0x00000002, + + /** + * This service is in the process of being unregistered. + *

+ * This event is delivered before the service + * has completed unregistering. + * + *

+ * If a module is using a service that is UNREGISTERING, the + * module should release its use of the service when it receives this event. + * If the module does not release its use of the service when it receives + * this event, the framework will automatically release the module's use of + * the service while completing the service unregistration operation. + * + * @see ServiceRegistration#Unregister + * @see ModuleContext#UngetService + */ + UNREGISTERING = 0x00000004, + + /** + * The properties of a registered service have been modified and the new + * properties no longer match the listener's filter. + *

+ * This event is delivered after the service + * properties have been modified. This event is only delivered to listeners + * which were added with a non-empty filter where the filter + * matched the service properties prior to the modification but the filter + * does not match the modified service properties. + * + * @see ServiceRegistration#SetProperties + */ + MODIFIED_ENDMATCH = 0x00000008 + + }; + + /** + * Creates an invalid instance. + */ + ServiceEvent(); + + ~ServiceEvent(); + + /** + * Can be used to check if this ServiceEvent instance is valid, + * or if it has been constructed using the default constructor. + * + * @return true if this event object is valid, + * false otherwise. + */ + bool IsNull() const; + + /** + * Creates a new service event object. + * + * @param type The event type. + * @param reference A ServiceReference object to the service + * that had a lifecycle change. + */ + ServiceEvent(Type type, const ServiceReference& reference); + + ServiceEvent(const ServiceEvent& other); + + ServiceEvent& operator=(const ServiceEvent& other); + + /** + * Returns a reference to the service that had a change occur in its + * lifecycle. + *

+ * This reference is the source of the event. + * + * @return Reference to the service that had a lifecycle change. + */ + ServiceReference GetServiceReference() const; + + /** + * Returns the type of event. The event type values are: + *

    + *
  • {@link #REGISTERED}
  • + *
  • {@link #MODIFIED}
  • + *
  • {@link #MODIFIED_ENDMATCH}
  • + *
  • {@link #UNREGISTERING}
  • + *
+ * + * @return Type of service lifecycle change. + */ + Type GetType() const; + +}; + +} + +/** + * \ingroup MicroServices + * @{ + */ +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, const mitk::ServiceEvent::Type& type); +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, const mitk::ServiceEvent& event); +/** @}*/ + +#endif // MITKSERVICEEVENT_H diff --git a/Core/Code/Service/mitkServiceException.cpp b/Core/Code/Service/mitkServiceException.cpp new file mode 100644 index 0000000000..7d2b86f75c --- /dev/null +++ b/Core/Code/Service/mitkServiceException.cpp @@ -0,0 +1,54 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkServiceException.h" + +#include + +namespace mitk +{ + +ServiceException::ServiceException(const std::string& msg, const Type& type) + : std::runtime_error(msg), type(type) +{ + +} + +ServiceException::ServiceException(const ServiceException& o) + : std::runtime_error(o), type(o.type) +{ + +} + +ServiceException& ServiceException::operator=(const ServiceException& o) +{ + std::runtime_error::operator=(o); + this->type = o.type; + return *this; +} + +ServiceException::Type ServiceException::GetType() const +{ + return type; +} + +} + +std::ostream& operator<<(std::ostream& os, const mitk::ServiceException& exc) +{ + return os << "mitk::ServiceException: " << exc.what(); +} diff --git a/Core/Code/Service/mitkServiceException.h b/Core/Code/Service/mitkServiceException.h new file mode 100644 index 0000000000..2afb2090d3 --- /dev/null +++ b/Core/Code/Service/mitkServiceException.h @@ -0,0 +1,114 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICEEXCEPTION_H +#define MITKSERVICEEXCEPTION_H + +#include + +#include + +namespace mitk { + +/** + * \ingroup MicroServices + * + * A service exception used to indicate that a service problem occurred. + * + *

+ * A ServiceException object is created by the framework or + * to denote an exception condition in the service. An enum + * type is used to identify the exception type for future extendability. + * + *

+ * This exception conforms to the general purpose exception chaining mechanism. + */ +class MITK_CORE_EXPORT ServiceException : public std::runtime_error +{ +public: + + enum Type { + /** + * No exception type is unspecified. + */ + UNSPECIFIED = 0, + /** + * The service has been unregistered. + */ + UNREGISTERED = 1, + /** + * The service factory produced an invalid service object. + */ + FACTORY_ERROR = 2, + /** + * The service factory threw an exception. + */ + FACTORY_EXCEPTION = 3, + /** + * An error occurred invoking a remote service. + */ + REMOTE = 5, + /** + * The service factory resulted in a recursive call to itself for the + * requesting module. + */ + FACTORY_RECURSION = 6 + }; + + /** + * Creates a ServiceException with the specified message, + * type and exception cause. + * + * @param msg The associated message. + * @param type The type for this exception. + * @param cause The cause of this exception. + */ + ServiceException(const std::string& msg, const Type& type = UNSPECIFIED); + + ServiceException(const ServiceException& o); + ServiceException& operator=(const ServiceException& o); + + ~ServiceException() throw() { } + + /** + * Returns the type for this exception or UNSPECIFIED if the + * type was unspecified or unknown. + * + * @return The type of this exception. + */ + Type GetType() const; + +private: + + /** + * Type of service exception. + */ + Type type; + +}; + +} + +/** + * \ingroup MicroServices + * @{ + */ +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, const mitk::ServiceException& exc); +/** @}*/ + +#endif // MITKSERVICEEXCEPTION_H diff --git a/Core/Code/Service/mitkServiceFactory.h b/Core/Code/Service/mitkServiceFactory.h new file mode 100644 index 0000000000..afb0a895cb --- /dev/null +++ b/Core/Code/Service/mitkServiceFactory.h @@ -0,0 +1,106 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "mitkServiceRegistration.h" + +namespace mitk { + +/** + * \ingroup MicroServices + * + * Allows services to provide customized service objects in the module + * environment. + * + *

+ * When registering a service, a ServiceFactory object can be + * used instead of a service object, so that the module developer can gain + * control of the specific service object granted to a module that is using the + * service. + * + *

+ * When this happens, the + * ModuleContext::GetService(const ServiceReference&) method calls the + * ServiceFactory::GetService method to create a service object + * specifically for the requesting module. The service object returned by the + * ServiceFactory is cached by the framework until the module + * releases its use of the service. + * + *

+ * When the module's use count for the service equals zero (including the module + * unloading or the service being unregistered), the + * ServiceFactory::UngetService method is called. + * + *

+ * ServiceFactory objects are only used by the framework and are + * not made available to other modules in the module environment. The framework + * may concurrently call a ServiceFactory. + * + * @see ModuleContext#GetService + * @remarks This class is thread safe. + */ +class ServiceFactory +{ + +public: + + /** + * Creates a new service object. + * + *

+ * The Framework invokes this method the first time the specified + * module requests a service object using the + * ModuleContext::GetService(const ServiceReference&) method. The + * service factory can then return a specific service object for each + * module. + * + *

+ * The framework caches the value returned (unless it is 0), + * and will return the same service object on any future call to + * ModuleContext::GetService for the same modules. This means the + * framework must not allow this method to be concurrently called for the + * same module. + * + * @param module The module using the service. + * @param registration The ServiceRegistration object for the + * service. + * @return A service object that must be an instance of all + * the classes named when the service was registered. + * @see ModuleContext#GetService + */ + virtual itk::LightObject* GetService(Module* module, const ServiceRegistration& registration) = 0; + + /** + * Releases a service object. + * + *

+ * The framework invokes this method when a service has been released by a + * module. The service object may then be destroyed. + * + * @param module The Module releasing the service. + * @param registration The ServiceRegistration object for the + * service. + * @param service The service object returned by a previous call to the + * ServiceFactory::getService method. + * @see ModuleContext#UngetService + */ + virtual void UngetService(Module* module, const ServiceRegistration& registration, + itk::LightObject* service) = 0; +}; + +} + diff --git a/Core/Code/Service/mitkServiceInterface.h b/Core/Code/Service/mitkServiceInterface.h new file mode 100644 index 0000000000..725c61495e --- /dev/null +++ b/Core/Code/Service/mitkServiceInterface.h @@ -0,0 +1,50 @@ +/*============================================================================= + + Library: CTK + + Copyright (c) German Cancer Research Center, + Division of Medical and Biological Informatics + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=============================================================================*/ + + +#ifndef MITKSERVICEINTERFACE_H +#define MITKSERVICEINTERFACE_H + +template inline const char* mitk_service_interface_iid() +{ return 0; } + +#if defined(QT_DEBUG) || defined(QT_NODEBUG) +#include + +#define MITK_DECLARE_SERVICE_INTERFACE(IFace, IId) \ + template <> inline const char* qobject_interface_iid() \ + { return IId; } \ + template <> inline const char* mitk_service_interface_iid() \ + { return IId; } \ + template <> inline IFace *qobject_cast(QObject *object) \ + { return reinterpret_cast((object ? object->qt_metacast(IId) : 0)); } \ + template <> inline IFace *qobject_cast(const QObject *object) \ + { return reinterpret_cast((object ? const_cast(object)->qt_metacast(IId) : 0)); } + +#else + +#define MITK_DECLARE_SERVICE_INTERFACE(IFace, IId) \ + template <> inline const char* mitk_service_interface_iid() \ + { return IId; } \ + +#endif + +#endif // MITKSERVICEINTERFACE_H diff --git a/Core/Code/Service/mitkServiceListenerEntry.cpp b/Core/Code/Service/mitkServiceListenerEntry.cpp new file mode 100644 index 0000000000..0b3bc26c7c --- /dev/null +++ b/Core/Code/Service/mitkServiceListenerEntry.cpp @@ -0,0 +1,137 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "mitkServiceListenerEntry_p.h" + +namespace mitk { + +class ServiceListenerEntryData : public SharedData +{ +public: + + ServiceListenerEntryData(Module* mc, const ServiceListenerDelegate& l, const std::string& filter) + : mc(mc), listener(l.Clone()), bRemoved(false), ldap() + { + if (!filter.empty()) + { + ldap = LDAPExpr(filter); + } + } + + ~ServiceListenerEntryData() + { + delete listener; + } + + Module* const mc; + const ServiceListenerDelegate* const listener; + bool bRemoved; + LDAPExpr ldap; + + /** + * The elements of "simple" filters are cached, for easy lookup. + * + * The grammar for simple filters is as follows: + * + *

+   * Simple = '(' attr '=' value ')'
+   *        | '(' '|' Simple+ ')'
+   * 
+ * where attr is one of {@link Constants#OBJECTCLASS}, + * {@link Constants#SERVICE_ID} or {@link Constants#SERVICE_PID}, and + * value must not contain a wildcard character. + *

+ * The index of the vector determines which key the cache is for + * (see {@link ServiceListenerState#hashedKeys}). For each key, there is + * a vector pointing out the values which are accepted by this + * ServiceListenerEntry's filter. This cache is maintained to make + * it easy to remove this service listener. + */ + LDAPExpr::LocalCache local_cache; +}; + +ServiceListenerEntry::ServiceListenerEntry(const ServiceListenerEntry& other) + : d(other.d) +{ + +} + +ServiceListenerEntry::~ServiceListenerEntry() +{ + +} + +ServiceListenerEntry& ServiceListenerEntry::operator=(const ServiceListenerEntry& other) +{ + d = other.d; + return *this; +} + +bool ServiceListenerEntry::operator==(const ServiceListenerEntry& other) const +{ + return ((d->mc == 0 || other.d->mc == 0) || d->mc == other.d->mc) && + (d->listener->operator ==(other.d->listener)); +} + +bool ServiceListenerEntry::operator<(const ServiceListenerEntry& other) const +{ + return d->mc < other.d->mc; +} + +void ServiceListenerEntry::SetRemoved(bool removed) const +{ + d->bRemoved = removed; +} + +bool ServiceListenerEntry::IsRemoved() const +{ + return d->bRemoved; +} + +ServiceListenerEntry::ServiceListenerEntry(Module* mc, const ServiceListenerDelegate& l, const std::string& filter) + : d(new ServiceListenerEntryData(mc, l, filter)) +{ + +} + +Module* ServiceListenerEntry::GetModule() const +{ + return d->mc; +} + +std::string ServiceListenerEntry::GetFilter() const +{ + return d->ldap.IsNull() ? std::string() : d->ldap.ToString(); +} + +LDAPExpr ServiceListenerEntry::GetLDAPExpr() const +{ + return d->ldap; +} + +LDAPExpr::LocalCache& ServiceListenerEntry::GetLocalCache() const +{ + return d->local_cache; +} + +void ServiceListenerEntry::CallDelegate(const ServiceEvent& event) const +{ + d->listener->Execute(event); +} + +} diff --git a/Core/Code/Service/mitkServiceListenerEntry_p.h b/Core/Code/Service/mitkServiceListenerEntry_p.h new file mode 100644 index 0000000000..0ac8790317 --- /dev/null +++ b/Core/Code/Service/mitkServiceListenerEntry_p.h @@ -0,0 +1,111 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICELISTENERENTRY_H +#define MITKSERVICELISTENERENTRY_H + +#include "mitkLDAPExpr_p.h" + +#include "mitkModuleContext.h" + +namespace mitk { + +class Module; +class ServiceListenerEntryData; + +/** + * Data structure for saving service listener info. Contains + * the optional service listener filter, in addition to the info + * in ListenerEntry. + */ +class ServiceListenerEntry +{ + +public: + + ServiceListenerEntry(const ServiceListenerEntry& other); + ~ServiceListenerEntry(); + ServiceListenerEntry& operator=(const ServiceListenerEntry& other); + + bool operator==(const ServiceListenerEntry& other) const; + + bool operator<(const ServiceListenerEntry& other) const; + + void SetRemoved(bool removed) const; + bool IsRemoved() const; + + ServiceListenerEntry(Module* mc, const ServiceListenerDelegate& l, const std::string& filter = ""); + + Module* GetModule() const; + + std::string GetFilter() const; + + LDAPExpr GetLDAPExpr() const; + + LDAPExpr::LocalCache& GetLocalCache() const; + + void CallDelegate(const ServiceEvent& event) const; + +private: + +#ifdef MITK_HAS_UNORDERED_MAP_H + friend class std::hash; +#elif defined(__GNUC__) + friend class __gnu_cxx::hash; +#else + friend struct itk::hash; +#endif + + ExplicitlySharedDataPointer d; +}; + +} + +#ifdef MITK_HAS_UNORDERED_MAP_H +namespace std { +#elif defined(__GNUC__) +namespace __gnu_cxx { +#else +namespace itk { +#endif + +template<> +class hash : public std::unary_function +{ +public: + size_t operator()(const mitk::ServiceListenerEntry& sle) const + { +#ifdef MITK_HAS_HASH_SIZE_T + return hash()(reinterpret_cast(sle.d.ConstData())); +#else + unsigned long long key = reinterpret_cast(sle.d.ConstData()); + if (sizeof(unsigned long long) > sizeof(std::size_t)) + { + return std::size_t(((key >> (8 * sizeof(std::size_t) - 1)) ^ key) & (~0U)); + } + else + { + return std::size_t(key & (~0U)); + } +#endif + } +}; + +} + +#endif // MITKSERVICELISTENERENTRY_H diff --git a/Core/Code/Service/mitkServiceListeners.cpp b/Core/Code/Service/mitkServiceListeners.cpp new file mode 100644 index 0000000000..0aa6c24523 --- /dev/null +++ b/Core/Code/Service/mitkServiceListeners.cpp @@ -0,0 +1,268 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "mitkServiceListeners_p.h" +#include "mitkServiceReferencePrivate.h" + +#include "mitkModule.h" + +namespace mitk { + +const int ServiceListeners::OBJECTCLASS_IX = 0; +const int ServiceListeners::SERVICE_ID_IX = 1; + +ServiceListeners::ServiceListeners() +{ + hashedServiceKeys.push_back(ServiceConstants::OBJECTCLASS()); + hashedServiceKeys.push_back(ServiceConstants::SERVICE_ID()); +} + +void ServiceListeners::AddServiceListener(ModuleContext* mc, const ServiceListenerDelegate& listener, + const std::string& filter) +{ + MutexLocker lock(mutex); + ServiceListenerEntry sle(mc->GetModule(), listener, filter); + if (serviceSet.find(sle) != serviceSet.end()) + { + RemoveServiceListener_unlocked(sle); + } + serviceSet.insert(sle); + CheckSimple(sle); +} + +void ServiceListeners::RemoveServiceListener(ModuleContext* mc, const ServiceListenerDelegate& listener) +{ + ServiceListenerEntry entryToRemove(mc->GetModule(), listener); + + MutexLocker lock(mutex); + RemoveServiceListener_unlocked(entryToRemove); +} + +void ServiceListeners::RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove) +{ + for (ServiceListenerEntries::iterator it = serviceSet.begin(); + it != serviceSet.end(); ++it) + { + if (it->operator ==(entryToRemove)) + { + it->SetRemoved(true); + RemoveFromCache(*it); + serviceSet.erase(it); + break; + } + } +} + +void ServiceListeners::AddModuleListener(ModuleContext* mc, const ModuleListenerDelegate& listener) +{ + MutexLocker lock(moduleListenerMapMutex); + moduleListenerMap[mc] += listener; +} + +void ServiceListeners::RemoveModuleListener(ModuleContext* mc, const ModuleListenerDelegate& listener) +{ + MutexLocker lock(moduleListenerMapMutex); + moduleListenerMap[mc] -= listener; +} + +void ServiceListeners::RemoveAllListeners(ModuleContext* mc) +{ + { + MutexLocker lock(mutex); + for (ServiceListenerEntries::iterator it = serviceSet.begin(); + it != serviceSet.end(); ) + { + if (it->GetModule() == mc->GetModule()) + { + RemoveFromCache(*it); + serviceSet.erase(it++); + } + else + { + ++it; + } + } + } + + { + MutexLocker lock(moduleListenerMapMutex); + moduleListenerMap.erase(mc); + } +} + +void ServiceListeners::ServiceChanged(const ServiceListenerEntries& receivers, + const ServiceEvent& evt) +{ + ServiceListenerEntries matchBefore; + ServiceChanged(receivers, evt, matchBefore); +} + +void ServiceListeners::ServiceChanged(const ServiceListenerEntries& receivers, + const ServiceEvent& evt, + ServiceListenerEntries& matchBefore) +{ + ServiceReference sr = evt.GetServiceReference(); + int n = 0; + + for (ServiceListenerEntries::const_iterator l = receivers.begin(); + l != receivers.end(); ++l) + { + if (!matchBefore.empty()) + { + matchBefore.erase(*l); + } + + if (!l->IsRemoved()) + { + try + { + ++n; + l->CallDelegate(evt); + } + catch (...) + { + MITK_ERROR << "Service listener in " << l->GetModule()->GetName() + << " threw an exception!"; + } + } + } + + MITK_INFO << "Notified " << n << " listeners"; +} + +void ServiceListeners::GetMatchingServiceListeners(const ServiceReference& sr, ServiceListenerEntries& set) +{ + MutexLocker lock(mutex); + + // Check complicated or empty listener filters + int n = 0; + for (std::list::const_iterator sse = complicatedListeners.begin(); + sse != complicatedListeners.end(); ++sse) + { + ++n; + if (sse->GetLDAPExpr().IsNull() || + sse->GetLDAPExpr().Evaluate(sr.d->GetProperties(), false)) + { + set.insert(*sse); + } + } + + MITK_INFO << "Added " << set.size() << " out of " << n + << " listeners with complicated filters"; + + // Check the cache + const std::list c(any_cast > + (sr.GetProperty(ServiceConstants::OBJECTCLASS()))); + for (std::list::const_iterator objClass = c.begin(); + objClass != c.end(); ++objClass) + { + AddToSet(set, OBJECTCLASS_IX, *objClass); + } + + long service_id = any_cast(sr.GetProperty(ServiceConstants::SERVICE_ID())); + std::stringstream ss; + ss << service_id; + AddToSet(set, SERVICE_ID_IX, ss.str()); +} + +void ServiceListeners::ModuleChanged(const ModuleEvent& evt) +{ + MutexLocker lock(moduleListenerMapMutex); + for(ModuleListenerMap::iterator i = moduleListenerMap.begin(); + i != moduleListenerMap.end(); ++i) + { + i->second.Send(evt); + } +} + +void ServiceListeners::RemoveFromCache(const ServiceListenerEntry& sle) +{ + if (!sle.GetLocalCache().empty()) + { + for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) + { + CacheType& keymap = cache[i]; + std::vector& l = sle.GetLocalCache()[i]; + for (std::vector::const_iterator it = l.begin(); + it != l.end(); ++it) + { + std::list& sles = keymap[*it]; + sles.remove(sle); + if (sles.empty()) + { + keymap.erase(*it); + } + } + } + } + else + { + complicatedListeners.remove(sle); + } +} + + void ServiceListeners::CheckSimple(const ServiceListenerEntry& sle) { + if (sle.GetLDAPExpr().IsNull()) + { + complicatedListeners.push_back(sle); + } + else + { + LDAPExpr::LocalCache local_cache; + if (sle.GetLDAPExpr().IsSimple(hashedServiceKeys, local_cache, false)) + { + sle.GetLocalCache() = local_cache; + for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) + { + for (std::vector::const_iterator it = local_cache[i].begin(); + it != local_cache[i].end(); ++it) + { + std::list& sles = cache[i][*it]; + sles.push_back(sle); + } + } + } + else + { + MITK_INFO << "Too complicated filter: " << sle.GetFilter(); + complicatedListeners.push_back(sle); + } + } + } + +void ServiceListeners::AddToSet(ServiceListenerEntries& set, + int cache_ix, const std::string& val) +{ + std::list& l = cache[cache_ix][val]; + if (!l.empty()) + { + MITK_INFO << hashedServiceKeys[cache_ix] << " matches " << l.size(); + + for (std::list::const_iterator entry = l.begin(); + entry != l.end(); ++entry) + { + set.insert(*entry); + } + } + else + { + MITK_INFO << hashedServiceKeys[cache_ix] << " matches none"; + } +} + +} diff --git a/Core/Code/Service/mitkServiceListeners_p.h b/Core/Code/Service/mitkServiceListeners_p.h new file mode 100644 index 0000000000..e6b2270950 --- /dev/null +++ b/Core/Code/Service/mitkServiceListeners_p.h @@ -0,0 +1,191 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICELISTENERS_H +#define MITKSERVICELISTENERS_H + +#include +#include +#include + +#include + +#ifdef MITK_HAS_UNORDERED_MAP_H +#include +#else +#include "mitkItkHashMap.h" +#endif + +#ifdef MITK_HAS_UNORDERED_SET_H +#include +#else +#include "mitkItkHashSet.h" +#endif + +#include + +#include "mitkServiceUtils.h" +#include "mitkServiceListenerEntry_p.h" + +namespace mitk { + +class CoreModuleContext; +class ModuleContext; + +/** + * Here we handle all listeners that modules have registered. + * + */ +class ServiceListeners { + +public: + + typedef Message1 ModuleMessage; + +#ifdef MITK_HAS_UNORDERED_MAP_H + typedef std::unordered_map > CacheType; + typedef std::unordered_map ModuleListenerMap; +#else + typedef itk::hash_map > CacheType; + typedef itk::hash_map ModuleListenerMap; +#endif + +#ifdef MITK_HAS_UNORDERED_SET_H + typedef std::unordered_set ServiceListenerEntries; +#else + typedef itk::hash_set ServiceListenerEntries; +#endif + +private: + + std::vector hashedServiceKeys; + static const int OBJECTCLASS_IX; // = 0; + static const int SERVICE_ID_IX; // = 1; + + /* Service listeners with complicated or empty filters */ + std::list complicatedListeners; + + /* Service listeners with "simple" filters are cached. */ + CacheType cache[2]; + + ServiceListenerEntries serviceSet; + ModuleListenerMap moduleListenerMap; + + typedef itk::SimpleFastMutexLock MutexType; + typedef itk::MutexLockHolder MutexLocker; + + MutexType mutex; + MutexType moduleListenerMapMutex; + +public: + + ServiceListeners(); + + /** + * Add a new service listener. If an old one exists, and it has the + * same owning module, the old listener is removed first. + * + * @param mc The module context adding this listener. + * @param listener The service listener to add. + * @param filter An LDAP filter string to check when a service is modified. + * @exception org.osgi.framework.InvalidSyntaxException + * If the filter is not a correct LDAP expression. + */ + void AddServiceListener(ModuleContext* mc, const ServiceListenerDelegate& listener, + const std::string& filter); + + /** + * Remove service listener from current framework. Silently ignore + * if listener doesn't exist. If listener is registered more than + * once remove all instances. + * + * @param mc The module context who wants to remove listener. + * @param listener Object to remove. + */ + void RemoveServiceListener(ModuleContext* mc, const ServiceListenerDelegate& listener); + + /** + * Add a new service listener. + * + * @param mc The module context adding this listener. + * @param listener The service listener to add. + * @param filter An LDAP filter string to check when a service is modified. + * @exception org.osgi.framework.InvalidSyntaxException + * If the filter is not a correct LDAP expression. + */ + void AddModuleListener(ModuleContext* mc, const ModuleListenerDelegate& listener); + + /** + * Remove service listener from current framework. Silently ignore + * if listener doesn't exist. + * + * @param mc The module context who wants to remove listener. + * @param listener Object to remove. + */ + void RemoveModuleListener(ModuleContext* mc, const ModuleListenerDelegate& listener); + + /** + * Remove all listener registered by a module in the current framework. + * + * @param mc Module context which listeners we want to remove. + */ + void RemoveAllListeners(ModuleContext* mc); + + /** + * Receive notification that a service has had a change occur in its lifecycle. + * + * @see org.osgi.framework.ServiceListener#serviceChanged + */ + void ServiceChanged(const ServiceListenerEntries& receivers, + const ServiceEvent& evt, + ServiceListenerEntries& matchBefore); + + void ServiceChanged(const ServiceListenerEntries& receivers, + const ServiceEvent& evt); + + /** + * + * + */ + void GetMatchingServiceListeners(const ServiceReference& sr, ServiceListenerEntries& listeners); + + void ModuleChanged(const ModuleEvent& evt); + +private: + + void RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove); + + /** + * Remove all references to a service listener from the service listener + * cache. + */ + void RemoveFromCache(const ServiceListenerEntry& sle); + + /** + * Checks if the specified service listener's filter is simple enough + * to cache. + */ + void CheckSimple(const ServiceListenerEntry& sle); + + void AddToSet(ServiceListenerEntries& set, int cache_ix, const std::string& val); + +}; + +} + +#endif // MITKSERVICELISTENERS_H diff --git a/Core/Code/Service/mitkServiceProperties.cpp b/Core/Code/Service/mitkServiceProperties.cpp new file mode 100644 index 0000000000..271a4b58e3 --- /dev/null +++ b/Core/Code/Service/mitkServiceProperties.cpp @@ -0,0 +1,57 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include + +#include "mitkServiceProperties.h" +#include "mitkServiceUtils.h" + +const std::string& mitk::ServiceConstants::OBJECTCLASS() +{ + static const std::string s("objectclass"); + return s; +} + +const std::string& mitk::ServiceConstants::SERVICE_ID() +{ + static const std::string s("service.id"); + return s; +} + +const std::string& mitk::ServiceConstants::SERVICE_RANKING() +{ + static const std::string s("service.ranking"); + return s; +} + +namespace mitk { + +std::size_t hash_ci_string::operator()(const ci_string& s) const +{ + ci_string ls(s); + std::transform(ls.begin(), ls.end(), ls.begin(), tolower); + +#ifdef MITK_HAS_UNORDERED_MAP_H + using namespace std; +#else + using namespace itk; +#endif + return hash()(ls); +} + +} + diff --git a/Core/Code/Service/mitkServiceProperties.h b/Core/Code/Service/mitkServiceProperties.h new file mode 100644 index 0000000000..f68ff790eb --- /dev/null +++ b/Core/Code/Service/mitkServiceProperties.h @@ -0,0 +1,191 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITK_SERVICE_PROPERTIES_H +#define MITK_SERVICE_PROPERTIES_H + +#include + +#include + +#ifdef MITK_HAS_UNORDERED_MAP_H +#include +#else +#include "mitkItkHashMap.h" +#endif + +#include +#include "mitkAny.h" + +namespace mitk { + +struct ci_char_traits : public std::char_traits + // just inherit all the other functions + // that we don't need to override +{ + + static bool eq(char c1, char c2) + { + return std::toupper(c1) == std::toupper(c2); + } + + static bool ne(char c1, char c2) + { + return std::toupper(c1) != std::toupper(c2); + } + + static bool lt(char c1, char c2) + { + return std::toupper(c1) < std::toupper(c2); + } + + static bool gt(char c1, char c2) + { + return std::toupper(c1) > std::toupper(c2); + } + + static int compare(const char* s1, const char* s2, std::size_t n) + { + while (n-- > 0) + { + if (lt(*s1, *s2)) return -1; + if (gt(*s1, *s2)) return 1; + ++s1; ++s2; + } + return 0; + } + + static const char* find(const char* s, int n, char a) + { + while (n-- > 0 && std::toupper(*s) != std::toupper(a)) + { + ++s; + } + return s; + } + +}; + +class ci_string : public std::basic_string +{ +private: + + typedef std::basic_string Super; + +public: + + inline ci_string() : Super() {} + inline ci_string(const ci_string& cistr) : Super(cistr) {} + inline ci_string(const ci_string& cistr, size_t pos, size_t n) : Super(cistr, pos, n) {} + inline ci_string(const char* s, size_t n) : Super(s, n) {} + inline ci_string(const char* s) : Super(s) {} + inline ci_string(size_t n, char c) : Super(n, c) {} + + inline ci_string(const std::string& str) : Super(str.begin(), str.end()) {} + + template ci_string(InputIterator begin, InputIterator end) + : Super(begin, end) + {} + + inline operator std::string () const + { + return std::string(begin(), end()); + } +}; + +struct MITK_CORE_EXPORT hash_ci_string +{ + std::size_t operator()(const ci_string& s) const; +}; + +/** + * \ingroup MicroServices + * + * A hash table based map class with case-insensitive keys. This class + * uses ci_string as key type and Any as values. Due + * to the conversion capabilities of ci_string, std::string objects + * can be used transparantly to insert or retrieve key-value pairs. + * + *

+ * Note that the case of the keys will be preserved. + */ +#ifdef MITK_HAS_UNORDERED_MAP_H +typedef std::unordered_map ServiceProperties; +#else +typedef itk::hash_map ServiceProperties; +#endif + +/** + * \ingroup MicroServices + */ +namespace ServiceConstants { + +/** + * Service property identifying all of the class names under which a service + * was registered in the framework. The value of this property must be of + * type std::list<std::string>. + * + *

+ * This property is set by the framework when a service is registered. + */ +MITK_CORE_EXPORT const std::string& OBJECTCLASS(); // = "objectclass" + +/** + * Service property identifying a service's registration number. The value + * of this property must be of type long int. + * + *

+ * The value of this property is assigned by the framework when a service is + * registered. The framework assigns a unique value that is larger than all + * previously assigned values since the framework was started. These values + * are NOT persistent across restarts of the framework. + */ +MITK_CORE_EXPORT const std::string& SERVICE_ID(); // = "service.id" + +/** + * Service property identifying a service's ranking number. + * + *

+ * This property may be supplied in the + * ServiceProperties object passed to the + * ModuleContext::RegisterService method. The value of this + * property must be of type int. + * + *

+ * The service ranking is used by the framework to determine the natural + * order of services, see ServiceReference::operator<(const ServiceReference&), + * and the default service to be returned from a call to the + * {@link ModuleContext::GetServiceReference} method. + * + *

+ * The default ranking is zero (0). A service with a ranking of + * std::numeric_limits::max() is very likely to be returned as the + * default service, whereas a service with a ranking of + * std::numeric_limits::min() is very unlikely to be returned. + * + *

+ * If the supplied property value is not of type int, it is + * deemed to have a ranking value of zero. + */ +MITK_CORE_EXPORT const std::string& SERVICE_RANKING(); // = "service.ranking" + +} + +} + +#endif // MITK_SERVICE_PROPERTIES_H diff --git a/Core/Code/Service/mitkServiceReference.cpp b/Core/Code/Service/mitkServiceReference.cpp new file mode 100644 index 0000000000..e6dda32d33 --- /dev/null +++ b/Core/Code/Service/mitkServiceReference.cpp @@ -0,0 +1,197 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkServiceReference.h" +#include "mitkServiceReferencePrivate.h" +#include "mitkServiceRegistrationPrivate.h" + +#include "mitkModule.h" +#include "mitkModulePrivate.h" + +#include + +namespace mitk { + +typedef ServiceRegistrationPrivate::MutexType MutexType; +typedef itk::MutexLockHolder MutexLocker; + +ServiceReference::ServiceReference() + : d(new ServiceReferencePrivate(0)) +{ + +} + +ServiceReference::ServiceReference(const ServiceReference& ref) + : d(ref.d) +{ + d->ref.Ref(); +} + +ServiceReference::ServiceReference(ServiceRegistrationPrivate* reg) + : d(new ServiceReferencePrivate(reg)) +{ + +} + +ServiceReference::operator bool() const +{ + return GetModule() != 0; +} + +ServiceReference& ServiceReference::operator=(int null) +{ + if (null == 0) + { + if (d && !d->ref.Deref()) + delete d; + d = new ServiceReferencePrivate(0); + } + return *this; +} + +ServiceReference::~ServiceReference() +{ + if (!d->ref.Deref()) + delete d; +} + +Any ServiceReference::GetProperty(const std::string& key) const +{ + MutexLocker lock(d->registration->propsLock); + + ServiceProperties::const_iterator iter = d->registration->properties.find(key); + if (iter != d->registration->properties.end()) + return iter->second; + return Any(); +} + +void ServiceReference::GetPropertyKeys(std::vector& keys) const +{ + MutexLocker lock(d->registration->propsLock); + + ServiceProperties::const_iterator iterEnd = d->registration->properties.end(); + for (ServiceProperties::const_iterator iter = d->registration->properties.begin(); + iter != iterEnd; ++iter) + { + keys.push_back(iter->first); + } +} + +Module* ServiceReference::GetModule() const +{ + if (d->registration == 0 || d->registration->module == 0) + { + return 0; + } + + return d->registration->module->q; +} + +void ServiceReference::GetUsingModules(std::vector& modules) const +{ + MutexLocker lock(d->registration->propsLock); + + ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator end = d->registration->dependents.end(); + for (ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator iter = d->registration->dependents.begin(); + iter != end; ++iter) + { + modules.push_back(iter->first); + } +} + +bool ServiceReference::operator<(const ServiceReference& reference) const +{ + int r1 = 0; + int r2 = 0; + + mitk::Any anyR1 = GetProperty(ServiceConstants::SERVICE_RANKING()); + mitk::Any anyR2 = reference.GetProperty(ServiceConstants::SERVICE_RANKING()); + if (anyR1.Type() == typeid(int)) r1 = any_cast(anyR1); + if (anyR2.Type() == typeid(int)) r2 = any_cast(anyR2); + + if (r1 != r2) + { + // use ranking if ranking differs + return r1 < r2; + } + else + { + long int id1 = any_cast(GetProperty(ServiceConstants::SERVICE_ID())); + long int id2 = any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())); + + // otherwise compare using IDs, + // is less than if it has a higher ID. + return id2 < id1; + } +} + +bool ServiceReference::operator==(const ServiceReference& reference) const +{ + return d->registration == reference.d->registration; +} + +ServiceReference& ServiceReference::operator=(const ServiceReference& reference) +{ + ServiceReferencePrivate* curr_d = d; + d = reference.d; + d->ref.Ref(); + + if (!curr_d->ref.Deref()) + delete curr_d; + + return *this; +} + +} + +std::ostream& operator<<(std::ostream& os, const mitk::ServiceReference& serviceRef) +{ + os << "Reference for service object registered from " + << serviceRef.GetModule()->GetName() << " " << serviceRef.GetModule()->GetVersion() + << " ("; + std::vector keys; + serviceRef.GetPropertyKeys(keys); + int keySize = keys.size(); + for(int i = 0; i < keySize; ++i) + { + os << keys[i] << "=" << serviceRef.GetProperty(keys[i]); + if (i < keySize-1) os << ","; + } + os << ")"; + + return os; +} + +#ifdef MITK_HAS_UNORDERED_MAP_H +namespace std { +#elif defined(__GNUC__) +namespace __gnu_cxx { +#else +namespace itk { +#endif + +std::size_t hash::operator()(const mitk::ServiceReference& sr) const +{ +#ifdef MITK_HAS_HASH_SIZE_T + return hash()(reinterpret_cast(sr.d->registration)); +#else + std::size_t key = reinterpret_cast(sr.d->registration); + return std::size_t(key & (~0U)); +#endif +} + +} diff --git a/Core/Code/Service/mitkServiceReference.h b/Core/Code/Service/mitkServiceReference.h new file mode 100644 index 0000000000..2bb504c8db --- /dev/null +++ b/Core/Code/Service/mitkServiceReference.h @@ -0,0 +1,239 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKSERVICEREFERENCE_H +#define MITKSERVICEREFERENCE_H + +#include +#include + +#ifdef MITK_HAS_UNORDERED_MAP_H +namespace std { +#elif defined(__GNUC__) +namespace __gnu_cxx { +#else +namespace itk { +#endif + +template class hash; + +} + +namespace mitk { + +class Module; +class ServiceRegistrationPrivate; +class ServiceReferencePrivate; + +/** + * \ingroup MicroServices + * + * A reference to a service. + * + *

+ * The framework returns ServiceReference objects from the + * ModuleContext::GetServiceReference and + * ModuleContext::GetServiceReferences methods. + *

+ * A ServiceReference object may be shared between modules and + * can be used to examine the properties of the service and to get the service + * object. + *

+ * Every service registered in the framework has a unique + * ServiceRegistration object and may have multiple, distinct + * ServiceReference objects referring to it. + * ServiceReference objects associated with a + * ServiceRegistration are considered equal + * (more specifically, their operator==() + * method will return true when compared). + *

+ * If the same service object is registered multiple times, + * ServiceReference objects associated with different + * ServiceRegistration objects are not equal. + * + * @see ModuleContext::GetServiceReference + * @see ModuleContext::GetServiceReferences + * @see ModuleContext::GetService + * @remarks This class is thread safe. + */ +class MITK_CORE_EXPORT ServiceReference { + +public: + + /** + * Creates an invalid ServiceReference object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceReference(); + + ServiceReference(const ServiceReference& ref); + + /** + * Converts this ServiceReference instance into a boolean + * expression. If this instance was default constructed or + * the service it references has been unregistered, the conversion + * returns false, otherwise it returns true. + */ + operator bool() const; + + /** + * Releases any resources held or locked by this + * ServiceReference and renders it invalid. + */ + ServiceReference& operator=(int null); + + ~ServiceReference(); + + /** + * Returns the property value to which the specified property key is mapped + * in the properties ServiceProperties object of the service + * referenced by this ServiceReference object. + * + *

+ * Property keys are case-insensitive. + * + *

+ * This method continues to return property values after the service has + * been unregistered. This is so references to unregistered services can + * still be interrogated. + * + * @param key The property key. + * @return The property value to which the key is mapped; an invalid Any + * if there is no property named after the key. + */ + Any GetProperty(const std::string& key) const; + + /** + * Returns a list of the keys in the ServiceProperties + * object of the service referenced by this ServiceReference + * object. + * + *

+ * This method will continue to return the keys after the service has been + * unregistered. This is so references to unregistered services can + * still be interrogated. + * + * @param keys A vector being filled with the property keys. + */ + void GetPropertyKeys(std::vector& keys) const; + + /** + * Returns the module that registered the service referenced by this + * ServiceReference object. + * + *

+ * This method must return 0 when the service has been + * unregistered. This can be used to determine if the service has been + * unregistered. + * + * @return The module that registered the service referenced by this + * ServiceReference object; 0 if that + * service has already been unregistered. + * @see ModuleContext::RegisterService(const std::vector&, itk::LightObject*, const ServiceProperties&) + */ + Module* GetModule() const; + + /** + * Returns the modules that are using the service referenced by this + * ServiceReference object. Specifically, this method returns + * the modules whose usage count for that service is greater than zero. + * + * @param modules A list of modules whose usage count for the service referenced + * by this ServiceReference object is greater than + * zero. + */ + void GetUsingModules(std::vector& modules) const; + + /** + * Compares this ServiceReference with the specified + * ServiceReference for order. + * + *

+ * If this ServiceReference and the specified + * ServiceReference have the same {@link ServiceProperties::SERVICE_ID + * service id} they are equal. This ServiceReference is less + * than the specified ServiceReference if it has a lower + * {@link ServiceProperties::SERVICE_RANKING service ranking} and greater if it has a + * higher service ranking. Otherwise, if this ServiceReference + * and the specified ServiceReference have the same + * {@link ServiceProperties::SERVICE_RANKING service ranking}, this + * ServiceReference is less than the specified + * ServiceReference if it has a higher + * {@link ServiceProperties::SERVICE_ID service id} and greater if it has a lower + * service id. + * + * @param reference The ServiceReference to be compared. + * @return Returns a false or true if this + * ServiceReference is less than or greater + * than the specified ServiceReference. + */ + bool operator<(const ServiceReference& reference) const; + + bool operator==(const ServiceReference& reference) const; + + ServiceReference& operator=(const ServiceReference& reference); + + +protected: + + friend class ModulePrivate; + friend class ModuleContext; + friend class ServiceFilter; + friend class ServiceRegistrationPrivate; + friend class ServiceListeners; + friend class LDAPFilter; + + template friend class ServiceTracker; + template friend class ServiceTrackerPrivate; + template friend class ModuleAbstractTracked; + +#ifdef MITK_HAS_UNORDERED_MAP_H + friend class std::hash; +#elif defined(__GNUC__) + friend class __gnu_cxx::hash; +#else + friend struct itk::hash; +#endif + + + ServiceReference(ServiceRegistrationPrivate* reg); + + ServiceReferencePrivate* d; + +}; + +} + +MITK_CORE_EXPORT std::ostream& operator<<(std::ostream& os, const mitk::ServiceReference& serviceRef); + +#ifdef MITK_HAS_UNORDERED_MAP_H +namespace std { +#elif defined(__GNUC__) +namespace __gnu_cxx { +#else +namespace itk { +#endif + +template<> struct MITK_CORE_EXPORT hash +{ + std::size_t operator()(const mitk::ServiceReference& sr) const; +}; + +} + +#endif // MITKSERVICEREFERENCE_H diff --git a/Core/Code/Service/mitkServiceReferencePrivate.cpp b/Core/Code/Service/mitkServiceReferencePrivate.cpp new file mode 100644 index 0000000000..c778e50734 --- /dev/null +++ b/Core/Code/Service/mitkServiceReferencePrivate.cpp @@ -0,0 +1,157 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkServiceReferencePrivate.h" + +#include "mitkServiceFactory.h" +#include "mitkServiceException.h" +#include "mitkServiceRegistry_p.h" +#include "mitkServiceRegistrationPrivate.h" + +#include "mitkModule.h" +#include "mitkModulePrivate.h" +#include "mitkCoreModuleContext_p.h" + +#include + +namespace mitk { + +typedef ServiceRegistrationPrivate::MutexLocker MutexLocker; + +ServiceReferencePrivate::ServiceReferencePrivate(ServiceRegistrationPrivate* reg) + : ref(1), registration(reg) +{ +} + +itk::LightObject* ServiceReferencePrivate::GetService(Module* module) +{ + itk::LightObject* s = 0; + { + MutexLocker lock(registration->propsLock); + if (registration->available) + { + int count = registration->dependents[module]; + if (count == 0) + { + const std::list& classes = + ref_any_cast >(registration->properties[ServiceConstants::OBJECTCLASS()]); + registration->dependents[module] = 1; + if (ServiceFactory* serviceFactory = dynamic_cast(registration->GetService())) + { + try + { + s = serviceFactory->GetService(module, ServiceRegistration(registration)); + } + catch (...) + { + MITK_WARN << "mitk::ServiceFactory threw an exception"; + return 0; + } + if (s == 0) { + MITK_WARN << "mitk::ServiceFactory produced null"; + return 0; + } + for (std::list::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + if (!registration->module->coreCtx->services.CheckServiceClass(s, *i)) + { + MITK_WARN << "mitk::ServiceFactory produced an object " + "that did not implement: " << (*i); + return 0; + } + } + registration->serviceInstances.insert(std::make_pair(module, s)); + } + else + { + s = registration->GetService(); + } + } + else + { + registration->dependents.insert(std::make_pair(module, count + 1)); + if (dynamic_cast(registration->GetService())) + { + s = registration->serviceInstances[module]; + } + else + { + s = registration->GetService(); + } + } + } + } + return s; +} + +bool ServiceReferencePrivate::UngetService(Module* module, bool checkRefCounter) +{ + MutexLocker lock(registration->propsLock); + bool hadReferences = false; + bool removeService = false; + + int count= registration->dependents[module]; + if (count > 0) + { + hadReferences = true; + } + + if(checkRefCounter) + { + if (count > 1) + { + registration->dependents[module] = count - 1; + } + else if(count == 1) + { + removeService = true; + } + } + else + { + removeService = true; + } + + if (removeService) + { + itk::LightObject* sfi = registration->serviceInstances[module]; + registration->serviceInstances.erase(module); + if (sfi != 0) + { + try + { + dynamic_cast( + registration->GetService())->UngetService(module, ServiceRegistration(registration), sfi); + } + catch (const std::exception& /*e*/) + { + MITK_WARN << "mitk::ServiceFactory threw an exception"; + } + } + registration->dependents.erase(module); + } + + return hadReferences; +} + +ServiceProperties ServiceReferencePrivate::GetProperties() const +{ + return registration->properties; +} + +} diff --git a/Core/Code/Service/mitkServiceReferencePrivate.h b/Core/Code/Service/mitkServiceReferencePrivate.h new file mode 100644 index 0000000000..830baf39c9 --- /dev/null +++ b/Core/Code/Service/mitkServiceReferencePrivate.h @@ -0,0 +1,89 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICEREFERENCEPRIVATE_H +#define MITKSERVICEREFERENCEPRIVATE_H + +#include "mitkAtomicInt.h" + +#include "mitkServiceProperties.h" + +namespace itk { + class LightObject; +} + +namespace mitk { + +class Module; +class ServiceRegistrationPrivate; +class ServiceReferencePrivate; + + +/** + * \ingroup MicroServices + */ +class ServiceReferencePrivate +{ +public: + + ServiceReferencePrivate(ServiceRegistrationPrivate* reg); + + virtual ~ServiceReferencePrivate() {} + + /** + * Get the service object. + * + * @param module requester of service. + * @return Service requested or null in case of failure. + */ + itk::LightObject* GetService(Module* module); + + /** + * Unget the service object. + * + * @param module Module who wants remove service. + * @param checkRefCounter If true decrement refence counter and remove service + * if we reach zero. If false remove service without + * checking refence counter. + * @return True if service was remove or false if only refence counter was + * decremented. + */ + bool UngetService(Module* module, bool checkRefCounter); + + /** + * Get all properties registered with this service. + * + * @return A ServiceProperties object containing properties or being empty + * if service has been removed. + */ + ServiceProperties GetProperties() const; + + /** + * Reference count for implicitly shared private implementation. + */ + AtomicInt ref; + + /** + * Link to registration object for this reference. + */ + ServiceRegistrationPrivate* const registration; +}; + +} + +#endif // MITKSERVICEREFERENCEPRIVATE_H diff --git a/Core/Code/Service/mitkServiceRegistration.cpp b/Core/Code/Service/mitkServiceRegistration.cpp new file mode 100644 index 0000000000..7974483638 --- /dev/null +++ b/Core/Code/Service/mitkServiceRegistration.cpp @@ -0,0 +1,220 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkServiceRegistration.h" +#include "mitkServiceRegistrationPrivate.h" +#include "mitkServiceListenerEntry_p.h" +#include "mitkServiceRegistry_p.h" +#include "mitkServiceFactory.h" + +#include "mitkModulePrivate.h" +#include "mitkCoreModuleContext_p.h" + +#include + +namespace mitk { + +typedef ServiceRegistrationPrivate::MutexLocker MutexLocker; + +ServiceRegistration::ServiceRegistration() + : d(0) +{ + +} + +ServiceRegistration::ServiceRegistration(const ServiceRegistration& reg) + : d(reg.d) +{ + d->ref.Ref(); +} + +ServiceRegistration::ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate) + : d(registrationPrivate) +{ + d->ref.Ref(); +} + +ServiceRegistration::ServiceRegistration(ModulePrivate* module, itk::LightObject* service, + const ServiceProperties& props) + : d(new ServiceRegistrationPrivate(module, service, props)) +{ + +} + +ServiceRegistration::operator bool() const +{ + return d != 0; +} + +ServiceRegistration& ServiceRegistration::operator=(int null) +{ + if (null == 0) + { + if (d && !d->ref.Deref()) + { + delete d; + } + d = 0; + } + return *this; +} + +ServiceRegistration::~ServiceRegistration() +{ + if (d && !d->ref.Deref()) + delete d; +} + +ServiceReference ServiceRegistration::GetReference() const +{ + if (!d) throw std::logic_error("ServiceRegistration object invalid"); + if (!d->available) throw std::logic_error("Service is unregistered"); + + return d->reference; +} + +void ServiceRegistration::SetProperties(const ServiceProperties& props) +{ + if (!d) throw std::logic_error("ServiceRegistration object invalid"); + + MutexLocker lock(d->eventLock); + + ServiceListeners::ServiceListenerEntries before; + // TBD, optimize the locking of services + { + //MutexLocker lock2(d->module->coreCtx->globalFwLock); + MutexLocker lock3(d->propsLock); + + if (d->available) + { + // NYI! Optimize the MODIFIED_ENDMATCH code + int old_rank = any_cast(d->properties[ServiceConstants::SERVICE_RANKING()]); + d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, before); + const std::list& classes = ref_any_cast >(d->properties[ServiceConstants::OBJECTCLASS()]); + long int sid = any_cast(d->properties[ServiceConstants::SERVICE_ID()]); + d->properties = ServiceRegistry::CreateServiceProperties(props, classes, sid); + int new_rank = any_cast(d->properties[ServiceConstants::SERVICE_RANKING()]); + if (old_rank != new_rank) + { + d->module->coreCtx->services.UpdateServiceRegistrationOrder(*this, classes); + } + } + else + { + throw std::logic_error("Service is unregistered"); + } + } + ServiceListeners::ServiceListenerEntries matchingListeners; + d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, matchingListeners); + d->module->coreCtx->listeners.ServiceChanged(matchingListeners, + ServiceEvent(ServiceEvent::MODIFIED, d->reference), + before); + + d->module->coreCtx->listeners.ServiceChanged(before, + ServiceEvent(ServiceEvent::MODIFIED_ENDMATCH, d->reference)); +} + +void ServiceRegistration::Unregister() +{ + if (!d) throw std::logic_error("ServiceRegistration object invalid"); + + if (d->unregistering) return; // Silently ignore redundant unregistration. + { + MutexLocker lock(d->eventLock); + if (d->unregistering) return; + d->unregistering = true; + + if (d->available) + { + if (d->module) + { + d->module->coreCtx->services.RemoveServiceRegistration(*this); + } + } + else + { + throw std::logic_error("Service is unregistered"); + } + } + + if (d->module) + { + ServiceListeners::ServiceListenerEntries listeners; + d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, listeners); + d->module->coreCtx->listeners.ServiceChanged( + listeners, + ServiceEvent(ServiceEvent::UNREGISTERING, d->reference)); + } + + { + MutexLocker lock(d->eventLock); + { + MutexLocker lock2(d->propsLock); + d->available = false; + if (d->module) + { + ServiceRegistrationPrivate::ModuleToServicesMap::const_iterator end = d->serviceInstances.end(); + for (ServiceRegistrationPrivate::ModuleToServicesMap::const_iterator i = d->serviceInstances.begin(); + i != end; ++i) + { + itk::LightObject* obj = i->second; + try + { + // NYI, don't call inside lock + dynamic_cast(d->service)->UngetService(i->first, + *this, + obj); + } + catch (const std::exception& /*ue*/) + { + MITK_WARN << "mitk::ServiceFactory UngetService implementation threw an exception"; + } + } + } + d->module = 0; + d->dependents.clear(); + d->service = 0; + d->serviceInstances.clear();; + d->unregistering = false; + } + } +} + +bool ServiceRegistration::operator<(const ServiceRegistration& o) const +{ + if (!d) return true; + return d->reference <(o.d->reference); +} + +bool ServiceRegistration::operator==(const ServiceRegistration& registration) const +{ + return d == registration.d; +} + +ServiceRegistration& ServiceRegistration::operator=(const ServiceRegistration& registration) +{ + ServiceRegistrationPrivate* curr_d = d; + d = registration.d; + d->ref.Ref(); + + if (curr_d && !curr_d->ref.Deref()) + delete curr_d; + + return *this; +} + +} diff --git a/Core/Code/Service/mitkServiceRegistration.h b/Core/Code/Service/mitkServiceRegistration.h new file mode 100644 index 0000000000..e41630bbb2 --- /dev/null +++ b/Core/Code/Service/mitkServiceRegistration.h @@ -0,0 +1,171 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#ifndef MITKSERVICEREGISTRATION_H +#define MITKSERVICEREGISTRATION_H + +#include "mitkServiceProperties.h" +#include "mitkServiceReference.h" + +namespace mitk { + +class ModulePrivate; + +/** + * \ingroup MicroServices + * + * A registered service. + * + *

+ * The framework returns a ServiceRegistration object when a + * ModuleContext#RegisterService() method invocation is successful. + * The ServiceRegistration object is for the private use of the + * registering module and should not be shared with other modules. + *

+ * The ServiceRegistration object may be used to update the + * properties of the service or to unregister the service. + * + * @see ModuleContext#RegisterService() + * @remarks This class is thread safe. + */ +class MITK_CORE_EXPORT ServiceRegistration { + +public: + + /** + * Creates an invalid ServiceRegistration object. You can use + * this object in boolean expressions and it will evaluate to + * false. + */ + ServiceRegistration(); + + ServiceRegistration(const ServiceRegistration& reg); + + operator bool() const; + + /** + * Releases any resources held or locked by this + * ServiceRegistration and renders it invalid. + */ + ServiceRegistration& operator=(int null); + + ~ServiceRegistration(); + + /** + * Returns a ServiceReference object for a service being + * registered. + *

+ * The ServiceReference object may be shared with other + * modules. + * + * @throws std::logic_error If this + * ServiceRegistration object has already been + * unregistered or if it is invalid. + * @return ServiceReference object. + */ + ServiceReference GetReference() const; + + /** + * Updates the properties associated with a service. + * + *

+ * The {@link ServiceProperties#OBJECTCLASS} and {@link ServiceProperties#SERVICE_ID} keys + * cannot be modified by this method. These values are set by the framework + * when the service is registered in the environment. + * + *

+ * The following steps are taken to modify service properties: + *

    + *
  1. The service's properties are replaced with the provided properties. + *
  2. A service event of type {@link ServiceEvent#MODIFIED} is fired. + *
+ * + * @param properties The properties for this service. See {@link ServiceProperties} + * for a list of standard service property keys. Changes should not + * be made to this object after calling this method. To update the + * service's properties this method should be called again. + * + * @throws std::logic_error If this ServiceRegistration + * object has already been unregistered or if it is invalid. + * @throws std::invalid_argument If properties contains + * case variants of the same key name. + */ + void SetProperties(const ServiceProperties& properties); + + /** + * Unregisters a service. Remove a ServiceRegistration object + * from the framework service registry. All ServiceRegistration + * objects associated with this ServiceRegistration object + * can no longer be used to interact with the service once unregistration is + * complete. + * + *

+ * The following steps are taken to unregister a service: + *

    + *
  1. The service is removed from the framework service registry so that + * it can no longer be obtained. + *
  2. A service event of type {@link ServiceEvent#UNREGISTERING} is fired + * so that modules using this service can release their use of the service. + * Once delivery of the service event is complete, the + * ServiceRegistration objects for the service may no longer be + * used to get a service object for the service. + *
  3. For each module whose use count for this service is greater than + * zero:
    + * The module's use count for this service is set to zero.
    + * If the service was registered with a {@link ServiceFactory} object, the + * ServiceFactory#UngetService method is called to release + * the service object for the module. + *
+ * + * @throws std::logic_error If this + * ServiceRegistration object has already been + * unregistered or if it is invalid. + * @see ModuleContext#UngetService + * @see ServiceFactory#UngetService + */ + virtual void Unregister(); + + bool operator<(const ServiceRegistration& o) const; + + bool operator==(const ServiceRegistration& registration) const; + + ServiceRegistration& operator=(const ServiceRegistration& registration); + + +protected: + + friend class ServiceRegistry; + friend class ServiceReferencePrivate; + friend struct HashServiceRegistration; + + ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate); + + ServiceRegistration(ModulePrivate* module, itk::LightObject* service, + const ServiceProperties& props); + + ServiceRegistrationPrivate* d; + +}; + +} + +inline std::ostream& operator<<(std::ostream& os, const mitk::ServiceRegistration& /*reg*/) +{ + return os << "mitk::ServiceRegistration object"; +} + +#endif // MITKSERVICEREGISTRATION_H diff --git a/Core/Code/Service/mitkServiceRegistrationPrivate.cpp b/Core/Code/Service/mitkServiceRegistrationPrivate.cpp new file mode 100644 index 0000000000..26d12eb3ca --- /dev/null +++ b/Core/Code/Service/mitkServiceRegistrationPrivate.cpp @@ -0,0 +1,46 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkServiceRegistrationPrivate.h" + +namespace mitk { + +ServiceRegistrationPrivate::ServiceRegistrationPrivate( + ModulePrivate* module, itk::LightObject* service, + const ServiceProperties& props) + : ref(1), service(service), module(module), reference(this), + properties(props), available(true), unregistering(false) +{ + +} + +ServiceRegistrationPrivate::~ServiceRegistrationPrivate() +{ + +} + +bool ServiceRegistrationPrivate::IsUsedByModule(Module* p) +{ + return dependents.find(p) != dependents.end(); +} + +itk::LightObject* ServiceRegistrationPrivate::GetService() +{ + return service; +} + +} diff --git a/Core/Code/Service/mitkServiceRegistrationPrivate.h b/Core/Code/Service/mitkServiceRegistrationPrivate.h new file mode 100644 index 0000000000..7d3b4400ca --- /dev/null +++ b/Core/Code/Service/mitkServiceRegistrationPrivate.h @@ -0,0 +1,134 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICEREGISTRATIONPRIVATE_H +#define MITKSERVICEREGISTRATIONPRIVATE_H + +#include "mitkModule.h" +#include "mitkServiceReference.h" +#include "mitkServiceProperties.h" +#include "mitkAtomicInt.h" + +#include + +namespace mitk { + +class ModulePrivate; +class ServiceRegistration; + +/** + * \ingroup MicroServices + */ +class ServiceRegistrationPrivate +{ + +protected: + + friend class ServiceRegistration; + + /** + * Reference count for implicitly shared private implementation. + */ + AtomicInt ref; + + /** + * Service or ServiceFactory object. + */ + itk::LightObject* service; + +public: + + typedef itk::SimpleFastMutexLock MutexType; + typedef itk::MutexLockHolder MutexLocker; + +#ifdef MITK_HAS_UNORDERED_MAP_H + typedef std::unordered_map ModuleToRefsMap; + typedef std::unordered_map ModuleToServicesMap; +#else + typedef itk::hash_map ModuleToRefsMap; + typedef itk::hash_map ModuleToServicesMap; +#endif + + /** + * Module registering this service. + */ + ModulePrivate* module; + + /** + * Reference object to this service registration. + */ + ServiceReference reference; + + /** + * Service properties. + */ + ServiceProperties properties; + + /** + * Modules dependent on this service. Integer is used as + * reference counter, counting number of unbalanced getService(). + */ + ModuleToRefsMap dependents; + + /** + * Object instances that factory has produced. + */ + ModuleToServicesMap serviceInstances; + + /** + * Is service available. I.e., if true then holders + * of a ServiceReference for the service are allowed to get it. + */ + volatile bool available; + + /** + * Avoid recursive unregistrations. I.e., if true then + * unregistration of this service has started but is not yet + * finished. + */ + volatile bool unregistering; + + /** + * Lock object for synchronous event delivery. + */ + MutexType eventLock; + + // needs to be recursive + MutexType propsLock; + + ServiceRegistrationPrivate(ModulePrivate* module, itk::LightObject* service, + const ServiceProperties& props); + + virtual ~ServiceRegistrationPrivate(); + + /** + * Check if a module uses this service + * + * @param p Module to check + * @return true if module uses this service + */ + bool IsUsedByModule(Module* m); + + virtual itk::LightObject* GetService(); + +}; + +} + + +#endif // MITKSERVICEREGISTRATIONPRIVATE_H diff --git a/Core/Code/Service/mitkServiceRegistry.cpp b/Core/Code/Service/mitkServiceRegistry.cpp new file mode 100644 index 0000000000..3f6644f91f --- /dev/null +++ b/Core/Code/Service/mitkServiceRegistry.cpp @@ -0,0 +1,329 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include + +#include "mitkServiceRegistry_p.h" +#include "mitkServiceFactory.h" +#include "mitkServiceRegistry_p.h" +#include "mitkServiceRegistrationPrivate.h" +#include "mitkModulePrivate.h" +#include "mitkCoreModuleContext_p.h" + +#include "itkMutexLockHolder.h" + + +namespace mitk { + +typedef itk::MutexLockHolder MutexLocker; + +std::size_t HashServiceRegistration::operator()(const ServiceRegistration& s) const +{ + return reinterpret_cast(s.d); +} + + +struct ServiceRegistrationComparator +{ + bool operator()(const ServiceRegistration& a, const ServiceRegistration& b) const + { + return a < b; + } +}; + +ServiceProperties ServiceRegistry::CreateServiceProperties(const ServiceProperties& in, + const std::list& classes, + long sid) +{ + static long nextServiceID = 1; + ServiceProperties props(in); + + if (!classes.empty()) + { + props.insert(std::make_pair(ServiceConstants::OBJECTCLASS(), classes)); + } + + props.insert(std::make_pair(ServiceConstants::SERVICE_ID(), sid != -1 ? sid : nextServiceID++)); + + return props; +} + +ServiceRegistry::ServiceRegistry(CoreModuleContext* coreCtx) + : core(coreCtx) +{ + +} + +ServiceRegistry::~ServiceRegistry() +{ + Clear(); +} + +void ServiceRegistry::Clear() +{ + services.clear(); + serviceRegistrations.clear(); + classServices.clear(); + core = 0; +} + +ServiceRegistration ServiceRegistry::RegisterService(ModulePrivate* module, + const std::list& classes, + itk::LightObject* service, + const ServiceProperties& properties) +{ + if (service == 0) + { + throw std::invalid_argument("Can't register 0 as a service"); + } + + // Check if service implements claimed classes and that they exist. + for (std::list::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + if (i->empty()) + { + throw std::invalid_argument("Can't register as null class"); + } + + if (!(dynamic_cast(service))) + { + if (!CheckServiceClass(service, *i)) + { + std::string msg; + std::stringstream ss(msg); + ss << "Service class " << service->GetNameOfClass() << " is not an instance of " + << (*i) << ". Maybe you forgot to export the RTTI information for the interface."; + throw std::invalid_argument(msg); + } + } + } + + ServiceRegistration res(module, service, + CreateServiceProperties(properties, classes)); + { + MutexLocker lock(mutex); + services.insert(std::make_pair(res, classes)); + serviceRegistrations.push_back(res); + for (std::list::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + std::list& s = classServices[*i]; + std::list::iterator ip = + std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator()); + s.insert(ip, res); + } + } + + ServiceReference r = res.GetReference(); + ServiceListeners::ServiceListenerEntries listeners; + module->coreCtx->listeners.GetMatchingServiceListeners(r, listeners); + module->coreCtx->listeners.ServiceChanged(listeners, + ServiceEvent(ServiceEvent::REGISTERED, r)); + return res; +} + +void ServiceRegistry::UpdateServiceRegistrationOrder(const ServiceRegistration& sr, + const std::list& classes) +{ + MutexLocker lock(mutex); + for (std::list::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + std::list& s = classServices[*i]; + std::remove(s.begin(), s.end(), sr); + s.insert(std::lower_bound(s.begin(), s.end(), sr, ServiceRegistrationComparator()), sr); + } +} + +bool ServiceRegistry::CheckServiceClass(itk::LightObject* , const std::string& ) const +{ + //return service->inherits(cls.toAscii()); + // No possibility to check inheritance based on string literals. + return true; +} + +void ServiceRegistry::Get(const std::string& clazz, + std::list& serviceRegs) const +{ + MutexLocker lock(mutex); + MapClassServices::const_iterator i = classServices.find(clazz); + if (i != classServices.end()) + { + serviceRegs = i->second; + } +} + +ServiceReference ServiceRegistry::Get(ModulePrivate* module, const std::string& clazz) const +{ + MutexLocker lock(mutex); + try + { + std::list srs; + Get_Unlocked(clazz, "", module, srs); + MITK_INFO << "get service ref " << clazz << " for module " + << module->info.name << " = " << srs.size() << " refs"; + + if (!srs.empty()) + { + return srs.front(); + } + } + catch (const std::invalid_argument& ) + { } + + return ServiceReference(); +} + +void ServiceRegistry::Get(const std::string& clazz, const std::string& filter, + ModulePrivate* module, std::list& res) const +{ + MutexLocker lock(mutex); + Get_Unlocked(clazz, filter, module, res); +} + +void ServiceRegistry::Get_Unlocked(const std::string& clazz, const std::string& filter, + ModulePrivate* /*module*/, std::list& res) const +{ + std::list::const_iterator s; + std::list::const_iterator send; + std::list v; + LDAPExpr ldap; + if (clazz.empty()) + { + if (!filter.empty()) + { + ldap = LDAPExpr(filter); + LDAPExpr::ObjectClassSet matched; + if (ldap.GetMatchedObjectClasses(matched)) + { + v.clear(); + for(LDAPExpr::ObjectClassSet::const_iterator className = matched.begin(); + className != matched.end(); ++className) + { + MapClassServices::const_iterator i = classServices.find(*className); + if (i != classServices.end()) + { + std::copy(i->second.begin(), i->second.end(), std::back_inserter(v)); + } + } + if (!v.empty()) + { + s = v.begin(); + send = v.end(); + } + else + { + return; + } + } + else + { + s = serviceRegistrations.begin(); + send = serviceRegistrations.end(); + } + } + else + { + s = serviceRegistrations.begin(); + send = serviceRegistrations.end(); + } + } + else + { + MapClassServices::const_iterator it = classServices.find(clazz); + if (it != classServices.end()) + { + s = it->second.begin(); + send = it->second.end(); + } + else + { + return; + } + if (!filter.empty()) + { + ldap = LDAPExpr(filter); + } + } + + for (; s != send; ++s) + { + ServiceReference sri = s->GetReference(); + + if (filter.empty() || ldap.Evaluate(s->d->properties, false)) + { + res.push_back(sri); + } + } +} + +void ServiceRegistry::RemoveServiceRegistration(const ServiceRegistration& sr) +{ + MutexLocker lock(mutex); + + const std::list& classes = ref_any_cast >( + sr.d->properties[ServiceConstants::OBJECTCLASS()]); + services.erase(sr); + serviceRegistrations.remove(sr); + for (std::list::const_iterator i = classes.begin(); + i != classes.end(); ++i) + { + std::list& s = classServices[*i]; + if (s.size() > 1) + { + std::remove(s.begin(), s.end(), sr); + } + else + { + classServices.erase(*i); + } + } +} + +void ServiceRegistry::GetRegisteredByModule(ModulePrivate* p, + std::list& res) const +{ + MutexLocker lock(mutex); + + for (std::list::const_iterator i = serviceRegistrations.begin(); + i != serviceRegistrations.end(); ++i) + { + if (i->d->module == p) + { + res.push_back(*i); + } + } +} + +void ServiceRegistry::GetUsedByModule(Module* p, + std::list& res) const +{ + MutexLocker lock(mutex); + + for (std::list::const_iterator i = serviceRegistrations.begin(); + i != serviceRegistrations.end(); ++i) + { + if (i->d->IsUsedByModule(p)) + { + res.push_back(*i); + } + } +} + +} // end namespace mitk + diff --git a/Core/Code/Service/mitkServiceRegistry_p.h b/Core/Code/Service/mitkServiceRegistry_p.h new file mode 100644 index 0000000000..34c7938797 --- /dev/null +++ b/Core/Code/Service/mitkServiceRegistry_p.h @@ -0,0 +1,198 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICEREGISTRY_H +#define MITKSERVICEREGISTRY_H + +#include + +#include + +#include "mitkServiceRegistration.h" +#include "mitkServiceProperties.h" +#include "mitkServiceUtils.h" + +namespace mitk { + +class CoreModuleContext; +class ModulePrivate; + +struct HashServiceRegistration +{ + std::size_t operator()(const ServiceRegistration& s) const; +}; + +/** + * Here we handle all the MITK services that are registered. + */ +class ServiceRegistry +{ + +public: + + typedef itk::SimpleFastMutexLock MutexType; + + mutable MutexType mutex; + + /** + * Creates a new ServiceProperties object containing in + * with the keys converted to lower case. + * + * @param classes A list of class names which will be added to the + * created ServiceProperties object under the key + * ModuleConstants::OBJECTCLASS. + * @param sid A service id which will be used instead of a default one. + */ + static ServiceProperties CreateServiceProperties(const ServiceProperties& in, + const std::list& classes = std::list(), + long sid = -1); + +#ifdef MITK_HAS_UNORDERED_MAP_H + typedef std::unordered_map, HashServiceRegistration> MapServiceClasses; + typedef std::unordered_map > MapClassServices; +#else + typedef itk::hash_map, HashServiceRegistration> MapServiceClasses; + typedef itk::hash_map > MapClassServices; +#endif + + /** + * All registered services in the current framework. + * Mapping of registered service to class names under which + * the service is registerd. + */ + MapServiceClasses services; + + std::list serviceRegistrations; + + /** + * Mapping of classname to registered service. + * The List of registered services are ordered with the highest + * ranked service first. + */ + MapClassServices classServices; + + CoreModuleContext* core; + + ServiceRegistry(CoreModuleContext* coreCtx); + + ~ServiceRegistry(); + + void Clear(); + + /** + * Register a service in the framework wide register. + * + * @param module The module registering the service. + * @param classes The class names under which the service can be located. + * @param service The service object. + * @param properties The properties for this service. + * @return A ServiceRegistration object. + * @exception std::invalid_argument If one of the following is true: + *
    + *
  • The service object is 0.
  • + *
  • The service parameter is not a ServiceFactory or an + * instance of all the named classes in the classes parameter.
  • + *
+ */ + ServiceRegistration RegisterService(ModulePrivate* module, + const std::list& clazzes, + itk::LightObject* service, + const ServiceProperties& properties); + + /** + * Service ranking changed, reorder registered services + * according to ranking. + * + * @param serviceRegistration The ServiceRegistrationPrivate object. + * @param rank New rank of object. + */ + void UpdateServiceRegistrationOrder(const ServiceRegistration& sr, + const std::list& classes); + + /** + * Checks that a given service object is an instance of the given + * class name. + * + * @param service The service object to check. + * @param cls The class name to check for. + */ + bool CheckServiceClass(itk::LightObject* service, const std::string& cls) const; + + /** + * Get all services implementing a certain class. + * Only used internally by the framework. + * + * @param clazz The class name of the requested service. + * @return A sorted list of {@link ServiceRegistrationPrivate} objects. + */ + void Get(const std::string& clazz, std::list& serviceRegs) const; + + /** + * Get a service implementing a certain class. + * + * @param module The module requesting reference + * @param clazz The class name of the requested service. + * @return A {@link ServiceReference} object. + */ + ServiceReference Get(ModulePrivate* module, const std::string& clazz) const; + + /** + * Get all services implementing a certain class and then + * filter these with a property filter. + * + * @param clazz The class name of requested service. + * @param filter The property filter. + * @param module The module requesting reference. + * @return A list of {@link ServiceReference} object. + */ + void Get(const std::string& clazz, const std::string& filter, + ModulePrivate* module, std::list& serviceRefs) const; + + /** + * Remove a registered service. + * + * @param sr The ServiceRegistration object that is registered. + */ + void RemoveServiceRegistration(const ServiceRegistration& sr) ; + + /** + * Get all services that a module has registered. + * + * @param p The module + * @return A set of {@link ServiceRegistration} objects + */ + void GetRegisteredByModule(ModulePrivate* m, std::list& serviceRegs) const; + + /** + * Get all services that a module uses. + * + * @param p The module + * @return A set of {@link ServiceRegistration} objects + */ + void GetUsedByModule(Module* m, std::list& serviceRegs) const; + +private: + + void Get_Unlocked(const std::string& clazz, const std::string& filter, + ModulePrivate* module, std::list& serviceRefs) const; + +}; + +} + +#endif // MITKSERVICEREGISTRY_H diff --git a/Core/Code/Service/mitkServiceTracker.h b/Core/Code/Service/mitkServiceTracker.h new file mode 100644 index 0000000000..88efdc10f1 --- /dev/null +++ b/Core/Code/Service/mitkServiceTracker.h @@ -0,0 +1,429 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICETRACKER_H +#define MITKSERVICETRACKER_H + +#include "mitkCommon.h" + +#include "mitkServiceReference.h" +#include "mitkServiceTrackerCustomizer.h" +#include "mitkLDAPFilter.h" + +namespace mitk { + +template class TrackedService; +template class ServiceTrackerPrivate; +class ModuleContext; + +/** + * \ingroup MicroServices + * + * The ServiceTracker class simplifies using services from the + * framework's service registry. + *

+ * A ServiceTracker object is constructed with search criteria and + * a ServiceTrackerCustomizer object. A ServiceTracker + * can use a ServiceTrackerCustomizer to customize the service + * objects to be tracked. The ServiceTracker can then be opened to + * begin tracking all services in the framework's service registry that match + * the specified search criteria. The ServiceTracker correctly + * handles all of the details of listening to ServiceEvents and + * getting and ungetting services. + *

+ * The GetServiceReferences method can be called to get references + * to the services being tracked. The GetService and + * GetServices methods can be called to get the service objects for + * the tracked service. + *

+ * The ServiceTracker class is thread-safe. It does not call a + * ServiceTrackerCustomizer while holding any locks. + * ServiceTrackerCustomizer implementations must also be + * thread-safe. + * + * \tparam S The type of the service being tracked. The type must be an + * assignable datatype. Further, if the + * ServiceTracker(ModuleContext*, ServiceTrackerCustomizer*) + * constructor is used, the type must have an associated interface id via + * MITK_DECLARE_SERVICE_INTERFACE. + * \tparam T The type of the tracked object. The type must be an assignable + * datatype, provide a boolean conversion function, and provide + * a constructor and an assignment operator which can handle 0 as an argument. + * \remarks This class is thread safe. + */ +template +class ServiceTracker : protected ServiceTrackerCustomizer +{ +public: + + typedef std::map TrackingMap; + + ~ServiceTracker(); + + /** + * Create a ServiceTracker on the specified + * ServiceReference. + * + *

+ * The service referenced by the specified ServiceReference + * will be tracked by this ServiceTracker. + * + * @param context The ModuleContext against which the tracking + * is done. + * @param reference The ServiceReference for the service to be + * tracked. + * @param customizer The customizer object to call when services are added, + * modified, or removed in this ServiceTracker. If + * customizer is null, then this + * ServiceTracker will be used as the + * ServiceTrackerCustomizer and this + * ServiceTracker will call the + * ServiceTrackerCustomizer methods on itself. + */ + ServiceTracker(ModuleContext* context, + const ServiceReference& reference, + ServiceTrackerCustomizer* customizer = 0); + + /** + * Create a ServiceTracker on the specified class name. + * + *

+ * Services registered under the specified class name will be tracked by + * this ServiceTracker. + * + * @param context The ModuleContext against which the tracking + * is done. + * @param clazz The class name of the services to be tracked. + * @param customizer The customizer object to call when services are added, + * modified, or removed in this ServiceTracker. If + * customizer is null, then this + * ServiceTracker will be used as the + * ServiceTrackerCustomizer and this + * ServiceTracker will call the + * ServiceTrackerCustomizer methods on itself. + */ + ServiceTracker(ModuleContext* context, const std::string& clazz, + ServiceTrackerCustomizer* customizer = 0); + + /** + * Create a ServiceTracker on the specified + * LDAPFilter object. + * + *

+ * Services which match the specified LDAPFilter object will be + * tracked by this ServiceTracker. + * + * @param context The ModuleContext against which the tracking + * is done. + * @param filter The LDAPFilter to select the services to be + * tracked. + * @param customizer The customizer object to call when services are added, + * modified, or removed in this ServiceTracker. If + * customizer is null, then this ServiceTracker will be + * used as the ServiceTrackerCustomizer and this + * ServiceTracker will call the + * ServiceTrackerCustomizer methods on itself. + */ + ServiceTracker(ModuleContext* context, const LDAPFilter& filter, + ServiceTrackerCustomizer* customizer = 0); + + /** + * Create a ServiceTracker on the class template + * argument S. + * + *

+ * Services registered under the interface name of the class template + * argument S will be tracked by this ServiceTracker. + * + * @param context The ModuleContext against which the tracking + * is done. + * @param customizer The customizer object to call when services are added, + * modified, or removed in this ServiceTracker. If + * customizer is null, then this ServiceTracker will be + * used as the ServiceTrackerCustomizer and this + * ServiceTracker will call the + * ServiceTrackerCustomizer methods on itself. + */ + ServiceTracker(ModuleContext* context, ServiceTrackerCustomizer* customizer = 0); + + /** + * Open this ServiceTracker and begin tracking services. + * + *

+ * Services which match the search criteria specified when this + * ServiceTracker was created are now tracked by this + * ServiceTracker. + * + * @throws std::logic_error If the ModuleContext + * with which this ServiceTracker was created is no + * longer valid. + */ + virtual void Open(); + + /** + * Close this ServiceTracker. + * + *

+ * This method should be called when this ServiceTracker should + * end the tracking of services. + * + *

+ * This implementation calls GetServiceReferences() to get the list + * of tracked services to remove. + */ + virtual void Close(); + + /** + * Wait for at least one service to be tracked by this + * ServiceTracker. This method will also return when this + * ServiceTracker is closed. + * + *

+ * It is strongly recommended that WaitForService is not used + * during the calling of the ModuleActivator methods. + * ModuleActivator methods are expected to complete in a short + * period of time. + * + *

+ * This implementation calls GetService() to determine if a service + * is being tracked. + * + * @return Returns the result of GetService(). + */ + virtual T WaitForService(); + + /** + * Return a list of ServiceReferences for all services being + * tracked by this ServiceTracker. + * + * @param refs List of ServiceReferences. + */ + virtual void GetServiceReferences(std::list& refs) const; + + /** + * Returns a ServiceReference for one of the services being + * tracked by this ServiceTracker. + * + *

+ * If multiple services are being tracked, the service with the highest + * ranking (as specified in its service.ranking property) is + * returned. If there is a tie in ranking, the service with the lowest + * service ID (as specified in its service.id property); that + * is, the service that was registered first is returned. This is the same + * algorithm used by ModuleContext::GetServiceReference(). + * + *

+ * This implementation calls GetServiceReferences() to get the list + * of references for the tracked services. + * + * @return A ServiceReference for a tracked service. + * @throws ServiceException if no services are being tracked. + */ + virtual ServiceReference GetServiceReference() const; + + /** + * Returns the service object for the specified + * ServiceReference if the specified referenced service is + * being tracked by this ServiceTracker. + * + * @param reference The reference to the desired service. + * @return A service object or null if the service referenced + * by the specified ServiceReference is not being + * tracked. + */ + virtual T GetService(const ServiceReference& reference) const; + + /** + * Return a list of service objects for all services being tracked by this + * ServiceTracker. + * + *

+ * This implementation calls GetServiceReferences() to get the list + * of references for the tracked services and then calls + * GetService(const ServiceReference&) for each reference to get the + * tracked service object. + * + * @param services A list of service objects or an empty list if no services + * are being tracked. + */ + virtual void GetServices(std::list& services) const; + + /** + * Returns a service object for one of the services being tracked by this + * ServiceTracker. + * + *

+ * If any services are being tracked, this implementation returns the result + * of calling %GetService(%GetServiceReference()). + * + * @return A service object or null if no services are being + * tracked. + */ + virtual T GetService() const; + + /** + * Remove a service from this ServiceTracker. + * + * The specified service will be removed from this + * ServiceTracker. If the specified service was being tracked + * then the ServiceTrackerCustomizer::RemovedService method will + * be called for that service. + * + * @param reference The reference to the service to be removed. + */ + virtual void Remove(const ServiceReference& reference); + + /** + * Return the number of services being tracked by this + * ServiceTracker. + * + * @return The number of services being tracked. + */ + virtual int Size() const; + + /** + * Returns the tracking count for this ServiceTracker. + * + * The tracking count is initialized to 0 when this + * ServiceTracker is opened. Every time a service is added, + * modified or removed from this ServiceTracker, the tracking + * count is incremented. + * + *

+ * The tracking count can be used to determine if this + * ServiceTracker has added, modified or removed a service by + * comparing a tracking count value previously collected with the current + * tracking count value. If the value has not changed, then no service has + * been added, modified or removed from this ServiceTracker + * since the previous tracking count was collected. + * + * @return The tracking count for this ServiceTracker or -1 if + * this ServiceTracker is not open. + */ + virtual int GetTrackingCount() const; + + /** + * Return a sorted map of the ServiceReferences and + * service objects for all services being tracked by this + * ServiceTracker. The map is sorted in natural order + * of ServiceReference. That is, the last entry is the service + * with the highest ranking and the lowest service id. + * + * @param tracked A TrackingMap with the ServiceReferences + * and service objects for all services being tracked by this + * ServiceTracker. If no services are being tracked, + * then the returned map is empty. + */ + virtual void GetTracked(TrackingMap& tracked) const; + + /** + * Return if this ServiceTracker is empty. + * + * @return true if this ServiceTracker is not tracking any + * services. + */ + virtual bool IsEmpty() const; + +protected: + + /** + * Default implementation of the + * ServiceTrackerCustomizer::AddingService method. + * + *

+ * This method is only called when this ServiceTracker has been + * constructed with a null ServiceTrackerCustomizer argument. + * + *

+ * This implementation returns the result of calling GetService + * on the ModuleContext with which this + * ServiceTracker was created passing the specified + * ServiceReference. + *

+ * This method can be overridden in a subclass to customize the service + * object to be tracked for the service being added. In that case, take care + * not to rely on the default implementation of + * \link RemovedService(const ServiceReference&, T service) removedService\endlink + * to unget the service. + * + * @param reference The reference to the service being added to this + * ServiceTracker. + * @return The service object to be tracked for the service added to this + * ServiceTracker. + * @see ServiceTrackerCustomizer::AddingService(const ServiceReference&) + */ + T AddingService(const ServiceReference& reference); + + /** + * Default implementation of the + * ServiceTrackerCustomizer::ModifiedService method. + * + *

+ * This method is only called when this ServiceTracker has been + * constructed with a null ServiceTrackerCustomizer argument. + * + *

+ * This implementation does nothing. + * + * @param reference The reference to modified service. + * @param service The service object for the modified service. + * @see ServiceTrackerCustomizer::ModifiedService(const ServiceReference&, itk::LighObject*) + */ + void ModifiedService(const ServiceReference& reference, T service); + + /** + * Default implementation of the + * ServiceTrackerCustomizer::RemovedService method. + * + *

+ * This method is only called when this ServiceTracker has been + * constructed with a null ServiceTrackerCustomizer argument. + * + *

+ * This implementation calls UngetService, on the + * ModuleContext with which this ServiceTracker + * was created, passing the specified ServiceReference. + *

+ * This method can be overridden in a subclass. If the default + * implementation of \link AddingService(const ServiceReference&) AddingService\endlink + * method was used, this method must unget the service. + * + * @param reference The reference to removed service. + * @param service The service object for the removed service. + * @see ServiceTrackerCustomizer::RemovedService(const ServiceReference&, itk::LighObject*) + */ + void RemovedService(const ServiceReference& reference, T service); + +private: + + typedef ServiceTracker _ServiceTracker; + typedef TrackedService _TrackedService; + typedef ServiceTrackerPrivate _ServiceTrackerPrivate; + typedef ServiceTrackerCustomizer _ServiceTrackerCustomizer; + + friend class TrackedService; + friend class ServiceTrackerPrivate; + + _ServiceTrackerPrivate* const d; +}; + +} + +#include "mitkServiceTracker.tpp" + +#endif // MITKSERVICETRACKER_H diff --git a/Core/Code/Service/mitkServiceTracker.tpp b/Core/Code/Service/mitkServiceTracker.tpp new file mode 100644 index 0000000000..54871059f7 --- /dev/null +++ b/Core/Code/Service/mitkServiceTracker.tpp @@ -0,0 +1,436 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "mitkServiceTrackerPrivate.h" +#include "mitkTrackedService.h" +#include "mitkServiceException.h" +#include "mitkModuleContext.h" + +#include +#include + +namespace mitk { + +template +ServiceTracker::~ServiceTracker() +{ + delete d; +} + +template +ServiceTracker::ServiceTracker(ModuleContext* context, + const ServiceReference& reference, + _ServiceTrackerCustomizer* customizer) + : d(new _ServiceTrackerPrivate(this, context, reference, customizer)) +{ +} + +template +ServiceTracker::ServiceTracker(ModuleContext* context, const std::string& clazz, + _ServiceTrackerCustomizer* customizer) + : d(new _ServiceTrackerPrivate(this, context, clazz, customizer)) +{ +} + +template +ServiceTracker::ServiceTracker(ModuleContext* context, const LDAPFilter& filter, + _ServiceTrackerCustomizer* customizer) + : d(new _ServiceTrackerPrivate(this, context, filter, customizer)) +{ +} + +template +ServiceTracker::ServiceTracker(ModuleContext *context, ServiceTrackerCustomizer *customizer) + : d(new _ServiceTrackerPrivate(this, context, mitk_service_interface_iid(), customizer)) +{ + const char* clazz = mitk_service_interface_iid(); + if (clazz == 0) throw ServiceException("The service interface class has no MITK_DECLARE_SERVICE_INTERFACE macro"); +} + +template +void ServiceTracker::Open() +{ + itk::SmartPointer<_TrackedService> t; + { + MutexLocker lock(d->mutex); + if (d->trackedService) + { + return; + } + + MITK_DEBUG(d->DEBUG) << "ServiceTracker::Open: " << d->filter; + + t = itk::SmartPointer<_TrackedService>( + new _TrackedService(this, d->customizer)); + { + itk::MutexLockHolder lockT(*t); + try { + d->context->AddServiceListener(t.GetPointer(), &_TrackedService::ServiceChanged, d->listenerFilter); + std::list references; + if (!d->trackClass.empty()) + { + references = d->GetInitialReferences(d->trackClass, std::string()); + } + else + { + if (d->trackReference.GetModule() != 0) + { + references.push_back(d->trackReference); + } + else + { /* user supplied filter */ + references = d->GetInitialReferences(std::string(), + (d->listenerFilter.empty()) ? d->filter.ToString() : d->listenerFilter); + } + } + /* set tracked with the initial references */ + t->SetInitial(references); + } + catch (const std::invalid_argument& e) + { + throw std::runtime_error(std::string("unexpected std::invalid_argument exception: ") + + e.what()); + } + } + d->trackedService = t; + } + /* Call tracked outside of synchronized region */ + t->TrackInitial(); /* process the initial references */ +} + +template +void ServiceTracker::Close() +{ + itk::SmartPointer<_TrackedService> outgoing; + std::list references; + { + MutexLocker lock(d->mutex); + outgoing = d->trackedService; + if (outgoing.IsNull()) + { + return; + } + MITK_DEBUG(d->DEBUG) << "ServiceTracker::close:" << d->filter; + outgoing->Close(); + GetServiceReferences(references); + d->trackedService = 0; + try + { + d->context->RemoveServiceListener(outgoing.GetPointer(), &_TrackedService::ServiceChanged); + } + catch (const std::logic_error& /*e*/) + { + /* In case the context was stopped. */ + } + } + d->Modified(); /* clear the cache */ + { + itk::MutexLockHolder lockT(*outgoing); + outgoing->WakeAll(); /* wake up any waiters */ + } + for(std::list::const_iterator ref = references.begin(); + ref != references.end(); ++ref) + { + outgoing->Untrack(*ref, ServiceEvent()); + } + + if (d->DEBUG) + { + MutexLocker lock(d->mutex); + if ((d->cachedReference.GetModule() == 0) && (d->cachedService == 0)) + { + MITK_DEBUG(true) << "ServiceTracker::close[cached cleared]:" + << d->filter; + } + } +} + +template +T ServiceTracker::WaitForService() +{ + T object = GetService(); + while (object == 0) + { + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return 0; + } + { + itk::MutexLockHolder lockT(*t); + if (t->Size() == 0) + { + t->Wait(); + } + } + object = GetService(); + } + return object; +} + +template +void ServiceTracker::GetServiceReferences(std::list& refs) const +{ + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return; + } + { + itk::MutexLockHolder lockT(*t); + if (t->Size() == 0) + { + return; + } + t->GetTracked(refs); + } +} + +template +ServiceReference ServiceTracker::GetServiceReference() const +{ + ServiceReference reference(0); + { + MutexLocker lock(d->mutex); + reference = d->cachedReference; + } + if (reference.GetModule() != 0) + { + MITK_DEBUG(d->DEBUG) << "ServiceTracker::getServiceReference[cached]:" + << d->filter; + return reference; + } + MITK_DEBUG(d->DEBUG) << "ServiceTracker::getServiceReference:" << d->filter; + std::list references; + GetServiceReferences(references); + int length = references.size(); + if (length == 0) + { /* if no service is being tracked */ + throw ServiceException("No service is being tracked"); + } + std::list::const_iterator selectedRef; + if (length > 1) + { /* if more than one service, select highest ranking */ + std::vector rankings(length); + int count = 0; + int maxRanking = std::numeric_limits::min(); + std::list::const_iterator refIter = references.begin(); + for (int i = 0; i < length; i++) + { + bool ok = false; + Any rankingAny = refIter->GetProperty(ServiceConstants::SERVICE_RANKING()); + int ranking = 0; + if (rankingAny.Type() == typeid(int)) + { + ranking = any_cast(rankingAny); + ok = true; + } + + rankings[i] = ranking; + if (ranking > maxRanking) + { + selectedRef = refIter; + maxRanking = ranking; + count = 1; + } + else + { + if (ranking == maxRanking) + { + count++; + } + } + } + if (count > 1) + { /* if still more than one service, select lowest id */ + long int minId = std::numeric_limits::max(); + for (int i = 0; i < length; i++) + { + if (rankings[i] == maxRanking) + { + Any idAny = refIter->GetProperty(ServiceConstants::SERVICE_ID()); + long int id = 0; + if (idAny.Type() == typeid(long int)) + { + id = any_cast(idAny); + } + if (id < minId) + { + selectedRef = refIter; + minId = id; + } + } + } + } + ++refIter; + } + + { + MutexLocker lock(d->mutex); + d->cachedReference = *selectedRef; + return d->cachedReference; + } +} + +template +T ServiceTracker::GetService(const ServiceReference& reference) const +{ + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return 0; + } + { + itk::MutexLockHolder lockT(*t); + return t->GetCustomizedObject(reference); + } +} + +template +void ServiceTracker::GetServices(std::list& services) const +{ + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return; + } + { + itk::MutexLockHolder lockT(*t); + std::list references; + GetServiceReferences(references); + for(std::list::const_iterator ref = references.begin(); + ref != references.end(); ++ref) + { + services.push_back(GetService(*ref)); + } + } +} + +template +T ServiceTracker::GetService() const +{ + T service = d->cachedService; + if (service != 0) + { + MITK_DEBUG(d->DEBUG) << "ServiceTracker::getService[cached]:" + << d->filter; + return service; + } + MITK_DEBUG(d->DEBUG) << "ServiceTracker::getService:" << d->filter; + + try + { + ServiceReference reference = GetServiceReference(); + if (reference.GetModule() == 0) + { + return 0; + } + return d->cachedService = GetService(reference); + } + catch (const ServiceException&) + { + return 0; + } +} + +template +void ServiceTracker::Remove(const ServiceReference& reference) +{ + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return; + } + t->Untrack(reference, ServiceEvent()); +} + +template +int ServiceTracker::Size() const +{ + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return 0; + } + { + itk::MutexLockHolder lockT(*t); + return t->Size(); + } +} + +template +int ServiceTracker::GetTrackingCount() const +{ + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return -1; + } + { + itk::MutexLockHolder lockT(*t); + return t->GetTrackingCount(); + } +} + +template +void ServiceTracker::GetTracked(TrackingMap& map) const +{ + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return; + } + { + itk::MutexLockHolder lockT(*t); + t->CopyEntries(map); + } +} + +template +bool ServiceTracker::IsEmpty() const +{ + itk::SmartPointer<_TrackedService> t = d->Tracked(); + if (t.IsNull()) + { /* if ServiceTracker is not open */ + return true; + } + { + itk::MutexLockHolder lockT(*t); + return t->IsEmpty(); + } +} + +template +T ServiceTracker::AddingService(const ServiceReference& reference) +{ + return dynamic_cast(d->context->GetService(reference)); +} + +template +void ServiceTracker::ModifiedService(const ServiceReference& /*reference*/, T /*service*/) +{ + /* do nothing */ +} + +template +void ServiceTracker::RemovedService(const ServiceReference& reference, T /*service*/) +{ + d->context->UngetService(reference); +} + +} // end namespace mitk diff --git a/Core/Code/Service/mitkServiceTrackerCustomizer.h b/Core/Code/Service/mitkServiceTrackerCustomizer.h new file mode 100644 index 0000000000..8d055dc0db --- /dev/null +++ b/Core/Code/Service/mitkServiceTrackerCustomizer.h @@ -0,0 +1,109 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICETRACKERCUSTOMIZER_H +#define MITKSERVICETRACKERCUSTOMIZER_H + +#include "mitkServiceReference.h" + +namespace mitk { + +/** + * \ingroup MicroServices + * + * The ServiceTrackerCustomizer interface allows a + * ServiceTracker to customize the service objects that are + * tracked. A ServiceTrackerCustomizer is called when a service is + * being added to a ServiceTracker. The + * ServiceTrackerCustomizer can then return an object for the + * tracked service. A ServiceTrackerCustomizer is also called when + * a tracked service is modified or has been removed from a + * ServiceTracker. + * + *

+ * The methods in this interface may be called as the result of a + * ServiceEvent being received by a ServiceTracker. + * Since ServiceEvents are synchronously delivered, + * it is highly recommended that implementations of these methods do + * not register (ModuleContext::RegisterService), modify ( + * ServiceRegistration::SetProperties) or unregister ( + * ServiceRegistration::Unregister) a service while being + * synchronized on any object. + * + *

+ * The ServiceTracker class is thread-safe. It does not call a + * ServiceTrackerCustomizer while holding any locks. + * ServiceTrackerCustomizer implementations must also be + * thread-safe. + * + * \tparam T The type of the tracked object. + * \remarks This class is thread safe. + */ +template +struct ServiceTrackerCustomizer { + + virtual ~ServiceTrackerCustomizer() {} + + /** + * A service is being added to the ServiceTracker. + * + *

+ * This method is called before a service which matched the search + * parameters of the ServiceTracker is added to the + * ServiceTracker. This method should return the service object + * to be tracked for the specified ServiceReference. The + * returned service object is stored in the ServiceTracker and + * is available from the GetService and + * GetServices methods. + * + * @param reference The reference to the service being added to the + * ServiceTracker. + * @return The service object to be tracked for the specified referenced + * service or 0 if the specified referenced service + * should not be tracked. + */ + virtual T AddingService(const ServiceReference& reference) = 0; + + /** + * A service tracked by the ServiceTracker has been modified. + * + *

+ * This method is called when a service being tracked by the + * ServiceTracker has had it properties modified. + * + * @param reference The reference to the service that has been modified. + * @param service The service object for the specified referenced service. + */ + virtual void ModifiedService(const ServiceReference& reference, T service) = 0; + + /** + * A service tracked by the ServiceTracker has been removed. + * + *

+ * This method is called after a service is no longer being tracked by the + * ServiceTracker. + * + * @param reference The reference to the service that has been removed. + * @param service The service object for the specified referenced service. + */ + virtual void RemovedService(const ServiceReference& reference, T service) = 0; +}; + +} + +#endif // MITKSERVICETRACKERCUSTOMIZER_H diff --git a/Core/Code/Service/mitkServiceTrackerPrivate.h b/Core/Code/Service/mitkServiceTrackerPrivate.h new file mode 100644 index 0000000000..a4ccf33b03 --- /dev/null +++ b/Core/Code/Service/mitkServiceTrackerPrivate.h @@ -0,0 +1,170 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKSERVICETRACKERPRIVATE_H +#define MITKSERVICETRACKERPRIVATE_H + +#include "mitkServiceReference.h" +#include "mitkLDAPFilter.h" + +#include + +namespace mitk { + +/** + * \ingroup MicroServices + */ +template +class ServiceTrackerPrivate +{ + +public: + + typedef itk::SimpleFastMutexLock MutexType; + + ServiceTrackerPrivate(ServiceTracker* st, + ModuleContext* context, + const ServiceReference& reference, + ServiceTrackerCustomizer* customizer); + + ServiceTrackerPrivate(ServiceTracker* st, + ModuleContext* context, const std::string& clazz, + ServiceTrackerCustomizer* customizer); + + ServiceTrackerPrivate(ServiceTracker* st, + ModuleContext* context, const LDAPFilter& filter, + ServiceTrackerCustomizer* customizer); + + ~ServiceTrackerPrivate(); + + /** + * Returns the list of initial ServiceReferences that will be + * tracked by this ServiceTracker. + * + * @param className The class name with which the service was registered, or + * null for all services. + * @param filterString The filter criteria or null for all + * services. + * @return The list of initial ServiceReferences. + * @throws std::invalid_argument If the specified filterString has an + * invalid syntax. + */ + std::list GetInitialReferences(const std::string& className, + const std::string& filterString); + + /* set this to true to compile in debug messages */ + static const bool DEBUG; // = false; + + /** + * The Module Context used by this ServiceTracker. + */ + ModuleContext* const context; + + /** + * The filter used by this ServiceTracker which specifies the + * search criteria for the services to track. + */ + LDAPFilter filter; + + /** + * The ServiceTrackerCustomizer for this tracker. + */ + ServiceTrackerCustomizer* customizer; + + /** + * Filter string for use when adding the ServiceListener. If this field is + * set, then certain optimizations can be taken since we don't have a user + * supplied filter. + */ + std::string listenerFilter; + + /** + * Class name to be tracked. If this field is set, then we are tracking by + * class name. + */ + std::string trackClass; + + /** + * Reference to be tracked. If this field is set, then we are tracking a + * single ServiceReference. + */ + ServiceReference trackReference; + + /** + * Tracked services: ServiceReference -> customized Object and + * ServiceListenerEntry object + */ + itk::SmartPointer > trackedService; + + /** + * Accessor method for the current TrackedService object. This method is only + * intended to be used by the unsynchronized methods which do not modify the + * trackedService field. + * + * @return The current Tracked object. + */ + itk::SmartPointer > Tracked() const; + + /** + * Called by the TrackedService object whenever the set of tracked services is + * modified. Clears the cache. + */ + /* + * This method must not be synchronized since it is called by TrackedService while + * TrackedService is synchronized. We don't want synchronization interactions + * between the listener thread and the user thread. + */ + void Modified(); + + /** + * Cached ServiceReference for getServiceReference. + */ + mutable ServiceReference cachedReference; + + /** + * Cached service object for GetService. + * + * This field is volatile since it is accessed by multiple threads. + */ + mutable T volatile cachedService; + + mutable MutexType mutex; + +private: + + inline ServiceTracker* q_func() + { + return static_cast *>(q_ptr); + } + + inline const ServiceTracker* q_func() const + { + return static_cast *>(q_ptr); + } + + friend class ServiceTracker; + + ServiceTracker * const q_ptr; + +}; + +} + +#include "mitkServiceTrackerPrivate.tpp" + +#endif // MITKSERVICETRACKERPRIVATE_H diff --git a/Core/Code/Service/mitkServiceTrackerPrivate.tpp b/Core/Code/Service/mitkServiceTrackerPrivate.tpp new file mode 100644 index 0000000000..bc56586828 --- /dev/null +++ b/Core/Code/Service/mitkServiceTrackerPrivate.tpp @@ -0,0 +1,128 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "mitkTrackedService.h" + +#include "mitkModuleContext.h" +#include "mitkLDAPFilter.h" + +#include + +namespace mitk { + +template +const bool ServiceTrackerPrivate::DEBUG = true; + +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, ModuleContext* context, + const ServiceReference& reference, + ServiceTrackerCustomizer* customizer) + : context(context), customizer(customizer), trackReference(reference), + trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) +{ + this->customizer = customizer ? customizer : q_func(); + this->listenerFilter = std::string("(") + ServiceConstants::SERVICE_ID() + + "=" + any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())) + ")"; + try + { + this->filter = LDAPFilter(listenerFilter); + } + catch (const std::invalid_argument& e) + { + /* + * we could only get this exception if the ServiceReference was + * invalid + */ + std::invalid_argument ia(std::string("unexpected std::invalid_argument exception: ") + e.what()); + throw ia; + } +} + +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, + ModuleContext* context, const std::string& clazz, + ServiceTrackerCustomizer* customizer) + : context(context), customizer(customizer), trackClass(clazz), + trackReference(0), trackedService(0), cachedReference(0), + cachedService(0), q_ptr(st) +{ + this->customizer = customizer ? customizer : q_func(); + this->listenerFilter = std::string("(") + mitk::ServiceConstants::OBJECTCLASS() + "=" + + clazz + ")"; + try + { + this->filter = LDAPFilter(listenerFilter); + } + catch (const std::invalid_argument& e) + { + /* + * we could only get this exception if the clazz argument was + * malformed + */ + std::invalid_argument ia( + std::string("unexpected std::invalid_argument exception: ") + e.what()); + throw ia; + } +} + +template +ServiceTrackerPrivate::ServiceTrackerPrivate( + ServiceTracker* st, + ModuleContext* context, const LDAPFilter& filter, + ServiceTrackerCustomizer* customizer) + : context(context), filter(filter), customizer(customizer), + listenerFilter(filter.ToString()), trackReference(0), + trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) +{ + this->customizer = customizer ? customizer : q_func(); + if (context == 0) + { + throw std::invalid_argument("The module context cannot be null."); + } +} + +template +ServiceTrackerPrivate::~ServiceTrackerPrivate() +{ + +} + +template +std::list ServiceTrackerPrivate::GetInitialReferences( + const std::string& className, const std::string& filterString) +{ + return context->GetServiceReferences(className, filterString); +} + +template +itk::SmartPointer > ServiceTrackerPrivate::Tracked() const +{ + return trackedService; +} + +template +void ServiceTrackerPrivate::Modified() +{ + cachedReference = 0; /* clear cached value */ + cachedService = 0; /* clear cached value */ + MITK_DEBUG(DEBUG) << "ServiceTracker::Modified(): " << filter; +} + +} // end namespace mitk diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Core/Code/Service/mitkServiceUtils.h similarity index 52% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Core/Code/Service/mitkServiceUtils.h index c09a6d26ee..9701f9506f 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Core/Code/Service/mitkServiceUtils.h @@ -1,33 +1,51 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +Date: $Date$ +Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#ifndef MITKSERVICEUTILS_H +#define MITKSERVICEUTILS_H -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog -{ - Q_OBJECT +#ifndef MITK_HAS_HASH_STRING + +#ifdef MITK_HAS_UNORDERED_MAP_H +#include +namespace std { +#else - public: +#include "mitkItkHashMap.h" +#if defined(__GNUC__) +namespace __gnu_cxx { +#else +namespace itk { +#endif - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); +#endif // MITK_HAS_UNORDERED_MAP_H +template<> +struct hash +{ + std::size_t operator()(const std::string& str) const + { + return hash()(str.c_str()); + } }; + +} + +#endif // MITK_HAS_HASH_STRING + +#endif // MITKSERVICEUTILS_H diff --git a/Core/Code/Service/mitkSharedData.h b/Core/Code/Service/mitkSharedData.h new file mode 100644 index 0000000000..f4f81e5bae --- /dev/null +++ b/Core/Code/Service/mitkSharedData.h @@ -0,0 +1,262 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +Modified version of qshareddata.h from Qt 4.7.3 for MITK. +Original copyright (c) Nokia Corporation. Usage covered by the +GNU Lesser General Public License version 2.1 +(http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) and the Nokia Qt +LGPL Exception version 1.1 (file LGPL_EXCEPTION.txt in Qt 4.7.3 package). + +=========================================================================*/ + +#ifndef MITKSHAREDDATA_H +#define MITKSHAREDDATA_H + +#include +#include + +#include +#include "mitkAtomicInt.h" + +namespace mitk { + +template class SharedDataPointer; + +class MITK_CORE_EXPORT SharedData +{ +public: + mutable AtomicInt ref; + + inline SharedData() : ref(0) { } + inline SharedData(const SharedData&) : ref(0) { } + +private: + // using the assignment operator would lead to corruption in the ref-counting + SharedData& operator=(const SharedData&); +}; + +template class SharedDataPointer +{ +public: + typedef T Type; + typedef T* pointer; + + inline void Detach() { if (d && d->ref != 1) Detach_helper(); } + inline T& operator*() { Detach(); return *d; } + inline const T& operator*() const { return *d; } + inline T* operator->() { Detach(); return d; } + inline const T* operator->() const { return d; } + inline operator T*() { Detach(); return d; } + inline operator const T*() const { return d; } + inline T* Data() { Detach(); return d; } + inline const T* Data() const { return d; } + inline const T* ConstData() const { return d; } + + inline bool operator==(const SharedDataPointer& other) const { return d == other.d; } + inline bool operator!=(const SharedDataPointer& other) const { return d != other.d; } + + inline SharedDataPointer() { d = 0; } + inline ~SharedDataPointer() { if (d && !d->ref.Deref()) delete d; } + + explicit SharedDataPointer(T* data); + inline SharedDataPointer(const SharedDataPointer& o) : d(o.d) { if (d) d->ref.Ref(); } + + inline SharedDataPointer & operator=(const SharedDataPointer& o) + { + if (o.d != d) + { + if (o.d) + o.d->ref.Ref(); + T *old = d; + d = o.d; + if (old && !old->ref.Deref()) + delete old; + } + return *this; + } + + inline SharedDataPointer &operator=(T *o) + { + if (o != d) + { + if (o) + o->ref.Ref(); + T *old = d; + d = o; + if (old && !old->ref.Deref()) + delete old; + } + return *this; + } + + inline bool operator!() const { return !d; } + + inline void Swap(SharedDataPointer& other) + { + using std::swap; + swap(d, other.d); + } + +protected: + T* Clone(); + +private: + void Detach_helper(); + + T *d; +}; + +template class ExplicitlySharedDataPointer +{ +public: + typedef T Type; + typedef T* pointer; + + inline T& operator*() const { return *d; } + inline T* operator->() { return d; } + inline T* operator->() const { return d; } + inline T* Data() const { return d; } + inline const T* ConstData() const { return d; } + + inline void Detach() { if (d && d->ref != 1) Detach_helper(); } + + inline void Reset() + { + if(d && !d->ref.Deref()) + delete d; + + d = 0; + } + + inline operator bool () const { return d != 0; } + + inline bool operator==(const ExplicitlySharedDataPointer& other) const { return d == other.d; } + inline bool operator!=(const ExplicitlySharedDataPointer& other) const { return d != other.d; } + inline bool operator==(const T* ptr) const { return d == ptr; } + inline bool operator!=(const T* ptr) const { return d != ptr; } + + inline ExplicitlySharedDataPointer() { d = 0; } + inline ~ExplicitlySharedDataPointer() { if (d && !d->ref.Deref()) delete d; } + + explicit ExplicitlySharedDataPointer(T* data); + inline ExplicitlySharedDataPointer(const ExplicitlySharedDataPointer &o) + : d(o.d) { if (d) d->ref.Ref(); } + + template + inline ExplicitlySharedDataPointer(const ExplicitlySharedDataPointer& o) + : d(static_cast(o.Data())) + { + if(d) + d->ref.Ref(); + } + + inline ExplicitlySharedDataPointer& operator=(const ExplicitlySharedDataPointer& o) + { + if (o.d != d) + { + if (o.d) + o.d->ref.Ref(); + T *old = d; + d = o.d; + if (old && !old->ref.Deref()) + delete old; + } + return *this; + } + + inline ExplicitlySharedDataPointer& operator=(T* o) + { + if (o != d) + { + if (o) + o->ref.Ref(); + T *old = d; + d = o; + if (old && !old->ref.Deref()) + delete old; + } + return *this; + } + + inline bool operator!() const { return !d; } + + inline void Swap(ExplicitlySharedDataPointer& other) + { + using std::swap; + swap(d, other.d); + } + +protected: + T* Clone(); + +private: + void Detach_helper(); + + T *d; +}; + + +template +SharedDataPointer::SharedDataPointer(T* adata) : d(adata) +{ if (d) d->ref.Ref(); } + +template +T* SharedDataPointer::Clone() +{ + return new T(*d); +} + +template +void SharedDataPointer::Detach_helper() +{ + T *x = Clone(); + x->ref.Ref(); + if (!d->ref.Deref()) + delete d; + d = x; +} + +template +T* ExplicitlySharedDataPointer::Clone() +{ + return new T(*d); +} + +template +void ExplicitlySharedDataPointer::Detach_helper() +{ + T *x = Clone(); + x->ref.Ref(); + if (!d->ref.Deref()) + delete d; + d = x; +} + +template +ExplicitlySharedDataPointer::ExplicitlySharedDataPointer(T* adata) + : d(adata) +{ if (d) d->ref.Ref(); } + +template +void swap(mitk::SharedDataPointer& p1, mitk::SharedDataPointer& p2) +{ p1.Swap(p2); } + +template +void swap(mitk::ExplicitlySharedDataPointer& p1, mitk::ExplicitlySharedDataPointer& p2) +{ p1.Swap(p2); } + +} + +#endif // MITKSHAREDDATA_H diff --git a/Core/Code/Service/mitkStaticInit.h b/Core/Code/Service/mitkStaticInit.h new file mode 100644 index 0000000000..86b1634786 --- /dev/null +++ b/Core/Code/Service/mitkStaticInit.h @@ -0,0 +1,123 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +Extracted from qglobal.h from Qt 4.7.3 and adapted for MITK. +Original copyright (c) Nokia Corporation. Usage covered by the +GNU Lesser General Public License version 2.1 +(http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) and the Nokia Qt +LGPL Exception version 1.1 (file LGPL_EXCEPTION.txt in Qt 4.7.3 package). + +=========================================================================*/ + +#ifndef MITK_STATIC_INIT_H +#define MITK_STATIC_INIT_H + +#include + +namespace mitk { + +// POD for MITK_GLOBAL_STATIC +template +class GlobalStatic +{ +public: + T* pointer; + bool destroyed; + + // Guards acces to "pointer". If a "atomic pointer" class is available, + // this should be used instead of an explicit mutex. + itk::SimpleFastMutexLock mutex; +}; + +// Created as a function-local static to delete a GlobalStatic +template +class GlobalStaticDeleter +{ +public: + GlobalStatic &globalStatic; + + GlobalStaticDeleter(GlobalStatic &_globalStatic) + : globalStatic(_globalStatic) + { } + + inline ~GlobalStaticDeleter() + { + delete globalStatic.pointer; + globalStatic.pointer = 0; + globalStatic.destroyed = true; + } +}; + +} // namespace mitk + +#define MITK_GLOBAL_STATIC_INIT(TYPE, NAME) \ + static ::mitk::GlobalStatic& this_##NAME() \ + { \ + static ::mitk::GlobalStatic l = \ + { 0, false, itk::SimpleFastMutexLock() }; \ + return l; \ + } + +#define MITK_GLOBAL_STATIC(TYPE, NAME) \ + MITK_GLOBAL_STATIC_INIT(TYPE, NAME) \ + static TYPE *NAME() \ + { \ + if (!this_##NAME().pointer && !this_##NAME().destroyed) \ + { \ + TYPE *x = new TYPE; \ + bool ok = false; \ + { \ + this_##NAME().mutex.Lock(); \ + if (!this_##NAME().pointer) \ + { \ + this_##NAME().pointer = x; \ + ok = true; \ + } \ + this_##NAME().mutex.Unlock(); \ + } \ + if (!ok) \ + delete x; \ + else \ + static ::mitk::GlobalStaticDeleter cleanup(this_##NAME());\ + } \ + return this_##NAME().pointer; \ + } + +#define MITK_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS) \ + MITK_GLOBAL_STATIC_INIT(TYPE, NAME) \ + static TYPE *NAME() \ + { \ + if (!this_##NAME().pointer && !this_##NAME().destroyed) \ + { \ + TYPE *x = new TYPE ARGS; \ + bool ok = false; \ + { \ + this_##NAME().mutex.Lock(); \ + if (!this_##NAME().pointer) \ + { \ + this_##NAME().pointer = x; \ + ok = true; \ + } \ + this_##NAME().mutex.Unlock(); \ + } \ + if (!ok) \ + delete x; \ + else \ + static ::mitk::GlobalStaticDeleter cleanup(this_##NAME());\ + } \ + return this_##NAME().pointer; \ + } + +#endif // MITK_STATIC_INIT_H diff --git a/Core/Code/Service/mitkTrackedService.h b/Core/Code/Service/mitkTrackedService.h new file mode 100644 index 0000000000..56acf94ee3 --- /dev/null +++ b/Core/Code/Service/mitkTrackedService.h @@ -0,0 +1,103 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKTRACKEDSERVICE_H +#define MITKTRACKEDSERVICE_H + +#include "mitkTrackedServiceListener.h" +#include "mitkModuleAbstractTracked.h" +#include "mitkServiceEvent.h" + +namespace mitk { + +/** + * This class is not intended to be used directly. It is exported to support + * the MITK module system. + */ +template +class TrackedService : public TrackedServiceListener, + public ModuleAbstractTracked +{ + +public: + TrackedService(ServiceTracker* serviceTracker, + ServiceTrackerCustomizer* customizer); + + /** + * Method connected to service events for the + * ServiceTracker class. This method must NOT be + * synchronized to avoid deadlock potential. + * + * @param event ServiceEvent object from the framework. + */ + void ServiceChanged(const ServiceEvent& event); + +private: + + typedef ModuleAbstractTracked Superclass; + + ServiceTracker* serviceTracker; + ServiceTrackerCustomizer* customizer; + + /** + * Increment the tracking count and tell the tracker there was a + * modification. + * + * @GuardedBy this + */ + void Modified(); + + /** + * Call the specific customizer adding method. This method must not be + * called while synchronized on this object. + * + * @param item Item to be tracked. + * @param related Action related object. + * @return Customized object for the tracked item or null + * if the item is not to be tracked. + */ + T CustomizerAdding(ServiceReference item, const ServiceEvent& related); + + /** + * Call the specific customizer modified method. This method must not be + * called while synchronized on this object. + * + * @param item Tracked item. + * @param related Action related object. + * @param object Customized object for the tracked item. + */ + void CustomizerModified(ServiceReference item, + const ServiceEvent& related, T object) ; + + /** + * Call the specific customizer removed method. This method must not be + * called while synchronized on this object. + * + * @param item Tracked item. + * @param related Action related object. + * @param object Customized object for the tracked item. + */ + void CustomizerRemoved(ServiceReference item, + const ServiceEvent& related, T object) ; +}; + +} + +#include "mitkTrackedService.tpp" + +#endif // MITKTRACKEDSERVICE_H diff --git a/Core/Code/Service/mitkTrackedService.tpp b/Core/Code/Service/mitkTrackedService.tpp new file mode 100644 index 0000000000..00c46426bd --- /dev/null +++ b/Core/Code/Service/mitkTrackedService.tpp @@ -0,0 +1,119 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +namespace mitk { + +template +TrackedService::TrackedService(ServiceTracker* serviceTracker, + ServiceTrackerCustomizer* customizer) + : serviceTracker(serviceTracker), customizer(customizer) +{ + +} + +template +void TrackedService::ServiceChanged(const ServiceEvent& event) +{ + /* + * Check if we had a delayed call (which could happen when we + * close). + */ + if (this->closed) + { + return; + } + + ServiceReference reference = event.GetServiceReference(); + MITK_DEBUG(serviceTracker->d->DEBUG) << "TrackedService::ServiceChanged[" + << event.GetType() << "]: " << reference; + + switch (event.GetType()) + { + case ServiceEvent::REGISTERED : + case ServiceEvent::MODIFIED : + { + if (!serviceTracker->d->listenerFilter.empty()) + { // service listener added with filter + this->Track(reference, event); + /* + * If the customizer throws an unchecked exception, it + * is safe to let it propagate + */ + } + else + { // service listener added without filter + if (serviceTracker->d->filter.Match(reference)) + { + this->Track(reference, event); + /* + * If the customizer throws an unchecked exception, + * it is safe to let it propagate + */ + } + else + { + this->Untrack(reference, event); + /* + * If the customizer throws an unchecked exception, + * it is safe to let it propagate + */ + } + } + break; + } + case ServiceEvent::MODIFIED_ENDMATCH : + case ServiceEvent::UNREGISTERING : + this->Untrack(reference, event); + /* + * If the customizer throws an unchecked exception, it is + * safe to let it propagate + */ + break; + } +} + +template +void TrackedService::Modified() +{ + Superclass::Modified(); /* increment the modification count */ + serviceTracker->d->Modified(); +} + +template +T TrackedService::CustomizerAdding(ServiceReference item, + const ServiceEvent& /*related*/) +{ + return customizer->AddingService(item); +} + +template +void TrackedService::CustomizerModified(ServiceReference item, + const ServiceEvent& /*related*/, + T object) +{ + customizer->ModifiedService(item, object); +} + +template +void TrackedService::CustomizerRemoved(ServiceReference item, + const ServiceEvent& /*related*/, + T object) +{ + customizer->RemovedService(item, object); +} + +} // end namespace mitk diff --git a/Core/Code/Service/mitkTrackedServiceListener.h b/Core/Code/Service/mitkTrackedServiceListener.h new file mode 100644 index 0000000000..d88d942fc1 --- /dev/null +++ b/Core/Code/Service/mitkTrackedServiceListener.h @@ -0,0 +1,48 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef MITKTRACKEDSERVICELISTENER_H +#define MITKTRACKEDSERVICELISTENER_H + +#include + +#include "mitkServiceEvent.h" + +namespace mitk { + +/** + * This class is not intended to be used directly. It is exported to support + * the MITK module system. + */ +struct TrackedServiceListener : public itk::LightObject +{ + + /** + * Slot connected to service events for the + * ServiceTracker class. This method must NOT be + * synchronized to avoid deadlock potential. + * + * @param event ServiceEvent object from the framework. + */ + virtual void ServiceChanged(const ServiceEvent& event) = 0; + +}; + +} + +#endif // MITKTRACKEDSERVICELISTENER_H diff --git a/Core/Code/Testing/CMakeLists.txt b/Core/Code/Testing/CMakeLists.txt index baf13522b7..0b705254e3 100644 --- a/Core/Code/Testing/CMakeLists.txt +++ b/Core/Code/Testing/CMakeLists.txt @@ -1,36 +1,38 @@ + MITK_CREATE_MODULE_TESTS(LABELS MITK-Core) # MITK_INSTALL_TARGETS(EXECUTABLES MitkTestDriver) mitkAddCustomModuleTest(mitkPicFileReaderTest_emptyFile mitkPicFileReaderTest ${CMAKE_CURRENT_SOURCE_DIR}/Data/emptyFile.pic) mitkAddCustomModuleTest(mitkPicFileReaderTest_emptyGzipFile mitkPicFileReaderTest ${CMAKE_CURRENT_SOURCE_DIR}/Data/emptyFile.pic.gz) mitkAddCustomModuleTest(mitkDICOMLocaleTest_spacingOk_CT mitkDICOMLocaleTest ${MITK_DATA_DIR}/spacing-ok-ct.dcm) mitkAddCustomModuleTest(mitkDICOMLocaleTest_spacingOk_MR mitkDICOMLocaleTest ${MITK_DATA_DIR}/spacing-ok-mr.dcm) mitkAddCustomModuleTest(mitkDICOMLocaleTest_spacingOk_SC mitkDICOMLocaleTest ${MITK_DATA_DIR}/spacing-ok-sc.dcm) mitkAddCustomModuleTest(mitkEventMapperTest_Test1And2 mitkEventMapperTest ${MITK_DATA_DIR}/TestStateMachine1.xml ${MITK_DATA_DIR}/TestStateMachine2.xml) mitkAddCustomModuleTest(mitkNodeDependentPointSetInteractorTest mitkNodeDependentPointSetInteractorTest ${MITK_DATA_DIR}/Pic3D.pic.gz ${MITK_DATA_DIR}/BallBinary30x30x30.pic.gz) mitkAddCustomModuleTest(mitkDataStorageTest_US4DCyl mitkDataStorageTest ${MITK_DATA_DIR}/US4DCyl.pic.gz) mitkAddCustomModuleTest(mitkStateMachineFactoryTest_TestStateMachine1_2 mitkStateMachineFactoryTest ${MITK_DATA_DIR}/TestStateMachine1.xml ${MITK_DATA_DIR}/TestStateMachine2.xml) mitkAddCustomModuleTest(mitkDicomSeriesReaderTest_CTImage mitkDicomSeriesReaderTest ${MITK_DATA_DIR}/TinyCTAbdomen) ADD_TEST(mitkPointSetLocaleTest ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} mitkPointSetLocaleTest ${MITK_DATA_DIR}/pointSet.mps) SET_PROPERTY(TEST mitkPointSetLocaleTest PROPERTY LABELS MITK-Core) ADD_TEST(mitkPicFileReaderTest_emptyGzipFile ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} mitkPicFileReaderTest ${CMAKE_CURRENT_SOURCE_DIR}/Data/emptyFile.pic.gz) SET_PROPERTY(TEST mitkPicFileReaderTest_emptyGzipFile PROPERTY LABELS MITK-Core) ADD_TEST(mitkImageTest_brainImage ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} mitkImageTest ${MITK_DATA_DIR}/brain.mhd) SET_PROPERTY(TEST mitkImageTest_brainImage PROPERTY LABELS MITK-Core) # ADD_TEST(mitkImageTest_4DImageData ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} mitkImageTest ${MITK_DATA_DIR}/US4DCyl.pic.gz) # SET_PROPERTY(TEST mitkImageTest_4DImageData PROPERTY LABELS MITK-Core) ADD_TEST(mitkImageWriterTest_nrrdImage ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} mitkImageWriterTest ${MITK_DATA_DIR}/NrrdWritingTestImage.jpg) SET_PROPERTY(TEST mitkImageWriterTest_nrrdImage PROPERTY LABELS MITK-Core) add_subdirectory(DICOMTesting) +add_subdirectory(TestModules) diff --git a/Core/Code/Testing/TestModules/CMakeLists.txt b/Core/Code/Testing/TestModules/CMakeLists.txt new file mode 100644 index 0000000000..4364c60eeb --- /dev/null +++ b/Core/Code/Testing/TestModules/CMakeLists.txt @@ -0,0 +1,5 @@ +add_subdirectory(libA) +add_subdirectory(libA2) +add_subdirectory(libSL1) +add_subdirectory(libSL3) +add_subdirectory(libSL4) diff --git a/Core/Code/Testing/TestModules/libA/CMakeLists.txt b/Core/Code/Testing/TestModules/libA/CMakeLists.txt new file mode 100644 index 0000000000..45b499309a --- /dev/null +++ b/Core/Code/Testing/TestModules/libA/CMakeLists.txt @@ -0,0 +1,5 @@ + +MITK_CREATE_MODULE(TestModuleA + DEPENDS Mitk) + +add_dependencies(${TESTDRIVER} TestModuleA) diff --git a/Core/Code/Testing/TestModules/libA/files.cmake b/Core/Code/Testing/TestModules/libA/files.cmake new file mode 100644 index 0000000000..1ca4954517 --- /dev/null +++ b/Core/Code/Testing/TestModules/libA/files.cmake @@ -0,0 +1,5 @@ +set(H_FILES ) + +set(CPP_FILES + mitkTestModuleA.cpp +) diff --git a/Core/Code/Testing/TestModules/libA/mitkTestModuleA.cpp b/Core/Code/Testing/TestModules/libA/mitkTestModuleA.cpp new file mode 100644 index 0000000000..a9baa930c1 --- /dev/null +++ b/Core/Code/Testing/TestModules/libA/mitkTestModuleA.cpp @@ -0,0 +1,60 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkTestModuleAService.h" + +#include + +#include +#include + +namespace mitk { + +struct TestModuleA : public itk::LightObject, public TestModuleAService +{ + + TestModuleA(ModuleContext* mc) + { + MITK_INFO << "Registering TestModuleAService"; + mc->RegisterService(this); + } + +}; + +class TestModuleAActivator : public ModuleActivator +{ +public: + + void Load(ModuleContext* context) + { + s = new TestModuleA(context); + } + + void Unload(ModuleContext*) + { + + } + +private: + + itk::SmartPointer s; +}; + +} + +MITK_EXPORT_MODULE_ACTIVATOR(TestModuleA, mitk::TestModuleAActivator) + diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Core/Code/Testing/TestModules/libA/mitkTestModuleAService.h similarity index 63% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Core/Code/Testing/TestModules/libA/mitkTestModuleAService.h index c09a6d26ee..3df74eaf90 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Core/Code/Testing/TestModules/libA/mitkTestModuleAService.h @@ -1,33 +1,35 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +Date: $Date$ +Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#ifndef MITKTESTMODULEASERVICE_H +#define MITKTESTMODULEASERVICE_H -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog +#include + +namespace mitk { + +struct TestModuleAService { - Q_OBJECT + virtual ~TestModuleAService() {} +}; - public: +} - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); +MITK_DECLARE_SERVICE_INTERFACE(mitk::TestModuleAService, "org.mitk.TestModuleAService") -}; +#endif // MITKTESTMODULEASERVICE_H diff --git a/Core/Code/Testing/TestModules/libA2/CMakeLists.txt b/Core/Code/Testing/TestModules/libA2/CMakeLists.txt new file mode 100644 index 0000000000..56fbd7af24 --- /dev/null +++ b/Core/Code/Testing/TestModules/libA2/CMakeLists.txt @@ -0,0 +1,5 @@ + +MITK_CREATE_MODULE(TestModuleA2 + DEPENDS Mitk) + +add_dependencies(${TESTDRIVER} TestModuleA2) diff --git a/Core/Code/Testing/TestModules/libA2/files.cmake b/Core/Code/Testing/TestModules/libA2/files.cmake new file mode 100644 index 0000000000..6cd482f4cb --- /dev/null +++ b/Core/Code/Testing/TestModules/libA2/files.cmake @@ -0,0 +1,5 @@ +set(H_FILES ) + +set(CPP_FILES + mitkTestModuleA2.cpp +) diff --git a/Core/Code/Testing/TestModules/libA2/mitkTestModuleA2.cpp b/Core/Code/Testing/TestModules/libA2/mitkTestModuleA2.cpp new file mode 100644 index 0000000000..8e9f778b4d --- /dev/null +++ b/Core/Code/Testing/TestModules/libA2/mitkTestModuleA2.cpp @@ -0,0 +1,71 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include "mitkTestModuleA2Service.h" + +#include + +#include +#include + +namespace mitk { + +struct TestModuleA2 : public itk::LightObject, public TestModuleA2Service +{ + + TestModuleA2(ModuleContext* mc) + { + MITK_INFO << "Registering TestModuleA2Service"; + sr = mc->RegisterService(this); + } + + void Unregister() + { + if (sr) + { + sr.Unregister(); + } + } + +private: + + ServiceRegistration sr; +}; + +class TestModuleA2Activator : public ModuleActivator +{ +public: + + void Load(ModuleContext* context) + { + s = new TestModuleA2(context); + } + + void Unload(ModuleContext* /*context*/) + { + s->Unregister(); + } + +private: + + itk::SmartPointer s; +}; + +} + +MITK_EXPORT_MODULE_ACTIVATOR(TestModuleA2, mitk::TestModuleA2Activator) + diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Core/Code/Testing/TestModules/libA2/mitkTestModuleA2Service.h similarity index 63% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Core/Code/Testing/TestModules/libA2/mitkTestModuleA2Service.h index c09a6d26ee..5249cf31e2 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Core/Code/Testing/TestModules/libA2/mitkTestModuleA2Service.h @@ -1,33 +1,35 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +Date: $Date$ +Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#ifndef MITKTESTMODULEA2SERVICE_H +#define MITKTESTMODULEA2SERVICE_H -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog +#include + +namespace mitk { + +struct TestModuleA2Service { - Q_OBJECT + virtual ~TestModuleA2Service() {} +}; - public: +} - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); +MITK_DECLARE_SERVICE_INTERFACE(mitk::TestModuleA2Service, "org.mitk.TestModuleA2Service") -}; +#endif // MITKTESTMODULEA2SERVICE_H diff --git a/Core/Code/Testing/TestModules/libSL1/CMakeLists.txt b/Core/Code/Testing/TestModules/libSL1/CMakeLists.txt new file mode 100644 index 0000000000..284f7811e1 --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL1/CMakeLists.txt @@ -0,0 +1,4 @@ +MITK_CREATE_MODULE(TestModuleSL1 + DEPENDS Mitk) + +add_dependencies(${TESTDRIVER} TestModuleSL1) diff --git a/Core/Code/Testing/TestModules/libSL1/files.cmake b/Core/Code/Testing/TestModules/libSL1/files.cmake new file mode 100644 index 0000000000..b2c1639489 --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL1/files.cmake @@ -0,0 +1,7 @@ +set(H_FILES + mitkFooService.h +) + +set(CPP_FILES + mitkActivatorSL1.cpp +) diff --git a/Core/Code/Testing/TestModules/libSL1/mitkActivatorSL1.cpp b/Core/Code/Testing/TestModules/libSL1/mitkActivatorSL1.cpp new file mode 100644 index 0000000000..85eadda1c9 --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL1/mitkActivatorSL1.cpp @@ -0,0 +1,103 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include + +#include +#include + +#include +#include + +#include "mitkFooService.h" + +namespace mitk { + +class ActivatorSL1 : + public itk::LightObject, public ModuleActivator, public ModulePropsInterface, + public ServiceTrackerCustomizer +{ + +public: + + ActivatorSL1() + : tracker(0), context(0) + { + + } + + ~ActivatorSL1() + { + delete tracker; + --m_ReferenceCount; + } + + void Load(ModuleContext* context) + { + this->context = context; + + context->RegisterService("mitk::ActivatorSL1", this); + + delete tracker; + tracker = new FooTracker(context, this); + tracker->Open(); + } + + void Unload(ModuleContext* /*context*/) + { + tracker->Close(); + } + + const Properties& GetProperties() const + { + return props; + } + + FooService* AddingService(const ServiceReference& reference) + { + props["serviceAdded"] = true; + + FooService* fooService = context->GetService(reference); + fooService->foo(); + return fooService; + } + + void ModifiedService(const ServiceReference& /*reference*/, FooService* /*service*/) + {} + + void RemovedService(const ServiceReference& /*reference*/, FooService* /*service*/) + { + props["serviceRemoved"] = true; + } + +private: + + ModulePropsInterface::Properties props; + + typedef ServiceTracker FooTracker; + + FooTracker* tracker; + ModuleContext* context; + +}; // ActivatorSL1 + +} // end namespace mitk + +MITK_EXPORT_MODULE_ACTIVATOR(TestModuleSL1, mitk::ActivatorSL1) + + diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Core/Code/Testing/TestModules/libSL1/mitkFooService.h similarity index 63% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Core/Code/Testing/TestModules/libSL1/mitkFooService.h index c09a6d26ee..20989176d7 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Core/Code/Testing/TestModules/libSL1/mitkFooService.h @@ -1,33 +1,36 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +Date: $Date$ +Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#ifndef MITKFOOSERVICE_H +#define MITKFOOSERVICE_H -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog +#include + +namespace mitk { + +struct FooService { - Q_OBJECT + virtual ~FooService() {} + virtual void foo() = 0; +}; - public: +} - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); +MITK_DECLARE_SERVICE_INTERFACE(mitk::FooService, "org.mitk.testing.FooService") -}; +#endif // MITKFOOSERVICE_H diff --git a/Core/Code/Testing/TestModules/libSL3/CMakeLists.txt b/Core/Code/Testing/TestModules/libSL3/CMakeLists.txt new file mode 100644 index 0000000000..cf106c4916 --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL3/CMakeLists.txt @@ -0,0 +1,6 @@ +MITK_CREATE_MODULE(TestModuleSL3 + DEPENDS Mitk + INTERNAL_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/../libSL1" +) + +add_dependencies(${TESTDRIVER} TestModuleSL3) diff --git a/Core/Code/Testing/TestModules/libSL3/files.cmake b/Core/Code/Testing/TestModules/libSL3/files.cmake new file mode 100644 index 0000000000..6f2bcba46a --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL3/files.cmake @@ -0,0 +1,7 @@ +set(H_FILES + +) + +set(CPP_FILES + mitkActivatorSL3.cpp +) diff --git a/Core/Code/Testing/TestModules/libSL3/mitkActivatorSL3.cpp b/Core/Code/Testing/TestModules/libSL3/mitkActivatorSL3.cpp new file mode 100644 index 0000000000..4e7f960702 --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL3/mitkActivatorSL3.cpp @@ -0,0 +1,93 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include +#include +#include +#include +#include + +namespace mitk { + +class ActivatorSL3 : + public itk::LightObject, public ModuleActivator, public ModulePropsInterface, + public ServiceTrackerCustomizer +{ + +public: + + ActivatorSL3() : tracker(0), context(0) {} + + ~ActivatorSL3() + { delete tracker; --m_ReferenceCount; } + + void Load(ModuleContext* context) + { + this->context = context; + + context->RegisterService("mitk::ActivatorSL3", this); + delete tracker; + tracker = new FooTracker(context, this); + tracker->Open(); + } + + void Unload(ModuleContext* /*context*/) + { + tracker->Close(); + } + + const ModulePropsInterface::Properties& GetProperties() const + { + return props; + } + + FooService* AddingService(const ServiceReference& reference) + { + props["serviceAdded"] = true; + MITK_INFO << "SL3: Adding reference =" << reference; + + FooService* fooService = context->GetService(reference); + fooService->foo(); + return fooService; + } + + void ModifiedService(const ServiceReference& /*reference*/, FooService* /*service*/) + { + + } + + void RemovedService(const ServiceReference& reference, FooService* /*service*/) + { + props["serviceRemoved"] = true; + MITK_INFO << "SL3: Removing reference =" << reference; + } + +private: + + typedef ServiceTracker FooTracker; + FooTracker* tracker; + ModuleContext* context; + + ModulePropsInterface::Properties props; + +}; + +} + +MITK_EXPORT_MODULE_ACTIVATOR(TestModuleSL3, mitk::ActivatorSL3) + + diff --git a/Core/Code/Testing/TestModules/libSL4/CMakeLists.txt b/Core/Code/Testing/TestModules/libSL4/CMakeLists.txt new file mode 100644 index 0000000000..5ea9355c85 --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL4/CMakeLists.txt @@ -0,0 +1,6 @@ +MITK_CREATE_MODULE(TestModuleSL4 + DEPENDS Mitk + INTERNAL_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/../libSL1" +) + +add_dependencies(${TESTDRIVER} TestModuleSL4) diff --git a/Core/Code/Testing/TestModules/libSL4/files.cmake b/Core/Code/Testing/TestModules/libSL4/files.cmake new file mode 100644 index 0000000000..b10793d5f8 --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL4/files.cmake @@ -0,0 +1,7 @@ +set(H_FILES + +) + +set(CPP_FILES + mitkActivatorSL4.cpp +) diff --git a/Core/Code/Testing/TestModules/libSL4/mitkActivatorSL4.cpp b/Core/Code/Testing/TestModules/libSL4/mitkActivatorSL4.cpp new file mode 100644 index 0000000000..ad45511ece --- /dev/null +++ b/Core/Code/Testing/TestModules/libSL4/mitkActivatorSL4.cpp @@ -0,0 +1,60 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include + +#include +#include +#include + +#include + +namespace mitk { + +class ActivatorSL4 : + public itk::LightObject, public ModuleActivator, public FooService +{ + +public: + + ~ActivatorSL4() + { + --m_ReferenceCount; + } + + void foo() + { + MITK_INFO << "TestModuleSL4: Doing foo"; + } + + void Load(ModuleContext* context) + { + ServiceRegistration registration = + context->RegisterService(this); + MITK_INFO << "TestModuleSL4: Registered" << registration; + } + + void Unload(ModuleContext* /*context*/) + { + //unregister will be done automagically + } + +}; + +} + +MITK_EXPORT_MODULE_ACTIVATOR(TestModuleSL4, mitk::ActivatorSL4) diff --git a/Core/Code/Testing/files.cmake b/Core/Code/Testing/files.cmake index 1d7df8917e..21114146e6 100644 --- a/Core/Code/Testing/files.cmake +++ b/Core/Code/Testing/files.cmake @@ -1,95 +1,117 @@ # tests with no extra command line parameter SET(MODULE_TESTS mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkPointSetWriterTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkEnumerationPropertyTest.cpp mitkEventTest.cpp mitkFocusManagerTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkGlobalInteractionTest.cpp mitkImageDataItemTest.cpp #mitkImageMapper2DTest.cpp mitkImageGeneratorTest.cpp mitkBaseDataTest.cpp #mitkImageToItkTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkInteractorTest.cpp mitkITKThreadingTest.cpp + mitkLDAPFilterTest.cpp # mitkLevelWindowManagerTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp + mitkModuleTest.cpp #mitkPipelineSmartPointerCorrectnessTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetTest.cpp mitkPointSetInteractorTest.cpp mitkPropertyListTest.cpp #mitkRegistrationBaseTest.cpp #mitkSegmentationInterpolationTest.cpp + mitkServiceListenerTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkStateMachineTest.cpp mitkStateTest.cpp mitkSurfaceTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeSlicedGeometryTest.cpp mitkTransitionTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp #mitkAbstractTransformGeometryTest.cpp #mitkPicFileIOTest.cpp mitkStepperTest.cpp itkTotalVariationDenoisingImageFilterTest.cpp mitkRenderingManagerTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp ) # test with image filename as an extra command line parameter SET(MODULE_IMAGE_TESTS mitkSurfaceVtkWriterTest.cpp mitkPicFileWriterTest.cpp #mitkImageSliceSelectorTest.cpp mitkImageTimeSelectorTest.cpp mitkPicFileReaderTest.cpp # mitkVtkPropRendererTest.cpp mitkDataNodeFactoryTest.cpp #mitkSTLFileReaderTest.cpp ) # list of images for which the tests are run SET(MODULE_TESTIMAGES US4DCyl.pic.gz Pic3D.pic.gz Pic2DplusT.pic.gz BallBinary30x30x30.pic.gz 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 + mitkImageWriterTest.cpp ) + +# Create an artificial module initializing class for +# the mitkServiceListenerTest.cpp + +SET(module_name_orig ${MODULE_NAME}) +SET(module_libname_orig ${MODULE_LIBNAME}) +SET(MODULE_NAME "${MODULE_NAME}TestDriver") +SET(MODULE_LIBNAME "") +SET(MODULE_DEPENDS_STR "Mitk") +SET(MODULE_PACKAGE_DEPENDS_STR "") +SET(MODULE_VERSION "0.1.0") +SET(MODULE_QT_BOOL "false") + +SET(testdriver_init_file "${CMAKE_CURRENT_BINARY_DIR}/MitkTestDriver_init.cpp") +CONFIGURE_FILE("${MITK_SOURCE_DIR}/CMake/mitkModuleInit.cpp" ${testdriver_init_file} @ONLY) +SET(TEST_CPP_FILES ${testdriver_init_file}) + +SET(MODULE_NAME ${module_name_orig}) +SET(MODULE_LIBNAME ${module_libname_orig}) diff --git a/Core/Code/Testing/mitkLDAPFilterTest.cpp b/Core/Code/Testing/mitkLDAPFilterTest.cpp new file mode 100644 index 0000000000..70f729c9ec --- /dev/null +++ b/Core/Code/Testing/mitkLDAPFilterTest.cpp @@ -0,0 +1,142 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include + +#include + +int TestParsing() +{ + // WELL FORMED Expr + try + { + MITK_TEST_OUTPUT(<< "Parsing (cn=Babs Jensen)") + mitk::LDAPFilter ldap( "(cn=Babs Jensen)" ); + MITK_TEST_OUTPUT(<< "Parsing (!(cn=Tim Howes))") + ldap = mitk::LDAPFilter( "(!(cn=Tim Howes))" ); + MITK_TEST_OUTPUT(<< "Parsing " << std::string("(&(") + mitk::ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))") + ldap = mitk::LDAPFilter( std::string("(&(") + mitk::ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))" ); + MITK_TEST_OUTPUT(<< "Parsing (o=univ*of*mich*)") + ldap = mitk::LDAPFilter( "(o=univ*of*mich*)" ); + } + catch (const std::invalid_argument& e) + { + MITK_TEST_OUTPUT(<< e.what()); + return EXIT_FAILURE; + } + + + // MALFORMED Expr + try + { + MITK_TEST_OUTPUT( << "Parsing malformed expr: cn=Babs Jensen)") + mitk::LDAPFilter ldap( "cn=Babs Jensen)" ); + return EXIT_FAILURE; + } + catch (const std::invalid_argument&) + { + } + + return EXIT_SUCCESS; +} + + +int TestEvaluate() +{ + // EVALUATE + try + { + mitk::LDAPFilter ldap( "(Cn=Babs Jensen)" ); + mitk::ServiceProperties props; + bool eval = false; + + // Several values + props["cn"] = std::string("Babs Jensen"); + props["unused"] = std::string("Jansen"); + MITK_TEST_OUTPUT(<< "Evaluating expr: " << ldap.ToString()) + eval = ldap.Match(props); + if (!eval) + { + return EXIT_FAILURE; + } + + // WILDCARD + ldap = mitk::LDAPFilter( "(cn=Babs *)" ); + props.clear(); + props["cn"] = std::string("Babs Jensen"); + MITK_TEST_OUTPUT(<< "Evaluating wildcard expr: " << ldap.ToString()) + eval = ldap.Match(props); + if ( !eval ) + { + return EXIT_FAILURE; + } + + // NOT FOUND + ldap = mitk::LDAPFilter( "(cn=Babs *)" ); + props.clear(); + props["unused"] = std::string("New"); + MITK_TEST_OUTPUT(<< "Expr not found test: " << ldap.ToString()) + eval = ldap.Match(props); + if ( eval ) + { + return EXIT_FAILURE; + } + + // std::vector with integer values + ldap = mitk::LDAPFilter( " ( |(cn=Babs *)(sn=1) )" ); + props.clear(); + std::vector list; + list.push_back(std::string("Babs Jensen")); + list.push_back(std::string("1")); + props["sn"] = list; + MITK_TEST_OUTPUT(<< "Evaluating vector expr: " << ldap.ToString()) + eval = ldap.Match(props); + if (!eval) + { + return EXIT_FAILURE; + } + + // wrong case + ldap = mitk::LDAPFilter( "(cN=Babs *)" ); + props.clear(); + props["cn"] = std::string("Babs Jensen"); + MITK_TEST_OUTPUT(<< "Evaluating case sensitive expr: " << ldap.ToString()) + eval = ldap.MatchCase(props); + if (eval) + { + return EXIT_FAILURE; + } + } + catch (const std::invalid_argument& e) + { + MITK_TEST_OUTPUT( << e.what() ) + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} + +int mitkLDAPFilterTest(int /*argc*/, char* /*argv*/[]) +{ + MITK_TEST_BEGIN("LDAPFilterTest"); + + MITK_TEST_CONDITION(TestParsing() == EXIT_SUCCESS, "Parsing LDAP expressions: ") + MITK_TEST_CONDITION(TestEvaluate() == EXIT_SUCCESS, "Evaluating LDAP expressions: ") + + MITK_TEST_END() +} + diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Core/Code/Testing/mitkModulePropsInterface.h similarity index 55% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Core/Code/Testing/mitkModulePropsInterface.h index c09a6d26ee..befb63f090 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Core/Code/Testing/mitkModulePropsInterface.h @@ -1,33 +1,40 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ +Date: $Date$ +Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#ifndef MITKMODULEPROPSINTERFACE_H +#define MITKMODULEPROPSINTERFACE_H -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog -{ - Q_OBJECT +#include +#include + +namespace mitk { - public: +struct ModulePropsInterface +{ + typedef ServiceProperties Properties; - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); + virtual ~ModulePropsInterface() {} + virtual const Properties& GetProperties() const = 0; }; + +} + +MITK_DECLARE_SERVICE_INTERFACE(mitk::ModulePropsInterface, "org.mitk.testing.ModulePropsInterface") + +#endif // MITKMODULEPROPSINTERFACE_H diff --git a/Core/Code/Testing/mitkModuleTest.cpp b/Core/Code/Testing/mitkModuleTest.cpp new file mode 100644 index 0000000000..e8b7d68bad --- /dev/null +++ b/Core/Code/Testing/mitkModuleTest.cpp @@ -0,0 +1,353 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include +#include +#include +#include +#include "mitkTestUtilSharedLibrary.cpp" + +#include + +class ModuleListener { + +public: + + ModuleListener(mitk::ModuleContext* mc) : mc(mc) + {} + + void ModuleChanged(const mitk::ModuleEvent& event) + { + moduleEvents.push_back(event); + MITK_DEBUG << "ModuleEvent:" << event; + } + + void ServiceChanged(const mitk::ServiceEvent& event) + { + serviceEvents.push_back(event); + MITK_DEBUG << "ServiceEvent:" << event; + } + + mitk::ModuleEvent GetModuleEvent() const + { + if (moduleEvents.empty()) + { + return mitk::ModuleEvent(); + } + return moduleEvents.back(); + } + + mitk::ServiceEvent GetServiceEvent() const + { + if (serviceEvents.empty()) + { + return mitk::ServiceEvent(); + } + return serviceEvents.back(); + } + + bool CheckListenerEvents( + bool pexp, mitk::ModuleEvent::Type ptype, + bool sexp, mitk::ServiceEvent::Type stype, + mitk::Module* moduleX, mitk::ServiceReference* servX) + { + std::vector pEvts; + std::vector seEvts; + + if (pexp) pEvts.push_back(mitk::ModuleEvent(ptype, moduleX)); + if (sexp) seEvts.push_back(mitk::ServiceEvent(stype, *servX)); + + return CheckListenerEvents(pEvts, seEvts); + } + + bool CheckListenerEvents( + const std::vector& pEvts, + const std::vector& seEvts) + { + bool listenState = true; // assume everything will work + + if (pEvts.size() != moduleEvents.size()) + { + listenState = false; + MITK_DEBUG << "*** Module event mismatch: expected " + << pEvts.size() << " event(s), found " + << moduleEvents.size() << " event(s)."; + + const std::size_t max = pEvts.size() > moduleEvents.size() ? pEvts.size() : moduleEvents.size(); + for (std::size_t i = 0; i < max; ++i) + { + const mitk::ModuleEvent& pE = i < pEvts.size() ? pEvts[i] : mitk::ModuleEvent(); + const mitk::ModuleEvent& pR = i < moduleEvents.size() ? moduleEvents[i] : mitk::ModuleEvent(); + MITK_DEBUG << " " << pE << " - " << pR; + } + } + else + { + for (std::size_t i = 0; i < pEvts.size(); ++i) + { + const mitk::ModuleEvent& pE = pEvts[i]; + const mitk::ModuleEvent& pR = moduleEvents[i]; + if (pE.GetType() != pR.GetType() + || pE.GetModule() != pR.GetModule()) + { + listenState = false; + MITK_DEBUG << "*** Wrong module event: " << pR << " expected " << pE; + } + } + } + + if (seEvts.size() != serviceEvents.size()) + { + listenState = false; + MITK_DEBUG << "*** Service event mismatch: expected " + << seEvts.size() << " event(s), found " + << serviceEvents.size() << " event(s)."; + + const std::size_t max = seEvts.size() > serviceEvents.size() + ? seEvts.size() : serviceEvents.size(); + for (std::size_t i = 0; i < max; ++i) + { + const mitk::ServiceEvent& seE = i < seEvts.size() ? seEvts[i] : mitk::ServiceEvent(); + const mitk::ServiceEvent& seR = i < serviceEvents.size() ? serviceEvents[i] : mitk::ServiceEvent(); + MITK_DEBUG << " " << seE << " - " << seR; + } + } + else + { + for (std::size_t i = 0; i < seEvts.size(); ++i) + { + const mitk::ServiceEvent& seE = seEvts[i]; + const mitk::ServiceEvent& seR = serviceEvents[i]; + if (seE.GetType() != seR.GetType() + || (!(seE.GetServiceReference() == seR.GetServiceReference()))) + { + listenState = false; + MITK_DEBUG << "*** Wrong service event: " << seR << " expected " << seE; + } + } + } + + moduleEvents.clear(); + serviceEvents.clear(); + return listenState; + } + +private: + + mitk::ModuleContext* const mc; + + std::vector serviceEvents; + std::vector moduleEvents; +}; + +// Verify information from the ModuleInfo struct +void frame005a(mitk::ModuleContext* mc) +{ + mitk::Module* m = mc->GetModule(); + + // check expected headers + + MITK_TEST_CONDITION("MitkTestDriver" == m->GetName(), "Test module name"); +// MITK_DEBUG << "Version: " << m->GetVersion(); + MITK_TEST_CONDITION(mitk::ModuleVersion(0,1,0) == m->GetVersion(), "Test module version") +} + +// Get context id, location and status of the module +void frame010a(mitk::ModuleContext* mc) +{ + mitk::Module* m = mc->GetModule(); + + long int contextid = m->GetModuleId(); + MITK_DEBUG << "CONTEXT ID:" << contextid; + + std::string location = m->GetLocation(); + MITK_DEBUG << "LOCATION:" << location; + MITK_TEST_CONDITION(!location.empty(), "Test for non-empty module location") + + MITK_TEST_CONDITION(m->IsLoaded(), "Test for loaded flag") +} + +//---------------------------------------------------------------------------- +//Test result of GetService(mitk::ServiceReference()). Should throw std::invalid_argument +void frame018a(mitk::ModuleContext* mc) +{ + try + { + itk::LightObject* obj = mc->GetService(mitk::ServiceReference()); + MITK_DEBUG << "Got service object = " << obj->GetNameOfClass() << ", excpected std::invalid_argument exception"; + MITK_TEST_FAILED_MSG(<< "Got service object, excpected std::invalid_argument exception") + } + catch (const std::invalid_argument& ) + {} + catch (...) + { + MITK_TEST_FAILED_MSG(<< "Got wrong exception, expected std::invalid_argument") + } +} + +// Load libA and check that it exists and that the service it registers exists, +// also check that the expected events occur +void frame020a(mitk::ModuleContext* mc, ModuleListener& listener, mitk::SharedLibraryHandle& libA) +{ + try + { + libA.Load(); + } + catch (const std::exception& e) + { + MITK_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) + } + + mitk::Module* moduleA = mitk::ModuleRegistry::GetModule("TestModuleA"); + MITK_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing moudle TestModuleA") + + MITK_TEST_CONDITION(moduleA->GetName() == "TestModuleA", "Test module name") + + // Check if libA registered the expected service + try + { + mitk::ServiceReference sr1 = mc->GetServiceReference("org.mitk.TestModuleAService"); + itk::LightObject* o1 = mc->GetService(sr1); + MITK_TEST_CONDITION(o1 != 0, "Test if service object found"); + + try + { + MITK_TEST_CONDITION(mc->UngetService(sr1), "Test if Service UnGet returns true"); + } + catch (const std::logic_error le) + { + MITK_TEST_FAILED_MSG(<< "UnGetService exception: " << le.what()) + } + + // check the listeners for events + std::vector pEvts; + pEvts.push_back(mitk::ModuleEvent(mitk::ModuleEvent::LOADING, moduleA)); + pEvts.push_back(mitk::ModuleEvent(mitk::ModuleEvent::LOADED, moduleA)); + + std::vector seEvts; + seEvts.push_back(mitk::ServiceEvent(mitk::ServiceEvent::REGISTERED, sr1)); + + MITK_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); + + } + catch (const mitk::ServiceException& /*se*/) + { + MITK_TEST_FAILED_MSG(<< "test moudle, expected service not found"); + } + + MITK_TEST_CONDITION(moduleA->IsLoaded() == true, "Test if loaded correctly"); +} + + +// Unload libA and check for correct events +void frame030b(mitk::ModuleContext* mc, ModuleListener& listener, mitk::SharedLibraryHandle& libA) +{ + mitk::Module* moduleA = mitk::ModuleRegistry::GetModule("TestModuleA"); + MITK_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for non-null module") + + mitk::ServiceReference sr1 + = mc->GetServiceReference("org.mitk.TestModuleAService"); + MITK_TEST_CONDITION(sr1, "Test for valid service reference") + + try + { + libA.Unload(); + MITK_TEST_CONDITION(moduleA->IsLoaded() == false, "Test for unloaded state") + } + catch (const std::exception& e) + { + MITK_TEST_FAILED_MSG(<< "UnLoad module exception: " << e.what()) + } + + std::vector pEvts; + pEvts.push_back(mitk::ModuleEvent(mitk::ModuleEvent::UNLOADING, moduleA)); + pEvts.push_back(mitk::ModuleEvent(mitk::ModuleEvent::UNLOADED, moduleA)); + + std::vector seEvts; + seEvts.push_back(mitk::ServiceEvent(mitk::ServiceEvent::UNREGISTERING, sr1)); + + MITK_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); +} + + +struct LocalListener { + void ServiceChanged(const mitk::ServiceEvent&) {} +}; + +// Add a service listener with a broken LDAP filter to Get an exception +void frame045a(mitk::ModuleContext* mc) +{ + LocalListener sListen1; + std::string brokenFilter = "A broken LDAP filter"; + + try + { + mc->AddServiceListener(&sListen1, &LocalListener::ServiceChanged, brokenFilter); + } + catch (const std::invalid_argument& /*ia*/) + { + //assertEquals("InvalidSyntaxException.GetFilter should be same as input string", brokenFilter, ise.GetFilter()); + } + catch (...) + { + MITK_TEST_FAILED_MSG(<< "test module, wrong exception on broken LDAP filter:"); + } +} + + +int mitkModuleTest(int /*argc*/, char* /*argv*/[]) +{ + MITK_TEST_BEGIN("ModuleTest"); + + mitk::ModuleContext* mc = mitk::GetModuleContext(); + ModuleListener listener(mc); + + try + { + mc->AddModuleListener(&listener, &ModuleListener::ModuleChanged); + } + catch (const std::logic_error& ise) + { + MITK_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); + throw; + } + + try + { + mc->AddServiceListener(&listener, &ModuleListener::ServiceChanged); + } + catch (const std::logic_error& ise) + { + MITK_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); + throw; + } + + frame005a(mc); + frame010a(mc); + frame018a(mc); + + mitk::SharedLibraryHandle libA("TestModuleA"); + frame020a(mc, listener, libA); + frame030b(mc, listener, libA); + + frame045a(mc); + + mc->RemoveModuleListener(&listener, &ModuleListener::ModuleChanged); + mc->RemoveServiceListener(&listener, &ModuleListener::ServiceChanged); + + MITK_TEST_END() +} diff --git a/Core/Code/Testing/mitkServiceListenerTest.cpp b/Core/Code/Testing/mitkServiceListenerTest.cpp new file mode 100644 index 0000000000..91cf2b197e --- /dev/null +++ b/Core/Code/Testing/mitkServiceListenerTest.cpp @@ -0,0 +1,506 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include + +#include +#include +#include + +#include + +#include "mitkTestUtilSharedLibrary.cpp" + + +class ServiceListener +{ + +private: + + friend bool runLoadUnloadTest(const std::string&, int cnt, mitk::SharedLibraryHandle&, + const std::vector&); + + const bool checkUsingModules; + std::vector events; + + bool teststatus; + + mitk::ModuleContext* mc; + +public: + + ServiceListener(mitk::ModuleContext* mc, bool checkUsingModules = true) + : checkUsingModules(checkUsingModules), teststatus(true), mc(mc) + {} + + bool getTestStatus() const + { + return teststatus; + } + + void clearEvents() + { + events.clear(); + } + + bool checkEvents(const std::vector& eventTypes) + { + if (events.size() != eventTypes.size()) + { + dumpEvents(eventTypes); + return false; + } + + for (std::size_t i=0; i < eventTypes.size(); ++i) + { + if (eventTypes[i] != events[i].GetType()) + { + dumpEvents(eventTypes); + return false; + } + } + return true; + } + + void serviceChanged(const mitk::ServiceEvent& evt) + { + events.push_back(evt); + MITK_TEST_OUTPUT( << "ServiceEvent: " << evt ); + if (mitk::ServiceEvent::UNREGISTERING == evt.GetType()) + { + mitk::ServiceReference sr = evt.GetServiceReference(); + + // Validate that no module is marked as using the service + std::vector usingModules; + sr.GetUsingModules(usingModules); + if (checkUsingModules && !usingModules.empty()) + { + teststatus = false; + printUsingModules(sr, "*** Using modules (unreg) should be empty but is: "); + } + + // Check if the service can be fetched + itk::LightObject* service = mc->GetService(sr); + sr.GetUsingModules(usingModules); + // if (UNREGISTERSERVICE_VALID_DURING_UNREGISTERING) { + // In this mode the service shall be obtainable during + // unregistration. + if (service == 0) + { + teststatus = false; + MITK_TEST_OUTPUT( << "*** Service should be available to ServiceListener " + << "while handling unregistering event." ); + } + MITK_TEST_OUTPUT( << "Service (unreg): " << service->GetNameOfClass() ); + if (checkUsingModules && usingModules.size() != 1) + { + teststatus = false; + printUsingModules(sr, "*** One using module expected " + "(unreg, after getService), found: "); + } + else + { + printUsingModules(sr, "Using modules (unreg, after getService): "); + } + // } else { + // // In this mode the service shall NOT be obtainable during + // // unregistration. + // if (null!=service) { + // teststatus = false; + // out.print("*** Service should not be available to ServiceListener " + // +"while handling unregistering event."); + // } + // if (checkUsingBundles && null!=usingBundles) { + // teststatus = false; + // printUsingBundles(sr, + // "*** Using bundles (unreg, after getService), " + // +"should be null but is: "); + // } else { + // printUsingBundles(sr, + // "Using bundles (unreg, after getService): null"); + // } + // } + mc->UngetService(sr); + + // Check that the UNREGISTERING service can not be looked up + // using the service registry. + try + { + long sid = mitk::any_cast(sr.GetProperty(mitk::ServiceConstants::SERVICE_ID())); + std::stringstream ss; + ss << "(" << mitk::ServiceConstants::SERVICE_ID() << "=" << sid << ")"; + std::list srs = mc->GetServiceReferences("", ss.str()); + if (srs.empty()) + { + MITK_TEST_OUTPUT( << "mitk::ServiceReference for UNREGISTERING service is not" + " found in the service registry; ok." ); + } + else + { + teststatus = false; + MITK_TEST_OUTPUT( << "*** mitk::ServiceReference for UNREGISTERING service," + << sr << ", not found in the service registry; fail." ); + MITK_TEST_OUTPUT( << "Found the following Service references:") ; + for(std::list::const_iterator sr = srs.begin(); + sr != srs.end(); ++sr) + { + MITK_TEST_OUTPUT( << (*sr) ); + } + } + } + catch (const std::exception& e) + { + teststatus = false; + MITK_TEST_OUTPUT( << "*** Unexpected excpetion when trying to lookup a" + " service while it is in state UNREGISTERING: " + << e.what() ); + } + } + } + + void printUsingModules(const mitk::ServiceReference& sr, const std::string& caption) + { + std::vector usingModules; + sr.GetUsingModules(usingModules); + + MITK_TEST_OUTPUT( << (caption.empty() ? "Using modules: " : caption) ); + for(std::vector::const_iterator module = usingModules.begin(); + module != usingModules.end(); ++module) + { + MITK_TEST_OUTPUT( << " -" << (*module) ); + } + } + + // Print expected and actual service events. + void dumpEvents(const std::vector& eventTypes) + { + std::size_t max = events.size() > eventTypes.size() ? events.size() : eventTypes.size(); + MITK_TEST_OUTPUT( << "Expected event type -- Actual event" ); + for (std::size_t i=0; i < max; ++i) + { + mitk::ServiceEvent evt = i < events.size() ? events[i] : mitk::ServiceEvent(); + if (i < eventTypes.size()) + { + MITK_TEST_OUTPUT( << " " << eventTypes[i] << "--" << evt ); + } + else + { + MITK_TEST_OUTPUT( << " " << "- NONE - " << "--" << evt ); + } + } + } + +}; // end of class ServiceListener + +bool runLoadUnloadTest(const std::string& name, int cnt, mitk::SharedLibraryHandle& target, + const std::vector& events) +{ + bool teststatus = true; + + mitk::ModuleContext* mc = mitk::GetModuleContext(); + + for (int i = 0; i < cnt && teststatus; ++i) + { + ServiceListener sListen(mc); + try + { + mc->AddServiceListener(&sListen, &ServiceListener::serviceChanged); + //mc->AddServiceListener(mitk::MessageDelegate1(&sListen, &ServiceListener::serviceChanged)); + } + catch (const std::logic_error& ise) + { + teststatus = false; + MITK_TEST_OUTPUT( << "service listener registration failed " << ise.what() + << " :" << name << ":FAIL" ); + } + + // Start the test target to get a service published. + try + { + target.Load(); + } + catch (const std::exception& e) + { + teststatus = false; + MITK_TEST_OUTPUT( << "Failed to load module, got exception: " + << e.what() << " + in " << name << ":FAIL" ); + } + + // Stop the test target to get a service unpublished. + try + { + target.Unload(); + } + catch (const std::exception& e) + { + teststatus = false; + MITK_TEST_OUTPUT( << "Failed to unload module, got exception: " + << e.what() << " + in " << name << ":FAIL" ); + } + + if (teststatus && !sListen.checkEvents(events)) + { + teststatus = false; + MITK_TEST_OUTPUT( << "Service listener event notification error :" + << name << ":FAIL" ); + } + + try + { + mc->RemoveServiceListener(&sListen, &ServiceListener::serviceChanged); + teststatus &= sListen.teststatus; + sListen.clearEvents(); + } + catch (const std::logic_error& ise) + { + teststatus = false; + MITK_TEST_OUTPUT( << "service listener removal failed " << ise.what() + << " :" << name << ":FAIL" ); + } + } + return teststatus; +} + +void frameSL05a() +{ + std::vector events; + events.push_back(mitk::ServiceEvent::REGISTERED); + events.push_back(mitk::ServiceEvent::UNREGISTERING); + mitk::SharedLibraryHandle libA("TestModuleA"); + bool testStatus = runLoadUnloadTest("FrameSL05a", 1, libA, events); + MITK_TEST_CONDITION(testStatus, "FrameSL05a") +} + +void frameSL10a() +{ + std::vector events; + events.push_back(mitk::ServiceEvent::REGISTERED); + events.push_back(mitk::ServiceEvent::UNREGISTERING); + mitk::SharedLibraryHandle libA2("TestModuleA2"); + bool testStatus = runLoadUnloadTest("FrameSL10a", 1, libA2, events); + MITK_TEST_CONDITION(testStatus, "FrameSL10a") +} + +void frameSL25a() +{ + mitk::ModuleContext* mc = mitk::GetModuleContext(); + + ServiceListener sListen(mc, false); + try + { + mc->AddServiceListener(&sListen, &ServiceListener::serviceChanged); + } + catch (const std::logic_error& ise) + { + MITK_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); + throw; + } + + mitk::SharedLibraryHandle libSL1("TestModuleSL1"); + mitk::SharedLibraryHandle libSL3("TestModuleSL3"); + mitk::SharedLibraryHandle libSL4("TestModuleSL4"); + + std::vector expectedServiceEventTypes; + + // Startup + expectedServiceEventTypes.push_back(mitk::ServiceEvent::REGISTERED); // at start of libSL1 + expectedServiceEventTypes.push_back(mitk::ServiceEvent::REGISTERED); // mitk::FooService at start of libSL4 + expectedServiceEventTypes.push_back(mitk::ServiceEvent::REGISTERED); // at start of libSL3 + + // Stop libSL4 + expectedServiceEventTypes.push_back(mitk::ServiceEvent::UNREGISTERING); // mitk::FooService at first stop of libSL4 + + // Shutdown + expectedServiceEventTypes.push_back(mitk::ServiceEvent::UNREGISTERING); // at stop of libSL1 + expectedServiceEventTypes.push_back(mitk::ServiceEvent::UNREGISTERING); // at stop of libSL3 + + + // Start libModuleTestSL1 to ensure that the Service interface is available. + try + { + MITK_TEST_OUTPUT( << "Starting libModuleTestSL1: " << libSL1.GetAbsolutePath() ); + libSL1.Load(); + } + catch (const std::exception& e) + { + MITK_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); + throw; + } + + // Start libModuleTestSL4 that will require the serivce interface and publish + // ctkFooService + try + { + MITK_TEST_OUTPUT( << "Starting libModuleTestSL4: " << libSL4.GetAbsolutePath() ); + libSL4.Load(); + } + catch (const std::exception& e) + { + MITK_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); + throw; + } + + // Start libModuleTestSL3 that will require the serivce interface and get the service + try + { + MITK_TEST_OUTPUT( << "Starting libModuleTestSL3: " << libSL3.GetAbsolutePath() ); + libSL3.Load(); + } + catch (const std::exception& e) + { + MITK_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); + throw; + } + + // Check that libSL3 has been notified about the mitk::FooService. + MITK_TEST_OUTPUT( << "Check that mitk::FooService is added to service tracker in libSL3" ); + try + { + mitk::ServiceReference libSL3SR = mc->GetServiceReference("mitk::ActivatorSL3"); + itk::LightObject* libSL3Activator = mc->GetService(libSL3SR); + MITK_TEST_CONDITION_REQUIRED(libSL3Activator, "mitk::ActivatorSL3 service != 0"); + + mitk::ModulePropsInterface* propsInterface = dynamic_cast(libSL3Activator); + MITK_TEST_CONDITION_REQUIRED(propsInterface, "Cast to mitk::ModulePropsInterface"); + + mitk::ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceAdded"); + MITK_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceAdded"); + mitk::Any serviceAddedField3 = i->second; + MITK_TEST_CONDITION_REQUIRED(!serviceAddedField3.Empty() && mitk::any_cast(serviceAddedField3), + "libSL3 notified about presence of mitk::FooService"); + mc->UngetService(libSL3SR); + } + catch (const mitk::ServiceException& se) + { + MITK_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); + } + + // Check that libSL1 has been notified about the mitk::FooService. + MITK_TEST_OUTPUT( << "Check that mitk::FooService is added to service tracker in libSL1" ); + try + { + mitk::ServiceReference libSL1SR = mc->GetServiceReference("mitk::ActivatorSL1"); + itk::LightObject* libSL1Activator = mc->GetService(libSL1SR); + MITK_TEST_CONDITION_REQUIRED(libSL1Activator, "mitk::ActivatorSL1 service != 0"); + + mitk::ModulePropsInterface* propsInterface = dynamic_cast(libSL1Activator); + MITK_TEST_CONDITION_REQUIRED(propsInterface, "Cast to mitk::ModulePropsInterface"); + + mitk::ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceAdded"); + MITK_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceAdded"); + mitk::Any serviceAddedField1 = i->second; + MITK_TEST_CONDITION_REQUIRED(!serviceAddedField1.Empty() && mitk::any_cast(serviceAddedField1), + "libSL1 notified about presence of mitk::FooService"); + mc->UngetService(libSL1SR); + } + catch (const mitk::ServiceException& se) + { + MITK_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); + } + + // Stop the service provider: libSL4 + try + { + MITK_TEST_OUTPUT( << "Stop libSL4: " << libSL4.GetAbsolutePath() ); + libSL4.Unload(); + } + catch (const std::exception& e) + { + MITK_TEST_OUTPUT( << "Failed to unload module, got exception:" << e.what() ); + throw; + } + + // Check that libSL3 has been notified about the removal of mitk::FooService. + MITK_TEST_OUTPUT( << "Check that mitk::FooService is removed from service tracker in libSL3" ); + try + { + mitk::ServiceReference libSL3SR = mc->GetServiceReference("mitk::ActivatorSL3"); + itk::LightObject* libSL3Activator = mc->GetService(libSL3SR); + MITK_TEST_CONDITION_REQUIRED(libSL3Activator, "mitk::ActivatorSL3 service != 0"); + + mitk::ModulePropsInterface* propsInterface = dynamic_cast(libSL3Activator); + MITK_TEST_CONDITION_REQUIRED(propsInterface, "Cast to mitk::ModulePropsInterface"); + + mitk::ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceRemoved"); + MITK_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceRemoved"); + + mitk::Any serviceRemovedField3 = i->second; + MITK_TEST_CONDITION(!serviceRemovedField3.Empty() && mitk::any_cast(serviceRemovedField3), + "libSL3 notified about removal of mitk::FooService"); + mc->UngetService(libSL3SR); + } + catch (const mitk::ServiceException& se) + { + MITK_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); + } + + // Stop libSL1 + try + { + MITK_TEST_OUTPUT( << "Stop libSL1:" << libSL1.GetAbsolutePath() ); + libSL1.Unload(); + } + catch (const std::exception& e) + { + MITK_TEST_OUTPUT( << "Failed to unload module got exception" << e.what() ); + throw; + } + + // Stop pSL3 + try + { + MITK_TEST_OUTPUT( << "Stop libSL3:" << libSL3.GetAbsolutePath() ); + libSL3.Unload(); + } + catch (const std::exception& e) + { + MITK_TEST_OUTPUT( << "Failed to unload module got exception" << e.what() ); + throw; + } + + // Check service events seen by this class + MITK_TEST_OUTPUT( << "Checking ServiceEvents(ServiceListener):" ); + if (!sListen.checkEvents(expectedServiceEventTypes)) + { + MITK_TEST_FAILED_MSG( << "Service listener event notification error" ); + } + + MITK_TEST_CONDITION_REQUIRED(sListen.getTestStatus(), "Service listener checks"); + try + { + mc->RemoveServiceListener(&sListen, &ServiceListener::serviceChanged); + sListen.clearEvents(); + } + catch (const std::logic_error& ise) + { + MITK_TEST_FAILED_MSG( << "service listener removal failed: " << ise.what() ); + } + +} + +int mitkServiceListenerTest(int /*argc*/, char* /*argv*/[]) +{ + MITK_TEST_BEGIN("ServiceListenerTest"); + + frameSL05a(); + frameSL10a(); + frameSL25a(); + + MITK_TEST_END() +} + diff --git a/Core/Code/Testing/mitkTestUtilSharedLibrary.cpp b/Core/Code/Testing/mitkTestUtilSharedLibrary.cpp new file mode 100644 index 0000000000..5e48b10b60 --- /dev/null +++ b/Core/Code/Testing/mitkTestUtilSharedLibrary.cpp @@ -0,0 +1,168 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date$ +Version: $Revision$ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + +#include +#include + +#include "mitkTestingConfig.h" + +#if defined(__APPLE__) + #define PLATFORM_APPLE +#endif + +#if defined(unix) || defined(__unix) || defined(__APPLE__) + #include + #define PLATFORM_UNIX +#elif defined(_WIN32) + #include + #include + #define PLATFORM_WINDOWS +#else + #error Unsupported platform +#endif + + +namespace mitk { + +class SharedLibraryHandle +{ +public: + + SharedLibraryHandle() : m_Handle(0) {} + + SharedLibraryHandle(const std::string& name) + : m_Name(name), m_Handle(0) + {} + + virtual ~SharedLibraryHandle() {} + + void Load() + { + Load(m_Name); + } + + void Load(const std::string& name) + { + if (m_Handle) throw std::logic_error(std::string("Library already loaded: ") + name); + std::string libPath = GetAbsolutePath(name); +#ifdef PLATFORM_UNIX + m_Handle = dlopen(libPath.c_str(), RTLD_LAZY | RTLD_GLOBAL); + if (!m_Handle) + { + const char* err = dlerror(); + throw std::runtime_error(err ? std::string(err) : libPath); + } +#else + m_Handle = LoadLibrary(libPath.c_str()); + if (!m_Handle) + { + // Retrieve the system error message for the last-error code + LPVOID lpMsgBuf; + LPVOID lpDisplayBuf; + DWORD dw = GetLastError(); + + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + dw, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &lpMsgBuf, + 0, NULL ); + + // Display the error message and exit the process + + lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, + (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)libPath.c_str()) + 50) * sizeof(TCHAR)); + StringCchPrintf((LPTSTR)lpDisplayBuf, + LocalSize(lpDisplayBuf) / sizeof(TCHAR), + TEXT("Loading %s failed with error %d: %s"), + libPath.c_str(), dw, lpMsgBuf); + + std::string errMsg((LPCTSTR)lpDisplayBuf); + + LocalFree(lpMsgBuf); + LocalFree(lpDisplayBuf); + + throw std::runtime_error(errMsg); + } +#endif + + m_Name = name; + } + + void Unload() + { + if (m_Handle) + { +#ifdef PLATFORM_UNIX + dlclose(m_Handle); +#else + FreeLibrary((HMODULE)m_Handle); +#endif + m_Handle = 0; + } + } + + std::string GetAbsolutePath(const std::string& name) + { + return GetLibraryPath() + "/" + Prefix() + name + Suffix(); + } + + std::string GetAbsolutePath() + { + return GetLibraryPath() + "/" + Prefix() + m_Name + Suffix(); + } + + static std::string GetLibraryPath() + { + return std::string(MITK_RUNTIME_OUTPUT_DIR); + } + + static std::string Suffix() + { +#ifdef PLATFORM_WINDOWS + return ".dll"; +#elif defined(PLATFORM_APPLE) + return ".dylib"; +#else + return ".so"; +#endif + } + + static std::string Prefix() + { +#if defined(PLATFORM_UNIX) + return "lib"; +#else + return ""; +#endif + } + +private: + + SharedLibraryHandle(const SharedLibraryHandle&); + SharedLibraryHandle& operator = (const SharedLibraryHandle&); + + std::string m_Name; + void* m_Handle; +}; + + +} // namespace mitk + diff --git a/Core/Code/files.cmake b/Core/Code/files.cmake index 24abc1d0c4..7329086108 100644 --- a/Core/Code/files.cmake +++ b/Core/Code/files.cmake @@ -1,278 +1,324 @@ 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/mitkImageAccessByItk.h Algorithms/mitkImageCast.h Algorithms/mitkImageToItk.h Algorithms/mitkImageToItk.txx Algorithms/mitkInstantiateAccessFunctions.h Algorithms/mitkITKImageImport.h Algorithms/mitkITKImageImport.txx 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 DataManagement/mitkCommon.h Interactions/mitkEventMapperAddOn.h + + Service/mitkAny.h + Service/mitkGetModuleContext.h + Service/mitkItkHashMap.h + Service/mitkItkHashSet.h + Service/mitkItkHashTable.h + Service/mitkModuleAbstractTracked.h + Service/mitkModuleAbstractTracked.tpp + Service/mitkModuleActivator.h + Service/mitkServiceFactory.h + Service/mitkServiceTracker.h + Service/mitkServiceTracker.tpp + Service/mitkServiceTrackerCustomizer.h + Service/mitkServiceTrackerPrivate.h + Service/mitkServiceTrackerPrivate.tpp + Service/mitkServiceUtils.h + Service/mitkSharedData.h + Service/mitkStaticInit.h + Service/mitkTrackedService.h + Service/mitkTrackedService.tpp + Service/mitkTrackedServiceListener.h ) SET(CPP_FILES Algorithms/mitkBaseDataSource.cpp Algorithms/mitkBaseProcess.cpp Algorithms/mitkCoreObjectFactoryBase.cpp Algorithms/mitkCoreObjectFactory.cpp Algorithms/mitkDataNodeFactory.cpp Algorithms/mitkDataNodeSource.cpp Algorithms/mitkGeometry2DDataToSurfaceFilter.cpp Algorithms/mitkHistogramGenerator.cpp Algorithms/mitkImageCaster.cpp Algorithms/mitkImageCastPart1.cpp Algorithms/mitkImageCastPart2.cpp Algorithms/mitkImageCastPart3.cpp Algorithms/mitkImageCastPart4.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 Controllers/mitkBaseController.cpp Controllers/mitkCallbackFromGUIThread.cpp Controllers/mitkCameraController.cpp Controllers/mitkCameraRotationController.cpp Controllers/mitkFocusManager.cpp Controllers/mitkLimitedLinearUndo.cpp Controllers/mitkOperationEvent.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/mitkColorProperty.cpp DataManagement/mitkDataStorage.cpp #DataManagement/mitkDataTree.cpp DataManagement/mitkDataNode.cpp #DataManagement/mitkDataTreeStorage.cpp DataManagement/mitkDisplayGeometry.cpp DataManagement/mitkEnumerationProperty.cpp DataManagement/mitkGeometry2D.cpp DataManagement/mitkGeometry2DData.cpp DataManagement/mitkGeometry3D.cpp DataManagement/mitkGeometryData.cpp DataManagement/mitkGroupTagProperty.cpp DataManagement/mitkImage.cpp DataManagement/mitkImageDataItem.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/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/mitkTransferFunctionInitializer.cpp DataManagement/mitkVector.cpp DataManagement/mitkVtkInterpolationProperty.cpp DataManagement/mitkVtkRepresentationProperty.cpp DataManagement/mitkVtkResliceInterpolationProperty.cpp DataManagement/mitkVtkScalarModeProperty.cpp DataManagement/mitkVtkVolumeRenderingProperty.cpp DataManagement/mitkWeakPointerProperty.cpp DataManagement/mitkShaderProperty.cpp DataManagement/mitkResliceMethodProperty.cpp DataManagement/mitkMaterial.cpp Interactions/mitkAction.cpp Interactions/mitkAffineInteractor.cpp Interactions/mitkCoordinateSupplier.cpp Interactions/mitkDisplayCoordinateOperation.cpp Interactions/mitkDisplayInteractor.cpp Interactions/mitkDisplayPositionEvent.cpp Interactions/mitkDisplayVectorInteractor.cpp Interactions/mitkDisplayVectorInteractorLevelWindow.cpp Interactions/mitkDisplayVectorInteractorScroll.cpp Interactions/mitkEvent.cpp Interactions/mitkEventDescription.cpp Interactions/mitkEventMapper.cpp Interactions/mitkGlobalInteraction.cpp Interactions/mitkInteractor.cpp Interactions/mitkMouseMovePointSetInteractor.cpp Interactions/mitkMoveSurfaceInteractor.cpp Interactions/mitkNodeDepententPointSetInteractor.cpp Interactions/mitkPointSetInteractor.cpp Interactions/mitkPositionEvent.cpp Interactions/mitkPositionTracker.cpp Interactions/mitkState.cpp Interactions/mitkStateEvent.cpp Interactions/mitkStateMachine.cpp Interactions/mitkStateMachineFactory.cpp Interactions/mitkTransition.cpp Interactions/mitkWheelEvent.cpp Interactions/mitkKeyEvent.cpp Interactions/mitkVtkEventAdapter.cpp Interactions/mitkCrosshairPositionEvent.cpp IO/mitkBaseDataIOFactory.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/mitkItkPictureWrite.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/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/mitkVtkMapper2D.cpp Rendering/mitkVtkMapper3D.cpp Rendering/mitkRenderWindowFrame.cpp Rendering/mitkGeometry2DDataMapper2D.cpp Rendering/mitkGeometry2DDataVtkMapper3D.cpp Rendering/mitkGLMapper2D.cpp Rendering/mitkGradientBackground.cpp Rendering/mitkManufacturerLogo.cpp Rendering/mitkMapper2D.cpp Rendering/mitkMapper3D.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/mitkImageMapperGL2D.cpp Rendering/vtkMitkThickSlicesFilter.cpp + + Service/mitkAny.cpp + Service/mitkAtomicInt.cpp + Service/mitkCoreActivator.cpp + Service/mitkCoreModuleContext.cpp + Service/mitkModule.cpp + Service/mitkModuleContext.cpp + Service/mitkModuleEvent.cpp + Service/mitkModuleInfo.cpp + Service/mitkModulePrivate.cpp + Service/mitkModuleRegistry.cpp + Service/mitkModuleUtils.cpp + Service/mitkModuleVersion.cpp + Service/mitkLDAPExpr.cpp + Service/mitkLDAPFilter.cpp + Service/mitkServiceEvent.cpp + Service/mitkServiceException.cpp + Service/mitkServiceListenerEntry.cpp + Service/mitkServiceListeners.cpp + Service/mitkServiceProperties.cpp + Service/mitkServiceReference.cpp + Service/mitkServiceReferencePrivate.cpp + Service/mitkServiceRegistration.cpp + Service/mitkServiceRegistrationPrivate.cpp + Service/mitkServiceRegistry.cpp ) diff --git a/Documentation/CMakeLists.txt b/Documentation/CMakeLists.txt index f1d514c513..caef1b7ebf 100644 --- a/Documentation/CMakeLists.txt +++ b/Documentation/CMakeLists.txt @@ -1,163 +1,175 @@ # # Variables: # MITK_DOXYGEN_OUTPUT_DIR: doxygen output directory (optional) +# Compile source code snippets +add_subdirectory(Snippets) + FIND_PACKAGE(Doxygen) IF(DOXYGEN_FOUND) OPTION(USE_DOT "Use dot program for generating graphical class diagrams with doxygen, if available" ON) OPTION(MITK_DOXYGEN_BUILD_ALWAYS "Always build the MITK documentation when building the default target" OFF) OPTION(MITK_DOXYGEN_GENERATE_QCH_FILES "Use doxygen to generate Qt compressed help files for MITK docs" OFF) MARK_AS_ADVANCED(USE_DOT MITK_DOXYGEN_BUILD_ALWAYS MITK_DOXYGEN_GENERATE_QCH_FILES) SET(HAVE_DOT "NO") IF(DOXYGEN_DOT_EXECUTABLE AND USE_DOT) SET(HAVE_DOT "YES") ENDIF() SET(MITK_DOXYGEN_OUTPUT_DIR ${PROJECT_BINARY_DIR}/Documentation/Doxygen CACHE PATH "Output directory for doxygen generated documentation." ) SET(MITK_DOXYGEN_TAGFILE_NAME ${MITK_DOXYGEN_OUTPUT_DIR}/MITK.tag CACHE INTERNAL "MITK Doxygen tag file") # This is relative to the working directory of the doxygen command SET(MITK_DOXYGEN_STYLESHEET mitk_doxygen.css) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${MITK_DOXYGEN_STYLESHEET} ${CMAKE_CURRENT_BINARY_DIR}/${MITK_DOXYGEN_STYLESHEET} @COPYONLY) # Create QCH files for MITK and external projects SET(MITK_DOXYGEN_GENERATE_QHP "NO") IF(MITK_DOXYGEN_GENERATE_QCH_FILES) FIND_PROGRAM(QT_HELPGENERATOR_EXECUTABLE NAMES qhelpgenerator qhelpgenerator-qt4 qhelpgenerator4 PATHS ${QT_BINARY_DIR} DOC "The location of the the Qt help generator executable" NO_DEFAULT_PATH ) MARK_AS_ADVANCED(QT_HELPGENERATOR_EXECUTABLE) IF(NOT QT_HELPGENERATOR_EXECUTABLE) MESSAGE(SEND_ERROR "The Qt help generator could not be found. Disabling qch generation") ELSE() SET(MITK_DOXYGEN_GENERATE_QHP "YES") ENDIF() # The name of the generated MITK qch file, relative to the # Doxygen HTML output folder SET(MITK_DOXYGEN_QCH_FILE "../MITK-${MITK_REVISION_ID}.qch") # Generating ITK and VTK docs it not done yet #OPTION(MITK_DOXYGEN_GENERATE_VTK_QCH_FILE "Use doxygen to generate a Qt compressed help file for VTK docs" OFF) #OPTION(MITK_DOXYGEN_GENERATE_ITK_QCH_FILE "Use doxygen to generate a Qt compressed help file for ITK docs" OFF) #MARK_AS_ADVANCED(MITK_DOXYGEN_GENERATE_VTK_QCH_FILE MITK_DOXYGEN_GENERATE_ITK_QCH_FILE) ENDIF() IF(MITK_USE_BLUEBERRY) FILE(RELATIVE_PATH _blueberry_doxygen_path ${MITK_DOXYGEN_OUTPUT_DIR}/html ${BLUEBERRY_DOXYGEN_OUTPUT_DIR}/html) SET(BLUEBERRY_DOXYGEN_TAGFILE "${BLUEBERRY_DOXYGEN_TAGFILE_NAME}=${_blueberry_doxygen_path}") SET(BLUEBERRY_DOXYGEN_LINK "BlueBerry Documentation") SET(MITK_XP_LINK "\\ref mitkExtPointsIndex") CONFIGURE_FILE(schema.css ${MITK_DOXYGEN_OUTPUT_DIR}/html/schema.css) SET(MITK_DOXYGEN_ENABLED_SECTIONS "${MITK_DOXYGEN_ENABLED_SECTIONS} BLUEBERRY") ENDIF(MITK_USE_BLUEBERRY) # Compile a doxygen input filter for processing CMake scripts INCLUDE(mitkFunctionCMakeDoxygenFilterCompile) mitkFunctionCMakeDoxygenFilterCompile(NAMESPACE "CMake") # Configure some doxygen options +IF(NOT MITK_DOXYGEN_INTERNAL_DOCS) + SET(MITK_DOXYGEN_INTERNAL_DOCS "NO") + SET(MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS "YES") + SET(MITK_DOXYGEN_EXCLUDE_PATTERNS "*_p.* *Private.h */internal/*") +ELSE() + SET(MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS "NO") + SET(MITK_DOXYGEN_EXCLUDE_PATTERNS "") +ENDIF() + IF(NOT MITK_DOXYGEN_GENERATE_TODOLIST) SET(MITK_DOXYGEN_GENERATE_TODOLIST "NO") ENDIF() IF(NOT MITK_DOXYGEN_GENERATE_BUGLIST) SET(MITK_DOXYGEN_GENERATE_BUGLIST "NO") ENDIF() IF(NOT MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS) SET(MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS "NO") ENDIF() IF(NOT MITK_DOXYGEN_UML_LOOK) SET(MITK_DOXYGEN_UML_LOOK "NO") ENDIF() IF(NOT MITK_DOXYGEN_GENERATE_DEPRECATEDLIST) SET(MITK_DOXYGEN_GENERATE_DEPRECATEDLIST "YES") ENDIF() IF(NOT DEFINED MITK_DOXYGEN_DOT_NUM_THREADS) SET(MITK_DOXYGEN_DOT_NUM_THREADS 0) ENDIF() CONFIGURE_FILE(Doxygen/MainPage.dox.in ${CMAKE_CURRENT_BINARY_DIR}/Doxygen/MainPage.dox) CONFIGURE_FILE(doxygen.conf.in ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf) IF(MITK_DOXYGEN_BUILD_ALWAYS) SET(_doc_in_all "ALL") ELSE() SET(_doc_in_all "") ENDIF() ADD_CUSTOM_TARGET(doc ${_doc_in_all} ${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ) IF (MITK_USE_BLUEBERRY) # convert the extension points schema files into html FIND_PACKAGE(Ant) IF(ANT_FOUND AND BLUEBERRY_DOC_TOOLS_DIR) LIST(APPEND MITK_XP_GLOB_EXPRESSIONS ${MITK_SOURCE_DIR}/CoreUI/Bundles/plugin.xml ${MITK_SOURCE_DIR}/Modules/Bundles/plugin.xml) FILE(GLOB_RECURSE _plugin_xmls ${MITK_XP_GLOB_EXPRESSIONS}) MACRO_CONVERT_SCHEMA(INPUT ${_plugin_xmls} OUTPUT_DIR "${MITK_DOXYGEN_OUTPUT_DIR}/html/extension-points/html" TARGET_NAME mitkXPDoc ) ADD_DEPENDENCIES(doc mitkXPDoc) IF(${PROJECT_NAME} STREQUAL "MITK") ADD_DEPENDENCIES(doc BlueBerryDoc) ENDIF() ENDIF(ANT_FOUND AND BLUEBERRY_DOC_TOOLS_DIR) ENDIF (MITK_USE_BLUEBERRY) #IF(MITK_DOXYGEN_GENERATE_ITK_QCH_FILE) # # add the command to generate the ITK documantation # ADD_CUSTOM_TARGET(doc-itk # COMMAND ${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.itk.conf) # ADD_DEPENDENCIES(doc doc-itk) #ENDIF() #IF(MITK_DOXYGEN_GENERATE_VTK_QCH_FILE) # # add the command to generate the VTK documantation # ADD_CUSTOM_TARGET(doc-vtk # COMMAND ${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.vtk.conf) # ADD_DEPENDENCIES(doc doc-vtk) #ENDIF() ELSE(DOXYGEN_FOUND) # copy blank documentation page to prevent QtHelp from being shown # copy the .qhc and .qch files to $MITK_BIN/mitk/bin/ExtBundles/resources/ CONFIGURE_FILE(pregenerated/MITKBlankPage.qch ${MITK_BINARY_DIR}/bin/ExtBundles/org.mitk.gui.qt.extapplication/resources/MITKBlankPage.qch COPYONLY) CONFIGURE_FILE(pregenerated/MitkExtQtHelpCollection.qhc ${MITK_BINARY_DIR}/bin/ExtBundles/org.mitk.gui.qt.extapplication/resources/MitkExtQtHelpCollection.qhc COPYONLY) ENDIF(DOXYGEN_FOUND) diff --git a/Documentation/Doxygen/Modules.dox b/Documentation/Doxygen/Modules.dox index 4776c93d90..57ee480242 100644 --- a/Documentation/Doxygen/Modules.dox +++ b/Documentation/Doxygen/Modules.dox @@ -1,115 +1,123 @@ +/** + \defgroup Core Core Classes + + \brief This category includes classes of the MITK Core library. +*/ + /** \defgroup Data Data Classes \ingroup DataManagement \brief This subcategory includes the data classes, e.g., for images (mitk::Image), surfaces (mitk::Surface), vessel-trees (mitk::VesselTreeData), etc. Data access classes are only included, if there is no equivalent in itk (see \ref ProcessAndAdaptorClasses "Process and Adaptor Classes" below). */ /** \defgroup IO IO Classes \ingroup DataManagement \brief This subcategory includes the IO classes to read or write data objects. */ /** \defgroup DataStorage Data Storage Classes \ingroup DataManagement \brief This subcategory includes the classes to store and retrieve objects from the mitk::DataStorage */ /** - \defgroup ProcessAdaptor Process and Adaptor Classes + \defgroup ProcessAdaptor Process and Adaptor Classes + \ingroup Core \anchor ProcessAndAdaptorClasses \brief This category includes process (algorithm) classes developed specifically for mitk and (mainly) adaptor classes for the integration of algorithms from other toolkits (currently vtk, itk). The itk adaptor classes are also useful for data access to mitk data objects. */ /** \defgroup Process Process Classes \ingroup ProcessAdaptor \brief This subcategory includes process (algorithm) classes developed specifically for mitk. */ /** \defgroup InteractionUndo Interaction and Undo Classes + \ingroup Core \brief This category includes classes that support the developer to create software that allows the user to interact with the data. This includes complex interactions that have multiple states (e.g., moving a handle of an active contour vs changing its local elasicity) and a concept to realize an undo/redo-mechanism. A detailed description of the rationale for these classes can be found in \ref InteractionPage. */ /** \defgroup Interaction Interaction Classes \ingroup InteractionUndo \brief This subcategory includes interaction classes (subclasses of mitk::StateMachine) that change the data according to the input of the user. For undo-support, the change is done by sending an OperationEvent to the respective data object, which changes itself accordingly. A detailed description of the rationale for these classes can be found in \ref InteractionPage. */ /** \defgroup Undo Undo Classes \ingroup InteractionUndo \brief This subcategory includes the undo/redo-specific classes. For undo-support, the change is done by sending an OperationEvent to the respective data object, which changes itself accordingly. A detailed description of the rationale for these classes can be found in \ref InteractionPage. */ /** \defgroup ToolManagerEtAl Classes related to the Segmentation bundle \brief A couple of classes related to the Segmentation bundle. See also \ref QmitkSegmentationTechnicalPage */ /** \defgroup Registration Registration \brief A couple of classes related to registration. */ /** \defgroup RigidRegistration Classes related to rigid registration \ingroup Registration \brief A couple of classes related to rigid registration. */ /** \defgroup PointBasedRegistration Classes related to point based registration \ingroup Registration \brief A couple of classes related to point based registration. */ /** \defgroup MITKPlugins MITK Plugins \brief This group includes all MITK Plugins */ diff --git a/Documentation/Doxygen/Modules/ModuleDataManagement.dox b/Documentation/Doxygen/Modules/ModuleDataManagement.dox index b0803201fd..e6f919743f 100644 --- a/Documentation/Doxygen/Modules/ModuleDataManagement.dox +++ b/Documentation/Doxygen/Modules/ModuleDataManagement.dox @@ -1,26 +1,27 @@ /** \defgroup DataManagement Data Management Classes +\ingroup Core \brief This category includes the data classes themselves (images, surfaces, etc.) as well as management classes to organize the data during run-time in a tree structure, called the data tree (mitk::DataTree). \section DataManagementOverview Overview There are two things in MITK: data itself and the organization of data in a tree. The data tree is used for communication between different parts of an application: The renderer uses it to find the things to render, functionalities use it to find "all images" or "all surfaces", and the event handling uses it to distribute events to interactors. For a list of all possible kind of data, look at \ref Data. \ref IO lists classes that help to read and write data sets. For an explanation of the data tree, iterators and tree nodes, refer to \ref DataTree. \ref Geometry groups all classes that describe the spatial/temporal position and orientation of data sets. */ diff --git a/Documentation/Doxygen/Modules/ModuleMicroServices.dox b/Documentation/Doxygen/Modules/ModuleMicroServices.dox new file mode 100644 index 0000000000..dd8176c71d --- /dev/null +++ b/Documentation/Doxygen/Modules/ModuleMicroServices.dox @@ -0,0 +1,10 @@ + +/** + +\defgroup MicroServices Micro Services Classes +\ingroup Core + +\brief This category includes classes related to the MITK Micro Services component. + + +*/ diff --git a/Documentation/Doxygen/Modules/ModuleVisualization.dox b/Documentation/Doxygen/Modules/ModuleVisualization.dox index 89106dc1c5..b63b43f940 100644 --- a/Documentation/Doxygen/Modules/ModuleVisualization.dox +++ b/Documentation/Doxygen/Modules/ModuleVisualization.dox @@ -1,44 +1,45 @@ /** \defgroup Visualization Visualization and Visualization Organization Classes +\ingroup Core \brief This category includes renderwindows (currently one for OpenGL), renderers (currently only one, for OpenGL-based renderwindows), mappers and classes for navigating in the data. \section overviewVisualization Rationale and overview Mappers visualize data objects of a specific classes by creating rendering primitives that interface to the graphics library (e.g., OpenGL, vtk). Renderers organize the rendering process. A Renderer contains a reference to a (sub-) data tree and asks the mappers of the data objects to render the data into the renderwindow it is associated to. More details can be found in the section on \ref Rendering. \subsection inthisgroupVisualization What belongs into this group \section implementVisualization Practical issues \section futureVisualization Plans for the future - Abort mechanism - level-of-detail rendering mechanism - allow multiple renderers per renderwindow - modified detection mechanism: - allow to detect whether a modification of data/property/dislaygeometry /camera requires to re-render. E.g., mark whether a property effects the rendering. - analyze which type of modification requires which kind of action, e.g.: if the displaygeometry or the color has changed, we do not need to resample an image, but we do need to redraw. The first step is to analyze which types of modifications (e.g., displaygeometry changed, properties changed; can we group these?) and actions exist. - improved design of navigation controllers, probably more focused on steppers (then on BaseController). Have in mind: - rotatable slices - dependent views: e.g., sequence of renderers showing series of consecutive slices (maybe realized as master stepper and dependent offset steppers) - consider time vs. slice stepping - use stepper mechanism for additional purposes, e.g., for animating transfer functions */ diff --git a/Documentation/Snippets/CMakeLists.txt b/Documentation/Snippets/CMakeLists.txt new file mode 100644 index 0000000000..65273aae45 --- /dev/null +++ b/Documentation/Snippets/CMakeLists.txt @@ -0,0 +1,5 @@ +if(BUILD_TESTING) + include_directories(${MITK_INCLUDE_DIRS} ${ITK_INCLUDE_DIRS} ${VTK_INCLUDE_DIRS}) + link_directories(${MITK_LINK_DIRECTORIES}) + mitkFunctionCompileSnippets("${CMAKE_CURRENT_SOURCE_DIR}" ${MITK_LIBRARIES}) +endif() diff --git a/Documentation/Snippets/uServices-activator/main.cpp b/Documentation/Snippets/uServices-activator/main.cpp new file mode 100644 index 0000000000..2c92be2050 --- /dev/null +++ b/Documentation/Snippets/uServices-activator/main.cpp @@ -0,0 +1,26 @@ +//! [0] +#include +#include + +class MyActivator : public mitk::ModuleActivator +{ + +public: + + void Load(mitk::ModuleContext* context) + { /* register stuff */ } + + + void Unload(mitk::ModuleContext* context) + { /* cleanup */ } + +}; + +MITK_EXPORT_MODULE_ACTIVATOR(mylibname, MyActivator) +//![0] + +int main(int argc, char* argv[]) +{ + MyActivator ma; + return 0; +} diff --git a/Documentation/doxygen.conf.in b/Documentation/doxygen.conf.in index 7eaf1b3a4b..71d798b150 100644 --- a/Documentation/doxygen.conf.in +++ b/Documentation/doxygen.conf.in @@ -1,1768 +1,1772 @@ # Doxyfile 1.7.3 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = MITK # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = @MITK_VERSION_STRING@ # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "Medical Imaging Interaction Toolkit" # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = @MITK_DOXYGEN_OUTPUT_DIR@ # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = "FIXME=\par Fix Me's:\n" \ "BlueBerry=\if BLUEBERRY" \ "endBlueBerry=\endif" \ "bundlemainpage{1}=\page \1" # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this # tag. The format is ext=language, where ext is a file extension, and language # is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, # C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make # doxygen treat .inc files as Fortran files (default is PHP), and .f files as C # (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions # you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols SYMBOL_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. -EXTRACT_LOCAL_CLASSES = NO +EXTRACT_LOCAL_CLASSES = @MITK_DOXYGEN_INTERNAL_DOCS@ # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. -HIDE_FRIEND_COMPOUNDS = NO +HIDE_FRIEND_COMPOUNDS = @MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS@ # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. -INTERNAL_DOCS = NO +INTERNAL_DOCS = @MITK_DOXYGEN_INTERNAL_DOCS@ # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = YES # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even if there is only one candidate or it is obvious which candidate to choose by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = @MITK_DOXYGEN_GENERATE_TODOLIST@ # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = @MITK_DOXYGEN_GENERATE_BUGLIST@ # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= @MITK_DOXYGEN_GENERATE_DEPRECATEDLIST@ # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = @MITK_DOXYGEN_ENABLED_SECTIONS@ # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 0 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. The create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = ./ \ @MITK_SOURCE_DIR@ \ @MITK_BINARY_DIR@ \ @MITK_DOXYGEN_ADDITIONAL_INPUT_DIRS@ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = *.h \ *.cpp \ *.dox \ *.txx \ + *.tpp \ *.cxx \ *.cmake # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = @MITK_SOURCE_DIR@/Utilities/vecmath/ \ @MITK_SOURCE_DIR@/Utilities/ann/ \ @MITK_SOURCE_DIR@/Utilities/glew/ \ @MITK_SOURCE_DIR@/Utilities/KWStyle/ \ @MITK_SOURCE_DIR@/Utilities/qwt/ \ @MITK_SOURCE_DIR@/Utilities/qxt/ \ @MITK_SOURCE_DIR@/Utilities/tinyxml/ \ @MITK_SOURCE_DIR@/Utilities/Poco/ \ @MITK_SOURCE_DIR@/Applications/PluginGenerator/ \ @MITK_SOURCE_DIR@/BlueBerry/ \ @MITK_SOURCE_DIR@/Deprecated/ \ @MITK_SOURCE_DIR@/Build/ \ + @MITK_SOURCE_DIR@/Documentation/Snippets/ \ @MITK_SOURCE_DIR@/Core/Testing/ \ @MITK_SOURCE_DIR@/CMake/PackageDepends \ @MITK_SOURCE_DIR@/CMake/QBundleTemplate \ @MITK_SOURCE_DIR@/CMakeExternals \ @MITK_SOURCE_DIR@/Modules/QmitkExt/vtkQtChartHeaders/ \ - @MITK_BINARY_DIR@/MITK-ProjectTemplate/ \ - @MITK_BINARY_DIR@/GeneratedTestProject/ \ + @MITK_BINARY_DIR@/MITK-ProjectTemplate/ \ + @MITK_BINARY_DIR@/GeneratedTestProject/ \ @MITK_DOXYGEN_ADDITIONAL_EXCLUDE_DIRS@ # The EXCLUDE_SYMLINKS tag can be used select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = moc_* \ Register* \ */files.cmake \ - @MITK_BINARY_DIR@/*.cmake + @MITK_BINARY_DIR@/*.cmake \ + @MITK_DOXYGEN_EXCLUDE_PATTERNS@ # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = @MITK_SOURCE_DIR@/Applications/Tutorial/ \ @MITK_SOURCE_DIR@/Core/Code/ \ @MITK_SOURCE_DIR@/Applications/Tests/QtFreeRender/ \ - @MITK_DOXYGEN_OUTPUT_DIR@/html/extension-points/html/ + @MITK_DOXYGEN_OUTPUT_DIR@/html/extension-points/html/ \ + @MITK_SOURCE_DIR@/Documentation/Snippets/ # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = YES # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = @MITK_SOURCE_DIR@/Documentation/Doxygen/ \ @MITK_SOURCE_DIR@/Documentation/Doxygen/Modules/ \ @MITK_SOURCE_DIR@/Documentation/Doxygen/Tutorial/ \ @MITK_SOURCE_DIR@/Core/DataStructures/ \ @MITK_SOURCE_DIR@ # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = *.cmake=@CMakeDoxygenFilter_EXECUTABLE@ # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 3 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = @MITK_DOXYGEN_STYLESHEET@ # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the stylesheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = @MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS@ # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = @MITK_DOXYGEN_GENERATE_QHP@ # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = @MITK_DOXYGEN_QCH_FILE@ # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = "org.mitk" # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = MITK # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = @QT_HELPGENERATOR_EXECUTABLE@ # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [0,1..20]) # that doxygen will group on one line in the generated HTML documentation. # Note that a value of 0 will completely suppress the enum values from appearing in the overview section. ENUM_VALUES_PER_LINE = 4 # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. GENERATE_TREEVIEW = YES # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 300 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the mathjax.org site, so you can quickly see the result without installing # MathJax, but it is strongly recommended to install a local copy of MathJax # before deployment. MATHJAX_RELPATH = http://www.mathjax.org/mathjax # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a PHP enabled web server instead of at the web client # using Javascript. Doxygen will generate the search PHP script and index # file to put on the web server. The advantage of the server # based approach is that it scales better to large projects and allows # full text search. The disadvantages are that it is more difficult to setup # and does not have live searching capabilities. SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = amssymb # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = itkNotUsed(x)= \ "itkSetMacro(name,type)= virtual void Set##name (type _arg);" \ "itkGetMacro(name,type)= virtual type Get##name ();" \ "itkGetConstMacro(name,type)= virtual type Get##name () const;" \ "itkSetStringMacro(name)= virtual void Set##name (const char* _arg);" \ "itkGetStringMacro(name)= virtual const char* Get##name () const;" \ "itkSetClampMacro(name,type,min,max)= virtual void Set##name (type _arg);" \ "itkSetObjectMacro(name,type)= virtual void Set##name (type* _arg);" \ "itkGetObjectMacro(name,type)= virtual type* Get##name ();" \ "itkSetConstObjectMacro(name,type)= virtual void Set##name ( const type* _arg);" \ "itkGetConstObjectMacro(name,type)= virtual const type* Get##name ();" \ "itkGetConstReferenceMacro(name,type)= virtual const type& Get##name ();" \ "itkGetConstReferenceObjectMacro(name,type)= virtual const type::Pointer& Get##name () const;" \ "itkBooleanMacro(name)= virtual void name##On (); virtual void name##Off ();" \ "itkSetVector2Macro(name,type)= virtual void Set##name (type _arg1, type _arg2) virtual void Set##name (type _arg[2]);" \ "itkGetVector2Macro(name,type)= virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2) const; virtual void Get##name (type _arg[2]) const;" \ "itkSetVector3Macro(name,type)= virtual void Set##name (type _arg1, type _arg2, type _arg3) virtual void Set##name (type _arg[3]);" \ "itkGetVector3Macro(name,type)= virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3) const; virtual void Get##name (type _arg[3]) const;" \ "itkSetVector4Macro(name,type)= virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4) virtual void Set##name (type _arg[4]);" \ "itkGetVector4Macro(name,type)= virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3, type& _arg4) const; virtual void Get##name (type _arg[4]) const;" \ "itkSetVector6Macro(name,type)= virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4, type _arg5, type _arg6) virtual void Set##name (type _arg[6]);" \ "itkGetVector6Macro(name,type)= virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3, type& _arg4, type& _arg5, type& _arg6) const; virtual void Get##name (type _arg[6]) const;" \ "itkSetVectorMacro(name,type,count)= virtual void Set##name(type data[]);" \ "itkGetVectorMacro(name,type,count)= virtual type* Get##name () const;" \ "itkNewMacro(type)= static Pointer New();" \ "itkTypeMacro(thisClass,superclass)= virtual const char *GetClassName() const;" \ "itkConceptMacro(name,concept)= enum { name = 0 };" \ "ITK_NUMERIC_LIMITS= std::numeric_limits" \ "ITK_TYPENAME= typename" \ "FEM_ABSTRACT_CLASS(thisClass,parentClass)= public: /** Standard Self typedef.*/ typedef thisClass Self; /** Standard Superclass typedef. */ typedef parentClass Superclass; /** Pointer or SmartPointer to an object. */ typedef Self* Pointer; /** Const pointer or SmartPointer to an object. */ typedef const Self* ConstPointer; private:" \ "FEM_CLASS(thisClass,parentClass)= FEM_ABSTRACT_CLASS(thisClass,parentClass) public: /** Create a new object from the existing one */ virtual Baseclass::Pointer Clone() const; /** Class ID for FEM object factory */ static const int CLID; /** Virtual function to access the class ID */ virtual int ClassID() const { return CLID; } /** Object creation in an itk compatible way */ static Self::Pointer New() { return new Self(); } private:" \ FREEVERSION \ ERROR_CHECKING \ HAS_TIFF \ HAS_JPEG \ HAS_NETLIB \ HAS_PNG \ HAS_ZLIB \ HAS_GLUT \ HAS_QT \ VCL_USE_NATIVE_STL=1 \ VCL_USE_NATIVE_COMPLEX=1 \ VCL_HAS_BOOL=1 \ VXL_BIG_ENDIAN=1 \ VXL_LITTLE_ENDIAN=0 \ VNL_DLL_DATA= \ size_t=vcl_size_t \ DOXYGEN_SKIP # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = @BLUEBERRY_DOXYGEN_TAGFILE@ # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = @MITK_DOXYGEN_TAGFILE_NAME@ # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = NO # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = @HAVE_DOT@ # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = @MITK_DOXYGEN_DOT_NUM_THREADS@ # By default doxygen will write a font called Helvetica to the output # directory and reference it in all dot files that doxygen generates. # When you want a differently looking font you can specify the font name # using DOT_FONTNAME. You need to make sure dot is able to find the font, # which can be done by putting it in a standard location or by setting the # DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory # containing the font. DOT_FONTNAME = FreeSans.ttf # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the output directory to look for the # FreeSans.ttf font (which doxygen will put there itself). If you specify a # different font using DOT_FONTNAME you can set the path where dot # can find it using this tag. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = @MITK_DOXYGEN_UML_LOOK@ # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = NO # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = NO # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, svg, gif or svg. # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = @DOXYGEN_DOT_PATH@ # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES diff --git a/Modules/Bundles/org.mitk.gui.qt.ext/files.cmake b/Modules/Bundles/org.mitk.gui.qt.ext/files.cmake index cfdfc7fdef..25763e1c3a 100644 --- a/Modules/Bundles/org.mitk.gui.qt.ext/files.cmake +++ b/Modules/Bundles/org.mitk.gui.qt.ext/files.cmake @@ -1,52 +1,55 @@ SET(SRC_CPP_FILES QmitkCommonWorkbenchWindowAdvisor.cpp QmitkExtPreferencePage.cpp QmitkInputDevicesPrefPage.cpp QmitkExtActionBarAdvisor.cpp QmitkExtWorkbenchWindowAdvisor.cpp QmitkExtFileOpenAction.cpp QmitkExtDnDFrameWidget.cpp QmitkExtFileSaveProjectAction.cpp ) SET(INTERNAL_CPP_FILES QmitkCommonExtPlugin.cpp + QmitkModuleView.cpp ) SET(UI_FILES ) SET(MOC_H_FILES src/internal/QmitkCommonExtPlugin.h src/internal/QmitkExtWorkbenchWindowAdvisorHack.h + src/internal/QmitkModuleView.h src/QmitkExtFileOpenAction.h src/QmitkExtFileSaveProjectAction.h src/QmitkExtDnDFrameWidget.h src/QmitkExtPreferencePage.h src/QmitkExtWorkbenchWindowAdvisor.h src/QmitkInputDevicesPrefPage.h ) SET(CACHED_RESOURCE_FILES # list of resource files which can be used by the plug-in # system without loading the plug-ins shared library, # for example the icon used in the menu and tabs for the # plug-in views in the workbench plugin.xml + resources/ModuleView.png ) SET(QRC_FILES # uncomment the following line if you want to use Qt resources resources/org_mitk_gui_qt_ext.qrc ) SET(CPP_FILES ) foreach(file ${SRC_CPP_FILES}) SET(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) SET(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/Modules/Bundles/org.mitk.gui.qt.ext/plugin.xml b/Modules/Bundles/org.mitk.gui.qt.ext/plugin.xml index 07393a4cb7..3ae9e69f12 100644 --- a/Modules/Bundles/org.mitk.gui.qt.ext/plugin.xml +++ b/Modules/Bundles/org.mitk.gui.qt.ext/plugin.xml @@ -1,18 +1,27 @@ - + + + + + diff --git a/Modules/Bundles/org.mitk.gui.qt.ext/resources/ModuleView.png b/Modules/Bundles/org.mitk.gui.qt.ext/resources/ModuleView.png new file mode 100644 index 0000000000..d6c2e526f4 Binary files /dev/null and b/Modules/Bundles/org.mitk.gui.qt.ext/resources/ModuleView.png differ diff --git a/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp b/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp index 0394e857f4..3057e3f1d7 100644 --- a/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp @@ -1,51 +1,55 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkCommonExtPlugin.h" #include #include "../QmitkExtPreferencePage.h" #include "../QmitkInputDevicesPrefPage.h" +#include "QmitkModuleView.h" + #include ctkPluginContext* QmitkCommonExtPlugin::_context = 0; void QmitkCommonExtPlugin::start(ctkPluginContext* context) { this->_context = context; QmitkExtRegisterClasses(); BERRY_REGISTER_EXTENSION_CLASS(QmitkExtPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkInputDevicesPrefPage, context) + + BERRY_REGISTER_EXTENSION_CLASS(QmitkModuleView, context) } void QmitkCommonExtPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) this->_context = 0; } ctkPluginContext* QmitkCommonExtPlugin::getContext() { return _context; } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_ext, QmitkCommonExtPlugin) diff --git a/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp b/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp new file mode 100644 index 0000000000..bf3613cb65 --- /dev/null +++ b/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp @@ -0,0 +1,100 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ +Version: $Revision: 18127 $ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "QmitkModuleView.h" + +#include + +#include +#include +#include +#include +#include + +QmitkModuleView::QmitkModuleView() + : tableView(0) +{ +} + +void QmitkModuleView::SetFocus() +{ + //tableView->setFocus(); +} + +void QmitkModuleView::CreateQtPartControl(QWidget *parent) +{ + QHBoxLayout* layout = new QHBoxLayout(); + layout->setMargin(0); + parent->setLayout(layout); + + tableView = new QTableView(parent); + QmitkModuleTableModel* tableModel = new QmitkModuleTableModel(tableView); + QSortFilterProxyModel* sortProxyModel = new QSortFilterProxyModel(tableView); + sortProxyModel->setSourceModel(tableModel); + sortProxyModel->setDynamicSortFilter(true); + tableView->setModel(sortProxyModel); + + tableView->verticalHeader()->hide(); + tableView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); + tableView->setSelectionBehavior(QAbstractItemView::SelectRows); + tableView->setSelectionMode(QAbstractItemView::ExtendedSelection); + tableView->setTextElideMode(Qt::ElideMiddle); + tableView->setSortingEnabled(true); + tableView->sortByColumn(0, Qt::AscendingOrder); + + tableView->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); + tableView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents); + tableView->horizontalHeader()->setResizeMode(5, QHeaderView::ResizeToContents); + tableView->horizontalHeader()->setStretchLastSection(true); + tableView->horizontalHeader()->setCascadingSectionResizes(true); + + layout->addWidget(tableView); + + if (viewState) + { + berry::IMemento::Pointer tableHeaderState = viewState->GetChild("tableHeader"); + if (tableHeaderState) + { + std::string key; + tableHeaderState->GetString("qsettings-key", key); + if (!key.empty()) + { + QSettings settings; + QByteArray ba = settings.value(QString::fromStdString(key)).toByteArray(); + tableView->horizontalHeader()->restoreState(ba); + } + } + } +} + +void QmitkModuleView::Init(berry::IViewSite::Pointer site, berry::IMemento::Pointer memento) +{ + berry::QtViewPart::Init(site, memento); + viewState = memento; +} + +void QmitkModuleView::SaveState(berry::IMemento::Pointer memento) +{ + QString key = "QmitkModuleView_tableHeader"; + QByteArray ba = tableView->horizontalHeader()->saveState(); + QSettings settings; + settings.setValue(key, ba); + + berry::IMemento::Pointer tableHeaderState = memento->CreateChild("tableHeader"); + tableHeaderState->PutString("qsettings-key", key.toStdString()); +} diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.h similarity index 59% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.h index c09a6d26ee..633601a808 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Modules/Bundles/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.h @@ -1,33 +1,47 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ Version: $Revision: 18127 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include -#include "QmitkExtExports.h" -#include -#include +#ifndef QMITKMODULEVIEW_H +#define QMITKMODULEVIEW_H -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog +#include + +class QTableView; + +class QmitkModuleView : public berry::QtViewPart { Q_OBJECT - public: +public: + QmitkModuleView(); + +protected: - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); + void SetFocus(); + void CreateQtPartControl(QWidget *parent); + void Init(berry::IViewSite::Pointer site, berry::IMemento::Pointer memento); + void SaveState(berry::IMemento::Pointer memento); + +private: + + QTableView* tableView; + berry::IMemento::Pointer viewState; }; + +#endif // QMITKMODULEVIEW_H diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.cpp b/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.cpp index ef040537ae..04275baf08 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.cpp +++ b/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.cpp @@ -1,59 +1,60 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ Version: $Revision: 18127 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkAboutDialog.h" +#include #include +#include "QmitkModulesDialog.h" #include #include #include QmitkAboutDialog::QmitkAboutDialog(QWidget* parent, Qt::WindowFlags f) :QDialog(parent, f) { Ui::QmitkAboutDialog gui; gui.setupUi(this); QString mitkRevision(MITK_REVISION); //mitkRevision.replace( QRegExp("[^0-9]+(\\d+).*"), "\\1"); QString itkVersion = "%1.%2.%3"; itkVersion = itkVersion.arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH); QString vtkVersion = "%1.%2.%3"; vtkVersion = vtkVersion.arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION); gui.m_PropsLabel->setText(gui.m_PropsLabel->text().arg(itkVersion, QT_VERSION_STR, vtkVersion, mitkRevision)); - - //general - //connect( m_GUI->btnQuitApplication,SIGNAL(clicked()), qApp, SLOT(closeAllWindows()) ); + QPushButton* btnModules = new QPushButton(QIcon(":/qmitk/ModuleView.png"), "Modules"); + gui.m_ButtonBox->addButton(btnModules, QDialogButtonBox::ActionRole); + + connect(btnModules, SIGNAL(clicked()), this, SLOT(ShowModules())); + connect(gui.m_ButtonBox, SIGNAL(rejected()), this, SLOT(reject())); } QmitkAboutDialog::~QmitkAboutDialog() { } - - - - - - - - +void QmitkAboutDialog::ShowModules() +{ + QmitkModulesDialog dialog(this); + dialog.exec(); +} diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h index c09a6d26ee..66eeaf5073 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h @@ -1,33 +1,37 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ Version: $Revision: 18127 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include #include "QmitkExtExports.h" #include #include class QmitkExt_EXPORT QmitkAboutDialog : public QDialog { Q_OBJECT public: - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); + QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); virtual ~QmitkAboutDialog(); +protected slots: + + void ShowModules(); + }; diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialogGUI.ui b/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialogGUI.ui index 02314cce65..6e69952c4c 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialogGUI.ui +++ b/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialogGUI.ui @@ -1,217 +1,198 @@ QmitkAboutDialog 0 0 534 436 About false - - + + + + + + + + + + 0 + 0 + + + + + MS Sans Serif + 48 + 75 + true + + + + MITK + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + + + + + + 0 + 0 + + + + Version 1.0 + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + + + + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 40 + 20 + + + + + + + + + 84 + 56 + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="http://www.dkfz.de/en/mbi/"><span style=" text-decoration: underline; color:#0000ff;"><img src=":/qmitk/Logo_mbiATdkfz_small.png" /></span></a></p></body></html> + + + true + + + true + + + + + + true 0 0 - 424 - 642 + 498 + 629 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">MITK 3M3 has been developed in joint effort by the division of Medical and Biological Informatics at the German Cancer Research Institute (</span><a href="http://www.dkfz.de/en/mbi/index.html"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">http://www.dkfz.de/en/mbi/index.html</span></a><span style=" font-size:8pt;">) and mint medical (</span><a href="http://mint-medical.com/"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">http://mint-medical.com/</span></a><span style=" font-size:8pt;">).</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">To contact the MITK 3M3 Team, please use the </span><a href="http://mint-medical.de/mitk-3m3#feedback"><span style=" text-decoration: underline; color:#0000ff;">feedback form.</span></a></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The team:</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Matthias Baumhauer</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Thiago dos Santos</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Markus Fangerau</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Alfred Franz</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Klaus Fritzsche</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Ingmar Gergel</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Caspar Goch</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Anja Groch</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Philipp Hartmann</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Jan Hering</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Johannes Kast</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Kerstin-Meike Knautz</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Lena Maier-Hein</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Daniel Maleike</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Hans-Peter Meinzer</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Michael Müller</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Jochen Neuhaus</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Marco Nolden</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Urte Rietdorf</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Sabrina Schmidt</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Tobias Schwarz</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Alexander Seitel</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Mathias Seitel</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Daniel Stein</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Johanna Stuke</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Diana Wald</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Xin Wang</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Ingmar Wegner </span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Jan Wörner</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Sascha Zelzer</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Third party products used in this software are:</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The </span><a href="http://www.boost.org/"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">boost</span></a><span style=" font-size:8pt;"> C++ libraries (version 1.40)</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The </span><a href="http://dicom.offis.de/dcmtk.php.en"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">DCMTK</span></a><span style=" font-size:8pt;"> libraries (version 3.5.4)</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The Insight Segmentation and Registration Toolkit (</span><a href="http://www.itk.org/"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">ITK</span></a><span style=" font-size:8pt;">) (version %1)</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The </span><a href="http://qt.nokia.com/products"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">Qt</span></a><span style=" font-size:8pt;"> libraries (version %2)</span></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">The Visualization Toolkit (</span><a href="http://www.vtk.org/"><span style=" font-size:8pt; text-decoration: underline; color:#0000ff;">VTK</span></a><span style=" font-size:8pt;">) (version %3)</span></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8pt;"></p> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">MITK (revision %4)</span></p></body></html> +</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">MITK has been developed in joint effort by the division of Medical and Biological Informatics at the German Cancer Research Institute (</span><a href="http://www.dkfz.de/en/mbi/index.html"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">http://www.dkfz.de/en/mbi/index.html</span></a><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">) and mint medical (</span><a href="http://mint-medical.com/"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">http://mint-medical.com/</span></a><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">).</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">To contact the MITK Team, please use the </span><a href="http://mint-medical.de/mitk-3m3#feedback"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">feedback form.</span></a></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">The team:</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Matthias Baumhauer</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Thiago dos Santos</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Markus Fangerau</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Alfred Franz</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Klaus Fritzsche</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Ingmar Gergel</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Caspar Goch</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Anja Groch</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Philipp Hartmann</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Jan Hering</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Johannes Kast</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Kerstin-Meike Knautz</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Lena Maier-Hein</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Daniel Maleike</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Hans-Peter Meinzer</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Michael Müller</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Jochen Neuhaus</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Marco Nolden</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Urte Rietdorf</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Sabrina Schmidt</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Tobias Schwarz</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Alexander Seitel</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Mathias Seitel</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Daniel Stein</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Johanna Stuke</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Diana Wald</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Xin Wang</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Ingmar Wegner </span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Jan Wörner</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Sascha Zelzer</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">Third party products used in this software are:</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">The </span><a href="http://www.boost.org/"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">boost</span></a><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> C++ libraries (version 1.40)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">The </span><a href="http://dicom.offis.de/dcmtk.php.en"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">DCMTK</span></a><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> libraries (version 3.5.4)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">The Insight Segmentation and Registration Toolkit (</span><a href="http://www.itk.org/"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">ITK</span></a><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">) (version %1)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">The </span><a href="http://qt.nokia.com/products"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">Qt</span></a><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;"> libraries (version %2)</span></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">The Visualization Toolkit (</span><a href="http://www.vtk.org/"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; text-decoration: underline; color:#0000ff;">VTK</span></a><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">) (version %3)</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt;">MITK (revision %4)</span></p></body></html> true true - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 84 - 56 - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="http://www.dkfz.de/en/mbi/"><span style=" text-decoration: underline; color:#0000ff;"><img src=":/qmitk/Logo_mbiATdkfz_small.png" /></span></a></p></body></html> - - - true - - - true + + + + QDialogButtonBox::Close - - - - - - - 0 - 0 - - - - - MS Sans Serif - 48 - 75 - true - - - - MITK - - - Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft - - - - - - - - 0 - 0 - - - - Version 1.0 - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - + diff --git a/Modules/QmitkExt/QmitkModuleTableModel.cpp b/Modules/QmitkExt/QmitkModuleTableModel.cpp new file mode 100644 index 0000000000..7694eb64df --- /dev/null +++ b/Modules/QmitkExt/QmitkModuleTableModel.cpp @@ -0,0 +1,182 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ +Version: $Revision: 18127 $ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "QmitkModuleTableModel.h" + +#include +#include +#include + +#include + + +class QmitkModuleTableModelPrivate +{ + +public: + + QmitkModuleTableModelPrivate(QmitkModuleTableModel* q, mitk::ModuleContext* mc) + : q(q), context(mc) + { + std::vector m; + context->GetModules(m); + for (std::vector::const_iterator it = m.begin(); + it != m.end(); ++it) + { + modules[(*it)->GetModuleId()] = *it; + } + + context->AddModuleListener(this, &QmitkModuleTableModelPrivate::ModuleChanged); + } + + ~QmitkModuleTableModelPrivate() + { + context->RemoveModuleListener(this, &QmitkModuleTableModelPrivate::ModuleChanged); + } + + void ModuleChanged(const mitk::ModuleEvent& event) + { + q->insertModule(event.GetModule()); + } + + QmitkModuleTableModel* q; + mitk::ModuleContext* context; + QMap modules; +}; + +QmitkModuleTableModel::QmitkModuleTableModel(QObject* parent, mitk::ModuleContext* mc) + : QAbstractTableModel(parent), + d(new QmitkModuleTableModelPrivate(this, mc ? mc : mitk::GetModuleContext())) +{ +} + +QmitkModuleTableModel::~QmitkModuleTableModel() +{ + delete d; +} + +int QmitkModuleTableModel::rowCount(const QModelIndex& parent) const +{ + if (parent.isValid()) return 0; + return d->modules.size(); +} + +int QmitkModuleTableModel::columnCount(const QModelIndex& parent) const +{ + if (parent.isValid()) return 0; + return 7; +} + +QVariant QmitkModuleTableModel::data(const QModelIndex& index, int role) const +{ + if (!index.isValid()) return QVariant(); + + if (role == Qt::DisplayRole) + { + mitk::Module* module = d->modules[index.row()+1]; + switch(index.column()) + { + case 0: return QVariant::fromValue(static_cast(module->GetModuleId())); + case 1: return QString::fromStdString(module->GetName()); + case 2: return QString::fromStdString(module->GetVersion().ToString()); + case 3: + { + QString deps = QString::fromStdString(module->GetProperty(mitk::Module::PROP_MODULE_DEPENDS())); + QString libDeps = QString::fromStdString(module->GetProperty(mitk::Module::PROP_LIB_DEPENDS())); + if (!libDeps.isEmpty()) + { + if (!deps.isEmpty()) deps.append(", "); + deps.append(libDeps); + } + return deps; + } + case 4: return QString::fromStdString(module->GetProperty(mitk::Module::PROP_PACKAGE_DEPENDS())); + case 6: return QString::fromStdString(module->GetLocation()); + } + } + else if (role == Qt::CheckStateRole) + { + if (index.column() == 5) + { + mitk::Module* module = d->modules[index.row()+1]; + return module->GetProperty(mitk::Module::PROP_QT()) == "true" ? Qt::Checked : Qt::Unchecked; + } + } + else if (role == Qt::ForegroundRole) + { + mitk::Module* module = d->modules[index.row()+1]; + if (!module->IsLoaded()) + { + return QBrush(Qt::gray); + } + } + else if (role == Qt::ToolTipRole) + { + mitk::Module* module = d->modules[index.row()+1]; + QString id = QString::number(module->GetModuleId()); + QString name = QString::fromStdString(module->GetName()); + QString version = QString::fromStdString(module->GetVersion().ToString()); + QString moduleDepends = QString::fromStdString(module->GetProperty(mitk::Module::PROP_MODULE_DEPENDS())); + QString packageDepends = QString::fromStdString(module->GetProperty(mitk::Module::PROP_PACKAGE_DEPENDS())); + QString libDepends = QString::fromStdString(module->GetProperty(mitk::Module::PROP_LIB_DEPENDS())); + QString location = QString::fromStdString(module->GetLocation()); + QString isQt = module->GetProperty(mitk::Module::PROP_QT()) == "true" ? "Yes" : "No"; + QString state = module->IsLoaded() ? "Loaded" : "Unloaded"; + + QString tooltip = "Id: %1\nName: %2\nVersion: %3\nModule Dependencies: %4\nPackage Dependencies: %5\nLibrary Dependencies: %6\nLocation: %7\nQt Module: %8\nState: %9"; + + return tooltip.arg(id, name, version, moduleDepends, packageDepends, libDepends, location, isQt, state); + } + return QVariant(); +} + +QVariant QmitkModuleTableModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if (orientation != Qt::Horizontal || role != Qt::DisplayRole) + return QVariant(); + + switch (section) + { + case 0: return "Id"; + case 1: return "Name"; + case 2: return "Version"; + case 3: return "Depends"; + case 4: return "Packages"; + case 5: return "Qt"; + case 6: return "Location"; + } + return QVariant(); +} + +void QmitkModuleTableModel::insertModule(mitk::Module* module) +{ + long id = module->GetModuleId(); + if (d->modules.contains(id)) + { + d->modules[id] = module; + emit dataChanged(createIndex(id-1, 0), createIndex(id-1, columnCount())); + return; + } + else + { + beginInsertRows(QModelIndex(), id-1, id-1); + d->modules[id] = module; + endInsertRows(); + } +} + diff --git a/Modules/QmitkExt/QmitkModuleTableModel.h b/Modules/QmitkExt/QmitkModuleTableModel.h new file mode 100644 index 0000000000..4fb2b87758 --- /dev/null +++ b/Modules/QmitkExt/QmitkModuleTableModel.h @@ -0,0 +1,60 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ +Version: $Revision: 18127 $ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#ifndef QMITKMODULETABLEMODEL_H +#define QMITKMODULETABLEMODEL_H + +#include +#include + +#include + +namespace mitk { +class ModuleContext; +class Module; +} + +class QmitkModuleTableModelPrivate; + +class QmitkExt_EXPORT QmitkModuleTableModel : public QAbstractTableModel +{ +public: + + QmitkModuleTableModel(QObject* parent = 0, mitk::ModuleContext* mc = 0); + ~QmitkModuleTableModel(); + +protected: + + int rowCount(const QModelIndex& parent = QModelIndex()) const; + + int columnCount(const QModelIndex& parent = QModelIndex()) const; + + QVariant data(const QModelIndex& index, int role) const; + + QVariant headerData(int section, Qt::Orientation orientation, int role) const; + +private: + + friend class QmitkModuleTableModelPrivate; + + void insertModule(mitk::Module* module); + + QmitkModuleTableModelPrivate* const d; +}; + +#endif // QMITKMODULETABLEMODEL_H diff --git a/Modules/QmitkExt/QmitkModulesDialog.cpp b/Modules/QmitkExt/QmitkModulesDialog.cpp new file mode 100644 index 0000000000..b101d4c87b --- /dev/null +++ b/Modules/QmitkExt/QmitkModulesDialog.cpp @@ -0,0 +1,66 @@ +/*========================================================================= + +Program: Medical Imaging & Interaction Toolkit +Language: C++ +Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ +Version: $Revision: 18127 $ + +Copyright (c) German Cancer Research Center, Division of Medical and +Biological Informatics. All rights reserved. +See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notices for more information. + +=========================================================================*/ + + +#include "QmitkModulesDialog.h" + +#include +#include +#include +#include +#include + +#include "QmitkModuleTableModel.h" + +QmitkModulesDialog::QmitkModulesDialog(QWidget *parent, Qt::WindowFlags f) : + QDialog(parent, f) +{ + this->setWindowTitle("MITK Modules"); + + QVBoxLayout* layout = new QVBoxLayout(); + this->setLayout(layout); + + QTableView* tableView = new QTableView(this); + QmitkModuleTableModel* tableModel = new QmitkModuleTableModel(tableView); + QSortFilterProxyModel* sortProxyModel = new QSortFilterProxyModel(tableView); + sortProxyModel->setSourceModel(tableModel); + sortProxyModel->setDynamicSortFilter(true); + tableView->setModel(sortProxyModel); + + tableView->verticalHeader()->hide(); + tableView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); + tableView->setSelectionBehavior(QAbstractItemView::SelectRows); + tableView->setSelectionMode(QAbstractItemView::ExtendedSelection); + tableView->setTextElideMode(Qt::ElideMiddle); + tableView->setSortingEnabled(true); + tableView->sortByColumn(0, Qt::AscendingOrder); + + tableView->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); + tableView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents); + tableView->horizontalHeader()->setResizeMode(5, QHeaderView::ResizeToContents); + tableView->horizontalHeader()->setStretchLastSection(true); + tableView->horizontalHeader()->setCascadingSectionResizes(true); + + layout->addWidget(tableView); + + QDialogButtonBox* btnBox = new QDialogButtonBox(QDialogButtonBox::Close); + layout->addWidget(btnBox); + + this->resize(800, 600); + + connect(btnBox, SIGNAL(rejected()), this, SLOT(reject())); +} diff --git a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h b/Modules/QmitkExt/QmitkModulesDialog.h similarity index 70% copy from Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h copy to Modules/QmitkExt/QmitkModulesDialog.h index c09a6d26ee..c8e648af42 100644 --- a/Modules/QmitkExt/QmitkAboutDialog/QmitkAboutDialog.h +++ b/Modules/QmitkExt/QmitkModulesDialog.h @@ -1,33 +1,35 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ Version: $Revision: 18127 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ + +#ifndef QMITKMODULESDIALOG_H +#define QMITKMODULESDIALOG_H + #include -#include "QmitkExtExports.h" -#include -#include +#include -class QmitkExt_EXPORT QmitkAboutDialog : public QDialog +class QmitkExt_EXPORT QmitkModulesDialog : public QDialog { - Q_OBJECT - public: +public: - QmitkAboutDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); - virtual ~QmitkAboutDialog(); + explicit QmitkModulesDialog(QWidget *parent = 0, Qt::WindowFlags f = Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); }; + +#endif // QMITKMODULESDIALOG_H diff --git a/Modules/QmitkExt/files.cmake b/Modules/QmitkExt/files.cmake index b5aaea16f6..f17db75f4d 100644 --- a/Modules/QmitkExt/files.cmake +++ b/Modules/QmitkExt/files.cmake @@ -1,255 +1,258 @@ SET(CPP_FILES QmitkApplicationBase/QmitkCommonFunctionality.cpp #QmitkModels/QmitkDataStorageListModel.cpp #QmitkModels/QmitkPropertiesTableModel.cpp #QmitkModels/QmitkDataStorageTreeModel.cpp #QmitkModels/QmitkDataStorageTableModel.cpp #QmitkModels/QmitkPropertyDelegate.cpp #QmitkModels/QmitkPointListModel.cpp #QmitkAlgorithmFunctionalityComponent.cpp #QmitkBaseAlgorithmComponent.cpp QmitkAboutDialog/QmitkAboutDialog.cpp #QmitkFunctionalityComponents/QmitkSurfaceCreatorComponent.cpp #QmitkFunctionalityComponents/QmitkPixelGreyValueManipulatorComponent.cpp #QmitkFunctionalityComponents/QmitkConnectivityFilterComponent.cpp #QmitkFunctionalityComponents/QmitkImageCropperComponent.cpp #QmitkFunctionalityComponents/QmitkSeedPointSetComponent.cpp #QmitkFunctionalityComponents/QmitkSurfaceTransformerComponent.cpp QmitkPropertyObservers/QmitkBasePropertyView.cpp QmitkPropertyObservers/QmitkBoolPropertyWidget.cpp QmitkPropertyObservers/QmitkColorPropertyEditor.cpp QmitkPropertyObservers/QmitkColorPropertyView.cpp QmitkPropertyObservers/QmitkEnumerationPropertyWidget.cpp QmitkPropertyObservers/QmitkNumberPropertyEditor.cpp QmitkPropertyObservers/QmitkNumberPropertyView.cpp QmitkPropertyObservers/QmitkPropertyViewFactory.cpp QmitkPropertyObservers/QmitkStringPropertyEditor.cpp QmitkPropertyObservers/QmitkStringPropertyOnDemandEdit.cpp QmitkPropertyObservers/QmitkStringPropertyView.cpp QmitkPropertyObservers/QmitkNumberPropertySlider.cpp QmitkPropertyObservers/QmitkUGCombinedRepresentationPropertyWidget.cpp qclickablelabel.cpp #QmitkAbortEventFilter.cpp # QmitkApplicationCursor.cpp QmitkCallbackFromGUIThread.cpp QmitkEditPointDialog.cpp QmitkExtRegisterClasses.cpp QmitkFileChooser.cpp # QmitkRenderingManager.cpp # QmitkRenderingManagerFactory.cpp # QmitkRenderWindow.cpp # QmitkEventAdapter.cpp QmitkFloatingPointSpanSlider.cpp QmitkColorTransferFunctionCanvas.cpp QmitkSlicesInterpolator.cpp QmitkStandardViews.cpp QmitkStepperAdapter.cpp # QmitkLineEditLevelWindowWidget.cpp # mitkSliderLevelWindowWidget.cpp # QmitkLevelWindowWidget.cpp # QmitkPointListWidget.cpp # QmitkPointListView.cpp QmitkPiecewiseFunctionCanvas.cpp QmitkSliderNavigatorWidget.cpp QmitkTransferFunctionCanvas.cpp QmitkCrossWidget.cpp #QmitkLevelWindowRangeChangeDialog.cpp #QmitkLevelWindowPresetDefinitionDialog.cpp # QmitkLevelWindowWidgetContextMenu.cpp QmitkSliceWidget.cpp # QmitkStdMultiWidget.cpp QmitkTransferFunctionWidget.cpp QmitkTransferFunctionGeneratorWidget.cpp QmitkSelectableGLWidget.cpp QmitkToolReferenceDataSelectionBox.cpp QmitkToolWorkingDataSelectionBox.cpp QmitkToolGUIArea.cpp QmitkToolSelectionBox.cpp # QmitkPropertyListPopup.cpp QmitkToolGUI.cpp QmitkNewSegmentationDialog.cpp QmitkPaintbrushToolGUI.cpp QmitkDrawPaintbrushToolGUI.cpp QmitkErasePaintbrushToolGUI.cpp QmitkBinaryThresholdToolGUI.cpp QmitkCalculateGrayValueStatisticsToolGUI.cpp QmitkCopyToClipBoardDialog.cpp # QmitkMaterialEditor.cpp # QmitkMaterialShowcase.cpp # QmitkPropertiesTableEditor.cpp QmitkPrimitiveMovieNavigatorWidget.cpp # QmitkDataStorageComboBox.cpp QmitkHistogram.cpp QmitkHistogramWidget.cpp QmitkPlotWidget.cpp QmitkPlotDialog.cpp QmitkPointListModel.cpp QmitkPointListView.cpp QmitkPointListWidget.cpp QmitkPointListViewWidget.cpp QmitkCorrespondingPointSetsView.cpp QmitkCorrespondingPointSetsModel.cpp QmitkCorrespondingPointSetsWidget.cpp QmitkVideoBackground.cpp QmitkHotkeyLineEdit.cpp QmitkErodeToolGUI.cpp QmitkDilateToolGUI.cpp QmitkMorphologicToolGUI.cpp QmitkOpeningToolGUI.cpp QmitkClosingToolGUI.cpp QmitkBinaryThresholdULToolGUI.cpp QmitkPixelManipulationToolGUI.cpp QmitkRegionGrow3DToolGUI.cpp QmitkToolRoiDataSelectionBox.cpp QmitkBoundingObjectWidget.cpp + + QmitkModuleTableModel.cpp + QmitkModulesDialog.cpp ) IF ( NOT ${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION}.${VTK_BUILD_VERSION} VERSION_LESS 5.4.0 ) SET(CPP_FILES ${CPP_FILES} QmitkVtkHistogramWidget.cpp QmitkVtkLineProfileWidget.cpp ) ENDIF() IF (NOT APPLE) SET(CPP_FILES ${CPP_FILES} QmitkBaseComponent.cpp QmitkBaseFunctionalityComponent.cpp QmitkFunctionalityComponentContainer.cpp QmitkFunctionalityComponents/QmitkThresholdComponent.cpp ) ENDIF() QT4_ADD_RESOURCES(CPP_FILES resources/QmitkResources.qrc) SET(MOC_H_FILES QmitkPropertyObservers/QmitkBasePropertyView.h QmitkPropertyObservers/QmitkBoolPropertyWidget.h QmitkPropertyObservers/QmitkColorPropertyEditor.h QmitkPropertyObservers/QmitkColorPropertyView.h QmitkPropertyObservers/QmitkEnumerationPropertyWidget.h QmitkPropertyObservers/QmitkNumberPropertyEditor.h QmitkPropertyObservers/QmitkNumberPropertyView.h QmitkPropertyObservers/QmitkStringPropertyEditor.h QmitkPropertyObservers/QmitkStringPropertyOnDemandEdit.h QmitkPropertyObservers/QmitkStringPropertyView.h QmitkPropertyObservers/QmitkNumberPropertySlider.h QmitkPropertyObservers/QmitkUGCombinedRepresentationPropertyWidget.h # QmitkFunctionalityComponents/QmitkSurfaceCreatorComponent.h #QmitkFunctionalityComponents/QmitkPixelGreyValueManipulatorComponent.h # QmitkFunctionalityComponents/QmitkConnectivityFilterComponent.h # QmitkFunctionalityComponents/QmitkImageCropperComponent.h # QmitkFunctionalityComponents/QmitkSeedPointSetComponent.h # QmitkFunctionalityComponents/QmitkSurfaceTransformerComponent.h qclickablelabel.h QmitkCallbackFromGUIThread.h QmitkEditPointDialog.h #QmitkAlgorithmFunctionalityComponent.h #QmitkBaseAlgorithmComponent.h QmitkStandardViews.h QmitkStepperAdapter.h QmitkSliderNavigatorWidget.h QmitkSliceWidget.h QmitkSlicesInterpolator.h QmitkColorTransferFunctionCanvas.h QmitkPiecewiseFunctionCanvas.h QmitkTransferFunctionCanvas.h QmitkFloatingPointSpanSlider.h QmitkCrossWidget.h QmitkTransferFunctionWidget.h QmitkTransferFunctionGeneratorWidget.h QmitkToolGUIArea.h QmitkToolGUI.h QmitkToolReferenceDataSelectionBox.h QmitkToolWorkingDataSelectionBox.h QmitkToolSelectionBox.h # QmitkPropertyListPopup.h #QmitkSelectableGLWidget.h QmitkNewSegmentationDialog.h QmitkPaintbrushToolGUI.h QmitkDrawPaintbrushToolGUI.h QmitkErasePaintbrushToolGUI.h QmitkBinaryThresholdToolGUI.h QmitkCalculateGrayValueStatisticsToolGUI.h QmitkCopyToClipBoardDialog.h QmitkPrimitiveMovieNavigatorWidget.h QmitkPlotWidget.h QmitkPointListModel.h QmitkPointListView.h QmitkPointListWidget.h QmitkPointListViewWidget.h QmitkCorrespondingPointSetsView.h QmitkCorrespondingPointSetsModel.h QmitkCorrespondingPointSetsWidget.h QmitkHistogramWidget.h QmitkVideoBackground.h QmitkFileChooser.h QmitkHotkeyLineEdit.h QmitkAboutDialog/QmitkAboutDialog.h QmitkErodeToolGUI.h QmitkDilateToolGUI.h QmitkMorphologicToolGUI.h QmitkOpeningToolGUI.h QmitkClosingToolGUI.h QmitkBinaryThresholdULToolGUI.h QmitkPixelManipulationToolGUI.h QmitkRegionGrow3DToolGUI.h QmitkToolRoiDataSelectionBox.h QmitkBoundingObjectWidget.h QmitkPlotWidget.h ) IF ( NOT ${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION}.${VTK_BUILD_VERSION} VERSION_LESS 5.4.0 ) SET(MOC_H_FILES ${MOC_H_FILES} QmitkVtkHistogramWidget.h QmitkVtkLineProfileWidget.h ) ENDIF() IF (NOT APPLE) SET(MOC_H_FILES ${MOC_H_FILES} QmitkBaseComponent.h QmitkBaseFunctionalityComponent.h QmitkFunctionalityComponentContainer.h QmitkFunctionalityComponents/QmitkThresholdComponent.h ) ENDIF() SET(UI_FILES QmitkSliderNavigator.ui # QmitkLevelWindowRangeChange.ui # QmitkLevelWindowPresetDefinition.ui # QmitkLevelWindowWidget.ui QmitkSliceWidget.ui QmitkTransferFunctionWidget.ui QmitkTransferFunctionGeneratorWidget.ui QmitkSelectableGLWidget.ui QmitkPrimitiveMovieNavigatorWidget.ui QmitkFunctionalityComponentContainerControls.ui QmitkFunctionalityComponents/QmitkThresholdComponentControls.ui QmitkAboutDialog/QmitkAboutDialogGUI.ui ) SET(QRC_FILES QmitkExt.qrc ) diff --git a/Modules/QmitkExt/resources/ModuleView.png b/Modules/QmitkExt/resources/ModuleView.png new file mode 100644 index 0000000000..ce0f4af124 Binary files /dev/null and b/Modules/QmitkExt/resources/ModuleView.png differ diff --git a/Modules/QmitkExt/resources/QmitkResources.qrc b/Modules/QmitkExt/resources/QmitkResources.qrc index 653537ad8f..fbeade59c1 100644 --- a/Modules/QmitkExt/resources/QmitkResources.qrc +++ b/Modules/QmitkExt/resources/QmitkResources.qrc @@ -1,17 +1,18 @@ - - Logo_mbiATdkfz_small.png - cross.png - QmitkStandardViewsDialogBar.xpm - play.xpm - stop.xpm - logo_mint-medical.png - Logo_mbiATdkfz_gross.png - btnSetPoints.png - btnAddPointSet.png - btnMoveUp.png - btnMoveDown.png - btnRemovePoint.png - btnSwapSets.png - + + Logo_mbiATdkfz_small.png + cross.png + QmitkStandardViewsDialogBar.xpm + play.xpm + stop.xpm + logo_mint-medical.png + Logo_mbiATdkfz_gross.png + btnSetPoints.png + btnAddPointSet.png + btnMoveUp.png + btnMoveDown.png + btnRemovePoint.png + btnSwapSets.png + ModuleView.png + diff --git a/Utilities/glew/CMakeLists.txt b/Utilities/glew/CMakeLists.txt index 718039e4b7..d366020a1a 100644 --- a/Utilities/glew/CMakeLists.txt +++ b/Utilities/glew/CMakeLists.txt @@ -1,6 +1,7 @@ MITK_CREATE_MODULE(glew INCLUDE_DIRS external/include INTERNAL_INCLUDE_DIRS external/include PACKAGE_DEPENDS VTK GCC_DEFAULT_VISIBILITY + NO_INIT ) diff --git a/mitkConfig.h.in b/mitkConfig.h.in index 76743f7327..783a35ebf7 100644 --- a/mitkConfig.h.in +++ b/mitkConfig.h.in @@ -1,43 +1,48 @@ /* mitkConfig.h this file is generated. Do not change! */ #ifndef MITKCONFIG_H #define MITKCONFIG_H #define MITK_ROOT "${PROJECT_SOURCE_DIR}/" #cmakedefine MITK_BUILD_SHARED_CORE #cmakedefine USE_ITKZLIB #cmakedefine MITK_CHILI_PLUGIN #cmakedefine MITK_USE_TD_MOUSE +#cmakedefine MITK_HAS_UNORDERED_MAP_H +#cmakedefine MITK_HAS_UNORDERED_SET_H +#cmakedefine MITK_HAS_HASH_STRING +#cmakedefine MITK_HAS_HASH_SIZE_T + #define MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES @MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES@ #define MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES @MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES@ #define MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES @MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES@ #define MITK_ACCESSBYITK_PIXEL_TYPES @MITK_ACCESSBYITK_PIXEL_TYPES@ #define MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES_SEQ @MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES_SEQ@ #define MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES_SEQ @MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES_SEQ@ #define MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES_SEQ @MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES_SEQ@ #define MITK_ACCESSBYITK_PIXEL_TYPES_SEQ @MITK_ACCESSBYITK_PIXEL_TYPES_SEQ@ #define MITK_ACCESSBYITK_DIMENSIONS @MITK_ACCESSBYITK_DIMENSIONS@ #define MITK_ACCESSBYITK_DIMENSIONS_SEQ @MITK_ACCESSBYITK_DIMENSIONS_SEQ@ #define MITK_ACCESSBYITK_INTEGRAL_TYPES_DIMN_SEQ(dim) @MITK_ACCESSBYITK_INTEGRAL_TYPES_DIMN_SEQ@ #define MITK_ACCESSBYITK_FLOATING_TYPES_DIMN_SEQ(dim) @MITK_ACCESSBYITK_FLOATING_TYPES_DIMN_SEQ@ #define MITK_ACCESSBYITK_COMPOSITE_TYPES_DIMN_SEQ(dim) @MITK_ACCESSBYITK_COMPOSITE_TYPES_DIMN_SEQ@ #define MITK_ACCESSBYITK_TYPES_DIMN_SEQ(dim) @MITK_ACCESSBYITK_TYPES_DIMN_SEQ@ #define MITK_CHILI_PLUGIN_SDK_IPPIC_H "@MITK_CHILI_PLUGIN_SDK_IPPIC_H@" #define MITK_CHILI_PLUGIN_SDK_IPTYPES_H "@MITK_CHILI_PLUGIN_SDK_IPTYPES_H@" #define MITK_DOXYGEN_OUTPUT_DIR "@MITK_DOXYGEN_OUTPUT_DIR@" #define MITK_HELPPAGES_OUTPUT_DIR "@MITK_HELPPAGES_OUTPUT_DIR@" #define MITK_VERSION_MAJOR @MITK_VERSION_MAJOR@ #define MITK_VERSION_MINOR @MITK_VERSION_MINOR@ #define MITK_VERSION_PATCH @MITK_VERSION_PATCH@ #define MITK_VERSION_STRING "@MITK_VERSION_STRING@" #endif // MITKCONFIG_H diff --git a/mitkTestingConfig.h.in b/mitkTestingConfig.h.in index 930ea5992c..02b0b416ec 100644 --- a/mitkTestingConfig.h.in +++ b/mitkTestingConfig.h.in @@ -1,8 +1,13 @@ /* mitkTestingConfig.h this file is generated. Do not change! */ #cmakedefine BUILD_TESTING #cmakedefine MITK_FAST_TESTING #define MITK_TEST_OUTPUT_DIR "@MITK_TEST_OUTPUT_DIR@" +#ifdef CMAKE_INTDIR +#define MITK_RUNTIME_OUTPUT_DIR "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@/" ## CMAKE_INTDIR +#else +#define MITK_RUNTIME_OUTPUT_DIR "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@" +#endif