diff --git a/CMake/mitkFunctionAddCustomModuleTest.cmake b/CMake/mitkFunctionAddCustomModuleTest.cmake index 67de10bcd8..4659520d33 100644 --- a/CMake/mitkFunctionAddCustomModuleTest.cmake +++ b/CMake/mitkFunctionAddCustomModuleTest.cmake @@ -1,23 +1,28 @@ #! #! \brief Add a custom test for MITK module #! #! \param test_name Unique identifier for the test #! \param test_function Name of the test function (the one with the argc,argv signature) #! #! Additional parameters will be passed as command line parameters to the test. #! function(mitkAddCustomModuleTest test_name test_function) if (BUILD_TESTING AND MODULE_IS_ENABLED) - add_test(${test_name} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} ${test_function} ${ARGN}) + if(MITK_XVFB_TESTING) + set(xvfb_run "xvfb-run" "--auto-servernum") + else() + set(xvfb_run ) + endif() + add_test(NAME ${test_name} COMMAND ${xvfb_run} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} ${test_function} ${ARGN}) set_property(TEST ${test_name} PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) mitkFunctionGetLibrarySearchPaths(MITK_RUNTIME_PATH_RELEASE release RELEASE) mitkFunctionGetLibrarySearchPaths(MITK_RUNTIME_PATH_DEBUG debug DEBUG) set(test_env_path ${MITK_RUNTIME_PATH_RELEASE} ${MITK_RUNTIME_PATH_DEBUG} $ENV{PATH}) list(REMOVE_DUPLICATES test_env_path) string (REGEX REPLACE "\;" "\\\;" test_env_path "${test_env_path}") set_property(TEST ${test_name} PROPERTY ENVIRONMENT "PATH=${test_env_path}" APPEND) set_property(TEST ${test_name} PROPERTY SKIP_RETURN_CODE 77) endif() endfunction() diff --git a/CMake/mitkInstallRules.cmake b/CMake/mitkInstallRules.cmake index c07ba835cf..0b02b0bc21 100644 --- a/CMake/mitkInstallRules.cmake +++ b/CMake/mitkInstallRules.cmake @@ -1,94 +1,109 @@ # Install MITK icon and logo MITK_INSTALL(FILES "${MITK_SOURCE_DIR}/mitk.ico" "${MITK_SOURCE_DIR}/mitk.bmp") +# Helper vars + +if(WIN32) + set(_prefix "") + set(_ext ".dll") +elseif(UNIX) + set(_prefix "lib") + if(APPLE) + set(_ext ".dylib") + else() + set(_ext ".so") + endif() +endif() + +# Install PythonQt + +if(MITK_USE_Python3 AND PythonQt_DIR) + set(_python_qt_lib "${PythonQt_DIR}/") + if(WIN32) + set(_python_qt_lib "${_python_qt_lib}bin") + else() + set(_python_qt_lib "${_python_qt_lib}lib") + endif() + set(_python_qt_lib "${_python_qt_lib}/${_prefix}PythonQt${_ext}") + MITK_INSTALL(FILES ${_python_qt_lib}) +endif() + # Install Qt plugins if(MITK_USE_Qt5) get_property(_qmake_location TARGET ${Qt5Core_QMAKE_EXECUTABLE} PROPERTY IMPORT_LOCATION) get_filename_component(_qmake_path ${_qmake_location} DIRECTORY) - if(WIN32) - set(_prefix "") - set(_ext ".dll") - elseif(UNIX) - set(_prefix "lib") - if(APPLE) - set(_ext ".dylib") - else() - set(_ext ".so") - endif() - endif() - set(_install_DESTINATION "plugins/sqldrivers") MITK_INSTALL(FILES "${_qmake_path}/../plugins/sqldrivers/${_prefix}qsqlite${_ext}") set(_install_DESTINATION "plugins/imageformats") MITK_INSTALL(FILES "${_qmake_path}/../plugins/imageformats/${_prefix}qsvg${_ext}") set(_install_DESTINATION "plugins/iconengines") MITK_INSTALL(FILES "${_qmake_path}/../plugins/iconengines/${_prefix}qsvgicon${_ext}") # Install platform-specific Qt plugins set(_install_DESTINATION "plugins/platforms") if(WIN32) MITK_INSTALL(FILES "${_qmake_path}/../plugins/platforms/qwindows.dll") elseif(APPLE) MITK_INSTALL(FILES "${_qmake_path}/../plugins/platforms/libqcocoa.dylib") elseif(UNIX) MITK_INSTALL(FILES "${_qmake_path}/../plugins/platforms/libqxcb.so") set(_install_DESTINATION "plugins/xcbglintegrations") MITK_INSTALL(FILES "${_qmake_path}/../plugins/xcbglintegrations/libqxcb-glx-integration.so") endif() # Install platform-specific Qt styles set(_install_DESTINATION "plugins/styles") if(WIN32) MITK_INSTALL(FILES "${_qmake_path}/../plugins/styles/qwindowsvistastyle.dll") elseif(APPLE) MITK_INSTALL(FILES "${_qmake_path}/../plugins/styles/libqmacstyle.dylib") endif() # Install Qt WebEngine if(APPLE) set(_install_DESTINATION "../Frameworks/QtWebEngineCore.framework") get_filename_component(_real_path "${_qmake_path}/../lib/QtWebEngineCore.framework/Helpers" REALPATH) MITK_INSTALL(DIRECTORY ${_real_path} USE_SOURCE_PERMISSIONS) # Translations are included in the Resources directory of # QtWebEngineCore.framework and are installed by default. else() set(_install_DESTINATION "") if(WIN32) MITK_INSTALL(PROGRAMS "${_qmake_path}/QtWebEngineProcess.exe") elseif(UNIX) MITK_INSTALL(PROGRAMS "${_qmake_path}/../libexec/QtWebEngineProcess") endif() MITK_INSTALL(DIRECTORY "${_qmake_path}/../resources") set(_install_DESTINATION "translations") MITK_INSTALL(DIRECTORY "${_qmake_path}/../translations/qtwebengine_locales") endif() endif() set(_install_DESTINATION "") # Install MatchPoint binaries that are not auto-detected if(MITK_USE_MatchPoint) MITK_INSTALL(DIRECTORY "${MITK_EXTERNAL_PROJECT_PREFIX}/bin/" FILES_MATCHING PATTERN "MapUtilities*") MITK_INSTALL(DIRECTORY "${MITK_EXTERNAL_PROJECT_PREFIX}/bin/" FILES_MATCHING PATTERN "MapAlgorithms*") endif() # IMPORTANT: Restore default install destination! Do not edit this file beyond this line! set(_install_DESTINATION "") diff --git a/CMake/mitkMacroCreateModuleTests.cmake b/CMake/mitkMacroCreateModuleTests.cmake index 2a26abd10e..9cd2e0a889 100644 --- a/CMake/mitkMacroCreateModuleTests.cmake +++ b/CMake/mitkMacroCreateModuleTests.cmake @@ -1,100 +1,106 @@ # # 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) cmake_parse_arguments(MODULE_TEST "US_MODULE;NO_INIT" "EXTRA_DRIVER_INIT;EXTRA_DRIVER_INCLUDE" "EXTRA_DEPENDS;DEPENDS;PACKAGE_DEPENDS" ${ARGN}) if(BUILD_TESTING AND MODULE_IS_ENABLED) include(files.cmake) include_directories(.) set(TESTDRIVER ${MODULE_NAME}TestDriver) set(MODULE_TEST_EXTRA_DRIVER_INIT "${MODULE_TEST_EXTRA_DRIVER_INIT}") + if(MITK_XVFB_TESTING) + set(xvfb_run "xvfb-run" "--auto-servernum") + else() + set(xvfb_run ) + endif() + if(MODULE_TEST_US_MODULE) message(WARNING "The US_MODULE argument is deprecated and should be removed") endif() if(MODULE_TEST_US_MODULE AND MODULE_TEST_NO_INIT) message(WARNING "Conflicting arguments US_MODULE and NO_INIT: NO_INIT wins.") endif() set(_no_init) if(MODULE_TEST_NO_INIT) set(_no_init NO_INIT) endif() set(MITK_MODULE_NAME_REGEX_MATCH ) set(MITK_MODULE_NAME_REGEX_NOT_MATCH ) set(_testdriver_file_list ${CMAKE_CURRENT_BINARY_DIR}/testdriver_files.cmake) configure_file(${MITK_CMAKE_DIR}/mitkTestDriverFiles.cmake.in ${_testdriver_file_list} @ONLY) mitk_create_executable(${TESTDRIVER} DEPENDS ${MODULE_NAME} ${MODULE_TEST_DEPENDS} ${MODULE_TEST_EXTRA_DEPENDS} MitkTestingHelper PACKAGE_DEPENDS ${MODULE_TEST_PACKAGE_DEPENDS} SUBPROJECTS ${MODULE_SUBPROJECTS} FILES_CMAKE ${_testdriver_file_list} NO_FEATURE_INFO NO_BATCH_FILE ${_no_init}) set_property(TARGET ${EXECUTABLE_TARGET} PROPERTY FOLDER "${MITK_ROOT_FOLDER}/Modules/Tests") # # 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. # include(files.cmake) foreach( test ${MODULE_TESTS} ) get_filename_component(TName ${test} NAME_WE) - add_test(${TName} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} ${TName}) + add_test(NAME ${TName} COMMAND ${xvfb_run} ${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() mitkFunctionGetLibrarySearchPaths(MITK_RUNTIME_PATH_RELEASE release RELEASE) mitkFunctionGetLibrarySearchPaths(MITK_RUNTIME_PATH_DEBUG debug DEBUG) set(test_env_path ${MITK_RUNTIME_PATH_RELEASE} ${MITK_RUNTIME_PATH_DEBUG} $ENV{PATH}) list(REMOVE_DUPLICATES test_env_path) string (REGEX REPLACE "\;" "\\\;" test_env_path "${test_env_path}") set_property(TEST ${TName} PROPERTY ENVIRONMENT "PATH=${test_env_path}" APPEND) set_property(TEST ${TName} PROPERTY SKIP_RETURN_CODE 77) endforeach() set(TEST_TYPES IMAGE SURFACE POINTSET) # add other file types here foreach(test_type ${TEST_TYPES}) foreach(test_data ${MODULE_TEST${test_type}} ${ADDITIONAL_TEST_${test_type}}) if(EXISTS ${test_data}) set(TEST_DATA_FULL_PATH ${test_data}) else() # todo: maybe search other paths as well # yes, please in mitk/Testing/Data, too set(TEST_DATA_FULL_PATH ${MITK_DATA_DIR}/${test_data}) endif() if(EXISTS ${TEST_DATA_FULL_PATH}) foreach( test ${MODULE_${test_type}_TESTS}) get_filename_component(TName ${test} NAME_WE) get_filename_component(DName ${TEST_DATA_FULL_PATH} NAME) - add_test(${TName}_${DName} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} ${TName} ${TEST_DATA_FULL_PATH}) + add_test(NAME ${TName}_${DName} COMMAND ${xvfb_run} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} ${TName} ${TEST_DATA_FULL_PATH}) # Add labels for CDash subproject support if(MODULE_SUBPROJECTS) set_property(TEST ${TName}_${DName} PROPERTY LABELS ${MODULE_SUBPROJECTS} MITK) endif() set_property(TEST ${TName}_${DName} PROPERTY ENVIRONMENT "PATH=${test_env_path}" APPEND) set_property(TEST ${TName}_${DName} PROPERTY SKIP_RETURN_CODE 77) endforeach() else() message("!!!!! No such file: ${TEST_DATA_FULL_PATH} !!!!!") endif() endforeach() endforeach() endif() endmacro() diff --git a/CMake/mitkMacroInstall.cmake b/CMake/mitkMacroInstall.cmake index 7ed361b728..82939b49fd 100644 --- a/CMake/mitkMacroInstall.cmake +++ b/CMake/mitkMacroInstall.cmake @@ -1,204 +1,204 @@ # # MITK specific install macro # # On Mac everything is installed for each bundle listed in MACOSX_BUNDLE_NAMES # by replacing the DESTINATION parameter. Everything else is passed to the CMake INSTALL command # # Usage: MITK_INSTALL( ) # macro(MITK_INSTALL) set(ARGS ${ARGN}) set(install_directories "") list(FIND ARGS DESTINATION _destination_index) if(_destination_index GREATER -1) message(SEND_ERROR "MITK_INSTALL macro must not be called with a DESTINATION parameter.") else() # If there is a FILES_MATCHING parameter we need to make sure that the # DESTINATION parameter is located in front of it. set(ARGS1 "") set(ARGS2 "") list(FIND ARGS FILES_MATCHING _files_matching_index) if(_files_matching_index GREATER -1) set(_index "0") list(LENGTH ARGS _count) while(_index LESS _files_matching_index ) list(GET ARGS ${_index} _arg) list(APPEND ARGS1 ${_arg}) math(EXPR _index "${_index}+1") endwhile() while(_index LESS _count) list(GET ARGS ${_index} _arg) list(APPEND ARGS2 ${_arg}) math(EXPR _index "${_index}+1") endwhile() else() set(ARGS1 ${ARGS}) endif() if(NOT MACOSX_BUNDLE_NAMES) install(${ARGS1} DESTINATION bin/${_install_DESTINATION} ${ARGS2}) else() foreach(bundle_name ${MACOSX_BUNDLE_NAMES}) install(${ARGS1} DESTINATION ${bundle_name}.app/Contents/MacOS/${_install_DESTINATION} ${ARGS2}) endforeach() endif() endif() endmacro() # Fix _target_location # This is used in several install macros macro(_fixup_target) if(NOT intermediate_dir) if(WIN32) set(intermediate_dir Release) else() set(intermediate_dir .) endif() endif() mitkFunctionGetLibrarySearchPaths(_search_paths ${intermediate_dir}) install(CODE " set(_bundle_dest_dir \"${_bundle_dest_dir}\") if(_bundle_dest_dir) set(_bin_path \"\${CMAKE_INSTALL_PREFIX}/\${_bundle_dest_dir}\") else() set(_bin_path \"\${CMAKE_INSTALL_PREFIX}/bin\") endif() macro(gp_item_default_embedded_path_override item default_embedded_path_var) get_filename_component(_item_name \"\${item}\" NAME) get_filename_component(_item_path \"\${item}\" PATH) # We have to fix all path references to build trees for plugins if(NOT _item_path MATCHES \"\${CMAKE_INSTALL_PREFIX}/${_bundle_dest_dir}\") # item with relative path or embedded path pointing to some build dir set(full_path \"full_path-NOTFOUND\") file(GLOB_RECURSE full_path \${CMAKE_INSTALL_PREFIX}/${_bundle_dest_dir}/\${_item_name} ) list(LENGTH full_path full_path_length) if(full_path_length GREATER 1) list(GET full_path 0 full_path) endif() get_filename_component(_item_path \"\${full_path}\" PATH) endif() set(_plugins_path \"\${_bin_path}/plugins\") if(_item_path STREQUAL _plugins_path OR (_item_path MATCHES \"\${_plugins_path}/\" AND _item_name MATCHES \"liborg\") # this is for legacy BlueBerry bundle support ) # Only fix plugins message(\"override: \${item}\") message(\"found file: \${_item_path}/\${_item_name}\") if(APPLE) string(REPLACE \${CMAKE_INSTALL_PREFIX}/${_bundle_dest_dir} @executable_path \${default_embedded_path_var} \"\${_item_path}\" ) else() set(\${default_embedded_path_var} \"\${_item_path}\") endif() message(\"override result: \${\${default_embedded_path_var}}\") endif() endmacro(gp_item_default_embedded_path_override) macro(gp_resolved_file_type_override file type) if(NOT APPLE) get_filename_component(_file_path \"\${file}\" PATH) get_filename_component(_file_name \"\${file}\" NAME) if(_file_path MATCHES \"^\${CMAKE_INSTALL_PREFIX}\") set(\${type} \"local\") endif() if(_file_name MATCHES gdiplus) set(\${type} \"system\") endif(_file_name MATCHES gdiplus) endif() if(WIN32) if(file MATCHES \"BluetoothApis.dll\") set(\${type} \"system\" ) endif() endif() endmacro(gp_resolved_file_type_override) if(NOT APPLE) macro(gp_resolve_item_override context item exepath dirs resolved_item_var resolved_var) if(\${item} MATCHES \"blueberry_core_runtime\") get_filename_component(_item_name \${item} NAME) set(\${resolved_item_var} \"\${exepath}/plugins/\${_item_name}\") set(\${resolved_var} 1) endif() endmacro() endif() if(\"${_install_GLOB_PLUGINS}\" STREQUAL \"TRUE\") set(GLOBBED_PLUGINS ) set(_bb_runtime_lib \"\${_bin_path}/liborg_blueberry_core_runtime${CMAKE_SHARED_LIBRARY_SUFFIX}\") if(EXISTS \"\${_bb_runtime_lib}\") list(APPEND GLOBBED_PLUGINS \"\${_bb_runtime_lib}\") endif() # Iterate over all sub-directories which contain plug-ins # (BlueBerry plug-ins, Qt plug-ins, and auto-load modules) file(GLOB _children \"\${_bin_path}/*\") foreach(_child \${_children}) if(IS_DIRECTORY \${_child}) set(_plugins ) set(_modules ) file(GLOB_RECURSE _plugins \"\${_child}/*${CMAKE_SHARED_LIBRARY_SUFFIX}\") if(_plugins) list(APPEND GLOBBED_PLUGINS \${_plugins}) endif() # Now glob for all modules which might have a different extensions. # E.g. on MacOS plugins could have a .dylib extension as well as a .so extension if(NOT \"${CMAKE_SHARED_MODULE_SUFFIX}\" STREQUAL \"\" AND NOT \"${CMAKE_SHARED_MODULE_SUFFIX}\" STREQUAL \"${CMAKE_SHARED_LIBRARY_SUFFIX}\") file(GLOB_RECURSE _modules \"\${_child}/*${CMAKE_SHARED_MODULE_SUFFIX}\") endif() if(_modules) list(APPEND GLOBBED_PLUGINS \${_modules}) endif() endif() endforeach() endif() file(GLOB _match_point_plugins \"\${_bin_path}/mdra-*\") set(PLUGINS ) foreach(_plugin ${_install_PLUGINS} \${GLOBBED_PLUGINS} \${_match_point_plugins}) get_filename_component(_plugin_realpath \${_plugin} REALPATH) list(APPEND PLUGINS \${_plugin_realpath}) endforeach() if(PLUGINS) list(REMOVE_DUPLICATES PLUGINS) endif(PLUGINS) message(\"globbed plugins: \${PLUGINS}\") set(CMAKE_MODULE_PATH ${MITK_SOURCE_DIR}/CMake ${CMAKE_MODULE_PATH} ) set(DIRS \"${_search_paths}\") set(_additional_search_paths ${_install_LIBRARY_DIRS}) if(_additional_search_paths) set(DIRS \"\${DIRS};\${_additional_search_paths}\") endif() foreach(_plugin \${PLUGINS}) get_filename_component(_pluginpath \${_plugin} PATH) list(APPEND DIRS \"\${_pluginpath}\") endforeach(_plugin) list(REMOVE_DUPLICATES DIRS) # use custom version of BundleUtilities include(BundleUtilities) set(BU_CHMOD_BUNDLE_ITEMS ON) - fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/${_target_location}\" \"\${PLUGINS}\" \"\${DIRS}\") + fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/${_target_location}\" \"\${PLUGINS}\" \"\${DIRS}\" IGNORE_ITEM Python) if(APPLE) include(FixMacOSInstaller) endif() ") endmacro() diff --git a/CMakeLists.txt b/CMakeLists.txt index e148bc017d..f762d2a8fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,1472 +1,1466 @@ set(MITK_CMAKE_MINIMUM_REQUIRED_VERSION 3.14.5) cmake_minimum_required(VERSION ${MITK_CMAKE_MINIMUM_REQUIRED_VERSION}) #----------------------------------------------------------------------------- # See https://cmake.org/cmake/help/v3.14/manual/cmake-policies.7.html for details #----------------------------------------------------------------------------- set(project_policies ) foreach(policy ${project_policies}) if(POLICY ${policy}) cmake_policy(SET ${policy} NEW) endif() endforeach() #----------------------------------------------------------------------------- # 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 VERSION 2018.04.99) include_directories(SYSTEM ${MITK_SUPERBUILD_BINARY_DIR}) endif() #----------------------------------------------------------------------------- # MITK Extension Feature #----------------------------------------------------------------------------- set(MITK_EXTENSION_DIRS "" CACHE STRING "") set(MITK_DIR_PLUS_EXTENSION_DIRS ${MITK_SOURCE_DIR} ${MITK_EXTENSION_DIRS}) #----------------------------------------------------------------------------- # Update CMake module path #----------------------------------------------------------------------------- set(MITK_CMAKE_DIR ${MITK_SOURCE_DIR}/CMake) set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR}) foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) set(MITK_CMAKE_EXTENSION_DIR ${MITK_EXTENSION_DIR}/CMake) get_filename_component(MITK_CMAKE_EXTENSION_DIR ${MITK_CMAKE_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_CMAKE_EXTENSION_DIR}) list(APPEND CMAKE_MODULE_PATH ${MITK_CMAKE_EXTENSION_DIR}) endif() endforeach() #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- # Standard CMake macros include(FeatureSummary) include(CTestUseLaunchers) include(CMakeParseArguments) include(FindPackageHandleStandardArgs) # MITK macros include(mitkFunctionGetGccVersion) include(mitkFunctionCheckCompilerFlags) include(mitkFunctionSuppressWarnings) # includes several functions include(mitkMacroEmptyExternalProject) include(mitkFunctionGenerateProjectXml) include(mitkFunctionEnableBuildConfiguration) include(mitkFunctionWhitelists) include(mitkFunctionAddExternalProject) include(mitkFunctionAddLibrarySearchPaths) SUPPRESS_VC_DEPRECATED_WARNINGS() #----------------------------------------------------------------------------- # 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() #----------------------------------------------------------------------------- # Check miminum macOS version #----------------------------------------------------------------------------- # The minimum supported macOS version is 10.13. If you use a version less than 10.13, there is no guarantee that the build still works. if(APPLE) exec_program(sw_vers ARGS -productVersion OUTPUT_VARIABLE macos_version) if (macos_version VERSION_LESS "10.13") message(WARNING "Detected macOS version \"${macos_version}\" is not supported anymore. Minimum required macOS version is at least 10.13.") endif() if (CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS 10.13) message(WARNING "Detected macOS deployment target \"${CMAKE_OSX_DEPLOYMENT_TARGET}\" is not supported anymore. Minimum required macOS version is at least 10.13.") endif() endif() #----------------------------------------------------------------------------- # Check miminum compiler versions #----------------------------------------------------------------------------- if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") # require at least gcc 4.9 as provided by ppa:ubuntu-toolchain-r/test for Ubuntu 14.04 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) message(FATAL_ERROR "GCC version must be at least 4.9 If you are using Ubuntu 14.04, you can easily install gcc and g++ 4.9 (or any later version available) in addition to your version ${CMAKE_CXX_COMPILER_VERSION}: sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update sudo apt-get install gcc-4.9 g++-4.9 Make sure to explicitly specify these compilers when configuring MITK: CMAKE_C_COMPILER:FILEPATH=/usr/bin/gcc-4.9 CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/g++-4.9 For more information on the proposed PPA see the Toolchain Updates section of https://wiki.ubuntu.com/ToolChain.") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") # require at least clang 3.4 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4) message(FATAL_ERROR "Clang version must be at least 3.4") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") # require at least clang 5.0 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) message(FATAL_ERROR "Apple Clang version must be at least 5.0") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") # require at least Visual Studio 2017 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) message(FATAL_ERROR "Microsoft Visual Studio 2017 or newer required") endif() else() message(WARNING "You are using an unsupported compiler! Compilation has only been tested with Clang (Linux or Apple), GCC and MSVC.") endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) else() set(GCC_VERSION 0) endif() set(MITK_CXX_STANDARD 14) set(CMAKE_CXX_EXTENSIONS 0) set(CMAKE_CXX_STANDARD ${MITK_CXX_STANDARD}) set(CMAKE_CXX_STANDARD_REQUIRED 1) # This is necessary to avoid problems with compile feature checks. # CMAKE_CXX_STANDARD seems to only set the -std=c++14 flag for targets. # However, compile flag checks also need to be done with -std=c++14. # The MITK_CXX14_FLAG variable is also used for external projects # build during the MITK super-build. mitkFunctionCheckCompilerFlags("-std=c++14" MITK_CXX14_FLAG) #----------------------------------------------------------------------------- # Warn if source or build path is too long #----------------------------------------------------------------------------- if(WIN32) set(_src_dir_length_max 50) set(_bin_dir_length_max 50) if(MITK_USE_SUPERBUILD) set(_src_dir_length_max 34) # _src_dir_length_max - strlen(ep/src/ITK-build) set(_bin_dir_length_max 40) # _bin_dir_length_max - strlen(MITK-build) endif() string(LENGTH "${MITK_SOURCE_DIR}" _src_n) string(LENGTH "${MITK_BINARY_DIR}" _bin_n) # The warnings should be converted to errors if(_src_n GREATER _src_dir_length_max) message(WARNING "MITK source code directory path length is too long (${_src_n} > ${_src_dir_length_max})." "Please move the MITK source code directory to a directory with a shorter path." ) endif() if(_bin_n GREATER _bin_dir_length_max) message(WARNING "MITK build directory path length is too long (${_bin_n} > ${_bin_dir_length_max})." "Please move the MITK build directory to a directory with a shorter path." ) endif() endif() #----------------------------------------------------------------------------- # Additional MITK Options (also shown during superbuild) #----------------------------------------------------------------------------- # ----------------------------------------- # General build options option(BUILD_SHARED_LIBS "Build MITK with shared libraries" ON) option(WITH_COVERAGE "Enable/Disable coverage" OFF) option(BUILD_TESTING "Test the project" ON) option(MITK_FAST_TESTING "Disable long-running tests like packaging" OFF) +option(MITK_XVFB_TESTING "Execute test drivers through xvfb-run" OFF) option(MITK_BUILD_ALL_APPS "Build all MITK applications" OFF) option(MITK_BUILD_EXAMPLES "Build the MITK Examples" OFF) option(MITK_ENABLE_PIC_READER "Enable support for reading the DKFZ pic file format." ON) mark_as_advanced( + MITK_XVFB_TESTING MITK_FAST_TESTING MITK_BUILD_ALL_APPS MITK_ENABLE_PIC_READER ) # ----------------------------------------- # Qt version related variables option(MITK_USE_Qt5 "Use Qt 5 library" ON) if(MITK_USE_Qt5) set(MITK_QT5_MINIMUM_VERSION 5.12) set(MITK_QT5_COMPONENTS Concurrent OpenGL PrintSupport Script Sql Svg Widgets Xml XmlPatterns WebEngineWidgets UiTools Help LinguistTools) if(APPLE) list(APPEND MITK_QT5_COMPONENTS DBus) elseif(UNIX) list(APPEND MITK_QT5_COMPONENTS X11Extras) endif() # Hint at default install locations of Qt if(NOT Qt5_DIR) if(MSVC) set(_dir_candidates "C:/Qt") if(CMAKE_GENERATOR MATCHES "^Visual Studio [0-9]+ ([0-9]+)") set(_compilers "msvc${CMAKE_MATCH_1}") elseif(CMAKE_GENERATOR MATCHES "Ninja") include(mitkFunctionGetMSVCVersion) mitkFunctionGetMSVCVersion() if(VISUAL_STUDIO_PRODUCT_NAME MATCHES "^Visual Studio ([0-9]+)") set(_compilers "msvc${CMAKE_MATCH_1}") endif() endif() if(_compilers MATCHES "[0-9]+") if (CMAKE_MATCH_0 EQUAL 2019) list(APPEND _compilers "msvc2017") # Binary compatible to 2019 endif() endif() else() set(_dir_candidates ~/Qt) if(APPLE) set(_compilers clang) else() list(APPEND _dir_candidates /opt/Qt) set(_compilers gcc) endif() endif() if(CMAKE_SIZEOF_VOID_P EQUAL 8) foreach(_compiler ${_compilers}) list(APPEND _compilers64 "${_compiler}_64") endforeach() set(_compilers ${_compilers64}) endif() foreach(_dir_candidate ${_dir_candidates}) get_filename_component(_dir_candidate ${_dir_candidate} REALPATH) foreach(_compiler ${_compilers}) set(_glob_expression "${_dir_candidate}/5.*/${_compiler}") file(GLOB _hints ${_glob_expression}) list(SORT _hints) list(APPEND MITK_QT5_HINTS ${_hints}) endforeach() endforeach() endif() find_package(Qt5 ${MITK_QT5_MINIMUM_VERSION} COMPONENTS ${MITK_QT5_COMPONENTS} REQUIRED HINTS ${MITK_QT5_HINTS}) if(${Qt5_VERSION} VERSION_GREATER_EQUAL 5.13) message(FATAL_ERROR "Qt version ${Qt5_VERSION_MAJOR}.${Qt5_VERSION_MINOR} is not yet supported. We recommend using the latest long-term support version 5.12.x.") endif() endif() set_property(GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS "") include(CMakeExternals/ExternalProjectList.cmake) foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) set(MITK_CMAKE_EXTERNALS_EXTENSION_DIR ${MITK_EXTENSION_DIR}/CMakeExternals) get_filename_component(MITK_CMAKE_EXTERNALS_EXTENSION_DIR ${MITK_CMAKE_EXTERNALS_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_CMAKE_EXTERNALS_EXTENSION_DIR}/ExternalProjectList.cmake) include(${MITK_CMAKE_EXTERNALS_EXTENSION_DIR}/ExternalProjectList.cmake) endif() endforeach() # ----------------------------------------- # Other MITK_USE_* options not related to # external projects build via the # MITK superbuild option(MITK_USE_BLUEBERRY "Build the BlueBerry platform" ON) option(MITK_USE_OpenCL "Use OpenCL GPU-Computing library" OFF) option(MITK_USE_OpenMP "Use OpenMP" OFF) option(MITK_USE_Python3 "Use Python 3" OFF) #----------------------------------------------------------------------------- # Build configurations #----------------------------------------------------------------------------- set(_buildConfigs "Custom") file(GLOB _buildConfigFiles CMake/BuildConfigurations/*.cmake) foreach(_buildConfigFile ${_buildConfigFiles}) get_filename_component(_buildConfigFile ${_buildConfigFile} NAME_WE) list(APPEND _buildConfigs ${_buildConfigFile}) endforeach() foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) file(GLOB _extBuildConfigFiles ${MITK_EXTENSION_DIR}/CMake/BuildConfigurations/*.cmake) foreach(_extBuildConfigFile ${_extBuildConfigFiles}) get_filename_component(_extBuildConfigFile ${_extBuildConfigFile} NAME_WE) list(APPEND _buildConfigs ${_extBuildConfigFile}) endforeach() list(REMOVE_DUPLICATES _buildConfigs) endforeach() set(MITK_BUILD_CONFIGURATION "Custom" CACHE STRING "Use pre-defined MITK configurations") set_property(CACHE MITK_BUILD_CONFIGURATION PROPERTY STRINGS ${_buildConfigs}) mitkFunctionEnableBuildConfiguration() mitkFunctionCreateWhitelistPaths(MITK) mitkFunctionFindWhitelists(MITK) # ----------------------------------------- # Custom dependency logic option(MITK_USE_SYSTEM_Boost "Use the system Boost" OFF) set(MITK_USE_Boost_LIBRARIES "" CACHE STRING "A semi-colon separated list of required Boost libraries") if(MITK_USE_cpprestsdk) find_package(OpenSSL QUIET) if(NOT OpenSSL_FOUND) set(openssl_message "Could not find OpenSSL (dependency of C++ REST SDK).\n") if(UNIX) if(APPLE) set(openssl_message "${openssl_message}Please install it using your favorite package management " "system (i.e. Homebrew or MacPorts).\n") else() set(openssl_message "${openssl_message}Please install the dev package of OpenSSL (i.e. libssl-dev).\n") endif() else() set(openssl_message "${openssl_message}Please install Win32 OpenSSL:\n" " https://slproweb.com/products/Win32OpenSSL.html\n") endif() set(openssl_message "${openssl_message}If it still cannot be found, you can hint CMake to find OpenSSL by " "adding/setting the OPENSSL_ROOT_DIR variable to the root directory of an " "OpenSSL installation. Make sure to clear variables of partly found " "versions of OpenSSL before, or they will be mixed up.") message(FATAL_ERROR ${openssl_message}) endif() list(APPEND MITK_USE_Boost_LIBRARIES date_time regex system) if(UNIX) list(APPEND MITK_USE_Boost_LIBRARIES atomic chrono filesystem random thread) endif() list(REMOVE_DUPLICATES MITK_USE_Boost_LIBRARIES) set(MITK_USE_Boost_LIBRARIES ${MITK_USE_Boost_LIBRARIES} CACHE STRING "A semi-colon separated list of required Boost libraries" FORCE) endif() if(MITK_USE_Python3) set(MITK_USE_ZLIB ON CACHE BOOL "" FORCE) if(APPLE AND CMAKE_FRAMEWORK_PATH AND CMAKE_FRAMEWORK_PATH MATCHES "python3\\.?([0-9]+)") find_package(Python3 3.${CMAKE_MATCH_1} EXACT REQUIRED COMPONENTS Interpreter Development NumPy) else() find_package(Python3 REQUIRED COMPONENTS Interpreter Development NumPy) endif() if(WIN32) string(REPLACE "\\" "/" Python3_STDARCH "${Python3_STDARCH}") string(REPLACE "\\" "/" Python3_STDLIB "${Python3_STDLIB}") string(REPLACE "\\" "/" Python3_SITELIB "${Python3_SITELIB}") endif() endif() if(BUILD_TESTING AND NOT MITK_USE_CppUnit) message("> Forcing MITK_USE_CppUnit to ON because BUILD_TESTING=ON") set(MITK_USE_CppUnit ON CACHE BOOL "Use CppUnit for unit tests" FORCE) endif() if(MITK_USE_BLUEBERRY) option(MITK_BUILD_ALL_PLUGINS "Build all MITK plugins" OFF) mark_as_advanced(MITK_BUILD_ALL_PLUGINS) if(NOT MITK_USE_CTK) message("> Forcing MITK_USE_CTK to ON because of MITK_USE_BLUEBERRY") set(MITK_USE_CTK ON CACHE BOOL "Use CTK in MITK" FORCE) endif() endif() #----------------------------------------------------------------------------- # Pixel type multiplexing #----------------------------------------------------------------------------- # Customize the default pixel types for multiplex macros 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 "itk::RGBPixel, itk::RGBAPixel" 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(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_COMPOSITE_PIXEL_TYPES) set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) string(REPLACE "," ";" _integral_types ${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES}) string(REPLACE "," ";" _floating_types ${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES}) foreach(_scalar_type ${_integral_types} ${_floating_types}) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}itk::VariableLengthVector<${_scalar_type}>,") endforeach() string(LENGTH "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" _length) math(EXPR _length "${_length} - 1") string(SUBSTRING "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" 0 ${_length} MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES ${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES} CACHE STRING "List of vector pixel types used in AccessByItk and InstantiateAccessFunction macros for itk::VectorImage types" 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() #----------------------------------------------------------------------------- # Project.xml #----------------------------------------------------------------------------- # A list of topologically ordered targets set(CTEST_PROJECT_SUBPROJECTS) list(APPEND CTEST_PROJECT_SUBPROJECTS MITK-Core MITK-CoreUI MITK-IGT MITK-ToF MITK-Diffusion MITK-Modules # all modules not contained in a specific subproject MITK-Plugins # all plugins not contained in a specific subproject MITK-Examples 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") # Print configuration summary message("\n\n") feature_summary( DESCRIPTION "------- FEATURE SUMMARY FOR ${PROJECT_NAME} -------" WHAT ALL) return() endif() #***************************************************************************** #**************************** END OF SUPERBUILD **************************** #***************************************************************************** #----------------------------------------------------------------------------- # Organize MITK targets in folders #----------------------------------------------------------------------------- set_property(GLOBAL PROPERTY USE_FOLDERS ON) set(MITK_ROOT_FOLDER "MITK" CACHE STRING "") mark_as_advanced(MITK_ROOT_FOLDER) #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- include(WriteBasicConfigVersionFile) include(CheckCXXSourceCompiles) include(GenerateExportHeader) include(mitkFunctionAddCustomModuleTest) include(mitkFunctionCheckModuleDependencies) include(mitkFunctionCompileSnippets) include(mitkFunctionConfigureVisualStudioUserProjectFile) include(mitkFunctionConvertXPSchema) include(mitkFunctionCreateBlueBerryApplication) include(mitkFunctionCreateCommandLineApp) include(mitkFunctionCreateModule) include(mitkFunctionCreatePlugin) include(mitkFunctionCreateProvisioningFile) include(mitkFunctionGetLibrarySearchPaths) include(mitkFunctionGetVersion) include(mitkFunctionGetVersionDescription) include(mitkFunctionInstallAutoLoadModules) include(mitkFunctionInstallCTKPlugin) include(mitkFunctionInstallProvisioningFiles) include(mitkFunctionInstallThirdPartyCTKPlugins) include(mitkFunctionOrganizeSources) include(mitkFunctionTestPlugin) include(mitkFunctionUseModules) if( ${MITK_USE_MatchPoint} ) include(mitkFunctionCreateMatchPointDeployedAlgorithm) endif() include(mitkMacroConfigureItkPixelTypes) include(mitkMacroCreateExecutable) include(mitkMacroCreateModuleTests) include(mitkMacroGenerateToolsLibrary) include(mitkMacroGetLinuxDistribution) include(mitkMacroGetPMDPlatformString) include(mitkMacroInstall) include(mitkMacroInstallHelperApp) include(mitkMacroInstallTargets) include(mitkMacroMultiplexPicType) # Deprecated include(mitkMacroCreateCTKPlugin) #----------------------------------------------------------------------------- # Global CMake variables #----------------------------------------------------------------------------- # Required and enabled C++14 features for all MITK code. # These are added as PUBLIC compile features to all MITK modules. set(MITK_CXX_FEATURES cxx_auto_type cxx_decltype cxx_enum_forward_declarations cxx_extended_friend_declarations cxx_extern_templates cxx_final cxx_lambdas cxx_local_type_template_args cxx_long_long_type cxx_nullptr cxx_override cxx_range_for cxx_right_angle_brackets cxx_rvalue_references cxx_static_assert cxx_strong_enums cxx_template_template_parameters cxx_trailing_return_types cxx_variadic_macros ) if(NOT DEFINED CMAKE_DEBUG_POSTFIX) # We can't do this yet because the CTK Plugin Framework # cannot cope with a postfix yet. #set(CMAKE_DEBUG_POSTFIX d) endif() #----------------------------------------------------------------------------- # Output directories. #----------------------------------------------------------------------------- set(_default_LIBRARY_output_dir lib) set(_default_RUNTIME_output_dir bin) set(_default_ARCHIVE_output_dir lib) foreach(type LIBRARY RUNTIME ARCHIVE) # Make sure the directory exists if(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_CMAKE_${type}_OUTPUT_DIRECTORY) set(CMAKE_${type}_OUTPUT_DIRECTORY ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) else() set(CMAKE_${type}_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/${_default_${type}_output_dir}) set(MITK_CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY}) endif() set(CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY} CACHE INTERNAL "Output directory for ${type} files.") mark_as_advanced(CMAKE_${type}_OUTPUT_DIRECTORY) endforeach() #----------------------------------------------------------------------------- # Set MITK specific options and variables (NOT available during superbuild) #----------------------------------------------------------------------------- # Look for optional Doxygen package find_package(Doxygen) option(BLUEBERRY_DEBUG_SMARTPOINTER "Enable code for debugging smart pointers" OFF) mark_as_advanced(BLUEBERRY_DEBUG_SMARTPOINTER) # ASK THE USER TO SHOW THE CONSOLE WINDOW FOR CoreApp and mitkWorkbench 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" OR MITK_CTEST_SCRIPT_MODE STREQUAL "experimental") ) set(MITK_FAST_TESTING ON) endif() endif() if(NOT UNIX) set(MITK_WIN32_FORCE_STATIC "STATIC" CACHE INTERNAL "Use this variable to always build static libraries on non-unix platforms") endif() if(MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS_OPTION "FORCE_BUILD_ALL") endif() # Configure pixel types used for ITK image access multiplexing mitkMacroConfigureItkPixelTypes() # Configure module naming conventions set(MITK_MODULE_NAME_REGEX_MATCH "^[A-Z].*$") set(MITK_MODULE_NAME_REGEX_NOT_MATCH "^[Mm][Ii][Tt][Kk].*$") set(MITK_DEFAULT_MODULE_NAME_PREFIX "Mitk") set(MITK_MODULE_NAME_PREFIX ${MITK_DEFAULT_MODULE_NAME_PREFIX}) set(MITK_MODULE_NAME_DEFAULTS_TO_DIRECTORY_NAME 1) #----------------------------------------------------------------------------- # Get MITK version info #----------------------------------------------------------------------------- mitkFunctionGetVersion(${MITK_SOURCE_DIR} MITK) mitkFunctionGetVersionDescription(${MITK_SOURCE_DIR} MITK) # MITK_VERSION set(MITK_VERSION_STRING "${MITK_VERSION_MAJOR}.${MITK_VERSION_MINOR}.${MITK_VERSION_PATCH}") if(MITK_VERSION_PATCH STREQUAL "99") set(MITK_VERSION_STRING "${MITK_VERSION_STRING}-${MITK_REVISION_SHORTID}") endif() #----------------------------------------------------------------------------- # Installation preparation # # These should be set before any MITK install macros are used #----------------------------------------------------------------------------- # on macOS all BlueBerry plugins get copied into every # application bundle (.app directory) specified here if(MITK_USE_BLUEBERRY AND APPLE) foreach(MITK_EXTENSION_DIR ${MITK_DIR_PLUS_EXTENSION_DIRS}) set(MITK_APPLICATIONS_EXTENSION_DIR ${MITK_EXTENSION_DIR}/Applications) get_filename_component(MITK_APPLICATIONS_EXTENSION_DIR ${MITK_APPLICATIONS_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_APPLICATIONS_EXTENSION_DIR}/AppList.cmake) set(MITK_APPS "") include(${MITK_APPLICATIONS_EXTENSION_DIR}/AppList.cmake) foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 1 option_name) list(GET target_info_list 0 app_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) set(MACOSX_BUNDLE_NAMES ${MACOSX_BUNDLE_NAMES} Mitk${app_name}) endif() endforeach() endif() endforeach() 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}") set(MITK_C_FLAGS_DEBUG ) set(MITK_C_FLAGS_RELEASE ) set(MITK_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${MITK_CXX14_FLAG}") set(MITK_CXX_FLAGS_DEBUG ) set(MITK_CXX_FLAGS_RELEASE ) set(MITK_EXE_LINKER_FLAGS ) set(MITK_SHARED_LINKER_FLAGS ) if(WIN32) set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} -DPOCO_NO_UNWINDOWS -DWIN32_LEAN_AND_MEAN -DNOMINMAX") mitkFunctionCheckCompilerFlags("/wd4005" MITK_CXX_FLAGS) # warning C4005: macro redefinition mitkFunctionCheckCompilerFlags("/wd4231" MITK_CXX_FLAGS) # warning C4231: nonstandard extension used : 'extern' before template explicit instantiation # the following line should be removed after fixing bug 17637 mitkFunctionCheckCompilerFlags("/wd4316" MITK_CXX_FLAGS) # warning C4316: object alignment on heap mitkFunctionCheckCompilerFlags("/wd4180" MITK_CXX_FLAGS) # warning C4180: qualifier applied to function type has no meaning mitkFunctionCheckCompilerFlags("/wd4251" MITK_CXX_FLAGS) # warning C4251: 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' endif() if(APPLE) set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} -DGL_SILENCE_DEPRECATION") # Apple deprecated OpenGL in macOS 10.14 endif() if(NOT MSVC_VERSION) foreach(_flag -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -Wno-error=gnu -Wno-error=unknown-pragmas # The strict-overflow warning is generated by ITK template code -Wno-error=strict-overflow -Woverloaded-virtual -Wstrict-null-sentinel #-Wold-style-cast #-Wsign-promo -Wno-error=deprecated-copy -Wno-array-bounds -fdiagnostics-show-option ) mitkFunctionCheckCAndCXXCompilerFlags(${_flag} MITK_C_FLAGS MITK_CXX_FLAGS) endforeach() endif() if(CMAKE_COMPILER_IS_GNUCXX AND NOT APPLE) mitkFunctionCheckCompilerFlags("-Wl,--no-undefined" MITK_SHARED_LINKER_FLAGS) mitkFunctionCheckCompilerFlags("-Wl,--as-needed" MITK_SHARED_LINKER_FLAGS) endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionCheckCAndCXXCompilerFlags("-fstack-protector-all" MITK_C_FLAGS MITK_CXX_FLAGS) set(MITK_CXX_FLAGS_RELEASE "-U_FORTIFY_SOURCES -D_FORTIFY_SOURCE=2 ${MITK_CXX_FLAGS_RELEASE}") endif() set(MITK_MODULE_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) set(MITK_EXE_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) #----------------------------------------------------------------------------- # MITK Packages #----------------------------------------------------------------------------- set(MITK_MODULES_PACKAGE_DEPENDS_DIR ${MITK_SOURCE_DIR}/CMake/PackageDepends) set(MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR}) foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) set(MITK_PACKAGE_DEPENDS_EXTENSION_DIR ${MITK_EXTENSION_DIR}/CMake/PackageDepends) get_filename_component(MITK_PACKAGE_DEPENDS_EXTENSION_DIR ${MITK_PACKAGE_DEPENDS_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_PACKAGE_DEPENDS_EXTENSION_DIR}) list(APPEND MODULES_PACKAGE_DEPENDS_DIRS ${MITK_PACKAGE_DEPENDS_EXTENSION_DIR}) endif() endforeach() if(NOT MITK_USE_SYSTEM_Boost) set(Boost_NO_SYSTEM_PATHS 1) endif() set(Boost_USE_MULTITHREADED 1) set(Boost_USE_STATIC_LIBS 0) set(Boost_USE_STATIC_RUNTIME 0) set(Boost_ADDITIONAL_VERSIONS 1.68 1.68.0) # We need this later for a DCMTK workaround set(_dcmtk_dir_orig ${DCMTK_DIR}) # This property is populated at the top half of this file get_property(MITK_EXTERNAL_PROJECTS GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS) foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_package GLOBAL PROPERTY MITK_${ep}_PACKAGE) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) if(MITK_USE_${ep} AND _package) if(_components) find_package(${_package} COMPONENTS ${_components} REQUIRED CONFIG) else() # Prefer config mode first because it finds external # Config.cmake files pointed at by _DIR variables. # Otherwise, existing Find.cmake files could fail. if(DEFINED ${_package}_DIR) #we store the information because it will be overwritten by find_package #and would get lost for all EPs that use on Find.cmake instead of config #files. set(_temp_EP_${_package}_dir ${${_package}_DIR}) endif(DEFINED ${_package}_DIR) find_package(${_package} QUIET CONFIG) string(TOUPPER "${_package}" _package_uc) if(NOT (${_package}_FOUND OR ${_package_uc}_FOUND)) if(DEFINED _temp_EP_${_package}_dir) set(${_package}_DIR ${_temp_EP_${_package}_dir} CACHE PATH "externaly set dir of the package ${_package}" FORCE) endif(DEFINED _temp_EP_${_package}_dir) find_package(${_package} REQUIRED) endif() endif() endif() endforeach() # Ensure that the MITK CMake module path comes first set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR} ${CMAKE_MODULE_PATH} ) if(MITK_USE_DCMTK) # Due to the preferred CONFIG mode in find_package calls above, # the DCMTKConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMTK. if(${_dcmtk_dir_orig} MATCHES "${MITK_EXTERNAL_PROJECT_PREFIX}.*") # Help our FindDCMTK.cmake script find our super-build DCMTK set(DCMTK_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) else() # Use the original value set(DCMTK_DIR ${_dcmtk_dir_orig}) endif() find_package(DCMTK REQUIRED MODULE) endif() if(MITK_USE_DCMQI) # Due to the preferred CONFIG mode in find_package calls above, # the DCMQIConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMQI. # Help our FindDCMQI.cmake script find our super-build DCMQI set(DCMQI_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) find_package(DCMQI REQUIRED) endif() link_directories(${Boost_LIBRARY_DIRS}) if(MITK_USE_OpenIGTLink) link_directories(${OpenIGTLink_LIBRARY_DIRS}) endif() if(MITK_USE_OpenCL) find_package(OpenCL REQUIRED) endif() if(MITK_USE_OpenMP) find_package(OpenMP REQUIRED COMPONENTS CXX) else() find_package(OpenMP QUIET COMPONENTS CXX) if(OpenMP_FOUND) set(MITK_USE_OpenMP ON CACHE BOOL "" FORCE) elseif(APPLE AND OpenMP_libomp_LIBRARY AND NOT OpenMP_CXX_LIB_NAMES) set(OpenMP_CXX_LIB_NAMES libomp CACHE STRING "" FORCE) get_filename_component(openmp_lib_dir "${OpenMP_libomp_LIBRARY}" DIRECTORY) set(openmp_include_dir "${openmp_lib_dir}/../include") if(EXISTS "${openmp_include_dir}") get_filename_component(openmp_include_dir "${openmp_include_dir}" REALPATH) set(OpenMP_CXX_FLAGS "-Xpreprocessor -fopenmp -I${openmp_include_dir}" CACHE STRING "" FORCE) find_package(OpenMP QUIET COMPONENTS CXX) if(OpenMP_FOUND) set(MITK_USE_OpenMP ON CACHE BOOL "" FORCE) endif() endif() endif() endif() # Qt support if(MITK_USE_Qt5) find_package(Qt5Core ${MITK_QT5_MINIMUM_VERSION} REQUIRED) # at least Core required get_target_property(_qmake_exec Qt5::qmake LOCATION) execute_process(COMMAND ${_qmake_exec} -query QT_INSTALL_BINS RESULT_VARIABLE _result OUTPUT_VARIABLE QT_BINARY_DIR ERROR_VARIABLE _error ) string(STRIP "${QT_BINARY_DIR}" QT_BINARY_DIR) if(_result OR NOT EXISTS "${QT_BINARY_DIR}") message(FATAL_ERROR "Could not determine Qt binary directory: ${_result} ${QT_BINARY_DIR} ${_error}") endif() find_program(QT_HELPGENERATOR_EXECUTABLE NAMES qhelpgenerator qhelpgenerator-qt5 qhelpgenerator5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_COLLECTIONGENERATOR_EXECUTABLE NAMES qcollectiongenerator qcollectiongenerator-qt5 qcollectiongenerator5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_ASSISTANT_EXECUTABLE NAMES assistant assistant-qt5 assistant5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_XMLPATTERNS_EXECUTABLE NAMES xmlpatterns PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) mark_as_advanced(QT_HELPGENERATOR_EXECUTABLE QT_COLLECTIONGENERATOR_EXECUTABLE QT_ASSISTANT_EXECUTABLE QT_XMLPATTERNS_EXECUTABLE ) if(MITK_USE_BLUEBERRY) option(BLUEBERRY_USE_QT_HELP "Enable support for integrating plugin documentation into Qt Help" ${DOXYGEN_FOUND}) mark_as_advanced(BLUEBERRY_USE_QT_HELP) # Sanity checks for in-application BlueBerry plug-in help generation if(BLUEBERRY_USE_QT_HELP) set(_force_blueberry_use_qt_help_to_off 0) if(NOT DOXYGEN_FOUND) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because Doxygen was not found.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(DOXYGEN_FOUND AND DOXYGEN_VERSION VERSION_LESS 1.8.7) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because Doxygen version 1.8.7 or newer not found.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT QT_HELPGENERATOR_EXECUTABLE) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because QT_HELPGENERATOR_EXECUTABLE is empty.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT MITK_USE_Qt5) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because MITK_USE_Qt5 is OFF.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT QT_XMLPATTERNS_EXECUTABLE) message("You have enabled Qt Help support, but QT_XMLPATTERNS_EXECUTABLE is empty") set(_force_blueberry_use_qt_help_to_off 1) endif() if(_force_blueberry_use_qt_help_to_off) set(BLUEBERRY_USE_QT_HELP OFF CACHE BOOL "Enable support for integrating plugin documentation into Qt Help" FORCE) endif() endif() if(BLUEBERRY_QT_HELP_REQUIRED AND NOT BLUEBERRY_USE_QT_HELP) message(FATAL_ERROR "BLUEBERRY_USE_QT_HELP is required to be set to ON") endif() endif() endif() #----------------------------------------------------------------------------- # Testing #----------------------------------------------------------------------------- if(BUILD_TESTING) enable_testing() include(CTest) mark_as_advanced(TCL_TCLSH DART_ROOT) - option(MITK_ENABLE_RENDERING_TESTING OFF "Enable the MITK rendering tests. Requires x-server in Linux.") - #Rendering testing does not work for Linux nightlies, thus it is disabled per default - #and activated for Mac and Windows. - if(WIN32 OR APPLE) - set(MITK_ENABLE_RENDERING_TESTING ON) - endif() - mark_as_advanced( MITK_ENABLE_RENDERING_TESTING ) - # Setup file for setting custom ctest vars configure_file( CMake/CTestCustom.cmake.in ${MITK_BINARY_DIR}/CTestCustom.cmake @ONLY ) # Initial cache for ProjectTemplate and PluginGenerator tests configure_file( CMake/mitkTestInitialCache.txt.in ${MITK_BINARY_DIR}/mitkTestInitialCache.txt @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 ( const 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 package target include(mitkPackageTest) 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() #----------------------------------------------------------------------------- # Set C/CXX and linker flags for MITK code #----------------------------------------------------------------------------- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MITK_CXX_FLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${MITK_CXX_FLAGS_DEBUG}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${MITK_CXX_FLAGS_RELEASE}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${MITK_C_FLAGS}") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${MITK_C_FLAGS_DEBUG}") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${MITK_C_FLAGS_RELEASE}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MITK_EXE_LINKER_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${MITK_SHARED_LINKER_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${MITK_MODULE_LINKER_FLAGS}") #----------------------------------------------------------------------------- # Add custom targets representing CDash subprojects #----------------------------------------------------------------------------- foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) if(NOT TARGET ${subproject} AND NOT subproject MATCHES "Unlabeled") add_custom_target(${subproject}) set_property(TARGET ${subproject} PROPERTY FOLDER "${MITK_ROOT_FOLDER}/CTestSubprojects") endif() endforeach() #----------------------------------------------------------------------------- # Add subdirectories #----------------------------------------------------------------------------- add_subdirectory(Utilities) add_subdirectory(Modules) include("${CMAKE_CURRENT_SOURCE_DIR}/Modules/ModuleList.cmake") mitkFunctionWhitelistModules(MITK MITK_MODULES) set(MITK_ROOT_FOLDER_BACKUP "${MITK_ROOT_FOLDER}") foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) get_filename_component(MITK_ROOT_FOLDER ${MITK_EXTENSION_DIR} NAME) set(MITK_MODULES_EXTENSION_DIR ${MITK_EXTENSION_DIR}/Modules) get_filename_component(MITK_MODULES_EXTENSION_DIR ${MITK_MODULES_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_MODULES_EXTENSION_DIR}/ModuleList.cmake) set(MITK_MODULES "") include(${MITK_MODULES_EXTENSION_DIR}/ModuleList.cmake) foreach(mitk_module ${MITK_MODULES}) add_subdirectory(${MITK_MODULES_EXTENSION_DIR}/${mitk_module} Modules/${mitk_module}) endforeach() endif() set(MITK_MODULE_NAME_PREFIX ${MITK_DEFAULT_MODULE_NAME_PREFIX}) endforeach() set(MITK_ROOT_FOLDER "${MITK_ROOT_FOLDER_BACKUP}") add_subdirectory(Wrapping) if(MITK_USE_BLUEBERRY) set(BLUEBERRY_XPDOC_OUTPUT_DIR ${MITK_DOXYGEN_OUTPUT_DIR}/html/extension-points/html/) # Plug-in testing (needs some work to be enabled again) if(BUILD_TESTING) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp") if(TARGET 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() endif() set(BLUEBERRY_TEST_APP_ID "org.mitk.qt.coreapplication") endif() include("${CMAKE_CURRENT_SOURCE_DIR}/Plugins/PluginList.cmake") mitkFunctionWhitelistPlugins(MITK MITK_PLUGINS) set(mitk_plugins_fullpath "") foreach(mitk_plugin ${MITK_PLUGINS}) list(APPEND mitk_plugins_fullpath Plugins/${mitk_plugin}) endforeach() set(MITK_PLUGIN_REGEX_LIST "") foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) set(MITK_PLUGINS_EXTENSION_DIR ${MITK_EXTENSION_DIR}/Plugins) get_filename_component(MITK_PLUGINS_EXTENSION_DIR ${MITK_PLUGINS_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_PLUGINS_EXTENSION_DIR}/PluginList.cmake) set(MITK_PLUGINS "") include(${MITK_PLUGINS_EXTENSION_DIR}/PluginList.cmake) foreach(mitk_plugin ${MITK_PLUGINS}) list(APPEND mitk_plugins_fullpath ${MITK_PLUGINS_EXTENSION_DIR}/${mitk_plugin}) endforeach() endif() endforeach() if(EXISTS ${MITK_PRIVATE_MODULES}/PluginList.cmake) include(${MITK_PRIVATE_MODULES}/PluginList.cmake) foreach(mitk_plugin ${MITK_PRIVATE_PLUGINS}) list(APPEND mitk_plugins_fullpath ${MITK_PRIVATE_MODULES}/${mitk_plugin}) endforeach() endif() if(MITK_BUILD_EXAMPLES) include("${CMAKE_CURRENT_SOURCE_DIR}/Examples/Plugins/PluginList.cmake") set(mitk_example_plugins_fullpath ) foreach(mitk_example_plugin ${MITK_EXAMPLE_PLUGINS}) list(APPEND mitk_example_plugins_fullpath Examples/Plugins/${mitk_example_plugin}) list(APPEND mitk_plugins_fullpath Examples/Plugins/${mitk_example_plugin}) endforeach() endif() # Specify which plug-ins belong to this project macro(GetMyTargetLibraries all_target_libraries varname) set(re_ctkplugin_mitk "^org_mitk_[a-zA-Z0-9_]+$") set(re_ctkplugin_bb "^org_blueberry_[a-zA-Z0-9_]+$") set(_tmp_list) list(APPEND _tmp_list ${all_target_libraries}) ctkMacroListFilter(_tmp_list re_ctkplugin_mitk re_ctkplugin_bb MITK_PLUGIN_REGEX_LIST OUTPUT_VARIABLE ${varname}) endmacro() # Get infos about application directories and build options set(mitk_apps_fullpath "") foreach(MITK_EXTENSION_DIR ${MITK_DIR_PLUS_EXTENSION_DIRS}) set(MITK_APPLICATIONS_EXTENSION_DIR ${MITK_EXTENSION_DIR}/Applications) get_filename_component(MITK_APPLICATIONS_EXTENSION_DIR ${MITK_APPLICATIONS_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_APPLICATIONS_EXTENSION_DIR}/AppList.cmake) set(MITK_APPS "") include(${MITK_APPLICATIONS_EXTENSION_DIR}/AppList.cmake) foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 directory_name) list(GET target_info_list 1 option_name) if(${option_name}) list(APPEND mitk_apps_fullpath "${MITK_APPLICATIONS_EXTENSION_DIR}/${directory_name}^^${option_name}") endif() endforeach() endif() endforeach() if (mitk_plugins_fullpath) ctkMacroSetupPlugins(${mitk_plugins_fullpath} BUILD_OPTION_PREFIX MITK_BUILD_ APPS ${mitk_apps_fullpath} BUILD_ALL ${MITK_BUILD_ALL_PLUGINS} COMPACT_OPTIONS) endif() set(MITK_PLUGIN_USE_FILE "${MITK_BINARY_DIR}/MitkPluginUseFile.cmake") if(${PROJECT_NAME}_PLUGIN_LIBRARIES) ctkFunctionGeneratePluginUseFile(${MITK_PLUGIN_USE_FILE}) else() file(REMOVE ${MITK_PLUGIN_USE_FILE}) set(MITK_PLUGIN_USE_FILE ) endif() endif() #----------------------------------------------------------------------------- # Documentation #----------------------------------------------------------------------------- if(DOXYGEN_FOUND) add_subdirectory(Documentation) endif() #----------------------------------------------------------------------------- # Installation #----------------------------------------------------------------------------- # set MITK cpack variables # These are the default variables, which can be overwritten ( see below ) include(mitkSetupCPack) set(use_default_config ON) set(ALL_MITK_APPS "") set(activated_apps_no 0) foreach(MITK_EXTENSION_DIR ${MITK_DIR_PLUS_EXTENSION_DIRS}) set(MITK_APPLICATIONS_EXTENSION_DIR ${MITK_EXTENSION_DIR}/Applications) get_filename_component(MITK_APPLICATIONS_EXTENSION_DIR ${MITK_APPLICATIONS_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_APPLICATIONS_EXTENSION_DIR}/AppList.cmake) set(MITK_APPS "") include(${MITK_APPLICATIONS_EXTENSION_DIR}/AppList.cmake) foreach(mitk_app ${MITK_APPS}) string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 directory_name) list(GET target_info_list 1 option_name) list(GET target_info_list 2 executable_name) list(APPEND ALL_MITK_APPS "${MITK_EXTENSION_DIR}/Applications/${directory_name}^^${option_name}^^${executable_name}") if(${option_name} OR MITK_BUILD_ALL_APPS) MATH(EXPR activated_apps_no "${activated_apps_no} + 1") endif() endforeach() endif() endforeach() list(LENGTH ALL_MITK_APPS app_count) if(app_count EQUAL 1 AND (activated_apps_no EQUAL 1 OR MITK_BUILD_ALL_APPS)) # Corner case if there is only one app in total set(use_project_cpack ON) elseif(activated_apps_no EQUAL 1 AND NOT MITK_BUILD_ALL_APPS) # Only one app is enabled (no "build all" flag set) set(use_project_cpack ON) else() # Less or more then one app is enabled set(use_project_cpack OFF) endif() foreach(mitk_app ${ALL_MITK_APPS}) # extract target_dir and option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 target_dir) list(GET target_info_list 1 option_name) list(GET target_info_list 2 executable_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) # check whether application specific configuration files will be used if(use_project_cpack) # use files if they exist if(EXISTS "${target_dir}/CPackOptions.cmake") include("${target_dir}/CPackOptions.cmake") endif() if(EXISTS "${target_dir}/CPackConfig.cmake.in") set(CPACK_PROJECT_CONFIG_FILE "${target_dir}/CPackConfig.cmake") configure_file(${target_dir}/CPackConfig.cmake.in ${CPACK_PROJECT_CONFIG_FILE} @ONLY) set(use_default_config OFF) endif() endif() # add link to the list list(APPEND CPACK_CREATE_DESKTOP_LINKS "${executable_name}") endif() endforeach() # if no application specific configuration file was used, use default if(use_default_config) configure_file(${MITK_SOURCE_DIR}/MITKCPackOptions.cmake.in ${MITK_BINARY_DIR}/MITKCPackOptions.cmake @ONLY) set(CPACK_PROJECT_CONFIG_FILE "${MITK_BINARY_DIR}/MITKCPackOptions.cmake") endif() # include CPack model once all variables are set include(CPack) # Additional installation rules include(mitkInstallRules) #----------------------------------------------------------------------------- # Last configuration steps #----------------------------------------------------------------------------- # ---------------- Export targets ----------------- set(MITK_EXPORTS_FILE "${MITK_BINARY_DIR}/MitkExports.cmake") file(REMOVE ${MITK_EXPORTS_FILE}) set(targets_to_export) get_property(module_targets GLOBAL PROPERTY MITK_MODULE_TARGETS) if(module_targets) list(APPEND targets_to_export ${module_targets}) endif() if(MITK_USE_BLUEBERRY) if(MITK_PLUGIN_LIBRARIES) list(APPEND targets_to_export ${MITK_PLUGIN_LIBRARIES}) endif() endif() export(TARGETS ${targets_to_export} APPEND FILE ${MITK_EXPORTS_FILE}) set(MITK_EXPORTED_TARGET_PROPERTIES ) foreach(target_to_export ${targets_to_export}) get_target_property(autoload_targets ${target_to_export} MITK_AUTOLOAD_TARGETS) if(autoload_targets) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_AUTOLOAD_TARGETS \"${autoload_targets}\")") endif() get_target_property(autoload_dir ${target_to_export} MITK_AUTOLOAD_DIRECTORY) if(autoload_dir) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_AUTOLOAD_DIRECTORY \"${autoload_dir}\")") endif() get_target_property(deprecated_module ${target_to_export} MITK_MODULE_DEPRECATED_SINCE) if(deprecated_module) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_MODULE_DEPRECATED_SINCE \"${deprecated_module}\")") endif() endforeach() # ---------------- External projects ----------------- get_property(MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS_CONFIG GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS) set(MITK_CONFIG_EXTERNAL_PROJECTS ) #string(REPLACE "^^" ";" _mitk_external_projects ${MITK_EXTERNAL_PROJECTS}) foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) set(MITK_CONFIG_EXTERNAL_PROJECTS "${MITK_CONFIG_EXTERNAL_PROJECTS} set(MITK_USE_${ep} ${MITK_USE_${ep}}) set(MITK_${ep}_DIR \"${${ep}_DIR}\") set(MITK_${ep}_COMPONENTS ${_components}) ") endforeach() foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_package GLOBAL PROPERTY MITK_${ep}_PACKAGE) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) if(_components) set(_components_arg COMPONENTS \${_components}) else() set(_components_arg) endif() if(_package) set(MITK_CONFIG_EXTERNAL_PROJECTS "${MITK_CONFIG_EXTERNAL_PROJECTS} if(MITK_USE_${ep}) set(${ep}_DIR \${MITK_${ep}_DIR}) if(MITK_${ep}_COMPONENTS) mitkMacroFindDependency(${_package} COMPONENTS \${MITK_${ep}_COMPONENTS}) else() mitkMacroFindDependency(${_package}) endif() endif()") endif() endforeach() # ---------------- Tools ----------------- 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 files ----------------- configure_file(mitkVersion.h.in ${MITK_BINARY_DIR}/mitkVersion.h) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) 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) write_basic_config_version_file(${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake VERSION ${MITK_VERSION_STRING} COMPATIBILITY AnyNewerVersion) #----------------------------------------------------------------------------- # MITK Applications #----------------------------------------------------------------------------- # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Applications) if(MSVC AND TARGET MitkWorkbench) set_directory_properties(PROPERTIES VS_STARTUP_PROJECT MitkWorkbench) endif() foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) set(MITK_APPLICATIONS_EXTENSION_DIR ${MITK_EXTENSION_DIR}/Applications) get_filename_component(MITK_APPLICATIONS_EXTENSION_DIR ${MITK_APPLICATIONS_EXTENSION_DIR} ABSOLUTE) if(EXISTS ${MITK_APPLICATIONS_EXTENSION_DIR}/CMakeLists.txt) add_subdirectory(${MITK_APPLICATIONS_EXTENSION_DIR} Applications) endif() endforeach() #----------------------------------------------------------------------------- # MITK Examples #----------------------------------------------------------------------------- if(MITK_BUILD_EXAMPLES) # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Examples) endif() #----------------------------------------------------------------------------- # Print configuration summary #----------------------------------------------------------------------------- message("\n\n") feature_summary( DESCRIPTION "------- FEATURE SUMMARY FOR ${PROJECT_NAME} -------" WHAT ALL ) diff --git a/Examples/Tutorial/QtTesting.cpp b/Examples/Tutorial/QtTesting.cpp deleted file mode 100644 index dad5e46090..0000000000 --- a/Examples/Tutorial/QtTesting.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ -#include -#include - -#include -#include - -int QtTesting(void) -{ - // QtTestingClass *qttestingclass = new QtTestingClass; - std::cout << "Testing ... " << std::endl; - auto timer = new QTimer(QApplication::instance()); - timer->setSingleShot(true); - QObject::connect(timer, SIGNAL(timeout()), QApplication::instance(), SLOT(quit())); - timer->start(2000); // 2 seconds single-shot timer - QApplication::instance()->exec(); - return EXIT_SUCCESS; -} diff --git a/Examples/Tutorial/QtTesting.h b/Examples/Tutorial/QtTesting.h deleted file mode 100644 index 66c4a6f467..0000000000 --- a/Examples/Tutorial/QtTesting.h +++ /dev/null @@ -1,23 +0,0 @@ -/*============================================================================ - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center (DKFZ) -All rights reserved. - -Use of this source code is governed by a 3-clause BSD license that can be -found in the LICENSE file. - -============================================================================*/ - -//#include - -int QtTesting(void); - -// class QtTestingClass : public QObject -//{ -// Q_OBJECT -// public: -// QtTestingClass( QObject * parent = 0, const char * name = 0 ); -// -//} diff --git a/Examples/Tutorial/Step1/Step1.cpp b/Examples/Tutorial/Step1/Step1.cpp index c0fe5e65a5..c203119b7f 100644 --- a/Examples/Tutorial/Step1/Step1.cpp +++ b/Examples/Tutorial/Step1/Step1.cpp @@ -1,93 +1,85 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRegisterClasses.h" #include "QmitkRenderWindow.h" #include #include #include #include //##Documentation //## @brief Load image (nrrd format) and display it in a 2D view int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); if (argc < 2) { fprintf(stderr, "Usage: %s [filename] \n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str()); return 1; } // Register Qmitk-dependent global instances QmitkRegisterClasses(); //************************************************************************* // Part I: Basic initialization //************************************************************************* // Create a DataStorage // The DataStorage manages all data objects. It is used by the // rendering mechanism to render all data objects // We use the standard implementation mitk::StandaloneDataStorage. mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); //************************************************************************* // Part II: Create some data by reading a file //************************************************************************* // Load datanode (eg. many image formats, surface formats, etc.) mitk::IOUtil::Load(argv[1], *ds); //************************************************************************* // Part IV: Create window and pass the datastorage to it //************************************************************************* // Create a RenderWindow QmitkRenderWindow renderWindow; // Tell the RenderWindow which (part of) the datastorage to render renderWindow.GetRenderer()->SetDataStorage(ds); // Initialize the RenderWindow auto geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // mitk::RenderingManager::GetInstance()->InitializeViews(); // Select a slice mitk::SliceNavigationController::Pointer sliceNaviController = renderWindow.GetSliceNavigationController(); if (sliceNaviController) sliceNaviController->GetSlice()->SetPos(0); //************************************************************************* // Part V: Qt-specific initialization //************************************************************************* renderWindow.show(); renderWindow.resize(256, 256); -// for testing -#include "QtTesting.h" - if (strcmp(argv[argc - 1], "-testing") != 0) - return qtapplication.exec(); - else - return QtTesting(); - - // cleanup: Remove References to DataStorage. This will delete the object - ds = nullptr; + return qtapplication.exec(); } /** \example Step1.cpp */ diff --git a/Examples/Tutorial/Step1/files.cmake b/Examples/Tutorial/Step1/files.cmake index f737b9bdaa..8568729050 100644 --- a/Examples/Tutorial/Step1/files.cmake +++ b/Examples/Tutorial/Step1/files.cmake @@ -1,4 +1,3 @@ set(CPP_FILES Step1.cpp - ../QtTesting.cpp - ) +) diff --git a/Examples/Tutorial/Step2/Step2.cpp b/Examples/Tutorial/Step2/Step2.cpp index 8de4088bed..690cecd5b4 100644 --- a/Examples/Tutorial/Step2/Step2.cpp +++ b/Examples/Tutorial/Step2/Step2.cpp @@ -1,98 +1,93 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRegisterClasses.h" #include "QmitkRenderWindow.h" #include #include #include #include //##Documentation //## @brief Load one or more data sets (many image, surface //## and other formats) and display it in a 2D view int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); if (argc < 2) { fprintf( stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str()); return 1; } // Register Qmitk-dependent global instances QmitkRegisterClasses(); //************************************************************************* // Part I: Basic initialization //************************************************************************* // Create a data storage object. We will use it as a singleton mitk::StandaloneDataStorage::Pointer storage = mitk::StandaloneDataStorage::New(); //************************************************************************* // Part II: Create some data by reading files //************************************************************************* int i; for (i = 1; i < argc; ++i) { // For testing if (strcmp(argv[i], "-testing") == 0) continue; //********************************************************************* // Part III: Put the data into the datastorage //********************************************************************* // Add the node to the DataStorage mitk::IOUtil::Load(argv[i], *storage); } //************************************************************************* // Part IV: Create window and pass the datastorage to it //************************************************************************* // Create a RenderWindow QmitkRenderWindow renderWindow; // Tell the RenderWindow which (part of) the datastorage to render renderWindow.GetRenderer()->SetDataStorage(storage); // Initialize the RenderWindow auto geo = storage->ComputeBoundingGeometry3D(storage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Select a slice mitk::SliceNavigationController::Pointer sliceNaviController = renderWindow.GetSliceNavigationController(); if (sliceNaviController) sliceNaviController->GetSlice()->SetPos(2); //************************************************************************* // Part V: Qt-specific initialization //************************************************************************* renderWindow.show(); renderWindow.resize(256, 256); -// for testing -#include "QtTesting.h" - if (strcmp(argv[argc - 1], "-testing") != 0) - return qtapplication.exec(); - else - return QtTesting(); + return qtapplication.exec(); } /** \example Step2.cpp */ diff --git a/Examples/Tutorial/Step2/files.cmake b/Examples/Tutorial/Step2/files.cmake index 228aaba31f..d062a05faa 100644 --- a/Examples/Tutorial/Step2/files.cmake +++ b/Examples/Tutorial/Step2/files.cmake @@ -1,4 +1,3 @@ set(CPP_FILES Step2.cpp - ../QtTesting.cpp - ) +) diff --git a/Examples/Tutorial/Step3/Step3.cpp b/Examples/Tutorial/Step3/Step3.cpp index 6e5015d309..dd50e6d8d4 100644 --- a/Examples/Tutorial/Step3/Step3.cpp +++ b/Examples/Tutorial/Step3/Step3.cpp @@ -1,159 +1,154 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRegisterClasses.h" #include "QmitkRenderWindow.h" #include #include #include #include #include #include #include #include //##Documentation //## @brief Change the type of display to 3D //## //## As in Step2, load one or more data sets (many image, surface //## and other formats), but display it in a 3D view. //## The QmitkRenderWindow is now used for displaying a 3D view, by //## setting the used mapper-slot to Standard3D. //## Since volume-rendering is a (rather) slow procedure, the default //## is that images are not displayed in the 3D view. For this example, //## we want volume-rendering, thus we switch it on by setting //## the Boolean-property "volumerendering" to "true". int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); if (argc < 2) { fprintf( stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str()); return 1; } // Register Qmitk-dependent global instances QmitkRegisterClasses(); //************************************************************************* // Part I: Basic initialization //************************************************************************* // Create a DataStorage mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); //************************************************************************* // Part II: Create some data by reading files //************************************************************************* int i; for (i = 1; i < argc; ++i) { // For testing if (strcmp(argv[i], "-testing") == 0) continue; //********************************************************************* // Part III: Put the data into the datastorage //********************************************************************* // Load datanode (eg. many image formats, surface formats, etc.) mitk::StandaloneDataStorage::SetOfObjects::Pointer dataNodes = mitk::IOUtil::Load(argv[i], *ds); if (dataNodes->empty()) { fprintf(stderr, "Could not open file %s \n\n", argv[i]); exit(2); } mitk::DataNode::Pointer node = dataNodes->at(0); // ********************************************************* // ********************* START OF NEW PART 1 (Step 3a) ***** // ********************************************************* //********************************************************************* // Part IV: We want all images to be volume-rendered //********************************************************************* // Check if the data is an image by dynamic_cast-ing the data // contained in the node. Warning: dynamic_cast's are rather slow, // do not use it too often! mitk::Image::Pointer image = dynamic_cast(node->GetData()); if (image.IsNotNull()) { // Set the property "volumerendering" to the Boolean value "true" node->SetProperty("volumerendering", mitk::BoolProperty::New(true)); // Create a transfer function to assign optical properties (color and opacity) to grey-values of the data mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); tf->InitializeByMitkImage(image); // Set the color transfer function AddRGBPoint(double x, double r, double g, double b) tf->GetColorTransferFunction()->AddRGBPoint(tf->GetColorTransferFunction()->GetRange()[0], 1.0, 0.0, 0.0); tf->GetColorTransferFunction()->AddRGBPoint(tf->GetColorTransferFunction()->GetRange()[1], 1.0, 1.0, 0.0); // Set the piecewise opacity transfer function AddPoint(double x, double y) tf->GetScalarOpacityFunction()->AddPoint(0, 0); tf->GetScalarOpacityFunction()->AddPoint(tf->GetColorTransferFunction()->GetRange()[1], 1); node->SetProperty("TransferFunction", mitk::TransferFunctionProperty::New(tf.GetPointer())); } // ********************************************************* // ******************* END OF NEW PART 1 (Step 3a) ********* // ********************************************************* } //************************************************************************* // Part V: Create window and pass the tree to it //************************************************************************* // Create a renderwindow QmitkRenderWindow renderWindow; // Tell the renderwindow which (part of) the datastorage to render renderWindow.GetRenderer()->SetDataStorage(ds); // ********************************************************* // ****************** START OF NEW PART 2 (Step 3b) ******** // ********************************************************* // Use it as a 3D view! renderWindow.GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D); // Reposition the camera to include all visible actors renderWindow.GetRenderer()->GetVtkRenderer()->ResetCamera(); // ********************************************************* // ******************* END OF NEW PART 2 (Step 3b) ********* // ********************************************************* //************************************************************************* // Part VI: Qt-specific initialization //************************************************************************* renderWindow.show(); renderWindow.resize(256, 256); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); -// for testing -#include "QtTesting.h" - if (strcmp(argv[argc - 1], "-testing") != 0) - return qtapplication.exec(); - else - return QtTesting(); + return qtapplication.exec(); } /** \example Step3.cpp */ diff --git a/Examples/Tutorial/Step3/files.cmake b/Examples/Tutorial/Step3/files.cmake index 92387dd3f9..30d2410c08 100644 --- a/Examples/Tutorial/Step3/files.cmake +++ b/Examples/Tutorial/Step3/files.cmake @@ -1,4 +1,3 @@ set(CPP_FILES Step3.cpp - ../QtTesting.cpp - ) +) diff --git a/Examples/Tutorial/Step4/Step4.cpp b/Examples/Tutorial/Step4/Step4.cpp index 36e6888a4c..236d2200c0 100644 --- a/Examples/Tutorial/Step4/Step4.cpp +++ b/Examples/Tutorial/Step4/Step4.cpp @@ -1,169 +1,164 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRegisterClasses.h" #include "QmitkRenderWindow.h" #include "QmitkSliceWidget.h" #include "mitkNodePredicateDataType.h" #include "mitkProperties.h" #include "mitkRenderingManager.h" #include "mitkStandaloneDataStorage.h" #include #include #include #include #include //##Documentation //## @brief Use several views to explore data //## //## As in Step2 and Step3, load one or more data sets (many image, //## surface and other formats), but create 3 views on the data. //## The QmitkRenderWindow is used for displaying a 3D view as in Step3, //## but without volume-rendering. //## Furthermore, we create two 2D views for slicing through the data. //## We use the class QmitkSliceWidget, which is based on the class //## QmitkRenderWindow, but additionally provides sliders //## to slice through the data. We create two instances of //## QmitkSliceWidget, one for axial and one for sagittal slicing. //## The two slices are also shown at their correct position in 3D as //## well as intersection-line, each in the other 2D view. int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); if (argc < 2) { fprintf( stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str()); return 1; } // Register Qmitk-dependent global instances QmitkRegisterClasses(); //************************************************************************* // Part I: Basic initialization //************************************************************************* // Create a DataStorage mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); //************************************************************************* // Part II: Create some data by reading files //************************************************************************* int i; for (i = 1; i < argc; ++i) { // For testing if (strcmp(argv[i], "-testing") == 0) continue; //********************************************************************* // Part III: Put the data into the datastorage //********************************************************************* // Load datanode (eg. many image formats, surface formats, etc.) mitk::IOUtil::Load(argv[i], *ds); } //************************************************************************* // Part IV: Create windows and pass the tree to it //************************************************************************* // Create toplevel widget with horizontal layout QWidget toplevelWidget; QHBoxLayout layout; layout.setSpacing(2); layout.setMargin(0); toplevelWidget.setLayout(&layout); //************************************************************************* // Part IVa: 3D view //************************************************************************* // Create a renderwindow QmitkRenderWindow renderWindow(&toplevelWidget); layout.addWidget(&renderWindow); // Tell the renderwindow which (part of) the datastorage to render renderWindow.GetRenderer()->SetDataStorage(ds); // Use it as a 3D view renderWindow.GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D); // Reposition the camera to include all visible actors renderWindow.GetRenderer()->GetVtkRenderer()->ResetCamera(); // ******************************************************* // ****************** START OF NEW PART ****************** // ******************************************************* //************************************************************************* // Part IVb: 2D view for slicing axially //************************************************************************* // Create QmitkSliceWidget, which is based on the class // QmitkRenderWindow, but additionally provides sliders QmitkSliceWidget view2(&toplevelWidget); layout.addWidget(&view2); view2.SetLevelWindowEnabled(true); // Tell the QmitkSliceWidget which (part of) the tree to render. // By default, it slices the data axially view2.SetDataStorage(ds); // Get the image from the data storage. A predicate (mitk::NodePredicateBase) // is used to get only nodes of the type mitk::Image. mitk::DataStorage::SetOfObjects::ConstPointer rs = ds->GetSubset(mitk::TNodePredicateDataType::New()); view2.SetData(rs->Begin(), mitk::SliceNavigationController::Axial); // We want to see the position of the slice in 2D and the // slice itself in 3D: add it to the datastorage! ds->Add(view2.GetRenderer()->GetCurrentWorldPlaneGeometryNode()); //************************************************************************* // Part IVc: 2D view for slicing sagitally //************************************************************************* // Create QmitkSliceWidget, which is based on the class // QmitkRenderWindow, but additionally provides sliders QmitkSliceWidget view3(&toplevelWidget); layout.addWidget(&view3); view3.SetDataStorage(ds); // Tell the QmitkSliceWidget which (part of) the datastorage to render // and to slice sagitally view3.SetData(rs->Begin(), mitk::SliceNavigationController::Sagittal); // We want to see the position of the slice in 2D and the // slice itself in 3D: add it to the datastorage! ds->Add(view3.GetRenderer()->GetCurrentWorldPlaneGeometryNode()); // ******************************************************* // ******************* END OF NEW PART ******************* // ******************************************************* //************************************************************************* // Part V: Qt-specific initialization //************************************************************************* toplevelWidget.show(); -// for testing -#include "QtTesting.h" - if (strcmp(argv[argc - 1], "-testing") != 0) - return qtapplication.exec(); - else - return QtTesting(); + return qtapplication.exec(); } /** \example Step4.cpp */ diff --git a/Examples/Tutorial/Step4/files.cmake b/Examples/Tutorial/Step4/files.cmake index 97d991f251..f092ddd9de 100644 --- a/Examples/Tutorial/Step4/files.cmake +++ b/Examples/Tutorial/Step4/files.cmake @@ -1,4 +1,3 @@ set(CPP_FILES Step4.cpp - ../QtTesting.cpp - ) +) diff --git a/Examples/Tutorial/Step5/Step5.cpp b/Examples/Tutorial/Step5/Step5.cpp index f6f81e571d..6e3204d641 100644 --- a/Examples/Tutorial/Step5/Step5.cpp +++ b/Examples/Tutorial/Step5/Step5.cpp @@ -1,208 +1,203 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRegisterClasses.h" #include "QmitkRenderWindow.h" #include "QmitkSliceWidget.h" #include "mitkNodePredicateDataType.h" #include "mitkProperties.h" #include "mitkRenderingManager.h" #include "mitkStandaloneDataStorage.h" #include "mitkPointSet.h" // NEW INCLUDE #include "mitkPointSetDataInteractor.h" #include #include #include #include //##Documentation //## @brief Interactively add points //## //## As in Step4, load one or more data sets (many image, //## surface and other formats) and create 3 views on the data. //## Additionally, we want to interactively add points. A node containing //## a PointSet as data is added to the data tree and a PointSetDataInteractor //## is associated with the node, which handles the interaction. The //## @em interaction @em pattern is defined in a state-machine, stored in an //## external XML file. Thus, we need to load a state-machine //## The interaction patterns defines the @em events, //## on which the interactor reacts (e.g., which mouse buttons are used to //## set a point), the @em transition to the next state (e.g., the initial //## may be "empty point set") and associated @a actions (e.g., add a point //## at the position where the mouse-click occured). int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); if (argc < 2) { fprintf( stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str()); return 1; } // Register Qmitk-dependent global instances QmitkRegisterClasses(); //************************************************************************* // Part I: Basic initialization //************************************************************************* // Create a DataStorage mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); //************************************************************************* // Part II: Create some data by reading files //************************************************************************* int i; for (i = 1; i < argc; ++i) { // For testing if (strcmp(argv[i], "-testing") == 0) continue; // Load datanode (eg. many image formats, surface formats, etc.) mitk::StandaloneDataStorage::SetOfObjects::Pointer dataNodes = mitk::IOUtil::Load(argv[i], *ds); //********************************************************************* // Part III: Put the data into the datastorage //********************************************************************* // Add the node to the DataStorage if (dataNodes->empty()) { fprintf(stderr, "Could not open file %s \n\n", argv[i]); exit(2); } } //************************************************************************* // Part V: Create windows and pass the tree to it //************************************************************************* // Create toplevel widget with horizontal layout QWidget toplevelWidget; QHBoxLayout layout; layout.setSpacing(2); layout.setMargin(0); toplevelWidget.setLayout(&layout); //************************************************************************* // Part Va: 3D view //************************************************************************* // Create a renderwindow QmitkRenderWindow renderWindow(&toplevelWidget); layout.addWidget(&renderWindow); // Tell the renderwindow which (part of) the tree to render renderWindow.GetRenderer()->SetDataStorage(ds); // Use it as a 3D view renderWindow.GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D); // Reposition the camera to include all visible actors renderWindow.GetRenderer()->GetVtkRenderer()->ResetCamera(); //************************************************************************* // Part Vb: 2D view for slicing axially //************************************************************************* // Create QmitkSliceWidget, which is based on the class // QmitkRenderWindow, but additionally provides sliders QmitkSliceWidget view2(&toplevelWidget); layout.addWidget(&view2); // Tell the QmitkSliceWidget which (part of) the tree to render. // By default, it slices the data axially view2.SetDataStorage(ds); mitk::DataStorage::SetOfObjects::ConstPointer rs = ds->GetSubset(mitk::TNodePredicateDataType::New()); view2.SetData(rs->Begin(), mitk::SliceNavigationController::Axial); // We want to see the position of the slice in 2D and the // slice itself in 3D: add it to the tree! ds->Add(view2.GetRenderer()->GetCurrentWorldPlaneGeometryNode()); //************************************************************************* // Part Vc: 2D view for slicing sagitally //************************************************************************* // Create QmitkSliceWidget, which is based on the class // QmitkRenderWindow, but additionally provides sliders QmitkSliceWidget view3(&toplevelWidget); layout.addWidget(&view3); // Tell the QmitkSliceWidget which (part of) the tree to render // and to slice sagitall view3.SetDataStorage(ds); view3.SetData(rs->Begin(), mitk::SliceNavigationController::Sagittal); // We want to see the position of the slice in 2D and the // slice itself in 3D: add it to the tree! ds->Add(view3.GetRenderer()->GetCurrentWorldPlaneGeometryNode()); // ******************************************************* // ****************** START OF NEW PART ****************** // ******************************************************* //************************************************************************* // Part VI: For allowing to interactively add points ... //************************************************************************* // ATTENTION: It is very important that the renderer already know their DataStorage, // because registerig DataInteractors with the render windows is done automatically // and only works if the BaseRenderer and the DataStorage know each other. // Create PointSet and a node for it mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New(); // Store the point set in the DataNode pointSetNode->SetData(pointSet); // Add the node to the tree ds->Add(pointSetNode); // Create PointSetDataInteractor mitk::PointSetDataInteractor::Pointer interactor = mitk::PointSetDataInteractor::New(); // Set the StateMachine pattern that describes the flow of the interactions interactor->LoadStateMachine("PointSet.xml"); // Set the configuration file, which describes the user interactions that trigger actions // in this file SHIFT + LeftClick triggers add Point, but by modifying this file, // it could as well be changes to any other user interaction. interactor->SetEventConfig("PointSetConfig.xml"); // Assign the pointSetNode to the interactor, // alternatively one could also add the DataInteractor to the pointSetNode using the SetDataInteractor() method. interactor->SetDataNode(pointSetNode); // ******************************************************* // ******************* END OF NEW PART ******************* // ******************************************************* //************************************************************************* // Part VII: Qt-specific initialization //************************************************************************* toplevelWidget.show(); -// For testing -#include "QtTesting.h" - if (strcmp(argv[argc - 1], "-testing") != 0) - return qtapplication.exec(); - else - return QtTesting(); + return qtapplication.exec(); } /** \example Step5.cpp */ diff --git a/Examples/Tutorial/Step5/files.cmake b/Examples/Tutorial/Step5/files.cmake index 37b77371cc..61cbad6823 100644 --- a/Examples/Tutorial/Step5/files.cmake +++ b/Examples/Tutorial/Step5/files.cmake @@ -1,4 +1,3 @@ set(CPP_FILES Step5.cpp - ../QtTesting.cpp - ) +) diff --git a/Examples/Tutorial/Step6/Step6main.cpp b/Examples/Tutorial/Step6/Step6main.cpp index e6c2c61f3a..119da5e240 100644 --- a/Examples/Tutorial/Step6/Step6main.cpp +++ b/Examples/Tutorial/Step6/Step6main.cpp @@ -1,47 +1,42 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRegisterClasses.h" #include "Step6.h" #include "mitkDataStorage.h" #include #include int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); if (argc < 2) { fprintf( stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str()); return 1; } // Register Qmitk-dependent global instances QmitkRegisterClasses(); Step6 mainWidget(argc, argv, nullptr); mainWidget.Initialize(); mainWidget.show(); -// for testing -#include "QtTesting.h" - if (strcmp(argv[argc - 1], "-testing") != 0) - return qtapplication.exec(); - else - return QtTesting(); + return qtapplication.exec(); } /** \example Step6main.cpp */ diff --git a/Examples/Tutorial/Step6/files.cmake b/Examples/Tutorial/Step6/files.cmake index 51e4db2011..f3137dce13 100644 --- a/Examples/Tutorial/Step6/files.cmake +++ b/Examples/Tutorial/Step6/files.cmake @@ -1,12 +1,11 @@ set(CPP_FILES Step6.cpp Step6RegionGrowing1.cpp Step6RegionGrowing2.cpp Step6RegionGrowing3.cpp Step6main.cpp - ../QtTesting.cpp - ) +) set(MOC_H_FILES Step6.h - ) +) diff --git a/Examples/Tutorial/Step7/Step7main.cpp b/Examples/Tutorial/Step7/Step7main.cpp index fb44f54b43..e6139d294e 100644 --- a/Examples/Tutorial/Step7/Step7main.cpp +++ b/Examples/Tutorial/Step7/Step7main.cpp @@ -1,47 +1,42 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRegisterClasses.h" #include "Step7.h" #include #include int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); if (argc < 2) { fprintf( stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str()); return 1; } // Register Qmitk-dependent global instances QmitkRegisterClasses(); Step7 mainWidget(argc, argv, nullptr); mainWidget.Initialize(); mainWidget.show(); -// for testing -#include "QtTesting.h" - if (strcmp(argv[argc - 1], "-testing") != 0) - return qtapplication.exec(); - else - return QtTesting(); + return qtapplication.exec(); } /** \example Step7main.cpp */ diff --git a/Examples/Tutorial/Step7/files.cmake b/Examples/Tutorial/Step7/files.cmake index 72cf47060e..136d4ba66f 100644 --- a/Examples/Tutorial/Step7/files.cmake +++ b/Examples/Tutorial/Step7/files.cmake @@ -1,14 +1,13 @@ set(CPP_FILES Step7.cpp Step7main.cpp ../Step6/Step6RegionGrowing1.cpp ../Step6/Step6RegionGrowing2.cpp ../Step6/Step6RegionGrowing3.cpp ../Step6/Step6.cpp - ../QtTesting.cpp - ) +) set(MOC_H_FILES ../Step6/Step6.h Step7.h - ) +) diff --git a/Examples/Tutorial/Step8/Step8main.cpp b/Examples/Tutorial/Step8/Step8main.cpp index ecf82688a9..c1f72618a6 100644 --- a/Examples/Tutorial/Step8/Step8main.cpp +++ b/Examples/Tutorial/Step8/Step8main.cpp @@ -1,46 +1,41 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkRegisterClasses.h" #include "Step8.h" #include #include int main(int argc, char *argv[]) { QApplication qtapplication(argc, argv); if (argc < 2) { fprintf( stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str()); return 1; } // Register Qmitk-dependent global instances QmitkRegisterClasses(); Step8 mainWidget(argc, argv, nullptr); mainWidget.Initialize(); mainWidget.show(); -// for testing -#include "QtTesting.h" - if (strcmp(argv[argc - 1], "-testing") != 0) - return qtapplication.exec(); - else - return QtTesting(); + return qtapplication.exec(); } /** \example Step8main.cpp */ diff --git a/Examples/Tutorial/Step8/files.cmake b/Examples/Tutorial/Step8/files.cmake index 1be2ec21f7..1570dd9dda 100644 --- a/Examples/Tutorial/Step8/files.cmake +++ b/Examples/Tutorial/Step8/files.cmake @@ -1,16 +1,15 @@ set(CPP_FILES Step8.cpp Step8main.cpp ../Step6/Step6RegionGrowing1.cpp ../Step6/Step6RegionGrowing2.cpp ../Step6/Step6RegionGrowing3.cpp ../Step6/Step6.cpp ../Step7/Step7.cpp - ../QtTesting.cpp - ) +) set(MOC_H_FILES ../Step6/Step6.h ../Step7/Step7.h Step8.h - ) +) diff --git a/Modules/Annotation/test/files.cmake b/Modules/Annotation/test/files.cmake index 8b6efdd163..a9960f8d92 100644 --- a/Modules/Annotation/test/files.cmake +++ b/Modules/Annotation/test/files.cmake @@ -1,18 +1,11 @@ - set(MODULE_TESTS - mitkAnnotationTest.cpp -) - -if(MITK_ENABLE_RENDERING_TESTING) -set(MODULE_TESTS - ${MODULE_TESTS} + mitkAnnotationTest.cpp mitkManualPlacementAnnotationRendererTest.cpp mitkColorBarAnnotationTest.cpp mitkLabelAnnotation3DTest.cpp mitkLogoAnnotationTest.cpp mitkLayoutAnnotationRendererTest.cpp mitkScaleLegendAnnotationTest.cpp mitkTextAnnotation2DTest.cpp mitkTextAnnotation3DTest.cpp ) -endif() diff --git a/Modules/BasicImageProcessing/CMakeLists.txt b/Modules/BasicImageProcessing/CMakeLists.txt index 6302c23500..b4e12f4b38 100644 --- a/Modules/BasicImageProcessing/CMakeLists.txt +++ b/Modules/BasicImageProcessing/CMakeLists.txt @@ -1,8 +1,8 @@ MITK_CREATE_MODULE( - DEPENDS MitkCore MitkMatchPointRegistration MitkMatchPointRegistrationIO + DEPENDS MitkCore MitkMatchPointRegistration PACKAGE_DEPENDS PUBLIC PRIVATE ITK|ITKIOImageBase+ITKIOGDCM ) add_subdirectory(MiniApps) diff --git a/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h b/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h index b21e660f89..070a3d87d9 100644 --- a/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h +++ b/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h @@ -1,221 +1,212 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkRenderingTestHelper_h #define mitkRenderingTestHelper_h #include #include #include #include #include class vtkRenderWindow; class vtkRenderer; namespace mitk { class MITKTESTINGHELPER_EXPORT RenderingTestHelper { public: /** @brief Generate a rendering test helper object including a render window of the size width * height (in pixel). @param argc Number of parameters. (here: Images) "Usage: [filename1 filenam2 -V referenceScreenshot (optional -T /directory/to/save/differenceImage)] @param argv Given parameters. If no data is inserted via commandline, you can add data later via AddNodeToDataStorage(). @param renderingMode The rendering mode. **/ RenderingTestHelper( int width, int height, int argc, char *argv[], AntiAliasing antiAliasing = AntiAliasing::None); /** @brief Generate a rendering test helper object including a render window of the size width * height (in * pixel).*/ RenderingTestHelper( int width, int height, AntiAliasing antiAliasing = AntiAliasing::None); /** Default destructor */ ~RenderingTestHelper(); /** @brief Getter for the vtkRenderer. **/ vtkRenderer *GetVtkRenderer(); /** @brief Getter for the vtkRenderWindow which should be used to call vtkRegressionTestImage. **/ vtkRenderWindow *GetVtkRenderWindow(); /** @brief Method can be used to save a screenshot (e.g. reference screenshot as a .png file. @param fileName The filename of the new screenshot (including path). **/ void SaveAsPNG(std::string fileName); /** * @brief SetStopRenderWindow Convenience method to make the renderwindow hold after rendering. Usefull for * debugging. * @param flag Flag indicating whether the renderwindow should automatically close (false, default) or stay open * (true). Usefull for debugging. */ void SetAutomaticallyCloseRenderWindow(bool automaticallyCloseRenderWindow); /** @brief This method set the property of the member datastorage @param property Set a property for each image in the datastorage m_DataStorage. If you want to set the property for a single data node, use GetDataStorage() and set the property yourself for the destinct node. **/ void SetImageProperty(const char *propertyKey, mitk::BaseProperty *property); /** @brief Set the view direction of the renderwindow (e.g. sagittal, coronal, axial) **/ void SetViewDirection(mitk::SliceNavigationController::ViewDirection viewDirection); /** @brief Reorient the slice (e.g. rotation and translation like the swivel mode). **/ void ReorientSlices(mitk::Point3D origin, mitk::Vector3D rotation); /** @brief Render everything into an mitkRenderWindow. Call SetViewDirection() and SetProperty() before this method. **/ void Render(); /** @brief Returns the datastorage, in order to modify the data inside a rendering test. **/ mitk::DataStorage::Pointer GetDataStorage(); /** * @brief SetMapperID Change between Standard2D and 3D mappers. * @param id Enum mitk::BaseRenderer::StandardMapperSlot which defines the mapper. */ void SetMapperID(mitk::BaseRenderer::StandardMapperSlot id); /** * @brief AddNodeToStorage Add a node to the datastorage and perform a reinit which is necessary for rendering. * @param node The data you want to add. */ void AddNodeToStorage(mitk::DataNode::Pointer node); /** * @brief SetMapperIDToRender3D Convenience method to render in a 3D renderwindow. * @warning Does not add helper objects like the image planes to render images in 3D. */ void SetMapperIDToRender3D(); /** * @brief SetMapperIDToRender2D Convenience method to render in a 2D renderwindow. */ void SetMapperIDToRender2D(); /** * @brief SaveReferenceScreenShot Convenience method to save a reference screen shot. * @param fileName Path/to/save/the/png/file. */ void SaveReferenceScreenShot(std::string fileName); /** * @brief CompareRenderWindowAgainstReference Convenience method to compare the image rendered in the internal renderwindow against a reference screen shot. * Usage of vtkTesting::Test: vtkTesting::Test( argc, argv, vtkRenderWindow, threshold ) Set a vtkRenderWindow containing the desired scene. This is automatically rendered. vtkTesting::Test() automatically searches in argc and argv[] for a path a valid image with -V. If the test failed with the first image (foo.png) it checks if there are images of the form foo_N.png (where N=1,2,3...) and compare against them. This allows for multiple valid images. * @param argc Number of arguments. * @param argv Arguments must(!) contain the term "-V Path/To/Valid/Image.png" * @param threshold Allowed difference between two images. Default = 10.0 and was taken from VTK. * @return True if the images are equal regarding the threshold. False in all other cases. */ bool CompareRenderWindowAgainstReference(int argc, char *argv[], double threshold = 10.0); - /** @brief Returns true if the opengl context is compatible for advanced vtk effects **/ - bool IsAdvancedOpenGL(); - /** * @brief The ArgcHelperClass class is a convinience class to convert a vector * of strings to the standard c++ argv and argc arguments. This is necessary for * the vtkTesting::Test, since is requires the reference image (and other * optional parameters) via command line. */ class ArgcHelperClass { private: /** * Members for conversion. */ std::vector argv; std::vector> argvec; public: ArgcHelperClass(const std::vector &argstrings) : argv(argstrings.size() + 1), argvec(argstrings.size() + 1) { std::vector cmdArgs; cmdArgs.push_back(mitk::IOUtil::GetProgramPath()); cmdArgs.insert(cmdArgs.end(), argstrings.begin(), argstrings.end()); for (std::size_t i = 0; i < cmdArgs.size(); ++i) { argvec[i].assign(cmdArgs[i].begin(), cmdArgs[i].end()); argvec[i].push_back('\0'); argv[i] = &argvec[i][0]; } } char **GetArgv() { return &argv[0]; } int GetArgc() { return argv.size(); } }; protected: /** * @brief Initialize Internal method to initialize the renderwindow and set the datastorage. * @param width Height of renderwindow. * @param height Width of renderwindow. * @param renderingMode The rendering mode. */ void Initialize( int width, int height, AntiAliasing antiAliasing = AntiAliasing::None); - /** @brief Prints the opengl information, e.g. version, vendor and extensions, - * This function can only be called after an opengl context is active. - * It only prints the context after the vtkRenderwindow is fully initialized. - **/ - void PrintGLInfo(); - /** @brief This method tries to load the given file into a member datastorage, in order to render it. @param fileName The filename of the file to be loaded (including path). **/ void AddToStorage(const std::string &filename); /** @brief This method tries to parse the given argv for files (e.g. images) and load them into a member datastorage, in order to render it. @param argc Number of parameters. @param argv Given parameters. **/ void SetInputFileNames(int argc, char *argv[]); mitk::RenderWindow::Pointer m_RenderWindow; //<< Contains the mitkRenderWindow into which the test renders the data mitk::DataStorage::Pointer m_DataStorage; //<< Contains the mitkDataStorage which contains the data to be rendered bool m_AutomaticallyCloseRenderWindow; //<< Flag indicating whether the renderwindow should automatically close (true, // default) or stay open (false). Usefull for debugging. }; } // namespace mitk #endif diff --git a/Modules/Core/TestingHelper/src/mitkRenderingTestHelper.cpp b/Modules/Core/TestingHelper/src/mitkRenderingTestHelper.cpp index 4991a2d86e..ac0d4f036e 100644 --- a/Modules/Core/TestingHelper/src/mitkRenderingTestHelper.cpp +++ b/Modules/Core/TestingHelper/src/mitkRenderingTestHelper.cpp @@ -1,313 +1,292 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // VTK #include +#include #include #include #include #include // MITK #include #include #include #include #include #include #include #include -// include gl to read out properties -#include -#include - #if defined _MSC_VER #if _MSC_VER >= 1700 #define RESIZE_WORKAROUND #endif #endif #ifdef RESIZE_WORKAROUND #include "vtkWin32OpenGLRenderWindow.h" #endif // VTK Testing to compare the rendered image pixel-wise against a reference screen shot #include "vtkTesting.h" mitk::RenderingTestHelper::RenderingTestHelper(int width, int height, AntiAliasing antiAliasing) : m_AutomaticallyCloseRenderWindow(true) { this->Initialize(width, height, antiAliasing); } mitk::RenderingTestHelper::RenderingTestHelper( int width, int height, int argc, char *argv[], AntiAliasing antiAliasing) : m_AutomaticallyCloseRenderWindow(true) { this->Initialize(width, height, antiAliasing); this->SetInputFileNames(argc, argv); } void mitk::RenderingTestHelper::Initialize(int width, int height, AntiAliasing antiAliasing) { RenderingManager::GetInstance()->SetAntiAliasing(antiAliasing); mitk::UIDGenerator uidGen = mitk::UIDGenerator("UnnamedRenderer_", 8); m_RenderWindow = mitk::RenderWindow::New(nullptr, uidGen.GetUID().c_str()); + auto renderWindow = m_RenderWindow->GetVtkRenderWindow(); + + if (0 == renderWindow->SupportsOpenGL()) + { + auto openGLRenderWindow = dynamic_cast(renderWindow); + + auto message = nullptr != openGLRenderWindow + ? openGLRenderWindow->GetOpenGLSupportMessage() + : std::string("No details available."); + + mitkThrowException(mitk::TestNotRunException) << "OpenGL not supported: " << message; + } + m_DataStorage = mitk::StandaloneDataStorage::New(); m_RenderWindow->GetRenderer()->SetDataStorage(m_DataStorage); this->SetMapperIDToRender2D(); this->GetVtkRenderWindow()->SetSize(width, height); - if (!IsAdvancedOpenGL()) - { - mitkThrowException(mitk::TestNotRunException) << "Insufficient OpenGL version"; - } - #ifdef RESIZE_WORKAROUND HWND hWnd = static_cast(this->GetVtkRenderWindow())->GetWindowId(); RECT r; r.left = 10; r.top = 10; r.right = r.left + width; r.bottom = r.top + height; LONG style = GetWindowLong(hWnd, GWL_STYLE); AdjustWindowRect(&r, style, FALSE); MITK_INFO << "WANTED:"; MITK_INFO << r.right - r.left; MITK_INFO << r.bottom - r.top; RECT rect; if (GetWindowRect(hWnd, &rect)) { int width = rect.right - rect.left; int height = rect.bottom - rect.top; MITK_INFO << "ACTUAL:"; MITK_INFO << width; MITK_INFO << height; } SetWindowPos(hWnd, HWND_TOP, 0, 0, r.right - r.left, r.bottom - r.top, SWP_NOZORDER); GetWindowRect(hWnd, &rect); int width2 = rect.right - rect.left; int height2 = rect.bottom - rect.top; MITK_INFO << "ACTUAL2:"; MITK_INFO << width2; MITK_INFO << height2; SetWindowPos(hWnd, HWND_TOP, 0, 0, 2 * (r.right - r.left) - width2, 2 * (r.bottom - r.top) - height2, SWP_NOZORDER); #endif m_RenderWindow->GetRenderer()->Resize(width, height); - - // Prints the glinfo after creation of the vtkrenderwindow, we always want to do this for debugging. - this->PrintGLInfo(); } mitk::RenderingTestHelper::~RenderingTestHelper() { } -bool mitk::RenderingTestHelper::IsAdvancedOpenGL() -{ - const GLubyte *version = glGetString(GL_VERSION); - if (!version) - return false; - return *version >= '2'; -} - -void mitk::RenderingTestHelper::PrintGLInfo() -{ - GLint maxTextureSize; - - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); - ; - - //MITK_INFO << "OpenGL Render Context Information: \n" - // << "- GL_VENDOR: " << glGetString(GL_VENDOR) << "\n" - // << "- GL_RENDERER: " << glGetString(GL_RENDERER) << "\n" - // << "- GL_VERSION: " << glGetString(GL_VERSION) << "\n" - // << "- GL_MAX_TEXTURE_SIZE: " << maxTextureSize << "\n" - // << "- GL_EXTENSIONS: " << glGetString(GL_EXTENSIONS); -} - void mitk::RenderingTestHelper::SetMapperID(mitk::BaseRenderer::StandardMapperSlot id) { m_RenderWindow->GetRenderer()->SetMapperID(id); } void mitk::RenderingTestHelper::SetMapperIDToRender3D() { this->SetMapperID(mitk::BaseRenderer::Standard3D); mitk::RenderingManager::GetInstance()->InitializeViews( this->GetDataStorage()->ComputeBoundingGeometry3D(this->GetDataStorage()->GetAll())); } void mitk::RenderingTestHelper::SetMapperIDToRender2D() { this->SetMapperID(mitk::BaseRenderer::Standard2D); } void mitk::RenderingTestHelper::Render() { // if the datastorage is initialized and at least 1 image is loaded render it if (m_DataStorage.IsNotNull() || m_DataStorage->GetAll()->Size() >= 1) { // Prepare the VTK camera before rendering. m_RenderWindow->GetRenderer()->PrepareRender(); this->GetVtkRenderWindow()->Render(); this->GetVtkRenderWindow()->WaitForCompletion(); if (m_AutomaticallyCloseRenderWindow == false) { // Use interaction to stop the test this->GetVtkRenderWindow()->GetInteractor()->Start(); } } else { MITK_ERROR << "No images loaded in data storage!"; } } mitk::DataStorage::Pointer mitk::RenderingTestHelper::GetDataStorage() { return m_DataStorage; } void mitk::RenderingTestHelper::SetInputFileNames(int argc, char *argv[]) { // i is set 1, because 0 is the testname as string // parse parameters for (int i = 1; i < argc; ++i) { // add everything to a list but -T and -V std::string tmp = argv[i]; if ((tmp.compare("-T")) && (tmp.compare("-V"))) { this->AddToStorage(tmp); } else { break; } } } void mitk::RenderingTestHelper::SetViewDirection(mitk::SliceNavigationController::ViewDirection viewDirection) { mitk::BaseRenderer::GetInstance(m_RenderWindow->GetVtkRenderWindow()) ->GetSliceNavigationController() ->SetDefaultViewDirection(viewDirection); mitk::RenderingManager::GetInstance()->InitializeViews( m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll())); } void mitk::RenderingTestHelper::ReorientSlices(mitk::Point3D origin, mitk::Vector3D rotation) { mitk::SliceNavigationController::Pointer sliceNavigationController = mitk::BaseRenderer::GetInstance(m_RenderWindow->GetVtkRenderWindow())->GetSliceNavigationController(); sliceNavigationController->ReorientSlices(origin, rotation); } vtkRenderer *mitk::RenderingTestHelper::GetVtkRenderer() { return m_RenderWindow->GetRenderer()->GetVtkRenderer(); } void mitk::RenderingTestHelper::SetImageProperty(const char *propertyKey, mitk::BaseProperty *property) { this->m_DataStorage->GetNode(mitk::NodePredicateDataType::New("Image"))->SetProperty(propertyKey, property); } vtkRenderWindow *mitk::RenderingTestHelper::GetVtkRenderWindow() { return m_RenderWindow->GetVtkRenderWindow(); } bool mitk::RenderingTestHelper::CompareRenderWindowAgainstReference(int argc, char *argv[], double threshold) { this->Render(); // retVal meanings: (see VTK/Rendering/vtkTesting.h) // 0 = test failed // 1 = test passed // 2 = test not run // 3 = something with vtkInteraction if (vtkTesting::Test(argc, argv, this->GetVtkRenderWindow(), threshold) == 1) return true; else return false; } // method to save a screenshot of the renderwindow (e.g. create a reference screenshot) void mitk::RenderingTestHelper::SaveAsPNG(std::string fileName) { vtkSmartPointer renderer = this->GetVtkRenderer(); bool doubleBuffering(renderer->GetRenderWindow()->GetDoubleBuffer()); renderer->GetRenderWindow()->DoubleBufferOff(); vtkSmartPointer magnifier = vtkSmartPointer::New(); magnifier->SetInput(renderer); magnifier->SetMagnification(1); vtkSmartPointer fileWriter = vtkSmartPointer::New(); fileWriter->SetInputConnection(magnifier->GetOutputPort()); fileWriter->SetFileName(fileName.c_str()); fileWriter->Write(); renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering); } void mitk::RenderingTestHelper::SetAutomaticallyCloseRenderWindow(bool automaticallyCloseRenderWindow) { m_AutomaticallyCloseRenderWindow = automaticallyCloseRenderWindow; } void mitk::RenderingTestHelper::SaveReferenceScreenShot(std::string fileName) { this->SaveAsPNG(fileName); } void mitk::RenderingTestHelper::AddToStorage(const std::string &filename) { try { mitk::IOUtil::Load(filename, *m_DataStorage.GetPointer()); mitk::RenderingManager::GetInstance()->InitializeViews( m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll())); } catch ( const itk::ExceptionObject &e ) { MITK_ERROR << "Failed loading test data '" << filename << "': " << e.what(); } } void mitk::RenderingTestHelper::AddNodeToStorage(mitk::DataNode::Pointer node) { this->m_DataStorage->Add(node); mitk::RenderingManager::GetInstance()->InitializeViews( m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll())); } diff --git a/Modules/Core/test/CMakeLists.txt b/Modules/Core/test/CMakeLists.txt index 0e4dbdc277..7b3e5e46e9 100644 --- a/Modules/Core/test/CMakeLists.txt +++ b/Modules/Core/test/CMakeLists.txt @@ -1,200 +1,192 @@ # The core tests need relaxed compiler flags... # TODO fix core tests to compile without these additional no-error flags if(MSVC_VERSION) # disable deprecated warnings (they would lead to errors) mitkFunctionCheckCAndCXXCompilerFlags("/wd4996" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) else() mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=deprecated" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=deprecated-declarations" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) endif() MITK_CREATE_MODULE_TESTS() if(TARGET ${TESTDRIVER}) mitk_use_modules(TARGET ${TESTDRIVER} PACKAGES ITK|ITKThresholding+ITKTestKernel VTK|vtkTestingRendering tinyxml) mitkAddCustomModuleTest(mitkVolumeCalculatorTest_Png2D-bw mitkVolumeCalculatorTest ${MITK_DATA_DIR}/Png2D-bw.png ${MITK_DATA_DIR}/Pic2DplusT.nrrd ) mitkAddCustomModuleTest(mitkEventConfigTest_CreateObjectInDifferentWays mitkEventConfigTest ${MITK_SOURCE_DIR}/Modules/Core/test/resource/Interactions/StatemachineConfigTest.xml ) mitkAddCustomModuleTest(mitkDataStorageTest_US4DCyl mitkDataStorageTest ${MITK_DATA_DIR}/US4DCyl.nrrd ) mitkAddCustomModuleTest(mitkPointSetReaderTest mitkPointSetReaderTest ${MITK_DATA_DIR}/PointSetReaderTestData.mps ) mitkAddCustomModuleTest(mitkImageTest_4DImageData mitkImageTest ${MITK_DATA_DIR}/US4DCyl.nrrd ) mitkAddCustomModuleTest(mitkImageTest_2D+tImageData mitkImageTest ${MITK_DATA_DIR}/Pic2DplusT.nrrd ) mitkAddCustomModuleTest(mitkImageTest_3DImageData mitkImageTest ${MITK_DATA_DIR}/Pic3D.nrrd ) mitkAddCustomModuleTest(mitkImageEqualTest mitkImageEqualTest) mitkAddCustomModuleTest(mitkImageTest_brainImage mitkImageTest ${MITK_DATA_DIR}/brain.mhd ) - mitkAddCustomModuleTest(mitkImageTest_3DImageData mitkImageGeneratorTest - ${MITK_DATA_DIR}/Pic3D.nrrd - ) - mitkAddCustomModuleTest(mitkLevelWindowManagerTest mitkLevelWindowManagerTest ${MITK_DATA_DIR}/Pic3D.nrrd ) mitkAddCustomModuleTest(mitkMultiComponentImageDataComparisonFilterTest mitkMultiComponentImageDataComparisonFilterTest ${MITK_DATA_DIR}/NrrdWritingTestImage.jpg ) mitkAddCustomModuleTest(mitkImageToItkTest mitkImageToItkTest ${MITK_DATA_DIR}/Pic3D.nrrd ) mitkAddCustomModuleTest(mitkImageSliceSelectorTest mitkImageSliceSelectorTest ${MITK_DATA_DIR}/Pic2DplusT.nrrd ) mitkAddCustomModuleTest(mitkRotatedSlice4DTest mitkRotatedSlice4DTest ${MITK_DATA_DIR}/UltrasoundImages/4D_TEE_Data_MV.dcm ) - if(MITK_ENABLE_RENDERING_TESTING) ### since the rendering test's do not run in ubuntu, yet, we build them only for other systems or if the user explicitly sets the variable MITK_ENABLE_RENDERING_TESTING - mitkAddCustomModuleTest(mitkImageVtkMapper2D_rgbaImage640x480 mitkImageVtkMapper2DTest - ${MITK_DATA_DIR}/RenderingTestData/rgbaImage.png #input image to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/rgbaImage640x480REF.png #corresponding reference screenshot - ) - mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3d640x480 mitkImageVtkMapper2DTest #test for standard Pic3D axial slice - ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3d640x480REF.png #corresponding reference screenshot - ) - mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3dColorBlue640x480 mitkImageVtkMapper2DColorTest #test for color property (=blue) Pic3D sagittal slice - ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dColorBlue640x480REF.png #corresponding reference screenshot - ) - mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3dLevelWindow640x480 mitkImageVtkMapper2DLevelWindowTest #test for levelwindow property (=blood) #Pic3D sagittal slice - ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dLevelWindowBlood640x480REF.png #corresponding reference #screenshot - ) - #mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3dOpacity640x480 mitkImageVtkMapper2DOpacityTest #test for opacity (=0.5) Pic3D coronal slice - # ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage - # -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dOpacity640x480REF.png corresponding reference screenshot - #) - mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3dSwivel640x480 mitkImageVtkMapper2DSwivelTest #test for a randomly chosen Pic3D swivelled slice - ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dSwivel640x480REF.png #corresponding reference screenshot - ) - mitkAddCustomModuleTest(mitkPointSetVtkMapper2D_openMeAlone640x480 mitkPointSetVtkMapper2DTest - ${MITK_DATA_DIR}/RenderingTestData/openMeAlone.mps #input point set to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/openMeAlone640x480REF.png #corresponding reference screenshot - ) - mitkAddCustomModuleTest(mitkPointSetVtkMapper2D_Pic3DPointSetForPic3D640x480 mitkPointSetVtkMapper2DImageTest - ${MITK_DATA_DIR}/Pic3D.nrrd ${MITK_DATA_DIR}/RenderingTestData/PointSetForPic3D.mps #input point set and image to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Pic3DPointSetForPic3D640x480REF.png #corresponding reference screenshot - ) - mitkAddCustomModuleTest(mitkPointSetVtkMapper2D_openMeAloneGlyphType640x480 mitkPointSetVtkMapper2DGlyphTypeTest - ${MITK_DATA_DIR}/RenderingTestData/openMeAlone.mps #input point set to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/openMeAloneGlyphType640x480REF.png #corresponding reference screenshot - ) - mitkAddCustomModuleTest(mitkPointSetVtkMapper2D_openMeAloneTransformed640x480 mitkPointSetVtkMapper2DTransformedPointsTest - ${MITK_DATA_DIR}/RenderingTestData/openMeAlone.mps #input point set to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/openMeAloneTransformedPoints640x480REF.png #corresponding reference screenshot - ) - # Currently not working on windows because of a rendering timing issue - # see bug 18083 for details - if(NOT WIN32) + mitkAddCustomModuleTest(mitkImageVtkMapper2D_rgbaImage640x480 mitkImageVtkMapper2DTest + ${MITK_DATA_DIR}/RenderingTestData/rgbaImage.png #input image to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/rgbaImage640x480REF.png #corresponding reference screenshot + ) + mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3d640x480 mitkImageVtkMapper2DTest #test for standard Pic3D axial slice + ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3d640x480REF.png #corresponding reference screenshot + ) + mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3dColorBlue640x480 mitkImageVtkMapper2DColorTest #test for color property (=blue) Pic3D sagittal slice + ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dColorBlue640x480REF.png #corresponding reference screenshot + ) + mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3dLevelWindow640x480 mitkImageVtkMapper2DLevelWindowTest #test for levelwindow property (=blood) #Pic3D sagittal slice + ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dLevelWindowBlood640x480REF.png #corresponding reference #screenshot + ) + #mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3dOpacity640x480 mitkImageVtkMapper2DOpacityTest #test for opacity (=0.5) Pic3D coronal slice + # ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage + # -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dOpacity640x480REF.png corresponding reference screenshot + #) + mitkAddCustomModuleTest(mitkImageVtkMapper2D_pic3dSwivel640x480 mitkImageVtkMapper2DSwivelTest #test for a randomly chosen Pic3D swivelled slice + ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dSwivel640x480REF.png #corresponding reference screenshot + ) + mitkAddCustomModuleTest(mitkPointSetVtkMapper2D_openMeAlone640x480 mitkPointSetVtkMapper2DTest + ${MITK_DATA_DIR}/RenderingTestData/openMeAlone.mps #input point set to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/openMeAlone640x480REF.png #corresponding reference screenshot + ) + mitkAddCustomModuleTest(mitkPointSetVtkMapper2D_Pic3DPointSetForPic3D640x480 mitkPointSetVtkMapper2DImageTest + ${MITK_DATA_DIR}/Pic3D.nrrd ${MITK_DATA_DIR}/RenderingTestData/PointSetForPic3D.mps #input point set and image to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Pic3DPointSetForPic3D640x480REF.png #corresponding reference screenshot + ) + mitkAddCustomModuleTest(mitkPointSetVtkMapper2D_openMeAloneGlyphType640x480 mitkPointSetVtkMapper2DGlyphTypeTest + ${MITK_DATA_DIR}/RenderingTestData/openMeAlone.mps #input point set to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/openMeAloneGlyphType640x480REF.png #corresponding reference screenshot + ) + mitkAddCustomModuleTest(mitkPointSetVtkMapper2D_openMeAloneTransformed640x480 mitkPointSetVtkMapper2DTransformedPointsTest + ${MITK_DATA_DIR}/RenderingTestData/openMeAlone.mps #input point set to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/openMeAloneTransformedPoints640x480REF.png #corresponding reference screenshot + ) + # Currently not working on windows because of a rendering timing issue + # see bug 18083 for details + if(NOT WIN32) mitkAddCustomModuleTest(mitkSurfaceDepthSortingTransparency_StanfordBunnySTL640x480 mitkSurfaceDepthSortingTest ${MITK_DATA_DIR}/RenderingTestData/Stanford_bunny.stl - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Stanford_bunnySTLDepthSorting640x480REF.png - ) - endif() - -# BUG 18695 - tests deactivated, because win 32 bit continuous renders images slightly different. TODO! - #Test reslice interpolation - #note: nearest mode is already tested by swivel test - #mitkAddCustomModuleTest(ResliceInterpolationIsLinear mitkImageVtkMapper2DResliceInterpolationPropertyTest - # 1 #linear - # ${MITK_DATA_DIR}/Pic3D.nrrd - # -V - # ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dRefLinear.png #corresponding reference screenshot LINEAR - #) - - #mitkAddCustomModuleTest(ResliceInterpolationIsCubic mitkImageVtkMapper2DResliceInterpolationPropertyTest - # 3 #cubic - # ${MITK_DATA_DIR}/Pic3D.nrrd - # -V - # ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dRefCubic.png #corresponding reference screenshot CUBIC - #) - #End test reslice interpolation - - # Testing of the rendering of binary images - #mitkAddCustomModuleTest(mitkImageVtkMapper2D_binaryTestImage640x480 mitkImageVtkMapper2DTest #test for standard Pic3D axial slice - # ${MITK_DATA_DIR}/RenderingTestData/binaryImage.nrrd #input image to load in data storage - # -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/binaryImage640x480REF.png #corresponding reference screenshot - #) - #mitkAddCustomModuleTest(mitkImageVtkMapper2D_binaryTestImageWithRef640x480 mitkImageVtkMapper2DTest #test for standard Pic3D axial slice - # ${MITK_DATA_DIR}/Pic3D.nrrd ${MITK_DATA_DIR}/RenderingTestData/binaryImage.nrrd #input image to load in data storage - # -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/binaryImageWithRef640x480REF.png #corresponding reference screenshot - #) - # End of binary image tests - - mitkAddCustomModuleTest(mitkSurfaceVtkMapper3DTest_TextureProperty mitkSurfaceVtkMapper3DTest - ${MITK_DATA_DIR}/RenderingTestData/earth.jpg - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/texturedSphere640x480REF.png #corresponding reference screenshot - ) - - mitkAddCustomModuleTest(mitkImageVtkMapper2DTransferFunctionTest_Png2D-bw mitkImageVtkMapper2DTransferFunctionTest - ${MITK_DATA_DIR}/Png2D-bw.png - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Png2D-bw-TransferFunctionRGBImage640x480REF.png #corresponding reference screenshot - ) - - mitkAddCustomModuleTest(mitkImageVtkMapper2DOpacityTransferFunctionTest_Png2D-bw mitkImageVtkMapper2DOpacityTransferFunctionTest - ${MITK_DATA_DIR}/Png2D-bw.png - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Png2D-bw-OpacityTransferFunctionRGBImage640x480REF.png #corresponding reference screenshot - ) - - ############################## DISABLED TESTS - - mitkAddCustomModuleTest(mitkImageVtkMapper2DLookupTableTest_Png2D-bw mitkImageVtkMapper2DLookupTableTest - ${MITK_DATA_DIR}/Png2D-bw.png - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Png2D-bw-LookupTableRGBImage640x480REF.png #corresponding reference screenshot - ) - - #mitkAddCustomModuleTest(mitkImageTest_color2DImage mitkImageTest - # ${MITK_DATA_DIR}/NrrdWritingTestImage.jpg - #) - - #mitkAddCustomModuleTest(mitkNodeDependentPointSetInteractorTest mitkNodeDependentPointSetInteractorTest - # ${MITK_DATA_DIR}/Pic3D.pic.gz ${MITK_DATA_DIR}/BallBinary30x30x30.pic.gz - #) - - mitkAddCustomModuleTest(mitkPlaneGeometryDataMapper2DTest mitkPlaneGeometryDataMapper2DTest - ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/PlaneGeometryMapper640x480REF.png #corresponding reference screenshot - ) - - - SET_PROPERTY(TEST mitkRotatedSlice4DTest mitkImageVtkMapper2D_rgbaImage640x480 mitkImageVtkMapper2D_pic3d640x480 mitkImageVtkMapper2D_pic3dColorBlue640x480 mitkImageVtkMapper2D_pic3dLevelWindow640x480 mitkImageVtkMapper2D_pic3dSwivel640x480 mitkImageVtkMapper2DTransferFunctionTest_Png2D-bw - # mitkImageVtkMapper2D_pic3dOpacity640x480 - mitkSurfaceVtkMapper2DTest mitkSurfaceVtkMapper3DTest_TextureProperty mitkPointSetVtkMapper2D_Pic3DPointSetForPic3D640x480 mitkPointSetVtkMapper2D_openMeAlone640x480 mitkPointSetVtkMapper2D_openMeAloneGlyphType640x480 mitkPointSetVtkMapper2D_openMeAloneTransformed640x480 - mitkPlaneGeometryDataMapper2DTest - PROPERTY RUN_SERIAL TRUE) - + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Stanford_bunnySTLDepthSorting640x480REF.png) endif() + # BUG 18695 - tests deactivated, because win 32 bit continuous renders images slightly different. TODO! + #Test reslice interpolation + #note: nearest mode is already tested by swivel test + #mitkAddCustomModuleTest(ResliceInterpolationIsLinear mitkImageVtkMapper2DResliceInterpolationPropertyTest + # 1 #linear + # ${MITK_DATA_DIR}/Pic3D.nrrd + # -V + # ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dRefLinear.png #corresponding reference screenshot LINEAR + #) + + #mitkAddCustomModuleTest(ResliceInterpolationIsCubic mitkImageVtkMapper2DResliceInterpolationPropertyTest + # 3 #cubic + # ${MITK_DATA_DIR}/Pic3D.nrrd + # -V + # ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/pic3dRefCubic.png #corresponding reference screenshot CUBIC + #) + #End test reslice interpolation + + # Testing of the rendering of binary images + #mitkAddCustomModuleTest(mitkImageVtkMapper2D_binaryTestImage640x480 mitkImageVtkMapper2DTest #test for standard Pic3D axial slice + # ${MITK_DATA_DIR}/RenderingTestData/binaryImage.nrrd #input image to load in data storage + # -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/binaryImage640x480REF.png #corresponding reference screenshot + #) + #mitkAddCustomModuleTest(mitkImageVtkMapper2D_binaryTestImageWithRef640x480 mitkImageVtkMapper2DTest #test for standard Pic3D axial slice + # ${MITK_DATA_DIR}/Pic3D.nrrd ${MITK_DATA_DIR}/RenderingTestData/binaryImage.nrrd #input image to load in data storage + # -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/binaryImageWithRef640x480REF.png #corresponding reference screenshot + #) + # End of binary image tests + + mitkAddCustomModuleTest(mitkSurfaceVtkMapper3DTest_TextureProperty mitkSurfaceVtkMapper3DTest + ${MITK_DATA_DIR}/RenderingTestData/earth.jpg + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/texturedSphere640x480REF.png #corresponding reference screenshot + ) + + mitkAddCustomModuleTest(mitkImageVtkMapper2DTransferFunctionTest_Png2D-bw mitkImageVtkMapper2DTransferFunctionTest + ${MITK_DATA_DIR}/Png2D-bw.png + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Png2D-bw-TransferFunctionRGBImage640x480REF.png #corresponding reference screenshot + ) + + mitkAddCustomModuleTest(mitkImageVtkMapper2DOpacityTransferFunctionTest_Png2D-bw mitkImageVtkMapper2DOpacityTransferFunctionTest + ${MITK_DATA_DIR}/Png2D-bw.png + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Png2D-bw-OpacityTransferFunctionRGBImage640x480REF.png #corresponding reference screenshot + ) + + ############################## DISABLED TESTS + + mitkAddCustomModuleTest(mitkImageVtkMapper2DLookupTableTest_Png2D-bw mitkImageVtkMapper2DLookupTableTest + ${MITK_DATA_DIR}/Png2D-bw.png + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/Png2D-bw-LookupTableRGBImage640x480REF.png #corresponding reference screenshot + ) + + #mitkAddCustomModuleTest(mitkImageTest_color2DImage mitkImageTest + # ${MITK_DATA_DIR}/NrrdWritingTestImage.jpg + #) + + #mitkAddCustomModuleTest(mitkNodeDependentPointSetInteractorTest mitkNodeDependentPointSetInteractorTest + # ${MITK_DATA_DIR}/Pic3D.pic.gz ${MITK_DATA_DIR}/BallBinary30x30x30.pic.gz + #) + + mitkAddCustomModuleTest(mitkPlaneGeometryDataMapper2DTest mitkPlaneGeometryDataMapper2DTest + ${MITK_DATA_DIR}/Pic3D.nrrd #input image to load in data storage + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/PlaneGeometryMapper640x480REF.png #corresponding reference screenshot + ) + + + SET_PROPERTY(TEST mitkRotatedSlice4DTest mitkImageVtkMapper2D_rgbaImage640x480 mitkImageVtkMapper2D_pic3d640x480 mitkImageVtkMapper2D_pic3dColorBlue640x480 mitkImageVtkMapper2D_pic3dLevelWindow640x480 mitkImageVtkMapper2D_pic3dSwivel640x480 mitkImageVtkMapper2DTransferFunctionTest_Png2D-bw + # mitkImageVtkMapper2D_pic3dOpacity640x480 + mitkSurfaceVtkMapper2DTest mitkSurfaceVtkMapper3DTest_TextureProperty mitkPointSetVtkMapper2D_Pic3DPointSetForPic3D640x480 mitkPointSetVtkMapper2D_openMeAlone640x480 mitkPointSetVtkMapper2D_openMeAloneGlyphType640x480 mitkPointSetVtkMapper2D_openMeAloneTransformed640x480 + mitkPlaneGeometryDataMapper2DTest + PROPERTY RUN_SERIAL TRUE) + endif() # TARGET ${TESTDRIVER} diff --git a/Modules/Core/test/files.cmake b/Modules/Core/test/files.cmake index bddcd8ca8e..f98fb8a5df 100644 --- a/Modules/Core/test/files.cmake +++ b/Modules/Core/test/files.cmake @@ -1,201 +1,193 @@ # tests with no extra command line parameter set(MODULE_TESTS # IMPORTANT: If you plan to deactivate / comment out a test please write a bug number to the commented out line of code. # # Example: #mitkMyTest #this test is commented out because of bug 12345 # # It is important that the bug is open and that the test will be activated again before the bug is closed. This assures that # no test is forgotten after it was commented out. If there is no bug for your current problem, please add a new one and # mark it as critical. ################## DISABLED TESTS ################################################# #mitkAbstractTransformGeometryTest.cpp #seems as tested class mitkExternAbstractTransformGeometry doesnt exist any more #mitkStateMachineContainerTest.cpp #rewrite test, indirect since no longer exported Bug 14529 #mitkRegistrationBaseTest.cpp #tested class mitkRegistrationBase doesn't exist any more #mitkSegmentationInterpolationTest.cpp #file doesn't exist! #mitkPipelineSmartPointerCorrectnessTest.cpp #file doesn't exist! #mitkITKThreadingTest.cpp #test outdated because itk::Semaphore was removed from ITK #mitkAbstractTransformPlaneGeometryTest.cpp #mitkVtkAbstractTransformPlaneGeometry doesn't exist any more #mitkTestUtilSharedLibrary.cpp #Linker problem with this test... #mitkTextOverlay2DSymbolsRenderingTest.cpp #Implementation of the tested feature is not finished yet. Ask Christoph or see bug 15104 for details. ################# RUNNING TESTS ################################################### mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkDataNodeTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkDispatcherTest.cpp mitkEnumerationPropertyTest.cpp mitkFileReaderRegistryTest.cpp #mitkFileWriterRegistryTest.cpp mitkFloatToStringTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometry3DEqualTest.cpp mitkGeometryDataIOTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkImageCastTest.cpp - mitkImageEqualTest.cpp mitkImageDataItemTest.cpp mitkImageGeneratorTest.cpp mitkIOUtilTest.cpp mitkBaseDataTest.cpp mitkImportItkImageTest.cpp mitkGrabItkImageMemoryTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetTest.cpp mitkPointSetEqualTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetOnEmptyTest.cpp mitkPointSetLocaleTest.cpp mitkPointSetWriterTest.cpp - mitkPointSetReaderTest.cpp mitkPointSetPointOperationsTest.cpp mitkProgressBarTest.cpp mitkPropertyTest.cpp mitkPropertyListTest.cpp mitkPropertyPersistenceTest.cpp mitkPropertyPersistenceInfoTest.cpp mitkPropertyRelationRuleBaseTest.cpp mitkPropertyRelationsTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkSurfaceTest.cpp mitkSurfaceEqualTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeGeometryTest.cpp mitkProportionalTimeGeometryTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp mitkStepperTest.cpp mitkRenderingManagerTest.cpp mitkCompositePixelValueToStringTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkNodePredicateDataPropertyTest.cpp mitkNodePredicateFunctionTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp mitkExceptionTest.cpp mitkExtractSliceFilterTest.cpp mitkLogTest.cpp mitkImageDimensionConverterTest.cpp mitkLoggingAdapterTest.cpp mitkUIDGeneratorTest.cpp mitkPlanePositionManagerTest.cpp mitkAffineTransformBaseTest.cpp mitkPropertyAliasesTest.cpp mitkPropertyDescriptionsTest.cpp mitkPropertyExtensionsTest.cpp mitkPropertyFiltersTest.cpp mitkPropertyKeyPathTest.cpp mitkTinyXMLTest.cpp mitkRawImageFileReaderTest.cpp mitkInteractionEventTest.cpp mitkLookupTableTest.cpp mitkSTLFileReaderTest.cpp mitkPointTypeConversionTest.cpp mitkVectorTypeConversionTest.cpp mitkMatrixTypeConversionTest.cpp mitkArrayTypeConversionTest.cpp mitkSurfaceToImageFilterTest.cpp mitkBaseGeometryTest.cpp mitkImageToSurfaceFilterTest.cpp mitkEqualTest.cpp mitkLineTest.cpp mitkArbitraryTimeGeometryTest.cpp mitkItkImageIOTest.cpp - mitkRotatedSlice4DTest.cpp mitkLevelWindowManagerCppUnitTest.cpp mitkVectorPropertyTest.cpp mitkTemporoSpatialStringPropertyTest.cpp mitkPropertyNameHelperTest.cpp mitkNodePredicateGeometryTest.cpp mitkPreferenceListReaderOptionsFunctorTest.cpp mitkGenericIDRelationRuleTest.cpp mitkSourceImageRelationRuleTest.cpp -) - -if(MITK_ENABLE_RENDERING_TESTING) -set(MODULE_TESTS - ${MODULE_TESTS} - mitkPlaneGeometryDataMapper2DTest.cpp mitkPointSetDataInteractorTest.cpp #since mitkInteractionTestHelper is currently creating a vtkRenderWindow mitkSurfaceVtkMapper2DTest.cpp #new rendering test in CppUnit style mitkSurfaceVtkMapper2D3DTest.cpp # comparisons/consistency 2D/3D ) -endif() - - # test with image filename as an extra command line parameter set(MODULE_IMAGE_TESTS mitkImageTimeSelectorTest.cpp #only runs on images mitkImageAccessorTest.cpp #only runs on images ) set(MODULE_SURFACE_TESTS mitkSurfaceVtkWriterTest.cpp #only runs on surfaces ) # list of images for which the tests are run set(MODULE_TESTIMAGE US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd Png2D-bw.png ) set(MODULE_TESTSURFACE binary.stl ball.stl ) set(MODULE_CUSTOM_TESTS mitkDataStorageTest.cpp mitkDataNodeTest.cpp mitkEventConfigTest.cpp mitkPointSetLocaleTest.cpp mitkImageTest.cpp mitkImageVtkMapper2DTest.cpp mitkImageVtkMapper2DLevelWindowTest.cpp mitkImageVtkMapper2DOpacityTest.cpp mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp mitkImageVtkMapper2DColorTest.cpp mitkImageVtkMapper2DSwivelTest.cpp mitkImageVtkMapper2DTransferFunctionTest.cpp mitkImageVtkMapper2DOpacityTransferFunctionTest.cpp mitkImageVtkMapper2DLookupTableTest.cpp mitkSurfaceVtkMapper3DTest.cpp mitkVolumeCalculatorTest.cpp mitkLevelWindowManagerTest.cpp mitkPointSetVtkMapper2DTest.cpp mitkPointSetVtkMapper2DImageTest.cpp mitkPointSetVtkMapper2DGlyphTypeTest.cpp mitkPointSetVtkMapper2DTransformedPointsTest.cpp mitkVTKRenderWindowSizeTest.cpp mitkMultiComponentImageDataComparisonFilterTest.cpp mitkImageToItkTest.cpp mitkImageSliceSelectorTest.cpp + mitkPointSetReaderTest.cpp + mitkImageEqualTest.cpp + mitkRotatedSlice4DTest.cpp + mitkPlaneGeometryDataMapper2DTest.cpp ) # Currently not working on windows because of a rendering timing issue # see bug 18083 for details if(NOT WIN32) set(MODULE_CUSTOM_TESTS ${MODULE_CUSTOM_TESTS} mitkSurfaceDepthSortingTest.cpp) endif() set(RESOURCE_FILES Interactions/AddAndRemovePoints.xml Interactions/globalConfig.xml Interactions/StatemachineTest.xml Interactions/StatemachineConfigTest.xml ) diff --git a/Modules/Core/test/mitkBaseDataTest.cpp b/Modules/Core/test/mitkBaseDataTest.cpp index 0e7be67417..16a242f275 100644 --- a/Modules/Core/test/mitkBaseDataTest.cpp +++ b/Modules/Core/test/mitkBaseDataTest.cpp @@ -1,279 +1,278 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Testing #include "mitkTestFixture.h" #include "mitkTestingMacros.h" // std includes #include // MITK includes #include "mitkBaseDataTestImplementation.h" #include "mitkStringProperty.h" #include #include -// itksys #include "itkImage.h" // VTK includes #include class mitkBaseDataTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkBaseDataTestSuite); MITK_TEST(CreateBaseData_Success); MITK_TEST(InitializationOfBaseData_Success); MITK_TEST(CreateCloneBaseData_Success); MITK_TEST(InitializationOfCloneBaseData_Success); MITK_TEST(GetAndSetTimeGeometry_Success); MITK_TEST(ResetTimeGeometry_Success); MITK_TEST(ReinitOfTimeGeometry_Success); MITK_TEST(GetGeometryForSingleTimeGeometries_Failure); MITK_TEST(TestingExpand_Success); MITK_TEST(TestingGetUpdateGeometry_Success); MITK_TEST(GetOriginOfBaseData_Success); MITK_TEST(GetOriginOfCloneBaseData); MITK_TEST(ClearATimeStep); MITK_TEST(BaseDataSetAndGetProperty_Success); MITK_TEST(CloneBaseDataSetAndGetProperty_Success); MITK_TEST(BasePropertyListIsSet_Success); MITK_TEST(BasePorpertyIsSetInPropertyList_Success); MITK_TEST(UpdateOutputInformationOfBaseData_Failure); MITK_TEST(CopyingInformationOfBaseData_Failure); CPPUNIT_TEST_SUITE_END(); private: mitk::BaseDataTestImplementation::Pointer m_BaseDataImpl; mitk::BaseDataTestImplementation::Pointer m_CloneBaseData; mitk::TimeGeometry *m_Geo; mitk::ProportionalTimeGeometry::Pointer m_Geo2; mitk::Geometry3D::Pointer m_Geometry3D; mitk::BaseGeometry::Pointer m_Geo3; mitk::ScalarType m_X[3]; mitk::PropertyList::Pointer m_PropertyList; public: void setUp() override { m_BaseDataImpl = mitk::BaseDataTestImplementation::New(); m_CloneBaseData = m_BaseDataImpl->Clone(); m_Geo = nullptr; m_Geo2 = mitk::ProportionalTimeGeometry::New(); m_Geometry3D = mitk::Geometry3D::New(); m_Geo3 = dynamic_cast(m_Geometry3D.GetPointer()); m_X[0] = 2; m_X[1] = 4; m_X[2] = 6; m_PropertyList = mitk::PropertyList::New(); } void tearDown() override { m_BaseDataImpl = nullptr; m_CloneBaseData = nullptr; m_Geo = nullptr; m_Geo2 = nullptr; m_Geometry3D = nullptr; m_Geo3 = nullptr; m_X[0] = 0; m_X[1] = 0; m_X[2] = 0; m_PropertyList = nullptr; } void CreateBaseData_Success() { // Create a BaseData implementation MITK_INFO << "Creating a base data instance..."; CPPUNIT_ASSERT_MESSAGE("Testing instantiation", m_BaseDataImpl.IsNotNull()); } void InitializationOfBaseData_Success() { CPPUNIT_ASSERT_MESSAGE("BaseDataTestImplementation is initialized", m_BaseDataImpl->IsInitialized()); CPPUNIT_ASSERT_MESSAGE("BaseDataTestImplementation is initialized and empty", m_BaseDataImpl->IsEmpty()); } void CreateCloneBaseData_Success() { // Create CloneBaseData implementation MITK_INFO << "Creating a clone base data instance..."; CPPUNIT_ASSERT_MESSAGE("Testing instantiation of base data clone", m_CloneBaseData.IsNotNull()); } void InitializationOfCloneBaseData_Success() { CPPUNIT_ASSERT_MESSAGE("Clone of BaseDataTestImplementation is initialized", m_CloneBaseData->IsInitialized()); CPPUNIT_ASSERT_MESSAGE("Clone of BaseDataTestImplementation is initialized and empty", m_CloneBaseData->IsEmpty()); } void GetAndSetTimeGeometry_Success() { // test method GetTimeGeometry() MITK_INFO << "Testing setter and getter for geometries..."; CPPUNIT_ASSERT_MESSAGE("Testing creation of TimeGeometry", m_BaseDataImpl->GetTimeGeometry()); } void ResetTimeGeometry_Success() { m_BaseDataImpl->SetTimeGeometry(m_Geo); CPPUNIT_ASSERT_MESSAGE("Reset Geometry", m_BaseDataImpl->GetTimeGeometry() == nullptr); } void ReinitOfTimeGeometry_Success() { m_BaseDataImpl->SetTimeGeometry(m_Geo2); m_Geo2->Initialize(2); CPPUNIT_ASSERT_MESSAGE("Correct Reinit of TimeGeometry", m_BaseDataImpl->GetTimeGeometry() == m_Geo2.GetPointer()); } void GetGeometryForSingleTimeGeometries_Failure() { // test method GetGeometry(int timeStep) CPPUNIT_ASSERT_MESSAGE("Testing Creation of single TimeGeometries", m_BaseDataImpl->GetGeometry(1) == nullptr); } void TestingExpand_Success() { // test method Expand(unsigned int timeSteps) m_BaseDataImpl->Expand(5); CPPUNIT_ASSERT_MESSAGE("Expand the geometry to further time slices!", m_BaseDataImpl->GetTimeSteps() == 5); } void TestingGetUpdateGeometry_Success() { // test method GetUpdatedGeometry(int timeStep); m_BaseDataImpl->Expand(5); mitk::ProportionalTimeGeometry::Pointer timeGeometry = dynamic_cast(m_BaseDataImpl->GetTimeGeometry()); if (timeGeometry.IsNotNull()) { timeGeometry->SetTimeStepGeometry(m_Geo3, 1); } CPPUNIT_ASSERT_MESSAGE("Set Geometry for time step 1", m_BaseDataImpl->GetUpdatedGeometry(1) == m_Geo3); CPPUNIT_ASSERT_MESSAGE("Check if modified time is set", m_BaseDataImpl->GetMTime() != 0); } void GetOriginOfBaseData_Success() { m_BaseDataImpl->Expand(5); m_BaseDataImpl->SetClonedGeometry(m_Geo3, 1); mitk::Point3D p3d(m_X); m_BaseDataImpl->SetOrigin(p3d); m_Geo3->SetOrigin(p3d); CPPUNIT_ASSERT_MESSAGE("Testing Origin set", m_BaseDataImpl->GetGeometry(1)->GetOrigin() == m_Geo3->GetOrigin()); } void GetOriginOfCloneBaseData() { m_BaseDataImpl->Expand(5); m_BaseDataImpl->SetClonedGeometry(m_Geo3, 1); mitk::Point3D p3d(m_X); m_BaseDataImpl->SetOrigin(p3d); m_Geo3->SetOrigin(p3d); m_CloneBaseData = m_BaseDataImpl->Clone(); CPPUNIT_ASSERT_MESSAGE("Testing origin set in clone!", m_CloneBaseData->GetGeometry(1)->GetOrigin() == m_Geo3->GetOrigin()); } void ClearATimeStep() { CPPUNIT_ASSERT_MESSAGE("Is not empty before clear()!", !m_BaseDataImpl->IsEmptyTimeStep(1)); m_BaseDataImpl->Clear(); CPPUNIT_ASSERT_MESSAGE("...but afterwards!", m_BaseDataImpl->IsEmptyTimeStep(1)); } void BaseDataSetAndGetProperty_Success() { // test method Set-/GetProperty() m_BaseDataImpl->SetProperty("property38", mitk::StringProperty::New("testproperty")); CPPUNIT_ASSERT_MESSAGE("Check if base property is set correctly!", m_BaseDataImpl->GetProperty("property38")->GetValueAsString() == "testproperty"); } void CloneBaseDataSetAndGetProperty_Success() { m_BaseDataImpl->SetProperty("property38", mitk::StringProperty::New("testproperty")); m_CloneBaseData = m_BaseDataImpl->Clone(); CPPUNIT_ASSERT_MESSAGE("Testing origin set in clone!", m_CloneBaseData->GetProperty("property38")->GetValueAsString() == "testproperty"); } void BasePropertyListIsSet_Success() { // test method Set-/GetPropertyList m_PropertyList->SetFloatProperty("floatProperty1", 123.45); m_PropertyList->SetBoolProperty("visibility", true); m_PropertyList->SetStringProperty("nameXY", "propertyName"); m_BaseDataImpl->SetPropertyList(m_PropertyList); CPPUNIT_ASSERT_MESSAGE("Check if base property list is set correctly!", m_BaseDataImpl->GetPropertyList() == m_PropertyList); } void BasePorpertyIsSetInPropertyList_Success() { m_PropertyList->SetFloatProperty("floatProperty1", 123.45); m_PropertyList->SetBoolProperty("visibility", true); m_PropertyList->SetStringProperty("nameXY", "propertyName"); m_BaseDataImpl->SetPropertyList(m_PropertyList); bool value = false; CPPUNIT_ASSERT_MESSAGE("Check if base property is set correctly in the property list!", m_BaseDataImpl->GetPropertyList()->GetBoolProperty("visibility", value) == true); } void UpdateOutputInformationOfBaseData_Failure() { // test method UpdateOutputInformation() m_BaseDataImpl->UpdateOutputInformation(); m_Geo2->Initialize(2); m_Geo2.GetPointer(); CPPUNIT_ASSERT_MESSAGE("TimeGeometry update!", m_BaseDataImpl->GetUpdatedTimeGeometry() != m_Geo2); } void CopyingInformationOfBaseData_Failure() { // Test method CopyInformation() mitk::BaseDataTestImplementation::Pointer newBaseData = mitk::BaseDataTestImplementation::New(); newBaseData->CopyInformation(m_BaseDataImpl); CPPUNIT_ASSERT_MESSAGE("Check copying of Basedata Data Object!", newBaseData->GetTimeGeometry()->CountTimeSteps() != 5); } }; MITK_TEST_SUITE_REGISTRATION(mitkBaseData) diff --git a/Modules/Core/test/mitkDispatcherTest.cpp b/Modules/Core/test/mitkDispatcherTest.cpp index 87169dd319..3b622050d5 100644 --- a/Modules/Core/test/mitkDispatcherTest.cpp +++ b/Modules/Core/test/mitkDispatcherTest.cpp @@ -1,119 +1,203 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "itkLightObject.h" +// Testing +#include "mitkTestFixture.h" +#include "mitkTestingMacros.h" +// MITK includes +#include #include "mitkBaseRenderer.h" #include "mitkDataInteractor.h" #include "mitkDataNode.h" #include "mitkDispatcher.h" #include "mitkStandaloneDataStorage.h" -#include "mitkTestingMacros.h" #include "mitkVtkPropRenderer.h" +// ITK includes +#include "itkLightObject.h" -int mitkDispatcherTest(int /*argc*/, char * /*argv*/ []) +class mitkDispatcherTestSuite : public mitk::TestFixture { - MITK_TEST_BEGIN("Dispatcher") + CPPUNIT_TEST_SUITE(mitkDispatcherTestSuite); + MITK_TEST(DispatcherExists_Success); + MITK_TEST(AddInteractorConnectedToDataStorage_IncreaseNumberOfInteractors); + MITK_TEST(AddDataNodeToInteractor_NoIncreasedNumberOfInteractors); + MITK_TEST(AddInteractorNotConnectedToDataStorage_NoRegisteredInteractor); + MITK_TEST(ConnectInteractorToDataStorage_ReplaceInteractorEntry); + MITK_TEST(NewDataNodeAndInteractor_IncreasedNumberOfInteractors); + MITK_TEST(InteractorsPointToSameDataNode_DecreasedNumberOfInteractors); + MITK_TEST(SetDataNodeToNullptr_RemoveInteractor); + MITK_TEST(RemoveDataNode_RemoveInteractor); + MITK_TEST(GetReferenceCountDataNode_Success); + MITK_TEST(GetReferenceCountInteractors_Success); + CPPUNIT_TEST_SUITE_END(); + +private: + + vtkRenderWindow *m_RenWin; + mitk::VtkPropRenderer::Pointer m_Renderer; + + mitk::StandaloneDataStorage::Pointer m_Ds; + mitk::DataNode::Pointer m_Dn; + + mitk::DataNode::Pointer m_Dn2; + mitk::DataInteractor::Pointer m_Ei; + mitk::DataInteractor::Pointer m_Ei2; +public: /* - * Tests the process of creating Interactors and assigning DataNodes to them. - * Test checks if these Interactors are added to the Dispatcher under different conditions, - * and in different call order. - */ - - // Here BindDispatcherInteractor and Dispatcher should be created automatically - vtkRenderWindow *renWin = vtkRenderWindow::New(); - mitk::VtkPropRenderer::Pointer renderer = - mitk::VtkPropRenderer::New("ContourRenderer", renWin); - - mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); - mitk::DataNode::Pointer dn; - - dn = mitk::DataNode::New(); - mitk::DataNode::Pointer dn2 = mitk::DataNode::New(); - mitk::DataInteractor::Pointer ei = mitk::DataInteractor::New(); - mitk::DataInteractor::Pointer ei2 = mitk::DataInteractor::New(); - - MITK_TEST_CONDITION_REQUIRED(renderer->GetDispatcher()->GetNumberOfInteractors() == 0, - "01 Check Existence of Dispatcher."); - - ei->SetDataNode(dn); - renderer->SetDataStorage(ds); - ds->Add(dn); - - int num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 1, "02 Number of registered Interactors " << num << " , expected 1"); - - // This _must not_ result in additionally registered interactors. - ei->SetDataNode(dn); - ei->SetDataNode(dn); - - num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 1, "03 Number of registered Interactors " << num << " , expected 1"); - - // Switching the DataNode of an Interactor also must not result in extra registered Interactors in Dispatcher - // since dn2 is not connected to DataStorage - // ei will be dropped from dispatcher - ei->SetDataNode(dn2); - - num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 0, "04 Number of registered Interactors " << num << " , expected 0"); - - // DataNode Added to DataStorage, now Interactor entry in Dispatcher should be replaced, - // hence we restore Interactor in the Dispatcher - ds->Add(dn2); - - num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 1, "05 Number of registered Interactors " << num << " , expected 1"); - - // New DataNode and new interactor, this should result in additional Interactor in the Dispatcher. - - ei2->SetDataNode(dn); - - num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 2, "06 Number of registered Interactors " << num << " , expected 2"); - - // Here ei and ei2 point to the same dn2; dn2 now only points to ei2, so ei is abandoned, - // therefore ei1 is expected to be removed - - ei2->SetDataNode(dn2); - num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 1, "07 Number of registered Interactors " << num << " , expected 1"); - - // Setting DataNode in Interactor to nullptr, should remove Interactor from Dispatcher - ei2->SetDataNode(nullptr); - num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 0, "08 Number of registered Interactors " << num << " , expected 0"); - - // Add DN again check if it is registered - - ei2->SetDataNode(dn); - - num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 1, "09 Number of registered Interactors " << num << " , expected 1"); - - // If DN is removed Interactors should be too - ds->Remove(dn); - num = renderer->GetDispatcher()->GetNumberOfInteractors(); - MITK_TEST_CONDITION_REQUIRED(num == 0, "10 Number of registered Interactors " << num << " , expected 0"); - - // after DN is removed from DS its reference count must be back to one - - MITK_TEST_CONDITION_REQUIRED(dn->GetReferenceCount() == 1, - "10 Number of references of DataNode " << num << " , expected 1"); - - MITK_TEST_CONDITION_REQUIRED(ei->GetReferenceCount() == 1, - "11 Number of references of Interactors " << num << " , expected 1"); - - renWin->Delete(); - // always end with this! - MITK_TEST_END() -} + * Tests the process of creating Interactors and assigning DataNodes to them. + * Test checks if these Interactors are added to the Dispatcher under different conditions, + * and in different call order. + */ + + void setUp() + { + // Here BindDispatcherInteractor and Dispatcher should be created automatically + m_RenWin = vtkRenderWindow::New(); + m_Renderer = mitk::VtkPropRenderer::New("ContourRenderer", m_RenWin); + m_Ds = mitk::StandaloneDataStorage::New(); + m_Dn = mitk::DataNode::New(); + m_Dn2 = mitk::DataNode::New(); + m_Ei = mitk::DataInteractor::New(); + m_Ei2 = mitk::DataInteractor::New(); + m_Renderer->SetDataStorage(m_Ds); + } + + void tearDown() + { + m_RenWin->Delete(); + m_Renderer = nullptr; + m_Ds = nullptr; + m_Dn = nullptr; + m_Dn2 = nullptr; + m_Ei = nullptr; + m_Ei2 = nullptr; + } + + void DispatcherExists_Success() + { + CPPUNIT_ASSERT_MESSAGE("01 Check Existence of Dispatcher.", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 0); + } + + void AddInteractorConnectedToDataStorage_IncreaseNumberOfInteractors() + { + m_Ei->SetDataNode(m_Dn); + m_Ds->Add(m_Dn); + + CPPUNIT_ASSERT_MESSAGE("02 Expected number of registered Interactors is 1", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 1); + } + + void AddDataNodeToInteractor_NoIncreasedNumberOfInteractors() + { + m_Ei->SetDataNode(m_Dn); + m_Renderer->SetDataStorage(m_Ds); + m_Ds->Add(m_Dn); + // This _must not_ result in additionally registered interactors. + m_Ei->SetDataNode(m_Dn); + CPPUNIT_ASSERT_MESSAGE("03 Expected number of registered Interactors is 1", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 1); + } + + void AddInteractorNotConnectedToDataStorage_NoRegisteredInteractor() + { + // Switching the DataNode of an Interactor also must not result in extra registered Interactors in Dispatcher + // since dn2 is not connected to DataStorage + m_Ei->SetDataNode(m_Dn2); + + CPPUNIT_ASSERT_MESSAGE("04 Expected number of registered Interactors is 0", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 0); + } + + void ConnectInteractorToDataStorage_ReplaceInteractorEntry() + { + m_Ei->SetDataNode(m_Dn2); + // DataNode Added to DataStorage, now Interactor entry in Dispatcher should be replaced, + // hence we restore Interactor in the Dispatcher + m_Ds->Add(m_Dn2); + + CPPUNIT_ASSERT_MESSAGE("05 Expected number of registered Interactors is 1", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 1); + } + + void NewDataNodeAndInteractor_IncreasedNumberOfInteractors() + { + m_Ei->SetDataNode(m_Dn2); + m_Ds->Add(m_Dn2); + m_Ds->Add(m_Dn); + // New DataNode and new interactor, this should result in additional Interactor in the Dispatcher. + m_Ei2->SetDataNode(m_Dn); + + CPPUNIT_ASSERT_MESSAGE("06 Exprected number of registered Interactors is 2", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 2); + } + + void InteractorsPointToSameDataNode_DecreasedNumberOfInteractors() + { + m_Ds->Add(m_Dn2); + m_Ds->Add(m_Dn); + m_Ei->SetDataNode(m_Dn2); + m_Ei2->SetDataNode(m_Dn); + // Here ei and ei2 point to the same dn2; dn2 now only points to ei2, so ei is abandoned, + // therefore ei1 is expected to be removed + + m_Ei2->SetDataNode(m_Dn2); + CPPUNIT_ASSERT_MESSAGE("07 Expected number of registered Interactors is 1", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 1); + } + + void SetDataNodeToNullptr_RemoveInteractor() + { + m_Ds->Add(m_Dn2); + m_Ei2->SetDataNode(m_Dn2); + // Setting DataNode in Interactor to nullptr, should remove Interactor from Dispatcher + m_Ei2->SetDataNode(nullptr); + CPPUNIT_ASSERT_MESSAGE("08 Expected number of registered Interactors is 0", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 0); + } + + void RemoveDataNode_RemoveInteractor() + { + // Add DN again check if it is registered + m_Ds->Add(m_Dn); + m_Ei2->SetDataNode(m_Dn); + + CPPUNIT_ASSERT_MESSAGE("09 Expected number of registered Interactors is 1", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 1); + + // If DN is removed Interactors should be too + m_Ds->Remove(m_Dn); + CPPUNIT_ASSERT_MESSAGE("10 ExpectedNumber of registered Interactors is 0", + m_Renderer->GetDispatcher()->GetNumberOfInteractors() == 0); + } + + void GetReferenceCountDataNode_Success() + { + m_Ds->Add(m_Dn); + m_Ei2->SetDataNode(m_Dn); + m_Ds->Remove(m_Dn); + // after DN is removed from DS its reference count must be back to one + CPPUNIT_ASSERT_MESSAGE("11 Expected number of references of DataNode is 1", + m_Dn->GetReferenceCount() == 1); + } + + void GetReferenceCountInteractors_Success() + { + m_Ei->SetDataNode(m_Dn2); + m_Ds->Add(m_Dn2); + m_Ei2->SetDataNode(m_Dn2); + CPPUNIT_ASSERT_MESSAGE("12 Expected number of references of Interactors is 1", + m_Ei->GetReferenceCount() == 1); + } +}; +MITK_TEST_SUITE_REGISTRATION(mitkDispatcher) diff --git a/Modules/Core/test/mitkImageGeneratorTest.cpp b/Modules/Core/test/mitkImageGeneratorTest.cpp index aeaed85d9a..8dfd22dea4 100644 --- a/Modules/Core/test/mitkImageGeneratorTest.cpp +++ b/Modules/Core/test/mitkImageGeneratorTest.cpp @@ -1,126 +1,327 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ +// Testing +#include "mitkTestFixture.h" +#include +// MITK includes +#include #include "mitkImage.h" #include "mitkImageGenerator.h" #include "mitkImageReadAccessor.h" #include "mitkImageStatisticsHolder.h" -#include -int mitkImageGeneratorTest(int /*argc*/, char * /*argv*/ []) +class mitkImageGeneratorTestSuite : public mitk::TestFixture { - MITK_TEST_BEGIN("ImageGeneratorTest"); + CPPUNIT_TEST_SUITE(mitkImageGeneratorTestSuite); + MITK_TEST(SetSpacingX2D_Success); + MITK_TEST(SetDefaultSpacingX2D_Success); + MITK_TEST(SetSpacingX3D_Success); + MITK_TEST(SetSpacingY2D_Success); + MITK_TEST(SetDefaultSpacingY2D_Success); + MITK_TEST(SetSpacingY3D_Success); + MITK_TEST(SetSpacingZ2D_Success); + MITK_TEST(SetDefaultSpacingZ2D_Success); + MITK_TEST(SetSpacingZ3D_Success); + MITK_TEST(SetDimension2D_Success); + MITK_TEST(SetDimension3D_Success); + MITK_TEST(SetDimension4D_Success); + MITK_TEST(SetDimensionX2D_Success); + MITK_TEST(SetDimensionY2D_Success); + MITK_TEST(SetDimensionZ3D_Success); + MITK_TEST(SetDimensionT4D_Success); + MITK_TEST(SetDimensions3Dc_Success); + MITK_TEST(SetDataTypeFloat2D_Success); + MITK_TEST(SetDataTypeUChar2D_Success); + MITK_TEST(SetDataTypeInt3D_Success); + MITK_TEST(SetDataTypeDouble3D_Success); + MITK_TEST(SetDataTypeFloat4D_Success); + MITK_TEST(SetDataTypeUChar4D_Success); + MITK_TEST(SetDataTypeUInt3D_Success); + MITK_TEST(SetPixelTypeFloat2D_Success); + MITK_TEST(SetPixelTypeUChar2D_Success); + MITK_TEST(SetPixelTypeInt3D_Success); + MITK_TEST(SetPixelTypeDouble3D_Success); + MITK_TEST(SetPixelTypeFloat4D_Success); + MITK_TEST(SetPixelTypeUChar4D_Success); + MITK_TEST(SetPixelTypeUInt3D_Success); + MITK_TEST(MaxValueHolds_Success); + MITK_TEST(MinValueHolds_Success); + MITK_TEST(DefaultMaxValueHolds_Success); + MITK_TEST(DefaultMinValueHolds_Success); + MITK_TEST(SetGradientImageValues_Success); + CPPUNIT_TEST_SUITE_END(); +private: // create some images with arbitrary parameters (corner cases) - mitk::Image::Pointer image2Da = - mitk::ImageGenerator::GenerateRandomImage(120, 205, 0, 0, 0.1, 0.2, 0.3, 577, 23); - mitk::Image::Pointer image2Db = mitk::ImageGenerator::GenerateRandomImage(1, 1, 0, 0); - mitk::Image::Pointer image3Da = mitk::ImageGenerator::GenerateRandomImage(512, 205, 1, 0); - mitk::Image::Pointer image3Db = mitk::ImageGenerator::GenerateRandomImage(512, 532, 112, 0); - mitk::Image::Pointer image4Da = mitk::ImageGenerator::GenerateRandomImage(120, 205, 78, 1); - mitk::Image::Pointer image4Db = mitk::ImageGenerator::GenerateRandomImage(550, 33, 78, 150); - - mitk::Image::Pointer image3Dc = mitk::ImageGenerator::GenerateGradientImage(1, 2, 3, 4, 5, 6); - - MITK_TEST_CONDITION_REQUIRED(fabs(image2Da->GetGeometry()->GetSpacing()[0] - 0.1) < 0.0001, - "Testing if spacing x is set correctly."); - MITK_TEST_CONDITION_REQUIRED(fabs(image2Da->GetGeometry()->GetSpacing()[1] - 0.2) < 0.0001, - "Testing if spacing y is set correctly."); - MITK_TEST_CONDITION_REQUIRED(fabs(image2Da->GetGeometry()->GetSpacing()[2] - 0.3) < 0.0001, - "Testing if spacing z is set correctly."); - - MITK_TEST_CONDITION_REQUIRED(fabs(image2Db->GetGeometry()->GetSpacing()[0] - 1.0) < 0.0001, - "Testing if default spacing x is set correctly."); - MITK_TEST_CONDITION_REQUIRED(fabs(image2Db->GetGeometry()->GetSpacing()[1] - 1.0) < 0.0001, - "Testing if default spacing y is set correctly."); - MITK_TEST_CONDITION_REQUIRED(fabs(image2Db->GetGeometry()->GetSpacing()[2] - 1.0) < 0.0001, - "Testing if default spacing z is set correctly."); - - MITK_TEST_CONDITION_REQUIRED(fabs(image3Dc->GetGeometry()->GetSpacing()[0] - 4) < 0.0001, - "Testing if spacing x is set correctly."); - MITK_TEST_CONDITION_REQUIRED(fabs(image3Dc->GetGeometry()->GetSpacing()[1] - 5) < 0.0001, - "Testing if spacing y is set correctly."); - MITK_TEST_CONDITION_REQUIRED(fabs(image3Dc->GetGeometry()->GetSpacing()[2] - 6) < 0.0001, - "Testing if spacing z is set correctly."); - - MITK_TEST_CONDITION_REQUIRED(image2Da->GetDimension() == 2, "Testing if the dimension is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image2Db->GetDimension() == 2, "Testing if the dimension is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Da->GetDimension() == 2, "Testing if the dimension is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Db->GetDimension() == 3, "Testing if the dimension is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image4Da->GetDimension() == 3, "Testing if the dimension is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image4Db->GetDimension() == 4, "Testing if the dimension is set correctly."); - - MITK_TEST_CONDITION_REQUIRED(image2Da->GetDimension(0) == 120, "Testing if the dimensions are set correctly."); - MITK_TEST_CONDITION_REQUIRED(image2Db->GetDimension(1) == 1, "Testing if the dimensions are set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Da->GetDimension(2) == 1, "Testing if the dimensions are set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Db->GetDimension(2) == 112, "Testing if the dimensions are set correctly."); - MITK_TEST_CONDITION_REQUIRED(image4Da->GetDimension(3) == 1, "Testing if the dimensions are set correctly."); - MITK_TEST_CONDITION_REQUIRED(image4Db->GetDimension(3) == 150, "Testing if the dimensions are set correctly."); - - MITK_TEST_CONDITION_REQUIRED(image3Dc->GetDimension(0) == 1, "Testing if image3Dc dimension x is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Dc->GetDimension(1) == 2, "Testing if image3Dc dimension y is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Dc->GetDimension(2) == 3, "Testing if image3Dc dimension z is set correctly."); - - itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; - - MITK_TEST_CONDITION_REQUIRED(image2Da->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT, - "Testing if the data type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image2Da->GetPixelType().GetPixelType() == scalarType, - "Testing if the pixel type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image2Db->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR, - "Testing if the data type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image2Db->GetPixelType().GetPixelType() == scalarType, - "Testing if the data type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Da->GetPixelType().GetComponentType() == itk::ImageIOBase::INT, - "Testing if the data type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Da->GetPixelType().GetPixelType() == scalarType, - "Testing if the pixel type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Db->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE, - "Testing if the data type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Db->GetPixelType().GetPixelType() == scalarType, - "Testing if the pixel type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image4Da->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT, - "Testing if the data type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image4Da->GetPixelType().GetPixelType() == scalarType, - "Testing if the pixel type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image4Db->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR, - "Testing if the data type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image4Db->GetPixelType().GetPixelType() == scalarType, - "Testing if the pixel type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Dc->GetPixelType().GetComponentType() == itk::ImageIOBase::UINT, - "Testing if the data type is set correctly."); - MITK_TEST_CONDITION_REQUIRED(image3Dc->GetPixelType().GetPixelType() == scalarType, - "Testing if the pixel type is set correctly."); - - MITK_TEST_CONDITION_REQUIRED(image2Da->GetStatistics()->GetScalarValueMax() <= 577, "Testing if max value holds"); - MITK_TEST_CONDITION_REQUIRED(image2Da->GetStatistics()->GetScalarValueMin() >= 23, "Testing if min value holds"); - - MITK_TEST_CONDITION_REQUIRED(image3Da->GetStatistics()->GetScalarValueMax() <= 1000, "Testing if max value holds"); - MITK_TEST_CONDITION_REQUIRED(image3Da->GetStatistics()->GetScalarValueMin() >= 0, "Testing if min value holds"); - - const unsigned int *image3DcBuffer = nullptr; - try - { - mitk::ImageReadAccessor readAccess(image3Dc); - image3DcBuffer = static_cast(readAccess.GetData()); - } - catch (...) - { - MITK_ERROR << "Read access not granted on mitk::Image."; - } - for (unsigned int i = 0; i < 2 * 3; i++) - { - MITK_TEST_CONDITION_REQUIRED(image3DcBuffer[i] == i, "Testing if gradient image values are set correctly"); - } - - MITK_TEST_END(); -} + mitk::Image::Pointer m_Image2Da; + mitk::Image::Pointer m_Image2Db; + mitk::Image::Pointer m_Image3Da; + mitk::Image::Pointer m_Image3Db; + mitk::Image::Pointer m_Image4Da; + mitk::Image::Pointer m_Image4Db; + mitk::Image::Pointer m_Image3Dc; + +public: + void setUp() + { + m_Image2Da = mitk::ImageGenerator::GenerateRandomImage(120, 205, 0, 0, 0.1, 0.2, 0.3, 577, 23); + m_Image2Db = mitk::ImageGenerator::GenerateRandomImage(1, 1, 0, 0); + m_Image3Da = mitk::ImageGenerator::GenerateRandomImage(512, 205, 1, 0); + m_Image3Db = mitk::ImageGenerator::GenerateRandomImage(512, 532, 112, 0); + m_Image4Da = mitk::ImageGenerator::GenerateRandomImage(120, 205, 78, 1); + m_Image4Db = mitk::ImageGenerator::GenerateRandomImage(550, 33, 78, 150); + m_Image3Dc = mitk::ImageGenerator::GenerateGradientImage(1, 2, 3, 4, 5, 6); + } + void tearDown() + { + m_Image2Da = nullptr; + m_Image2Db = nullptr; + m_Image3Da = nullptr; + m_Image3Db = nullptr; + m_Image4Da = nullptr; + m_Image4Db = nullptr; + m_Image3Dc = nullptr; + } + + void SetSpacingX2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if spacing 2D x is set correctly.", + fabs(m_Image2Da->GetGeometry()->GetSpacing()[0] - 0.1) < 0.0001); + } + + void SetDefaultSpacingX2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if default spacing 2D x is set correctly.", + fabs(m_Image2Db->GetGeometry()->GetSpacing()[0] - 1.0) < 0.0001); + } + + void SetSpacingX3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if spacing 3D x is set correctly.", + fabs(m_Image3Dc->GetGeometry()->GetSpacing()[0] - 4) < 0.0001); + } + + void SetSpacingY2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if spacing 2D y is set correctly.", + fabs(m_Image2Da->GetGeometry()->GetSpacing()[1] - 0.2) < 0.0001); + } + + void SetDefaultSpacingY2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if default spacing 2D y is set correctly.", + fabs(m_Image2Db->GetGeometry()->GetSpacing()[1] - 1.0) < 0.0001); + } + + void SetSpacingY3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if spacing 3D y is set correctly.", + fabs(m_Image3Dc->GetGeometry()->GetSpacing()[1] - 5) < 0.0001); + } + + void SetSpacingZ2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if spacing 2D z is set correctly.", + fabs(m_Image2Da->GetGeometry()->GetSpacing()[2] - 0.3) < 0.0001); + } + + void SetDefaultSpacingZ2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if default spacing 2D z is set correctly.", + fabs(m_Image2Db->GetGeometry()->GetSpacing()[2] - 1.0) < 0.0001); + } + + void SetSpacingZ3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if spacing z is set correctly.", + fabs(m_Image3Dc->GetGeometry()->GetSpacing()[2] - 6) < 0.0001); + } + + void SetDimension2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 2D is set correctly.", m_Image2Da->GetDimension() == 2); + CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 2D is set correctly.", m_Image2Db->GetDimension() == 2); + } + + void SetDimension3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 3D is set correctly.",m_Image3Da->GetDimension() == 2); + CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 3D is set correctly.", m_Image3Db->GetDimension() == 3); + } + + void SetDimension4D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 4D is set correctly.", m_Image4Da->GetDimension() == 3); + CPPUNIT_ASSERT_MESSAGE("Testing if the dimension 4D is set correctly.", m_Image4Db->GetDimension() == 4); + } + + void SetDimensionX2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the X dimension of the 2D image is set correctly.", m_Image2Da->GetDimension(0) == 120); + } + + void SetDimensionY2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the Y dimension of the 2D image is set correctly.", m_Image2Db->GetDimension(1) == 1); + } + + void SetDimensionZ3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the Z dimension of the 3D image is set correctly.", m_Image3Da->GetDimension(2) == 1); + CPPUNIT_ASSERT_MESSAGE("Testing if the Z dimension of the 3D image is set correctly.", m_Image3Db->GetDimension(2) == 112); + } + + void SetDimensionT4D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the T dimension of the 4D image is set correctly.", m_Image4Da->GetDimension(3) == 1); + CPPUNIT_ASSERT_MESSAGE("Testing if the T dimension of the 4D image is set correctly.", m_Image4Db->GetDimension(3) == 150); + } + + void SetDimensions3Dc_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if image3Dc dimension x is set correctly.", m_Image3Dc->GetDimension(0) == 1); + CPPUNIT_ASSERT_MESSAGE("Testing if image3Dc dimension y is set correctly.", m_Image3Dc->GetDimension(1) == 2); + CPPUNIT_ASSERT_MESSAGE("Testing if image3Dc dimension z is set correctly.", m_Image3Dc->GetDimension(2) == 3); + } + + void SetDataTypeFloat2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a float 3D image is set correctly.", + m_Image2Da->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT); + } + + void SetDataTypeUChar2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a UChar 2D image is set correctly.", + m_Image2Db->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR); + } + + void SetDataTypeInt3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a Int 3D image is set correctly.", + m_Image3Da->GetPixelType().GetComponentType() == itk::ImageIOBase::INT); + } + + void SetDataTypeDouble3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a Double 3D image is set correctly.", + m_Image3Db->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE); + } + + void SetDataTypeFloat4D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a Float 4D image is set correctly.", + m_Image4Da->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT); + } + + void SetDataTypeUChar4D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a UChar 4D image is set correctly.", + m_Image4Db->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR); + } + + void SetDataTypeUInt3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if the data type for a UInt 3D image is set correctly.", + m_Image3Dc->GetPixelType().GetComponentType() == itk::ImageIOBase::UINT); + } + + void SetPixelTypeFloat2D_Success() + { + itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; + CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a Float 2D image is set correctly.", + m_Image2Da->GetPixelType().GetPixelType() == scalarType); + } + + void SetPixelTypeUChar2D_Success() + { + itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; + CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a UChar 2D image is set correctly.", + m_Image2Db->GetPixelType().GetPixelType() == scalarType); + } + + void SetPixelTypeInt3D_Success() + { + itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; + CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a Int 3D image is set correctly.", + m_Image3Da->GetPixelType().GetPixelType() == scalarType); + } + + void SetPixelTypeDouble3D_Success() + { + itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; + CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a Double 3D image is set correctly.", + m_Image3Db->GetPixelType().GetPixelType() == scalarType); + } + + void SetPixelTypeFloat4D_Success() + { + itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; + CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a Float 4D image is set correctly.", + m_Image4Da->GetPixelType().GetPixelType() == scalarType); + } + + void SetPixelTypeUChar4D_Success() + { + itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; + CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a UChar 4D image is set correctly.", + m_Image4Db->GetPixelType().GetPixelType() == scalarType); + } + + void SetPixelTypeUInt3D_Success() + { + itk::ImageIOBase::IOPixelType scalarType = itk::ImageIOBase::SCALAR; + CPPUNIT_ASSERT_MESSAGE("Testing if the pixel type for a UInt 3D image is set correctly.", + m_Image3Dc->GetPixelType().GetPixelType() == scalarType); + } + + void MaxValueHolds_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if max value holds", m_Image2Da->GetStatistics()->GetScalarValueMax() <= 577); + } + + void MinValueHolds_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if min value holds", m_Image2Da->GetStatistics()->GetScalarValueMin() >= 23); + } + + void DefaultMaxValueHolds_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if default max value holds", m_Image3Da->GetStatistics()->GetScalarValueMax() <= 1000); + } + + void DefaultMinValueHolds_Success() + { + CPPUNIT_ASSERT_MESSAGE("Testing if default min value holds", m_Image3Da->GetStatistics()->GetScalarValueMin() >= 0); + } + + void SetGradientImageValues_Success() + { + const unsigned int *image3DcBuffer = nullptr; + try + { + mitk::ImageReadAccessor readAccess(m_Image3Dc); + image3DcBuffer = static_cast(readAccess.GetData()); + } + catch (...) + { + MITK_ERROR << "Read access not granted on mitk::Image."; + } + for (unsigned int i = 0; i < 2 * 3; i++) + { + CPPUNIT_ASSERT_MESSAGE("Testing if gradient image values are set correctly", image3DcBuffer[i] == i); + } + } +}; +MITK_TEST_SUITE_REGISTRATION(mitkImageGenerator) + diff --git a/Modules/Core/test/mitkInteractionEventTest.cpp b/Modules/Core/test/mitkInteractionEventTest.cpp index a042082ce0..ce740a3a7e 100644 --- a/Modules/Core/test/mitkInteractionEventTest.cpp +++ b/Modules/Core/test/mitkInteractionEventTest.cpp @@ -1,89 +1,116 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ +// Testing +#include "mitkTestFixture.h" +#include "mitkTestingMacros.h" +// MITK includes +#include #include "mitkInteractionEventConst.h" #include "mitkMouseMoveEvent.h" #include "mitkMousePressEvent.h" #include "mitkMouseReleaseEvent.h" -#include "mitkTestingMacros.h" +// VTK includes #include "mitkVtkPropRenderer.h" -int mitkInteractionEventTest(int /*argc*/, char * /*argv*/ []) +class mitkInteractionEventTestSuite : public mitk::TestFixture { - /* - * Create different Events, fill them with data. - * And check if isEqual method is implemented properly. - */ - MITK_TEST_BEGIN("InteractionEvent") - - mitk::VtkPropRenderer::Pointer renderer = nullptr; - - mitk::InteractionEvent::MouseButtons buttonStates = - mitk::InteractionEvent::LeftMouseButton | mitk::InteractionEvent::RightMouseButton; - mitk::InteractionEvent::MouseButtons eventButton = mitk::InteractionEvent::LeftMouseButton; - mitk::InteractionEvent::ModifierKeys modifiers = mitk::InteractionEvent::ControlKey | mitk::InteractionEvent::AltKey; - - mitk::Point2D point; - point[0] = 17; - point[1] = 170; - - mitk::Point3D worldPos; - worldPos[0] = 0.5; - worldPos[1] = 10.609; - worldPos[2] = 5.0; - - // MousePress Events - mitk::MousePressEvent::Pointer me1 = - mitk::MousePressEvent::New(renderer, point, buttonStates, modifiers, eventButton); - mitk::MousePressEvent::Pointer me2 = - mitk::MousePressEvent::New(renderer, point, buttonStates, modifiers, eventButton); - point[0] = 178; - point[1] = 170; - mitk::MousePressEvent::Pointer me3 = - mitk::MousePressEvent::New(renderer, point, buttonStates, modifiers, eventButton); - modifiers = mitk::InteractionEvent::ControlKey; - mitk::MousePressEvent::Pointer me4 = - mitk::MousePressEvent::New(renderer, point, buttonStates, modifiers, eventButton); - - MITK_TEST_CONDITION_REQUIRED(*me1 == *me2 && *me1 == *me3 && *me2 == *me3 && *me3 != *me4, - "Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MousePressEvent"); - - // MouseReleaseEvents - mitk::MouseReleaseEvent::Pointer mr1 = - mitk::MouseReleaseEvent::New(renderer, point, buttonStates, modifiers, eventButton); - mitk::MouseReleaseEvent::Pointer mr2 = - mitk::MouseReleaseEvent::New(renderer, point, buttonStates, modifiers, eventButton); - point[0] = 178; - point[1] = 170; - mitk::MouseReleaseEvent::Pointer mr3 = - mitk::MouseReleaseEvent::New(renderer, point, buttonStates, modifiers, eventButton); - eventButton = mitk::InteractionEvent::RightMouseButton; - mitk::MouseReleaseEvent::Pointer mr4 = - mitk::MouseReleaseEvent::New(renderer, point, buttonStates, modifiers, eventButton); - - MITK_TEST_CONDITION_REQUIRED(*mr1 == *mr2 && *mr1 == *mr3 && *mr2 == *mr3 && *mr3 != *mr4, - "Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MouseReleaseEvent"); - - // MouseMoveEvents - mitk::MouseMoveEvent::Pointer mm1 = mitk::MouseMoveEvent::New(renderer, point, buttonStates, modifiers); - point[0] = 178; - point[1] = 170; - mitk::MouseMoveEvent::Pointer mm3 = mitk::MouseMoveEvent::New(renderer, point, buttonStates, modifiers); - modifiers = mitk::InteractionEvent::AltKey; - mitk::MouseMoveEvent::Pointer mm4 = mitk::MouseMoveEvent::New(renderer, point, buttonStates, modifiers); - - MITK_TEST_CONDITION_REQUIRED(*mm1 == *mm3 && *mm3 != *mm4, - "Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MouseMoveEvent"); - - // always end with this! - MITK_TEST_END() -} + CPPUNIT_TEST_SUITE(mitkInteractionEventTestSuite); + MITK_TEST(MousePressEvent_Success); + MITK_TEST(MouseReleaseEvent_Success); + MITK_TEST(MouseMoveEvent_Success); + CPPUNIT_TEST_SUITE_END(); + +private: + mitk::VtkPropRenderer::Pointer m_Renderer; + + mitk::InteractionEvent::MouseButtons m_ButtonStates; + mitk::InteractionEvent::MouseButtons m_EventButton; + mitk::InteractionEvent::ModifierKeys m_Modifiers; + + mitk::Point2D m_Point; + + mitk::Point3D m_WorldPos; + +public: + void setUp() + { + m_Renderer = nullptr; + m_ButtonStates = mitk::InteractionEvent::LeftMouseButton | mitk::InteractionEvent::RightMouseButton; + m_EventButton = mitk::InteractionEvent::LeftMouseButton; + m_Modifiers = mitk::InteractionEvent::ControlKey | mitk::InteractionEvent::AltKey; + + m_Point[0] = 17; + m_Point[1] = 170; + + m_WorldPos[0] = 0.5; + m_WorldPos[1] = 10.609; + m_WorldPos[2] = 5.0; + } + void tearDown() + { + } + + void MousePressEvent_Success() + { + // MousePress Events + mitk::MousePressEvent::Pointer me1 = + mitk::MousePressEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers, m_EventButton); + mitk::MousePressEvent::Pointer me2 = + mitk::MousePressEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers, m_EventButton); + m_Point[0] = 178; + m_Point[1] = 170; + mitk::MousePressEvent::Pointer me3 = + mitk::MousePressEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers, m_EventButton); + m_Modifiers = mitk::InteractionEvent::ControlKey; + mitk::MousePressEvent::Pointer me4 = + mitk::MousePressEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers, m_EventButton); + + CPPUNIT_ASSERT_MESSAGE("Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MousePressEvent", + *me1 == *me2 && *me1 == *me3 && *me2 == *me3 && *me3 != *me4); + } + + void MouseReleaseEvent_Success() + { + // MouseReleaseEvents + mitk::MouseReleaseEvent::Pointer mr1 = + mitk::MouseReleaseEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers, m_EventButton); + mitk::MouseReleaseEvent::Pointer mr2 = + mitk::MouseReleaseEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers, m_EventButton); + m_Point[0] = 178; + m_Point[1] = 170; + mitk::MouseReleaseEvent::Pointer mr3 = + mitk::MouseReleaseEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers, m_EventButton); + m_EventButton = mitk::InteractionEvent::RightMouseButton; + mitk::MouseReleaseEvent::Pointer mr4 = + mitk::MouseReleaseEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers, m_EventButton); + + CPPUNIT_ASSERT_MESSAGE("Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MouseReleaseEvent", + *mr1 == *mr2 && *mr1 == *mr3 && *mr2 == *mr3 && *mr3 != *mr4); + } + + void MouseMoveEvent_Success() + { + // MouseMoveEvents + mitk::MouseMoveEvent::Pointer mm1 = mitk::MouseMoveEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers); + m_Point[0] = 178; + m_Point[1] = 170; + mitk::MouseMoveEvent::Pointer mm3 = mitk::MouseMoveEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers); + m_Modifiers = mitk::InteractionEvent::AltKey; + mitk::MouseMoveEvent::Pointer mm4 = mitk::MouseMoveEvent::New(m_Renderer, m_Point, m_ButtonStates, m_Modifiers); + + CPPUNIT_ASSERT_MESSAGE("Checking isEqual and Constructors of mitk::InteractionEvent, mitk::MouseMoveEvent", + *mm1 == *mm3 && *mm3 != *mm4); + } + +}; +MITK_TEST_SUITE_REGISTRATION(mitkInteractionEvent) diff --git a/Modules/Core/test/mitkPixelTypeTest.cpp b/Modules/Core/test/mitkPixelTypeTest.cpp index a5596f9451..0df8ef5104 100644 --- a/Modules/Core/test/mitkPixelTypeTest.cpp +++ b/Modules/Core/test/mitkPixelTypeTest.cpp @@ -1,150 +1,241 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include "mitkPixelType.h" +// Testing +#include "mitkTestFixture.h" #include "mitkTestingMacros.h" -#include +// std includes +#include +// MITK includes +#include "mitkPixelType.h" #include - +// ITK includes +#include "itkImage.h" #include +// VTK includes +#include struct MyObscurePixelType { typedef float ValueType; static const size_t Length = 2; }; //## Documentation //## main testing method -int mitkPixelTypeTest(int /*argc*/, char * /*argv*/ []) +class mitkPixelTypeTestSuite : public mitk::TestFixture { - MITK_TEST_BEGIN("PixelTypeTest"); - - MITK_INFO << "ptype = mitk::MakePixelType();"; - MITK_INFO - << "itkPtype = mitk::MakePixelType();\n with itk::Image, 3> ItkImageType"; - - mitk::PixelType ptype = mitk::MakePixelType(); + CPPUNIT_TEST_SUITE(mitkPixelTypeTestSuite); + + MITK_TEST(GetComponentType_Success); + MITK_TEST(GetPixelTypeAsString_Success); + MITK_TEST(GetBpePtype_Success); + MITK_TEST(GetNumberOfComponentsPtype_Success); + MITK_TEST(GetBitsPerComponentPtype_Success); + MITK_TEST(GetBpeItkPtype_Success); + MITK_TEST(GetNumberOfComponentsItkPtype_Success); + MITK_TEST(GetBitsPerComponentItkPtype_Success); + MITK_TEST(ConstructorWithBrackets_Success); + MITK_TEST(InitializeWithEqualSign_Success); + MITK_TEST(EqualityOperator_Success); + MITK_TEST(NotEqualityOperator_Success); + MITK_TEST(GetPixelTypeUnknown_Success); + MITK_TEST(SetLengthCorrectly_Success); + MITK_TEST(ValueTypeCorresponds_Success); + MITK_TEST(ImageTypeTraitInt3D_Success); + MITK_TEST(ImageTypeTraitShort2D_Success); + MITK_TEST(ImageTypeTraitVectorShort3D_Success); + MITK_TEST(ImageTypeTraitItkInt3D_Success); + MITK_TEST(ImageTypeTraitItkShort2D_Success); + MITK_TEST(ImageTypeTraitItkVectorShort3D_Success); + + CPPUNIT_TEST_SUITE_END(); + +private: typedef itk::Image, 3> ItkImageType; - mitk::PixelType itkPtype = mitk::MakePixelType(); - - MITK_TEST_CONDITION_REQUIRED(ptype.GetComponentType() == itk::ImageIOBase::INT, "GetComponentType()"); - // MITK_TEST_CONDITION( ptype.GetPixelTypeId() == typeid(ItkImageType), "GetPixelTypeId()"); - - MITK_INFO << ptype.GetPixelTypeAsString(); - MITK_INFO << typeid(ItkImageType).name(); - - MITK_TEST_CONDITION_REQUIRED(ptype.GetBpe() == 8 * sizeof(int) * 5, "[ptype] GetBpe()"); - MITK_TEST_CONDITION_REQUIRED(ptype.GetNumberOfComponents() == 5, "[ptype]GetNumberOfComponents()"); - MITK_TEST_CONDITION_REQUIRED(ptype.GetBitsPerComponent() == 8 * sizeof(int), "[ptype]GetBitsPerComponent()"); - - MITK_TEST_CONDITION_REQUIRED(itkPtype.GetBpe() == 8 * sizeof(int) * 5, "[itkPType] GetBpe()"); - MITK_TEST_CONDITION_REQUIRED(itkPtype.GetNumberOfComponents() == 5, "[itkPType] GetNumberOfComponents()"); - MITK_TEST_CONDITION_REQUIRED(itkPtype.GetBitsPerComponent() == 8 * sizeof(int), "[itkPType] GetBitsPerComponent()"); - - // MITK_TEST_CONDITION_REQUIRED( itkPtype == ptype, "[itkPtype = ptype]"); - - // MITK_TEST_CONDITION( ptype.GetPixelTypeAsString().compare("unknown") == 0, "GetPixelTypeAsString()"); - { - { - mitk::PixelType ptype2(ptype); - MITK_TEST_CONDITION_REQUIRED(ptype2.GetComponentType() == itk::ImageIOBase::INT, - "ptype2( ptype)- GetComponentType()"); - MITK_TEST_CONDITION(ptype2.GetPixelType() == ptype.GetPixelType(), "ptype2( ptype)-GetPixelType("); - MITK_TEST_CONDITION(ptype2.GetComponentType() == ptype.GetComponentType(), "ptype2( ptype)-GetComponentType("); - MITK_TEST_CONDITION_REQUIRED(ptype2.GetBpe() == 8 * sizeof(int) * 5, "ptype2( ptype)-GetBpe()"); - MITK_TEST_CONDITION_REQUIRED(ptype2.GetNumberOfComponents() == 5, "ptype2( ptype)-GetNumberOfComponents()"); - MITK_TEST_CONDITION_REQUIRED(ptype2.GetBitsPerComponent() == 8 * sizeof(int), - "ptype2( ptype)-GetBitsPerComponent()"); - // MITK_TEST_CONDITION_REQUIRED( ptype.GetPixelTypeAsString().compare("unknown") == 0, "ptype2( - // ptype)-GetPixelTypeAsString()"); - } - - { - mitk::PixelType ptype2 = ptype; - MITK_TEST_CONDITION_REQUIRED(ptype2.GetComponentType() == itk::ImageIOBase::INT, - "ptype2 = ptype- GetComponentType()"); - MITK_TEST_CONDITION(ptype2.GetPixelType() == ptype.GetPixelType(), "ptype2 = ptype- GetPixelType("); - MITK_TEST_CONDITION(ptype2.GetComponentType() == ptype.GetComponentType(), "ptype2( ptype)-GetComponentType("); - MITK_TEST_CONDITION_REQUIRED(ptype2.GetBpe() == 8 * sizeof(int) * 5, "ptype2 = ptype- GetBpe()"); - MITK_TEST_CONDITION_REQUIRED(ptype2.GetNumberOfComponents() == 5, "ptype2 = ptype- GetNumberOfComponents()"); - MITK_TEST_CONDITION_REQUIRED(ptype2.GetBitsPerComponent() == 8 * sizeof(int), - "ptype2 = ptype- GetBitsPerComponent()"); - // MITK_TEST_CONDITION_REQUIRED( ptype.GetPixelTypeAsString().compare("unknown") == 0, "ptype2 = ptype- - // GetPixelTypeAsString()"); - } - - { - mitk::PixelType ptype2 = ptype; - MITK_TEST_CONDITION_REQUIRED(ptype == ptype2, "operator =="); - // MITK_TEST_CONDITION_REQUIRED( ptype == typeid(int), "operator =="); - // mitk::PixelType ptype3 = mitk::MakePixelType; - // MITK_TEST_CONDITION_REQUIRED( ptype != ptype3, "operator !="); - // MITK_TEST_CONDITION_REQUIRED( *ptype3 != typeid(int), "operator !="); - } - } - - // test instantiation typedef itk::Image MyObscureImageType; - mitk::PixelType obscurePixelType = mitk::MakePixelType(); + typedef itk::VectorImage VectorImageType; + typedef itk::Image> FixedVectorImageType; - MITK_TEST_CONDITION(obscurePixelType.GetPixelType() == itk::ImageIOBase::UNKNOWNPIXELTYPE, - "PixelTypeId is 'UNKNOWN' "); - MITK_TEST_CONDITION(obscurePixelType.GetNumberOfComponents() == MyObscurePixelType::Length, - "Lenght was set correctly"); - MITK_TEST_CONDITION( - obscurePixelType.GetComponentType() == mitk::MapPixelComponentType::value, - "ValueType corresponds."); - typedef itk::VectorImage VectorImageType; - mitk::PixelType vectorPixelType = mitk::MakePixelType(78); - // vectorPixelType.SetVectorLength( 78 ); +public: + void setUp() override + { + } - typedef itk::Image> FixedVectorImageType; - mitk::PixelType fixedVectorPixelType = mitk::MakePixelType(); + void tearDown() override + { + } + + void GetComponentType_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + MITK_INFO << "m_Ptype = mitk::MakePixelType();"; + MITK_INFO + << "m_ItkPtype = mitk::MakePixelType();\n with itk::Image, 3> ItkImageType"; + CPPUNIT_ASSERT_MESSAGE("GetComponentType()", ptype.GetComponentType() == itk::ImageIOBase::INT); + } + + void GetPixelTypeAsString_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + MITK_INFO << ptype.GetPixelTypeAsString(); + MITK_INFO << typeid(ItkImageType).name(); + } + + void GetBpePtype_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("[m_Ptype] GetBpe()", ptype.GetBpe() == 8 * sizeof(int) * 5); + } + + void GetNumberOfComponentsPtype_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("[ptype]GetNumberOfComponents()", ptype.GetNumberOfComponents() == 5); + } + + void GetBitsPerComponentPtype_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("[ptype]GetBitsPerComponent()", ptype.GetBitsPerComponent() == 8 * sizeof(int)); + } + + void GetBpeItkPtype_Success() + { + mitk::PixelType itkPtype = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("[itkPType] GetBpe()", itkPtype.GetBpe() == 8 * sizeof(int) * 5); + } + + void GetNumberOfComponentsItkPtype_Success() + { + mitk::PixelType itkPtype = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("[itkPType] GetNumberOfComponents()", itkPtype.GetNumberOfComponents() == 5); + } + + void GetBitsPerComponentItkPtype_Success() + { + mitk::PixelType itkPtype = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("[itkPType] GetBitsPerComponent()", itkPtype.GetBitsPerComponent() == 8 * sizeof(int)); + } + + void ConstructorWithBrackets_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + mitk::PixelType ptype2(ptype); + CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)- GetComponentType()", ptype2.GetComponentType() == itk::ImageIOBase::INT); + CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetPixelType(", ptype2.GetPixelType() == ptype.GetPixelType()); + CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetComponentType(", ptype2.GetComponentType() == ptype.GetComponentType()); + CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetBpe()", ptype2.GetBpe() == 8 * sizeof(int) * 5); + CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetNumberOfComponents()", ptype2.GetNumberOfComponents() == 5); + CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetBitsPerComponent()", ptype2.GetBitsPerComponent() == 8 * sizeof(int)); + } + + void InitializeWithEqualSign_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + mitk::PixelType ptype2 = ptype; + CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetComponentType()", ptype2.GetComponentType() == itk::ImageIOBase::INT); + CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetPixelType(", ptype2.GetPixelType() == ptype.GetPixelType()); + CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetComponentType(", ptype2.GetComponentType() == ptype.GetComponentType()); + CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetBpe()", ptype2.GetBpe() == 8 * sizeof(int) * 5); + CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetNumberOfComponents()", ptype2.GetNumberOfComponents() == 5); + CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetBitsPerComponent()", ptype2.GetBitsPerComponent() == 8 * sizeof(int)); + } + + void EqualityOperator_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + mitk::PixelType ptype2 = ptype; + CPPUNIT_ASSERT_MESSAGE("operator ==", ptype == ptype2); + } + + void NotEqualityOperator_Success() + { + mitk::PixelType ptype = mitk::MakePixelType(); + mitk::PixelType ptype3 = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("operator !=", ptype != ptype3); + } + + void GetPixelTypeUnknown_Success() + { + // test instantiation + mitk::PixelType obscurePixelType = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("PixelTypeId is 'UNKNOWN' ", obscurePixelType.GetPixelType() == itk::ImageIOBase::UNKNOWNPIXELTYPE); + } + + void SetLengthCorrectly_Success() + { + mitk::PixelType obscurePixelType = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("Lenght was set correctly", obscurePixelType.GetNumberOfComponents() == MyObscurePixelType::Length); + } - mitk::PixelType scalarPixelType = mitk::MakeScalarPixelType(); + void ValueTypeCorresponds_Success() + { + mitk::PixelType obscurePixelType = mitk::MakePixelType(); + CPPUNIT_ASSERT_MESSAGE("ValueType corresponds.", - // test ImageTypeTrait traits class - MITK_TEST_CONDITION(typeid(mitk::ImageTypeTrait::ImageType) == typeid(itk::Image), "ImageTypeTrait"); - MITK_TEST_CONDITION((mitk::ImageTypeTrait::IsVectorImage == false), "ImageTypeTrait"); + obscurePixelType.GetComponentType() == mitk::MapPixelComponentType::value); + } + + void ImageTypeTraitInt3D_Success() + { + // test ImageTypeTrait traits class + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid int 3D equals ITK typeid", + + typeid(mitk::ImageTypeTrait::ImageType) == typeid(itk::Image)); + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is no vector image", (mitk::ImageTypeTrait::IsVectorImage == false)); + } + + void ImageTypeTraitShort2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid short 2D equals ITK typeid", + typeid(mitk::ImageTypeTrait, 3>::ImageType) == + typeid(itk::Image, 3>)); + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is no vector image", (mitk::ImageTypeTrait, 3>::IsVectorImage == false)); + } - MITK_TEST_CONDITION(typeid(mitk::ImageTypeTrait, 3>::ImageType) == - typeid(itk::Image, 3>), - "ImageTypeTrait"); - MITK_TEST_CONDITION((mitk::ImageTypeTrait, 3>::IsVectorImage == false), "ImageTypeTrait"); + void ImageTypeTraitVectorShort3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid short 3D equals ITK typeid", + typeid(mitk::ImageTypeTrait, 3>::ImageType) == typeid(itk::VectorImage)); + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is a vector image", (mitk::ImageTypeTrait, 3>::IsVectorImage == true)); + } - MITK_TEST_CONDITION( - typeid(mitk::ImageTypeTrait, 3>::ImageType) == typeid(itk::VectorImage), - "ImageTypeTrait"); - MITK_TEST_CONDITION((mitk::ImageTypeTrait, 3>::IsVectorImage == true), - "ImageTypeTrait"); + void ImageTypeTraitItkInt3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid ITK int 3D equals ITK typeid", + typeid(mitk::ImageTypeTrait>::ImageType) == typeid(itk::Image)); + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is no vector image", (mitk::ImageTypeTrait>::IsVectorImage == false)); + } - MITK_TEST_CONDITION(typeid(mitk::ImageTypeTrait>::ImageType) == typeid(itk::Image), - "ImageTypeTrait"); - MITK_TEST_CONDITION((mitk::ImageTypeTrait>::IsVectorImage == false), "ImageTypeTrait"); + void ImageTypeTraitItkShort2D_Success() + { + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid ITK short 2D equals ITK typeid", + typeid(mitk::ImageTypeTrait, 3>>::ImageType) == + typeid(itk::Image, 3>)); + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is no vector image", - MITK_TEST_CONDITION(typeid(mitk::ImageTypeTrait, 3>>::ImageType) == - typeid(itk::Image, 3>), - "ImageTypeTrait"); - MITK_TEST_CONDITION((mitk::ImageTypeTrait, 3>>::IsVectorImage == false), - "ImageTypeTrait"); + (mitk::ImageTypeTrait, 3>>::IsVectorImage == false)); + } - MITK_TEST_CONDITION( - typeid(mitk::ImageTypeTrait>::ImageType) == typeid(itk::VectorImage), - "ImageTypeTrait"); - MITK_TEST_CONDITION((mitk::ImageTypeTrait>::IsVectorImage == true), "ImageTypeTrait"); + void ImageTypeTraitItkVectorShort3D_Success() + { + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid ITK short 3D equals ITK typeid", + typeid(mitk::ImageTypeTrait>::ImageType) == typeid(itk::VectorImage)); + CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is a vector image", + (mitk::ImageTypeTrait>::IsVectorImage == true)); + } +}; +MITK_TEST_SUITE_REGISTRATION(mitkPixelType) - // test CastableTo - MITK_TEST_END(); -} diff --git a/Modules/Core/test/mitkPropertyAliasesTest.cpp b/Modules/Core/test/mitkPropertyAliasesTest.cpp index 22dd5d8ec0..3188a48066 100644 --- a/Modules/Core/test/mitkPropertyAliasesTest.cpp +++ b/Modules/Core/test/mitkPropertyAliasesTest.cpp @@ -1,63 +1,106 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ +// Testing +#include "mitkTestFixture.h" +#include "mitkTestingMacros.h" +// std includes +#include #include +// MITK includes #include #include -#include +// VTK includes +#include -int mitkPropertyAliasesTest(int, char *[]) +class mitkPropertyAliasesTestSuite : public mitk::TestFixture { - MITK_TEST_BEGIN("mitkPropertyAliasesTest"); - - mitk::IPropertyAliases *propertyAliases = mitk::CoreServices::GetPropertyAliases(); - MITK_TEST_CONDITION_REQUIRED(propertyAliases != nullptr, "Get property aliases service"); - - propertyAliases->AddAlias("propertyName1", "alias1a"); - propertyAliases->AddAlias("propertyName1", "alias1b"); - propertyAliases->AddAlias("propertyName2", "alias2a"); - propertyAliases->AddAlias("propertyName2", "alias2b", "className"); - + CPPUNIT_TEST_SUITE(mitkPropertyAliasesTestSuite); + MITK_TEST(GetPropertyAliasesService_Success); + MITK_TEST(GetAliases_Success); + MITK_TEST(GetAliasesRestricted_Success); + MITK_TEST(GetPropertyName_Success); + MITK_TEST(GetPropertyNameNonexisting_Empty); + MITK_TEST(GetPropertyNameRestricted_Success); + CPPUNIT_TEST_SUITE_END(); + +private: + mitk::IPropertyAliases *m_PropertyAliases; typedef std::vector Aliases; - - Aliases aliases = propertyAliases->GetAliases("propertyName1"); - auto it1 = std::find(aliases.begin(), aliases.end(), "alias1a"); - auto it2 = std::find(aliases.begin(), aliases.end(), "alias1b"); - - MITK_TEST_CONDITION(aliases.size() == 2 && it1 != aliases.end() && it2 != aliases.end(), - "Get aliases of \"propertyName1\""); - - aliases = propertyAliases->GetAliases("propertyName2"); - it1 = std::find(aliases.begin(), aliases.end(), "alias2a"); - - MITK_TEST_CONDITION(aliases.size() == 1 && it1 != aliases.end(), "Get aliases of \"propertyName2\""); - - aliases = propertyAliases->GetAliases("propertyName2", "className"); - it1 = std::find(aliases.begin(), aliases.end(), "alias2b"); - - MITK_TEST_CONDITION(aliases.size() == 1 && it1 != aliases.end(), - "Get aliases of \"propertyName2\" restricted to \"className\""); - - std::string propertyName = propertyAliases->GetPropertyName("alias1b"); - - MITK_TEST_CONDITION(propertyName == "propertyName1", "Get property name of \"alias1b\""); - - propertyName = propertyAliases->GetPropertyName("alias2b"); - - MITK_TEST_CONDITION(propertyName.empty(), "Get property name of non-existing unrestricted \"alias2b\""); - - propertyName = propertyAliases->GetPropertyName("alias2b", "className"); - - MITK_TEST_CONDITION(propertyName == "propertyName2", "Get property name of restricted \"alias2b\""); - - MITK_TEST_END(); -} + Aliases m_Aliases; + std::string m_PropertyName; + +public: + void setUp() + { + m_PropertyAliases = mitk::CoreServices::GetPropertyAliases(); + m_PropertyAliases->AddAlias("propertyName1", "alias1a"); + m_PropertyAliases->AddAlias("propertyName1", "alias1b"); + m_PropertyAliases->AddAlias("propertyName2", "alias2a"); + m_PropertyAliases->AddAlias("propertyName2", "alias2b", "className"); + } + void tearDown() + { + m_PropertyAliases = nullptr; + } + + + void GetPropertyAliasesService_Success() + { + CPPUNIT_ASSERT_MESSAGE("Get property aliases service", m_PropertyAliases != nullptr); + } + + void GetAliases_Success() + { + m_Aliases = m_PropertyAliases->GetAliases("propertyName1"); + auto it1 = std::find(m_Aliases.begin(), m_Aliases.end(), "alias1a"); + auto it2 = std::find(m_Aliases.begin(), m_Aliases.end(), "alias1b"); + + CPPUNIT_ASSERT_MESSAGE("Get aliases of \"propertyName1\"", m_Aliases.size() == 2 && it1 != m_Aliases.end() && it2 != m_Aliases.end()); + + m_Aliases = m_PropertyAliases->GetAliases("propertyName2"); + it1 = std::find(m_Aliases.begin(), m_Aliases.end(), "alias2a"); + + CPPUNIT_ASSERT_MESSAGE("Get aliases of \"propertyName2\"", m_Aliases.size() == 1 && it1 != m_Aliases.end()); + } + + void GetAliasesRestricted_Success() + { + m_Aliases = m_PropertyAliases->GetAliases("propertyName2", "className"); + auto it1 = std::find(m_Aliases.begin(), m_Aliases.end(), "alias2b"); + + CPPUNIT_ASSERT_MESSAGE("Get aliases of \"propertyName2\" restricted to \"className\"", m_Aliases.size() == 1 && it1 != m_Aliases.end()); + } + + void GetPropertyName_Success() + { + m_PropertyName = m_PropertyAliases->GetPropertyName("alias1b"); + + CPPUNIT_ASSERT_MESSAGE("Get property name of \"alias1b\"", m_PropertyName == "propertyName1"); + } + + void GetPropertyNameNonexisting_Empty() + { + m_PropertyName = m_PropertyAliases->GetPropertyName("alias2b"); + + CPPUNIT_ASSERT_MESSAGE("Get property name of non-existing unrestricted \"alias2b\"", m_PropertyName.empty()); + } + + void GetPropertyNameRestricted_Success() + { + m_PropertyName = m_PropertyAliases->GetPropertyName("alias2b", "className"); + + CPPUNIT_ASSERT_MESSAGE("Get property name of restricted \"alias2b\"", m_PropertyName == "propertyName2"); + } +}; + +MITK_TEST_SUITE_REGISTRATION(mitkPropertyAliases) diff --git a/Modules/Core/test/mitkPropertyDescriptionsTest.cpp b/Modules/Core/test/mitkPropertyDescriptionsTest.cpp index 6b7e98b5f0..4b58119a59 100644 --- a/Modules/Core/test/mitkPropertyDescriptionsTest.cpp +++ b/Modules/Core/test/mitkPropertyDescriptionsTest.cpp @@ -1,43 +1,80 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ +// Testing +#include "mitkTestFixture.h" +#include "mitkTestingMacros.h" +// std includes +#include +#include +// MITK includes #include #include -#include +// VTK includes +#include -int mitkPropertyDescriptionsTest(int, char *[]) +class mitkPropertyDescriptionsTestSuite : public mitk::TestFixture { - MITK_TEST_BEGIN("mitkPropertyDescriptionsTest"); + CPPUNIT_TEST_SUITE(mitkPropertyDescriptionsTestSuite); + MITK_TEST(GetPropertyDescriptionService_Success); + MITK_TEST(GetPropertyDescription_Success); + MITK_TEST(GetOverwrittenDescription_Success); + MITK_TEST(GetPropertyDescriptionRestricted_Success); + CPPUNIT_TEST_SUITE_END(); - mitk::IPropertyDescriptions *propertyDescriptions = mitk::CoreServices::GetPropertyDescriptions(); - MITK_TEST_CONDITION_REQUIRED(propertyDescriptions != nullptr, "Get property descriptions service"); + private: + mitk::IPropertyDescriptions *m_PropertyDescriptions; + std::string m_Description1; - propertyDescriptions->AddDescription("propertyName1", "description1a"); - propertyDescriptions->AddDescription("propertyName1", "description1b"); - std::string description1 = propertyDescriptions->GetDescription("propertyName1"); + public: + void setUp() + { + m_PropertyDescriptions = mitk::CoreServices::GetPropertyDescriptions(); + m_PropertyDescriptions->AddDescription("propertyName1", "description1a"); + m_PropertyDescriptions->AddDescription("propertyName1", "description1b"); + } - MITK_TEST_CONDITION(description1 == "description1a", "Get description of \"propertyName1\""); + void tearDown() + { + m_PropertyDescriptions = nullptr; + } - propertyDescriptions->AddDescription("propertyName1", "description1b", "", true); - description1 = propertyDescriptions->GetDescription("propertyName1"); + void GetPropertyDescriptionService_Success() + { + CPPUNIT_ASSERT_MESSAGE("Get property descriptions service", m_PropertyDescriptions != nullptr); + } - MITK_TEST_CONDITION(description1 == "description1b", "Get overwritten description of \"propertyName1\""); + void GetPropertyDescription_Success() + { + m_Description1 = m_PropertyDescriptions->GetDescription("propertyName1"); + CPPUNIT_ASSERT_MESSAGE("Get description of \"propertyName1\"", m_Description1 == "description1a"); + } - propertyDescriptions->AddDescription("propertyName1", "description1c", "className"); - std::string description2 = propertyDescriptions->GetDescription("propertyName1", "className"); - description1 = propertyDescriptions->GetDescription("propertyName1"); + void GetOverwrittenDescription_Success() + { + m_PropertyDescriptions->AddDescription("propertyName1", "description1b", "", true); + m_Description1 = m_PropertyDescriptions->GetDescription("propertyName1"); + CPPUNIT_ASSERT_MESSAGE("Get overwritten description of \"propertyName1\"", m_Description1 == "description1b"); + } - MITK_TEST_CONDITION(description1 == "description1b" && description2 == "description1c", - "Get description of \"propertyName1\" restricted to \"className\""); + void GetPropertyDescriptionRestricted_Success() + { + m_PropertyDescriptions->AddDescription("propertyName1", "description1c", "className"); + std::string description2 = m_PropertyDescriptions->GetDescription("propertyName1", "className"); + m_Description1 = m_PropertyDescriptions->GetDescription("propertyName1"); + + CPPUNIT_ASSERT_MESSAGE("Get description of \"propertyName1\" restricted to \"className\"", + m_Description1 == "description1b" && description2 == "description1c"); + } +}; - MITK_TEST_END(); -} +MITK_TEST_SUITE_REGISTRATION(mitkPropertyDescriptions) diff --git a/Modules/Core/test/mitkPropertyExtensionsTest.cpp b/Modules/Core/test/mitkPropertyExtensionsTest.cpp index 8404dcc0cb..af38679513 100644 --- a/Modules/Core/test/mitkPropertyExtensionsTest.cpp +++ b/Modules/Core/test/mitkPropertyExtensionsTest.cpp @@ -1,63 +1,100 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ +// Testing +#include "mitkTestFixture.h" +#include "mitkTestingMacros.h" +// std includes +#include +#include +// MITK includes #include #include #include -#include +// VTK includes +#include class TestPropertyExtension : public mitk::PropertyExtension { public: mitkClassMacro(TestPropertyExtension, mitk::PropertyExtension); mitkNewMacro1Param(Self, const std::string &); std::string GetName() const { return m_Name; } private: explicit TestPropertyExtension(const std::string &name) : m_Name(name) {} ~TestPropertyExtension() override {} std::string m_Name; }; -int mitkPropertyExtensionsTest(int, char *[]) +class mitkPropertyExtensionsTestSuite : public mitk::TestFixture { - MITK_TEST_BEGIN("mitkPropertyExtensionsTest"); + CPPUNIT_TEST_SUITE(mitkPropertyExtensionsTestSuite); + MITK_TEST(GetPropertyExtensionService_Success); + MITK_TEST(GetPropertyExtension_Success); + MITK_TEST(GetOverwrittenExtension_Success); + MITK_TEST(GetPropertyExtensionRestricted_Success); + CPPUNIT_TEST_SUITE_END(); - mitk::IPropertyExtensions *propertyExtensions = mitk::CoreServices::GetPropertyExtensions(); - MITK_TEST_CONDITION_REQUIRED(propertyExtensions != nullptr, "Get property extensions service"); - - propertyExtensions->AddExtension("propertyName1", TestPropertyExtension::New("extension1a").GetPointer()); - propertyExtensions->AddExtension("propertyName1", TestPropertyExtension::New("extension1b").GetPointer()); - TestPropertyExtension::Pointer extension1 = - dynamic_cast(propertyExtensions->GetExtension("propertyName1").GetPointer()); - - MITK_TEST_CONDITION(extension1.IsNotNull() && extension1->GetName() == "extension1a", - "Get extension of \"propertyName1\""); - - propertyExtensions->AddExtension("propertyName1", TestPropertyExtension::New("extension1b").GetPointer(), "", true); - extension1 = dynamic_cast(propertyExtensions->GetExtension("propertyName1").GetPointer()); - - MITK_TEST_CONDITION(extension1.IsNotNull() && extension1->GetName() == "extension1b", - "Get overwritten extension of \"propertyName1\""); - - propertyExtensions->AddExtension( - "propertyName1", TestPropertyExtension::New("extension1c").GetPointer(), "className"); - TestPropertyExtension::Pointer extension2 = - dynamic_cast(propertyExtensions->GetExtension("propertyName1", "className").GetPointer()); - extension1 = dynamic_cast(propertyExtensions->GetExtension("propertyName1").GetPointer()); +private: + mitk::IPropertyExtensions *m_PropertyExtensions; + TestPropertyExtension::Pointer m_Extension1; - MITK_TEST_CONDITION(extension1.IsNotNull() && extension1->GetName() == "extension1b" && extension2.IsNotNull() && - extension2->GetName() == "extension1c", - "Get extension of \"propertyName1\" restricted to \"className\""); +public: + void setUp() + { + m_PropertyExtensions = mitk::CoreServices::GetPropertyExtensions(); + m_PropertyExtensions->AddExtension("propertyName1", TestPropertyExtension::New("extension1a").GetPointer()); + m_PropertyExtensions->AddExtension("propertyName1", TestPropertyExtension::New("extension1b").GetPointer()); + } + + void tearDown() + { + m_PropertyExtensions = nullptr; + } + + void GetPropertyExtensionService_Success() + { + CPPUNIT_ASSERT_MESSAGE("Get property extensions service", m_PropertyExtensions != nullptr); + } + + void GetPropertyExtension_Success() + { + TestPropertyExtension::Pointer extension1 = + dynamic_cast(m_PropertyExtensions->GetExtension("propertyName1").GetPointer()); + + CPPUNIT_ASSERT_MESSAGE("Get extension of \"propertyName1\"", + extension1.IsNotNull() && extension1->GetName() == "extension1a"); + } + + void GetOverwrittenExtension_Success() + { + m_PropertyExtensions->AddExtension("propertyName1", TestPropertyExtension::New("extension1b").GetPointer(), "", true); + m_Extension1 = dynamic_cast(m_PropertyExtensions->GetExtension("propertyName1").GetPointer()); + CPPUNIT_ASSERT_MESSAGE("Get overwritten extension of \"propertyName1\"", + m_Extension1.IsNotNull() && m_Extension1->GetName() == "extension1b"); + } + + void GetPropertyExtensionRestricted_Success() + { + m_PropertyExtensions->AddExtension("propertyName1", TestPropertyExtension::New("extension1c").GetPointer(), "className"); + TestPropertyExtension::Pointer extension2 = + dynamic_cast(m_PropertyExtensions->GetExtension("propertyName1", "className").GetPointer()); + m_Extension1 = dynamic_cast(m_PropertyExtensions->GetExtension("propertyName1").GetPointer()); + + CPPUNIT_ASSERT_MESSAGE("Get extension of \"propertyName1\" restricted to \"className\"", + m_Extension1.IsNotNull() && m_Extension1->GetName() == "extension1b" && extension2.IsNotNull() && + extension2->GetName() == "extension1c"); + } + }; + MITK_TEST_SUITE_REGISTRATION(mitkPropertyExtensions) - MITK_TEST_END(); -} diff --git a/Modules/Core/test/mitkPropertyFiltersTest.cpp b/Modules/Core/test/mitkPropertyFiltersTest.cpp index 2eba270d66..f48ff6725f 100644 --- a/Modules/Core/test/mitkPropertyFiltersTest.cpp +++ b/Modules/Core/test/mitkPropertyFiltersTest.cpp @@ -1,65 +1,96 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ -#include +// Testing +#include "mitkTestFixture.h" +#include "mitkTestingMacros.h" +// std includes +#include +#include +// MITK includes #include #include #include #include -#include -#include +// VTK includes +#include -int mitkPropertyFiltersTest(int, char *[]) +class mitkPropertyFiltersTestSuite : public mitk::TestFixture { - MITK_TEST_BEGIN("mitkPropertyFiltersTest"); - - mitk::IPropertyFilters *propertyFilters = mitk::CoreServices::GetPropertyFilters(); - MITK_TEST_CONDITION_REQUIRED(propertyFilters != nullptr, "Get property filters service"); - + CPPUNIT_TEST_SUITE(mitkPropertyFiltersTestSuite); + MITK_TEST(GetPropertyFiltersService_Success); + MITK_TEST(ApplyGlobalPropertyFilter_Success); + MITK_TEST(ApplyRestrictedPropertyFilter_Success); + CPPUNIT_TEST_SUITE_END(); + +private: + mitk::IPropertyFilters *m_PropertyFilters; typedef std::map PropertyMap; typedef PropertyMap::const_iterator PropertyMapConstIterator; - - PropertyMap propertyMap; - propertyMap.insert(std::make_pair("propertyName1", mitk::BoolProperty::New().GetPointer())); - propertyMap.insert(std::make_pair("propertyName2", mitk::BoolProperty::New().GetPointer())); - propertyMap.insert(std::make_pair("propertyName3", mitk::BoolProperty::New().GetPointer())); - - mitk::PropertyFilter filter; - filter.AddEntry("propertyName1", mitk::PropertyFilter::Whitelist); - filter.AddEntry("propertyName2", mitk::PropertyFilter::Whitelist); - - mitk::PropertyFilter restrictedFilter; - restrictedFilter.AddEntry("propertyName2", mitk::PropertyFilter::Blacklist); - - propertyFilters->AddFilter(filter); - propertyFilters->AddFilter(restrictedFilter, "className"); - - PropertyMap filteredPropertyMap = propertyFilters->ApplyFilter(propertyMap); - PropertyMapConstIterator it1 = filteredPropertyMap.find("propertyName1"); - PropertyMapConstIterator it2 = filteredPropertyMap.find("propertyName2"); - PropertyMapConstIterator it3 = filteredPropertyMap.find("propertyName3"); - - MITK_TEST_CONDITION( - it1 != filteredPropertyMap.end() && it2 != filteredPropertyMap.end() && it3 == filteredPropertyMap.end(), - "Apply global property filter"); - - filteredPropertyMap = propertyFilters->ApplyFilter(propertyMap, "className"); - it1 = filteredPropertyMap.find("propertyName1"); - it2 = filteredPropertyMap.find("propertyName2"); - it3 = filteredPropertyMap.find("propertyName3"); - - MITK_TEST_CONDITION( - it1 != filteredPropertyMap.end() && it2 == filteredPropertyMap.end() && it3 == filteredPropertyMap.end(), - "Apply restricted property filter (also respects global filter)"); - - MITK_TEST_END(); -} + PropertyMap m_PropertyMap; + mitk::PropertyFilter m_Filter; + mitk::PropertyFilter m_RestrictedFilter; + PropertyMap m_FilteredPropertyMap; + PropertyMapConstIterator m_It1; + PropertyMapConstIterator m_It2; + PropertyMapConstIterator m_It3; + +public: + void setUp() + { + m_PropertyFilters = mitk::CoreServices::GetPropertyFilters(); + + m_PropertyMap.insert(std::make_pair("propertyName1", mitk::BoolProperty::New().GetPointer())); + m_PropertyMap.insert(std::make_pair("propertyName2", mitk::BoolProperty::New().GetPointer())); + m_PropertyMap.insert(std::make_pair("propertyName3", mitk::BoolProperty::New().GetPointer())); + + m_Filter.AddEntry("propertyName1", mitk::PropertyFilter::Whitelist); + m_Filter.AddEntry("propertyName2", mitk::PropertyFilter::Whitelist); + + m_RestrictedFilter.AddEntry("propertyName2", mitk::PropertyFilter::Blacklist); + + m_PropertyFilters->AddFilter(m_Filter); + m_PropertyFilters->AddFilter(m_RestrictedFilter, "className"); + } + void tearDown() + { + m_PropertyFilters = nullptr; + } + + void GetPropertyFiltersService_Success() + { + CPPUNIT_ASSERT_MESSAGE("Get property filters service", m_PropertyFilters != nullptr); + } + + void ApplyGlobalPropertyFilter_Success() + { + m_FilteredPropertyMap = m_PropertyFilters->ApplyFilter(m_PropertyMap); + m_It1 = m_FilteredPropertyMap.find("propertyName1"); + m_It2 = m_FilteredPropertyMap.find("propertyName2"); + m_It3 = m_FilteredPropertyMap.find("propertyName3"); + + CPPUNIT_ASSERT_MESSAGE("Apply global property filter", + m_It1 != m_FilteredPropertyMap.end() && m_It2 != m_FilteredPropertyMap.end() && m_It3 == m_FilteredPropertyMap.end()); + } + + void ApplyRestrictedPropertyFilter_Success() + { + m_FilteredPropertyMap = m_PropertyFilters->ApplyFilter(m_PropertyMap, "className"); + m_It1 = m_FilteredPropertyMap.find("propertyName1"); + m_It2 = m_FilteredPropertyMap.find("propertyName2"); + m_It3 = m_FilteredPropertyMap.find("propertyName3"); + + CPPUNIT_ASSERT_MESSAGE("Apply restricted property filter (also respects global filter)", + m_It1 != m_FilteredPropertyMap.end() && m_It2 == m_FilteredPropertyMap.end() && m_It3 == m_FilteredPropertyMap.end()); + } +}; +MITK_TEST_SUITE_REGISTRATION(mitkPropertyFilters) diff --git a/Modules/Core/test/mitkPropertyTest.cpp b/Modules/Core/test/mitkPropertyTest.cpp index 01a23ef6ec..3d2fa11b29 100644 --- a/Modules/Core/test/mitkPropertyTest.cpp +++ b/Modules/Core/test/mitkPropertyTest.cpp @@ -1,434 +1,489 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ +// Testing +#include "mitkTestFixture.h" #include "mitkTestingMacros.h" - +// std includes +#include +// MITK includes #include #include #include #include #include #include #include #include #include #include #include - +#include +// ITK includes #include +// VTK includes +#include struct PropertyModifiedListener { typedef itk::SimpleMemberCommand CmdType; PropertyModifiedListener() : m_Modified(false), m_Cmd(CmdType::New()) { m_Cmd->SetCallbackFunction(this, &PropertyModifiedListener::Modified); } void Modified() { m_Modified = true; } bool Pop() { bool b = m_Modified; m_Modified = false; return b; } bool m_Modified; CmdType::Pointer m_Cmd; }; -template -void TestPropInequality(T prop, T prop2) -{ - mitk::BaseProperty::Pointer baseProp2(prop2.GetPointer()); - MITK_TEST_CONDITION_REQUIRED(!(*prop == *prop2), "Test inequality 1"); - MITK_TEST_CONDITION_REQUIRED(!(*prop == *baseProp2), "Test polymorphic inequality 1"); - MITK_TEST_CONDITION_REQUIRED(!(*baseProp2 == *prop), "Test polymorphic inequality 2"); -} - -template -void TestPropAssignment(T prop, T prop2, const std::string &strProp) -{ - PropertyModifiedListener l; - unsigned long tag = prop->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); - - mitk::BaseProperty::Pointer baseProp2(prop2.GetPointer()); - *prop = *baseProp2; - MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified event"); - std::string msg = std::string("Test assignment [") + prop->GetValueAsString() + " == " + strProp + "]"; - MITK_TEST_CONDITION_REQUIRED(prop->GetValueAsString() == strProp, msg); - MITK_TEST_CONDITION_REQUIRED(*prop == *prop2, "Test equality"); - MITK_TEST_CONDITION_REQUIRED(*prop == *baseProp2, "Test equality"); - MITK_TEST_CONDITION_REQUIRED(*baseProp2 == *prop, "Test polymorphic equality"); - - prop->RemoveObserver(tag); -} - -template -void TestPropPolymorphicAssignment(T prop, T prop2, const std::string &strProp) +class mitkPropertyTestSuite : public mitk::TestFixture { - mitk::BaseProperty::Pointer baseProp(prop.GetPointer()); - - PropertyModifiedListener l; - unsigned long tag = baseProp->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); - - *baseProp = *prop2; - MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified event"); - std::string msg = - std::string("Test polymorphic assignment [") + baseProp->GetValueAsString() + " == " + strProp + "]"; - MITK_TEST_CONDITION_REQUIRED(baseProp->GetValueAsString() == strProp, msg); - MITK_TEST_CONDITION_REQUIRED(*prop == *prop2, "Test equality"); - MITK_TEST_CONDITION_REQUIRED(*prop2 == *baseProp, "Test equality"); - MITK_TEST_CONDITION_REQUIRED(*baseProp == *prop2, "Test polymorphic equality"); - - baseProp->RemoveObserver(tag); -} - -template -void TestPropCloning(T prop) -{ - T prop2 = prop->Clone(); - MITK_TEST_CONDITION_REQUIRED(prop.GetPointer() != prop2.GetPointer(), "Test clone pointer") - MITK_TEST_CONDITION_REQUIRED(*prop == *prop2, "Test equality of the clone") -} - -template -void TestProperty(const typename T::ValueType &v1, - const typename T::ValueType &v2, - const std::string &strV1, - const std::string &strV2) -{ - PropertyModifiedListener l; - - typename T::Pointer prop = T::New(v1); - MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); + CPPUNIT_TEST_SUITE(mitkPropertyTestSuite); + MITK_TEST(TestBoolProperty_Success); + MITK_TEST(TestIntProperty_Success); + MITK_TEST(TestFloatProperty_Success); + MITK_TEST(TestDoubleProperty_Success); + MITK_TEST(TestVector3DProperty_Success); + MITK_TEST(TestPoint3D_Success); + MITK_TEST(TestPoint4D_Success); + MITK_TEST(TestPoint3I_Success); + MITK_TEST(TestFloatLookupTable_Success); + MITK_TEST(TestBoolLookupTable_Success); + MITK_TEST(TestIntLookupTable_Success); + MITK_TEST(TestStringLookupTable_Success); + MITK_TEST(TestAnnotationProperty_Success); + MITK_TEST(TestClippingProperty_Success); + MITK_TEST(TestColorProperty_Success); + MITK_TEST(TestLevelWindowProperty_Success); + MITK_TEST(TestSmartPointerProperty_Success); + MITK_TEST(TestStringProperty_Success); + MITK_TEST(TestTransferFunctionProperty_Success); + MITK_TEST(TestWeakPointerProperty_Success); + MITK_TEST(TestLookupTablePropertyProperty_Success); + CPPUNIT_TEST_SUITE_END(); + +private: + PropertyModifiedListener m_L; +public: + void setUp() + { + } + void tearDown() + { + } - MITK_TEST_CONDITION_REQUIRED(prop->GetValue() == v1, "Test constructor"); - std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + strV1 + "]"; - MITK_TEST_CONDITION_REQUIRED(prop->GetValueAsString() == strV1, msg); + template + void TestPropInequality(T prop, T prop2) + { + mitk::BaseProperty::Pointer baseProp2(prop2.GetPointer()); + CPPUNIT_ASSERT_MESSAGE("Test inequality 1", !(*prop == *prop2)); + CPPUNIT_ASSERT_MESSAGE("Test polymorphic inequality 1", !(*prop == *baseProp2)); + CPPUNIT_ASSERT_MESSAGE("Test polymorphic inequality 2", !(*baseProp2 == *prop)); + } - TestPropCloning(prop); + template + void TestPropAssignment(T prop, T prop2, const std::string &strProp) + { + unsigned long tag = prop->AddObserver(itk::ModifiedEvent(), m_L.m_Cmd.GetPointer()); + + mitk::BaseProperty::Pointer baseProp2(prop2.GetPointer()); + *prop = *baseProp2; + CPPUNIT_ASSERT_MESSAGE("Test modified event", m_L.Pop()); + std::string msg = std::string("Test assignment [") + prop->GetValueAsString() + " == " + strProp + "]"; + CPPUNIT_ASSERT_MESSAGE(msg, prop->GetValueAsString() == strProp); + CPPUNIT_ASSERT_MESSAGE("Test equality", *prop == *prop2); + CPPUNIT_ASSERT_MESSAGE("Test equality", *prop == *baseProp2); + CPPUNIT_ASSERT_MESSAGE("Test polymorphic equality", *baseProp2 == *prop); + + prop->RemoveObserver(tag); + } - typename T::Pointer prop2 = T::New(); - prop2->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); - MITK_TEST_CONDITION_REQUIRED(!l.m_Modified, "Test modified"); - prop2->SetValue(v2); - MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); - MITK_TEST_CONDITION_REQUIRED(prop2->GetValue() == v2, "Test SetValue()"); + template + void TestPropPolymorphicAssignment(T prop, T prop2, const std::string &strProp) + { + mitk::BaseProperty::Pointer baseProp(prop.GetPointer()); + + unsigned long tag = baseProp->AddObserver(itk::ModifiedEvent(), m_L.m_Cmd.GetPointer()); + + *baseProp = *prop2; + CPPUNIT_ASSERT_MESSAGE("Test modified event", m_L.Pop()); + std::string msg = + std::string("Test polymorphic assignment [") + baseProp->GetValueAsString() + " == " + strProp + "]"; + CPPUNIT_ASSERT_MESSAGE(msg, baseProp->GetValueAsString() == strProp); + CPPUNIT_ASSERT_MESSAGE("Test equality", *prop == *prop2); + CPPUNIT_ASSERT_MESSAGE("Test equality", *prop2 == *baseProp); + CPPUNIT_ASSERT_MESSAGE("Test polymorphic equality", *baseProp == *prop2); + baseProp->RemoveObserver(tag); + } + + template + void TestPropCloning(T prop) + { + T prop2 = prop->Clone(); + CPPUNIT_ASSERT_MESSAGE("Test clone pointer", prop.GetPointer() != prop2.GetPointer()); + CPPUNIT_ASSERT_MESSAGE("Test equality of the clone", *prop == *prop2); + } + + template + void TestProperty(const typename T::ValueType &v1, + const typename T::ValueType &v2, + const std::string &strV1, + const std::string &strV2) + { + typename T::Pointer prop = T::New(v1); + MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); + + CPPUNIT_ASSERT_MESSAGE("Test constructor", prop->GetValue() == v1); + std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + strV1 + "]"; + CPPUNIT_ASSERT_MESSAGE(msg, prop->GetValueAsString() == strV1); + + TestPropCloning(prop); + + typename T::Pointer prop2 = T::New(); + prop2->AddObserver(itk::ModifiedEvent(), m_L.m_Cmd.GetPointer()); + CPPUNIT_ASSERT_MESSAGE("Test modified", !m_L.m_Modified); + prop2->SetValue(v2); + CPPUNIT_ASSERT_MESSAGE("Test modified", m_L.Pop()); + CPPUNIT_ASSERT_MESSAGE("Test SetValue()", prop2->GetValue() == v2); + prop2->SetValue(v2); + CPPUNIT_ASSERT_MESSAGE("Test for no modification", !m_L.Pop()); + + TestPropInequality(prop, prop2); + TestPropAssignment(prop, prop2, strV2); + + prop->SetValue(v1); + TestPropPolymorphicAssignment(prop2, prop, strV1); + } - prop2->SetValue(v2); - MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); + void TestBoolProperty_Success() + { + TestProperty(false, true, "0", "1"); + } - TestPropInequality(prop, prop2); - TestPropAssignment(prop, prop2, strV2); + void TestIntProperty_Success() + { + TestProperty(3, 5, "3", "5"); + } - prop->SetValue(v1); - TestPropPolymorphicAssignment(prop2, prop, strV1); -} + void TestFloatProperty_Success() + { + TestProperty(0.3f, -23.5f, "0.3", "-23.5"); + } -void TestGenericProperties() -{ - TestProperty(false, true, "0", "1"); - TestProperty(3, 5, "3", "5"); - TestProperty(0.3f, -23.5f, "0.3", "-23.5"); - TestProperty(64.1f, 2.34f, "64.1", "2.34"); + void TestDoubleProperty_Success() + { + TestProperty(64.1f, 2.34f, "64.1", "2.34"); + } + void TestVector3DProperty_Success() { mitk::Vector3D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; mitk::Vector3D p2; p2[0] = -1.0; p2[1] = 2.0; p2[2] = 3.0; TestProperty(p1, p2, "[2, 3, 4]", "[-1, 2, 3]"); } + void TestPoint3D_Success() { mitk::Point3D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; mitk::Point3D p2; p2[0] = -1.0; p2[1] = 2.0; p2[2] = 3.0; TestProperty(p1, p2, "[2, 3, 4]", "[-1, 2, 3]"); } + void TestPoint4D_Success() { mitk::Point4D p1; p1[0] = 2.0; p1[1] = 3.0; p1[2] = 4.0; p1[3] = -2.0; mitk::Point4D p2; p2[0] = -1.0; p2[1] = 2.0; p2[2] = 3.0; p2[3] = 5.0; TestProperty(p1, p2, "[2, 3, 4, -2]", "[-1, 2, 3, 5]"); } + void TestPoint3I_Success() { mitk::Point3I p1; p1[0] = 2; p1[1] = 3; p1[2] = 4; mitk::Point3I p2; p2[0] = 8; p2[1] = 7; p2[2] = 6; TestProperty(p1, p2, "[2, 3, 4]", "[8, 7, 6]"); } + void TestFloatLookupTable_Success() { mitk::FloatLookupTable lut1; lut1.SetTableValue(1, 0.3f); lut1.SetTableValue(4, 323.7f); mitk::FloatLookupTable lut2; lut2.SetTableValue(6, -0.3f); lut2.SetTableValue(2, 25.7f); TestProperty(lut1, lut2, "[1 -> 0.3, 4 -> 323.7]", "[2 -> 25.7, 6 -> -0.3]"); } + void TestBoolLookupTable_Success() { mitk::BoolLookupTable lut1; lut1.SetTableValue(3, false); lut1.SetTableValue(5, true); mitk::BoolLookupTable lut2; lut2.SetTableValue(1, false); lut2.SetTableValue(2, false); TestProperty(lut1, lut2, "[3 -> 0, 5 -> 1]", "[1 -> 0, 2 -> 0]"); } + void TestIntLookupTable_Success() { mitk::IntLookupTable lut1; lut1.SetTableValue(5, -12); lut1.SetTableValue(7, 3); mitk::IntLookupTable lut2; lut2.SetTableValue(4, -6); lut2.SetTableValue(8, -45); TestProperty(lut1, lut2, "[5 -> -12, 7 -> 3]", "[4 -> -6, 8 -> -45]"); } + void TestStringLookupTable_Success() { mitk::StringLookupTable lut1; lut1.SetTableValue(0, "a"); lut1.SetTableValue(2, "b"); mitk::StringLookupTable lut2; lut2.SetTableValue(0, "a"); lut2.SetTableValue(2, "c"); TestProperty(lut1, lut2, "[0 -> a, 2 -> b]", "[0 -> a, 2 -> c]"); } -} - -void TestAnnotationProperty() -{ - PropertyModifiedListener l; - - std::string label1("Label1"); - mitk::Point3D point1; - point1[0] = 3; - point1[1] = 5; - point1[2] = -4; - std::string str1 = "Label1[3, 5, -4]"; - - std::string label2("Label2"); - mitk::Point3D point2; - point2[0] = -2; - point2[1] = 8; - point2[2] = -4; - std::string str2 = "Label2[-2, 8, -4]"; - - mitk::AnnotationProperty::Pointer prop = mitk::AnnotationProperty::New(label1, point1); - MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); - - MITK_TEST_CONDITION_REQUIRED(prop->GetLabel() == label1 && prop->GetPosition() == point1, "Test constructor"); - std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + str1 + "]"; - MITK_TEST_CONDITION_REQUIRED(prop->GetValueAsString() == str1, msg); - - mitk::AnnotationProperty::Pointer prop2 = mitk::AnnotationProperty::New(); - prop2->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); - MITK_TEST_CONDITION_REQUIRED(!l.m_Modified, "Test not modified"); - prop2->SetLabel(label2); - MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); - prop2->SetPosition(point2); - MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); - MITK_TEST_CONDITION_REQUIRED(prop2->GetLabel() == label2 && prop2->GetPosition() == point2, "Test Setter"); - - prop2->SetLabel(label2); - MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); - prop2->SetPosition(point2); - MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); - - TestPropInequality(prop, prop2); - TestPropAssignment(prop, prop2, str2); - - prop->SetLabel(label1); - prop->SetPosition(point1); - TestPropPolymorphicAssignment(prop2, prop, str1); -} - -void TestClippingProperty() -{ - PropertyModifiedListener l; - - bool enabled1 = true; - mitk::Point3D point1; - point1[0] = 3; - point1[1] = 5; - point1[2] = -4; - mitk::Vector3D vec1; - vec1[0] = 0; - vec1[1] = 2; - vec1[2] = -1; - std::string str1 = "1[3, 5, -4][0, 2, -1]"; - - bool enabled2 = false; - mitk::Point3D point2; - point2[0] = -2; - point2[1] = 8; - point2[2] = -4; - mitk::Vector3D vec2; - vec2[0] = 0; - vec2[1] = 2; - vec2[2] = 4; - std::string str2 = "0[-2, 8, -4][0, 2, 4]"; - - mitk::ClippingProperty::Pointer prop = mitk::ClippingProperty::New(point1, vec1); - MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); - - MITK_TEST_CONDITION_REQUIRED( - prop->GetClippingEnabled() == enabled1 && prop->GetOrigin() == point1 && prop->GetNormal() == vec1, - "Test constructor"); - std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + str1 + "]"; - MITK_TEST_CONDITION_REQUIRED(prop->GetValueAsString() == str1, msg); - - mitk::ClippingProperty::Pointer prop2 = mitk::ClippingProperty::New(); - prop2->AddObserver(itk::ModifiedEvent(), l.m_Cmd.GetPointer()); - MITK_TEST_CONDITION_REQUIRED(!l.m_Modified, "Test not modified"); - prop2->SetClippingEnabled(enabled2); - MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test not modified"); - prop2->SetOrigin(point2); - MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); - prop2->SetNormal(vec2); - MITK_TEST_CONDITION_REQUIRED(l.Pop(), "Test modified"); - - MITK_TEST_CONDITION_REQUIRED( - prop2->GetClippingEnabled() == enabled2 && prop2->GetOrigin() == point2 && prop2->GetNormal() == vec2, - "Test Setter"); - - prop2->SetClippingEnabled(enabled2); - MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); - prop2->SetOrigin(point2); - MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); - prop2->SetNormal(vec2); - MITK_TEST_CONDITION_REQUIRED(!l.Pop(), "Test for no modification"); - - TestPropInequality(prop, prop2); - TestPropAssignment(prop, prop2, str2); - - prop->SetClippingEnabled(enabled1); - prop->SetOrigin(point1); - prop->SetNormal(vec1); - TestPropPolymorphicAssignment(prop2, prop, str1); -} - -int mitkPropertyTest(int /* argc */, char * /*argv*/ []) -{ - MITK_TEST_BEGIN("Testing MITK Properties") - TestGenericProperties(); + void TestAnnotationProperty_Success() + { + std::string label1("Label1"); + mitk::Point3D point1; + point1[0] = 3; + point1[1] = 5; + point1[2] = -4; + std::string str1 = "Label1[3, 5, -4]"; + + std::string label2("Label2"); + mitk::Point3D point2; + point2[0] = -2; + point2[1] = 8; + point2[2] = -4; + std::string str2 = "Label2[-2, 8, -4]"; + + mitk::AnnotationProperty::Pointer prop = mitk::AnnotationProperty::New(label1, point1); + MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); + + CPPUNIT_ASSERT_MESSAGE("Test constructor", prop->GetLabel() == label1 && prop->GetPosition() == point1); + std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + str1 + "]"; + CPPUNIT_ASSERT_MESSAGE(msg, prop->GetValueAsString() == str1); + + mitk::AnnotationProperty::Pointer prop2 = mitk::AnnotationProperty::New(); + prop2->AddObserver(itk::ModifiedEvent(), m_L.m_Cmd.GetPointer()); + CPPUNIT_ASSERT_MESSAGE("Test not modified", !m_L.m_Modified); + prop2->SetLabel(label2); + CPPUNIT_ASSERT_MESSAGE("Test modified", m_L.Pop()); + prop2->SetPosition(point2); + CPPUNIT_ASSERT_MESSAGE("Test modified", m_L.Pop()); + CPPUNIT_ASSERT_MESSAGE("Test Setter", prop2->GetLabel() == label2 && prop2->GetPosition() == point2); + + prop2->SetLabel(label2); + CPPUNIT_ASSERT_MESSAGE("Test for no modification", !m_L.Pop()); + prop2->SetPosition(point2); + CPPUNIT_ASSERT_MESSAGE("Test for no modification", !m_L.Pop()); + + TestPropInequality(prop, prop2); + TestPropAssignment(prop, prop2, str2); + + prop->SetLabel(label1); + prop->SetPosition(point1); + TestPropPolymorphicAssignment(prop2, prop, str1); + } - TestAnnotationProperty(); - TestClippingProperty(); + void TestClippingProperty_Success() + { + bool enabled1 = true; + mitk::Point3D point1; + point1[0] = 3; + point1[1] = 5; + point1[2] = -4; + mitk::Vector3D vec1; + vec1[0] = 0; + vec1[1] = 2; + vec1[2] = -1; + std::string str1 = "1[3, 5, -4][0, 2, -1]"; + + bool enabled2 = false; + mitk::Point3D point2; + point2[0] = -2; + point2[1] = 8; + point2[2] = -4; + mitk::Vector3D vec2; + vec2[0] = 0; + vec2[1] = 2; + vec2[2] = 4; + std::string str2 = "0[-2, 8, -4][0, 2, 4]"; + + mitk::ClippingProperty::Pointer prop = mitk::ClippingProperty::New(point1, vec1); + MITK_TEST_OUTPUT(<< "**** Test [" << prop->GetNameOfClass() << "] ****"); + + CPPUNIT_ASSERT_MESSAGE("Test constructor", + prop->GetClippingEnabled() == enabled1 && prop->GetOrigin() == point1 && prop->GetNormal() == vec1); + std::string msg = std::string("Test GetValueAsString() [") + prop->GetValueAsString() + " == " + str1 + "]"; + CPPUNIT_ASSERT_MESSAGE(msg, prop->GetValueAsString() == str1); + + mitk::ClippingProperty::Pointer prop2 = mitk::ClippingProperty::New(); + prop2->AddObserver(itk::ModifiedEvent(), m_L.m_Cmd.GetPointer()); + CPPUNIT_ASSERT_MESSAGE("Test not modified", !m_L.m_Modified); + prop2->SetClippingEnabled(enabled2); + CPPUNIT_ASSERT_MESSAGE("Test not modified", !m_L.Pop()); + prop2->SetOrigin(point2); + CPPUNIT_ASSERT_MESSAGE("Test modified", m_L.Pop()); + prop2->SetNormal(vec2); + CPPUNIT_ASSERT_MESSAGE("Test modified", m_L.Pop()); + + CPPUNIT_ASSERT_MESSAGE("Test Setter", + prop2->GetClippingEnabled() == enabled2 && prop2->GetOrigin() == point2 && prop2->GetNormal() == vec2); + + prop2->SetClippingEnabled(enabled2); + CPPUNIT_ASSERT_MESSAGE("Test for no modification", !m_L.Pop()); + prop2->SetOrigin(point2); + CPPUNIT_ASSERT_MESSAGE("Test for no modification", !m_L.Pop()); + prop2->SetNormal(vec2); + CPPUNIT_ASSERT_MESSAGE("Test for no modification", !m_L.Pop()); + + TestPropInequality(prop, prop2); + TestPropAssignment(prop, prop2, str2); + + prop->SetClippingEnabled(enabled1); + prop->SetOrigin(point1); + prop->SetNormal(vec1); + TestPropPolymorphicAssignment(prop2, prop, str1); + } - mitk::Color c1; - c1[0] = 0.2; - c1[1] = 0.6; - c1[2] = 0.8; - mitk::Color c2; - c2[0] = 0.2; - c2[1] = 0.4; - c2[2] = 0.1; - TestProperty(c1, c2, "0.2 0.6 0.8", "0.2 0.4 0.1"); + void TestColorProperty_Success() + { + mitk::Color c1; + c1[0] = 0.2; + c1[1] = 0.6; + c1[2] = 0.8; + mitk::Color c2; + c2[0] = 0.2; + c2[1] = 0.4; + c2[2] = 0.1; + TestProperty(c1, c2, "0.2 0.6 0.8", "0.2 0.4 0.1"); + } - mitk::LevelWindow lw1(50, 100); - mitk::LevelWindow lw2(120, 30); - TestProperty(lw1, lw2, "L:50 W:100", "L:120 W:30"); + void TestLevelWindowProperty_Success() + { + mitk::LevelWindow lw1(50, 100); + mitk::LevelWindow lw2(120, 30); + TestProperty(lw1, lw2, "L:50 W:100", "L:120 W:30"); + } + void TestSmartPointerProperty_Success() { itk::Object::Pointer sp1 = itk::Object::New(); itk::Object::Pointer sp2 = itk::Object::New(); // to generate the UIDs, we set the smartpointers mitk::SmartPointerProperty::Pointer spp1 = mitk::SmartPointerProperty::New(sp1.GetPointer()); mitk::SmartPointerProperty::Pointer spp2 = mitk::SmartPointerProperty::New(sp2.GetPointer()); TestProperty(sp1, sp2, spp1->GetReferenceUIDFor(sp1), spp2->GetReferenceUIDFor(sp2)); } - TestProperty("1", "2", "1", "2"); + void TestStringProperty_Success() + { + TestProperty("1", "2", "1", "2"); + } + void TestTransferFunctionProperty_Success() { mitk::TransferFunction::Pointer tf1 = mitk::TransferFunction::New(); mitk::TransferFunction::Pointer tf2 = mitk::TransferFunction::New(); tf2->AddScalarOpacityPoint(0.4, 0.8); std::stringstream ss; ss << tf1; std::string strTF1 = ss.str(); ss.str(""); ss << tf2; std::string strTF2 = ss.str(); TestProperty(tf1, tf2, strTF1, strTF2); } + void TestWeakPointerProperty_Success() { itk::Object::Pointer sp1 = itk::Object::New(); itk::Object::Pointer sp2 = itk::Object::New(); mitk::WeakPointerProperty::ValueType wp1 = sp1.GetPointer(); mitk::WeakPointerProperty::ValueType wp2 = sp2.GetPointer(); std::stringstream ss; ss << sp1.GetPointer(); std::string str1 = ss.str(); ss.str(""); ss << sp2.GetPointer(); std::string str2 = ss.str(); TestProperty(wp1, wp2, str1, str2); } + void TestLookupTablePropertyProperty_Success() { mitk::LookupTable::Pointer lut1 = mitk::LookupTable::New(); lut1->GetVtkLookupTable()->SetTableValue(0, 0.2, 0.3, 0.4); mitk::LookupTable::Pointer lut2 = mitk::LookupTable::New(); lut2->GetVtkLookupTable()->SetTableValue(0, 0.2, 0.4, 0.4); std::stringstream ss; ss << lut1; std::string strLUT1 = ss.str(); ss.str(""); ss << lut2; std::string strLUT2 = ss.str(); TestProperty(lut1, lut2, strLUT1, strLUT2); } +}; +MITK_TEST_SUITE_REGISTRATION(mitkProperty) - MITK_TEST_END() -} diff --git a/Modules/Core/test/mitkTinyXMLTest.cpp b/Modules/Core/test/mitkTinyXMLTest.cpp index db5273b47d..ddd251e473 100644 --- a/Modules/Core/test/mitkTinyXMLTest.cpp +++ b/Modules/Core/test/mitkTinyXMLTest.cpp @@ -1,160 +1,159 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Testing #include "mitkTestFixture.h" #include // std includes #include #include -#include #include // MITK includes #include "mitkStringProperty.h" #include // itksys #include // VTK includes #include // vnl includes #include class mitkTinyXMLTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkTinyXMLTestSuite); MITK_TEST(TestingFunctionSetupWorks_Success); MITK_TEST(TestingReadValueFromSetupDocument_Success); MITK_TEST(TestingReadOutValueWorks_Success); MITK_TEST(TestDoubleValueWriteOut_Success); MITK_TEST(TestDoubleValueWriteOutManyDecimalPlaces_Success); CPPUNIT_TEST_SUITE_END(); private: const std::string m_Filename = itksys::SystemTools::GetCurrentWorkingDirectory() + "/TinyXMLTest.txt"; const std::string m_ElementToStoreAttributeName = "DoubleTest"; const std::string m_AttributeToStoreName = "CommaValue"; TiXmlDocument m_Document; TiXmlElement *m_DoubleTest; double calcPrecision(const unsigned int requiredDecimalPlaces) { return pow(10.0, -1.0 * ((double)requiredDecimalPlaces)); } bool Setup(double valueToWrite) { // 1. create simple document auto decl = new TiXmlDeclaration("1.0", "", ""); // TODO what to write here? encoding? etc.... m_Document.LinkEndChild(decl); auto version = new TiXmlElement("Version"); version->SetAttribute("Writer", __FILE__); version->SetAttribute("CVSRevision", "$Revision: 17055 $"); version->SetAttribute("FileVersion", 1); m_Document.LinkEndChild(version); // 2. store one element containing a double value with potentially many after comma digits. auto vElement = new TiXmlElement(m_ElementToStoreAttributeName); vElement->SetDoubleAttribute(m_AttributeToStoreName, valueToWrite); m_Document.LinkEndChild(vElement); // 3. store in file. return m_Document.SaveFile(m_Filename); } public: void setUp() override {} void tearDown() override {} void TestingFunctionSetupWorks_Success() { CPPUNIT_ASSERT_MESSAGE("Test if Setup correctly writes data to file", Setup(1.0)); } int readValueFromSetupDocument(double &readOutValue) { if (!m_Document.LoadFile(m_Filename)) { CPPUNIT_ASSERT_MESSAGE("Test Setup failed, could not open file", false); return TIXML_NO_ATTRIBUTE; } else { m_DoubleTest = m_Document.FirstChildElement(m_ElementToStoreAttributeName); return m_DoubleTest->QueryDoubleAttribute(m_AttributeToStoreName, &readOutValue); } } void TestingReadValueFromSetupDocument_Success() { if (!m_Document.LoadFile(m_Filename)) { CPPUNIT_ASSERT_MESSAGE("Test Setup failed, could not open file", !m_Document.LoadFile(m_Filename)); } else { m_DoubleTest = m_Document.FirstChildElement(m_ElementToStoreAttributeName); CPPUNIT_ASSERT_MESSAGE("Test Setup could open file", m_DoubleTest != nullptr); } } /** * this first test ensures we can correctly readout values from the * TinyXMLDocument. */ void TestingReadOutValueWorks_Success() { double readValue; CPPUNIT_ASSERT_MESSAGE("checking if readout mechanism works.", TIXML_SUCCESS == readValueFromSetupDocument(readValue)); } void TestDoubleValueWriteOut_Success() { const double valueToWrite = -1.123456; const int validDigitsAfterComma = 6; // indicates the number of valid digits after comma of valueToWrite const double neededPrecision = calcPrecision(validDigitsAfterComma + 1); double readValue; Setup(valueToWrite); readValueFromSetupDocument(readValue); CPPUNIT_ASSERT_MESSAGE("Testing if value valueToWrite equals readValue which was retrieved from TinyXML document", mitk::Equal(valueToWrite, readValue, neededPrecision)); } void TestDoubleValueWriteOutManyDecimalPlaces_Success() { const double valueToWrite = -1.12345678910111; const int validDigitsAfterComma = 14; // indicates the number of valid digits after comma of valueToWrite const double neededPrecision = calcPrecision(validDigitsAfterComma + 1); double readValue; Setup(valueToWrite); readValueFromSetupDocument(readValue); CPPUNIT_ASSERT_MESSAGE("Testing if value valueToWrite equals readValue which was retrieved from TinyXML document", mitk::Equal(valueToWrite, readValue, neededPrecision)); } }; MITK_TEST_SUITE_REGISTRATION(mitkTinyXML) diff --git a/Modules/Core/test/mitkUIDGeneratorTest.cpp b/Modules/Core/test/mitkUIDGeneratorTest.cpp index 84b7f86640..12dd6aa337 100644 --- a/Modules/Core/test/mitkUIDGeneratorTest.cpp +++ b/Modules/Core/test/mitkUIDGeneratorTest.cpp @@ -1,59 +1,65 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ +// Testing +#include "mitkTestFixture.h" +#include "mitkTestingMacros.h" +// std includes +#include +// MITK includes #include "mitkUIDGenerator.h" #include #include #include class mitkUIDGeneratorTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkUIDGeneratorTestSuite); MITK_TEST(UIDGeneratorInstanceRenewalSucceed); MITK_TEST(UIDGeneratorMultipleInstancesSucceed); CPPUNIT_TEST_SUITE_END(); unsigned short m_UidLengthStart = 5; unsigned short m_UidLengthEnd = 20; void UIDGeneratorInstanceRenewalSucceed() { for (auto k = m_UidLengthStart; k < m_UidLengthEnd; ++k) { mitk::UIDGenerator uidGen1("UID_", k); auto uid1_1 = uidGen1.GetUID(); uidGen1 = mitk::UIDGenerator("UID_", k); auto uid2_1 = uidGen1.GetUID(); CPPUNIT_ASSERT_MESSAGE("Different UIDs are not allowed to be equal", uid1_1 != uid2_1); } } void UIDGeneratorMultipleInstancesSucceed() { for (auto k = m_UidLengthStart; k < m_UidLengthEnd; ++k) { mitk::UIDGenerator uidGen1("UID_", k); mitk::UIDGenerator uidGen2("UID_", k); auto uid1_1 = uidGen1.GetUID(); auto uid2_1 = uidGen2.GetUID(); CPPUNIT_ASSERT_MESSAGE("Different UIDs are not allowed to be equal", uid1_1 != uid2_1); } } }; MITK_TEST_SUITE_REGISTRATION(mitkUIDGenerator) diff --git a/Modules/IGTUI/files.cmake b/Modules/IGTUI/files.cmake index 5773331a13..5c6808a6d6 100644 --- a/Modules/IGTUI/files.cmake +++ b/Modules/IGTUI/files.cmake @@ -1,113 +1,112 @@ set(CPP_FILES Qmitk/QmitkTrackingDeviceWidget.cpp Qmitk/QmitkTrackingDeviceConfigurationWidget.cpp Qmitk/QmitkNDIConfigurationWidget.cpp Qmitk/QmitkFiducialRegistrationWidget.cpp Qmitk/QmitkNDIToolDelegate.cpp Qmitk/QmitkNavigationToolManagementWidget.cpp Qmitk/QmitkIGTLoggerWidget.cpp Qmitk/QmitkUpdateTimerWidget.cpp Qmitk/QmitkToolDistanceWidget.cpp Qmitk/QmitkToolTrackingStatusWidget.cpp Qmitk/QmitkTrackingSourcesCheckBoxPanelWidget.cpp Qmitk/QmitkIGTPlayerWidget.cpp Qmitk/QmitkIGTConnectionWidget.cpp Qmitk/QmitkToolSelectionWidget.cpp Qmitk/QmitkNavigationToolCreationWidget.cpp Qmitk/QmitkNavigationDataSourceSelectionWidget.cpp Qmitk/QmitkInteractiveTransformationWidget.cpp Qmitk/QmitkNavigationToolStorageSelectionWidget.cpp Qmitk/QmitkNavigationDataPlayerControlWidget.cpp Qmitk/QmitkNavigationDataSequentialPlayerControlWidget.cpp Qmitk/QmitkNDIAuroraWidget.cpp Qmitk/QmitkNDIPolarisWidget.cpp Qmitk/QmitkMicronTrackerWidget.cpp Qmitk/QmitkNPOptitrackWidget.cpp Qmitk/QmitkVirtualTrackerWidget.cpp Qmitk/QmitkOpenIGTLinkWidget.cpp Qmitk/mitkTrackingDeviceWidgetCollection.cpp Qmitk/QmitkTrackingDeviceConfigurationWidgetScanPortsWorker.cpp Qmitk/QmitkTrackingDeviceConfigurationWidgetConnectionWorker.cpp Qmitk/QmitkNDIAbstractDeviceWidget.cpp Qmitk/QmitkAbstractTrackingDeviceWidget.cpp Qmitk/QmitkIGTCommonHelper.cpp ) set(UI_FILES Qmitk/QmitkNavigationToolManagementWidgetControls.ui Qmitk/QmitkTrackingDeviceConfigurationWidgetControls.ui Qmitk/QmitkNDIConfigurationWidget.ui Qmitk/QmitkFiducialRegistrationWidget.ui Qmitk/QmitkIGTLoggerWidgetControls.ui Qmitk/QmitkUpdateTimerWidgetControls.ui Qmitk/QmitkToolDistanceWidgetControls.ui Qmitk/QmitkToolTrackingStatusWidgetControls.ui Qmitk/QmitkTrackingSourcesCheckBoxPanelWidgetControls.ui Qmitk/QmitkIGTPlayerWidgetControls.ui Qmitk/QmitkIGTConnectionWidgetControls.ui Qmitk/QmitkToolSelectionWidgetControls.ui Qmitk/QmitkNavigationToolCreationWidget.ui Qmitk/QmitkNavigationDataSourceSelectionWidgetControls.ui Qmitk/QmitkInteractiveTransformationWidgetControls.ui Qmitk/QmitkNavigationToolStorageSelectionWidgetControls.ui Qmitk/QmitkNavigationDataPlayerControlWidget.ui Qmitk/QmitkNavigationDataSequentialPlayerControlWidget.ui Qmitk/QmitkNDIAuroraWidget.ui Qmitk/QmitkNDIPolarisWidget.ui Qmitk/QmitkMicronTrackerWidget.ui Qmitk/QmitkNPOptitrackWidget.ui Qmitk/QmitkVirtualTrackerWidget.ui Qmitk/QmitkOpenIGTLinkWidget.ui ) set(MOC_H_FILES Qmitk/QmitkNavigationToolManagementWidget.h Qmitk/QmitkTrackingDeviceWidget.h Qmitk/QmitkTrackingDeviceConfigurationWidget.h Qmitk/QmitkNDIConfigurationWidget.h Qmitk/QmitkFiducialRegistrationWidget.h Qmitk/QmitkNDIToolDelegate.h Qmitk/QmitkIGTLoggerWidget.h Qmitk/QmitkUpdateTimerWidget.h Qmitk/QmitkToolDistanceWidget.h Qmitk/QmitkToolTrackingStatusWidget.h Qmitk/QmitkTrackingSourcesCheckBoxPanelWidget.h Qmitk/QmitkIGTPlayerWidget.h Qmitk/QmitkIGTConnectionWidget.h Qmitk/QmitkToolSelectionWidget.h Qmitk/QmitkNavigationToolCreationWidget.h Qmitk/QmitkNavigationDataSourceSelectionWidget.h Qmitk/QmitkInteractiveTransformationWidget.h Qmitk/QmitkNavigationToolStorageSelectionWidget.h Qmitk/QmitkNavigationDataPlayerControlWidget.h Qmitk/QmitkNavigationDataSequentialPlayerControlWidget.h Qmitk/QmitkNDIAuroraWidget.h Qmitk/QmitkNDIPolarisWidget.h Qmitk/QmitkMicronTrackerWidget.h Qmitk/QmitkNPOptitrackWidget.h Qmitk/QmitkVirtualTrackerWidget.h Qmitk/QmitkOpenIGTLinkWidget.h Qmitk/QmitkTrackingDeviceConfigurationWidgetScanPortsWorker.h Qmitk/QmitkTrackingDeviceConfigurationWidgetConnectionWorker.h Qmitk/QmitkNDIAbstractDeviceWidget.h Qmitk/QmitkAbstractTrackingDeviceWidget.h - Qmitk/QmitkIGTCommonHelper.h ) if(MITK_USE_POLHEMUS_TRACKER) set(CPP_FILES ${CPP_FILES} Qmitk/QmitkPolhemusTrackerWidget.cpp) set(UI_FILES ${UI_FILES} Qmitk/QmitkPolhemusTrackerWidget.ui) set(MOC_H_FILES ${MOC_H_FILES} Qmitk/QmitkPolhemusTrackerWidget.h) endif(MITK_USE_POLHEMUS_TRACKER) set(QRC_FILES resources/IGTUI.qrc ) diff --git a/Modules/MapperExt/test/CMakeLists.txt b/Modules/MapperExt/test/CMakeLists.txt index 73f9b305cf..bcc0538ea2 100644 --- a/Modules/MapperExt/test/CMakeLists.txt +++ b/Modules/MapperExt/test/CMakeLists.txt @@ -1,5 +1,5 @@ mitk_create_module_tests() -if(TARGET ${TESTDRIVER} AND MITK_ENABLE_RENDERING_TESTING) +if(TARGET ${TESTDRIVER}) set_property(TEST mitkSplineVtkMapper3DTest PROPERTY RUN_SERIAL TRUE) endif() diff --git a/Modules/MapperExt/test/files.cmake b/Modules/MapperExt/test/files.cmake index 6e0a4d2dcf..ace07fe6e0 100644 --- a/Modules/MapperExt/test/files.cmake +++ b/Modules/MapperExt/test/files.cmake @@ -1,8 +1,3 @@ set(MODULE_TESTS + mitkSplineVtkMapper3DTest.cpp ) - -if(MITK_ENABLE_RENDERING_TESTING) - list(APPEND MODULE_TESTS - mitkSplineVtkMapper3DTest.cpp - ) -endif() diff --git a/Modules/PhotoacousticsLib/test/files.cmake b/Modules/PhotoacousticsLib/test/files.cmake index c6a200ad69..c36e74635f 100644 --- a/Modules/PhotoacousticsLib/test/files.cmake +++ b/Modules/PhotoacousticsLib/test/files.cmake @@ -1,40 +1,40 @@ set(MODULE_TESTS # IMPORTANT: If you plan to deactivate / comment out a test please write a bug number to the commented out line of code. # # Example: #mitkMyTest #this test is commented out because of bug 12345 # # It is important that the bug is open and that the test will be activated again before the bug is closed. This assures that # no test is forgotten after it was commented out. If there is no bug for your current problem, please add a new one and # mark it as critical. ################## ON THE FENCE TESTS ################################################# # none ################## DISABLED TESTS ##################################################### # mitkMCThreadHandlerTest.cpp #Timing issue on VMs # mitkPhotoacousticIOTest.cpp #Not suitable for large scale testing as it performs IO actions. ################# RUNNING TESTS ####################################################### mitkSlicedVolumeGeneratorTest.cpp mitkPhotoacousticTissueGeneratorTest.cpp mitkPhotoacousticVectorTest.cpp mitkPhotoacoustic3dVolumeTest.cpp mitkPhotoacousticVolumeTest.cpp mitkPhotoacousticVesselTreeTest.cpp mitkMcxyzXmlTest.cpp mitkPhotoacousticComposedVolumeTest.cpp mitkPhotoacousticNoiseGeneratorTest.cpp mitkSimulationBatchGeneratorTest.cpp mitkPropertyCalculatorTest.cpp - mitkSpectralUnmixingTest.cpp + # mitkSpectralUnmixingTest.cpp (See T27024) mitkPhotoacousticVesselMeanderStrategyTest.cpp mitkPhotoacousticVesselTest.cpp ) set(RESOURCE_FILES pointsource.xml circlesource.xml rectanglesource.xml twopointsources.xml allsources.xml ) diff --git a/Modules/PlanarFigure/test/CMakeLists.txt b/Modules/PlanarFigure/test/CMakeLists.txt index 55f7454d12..d6f5cf2a16 100644 --- a/Modules/PlanarFigure/test/CMakeLists.txt +++ b/Modules/PlanarFigure/test/CMakeLists.txt @@ -1,155 +1,153 @@ MITK_CREATE_MODULE_TESTS() if(TARGET ${TESTDRIVER}) mitk_use_modules(TARGET ${TESTDRIVER} PACKAGES VTK|vtkTestingRendering) set(testcaseBasename mitkViewportRenderingTest) # set verbose to 1 to get a list of all defined test cases during CMake configuration set(verbose 0) # viewportTest(): # # 1. Sets up a scene with a DICOM image, several planar figures, an STL file # 2. Modifies the viewport of the VTK renderer to only a part of the render window # 3. Compares the rendering result against an expected version # # Parameters determine the size and position of the viewport and the render window # The expected result is mitkViewportRenderingTest_${testPostfix}.png # function(viewportTest testPostfix # postfix to uniquely identify the test case rwWidth rwHeight # "rw" = render window vpLeft vpBottom vpWidth vpHeight # "vp" = viewport # list of images/files for visualization ) set(data ${ARGN}) # use all ADDITIONAL parameters after vpHeight as filenames # transform the input parameters in required test parameters math(EXPR vpRight "${vpLeft} + ${vpWidth}") math(EXPR vpTop "${vpBottom} + ${vpHeight}") #message(STATUS "Testing viewport of ${vpWidth}x${vpHeight} at ${vpLeft},${vpBottom} in render window of size ${rwWidth}x${rwHeight} ('${testPostfix}')") # add the actual test mitkAddCustomModuleTest( mitkViewportRenderingTest_${testPostfix} mitkViewportRenderingTest ${rwWidth} ${rwHeight} ${vpLeft} ${vpBottom} ${vpRight} ${vpTop} ${data} -V ${MITK_DATA_DIR}/RenderingTestData/viewport/mitkViewportRenderingTest_${testPostfix}.png #corresponding reference screenshot ) set_property(TEST mitkViewportRenderingTest_${testPostfix} PROPERTY RUN_SERIAL TRUE) endfunction() function(getFirstCharacter string charVar) string(SUBSTRING ${string} 0 1 c) set(${charVar} ${c} PARENT_SCOPE) endfunction() # The following lines loop over several variations of aspect ratios for # - render window # - a viewport within this render window # - an input image (defines the input world geometry) # --------------------------------------------------------------------- # # Render window # - Square # - Landscape # - Portrait # # Viewport # - Square # - Landscape # - Portrait # # World / Image # - Square # - Landscape # - Portrait # - if(MITK_ENABLE_RENDERING_TESTING) ### since the rendering test's do not run in ubuntu, yet, we build them only for other systems or if the user explicitly sets the variable MITK_ENABLE_RENDERING_TESTING foreach(renderWindowAspect Square Landscape Portrait) foreach(viewportAspect Square Landscape Portrait) foreach(worldAspect Square Landscape Portrait) getFirstCharacter(${renderWindowAspect} renderWindowAspectSymbol) getFirstCharacter(${viewportAspect} viewportAspectSymbol) getFirstCharacter(${worldAspect} worldAspectSymbol) # construct test case name from various aspect ratios set(testCaseShortname "r${renderWindowAspectSymbol}v${viewportAspectSymbol}w${worldAspectSymbol}") # construct test image name from aspect ratio set(testImage ${MITK_DATA_DIR}/RenderingTestData/viewport/input_${worldAspect}/SCSFREN.dcm) # nice DICOM name encoding and gray value test image set(testObjects ${MITK_DATA_DIR}/RenderingTestData/PlanarFigures/Line1.pf ${MITK_DATA_DIR}/RenderingTestData/PlanarFigures/Path1.pf ${MITK_DATA_DIR}/RenderingTestData/PlanarFigures/FourPointAngle1.pf ${MITK_DATA_DIR}/RenderingTestData/PlanarFigures/Rectangle1.pf ${MITK_DATA_DIR}/binary.stl ) # render window size if (renderWindowAspect STREQUAL Landscape) set(renderWindowWidth 600) else() set(renderWindowWidth 500) endif() if (renderWindowAspect STREQUAL Portrait) set(renderWindowHeight 600) else() set(renderWindowHeight 500) endif() # viewport size if (viewportAspect STREQUAL Landscape) set(viewportWidth 450) else() set(viewportWidth 300) endif() if (viewportAspect STREQUAL Portrait) set(viewportHeight 450) else() set(viewportHeight 300) endif() # world size if (worldAspect STREQUAL Portrait) set(worldWidth 300) set(worldHeight 420) elseif (worldAspect STREQUAL Landscape) set(worldWidth 420) set(worldHeight 300) else() set(worldWidth 512) set(worldHeight 512) endif() # Summary set(viewportX 30) set(viewportY 45) if (verbose) message(STATUS "(${testCaseShortname}) " "Render window ${renderWindowAspect} (${renderWindowWidth}x${renderWindowHeight}), " "Viewport ${viewportAspect} (${viewportWidth}x${viewportHeight}+${viewportX}+${viewportY}), " "World ${worldAspect} (${worldWidth}x${worldHeight})" ) endif() viewPortTest(${testCaseShortname} ${renderWindowWidth} ${renderWindowHeight} ${viewportX} ${viewportY} ${viewportWidth} ${viewportHeight} ${testImage} ${testObjects}) endforeach() endforeach() endforeach() - endif() # endif MITK_ENABLE_RENDERING_TESTING endif() # endif TARGET ${TESTDRIVER} diff --git a/Modules/PlanarFigure/test/files.cmake b/Modules/PlanarFigure/test/files.cmake index 5644cbb13b..7cccdb7726 100644 --- a/Modules/PlanarFigure/test/files.cmake +++ b/Modules/PlanarFigure/test/files.cmake @@ -1,18 +1,12 @@ set(MODULE_TESTS mitkPlanarCrossTest.cpp mitkPlanarPolygonTest.cpp mitkPlanarSubdivisionPolygonTest.cpp mitkPlanarFigureIOTest.cpp mitkPlanarArrowTest.cpp + mitkPlanarFigureInteractionTest.cpp ) set(MODULE_CUSTOM_TESTS mitkViewportRenderingTest.cpp ) - -if(MITK_ENABLE_RENDERING_TESTING) #since mitkInteractionTestHelper is currently creating a vtkRenderWindow -set(MODULE_TESTS - ${MODULE_TESTS} - mitkPlanarFigureInteractionTest.cpp -) -endif() diff --git a/Modules/QtWidgets/files.cmake b/Modules/QtWidgets/files.cmake index f0e3cf0a82..970d05401a 100644 --- a/Modules/QtWidgets/files.cmake +++ b/Modules/QtWidgets/files.cmake @@ -1,133 +1,135 @@ file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*") set(CPP_FILES QmitkAbstractDataStorageModel.cpp QmitkAbstractMultiWidget.cpp QmitkApplicationCursor.cpp QmitkDataStorageComboBox.cpp QmitkDataStorageDefaultListModel.cpp QmitkDataStorageHistoryModel.cpp QmitkDataStorageListModel.cpp QmitkDataStorageTableModel.cpp QmitkDataStorageSimpleTreeModel.cpp QmitkDataStorageTreeModel.cpp QmitkDataStorageTreeModelInternalItem.cpp QmitkDnDDataNodeWidget.cpp QmitkFileReaderOptionsDialog.cpp QmitkFileReaderWriterOptionsWidget.cpp QmitkFileWriterOptionsDialog.cpp QmitkInteractionSchemeToolBar.cpp QmitkIOUtil.cpp QmitkLevelWindowPresetDefinitionDialog.cpp QmitkLevelWindowRangeChangeDialog.cpp QmitkLevelWindowWidgetContextMenu.cpp QmitkLevelWindowWidget.cpp QmitkLineEditLevelWindowWidget.cpp QmitkMemoryUsageIndicatorView.cpp QmitkMouseModeSwitcher.cpp QmitkMimeTypes.cpp QmitkMultiWidgetConfigurationToolBar.cpp QmitkMultiWidgetLayoutManager.cpp QmitkMultiWidgetLayoutSelectionWidget.cpp QmitkNodeDescriptor.cpp QmitkColoredNodeDescriptor.cpp QmitkNodeDescriptorManager.cpp QmitkProgressBar.cpp QmitkPropertiesTableEditor.cpp QmitkPropertiesTableModel.cpp QmitkPropertyDelegate.cpp QmitkRegisterClasses.cpp QmitkRenderingManager.cpp QmitkRenderingManagerFactory.cpp QmitkRenderWindow.cpp QmitkRenderWindowMenu.cpp QmitkRenderWindowWidget.cpp QmitkServiceListWidget.cpp QmitkSliderLevelWindowWidget.cpp QmitkStdMultiWidget.cpp QmitkMxNMultiWidget.cpp QmitkDataStorageComboBoxWithSelectNone.cpp QmitkDataStorageFilterProxyModel.cpp QmitkPropertyItem.cpp QmitkPropertyItemDelegate.cpp QmitkPropertyItemModel.cpp QmitkStyleManager.cpp QmitkAbstractDataStorageInspector.cpp + QmitkDataStorageFavoriteNodesInspector.cpp QmitkDataStorageListInspector.cpp QmitkDataStorageTreeInspector.cpp QmitkDataStorageSelectionHistoryInspector.cpp QmitkModelViewSelectionConnector.cpp mitkIDataStorageInspectorProvider.cpp mitkQtWidgetsActivator.cpp mitkDataStorageInspectorGenerator.cpp QmitkOverlayWidget.cpp QmitkNodeDetailsDialog.cpp ) set(MOC_H_FILES include/QmitkAbstractDataStorageModel.h include/QmitkAbstractMultiWidget.h include/QmitkDataStorageComboBox.h include/QmitkDataStorageTableModel.h include/QmitkDataStorageTreeModel.h include/QmitkDataStorageSimpleTreeModel.h include/QmitkDataStorageDefaultListModel.h include/QmitkDnDDataNodeWidget.h include/QmitkFileReaderOptionsDialog.h include/QmitkFileReaderWriterOptionsWidget.h include/QmitkFileWriterOptionsDialog.h include/QmitkInteractionSchemeToolBar.h include/QmitkLevelWindowPresetDefinitionDialog.h include/QmitkLevelWindowRangeChangeDialog.h include/QmitkLevelWindowWidgetContextMenu.h include/QmitkLevelWindowWidget.h include/QmitkLineEditLevelWindowWidget.h include/QmitkMemoryUsageIndicatorView.h include/QmitkMouseModeSwitcher.h include/QmitkMultiWidgetConfigurationToolBar.h include/QmitkMultiWidgetLayoutManager.h include/QmitkMultiWidgetLayoutSelectionWidget.h include/QmitkNodeDescriptor.h include/QmitkColoredNodeDescriptor.h include/QmitkNodeDescriptorManager.h include/QmitkProgressBar.h include/QmitkPropertiesTableEditor.h include/QmitkPropertyDelegate.h include/QmitkRenderingManager.h include/QmitkRenderWindow.h include/QmitkRenderWindowMenu.h include/QmitkRenderWindowWidget.h include/QmitkServiceListWidget.h include/QmitkSliderLevelWindowWidget.h include/QmitkStdMultiWidget.h include/QmitkMxNMultiWidget.h include/QmitkDataStorageComboBoxWithSelectNone.h include/QmitkPropertyItemDelegate.h include/QmitkPropertyItemModel.h - include/QmitkDataStorageListInspector.h include/QmitkAbstractDataStorageInspector.h + include/QmitkDataStorageFavoriteNodesInspector.h + include/QmitkDataStorageListInspector.h include/QmitkDataStorageTreeInspector.h include/QmitkDataStorageHistoryModel.h include/QmitkDataStorageSelectionHistoryInspector.h include/QmitkModelViewSelectionConnector.h include/QmitkOverlayWidget.h include/QmitkNodeDetailsDialog.h ) set(UI_FILES src/QmitkFileReaderOptionsDialog.ui src/QmitkFileWriterOptionsDialog.ui src/QmitkLevelWindowPresetDefinition.ui src/QmitkLevelWindowWidget.ui src/QmitkLevelWindowRangeChange.ui src/QmitkMemoryUsageIndicator.ui src/QmitkMultiWidgetLayoutSelectionWidget.ui src/QmitkServiceListWidgetControls.ui src/QmitkDataStorageListInspector.ui src/QmitkDataStorageTreeInspector.ui src/QmitkDataStorageSelectionHistoryInspector.ui ) set(QRC_FILES resource/Qmitk.qrc ) diff --git a/Modules/QtWidgets/include/QmitkAbstractDataStorageInspector.h b/Modules/QtWidgets/include/QmitkAbstractDataStorageInspector.h index 9c2100f766..1f0fc6c9e3 100644 --- a/Modules/QtWidgets/include/QmitkAbstractDataStorageInspector.h +++ b/Modules/QtWidgets/include/QmitkAbstractDataStorageInspector.h @@ -1,127 +1,129 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKABSTRACTDATASTORAGEINSPECTOR_H #define QMITKABSTRACTDATASTORAGEINSPECTOR_H #include #include // mitk core #include #include // qt #include class QAbstractItemVew; /** -* @brief This abstract class is a convinient base class for easy implementation of widgets that +* @brief This abstract class is a convenient base class for easy implementation of widgets that * offer a specific view onto a given DataStorage instance to inspect its contents. * One may also get the selection in this inspector of the data storage. */ class MITKQTWIDGETS_EXPORT QmitkAbstractDataStorageInspector : public QWidget { Q_OBJECT public: + ~QmitkAbstractDataStorageInspector() override; /** * @brief Sets the data storage that will be used /monitored by the widget. * * @param dataStorage A pointer to the data storage to set. */ void SetDataStorage(mitk::DataStorage* dataStorage); /** * @brief Sets the node predicate and updates the widget, according to the node predicate. * * @param nodePredicate A pointer to node predicate. */ virtual void SetNodePredicate(mitk::NodePredicateBase* nodePredicate); mitk::NodePredicateBase* GetNodePredicate() const; using NodeList = QList; /** Returns the list of currently selected nodes.*/ NodeList GetSelectedNodes() const; /** Returns an pointer to the view that is used in the inspector to show the content.*/ virtual QAbstractItemView* GetView() = 0; virtual const QAbstractItemView* GetView() const = 0; /** Returns the setting of the internal connector. It can be changed by SetSelectOnlyVisibleNodes()*/ bool GetSelectOnlyVisibleNodes() const; using SelectionMode = QAbstractItemView::SelectionMode; + /** Sets the selection mode of the inspector.*/ virtual void SetSelectionMode(SelectionMode mode) = 0; virtual SelectionMode GetSelectionMode() const = 0; Q_SIGNALS: /** * @brief A signal that will be emitted if the selected node has changed. * * @param nodes A list of data nodes that are newly selected. */ void CurrentSelectionChanged(NodeList nodes); public Q_SLOTS: /** * @brief Change the selection modus of the item view's selection model. * * If true, an incoming selection will be filtered (reduced) to only those nodes that are visible by the current view. * An outgoing selection can then at most contain the filtered nodes. * If false, the incoming non-visible selection will be stored and later added to the outgoing selection, * to include the original selection that could not be modified. * The part of the original selection, that is non-visible are the nodes that are not * * @param selectOnlyVisibleNodes The bool value to define the selection modus. */ void SetSelectOnlyVisibleNodes(bool selectOnlyVisibleNodes); /** * @brief Transform a list of data nodes into a model selection and set this as a new selection of the * selection model of the private member item view. * * The function filters the given list of nodes according to the 'm_SelectOnlyVisibleNodes' member variable. If * necessary, the non-visible nodes are stored. This is done if 'm_SelectOnlyVisibleNodes' is false: In this case * the selection may be filtered and only a subset of the selected nodes may be visible and therefore (de-)selectable * in the data storage viewer. By storing the non-visible nodes it is possible to send the new, modified selection * but also include the selected nodes from the original selection that could not be modified (see 'SetSelectOnlyVisibleNodes'). * * @param nodes A list of data nodes that should be newly selected. */ void SetCurrentSelection(NodeList selectedNodes); protected Q_SLOTS: void OnSelectionChanged(NodeList selectedNodes); protected: /** Helper function is called if data storage or predicate is changed to (re) initialize the widget correctly. Implement the function in derived classes.*/ virtual void Initialize() = 0; mitk::WeakPointer m_DataStorage; mitk::NodePredicateBase::Pointer m_NodePredicate; std::unique_ptr m_Connector; QmitkAbstractDataStorageInspector(QWidget* parent = nullptr); }; #endif // QMITKABSTRACTDATASTORAGEMODEL_H diff --git a/Modules/QtWidgets/include/QmitkDataStorageFavoriteNodesInspector.h b/Modules/QtWidgets/include/QmitkDataStorageFavoriteNodesInspector.h new file mode 100644 index 0000000000..53a1c49a4f --- /dev/null +++ b/Modules/QtWidgets/include/QmitkDataStorageFavoriteNodesInspector.h @@ -0,0 +1,53 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#ifndef QMITKDATASTORAGEFAVORITENODESINSPECTOR_H +#define QMITKDATASTORAGEFAVORITENODESINSPECTOR_H + +#include + +#include + +#include "mitkNodePredicateProperty.h" + +/* +* @brief This is an inspector that offers a simple list view on favorite nodes of a data storage. +*/ +class MITKQTWIDGETS_EXPORT QmitkDataStorageFavoriteNodesInspector : public QmitkDataStorageListInspector +{ + Q_OBJECT + +public: + + QmitkDataStorageFavoriteNodesInspector(QWidget* parent = nullptr); + + /** + * @brief Overrides the corresponding function of QmitkAbstractDataStorageInspector: + * The custom favorite nodes predicate is added to the parameter predicate + * which results in a combined node predicate that always filters nodes according + * to their favorite-property-state. + * + * @param nodePredicate A pointer to a node predicate. + */ + void SetNodePredicate(mitk::NodePredicateBase* nodePredicate) override; + +protected Q_SLOTS: + + void OnFavoriteNodesButtonClicked(); + +private: + + mitk::NodePredicateProperty::Pointer m_FavoriteNodeSelectionPredicate; + +}; + +#endif // QMITKDATASTORAGEFAVORITENODESINSPECTOR_H diff --git a/Modules/QtWidgets/src/QmitkDataStorageDefaultListModel.cpp b/Modules/QtWidgets/src/QmitkDataStorageDefaultListModel.cpp index 66b4b31d54..e73950da81 100644 --- a/Modules/QtWidgets/src/QmitkDataStorageDefaultListModel.cpp +++ b/Modules/QtWidgets/src/QmitkDataStorageDefaultListModel.cpp @@ -1,168 +1,178 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include // qt widgets module #include "QmitkCustomVariants.h" #include "QmitkEnums.h" #include "QmitkNodeDescriptorManager.h" QmitkDataStorageDefaultListModel::QmitkDataStorageDefaultListModel(QObject *parent) : QmitkAbstractDataStorageModel(parent) { } void QmitkDataStorageDefaultListModel::DataStorageChanged() { UpdateModelData(); } void QmitkDataStorageDefaultListModel::NodePredicateChanged() { UpdateModelData(); } void QmitkDataStorageDefaultListModel::NodeAdded(const mitk::DataNode* /*node*/) { UpdateModelData(); } -void QmitkDataStorageDefaultListModel::NodeChanged(const mitk::DataNode* /*node*/) +void QmitkDataStorageDefaultListModel::NodeChanged(const mitk::DataNode* node) { - // nothing here, since the "'NodeChanged'-event is currently sent far too often - //UpdateModelData(); + // since the "NodeChanged" event is sent quite often, we check here, if it is relevant for this model + if (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node)) + { + UpdateModelData(); + return; + } + + // not relevant - need to check if we have to remove it + if (std::find(m_DataNodes.begin(), m_DataNodes.end(), node) != m_DataNodes.end()) + { + UpdateModelData(); + } } void QmitkDataStorageDefaultListModel::NodeRemoved(const mitk::DataNode* /*node*/) { UpdateModelData(); } QModelIndex QmitkDataStorageDefaultListModel::index(int row, int column, const QModelIndex &parent) const { bool hasIndex = this->hasIndex(row, column, parent); if (hasIndex) { return this->createIndex(row, column); } return QModelIndex(); } QModelIndex QmitkDataStorageDefaultListModel::parent(const QModelIndex &/*child*/) const { return QModelIndex(); } int QmitkDataStorageDefaultListModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return m_DataNodes.size(); } int QmitkDataStorageDefaultListModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return 1; } QVariant QmitkDataStorageDefaultListModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.model() != this) { return QVariant(); } if(index.row() < 0 || index.row() >= static_cast(m_DataNodes.size())) { return QVariant(); } mitk::DataNode::Pointer dataNode = m_DataNodes.at(index.row()); QString nodeName = QString::fromStdString(dataNode->GetName()); if (nodeName.isEmpty()) nodeName = "unnamed"; if (role == Qt::DisplayRole) return nodeName; else if (role == Qt::ToolTipRole) return nodeName; else if (role == Qt::DecorationRole) { QmitkNodeDescriptor *nodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(dataNode); return nodeDescriptor->GetIcon(dataNode); } else if (role == QmitkDataNodeRole) { return QVariant::fromValue(mitk::DataNode::Pointer(dataNode)); } else if (role == QmitkDataNodeRawPointerRole) { return QVariant::fromValue(dataNode); } return QVariant(); } QVariant QmitkDataStorageDefaultListModel::headerData(int /*section*/, Qt::Orientation /*orientation*/, int /*role*/) const { return QVariant(tr("Nodes")); } Qt::ItemFlags QmitkDataStorageDefaultListModel::flags(const QModelIndex &index) const { if (index.isValid() && index.model() == this) { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } return Qt::NoItemFlags; } void QmitkDataStorageDefaultListModel::UpdateModelData() { mitk::DataStorage::SetOfObjects::ConstPointer dataNodes; if (!m_DataStorage.IsExpired()) { auto dataStorage = m_DataStorage.Lock(); if (m_NodePredicate.IsNotNull()) { dataNodes = dataStorage->GetSubset(m_NodePredicate); } else { dataNodes = dataStorage->GetAll(); } } // update the model, so that it will be filled with the nodes of the new data storage beginResetModel(); m_DataNodes.clear(); // add all (filtered) nodes to the vector of nodes if (dataNodes != nullptr) { for (auto& node : *dataNodes) { m_DataNodes.push_back(node); } } endResetModel(); } diff --git a/Modules/QtWidgets/src/QmitkDataStorageFavoriteNodesInspector.cpp b/Modules/QtWidgets/src/QmitkDataStorageFavoriteNodesInspector.cpp new file mode 100644 index 0000000000..d3e059bbb3 --- /dev/null +++ b/Modules/QtWidgets/src/QmitkDataStorageFavoriteNodesInspector.cpp @@ -0,0 +1,50 @@ +/*============================================================================ + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center (DKFZ) +All rights reserved. + +Use of this source code is governed by a 3-clause BSD license that can be +found in the LICENSE file. + +============================================================================*/ + +#include + +#include + +#include "mitkNodePredicateAnd.h" + +#include "QPushButton" + +QmitkDataStorageFavoriteNodesInspector::QmitkDataStorageFavoriteNodesInspector(QWidget* parent/* = nullptr*/) + : QmitkDataStorageListInspector(parent) +{ + auto favoriteNodesButton = new QPushButton("Remove selection from favorites", parent); + QmitkDataStorageListInspector::m_Controls.verticalLayout->addWidget(favoriteNodesButton, 0, Qt::AlignRight); + + m_FavoriteNodeSelectionPredicate = mitk::NodePredicateProperty::New("org.mitk.selection.favorite", mitk::BoolProperty::New(true)); + m_NodePredicate = m_FavoriteNodeSelectionPredicate; + + connect(favoriteNodesButton, &QPushButton::clicked, this, &QmitkDataStorageFavoriteNodesInspector::OnFavoriteNodesButtonClicked); +} + +void QmitkDataStorageFavoriteNodesInspector::SetNodePredicate(mitk::NodePredicateBase* nodePredicate) +{ + mitk::NodePredicateAnd::Pointer combinedPredicate = mitk::NodePredicateAnd::New(); + + combinedPredicate->AddPredicate(m_FavoriteNodeSelectionPredicate); + combinedPredicate->AddPredicate(nodePredicate); + + QmitkDataStorageListInspector::SetNodePredicate(combinedPredicate); +} + +void QmitkDataStorageFavoriteNodesInspector::OnFavoriteNodesButtonClicked() +{ + auto selectedNodes = GetSelectedNodes(); + for (auto node : selectedNodes) + { + node->SetBoolProperty("org.mitk.selection.favorite", false); + } +} diff --git a/Modules/QtWidgets/src/QmitkLevelWindowPresetDefinitionDialog.cpp b/Modules/QtWidgets/src/QmitkLevelWindowPresetDefinitionDialog.cpp index e83cf30a06..602193fd54 100644 --- a/Modules/QtWidgets/src/QmitkLevelWindowPresetDefinitionDialog.cpp +++ b/Modules/QtWidgets/src/QmitkLevelWindowPresetDefinitionDialog.cpp @@ -1,321 +1,323 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkLevelWindowPresetDefinitionDialog.h" #include #include #include QmitkLevelWindowPresetDefinitionDialog::QmitkLevelWindowPresetDefinitionDialog(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f), m_TableModel(nullptr), m_SortModel(this) { this->setupUi(this); QObject::connect(addButton, SIGNAL(clicked()), this, SLOT(addPreset())); QObject::connect(removeButton, SIGNAL(clicked()), this, SLOT(removePreset())); QObject::connect(changeButton, SIGNAL(clicked()), this, SLOT(changePreset())); QObject::connect(presetView->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(sortPresets(int))); presetView->verticalHeader()->setVisible(false); presetView->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed); presetView->setModel(&m_SortModel); } QmitkLevelWindowPresetDefinitionDialog::~QmitkLevelWindowPresetDefinitionDialog() { delete m_TableModel; } void QmitkLevelWindowPresetDefinitionDialog::sortPresets(int index) { static Qt::SortOrder order[3] = {Qt::AscendingOrder}; presetView->sortByColumn(index, order[index]); if (order[index] == Qt::AscendingOrder) order[index] = Qt::DescendingOrder; else order[index] = Qt::AscendingOrder; } void QmitkLevelWindowPresetDefinitionDialog::resizeEvent(QResizeEvent *event) { QDialog::resizeEvent(event); this->resizeColumns(); } void QmitkLevelWindowPresetDefinitionDialog::showEvent(QShowEvent *event) { this->resizeColumns(); QDialog::showEvent(event); } void QmitkLevelWindowPresetDefinitionDialog::resizeColumns() { int width = presetView->viewport()->size().width() - presetView->columnWidth(1) - presetView->columnWidth(2); if (width < 50) width = 50; presetView->setColumnWidth(0, width); } void QmitkLevelWindowPresetDefinitionDialog::addPreset() { std::string name(presetnameLineEdit->text().toStdString()); if (m_TableModel->contains(name)) { QMessageBox::critical(this, "Preset definition", "Presetname already exists.\n" "You have to enter another one."); } else if (presetnameLineEdit->text() == "") { QMessageBox::critical(this, "Preset definition", "Presetname has to be set.\n" "You have to enter a Presetname."); } else { m_TableModel->addPreset(name, levelSpinBox->value(), windowSpinBox->value()); } } void QmitkLevelWindowPresetDefinitionDialog::removePreset() { - QModelIndex index(presetView->selectionModel()->currentIndex()); + QModelIndex index(m_SortModel.mapToSource(presetView->selectionModel()->currentIndex())); + if (!index.isValid()) return; m_TableModel->removePreset(index); } void QmitkLevelWindowPresetDefinitionDialog::changePreset() { - if (presetView->selectionModel()->hasSelection()) + QModelIndex index(m_SortModel.mapToSource(presetView->selectionModel()->currentIndex())); + + if (!index.isValid()) + return; + + std::string name(presetnameLineEdit->text().toStdString()); + if (name == "") { - std::string name(presetnameLineEdit->text().toStdString()); - if (name == "") - { - QMessageBox::critical(this, - "Preset definition", - "Presetname has to be set.\n" - "You have to enter a Presetname."); - } - else if (m_TableModel->contains(name) && - (m_TableModel->getPreset(presetView->selectionModel()->currentIndex()).name != name)) - { - QMessageBox::critical(this, - "Preset definition", - "Presetname already exists.\n" - "You have to enter another one."); - } - else - { - m_TableModel->changePreset( - presetView->selectionModel()->currentIndex().row(), name, levelSpinBox->value(), windowSpinBox->value()); - } + QMessageBox::critical(this, + "Preset definition", + "Presetname has to be set.\n" + "You have to enter a Presetname."); + } + else if (m_TableModel->contains(name) && + (m_TableModel->getPreset(index).name != name)) + { + QMessageBox::critical(this, + "Preset definition", + "Presetname already exists.\n" + "You have to enter another one."); + } + else + { + m_TableModel->changePreset(index.row(), name, levelSpinBox->value(), windowSpinBox->value()); } } void QmitkLevelWindowPresetDefinitionDialog::setPresets(std::map &level, std::map &window, QString initLevel, QString initWindow) { levelSpinBox->setValue(initLevel.toInt()); windowSpinBox->setValue(initWindow.toInt()); delete m_TableModel; m_TableModel = new PresetTableModel(level, window, this); m_SortModel.setSourceModel(m_TableModel); QObject::connect(presetView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(ListViewSelectionChanged(const QItemSelection &, const QItemSelection &))); this->sortPresets(0); presetView->resizeColumnsToContents(); } std::map QmitkLevelWindowPresetDefinitionDialog::getLevelPresets() { std::map levels; m_TableModel->getLevels(levels); return levels; } std::map QmitkLevelWindowPresetDefinitionDialog::getWindowPresets() { std::map windows; m_TableModel->getWindows(windows); return windows; } void QmitkLevelWindowPresetDefinitionDialog::ListViewSelectionChanged(const QItemSelection &selected, const QItemSelection & /*deselected*/) { QModelIndexList indexes(selected.indexes()); if (indexes.empty()) { presetnameLineEdit->setText(""); levelSpinBox->setValue(0); windowSpinBox->setValue(0); } else { // use the sorted index to get the entry PresetTableModel::Entry entry(m_TableModel->getPreset((m_SortModel.mapToSource(indexes.first())))); presetnameLineEdit->setText(QString(entry.name.c_str())); levelSpinBox->setValue((int)entry.level); windowSpinBox->setValue((int)entry.window); } } QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::PresetTableModel(std::map &levels, std::map &windows, QObject *parent) : QAbstractTableModel(parent) { for (auto iter = levels.begin(); iter != levels.end(); ++iter) { m_Entries.push_back(Entry(iter->first, iter->second, windows[iter->first])); } } void QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::getLevels(std::map &levels) { for (auto iter = m_Entries.begin(); iter != m_Entries.end(); ++iter) { levels[iter->name] = iter->level; } } void QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::getWindows(std::map &windows) { for (auto iter = m_Entries.begin(); iter != m_Entries.end(); ++iter) { windows[iter->name] = iter->window; } } void QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::addPreset(std::string &name, double level, double window) { this->beginInsertRows(QModelIndex(), (int)m_Entries.size(), (int)m_Entries.size()); m_Entries.push_back(Entry(name, level, window)); this->endInsertRows(); } bool QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::contains(std::string &name) { for (auto iter = m_Entries.begin(); iter != m_Entries.end(); ++iter) { if (iter->name == name) return true; } return false; } void QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::removePreset(const QModelIndex &index) { int row = index.row(); this->beginRemoveRows(QModelIndex(), row, row); m_Entries.erase(m_Entries.begin() + row); this->endRemoveRows(); } void QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::changePreset(int row, std::string &name, double level, double window) { m_Entries[row].name = name; m_Entries[row].level = level; m_Entries[row].window = window; this->dataChanged(index(row, 0), index(row, 2)); } QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::Entry QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::getPreset(const QModelIndex &index) const { int row = index.row(); if (row < 0 || (unsigned int)row >= m_Entries.size()) return Entry("", 0, 0); return m_Entries[row]; } int QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::rowCount(const QModelIndex &) const { return (int)m_Entries.size(); } int QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::columnCount(const QModelIndex &) const { return 3; } QVariant QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return QVariant(QString(m_Entries[index.row()].name.c_str())); case 1: { return QVariant(m_Entries[index.row()].level); } case 2: return QVariant(m_Entries[index.row()].window); } } return QVariant(); } QVariant QmitkLevelWindowPresetDefinitionDialog::PresetTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return QVariant("Preset"); case 1: return QVariant("Level"); case 2: return QVariant("Window"); } } return QVariant(); } diff --git a/Modules/QtWidgets/src/mitkQtWidgetsActivator.cpp b/Modules/QtWidgets/src/mitkQtWidgetsActivator.cpp index 4e6006ce11..deaf7af8b7 100644 --- a/Modules/QtWidgets/src/mitkQtWidgetsActivator.cpp +++ b/Modules/QtWidgets/src/mitkQtWidgetsActivator.cpp @@ -1,36 +1,38 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkQtWidgetsActivator.h" // Micro Services #include #include // Qmitk #include "QmitkDataStorageInspectorProviderBase.h" #include "QmitkDataStorageListInspector.h" #include "QmitkDataStorageTreeInspector.h" #include "QmitkDataStorageSelectionHistoryInspector.h" +#include "QmitkDataStorageFavoriteNodesInspector.h" void MitkQtWidgetsActivator::Load(us::ModuleContext * /*context*/) { m_TreeInspector.reset(new QmitkDataStorageInspectorProviderBase("org.mitk.QmitkDataStorageListInspector", "Simple list", "Displays the filtered content of the data storage in a simple list.")); m_ListInspector.reset(new QmitkDataStorageInspectorProviderBase("org.mitk.QmitkDataStorageTreeInspector", "Rendering tree", "Displays the filtered content of the data storage as the current rendering tree. \n(Equals the old data manager view)")); m_HistoryInspector.reset(new QmitkDataStorageInspectorProviderBase("org.mitk.QmitkDataStorageSelectionHistoryInspector", "Selection history", "Displays the filtered history of all node selections in this application session. \nThe nodes are sorted from new to old selections.\nOnly nodes that are still in the data storage will be displayed.")); + m_FavoriteNodesInspector.reset(new QmitkDataStorageInspectorProviderBase("org.mitk.QmitkDataStorageFavoriteNodesInspector", "Favorite nodes list", "Displays the favorite nodes of the data storage in a simple list.")); } void MitkQtWidgetsActivator::Unload(us::ModuleContext *) { } US_EXPORT_MODULE_ACTIVATOR(MitkQtWidgetsActivator) diff --git a/Modules/QtWidgets/src/mitkQtWidgetsActivator.h b/Modules/QtWidgets/src/mitkQtWidgetsActivator.h index d515f6b312..6a72708a07 100644 --- a/Modules/QtWidgets/src/mitkQtWidgetsActivator.h +++ b/Modules/QtWidgets/src/mitkQtWidgetsActivator.h @@ -1,41 +1,42 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKQTWIDGETSACTIVATOR_H_ #define MITKQTWIDGETSACTIVATOR_H_ // Micro Services #include #include #include #include #include #include "mitkIDataStorageInspectorProvider.h" /* * This is the module activator for the "QtWidgets" module. */ class MitkQtWidgetsActivator : public us::ModuleActivator { public: void Load(us::ModuleContext *context) override; void Unload(us::ModuleContext *) override; private: std::unique_ptr m_TreeInspector; std::unique_ptr m_ListInspector; std::unique_ptr m_HistoryInspector; + std::unique_ptr m_FavoriteNodesInspector; }; #endif // MITKCOREACTIVATOR_H_ diff --git a/Modules/QtWidgets/test/files.cmake b/Modules/QtWidgets/test/files.cmake index e915c0c8b2..370a32a208 100644 --- a/Modules/QtWidgets/test/files.cmake +++ b/Modules/QtWidgets/test/files.cmake @@ -1,13 +1,10 @@ # test fails easily on MacOS, rarely on Windows, needs to be fixed before permanent activation (bug 15479) -if (BUG_15479_FIXED) - - set(MODULE_TESTS - QmitkThreadedLogTest.cpp - ) +set(MODULE_TESTS ) +if(BUG_15479_FIXED) + list(APPEND MODULE_TESTS QmitkThreadedLogTest.cpp) endif() - -set(MODULE_TESTS ${MODULE_TESTS} +set(MODULE_CUSTOM_TESTS ${MODULE_TESTS} QmitkDataStorageListModelTest.cpp ) diff --git a/Modules/SceneSerialization/test/CMakeLists.txt b/Modules/SceneSerialization/test/CMakeLists.txt index 00442dea82..07a93f524e 100644 --- a/Modules/SceneSerialization/test/CMakeLists.txt +++ b/Modules/SceneSerialization/test/CMakeLists.txt @@ -1,27 +1,25 @@ MITK_CREATE_MODULE_TESTS(LABELS MITK-Modules) if(TARGET ${TESTDRIVER}) if(BUILD_TESTING AND MODULE_IS_ENABLED) add_test(mitkSceneIOTest_Pic3D.nrrd_binary.stl ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} mitkSceneIOTest ${MITK_DATA_DIR}/Pic3D.nrrd ${MITK_DATA_DIR}/binary.stl ) set_property(TEST mitkSceneIOTest_Pic3D.nrrd_binary.stl PROPERTY LABELS MITK-Modules) - if(MITK_ENABLE_RENDERING_TESTING) mitkAddCustomModuleTest(mitkSceneIOCompatibility_NoRainbowCT mitkSceneIOCompatibilityTest ${MITK_DATA_DIR}/RenderingTestData/SceneFiles/rainbows-post-17547.mitk # scene to load -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/rainbows-post-17547.png) # reference rendering - if (false) # fix not yet integrated - mitkAddCustomModuleTest(mitkSceneIOCompatibility_SurfaceIntLineWidth mitkSceneIOCompatibilityTest - ${MITK_DATA_DIR}/RenderingTestData/SceneFiles/surface-pre-18528.mitk # scene to load - -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/surface-pre-18528.png) # reference rendering - endif() - endif() + if (FALSE) # fix not yet integrated + mitkAddCustomModuleTest(mitkSceneIOCompatibility_SurfaceIntLineWidth mitkSceneIOCompatibilityTest + ${MITK_DATA_DIR}/RenderingTestData/SceneFiles/surface-pre-18528.mitk # scene to load + -V ${MITK_DATA_DIR}/RenderingTestData/ReferenceScreenshots/surface-pre-18528.png) # reference rendering + endif() endif() endif() diff --git a/Modules/Segmentation/Testing/files.cmake b/Modules/Segmentation/Testing/files.cmake index 998fe8337d..9330f21eb2 100644 --- a/Modules/Segmentation/Testing/files.cmake +++ b/Modules/Segmentation/Testing/files.cmake @@ -1,35 +1,29 @@ set(MODULE_TESTS mitkContourMapper2DTest.cpp mitkContourTest.cpp mitkContourModelSetToImageFilterTest.cpp mitkDataNodeSegmentationTest.cpp mitkFeatureBasedEdgeDetectionFilterTest.cpp mitkImageToContourFilterTest.cpp mitkSegmentationInterpolationTest.cpp mitkOverwriteSliceFilterTest.cpp mitkOverwriteSliceFilterObliquePlaneTest.cpp # mitkToolManagerTest.cpp mitkToolManagerProviderTest.cpp mitkManualSegmentationToSurfaceFilterTest.cpp #new cpp unit style -) - -if(MITK_ENABLE_RENDERING_TESTING) #since mitkInteractionTestHelper is currently creating a vtkRenderWindow -set(MODULE_TESTS - ${MODULE_TESTS} mitkToolInteractionTest.cpp ) -endif() set(MODULE_IMAGE_TESTS mitkOverwriteSliceImageFilterTest.cpp #only runs on images ) set(MODULE_CUSTOM_TESTS ) set(MODULE_TESTIMAGE US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd Png2D-bw.png ) diff --git a/Modules/ToFHardware/Testing/CMakeLists.txt b/Modules/ToFHardware/Testing/CMakeLists.txt index 26dd603442..99276c61d6 100644 --- a/Modules/ToFHardware/Testing/CMakeLists.txt +++ b/Modules/ToFHardware/Testing/CMakeLists.txt @@ -1,22 +1,15 @@ MITK_CREATE_MODULE_TESTS() if(TARGET ${TESTDRIVER}) mitk_use_modules(TARGET ${TESTDRIVER} PACKAGES VTK|vtkTestingRendering) - #Only enabled for Windows and Mac nightlies. - #If you want to run this on linux, just enable the flag in the superbuild. - if(MITK_ENABLE_RENDERING_TESTING) - mitkAddCustomModuleTest(mitkPlayerLoadAndRenderDepthDataTest_KinectDepthImage #testname mitkPlayerLoadAndRenderDepthDataTest #testclassname Kinect_LiverPhantom_DistanceImage.nrrd #input image -V ${MITK_DATA_DIR}/ToF-Data/ReferenceScreenshots/Kinect_LiverPhantom_DistanceImage640x480REF.png #reference image ) mitkAddCustomModuleTest(mitkPlayerLoadAndRenderRGBDataTest_KinectRGBImage mitkPlayerLoadAndRenderRGBDataTest Kinect_LiverPhantom_RGBImage.nrrd -V ${MITK_DATA_DIR}/ToF-Data/ReferenceScreenshots/Kinect_LiverPhantom_RGBImage640x480REF.png) #rendering tests cannot run in parallel SET_PROPERTY(TEST mitkPlayerLoadAndRenderDepthDataTest_KinectDepthImage mitkPlayerLoadAndRenderRGBDataTest_KinectRGBImage PROPERTY RUN_SERIAL TRUE) - - endif() endif() - diff --git a/Modules/XNAT/files.cmake b/Modules/XNAT/files.cmake index c7bac427c8..99014ede7f 100644 --- a/Modules/XNAT/files.cmake +++ b/Modules/XNAT/files.cmake @@ -1,38 +1,37 @@ file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*") set(CPP_FILES mitkXnatSessionTracker.cpp QmitkXnatTreeModel.cpp QmitkXnatProjectWidget.cpp QmitkXnatSubjectWidget.cpp QmitkXnatExperimentWidget.cpp QmitkXnatCreateObjectDialog.cpp QmitkSelectXnatUploadDestinationDialog.cpp QmitkXnatUploadFromDataStorageDialog.cpp QmitkHttpStatusCodeHandler.cpp ) set(MOC_H_FILES include/mitkXnatSessionTracker.h include/QmitkXnatTreeModel.h include/QmitkXnatProjectWidget.h include/QmitkXnatSubjectWidget.h include/QmitkXnatExperimentWidget.h include/QmitkXnatCreateObjectDialog.h include/QmitkSelectXnatUploadDestinationDialog.h include/QmitkXnatUploadFromDataStorageDialog.h - include/QmitkHttpStatusCodeHandler.h ) set(QRC_FILES resources/xnat.qrc ) set(UI_FILES src/QmitkXnatExperimentWidgetControls.ui src/QmitkXnatProjectWidgetControls.ui src/QmitkSelectXnatUploadDestinationDialog.ui src/QmitkXnatSubjectWidgetControls.ui src/QmitkXnatUploadFromDataStorageDialog.ui ) diff --git a/Plugins/org.mitk.gui.qt.application/files.cmake b/Plugins/org.mitk.gui.qt.application/files.cmake index 9bf54191ea..4d661dfef3 100644 --- a/Plugins/org.mitk.gui.qt.application/files.cmake +++ b/Plugins/org.mitk.gui.qt.application/files.cmake @@ -1,87 +1,86 @@ set(SRC_CPP_FILES QmitkAbstractDataNodeAction.cpp QmitkCloseProjectAction.cpp QmitkDataNodeColorAction.cpp QmitkDataNodeColorMapAction.cpp QmitkDataNodeComponentAction.cpp QmitkDataNodeContextMenu.cpp QmitkDataNodeGlobalReinitAction.cpp QmitkDataNodeHideAllAction.cpp QmitkDataNodeOpacityAction.cpp QmitkDataNodeOpenInAction.cpp QmitkDataNodeReinitAction.cpp QmitkDataNodeRemoveAction.cpp QmitkDataNodeShowDetailsAction.cpp QmitkDataNodeShowSelectedNodesAction.cpp QmitkDataNodeSurfaceRepresentationAction.cpp QmitkDataNodeTextureInterpolationAction.cpp QmitkDataNodeToggleVisibilityAction.cpp QmitkDefaultDropTargetListener.cpp QmitkFileExitAction.cpp QmitkFileOpenAction.cpp QmitkFileSaveAction.cpp QmitkUndoAction.cpp QmitkRedoAction.cpp QmitkPreferencesDialog.cpp QmitkStatusBar.cpp ) set(INTERNAL_CPP_FILES org_mitk_gui_qt_application_Activator.cpp QmitkEditorsPreferencePage.cpp QmitkGeneralPreferencePage.cpp QmitkShowPreferencePageHandler.cpp ) set(MOC_H_FILES - src/QmitkAbstractDataNodeAction.h src/QmitkCloseProjectAction.h src/QmitkDataNodeColorAction.h src/QmitkDataNodeColorMapAction.h src/QmitkDataNodeComponentAction.h src/QmitkDataNodeGlobalReinitAction.h src/QmitkDataNodeContextMenu.h src/QmitkDataNodeHideAllAction.h src/QmitkDataNodeOpacityAction.h src/QmitkDataNodeOpenInAction.h src/QmitkDataNodeReinitAction.h src/QmitkDataNodeRemoveAction.h src/QmitkDataNodeShowDetailsAction.h src/QmitkDataNodeShowSelectedNodesAction.h src/QmitkDataNodeSurfaceRepresentationAction.h src/QmitkDataNodeTextureInterpolationAction.h src/QmitkDataNodeToggleVisibilityAction.h src/QmitkFileExitAction.h src/QmitkFileOpenAction.h src/QmitkFileSaveAction.h src/QmitkUndoAction.h src/QmitkRedoAction.h src/QmitkPreferencesDialog.h src/internal/org_mitk_gui_qt_application_Activator.h src/internal/QmitkEditorsPreferencePage.h src/internal/QmitkGeneralPreferencePage.h src/internal/QmitkShowPreferencePageHandler.h ) set(UI_FILES src/QmitkPreferencesDialog.ui ) set(CACHED_RESOURCE_FILES plugin.xml ) set(QRC_FILES resources/resources.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/Plugins/org.mitk.gui.qt.common/files.cmake b/Plugins/org.mitk.gui.qt.common/files.cmake index 67e72c7578..0bde8b2087 100755 --- a/Plugins/org.mitk.gui.qt.common/files.cmake +++ b/Plugins/org.mitk.gui.qt.common/files.cmake @@ -1,72 +1,71 @@ set(SRC_CPP_FILES QmitkAbstractMultiWidgetEditor.cpp QmitkAbstractRenderEditor.cpp QmitkAbstractView.cpp QmitkDataNodeSelectionProvider.cpp QmitkDnDFrameWidget.cpp QmitkSelectionServiceConnector.cpp QmitkSliceNavigationListener.cpp QmitkSingleNodeSelectionWidget.cpp QmitkNodeSelectionDialog.cpp QmitkAbstractNodeSelectionWidget.cpp QmitkMultiNodeSelectionWidget.cpp QmitkMultiWidgetDecorationManager.cpp QmitkNodeSelectionPreferenceHelper.cpp QmitkNodeSelectionButton.cpp QmitkSimpleTextOverlayWidget.cpp ) set(INTERNAL_CPP_FILES QmitkCommonActivator.cpp QmitkDataNodeItemModel.cpp QmitkDataNodeSelection.cpp QmitkViewCoordinator.cpp QmitkNodeSelectionConstants.cpp QmitkNodeSelectionPreferencePage.cpp QmitkNodeSelectionListItemWidget.cpp ) set(UI_FILES src/QmitkSingleNodeSelectionWidget.ui src/QmitkMultiNodeSelectionWidget.ui src/QmitkNodeSelectionDialog.ui src/internal/QmitkNodeSelectionPreferencePage.ui src/internal/QmitkNodeSelectionListItemWidget.ui ) set(MOC_H_FILES src/QmitkAbstractMultiWidgetEditor.h src/QmitkAbstractRenderEditor.h src/QmitkDnDFrameWidget.h src/QmitkSelectionServiceConnector.h src/QmitkSliceNavigationListener.h - src/ImporterUtil.h src/QmitkSingleNodeSelectionWidget.h src/QmitkNodeSelectionDialog.h src/QmitkAbstractNodeSelectionWidget.h src/QmitkMultiNodeSelectionWidget.h src/QmitkNodeSelectionButton.h src/QmitkSimpleTextOverlayWidget.h src/internal/QmitkCommonActivator.h src/internal/QmitkNodeSelectionPreferencePage.h src/internal/QmitkNodeSelectionListItemWidget.h ) set(CACHED_RESOURCE_FILES plugin.xml resources/times.svg ) set(QRC_FILES resources/common.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/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.cpp index d2b6d3c0a1..fc074dfb4a 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.cpp +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.cpp @@ -1,188 +1,199 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkNodeSelectionDialog.h" #include -#include #include #include QmitkNodeSelectionDialog::QmitkNodeSelectionDialog(QWidget* parent, QString title, QString hint) : QDialog(parent), m_NodePredicate(nullptr), m_SelectOnlyVisibleNodes(false), m_SelectedNodes(NodeList()), m_SelectionMode(QAbstractItemView::SingleSelection) { m_Controls.setupUi(this); auto providers = mitk::DataStorageInspectorGenerator::GetProviders(); auto visibleProviders = mitk::GetVisibleDataStorageInspectors(); auto favoriteID = mitk::GetFavoriteDataStorageInspector(); if (visibleProviders.empty()) { MITK_DEBUG << "No presets for visible node selection inspectors available. Use fallback (show all available inspectors)"; unsigned int order = 0; for (auto proIter : providers) { visibleProviders.insert(std::make_pair(order, proIter.first)); ++order; } } int favIndex = 0; bool favoriteFound = false; for (auto proIter : visibleProviders) { auto finding = providers.find(proIter.second); if (finding != providers.end()) { auto inspector = finding->second->CreateInspector(); QString name = QString::fromStdString(finding->second->GetInspectorDisplayName()); QString desc = QString::fromStdString(finding->second->GetInspectorDescription()); AddPanel(inspector, name, desc); favoriteFound = favoriteFound || proIter.second == favoriteID; if (!favoriteFound) { ++favIndex; } } else { MITK_DEBUG << "No provider registered for inspector that is defined as visible in the preferences. Illegal inspector ID: " << proIter.second; } } m_Controls.tabWidget->setCurrentIndex(favIndex); this->setWindowTitle(title); this->setToolTip(hint); m_Controls.hint->setText(hint); m_Controls.hint->setVisible(!hint.isEmpty()); + m_FavoriteNodesButton = new QPushButton("Add to favorites"); + m_Controls.buttonBox->addButton(m_FavoriteNodesButton, QDialogButtonBox::ActionRole); + + connect(m_FavoriteNodesButton, &QPushButton::clicked, this, &QmitkNodeSelectionDialog::OnFavoriteNodesButtonClicked); connect(m_Controls.buttonBox, SIGNAL(accepted()), this, SLOT(OnOK())); connect(m_Controls.buttonBox, SIGNAL(rejected()), this, SLOT(OnCancel())); } void QmitkNodeSelectionDialog::SetDataStorage(mitk::DataStorage* dataStorage) { if (m_DataStorage != dataStorage) { m_DataStorage = dataStorage; if (!m_DataStorage.IsExpired()) { for (auto panel : m_Panels) { panel->SetDataStorage(dataStorage); } } } } void QmitkNodeSelectionDialog::SetNodePredicate(mitk::NodePredicateBase* nodePredicate) { if (m_NodePredicate != nodePredicate) { m_NodePredicate = nodePredicate; for (auto panel : m_Panels) { panel->SetNodePredicate(m_NodePredicate); } } } mitk::NodePredicateBase* QmitkNodeSelectionDialog::GetNodePredicate() const { return m_NodePredicate; } QmitkNodeSelectionDialog::NodeList QmitkNodeSelectionDialog::GetSelectedNodes() const { return m_SelectedNodes; } void QmitkNodeSelectionDialog::SetSelectOnlyVisibleNodes(bool selectOnlyVisibleNodes) { if (m_SelectOnlyVisibleNodes != selectOnlyVisibleNodes) { m_SelectOnlyVisibleNodes = selectOnlyVisibleNodes; for (auto panel : m_Panels) { panel->SetSelectOnlyVisibleNodes(m_SelectOnlyVisibleNodes); } } } void QmitkNodeSelectionDialog::SetCurrentSelection(NodeList selectedNodes) { m_SelectedNodes = selectedNodes; for (auto panel : m_Panels) { panel->SetCurrentSelection(selectedNodes); } } void QmitkNodeSelectionDialog::OnSelectionChanged(NodeList selectedNodes) { SetCurrentSelection(selectedNodes); emit CurrentSelectionChanged(selectedNodes); } void QmitkNodeSelectionDialog::AddPanel(QmitkAbstractDataStorageInspector* view, QString name, QString desc) { view->setParent(this); view->SetSelectionMode(m_SelectionMode); auto tabPanel = new QWidget(); tabPanel->setObjectName(QString("tab_")+name); tabPanel->setToolTip(desc); m_Controls.tabWidget->insertTab(m_Controls.tabWidget->count(), tabPanel, name); auto verticalLayout = new QVBoxLayout(tabPanel); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(0, 0, 0, 0); verticalLayout->addWidget(view); m_Panels.push_back(view); connect(view, &QmitkAbstractDataStorageInspector::CurrentSelectionChanged, this, &QmitkNodeSelectionDialog::OnSelectionChanged); } +void QmitkNodeSelectionDialog::OnFavoriteNodesButtonClicked() +{ + for (auto node : m_SelectedNodes) + { + node->SetBoolProperty("org.mitk.selection.favorite", true); + } +} + void QmitkNodeSelectionDialog::OnOK() { for (auto node : m_SelectedNodes) { QmitkDataStorageSelectionHistoryInspector::AddNodeToHistory(node); } this->accept(); } void QmitkNodeSelectionDialog::OnCancel() { this->reject(); } void QmitkNodeSelectionDialog::SetSelectionMode(SelectionMode mode) { m_SelectionMode = mode; for (auto panel : m_Panels) { panel->SetSelectionMode(mode); } } QmitkNodeSelectionDialog::SelectionMode QmitkNodeSelectionDialog::GetSelectionMode() const { return m_SelectionMode; } diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.h b/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.h index 2d48d7e047..3fcb1d0db0 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkNodeSelectionDialog.h @@ -1,121 +1,125 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITK_NODE_SELECTION_DIALOG_H #define QMITK_NODE_SELECTION_DIALOG_H #include #include #include #include #include "org_mitk_gui_qt_common_Export.h" #include "ui_QmitkNodeSelectionDialog.h" #include +#include /** * \class QmitkNodeSelectionDialog * \brief Widget that allows to show and edit the content of an mitk::IsoDoseLevel instance. */ class MITK_QT_COMMON QmitkNodeSelectionDialog : public QDialog { Q_OBJECT public: explicit QmitkNodeSelectionDialog(QWidget* parent = nullptr, QString caption = "", QString hint = ""); /* * @brief Sets the data storage that will be used /monitored by widget. * * @param dataStorage A pointer to the data storage to set. */ void SetDataStorage(mitk::DataStorage* dataStorage); /* * @brief Sets the node predicate and updates the widget, according to the node predicate. * * @param nodePredicate A pointer to node predicate. */ virtual void SetNodePredicate(mitk::NodePredicateBase* nodePredicate); mitk::NodePredicateBase* GetNodePredicate() const; using NodeList = QList; NodeList GetSelectedNodes() const; bool GetSelectOnlyVisibleNodes() const; using SelectionMode = QAbstractItemView::SelectionMode; void SetSelectionMode(SelectionMode mode); SelectionMode GetSelectionMode() const; Q_SIGNALS: /* * @brief A signal that will be emitted if the selected node has changed. * * @param nodes A list of data nodes that are newly selected. */ void CurrentSelectionChanged(NodeList nodes); public Q_SLOTS: /* * @brief Change the selection modus of the item view's selection model. * * If true, an incoming selection will be filtered (reduced) to only those nodes that are visible by the current view. * An outgoing selection can then at most contain the filtered nodes. * If false, the incoming non-visible selection will be stored and later added to the outgoing selection, * to include the original selection that could not be modified. * The part of the original selection, that is non-visible are the nodes that are not * * @param selectOnlyVisibleNodes The bool value to define the selection modus. */ void SetSelectOnlyVisibleNodes(bool selectOnlyVisibleNodes); /* * @brief Transform a list of data nodes into a model selection and set this as a new selection of the * selection model of the private member item view. * * The function filters the given list of nodes according to the 'm_SelectOnlyVisibleNodes' member variable. If * necessary, the non-visible nodes are stored. This is done if 'm_SelectOnlyVisibleNodes' is false: In this case * the selection may be filtered and only a subset of the selected nodes may be visible and therefore (de-)selectable * in the data storage viewer. By storing the non-visible nodes it is possible to send the new, modified selection * but also include the selected nodes from the original selection that could not be modified (see 'SetSelectOnlyVisibleNodes'). * * @param nodes A list of data nodes that should be newly selected. */ void SetCurrentSelection(NodeList selectedNodes); protected Q_SLOTS: + void OnSelectionChanged(NodeList selectedNodes); + void OnFavoriteNodesButtonClicked(); void OnOK(); void OnCancel(); protected: void AddPanel(QmitkAbstractDataStorageInspector* view, QString name, QString desc); mitk::WeakPointer m_DataStorage; mitk::NodePredicateBase::Pointer m_NodePredicate; bool m_SelectOnlyVisibleNodes; NodeList m_SelectedNodes; SelectionMode m_SelectionMode; using PanelVectorType = std::vector; PanelVectorType m_Panels; + QPushButton* m_FavoriteNodesButton; Ui_QmitkNodeSelectionDialog m_Controls; }; -#endif // QmitkNodeSelectionDialog_H +#endif // QMITK_NODE_SELECTION_DIALOG_H diff --git a/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorView.cpp b/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorView.cpp index eff06bd45a..2a3a0f3090 100644 --- a/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorView.cpp +++ b/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorView.cpp @@ -1,385 +1,374 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ - // Blueberry #include #include #include // mitk #include #include #include // Qt #include #include #include #include #include "QmitkDicomInspectorView.h" const std::string QmitkDicomInspectorView::VIEW_ID = "org.mitk.gui.qt.dicominspector"; QmitkDicomInspectorView::ObserverInfo::ObserverInfo(mitk::SliceNavigationController* controller, int observerTag, const std::string& renderWindowName, mitk::IRenderWindowPart* part) : controller(controller), observerTag(observerTag), renderWindowName(renderWindowName), renderWindowPart(part) { } -QmitkDicomInspectorView::QmitkDicomInspectorView() : -m_renderWindowPart(nullptr), -m_PendingSliceChangedEvent(false), -m_currentSelectedTimeStep(0), -m_currentSelectedZSlice(0), -m_currentSelectedNode(nullptr), -m_internalUpdateFlag(false) +QmitkDicomInspectorView::QmitkDicomInspectorView() + : m_RenderWindowPart(nullptr) + , m_PendingSliceChangedEvent(false) + , m_SelectedNode(nullptr) + , m_SelectedTimeStep(0) + , m_CurrentSelectedZSlice(0) { - m_currentSelectedPosition.Fill(0.0); + m_SelectedPosition.Fill(0.0); } QmitkDicomInspectorView::~QmitkDicomInspectorView() { this->RemoveAllObservers(); } +void QmitkDicomInspectorView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) +{ + if (m_RenderWindowPart != renderWindowPart) + { + m_RenderWindowPart = renderWindowPart; + + if (!InitObservers()) + { + QMessageBox::information(nullptr, "Error", "Unable to set up the event observers. The " \ + "plot will not be triggered on changing the crosshair, " \ + "position or time step."); + } + } +} + +void QmitkDicomInspectorView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) +{ + m_RenderWindowPart = nullptr; + this->RemoveAllObservers(renderWindowPart); +} + +void QmitkDicomInspectorView::CreateQtPartControl(QWidget* parent) +{ + // create GUI widgets from the Qt Designer's .ui file + m_Controls.setupUi(parent); + + m_Controls.singleSlot->SetDataStorage(GetDataStorage()); + m_Controls.singleSlot->SetSelectionIsOptional(true); + m_Controls.singleSlot->SetEmptyInfo(QString("Please select a data node")); + m_Controls.singleSlot->SetPopUpTitel(QString("Select data node")); + + m_SelectionServiceConnector = std::make_unique(); + SetAsSelectionListener(true); + + m_Controls.timePointValueLabel->setText(QString("")); + m_Controls.sliceNumberValueLabel->setText(QString("")); + + connect(m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, + this, &QmitkDicomInspectorView::OnCurrentSelectionChanged); + + mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart(); + RenderWindowPartActivated(renderWindowPart); +} bool QmitkDicomInspectorView::InitObservers() { bool result = true; typedef QHash WindowMapType; - WindowMapType windowMap = m_renderWindowPart->GetQmitkRenderWindows(); + WindowMapType windowMap = m_RenderWindowPart->GetQmitkRenderWindows(); auto i = windowMap.begin(); while (i != windowMap.end()) { mitk::SliceNavigationController* sliceNavController = i.value()->GetSliceNavigationController(); if (sliceNavController) { - itk::ReceptorMemberCommand::Pointer cmdSliceEvent = - itk::ReceptorMemberCommand::New(); + auto cmdSliceEvent = itk::SimpleMemberCommand::New(); cmdSliceEvent->SetCallbackFunction(this, &QmitkDicomInspectorView::OnSliceChanged); int tag = sliceNavController->AddObserver( - mitk::SliceNavigationController::GeometrySliceEvent(nullptr, 0), - cmdSliceEvent); + mitk::SliceNavigationController::GeometrySliceEvent(nullptr, 0), cmdSliceEvent); m_ObserverMap.insert(std::make_pair(sliceNavController, ObserverInfo(sliceNavController, tag, - i.key().toStdString(), m_renderWindowPart))); + i.key().toStdString(), m_RenderWindowPart))); - itk::ReceptorMemberCommand::Pointer cmdTimeEvent = - itk::ReceptorMemberCommand::New(); + auto cmdTimeEvent = itk::SimpleMemberCommand::New(); cmdTimeEvent->SetCallbackFunction(this, &QmitkDicomInspectorView::OnSliceChanged); tag = sliceNavController->AddObserver( - mitk::SliceNavigationController::GeometryTimeEvent(nullptr, 0), - cmdTimeEvent); + mitk::SliceNavigationController::GeometryTimeEvent(nullptr, 0), cmdTimeEvent); m_ObserverMap.insert(std::make_pair(sliceNavController, ObserverInfo(sliceNavController, tag, - i.key().toStdString(), m_renderWindowPart))); + i.key().toStdString(), m_RenderWindowPart))); - itk::MemberCommand::Pointer cmdDelEvent = - itk::MemberCommand::New(); - cmdDelEvent->SetCallbackFunction(this, - &QmitkDicomInspectorView::OnSliceNavigationControllerDeleted); - tag = sliceNavController->AddObserver( - itk::DeleteEvent(), cmdDelEvent); + auto cmdDelEvent = itk::MemberCommand::New(); + cmdDelEvent->SetCallbackFunction(this, &QmitkDicomInspectorView::OnSliceNavigationControllerDeleted); + tag = sliceNavController->AddObserver(itk::DeleteEvent(), cmdDelEvent); m_ObserverMap.insert(std::make_pair(sliceNavController, ObserverInfo(sliceNavController, tag, - i.key().toStdString(), m_renderWindowPart))); + i.key().toStdString(), m_RenderWindowPart))); } ++i; result = result && sliceNavController; } return result; } -void QmitkDicomInspectorView::RemoveObservers(const mitk::SliceNavigationController* - deletedSlicer) +void QmitkDicomInspectorView::RemoveObservers(const mitk::SliceNavigationController* deletedSlicer) { - - std::pair < ObserverMapType::const_iterator, ObserverMapType::const_iterator> obsRange = + std::pair obsRange = m_ObserverMap.equal_range(deletedSlicer); for (ObserverMapType::const_iterator pos = obsRange.first; pos != obsRange.second; ++pos) { pos->second.controller->RemoveObserver(pos->second.observerTag); } m_ObserverMap.erase(deletedSlicer); } void QmitkDicomInspectorView::RemoveAllObservers(mitk::IRenderWindowPart* deletedPart) { for (ObserverMapType::const_iterator pos = m_ObserverMap.begin(); pos != m_ObserverMap.end();) { ObserverMapType::const_iterator delPos = pos++; - if (deletedPart == nullptr || deletedPart == delPos->second.renderWindowPart) + if (nullptr == deletedPart || deletedPart == delPos->second.renderWindowPart) { delPos->second.controller->RemoveObserver(delPos->second.observerTag); m_ObserverMap.erase(delPos); } } } -void QmitkDicomInspectorView::OnSliceNavigationControllerDeleted(const itk::Object* sender, - const itk::EventObject& /*e*/) +void QmitkDicomInspectorView::OnCurrentSelectionChanged(QList nodes) { - const mitk::SliceNavigationController* sendingSlicer = - dynamic_cast(sender); - - this->RemoveObservers(sendingSlicer); -} + if (nodes.empty() || nodes.front().IsNull()) + { + m_SelectedNode = nullptr; + m_SelectedData = nullptr; + UpdateData(); + return; + } -void QmitkDicomInspectorView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) -{ - if (m_renderWindowPart != renderWindowPart) + if (nodes.front() != this->m_SelectedNode) { - m_renderWindowPart = renderWindowPart; + // node is selected, create DICOM tag table + m_SelectedNode = nodes.front(); + m_SelectedData = this->m_SelectedNode->GetData(); - if (!InitObservers()) - { - QMessageBox::information(nullptr, "Error", "Unable to set up the event observers. The " \ - "plot will not be triggered on changing the crosshair, " \ - "position or time step."); - } + m_SelectedNodeTime.Modified(); + UpdateData(); + OnSliceChangedDelayed(); } } -void QmitkDicomInspectorView::RenderWindowPartDeactivated( - mitk::IRenderWindowPart* renderWindowPart) +void QmitkDicomInspectorView::OnSliceChanged() { - m_renderWindowPart = nullptr; - this->RemoveAllObservers(renderWindowPart); -} - -void QmitkDicomInspectorView::CreateQtPartControl(QWidget* parent) -{ - // create GUI widgets from the Qt Designer's .ui file - m_Controls.setupUi(parent); - - m_Controls.labelNode->setText(QString("select node...")); - m_Controls.labelTime->setText(QString("")); - m_Controls.labelSlice->setText(QString("")); - - mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart(); - RenderWindowPartActivated(renderWindowPart); -} + // Taken from QmitkStdMultiWidget::HandleCrosshairPositionEvent(). + // Since there are always 3 events arriving (one for each render window) every time the slice + // or time changes, the slot OnSliceChangedDelayed is triggered - and only if it hasn't been + // triggered yet - so it is only executed once for every slice/time change. + if (!m_PendingSliceChangedEvent) + { + m_PendingSliceChangedEvent = true; -void QmitkDicomInspectorView::SetFocus() -{ + QTimer::singleShot(0, this, SLOT(OnSliceChangedDelayed())); + } } -void QmitkDicomInspectorView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/, - const QList& nodes) +void QmitkDicomInspectorView::OnSliceNavigationControllerDeleted(const itk::Object* sender, const itk::EventObject& /*e*/) { - if (nodes.size() > 0) - { - if (nodes.front() != this->m_currentSelectedNode) - { - m_internalUpdateFlag = true; - this->m_currentSelectedNode = nodes.front(); - this->m_currentSelectedData = this->m_currentSelectedNode->GetData(); - m_internalUpdateFlag = false; - - m_selectedNodeTime.Modified(); - UpdateData(); - OnSliceChangedDelayed(); - } - } - else - { - if (this->m_currentSelectedNode.IsNotNull()) - { - m_internalUpdateFlag = true; - this->m_currentSelectedNode = nullptr; - this->m_currentSelectedData = nullptr; - m_internalUpdateFlag = false; - - m_selectedNodeTime.Modified(); - UpdateData(); - OnSliceChangedDelayed(); - } - } + auto sendingSlicer = dynamic_cast(sender); + this->RemoveObservers(sendingSlicer); } void QmitkDicomInspectorView::ValidateAndSetCurrentPosition() { mitk::Point3D currentSelectedPosition = GetRenderWindowPart()->GetSelectedPosition(nullptr); unsigned int currentSelectedTimeStep = GetRenderWindowPart()->GetTimeNavigationController()->GetTime()->GetPos(); - if (m_currentSelectedPosition != currentSelectedPosition - || m_currentSelectedTimeStep != currentSelectedTimeStep - || m_selectedNodeTime > m_currentPositionTime) + if (m_SelectedPosition != currentSelectedPosition + || m_SelectedTimeStep != currentSelectedTimeStep + || m_SelectedNodeTime > m_CurrentPositionTime) { - //the current position has been changed or the selected node has been changed since the last position validation -> check position - m_currentSelectedPosition = currentSelectedPosition; - m_currentSelectedTimeStep = currentSelectedTimeStep; - m_currentPositionTime.Modified(); - m_validSelectedPosition = false; - - if (m_currentSelectedData.IsNull()) + // the current position has been changed or the selected node has been changed since + // the last position validation -> check position + m_SelectedPosition = currentSelectedPosition; + m_SelectedTimeStep = currentSelectedTimeStep; + m_CurrentPositionTime.Modified(); + m_ValidSelectedPosition = false; + + if (m_SelectedData.IsNull()) { return; } - mitk::BaseGeometry::Pointer geometry = m_currentSelectedData->GetTimeGeometry()->GetGeometryForTimeStep( - m_currentSelectedTimeStep); + mitk::BaseGeometry::Pointer geometry = m_SelectedData->GetTimeGeometry()->GetGeometryForTimeStep( + m_SelectedTimeStep); // check for invalid time step if (geometry.IsNull()) { - geometry = m_currentSelectedData->GetTimeGeometry()->GetGeometryForTimeStep(0); + geometry = m_SelectedData->GetTimeGeometry()->GetGeometryForTimeStep(0); } if (geometry.IsNull()) { return; } - m_validSelectedPosition = geometry->IsInside(m_currentSelectedPosition); + m_ValidSelectedPosition = geometry->IsInside(m_SelectedPosition); itk::Index<3> index; - geometry->WorldToIndex(m_currentSelectedPosition, index); - - m_currentSelectedZSlice = index[2]; - } -} + geometry->WorldToIndex(m_SelectedPosition, index); -void QmitkDicomInspectorView::OnSliceChanged(const itk::EventObject&) -{ - // Taken from QmitkStdMultiWidget::HandleCrosshairPositionEvent(). - // Since there are always 3 events arriving (one for each render window) every time the slice - // or time changes, the slot OnSliceChangedDelayed is triggered - and only if it hasn't been - // triggered yet - so it is only executed once for every slice/time change. - if (!m_PendingSliceChangedEvent) - { - m_PendingSliceChangedEvent = true; - - QTimer::singleShot(0, this, SLOT(OnSliceChangedDelayed())); + m_CurrentSelectedZSlice = index[2]; } } void QmitkDicomInspectorView::OnSliceChangedDelayed() { m_PendingSliceChangedEvent = false; ValidateAndSetCurrentPosition(); - m_Controls.tableTags->setEnabled(m_validSelectedPosition); + m_Controls.tableTags->setEnabled(m_ValidSelectedPosition); - if (m_currentSelectedNode.IsNotNull()) + if (m_SelectedNode.IsNotNull()) { RenderTable(); } } void QmitkDicomInspectorView::RenderTable() { - assert(m_renderWindowPart != nullptr); + assert(nullptr != m_RenderWindowPart); // configure fit information unsigned int rowIndex = 0; for (const auto& element : m_Tags) { - QTableWidgetItem* newItem = new QTableWidgetItem(QString::fromStdString(element.second.prop->GetValue(m_currentSelectedTimeStep, m_currentSelectedZSlice, true, true))); + QTableWidgetItem* newItem = new QTableWidgetItem(QString::fromStdString( + element.second.prop->GetValue(m_SelectedTimeStep, m_CurrentSelectedZSlice, true, true))); m_Controls.tableTags->setItem(rowIndex, 3, newItem); ++rowIndex; } UpdateLabels(); } void QmitkDicomInspectorView::UpdateData() { QStringList headers; m_Controls.tableTags->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents); m_Tags.clear(); - if (m_currentSelectedData.IsNotNull()) + if (m_SelectedData.IsNotNull()) { - for (const auto& element : *(m_currentSelectedData->GetPropertyList()->GetMap())) + for (const auto& element : *(m_SelectedData->GetPropertyList()->GetMap())) { if (element.first.find("DICOM") == 0) { std::istringstream stream(element.first); std::string token; std::getline(stream, token, '.'); //drop the DICOM suffix std::getline(stream, token, '.'); //group id unsigned long dcmgroup = std::stoul(token, nullptr, 16); std::getline(stream, token, '.'); //element id unsigned long dcmelement = std::stoul(token, nullptr, 16); TagInfo info(mitk::DICOMTag(dcmgroup, dcmelement), dynamic_cast(element.second.GetPointer())); m_Tags.insert(std::make_pair(element.first, info)); } } } m_Controls.tableTags->setRowCount(m_Tags.size()); unsigned int rowIndex = 0; for (const auto& element : m_Tags) { QTableWidgetItem* newItem = new QTableWidgetItem(QString::number(element.second.tag.GetGroup(), 16)); m_Controls.tableTags->setItem(rowIndex, 0, newItem); newItem = new QTableWidgetItem(QString::number(element.second.tag.GetElement(), 16)); m_Controls.tableTags->setItem(rowIndex, 1, newItem); newItem = new QTableWidgetItem(QString::fromStdString(element.second.tag.GetName())); m_Controls.tableTags->setItem(rowIndex, 2, newItem); newItem = new QTableWidgetItem(QString::fromStdString(element.second.prop->GetValue())); m_Controls.tableTags->setItem(rowIndex, 3, newItem); ++rowIndex; } + UpdateLabels(); } void QmitkDicomInspectorView::UpdateLabels() { - if (m_currentSelectedData.IsNull()) + if (m_SelectedData.IsNull()) { - if (m_currentSelectedNode.IsNotNull()) - { - m_Controls.labelNode->setText(QString("INVALIDE NODE")); - } - else - { - m_Controls.labelNode->setText(QString("select node...")); - } - m_Controls.labelTime->setText(QString("")); - m_Controls.labelSlice->setText(QString("")); + m_Controls.timePointValueLabel->setText(QString("")); + m_Controls.sliceNumberValueLabel->setText(QString("")); } else { - m_Controls.labelNode->setText(QString::fromStdString(m_currentSelectedNode->GetName())); - if (m_validSelectedPosition) + if (m_ValidSelectedPosition) { - m_Controls.labelTime->setText(QString::number(m_currentSelectedTimeStep)); - m_Controls.labelSlice->setText(QString::number(m_currentSelectedZSlice)); + m_Controls.timePointValueLabel->setText(QString::number(m_SelectedTimeStep)); + m_Controls.sliceNumberValueLabel->setText(QString::number(m_CurrentSelectedZSlice)); } else { - m_Controls.labelTime->setText(QString("outside data geometry")); - m_Controls.labelSlice->setText(QString("outside data geometry")); + m_Controls.timePointValueLabel->setText(QString("outside data geometry")); + m_Controls.sliceNumberValueLabel->setText(QString("outside data geometry")); } } } + +void QmitkDicomInspectorView::SetAsSelectionListener(bool checked) +{ + if (checked) + { + m_SelectionServiceConnector->AddPostSelectionListener(GetSite()->GetWorkbenchWindow()->GetSelectionService()); + connect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, + m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); + } + else + { + m_SelectionServiceConnector->RemovePostSelectionListener(); + disconnect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, + m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); + } +} diff --git a/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorView.h b/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorView.h index 926eb5a5ac..8746fa6126 100644 --- a/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorView.h +++ b/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorView.h @@ -1,158 +1,155 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ - #ifndef QmitkDicomInspectorView_h #define QmitkDicomInspectorView_h +#include "ui_QmitkDicomInspectorViewControls.h" + // Blueberry -//#include #include -// mitk -#include -#include +// mitk DICOMReader module #include #include -// Qt -#include "ui_QmitkDicomInspectorViewControls.h" +// mitk gui common plugin +#include +// mitk gui qt common plugin +#include +#include /** - * @brief View class defining the UI part of the ModelFitVisualization plug-in. + * @brief View class to inspect all DICOM tags available for the data of a node. */ -class QmitkDicomInspectorView : - public QmitkAbstractView, - public mitk::IRenderWindowPartListener +class QmitkDicomInspectorView : public QmitkAbstractView, public mitk::IRenderWindowPartListener { - // this is needed for all Qt objects that should have a Qt meta-object - // (everything that derives from QObject and wants to have signal/slots) + Q_OBJECT public: QmitkDicomInspectorView(); ~QmitkDicomInspectorView() override; static const std::string VIEW_ID; - protected slots: + void SetFocus() override { }; - /** - * @brief Triggered when the voxel or time step selection changes. - * Calculates the curve and points for the current fit if the visualization is running. - */ - void OnSliceChangedDelayed(); + void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) override; + void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) override; protected: void CreateQtPartControl(QWidget* parent) override; - void SetFocus() override; + /** @brief Initializes and sets the observers that are used to monitor changes in the selected position + or time point in order to actualize the view*/ + bool InitObservers(); - /** @brief called by QmitkFunctionality when DataManager's selection has changed */ - void OnSelectionChanged(berry::IWorkbenchPart::Pointer source, - const QList& nodes) override; + /** @brief Removes all observers of the specific deleted slice navigation controller.*/ + void RemoveObservers(const mitk::SliceNavigationController* deletedSlicer); - /** @brief Calls OnSliceChangedDelayed so the event isn't triggered multiple times. */ - void OnSliceChanged(const itk::EventObject& e); + /** @brief Removes all observers of the deletedPart. If null pointer is passed all observers will be removed.*/ + void RemoveAllObservers(mitk::IRenderWindowPart* deletedPart = nullptr); - void OnSliceNavigationControllerDeleted(const itk::Object* sender, const itk::EventObject& /*e*/); + /** @brief Called by the selection widget when the selection has changed.*/ + void OnCurrentSelectionChanged(QList nodes); - void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) override; - void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) override; + /** @brief Calls OnSliceChangedDelayed so the event isn't triggered multiple times.*/ + void OnSliceChanged(); - /** Initializes and sets the observers that are used to monitor changes in the selected position - or time point in order to actualize the view.h*/ - bool InitObservers(); - void RemoveObservers(const mitk::SliceNavigationController* deletedSlicer); - /** Removes all observers of the deletedPart. If null pointer is passed all observers will be removed.*/ - void RemoveAllObservers(mitk::IRenderWindowPart* deletedPart = nullptr); + void OnSliceNavigationControllerDeleted(const itk::Object* sender, const itk::EventObject& /*e*/); - /** Sets m_currentSelectedPosition to the current selection and validates if this position is valid + /** @brief Sets m_currentSelectedPosition to the current selection and validates if this position is valid * for the input image of the currently selected fit. If it is valid, m_validSelectedPosition is set to true. * If the fit, his input image or geometry is not specified, it will also handled as invalid.*/ void ValidateAndSetCurrentPosition(); - Ui::DicomInspectorViewControls m_Controls; - mitk::IRenderWindowPart* m_renderWindowPart; +private Q_SLOTS: + + /** @brief Updates the current slice and time is correctly displayed.*/ + void OnSliceChangedDelayed(); + +private: + + void RenderTable(); + + /** (Re-)initializes the headers of the data table.*/ + void UpdateData(); + void UpdateLabels(); + + void SetAsSelectionListener(bool checked); - // Needed for observing the events for when a slice or time step is changed. + Ui::QmitkDicomInspectorViewControls m_Controls; + mitk::IRenderWindowPart* m_RenderWindowPart; + + std::unique_ptr m_SelectionServiceConnector; + + /** Needed for observing the events for when a slice or time step is changed.*/ bool m_PendingSliceChangedEvent; - /**Helper structure to manage the registered observer events.*/ + /** Helper structure to manage the registered observer events.*/ struct ObserverInfo { mitk::SliceNavigationController* controller; int observerTag; std::string renderWindowName; mitk::IRenderWindowPart* renderWindowPart; ObserverInfo(mitk::SliceNavigationController* controller, int observerTag, const std::string& renderWindowName, mitk::IRenderWindowPart* part); }; typedef std::multimap ObserverMapType; ObserverMapType m_ObserverMap; - /** @brief currently valid selected position in the inspector*/ - mitk::Point3D m_currentSelectedPosition; - /** @brief indicates if the currently selected position is valid for the currently selected fit. - * This it is within the input image */ - bool m_validSelectedPosition; - - unsigned int m_currentSelectedTimeStep; - - itk::IndexValueType m_currentSelectedZSlice; + /** @brief Currently selected node for the DICOM information.*/ + mitk::DataNode::ConstPointer m_SelectedNode; + /** @brief Base data of the currently selected node.*/ + mitk::BaseData::ConstPointer m_SelectedData; - /** @brief currently selected node for the visualization logic*/ - mitk::DataNode::ConstPointer m_currentSelectedNode; + /** @brief Valid selected position in the inspector.*/ + mitk::Point3D m_SelectedPosition; + /** @brief Indicates if the currently selected position is valid for the currently selected data.*/ + bool m_ValidSelectedPosition; - mitk::BaseData::ConstPointer m_currentSelectedData; + unsigned int m_SelectedTimeStep; - /** @brief Is a visualization currently running? */ - bool m_internalUpdateFlag; - - /** @brief Number of interpolation steps between two x values */ - static const unsigned int INTERPOLATION_STEPS; + itk::IndexValueType m_CurrentSelectedZSlice; /*************************************/ /* Members for visualizing the model */ - itk::TimeStamp m_selectedNodeTime; - itk::TimeStamp m_currentFitTime; - itk::TimeStamp m_currentPositionTime; - itk::TimeStamp m_lastRefreshTime; + itk::TimeStamp m_SelectedNodeTime; + itk::TimeStamp m_CurrentPositionTime; /**Helper structure to manage the registered observer events.*/ struct TagInfo { mitk::DICOMTag tag; mitk::DICOMProperty::ConstPointer prop; - TagInfo(const mitk::DICOMTag& aTag, mitk::DICOMProperty::ConstPointer aProp) : tag(aTag), prop(aProp) + TagInfo(const mitk::DICOMTag& aTag, mitk::DICOMProperty::ConstPointer aProp) + : tag(aTag) + , prop(aProp) { }; }; typedef std::map TagMapType; TagMapType m_Tags; - void RenderTable(); - - /** (re)initializes the headers of the data table*/ - void UpdateData(); - void UpdateLabels(); }; #endif // QmitkDicomInspectorView_h diff --git a/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorViewControls.ui b/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorViewControls.ui index bd7b2fad2c..8acd57fbec 100644 --- a/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorViewControls.ui +++ b/Plugins/org.mitk.gui.qt.dicominspector/src/internal/QmitkDicomInspectorViewControls.ui @@ -1,194 +1,195 @@ - DicomInspectorViewControls - + QmitkDicomInspectorViewControls + 0 0 - 402 - 777 + 300 + 600 - - - 0 - 0 - - - - QmitkTemplate - 5 5 5 5 5 - - - - Time point: - - - - + + +- +- 0 +- 0 +- +- - Node: + Selected data node - + - + 0 0 - - textlabel + + + 0 + 40 + - - - - + + + + 0 0 - TextLabel + Time point - - + + - + 0 0 + + + + + +- +- 0 +- 0 +- +- - Slice Nr: + Slice number - + - + 0 0 - - TextLabel - 8 QAbstractItemView::NoEditTriggers false QAbstractItemView::NoSelection false 75 false false true false 20 20 Group # Element # Name Value - - - - - - - + + + QmitkSingleNodeSelectionWidget + QWidget +
QmitkSingleNodeSelectionWidget.h
+ 1 +
+
diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp index 98933fe429..e70d8edae3 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp @@ -1,456 +1,439 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkGetPropertyService.h" #include "QmitkAddNewPropertyDialog.h" #include "QmitkPropertiesPreferencePage.h" #include "QmitkPropertyItemDelegate.h" #include "QmitkPropertyItemModel.h" #include "QmitkPropertyItemSortFilterProxyModel.h" #include "QmitkPropertyTreeView.h" #include #include #include #include #include #include #include #include const std::string QmitkPropertyTreeView::VIEW_ID = "org.mitk.views.properties"; QmitkPropertyTreeView::QmitkPropertyTreeView() - : m_Parent(nullptr), - m_PropertyNameChangedTag(0), - m_PropertyAliases(nullptr), + : m_PropertyAliases(nullptr), m_PropertyDescriptions(nullptr), m_PropertyPersistence(nullptr), m_ShowAliasesInDescription(true), m_ShowPersistenceInDescription(true), m_DeveloperMode(false), m_ProxyModel(nullptr), m_Model(nullptr), m_Delegate(nullptr), m_Renderer(nullptr) { } QmitkPropertyTreeView::~QmitkPropertyTreeView() { } -void QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent) +void QmitkPropertyTreeView::SetFocus() +{ + m_Controls.filterLineEdit->setFocus(); +} + +void QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* /*renderWindowPart*/) { - m_Parent = parent; + if (m_Controls.propertyListComboBox->count() == 2) + { + QHash renderWindows = this->GetRenderWindowPart()->GetQmitkRenderWindows(); + Q_FOREACH(QString renderWindow, renderWindows.keys()) + { + m_Controls.propertyListComboBox->insertItem(m_Controls.propertyListComboBox->count() - 1, QString("Data node: ") + renderWindow); + } + } +} + +void QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*) +{ + if (m_Controls.propertyListComboBox->count() > 2) + { + m_Controls.propertyListComboBox->clear(); + m_Controls.propertyListComboBox->addItem("Data node: common"); + m_Controls.propertyListComboBox->addItem("Base data"); + } +} + +void QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent) +{ m_Controls.setupUi(parent); m_Controls.propertyListComboBox->addItem("Data node: common"); mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); - if (renderWindowPart != nullptr) { QHash renderWindows = renderWindowPart->GetQmitkRenderWindows(); - Q_FOREACH(QString renderWindow, renderWindows.keys()) + for(const auto& renderWindow : renderWindows.keys()) { m_Controls.propertyListComboBox->addItem(QString("Data node: ") + renderWindow); } } m_Controls.propertyListComboBox->addItem("Base data"); m_Controls.newButton->setEnabled(false); this->HideAllIcons(); m_Controls.descriptionLabel->hide(); m_Controls.propertyListLabel->hide(); m_Controls.propertyListComboBox->hide(); m_Controls.newButton->hide(); m_ProxyModel = new QmitkPropertyItemSortFilterProxyModel(m_Controls.treeView); m_Model = new QmitkPropertyItemModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_Model); m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setDynamicSortFilter(true); m_Delegate = new QmitkPropertyItemDelegate(m_Controls.treeView); + m_Controls.singleSlot->SetDataStorage(GetDataStorage()); + m_Controls.singleSlot->SetSelectionIsOptional(true); + m_Controls.singleSlot->SetEmptyInfo(QString("Please select a data node")); + m_Controls.singleSlot->SetPopUpTitel(QString("Select data node")); + + m_SelectionServiceConnector = std::make_unique(); + SetAsSelectionListener(true); + m_Controls.filterLineEdit->setClearButtonEnabled(true); m_Controls.treeView->setItemDelegateForColumn(1, m_Delegate); m_Controls.treeView->setModel(m_ProxyModel); m_Controls.treeView->setColumnWidth(0, 160); m_Controls.treeView->sortByColumn(0, Qt::AscendingOrder); m_Controls.treeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked); const int ICON_SIZE = 32; auto icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/tags.svg")); m_Controls.tagsLabel->setPixmap(icon.pixmap(ICON_SIZE)); icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/tag.svg")); m_Controls.tagLabel->setPixmap(icon.pixmap(ICON_SIZE)); icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/document-save.svg")); m_Controls.saveLabel->setPixmap(icon.pixmap(ICON_SIZE)); - connect(m_Controls.filterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(OnFilterTextChanged(const QString&))); - connect(m_Controls.propertyListComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPropertyListChanged(int))); - connect(m_Controls.newButton, SIGNAL(clicked()), this, SLOT(OnAddNewProperty())); - connect(m_Controls.treeView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(OnCurrentRowChanged(const QModelIndex&, const QModelIndex&))); - connect(m_Model, SIGNAL(modelReset()), this, SLOT(OnModelReset())); + connect(m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, + this, &QmitkPropertyTreeView::OnCurrentSelectionChanged); + connect(m_Controls.filterLineEdit, &QLineEdit::textChanged, + this, &QmitkPropertyTreeView::OnFilterTextChanged); + connect(m_Controls.propertyListComboBox, static_cast(&QComboBox::currentIndexChanged), + this, &QmitkPropertyTreeView::OnPropertyListChanged); + connect(m_Controls.newButton, &QPushButton::clicked, + this, &QmitkPropertyTreeView::OnAddNewProperty); + connect(m_Controls.treeView->selectionModel(), &QItemSelectionModel::currentRowChanged, + this, &QmitkPropertyTreeView::OnCurrentRowChanged); + connect(m_Model, &QmitkPropertyItemModel::modelReset, + this, &QmitkPropertyTreeView::OnModelReset); +} + +void QmitkPropertyTreeView::OnPreferencesChanged(const berry::IBerryPreferences* preferences) +{ + bool showAliases = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES, true); + bool showDescriptions = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_DESCRIPTIONS, true); + bool showAliasesInDescription = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES_IN_DESCRIPTION, true); + bool showPersistenceInDescription = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_PERSISTENCE_IN_DESCRIPTION, true); + bool developerMode = preferences->GetBool(QmitkPropertiesPreferencePage::DEVELOPER_MODE, false); + bool filterProperties = preferences->GetBool(QmitkPropertiesPreferencePage::FILTER_PROPERTIES, true); + + m_Model->SetFilterProperties(filterProperties); + m_Model->SetShowAliases(showAliases); + + bool updateAliases = showAliases != (m_PropertyAliases != nullptr); + bool updateDescriptions = showDescriptions != (m_PropertyDescriptions != nullptr); + bool updateAliasesInDescription = showAliasesInDescription != m_ShowAliasesInDescription; + bool updatePersistenceInDescription = showPersistenceInDescription != m_ShowPersistenceInDescription; + bool updateDeveloperMode = developerMode != m_DeveloperMode; + + if (updateAliases) + m_PropertyAliases = showAliases + ? mitk::GetPropertyService() + : nullptr; + + if (updateDescriptions) + m_PropertyDescriptions = showDescriptions + ? mitk::GetPropertyService() + : nullptr; + + if (showPersistenceInDescription) + m_PropertyPersistence = mitk::GetPropertyService(); + + if (updateAliasesInDescription) + m_ShowAliasesInDescription = showAliasesInDescription; + + if (updatePersistenceInDescription) + m_ShowPersistenceInDescription = showPersistenceInDescription; + + if (updateDescriptions || updateAliasesInDescription || updatePersistenceInDescription) + { + QModelIndexList selection = m_Controls.treeView->selectionModel()->selectedRows(); + + if (!selection.isEmpty()) + this->OnCurrentRowChanged(selection[0], selection[0]); + } + + if (updateDeveloperMode) + { + m_DeveloperMode = developerMode; + + if (!developerMode) + m_Controls.propertyListComboBox->setCurrentIndex(0); + + m_Controls.propertyListLabel->setVisible(developerMode); + m_Controls.propertyListComboBox->setVisible(developerMode); + m_Controls.newButton->setVisible(developerMode); + } + + m_Model->OnPreferencesChanged(); +} + +void QmitkPropertyTreeView::SetAsSelectionListener(bool checked) +{ + if (checked) + { + m_SelectionServiceConnector->AddPostSelectionListener(GetSite()->GetWorkbenchWindow()->GetSelectionService()); + connect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); + } + else + { + m_SelectionServiceConnector->RemovePostSelectionListener(); + disconnect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); + } } QString QmitkPropertyTreeView::GetPropertyNameOrAlias(const QModelIndex& index) { QString propertyName; if (index.isValid()) { QModelIndex current = index; while (current.isValid()) { QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString(); propertyName.prepend(propertyName.isEmpty() ? name : name.append('.')); current = current.parent(); } } return propertyName; } +void QmitkPropertyTreeView::OnCurrentSelectionChanged(QList nodes) +{ + if (nodes.empty() || nodes.front().IsNull()) + { + m_SelectedNode = nullptr; + + this->SetPartName("Properties"); + m_Model->SetPropertyList(nullptr); + m_Delegate->SetPropertyList(nullptr); + + m_Controls.newButton->setEnabled(false); + + return; + } + + // node is selected, create tree with node properties + m_SelectedNode = nodes.front(); + mitk::PropertyList* propertyList = m_Model->GetPropertyList(); + if (m_Renderer == nullptr && m_Controls.propertyListComboBox->currentText() == "Base data") + { + propertyList = m_SelectedNode->GetData() != nullptr + ? m_SelectedNode->GetData()->GetPropertyList() + : nullptr; + } + else + { + propertyList = m_SelectedNode->GetPropertyList(m_Renderer); + } + + QString selectionClassName = m_SelectedNode->GetData() != nullptr + ? m_SelectedNode->GetData()->GetNameOfClass() + : ""; + + m_SelectionClassName = selectionClassName.toStdString(); + + m_Model->SetPropertyList(propertyList, selectionClassName); + m_Delegate->SetPropertyList(propertyList); + + m_Controls.newButton->setEnabled(true); + + if (!m_ProxyModel->filterRegExp().isEmpty()) + { + m_Controls.treeView->expandAll(); + } +} + +void QmitkPropertyTreeView::HideAllIcons() +{ + m_Controls.tagLabel->hide(); + m_Controls.tagsLabel->hide(); + m_Controls.saveLabel->hide(); +} + void QmitkPropertyTreeView::OnCurrentRowChanged(const QModelIndex& current, const QModelIndex&) { if (m_PropertyDescriptions != nullptr && current.isValid()) { QString name = this->GetPropertyNameOrAlias(current); if (!name.isEmpty()) { QString alias; bool isTrueName = true; if (m_PropertyAliases != nullptr) { std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString()); if (trueName.empty() && !m_SelectionClassName.empty()) trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName); if (!trueName.empty()) { alias = name; name = QString::fromStdString(trueName); isTrueName = false; } } QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString())); std::vector aliases; if (!isTrueName && m_PropertyAliases != nullptr) { aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName); if (aliases.empty() && !m_SelectionClassName.empty()) aliases = m_PropertyAliases->GetAliases(name.toStdString()); } bool isPersistent = false; if (m_PropertyPersistence != nullptr) isPersistent = m_PropertyPersistence->HasInfo(name.toStdString()); if (!description.isEmpty() || !aliases.empty() || isPersistent) { QString customizedDescription; if (m_ShowAliasesInDescription && !aliases.empty()) { customizedDescription = "

" + name + "

"; std::size_t numAliases = aliases.size(); std::size_t lastAlias = numAliases - 1; for (std::size_t i = 0; i < numAliases; ++i) { customizedDescription += i != lastAlias ? "
" : "
"; customizedDescription += QString::fromStdString(aliases[i]) + "
"; } } else { customizedDescription = "

" + name + "

"; } if (!description.isEmpty()) customizedDescription += "

" + description + "

"; m_Controls.tagsLabel->setVisible(!aliases.empty() && aliases.size() > 1); m_Controls.tagLabel->setVisible(!aliases.empty() && aliases.size() == 1); m_Controls.saveLabel->setVisible(isPersistent); m_Controls.descriptionLabel->setText(customizedDescription); m_Controls.descriptionLabel->show(); return; } } } m_Controls.descriptionLabel->hide(); this->HideAllIcons(); } -void QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter) -{ - m_ProxyModel->setFilterWildcard(filter); - - if (filter.isEmpty()) - m_Controls.treeView->collapseAll(); - else - m_Controls.treeView->expandAll(); -} - -void QmitkPropertyTreeView::OnModelReset() -{ - m_Controls.descriptionLabel->hide(); - this->HideAllIcons(); -} - -void QmitkPropertyTreeView::OnPreferencesChanged(const berry::IBerryPreferences* preferences) -{ - bool showAliases = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES, true); - bool showDescriptions = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_DESCRIPTIONS, true); - bool showAliasesInDescription = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES_IN_DESCRIPTION, true); - bool showPersistenceInDescription = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_PERSISTENCE_IN_DESCRIPTION, true); - bool developerMode = preferences->GetBool(QmitkPropertiesPreferencePage::DEVELOPER_MODE, false); - bool filterProperties = preferences->GetBool(QmitkPropertiesPreferencePage::FILTER_PROPERTIES, true); - - m_Model->SetFilterProperties(filterProperties); - m_Model->SetShowAliases(showAliases); - - bool updateAliases = showAliases != (m_PropertyAliases != nullptr); - bool updateDescriptions = showDescriptions != (m_PropertyDescriptions != nullptr); - bool updateAliasesInDescription = showAliasesInDescription != m_ShowAliasesInDescription; - bool updatePersistenceInDescription = showPersistenceInDescription != m_ShowPersistenceInDescription; - bool updateDeveloperMode = developerMode != m_DeveloperMode; - - if (updateAliases) - m_PropertyAliases = showAliases - ? mitk::GetPropertyService() - : nullptr; - - if (updateDescriptions) - m_PropertyDescriptions = showDescriptions - ? mitk::GetPropertyService() - : nullptr; - - if (showPersistenceInDescription) - m_PropertyPersistence = mitk::GetPropertyService(); - - if (updateAliasesInDescription) - m_ShowAliasesInDescription = showAliasesInDescription; - - if (updatePersistenceInDescription) - m_ShowPersistenceInDescription = showPersistenceInDescription; - - if (updateDescriptions || updateAliasesInDescription || updatePersistenceInDescription) - { - QModelIndexList selection = m_Controls.treeView->selectionModel()->selectedRows(); - - if (!selection.isEmpty()) - this->OnCurrentRowChanged(selection[0], selection[0]); - } - - if (updateDeveloperMode) - { - m_DeveloperMode = developerMode; - - if (!developerMode) - m_Controls.propertyListComboBox->setCurrentIndex(0); - - m_Controls.propertyListLabel->setVisible(developerMode); - m_Controls.propertyListComboBox->setVisible(developerMode); - m_Controls.newButton->setVisible(developerMode); - } - - m_Model->OnPreferencesChanged(); -} - -void QmitkPropertyTreeView::OnPropertyNameChanged(const itk::EventObject&) -{ - mitk::PropertyList* propertyList = m_Model->GetPropertyList(); - - if (propertyList != nullptr) - { - mitk::BaseProperty* nameProperty = propertyList->GetProperty("name"); - - if (nameProperty != nullptr) - { - QString partName = "Properties ("; - partName.append(QString::fromStdString(nameProperty->GetValueAsString())).append(')'); - this->SetPartName(partName); - } - } -} - -void QmitkPropertyTreeView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& nodes) -{ - mitk::PropertyList* propertyList = m_Model->GetPropertyList(); - - if (propertyList != nullptr) - { - mitk::BaseProperty* nameProperty = propertyList->GetProperty("name"); - - if (nameProperty != nullptr) - nameProperty->RemoveObserver(m_PropertyNameChangedTag); - - m_PropertyNameChangedTag = 0; - } - - if (nodes.empty() || nodes.front().IsNull()) - { - m_SelectedNode = nullptr; - - this->SetPartName("Properties"); - m_Model->SetPropertyList(nullptr); - m_Delegate->SetPropertyList(nullptr); - - m_Controls.newButton->setEnabled(false); - } - else - { - m_SelectedNode = nodes.front(); - - QString selectionClassName = m_SelectedNode->GetData() != nullptr - ? m_SelectedNode->GetData()->GetNameOfClass() - : ""; - - m_SelectionClassName = selectionClassName.toStdString(); - - mitk::PropertyList::Pointer propertyList; - - if (m_Renderer == nullptr && m_Controls.propertyListComboBox->currentText() == "Base data") - { - propertyList = m_SelectedNode->GetData() != nullptr - ? m_SelectedNode->GetData()->GetPropertyList() - : nullptr; - } - else - { - propertyList = m_SelectedNode->GetPropertyList(m_Renderer); - } - - m_Model->SetPropertyList(propertyList, selectionClassName); - m_Delegate->SetPropertyList(propertyList); - - OnPropertyNameChanged(itk::ModifiedEvent()); - - mitk::BaseProperty* nameProperty = m_SelectedNode->GetProperty("name"); - - if (nameProperty != nullptr) - { - itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); - command->SetCallbackFunction(this, &QmitkPropertyTreeView::OnPropertyNameChanged); - m_PropertyNameChangedTag = nameProperty->AddObserver(itk::ModifiedEvent(), command); - } - - m_Controls.newButton->setEnabled(true); - } - - if (!m_ProxyModel->filterRegExp().isEmpty()) - m_Controls.treeView->expandAll(); -} - -void QmitkPropertyTreeView::SetFocus() -{ - m_Controls.filterLineEdit->setFocus(); -} - -void QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* /*renderWindowPart*/) -{ - if (m_Controls.propertyListComboBox->count() == 2) - { - QHash renderWindows = this->GetRenderWindowPart()->GetQmitkRenderWindows(); - - Q_FOREACH(QString renderWindow, renderWindows.keys()) - { - m_Controls.propertyListComboBox->insertItem(m_Controls.propertyListComboBox->count() - 1, QString("Data node: ") + renderWindow); - } - } -} - -void QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*) -{ - if (m_Controls.propertyListComboBox->count() > 2) - { - m_Controls.propertyListComboBox->clear(); - m_Controls.propertyListComboBox->addItem("Data node: common"); - m_Controls.propertyListComboBox->addItem("Base data"); - } -} - void QmitkPropertyTreeView::OnPropertyListChanged(int index) { if (index == -1) return; QString renderer = m_Controls.propertyListComboBox->itemText(index); if (renderer.startsWith("Data node: ")) renderer = QString::fromStdString(renderer.toStdString().substr(11)); m_Renderer = renderer != "common" && renderer != "Base data" ? this->GetRenderWindowPart()->GetQmitkRenderWindow(renderer)->GetRenderer() : nullptr; QList nodes; if (m_SelectedNode.IsNotNull()) nodes << m_SelectedNode; - berry::IWorkbenchPart::Pointer workbenchPart; - - this->OnSelectionChanged(workbenchPart, nodes); + this->OnCurrentSelectionChanged(nodes); } void QmitkPropertyTreeView::OnAddNewProperty() { std::unique_ptr dialog(m_Controls.propertyListComboBox->currentText() != "Base data" - ? new QmitkAddNewPropertyDialog(m_SelectedNode, m_Renderer, m_Parent) - : new QmitkAddNewPropertyDialog(m_SelectedNode->GetData())); + ? new QmitkAddNewPropertyDialog(m_SelectedNode, m_Renderer) + : new QmitkAddNewPropertyDialog(m_SelectedNode->GetData())); if (dialog->exec() == QDialog::Accepted) this->m_Model->Update(); } -void QmitkPropertyTreeView::HideAllIcons() +void QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter) { - m_Controls.tagLabel->hide(); - m_Controls.tagsLabel->hide(); - m_Controls.saveLabel->hide(); + m_ProxyModel->setFilterWildcard(filter); + + if (filter.isEmpty()) + m_Controls.treeView->collapseAll(); + else + m_Controls.treeView->expandAll(); +} + +void QmitkPropertyTreeView::OnModelReset() +{ + m_Controls.descriptionLabel->hide(); + this->HideAllIcons(); } diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.h b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.h index 4c5c23f6c1..f0621609a7 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.h +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.h @@ -1,84 +1,99 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkPropertyTreeView_h #define QmitkPropertyTreeView_h +#include + +// mitk core module #include + +// mitk gui common plugin #include + +// mitk gui qt common plugin #include -#include +#include "QmitkSelectionServiceConnector.h" class QmitkPropertyItemDelegate; class QmitkPropertyItemModel; class QmitkPropertyItemSortFilterProxyModel; namespace mitk { class IPropertyAliases; class IPropertyDescriptions; class IPropertyPersistence; } class QmitkPropertyTreeView : public QmitkAbstractView, public mitk::IRenderWindowPartListener { Q_OBJECT public: + static const std::string VIEW_ID; berryObjectMacro(QmitkPropertyTreeView); QmitkPropertyTreeView(); ~QmitkPropertyTreeView() override; void SetFocus() override; void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) override; void RenderWindowPartDeactivated(mitk::IRenderWindowPart*) override; protected: + void CreateQtPartControl(QWidget* parent) override; private: - QString GetPropertyNameOrAlias(const QModelIndex& index); + void OnPreferencesChanged(const berry::IBerryPreferences* preferences) override; - void OnPropertyNameChanged(const itk::EventObject& event); - void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList& nodes) override; + + void SetAsSelectionListener(bool checked); + + QString GetPropertyNameOrAlias(const QModelIndex& index); + + void OnCurrentSelectionChanged(QList nodes); void HideAllIcons(); -private slots: +private Q_SLOTS: + void OnCurrentRowChanged(const QModelIndex& current, const QModelIndex& previous); void OnPropertyListChanged(int index); void OnAddNewProperty(); void OnFilterTextChanged(const QString& filter); void OnModelReset(); private: - QWidget* m_Parent; - unsigned long m_PropertyNameChangedTag; + std::string m_SelectionClassName; mitk::IPropertyAliases* m_PropertyAliases; mitk::IPropertyDescriptions* m_PropertyDescriptions; mitk::IPropertyPersistence* m_PropertyPersistence; bool m_ShowAliasesInDescription; bool m_ShowPersistenceInDescription; bool m_DeveloperMode; Ui::QmitkPropertyTreeView m_Controls; QmitkPropertyItemSortFilterProxyModel* m_ProxyModel; QmitkPropertyItemModel* m_Model; QmitkPropertyItemDelegate* m_Delegate; mitk::DataNode::Pointer m_SelectedNode; mitk::BaseRenderer* m_Renderer; + + std::unique_ptr m_SelectionServiceConnector; }; #endif diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.ui b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.ui index f572c39667..d1c7d1acce 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.ui +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.ui @@ -1,208 +1,249 @@ QmitkPropertyTreeView 0 0 300 600 + + + + + 0 + 0 + + + + Selected data node + + + + + + + + 0 + 0 + + + + + 0 + 40 + + + + + + + + 0 0 Property List 0 0 Add new property :/Properties/new.png:/Properties/new.png 16 16 false Filter Qt::NoFocus ::item { border-right: 1px solid palette(midlight); padding-bottom: 1px; padding-top: 1px; } ::item:last { border-right: 0; } ::item:selected { background: palette(highlight); color: palette(highlighted-text); } Qt::ScrollBarAsNeeded true true 54 0 0 Qt::RichText true Qt::Horizontal 40 20 32 32 32 32 32 32 32 32 32 32 32 32 + + + QmitkSingleNodeSelectionWidget + QWidget +
QmitkSingleNodeSelectionWidget.h
+ 1 +
+
diff --git a/SuperBuild.cmake b/SuperBuild.cmake index b77c18d592..c1a7f06b60 100644 --- a/SuperBuild.cmake +++ b/SuperBuild.cmake @@ -1,480 +1,481 @@ include(mitkFunctionInstallExternalCMakeProject) #----------------------------------------------------------------------------- # Convenient macro allowing to download a file #----------------------------------------------------------------------------- if(NOT MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL) set(MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL http://mitk.org/download/thirdparty) endif() macro(downloadFile url dest) file(DOWNLOAD ${url} ${dest} STATUS status) list(GET status 0 error_code) list(GET status 1 error_msg) if(error_code) message(FATAL_ERROR "error: Failed to download ${url} - ${error_msg}") endif() endmacro() #----------------------------------------------------------------------------- # MITK Prerequisites #----------------------------------------------------------------------------- if(UNIX AND NOT APPLE) include(mitkFunctionCheckPackageHeader) # Check for libxt-dev mitkFunctionCheckPackageHeader(StringDefs.h libxt-dev /usr/include/X11/) # Check for libtiff4-dev mitkFunctionCheckPackageHeader(tiff.h libtiff4-dev) endif() # We need a proper patch program. On Linux and MacOS, we assume # that "patch" is available. On Windows, we download patch.exe # if not patch program is found. find_program(PATCH_COMMAND patch) if((NOT PATCH_COMMAND OR NOT EXISTS ${PATCH_COMMAND}) AND WIN32) downloadFile(${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/patch.exe ${CMAKE_CURRENT_BINARY_DIR}/patch.exe) find_program(PATCH_COMMAND patch ${CMAKE_CURRENT_BINARY_DIR}) endif() if(NOT PATCH_COMMAND) message(FATAL_ERROR "No patch program found.") endif() #----------------------------------------------------------------------------- # ExternalProjects #----------------------------------------------------------------------------- get_property(external_projects GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS) if(MITK_CTEST_SCRIPT_MODE) # Write a file containing the list of enabled external project targets. # This file can be read by a ctest script to separately build projects. set(SUPERBUILD_TARGETS ) foreach(proj ${external_projects}) if(MITK_USE_${proj}) list(APPEND SUPERBUILD_TARGETS ${proj}) endif() endforeach() file(WRITE "${CMAKE_BINARY_DIR}/SuperBuildTargets.cmake" "set(SUPERBUILD_TARGETS ${SUPERBUILD_TARGETS})") endif() # A list of "nice" external projects, playing well together with CMake set(nice_external_projects ${external_projects}) list(REMOVE_ITEM nice_external_projects Boost) foreach(proj ${nice_external_projects}) if(MITK_USE_${proj}) set(EXTERNAL_${proj}_DIR "${${proj}_DIR}" CACHE PATH "Path to ${proj} build directory") mark_as_advanced(EXTERNAL_${proj}_DIR) if(EXTERNAL_${proj}_DIR) set(${proj}_DIR ${EXTERNAL_${proj}_DIR}) endif() endif() endforeach() set(EXTERNAL_BOOST_ROOT "${BOOST_ROOT}" CACHE PATH "Path to Boost directory") mark_as_advanced(EXTERNAL_BOOST_ROOT) if(EXTERNAL_BOOST_ROOT) set(BOOST_ROOT ${EXTERNAL_BOOST_ROOT}) endif() # Setup file for setting custom ctest vars configure_file( CMake/SuperbuildCTestCustom.cmake.in ${MITK_BINARY_DIR}/CTestCustom.cmake @ONLY ) if(BUILD_TESTING) set(EXTERNAL_MITK_DATA_DIR "${MITK_DATA_DIR}" CACHE PATH "Path to the MITK data directory") mark_as_advanced(EXTERNAL_MITK_DATA_DIR) if(EXTERNAL_MITK_DATA_DIR) set(MITK_DATA_DIR ${EXTERNAL_MITK_DATA_DIR}) endif() endif() #----------------------------------------------------------------------------- # External project settings #----------------------------------------------------------------------------- include(ExternalProject) include(mitkMacroQueryCustomEPVars) set(ep_prefix "${CMAKE_BINARY_DIR}/ep") set_property(DIRECTORY PROPERTY EP_PREFIX ${ep_prefix}) # Compute -G arg for configuring external projects with the same CMake generator: if(CMAKE_EXTRA_GENERATOR) set(gen "${CMAKE_EXTRA_GENERATOR} - ${CMAKE_GENERATOR}") else() set(gen "${CMAKE_GENERATOR}") endif() set(gen_platform ${CMAKE_GENERATOR_PLATFORM}) # Use this value where semi-colons are needed in ep_add args: set(sep "^^") ## if(MSVC_VERSION) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /bigobj /MP") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj /MP") endif() if(MITK_USE_Boost_LIBRARIES) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBOOST_ALL_DYN_LINK") endif() # This is a workaround for passing linker flags # actually down to the linker invocation set(_cmake_required_flags_orig ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "-Wl,-rpath") mitkFunctionCheckCompilerFlags(${CMAKE_REQUIRED_FLAGS} _has_rpath_flag) set(CMAKE_REQUIRED_FLAGS ${_cmake_required_flags_orig}) set(_install_rpath_linkflag ) if(_has_rpath_flag) if(APPLE) set(_install_rpath_linkflag "-Wl,-rpath,@loader_path/../lib") else() set(_install_rpath_linkflag "-Wl,-rpath='$ORIGIN/../lib'") endif() endif() set(_install_rpath) if(APPLE) set(_install_rpath "@loader_path/../lib") elseif(UNIX) # this work for libraries as well as executables set(_install_rpath "\$ORIGIN/../lib") endif() set(ep_common_args -DCMAKE_CXX_EXTENSIONS:STRING=${CMAKE_CXX_EXTENSIONS} -DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD} -DCMAKE_CXX_STANDARD_REQUIRED:BOOL=${CMAKE_CXX_STANDARD_REQUIRED} -DCMAKE_MACOSX_RPATH:BOOL=TRUE "-DCMAKE_INSTALL_RPATH:STRING=${_install_rpath}" -DBUILD_TESTING:BOOL=OFF -DCMAKE_INSTALL_PREFIX:PATH= -DBUILD_SHARED_LIBS:BOOL=ON -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER} -DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER} -DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} "-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} ${MITK_CXX14_FLAG}" #debug flags -DCMAKE_CXX_FLAGS_DEBUG:STRING=${CMAKE_CXX_FLAGS_DEBUG} -DCMAKE_C_FLAGS_DEBUG:STRING=${CMAKE_C_FLAGS_DEBUG} #release flags -DCMAKE_CXX_FLAGS_RELEASE:STRING=${CMAKE_CXX_FLAGS_RELEASE} -DCMAKE_C_FLAGS_RELEASE:STRING=${CMAKE_C_FLAGS_RELEASE} #relwithdebinfo -DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_C_FLAGS_RELWITHDEBINFO} #link flags -DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS} -DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS} -DCMAKE_MODULE_LINKER_FLAGS:STRING=${CMAKE_MODULE_LINKER_FLAGS} ) if(MSVC_VERSION) list(APPEND ep_common_args -DCMAKE_DEBUG_POSTFIX:STRING=d ) set(DCMTK_CMAKE_DEBUG_POSTFIX d) endif() set(ep_common_cache_args ) set(ep_common_cache_default_args "-DCMAKE_PREFIX_PATH:PATH=;${CMAKE_PREFIX_PATH}" "-DCMAKE_INCLUDE_PATH:PATH=${CMAKE_INCLUDE_PATH}" "-DCMAKE_LIBRARY_PATH:PATH=${CMAKE_LIBRARY_PATH}" ) # Pass the CMAKE_OSX variables to external projects if(APPLE) set(MAC_OSX_ARCHITECTURE_ARGS -DCMAKE_OSX_ARCHITECTURES:PATH=${CMAKE_OSX_ARCHITECTURES} -DCMAKE_OSX_DEPLOYMENT_TARGET:PATH=${CMAKE_OSX_DEPLOYMENT_TARGET} -DCMAKE_OSX_SYSROOT:PATH=${CMAKE_OSX_SYSROOT} ) set(ep_common_args ${MAC_OSX_ARCHITECTURE_ARGS} ${ep_common_args} ) endif() set(mitk_superbuild_ep_args) set(mitk_depends ) # Include external projects include(CMakeExternals/MITKData.cmake) foreach(p ${external_projects}) if(EXISTS ${CMAKE_SOURCE_DIR}/CMakeExternals/${p}.cmake) include(CMakeExternals/${p}.cmake) else() foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) get_filename_component(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIR} ABSOLUTE) set(MITK_CMAKE_EXTERNALS_EXTENSION_DIR ${MITK_EXTENSION_DIR}/CMakeExternals) if(EXISTS ${MITK_CMAKE_EXTERNALS_EXTENSION_DIR}/${p}.cmake) include(${MITK_CMAKE_EXTERNALS_EXTENSION_DIR}/${p}.cmake) break() endif() endforeach() endif() list(APPEND mitk_superbuild_ep_args -DMITK_USE_${p}:BOOL=${MITK_USE_${p}} ) get_property(_package GLOBAL PROPERTY MITK_${p}_PACKAGE) if(_package) list(APPEND mitk_superbuild_ep_args -D${p}_DIR:PATH=${${p}_DIR}) endif() list(APPEND mitk_depends ${${p}_DEPENDS}) endforeach() if (SWIG_EXECUTABLE) list(APPEND mitk_superbuild_ep_args -DSWIG_EXECUTABLE=${SWIG_EXECUTABLE}) endif() #----------------------------------------------------------------------------- # Set superbuild boolean args #----------------------------------------------------------------------------- set(mitk_cmake_boolean_args BUILD_SHARED_LIBS WITH_COVERAGE BUILD_TESTING MITK_BUILD_ALL_PLUGINS MITK_BUILD_ALL_APPS MITK_BUILD_EXAMPLES MITK_USE_Qt5 MITK_USE_SYSTEM_Boost MITK_USE_BLUEBERRY MITK_USE_OpenCL MITK_USE_OpenMP MITK_ENABLE_PIC_READER ) #----------------------------------------------------------------------------- # Create the final variable containing superbuild boolean args #----------------------------------------------------------------------------- set(mitk_superbuild_boolean_args) foreach(mitk_cmake_arg ${mitk_cmake_boolean_args}) list(APPEND mitk_superbuild_boolean_args -D${mitk_cmake_arg}:BOOL=${${mitk_cmake_arg}}) endforeach() if(MITK_BUILD_ALL_PLUGINS) list(APPEND mitk_superbuild_boolean_args -DBLUEBERRY_BUILD_ALL_PLUGINS:BOOL=ON) endif() #----------------------------------------------------------------------------- # MITK Utilities #----------------------------------------------------------------------------- set(proj MITK-Utilities) ExternalProject_Add(${proj} DOWNLOAD_COMMAND "" CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" DEPENDS ${mitk_depends} ) #----------------------------------------------------------------------------- # Additional MITK CXX/C Flags #----------------------------------------------------------------------------- set(MITK_ADDITIONAL_C_FLAGS "" CACHE STRING "Additional C Flags for MITK") set(MITK_ADDITIONAL_C_FLAGS_RELEASE "" CACHE STRING "Additional Release C Flags for MITK") set(MITK_ADDITIONAL_C_FLAGS_DEBUG "" CACHE STRING "Additional Debug C Flags for MITK") mark_as_advanced(MITK_ADDITIONAL_C_FLAGS MITK_ADDITIONAL_C_FLAGS_DEBUG MITK_ADDITIONAL_C_FLAGS_RELEASE) set(MITK_ADDITIONAL_CXX_FLAGS "" CACHE STRING "Additional CXX Flags for MITK") set(MITK_ADDITIONAL_CXX_FLAGS_RELEASE "" CACHE STRING "Additional Release CXX Flags for MITK") set(MITK_ADDITIONAL_CXX_FLAGS_DEBUG "" CACHE STRING "Additional Debug CXX Flags for MITK") mark_as_advanced(MITK_ADDITIONAL_CXX_FLAGS MITK_ADDITIONAL_CXX_FLAGS_DEBUG MITK_ADDITIONAL_CXX_FLAGS_RELEASE) set(MITK_ADDITIONAL_EXE_LINKER_FLAGS "" CACHE STRING "Additional exe linker flags for MITK") set(MITK_ADDITIONAL_SHARED_LINKER_FLAGS "" CACHE STRING "Additional shared linker flags for MITK") set(MITK_ADDITIONAL_MODULE_LINKER_FLAGS "" CACHE STRING "Additional module linker flags for MITK") mark_as_advanced(MITK_ADDITIONAL_EXE_LINKER_FLAGS MITK_ADDITIONAL_SHARED_LINKER_FLAGS MITK_ADDITIONAL_MODULE_LINKER_FLAGS) #----------------------------------------------------------------------------- # MITK Configure #----------------------------------------------------------------------------- if(MITK_INITIAL_CACHE_FILE) set(mitk_initial_cache_arg -C "${MITK_INITIAL_CACHE_FILE}") endif() set(mitk_optional_cache_args ) foreach(type RUNTIME ARCHIVE LIBRARY) if(DEFINED CTK_PLUGIN_${type}_OUTPUT_DIRECTORY) list(APPEND mitk_optional_cache_args -DCTK_PLUGIN_${type}_OUTPUT_DIRECTORY:PATH=${CTK_PLUGIN_${type}_OUTPUT_DIRECTORY}) endif() endforeach() # Optional python variables if(MITK_USE_Python3) list(APPEND mitk_optional_cache_args -DMITK_USE_Python3:BOOL=${MITK_USE_Python3} "-DPython3_EXECUTABLE:FILEPATH=${Python3_EXECUTABLE}" "-DPython3_INCLUDE_DIR:PATH=${Python3_INCLUDE_DIRS}" "-DPython3_LIBRARY:FILEPATH=${Python3_LIBRARY}" "-DPython3_STDLIB:FILEPATH=${Python3_STDLIB}" "-DPython3_SITELIB:FILEPATH=${Python3_SITELIB}" ) endif() if(OPENSSL_ROOT_DIR) list(APPEND mitk_optional_cache_args "-DOPENSSL_ROOT_DIR:PATH=${OPENSSL_ROOT_DIR}" ) endif() if(CMAKE_FRAMEWORK_PATH) list(APPEND mitk_optional_cache_args "-DCMAKE_FRAMEWORK_PATH:PATH=${CMAKE_FRAMEWORK_PATH}" ) endif() if(Eigen_INCLUDE_DIR) list(APPEND mitk_optional_cache_args -DEigen_INCLUDE_DIR:PATH=${Eigen_INCLUDE_DIR} ) endif() # Optional pass through of Doxygen if(DOXYGEN_EXECUTABLE) list(APPEND mitk_optional_cache_args -DDOXYGEN_EXECUTABLE:FILEPATH=${DOXYGEN_EXECUTABLE} ) endif() set(proj MITK-Configure) ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} DOWNLOAD_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_GENERATOR_PLATFORM ${gen_platform} CMAKE_CACHE_ARGS # --------------- Build options ---------------- -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_INSTALL_PREFIX} -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} "-DCMAKE_PREFIX_PATH:PATH=${ep_prefix};${CMAKE_PREFIX_PATH}" "-DCMAKE_LIBRARY_PATH:PATH=${CMAKE_LIBRARY_PATH}" "-DCMAKE_INCLUDE_PATH:PATH=${CMAKE_INCLUDE_PATH}" # --------------- Compile options ---------------- -DCMAKE_CXX_EXTENSIONS:STRING=${CMAKE_CXX_EXTENSIONS} -DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD} -DCMAKE_CXX_STANDARD_REQUIRED:BOOL=${CMAKE_CXX_STANDARD_REQUIRED} -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER} -DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER} "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} ${MITK_ADDITIONAL_C_FLAGS}" "-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} ${MITK_ADDITIONAL_CXX_FLAGS}" # debug flags "-DCMAKE_CXX_FLAGS_DEBUG:STRING=${CMAKE_CXX_FLAGS_DEBUG} ${MITK_ADDITIONAL_CXX_FLAGS_DEBUG}" "-DCMAKE_C_FLAGS_DEBUG:STRING=${CMAKE_C_FLAGS_DEBUG} ${MITK_ADDITIONAL_C_FLAGS_DEBUG}" # release flags "-DCMAKE_CXX_FLAGS_RELEASE:STRING=${CMAKE_CXX_FLAGS_RELEASE} ${MITK_ADDITIONAL_CXX_FLAGS_RELEASE}" "-DCMAKE_C_FLAGS_RELEASE:STRING=${CMAKE_C_FLAGS_RELEASE} ${MITK_ADDITIONAL_C_FLAGS_RELEASE}" # relwithdebinfo -DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_C_FLAGS_RELWITHDEBINFO} # link flags "-DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS} ${MITK_ADDITIONAL_EXE_LINKER_FLAGS}" "-DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS} ${MITK_ADDITIONAL_SHARED_LINKER_FLAGS}" "-DCMAKE_MODULE_LINKER_FLAGS:STRING=${CMAKE_MODULE_LINKER_FLAGS} ${MITK_ADDITIONAL_MODULE_LINKER_FLAGS}" # Output directories -DMITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY} -DMITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY} -DMITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY} # ------------- Boolean build options -------------- ${mitk_superbuild_boolean_args} ${mitk_optional_cache_args} -DMITK_USE_SUPERBUILD:BOOL=OFF -DMITK_BUILD_CONFIGURATION:STRING=${MITK_BUILD_CONFIGURATION} -DMITK_FAST_TESTING:BOOL=${MITK_FAST_TESTING} + -DMITK_XVFB_TESTING:BOOL=${MITK_XVFB_TESTING} -DCTEST_USE_LAUNCHERS:BOOL=${CTEST_USE_LAUNCHERS} # ----------------- Miscellaneous --------------- -DCMAKE_LIBRARY_PATH:PATH=${CMAKE_LIBRARY_PATH} -DCMAKE_INCLUDE_PATH:PATH=${CMAKE_INCLUDE_PATH} -DMITK_CTEST_SCRIPT_MODE:STRING=${MITK_CTEST_SCRIPT_MODE} -DMITK_SUPERBUILD_BINARY_DIR:PATH=${MITK_BINARY_DIR} -DMITK_MODULES_TO_BUILD:INTERNAL=${MITK_MODULES_TO_BUILD} -DMITK_WHITELIST:STRING=${MITK_WHITELIST} -DMITK_WHITELISTS_EXTERNAL_PATH:STRING=${MITK_WHITELISTS_EXTERNAL_PATH} -DMITK_WHITELISTS_INTERNAL_PATH:STRING=${MITK_WHITELISTS_INTERNAL_PATH} -DMITK_EXTENSION_DIRS:STRING=${MITK_EXTENSION_DIRS} -DMITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES} -DMITK_ACCESSBYITK_FLOATING_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES} -DMITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES} -DMITK_ACCESSBYITK_VECTOR_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES} -DMITK_ACCESSBYITK_DIMENSIONS:STRING=${MITK_ACCESSBYITK_DIMENSIONS} # --------------- External project options --------------- -DMITK_DATA_DIR:PATH=${MITK_DATA_DIR} -DMITK_EXTERNAL_PROJECT_PREFIX:PATH=${ep_prefix} -DCppMicroServices_DIR:PATH=${CppMicroServices_DIR} -DDCMTK_CMAKE_DEBUG_POSTFIX:STRING=${DCMTK_CMAKE_DEBUG_POSTFIX} -DBOOST_ROOT:PATH=${BOOST_ROOT} -DBOOST_LIBRARYDIR:PATH=${BOOST_LIBRARYDIR} -DMITK_USE_Boost_LIBRARIES:STRING=${MITK_USE_Boost_LIBRARIES} -DQt5_DIR:PATH=${Qt5_DIR} CMAKE_ARGS ${mitk_initial_cache_arg} ${MAC_OSX_ARCHITECTURE_ARGS} ${mitk_superbuild_ep_args} SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} BINARY_DIR ${CMAKE_BINARY_DIR}/MITK-build BUILD_COMMAND "" INSTALL_COMMAND "" DEPENDS MITK-Utilities ) mitkFunctionInstallExternalCMakeProject(${proj}) #----------------------------------------------------------------------------- # MITK #----------------------------------------------------------------------------- if(CMAKE_GENERATOR MATCHES ".*Makefiles.*") set(mitk_build_cmd "$(MAKE)") else() set(mitk_build_cmd ${CMAKE_COMMAND} --build ${CMAKE_CURRENT_BINARY_DIR}/MITK-build --config ${CMAKE_CFG_INTDIR}) endif() if(NOT DEFINED SUPERBUILD_EXCLUDE_MITKBUILD_TARGET OR NOT SUPERBUILD_EXCLUDE_MITKBUILD_TARGET) set(MITKBUILD_TARGET_ALL_OPTION "ALL") else() set(MITKBUILD_TARGET_ALL_OPTION "") endif() add_custom_target(MITK-build ${MITKBUILD_TARGET_ALL_OPTION} COMMAND ${mitk_build_cmd} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/MITK-build DEPENDS MITK-Configure ) #----------------------------------------------------------------------------- # Custom target allowing to drive the build of the MITK project itself #----------------------------------------------------------------------------- add_custom_target(MITK COMMAND ${mitk_build_cmd} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/MITK-build )