diff --git a/Applications/AppList.cmake b/Applications/AppList.cmake index 87fc225656..e82b1f64b1 100644 --- a/Applications/AppList.cmake +++ b/Applications/AppList.cmake @@ -1,21 +1,19 @@ # This file is included in the top-level MITK CMakeLists.txt file to # allow early dependency checking -option(MITK_BUILD_APP_CoreApp "Build the MITK CoreApp" OFF) option(MITK_BUILD_APP_Workbench "Build the MITK Workbench executable" ON) # This variable is fed to ctkFunctionSetupPlugins() macro in the # top-level MITK CMakeLists.txt file. This allows to automatically # enable required plug-in runtime dependencies for applications using # the CTK DGraph executable and the ctkMacroValidateBuildOptions macro. # For this to work, directories containing executables must contain # a CMakeLists.txt file containing a "project(...)" command and a # target_libraries.cmake file setting a list named "target_libraries" # with required plug-in target names. # Format is "Directory Name^^CMake Option Name^^Executable Name (without file suffix)" set(MITK_APPS - CoreApp^^MITK_BUILD_APP_CoreApp^^MitkCoreApp Workbench^^MITK_BUILD_APP_Workbench^^MitkWorkbench ) diff --git a/Applications/CoreApp/CMakeLists.txt b/Applications/CoreApp/CMakeLists.txt deleted file mode 100644 index e4a845e992..0000000000 --- a/Applications/CoreApp/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -project(CoreApp) - -# Create a cache entry for the provisioning file which is used to export -# the file name in the MITKConfig.cmake file. This will keep external projects -# which rely on this file happy. -set(MITK_COREAPP_PROVISIONING_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/MitkCoreApp.provisioning" CACHE INTERNAL "CoreApp provisioning file" FORCE) - -set(_plugins - org.mitk.gui.qt.coreapplication - org.mitk.gui.qt.stdmultiwidgeteditor -) - -# Plug-ins listed below will not be -# - added as a build-time dependency to the executable -# - listed in the provisioning file for the executable -# - installed if they are external plug-ins - -set(_exclude_plugins ) - -mitkFunctionCreateBlueBerryApplication( - NAME MitkCoreApp - DESCRIPTION "MITK - CoreApp Application" - PLUGINS ${_plugins} -) - -# subproject support -add_dependencies(MITK-CoreUI MitkCoreApp) diff --git a/Applications/CoreApp/MitkCoreApp.cpp b/Applications/CoreApp/MitkCoreApp.cpp deleted file mode 100644 index 25e2453df9..0000000000 --- a/Applications/CoreApp/MitkCoreApp.cpp +++ /dev/null @@ -1,46 +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 - -#if defined __GNUC__ && !defined __clang__ -# include -# include -# include -# include -#endif - -int main(int argc, char **argv) -{ - mitk::BaseApplication app(argc, argv); - - app.setApplicationName("MitkCoreApp"); - app.setOrganizationName("DKFZ"); - - // Preload the org.blueberry.core.expressions plugin to work around a bug in - // GCC that leads to undefined symbols while loading certain libraries even though - // the symbols are actually defined. -#if defined __GNUC__ && !defined __clang__ - auto library = QFileInfo(argv[0]).dir().path() + "/../lib/plugins/liborg_blueberry_core_expressions.so"; - - if (!QFileInfo(library).exists()) - library = "liborg_blueberry_core_expressions"; - - app.setPreloadLibraries(QStringList() << library); -#endif - - app.setProperty(mitk::BaseApplication::PROP_APPLICATION, "org.mitk.qt.coreapplication"); - - // Run the workbench. - return app.run(); -} diff --git a/Applications/CoreApp/MitkCoreApp.ini b/Applications/CoreApp/MitkCoreApp.ini deleted file mode 100644 index ee36908a94..0000000000 --- a/Applications/CoreApp/MitkCoreApp.ini +++ /dev/null @@ -1,2 +0,0 @@ -BlueBerry.home=@BLUEBERRY_BINARY_DIR@ -BlueBerry.provisioning=@MITK_COREAPP_PROVISIONING_FILE@ diff --git a/Applications/CoreApp/icons/CoreApp.rc b/Applications/CoreApp/icons/CoreApp.rc deleted file mode 100644 index bb10963fb3..0000000000 --- a/Applications/CoreApp/icons/CoreApp.rc +++ /dev/null @@ -1 +0,0 @@ -IDI_ICON1 ICON DISCARDABLE "icon.ico" \ No newline at end of file diff --git a/Applications/CoreApp/icons/icon.icns b/Applications/CoreApp/icons/icon.icns deleted file mode 100644 index 5afc942282..0000000000 Binary files a/Applications/CoreApp/icons/icon.icns and /dev/null differ diff --git a/Applications/CoreApp/icons/icon.ico b/Applications/CoreApp/icons/icon.ico deleted file mode 100644 index 27d4c9d1b9..0000000000 Binary files a/Applications/CoreApp/icons/icon.ico and /dev/null differ diff --git a/Applications/CoreApp/icons/icon.png b/Applications/CoreApp/icons/icon.png deleted file mode 100644 index b529577fab..0000000000 Binary files a/Applications/CoreApp/icons/icon.png and /dev/null differ diff --git a/Applications/CoreApp/startMitkCoreApp.bat.in b/Applications/CoreApp/startMitkCoreApp.bat.in deleted file mode 100644 index 608b954632..0000000000 --- a/Applications/CoreApp/startMitkCoreApp.bat.in +++ /dev/null @@ -1,2 +0,0 @@ -PATH=@MITK_RUNTIME_PATH@;%PATH% -@VS_BUILD_TYPE@\CoreApp.exe diff --git a/Applications/CoreApp/target_libraries.cmake b/Applications/CoreApp/target_libraries.cmake deleted file mode 100644 index b959c1b3b8..0000000000 --- a/Applications/CoreApp/target_libraries.cmake +++ /dev/null @@ -1,10 +0,0 @@ - -# A list of plug-in targets which should be automatically enabled -# (or be available in external projects) for this application. - -set(target_libraries - org_blueberry_ui_qt - org_blueberry_ui_qt_help - org_mitk_gui_qt_coreapplication - org_mitk_gui_qt_stdmultiwidgeteditor -) diff --git a/Applications/PluginGenerator/ProjectTemplate/CMakeExternals/MITK.cmake b/Applications/PluginGenerator/ProjectTemplate/CMakeExternals/MITK.cmake index dca1ebf8a2..43155e16cd 100644 --- a/Applications/PluginGenerator/ProjectTemplate/CMakeExternals/MITK.cmake +++ b/Applications/PluginGenerator/ProjectTemplate/CMakeExternals/MITK.cmake @@ -1,211 +1,211 @@ #----------------------------------------------------------------------------- # MITK #----------------------------------------------------------------------------- set(MITK_DEPENDS) set(proj_DEPENDENCIES) set(proj MITK) if(NOT MITK_DIR) #----------------------------------------------------------------------------- # Create CMake options to customize the MITK build #----------------------------------------------------------------------------- option(MITK_USE_SUPERBUILD "Use superbuild for MITK" ON) option(MITK_USE_BLUEBERRY "Build the BlueBerry platform in MITK" ON) option(MITK_BUILD_EXAMPLES "Build the MITK examples" OFF) option(MITK_BUILD_ALL_PLUGINS "Build all MITK plugins" OFF) option(MITK_BUILD_TESTING "Build the MITK unit tests" OFF) option(MITK_USE_ACVD "Use Approximated Centroidal Voronoi Diagrams" OFF) option(MITK_USE_CTK "Use CTK in MITK" ${MITK_USE_BLUEBERRY}) option(MITK_USE_DCMTK "Use DCMTK in MITK" ON) option(MITK_USE_Qt5 "Use Qt 5 library in MITK" ON) option(MITK_USE_DCMQI "Use dcmqi in MITK" OFF) option(MITK_USE_OpenCV "Use Intel's OpenCV library" OFF) option(MITK_USE_Python3 "Enable Python wrapping in MITK" OFF) if(MITK_USE_BLUEBERRY AND 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() if(MITK_USE_CTK AND NOT MITK_USE_Qt5) message("Forcing MITK_USE_Qt5 to ON because of MITK_USE_CTK") set(MITK_USE_Qt5 ON CACHE BOOL "Use Qt 5 library in MITK" FORCE) endif() set(MITK_USE_CableSwig ${MITK_USE_Python3}) set(MITK_USE_GDCM 1) set(MITK_USE_ITK 1) set(MITK_USE_VTK 1) mark_as_advanced(MITK_USE_SUPERBUILD MITK_BUILD_ALL_PLUGINS MITK_BUILD_TESTING ) set(mitk_cmake_boolean_args MITK_USE_SUPERBUILD MITK_USE_BLUEBERRY MITK_BUILD_EXAMPLES MITK_BUILD_ALL_PLUGINS MITK_USE_ACVD MITK_USE_CTK MITK_USE_DCMTK MITK_USE_Qt5 MITK_USE_DCMQI MITK_USE_OpenCV MITK_USE_Python3 ) if(MITK_USE_Qt5) # Look for Qt at the superbuild level, to catch missing Qt libs early find_package(Qt5Widgets REQUIRED) endif() set(additional_mitk_cmakevars ) # Configure the set of default 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") set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") foreach(_arg MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES MITK_ACCESSBYITK_DIMENSIONS) mark_as_advanced(${_arg}) list(APPEND additional_mitk_cmakevars "-D${_arg}:STRING=${${_arg}}") endforeach() #----------------------------------------------------------------------------- # Create options to inject pre-build dependencies #----------------------------------------------------------------------------- foreach(proj CTK DCMTK DCMQI GDCM VTK ACVD ITK OpenCV CableSwig) if(MITK_USE_${proj}) set(MITK_${proj}_DIR "${${proj}_DIR}" CACHE PATH "Path to ${proj} build directory") mark_as_advanced(MITK_${proj}_DIR) if(MITK_${proj}_DIR) list(APPEND additional_mitk_cmakevars "-D${proj}_DIR:PATH=${MITK_${proj}_DIR}") endif() endif() endforeach() set(MITK_BOOST_ROOT "${BOOST_ROOT}" CACHE PATH "Path to Boost directory") mark_as_advanced(MITK_BOOST_ROOT) if(MITK_BOOST_ROOT) list(APPEND additional_mitk_cmakevars "-DBOOST_ROOT:PATH=${MITK_BOOST_ROOT}") endif() set(MITK_SOURCE_DIR "" CACHE PATH "MITK source code location. If empty, MITK will be cloned from MITK_GIT_REPOSITORY") - set(MITK_GIT_REPOSITORY "https://phabricator.mitk.org/diffusion/MITK/mitk.git" CACHE STRING "The git repository for cloning MITK") + set(MITK_GIT_REPOSITORY "https://phabricator.mitk.org/source/mitk.git" CACHE STRING "The git repository for cloning MITK") set(MITK_GIT_TAG "origin/master" CACHE STRING "The git tag/hash to be used when cloning from MITK_GIT_REPOSITORY") mark_as_advanced(MITK_SOURCE_DIR MITK_GIT_REPOSITORY MITK_GIT_TAG) #----------------------------------------------------------------------------- # Create the final variable containing superbuild boolean args #----------------------------------------------------------------------------- set(mitk_boolean_args) foreach(mitk_cmake_arg ${mitk_cmake_boolean_args}) list(APPEND mitk_boolean_args -D${mitk_cmake_arg}:BOOL=${${mitk_cmake_arg}}) endforeach() #----------------------------------------------------------------------------- # Additional MITK CMake variables #----------------------------------------------------------------------------- if(MITK_USE_Qt5) list(APPEND additional_mitk_cmakevars "-DCMAKE_PREFIX_PATH:PATH=${CMAKE_PREFIX_PATH}") endif() if(MITK_USE_CTK) list(APPEND additional_mitk_cmakevars "-DGIT_EXECUTABLE:FILEPATH=${GIT_EXECUTABLE}") endif() if(MITK_INITIAL_CACHE_FILE) list(APPEND additional_mitk_cmakevars "-DMITK_INITIAL_CACHE_FILE:INTERNAL=${MITK_INITIAL_CACHE_FILE}") endif() if(MITK_USE_SUPERBUILD) set(MITK_BINARY_DIR ${proj}-superbuild) else() set(MITK_BINARY_DIR ${proj}-build) endif() set(proj_DEPENDENCIES) set(MITK_DEPENDS ${proj}) # Configure the MITK souce code location if(NOT MITK_SOURCE_DIR) set(mitk_source_location SOURCE_DIR ${CMAKE_BINARY_DIR}/${proj} GIT_REPOSITORY ${MITK_GIT_REPOSITORY} GIT_TAG ${MITK_GIT_TAG} ) else() set(mitk_source_location SOURCE_DIR ${MITK_SOURCE_DIR} ) endif() ExternalProject_Add(${proj} ${mitk_source_location} BINARY_DIR ${MITK_BINARY_DIR} PREFIX ${proj}${ep_suffix} INSTALL_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} ${mitk_boolean_args} ${additional_mitk_cmakevars} -DBUILD_SHARED_LIBS:BOOL=ON -DBUILD_TESTING:BOOL=${MITK_BUILD_TESTING} CMAKE_CACHE_ARGS ${ep_common_cache_args} CMAKE_CACHE_DEFAULT_ARGS ${ep_common_cache_default_args} DEPENDS ${proj_DEPENDENCIES} ) if(MITK_USE_SUPERBUILD) set(MITK_DIR "${CMAKE_CURRENT_BINARY_DIR}/${MITK_BINARY_DIR}/MITK-build") else() set(MITK_DIR "${CMAKE_CURRENT_BINARY_DIR}/${MITK_BINARY_DIR}") endif() else() # The project is provided using MITK_DIR, nevertheless since other # projects may depend on MITK, let's add an 'empty' one MacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") # Further, do some sanity checks in the case of a pre-built MITK set(my_itk_dir ${ITK_DIR}) set(my_vtk_dir ${VTK_DIR}) find_package(MITK REQUIRED) if(my_itk_dir AND NOT my_itk_dir STREQUAL ${ITK_DIR}) message(FATAL_ERROR "ITK packages do not match:\n ${MY_PROJECT_NAME}: ${my_itk_dir}\n MITK: ${ITK_DIR}") endif() if(my_vtk_dir AND NOT my_vtk_dir STREQUAL ${VTK_DIR}) message(FATAL_ERROR "VTK packages do not match:\n ${MY_PROJECT_NAME}: ${my_vtk_dir}\n MITK: ${VTK_DIR}") endif() endif() diff --git a/Applications/Solstice/CMakeLists.txt b/Applications/Solstice/CMakeLists.txt deleted file mode 100644 index 5ed2c29b1c..0000000000 --- a/Applications/Solstice/CMakeLists.txt +++ /dev/null @@ -1,62 +0,0 @@ -project(Solstice) - -set(MITK_EXTAPP_PROVISIONING_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/MitkWorkbench.provisioning") - -# Plug-ins listed below will not be -# - added as a build-time dependency to the executable -# - listed in the provisioning file for the executable -# - installed if they are external plug-ins - -set(_exclude_plugins - org.blueberry.test - org.blueberry.uitest - org.mitk.gui.qt.coreapplication - org.mitk.gui.qt.diffusionimagingapp -) - -FunctionCreateBlueBerryApplication( - NAME MitkSolstice - DESCRIPTION "MITK Workbench" - EXCLUDE_PLUGINS ${_exclude_plugins} -) - -add_executable(${OSGI_APP} MACOSX_BUNDLE "src/application/berryMain.cpp") - -target_link_libraries(${OSGI_APP} PRIVATE ${PROJECT_NAME} mbilog) -if(_ctk_test_plugins) - add_dependencies(${OSGI_APP} ${_ctk_test_plugins}) - add_dependencies(BlueBerry ${OSGI_APP}) - set_property(TARGET ${OSGI_APP} APPEND PROPERTY LABELS BlueBerry) -endif() - -configure_file(src/application/solstice.ini - ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${OSGI_APP}.ini) - - -add_executable(${OSGI_UI_APP} MACOSX_BUNDLE "src/application/berryMainUI.cpp") - -target_link_libraries(${OSGI_UI_APP} PRIVATE ${PROJECT_NAME} mbilog) -if(MITK_USE_Qt5) - target_link_libraries(${OSGI_UI_APP} PRIVATE Qt5::Widgets) -endif() - -if(_ctk_test_plugins) - add_dependencies(${OSGI_UI_APP} ${_ctk_test_plugins}) - add_dependencies(BlueBerry ${OSGI_UI_APP}) - set_property(TARGET ${OSGI_UI_APP} APPEND PROPERTY LABELS BlueBerry) -endif() - -configure_file(src/application/solstice.ini - ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${OSGI_UI_APP}.ini) - -# Add meta dependencies (e.g. on auto-load modules from depending modules) -if(TARGET ${CMAKE_PROJECT_NAME}-autoload) - add_dependencies(MitkWorkbench ${CMAKE_PROJECT_NAME}-autoload) -endif() - -#Setting application icon for macOS systems -set_target_properties(MitkWorkbench PROPERTIES MACOSX_BUNDLE_ICON_FILE "icon.icns") - -if(APPLE) - install(FILES "icons/icon.icns" DESTINATION "MitkWorkbench.app/Contents/Resources") -endif(APPLE) diff --git a/Applications/Solstice/MitkSolstice.cpp b/Applications/Solstice/MitkSolstice.cpp deleted file mode 100644 index bc2db3053e..0000000000 --- a/Applications/Solstice/MitkSolstice.cpp +++ /dev/null @@ -1,25 +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 "berryStarter.h" - -#include - -int main(int argc, char** argv) -{ - // Create a QCoreApplication instance first - QCoreApplication app(argc, argv); - app.setApplicationName("solstice"); - app.setOrganizationName("DKFZ"); - - return berry::Starter::Run(argc, argv, 0); -} diff --git a/Applications/Solstice/MitkSolstice.ini b/Applications/Solstice/MitkSolstice.ini deleted file mode 100644 index 30c36eee76..0000000000 --- a/Applications/Solstice/MitkSolstice.ini +++ /dev/null @@ -1,2 +0,0 @@ -BlueBerry.home=@BLUEBERRY_BINARY_DIR@ -BlueBerry.provisioning=@BLUEBERRY_TESTING_PROVISIONING_FILE@ diff --git a/Applications/Solstice/MitkSolsticeUI.cpp b/Applications/Solstice/MitkSolsticeUI.cpp deleted file mode 100644 index 4c8bafe2b7..0000000000 --- a/Applications/Solstice/MitkSolsticeUI.cpp +++ /dev/null @@ -1,25 +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 "berryStarter.h" - -#include - -int main(int argc, char** argv) -{ - // Create a QCoreApplication instance first - QApplication app(argc, argv); - app.setApplicationName("solstice_ui"); - app.setOrganizationName("DKFZ"); - - return berry::Starter::Run(argc, argv, 0); -} diff --git a/Applications/Workbench/CMakeLists.txt b/Applications/Workbench/CMakeLists.txt index 0c24e5d70b..360e89b9c1 100644 --- a/Applications/Workbench/CMakeLists.txt +++ b/Applications/Workbench/CMakeLists.txt @@ -1,50 +1,46 @@ project(Workbench) # Create a cache entry for the provisioning file which is used to export # the file name in the MITKConfig.cmake file. This will keep external projects # which rely on this file happy. set(MITK_EXTAPP_PROVISIONING_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/MitkWorkbench.provisioning" CACHE INTERNAL "MitkWorkbench provisioning file" FORCE) # Plug-ins listed below will not be # - added as a build-time dependency to the executable # - listed in the provisioning file for the executable # - installed if they are external plug-ins set(_exclude_plugins - org.blueberry.test - org.blueberry.uitest - org.mitk.gui.qt.coreapplication - org.mitk.gui.qt.diffusionimagingapp org.mitk.example.gui.customviewer org.mitk.example.gui.customviewer.views org.mitk.example.gui.selectionservicemitk org.mitk.example.gui.selectionservicemitk.views org.mitk.example.gui.selectionserviceqt org.mitk.example.gui.extensionpointcontribution org.mitk.example.gui.extensionpointdefinition org.mitk.example.gui.minimalapplication org.mitk.example.gui.multipleperspectives ) mitkFunctionCreateBlueBerryApplication( NAME MitkWorkbench DESCRIPTION "MITK Workbench" EXCLUDE_PLUGINS ${_exclude_plugins} ) # Add meta dependencies (e.g. on auto-load modules from depending modules) if(TARGET ${CMAKE_PROJECT_NAME}-autoload) add_dependencies(MitkWorkbench ${CMAKE_PROJECT_NAME}-autoload) endif() #Setting application icon for macOS systems set_target_properties(MitkWorkbench PROPERTIES MACOSX_BUNDLE_ICON_FILE "icon.icns") if(APPLE) install(FILES "icons/icon.icns" DESTINATION "MitkWorkbench.app/Contents/Resources") endif(APPLE) # Add a build time dependency to legacy BlueBerry bundles. if(MITK_MODULES_ENABLED_PLUGINS) add_dependencies(MitkWorkbench ${MITK_MODULES_ENABLED_PLUGINS}) endif() diff --git a/CMake/mitkFunctionTestPlugin.cmake b/CMake/mitkFunctionTestPlugin.cmake deleted file mode 100644 index 8defbbe751..0000000000 --- a/CMake/mitkFunctionTestPlugin.cmake +++ /dev/null @@ -1,69 +0,0 @@ - -# Call this macro after calling mitk_create_plugin for a test plugin -# in your CMakeLists.txt -# -# Variables: -# -# - BLUEBERRY_TEST_APP contains the name of the executable which will start the OSGi framework -# -function(mitkFunctionTestPlugin) - - set(_cla_switch "--") - if(WIN32) - if(MSYS) - set(_cla_switch "//") - else() - set(_cla_switch "/") - endif() - endif() - - if(NOT BUNDLE-SYMBOLICNAME) - string(REPLACE "_" "." BUNDLE-SYMBOLICNAME ${PROJECT_NAME}) - endif() - add_test(${BUNDLE-SYMBOLICNAME} ${BLUEBERRY_TEST_APP} ${_cla_switch}BlueBerry.application=coretestapplication ${_cla_switch}BlueBerry.testplugin=${BUNDLE-SYMBOLICNAME}) - - set(_labels ${ARGN}) - if(NOT _labels) - set(_labels BlueBerry) - endif() - set_property(TEST ${BUNDLE-SYMBOLICNAME} PROPERTY LABELS ${_labels}) - -endfunction() - -# Variables: -# -# - BLUEBERRY_UI_TEST_APP contains the name of the executable which will start the OSGi framework -# - BLUEBERRY_TEST_APP_ID contains the application id of the application to test. If empty, -# a minimalistic default application will be started -macro(MACRO_TEST_UIPLUGIN) - - set(_cla_switch "--") - if(WIN32) - if(MSYS) - set(_cla_switch "//") - else() - set(_cla_switch "/") - endif() - endif() - - if(NOT BUNDLE-SYMBOLICNAME) - string(REPLACE "_" "." BUNDLE-SYMBOLICNAME ${PROJECT_NAME}) - endif() - - if(BLUEBERRY_ENABLE_GUI_TESTING) - if(BLUEBERRY_TEST_APP_ID) - set(_app_id_arg "${_cla_switch}BlueBerry.testapplication=${BLUEBERRY_TEST_APP_ID}") - else() - set(_app_id_arg ) - endif() - - add_test(${BUNDLE-SYMBOLICNAME} ${BLUEBERRY_UI_TEST_APP} ${_cla_switch}BlueBerry.application=uitestapplication ${_app_id_arg} ${_cla_switch}BlueBerry.testplugin=${BUNDLE-SYMBOLICNAME}) - - set(_labels ${ARGN}) - if(NOT _labels) - set(_labels BlueBerry) - endif() - set_property(TEST ${BUNDLE-SYMBOLICNAME} PROPERTY LABELS ${_labels}) - endif() - -endmacro(MACRO_TEST_UIPLUGIN) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9026898987..63bdca3aff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,1467 +1,1464 @@ 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 ) +foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS}) + get_filename_component(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIR} ABSOLUTE) + if(EXISTS ${MITK_CMAKE_EXTENSION_DIR}/CMake/CTestSubprojectList.cmake) + set(MITK_CTEST_SUBPROJECTS "") + include(${MITK_CMAKE_EXTENSION_DIR}/CMake/CTestSubprojectList.cmake) + if(MITK_CTEST_SUBPROJECTS) + list(APPEND CTEST_PROJECT_SUBPROJECTS ${MITK_CTEST_SUBPROJECTS}) + endif() + endif() +endforeach() + # 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 +# Ask the user to show the console window for applications 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) # 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/") execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${BLUEBERRY_XPDOC_OUTPUT_DIR}) - # 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/Documentation/Doxygen/2-UserManual/Applications.dox b/Documentation/Doxygen/2-UserManual/Applications.dox index 6ffd3c0af2..30399faa7f 100644 --- a/Documentation/Doxygen/2-UserManual/Applications.dox +++ b/Documentation/Doxygen/2-UserManual/Applications.dox @@ -1,33 +1,30 @@ /** \page ApplicationsPage Using MITK and Applications \tableofcontents \section ApplicationsPageApplications What are Applications? Applications are special versions of MITK which contain functionality aimed at solving a special task. Usually they are aimed at a selective audience or solving a particular problem. As such they focus on certain capabilities of MITK, while ignoring others. The main reason for this is to supply the users of the application with the power of MITK for solving their tasks, without daunting them with an overwhelming number of menus and options. At the same time, this allows the creation of an elegant and easily comprehensible workflow for your task. -The Diffusion Imaging Application for example contains all the functionality necessary for the field of neuro-imaging, but does not contain support for ultrasound imaging. A typical example of this would be an application which contains only views related to the analysis of the human brain (particular question) or one which contains only what is necessary for displaying medical data in the classroom (specific audience). \section ApplicationsPageWhatAmIUsing Which Application am I using? If you are unsure which application you are currently using, start the application and have a look in the Title Bar. You should see it's name there. \imageMacro{ApplicationTitle.jpg,"The application name is displayed in the title bar",16} \section ApplicationsPageApplicationsList List of Applications If you are interested in using a specific application, currently developed by the MITK team you might want to take a look first at the \ref MITKUserManualPage . Further information on any application can be found here:
  • \subpage org_mitkworkbench -
  • \subpage org_dti_atlas_application -
  • \subpage org_mitk_gui_qt_diffusionimagingapp
-*/ \ No newline at end of file +*/ diff --git a/Documentation/Doxygen/3-DeveloperManual/Application/BlueBerryExtensionPointReference.dox b/Documentation/Doxygen/3-DeveloperManual/Application/BlueBerryExtensionPointReference.dox index 2631060b56..066fc9c444 100644 --- a/Documentation/Doxygen/3-DeveloperManual/Application/BlueBerryExtensionPointReference.dox +++ b/Documentation/Doxygen/3-DeveloperManual/Application/BlueBerryExtensionPointReference.dox @@ -1,99 +1,94 @@ /** \page BlueBerryExtPointsIndex BlueBerry Extension-Point Reference

BlueBerry Platform Extension Points

The following extension points can be used to extend the capabilities of the platform infrastructure:

Platform Core Expressions

  • \subpage xp_org_blueberry_core_expressions_definitions
  • \subpage xp_org_blueberry_core_expressions_commonExpression
  • \subpage xp_org_blueberry_core_expressions_propertyTesters

Platform Runtime

  • \subpage xp_org_blueberry_osgi_applications
  • \subpage xp_org_blueberry_core_runtime_products

Workbench

  • \subpage xp_org_blueberry_ui_editors
  • \subpage xp_org_blueberry_ui_elementFactories
  • \subpage xp_org_blueberry_ui_keywords
  • \subpage xp_org_blueberry_ui_menus
  • \subpage xp_org_blueberry_ui_perspectiveExtensions
  • \subpage xp_org_blueberry_ui_perspectives
  • \subpage xp_org_blueberry_ui_preferencePages
  • \subpage xp_org_blueberry_ui_presentationFactories
  • \subpage xp_org_blueberry_ui_services
  • \subpage xp_org_blueberry_ui_tweaklets
  • \subpage xp_org_blueberry_ui_views

Other

  • \subpage xp_org_blueberry_tests
\page xp_org_blueberry_core_expressions_definitions org.blueberry.core.expressions.definitions \htmlinclude org_blueberry_core_expressions_definitions.html \page xp_org_blueberry_core_expressions_commonExpression org.blueberry.core.expressions.commonExpression \htmlinclude org_blueberry_core_expressions_commonExpression.html \page xp_org_blueberry_core_expressions_propertyTesters org.blueberry.core.expressions.propertyTesters \htmlinclude org_blueberry_core_expressions_propertyTesters.html - \page xp_org_blueberry_osgi_applications org.blueberry.osgi.applications \htmlinclude org_blueberry_osgi_applications.html \page xp_org_blueberry_core_runtime_products org.blueberry.core.runtime.products \htmlinclude org_blueberry_core_runtime_products.html - \page xp_org_blueberry_ui_elementFactories org.blueberry.ui.elementFactories \htmlinclude org_blueberry_ui_elementFactories.html \page xp_org_blueberry_ui_menus org.blueberry.ui.menus \htmlinclude org_blueberry_ui_menus.html \page xp_org_blueberry_ui_perspectiveExtensions org.blueberry.ui.perspectiveExtensions \htmlinclude org_blueberry_ui_perspectiveExtensions.html \page xp_org_blueberry_ui_editors org.blueberry.ui.editors \htmlinclude org_blueberry_ui_editors.html \page xp_org_blueberry_ui_perspectives org.blueberry.ui.perspectives \htmlinclude org_blueberry_ui_perspectives.html \page xp_org_blueberry_ui_presentationFactories org.blueberry.ui.presentationFactories \htmlinclude org_blueberry_ui_presentationFactories.html \page xp_org_blueberry_ui_services org.blueberry.ui.services \htmlinclude org_blueberry_ui_services.html \page xp_org_blueberry_ui_keywords org.blueberry.ui.keywords \htmlinclude org_blueberry_ui_keywords.html \page xp_org_blueberry_ui_preferencePages org.blueberry.ui.preferencePages \htmlinclude org_blueberry_ui_preferencePages.html \page xp_org_blueberry_ui_tweaklets org.blueberry.ui.tweaklets \htmlinclude org_blueberry_ui_tweaklets.html \page xp_org_blueberry_ui_views org.blueberry.ui.views \htmlinclude org_blueberry_ui_views.html -\page xp_org_blueberry_tests org.blueberry.tests -\htmlinclude org_blueberry_tests.html - */ diff --git a/Documentation/Doxygen/3-DeveloperManual/Starting/Architecture.dox b/Documentation/Doxygen/3-DeveloperManual/Starting/Architecture.dox index 912a2a1cef..4387b2c242 100644 --- a/Documentation/Doxygen/3-DeveloperManual/Starting/Architecture.dox +++ b/Documentation/Doxygen/3-DeveloperManual/Starting/Architecture.dox @@ -1,47 +1,47 @@ /** \page Architecture The Architecture of MITK MITK is an open source software toolkit for medical image processing, subsequent data analysis and integration of medical hardware. It is designed with the aim of providing a modular and reusable code base to enable rapid development of new features. Following this design philosophy, MITK includes many specialized modules. This document is aimed at giving an overview of the general structure of MITK. It will give you an introduction to the coding and design concepts behind the toolkit. \section OverviewPage_DesignOverview Design Overview MITK is designed to be used either as a pure software library or as a complete application framework. Thus, a user of MITK can decide if he or she simply wants to add a new plug-in to the existing application framework or to implement an own application by using MITK as a software library. Depending on the type of use MITK uses different software libraries, which is shown in the next figure for overview. \imageMacro{MitkOverview.png,"Overview of MITK",16} As shown above, MITK uses the following libraries. These are the main libraries MITK is based on. For more functionality you can optionally include other libraries as well. A list of used libraries can be found \ref thirdpartylibs "here" . Based on these libraries, MITK includes the following features:
  • High level interactions with data.
  • Specialized medical imaging algorithms (e.g. segmentation)
  • Support of 3D + t data.
  • Complete application framework, expandable by plug-ins
  • Standard tools for medical imaging as default plug-ins (e.g. measurement, segmentation) -
  • Many specialized modules for different topics on medical imaging (e.g. diffusion imaging, image guided therapy, live image/ultrasound data processing) +
  • Many specialized modules for different topics on medical imaging (e.g. image guided therapy, live image/ultrasound data processing)
*/ diff --git a/Modules/AppUtil/include/mitkBaseApplication.h b/Modules/AppUtil/include/mitkBaseApplication.h index e1a36b1964..9b263db6d9 100644 --- a/Modules/AppUtil/include/mitkBaseApplication.h +++ b/Modules/AppUtil/include/mitkBaseApplication.h @@ -1,321 +1,317 @@ /*============================================================================ 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 mitkBaseApplication_h #define mitkBaseApplication_h #include #include #include #include class ctkPluginContext; class ctkPluginFramework; class QCoreApplication; class QTranslator; namespace mitk { /** * A utility class for starting BlueBerry applications. * * In the simplest case, create an instance of this class and call run(). * This will launch a CTK plugin framework instance and execute the * default application registered by a plug-in via the * org.blueberry.osgi.applications extension point. * * This class contains many convenience methods to: * - Put the application in \emph{safe mode} which catches unhandled * exceptions thrown in the Qt event loop and displays an error * message. * - Put the application in \emph{single mode} which by default * sends the command line arguments to an already running instance * of the same application instead of creating a second instance. * - Add a list of library names which should be pre-loaded at * application start-up, e.g. to speed up the initial launch during * the caching process of the plug-in meta-data. * - Set a custom provisioning file to start a specific set of CTK * plug-ins during application start-up. * - Set and get CTK plugin framework properties * * The behavior can further be customized by deriving from BaseApplication * and overriding specific methods, such as: * - initializeLibraryPaths() to add specific library / plugin search paths * - defineOptions(Poco::Util::OptionSet&) to define a custom set of * command line options * - getQApplication() to provide a custom QCoreApplication instance * * A simple but complete example: * * #include * * int main(int argc, char* argv[]) * { * mitk::BaseApplication app(argc, argv); * app.setApplicationName("MyApp"); * app.setOrganizationName("MyOrganization"); * * // Run the workbench * return app.run(); * } * */ class MITKAPPUTIL_EXPORT BaseApplication : public Poco::Util::Application { public: // Command line arguments static const QString ARG_APPLICATION; static const QString ARG_CLEAN; static const QString ARG_CONSOLELOG; static const QString ARG_DEBUG; static const QString ARG_FORCE_PLUGIN_INSTALL; static const QString ARG_HOME; static const QString ARG_NEWINSTANCE; static const QString ARG_NO_LAZY_REGISTRY_CACHE_LOADING; static const QString ARG_NO_REGISTRY_CACHE; static const QString ARG_PLUGIN_CACHE; static const QString ARG_PLUGIN_DIRS; static const QString ARG_PRELOAD_LIBRARY; static const QString ARG_PRODUCT; static const QString ARG_PROVISIONING; static const QString ARG_REGISTRY_MULTI_LANGUAGE; static const QString ARG_SPLASH_IMAGE; static const QString ARG_STORAGE_DIR; - static const QString ARG_TESTAPPLICATION; - static const QString ARG_TESTPLUGIN; static const QString ARG_XARGS; // BlueBerry specific plugin framework properties static const QString PROP_APPLICATION; static const QString PROP_FORCE_PLUGIN_INSTALL; static const QString PROP_NEWINSTANCE; static const QString PROP_NO_LAZY_REGISTRY_CACHE_LOADING; static const QString PROP_NO_REGISTRY_CACHE; static const QString PROP_PRODUCT; static const QString PROP_REGISTRY_MULTI_LANGUAGE; - static const QString PROP_TESTAPPLICATION; - static const QString PROP_TESTPLUGIN; BaseApplication(int argc, char **argv); ~BaseApplication() override; /** * Initialize the Qt library such that a QCoreApplication * instance is available and e.g. Qt widgets can be created. * * This is usually not called directly by the user. */ void initializeQt(); /** * Launches the BlueBerry framework and runs the default application * or the one specified in the PROP_APPLICATION framework property. * * @return The return code of the application after it was shut down. */ int run() override; void printHelp(const std::string &name, const std::string &value); /** * Set the application name. Same as QCoreApplication::setApplicationName. * @param name The application name. */ void setApplicationName(const QString &name); QString getApplicationName() const; /** * Set the organization name. Same as QCoreApplication::setOrganizationName. * @param name The organization name. */ void setOrganizationName(const QString &name); QString getOrganizationName() const; /** * Set the organization domain. Same as QCoreApplication::setOrganizationDomain. * @param name The organization domain. */ void setOrganizationDomain(const QString &name); QString getOrganizationDomain() const; /** * Put the application in single mode, which by default only allows * a single instance of the application to be created. * * Calling this method after run() has been called has no effect. * * @param singleMode */ void setSingleMode(bool singleMode); bool getSingleMode() const; /** * Put the application in safe mode, catching exceptions from the * Qt event loop. * * @param safeMode */ void setSafeMode(bool safeMode); bool getSafeMode() const; /** * Set a list of library names or absoulte file paths * which should be loaded at application start-up. The name * and file path may contain a library version appended at the * end and separated by a '$' charactger. * * For example liborg_mitk_gui_qt_common$1.0. * Platform specific suffixes are appended automatically. * * @param libraryBaseNames A list of library base names. */ void setPreloadLibraries(const QStringList &libraryBaseNames); /** * Get the list of library base names which should be pre-loaded. * * @return A list of pre-loaded libraries. */ QStringList getPreloadLibraries() const; /** * Set the path to the provisioning file. * * By default a provisioning file located in the same directory * as the executable and named .provisioning * is loaded if it exists. To disable parsing of provisioning * files, use an empty string as the argument. Use a * null QString (QString::null) to reset to the * default behaviour. * * @param filePath An absolute file path to the provisioning file. */ void setProvisioningFilePath(const QString &filePath); /** * Get the file path to the provisioning file. * @return The provisioning file path. */ QString getProvisioningFilePath() const; void setProperty(const QString &property, const QVariant &value); QVariant getProperty(const QString &property) const; void installTranslator(QTranslator*); bool isRunning(); void sendMessage(const QByteArray); protected: void initialize(Poco::Util::Application &self) override; void uninitialize() override; int getArgc() const; char **getArgv() const; /** * Get the framework storage directory for the CTK plugin * framework. This method is called in the initialize(Poco::Util::Application&) * method. It must not be called without a QCoreApplications instance. * * @return The CTK Plugin Framework storage directory. */ virtual QString getCTKFrameworkStorageDir() const; /** * Initialize the CppMicroServices library. * * The default implementation set the CppMicroServices storage * path to the current ctkPluginConstants::FRAMEWORK_STORAGE property * value. * * This method is called in the initialize(Poco::Util::Application&) * after the CTK Plugin Framework storage directory property * was set. */ virtual void initializeCppMicroServices(); /** * Get the QCoreApplication object. * * This method is called in the initialize(Poco::Util::Application&) * method and must create a QCoreApplication instance if the * global qApp variable is not initialized yet. * * @return The current QCoreApplication instance. This method * never returns null. */ virtual QCoreApplication *getQApplication() const; /** * Add plugin library search paths to the CTK Plugin Framework. * * This method is called in the nitialize(Poco::Util::Application&) * method after getQApplication() was called. */ virtual void initializeLibraryPaths(); /** * Runs the application for which the platform was started. The platform * must be running. *

* The given argument is passed to the application being run. If it is an invalid QVariant * then the command line arguments used in starting the platform, and not consumed * by the platform code, are passed to the application as a QStringList. *

* @param argument the argument passed to the application. May be invalid * @return the result of running the application * @throws std::exception if anything goes wrong */ int main(const std::vector &args) override; /** * Define command line arguments * @param options */ void defineOptions(Poco::Util::OptionSet &options) override; QSharedPointer getFramework() const; ctkPluginContext *getFrameworkContext() const; /** * Get the initial properties for the CTK plugin framework. * * The returned map contains the initial framework properties for * initializing the CTK plugin framework. The value of specific * properties may change at runtime and differ from the initial * value. * * @return The initial CTK Plugin Framework properties. */ QHash getFrameworkProperties() const; /* * Initialize and display the splash screen if an image filename is given * */ void initializeSplashScreen(QCoreApplication * application) const; private: struct Impl; Impl* d; }; } #endif // MITKBASEAPPLICATION_H diff --git a/Modules/AppUtil/src/mitkBaseApplication.cpp b/Modules/AppUtil/src/mitkBaseApplication.cpp index 316bd28185..c5b3252693 100644 --- a/Modules/AppUtil/src/mitkBaseApplication.cpp +++ b/Modules/AppUtil/src/mitkBaseApplication.cpp @@ -1,865 +1,853 @@ /*============================================================================ 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { void outputQtMessage(QtMsgType type, const QMessageLogContext&, const QString& msg) { auto message = msg.toStdString(); switch (type) { case QtDebugMsg: MITK_DEBUG << message; break; case QtInfoMsg: MITK_INFO << message; break; case QtWarningMsg: MITK_WARN << message; break; case QtCriticalMsg: MITK_ERROR << message; break; case QtFatalMsg: MITK_ERROR << message; abort(); default: MITK_INFO << message; break; } } } namespace mitk { const QString BaseApplication::ARG_APPLICATION = "BlueBerry.application"; const QString BaseApplication::ARG_CLEAN = "BlueBerry.clean"; const QString BaseApplication::ARG_CONSOLELOG = "BlueBerry.consoleLog"; const QString BaseApplication::ARG_DEBUG = "BlueBerry.debug"; const QString BaseApplication::ARG_FORCE_PLUGIN_INSTALL = "BlueBerry.forcePlugins"; const QString BaseApplication::ARG_HOME = "BlueBerry.home"; const QString BaseApplication::ARG_NEWINSTANCE = "BlueBerry.newInstance"; const QString BaseApplication::ARG_NO_LAZY_REGISTRY_CACHE_LOADING = "BlueBerry.noLazyRegistryCacheLoading"; const QString BaseApplication::ARG_NO_REGISTRY_CACHE = "BlueBerry.noRegistryCache"; const QString BaseApplication::ARG_PLUGIN_CACHE = "BlueBerry.plugin_cache_dir"; const QString BaseApplication::ARG_PLUGIN_DIRS = "BlueBerry.plugin_dirs"; const QString BaseApplication::ARG_PRELOAD_LIBRARY = "BlueBerry.preloadLibrary"; const QString BaseApplication::ARG_PRODUCT = "BlueBerry.product"; const QString BaseApplication::ARG_PROVISIONING = "BlueBerry.provisioning"; const QString BaseApplication::ARG_REGISTRY_MULTI_LANGUAGE = "BlueBerry.registryMultiLanguage"; const QString BaseApplication::ARG_SPLASH_IMAGE = "BlueBerry.splashscreen"; const QString BaseApplication::ARG_STORAGE_DIR = "BlueBerry.storageDir"; - const QString BaseApplication::ARG_TESTAPPLICATION = "BlueBerry.testapplication"; - const QString BaseApplication::ARG_TESTPLUGIN = "BlueBerry.testplugin"; const QString BaseApplication::ARG_XARGS = "xargs"; const QString BaseApplication::PROP_APPLICATION = "blueberry.application"; const QString BaseApplication::PROP_FORCE_PLUGIN_INSTALL = BaseApplication::ARG_FORCE_PLUGIN_INSTALL; const QString BaseApplication::PROP_NEWINSTANCE = BaseApplication::ARG_NEWINSTANCE; const QString BaseApplication::PROP_NO_LAZY_REGISTRY_CACHE_LOADING = BaseApplication::ARG_NO_LAZY_REGISTRY_CACHE_LOADING; const QString BaseApplication::PROP_NO_REGISTRY_CACHE = BaseApplication::ARG_NO_REGISTRY_CACHE; const QString BaseApplication::PROP_PRODUCT = "blueberry.product"; const QString BaseApplication::PROP_REGISTRY_MULTI_LANGUAGE = BaseApplication::ARG_REGISTRY_MULTI_LANGUAGE; - const QString BaseApplication::PROP_TESTAPPLICATION = "BlueBerry.testapplication"; - const QString BaseApplication::PROP_TESTPLUGIN = "BlueBerry.testplugin"; class SplashCloserCallback : public QRunnable { public: SplashCloserCallback(QSplashScreen* splashscreen) : m_Splashscreen(splashscreen) { } void run() override { this->m_Splashscreen->close(); } private: QSplashScreen *m_Splashscreen; // Owned by BaseApplication::Impl }; struct BaseApplication::Impl { ctkProperties m_FWProps; QCoreApplication *m_QApp; int m_Argc; char **m_Argv; #ifdef Q_OS_MAC std::vector m_Argv_macOS; #endif QString m_AppName; QString m_OrgaName; QString m_OrgaDomain; bool m_SingleMode; bool m_SafeMode; QSplashScreen *m_Splashscreen; SplashCloserCallback *m_SplashscreenClosingCallback; QStringList m_PreloadLibs; QString m_ProvFile; Impl(int argc, char **argv) : m_Argc(argc), m_Argv(argv), #ifdef Q_OS_MAC m_Argv_macOS(), #endif m_SingleMode(false), m_SafeMode(true), m_Splashscreen(nullptr), m_SplashscreenClosingCallback(nullptr) { #ifdef Q_OS_MAC /* On macOS the process serial number is passed as an command line argument (-psn_) in certain circumstances. This option causes a Poco exception. We remove it, if present. */ m_Argv_macOS.reserve(argc); const char psn[] = "-psn"; for (decltype(argc) i = 0; i < argc; ++i) { if (0 == strncmp(argv[i], psn, sizeof(psn))) continue; m_Argv_macOS.push_back(argv[i]); } m_Argc = static_cast(m_Argv_macOS.size()); m_Argv = m_Argv_macOS.data(); #endif } ~Impl() { delete m_SplashscreenClosingCallback; delete m_Splashscreen; delete m_QApp; } QVariant getProperty(const QString &property) const { auto iter = m_FWProps.find(property); return m_FWProps.end() != iter ? iter.value() : QVariant(); } void handleBooleanOption(const std::string &name, const std::string &) { auto fwKey = QString::fromStdString(name); // Translate some keys to proper framework properties if (ARG_CONSOLELOG == fwKey) fwKey = ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG; // For all other options we use the command line option name as the // framework property key. m_FWProps[fwKey] = true; } void handlePreloadLibraryOption(const std::string &, const std::string &value) { m_PreloadLibs.push_back(QString::fromStdString(value)); } void handleClean(const std::string &, const std::string &) { m_FWProps[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN] = ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT; } void initializeCTKPluginFrameworkProperties(Poco::Util::LayeredConfiguration &configuration) { // Add all configuration key/value pairs as framework properties Poco::Util::LayeredConfiguration::Keys keys; Poco::Util::LayeredConfiguration::Keys keyStack; configuration.keys(keyStack); std::vector keyChain; while (!keyStack.empty()) { const auto currSubKey = keyStack.back(); if (!keyChain.empty() && keyChain.back() == currSubKey) { keyChain.pop_back(); keyStack.pop_back(); continue; } Poco::Util::LayeredConfiguration::Keys subKeys; configuration.keys(currSubKey, subKeys); if (subKeys.empty()) { std::string finalKey; keyStack.pop_back(); for (const auto key : keyChain) finalKey += key + '.'; finalKey += currSubKey; keys.push_back(finalKey); } else { keyChain.push_back(currSubKey); for (const auto key : subKeys) keyStack.push_back(key); } } for (const auto key : keys) { if (configuration.hasProperty(key)) { // .ini and command line options overwrite already inserted keys auto qKey = QString::fromStdString(key); m_FWProps[qKey] = QString::fromStdString(configuration.getString(key)); } } } void parseProvisioningFile(const QString &filePath) { // Skip parsing if the file path is empty if (filePath.isEmpty()) return; auto consoleLog = this->getProperty(ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG).toBool(); // Read initial plugins from a provisioning file QFileInfo provFile(filePath); QStringList pluginsToStart; if (provFile.exists()) { MITK_INFO(consoleLog) << "Using provisioning file: " << qPrintable(provFile.absoluteFilePath()); ProvisioningInfo provInfo(provFile.absoluteFilePath()); // It can still happen that the encoding is not compatible with the fromUtf8 function (i.e. when // manipulating the LANG variable). The QStringList in provInfo is empty then. if (provInfo.getPluginDirs().empty()) { MITK_ERROR << "Cannot search for provisioning file, the retrieved directory list is empty.\n" << "This can happen if there are some special non-ASCII characters in the install path."; } else { for(const auto pluginPath : provInfo.getPluginDirs()) ctkPluginFrameworkLauncher::addSearchPath(pluginPath); auto pluginUrlsToStart = provInfo.getPluginsToStart(); for (const auto url : pluginUrlsToStart) pluginsToStart.push_back(url.toString()); } } else { MITK_INFO(consoleLog) << "Provisionig file does not exist."; } if (!pluginsToStart.isEmpty()) { m_FWProps[ctkPluginFrameworkLauncher::PROP_PLUGINS] = pluginsToStart; // Use transient start with declared activation policy (this helps when the provisioning file // changes and some plug-ins should not be installed in the application any more). ctkPlugin::StartOptions startOptions(ctkPlugin::START_TRANSIENT | ctkPlugin::START_ACTIVATION_POLICY); m_FWProps[ctkPluginFrameworkLauncher::PROP_PLUGINS_START_OPTIONS] = static_cast(startOptions); } } }; BaseApplication::BaseApplication(int argc, char **argv) : Application(), d(new Impl(argc, argv)) { } BaseApplication::~BaseApplication() { delete d; } void BaseApplication::printHelp(const std::string &, const std::string &) { Poco::Util::HelpFormatter help(this->options()); help.setAutoIndent(); help.setCommand(this->commandName()); help.format(std::cout); exit(EXIT_OK); } void BaseApplication::setApplicationName(const QString &name) { if (nullptr != qApp) qApp->setApplicationName(name); d->m_AppName = name; } QString BaseApplication::getApplicationName() const { return nullptr != qApp ? qApp->applicationName() : d->m_AppName; } void BaseApplication::setOrganizationName(const QString &name) { if (nullptr != qApp) qApp->setOrganizationName(name); d->m_OrgaName = name; } QString BaseApplication::getOrganizationName() const { return nullptr != qApp ? qApp->organizationName() : d->m_OrgaName; } void BaseApplication::setOrganizationDomain(const QString &domain) { if (nullptr != qApp) qApp->setOrganizationDomain(domain); d->m_OrgaDomain = domain; } QString BaseApplication::getOrganizationDomain() const { return nullptr != qApp ? qApp->organizationDomain() : d->m_OrgaDomain; } void BaseApplication::setSingleMode(bool singleMode) { if (nullptr != qApp) return; d->m_SingleMode = singleMode; } bool BaseApplication::getSingleMode() const { return d->m_SingleMode; } void BaseApplication::setSafeMode(bool safeMode) { if (nullptr != qApp && nullptr == d->m_QApp) return; d->m_SafeMode = safeMode; nullptr == d->m_QApp && getSingleMode() ? static_cast(d->m_QApp)->setSafeMode(safeMode) : static_cast(d->m_QApp)->setSafeMode(safeMode); } bool BaseApplication::getSafeMode() const { return d->m_SafeMode; } void BaseApplication::setPreloadLibraries(const QStringList &libraryBaseNames) { d->m_PreloadLibs = libraryBaseNames; } QStringList BaseApplication::getPreloadLibraries() const { return d->m_PreloadLibs; } void BaseApplication::setProvisioningFilePath(const QString &filePath) { d->m_ProvFile = filePath; } QString BaseApplication::getProvisioningFilePath() const { auto provFilePath = d->m_ProvFile; // A null QString means look up a default provisioning file if (provFilePath.isNull() && nullptr != qApp) { QFileInfo appFilePath(QCoreApplication::applicationFilePath()); QDir basePath(QCoreApplication::applicationDirPath()); auto provFileName = appFilePath.baseName() + ".provisioning"; QFileInfo provFile(basePath.absoluteFilePath(provFileName)); #ifdef Q_OS_MAC /* * On macOS, if started from the build directory, the .provisioning file is located at: * * The executable path is: * * In this case we have to cdUp threetimes. * * During packaging the MitkWorkbench.provisioning file is placed at the same * level like the executable. Nothing has to be done. */ if (!provFile.exists()) { basePath.cdUp(); basePath.cdUp(); basePath.cdUp(); provFile = basePath.absoluteFilePath(provFileName); } #endif if (provFile.exists()) { provFilePath = provFile.absoluteFilePath(); } #ifdef CMAKE_INTDIR else { basePath.cdUp(); provFile.setFile(basePath.absoluteFilePath(provFileName)); if (provFile.exists()) provFilePath = provFile.absoluteFilePath(); } #endif } return provFilePath; } void BaseApplication::initializeQt() { if (nullptr != qApp) return; // If parameters have been set before, we have to store them to hand them // through to the application auto appName = this->getApplicationName(); auto orgName = this->getOrganizationName(); auto orgDomain = this->getOrganizationDomain(); // Create a QCoreApplication instance this->getQApplication(); // Provide parameters to QCoreApplication this->setApplicationName(appName); this->setOrganizationName(orgName); this->setOrganizationDomain(orgDomain); qInstallMessageHandler(outputQtMessage); } void BaseApplication::initialize(Poco::Util::Application &self) { // 1. Call the super-class method Poco::Util::Application::initialize(self); // 2. Initialize the Qt framework (by creating a QCoreApplication) this->initializeQt(); // 3. Seed the random number generator, once at startup. QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // 4. Load the "default" configuration, which involves parsing // an optional .ini file and parsing any // command line arguments this->loadConfiguration(); // 5. Add configuration data from the command line and the // optional .ini file as CTK plugin // framework properties. d->initializeCTKPluginFrameworkProperties(this->config()); // 6. Initialize splash screen if an image path is provided // in the .ini file this->initializeSplashScreen(qApp); // 7. Set the custom CTK Plugin Framework storage directory QString storageDir = this->getCTKFrameworkStorageDir(); if (!storageDir.isEmpty()) d->m_FWProps[ctkPluginConstants::FRAMEWORK_STORAGE] = storageDir; // 8. Set the library search paths and the pre-load library property this->initializeLibraryPaths(); auto preloadLibs = this->getPreloadLibraries(); if (!preloadLibs.isEmpty()) d->m_FWProps[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES] = preloadLibs; // 9. Initialize the CppMicroServices library. // The initializeCppMicroServices() method reuses the // FRAMEWORK_STORAGE property, so we call it after the // getCTKFrameworkStorageDir method. this->initializeCppMicroServices(); // 10. Parse the (optional) provisioning file and set the // correct framework properties. d->parseProvisioningFile(this->getProvisioningFilePath()); // 11. Set the CTK Plugin Framework properties ctkPluginFrameworkLauncher::setFrameworkProperties(d->m_FWProps); } void BaseApplication::uninitialize() { auto pfw = this->getFramework(); if (pfw) { pfw->stop(); // Wait for up to 10 seconds for the CTK plugin framework to stop pfw->waitForStop(10000); } Poco::Util::Application::uninitialize(); } int BaseApplication::getArgc() const { return d->m_Argc; } char **BaseApplication::getArgv() const { return d->m_Argv; } QString BaseApplication::getCTKFrameworkStorageDir() const { QString storageDir; if (this->getSingleMode()) { // This function checks if an instance is already running and either sends a message to // it containing the command line arguments or checks if a new instance was forced by // providing the BlueBerry.newInstance command line argument. In the latter case, a path // to a temporary directory for the new application's storage directory is returned. storageDir = handleNewAppInstance(static_cast(d->m_QApp), d->m_Argc, d->m_Argv, ARG_NEWINSTANCE); } if (storageDir.isEmpty()) { // This is a new instance and no other instance is already running. We specify the // storage directory here (this is the same code as in berryInternalPlatform.cpp) // so that we can re-use the location for the persistent data location of the // the CppMicroServices library. // Append a hash value of the absolute path of the executable to the data location. // This allows to start the same application from different build or install trees. storageDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/" + this->getOrganizationName() + "/" + this->getApplicationName() + '_'; storageDir += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/"; } return storageDir; } void BaseApplication::initializeCppMicroServices() { auto storageDir = this->getProperty(ctkPluginConstants::FRAMEWORK_STORAGE).toString(); if (!storageDir.isEmpty()) us::ModuleSettings::SetStoragePath((storageDir + "us" + QDir::separator()).toStdString()); } QCoreApplication *BaseApplication::getQApplication() const { if (nullptr == qApp) { vtkOpenGLRenderWindow::SetGlobalMaximumNumberOfMultiSamples(0); auto defaultFormat = QVTKOpenGLWidget::defaultFormat(); defaultFormat.setSamples(0); QSurfaceFormat::setDefaultFormat(defaultFormat); #ifdef Q_OS_OSX QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); #endif QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); d->m_QApp = this->getSingleMode() ? static_cast(new QmitkSingleApplication(d->m_Argc, d->m_Argv, this->getSafeMode())) : static_cast(new QmitkSafeApplication(d->m_Argc, d->m_Argv, this->getSafeMode())); } return qApp; } void BaseApplication::initializeLibraryPaths() { QStringList suffixes; suffixes << "plugins"; #ifdef Q_OS_WINDOWS suffixes << "bin/plugins"; #ifdef CMAKE_INTDIR suffixes << "bin/" CMAKE_INTDIR "/plugins"; #endif #else suffixes << "lib/plugins"; #ifdef CMAKE_INTDIR suffixes << "lib/" CMAKE_INTDIR "/plugins"; #endif #endif #ifdef Q_OS_MAC suffixes << "../../plugins"; #endif // We add a couple of standard library search paths for plug-ins QDir appDir(QCoreApplication::applicationDirPath()); // Walk one directory up and add bin and lib sub-dirs; this might be redundant appDir.cdUp(); for (const auto suffix : suffixes) ctkPluginFrameworkLauncher::addSearchPath(appDir.absoluteFilePath(suffix)); } int BaseApplication::main(const std::vector &args) { // Start the plugin framework and all installed plug-ins according to their auto-start setting QStringList arguments; for (auto const &arg : args) arguments.push_back(QString::fromStdString(arg)); if (nullptr != d->m_Splashscreen) { // A splash screen is displayed. Create the closing callback. d->m_SplashscreenClosingCallback = new SplashCloserCallback(d->m_Splashscreen); } return ctkPluginFrameworkLauncher::run(d->m_SplashscreenClosingCallback, QVariant::fromValue(arguments)).toInt(); } void BaseApplication::defineOptions(Poco::Util::OptionSet &options) { Poco::Util::Option helpOption("help", "h", "print this help text"); helpOption.callback(Poco::Util::OptionCallback(this, &BaseApplication::printHelp)); options.addOption(helpOption); Poco::Util::Option newInstanceOption(ARG_NEWINSTANCE.toStdString(), "", "forces a new instance of this application"); newInstanceOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(newInstanceOption); Poco::Util::Option cleanOption(ARG_CLEAN.toStdString(), "", "cleans the plugin cache"); cleanOption.callback(Poco::Util::OptionCallback(d, &Impl::handleClean)); options.addOption(cleanOption); Poco::Util::Option productOption(ARG_PRODUCT.toStdString(), "", "the id of the product to be launched"); productOption.argument("").binding(PROP_PRODUCT.toStdString()); options.addOption(productOption); Poco::Util::Option appOption(ARG_APPLICATION.toStdString(), "", "the id of the application extension to be executed"); appOption.argument("").binding(PROP_APPLICATION.toStdString()); options.addOption(appOption); Poco::Util::Option provOption(ARG_PROVISIONING.toStdString(), "", "the location of a provisioning file"); provOption.argument("").binding(ARG_PROVISIONING.toStdString()); options.addOption(provOption); Poco::Util::Option storageDirOption(ARG_STORAGE_DIR.toStdString(), "", "the location for storing persistent application data"); storageDirOption.argument("").binding(ctkPluginConstants::FRAMEWORK_STORAGE.toStdString()); options.addOption(storageDirOption); Poco::Util::Option consoleLogOption(ARG_CONSOLELOG.toStdString(), "", "log messages to the console"); consoleLogOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(consoleLogOption); Poco::Util::Option debugOption(ARG_DEBUG.toStdString(), "", "enable debug mode"); debugOption.argument("", false).binding(ctkPluginFrameworkLauncher::PROP_DEBUG.toStdString()); options.addOption(debugOption); Poco::Util::Option forcePluginOption(ARG_FORCE_PLUGIN_INSTALL.toStdString(), "", "force installing plug-ins with same symbolic name"); forcePluginOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(forcePluginOption); Poco::Util::Option preloadLibsOption(ARG_PRELOAD_LIBRARY.toStdString(), "", "preload a library"); preloadLibsOption.argument("") .repeatable(true) .callback(Poco::Util::OptionCallback(d, &Impl::handlePreloadLibraryOption)); options.addOption(preloadLibsOption); - Poco::Util::Option testPluginOption(ARG_TESTPLUGIN.toStdString(), "", "the plug-in to be tested"); - testPluginOption.argument("").binding(PROP_TESTPLUGIN.toStdString()); - options.addOption(testPluginOption); - - Poco::Util::Option testAppOption(ARG_TESTAPPLICATION.toStdString(), "", "the application to be tested"); - testAppOption.argument("").binding(PROP_TESTAPPLICATION.toStdString()); - options.addOption(testAppOption); - Poco::Util::Option noRegistryCacheOption(ARG_NO_REGISTRY_CACHE.toStdString(), "", "do not use a cache for the registry"); noRegistryCacheOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(noRegistryCacheOption); Poco::Util::Option noLazyRegistryCacheLoadingOption(ARG_NO_LAZY_REGISTRY_CACHE_LOADING.toStdString(), "", "do not use lazy cache loading for the registry"); noLazyRegistryCacheLoadingOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(noLazyRegistryCacheLoadingOption); Poco::Util::Option registryMultiLanguageOption(ARG_REGISTRY_MULTI_LANGUAGE.toStdString(), "", "enable multi-language support for the registry"); registryMultiLanguageOption.callback(Poco::Util::OptionCallback(d, &Impl::handleBooleanOption)); options.addOption(registryMultiLanguageOption); Poco::Util::Option splashScreenOption(ARG_SPLASH_IMAGE.toStdString(), "", "optional picture to use as a splash screen"); splashScreenOption.argument("").binding(ARG_SPLASH_IMAGE.toStdString()); options.addOption(splashScreenOption); Poco::Util::Option xargsOption(ARG_XARGS.toStdString(), "", "Extended argument list"); xargsOption.argument("").binding(ARG_XARGS.toStdString()); options.addOption(xargsOption); Poco::Util::Application::defineOptions(options); } QSharedPointer BaseApplication::getFramework() const { return ctkPluginFrameworkLauncher::getPluginFramework(); } ctkPluginContext *BaseApplication::getFrameworkContext() const { auto framework = getFramework(); return framework ? framework->getPluginContext() : nullptr; } void BaseApplication::initializeSplashScreen(QCoreApplication * application) const { auto pixmapFileNameProp = d->getProperty(ARG_SPLASH_IMAGE); if (!pixmapFileNameProp.isNull()) { auto pixmapFileName = pixmapFileNameProp.toString(); QFileInfo checkFile(pixmapFileName); if (checkFile.exists() && checkFile.isFile()) { QPixmap pixmap(checkFile.absoluteFilePath()); d->m_Splashscreen = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint); d->m_Splashscreen->show(); application->processEvents(); } } } QHash BaseApplication::getFrameworkProperties() const { return d->m_FWProps; } int BaseApplication::run() { this->init(d->m_Argc, d->m_Argv); return Application::run(); } void BaseApplication::setProperty(const QString &property, const QVariant &value) { d->m_FWProps[property] = value; } QVariant BaseApplication::getProperty(const QString &property) const { return d->getProperty(property); } void BaseApplication::installTranslator(QTranslator* translator) { this->getQApplication()->installTranslator(translator); } bool BaseApplication::isRunning() { auto app = dynamic_cast(this->getQApplication()); if (nullptr != app) app->isRunning(); mitkThrow() << "Method not implemented."; } void BaseApplication::sendMessage(const QByteArray msg) { auto app = dynamic_cast(this->getQApplication()); if (nullptr != app) app->sendMessage(msg); mitkThrow() << "Method not implemented."; } } diff --git a/Modules/Classification/CLMiniApps/CMakeLists.txt b/Modules/Classification/CLMiniApps/CMakeLists.txt index 0bb6f5e560..162e071d36 100644 --- a/Modules/Classification/CLMiniApps/CMakeLists.txt +++ b/Modules/Classification/CLMiniApps/CMakeLists.txt @@ -1,122 +1,120 @@ option(BUILD_ClassificationMiniApps "Build commandline tools for classification" OFF) if(BUILD_ClassificationMiniApps OR MITK_BUILD_ALL_APPS) include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ) # list of miniapps # if an app requires additional dependencies # they are added after a "^^" and separated by "_" set( classificationminiapps RandomForestTraining^^MitkCLVigraRandomForest NativeHeadCTSegmentation^^MitkCLVigraRandomForest ManualSegmentationEvaluation^^MitkCLVigraRandomForest CLScreenshot^^MitkCore_MitkQtWidgetsExt_MitkCLUtilities CLDicom2Nrrd^^MitkCore CLResampleImageToReference^^MitkCore CLGlobalImageFeatures^^MitkCLUtilities_MitkQtWidgetsExt CLMRNormalization^^MitkCLUtilities_MitkCLMRUtilities CLStaple^^MitkCLUtilities CLVoxelFeatures^^MitkCLUtilities CLPolyToNrrd^^ CLPlanarFigureToNrrd^^MitkCore_MitkSegmentation_MitkMultilabel CLSimpleVoxelClassification^^MitkDataCollection_MitkCLVigraRandomForest CLVoxelClassification^^MitkDataCollection_MitkCLImportanceWeighting_MitkCLVigraRandomForest CLBrainMask^^MitkCLUtilities XRaxSimulationFromCT^^MitkCLUtilities CLRandomSampling^^MitkCore_MitkCLUtilities CLRemoveEmptyVoxels^^MitkCore CLN4^^MitkCore CLSkullMask^^MitkCore CLPointSetToSegmentation^^ CLMultiForestPrediction^^MitkDataCollection_MitkCLVigraRandomForest CLNrrdToPoly^^MitkCore CL2Dto3DImage^^MitkCore CLWeighting^^MitkCore_MitkCLImportanceWeighting_MitkCLUtilities CLOverlayRoiCenterOfMass^^MitkCore_MitkCLUtilities_MitkQtWidgetsExt CLLungSegmentation^^MitkCore_MitkSegmentation_MitkMultilabel # RandomForestPrediction^^MitkCLVigraRandomForest ) foreach(classificationminiapps ${classificationminiapps}) # extract mini app name and dependencies string(REPLACE "^^" "\\;" miniapp_info ${classificationminiapps}) set(miniapp_info_list ${miniapp_info}) list(GET miniapp_info_list 0 appname) list(GET miniapp_info_list 1 raw_dependencies) string(REPLACE "_" "\\;" dependencies "${raw_dependencies}") set(dependencies_list ${dependencies}) mitk_create_executable(${appname} DEPENDS MitkCore MitkCLCore MitkCommandLine ${dependencies_list} PACKAGE_DEPENDS ITK Qt5|Core Vigra CPP_FILES ${appname}.cpp ) # CPP_FILES ${appname}.cpp mitkCommandLineParser.cpp if(EXECUTABLE_IS_ENABLED) # On Linux, create a shell script to start a relocatable application if(UNIX AND NOT APPLE) install(PROGRAMS "${MITK_SOURCE_DIR}/CMake/RunInstalledApp.sh" DESTINATION "." RENAME ${EXECUTABLE_TARGET}.sh) endif() get_target_property(_is_bundle ${EXECUTABLE_TARGET} MACOSX_BUNDLE) if(APPLE) if(_is_bundle) set(_target_locations ${EXECUTABLE_TARGET}.app) set(${_target_locations}_qt_plugins_install_dir ${EXECUTABLE_TARGET}.app/Contents/MacOS) set(_bundle_dest_dir ${EXECUTABLE_TARGET}.app/Contents/MacOS) set(_qt_plugins_for_current_bundle ${EXECUTABLE_TARGET}.app/Contents/MacOS) set(_qt_conf_install_dirs ${EXECUTABLE_TARGET}.app/Contents/Resources) install(TARGETS ${EXECUTABLE_TARGET} BUNDLE DESTINATION . ) else() if(NOT MACOSX_BUNDLE_NAMES) set(_qt_conf_install_dirs bin) set(_target_locations bin/${EXECUTABLE_TARGET}) set(${_target_locations}_qt_plugins_install_dir bin) install(TARGETS ${EXECUTABLE_TARGET} RUNTIME DESTINATION bin) else() foreach(bundle_name ${MACOSX_BUNDLE_NAMES}) list(APPEND _qt_conf_install_dirs ${bundle_name}.app/Contents/Resources) set(_current_target_location ${bundle_name}.app/Contents/MacOS/${EXECUTABLE_TARGET}) list(APPEND _target_locations ${_current_target_location}) set(${_current_target_location}_qt_plugins_install_dir ${bundle_name}.app/Contents/MacOS) message( " set(${_current_target_location}_qt_plugins_install_dir ${bundle_name}.app/Contents/MacOS) ") install(TARGETS ${EXECUTABLE_TARGET} RUNTIME DESTINATION ${bundle_name}.app/Contents/MacOS/) endforeach() endif() endif() else() set(_target_locations bin/${EXECUTABLE_TARGET}${CMAKE_EXECUTABLE_SUFFIX}) set(${_target_locations}_qt_plugins_install_dir bin) set(_qt_conf_install_dirs bin) install(TARGETS ${EXECUTABLE_TARGET} RUNTIME DESTINATION bin) endif() endif() endforeach() - # This mini app does not depend on mitkDiffusionImaging at all - mitk_create_executable(CLMatchPointReg DEPENDS MitkCore MitkCLUtilities MitkMatchPointRegistration MitkCommandLine MitkMatchPointRegistrationUI PACKAGE_DEPENDS ITK Qt5|Core Vigra MatchPoint - CPP_FILES CLMatchPointReg.cpp + CPP_FILES CLMatchPointReg.cpp ) # On Linux, create a shell script to start a relocatable application if(UNIX AND NOT APPLE) install(PROGRAMS "${MITK_SOURCE_DIR}/CMake/RunInstalledApp.sh" DESTINATION "." RENAME ${EXECUTABLE_TARGET}.sh) endif() if(EXECUTABLE_IS_ENABLED) MITK_INSTALL_TARGETS(EXECUTABLES ${EXECUTABLE_TARGET}) endif() endif() diff --git a/Modules/Classification/DataCollection/ReaderWriter/mitkCollectionWriter.h b/Modules/Classification/DataCollection/ReaderWriter/mitkCollectionWriter.h index 5fdf9917b2..95a6eae1d3 100755 --- a/Modules/Classification/DataCollection/ReaderWriter/mitkCollectionWriter.h +++ b/Modules/Classification/DataCollection/ReaderWriter/mitkCollectionWriter.h @@ -1,77 +1,69 @@ /*============================================================================ 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 MITK_COLLECTION_WRITER_H #define MITK_COLLECTION_WRITER_H //#include "mitkCommon.h" #include "mitkDataCollection.h" #include "mitkCollectionReader.h" #include namespace mitk { class MITKDATACOLLECTION_EXPORT CollectionWriter { public: - - typedef float TensorScalar; /** * @brief ExportCollectionToFolder * * Creates an XML file and stores all data in the same folder as the xml file (creating sub-folders for sub-collections) * - * - * Naming Conventions (Neccessary for proper saving of these images): - * DWI - Diffusion Weighted Images - * DTI - Diffusion Tensor Images - * FIB - Fiber Bundles - * * @param dataCollection * @param xmlFile * @param filter - (optional) only items with names contained in this list are written, if list is empty all items are written * @return */ static bool ExportCollectionToFolder(DataCollection* dataCollection, std::string xmlFile , std::vector filter); static bool ExportCollectionToFolder(DataCollection* dataCollection, std::string xmlFile); /** * @brief SaveCollection - Stores data collection at original location * * Writes the collection back to the files given in the original XML file. * New data items are stored into the default location, which is relative to the XML file. * * If a XML file is provided the files are stored as stated above with the differences that a new XML file is generated and new files are saved * relative to the newly generated xml. * * @param dataCollection * @param filter * @param xmlFile * @return */ static bool SaveCollection(DataCollection* dataCollection, std::vector filter, std::string xmlFile = ""); static bool FolderToXml(std::string folder, std::string collectionType, std::string xmlFile, std::vector filter, std::vector seriesNames); // GTV last entry in filter list, this item will be made to TARGET static bool SingleFolderToXml(std::string folder, std::string xmlFile, std::vector filter, std::vector seriesNames, bool longDate = true, int skipUntil = 0, float months = 0); protected: private: static size_t GetIndexForinXMonths(CollectionReader::FileListType fileList, float months, size_t curIndex, std::vector filter); }; } // namespace mitk #endif /* MITK_COLLECTION_WRITER_H */ diff --git a/Modules/Core/include/mitkImageVtkMapper2D.h b/Modules/Core/include/mitkImageVtkMapper2D.h index f629db70c0..d4d7af9b93 100644 --- a/Modules/Core/include/mitkImageVtkMapper2D.h +++ b/Modules/Core/include/mitkImageVtkMapper2D.h @@ -1,307 +1,307 @@ /*============================================================================ 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 MITKIMAGEVTKMAPPER2D_H_HEADER_INCLUDED_C10E906E #define MITKIMAGEVTKMAPPER2D_H_HEADER_INCLUDED_C10E906E // MITK #include // MITK Rendering #include "mitkBaseRenderer.h" #include "mitkExtractSliceFilter.h" #include "mitkVtkMapper.h" // VTK #include #include class vtkActor; class vtkPolyDataMapper; class vtkPlaneSource; class vtkImageData; class vtkLookupTable; class vtkImageExtractComponents; class vtkImageReslice; class vtkImageChangeInformation; class vtkPoints; class vtkMitkThickSlicesFilter; class vtkPolyData; class vtkMitkApplyLevelWindowToRGBFilter; class vtkMitkLevelWindowFilter; namespace mitk { /** \brief Mapper to resample and display 2D slices of a 3D image. * * The following image gives a brief overview of the mapping and the involved parts. * * \image html imageVtkMapper2Darchitecture.png * * First, the image is resliced by means of vtkImageReslice. The volume image * serves as input to the mapper in addition to spatial placement of the slice and a few other * properties such as thick slices. This code was already present in the old version * (mitkImageMapperGL2D). * * Next, the obtained slice (m_ReslicedImage) is put into a vtkMitkLevelWindowFilter * and the scalar levelwindow, opacity levelwindow and optional clipping to * local image bounds are applied * * Next, the output of the vtkMitkLevelWindowFilter is used to create a texture * (m_Texture) and a plane onto which the texture is rendered (m_Plane). For * mapping purposes, a vtkPolyDataMapper (m_Mapper) is utilized. Orthographic * projection is applied to create the effect of a 2D image. The mapper and the * texture are assigned to the actor (m_Actor) which is passed to the VTK rendering * pipeline via the method GetVtkProp(). * * In order to transform the textured plane to the correct position in space, the * same transformation as used for reslicing is applied to both the camera and the * vtkActor. All important steps are explained in more detail below. The resulting * 2D image (by reslicing the underlying 3D input image appropriately) can either * be directly rendered in a 2D view or just be calculated to be used later by another * rendering entity, e.g. in texture mapping in a 3D view. * * Properties that can be set for images and influence the imageMapper2D are: * * - \b "opacity": (FloatProperty) Opacity of the image * - \b "color": (ColorProperty) Color of the image * - \b "LookupTable": (mitkLookupTableProperty) If this property is set, * the default lookuptable will be ignored and the "LookupTable" value * will be used instead. * - \b "Image Rendering.Mode": This property decides which mode is used to render images. (E.g. if a lookup table or a transferfunction is applied). Detailed documentation about the modes can be found here: \link - mitk::RenderingerModeProperty \endlink + mitk::RenderingModeProperty \endlink * - \b "Image Rendering.Transfer Function": (mitkTransferFunctionProperty) If this * property is set, a color transferfunction will be used to color the image. * - \b "binary": (BoolProperty) is the image a binary image or not * - \b "outline binary": (BoolProperty) show outline of the image or not * - \b "texture interpolation": (BoolProperty) texture interpolation of the image * - \b "reslice interpolation": (VtkResliceInterpolationProperty) reslice interpolation of the image * - \b "in plane resample extent by geometry": (BoolProperty) Do it or not * - \b "bounding box": (BoolProperty) Is the Bounding Box of the image shown or not * - \b "layer": (IntProperty) Layer of the image * - \b "volume annotation color": (ColorProperty) color of the volume annotation, TODO has to be reimplemented * - \b "volume annotation unit": (StringProperty) annotation unit as string (does not implicit convert the unit!) unit is ml or cm3, TODO has to be reimplemented * The default properties are: * - \b "opacity", mitk::FloatProperty::New(0.3f), renderer, overwrite ) * - \b "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ) * - \b "binary", mitk::BoolProperty::New( true ), renderer, overwrite ) * - \b "outline binary", mitk::BoolProperty::New( false ), renderer, overwrite ) * - \b "texture interpolation", mitk::BoolProperty::New( false ) ) * - \b "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ) * - \b "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ) * - \b "bounding box", mitk::BoolProperty::New( false ) ) * - \b "layer", mitk::IntProperty::New(10), renderer, overwrite) * - \b "Image Rendering.Transfer Function": Default color transfer function for CTs * - \b "LookupTable": Rainbow color. * If the modality-property is set for an image, the mapper uses modality-specific default properties, * e.g. color maps, if they are defined. * \ingroup Mapper */ class MITKCORE_EXPORT ImageVtkMapper2D : public VtkMapper { public: /** Standard class typedefs. */ mitkClassMacro(ImageVtkMapper2D, VtkMapper); /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Get the Image to map */ const mitk::Image *GetInput(void); /** \brief Checks whether this mapper needs to update itself and generate * data. */ void Update(mitk::BaseRenderer *renderer) override; //### methods of MITK-VTK rendering pipeline vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; //### end of methods of MITK-VTK rendering pipeline /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ /** * To render transveral, coronal, and sagittal, the mapper is called three times. * For performance reasons, the corresponding data for each view is saved in the * internal helper class LocalStorage. This allows rendering n views with just * 1 mitkMapper using n vtkMapper. * */ class MITKCORE_EXPORT LocalStorage : public mitk::Mapper::BaseLocalStorage { public: /** \brief Actor of a 2D render window. */ vtkSmartPointer m_Actor; vtkSmartPointer m_Actors; /** \brief Mapper of a 2D render window. */ vtkSmartPointer m_Mapper; vtkSmartPointer m_VectorComponentExtractor; /** \brief Current slice of a 2D render window.*/ vtkSmartPointer m_ReslicedImage; /** \brief Empty vtkPolyData that is set when rendering geometry does not * intersect the image geometry. * \warning This member variable is set to nullptr, * if no image geometry is inside the plane geometry * of the respective render window. Any user of this * slice has to check whether it is set to nullptr! */ vtkSmartPointer m_EmptyPolyData; /** \brief Plane on which the slice is rendered as texture. */ vtkSmartPointer m_Plane; /** \brief The texture which is used to render the current slice. */ vtkSmartPointer m_Texture; /** \brief The lookuptables for colors and level window */ vtkSmartPointer m_DefaultLookupTable; vtkSmartPointer m_BinaryLookupTable; vtkSmartPointer m_ColorLookupTable; /** \brief The actual reslicer (one per renderer) */ mitk::ExtractSliceFilter::Pointer m_Reslicer; /** \brief Filter for thick slices */ vtkSmartPointer m_TSFilter; /** \brief PolyData object containg all lines/points needed for outlining the contour. This container is used to save a computed contour for the next rendering execution. For instance, if you zoom or pann, there is no need to recompute the contour. */ vtkSmartPointer m_OutlinePolyData; /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** \brief mmPerPixel relation between pixel and mm. (World spacing).*/ mitk::ScalarType *m_mmPerPixel; /** \brief This filter is used to apply the level window to Grayvalue and RBG(A) images. */ vtkSmartPointer m_LevelWindowFilter; /** \brief Default constructor of the local storage. */ LocalStorage(); /** \brief Default deconstructor of the local storage. */ ~LocalStorage() override; }; /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; /** \brief Get the LocalStorage corresponding to the current renderer. */ LocalStorage *GetLocalStorage(mitk::BaseRenderer *renderer); /** \brief Set the default properties for general image rendering. */ static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); /** \brief This method switches between different rendering modes (e.g. use a lookup table or a transfer function). - * Detailed documentation about the modes can be found here: \link mitk::RenderingerModeProperty \endlink + * Detailed documentation about the modes can be found here: \link mitk::RenderingModeProperty \endlink */ void ApplyRenderingMode(mitk::BaseRenderer *renderer); protected: /** \brief Transforms the actor to the actual position in 3D. * \param renderer The current renderer corresponding to the render window. */ void TransformActor(mitk::BaseRenderer *renderer); /** \brief Generates a plane according to the size of the resliced image in milimeters. * * \image html texturedPlane.png * * In VTK a vtkPlaneSource is defined through three points. The origin and two * points defining the axes of the plane (see VTK documentation). The origin is * set to (xMin; yMin; Z), where xMin and yMin are the minimal bounds of the * resliced image in space. Z is relevant for blending and the layer property. * The center of the plane (C) is also the center of the view plane (cf. the image above). * * \note For the standard MITK view with three 2D render windows showing three * different slices, three such planes are generated. All these planes are generated * in the XY-plane (even if they depict a YZ-slice of the volume). * */ void GeneratePlane(mitk::BaseRenderer *renderer, double planeBounds[6]); /** \brief Generates a vtkPolyData object containing the outline of a given binary slice. \param renderer: Pointer to the renderer containing the needed information \note This code is based on code from the iil library. */ template vtkSmartPointer CreateOutlinePolyData(mitk::BaseRenderer *renderer); /** Default constructor */ ImageVtkMapper2D(); /** Default deconstructor */ ~ImageVtkMapper2D() override; /** \brief Does the actual resampling, without rendering the image yet. * All the data is generated inside this method. The vtkProp (or Actor) * is filled with content (i.e. the resliced image). * * After generation, a 4x4 transformation matrix(t) of the current slice is obtained * from the vtkResliceImage object via GetReslicesAxis(). This matrix is * applied to each textured plane (actor->SetUserTransform(t)) to transform everything * to the actual 3D position (cf. the following image). * * \image html cameraPositioning3D.png * */ void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; /** \brief This method uses the vtkCamera clipping range and the layer property * to calcualte the depth of the object (e.g. image or contour). The depth is used * to keep the correct order for the final VTK rendering.*/ float CalculateLayerDepth(mitk::BaseRenderer *renderer); /** \brief This method applies (or modifies) the lookuptable for all types of images. * \warning To use the lookup table, the property 'Lookup Table' must be set and a 'Image Rendering.Mode' * which uses the lookup table must be set. */ void ApplyLookuptable(mitk::BaseRenderer *renderer); /** \brief This method applies a color transfer function. * Internally, a vtkColorTransferFunction is used. This is usefull for coloring continous * images (e.g. float) * \warning To use the color transfer function, the property 'Image Rendering.Transfer Function' must be set and a * 'Image Rendering.Mode' which uses the color transfer function must be set. */ void ApplyColorTransferFunction(mitk::BaseRenderer *renderer); /** * @brief ApplyLevelWindow Apply the level window for the given renderer. * \warning To use the level window, the property 'LevelWindow' must be set and a 'Image Rendering.Mode' which uses * the level window must be set. * @param renderer Level window for which renderer? */ void ApplyLevelWindow(mitk::BaseRenderer *renderer); /** \brief Set the color of the image/polydata */ void ApplyColor(mitk::BaseRenderer *renderer); /** \brief Set the opacity of the actor. */ void ApplyOpacity(mitk::BaseRenderer *renderer); /** * \brief Calculates whether the given rendering geometry intersects the * given SlicedGeometry3D. * * This method checks if the given PlaneGeometry intersects the given * SlicedGeometry3D. It calculates the distance of the PlaneGeometry to all * 8 cornerpoints of the SlicedGeometry3D. If all distances have the same * sign (all positive or all negative) there is no intersection. * If the distances have different sign, there is an intersection. **/ bool RenderingGeometryIntersectsImage(const PlaneGeometry *renderingGeometry, SlicedGeometry3D *imageGeometry); }; } // namespace mitk #endif /* MITKIMAGEVTKMAPPER2D_H_HEADER_INCLUDED_C10E906E */ diff --git a/Modules/Core/include/vtkMitkLevelWindowFilter.h b/Modules/Core/include/vtkMitkLevelWindowFilter.h index c1604f429a..6b4d7caad7 100644 --- a/Modules/Core/include/vtkMitkLevelWindowFilter.h +++ b/Modules/Core/include/vtkMitkLevelWindowFilter.h @@ -1,98 +1,97 @@ /*============================================================================ 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 __vtkMitkLevelWindowFilter_h #define __vtkMitkLevelWindowFilter_h class vtkScalarsToColors; class vtkPiecewiseFunction; #include #include #include /** Documentation * \brief Applies the grayvalue or color/opacity level window to scalar or RGB(A) images. * -* This filter is used to apply the color level window to RGB images (e.g. -* diffusion tensor images). Therefore, the RGB channels are converted to -* the HSI color space, where the level window can be applied. Afterwards, -* the HSI values transformed back to the RGB space. +* This filter is used to apply the color level window to RGB images. +* Therefore, the RGB channels are converted to the HSI color space, where the level +* window can be applied. Afterwards, the HSI values transformed back to the RGB space. * * The filter is also able to apply an opacity level window to RGBA images. * * \ingroup Renderer */ class MITKCORE_EXPORT vtkMitkLevelWindowFilter : public vtkThreadedImageAlgorithm { public: vtkTypeMacro(vtkMitkLevelWindowFilter, vtkThreadedImageAlgorithm); static vtkMitkLevelWindowFilter *New(); vtkMTimeType GetMTime() override; /** \brief Get the lookup table for the RGB level window */ vtkScalarsToColors *GetLookupTable(); /** \brief Set the lookup table for the RGB level window */ void SetLookupTable(vtkScalarsToColors *lookupTable); /** \brief Get the piecewise function used to map scalar to alpha component value (only * used when the lookupTable is a vtkColorTransferFunction) */ vtkPiecewiseFunction *GetOpacityPiecewiseFunction() { return m_OpacityFunction; } /** \brief Set the piecewise function used to map scalar to alpha component value (only * used when the lookupTable is a vtkColorTransferFunction) */ void SetOpacityPiecewiseFunction(vtkPiecewiseFunction *opacityFunction); /** \brief Get/Set the lower window opacity for the alpha level window */ void SetMinOpacity(double minOpacity); inline double GetMinOpacity() const; /** \brief Get/Set the upper window opacity for the alpha level window */ void SetMaxOpacity(double maxOpacity); inline double GetMaxOpacity() const; /** \brief Set clipping bounds for the opaque part of the resliced 2d image */ void SetClippingBounds(double *); protected: /** Default constructor. */ vtkMitkLevelWindowFilter(); /** Default deconstructor. */ ~vtkMitkLevelWindowFilter() override; /** \brief Method for threaded execution of the filter. * \param *inData: The input. * \param *outData: The output of the filter. * \param extent: Specifies the region of the image to be updated inside this thread. * It is a six-component array of the form (xmin, xmax, ymin, ymax, zmin, zmax). * \param id: The thread id. */ void ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int extent[6], int id) override; // /** Standard VTK filter method to apply the filter. See VTK documentation.*/ int RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) override; // /** Standard VTK filter method to apply the filter. See VTK documentation. Not used at the moment.*/ // void ExecuteInformation(vtkImageData *vtkNotUsed(inData), vtkImageData *vtkNotUsed(outData)); private: /** m_LookupTable contains the lookup table for the RGB level window.*/ vtkScalarsToColors *m_LookupTable; /** The transfer function to map the scalar to alpha (4th component of the RGBA output value) */ vtkPiecewiseFunction *m_OpacityFunction; /** m_MinOpacity contains the lower bound for the alpha level window.*/ double m_MinOpacity; /** m_MaxOpacity contains the upper bound for the alpha level window.*/ double m_MaxOpacity; double m_ClippingBounds[4]; }; #endif diff --git a/Modules/CppMicroServices/core/include/usModuleContext.h b/Modules/CppMicroServices/core/include/usModuleContext.h index dfcae418d5..358cbe4d8b 100644 --- a/Modules/CppMicroServices/core/include/usModuleContext.h +++ b/Modules/CppMicroServices/core/include/usModuleContext.h @@ -1,851 +1,851 @@ /*============================================================================ Library: CppMicroServices Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================*/ #ifndef USMODULECONTEXT_H_ #define USMODULECONTEXT_H_ // TODO: Replace includes with forward directives! #include "usListenerFunctors_p.h" #include "usServiceInterface.h" #include "usServiceEvent.h" #include "usServiceRegistration.h" #include "usServiceException.h" #include "usModuleEvent.h" US_BEGIN_NAMESPACE typedef US_SERVICE_LISTENER_FUNCTOR ServiceListener; typedef US_MODULE_LISTENER_FUNCTOR ModuleListener; class ModuleContextPrivate; class ServiceFactory; template class ServiceObjects; /** * \ingroup MicroServices * * A module's execution context within the framework. The context is used to * grant access to other methods so that this module can interact with the * Micro Services Framework. * *

* ModuleContext methods allow a module to: *

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

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

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

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

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

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

* A module can register a service object that implements the * ServiceFactory or PrototypeServiceFactory interface to have more * flexibility in providing service objects to other modules. * *

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

    *
  1. The framework adds the following service properties to the service * properties from the specified ServiceProperties (which may be * omitted):
    - * A property named ServiceConstants#SERVICE_ID() identifying the + * A property named us::ServiceConstants::SERVICE_ID() identifying the * registration number of the service
    - * A property named ServiceConstants#OBJECTCLASS() containing all the + * A property named us::ServiceConstants::OBJECTCLASS() containing all the * specified classes.
    - * A property named ServiceConstants#SERVICE_SCOPE() identifying the scope + * A property named us::ServiceConstants::SERVICE_SCOPE() identifying the scope * of the service.
    * Properties with these names in the specified ServiceProperties will * be ignored. *
  2. The service is added to the framework service registry and may now be * used by other modules. *
  3. A service event of type ServiceEvent#REGISTERED is fired. *
  4. A ServiceRegistration object for this registration is * returned. *
* * @note This is a low-level method and should normally not be used directly. * Use one of the templated RegisterService methods instead. * * @param service The service object, which is a map of interface identifiers * to raw service pointers. * @param properties The properties for this service. The keys in the * properties object must all be std::string objects. See - * {@link ServiceConstants} for a list of standard service property keys. + * us::ServiceConstants for a list of standard service property keys. * Changes should not be made to this object after calling this * method. To update the service's properties the - * {@link ServiceRegistration::SetProperties} method must be called. + * us::ServiceRegistration::SetProperties method must be called. * The set of properties may be omitted if the service has * no properties. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * * @throws std::invalid_argument If one of the following is true: *
    *
  • service is 0. *
  • properties contains case variants of the same key name. *
* @throws std::logic_error If this ModuleContext is no longer valid. * * @see ServiceRegistration * @see ServiceFactory * @see PrototypeServiceFactory */ ServiceRegistrationU RegisterService(const InterfaceMap& service, const ServiceProperties& properties = ServiceProperties()); /** * Registers the specified service object with the specified properties * using the specified template argument with the framework. * *

* This method is provided as a convenience when service will only be registered under * a single class name whose type is available to the caller. It is otherwise identical to * RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred * since it avoids errors in the string literal identifying the class name or interface identifier. * * Example usage: * \snippet uServices-registration/main.cpp 1-1 * \snippet uServices-registration/main.cpp 1-2 * * @tparam S The type under which the service can be located. * @param service The service object or a ServiceFactory object. * @param properties The properties for this service. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException If the service type \c S is invalid or the * \c service object is nullptr. * * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ template ServiceRegistration RegisterService(S* service, const ServiceProperties& properties = ServiceProperties()) { InterfaceMap servicePointers = MakeInterfaceMap(service); return RegisterService(servicePointers, properties); } /** * Registers the specified service object with the specified properties * using the specified template argument with the framework. * *

* This method is provided as a convenience when registering a service under * two interface classes whose type is available to the caller. It is otherwise identical to * RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred * since it avoids errors in the string literal identifying the class name or interface identifier. * * Example usage: * \snippet uServices-registration/main.cpp 2-1 * \snippet uServices-registration/main.cpp 2-2 * * @tparam I1 The first interface type under which the service can be located. * @tparam I2 The second interface type under which the service can be located. * @param impl The service object or a ServiceFactory object. * @param properties The properties for this service. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException If the service type \c S is invalid or the * \c service object is nullptr. * * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ template ServiceRegistration RegisterService(Impl* impl, const ServiceProperties& properties = ServiceProperties()) { InterfaceMap servicePointers = MakeInterfaceMap(impl); return RegisterService(servicePointers, properties); } /** * Registers the specified service object with the specified properties * using the specified template argument with the framework. * *

* This method is identical to the RegisterService(Impl*, const ServiceProperties&) * method except that it supports three service interface types. * * @tparam I1 The first interface type under which the service can be located. * @tparam I2 The second interface type under which the service can be located. * @tparam I3 The third interface type under which the service can be located. * @param impl The service object or a ServiceFactory object. * @param properties The properties for this service. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException If the service type \c S is invalid or the * \c service object is nullptr. * * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ template ServiceRegistration RegisterService(Impl* impl, const ServiceProperties& properties = ServiceProperties()) { InterfaceMap servicePointers = MakeInterfaceMap(impl); return RegisterService(servicePointers, properties); } /** * Registers the specified service factory as a service with the specified properties * using the specified template argument as service interface type with the framework. * *

* This method is provided as a convenience when factory will only be registered under * a single class name whose type is available to the caller. It is otherwise identical to * RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred * since it avoids errors in the string literal identifying the class name or interface identifier. * * Example usage: * \snippet uServices-registration/main.cpp 1-1 * \snippet uServices-registration/main.cpp f1 * * @tparam S The type under which the service can be located. * @param factory The ServiceFactory or PrototypeServiceFactory object. * @param properties The properties for this service. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException If the service type \c S is invalid or the * \c service factory object is nullptr. * * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ template ServiceRegistration RegisterService(ServiceFactory* factory, const ServiceProperties& properties = ServiceProperties()) { InterfaceMap servicePointers = MakeInterfaceMap(factory); return RegisterService(servicePointers, properties); } /** * Registers the specified service factory as a service with the specified properties * using the specified template argument as service interface type with the framework. * *

* This method is identical to the RegisterService(ServiceFactory*, const ServiceProperties&) * method except that it supports two service interface types. * * Example usage: * \snippet uServices-registration/main.cpp 2-1 * \snippet uServices-registration/main.cpp f2 * * @tparam I1 The first interface type under which the service can be located. * @tparam I2 The second interface type under which the service can be located. * @param factory The ServiceFactory or PrototypeServiceFactory object. * @param properties The properties for this service. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException If the service type \c S is invalid or the * \c service factory object is nullptr. * * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ template ServiceRegistration RegisterService(ServiceFactory* factory, const ServiceProperties& properties = ServiceProperties()) { InterfaceMap servicePointers = MakeInterfaceMap(factory); return RegisterService(servicePointers, properties); } /** * Registers the specified service factory as a service with the specified properties * using the specified template argument as service interface type with the framework. * *

* This method is identical to the RegisterService(ServiceFactory*, const ServiceProperties&) * method except that it supports three service interface types. * * @tparam I1 The first interface type under which the service can be located. * @tparam I2 The second interface type under which the service can be located. * @tparam I3 The third interface type under which the service can be located. * @param factory The ServiceFactory or PrototypeServiceFactory object. * @param properties The properties for this service. * @return A ServiceRegistration object for use by the module * registering the service to update the service's properties or to * unregister the service. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws ServiceException If the service type \c S is invalid or the * \c service factory object is nullptr. * * @see RegisterService(const InterfaceMap&, const ServiceProperties&) */ template ServiceRegistration RegisterService(ServiceFactory* factory, const ServiceProperties& properties = ServiceProperties()) { InterfaceMap servicePointers = MakeInterfaceMap(factory); return RegisterService(servicePointers, properties); } /** * Returns a list of ServiceReference objects. The returned * list contains services that * were registered under the specified class and match the specified filter * expression. * *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* This is a convenience method which is identical to void* GetService(const ServiceReferenceBase&) * except that it casts the service object to the supplied template argument type * * @tparam S The type the service object will be cast to. * @return A service object for the service associated with * reference or 0 if the service is not * registered, the ServiceFactory threw * an exception or the service could not be casted to the desired type. * @throws std::logic_error If this ModuleContext is no * longer valid. * @throws std::invalid_argument If the specified * ServiceReference is invalid (default constructed). * @see #GetService(const ServiceReferenceBase&) * @see #UngetService(const ServiceReferenceBase&) * @see ServiceFactory */ template S* GetService(const ServiceReference& reference) { const ServiceReferenceBase& baseRef = reference; return reinterpret_cast(GetService(baseRef)); } /** * Returns the ServiceObjects object for the service referenced by the specified * ServiceReference object. The ServiceObjects object can be used to obtain * multiple service objects for services with prototype scope. For services with * singleton or module scope, the ServiceObjects::GetService() method behaves * the same as the GetService(const ServiceReference&) method and the * ServiceObjects::UngetService(const ServiceReferenceBase&) method behaves the * same as the UngetService(const ServiceReferenceBase&) method. That is, only one, * use-counted service object is available from the ServiceObjects object. * * @tparam S Type of Service. * @param reference A reference to the service. * @return A ServiceObjects object for the service associated with the specified * reference or an invalid instance if the service is not registered. * @throws std::logic_error If this ModuleContext is no longer valid. * @throws std::invalid_argument If the specified ServiceReference is invalid * (default constructed or the service has been unregistered) * * @see PrototypeServiceFactory */ template ServiceObjects GetServiceObjects(const ServiceReference& reference) { return ServiceObjects(this, reference); } /** * Releases the service object referenced by the specified * ServiceReference object. If the context module's use count * for the service is zero, this method returns false. * Otherwise, the context modules's use count for the service is decremented * by one. * *

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

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

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

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

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

* The callback is called if the filter criteria is met. To filter based * upon the class of the service, the filter should reference the - * ServiceConstants#OBJECTCLASS() property. If filter is + * us::ServiceConstants::OBJECTCLASS() property. If filter is * empty, all services are considered to match the filter. * *

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

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

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

* If the (receiver,callback) pair is not contained in this * context module's list of listeners, this method does nothing. * * @tparam R The type of the receiver (containing the member function to be removed) * @param receiver The object from which to disconnect. * @param callback The member function pointer to remove. * @throws std::logic_error If this ModuleContext is no * longer valid. * @see AddModuleListener() */ template void RemoveModuleListener(R* receiver, void(R::*callback)(const ModuleEvent)) { RemoveModuleListener(ModuleListenerMemberFunctor(receiver, callback), static_cast(receiver)); } /** * Get the absolute path for a file or directory in the persistent * storage area provided for the module. The returned path * might be empty if no storage path has been set previously. * If the path is non-empty, it is safe to assume that the path is writable. * * @see ModuleSettings::SetStoragePath(const std::string&) * * @param filename A relative name to the file or directory to be accessed. * @return The absolute path to the persistent storage area for the given file name. */ std::string GetDataFile(const std::string& filename) const; private: friend class Module; friend class ModulePrivate; ModuleContext(ModulePrivate* module); // purposely not implemented ModuleContext(const ModuleContext&); ModuleContext& operator=(const ModuleContext&); void AddServiceListener(const ServiceListener& delegate, void* data, const std::string& filter); void RemoveServiceListener(const ServiceListener& delegate, void* data); void AddModuleListener(const ModuleListener& delegate, void* data); void RemoveModuleListener(const ModuleListener& delegate, void* data); ModuleContextPrivate * const d; }; US_END_NAMESPACE #endif /* USMODULECONTEXT_H_ */ diff --git a/Modules/DICOMReader/doc/Doxygen/Modules.dox b/Modules/DICOMReader/doc/Doxygen/Modules.dox index a23b919558..2867b4a88e 100644 --- a/Modules/DICOMReader/doc/Doxygen/Modules.dox +++ b/Modules/DICOMReader/doc/Doxygen/Modules.dox @@ -1,39 +1,38 @@ /** \defgroup DICOMReaderModule The DICOMReader Module \ingroup MITKModules \brief DICOM This module contains a number of classes for DICOM image loading within MITK. \section DICOMReaderModule_overview Scope When people around MITK talk about loading DICOM images or series, they are really not interested in the images (2D slices) but in a 3D mitk::Image instance that groups DICOM images in a meaningful way. The task of this module is to provide - an interface for the general "DICOM files to mitk::Images" transformation: mitk::DICOMFileReader - a flexible default reader for the most common DICOM images: mitk::DICOMITKSeriesGDCMReader Most documentation is kept with these classes, so please have a look at their documentations. \remark Prior to this module, a class called DicomSeriesReader grew too much to be maintainable anymore. Its functionality is conserved by class mitk::ClassicDICOMSeriesReader. \section DICOMReaderModule_interface Module Interface The general loading proceduce is structured by mitk::DICOMFileReader, under the assumption that the best reader for a set of files is not known prior to inspection. To facilitate applications that need to select between possible readers based on what would be loaded, file readers are required to implement loading in two separate steps: 1. analysis of a list of files and description of potential mitk::Image%s by means of mitk::DICOMImageBlockDescriptor 2. actual loading of pixel data into mitk::Image%s A very simple implementation is mitk::DICOMFileReaderSelector which selects the reader with the least possible number of mitk::Images (least confusing for the user?). \section DICOMReaderModule_tasks Tasks for future development Unstructured development tasks and ideas for future extensions - - a reader for vector-valued diffusion images is currently being implemented - a multi-frame image reader based on DCMTK - perspective: slice-by-slice loading */ diff --git a/Modules/DICOMReader/include/mitkDICOMFileReaderSelector.h b/Modules/DICOMReader/include/mitkDICOMFileReaderSelector.h index 832f7fd456..ff12cd7730 100644 --- a/Modules/DICOMReader/include/mitkDICOMFileReaderSelector.h +++ b/Modules/DICOMReader/include/mitkDICOMFileReaderSelector.h @@ -1,100 +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. ============================================================================*/ #ifndef mitkDICOMFileReaderSelector_h #define mitkDICOMFileReaderSelector_h #include "mitkDICOMFileReader.h" #include namespace mitk { /** \ingroup DICOMReaderModule \brief Simple best-reader selection. This class implements a process of comparing different DICOMFileReader%s and selecting the reader with the minimal number of mitk::Image%s in its output. The code found in this class can - just be used to select a reader using this simple strategy - be taken as an example of how to use DICOMFileReader%s To create a selection of potential readers, the class makes use of mitk::DICOMReaderConfigurator, i.e. DICOMFileReaderSelector also expects the configuration files/strings to be in the format expected by mitk::DICOMReaderConfigurator. Two convenience methods load "default" configurations from compiled-in resources: LoadBuiltIn3DConfigs() and LoadBuiltIn3DnTConfigs(). */ class MITKDICOMREADER_EXPORT DICOMFileReaderSelector : public itk::LightObject { public: typedef std::list ReaderList; mitkClassMacroItkParent( DICOMFileReaderSelector, itk::LightObject ); itkNewMacro( DICOMFileReaderSelector ); /// \brief Add a configuration as expected by DICOMReaderConfigurator. /// Configs can only be reset by instantiating a new DICOMFileReaderSelector. void AddConfig(const std::string& xmlDescription); /// \brief Add a configuration as expected by DICOMReaderConfigurator. /// Configs can only be reset by instantiating a new DICOMFileReaderSelector. void AddConfigFile(const std::string& filename); /// \brief Add a whole pre-configured reader to the selection process. void AddFileReaderCanditate(DICOMFileReader::Pointer reader); - /// \brief Load 3D image creating configurations from the MITK module system (see \ref mitk::Module::FindResources). + /// \brief Load 3D image creating configurations from the MITK module system (see us::Module::FindResources()). /// For a default set of configurations, look into the directory Resources of the DICOMReader module. void LoadBuiltIn3DConfigs(); - /// \brief Load 3D+t image creating configurations from the MITK module system (see \ref mitk::Module::FindResources). + /// \brief Load 3D+t image creating configurations from the MITK module system (see us::Module::FindResources()). /// For a default set of configurations, look into the directory Resources of the DICOMReader module. void LoadBuiltIn3DnTConfigs(); /// \brief Return all the DICOMFileReader%s that are currently used for selection by this class. /// The readers returned by this method depend on what config files have been added earlier /// (or which of the built-in readers have been loaded) ReaderList GetAllConfiguredReaders() const; /// Input files void SetInputFiles(StringList filenames); /// Input files const StringList& GetInputFiles() const; /// Execute the analysis and selection process. The first reader with a minimal number of outputs will be returned. DICOMFileReader::Pointer GetFirstReaderWithMinimumNumberOfOutputImages(); protected: DICOMFileReaderSelector(); ~DICOMFileReaderSelector() override; void AddConfigsFromResources(const std::string& path); void AddConfigFromResource(const std::string& resourcename); void AddConfigFromResource(us::ModuleResource& resource); private: StringList m_PossibleConfigurations; StringList m_InputFilenames; ReaderList m_Readers; }; } // namespace #endif // mitkDICOMFileReaderSelector_h diff --git a/Modules/DicomRT/include/mitkDoseImageVtkMapper2D.h b/Modules/DicomRT/include/mitkDoseImageVtkMapper2D.h index 9c98014252..636f1a9ffe 100644 --- a/Modules/DicomRT/include/mitkDoseImageVtkMapper2D.h +++ b/Modules/DicomRT/include/mitkDoseImageVtkMapper2D.h @@ -1,309 +1,309 @@ /*============================================================================ 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 MITKDoseImageVtkMapper2D2D_H_HEADER_INCLUDED #define MITKDoseImageVtkMapper2D2D_H_HEADER_INCLUDED //MITK #include #include //MITK Rendering #include "mitkBaseRenderer.h" #include "mitkVtkMapper.h" #include "mitkExtractSliceFilter.h" //VTK #include #include #include class vtkActor; class vtkPolyDataMapper; class vtkPlaneSource; class vtkImageData; class vtkLookupTable; class vtkImageExtractComponents; class vtkImageReslice; class vtkImageChangeInformation; class vtkPoints; class vtkMitkThickSlicesFilter; class vtkPolyData; class vtkMitkApplyLevelWindowToRGBFilter; class vtkMitkLevelWindowFilter; namespace mitk { /** \brief Mapper to resample and display 2D slices of a 3D image. * * The following image gives a brief overview of the mapping and the involved parts. * * \image html DoseImageVtkMapper2Darchitecture.png * * First, the image is resliced by means of vtkImageReslice. The volume image * serves as input to the mapper in addition to spatial placement of the slice and a few other * properties such as thick slices. This code was already present in the old version * (mitkImageMapperGL2D). * * Next, the obtained slice (m_ReslicedImage) is put into a vtkMitkLevelWindowFilter * and the scalar levelwindow, opacity levelwindow and optional clipping to * local image bounds are applied * * Next, the output of the vtkMitkLevelWindowFilter is used to create a texture * (m_Texture) and a plane onto which the texture is rendered (m_Plane). For * mapping purposes, a vtkPolyDataMapper (m_Mapper) is utilized. Orthographic * projection is applied to create the effect of a 2D image. The mapper and the * texture are assigned to the actor (m_Actor) which is passed to the VTK rendering * pipeline via the method GetVtkProp(). * * In order to transform the textured plane to the correct position in space, the * same transformation as used for reslicing is applied to both the camera and the * vtkActor. All important steps are explained in more detail below. The resulting * 2D image (by reslicing the underlying 3D input image appropriately) can either * be directly rendered in a 2D view or just be calculated to be used later by another * rendering entity, e.g. in texture mapping in a 3D view. * * Properties that can be set for images and influence the imageMapper2D are: * * - \b "opacity": (FloatProperty) Opacity of the image * - \b "color": (ColorProperty) Color of the image * - \b "LookupTable": (mitkLookupTableProperty) If this property is set, * the default lookuptable will be ignored and the "LookupTable" value * will be used instead. - * - \b "Image Rendering.Mode": This property decides which mode is used to render images. (E.g. if a lookup table or a transferfunction is applied). Detailed documentation about the modes can be found here: \link mitk::RenderingerModeProperty \endlink + * - \b "Image Rendering.Mode": This property decides which mode is used to render images. (E.g. if a lookup table or a transferfunction is applied). Detailed documentation about the modes can be found here: \link mitk::RenderingModeProperty \endlink * - \b "Image Rendering.Transfer Function": (mitkTransferFunctionProperty) If this * property is set, a color transferfunction will be used to color the image. * - \b "binary": (BoolProperty) is the image a binary image or not * - \b "outline binary": (BoolProperty) show outline of the image or not * - \b "texture interpolation": (BoolProperty) texture interpolation of the image * - \b "reslice interpolation": (VtkResliceInterpolationProperty) reslice interpolation of the image * - \b "in plane resample extent by geometry": (BoolProperty) Do it or not * - \b "bounding box": (BoolProperty) Is the Bounding Box of the image shown or not * - \b "layer": (IntProperty) Layer of the image * - \b "volume annotation color": (ColorProperty) color of the volume annotation, TODO has to be reimplemented * - \b "volume annotation unit": (StringProperty) annotation unit as string (does not implicit convert the unit!) unit is ml or cm3, TODO has to be reimplemented * The default properties are: * - \b "opacity", mitk::FloatProperty::New(0.3f), renderer, overwrite ) * - \b "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ) * - \b "binary", mitk::BoolProperty::New( true ), renderer, overwrite ) * - \b "outline binary", mitk::BoolProperty::New( false ), renderer, overwrite ) * - \b "texture interpolation", mitk::BoolProperty::New( false ) ) * - \b "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ) * - \b "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ) * - \b "bounding box", mitk::BoolProperty::New( false ) ) * - \b "layer", mitk::IntProperty::New(10), renderer, overwrite) * - \b "Image Rendering.Transfer Function": Default color transfer function for CTs * - \b "LookupTable": Rainbow color. * If the modality-property is set for an image, the mapper uses modality-specific default properties, * e.g. color maps, if they are defined. * \ingroup Mapper */ class MITKDICOMRT_EXPORT DoseImageVtkMapper2D : public VtkMapper { public: /** Standard class typedefs. */ mitkClassMacro( DoseImageVtkMapper2D,VtkMapper ); /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Get the Image to map */ const mitk::Image *GetInput(void); /** \brief Checks whether this mapper needs to update itself and generate * data. */ void Update(mitk::BaseRenderer * renderer) override; //### methods of MITK-VTK rendering pipeline vtkProp* GetVtkProp(mitk::BaseRenderer* renderer) override; //### end of methods of MITK-VTK rendering pipeline /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ /** * To render transveral, coronal, and sagittal, the mapper is called three times. * For performance reasons, the corresponding data for each view is saved in the * internal helper class LocalStorage. This allows rendering n views with just * 1 mitkMapper using n vtkMapper. * */ class MITKDICOMRT_EXPORT LocalStorage : public mitk::Mapper::BaseLocalStorage { public: /** \brief Actor of a 2D render window. */ vtkSmartPointer m_Actor; vtkSmartPointer m_Actors; /** \brief Mapper of a 2D render window. */ vtkSmartPointer m_Mapper; vtkSmartPointer m_VectorComponentExtractor; /** \brief Current slice of a 2D render window.*/ vtkSmartPointer m_ReslicedImage; /** \brief Empty vtkPolyData that is set when rendering geometry does not * intersect the image geometry. * \warning This member variable is set to nullptr, * if no image geometry is inside the plane geometry * of the respective render window. Any user of this * slice has to check whether it is set to nullptr! */ vtkSmartPointer m_EmptyPolyData; /** \brief Plane on which the slice is rendered as texture. */ vtkSmartPointer m_Plane; /** \brief The texture which is used to render the current slice. */ vtkSmartPointer m_Texture; /** \brief The lookuptables for colors and level window */ vtkSmartPointer m_DefaultLookupTable; vtkSmartPointer m_BinaryLookupTable; vtkSmartPointer m_ColorLookupTable; /** \brief The actual reslicer (one per renderer) */ mitk::ExtractSliceFilter::Pointer m_Reslicer; /** \brief Filter for thick slices */ vtkSmartPointer m_TSFilter; /** \brief PolyData object containg all lines/points needed for outlining the contour. This container is used to save a computed contour for the next rendering execution. For instance, if you zoom or pann, there is no need to recompute the contour. */ vtkSmartPointer m_OutlinePolyData; /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** \brief mmPerPixel relation between pixel and mm. (World spacing).*/ mitk::ScalarType* m_mmPerPixel; /** \brief This filter is used to apply the level window to Grayvalue and RBG(A) images. */ vtkSmartPointer m_LevelWindowFilter; /** \brief Default constructor of the local storage. */ LocalStorage(); /** \brief Default deconstructor of the local storage. */ ~LocalStorage() override; }; /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; /** \brief Get the LocalStorage corresponding to the current renderer. */ LocalStorage* GetLocalStorage(mitk::BaseRenderer* renderer); /** \brief Set the default properties for general image rendering. */ static void SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer = nullptr, bool overwrite = false); /** \brief This method switches between different rendering modes (e.g. use a lookup table or a transfer function). - * Detailed documentation about the modes can be found here: \link mitk::RenderingerModeProperty \endlink + * Detailed documentation about the modes can be found here: \link mitk::RenderingModeProperty \endlink */ void ApplyRenderingMode(mitk::BaseRenderer *renderer); protected: /** \brief Transforms the actor to the actual position in 3D. * \param renderer The current renderer corresponding to the render window. */ void TransformActor(mitk::BaseRenderer* renderer); /** \brief Generates a plane according to the size of the resliced image in milimeters. * * \image html texturedPlane.png * * In VTK a vtkPlaneSource is defined through three points. The origin and two * points defining the axes of the plane (see VTK documentation). The origin is * set to (xMin; yMin; Z), where xMin and yMin are the minimal bounds of the * resliced image in space. Z is relevant for blending and the layer property. * The center of the plane (C) is also the center of the view plane (cf. the image above). * * \note For the standard MITK view with three 2D render windows showing three * different slices, three such planes are generated. All these planes are generated * in the XY-plane (even if they depict a YZ-slice of the volume). * */ void GeneratePlane(mitk::BaseRenderer* renderer, double planeBounds[6]); /** \brief Generates a vtkPolyData object containing the outline of a given binary slice. \param renderer: Pointer to the renderer containing the needed information \note This code is based on code from the iil library. */ vtkSmartPointer CreateOutlinePolyData(mitk::BaseRenderer* renderer); /** Default constructor */ DoseImageVtkMapper2D(); /** Default deconstructor */ ~DoseImageVtkMapper2D() override; /** \brief Does the actual resampling, without rendering the image yet. * All the data is generated inside this method. The vtkProp (or Actor) * is filled with content (i.e. the resliced image). * * After generation, a 4x4 transformation matrix(t) of the current slice is obtained * from the vtkResliceImage object via GetReslicesAxis(). This matrix is * applied to each textured plane (actor->SetUserTransform(t)) to transform everything * to the actual 3D position (cf. the following image). * * \image html cameraPositioning3D.png * */ void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; /** \brief This method uses the vtkCamera clipping range and the layer property * to calcualte the depth of the object (e.g. image or contour). The depth is used * to keep the correct order for the final VTK rendering.*/ float CalculateLayerDepth(mitk::BaseRenderer* renderer); /** \brief This method applies (or modifies) the lookuptable for all types of images. * \warning To use the lookup table, the property 'Lookup Table' must be set and a 'Image Rendering.Mode' * which uses the lookup table must be set. */ void ApplyLookuptable(mitk::BaseRenderer* renderer); /** \brief This method applies a color transfer function. * Internally, a vtkColorTransferFunction is used. This is usefull for coloring continous * images (e.g. float) * \warning To use the color transfer function, the property 'Image Rendering.Transfer Function' must be set and a 'Image Rendering.Mode' which uses the color transfer function must be set. */ void ApplyColorTransferFunction(mitk::BaseRenderer* renderer); /** * @brief ApplyLevelWindow Apply the level window for the given renderer. * \warning To use the level window, the property 'LevelWindow' must be set and a 'Image Rendering.Mode' which uses the level window must be set. * @param renderer Level window for which renderer? */ void ApplyLevelWindow(mitk::BaseRenderer* renderer); /** \brief Set the color of the image/polydata */ void ApplyColor( mitk::BaseRenderer* renderer ); /** \brief Set the opacity of the actor. */ void ApplyOpacity( mitk::BaseRenderer* renderer ); /** * \brief Calculates whether the given rendering geometry intersects the * given SlicedGeometry3D. * * This method checks if the given PlaneGeometry intersects the given * SlicedGeometry3D. It calculates the distance of the PlaneGeometry to all * 8 cornerpoints of the SlicedGeometry3D. If all distances have the same * sign (all positive or all negative) there is no intersection. * If the distances have different sign, there is an intersection. **/ bool RenderingGeometryIntersectsImage( const PlaneGeometry* renderingGeometry, SlicedGeometry3D* imageGeometry ); private: void CreateLevelOutline(mitk::BaseRenderer* renderer, const mitk::IsoDoseLevel* level, float pref, vtkSmartPointer points, vtkSmartPointer lines, vtkSmartPointer colors); }; } // namespace mitk #endif /* MITKDoseImageVtkMapper2D_H_HEADER_INCLUDED_C10E906E */ diff --git a/Modules/ModuleList.cmake b/Modules/ModuleList.cmake index d153e96dad..4daa70f838 100644 --- a/Modules/ModuleList.cmake +++ b/Modules/ModuleList.cmake @@ -1,86 +1,85 @@ # The entries in the mitk_modules list must be # ordered according to their dependencies. set(MITK_MODULES Core CommandLine AppUtil LegacyIO DataTypesExt Annotation LegacyGL AlgorithmsExt MapperExt DICOMReader DICOMReaderServices DICOMQI DICOMTesting SceneSerializationBase PlanarFigure ImageDenoising ImageExtraction SceneSerialization Gizmo GraphAlgorithms Multilabel Chart ImageStatistics ContourModel SurfaceInterpolation Segmentation QtWidgets QtWidgetsExt ImageStatisticsUI SegmentationUI MatchPointRegistration MatchPointRegistrationUI Classification OpenIGTLink IGTBase IGT CameraCalibration OpenCL OpenCVVideoSupport QtOverlays ToFHardware ToFProcessing ToFUI PhotoacousticsHardware PhotoacousticsAlgorithms PhotoacousticsLib US USUI DicomUI Remeshing Python QtPython Persistence OpenIGTLinkUI IGTUI DicomRT RTUI IOExt XNAT TubeGraph BiophotonicsHardware -# TumorInvasionAnalysis BoundingShape RenderWindowManager RenderWindowManagerUI SemanticRelations SemanticRelationsUI CEST BasicImageProcessing ModelFit ModelFitUI Pharmacokinetics PharmacokineticsUI DICOMPM REST RESTService DICOMweb ) if(MITK_ENABLE_PIC_READER) list(APPEND MITK_MODULES IpPicSupportIO) endif() diff --git a/Modules/Multilabel/mitkLabelSetImageVtkMapper2D.h b/Modules/Multilabel/mitkLabelSetImageVtkMapper2D.h index 224ec8c912..676305caf2 100644 --- a/Modules/Multilabel/mitkLabelSetImageVtkMapper2D.h +++ b/Modules/Multilabel/mitkLabelSetImageVtkMapper2D.h @@ -1,241 +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. ============================================================================*/ #ifndef __mitkLabelSetImageVtkMapper2D_H_ #define __mitkLabelSetImageVtkMapper2D_H_ // MITK #include "MitkMultilabelExports.h" #include "mitkCommon.h" // MITK Rendering #include "mitkBaseRenderer.h" #include "mitkExtractSliceFilter.h" #include "mitkLabelSetImage.h" #include "mitkVtkMapper.h" // VTK #include class vtkActor; class vtkPolyDataMapper; class vtkPlaneSource; class vtkImageData; class vtkLookupTable; class vtkImageReslice; class vtkPoints; class vtkMitkThickSlicesFilter; class vtkPolyData; class vtkMitkLevelWindowFilter; class vtkNeverTranslucentTexture; namespace mitk { /** \brief Mapper to resample and display 2D slices of a 3D labelset image. * * Properties that can be set for labelset images and influence this mapper are: * * - \b "labelset.contour.active": (BoolProperty) whether to show only the active label as a contour or not * - \b "labelset.contour.width": (FloatProperty) line width of the contour * The default properties are: * - \b "labelset.contour.active", mitk::BoolProperty::New( true ), renderer, overwrite ) * - \b "labelset.contour.width", mitk::FloatProperty::New( 2.0 ), renderer, overwrite ) * \ingroup Mapper */ class MITKMULTILABEL_EXPORT LabelSetImageVtkMapper2D : public VtkMapper { public: /** Standard class typedefs. */ mitkClassMacro(LabelSetImageVtkMapper2D, VtkMapper); /** Method for creation through the object factory. */ itkNewMacro(Self); /** \brief Get the Image to map */ const mitk::Image *GetInput(void); /** \brief Checks whether this mapper needs to update itself and generate * data. */ void Update(mitk::BaseRenderer *renderer) override; //### methods of MITK-VTK rendering pipeline vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; //### end of methods of MITK-VTK rendering pipeline /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ /** * To render transversal, coronal, and sagittal, the mapper is called three times. * For performance reasons, the corresponding data for each view is saved in the * internal helper class LocalStorage. This allows rendering n views with just * 1 mitkMapper using n vtkMapper. * */ class MITKMULTILABEL_EXPORT LocalStorage : public mitk::Mapper::BaseLocalStorage { public: vtkSmartPointer m_Actors; std::vector> m_LayerActorVector; std::vector> m_LayerMapperVector; std::vector> m_ReslicedImageVector; std::vector> m_LayerTextureVector; vtkSmartPointer m_EmptyPolyData; vtkSmartPointer m_Plane; std::vector m_ReslicerVector; vtkSmartPointer m_OutlinePolyData; /** \brief An actor for the outline */ vtkSmartPointer m_OutlineActor; /** \brief An actor for the outline shadow*/ vtkSmartPointer m_OutlineShadowActor; /** \brief A mapper for the outline */ vtkSmartPointer m_OutlineMapper; /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastDataUpdateTime; /** \brief Timestamp of last update of a property. */ itk::TimeStamp m_LastPropertyUpdateTime; /** \brief mmPerPixel relation between pixel and mm. (World spacing).*/ mitk::ScalarType *m_mmPerPixel; int m_NumberOfLayers; /** \brief This filter is used to apply the level window to Grayvalue and RBG(A) images. */ // vtkSmartPointer m_LevelWindowFilter; std::vector> m_LevelWindowFilterVector; /** \brief Default constructor of the local storage. */ LocalStorage(); /** \brief Default deconstructor of the local storage. */ ~LocalStorage() override; }; /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; /** \brief Get the LocalStorage corresponding to the current renderer. */ LocalStorage *GetLocalStorage(mitk::BaseRenderer *renderer); /** \brief Set the default properties for general image rendering. */ static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); /** \brief This method switches between different rendering modes (e.g. use a lookup table or a transfer function). - * Detailed documentation about the modes can be found here: \link mitk::RenderingerModeProperty \endlink + * Detailed documentation about the modes can be found here: \link mitk::RenderingModeProperty \endlink */ void ApplyRenderingMode(mitk::BaseRenderer *renderer); protected: /** \brief Transforms the actor to the actual position in 3D. * \param renderer The current renderer corresponding to the render window. */ void TransformActor(mitk::BaseRenderer *renderer); /** \brief Generates a plane according to the size of the resliced image in milimeters. * * \image html texturedPlane.png * * In VTK a vtkPlaneSource is defined through three points. The origin and two * points defining the axes of the plane (see VTK documentation). The origin is * set to (xMin; yMin; Z), where xMin and yMin are the minimal bounds of the * resliced image in space. Z is relevant for blending and the layer property. * The center of the plane (C) is also the center of the view plane (cf. the image above). * * \note For the standard MITK view with three 2D render windows showing three * different slices, three such planes are generated. All these planes are generated * in the XY-plane (even if they depict a YZ-slice of the volume). * */ void GeneratePlane(mitk::BaseRenderer *renderer, double planeBounds[6]); /** \brief Generates a vtkPolyData object containing the outline of a given binary slice. \param renderer: Pointer to the renderer containing the needed information \note This code is based on code from the iil library. */ vtkSmartPointer CreateOutlinePolyData(mitk::BaseRenderer *renderer, vtkImageData *image, int pixelValue = 1); /** Default constructor */ LabelSetImageVtkMapper2D(); /** Default deconstructor */ ~LabelSetImageVtkMapper2D() override; /** \brief Does the actual resampling, without rendering the image yet. * All the data is generated inside this method. The vtkProp (or Actor) * is filled with content (i.e. the resliced image). * * After generation, a 4x4 transformation matrix(t) of the current slice is obtained * from the vtkResliceImage object via GetReslicesAxis(). This matrix is * applied to each textured plane (actor->SetUserTransform(t)) to transform everything * to the actual 3D position (cf. the following image). * * \image html cameraPositioning3D.png * */ void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; /** \brief This method uses the vtkCamera clipping range and the layer property * to calcualte the depth of the object (e.g. image or contour). The depth is used * to keep the correct order for the final VTK rendering.*/ float CalculateLayerDepth(mitk::BaseRenderer *renderer); /** \brief This method applies (or modifies) the lookuptable for all types of images. * \warning To use the lookup table, the property 'Lookup Table' must be set and a 'Image Rendering.Mode' * which uses the lookup table must be set. */ void ApplyLookuptable(mitk::BaseRenderer *renderer, int layer); /** \brief This method applies a color transfer function. * Internally, a vtkColorTransferFunction is used. This is usefull for coloring continous * images (e.g. float) * \warning To use the color transfer function, the property 'Image Rendering.Transfer Function' must be set and a * 'Image Rendering.Mode' which uses the color transfer function must be set. */ void ApplyColorTransferFunction(mitk::BaseRenderer *renderer); /** * @brief ApplyLevelWindow Apply the level window for the given renderer. * \warning To use the level window, the property 'LevelWindow' must be set and a 'Image Rendering.Mode' which uses * the level window must be set. * @param renderer Level window for which renderer? */ void ApplyLevelWindow(mitk::BaseRenderer *renderer); /** \brief Set the color of the image/polydata */ void ApplyColor(mitk::BaseRenderer *renderer, const mitk::Color &color); /** \brief Set the opacity of the actor. */ void ApplyOpacity(mitk::BaseRenderer *renderer, int layer); /** * \brief Calculates whether the given rendering geometry intersects the * given SlicedGeometry3D. * * This method checks if the given Geometry2D intersects the given * SlicedGeometry3D. It calculates the distance of the Geometry2D to all * 8 cornerpoints of the SlicedGeometry3D. If all distances have the same * sign (all positive or all negative) there is no intersection. * If the distances have different sign, there is an intersection. **/ bool RenderingGeometryIntersectsImage(const PlaneGeometry *renderingGeometry, SlicedGeometry3D *imageGeometry); }; } // namespace mitk #endif // __mitkLabelSetImageVtkMapper2D_H_ diff --git a/Modules/QtWidgetsExt/include/QmitkFunctionalityComponentContainer.h b/Modules/QtWidgetsExt/include/QmitkFunctionalityComponentContainer.h deleted file mode 100644 index b2aa08832e..0000000000 --- a/Modules/QtWidgetsExt/include/QmitkFunctionalityComponentContainer.h +++ /dev/null @@ -1,180 +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. - -============================================================================*/ - -#ifndef QMITK_FUNCTIONALITYCOMPONENTCONTAINER_H -#define QMITK_FUNCTIONALITYCOMPONENTCONTAINER_H - -#include "MitkQtWidgetsExtExports.h" -#include "QmitkBaseFunctionalityComponent.h" - -#include "ui_QmitkFunctionalityComponentContainerControls.h" -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -/** -* \brief ContainerClass for components -* \ingroup QmitkFunctionalityComponent -* -* -* - \ref QmitkBaseFunctionalityComponent - -* -* \section QmitkFunctionalityComponentContainer Overview -* -* The FunctionalityComponentContainer is a containerclass for several components inherit from it. -* All Components including to one FunctionalityComponentContainer can be used together as one applied -* functionality. I.e. in particular that new functionalities can be combined with different components. -* As common ground for all inherit classes the FunctionalityComponentContainer includes a selector for -* marked data like image(s), segmentation(s) or model(s). -*/ - -class MITKQTWIDGETSEXT_EXPORT QmitkFunctionalityComponentContainer : public QmitkBaseFunctionalityComponent -{ - Q_OBJECT - -public: - /** \brief Standard-Constructor. */ - QmitkFunctionalityComponentContainer(QObject *parent = 0, - const char *parentName = 0, - bool updateSelector = true, - bool showSelector = true); - - /** \brief Destructor. */ - virtual ~QmitkFunctionalityComponentContainer(); - - /*! - \brief Method to create all Signale-Slot-Connections - */ - virtual void CreateConnections(); - - /*! - \brief Method to create the GUI-Object - */ - virtual void CreateQtPartControl(QWidget *parent, mitk::DataStorage::Pointer dataStorage); - - /** \brief Method to create the forward and backward -buttons to navigate through the wizard */ - void CreateNavigationButtons(); - - /** \brief Method to create a textLabel at the Top of the wizard where a description can be created */ - void SetWizardText(const QString &text); - - /** \brief also the Graphical User Interface for the component, like m_GUI, but with its specific type */ - Ui::QmitkFunctionalityComponentContainerGUI *GetFunctionalityComponentContainerGUI(); - - /** \brief Method to set the DataStorage*/ - virtual void SetDataStorage(mitk::DataStorage::Pointer dataStorage); - - /** \brief Method to get the DataStorage*/ - virtual mitk::DataStorage::Pointer GetDataStorage(); - - /** \brief Method to set the Name of the FunctionalityComponent */ - virtual void SetComponentName(QString name); - - /** \brief Method to get the Name of the FunctionalityComponent */ - virtual QString GetComponentName(); - - /** \brief Method to get the GUI of this component.*/ - QWidget *GetGUI(); - - virtual QmitkDataStorageComboBox *GetTreeNodeSelector(); - - /** \brief Method to set the Image Selector visible or invisible */ - virtual void SetSelectorVisibility(bool visibility); - - QmitkStdMultiWidget *GetMultiWidget(); - - /** \brief Method to return the ComboBox that includes all GUI-elements instead of the outermost checkable CheckBox - * and that can be set visible or not*/ - virtual QGroupBox *GetContentContainer(); - - /** \brief Method to return the outermost checkable ComboBox that is to decide whether the content shall be shown or - * not */ - virtual QGroupBox *GetMainCheckBoxContainer(); - - /** \brief Method to set the Tree-Node-Selector visible or not as his parent group-box is set shown or not. */ - virtual void SetShowTreeNodeSelector(bool show); - - /** \brief Method to return the group-box that contains the tree-node-selector */ - virtual QGroupBox *GetImageContent(); - - /** \brief Method to return the Image Selected in the Container Combo Box */ - virtual mitk::Image *GetParentMitkImage(); - - /** \brief Method to return the NextButton to switch to the next widgetStackPage*/ - QPushButton *GetNextButton(); - - /** \brief Method to return the BackButton to switch to the last widgetStackPage*/ - QPushButton *GetBackButton(); - - /** \brief method to add components into this component. */ - virtual void AddComponent(QmitkFunctionalityComponentContainer *componentContainer); - - /** \brief method to add components into this component. */ - virtual void AddComponent(QmitkFunctionalityComponentContainer *componentContainer, QString label, int stackPage); - - virtual void TreeChanged(const itk::EventObject &treeChangedEvent); - - virtual void Activated(); - - virtual void Deactivated(); - - /** \brief Attribute to decide whether the selector shall be updated when a parent-Selector is updatet or not */ - bool m_UpdateSelector; - - /** \brief Attribute to decide whether the selector shall be shown or not */ - bool m_ShowSelector; - - /** \brief Slot method that will be called if TreeNodeSelector widget was activated. */ - void ImageSelected(const mitk::DataNode *item); - -public slots: - - /** \brief Method to set the "GetContentContainer"-visible or not, addicted to the visibility of a parent-component - * and the status of the checkable ComboBox from "GetMainCheckBoxContainer()" */ - virtual void SetContentContainerVisibility(bool); - - virtual void TreeChanged(); - - virtual void DataStorageChanged(mitk::DataStorage::Pointer ds); - -protected: - /** \brief Method to update the content of all DataTreeComboBoxes. */ - virtual void UpdateDataTreeComboBoxes(); - - unsigned long m_ObserverTag; - QWidget *m_GUI; - bool m_Active; - QmitkDataStorageComboBox *m_SelectedItem; - mitk::DataStorage::Pointer m_DataStorage; - -private: - /** \brief also the Graphical User Interface for the component, like m_GUI, but with its specific type */ - Ui::QmitkFunctionalityComponentContainerGUI *m_FunctionalityComponentContainerGUI; - - QObject *m_Parent; - QString m_ComponentName; - QSpacerItem *m_Spacer; - QmitkStdMultiWidget *m_MulitWidget; - QPushButton *m_BackButton; - QPushButton *m_NextButton; - int m_MaximumWidgedStackSize; -}; - -#endif diff --git a/Modules/QtWidgetsExt/src/QmitkFunctionalityComponentContainer.cpp b/Modules/QtWidgetsExt/src/QmitkFunctionalityComponentContainer.cpp deleted file mode 100644 index 9cf43a280b..0000000000 --- a/Modules/QtWidgetsExt/src/QmitkFunctionalityComponentContainer.cpp +++ /dev/null @@ -1,452 +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 "QmitkFunctionalityComponentContainer.h" -#include "ui_QmitkFunctionalityComponentContainerControls.h" - -#include "mitkDataTreeFilterFunctions.h" -#include "mitkProperties.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -const QSizePolicy preferred(QSizePolicy::Preferred, QSizePolicy::Preferred); - -QmitkFunctionalityComponentContainer::QmitkFunctionalityComponentContainer(QObject *parent, - const char *parentName, - bool updateSelector, - bool showSelector) - : QmitkBaseFunctionalityComponent(parent, parentName), - m_UpdateSelector(updateSelector), - m_ShowSelector(showSelector), - m_GUI(nullptr), - m_Active(false), - m_SelectedItem(nullptr), - m_FunctionalityComponentContainerGUI(nullptr), - m_Parent(parent), - m_ComponentName("ComponentContainer"), - m_Spacer(nullptr), - m_BackButton(nullptr), - m_NextButton(nullptr), - m_MaximumWidgedStackSize(-1) -{ - SetAvailability(true); -} - -QmitkFunctionalityComponentContainer::~QmitkFunctionalityComponentContainer() -{ -} - -void QmitkFunctionalityComponentContainer::SetComponentName(QString name) -{ - m_ComponentName = name; -} - -QString QmitkFunctionalityComponentContainer::GetComponentName() -{ - return m_ComponentName; -} - -void QmitkFunctionalityComponentContainer::SetShowTreeNodeSelector(bool show) -{ - GetImageContent()->setShown(show); -} - -QGroupBox *QmitkFunctionalityComponentContainer::GetImageContent() -{ - return (QGroupBox *)m_FunctionalityComponentContainerGUI->m_ImageContent; -} - -QWidget *QmitkFunctionalityComponentContainer::GetGUI() -{ - return m_GUI; -} - -mitk::Image *QmitkFunctionalityComponentContainer::GetParentMitkImage() -{ - return m_ParentMitkImage; -} - -QmitkDataStorageComboBox *QmitkFunctionalityComponentContainer::GetTreeNodeSelector() -{ - if (m_FunctionalityComponentContainerGUI) - { - return m_FunctionalityComponentContainerGUI->m_TreeNodeSelector; - } - else - return nullptr; -} - -QmitkStdMultiWidget *QmitkFunctionalityComponentContainer::GetMultiWidget() -{ - return m_MulitWidget; -} - -void QmitkFunctionalityComponentContainer::TreeChanged(const itk::EventObject &) -{ - if (IsActivated()) - { - TreeChanged(); - } - else - TreeChanged(); -} - -void QmitkFunctionalityComponentContainer::TreeChanged() -{ - UpdateDataTreeComboBoxes(); - - for (unsigned int i = 0; i < m_AddedChildList.size(); i++) - { - m_AddedChildList[i]->TreeChanged(); - } -} - -void QmitkFunctionalityComponentContainer::UpdateDataTreeComboBoxes() -{ -} - -void QmitkFunctionalityComponentContainer::CreateConnections() -{ - if (m_FunctionalityComponentContainerGUI) - { - connect((QObject *)(m_FunctionalityComponentContainerGUI->m_TreeNodeSelector), - SIGNAL(OnSelectionChanged(const mitk::DataNode *)), - (QObject *)this, - SLOT(ImageSelected(const mitk::DataNode *))); - connect((QObject *)(m_FunctionalityComponentContainerGUI->m_ContainerBorder), - SIGNAL(toggled(bool)), - (QObject *)this, - SLOT(SetContentContainerVisibility(bool))); - } -} - -void QmitkFunctionalityComponentContainer::SetDataStorage(mitk::DataStorage::Pointer dataStorage) -{ - m_DataStorage = dataStorage; -} - -mitk::DataStorage::Pointer QmitkFunctionalityComponentContainer::GetDataStorage() -{ - return m_DataStorage; -} - -void QmitkFunctionalityComponentContainer::DataStorageChanged(mitk::DataStorage::Pointer ds) -{ - if (m_FunctionalityComponentContainerGUI != nullptr) - { - for (unsigned int i = 0; i < m_AddedChildList.size(); i++) - { - QmitkBaseFunctionalityComponent *functionalityComponent = - dynamic_cast(m_AddedChildList[i]); - if (functionalityComponent != nullptr) - { - functionalityComponent->DataStorageChanged(ds); - } - } - } - - if (m_FunctionalityComponentContainerGUI) - { - if (!m_FunctionalityComponentContainerGUI->m_TreeNodeSelector) - return; - if (!m_FunctionalityComponentContainerGUI->m_TreeNodeSelector->GetSelectedNode()) - return; - if (!m_FunctionalityComponentContainerGUI->m_TreeNodeSelector->GetSelectedNode()->GetData()) - return; - m_ParentMitkImage = static_cast( - m_FunctionalityComponentContainerGUI->m_TreeNodeSelector->GetSelectedNode()->GetData()); - - if (m_FunctionalityComponentContainerGUI != nullptr) - { - for (unsigned int i = 0; i < m_AddedChildList.size(); i++) - { - QmitkBaseFunctionalityComponent *functionalityComponent = - dynamic_cast(m_AddedChildList[i]); - if (functionalityComponent != nullptr) - { - if (!m_FunctionalityComponentContainerGUI->m_TreeNodeSelector->GetSelectedNode()->GetData()) - return; - functionalityComponent->m_ParentMitkImage = static_cast( - m_FunctionalityComponentContainerGUI->m_TreeNodeSelector->GetSelectedNode()->GetData()); - } - } - } - } -} - -void QmitkFunctionalityComponentContainer::ImageSelected(const mitk::DataNode *item) -{ - if (m_FunctionalityComponentContainerGUI != nullptr) - { - mitk::DataNode::Pointer selectedItem = const_cast(item); - GetTreeNodeSelector()->SetSelectedNode(selectedItem); - - for (unsigned int i = 0; i < m_AddedChildList.size(); i++) - { - QmitkBaseFunctionalityComponent *functionalityComponent = - dynamic_cast(m_AddedChildList[i]); - if (functionalityComponent != nullptr) - functionalityComponent->ImageSelected(item); - } - } - - if (m_FunctionalityComponentContainerGUI) - { - m_ParentMitkImage = static_cast(item->GetData()); - - if (m_FunctionalityComponentContainerGUI != nullptr) - { - for (unsigned int i = 0; i < m_AddedChildList.size(); i++) - { - QmitkBaseFunctionalityComponent *functionalityComponent = - dynamic_cast(m_AddedChildList[i]); - if (functionalityComponent != nullptr) - { - functionalityComponent->m_ParentMitkImage = static_cast(item->GetData()); - } - } - } - } - TreeChanged(); -} - -void QmitkFunctionalityComponentContainer::CreateQtPartControl(QWidget *, mitk::DataStorage::Pointer dataStorage) -{ - if (m_FunctionalityComponentContainerGUI == nullptr) - { - m_GUI = new QWidget; - m_FunctionalityComponentContainerGUI = new Ui::QmitkFunctionalityComponentContainerGUI; - m_FunctionalityComponentContainerGUI->setupUi(m_GUI); - - this->SetDataStorage(dataStorage); - - m_FunctionalityComponentContainerGUI->m_TreeNodeSelector->SetDataStorage(dataStorage); - m_FunctionalityComponentContainerGUI->m_TreeNodeSelector->SetPredicate(mitk::NodePredicateDataType::New("Image")); - - m_FunctionalityComponentContainerGUI->m_WidgetStack->setCurrentIndex(0); - } - this->CreateConnections(); -} - -QGroupBox *QmitkFunctionalityComponentContainer::GetContentContainer() -{ - return m_FunctionalityComponentContainerGUI->m_ImageContent; -} - -QGroupBox *QmitkFunctionalityComponentContainer::GetMainCheckBoxContainer() -{ - return m_FunctionalityComponentContainerGUI->m_ContainerBorder; -} - -void QmitkFunctionalityComponentContainer::SetContentContainerVisibility(bool) -{ - if (GetMainCheckBoxContainer() != nullptr) - { - if (GetMainCheckBoxContainer()->isChecked()) - { - Activated(); - } - else - { - Deactivated(); - } - } - for (unsigned int i = 0; i < m_AddedChildList.size(); i++) - { - if (m_AddedChildList[i]->GetContentContainer() != nullptr) - { - m_AddedChildList[i]->GetContentContainer()->setShown(GetMainCheckBoxContainer()->isChecked()); - } - if (m_AddedChildList[i]->GetMainCheckBoxContainer() != nullptr) - { - m_AddedChildList[i]->GetMainCheckBoxContainer()->setChecked(GetMainCheckBoxContainer()->isChecked()); - } - m_AddedChildList[i]->SetContentContainerVisibility(GetMainCheckBoxContainer()->isChecked()); - } -} - -void QmitkFunctionalityComponentContainer::SetSelectorVisibility(bool visibility) -{ - if (m_GUI) - { - m_FunctionalityComponentContainerGUI->m_ImageContent->setShown(visibility); - } - m_ShowSelector = visibility; -} - -void QmitkFunctionalityComponentContainer::Activated() -{ - TreeChanged(); - QmitkBaseFunctionalityComponent::Activated(); - m_Active = true; - for (unsigned int i = 0; i < m_AddedChildList.size(); i++) - { - m_AddedChildList[i]->Activated(); - } -} - -void QmitkFunctionalityComponentContainer::Deactivated() -{ - QmitkBaseFunctionalityComponent::Deactivated(); - m_Active = false; - for (unsigned int i = 0; i < m_AddedChildList.size(); i++) - { - m_AddedChildList[i]->Deactivated(); - } -} - -void QmitkFunctionalityComponentContainer::AddComponent(QmitkFunctionalityComponentContainer *component) -{ - if (component != nullptr) - { - QWidget *componentWidget = component->CreateControlWidget(m_GUI); - AddComponentListener(component); - m_GUI->layout()->addWidget(componentWidget); - component->CreateConnections(); - if (m_Spacer != nullptr) - { - m_GUI->layout()->removeItem(m_Spacer); - } - QSpacerItem *spacer = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding); - m_Spacer = spacer; - m_GUI->layout()->addItem(m_Spacer); - m_GUI->repaint(); - } -} - -QPushButton *QmitkFunctionalityComponentContainer::GetNextButton() -{ - return m_NextButton; -} - -QPushButton *QmitkFunctionalityComponentContainer::GetBackButton() -{ - return m_BackButton; -} - -void QmitkFunctionalityComponentContainer::AddComponent(QmitkFunctionalityComponentContainer *component, - QString label, - int stackPage) -{ - if (component != nullptr) - { - QWidget *visibleWidget = m_FunctionalityComponentContainerGUI->m_WidgetStack->currentWidget(); - int idVisibleWidget = m_FunctionalityComponentContainerGUI->m_WidgetStack->indexOf(visibleWidget); - if (idVisibleWidget > m_MaximumWidgedStackSize) - { - m_MaximumWidgedStackSize = idVisibleWidget; - } - if (m_MaximumWidgedStackSize < stackPage) - { - QWidget *w = new QWidget(m_FunctionalityComponentContainerGUI->m_WidgetStack); - m_FunctionalityComponentContainerGUI->m_WidgetStack->insertTab(stackPage, w, label); - m_MaximumWidgedStackSize++; - m_FunctionalityComponentContainerGUI->m_WidgetStack->setCurrentIndex(stackPage); - visibleWidget = m_FunctionalityComponentContainerGUI->m_WidgetStack->currentWidget(); - idVisibleWidget = m_FunctionalityComponentContainerGUI->m_WidgetStack->indexOf(visibleWidget); - new QVBoxLayout(visibleWidget); - } - - QLayout *layout; - if (m_FunctionalityComponentContainerGUI->m_WidgetStack->layout() == 0) - { - layout = new QVBoxLayout((QWidget *)(m_FunctionalityComponentContainerGUI->m_WidgetStack)); - } - else - { - layout = m_FunctionalityComponentContainerGUI->m_WidgetStack->layout(); - } - - component->CreateQtPartControl(m_FunctionalityComponentContainerGUI->m_WidgetStack->currentWidget(), - this->m_DataStorage); - QWidget *componentWidget = component->GetGUI(); - AddComponentListener(component); - m_FunctionalityComponentContainerGUI->m_WidgetStack->setCurrentIndex(stackPage); - QWidget *theCurrentWidget = m_FunctionalityComponentContainerGUI->m_WidgetStack->currentWidget(); - QLayout *theCurrentLayout = theCurrentWidget->layout(); - theCurrentLayout->addWidget(componentWidget); - - m_FunctionalityComponentContainerGUI->m_WidgetStack->setShown(true); - m_FunctionalityComponentContainerGUI->m_WidgetStack->updateGeometry(); - m_FunctionalityComponentContainerGUI->m_WidgetStack->layout()->activate(); - componentWidget->setShown(true); - component->CreateConnections(); - - m_GUI->repaint(); - } -} - -void QmitkFunctionalityComponentContainer::CreateNavigationButtons() -{ - QWidget *funcWidget = (QWidget *)m_FunctionalityComponentContainerGUI; - QLayout *functionalityLayout = funcWidget->layout(); - QBoxLayout *buttonLayout = new QHBoxLayout(funcWidget); - if (QBoxLayout *boxLayout = dynamic_cast(functionalityLayout)) - { - boxLayout->addLayout(buttonLayout); - } - if (m_BackButton == nullptr) - { - m_BackButton = new QPushButton("<<", (QWidget *)(m_FunctionalityComponentContainerGUI)); - } - if (m_NextButton == nullptr) - { - m_NextButton = new QPushButton(">>", (QWidget *)(m_FunctionalityComponentContainerGUI)); - } - buttonLayout->addWidget(m_BackButton); - buttonLayout->addWidget(m_NextButton); - m_BackButton->setShown(true); - m_NextButton->setShown(true); - m_GUI->layout()->activate(); - m_GUI->repaint(); - - m_FunctionalityComponentContainerGUI->m_WidgetStack->setCurrentIndex(1); - SetWizardText(""); - GetImageContent()->updateGeometry(); - if (m_Spacer != nullptr) - { - m_GUI->layout()->removeItem(m_Spacer); - } - QSpacerItem *spacer = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding); - m_Spacer = spacer; - m_GUI->layout()->addItem(m_Spacer); - m_GUI->updateGeometry(); - m_GUI->repaint(); -} - -void QmitkFunctionalityComponentContainer::SetWizardText(const QString &) -{ - GetImageContent()->updateGeometry(); - GetImageContent()->repaint(); - m_GUI->updateGeometry(); - m_GUI->layout()->activate(); - m_GUI->repaint(); -} - -Ui::QmitkFunctionalityComponentContainerGUI * - QmitkFunctionalityComponentContainer::GetFunctionalityComponentContainerGUI() -{ - return m_FunctionalityComponentContainerGUI; -} diff --git a/Modules/SceneSerialization/src/mitkSceneReaderV1.cpp b/Modules/SceneSerialization/src/mitkSceneReaderV1.cpp index 2775433865..adc64156f3 100644 --- a/Modules/SceneSerialization/src/mitkSceneReaderV1.cpp +++ b/Modules/SceneSerialization/src/mitkSceneReaderV1.cpp @@ -1,425 +1,421 @@ /*============================================================================ 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 "mitkSceneReaderV1.h" #include "Poco/Path.h" #include "mitkBaseRenderer.h" #include "mitkIOUtil.h" #include "mitkProgressBar.h" #include "mitkPropertyListDeserializer.h" #include "mitkSerializerMacros.h" #include MITK_REGISTER_SERIALIZER(SceneReaderV1) namespace { typedef std::pair> NodesAndParentsPair; bool NodeSortByLayerIsLessThan(const NodesAndParentsPair &left, const NodesAndParentsPair &right) { if (left.first.IsNotNull() && right.first.IsNotNull()) { int leftLayer; int rightLayer; if (left.first->GetIntProperty("layer", leftLayer) && right.first->GetIntProperty("layer", rightLayer)) { return leftLayer < rightLayer; } else { // fall back to name sort return left.first->GetName() < right.first->GetName(); } } // in all other cases, fall back to stupid pointer comparison // this is not reasonable but at least answers the sorting // question clearly return left.first.GetPointer() < right.first.GetPointer(); } } bool mitk::SceneReaderV1::LoadScene(TiXmlDocument &document, const std::string &workingDirectory, DataStorage *storage) { assert(storage); bool error(false); // TODO prepare to detect errors (such as cycles) from wrongly written or edited xml files // Get number of elements to initialze progress bar // 1. if there is a element, // - construct a name for the appropriate serializer // - try to instantiate this serializer via itk object factory // - if serializer could be created, use it to read the file into a BaseData object // - if successful, call the new node's SetData(..) // create a node for the tag "data" and test if node was created typedef std::vector DataNodeVector; DataNodeVector DataNodes; unsigned int listSize = 0; for (TiXmlElement *element = document.FirstChildElement("node"); element != nullptr; element = element->NextSiblingElement("node")) { ++listSize; } ProgressBar::GetInstance()->AddStepsToDo(listSize * 2); for (TiXmlElement *element = document.FirstChildElement("node"); element != nullptr; element = element->NextSiblingElement("node")) { DataNodes.push_back(LoadBaseDataFromDataTag(element->FirstChildElement("data"), workingDirectory, error)); ProgressBar::GetInstance()->Progress(); } // iterate all nodes // first level nodes should be elements auto nit = DataNodes.begin(); for (TiXmlElement *element = document.FirstChildElement("node"); element != nullptr || nit != DataNodes.end(); element = element->NextSiblingElement("node"), ++nit) { mitk::DataNode::Pointer node = *nit; // in case dataXmlElement is valid test whether it containts the "properties" child tag // and process further if and only if yes TiXmlElement *dataXmlElement = element->FirstChildElement("data"); if (dataXmlElement && dataXmlElement->FirstChildElement("properties")) { TiXmlElement *baseDataElement = dataXmlElement->FirstChildElement("properties"); if (node->GetData()) { DecorateBaseDataWithProperties(node->GetData(), baseDataElement, workingDirectory); } else { MITK_WARN << "BaseData properties stored in scene file, but BaseData could not be read" << std::endl; } } // 2. check child nodes const char *uida = element->Attribute("UID"); std::string uid(""); if (uida) { uid = uida; m_NodeForID[uid] = node.GetPointer(); m_IDForNode[node.GetPointer()] = uid; } else { MITK_ERROR << "No UID found for current node. Node will have no parents."; error = true; } // 3. if there are nodes, // - instantiate the appropriate PropertyListDeSerializer // - use them to construct PropertyList objects // - add these properties to the node (if necessary, use renderwindow name) bool success = DecorateNodeWithProperties(node, element, workingDirectory); if (!success) { MITK_ERROR << "Could not load properties for node."; error = true; } // remember node for later adding to DataStorage m_OrderedNodePairs.push_back(std::make_pair(node, std::list())); // 4. if there are elements, remember parent objects for (TiXmlElement *source = element->FirstChildElement("source"); source != nullptr; source = source->NextSiblingElement("source")) { const char *sourceUID = source->Attribute("UID"); if (sourceUID) { m_OrderedNodePairs.back().second.push_back(std::string(sourceUID)); } } ProgressBar::GetInstance()->Progress(); } // end for all // sort our nodes by their "layer" property // (to be inserted in that order) m_OrderedNodePairs.sort(&NodeSortByLayerIsLessThan); // remove all unknown parent UIDs for (auto nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { for (auto parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end();) { if (m_NodeForID.find(*parentsIter) == m_NodeForID.end()) { parentsIter = nodesIter->second.erase(parentsIter); MITK_WARN << "Found a DataNode with unknown parents. Will add it to DataStorage without any parent objects."; error = true; } else { ++parentsIter; } } } // repeat the following loop ... // ... for all created nodes unsigned int lastMapSize(0); while (lastMapSize != m_OrderedNodePairs .size()) // this is to prevent infinite loops; each iteration must at least add one node to DataStorage { lastMapSize = m_OrderedNodePairs.size(); // iterate (layer) ordered nodes backwards // we insert the highest layers first for (auto nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { bool addThisNode(true); // if any parent node is not yet in DataStorage, skip node for now and check later for (auto parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end(); ++parentsIter) { if (!storage->Exists(m_NodeForID[*parentsIter])) { addThisNode = false; break; } } if (addThisNode) { DataStorage::SetOfObjects::Pointer parents = DataStorage::SetOfObjects::New(); for (auto parentsIter = nodesIter->second.begin(); parentsIter != nodesIter->second.end(); ++parentsIter) { parents->push_back(m_NodeForID[*parentsIter]); } // if all parents are found in datastorage (or are unknown), add node to DataStorage storage->Add(nodesIter->first, parents); // remove this node from m_OrderedNodePairs m_OrderedNodePairs.erase(nodesIter); // break this for loop because iterators are probably invalid break; } } } // All nodes that are still in m_OrderedNodePairs at this point are not part of a proper directed graph structure. // We'll add such nodes without any parent information. for (auto nodesIter = m_OrderedNodePairs.begin(); nodesIter != m_OrderedNodePairs.end(); ++nodesIter) { storage->Add(nodesIter->first); MITK_WARN << "Encountered node that is not part of a directed graph structure. Will be added to DataStorage " "without parents."; error = true; } return !error; } mitk::DataNode::Pointer mitk::SceneReaderV1::LoadBaseDataFromDataTag(TiXmlElement *dataElement, const std::string &workingDirectory, bool &error) { DataNode::Pointer node; if (dataElement) { const char *filename = dataElement->Attribute("file"); if (filename && strlen(filename) != 0) { try { std::vector baseData = IOUtil::Load(workingDirectory + Poco::Path::separator() + filename); if (baseData.size() > 1) { MITK_WARN << "Discarding multiple base data results from " << filename << " except the first one."; } node = DataNode::New(); node->SetData(baseData.front()); } catch (std::exception &e) { MITK_ERROR << "Error during attempt to read '" << filename << "'. Exception says: " << e.what(); error = true; } if (node.IsNull()) { MITK_ERROR << "Error during attempt to read '" << filename << "'. Factory returned nullptr object."; error = true; } } } // in case there was no element we create a new empty node (for appending a propertylist later) if (node.IsNull()) { node = DataNode::New(); } return node; } void mitk::SceneReaderV1::ClearNodePropertyListWithExceptions(DataNode &node, PropertyList &propertyList) { // Basically call propertyList.Clear(), but implement exceptions (see bug 19354) BaseData *data = node.GetData(); PropertyList::Pointer propertiesToKeep = PropertyList::New(); if (dynamic_cast(data)) { /* Older scene files (before changes of bug 17547) could contain a RenderingMode property with value "LevelWindow_Color". Since bug 17547 this value has been removed and replaced by the default value LookupTable_LevelWindow_Color. This new default value does only result in "black-to-white" CT images (or others) if there is a corresponding lookup table. Such a lookup table is provided as a default value by the Image mapper. Since that value was never present in older scene files, we do well in not removing the new default value here. Otherwise the mapper would fall back to another default which is all the colors of the rainbow :-( */ BaseProperty::Pointer lutProperty = propertyList.GetProperty("LookupTable"); propertiesToKeep->SetProperty("LookupTable", lutProperty); /* Older scene files (before changes of T14807) may contain multi-component images without the "Image.Displayed Component" property. As the treatment as multi-component image and the corresponding visualization options hinges on that property we should not delete it, if it was added by the mapper. - Old diffusion images might contain the "DisplayChannel" property - which stores the same information, however ignoring it is an acceptable - loss of precision as usually which channel is selected is not terribly - important. This is a fix for the issue reported in T19919. */ BaseProperty::Pointer compProperty = propertyList.GetProperty("Image.Displayed Component"); if (compProperty.IsNotNull()) { propertiesToKeep->SetProperty("Image.Displayed Component", compProperty); } } propertyList.Clear(); propertyList.ConcatenatePropertyList(propertiesToKeep); } bool mitk::SceneReaderV1::DecorateNodeWithProperties(DataNode *node, TiXmlElement *nodeElement, const std::string &workingDirectory) { assert(node); assert(nodeElement); bool error(false); for (TiXmlElement *properties = nodeElement->FirstChildElement("properties"); properties != nullptr; properties = properties->NextSiblingElement("properties")) { const char *propertiesfilea(properties->Attribute("file")); std::string propertiesfile(propertiesfilea ? propertiesfilea : ""); const char *renderwindowa(properties->Attribute("renderwindow")); std::string renderwindow(renderwindowa ? renderwindowa : ""); PropertyList::Pointer propertyList = node->GetPropertyList(renderwindow); // DataNode implementation always returns a propertylist ClearNodePropertyListWithExceptions(*node, *propertyList); // use deserializer to construct new properties PropertyListDeserializer::Pointer deserializer = PropertyListDeserializer::New(); deserializer->SetFilename(workingDirectory + Poco::Path::separator() + propertiesfile); bool success = deserializer->Deserialize(); error |= !success; PropertyList::Pointer readProperties = deserializer->GetOutput(); if (readProperties.IsNotNull()) { propertyList->ConcatenatePropertyList(readProperties, true); // true = replace } else { MITK_ERROR << "Property list reader did not return a property list. This is an implementation error. Please tell " "your developer."; error = true; } } return !error; } bool mitk::SceneReaderV1::DecorateBaseDataWithProperties(BaseData::Pointer data, TiXmlElement *baseDataNodeElem, const std::string &workingDir) { // check given variables, initialize error variable assert(baseDataNodeElem); bool error(false); // get the file name stored in the tag const char *baseDataPropertyFile(baseDataNodeElem->Attribute("file")); // check if the filename was found if (baseDataPropertyFile) { // PropertyList::Pointer dataPropList = data->GetPropertyList(); PropertyListDeserializer::Pointer propertyDeserializer = PropertyListDeserializer::New(); // initialize the property reader propertyDeserializer->SetFilename(workingDir + Poco::Path::separator() + baseDataPropertyFile); bool ioSuccess = propertyDeserializer->Deserialize(); error = !ioSuccess; // get the output PropertyList::Pointer inProperties = propertyDeserializer->GetOutput(); // store the read-in properties to the given node or throw error otherwise if (inProperties.IsNotNull()) { data->SetPropertyList(inProperties); } else { MITK_ERROR << "The property deserializer did not return a (valid) property list."; error = true; } } else { MITK_ERROR << "Function DecorateBaseDataWithProperties(...) called with false TiXmlElement. \n \t ->Given element " "does not contain a 'file' attribute. \n"; error = true; } return !error; } diff --git a/Modules/Segmentation/Algorithms/mitkOverwriteDirectedPlaneImageFilter.h b/Modules/Segmentation/Algorithms/mitkOverwriteDirectedPlaneImageFilter.h index 2b112b0337..c87c74a6dd 100644 --- a/Modules/Segmentation/Algorithms/mitkOverwriteDirectedPlaneImageFilter.h +++ b/Modules/Segmentation/Algorithms/mitkOverwriteDirectedPlaneImageFilter.h @@ -1,120 +1,117 @@ /*============================================================================ 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 mitkOverwriteDirectedPlaneImageFilter_h_Included #define mitkOverwriteDirectedPlaneImageFilter_h_Included #include "mitkCommon.h" #include "mitkImageToImageFilter.h" #include #include namespace mitk { /** \deprecated This class is deprecated. Use mitkVtkImageOverwrite instead. \sa mitkVtkImageOverwrite \brief Writes a 2D slice into a 3D image. \sa SegTool2D \sa ContourTool \sa ExtractImageFilter \ingroup Process \ingroup Reliver - There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref - QmitkInteractiveSegmentationTechnicalPage - This class takes a 3D mitk::Image as input and tries to replace one slice in it with the second input image, which is specified by calling SetSliceImage with a 2D mitk::Image. Two parameters determine which slice is replaced: the "slice dimension" is that one, which is constant for all points in the plane, e.g. axial would mean 2. The "slice index" is the slice index in the image direction you specified with "affected dimension". Indices count from zero. This class works with all kind of image types, the only restrictions being that the input is 3D, and the slice image is 2D. If requested by SetCreateUndoInformation(true), this class will create instances of ApplyDiffImageOperation for the undo stack. These operations will (on user request) be executed by DiffImageApplier to perform undo. Last contributor: $Author: maleike $ */ class MITKSEGMENTATION_EXPORT OverwriteDirectedPlaneImageFilter : public ImageToImageFilter { public: mitkClassMacro(OverwriteDirectedPlaneImageFilter, ImageToImageFilter); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Which plane to overwrite */ const BaseGeometry *GetPlaneGeometry3D() const { return m_PlaneGeometry; } void SetPlaneGeometry3D(const BaseGeometry *geometry) { m_PlaneGeometry = geometry; } /** \brief Time step of the slice to overwrite */ itkSetMacro(TimeStep, unsigned int); itkGetConstMacro(TimeStep, unsigned int); /** \brief Whether to create undo operation in the MITK undo stack */ itkSetMacro(CreateUndoInformation, bool); itkGetConstMacro(CreateUndoInformation, bool); itkSetObjectMacro(SliceImage, Image); const Image *GetSliceImage() { return m_SliceImage.GetPointer(); } const Image *GetLastDifferenceImage() { return m_SliceDifferenceImage.GetPointer(); } protected: OverwriteDirectedPlaneImageFilter(); // purposely hidden ~OverwriteDirectedPlaneImageFilter() override; void GenerateData() override; template void ItkSliceOverwriting(itk::Image *input3D); template void ItkImageSwitch(itk::Image *image); template void ItkImageProcessing(itk::Image *itkImage1, itk::Image *itkImage2); // std::string EventDescription( unsigned int sliceDimension, unsigned int sliceIndex, unsigned int timeStep ); Image::ConstPointer m_SliceImage; Image::Pointer m_SliceDifferenceImage; const BaseGeometry *m_PlaneGeometry; const BaseGeometry *m_ImageGeometry3D; unsigned int m_TimeStep; unsigned int m_Dimension0; unsigned int m_Dimension1; bool m_CreateUndoInformation; }; } // namespace #endif diff --git a/Modules/Segmentation/Algorithms/mitkOverwriteSliceImageFilter.h b/Modules/Segmentation/Algorithms/mitkOverwriteSliceImageFilter.h index bbd80153ad..97db8915ef 100644 --- a/Modules/Segmentation/Algorithms/mitkOverwriteSliceImageFilter.h +++ b/Modules/Segmentation/Algorithms/mitkOverwriteSliceImageFilter.h @@ -1,124 +1,121 @@ /*============================================================================ 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 mitkOverwriteSliceImageFilter_h_Included #define mitkOverwriteSliceImageFilter_h_Included #include "mitkCommon.h" #include "mitkImageToImageFilter.h" #include #include namespace mitk { /** \deprecated This class is deprecated. Use mitkVtkImageOverwrite instead. \sa mitkVtkImageOverwrite \brief Writes a 2D slice into a 3D image. \sa SegTool2D \sa ContourTool \sa ExtractImageFilter \ingroup Process \ingroup ToolManagerEtAl - There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref - QmitkInteractiveSegmentationTechnicalPage - This class takes a 3D mitk::Image as input and tries to replace one slice in it with the second input image, which is specified by calling SetSliceImage with a 2D mitk::Image. Two parameters determine which slice is replaced: the "slice dimension" is that one, which is constant for all points in the plane, e.g. axial would mean 2. The "slice index" is the slice index in the image direction you specified with "affected dimension". Indices count from zero. This class works with all kind of image types, the only restrictions being that the input is 3D, and the slice image is 2D. If requested by SetCreateUndoInformation(true), this class will create instances of ApplyDiffImageOperation for the undo stack. These operations will (on user request) be executed by DiffImageApplier to perform undo. Last contributor: $Author$ */ class MITKSEGMENTATION_EXPORT OverwriteSliceImageFilter : public ImageToImageFilter { public: mitkClassMacro(OverwriteSliceImageFilter, ImageToImageFilter); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Which slice to overwrite (first one has index 0). */ itkSetMacro(SliceIndex, unsigned int); itkGetConstMacro(SliceIndex, unsigned int); /** \brief The orientation of the slice to overwrite. \a Parameter \a SliceDimension Number of the dimension which is constant for all pixels of the desired slices (e.g. 0 for axial) */ itkSetMacro(SliceDimension, unsigned int); itkGetConstMacro(SliceDimension, unsigned int); /** \brief Time step of the slice to overwrite */ itkSetMacro(TimeStep, unsigned int); itkGetConstMacro(TimeStep, unsigned int); /** \brief Whether to create undo operation in the MITK undo stack */ itkSetMacro(CreateUndoInformation, bool); itkGetConstMacro(CreateUndoInformation, bool); itkSetObjectMacro(SliceImage, Image); const Image *GetSliceImage() { return m_SliceImage.GetPointer(); } const Image *GetLastDifferenceImage() { return m_SliceDifferenceImage.GetPointer(); } protected: OverwriteSliceImageFilter(); // purposely hidden ~OverwriteSliceImageFilter() override; void GenerateData() override; template void ItkImageSwitch(itk::Image *image); template void ItkImageProcessing(const itk::Image *itkImage1, itk::Image *itkImage2); std::string EventDescription(unsigned int sliceDimension, unsigned int sliceIndex, unsigned int timeStep); Image::ConstPointer m_SliceImage; Image::Pointer m_SliceDifferenceImage; unsigned int m_SliceIndex; unsigned int m_SliceDimension; unsigned int m_TimeStep; unsigned int m_Dimension0; unsigned int m_Dimension1; bool m_CreateUndoInformation; }; } // namespace #endif diff --git a/Modules/Segmentation/Controllers/mitkSegmentationInterpolationController.h b/Modules/Segmentation/Controllers/mitkSegmentationInterpolationController.h index fe5c96c85f..53673f57e1 100644 --- a/Modules/Segmentation/Controllers/mitkSegmentationInterpolationController.h +++ b/Modules/Segmentation/Controllers/mitkSegmentationInterpolationController.h @@ -1,223 +1,220 @@ /*============================================================================ 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 mitkSegmentationInterpolationController_h_Included #define mitkSegmentationInterpolationController_h_Included #include "mitkCommon.h" #include "mitkImage.h" #include #include #include #include #include namespace mitk { class Image; /** \brief Generates interpolations of 2D slices. \sa QmitkSlicesInterpolator \sa QmitkInteractiveSegmentation \ingroup ToolManagerEtAl - There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref - QmitkInteractiveSegmentationTechnicalPage - This class keeps track of the contents of a 3D segmentation image. \attention mitk::SegmentationInterpolationController assumes that the image contains pixel values of 0 and 1. After you set the segmentation image using SetSegmentationVolume(), the whole image is scanned for pixels other than 0. SegmentationInterpolationController registers as an observer to the segmentation image, and repeats the scan whenvever the image is modified. You can prevent this (time consuming) scan if you do the changes slice-wise and send difference images to SegmentationInterpolationController. For this purpose SetChangedSlice() should be used. mitk::OverwriteImageFilter already does this every time it changes a slice of an image. There is a static method InterpolatorForImage(), which can be used to find out if there already is an interpolator instance for a specified image. OverwriteImageFilter uses this to get to know its interpolator. SegmentationInterpolationController needs to maintain some information about the image slices (in every dimension). This information is stored internally in m_SegmentationCountInSlice, which is basically three std::vectors (one for each dimension). Each item describes one image dimension, each vector item holds the count of pixels in "its" slice. This is perhaps better to understand from the following picture (where red items just mean to symbolize "there is some segmentation" - in reality there is an integer count). \image html slice_based_segmentation_interpolator.png $Author$ */ class MITKSEGMENTATION_EXPORT SegmentationInterpolationController : public itk::Object { public: mitkClassMacroItkParent(SegmentationInterpolationController, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Find interpolator for a given image. \return nullptr if there is no interpolator yet. This method is useful if several "clients" modify the same image and want to access the interpolations. Then they can share the same object. */ static SegmentationInterpolationController *InterpolatorForImage(const Image *); /** \brief Block reaction to an images Modified() events. Blocking the scan of the whole image is especially useful when you are about to change a single slice of the image. Then you would send a difference image of this single slice to SegmentationInterpolationController but call image->Modified() anyway. Before calling image->Modified() you should block SegmentationInterpolationController's reactions to this modified by using this method. */ void BlockModified(bool); /** \brief Initialize with a whole volume. Will scan the volume for segmentation pixels (values other than 0) and fill some internal data structures. You don't have to call this method every time something changes, but only when several slices at once change. When you change a single slice, call SetChangedSlice() instead. */ void SetSegmentationVolume(const Image *segmentation); /** \brief Set a reference image (original patient image) - optional. If this volume is set (must exactly match the dimensions of the segmentation), the interpolation algorithm may consider image content to improve the interpolated (estimated) segmentation. */ void SetReferenceVolume(const Image *segmentation); /** \brief Update after changing a single slice. \param sliceDiff is a 2D image with the difference image of the slice determined by sliceDimension and sliceIndex. The difference is (pixel value in the new slice minus pixel value in the old slice). \param sliceDimension Number of the dimension which is constant for all pixels of the meant slice. \param sliceIndex Which slice to take, in the direction specified by sliceDimension. Count starts from 0. \param timeStep Which time step is changed */ void SetChangedSlice(const Image *sliceDiff, unsigned int sliceDimension, unsigned int sliceIndex, unsigned int timeStep); void SetChangedVolume(const Image *sliceDiff, unsigned int timeStep); /** \brief Generates an interpolated image for the given slice. \param sliceDimension Number of the dimension which is constant for all pixels of the meant slice. \param sliceIndex Which slice to take, in the direction specified by sliceDimension. Count starts from 0. \param timeStep Which time step to use */ Image::Pointer Interpolate(unsigned int sliceDimension, unsigned int sliceIndex, const mitk::PlaneGeometry *currentPlane, unsigned int timeStep); void OnImageModified(const itk::EventObject &); /** * Activate/Deactivate the 2D interpolation. */ void Activate2DInterpolation(bool); /** \brief Get existing instance or create a new one */ static SegmentationInterpolationController *GetInstance(); protected: /** \brief Protected class of mitk::SegmentationInterpolationController. Don't use (you shouldn't be able to do so)! */ class MITKSEGMENTATION_EXPORT SetChangedSliceOptions { public: SetChangedSliceOptions( unsigned int sd, unsigned int si, unsigned int d0, unsigned int d1, unsigned int t, const void *pixels) : sliceDimension(sd), sliceIndex(si), dim0(d0), dim1(d1), timeStep(t), pixelData(pixels) { } unsigned int sliceDimension; unsigned int sliceIndex; unsigned int dim0; unsigned int dim1; unsigned int timeStep; const void *pixelData; }; typedef std::vector DirtyVectorType; // typedef std::vector< DirtyVectorType[3] > TimeResolvedDirtyVectorType; // cannot work with C++, so next line is // used for implementation typedef std::vector> TimeResolvedDirtyVectorType; typedef std::map InterpolatorMapType; SegmentationInterpolationController(); // purposely hidden ~SegmentationInterpolationController() override; /// internal scan of a single slice template void ScanChangedSlice(const itk::Image *, const SetChangedSliceOptions &options); template void ScanChangedVolume(const itk::Image *, unsigned int timeStep); template void ScanWholeVolume(const itk::Image *, const Image *volume, unsigned int timeStep); void PrintStatus(); /** An array of flags. One for each dimension of the image. A flag is set, when a slice in a certain dimension has at least one pixel that is not 0 (which would mean that it has to be considered by the interpolation algorithm). E.g. flags for axial slices are stored in m_SegmentationCountInSlice[0][index]. Enhanced with time steps it is now m_SegmentationCountInSlice[timeStep][0][index] */ TimeResolvedDirtyVectorType m_SegmentationCountInSlice; static InterpolatorMapType s_InterpolatorForImage; Image::ConstPointer m_Segmentation; Image::ConstPointer m_ReferenceImage; bool m_BlockModified; bool m_2DInterpolationActivated; }; } // namespace #endif diff --git a/Modules/Segmentation/Controllers/mitkSliceBasedInterpolationController.h b/Modules/Segmentation/Controllers/mitkSliceBasedInterpolationController.h index ba89047e97..4f8996d593 100644 --- a/Modules/Segmentation/Controllers/mitkSliceBasedInterpolationController.h +++ b/Modules/Segmentation/Controllers/mitkSliceBasedInterpolationController.h @@ -1,203 +1,200 @@ /*============================================================================ 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 mitkSliceBasedInterpolationController_h_Included #define mitkSliceBasedInterpolationController_h_Included #include "mitkLabelSetImage.h" #include #include #include #include #include namespace mitk { class Image; /** \brief Generates interpolations of 2D slices. \sa QmitkSlicesInterpolator \sa QmitkInteractiveSegmentation \ingroup ToolManagerEtAl - There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref - QmitkInteractiveSegmentationTechnicalPage - This class keeps track of the contents of a 3D segmentation image. \attention mitk::SliceBasedInterpolationController assumes that the image contains pixel values of 0 and 1. After you set the segmentation image using SetSegmentationVolume(), the whole image is scanned for pixels other than 0. SliceBasedInterpolationController registers as an observer to the segmentation image, and repeats the scan whenvever the image is modified. You can prevent this (time consuming) scan if you do the changes slice-wise and send difference images to SliceBasedInterpolationController. For this purpose SetChangedSlice() should be used. mitk::OverwriteImageFilter already does this every time it changes a slice of an image. There is a static method InterpolatorForImage(), which can be used to find out if there already is an interpolator instance for a specified image. OverwriteImageFilter uses this to get to know its interpolator. SliceBasedInterpolationController needs to maintain some information about the image slices (in every dimension). This information is stored internally in m_SegmentationCountInSlice, which is basically three std::vectors (one for each dimension). Each item describes one image dimension, each vector item holds the count of pixels in "its" slice. This is perhaps better to understand from the following picture (where red items just mean to symbolize "there is some segmentation" - in reality there is an integer count). \image html slice_based_segmentation_interpolator.png $Author$ */ class MITKSEGMENTATION_EXPORT SliceBasedInterpolationController : public itk::Object { public: mitkClassMacroItkParent(SliceBasedInterpolationController, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** \brief Find interpolator for a given image. \return nullptr if there is no interpolator yet. This method is useful if several "clients" modify the same image and want to access the interpolations. Then they can share the same object. */ static SliceBasedInterpolationController *InterpolatorForImage(const Image *); /** \brief Initialize with a whole volume. Will scan the volume for segmentation pixels (values other than 0) and fill some internal data structures. You don't have to call this method every time something changes, but only when several slices at once change. When you change a single slice, call SetChangedSlice() instead. */ void SetWorkingImage(LabelSetImage *image); /** \brief Set a reference image (original patient image) - optional. If this image is set (must exactly match the dimensions of the segmentation), the interpolation algorithm may consider image content to improve the interpolated (estimated) segmentation. */ void SetReferenceImage(Image *image); /** \brief Update after changing a single slice in the working image. \param image is a 2D image with the difference image of the slice determined by sliceDimension and sliceIndex. The difference is (pixel value in the new slice minus pixel value in the old slice). \param sliceDimension Number of the dimension which is constant for all pixels of the meant slice. \param sliceIndex Which slice to take, in the direction specified by sliceDimension. Count starts from 0. \param timeStep Which time step is changed */ void SetChangedSlice(const Image *image, unsigned int sliceDimension, unsigned int sliceIndex, unsigned int timeStep); /** \brief Update after changing the whole working image. \param image is a 3D image with the difference image of the slice determined by sliceDimension and sliceIndex. The difference is (pixel value in the new slice minus pixel value in the old slice). \param timeStep Which time step is changed */ // void SetChangedImage( const Image* image, unsigned int timeStep ); /** \brief Generates an interpolated image for the given slice. \param sliceDimension Number of the dimension which is constant for all pixels of the meant slice. \param sliceIndex Which slice to take, in the direction specified by sliceDimension. Count starts from 0. \param timeStep Which time step to use */ Image::Pointer Interpolate(unsigned int sliceDimension, unsigned int sliceIndex, const mitk::PlaneGeometry *currentPlane, unsigned int timeStep); /** \brief Initializes the internal container with the number of voxels per label. */ void ResetLabelCount(); protected: /** \brief Protected class of mitk::SliceBasedInterpolationController. Don't use (you shouldn't be able to do so)! */ class MITKSEGMENTATION_EXPORT SetChangedSliceOptions { public: SetChangedSliceOptions(unsigned int sd, unsigned int si, unsigned int d0, unsigned int d1, unsigned int t) : sliceDimension(sd), sliceIndex(si), dim0(d0), dim1(d1), timeStep(t) { } unsigned int sliceDimension; unsigned int sliceIndex; unsigned int dim0; unsigned int dim1; unsigned int timeStep; // void* pixelData; }; typedef std::vector LabelCounterVectorType; typedef std::vector LabelCounterSliceVectorType; typedef std::vector> LabelCounterSliceTimeVectorType; typedef std::map InterpolatorMapType; SliceBasedInterpolationController(); // purposely hidden ~SliceBasedInterpolationController() override; /// internal scan of a single slice template void ScanSliceITKProcessing(const itk::Image *, const SetChangedSliceOptions &options); /// internal scan of the whole image template void ScanImageITKProcessing(itk::Image *, unsigned int timeStep); /** An array that of flags. One for each dimension of the image. A flag is set, when a slice in a certain dimension has at least one pixel that is not 0 (which would mean that it has to be considered by the interpolation algorithm). E.g. flags for axial slices are stored in m_SegmentationCountInSlice[0][index]. Enhanced with time steps it is now m_SegmentationCountInSlice[timeStep][0][index] */ LabelCounterSliceTimeVectorType m_LabelCountInSlice; static InterpolatorMapType s_InterpolatorForImage; LabelSetImage::Pointer m_WorkingImage; Image::Pointer m_ReferenceImage; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkTool.h b/Modules/Segmentation/Interactions/mitkTool.h index 9313eb1c7e..e9110e2a7a 100644 --- a/Modules/Segmentation/Interactions/mitkTool.h +++ b/Modules/Segmentation/Interactions/mitkTool.h @@ -1,267 +1,265 @@ /*============================================================================ 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 mitkTool_h_Included #define mitkTool_h_Included #include "itkObjectFactoryBase.h" #include "itkVersion.h" #include "mitkCommon.h" #include "mitkDataNode.h" #include "mitkEventStateMachine.h" #include "mitkInteractionEventObserver.h" #include "mitkLabelSetImage.h" #include "mitkMessage.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateDimension.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateOr.h" #include "mitkNodePredicateProperty.h" #include "mitkToolEvents.h" #include "mitkToolFactoryMacro.h" #include #include #include #include #include #include #include "usServiceRegistration.h" namespace us { class ModuleResource; } namespace mitk { class ToolManager; /** \brief Base class of all tools used by mitk::ToolManager. \sa ToolManager \sa SegTool2D \ingroup Interaction \ingroup ToolManagerEtAl - There is a separate page describing the \ref QmitkInteractiveSegmentationTechnicalPage. - Every tool is a mitk::StateMachine, which can follow any transition pattern that it likes. One important thing to know is, that every derived tool should always call SuperClass::Deactivated() at the end of its own implementation of Deactivated, because mitk::Tool resets the StateMachine in this method. Only if you are very sure that you covered all possible things that might happen to your own tool, you should consider not to reset the StateMachine from time to time. To learn about the MITK implementation of state machines in general, have a look at \ref InteractionPage. To derive a non-abstract tool, you inherit from mitk::Tool (or some other base class further down the inheritance tree), and in your own parameterless constructor (that is called from the itkFactorylessNewMacro that you use) you pass a StateMachine pattern name to the superclass. Names for valid patterns can be found in StateMachine.xml (which might be enhanced by you). You have to implement at least GetXPM() and GetName() to provide some identification. Each Tool knows its ToolManager, which can provide the data that the tool should work on. \warning Only to be instantiated by mitk::ToolManager (because SetToolManager has to be called). All other uses are unsupported. $Author$ */ class MITKSEGMENTATION_EXPORT Tool : public EventStateMachine, public InteractionEventObserver { public: typedef mitk::Label::PixelType DefaultSegmentationDataType; /** * \brief To let GUI process new events (e.g. qApp->processEvents() ) */ Message<> GUIProcessEventsMessage; /** * \brief To send error messages (to be shown by some GUI) */ Message1 ErrorMessage; /** * \brief To send whether the tool is busy (to be shown by some GUI) */ Message1 CurrentlyBusy; /** * \brief To send general messages (to be shown by some GUI) */ Message1 GeneralMessage; mitkClassMacro(Tool, EventStateMachine); // no New(), there should only be subclasses /** \brief Returns an icon in the XPM format. This icon has to fit into some kind of button in most applications, so make it smaller than 25x25 pixels. XPM is e.g. supported by The Gimp. But if you open any XPM file in your text editor, you will see that you could also "draw" it with an editor. */ virtual const char **GetXPM() const = 0; /** * \brief Returns the path of an icon. * * This icon is preferred to the XPM icon. */ virtual std::string GetIconPath() const { return ""; } /** * \brief Returns the path of a cursor icon. * */ virtual us::ModuleResource GetCursorIconResource() const; /** * @brief Returns the tool button icon of the tool wrapped by a usModuleResource * @return a valid ModuleResource or an invalid if this function * is not reimplemented */ virtual us::ModuleResource GetIconResource() const; /** \brief Returns the name of this tool. Make it short! This name has to fit into some kind of button in most applications, so take some time to think of a good name! */ virtual const char *GetName() const = 0; /** \brief Name of a group. You can group several tools by assigning a group name. Graphical tool selectors might use this information to group tools. (What other reason could there be?) */ virtual const char *GetGroup() const; virtual void InitializeStateMachine(); /** * \brief Interface for GUI creation. * * This is the basic interface for creation of a GUI object belonging to one tool. * * Tools that support a GUI (e.g. for display/editing of parameters) should follow some rules: * * - A Tool and its GUI are two separate classes * - There may be several instances of a GUI at the same time. * - mitk::Tool is toolkit (Qt, wxWidgets, etc.) independent, the GUI part is of course dependent * - The GUI part inherits both from itk::Object and some GUI toolkit class * - The GUI class name HAS to be constructed like "toolkitPrefix" tool->GetClassName() + "toolkitPostfix", e.g. * MyTool -> wxMyToolGUI * - For each supported toolkit there is a base class for tool GUIs, which contains some convenience methods * - Tools notify the GUI about changes using ITK events. The GUI must observe interesting events. * - The GUI base class may convert all ITK events to the GUI toolkit's favoured messaging system (Qt -> signals) * - Calling methods of a tool by its GUI is done directly. * In some cases GUIs don't want to be notified by the tool when they cause a change in a tool. * There is a macro CALL_WITHOUT_NOTICE(method()), which will temporarily disable all notifications during a * method call. */ virtual itk::Object::Pointer GetGUI(const std::string &toolkitPrefix, const std::string &toolkitPostfix); virtual NodePredicateBase::ConstPointer GetReferenceDataPreference() const; virtual NodePredicateBase::ConstPointer GetWorkingDataPreference() const; DataNode::Pointer CreateEmptySegmentationNode(const Image *original, const std::string &organName, const mitk::Color &color); DataNode::Pointer CreateSegmentationNode(Image *image, const std::string &organName, const mitk::Color &color); virtual bool CanHandle(BaseData *referenceData) const; protected: friend class ToolManager; virtual void SetToolManager(ToolManager *); void ConnectActionsAndFunctions() override; /** \brief Called when the tool gets activated. Derived tools should call their parents implementation at the beginning of the overriding function. */ virtual void Activated(); /** \brief Called when the tool gets deactivated. Derived tools should call their parents implementation at the end of the overriding function. */ virtual void Deactivated(); /** \brief Let subclasses change their event configuration. */ std::string m_EventConfig; Tool(); // purposely hidden Tool(const char *, const us::Module *interactorModule = nullptr); // purposely hidden ~Tool() override; void Notify(InteractionEvent *interactionEvent, bool isHandled) override; bool FilterEvents(InteractionEvent *, DataNode *) override; ToolManager *m_ToolManager; private: // for reference data NodePredicateDataType::Pointer m_PredicateImages; NodePredicateDimension::Pointer m_PredicateDim3; NodePredicateDimension::Pointer m_PredicateDim4; NodePredicateOr::Pointer m_PredicateDimension; NodePredicateAnd::Pointer m_PredicateImage3D; NodePredicateProperty::Pointer m_PredicateBinary; NodePredicateNot::Pointer m_PredicateNotBinary; NodePredicateProperty::Pointer m_PredicateSegmentation; NodePredicateNot::Pointer m_PredicateNotSegmentation; NodePredicateProperty::Pointer m_PredicateHelper; NodePredicateNot::Pointer m_PredicateNotHelper; NodePredicateAnd::Pointer m_PredicateImageColorful; NodePredicateAnd::Pointer m_PredicateImageColorfulNotHelper; NodePredicateAnd::Pointer m_PredicateReference; // for working data NodePredicateAnd::Pointer m_IsSegmentationPredicate; std::string m_InteractorType; std::map m_DisplayInteractorConfigs; const us::Module *m_InteractorModule; }; } // namespace #endif diff --git a/Modules/SegmentationUI/Qmitk/QmitkSliceBasedInterpolatorWidget.h b/Modules/SegmentationUI/Qmitk/QmitkSliceBasedInterpolatorWidget.h index e0716789e1..af03e3829e 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkSliceBasedInterpolatorWidget.h +++ b/Modules/SegmentationUI/Qmitk/QmitkSliceBasedInterpolatorWidget.h @@ -1,198 +1,195 @@ /*============================================================================ 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 QmitkSliceBasedInterpolatorWidget_h_Included #define QmitkSliceBasedInterpolatorWidget_h_Included #include "MitkSegmentationUIExports.h" #include "mitkDataStorage.h" #include "mitkSliceBasedInterpolationController.h" #include #include #include "ui_QmitkSliceBasedInterpolatorWidgetGUIControls.h" namespace mitk { class PlaneGeometry; class SliceNavigationController; class LabelSetImage; class ToolManager; class DiffSliceOperation; } /** \brief GUI for slices interpolation. \ingroup ToolManagerEtAl \ingroup Widgets \sa QmitkInteractiveSegmentation \sa mitk::SegmentationInterpolation - There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref - QmitkInteractiveSegmentationTechnicalPage - While mitk::SegmentationInterpolation does the bookkeeping of interpolation (keeping track of which slices contain how much segmentation) and the algorithmic work, QmitkSliceBasedInterpolatorWidget is responsible to watch the GUI, to notice, which slice is currently visible. It triggers generation of interpolation suggestions and also triggers acception of suggestions. \todo show/hide feedback on demand Last contributor: $Author: maleike $ */ class MITKSEGMENTATIONUI_EXPORT QmitkSliceBasedInterpolatorWidget : public QWidget { Q_OBJECT public: QmitkSliceBasedInterpolatorWidget(QWidget *parent = nullptr, const char *name = nullptr); ~QmitkSliceBasedInterpolatorWidget() override; void SetDataStorage(mitk::DataStorage &storage); /** Sets the slice navigation controllers for getting slice changed events from the views. */ void SetSliceNavigationControllers(const QList &controllers); void OnToolManagerWorkingDataModified(); void OnTimeChanged(itk::Object *sender, const itk::EventObject &); void OnSliceChanged(itk::Object *sender, const itk::EventObject &); void OnSliceNavigationControllerDeleted(const itk::Object *sender, const itk::EventObject &); /** Just public because it is called by itk::Commands. You should not need to call this. */ void OnSliceInterpolationInfoChanged(const itk::EventObject &); Ui::QmitkSliceBasedInterpolatorWidgetGUIControls m_Controls; signals: void signalSliceBasedInterpolationEnabled(bool); public slots: /** \brief Reaction to "Start/Stop" button click */ void OnToggleWidgetActivation(bool); protected slots: /** \brief Reaction to "Accept Current Slice" button click. */ void OnAcceptInterpolationClicked(); /* \brief Reaction to "Accept All Slices" button click. Opens popup to ask about which orientation should be interpolated */ void OnAcceptAllInterpolationsClicked(); /* \brief Called from popup menu of OnAcceptAllInterpolationsClicked() Will trigger interpolation for all slices in given orientation */ void OnAcceptAllPopupActivated(QAction *action); protected: typedef std::map ActionToSliceDimensionMapType; const ActionToSliceDimensionMapType CreateActionToSliceDimension(); ActionToSliceDimensionMapType m_ActionToSliceDimensionMap; void AcceptAllInterpolations(mitk::SliceNavigationController *slicer); void WaitCursorOn(); void WaitCursorOff(); void RestoreOverrideCursor(); /** Gets the working slice based on the given plane geometry and last saved interaction \param planeGeometry a plane geometry */ mitk::Image::Pointer GetWorkingSlice(const mitk::PlaneGeometry *planeGeometry); /** Retrieves the currently selected PlaneGeometry from a SlicedGeometry3D that is generated by a SliceNavigationController and calls Interpolate to further process this PlaneGeometry into an interpolation. \param e is a actually a mitk::SliceNavigationController::GeometrySliceEvent, sent by a SliceNavigationController \param slice the SliceNavigationController */ void TranslateAndInterpolateChangedSlice(const itk::EventObject &e, mitk::SliceNavigationController *slicer); /** Given a PlaneGeometry, this method figures out which slice of the first working image (of the associated ToolManager) should be interpolated. The actual work is then done by our SegmentationInterpolation object. */ void Interpolate(mitk::PlaneGeometry *plane, unsigned int timeStep, mitk::SliceNavigationController *slicer); /** Called internally to update the interpolation suggestion. Finds out about the focused render window and requests an interpolation. */ void UpdateVisibleSuggestion(); private: mitk::SliceBasedInterpolationController::Pointer m_SliceInterpolatorController; mitk::ToolManager *m_ToolManager; bool m_Activated; template void WritePreviewOnWorkingImage(itk::Image *target, const mitk::Image *source, int overwritevalue); QHash m_ControllerToTimeObserverTag; QHash m_ControllerToSliceObserverTag; QHash m_ControllerToDeleteObserverTag; unsigned int m_InterpolationInfoChangedObserverTag; mitk::DiffSliceOperation *m_doOperation; mitk::DiffSliceOperation *m_undoOperation; mitk::DataNode::Pointer m_PreviewNode; mitk::Image::Pointer m_PreviewImage; mitk::LabelSetImage::Pointer m_WorkingImage; QHash m_TimeStep; mitk::DataStorage::Pointer m_DataStorage; mitk::SliceNavigationController *m_LastSNC; unsigned int m_LastSliceIndex; }; #endif diff --git a/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.h b/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.h index 9e66e70157..ce6c55bae2 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.h +++ b/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.h @@ -1,294 +1,291 @@ /*============================================================================ 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 QmitkSlicesInterpolator_h_Included #define QmitkSlicesInterpolator_h_Included #include "mitkDataNode.h" #include "mitkDataStorage.h" #include "mitkSegmentationInterpolationController.h" #include "mitkSliceNavigationController.h" #include "mitkSurfaceInterpolationController.h" #include "mitkToolManager.h" #include #include "mitkFeatureBasedEdgeDetectionFilter.h" #include "mitkPointCloudScoringFilter.h" #include #include #include #include #include #include #include #include "mitkVtkRepresentationProperty.h" #include "vtkProperty.h" // For running 3D interpolation in background #include #include #include #include namespace mitk { class PlaneGeometry; class SliceNavigationController; } class QPushButton; /** \brief GUI for slices interpolation. \ingroup ToolManagerEtAl \ingroup Widgets \sa QmitkInteractiveSegmentation \sa mitk::SegmentationInterpolation - There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref - QmitkInteractiveSegmentationTechnicalPage - While mitk::SegmentationInterpolation does the bookkeeping of interpolation (keeping track of which slices contain how much segmentation) and the algorithmic work, QmitkSlicesInterpolator is responsible to watch the GUI, to notice, which slice is currently visible. It triggers generation of interpolation suggestions and also triggers acception of suggestions. \todo show/hide feedback on demand Last contributor: $Author: maleike $ */ class MITKSEGMENTATIONUI_EXPORT QmitkSlicesInterpolator : public QWidget { Q_OBJECT public: QmitkSlicesInterpolator(QWidget *parent = nullptr, const char *name = nullptr); /** To be called once before real use. */ void Initialize(mitk::ToolManager *toolManager, const QList &controllers); void Uninitialize(); ~QmitkSlicesInterpolator() override; void SetDataStorage(mitk::DataStorage::Pointer storage); mitk::DataStorage *GetDataStorage(); /** Just public because it is called by itk::Commands. You should not need to call this. */ void OnToolManagerWorkingDataModified(); /** Just public because it is called by itk::Commands. You should not need to call this. */ void OnToolManagerReferenceDataModified(); void OnTimeChanged(itk::Object *sender, const itk::EventObject &); void OnSliceChanged(itk::Object *sender, const itk::EventObject &); void OnSliceNavigationControllerDeleted(const itk::Object *sender, const itk::EventObject &); /** Just public because it is called by itk::Commands. You should not need to call this. */ void OnInterpolationInfoChanged(const itk::EventObject &); /** Just public because it is called by itk::Commands. You should not need to call this. */ void OnSurfaceInterpolationInfoChanged(const itk::EventObject &); /** * @brief Set the visibility of the 3d interpolation */ void Show3DInterpolationResult(bool); signals: void SignalRememberContourPositions(bool); void SignalShowMarkerNodes(bool); public slots: virtual void setEnabled(bool); /** Call this from the outside to enable/disable interpolation */ void EnableInterpolation(bool); void Enable3DInterpolation(bool); /** Call this from the outside to accept all interpolations */ void FinishInterpolation(mitk::SliceNavigationController *slicer = nullptr); protected slots: /** Reaction to button clicks. */ void OnAcceptInterpolationClicked(); /* Opens popup to ask about which orientation should be interpolated */ void OnAcceptAllInterpolationsClicked(); /* Reaction to button clicks */ void OnAccept3DInterpolationClicked(); void OnReinit3DInterpolation(); void OnSuggestPlaneClicked(); /* * Will trigger interpolation for all slices in given orientation (called from popup menu of * OnAcceptAllInterpolationsClicked) */ void OnAcceptAllPopupActivated(QAction *action); /** Called on activation/deactivation */ void OnInterpolationActivated(bool); void On3DInterpolationActivated(bool); void OnInterpolationMethodChanged(int index); // Enhancement for 3D interpolation void On2DInterpolationEnabled(bool); void On3DInterpolationEnabled(bool); void OnInterpolationDisabled(bool); void OnShowMarkers(bool); void Run3DInterpolation(); void RunPlaneSuggestion(); void OnSurfaceInterpolationFinished(); void StartUpdateInterpolationTimer(); void StopUpdateInterpolationTimer(); void ChangeSurfaceColor(); protected: const std::map createActionToSliceDimension(); std::map ACTION_TO_SLICEDIMENSION; void AcceptAllInterpolations(mitk::SliceNavigationController *slicer); /** Retrieves the currently selected PlaneGeometry from a SlicedGeometry3D that is generated by a SliceNavigationController and calls Interpolate to further process this PlaneGeometry into an interpolation. \param e is a actually a mitk::SliceNavigationController::GeometrySliceEvent, sent by a SliceNavigationController \param slice the SliceNavigationController */ bool TranslateAndInterpolateChangedSlice(const itk::EventObject &e, mitk::SliceNavigationController *slicer); /** Given a PlaneGeometry, this method figures out which slice of the first working image (of the associated ToolManager) should be interpolated. The actual work is then done by our SegmentationInterpolation object. */ void Interpolate(mitk::PlaneGeometry *plane, unsigned int timeStep, mitk::SliceNavigationController *slicer); // void InterpolateSurface(); /** Called internally to update the interpolation suggestion. Finds out about the focused render window and requests an interpolation. */ void UpdateVisibleSuggestion(); void SetCurrentContourListID(); private: void HideAllInterpolationControls(); void Show2DInterpolationControls(bool show); void Show3DInterpolationControls(bool show); void CheckSupportedImageDimension(); void WaitForFutures(); void NodeRemoved(const mitk::DataNode* node); mitk::SegmentationInterpolationController::Pointer m_Interpolator; mitk::SurfaceInterpolationController::Pointer m_SurfaceInterpolator; mitk::FeatureBasedEdgeDetectionFilter::Pointer m_EdgeDetector; mitk::PointCloudScoringFilter::Pointer m_PointScorer; mitk::ToolManager::Pointer m_ToolManager; bool m_Initialized; QHash m_ControllerToTimeObserverTag; QHash m_ControllerToSliceObserverTag; QHash m_ControllerToDeleteObserverTag; unsigned int InterpolationInfoChangedObserverTag; unsigned int SurfaceInterpolationInfoChangedObserverTag; QGroupBox *m_GroupBoxEnableExclusiveInterpolationMode; QComboBox *m_CmbInterpolation; QPushButton *m_BtnApply2D; QPushButton *m_BtnApplyForAllSlices2D; QPushButton *m_BtnApply3D; QPushButton *m_BtnSuggestPlane; QCheckBox *m_ChkShowPositionNodes; QPushButton *m_BtnReinit3DInterpolation; mitk::DataNode::Pointer m_FeedbackNode; mitk::DataNode::Pointer m_InterpolatedSurfaceNode; mitk::DataNode::Pointer m_3DContourNode; mitk::Image *m_Segmentation; mitk::SliceNavigationController *m_LastSNC; unsigned int m_LastSliceIndex; QHash m_TimeStep; bool m_2DInterpolationEnabled; bool m_3DInterpolationEnabled; // unsigned int m_CurrentListID; mitk::DataStorage::Pointer m_DataStorage; QFuture m_Future; QFutureWatcher m_Watcher; QTimer *m_Timer; QFuture m_PlaneFuture; QFutureWatcher m_PlaneWatcher; bool m_FirstRun; }; #endif diff --git a/Modules/SegmentationUI/Qmitk/QmitkSurfaceBasedInterpolatorWidget.h b/Modules/SegmentationUI/Qmitk/QmitkSurfaceBasedInterpolatorWidget.h index 6561c4c3b4..a4582310dc 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkSurfaceBasedInterpolatorWidget.h +++ b/Modules/SegmentationUI/Qmitk/QmitkSurfaceBasedInterpolatorWidget.h @@ -1,122 +1,119 @@ /*============================================================================ 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 QmitkSurfaceBasedInterpolatorWidgetWidget_h_Included #define QmitkSurfaceBasedInterpolatorWidgetWidget_h_Included #include "MitkSegmentationUIExports.h" #include "mitkDataNode.h" #include "mitkDataStorage.h" #include "mitkLabelSetImage.h" #include "mitkSurfaceBasedInterpolationController.h" #include #include // For running 3D interpolation in background #include #include #include #include #include "ui_QmitkSurfaceBasedInterpolatorWidgetGUIControls.h" namespace mitk { class ToolManager; } /** \brief GUI for surface-based interpolation. \ingroup ToolManagerEtAl \ingroup Widgets \sa QmitkInteractiveSegmentation \sa mitk::SurfaceBasedInterpolationController - There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref - QmitkInteractiveSegmentationTechnicalPage - QmitkSurfaceBasedInterpolatorWidgetController is responsible to watch the GUI, to notice, which slice is currently visible. It triggers generation of interpolation suggestions and also triggers acception of suggestions. */ class MITKSEGMENTATIONUI_EXPORT QmitkSurfaceBasedInterpolatorWidget : public QWidget { Q_OBJECT public: QmitkSurfaceBasedInterpolatorWidget(QWidget *parent = nullptr, const char *name = nullptr); ~QmitkSurfaceBasedInterpolatorWidget() override; void SetDataStorage(mitk::DataStorage &storage); void OnToolManagerWorkingDataModified(); /** Just public because it is called by itk::Commands. You should not need to call this. */ void OnSurfaceInterpolationInfoChanged(const itk::EventObject &); /** * @brief Set the visibility of the interpolation */ void ShowInterpolationResult(bool); Ui::QmitkSurfaceBasedInterpolatorWidgetGUIControls m_Controls; public slots: /** \brief Reaction to "Start/Stop" button click */ void OnToggleWidgetActivation(bool); protected slots: void OnAcceptInterpolationClicked(); void OnSurfaceInterpolationFinished(); void OnRunInterpolation(); void OnShowMarkers(bool); void StartUpdateInterpolationTimer(); void StopUpdateInterpolationTimer(); void ChangeSurfaceColor(); private: mitk::SurfaceBasedInterpolationController::Pointer m_SurfaceBasedInterpolatorController; mitk::ToolManager *m_ToolManager; bool m_Activated; unsigned int m_SurfaceInterpolationInfoChangedObserverTag; mitk::DataNode::Pointer m_InterpolatedSurfaceNode; mitk::DataNode::Pointer m_3DContourNode; mitk::DataStorage::Pointer m_DataStorage; mitk::LabelSetImage::Pointer m_WorkingImage; QFuture m_Future; QFutureWatcher m_Watcher; QTimer *m_Timer; }; #endif diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolReferenceDataSelectionBox.h b/Modules/SegmentationUI/Qmitk/QmitkToolReferenceDataSelectionBox.h index b2901eb6b0..90097a1074 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkToolReferenceDataSelectionBox.h +++ b/Modules/SegmentationUI/Qmitk/QmitkToolReferenceDataSelectionBox.h @@ -1,126 +1,123 @@ /*============================================================================ 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 QmitkToolReferenceDataSelectionBox_h_Included #define QmitkToolReferenceDataSelectionBox_h_Included #include "mitkDataStorage.h" #include "mitkToolManager.h" #include #include #include class QmitkDataStorageComboBox; /** \brief Display the data selection of a ToolManager. \sa mitk::ToolManager \sa mitk::DataStorage \ingroup ToolManagerEtAl \ingroup Widgets -There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref -QmitkInteractiveSegmentationTechnicalPage - Shows the reference data of a ToolManager in a segmentation setting. The reference image can be selected from a combobox, where all images of the scene are listed. $Author: maleike $ */ class MITKSEGMENTATIONUI_EXPORT QmitkToolReferenceDataSelectionBox : public QWidget { Q_OBJECT public: /** * \brief What kind of items should be displayed. * * Every mitk::Tool holds a NodePredicateBase object, telling the kind of data that this * tool will successfully work with. There are two ways that this list box deals with * these predicates. * * DEFAULT is: list data if ANY one of the displayed tools' predicate matches. * Other option: list data if ALL one of the displayed tools' predicate matches */ enum DisplayMode { ListDataIfAllToolsMatch, ListDataIfAnyToolMatches }; QmitkToolReferenceDataSelectionBox(QWidget *parent = nullptr); ~QmitkToolReferenceDataSelectionBox() override; mitk::DataStorage *GetDataStorage(); void SetDataStorage(mitk::DataStorage &storage); /// initialization with a data storage object void Initialize(mitk::DataStorage *); void UpdateDataDisplay(); mitk::ToolManager *GetToolManager(); void SetToolManager(mitk::ToolManager &); // no nullptr pointer allowed here, a manager is required void OnToolManagerReferenceDataModified(); /** * \brief No brief description. * * Should be called to restrict the number of tools that are * evaluated to build up the list. Default is to ask all tools for their predicate, by * setting the 'groups' string this can be restricted to certain groups of tools * or single tools. */ void SetToolGroupsForFiltering(const std::string &groups); /** * \brief How the list contents is determined. * * See also documentation of DisplayMode. * * \sa DisplayMode */ void SetDisplayMode(DisplayMode mode); signals: void ReferenceNodeSelected(const mitk::DataNode *); protected slots: void OnReferenceDataSelected(const mitk::DataNode *node); void EnsureOnlyReferenceImageIsVisibile(); protected: mitk::DataStorage::SetOfObjects::ConstPointer GetAllPossibleReferenceImages(); mitk::NodePredicateBase::ConstPointer GetAllPossibleReferenceImagesPredicate(); mitk::ToolManager::Pointer m_ToolManager; QmitkDataStorageComboBox *m_ReferenceDataSelectionBox; bool m_SelfCall; DisplayMode m_DisplayMode; std::string m_ToolGroupsForFiltering; QVBoxLayout *m_Layout; }; #endif diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.h b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.h index ea8970ba74..643e32bd71 100755 --- a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.h +++ b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.h @@ -1,150 +1,147 @@ /*============================================================================ 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 QmitkToolSelectionBox_h_Included #define QmitkToolSelectionBox_h_Included #include "QmitkToolGUIArea.h" #include #include "mitkToolManager.h" #include #include #include #include class QmitkToolGUI; /** \brief Display the tool selection state of a mitk::ToolManager \sa mitk::ToolManager \ingroup org_mitk_gui_qt_interactivesegmentation \ingroup ToolManagerEtAl - There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref - QmitkInteractiveSegmentationTechnicalPage - This widget graphically displays the active tool of a mitk::ToolManager as a set of toggle buttons. Each button show the identification of a Tool (icon and name). When a button's toggle state is "down", the tool is activated. When a different button is clicked, the active tool is switched. When you click an already active button, the associated tool is deactivated with no replacement, which means that no tool is active then. When this widget is enabled/disabled it (normally) also enables/disables the tools. There could be cases where two QmitkToolSelectionBox widgets are associated to the same ToolManager, but if this happens, please look deeply into the code. Last contributor: $Author: maleike $ */ class MITKSEGMENTATIONUI_EXPORT QmitkToolSelectionBox : public QWidget //! { Q_OBJECT public: enum EnabledMode { EnabledWithReferenceAndWorkingDataVisible, EnabledWithReferenceData, EnabledWithWorkingData, AlwaysEnabled }; QmitkToolSelectionBox(QWidget *parent = nullptr, mitk::DataStorage *storage = nullptr); ~QmitkToolSelectionBox() override; mitk::ToolManager *GetToolManager(); void SetToolManager(mitk::ToolManager &); // no nullptr pointer allowed here, a manager is required void setTitle(const QString &title); /** You may specify a list of tool "groups" that should be displayed in this widget. Every Tool can report its group as a string. This method will try to find the tool's group inside the supplied string \param toolGroups. If there is a match, the tool is displayed. Effectively, you can provide a human readable list like "default, lymphnodevolumetry, oldERISstuff". */ void SetDisplayedToolGroups(const std::string &toolGroups = nullptr); void OnToolManagerToolModified(); void OnToolManagerReferenceDataModified(); void OnToolManagerWorkingDataModified(); void OnToolGUIProcessEventsMessage(); void OnToolErrorMessage(std::string s); void OnGeneralToolMessage(std::string s); void RecreateButtons(); signals: /// Whenever a tool is activated. id is the index of the active tool. Counting starts at 0, -1 indicates "no tool /// selected" /// This signal is also emitted, when the whole QmitkToolSelectionBox get disabled. Then it will claim /// ToolSelected(-1) /// When it is enabled again, there will be another ToolSelected event with the tool that is currently selected void ToolSelected(int id); public slots: virtual void setEnabled(bool); virtual void SetEnabledMode(EnabledMode mode); virtual void SetLayoutColumns(int); virtual void SetShowNames(bool); virtual void SetGenerateAccelerators(bool); virtual void SetToolGUIArea(QWidget *parentWidget); protected slots: void toolButtonClicked(int id); void SetGUIEnabledAccordingToToolManagerState(); protected: void showEvent(QShowEvent *) override; void hideEvent(QHideEvent *) override; void SetOrUnsetButtonForActiveTool(); mitk::ToolManager::Pointer m_ToolManager; bool m_SelfCall; std::string m_DisplayedGroups; /// stores relationship between button IDs of the Qt widget and tool IDs of ToolManager std::map m_ButtonIDForToolID; /// stores relationship between button IDs of the Qt widget and tool IDs of ToolManager std::map m_ToolIDForButtonID; int m_LayoutColumns; bool m_ShowNames; bool m_GenerateAccelerators; QWidget *m_ToolGUIWidget; QmitkToolGUI *m_LastToolGUI; // store buttons in this group QButtonGroup *m_ToolButtonGroup; QGridLayout *m_ButtonLayout; EnabledMode m_EnabledMode; }; #endif diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolWorkingDataSelectionBox.h b/Modules/SegmentationUI/Qmitk/QmitkToolWorkingDataSelectionBox.h index 0ab821f534..0275f2a869 100644 --- a/Modules/SegmentationUI/Qmitk/QmitkToolWorkingDataSelectionBox.h +++ b/Modules/SegmentationUI/Qmitk/QmitkToolWorkingDataSelectionBox.h @@ -1,141 +1,138 @@ /*============================================================================ 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 QmitkToolWorkingDataSelectionListBox_h_Included #define QmitkToolWorkingDataSelectionListBox_h_Included // mmueller #include #include #include "mitkProperties.h" #include "mitkToolManager.h" /** \brief Display the data selection of a ToolManager. \sa mitk::ToolManager \sa mitk::DataStorage \ingroup Widgets -There is a separate page describing the general design of QmitkInteractiveSegmentation: \ref -QmitkInteractiveSegmentationTechnicalPage - Shows the working data of a ToolManager in a segmentation setting. By default only the segmentation name is shown. The working images (segmentations) are listed in a QListView, each row telling the color and name of a single segmentation. One or several segmentations can be selected to be the "active" segmentations. $Author: maleike $ */ class MITKSEGMENTATIONUI_EXPORT QmitkToolWorkingDataSelectionBox : public QListWidget { Q_OBJECT public: /** * \brief What kind of items should be displayed. * * Every mitk::Tool holds a NodePredicateBase object, telling the kind of data that this * tool will successfully work with. There are two ways that this list box deals with * these predicates. * * DEFAULT is: list data if ANY one of the displayed tools' predicate matches. * Other option: list data if ALL one of the displayed tools' predicate matches */ enum DisplayMode { ListDataIfAllToolsMatch, ListDataIfAnyToolMatches }; QmitkToolWorkingDataSelectionBox(QWidget *parent = nullptr); ~QmitkToolWorkingDataSelectionBox() override; mitk::DataStorage *GetDataStorage(); void SetDataStorage(mitk::DataStorage &storage); /** \brief Can be called to trigger an update of the list contents. */ void UpdateDataDisplay(); /** \brief Returns the associated mitk::ToolManager. */ mitk::ToolManager *GetToolManager(); /** \brief Tell this object to listen to another ToolManager. */ void SetToolManager(mitk::ToolManager &); // no nullptr pointer allowed here, a manager is required /** * \brief A list of all displayed DataNode objects. * This method might be convenient for program modules that want to display * additional information about these nodes, like a total volume of all segmentations, etc. */ mitk::ToolManager::DataVectorType GetAllNodes(bool onlyDerivedFromOriginal = true); /** * \brief A list of all selected DataNode objects. * This method might be convenient for program modules that want to display * additional information about these nodes, like a total volume of all segmentations, etc. */ mitk::ToolManager::DataVectorType GetSelectedNodes(); /** * \brief Like GetSelectedNodes(), but will only return one object. * Will only return what QListView gives as selected object (documentation says nothing is returned if list is in * Single selection mode). */ mitk::DataNode *GetSelectedNode(); /** * \brief Callback function, no need to call it. * This is used to observe and react to changes in the mitk::ToolManager object. */ void OnToolManagerWorkingDataModified(); /** * \brief Callback function, no need to call it. * This is used to observe and react to changes in the mitk::ToolManager object. */ void OnToolManagerReferenceDataModified(); signals: void WorkingNodeSelected(const mitk::DataNode *); protected slots: void OnWorkingDataSelectionChanged(); protected: typedef std::map ItemNodeMapType; mitk::ToolManager::Pointer m_ToolManager; ItemNodeMapType m_Node; bool m_SelfCall; mitk::DataNode *m_LastSelectedReferenceData; std::string m_ToolGroupsForFiltering; bool m_DisplayOnlyDerivedNodes; }; #endif diff --git a/Modules/TumorInvasionAnalysis/CMakeLists.txt b/Modules/TumorInvasionAnalysis/CMakeLists.txt deleted file mode 100644 index 270882e798..0000000000 --- a/Modules/TumorInvasionAnalysis/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -MITK_CREATE_MODULE( - INCLUDE_DIRS PRIVATE src/Classification src/ImageFilters src/ReaderWriter - DEPENDS MitkCore MitkDiffusionCore MitkFiberTracking MitkDiffusionIO MitkDataCollection MitkSegmentation MitkCLVigraRandomForest #<-- modules on which your module depends - PACKAGE_DEPENDS PUBLIC ITK|ITKDiffusionTensorImage+ITKLevelSets Qt5|Core -) - - -if (MODULE_IS_ENABLED) - add_subdirectory(test) - ADD_SUBDIRECTORY(MiniApps) -endif() diff --git a/Modules/TumorInvasionAnalysis/MiniApps/BasicDistanceMaps.cpp b/Modules/TumorInvasionAnalysis/MiniApps/BasicDistanceMaps.cpp deleted file mode 100644 index 6e292ed37d..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/BasicDistanceMaps.cpp +++ /dev/null @@ -1,68 +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 "mitkCommandLineParser.h" -#include "mitkITKImageImport.h" -#include "mitkImage.h" -#include - -#include "itkSignedDanielssonDistanceMapImageFilter.h" - -using namespace std; - -typedef itk::Image BinaryType; -typedef itk::Image ResultType; - -int main(int argc, char *argv[]) -{ - mitkCommandLineParser parser; - parser.setTitle("Basic Distance Maps"); - parser.setCategory("Features"); - parser.setDescription("Creates Eucledian Distance Maps of a given ROI segmentation"); - parser.setContributor("German Cancer Research Center (DKFZ)"); - - parser.setArgumentPrefix("--", "-"); - parser.addArgument("input", "i", mitkCommandLineParser::Image, "(binary) seed file", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("output", "o", mitkCommandLineParser::File, "distance map file name", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - - map parsedArgs = parser.parseArguments(argc, argv); - - // Show a help message - if (parsedArgs.size() == 0 || parsedArgs.count("help") || parsedArgs.count("h")) - { - std::cout << parser.helpText(); - return EXIT_SUCCESS; - } - - std::string resultFile = us::any_cast(parsedArgs["output"]); - std::string seedFile = us::any_cast(parsedArgs["input"]); - - mitk::Image::Pointer seedImage = mitk::IOUtil::Load(seedFile); - - BinaryType::Pointer itkSeed = BinaryType::New(); - - mitk::CastToItkImage(seedImage, itkSeed); - - itk::SignedDanielssonDistanceMapImageFilter::Pointer danielssonDistance = - itk::SignedDanielssonDistanceMapImageFilter::New(); - danielssonDistance->SetInput(itkSeed); - danielssonDistance->SetUseImageSpacing(true); - danielssonDistance->Update(); - - mitk::Image::Pointer result = mitk::Image::New(); - mitk::GrabItkImageMemory(danielssonDistance->GetOutput(), result); - mitk::IOUtil::Save(result, resultFile); - - return EXIT_SUCCESS; -} diff --git a/Modules/TumorInvasionAnalysis/MiniApps/CMakeLists.txt b/Modules/TumorInvasionAnalysis/MiniApps/CMakeLists.txt deleted file mode 100644 index 8525a62c29..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/CMakeLists.txt +++ /dev/null @@ -1,41 +0,0 @@ -option(BUILD_TumorInvasionAnalysisMiniApps "Build commandline tools for tumor invasion analysis" OFF) - -if(BUILD_TumorInvasionAnalysisMiniApps OR MITK_BUILD_ALL_APPS) - - - include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR} - ) - - # list of miniapps - # if an app requires additional dependencies - # they are added after a "^^" and separated by "_" - set( tumorinvasionminiapps - BasicDistanceMaps^^ - MriNormalization^^ - MriOtsuNormalization^^ - #Resampling^^ - TumorResponseEvaluationTool^^ - HistogramAdaption^^ - TumorProgressionMapping^^ - ConnectednessFeatureMaps^^ - TumorInvasionAnalysisTool^^ - ) - - foreach(tumorinvasionminiapps ${tumorinvasionminiapps}) - # extract mini app name and dependencies - string(REPLACE "^^" "\\;" miniapp_info ${tumorinvasionminiapps}) - set(miniapp_info_list ${miniapp_info}) - list(GET miniapp_info_list 0 appname) - list(GET miniapp_info_list 1 raw_dependencies) - string(REPLACE "_" "\\;" dependencies "${raw_dependencies}") - set(dependencies_list ${dependencies}) - - mitkFunctionCreateCommandLineApp( - NAME ${appname} - DEPENDS MitkCore MitkCLCore MitkDataCollection MitkTumorInvasionAnalysis ${dependencies_list} - ) - endforeach() - -endif() diff --git a/Modules/TumorInvasionAnalysis/MiniApps/ConnectednessFeatureMaps.cpp b/Modules/TumorInvasionAnalysis/MiniApps/ConnectednessFeatureMaps.cpp deleted file mode 100644 index 9ee23bb745..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/ConnectednessFeatureMaps.cpp +++ /dev/null @@ -1,198 +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 "mitkCommandLineParser.h" -#include "mitkITKImageImport.h" -#include "mitkImage.h" -#include -#include -#include - -#include - -// ITK -#include "itkBinaryErodeImageFilter.h" -#include "itkFlatStructuringElement.h" - -using namespace std; - -typedef itk::Image BinaryType; -typedef itk::Image ResultType; -typedef itk::Image, 3> ItkTensorImage; - -int main(int argc, char *argv[]) -{ - // Setup CLI Module parsable interface - mitkCommandLineParser parser; - parser.setTitle("Connectedness Maps"); - parser.setCategory("Features"); - parser.setDescription("Computes connectedness maps"); - parser.setContributor("German Cancer Research Center (DKFZ)"); - - parser.setArgumentPrefix("--", "-"); - parser.addArgument("input", "i", mitkCommandLineParser::Image, "input file", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("seed", "s", mitkCommandLineParser::Image, "seed file", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("mask", "m", mitkCommandLineParser::Image, "mask file", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("mode", "t", mitkCommandLineParser::String, "Mode Feature | Vector | FeatureVector"); - parser.addArgument("vector", "v", mitkCommandLineParser::Image, "Tensor Image (.dti)", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument( - "confidence", "c", mitkCommandLineParser::Image, "confidence map (only when Tensor Images are used)", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("valueImage", "x", mitkCommandLineParser::Image, "image of values that are propagated", "", us::Any(), true, false, false, mitkCommandLineParser::Input); - - parser.addArgument("erodeSeed", "a", mitkCommandLineParser::Bool, "apply erosion of seed region"); - - parser.addArgument("rankFilter", "r", mitkCommandLineParser::Bool, "median filter for propagation"); - - parser.addArgument("propMap", "p", mitkCommandLineParser::File, "[out] propagated map", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument("distanceMap", "d", mitkCommandLineParser::File, "[out] connectedness map", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument("euclidDistanceMap", "e", mitkCommandLineParser::File, "[out] euclid distance map", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - - // Parse input parameters - map parsedArgs = parser.parseArguments(argc, argv); - - // Show a help message - if (parsedArgs.size() == 0 || parsedArgs.count("help") || parsedArgs.count("h")) - { - std::cout << parser.helpText(); - return EXIT_SUCCESS; - } - - bool useRank = false; - bool applyErosion = false; - bool useValueImage = false; - if (parsedArgs.count("rankFilter") || parsedArgs.count("r")) - useRank = true; - - if (parsedArgs.count("valueImage") || parsedArgs.count("x")) - useValueImage = true; - - if (parsedArgs.count("erodeSeed") || parsedArgs.count("a")) - applyErosion = true; - - std::string inputFile = us::any_cast(parsedArgs["input"]); - std::string propMap = us::any_cast(parsedArgs["propMap"]); - std::string conMap = us::any_cast(parsedArgs["distanceMap"]); - std::string tensImageFile = us::any_cast(parsedArgs["vector"]); - std::string maskFile = us::any_cast(parsedArgs["mask"]); - std::string mode = us::any_cast(parsedArgs["mode"]); - std::string seedFile = us::any_cast(parsedArgs["seed"]); - std::string confFile = us::any_cast(parsedArgs["confidence"]); - std::string euclidFile = us::any_cast(parsedArgs["euclidDistanceMap"]); - - std::string valueImageFile = ""; - if (useValueImage) - valueImageFile = us::any_cast(parsedArgs["valueImage"]); - - // Read-in image data - mitk::Image::Pointer tmpImage; - mitk::Image::Pointer inputImage = mitk::IOUtil::Load(inputFile); - mitk::Image::Pointer maskImage = mitk::IOUtil::Load(maskFile); - mitk::Image::Pointer seedImage = mitk::IOUtil::Load(seedFile); - - mitk::Image::Pointer valueImage; - if (useValueImage) - valueImage = mitk::IOUtil::Load(valueImageFile); - - mitk::Image::Pointer confImage; - if (mode == "Vector" || mode == "FeatureVector") - { - MITK_INFO << "Load Tensor/Confidence"; - tmpImage = mitk::IOUtil::Load(tensImageFile); - confImage = mitk::IOUtil::Load(confFile); - } - - mitk::TensorImage *diffusionImage = static_cast(tmpImage.GetPointer()); - - // Convert all input data to ITK - BinaryType::Pointer itkSeed = BinaryType::New(); - BinaryType::Pointer itkMask = BinaryType::New(); - ResultType::Pointer itkImage = ResultType::New(); - ItkTensorImage::Pointer itkTensor = ItkTensorImage::New(); - ResultType::Pointer itkWeight = ResultType::New(); - ResultType::Pointer itkValueImage = ResultType::New(); - - mitk::CastToItkImage(inputImage, itkImage); - mitk::CastToItkImage(maskImage, itkMask); - mitk::CastToItkImage(seedImage, itkSeed); - if (useValueImage) - mitk::CastToItkImage(valueImage, itkValueImage); - - if (applyErosion) - { - typedef itk::FlatStructuringElement<3> StructuringElementType; - StructuringElementType::RadiusType elementRadius; - elementRadius.Fill(2); - elementRadius[2] = 0; - StructuringElementType structuringElement = StructuringElementType::Box(elementRadius); - - typedef itk::BinaryErodeImageFilter BinaryErodeImageFilterType; - - BinaryErodeImageFilterType::Pointer erodeFilter = BinaryErodeImageFilterType::New(); - erodeFilter->SetInput(itkSeed); - erodeFilter->SetKernel(structuringElement); - erodeFilter->SetForegroundValue(1); - erodeFilter->Update(); - itkSeed = erodeFilter->GetOutput(); - } - - if (mode == "Vector" || mode == "FeatureVector") - { - mitk::CastToItkImage(diffusionImage, itkTensor); - mitk::CastToItkImage(confImage, itkWeight); - } - - // Setup filter - itk::ConnectednessFilter::Pointer filter = - itk::ConnectednessFilter::New(); - - filter->SetInputImage(itkImage); - filter->SetInputSeed(itkSeed); - filter->SetInputMask(itkMask); - if (mode == "Vector") - { - filter->SetInputVectorField(itkTensor); - filter->SetInputVectorFieldConfidenceMap(itkWeight); - filter->SetMode(itk::ConnectednessFilter::VectorAgreement); - } - else if (mode == "FeatureVector") - { - filter->SetInputVectorField(itkTensor); - filter->SetInputVectorFieldConfidenceMap(itkWeight); - filter->SetMode(itk::ConnectednessFilter::FeatureVectorAgreement); - } - else - filter->SetMode(itk::ConnectednessFilter::FeatureSimilarity); - - if (useValueImage) - filter->SetPropagationImage(itkValueImage); - - filter->SetApplyRankFilter(useRank); - filter->Update(); - - // Grab output and write results - mitk::Image::Pointer result = mitk::Image::New(); - mitk::GrabItkImageMemory(filter->GetOutput(), result); - - mitk::IOUtil::Save(result, propMap); - - mitk::Image::Pointer distance = mitk::Image::New(); - mitk::GrabItkImageMemory(filter->GetDistanceImage().GetPointer(), distance); - mitk::IOUtil::Save(distance, conMap); - - mitk::Image::Pointer euclidDistance = mitk::Image::New(); - mitk::GrabItkImageMemory(filter->GetEuclideanDistanceImage().GetPointer(), euclidDistance); - mitk::IOUtil::Save(euclidDistance, euclidFile); - - return EXIT_SUCCESS; -} diff --git a/Modules/TumorInvasionAnalysis/MiniApps/HistogramAdaption.cpp b/Modules/TumorInvasionAnalysis/MiniApps/HistogramAdaption.cpp deleted file mode 100644 index cac1581f62..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/HistogramAdaption.cpp +++ /dev/null @@ -1,100 +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 "itkImageRegionIterator.h" -#include "mitkIOUtil.h" -#include "mitkImageCast.h" -#include -#include - -using namespace std; - -typedef itk::Image SeedImage; -typedef itk::Image FeatureImage; - -typedef itk::ImageRegionIterator SeedIteratorType; -typedef itk::ImageRegionIterator FeatureIteratorType; - -int main(int argc, char *argv[]) -{ - mitkCommandLineParser parser; - parser.setTitle("Contrast Adaption"); - parser.setCategory("Preprocessing Tools"); - parser.setDescription("Stretches or pushes image intensities above a given threshold"); - parser.setContributor("German Cancer Research Center (DKFZ)"); - - parser.setArgumentPrefix("--", "-"); - - // Add command line argument names - parser.addArgument("input", "i", mitkCommandLineParser::Image, "input image", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("output", "o", mitkCommandLineParser::File, "output image", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument("cutOff", "c", mitkCommandLineParser::Float, "value at which different slope is to be applied"); - parser.addArgument( - "slope", "s", mitkCommandLineParser::Float, "slope to be applied (total delta to max value starting from cutOff)"); - - map parsedArgs = parser.parseArguments(argc, argv); - - if (parsedArgs.size() == 0) - return EXIT_FAILURE; - - // Show a help message - if (parsedArgs.count("help") || parsedArgs.count("h")) - { - std::cout << parser.helpText(); - return EXIT_SUCCESS; - } - - std::string outFile = us::any_cast(parsedArgs["output"]); - mitk::Image::Pointer inputFile = mitk::IOUtil::Load(us::any_cast(parsedArgs["input"])); - float cutOff = us::any_cast(parsedArgs["cutOff"]); - float slope = us::any_cast(parsedArgs["slope"]); - - FeatureImage::Pointer itkInputImage = FeatureImage::New(); - - mitk::CastToItkImage(inputFile, itkInputImage); - double max = -99999; - - itk::ImageRegionIterator inputIt(itkInputImage, itkInputImage->GetLargestPossibleRegion()); - - while (!inputIt.IsAtEnd()) - { - if (inputIt.Get() > max) - max = inputIt.Get(); - - ++inputIt; - } - - inputIt.GoToBegin(); - // Mapping - while (!inputIt.IsAtEnd()) - { - if (inputIt.Get() > cutOff) - { - inputIt.Set(cutOff + slope * (inputIt.Get() - cutOff) / (max - cutOff)); - } - ++inputIt; - } - - mitk::Image::Pointer mitkResult = mitk::Image::New(); - // !! CastToItk behaves very differently depending on the original data type - // if the target type is the same as the original, only a pointer to the data is set - // and an additional GrabItkImageMemory will cause a segfault when the image is destroyed - // GrabItkImageMemory - is not necessary in this case since we worked on the original data - // See Bug 17538. - if (inputFile->GetPixelType().GetComponentTypeAsString() != "double") - mitkResult = mitk::GrabItkImageMemory(itkInputImage); - else - mitkResult = inputFile; - - mitk::IOUtil::Save(mitkResult, outFile); - return EXIT_SUCCESS; -} diff --git a/Modules/TumorInvasionAnalysis/MiniApps/MriNormalization.cpp b/Modules/TumorInvasionAnalysis/MiniApps/MriNormalization.cpp deleted file mode 100644 index 867cf8ee69..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/MriNormalization.cpp +++ /dev/null @@ -1,118 +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 "itkImageRegionIterator.h" -#include "mitkCommandLineParser.h" -#include "mitkIOUtil.h" -#include "mitkImageCast.h" -#include - -using namespace std; - -typedef itk::Image SeedImage; -typedef itk::Image FeatureImage; - -typedef itk::ImageRegionIterator SeedIteratorType; -typedef itk::ImageRegionIterator FeatureIteratorType; - -int main(int argc, char *argv[]) -{ - mitkCommandLineParser parser; - parser.setTitle("Mri Normalization"); - parser.setCategory("Preprocessing Tools"); - parser.setDescription( - "Normalizes an MRI volume between medians of two given masks (e.g. ventricles and brain matter)"); - parser.setContributor("German Cancer Research Center (DKFZ)"); - - parser.setArgumentPrefix("--", "-"); - - // Add command line argument names - parser.addArgument("input", "i", mitkCommandLineParser::Image, "input image", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("output", "o", mitkCommandLineParser::File, "output image", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument( - "maxMask", "m", mitkCommandLineParser::Image, "mask of which median is set as maximal value (1)", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument( - "minMask", "l", mitkCommandLineParser::Image, "mask of which median is set as minimal value (0)", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument( - "excludeMask", "e", mitkCommandLineParser::Image, "region which is exluded from the other two", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - - map parsedArgs = parser.parseArguments(argc, argv); - - // Show a help message - if (parsedArgs.size() == 0 || parsedArgs.count("help") || parsedArgs.count("h")) - { - std::cout << parser.helpText(); - return EXIT_SUCCESS; - } - - std::string outFile = us::any_cast(parsedArgs["output"]); - mitk::Image::Pointer inputFile = mitk::IOUtil::Load(us::any_cast(parsedArgs["input"])); - mitk::Image::Pointer maxMask = mitk::IOUtil::Load(us::any_cast(parsedArgs["maxMask"])); - mitk::Image::Pointer minMask = mitk::IOUtil::Load(us::any_cast(parsedArgs["minMask"])); - mitk::Image::Pointer excludeMask = mitk::IOUtil::Load(us::any_cast(parsedArgs["excludeMask"])); - - SeedImage::Pointer itkMaxImage = SeedImage::New(); - SeedImage::Pointer itkMinImage = SeedImage::New(); - SeedImage::Pointer itkExcludeImage = SeedImage::New(); - - FeatureImage::Pointer itkInputImage = FeatureImage::New(); - - mitk::CastToItkImage(inputFile, itkInputImage); - mitk::CastToItkImage(maxMask, itkMaxImage); - mitk::CastToItkImage(minMask, itkMinImage); - mitk::CastToItkImage(excludeMask, itkExcludeImage); - - std::vector medianMin; - std::vector medianMax; - - itk::ImageRegionIterator inputIt(itkInputImage, itkInputImage->GetLargestPossibleRegion()); - itk::ImageRegionIterator excludeIt(itkExcludeImage, itkExcludeImage->GetLargestPossibleRegion()); - itk::ImageRegionIterator minIt(itkMinImage, itkMinImage->GetLargestPossibleRegion()); - itk::ImageRegionIterator maxIt(itkMaxImage, itkMaxImage->GetLargestPossibleRegion()); - - while (!inputIt.IsAtEnd()) - { - if (excludeIt.Get() == 0) - { - if (minIt.Get() != 0) - medianMin.push_back(inputIt.Get()); - - if (maxIt.Get() != 0) - medianMax.push_back(inputIt.Get()); - } - ++inputIt; - ++excludeIt; - ++minIt; - ++maxIt; - } - - std::sort(medianMax.begin(), medianMax.end()); - std::sort(medianMin.begin(), medianMin.end()); - - mitk::ScalarType minVal = medianMin.at(medianMin.size() / 2); - mitk::ScalarType maxVal = medianMax.at(medianMax.size() / 2); - - inputIt.GoToBegin(); - // Create mapping - while (!inputIt.IsAtEnd()) - { - inputIt.Set(1.0 * (inputIt.Get() - minVal) / (maxVal - minVal)); - ++inputIt; - } - - mitk::Image::Pointer mitkResult = mitk::Image::New(); - mitkResult = mitk::GrabItkImageMemory(itkInputImage); - - mitk::IOUtil::Save(mitkResult, outFile); - - return EXIT_SUCCESS; -} diff --git a/Modules/TumorInvasionAnalysis/MiniApps/MriOtsuNormalization.cpp b/Modules/TumorInvasionAnalysis/MiniApps/MriOtsuNormalization.cpp deleted file mode 100644 index bee84b9806..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/MriOtsuNormalization.cpp +++ /dev/null @@ -1,120 +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 "itkImageRegionIterator.h" -#include "mitkCommandLineParser.h" -#include "mitkIOUtil.h" -#include "mitkImageCast.h" -#include - -// ITK -#include - -using namespace std; - -typedef itk::Image SeedImage; -typedef itk::Image FeatureImage; - -typedef itk::ImageRegionIterator SeedIteratorType; -typedef itk::ImageRegionIterator FeatureIteratorType; - -int main(int argc, char *argv[]) -{ - mitkCommandLineParser parser; - parser.setTitle("Mri Normalization"); - parser.setCategory("Preprocessing Tools"); - parser.setDescription("Normalizes an MRI volume based on regions determined by Otsu."); - parser.setContributor("German Cancer Research Center (DKFZ)"); - - parser.setArgumentPrefix("--", "-"); - - // Add command line argument names - parser.addArgument("input", "i", mitkCommandLineParser::Image, "input image", "input image", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("output", "o", mitkCommandLineParser::File, "output image", "output image", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument("bins", "b", mitkCommandLineParser::Int, "number of regions (bins)", "number of regions (bins)"); - - parser.addArgument( - "minBin", "l", mitkCommandLineParser::Int, "bin of which median is set to 0", "bin of which median is set to 0"); - parser.addArgument( - "maxBin", "h", mitkCommandLineParser::Int, "bin of which median is set to 1", "bin of which median is set to 1"); - - map parsedArgs = parser.parseArguments(argc, argv); - - // Show a help message - if (parsedArgs.size() == 0 || parsedArgs.count("help") || parsedArgs.count("h")) - { - std::cout << parser.helpText(); - return EXIT_SUCCESS; - } - - std::string outFile = us::any_cast(parsedArgs["output"]); - mitk::Image::Pointer inputFile = mitk::IOUtil::Load(us::any_cast(parsedArgs["input"])); - int numberOfThresholds = us::any_cast(parsedArgs["bins"]); - int minBin = us::any_cast(parsedArgs["minBin"]); - int maxBin = us::any_cast(parsedArgs["maxBin"]); - - FeatureImage::Pointer itkInputImage = FeatureImage::New(); - mitk::CastToItkImage(inputFile, itkInputImage); - - typedef itk::OtsuMultipleThresholdsImageFilter FilterType; - FilterType::Pointer otsuFilter = FilterType::New(); - otsuFilter->SetInput(itkInputImage); - otsuFilter->SetNumberOfThresholds(numberOfThresholds - 1); - otsuFilter->Update(); - - FeatureImage::Pointer itkLabelImage = otsuFilter->GetOutput(); - - std::vector medianMin; - std::vector medianMax; - - itk::ImageRegionIterator inputIt(itkInputImage, itkInputImage->GetLargestPossibleRegion()); - itk::ImageRegionIterator labelIt(itkLabelImage, itkLabelImage->GetLargestPossibleRegion()); - - while (!inputIt.IsAtEnd()) - { - if (labelIt.Get() == minBin) - { - medianMin.push_back(inputIt.Get()); - } - else if (labelIt.Get() == maxBin) - { - medianMax.push_back(inputIt.Get()); - } - ++inputIt; - ++labelIt; - } - - std::sort(medianMax.begin(), medianMax.end()); - std::sort(medianMin.begin(), medianMin.end()); - - mitk::ScalarType minVal = medianMin.at(medianMin.size() / 2); - mitk::ScalarType maxVal = medianMax.at(medianMax.size() / 2); - - inputIt.GoToBegin(); - // labelIt.GoToBegin(); - // Create mapping - while (!inputIt.IsAtEnd()) - { - inputIt.Set(1.0 * (inputIt.Get() - minVal) / (maxVal - minVal)); - // inputIt.Set(labelIt.Get()); - ++inputIt; - - //++labelIt; - } - - mitk::Image::Pointer mitkResult = mitk::Image::New(); - mitkResult = mitk::GrabItkImageMemory(itkInputImage); - - mitk::IOUtil::Save(mitkResult, outFile); - - return EXIT_SUCCESS; -} diff --git a/Modules/TumorInvasionAnalysis/MiniApps/TumorInvasionAnalysisTool.cpp b/Modules/TumorInvasionAnalysis/MiniApps/TumorInvasionAnalysisTool.cpp deleted file mode 100644 index bc40bcc543..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/TumorInvasionAnalysisTool.cpp +++ /dev/null @@ -1,346 +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. - -============================================================================*/ - -// MITK - DataCollection -#include -#include -#include -#include - -#include "mitkDataCollectionImageIterator.h" -#include -#include -// CTK -#include "mitkCommandLineParser.h" -// ITK -#include - -using namespace std; - -int main(int argc, char *argv[]) -{ - // Setup CLI Module parsable interface - mitkCommandLineParser parser; - parser.setTitle("Tumor Invasion Analysis"); - parser.setCategory("Tumor Analysis"); - parser.setDescription("Learns and predicts Invasion behavior"); - parser.setContributor("German Cancer Research Center (DKFZ)"); - - parser.setArgumentPrefix("--", "-"); - // Add command line argument names - parser.addArgument("help", "h", mitkCommandLineParser::Bool, "Show options"); - parser.addArgument("loadFile", "l", mitkCommandLineParser::File, "DataCollection File", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument( - "colIds", "c", mitkCommandLineParser::String, "Patient Identifiers from DataCollection used for training"); - parser.addArgument( - "testId", "t", mitkCommandLineParser::String, "Patient Identifier from DataCollection used for testing"); - parser.addArgument("features", "b", mitkCommandLineParser::String, "Features"); - parser.addArgument("stats", "s", mitkCommandLineParser::String, "Output file for stats"); - parser.addArgument("ratio", "q", mitkCommandLineParser::Float, "ratio of tumor to healthy"); - parser.addArgument("treeDepth", "d", mitkCommandLineParser::Int, "limits tree depth"); - parser.addArgument("forestSize", "f", mitkCommandLineParser::Int, "number of trees"); - parser.addArgument("samplingMode", "m", mitkCommandLineParser::Int, "mode of sample selection"); - parser.addArgument("configName", "n", mitkCommandLineParser::String, "human readable name for configuration"); - parser.addArgument("output", "o", mitkCommandLineParser::Directory, "output folder for results", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument("forest", "t", mitkCommandLineParser::File, "store trained forest to file", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - - map parsedArgs = parser.parseArguments(argc, argv); - // Show a help message - if (parsedArgs.size() == 0) - return EXIT_SUCCESS; - if (parsedArgs.count("help") || parsedArgs.count("h")) - { - std::cout << parser.helpText(); - return EXIT_SUCCESS; - } - - // Default values - float ratio = 1.0; - bool useStatsFile = false; - unsigned int forestSize = 250; - unsigned int treeDepth = 0; - unsigned int samplingMode = 1; - std::string configName = ""; - std::string outputFolder = ""; - std::string forestFile = ""; - - std::vector features; - std::vector trainingIds; - std::vector testingIds; - std::vector loadIds; // features + masks needed for training and evaluation - std::string outputFile; - std::string xmlFile; - std::ofstream experimentFS; - - // Parse input parameters - { - if (parsedArgs.count("colIds") || parsedArgs.count("c")) - { - std::istringstream ss(us::any_cast(parsedArgs["colIds"])); - std::string token; - - while (std::getline(ss, token, ',')) - trainingIds.push_back(token); - } - - if (parsedArgs.count("output") || parsedArgs.count("o")) - { - outputFolder = us::any_cast(parsedArgs["output"]); - } - - if (parsedArgs.count("configName") || parsedArgs.count("n")) - { - configName = us::any_cast(parsedArgs["configName"]); - } - - if (parsedArgs.count("features") || parsedArgs.count("b")) - { - std::istringstream ss(us::any_cast(parsedArgs["features"])); - std::string token; - - while (std::getline(ss, token, ',')) - features.push_back(token); - } - - if (parsedArgs.count("treeDepth") || parsedArgs.count("d")) - { - treeDepth = us::any_cast(parsedArgs["treeDepth"]); - } - - if (parsedArgs.count("ratio") || parsedArgs.count("q")) - { - ratio = us::any_cast(parsedArgs["ratio"]); - } - - if (parsedArgs.count("forestSize") || parsedArgs.count("f")) - { - forestSize = us::any_cast(parsedArgs["forestSize"]); - } - - if (parsedArgs.count("samplingMode") || parsedArgs.count("m")) - { - samplingMode = us::any_cast(parsedArgs["samplingMode"]); - } - - if (parsedArgs.count("stats") || parsedArgs.count("s")) - { - useStatsFile = true; - experimentFS.open(us::any_cast(parsedArgs["stats"]).c_str(), std::ios_base::app); - } - - if (parsedArgs.count("forest") || parsedArgs.count("t")) - { - forestFile = us::any_cast(parsedArgs["stats"]); - } - - if (parsedArgs.count("testId") || parsedArgs.count("t")) - { - std::istringstream ss(us::any_cast(parsedArgs["testId"])); - std::string token; - - while (std::getline(ss, token, ',')) - testingIds.push_back(token); - } - - for (unsigned int i = 0; i < features.size(); i++) - { - loadIds.push_back(features.at(i)); - } - loadIds.push_back("GTV"); - loadIds.push_back("BRAINMASK"); - loadIds.push_back("TARGET"); - - if (parsedArgs.count("stats") || parsedArgs.count("s")) - { - outputFile = us::any_cast(parsedArgs["stats"]); - } - - if (parsedArgs.count("loadFile") || parsedArgs.count("l")) - { - xmlFile = us::any_cast(parsedArgs["loadFile"]); - } - else - { - MITK_ERROR << parser.helpText(); - return EXIT_FAILURE; - } - } - - mitk::DataCollection::Pointer trainCollection; - mitk::DataCollection::Pointer testCollection; - { - mitk::DiffusionCollectionReader colReader; - // Load only relevant images - colReader.SetDataItemNames(loadIds); - colReader.AddSubColIds(testingIds); - testCollection = colReader.LoadCollection(xmlFile); - colReader.ClearDataElementIds(); - colReader.ClearSubColIds(); - colReader.SetDataItemNames(loadIds); - colReader.AddSubColIds(trainingIds); - trainCollection = colReader.LoadCollection(xmlFile); - } - - std::cout << "Setup Training" << std::endl; - mitk::TumorInvasionClassification classifier; - - classifier.SetClassRatio(ratio); - classifier.SetTrainMargin(7, 1); - classifier.SamplesWeightingActivated(true); - classifier.SelectTrainingSamples(trainCollection, samplingMode); - // Learning stage - std::cout << "Start Training" << std::endl; - classifier.LearnProgressionFeatures(trainCollection, features, forestSize, treeDepth); - - if (forestFile != "") - classifier.SaveRandomForest(forestFile); - - std::cout << "Start Predict" << std::endl; - classifier.PredictInvasion(testCollection, features); - - if (false && outputFolder != "") - { - std::cout << "Saving files to " << outputFolder << std::endl; - mitk::DiffusionCollectionWriter::ExportCollectionToFolder(trainCollection, "/tmp/dumple"); - } - classifier.SanitizeResults(testCollection); - - { - mitk::DataCollectionImageIterator gtvIt(testCollection, "GTV"); - mitk::DataCollectionImageIterator result(testCollection, "RESULTOPEN"); - - while (!gtvIt.IsAtEnd()) - { - if (gtvIt.GetVoxel() != 0) - { - result.SetVoxel(2); - } - - result++; - gtvIt++; - } - } - - mitk::CollectionStatistic stat2; - mitk::ProgressionValueToIndexMapper progressionValueToIndexMapper; - mitk::BinaryValueToIndexMapper binaryValueToIndexMapper; - - stat2.SetCollection(testCollection); - stat2.SetClassCount(2); - stat2.SetGoldName("TARGET"); - stat2.SetTestName("RESULTOPEN"); - stat2.SetMaskName("BRAINMASK"); - stat2.SetGroundTruthValueToIndexMapper(&binaryValueToIndexMapper); - stat2.SetTestValueToIndexMapper(&progressionValueToIndexMapper); - - stat2.Update(); - stat2.ComputeRMSD(); - - // FIXME: DICE value available after calling Print method - std::ostringstream out2; - stat2.Print(out2, std::cout, true); - std::cout << std::endl << std::endl << out2.str() << std::endl; - - // Exclude GTV from Statistics by removing it from brain mask, - // insert GTV as tumor region, since it is known before, in the result. - { - mitk::DataCollectionImageIterator gtvIt(testCollection, "GTV"); - mitk::DataCollectionImageIterator brainMaskIter(testCollection, "BRAINMASK"); - mitk::DataCollectionImageIterator result(testCollection, "RESULTOPEN"); - - while (!gtvIt.IsAtEnd()) - { - if (gtvIt.GetVoxel() != 0) - { - brainMaskIter.SetVoxel(0); - result.SetVoxel(2); - } - result++; - gtvIt++; - brainMaskIter++; - } - } - - mitk::CollectionStatistic stat; - stat.SetCollection(testCollection); - stat.SetClassCount(2); - stat.SetGoldName("TARGET"); - stat.SetTestName("RESULTOPEN"); - stat.SetMaskName("BRAINMASK"); - stat.SetGroundTruthValueToIndexMapper(&binaryValueToIndexMapper); - stat.SetTestValueToIndexMapper(&progressionValueToIndexMapper); - - stat.Update(); - stat.ComputeRMSD(); - - // WARN: DICE value computed within Print method, so values are only available - // after - // calling Print() - std::ostringstream out; - stat.Print(out, std::cout, true); - std::cout << std::endl << std::endl << out.str() << std::endl; - - // Statistics for original GTV excluded (Dice,Sensitivity) and for Gold - // Standard vs prediction (RMSE) - mitk::StatisticData statData = stat.GetStatisticData(1).at(0); - mitk::StatisticData statData2 = stat2.GetStatisticData(1).at(0); - - std::cout << "Writing Stats to file" << std::endl; - // one line output - if (useStatsFile) - { - experimentFS << "Tree_Depth " << treeDepth << ','; - experimentFS << "Forest_Size " << forestSize << ','; - experimentFS << "Tumor/healthy_ratio " << ratio << ','; - experimentFS << "Sample_Selection " << samplingMode << ','; - - experimentFS << "Trainined_on: " << ','; - for (unsigned int i = 0; i < trainingIds.size(); i++) - { - experimentFS << trainingIds.at(i) << "/"; - } - experimentFS << ','; - - experimentFS << "Tested_on: " << ','; - for (unsigned int i = 0; i < testingIds.size(); i++) - { - experimentFS << testingIds.at(i) << "/"; - } - experimentFS << ','; - - experimentFS << "Features_used: " << ','; - if (configName == "") - { - for (unsigned int i = 0; i < features.size(); i++) - { - experimentFS << features.at(i) << "/"; - } - } - else - experimentFS << configName; - - experimentFS << ','; - experimentFS << "---- STATS ---" << ','; - experimentFS << " Sensitivity " << statData.m_Sensitivity << ','; - experimentFS << " DICE " << statData.m_DICE << ','; - experimentFS << " RMSE " << statData2.m_RMSD << ','; - experimentFS << std::endl; - } - - if (outputFolder != "") - { - std::cout << "Saving files to " << outputFolder << std::endl; - mitk::DiffusionCollectionWriter::ExportCollectionToFolder(testCollection, outputFolder); - } - - return EXIT_SUCCESS; -} diff --git a/Modules/TumorInvasionAnalysis/MiniApps/TumorProgressionMapping.cpp b/Modules/TumorInvasionAnalysis/MiniApps/TumorProgressionMapping.cpp deleted file mode 100644 index 45d832b4a8..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/TumorProgressionMapping.cpp +++ /dev/null @@ -1,550 +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. - -============================================================================*/ -// MITK -#include -#include -#include -#include -#include -#include -#include -#include - -// ITK -#include "itkImageDuplicator.h" -#include "itkPermuteAxesImageFilter.h" -#include "itkTileImageFilter.h" -#include -#include -#include -#include -#include - -#include -#include -// VTK -#include -#include -#include -#include -#include - -// MITK -#include - -#include "itkRescaleIntensityImageFilter.h" - -#include - -using namespace std; - -typedef unsigned short PixelType; -typedef double InputPixelType; -typedef itk::Image, 2> RGB2DImage; -typedef itk::RGBPixel RGBPixelType; - -typedef std::vector FileList; -typedef std::vector ImageList; - -/// Create list of all files in provided folder ending with same postfix -static FileList CreateFileList(std::string folder, std::string postfix) -{ - itk::Directory::Pointer dir = itk::Directory::New(); - FileList fileList; - - if (dir->Load(folder.c_str())) - { - int n = dir->GetNumberOfFiles(); - for (int r = 0; r < n; r++) - { - std::string filename = dir->GetFile(r); - if (filename == "." || filename == "..") - continue; - filename = folder + filename; - if (!itksys::SystemTools::FileExists(filename.c_str())) - continue; - - if (postfix.compare(filename.substr(filename.length() - postfix.length())) == 0) - fileList.push_back(filename); - } - } - std::sort(fileList.begin(), fileList.end()); - return fileList; -} - -class mitkProgressionVisualization -{ -public: - mitkProgressionVisualization() {} - /** - * @brief ConvertToRGBImage converts a gray image to RGB by filling all three channels with the gray intensity - * @param grayImage - * @return - */ - mitk::Image::Pointer ConvertToRGBImage(mitk::Image::Pointer grayImage) - { - mitk::Image::Pointer rgbImage = mitk::Image::New(); - unsigned int *dim = grayImage->GetDimensions(); - rgbImage->Initialize(mitk::MakePixelType(), 3, dim); - rgbImage->SetGeometry(grayImage->GetGeometry()); - - itk::Image::Pointer itkGrayImage = itk::Image::New(); - mitk::CastToItkImage(grayImage, itkGrayImage); - - mitk::ImagePixelWriteAccessor writeAcc(rgbImage); - - typedef itk::RescaleIntensityImageFilter, itk::Image> RescaleFilterType; - RescaleFilterType::Pointer rescaleFilter = RescaleFilterType::New(); - rescaleFilter->SetInput(itkGrayImage); - rescaleFilter->SetOutputMinimum(0); - rescaleFilter->SetOutputMaximum(255 * 255); - rescaleFilter->Update(); - - itk::Index<3> idx; - RGBPixelType value; - - // Fill rgb image with gray values - for (idx[2] = 0; (unsigned int)idx[2] < dim[2]; idx[2]++) - { - for (idx[1] = 0; (unsigned int)idx[1] < dim[1]; idx[1]++) - { - for (idx[0] = 0; (unsigned int)idx[0] < dim[0]; idx[0]++) - { - value.Fill(rescaleFilter->GetOutput()->GetPixel(idx)); - writeAcc.SetPixelByIndex(idx, value); - } - } - } - return rgbImage; - } - - RGB2DImage::Pointer TextAsImage(std::string text) - { - vtkSmartPointer textImage = vtkSmartPointer::New(); - vtkSmartPointer freetype = vtkSmartPointer::New(); - vtkSmartPointer prop = vtkSmartPointer::New(); - float color[3] = {1, 1, 1}; - float opacity = 1.0; - prop->SetColor(color[0], color[1], color[2]); - prop->SetFontSize(40); - prop->SetOpacity(opacity); - textImage->AllocateScalars(VTK_UNSIGNED_SHORT, 3); - freetype->RenderString(prop, vtkUnicodeString::from_utf8(text.c_str()), 72, textImage); - textImage->Modified(); - - int *extent = textImage->GetExtent(); - - RGB2DImage::Pointer itkImage = RGB2DImage::New(); - - RGB2DImage::IndexType start; - start.Fill(0); - RGB2DImage::SizeType size; - size[0] = extent[1]; - size[1] = extent[3]; - size[2] = 0; - - RGB2DImage::RegionType region(start, size); - itkImage->SetRegions(region); - itkImage->Allocate(); - RGB2DImage::IndexType idx; - - for (unsigned int y = 0; y < size[1]; y++) - { - for (unsigned int x = 0; x < size[0]; x++) - { - PixelType *pixel = static_cast(textImage->GetScalarPointer(x, y, 0)); - RGBPixelType values; - values.Fill(0); - values[0] = pixel[1]; - values[1] = pixel[1]; - values[2] = pixel[1]; - idx.Fill(0); - idx[0] = x; - idx[1] = y; - - itkImage->SetPixel(idx, values); - } - } - - typedef itk::PermuteAxesImageFilter PermuteAxesImageFilterType; - - itk::FixedArray order; - order[0] = 1; - order[1] = 0; - - PermuteAxesImageFilterType::Pointer permuteAxesFilter = PermuteAxesImageFilterType::New(); - permuteAxesFilter->SetInput(itkImage); - permuteAxesFilter->SetOrder(order); - permuteAxesFilter->Update(); - - RGB2DImage::Pointer itkResultImage = RGB2DImage::New(); - itkResultImage->SetRegions(region); - itkResultImage->Allocate(); - - itkResultImage->Graft(permuteAxesFilter->GetOutput()); - - return itkResultImage; - } - - /** - * @brief AddColouredOverlay - Overlays the rgbImage with an coloured overlay - * - * For all positions in overlayImage not zero, its value is multiplied the the colour value and added - * to the rgbImage. - * - * @param rgbImage - input rgbImage to which the coloured overlay is added - * @param overlayImage - * @param color - */ - void AddColouredOverlay(mitk::Image::Pointer rgbImage, mitk::Image::Pointer overlayImage, mitk::Color color) - { - unsigned int *dim = rgbImage->GetDimensions(); - itk::Image::Pointer itkOverlayImage = itk::Image::New(); - mitk::CastToItkImage(overlayImage.GetPointer(), itkOverlayImage); - mitk::ImagePixelWriteAccessor writeAcc(rgbImage); - - itk::Index<3> idx; - itk::RGBPixel value; - unsigned short overlayVal = 0; - // Fill rgb image with gray values - for (idx[2] = 0; (unsigned int)idx[2] < dim[2]; idx[2]++) - { - for (idx[1] = 0; (unsigned int)idx[1] < dim[1]; idx[1]++) - { - for (idx[0] = 0; (unsigned int)idx[0] < dim[0]; idx[0]++) - { - overlayVal = 255 * itkOverlayImage->GetPixel(idx); - value = writeAcc.GetPixelByIndex(idx); - value[0] = std::min((int)(value[0] + overlayVal * color[0]), 254 * 255); - value[1] = std::min((int)(value[1] + overlayVal * color[1]), 254 * 255); - value[2] = std::min((int)(value[2] + overlayVal * color[2]), 254 * 255); - writeAcc.SetPixelByIndex(idx, value); - } - } - } - } - - itk::Image, 2>::Pointer ExtractSlice( - itk::Image, 3>::Pointer itkImage, unsigned int sliceNo) - { - typedef itk::Image InputImageType; - typedef itk::Image OutputImageType; - - int dim[3]; - dim[0] = itkImage->GetLargestPossibleRegion().GetSize()[0]; - dim[1] = itkImage->GetLargestPossibleRegion().GetSize()[1]; - dim[2] = itkImage->GetLargestPossibleRegion().GetSize()[2]; - - itk::Index<3> desiredStart; - itk::Size<3> desiredSize; - - // case AXIAL: // 3rd dimension fixed - desiredStart.Fill(0); - desiredStart[2] = sliceNo; - desiredSize.Fill(0); - desiredSize[0] = dim[0]; - desiredSize[1] = dim[1]; - desiredSize[2] = 0; - - itk::ImageRegion<3> desiredRegion(desiredStart, desiredSize); - - // Extract slice - itk::ExtractImageFilter::Pointer extractSlice = - itk::ExtractImageFilter::New(); - extractSlice->SetInput(itkImage); - extractSlice->SetExtractionRegion(desiredRegion); - extractSlice->SetDirectionCollapseToIdentity(); - extractSlice->Update(); - - return extractSlice->GetOutput(); - } -}; - -static std::string GetName(std::string fileName, std::string suffix = "_T2.nrrd") -{ - fileName = itksys::SystemTools::GetFilenameName(fileName); - return fileName.substr(0, fileName.length() - suffix.length() - 11); // 10 = date length -} - -static std::string GetDate(std::string fileName, std::string suffix = "_T2.nrrd") -{ - fileName = itksys::SystemTools::GetFilenameName(fileName); - fileName = fileName.substr(fileName.length() - suffix.length() - 10, 10); // 10 = date length - return fileName; -} - -static ImageList LoadPreprocessedFiles(FileList files) -{ - ImageList images; - for (unsigned int i = 0; i < files.size(); ++i) - { - images.push_back(mitk::IOUtil::Load(files.at(i))); - } - return images; -} - -int main(int argc, char *argv[]) -{ - // Parse Command-Line Arguments - mitkCommandLineParser parser; - parser.setArgumentPrefix("--", "-"); - - parser.setTitle("Tumor Progression Mapping"); - parser.setCategory("Preprocessing Tools"); - parser.setContributor("German Cancer Research Center (DKFZ)"); - parser.setDescription("Convert a set of co-registered and resampled follow-up images into a 2D png overview (and " - "optionally in a 4D NRRD Volume).\nNaming convecntion of files is " - "IDENTIFIER_YYYY-MM-DD_MODALITY.nrrd"); - - parser.setArgumentPrefix("--", "-"); - parser.addArgument("input", "i", mitkCommandLineParser::Directory, "Input folder containing all follow ups", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument("output", "o", mitkCommandLineParser::File, "Output file (PNG)", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument("blanked", "b", mitkCommandLineParser::Bool, "Only Display Morphology"); - parser.addArgument("morphology", "m", mitkCommandLineParser::String, "Morphology postfix.", "_T2.nrrd"); - parser.addArgument( - "segmentation", "s", mitkCommandLineParser::String, "Segmentation postfix. Default: _GTV.nrrd", "_GTV.nrrd"); - parser.addArgument("4dVolume", "v", mitkCommandLineParser::File, "Filepath to merged 4d NRRD Volume.", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument( - "skip", "k", mitkCommandLineParser::Int, "Number of slices to be skipped from top and from button (Default 0)"); - parser.addArgument( - "interval", "n", mitkCommandLineParser::Int, "1 - for all slices, 2 - every second, 3 - every third ..."); - parser.addArgument("opacity", "c", mitkCommandLineParser::Float, "Opacity of overlay [0,1] invisible -> visible"); - - map parsedArgs = parser.parseArguments(argc, argv); - - if (parsedArgs.size() == 0) - return EXIT_SUCCESS; - - // Show a help message - if (parsedArgs.count("help") || parsedArgs.count("h")) - { - std::cout << parser.helpText(); - return EXIT_SUCCESS; - } - - std::string outputFile; - std::string inputFolder; - - if (parsedArgs.count("input") || parsedArgs.count("i")) - { - inputFolder = us::any_cast(parsedArgs["input"]) + "/"; - } - - if (parsedArgs.count("output") || parsedArgs.count("o")) - { - outputFile = us::any_cast(parsedArgs["output"]); - } - - int skip = 0; - int interval = 1; - float opacity = .3; - - if (parsedArgs.count("skip") || parsedArgs.count("k")) - { - skip = us::any_cast(parsedArgs["skip"]); - } - - if (parsedArgs.count("interval") || parsedArgs.count("n")) - { - interval = us::any_cast(parsedArgs["interval"]); - } - - if (parsedArgs.count("opacity") || parsedArgs.count("c")) - { - opacity = us::any_cast(parsedArgs["opacity"]); - } - - FileList morphFiles; - FileList segFiles; - - std::string refPattern; - std::string segPattern; - - if (parsedArgs.count("morphology") || parsedArgs.count("m")) - { - refPattern = us::any_cast(parsedArgs["morphology"]); - } - else - return EXIT_FAILURE; - - if (parsedArgs.count("segmentation") || parsedArgs.count("s")) - { - segPattern = us::any_cast(parsedArgs["segmentation"]); - } - - bool blank = false; - if (parsedArgs.count("blanked") || parsedArgs.count("b")) - { - blank = true; - } - /// END Parsing CL Options - typedef itk::Image OutputImageType; - typedef itk::Image InputImageType; - - mitkProgressionVisualization progressVis; - - morphFiles = CreateFileList(inputFolder, refPattern); - segFiles = CreateFileList(inputFolder, segPattern); - - ImageList morphImages = LoadPreprocessedFiles(morphFiles); - ImageList segImages; - if (segFiles.size() > 0 && blank == false) - segImages = LoadPreprocessedFiles(segFiles); - - mitk::Image::Pointer rgbImage; - - // define color for overlay image - mitk::Color color; - color.Fill(0); - color[0] = 200 * opacity; - color[1] = 0; - - // Set up itk time image filter to contain 0..N-1 images - itk::TileImageFilter::Pointer tileFilter = - itk::TileImageFilter::New(); - itk::FixedArray layout; - unsigned int noOfTimeSteps = morphImages.size(); - layout[0] = noOfTimeSteps; - layout[1] = 0; // automatic number of neccessary rows - tileFilter->SetLayout(layout); - - // Get Reference image (all images are expected to have exact same dimensions!) - - std::string fileName = morphFiles.at(0); - mitk::Image *referenceImg = morphImages.at(0); - - mitk::Image::Pointer merged4D; - std::string volumeFile; - - if (parsedArgs.count("4dVolume") || parsedArgs.count("v")) - { - volumeFile = us::any_cast(parsedArgs["4dVolume"]); - if (volumeFile != "") - { - unsigned int *dims = new unsigned int[4]; - dims[0] = referenceImg->GetDimensions()[0]; - dims[1] = referenceImg->GetDimensions()[1]; - dims[2] = referenceImg->GetDimensions()[2]; - dims[3] = morphImages.size(); - merged4D = mitk::Image::New(); - merged4D->Initialize(referenceImg->GetPixelType(), 4, dims); - merged4D->GetTimeGeometry()->Expand(noOfTimeSteps); - } - } - - unsigned int *dim = referenceImg->GetDimensions(); - unsigned int sliceMaxAxial = dim[2]; - - // Now iterate over all data sets, extract overlay and add it to reference image - mitk::Image *morphImage; - mitk::Image *segmentationImage = nullptr; - - for (unsigned int i = 0; i < noOfTimeSteps; i++) - { - MITK_INFO << "File : " << i << " of /" << noOfTimeSteps; - int currentSliceNo = 0; - - // Retrieve images of current time step - fileName = morphFiles.at(i); - morphImage = morphImages.at(i); - - // Create 4D Volume image - if (volumeFile != "") - { - mitk::ImagePixelReadAccessor readAc(morphImage); - - merged4D->GetGeometry(i)->SetSpacing(referenceImg->GetGeometry()->GetSpacing()); - merged4D->GetGeometry(i)->SetOrigin(referenceImg->GetGeometry()->GetOrigin()); - merged4D->GetGeometry(i)->SetIndexToWorldTransform(referenceImg->GetGeometry()->GetIndexToWorldTransform()); - merged4D->SetVolume(readAc.GetData(), i); - } - - MITK_INFO << "-- Convert to RGB"; - rgbImage = progressVis.ConvertToRGBImage(morphImage); - - // Add current seg in red - color.Fill(0); - color[0] = 200 * opacity; - - if (!blank) - { - segmentationImage = segImages.at(i); - if (segmentationImage != nullptr) - { - MITK_INFO << "-- Add Overlay"; - progressVis.AddColouredOverlay(rgbImage, segmentationImage, color); - } - } - // Add Segmentation of next time step in red - if (i == 0) - { - MITK_INFO << "Skipping retro view in first time step"; - } - else - { - color.Fill(0); - // Add previous in green - color[1] = 200 * opacity; - if (!blank) - { - mitk::Image *nextSeg = segImages.at(i - 1); - MITK_INFO << "-- Add Overlay of next Step"; - progressVis.AddColouredOverlay(rgbImage, nextSeg, color); - } - } - - // Now save all slices from overlay in output folder - MITK_INFO << "-- Extract Slices"; - for (int slice = sliceMaxAxial - skip - 1; slice > skip; slice -= interval) // sliceMaxAxial/40.0f)) - { - InputImageType::Pointer itkImage = InputImageType::New(); - InputImageType::Pointer itkImage2; - - mitk::CastToItkImage(rgbImage, itkImage); - typedef itk::ImageDuplicator DuplicatorType; - DuplicatorType::Pointer duplicator = DuplicatorType::New(); - duplicator->SetInputImage(itkImage); - duplicator->Update(); - itkImage2 = duplicator->GetOutput(); - - itk::Image::Pointer extractedSlice = itk::Image::New(); - extractedSlice->Graft(progressVis.ExtractSlice(itkImage2, slice)); - tileFilter->SetInput(((currentSliceNo + 1) * (noOfTimeSteps) + i), extractedSlice); - - tileFilter->SetInput(i, progressVis.TextAsImage(GetDate(fileName))); - - currentSliceNo++; - } - } - - MITK_INFO << "Tile Filter Update"; - tileFilter->Update(); - - // Write the output image - typedef itk::ImageFileWriter WriterType; - WriterType::Pointer writer = WriterType::New(); - writer->SetInput(tileFilter->GetOutput()); - std::string patientName; - - patientName = GetName(fileName); - - if (blank) - writer->SetFileName(outputFile); - else - writer->SetFileName(outputFile); - - writer->Update(); - if (volumeFile != "") - mitk::IOUtil::Save(merged4D, volumeFile); - - return EXIT_SUCCESS; -} diff --git a/Modules/TumorInvasionAnalysis/MiniApps/TumorResponseEvaluationTool.cpp b/Modules/TumorInvasionAnalysis/MiniApps/TumorResponseEvaluationTool.cpp deleted file mode 100644 index 9ace8b1448..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/TumorResponseEvaluationTool.cpp +++ /dev/null @@ -1,262 +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. - -============================================================================*/ - -// MITK - DataCollection -#include -#include -#include -#include - -#include "mitkDataCollectionImageIterator.h" -#include -#include -// CTK -#include "mitkCommandLineParser.h" -// ITK -#include - -using namespace std; - -int main(int argc, char *argv[]) -{ - // Setup CLI Module parsable interface - mitkCommandLineParser parser; - parser.setTitle("Tumor Invasion Analysis"); - parser.setCategory("Tumor Analysis"); - parser.setDescription("Learns and predicts Invasion behavior"); - parser.setContributor("German Cancer Research Center (DKFZ)"); - - parser.setArgumentPrefix("--", "-"); - // Add command line argument names - parser.addArgument("help", "h", mitkCommandLineParser::Bool, "Show options"); - parser.addArgument("loadFile", "l", mitkCommandLineParser::File, "DataCollection File", "", us::Any(), false, false, false, mitkCommandLineParser::Input); - parser.addArgument( - "colIds", "c", mitkCommandLineParser::String, "Patient Identifiers from DataCollection used for training"); - parser.addArgument( - "testId", "t", mitkCommandLineParser::String, "Patient Identifier from DataCollection used for testing"); - parser.addArgument("features", "b", mitkCommandLineParser::String, "Features"); - parser.addArgument("stats", "s", mitkCommandLineParser::String, "Output file for stats"); - parser.addArgument("ratio", "q", mitkCommandLineParser::Float, "ratio of tumor to healthy"); - parser.addArgument("treeDepth", "d", mitkCommandLineParser::Int, "limits tree depth"); - parser.addArgument("forestSize", "f", mitkCommandLineParser::Int, "number of trees"); - parser.addArgument("configName", "n", mitkCommandLineParser::String, "human readable name for configuration"); - parser.addArgument("output", "o", mitkCommandLineParser::Directory, "output folder for results", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - parser.addArgument("forest", "t", mitkCommandLineParser::File, "store trained forest to file", "", us::Any(), false, false, false, mitkCommandLineParser::Output); - - map parsedArgs = parser.parseArguments(argc, argv); - // Show a help message - if (parsedArgs.size() == 0) - return EXIT_SUCCESS; - if (parsedArgs.count("help") || parsedArgs.count("h")) - { - std::cout << parser.helpText(); - return EXIT_SUCCESS; - } - - // Default values - float ratio = 1.0; - bool useStatsFile = false; - unsigned int forestSize = 250; - unsigned int treeDepth = 0; - std::string configName = ""; - std::string outputFolder = ""; - std::string forestFile = ""; - - std::vector features; - std::vector trainingIds; - std::vector testingIds; - std::vector loadIds; // features + masks needed for training and evaluation - std::string outputFile; - std::string xmlFile; - std::ofstream experimentFS; - - // Parse input parameters - { - if (parsedArgs.count("colIds") || parsedArgs.count("c")) - { - std::istringstream ss(us::any_cast(parsedArgs["colIds"])); - std::string token; - - while (std::getline(ss, token, ',')) - trainingIds.push_back(token); - } - - if (parsedArgs.count("output") || parsedArgs.count("o")) - { - outputFolder = us::any_cast(parsedArgs["output"]); - } - - if (parsedArgs.count("configName") || parsedArgs.count("n")) - { - configName = us::any_cast(parsedArgs["configName"]); - } - - if (parsedArgs.count("features") || parsedArgs.count("b")) - { - std::istringstream ss(us::any_cast(parsedArgs["features"])); - std::string token; - - while (std::getline(ss, token, ',')) - features.push_back(token); - } - - if (parsedArgs.count("treeDepth") || parsedArgs.count("d")) - { - treeDepth = us::any_cast(parsedArgs["treeDepth"]); - } - - if (parsedArgs.count("ratio") || parsedArgs.count("q")) - { - ratio = us::any_cast(parsedArgs["ratio"]); - } - - if (parsedArgs.count("forestSize") || parsedArgs.count("f")) - { - forestSize = us::any_cast(parsedArgs["forestSize"]); - } - - if (parsedArgs.count("stats") || parsedArgs.count("s")) - { - useStatsFile = true; - experimentFS.open(us::any_cast(parsedArgs["stats"]).c_str(), std::ios_base::app); - } - - if (parsedArgs.count("forest") || parsedArgs.count("t")) - { - forestFile = us::any_cast(parsedArgs["stats"]); - } - - if (parsedArgs.count("testId") || parsedArgs.count("t")) - { - std::istringstream ss(us::any_cast(parsedArgs["testId"])); - std::string token; - - while (std::getline(ss, token, ',')) - testingIds.push_back(token); - } - - for (unsigned int i = 0; i < features.size(); i++) - { - loadIds.push_back(features.at(i)); - } - loadIds.push_back("GTV"); - loadIds.push_back("BRAINMASK"); - loadIds.push_back("TARGET"); - - if (parsedArgs.count("stats") || parsedArgs.count("s")) - { - outputFile = us::any_cast(parsedArgs["stats"]); - } - - if (parsedArgs.count("loadFile") || parsedArgs.count("l")) - { - xmlFile = us::any_cast(parsedArgs["loadFile"]); - } - else - { - MITK_ERROR << parser.helpText(); - return EXIT_FAILURE; - } - } - - mitk::DataCollection::Pointer trainCollection; - mitk::DataCollection::Pointer testCollection; - { - mitk::DiffusionCollectionReader colReader; - // Load only relevant images - colReader.SetDataItemNames(loadIds); - colReader.AddSubColIds(testingIds); - testCollection = colReader.LoadCollection(xmlFile); - colReader.ClearDataElementIds(); - colReader.ClearSubColIds(); - colReader.SetDataItemNames(loadIds); - colReader.AddSubColIds(trainingIds); - trainCollection = colReader.LoadCollection(xmlFile); - } - - std::cout << "Setup Training" << std::endl; - mitk::TumorInvasionClassification classifier; - - classifier.SetClassRatio(ratio); - classifier.SamplesWeightingActivated(true); - classifier.PrepareResponseSamples(trainCollection); - // Learning stage - std::cout << "Start Training" << std::endl; - classifier.LearnProgressionFeatures(trainCollection, features, forestSize, treeDepth); - - if (forestFile != "") - classifier.SaveRandomForest(forestFile); - - std::cout << "Start Predict" << std::endl; - classifier.PredictInvasion(testCollection, features); - - if (outputFolder != "") - { - std::cout << "Saving files to " << outputFolder << std::endl; - mitk::DiffusionCollectionWriter::ExportCollectionToFolder(trainCollection, "/tmp/dumple"); - } - - /* prepare target values to match training values: - * 0 - excluded (e.g. out of brainmask) - * 1 - no involvement (healthy all the time) - * 2 - formerly healthy, now tumor (rezivid) - * 3 - formerly tumor, now necroses (responsive) - */ - - { - mitk::DataCollectionImageIterator gtvIter(testCollection, "GTV"); - mitk::DataCollectionImageIterator targetIt(testCollection, "TARGET"); - - while (!gtvIter.IsAtEnd()) - { - if (targetIt.GetVoxel() == 0 && gtvIter.GetVoxel() == 0) - targetIt.SetVoxel(1); - - if (targetIt.GetVoxel() == 0 && gtvIter.GetVoxel() == 1) - targetIt.SetVoxel(3); - - if (targetIt.GetVoxel() == 1 && gtvIter.GetVoxel() == 0) - targetIt.SetVoxel(2); - - targetIt++; - gtvIter++; - } - } - - mitk::CollectionStatistic stats; - mitk::ProgressionValueToIndexMapper progressionValueToIndexMapper; - mitk::BinaryValueToIndexMapper binaryValueToIndexMapper; - - stats.SetCollection(testCollection); - stats.SetClassCount(4); - stats.SetGoldName("TARGET"); - stats.SetTestName("RESULT"); - stats.SetMaskName("BRAINMASK"); - stats.SetGroundTruthValueToIndexMapper(&binaryValueToIndexMapper); - stats.SetTestValueToIndexMapper(&binaryValueToIndexMapper); - - stats.Update(); - std::ostringstream outStr; - stats.Print(outStr, std::cout, true); - std::cout << std::endl << std::endl << outStr.str() << std::endl; - - if (useStatsFile) - std::cout << "dummy" << std::endl; - - if (outputFolder != "") - { - std::cout << "Saving files to " << outputFolder << std::endl; - mitk::DiffusionCollectionWriter::ExportCollectionToFolder(testCollection, outputFolder); - } - - return EXIT_SUCCESS; -} diff --git a/Modules/TumorInvasionAnalysis/MiniApps/typeExtension.h b/Modules/TumorInvasionAnalysis/MiniApps/typeExtension.h deleted file mode 100644 index eff3e5398d..0000000000 --- a/Modules/TumorInvasionAnalysis/MiniApps/typeExtension.h +++ /dev/null @@ -1,55 +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. - -============================================================================*/ - -// MITK -#include -#include -#include -#include - -// ITK -#include - -namespace mitk -{ - typedef itk::Image, 3> itkImageRGBUS3; - - template void _CastToItkImage2Access(const itkImageRGBUS3 *, itk::SmartPointer &); - - template - void _CastToItkImage2Access(const itk::Image *itkInputImage, - itk::SmartPointer &itkOutputImage) - { - typedef itk::Image ItkInputImageType; - if (typeid(ItkInputImageType) == typeid(ItkOutputImageType)) - { - itkOutputImage = const_cast(reinterpret_cast(itkInputImage)); - return; - } - typedef itk::CastImageFilter CastImageFilterType; - typename CastImageFilterType::Pointer castImageFilter = CastImageFilterType::New(); - castImageFilter->SetInput(itkInputImage); - castImageFilter->Update(); - itkOutputImage = castImageFilter->GetOutput(); - } - - template <> - void CastToItkImage(const mitk::Image *mitkImage, itk::SmartPointer &itkOutputImage) - { - typedef itkImageRGBUS3 ItkOutputImageType; - AccessFixedTypeByItk_1(mitkImage, - _CastToItkImage2Access, - (itk::RGBPixel), - (ItkOutputImageType::ImageDimension), - itkOutputImage); - } -} diff --git a/Modules/TumorInvasionAnalysis/files.cmake b/Modules/TumorInvasionAnalysis/files.cmake deleted file mode 100644 index a757fcc18b..0000000000 --- a/Modules/TumorInvasionAnalysis/files.cmake +++ /dev/null @@ -1,9 +0,0 @@ -file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*") - -SET(CPP_FILES - ReaderWriter/mitkDiffusionCollectionReader.cpp - ReaderWriter/mitkDiffusionCollectionWriter.cpp - Classification/mitkTumorInvasionClassification.cpp - ImageFilters/mitkCollectionDilatation.cpp - ImageFilters/mitkCollectionGrayOpening.cpp -) diff --git a/Modules/TumorInvasionAnalysis/include/itkConnectednessFilter.cxx b/Modules/TumorInvasionAnalysis/include/itkConnectednessFilter.cxx deleted file mode 100644 index cf5d4e4a3e..0000000000 --- a/Modules/TumorInvasionAnalysis/include/itkConnectednessFilter.cxx +++ /dev/null @@ -1,479 +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. - -============================================================================*/ - -#ifndef __ConnectednessFilter_hxx -#define __ConnectednessFilter_hxx - -#ifdef _MSC_VER -# pragma warning(disable : 4996) -#endif - -#include "itkConnectednessFilter.h" -#include "itkImageRegionConstIterator.h" -#include "itkImageRegionIterator.h" -#include "itkObjectFactory.h" -#include -// Vector Fields -#include "itkVectorImage.h" -#include -// -#include "itkConstantBoundaryCondition.h" -#include "itkNeighborhoodIterator.h" - -namespace itk -{ - template - void ConnectednessFilter::SetInputImage(const TFeatureImage *image) - { - this->SetNthInput(0, const_cast(image)); - } - - template - void ConnectednessFilter::SetInputSeed(const TSeedImage *image) - { - this->SetNthInput(1, const_cast(image)); - } - - template - void ConnectednessFilter::SetInputMask(const TSeedImage *image) - { - this->SetNthInput(2, const_cast(image)); - } - - template - void ConnectednessFilter::SetInputVectorFieldConfidenceMap( - const TFeatureImage *conf) - { - // DO NOT set it as nth input, since it is dti derived and therefore does - // not necessarily occupy the same space as the other images - m_ConfidenceImage = const_cast(conf); - } - - template - void ConnectednessFilter::SetPropagationImage(const TFeatureImage *image) - { - this->SetNthInput(3, const_cast(image)); - } - - template - typename TFeatureImage::Pointer ConnectednessFilter::GetDistanceImage() - { - return m_DistanceImage; - } - - template - typename TFeatureImage::Pointer - ConnectednessFilter::GetEuclideanDistanceImage() - { - return m_EuclideanDistance; - } - - template - void ConnectednessFilter::SetInputVectorField(const TTensorImage *vecs) - { - // DO NOT set it as nth input, since it is dti derived and therefore does - // not necessary occupy the same space as the other images - m_TensorImage = const_cast(vecs); - } - - template - void ConnectednessFilter::GenerateData() - { - const char untouchedValue = -10; - const char inListValue = -30; - // Get Inputs - m_InputImage = dynamic_cast(this->ProcessObject::GetInput(0)); - typename TSeedImage::Pointer seed = dynamic_cast(this->ProcessObject::GetInput(1)); - typename TSeedImage::Pointer mask = dynamic_cast(this->ProcessObject::GetInput(2)); - typename TFeatureImage::Pointer propagationImage = dynamic_cast(this->ProcessObject::GetInput(3)); - - if (propagationImage.IsNull()) - propagationImage = m_InputImage; - - // --- - // Allocate Output - typename TFeatureImage::Pointer output = this->GetOutput(); - output->SetRegions(m_InputImage->GetLargestPossibleRegion()); - output->Allocate(); - output->FillBuffer(untouchedValue); - - m_DistanceImage = TFeatureImage::New(); - m_DistanceImage->SetRegions(m_InputImage->GetLargestPossibleRegion()); - m_DistanceImage->Allocate(); - m_DistanceImage->FillBuffer(untouchedValue); - m_DistanceImage->SetOrigin(m_InputImage->GetOrigin()); - m_DistanceImage->SetDirection(m_InputImage->GetDirection()); - m_DistanceImage->SetSpacing(m_InputImage->GetSpacing()); - - m_EuclideanDistance = TFeatureImage::New(); - m_EuclideanDistance->SetRegions(m_InputImage->GetLargestPossibleRegion()); - m_EuclideanDistance->Allocate(); - m_EuclideanDistance->FillBuffer(0.0); - m_EuclideanDistance->SetOrigin(m_InputImage->GetOrigin()); - m_EuclideanDistance->SetDirection(m_InputImage->GetDirection()); - m_EuclideanDistance->SetSpacing(m_InputImage->GetSpacing()); - - // Helper Object - Indicates which voxels are currently in the FIFO, - // this prevents excessive memory and comptutational overhead - typename TFeatureImage::Pointer activeSeeds = TFeatureImage::New(); - activeSeeds->SetRegions(m_InputImage->GetLargestPossibleRegion()); - activeSeeds->Allocate(); - activeSeeds->FillBuffer(untouchedValue); - - // Create Iterators - SeedIteratorType seedIt(seed, seed->GetLargestPossibleRegion()); - FeatureIteratorType outIt(output, output->GetLargestPossibleRegion()); - FeatureIteratorType inputIt(m_InputImage, m_InputImage->GetLargestPossibleRegion()); - - // Set up Neighborhood Iterator to use a 3x3x3 neighborhood - typename itk::NeighborhoodIterator::RadiusType radius; - radius.Fill(1); - radius[2] = 1; - - typename itk::NeighborhoodIterator neighbIt(radius, seed, seed->GetRequestedRegion()); - typename itk::NeighborhoodIterator medianIt( - radius, propagationImage, propagationImage->GetRequestedRegion()); - - // Copy Input Image values from SeedRegion values into Output Image - // Collect border voxel indices to initialize seed list - typedef std::list ContainerType; - ContainerType fifo; - while (!seedIt.IsAtEnd()) - { - if (seedIt.Get() != 0) - { - outIt.Set(inputIt.Get()); - if (activeSeeds->GetPixel(seedIt.GetIndex()) == untouchedValue) - { - neighbIt.SetLocation(seedIt.GetIndex()); - for (unsigned int i = 0; i < neighbIt.Size(); ++i) - { - bool isInside = true; - neighbIt.GetPixel(i, isInside); - if (!isInside) - continue; - if (neighbIt.GetPixel(i) == 0) // border voxel - { - // add index of border voxel into FIFO - fifo.push_back(seedIt.GetIndex()); - activeSeeds->SetPixel(seedIt.GetIndex(), inListValue); - // write propagation value into output image - - if (m_ApplyRankFilter) - { - // Calculate median in 3x3x3 neighborhood and use this value to propagate - medianIt.SetLocation(seedIt.GetIndex()); - std::vector samples; - for (unsigned int j = 0; j < medianIt.Size(); ++j) - { - if (seed->GetPixel(medianIt.GetIndex(j)) != 0) // inside seed region - samples.push_back(medianIt.GetPixel(j)); - } - std::sort(samples.begin(), samples.end()); - - output->SetPixel(seedIt.GetIndex(), samples.at(samples.size() / 2)); - } - else - output->SetPixel(seedIt.GetIndex(), propagationImage->GetPixel(seedIt.GetIndex())); - - m_DistanceImage->SetPixel(seedIt.GetIndex(), 0); - break; - } - } - } - } - - ++inputIt; - ++outIt; - ++seedIt; - } - // - // Now iterate over items in fifo and check all possible paths starting from these indices - // to their neighbors and mark those with lowest cost - while (!fifo.empty()) - { - IndexType index = fifo.front(); - fifo.pop_front(); - // mark voxel as no longer present in fifo - activeSeeds->SetPixel(index, untouchedValue); - - if (mask->GetPixel(index) == 0) - continue; - - neighbIt.SetLocation(index); - - FeaturePixelType currDistance = m_DistanceImage->GetPixel(index); - FeaturePixelType currEuclidDistance = m_EuclideanDistance->GetPixel(index); - FeaturePixelType propagateValue = output->GetPixel(index); - - // compute cost to get to each neighborhood voxel - // if we find a lower way to a neighbor voxel, that voxel gets appended to the fifo - for (unsigned int i = 0; i < neighbIt.Size(); ++i) - { - bool isInside = true; - neighbIt.GetPixel(i, isInside); - if (!isInside || mask->GetPixel(neighbIt.GetIndex(i)) == 0) // || seed->GetPixel(neighbIt.GetIndex(i)) != 0) - continue; - - if (i == neighbIt.Size() / 2) // skip center voxel - continue; - - FeaturePixelType cost = GetDistanceValue(index, neighbIt.GetIndex(i)); - if (cost == -1) - continue; - if (currDistance + cost < m_DistanceImage->GetPixel(neighbIt.GetIndex(i)) || - m_DistanceImage->GetPixel(neighbIt.GetIndex(i)) == untouchedValue) - { - m_DistanceImage->SetPixel(neighbIt.GetIndex(i), currDistance + cost); - - // Compute Euclidean distance between indices - FeaturePixelType eDist = - sqrt(std::pow(index[0] - neighbIt.GetIndex(i)[0], 2) * m_InputImage->GetSpacing()[0] + - std::pow(index[1] - neighbIt.GetIndex(i)[1], 2) * m_InputImage->GetSpacing()[1] + - std::pow(index[2] - neighbIt.GetIndex(i)[2], 2) * m_InputImage->GetSpacing()[2]); - - m_EuclideanDistance->SetPixel(neighbIt.GetIndex(i), currEuclidDistance + eDist); - - output->SetPixel(neighbIt.GetIndex(i), propagateValue); - if (activeSeeds->GetPixel(neighbIt.GetIndex(i)) == untouchedValue) - { - fifo.push_back(neighbIt.GetIndex(i)); - activeSeeds->SetPixel(neighbIt.GetIndex(i), inListValue); - } - } - } - } - } - - template - double ConnectednessFilter::GetDistanceValue(IndexType idxStart, - IndexType idxEnd) - { - FeaturePixelType cost = 0; - - switch (m_Mode) - { - case (FeatureSimilarity): - { - cost = (-1 + exp(std::fabs(m_InputImage->GetPixel(idxStart) - m_InputImage->GetPixel(idxEnd)))); - break; - } - case (VectorAgreement): - { - // Rational - // Evaluate Confidence of Tensors (startIdx and endIdx), the higher the lower the cost - // Evaluate Path direction correspondence with tensor at start and end index - vnl_vector_fixed projection; - vnl_vector_fixed projectionEnd; - projection.fill(0); - projectionEnd.fill(0); - - itk::Point worldPosStart; - itk::Point worldPosEnd; - IndexTensorType tensorIdx; - IndexType featureIdxStart; - IndexTensorType tensorIdxEnd; - IndexType featureIdxEnd; - m_InputImage->TransformIndexToPhysicalPoint(idxStart, worldPosStart); - m_InputImage->TransformIndexToPhysicalPoint(idxEnd, worldPosEnd); - m_TensorImage->TransformPhysicalPointToIndex(worldPosStart, tensorIdx); - m_TensorImage->TransformPhysicalPointToIndex(worldPosEnd, tensorIdxEnd); - - m_ConfidenceImage->TransformPhysicalPointToIndex(worldPosStart, featureIdxStart); - m_ConfidenceImage->TransformPhysicalPointToIndex(worldPosEnd, featureIdxEnd); - - if (!m_TensorImage->GetLargestPossibleRegion().IsInside(tensorIdxEnd) || - !m_TensorImage->GetLargestPossibleRegion().IsInside(tensorIdx)) - return -1; - - if (m_ConfidenceImage->GetPixel(featureIdxStart) < .1) - return -1; - - vnl_vector_fixed direction; - direction[0] = (-worldPosStart[0] + worldPosEnd[0]); - direction[1] = (-worldPosStart[1] + worldPosEnd[1]); - direction[2] = (-worldPosStart[2] + worldPosEnd[2]); - - direction = direction.normalize(); - - TensorPixelType tensorEnd = m_TensorImage->GetPixel(tensorIdxEnd); - TensorPixelType tensorStart = m_TensorImage->GetPixel(tensorIdx); - - typename TensorPixelType::EigenValuesArrayType eigenvalues; - - tensorEnd.ComputeEigenValues(eigenvalues); - double maxEVEnd = std::fabs(eigenvalues[2]); - - tensorStart.ComputeEigenValues(eigenvalues); - double maxEVStart = std::fabs(eigenvalues[2]); - - if (maxEVEnd == 0.0) - maxEVEnd = 1; // no change then .. - // Normalize by largest EV - tensorEnd[0] /= maxEVEnd; - tensorEnd[1] /= maxEVEnd; - tensorEnd[2] /= maxEVEnd; - tensorEnd[3] /= maxEVEnd; - tensorEnd[4] /= maxEVEnd; - tensorEnd[5] /= maxEVEnd; - - if (maxEVStart == 0.0) - maxEVStart = 1; // no change then .. - // Normalize by largest EV - tensorStart[0] /= maxEVStart; - tensorStart[1] /= maxEVStart; - tensorStart[2] /= maxEVStart; - tensorStart[3] /= maxEVStart; - tensorStart[4] /= maxEVStart; - tensorStart[5] /= maxEVStart; - - /* Matrix Style - * | 0 1 2 | - * | X 3 4 | - * | X X 5 | - */ - // Multiply vector with tensor, and then take the magnitude of it. - projection[0] = direction[0] * tensorStart[0] + direction[1] * tensorStart[1] + direction[2] * tensorStart[2]; - projection[1] = direction[0] * tensorStart[1] + direction[1] * tensorStart[3] + direction[2] * tensorStart[4]; - projection[2] = direction[0] * tensorStart[2] + direction[1] * tensorStart[4] + direction[2] * tensorStart[5]; - - projectionEnd[0] = direction[0] * tensorEnd[0] + direction[1] * tensorEnd[1] + direction[2] * tensorEnd[2]; - projectionEnd[1] = direction[0] * tensorEnd[1] + direction[1] * tensorEnd[3] + direction[2] * tensorEnd[4]; - projectionEnd[2] = direction[0] * tensorEnd[2] + direction[1] * tensorEnd[4] + direction[2] * tensorEnd[5]; - - if (direction.magnitude() == 0.0 || projectionEnd.magnitude() == 0.0) - return -1; - - // Confidences higher than 1 are considered to be noise (due to the behavior of FA values derived from tensors - // with negative eigenvalues) - FeaturePixelType confStart = m_ConfidenceImage->GetPixel(featureIdxStart); - if (confStart > 1) - confStart = .1; - FeaturePixelType confEnd = m_ConfidenceImage->GetPixel(featureIdxEnd); - if (confEnd > 1) - confEnd = .1; - - // costs - cost = (1.1 - confStart) * (1.0 / sqrt(projection.magnitude())); - cost *= (1.1 - confEnd) * (1.0 / sqrt(projectionEnd.magnitude())); - - break; - } - case (FeatureVectorAgreement): - { - // Rational - // Evaluate Confidence of Tensors (startIdx and endIdx), the higher the lower the cost - // Evaluate Path direction correspondence with tensor at start and end index - vnl_vector_fixed projection; - vnl_vector_fixed projectionEnd; - projection.fill(0); - projectionEnd.fill(0); - - itk::Point worldPosStart; - itk::Point worldPosEnd; - IndexTensorType tensorIdx; - IndexType featureIdxStart; - IndexTensorType tensorIdxEnd; - IndexType featureIdxEnd; - m_InputImage->TransformIndexToPhysicalPoint(idxStart, worldPosStart); - m_InputImage->TransformIndexToPhysicalPoint(idxEnd, worldPosEnd); - m_TensorImage->TransformPhysicalPointToIndex(worldPosStart, tensorIdx); - m_TensorImage->TransformPhysicalPointToIndex(worldPosEnd, tensorIdxEnd); - - m_ConfidenceImage->TransformPhysicalPointToIndex(worldPosStart, featureIdxStart); - m_ConfidenceImage->TransformPhysicalPointToIndex(worldPosEnd, featureIdxEnd); - - if (!m_TensorImage->GetLargestPossibleRegion().IsInside(tensorIdxEnd) || - !m_TensorImage->GetLargestPossibleRegion().IsInside(tensorIdx)) - return -1; - - if (m_ConfidenceImage->GetPixel(featureIdxStart) < .1) - return -1; - - vnl_vector_fixed direction; - direction[0] = (-worldPosStart[0] + worldPosEnd[0]); - direction[1] = (-worldPosStart[1] + worldPosEnd[1]); - direction[2] = (-worldPosStart[2] + worldPosEnd[2]); - - direction = direction.normalize(); - - TensorPixelType tensorEnd = m_TensorImage->GetPixel(tensorIdxEnd); - TensorPixelType tensorStart = m_TensorImage->GetPixel(tensorIdx); - - typename TensorPixelType::EigenValuesArrayType eigenvalues; - - tensorEnd.ComputeEigenValues(eigenvalues); - double maxEVEnd = std::fabs(eigenvalues[2]); - - tensorStart.ComputeEigenValues(eigenvalues); - double maxEVStart = std::fabs(eigenvalues[2]); - - if (maxEVEnd == 0.0) - maxEVEnd = 1; // no change then .. - // Normalize by largest EV - tensorEnd[0] /= maxEVEnd; - tensorEnd[1] /= maxEVEnd; - tensorEnd[2] /= maxEVEnd; - tensorEnd[3] /= maxEVEnd; - tensorEnd[4] /= maxEVEnd; - tensorEnd[5] /= maxEVEnd; - - if (maxEVStart == 0.0) - maxEVStart = 1; // no change then .. - // Normalize by largest EV - tensorStart[0] /= maxEVStart; - tensorStart[1] /= maxEVStart; - tensorStart[2] /= maxEVStart; - tensorStart[3] /= maxEVStart; - tensorStart[4] /= maxEVStart; - tensorStart[5] /= maxEVStart; - - /* Matrix Style - * | 0 1 2 | - * | X 3 4 | - * | X X 5 | - */ - // Multiply vector with tensor, and then take the magnitude of it. - projection[0] = direction[0] * tensorStart[0] + direction[1] * tensorStart[1] + direction[2] * tensorStart[2]; - projection[1] = direction[0] * tensorStart[1] + direction[1] * tensorStart[3] + direction[2] * tensorStart[4]; - projection[2] = direction[0] * tensorStart[2] + direction[1] * tensorStart[4] + direction[2] * tensorStart[5]; - - projectionEnd[0] = direction[0] * tensorEnd[0] + direction[1] * tensorEnd[1] + direction[2] * tensorEnd[2]; - projectionEnd[1] = direction[0] * tensorEnd[1] + direction[1] * tensorEnd[3] + direction[2] * tensorEnd[4]; - projectionEnd[2] = direction[0] * tensorEnd[2] + direction[1] * tensorEnd[4] + direction[2] * tensorEnd[5]; - - if (direction.magnitude() == 0.0 || projectionEnd.magnitude() == 0.0) - return -1; - - // Confidences higher than 1 are considered to be noise (due to the behavior of FA values derived from tensors - // with negative eigenvalues) - FeaturePixelType confStart = m_ConfidenceImage->GetPixel(featureIdxStart); - if (confStart > 1) - confStart = .1; - FeaturePixelType confEnd = m_ConfidenceImage->GetPixel(featureIdxEnd); - if (confEnd > 1) - confEnd = .1; - - // costs - cost = (1.1 - confStart) * (1.0 / sqrt(projection.magnitude())); - cost *= (1.1 - confEnd) * (1.0 / sqrt(projectionEnd.magnitude())); - cost *= (-1 + exp(std::fabs(m_InputImage->GetPixel(idxStart) - m_InputImage->GetPixel(idxEnd)))); - - break; - } - } - return cost; - } - -} // end itk namespace - -#endif diff --git a/Modules/TumorInvasionAnalysis/include/itkConnectednessFilter.h b/Modules/TumorInvasionAnalysis/include/itkConnectednessFilter.h deleted file mode 100644 index 5858a70459..0000000000 --- a/Modules/TumorInvasionAnalysis/include/itkConnectednessFilter.h +++ /dev/null @@ -1,153 +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. - -============================================================================*/ - -#ifndef __itkConnectednessFilter_h -#define __itkConnectednessFilter_h - -#include "itkImageRegionIterator.h" -#include "itkImageToImageFilter.h" -#include - -namespace itk -{ - /** ConnectednessFilter - Propagate the border voxels of seed region, also calculates distance maps - * - * Propagates the values of the boder-region of the seed mask. This is done by looking for the shortes path - * w.r.t. some distance metric that can be chosen. - * - * Options are - * FeatureSimilarity - shortest path is determined by looking at feature differences only - * VectorAgreement - cost is determined by path agreement with supplied vector field - * FeatureVectorAgreement - cost is a combination of vector agreement and feature similarity - * - */ - - template - class ConnectednessFilter : public ImageToImageFilter - { - public: - /** Standard class typedefs. */ - typedef ConnectednessFilter Self; - typedef ImageToImageFilter Superclass; - typedef SmartPointer Pointer; - - typedef typename itk::Image, 3> TTensorImage; - - typedef typename TSeedImage::PixelType SeedPixelType; - typedef typename TFeatureImage::PixelType FeaturePixelType; - typedef typename TTensorImage::PixelType TensorPixelType; - - typedef typename TFeatureImage::IndexType IndexType; - typedef typename TSeedImage::IndexType IndexSeedType; - typedef typename TTensorImage::IndexType IndexTensorType; - - typedef typename itk::ImageRegionIterator SeedIteratorType; - typedef typename itk::ImageRegionIterator FeatureIteratorType; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); /** Run-time type information (and related methods). */ - itkTypeMacro(PropagateLocalFeaturesFilter, ImageToImageFilter); - - /** - * @brief The DistanceMode enum Available distance metrics - */ - enum DistanceMode { - FeatureSimilarity, - VectorAgreement, - FeatureVectorAgreement - }; - - void SetInputImage(const TFeatureImage *image); - - /** - * @brief SetInputSeed - seed area from which features are to be propagated - * @param mask - */ - void SetInputSeed(const TSeedImage *mask); - - /** - * @brief SetInputMask - Filter only operates in masked area - * @param mask - */ - void SetInputMask(const TSeedImage *mask); - - /** - * @brief SetInputVectorField - * @param vecs - */ - void SetInputVectorField(const TTensorImage *vecs); - - /** - * @brief SetInputVectorFieldConfidenceMap - Map that assigned a weight/confidence to each vector - * @param conf - */ - void SetInputVectorFieldConfidenceMap(const TFeatureImage *conf); - - /** - * @brief SetPropagationImage - OPTIONAL. Set image which values are propagated, it this is not supplied the - * InputImage is chosen as default. - * @param prop - */ - void SetPropagationImage(const TFeatureImage *prop); - - /** - * @brief GetDistanceImage - Return the distance image using the specified metric - * @return - */ - typename TFeatureImage::Pointer GetDistanceImage(); - - /** - * @brief GetEuclideanDistanceImage - Return distance image that provides distance of shortest path for each voxel - * w.r.t to euclidean space - * @return - */ - - typename TFeatureImage::Pointer GetEuclideanDistanceImage(); - - void SetMode(DistanceMode mode = FeatureSimilarity) { m_Mode = mode; } - /** - * @brief SetApplyRankFilter - if true the values propagated are determined by calculating the median within the - * mask within a 3x3x3 neighborhood - * @param applyFilter - */ - void SetApplyRankFilter(bool applyFilter) { m_ApplyRankFilter = applyFilter; } - protected: - ConnectednessFilter() { m_ApplyRankFilter = false; } - ~ConnectednessFilter() {} - /** Does the real work. */ - virtual void GenerateData(); - - virtual double GetDistanceValue(IndexType idxStart, IndexType idxEnd); - - private: - ConnectednessFilter(const Self &); // purposely not implemented - void operator=(const Self &); // purposely not implemented - - typename TFeatureImage::Pointer m_InputImage; - typename TTensorImage::Pointer m_TensorImage; - typename TFeatureImage::Pointer m_ConfidenceImage; - // Distance image w.r.t. to metric - typename TFeatureImage::Pointer m_DistanceImage; - // Euclidean distance, that keeps track of distance of shortest path - typename TFeatureImage::Pointer m_EuclideanDistance; - - DistanceMode m_Mode; - - bool m_ApplyRankFilter; - }; -} // namespace ITK - -#ifndef ITK_MANUAL_INSTANTIATION -#include "itkConnectednessFilter.cxx" -#endif - -#endif // itkConnectednessFilter_h diff --git a/Modules/TumorInvasionAnalysis/include/mitkCollectionDilatation.h b/Modules/TumorInvasionAnalysis/include/mitkCollectionDilatation.h deleted file mode 100644 index d24c9e7049..0000000000 --- a/Modules/TumorInvasionAnalysis/include/mitkCollectionDilatation.h +++ /dev/null @@ -1,65 +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. - -============================================================================*/ - -#ifndef mitkCollectionDilation_H -#define mitkCollectionDilation_H - -// MITK -#include "mitkCommon.h" -#include -#include - -namespace mitk -{ - class MITKTUMORINVASIONANALYSIS_EXPORT CollectionDilation - { - public: - typedef unsigned char BinaryType; - typedef itk::Image BinaryImage; - - CollectionDilation() {} - ~CollectionDilation() {} - /** - * @brief DilateBinaryByName - Dilate all occurances of a modality within a mitk::DataCollection - * @param dataCollection - * @param name - name of modality - * @param xy - dilatation in xy direction - * @param z - dilatation in z direction - * @param suffix - suffix that is appended to newly created image - */ - static void DilateBinaryByName(DataCollection *dataCollection, - std::string name, - unsigned int xy = 5, - unsigned int z = 0, - std::string suffix = "DILATE"); - - /** - * @brief ErodeBinaryByName - Erode all occurances of a modality within a mitk::DataCollection - * @param dataCollection - * @param name - name of modality - * @param xy - erosion in xy direction - * @param z - erosion in z direction - * @param suffix - suffix that is appended to newly created image - */ - static void ErodeBinaryByName(DataCollection *dataCollection, - std::string name, - unsigned int xy = 5, - unsigned int z = 0, - std::string suffix = "ERODE"); - - protected: - private: - // DATA - // FUNCTIONS - }; -} // end namespace -#endif diff --git a/Modules/TumorInvasionAnalysis/include/mitkCollectionGrayOpening.h b/Modules/TumorInvasionAnalysis/include/mitkCollectionGrayOpening.h deleted file mode 100644 index 378381bb1e..0000000000 --- a/Modules/TumorInvasionAnalysis/include/mitkCollectionGrayOpening.h +++ /dev/null @@ -1,47 +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. - -============================================================================*/ - -#ifndef mitkCollectionGrayDilation_H -#define mitkCollectionGrayDilation_H - -// MITK -#include "mitkCommon.h" -#include -#include - -namespace mitk -{ - class MITKTUMORINVASIONANALYSIS_EXPORT CollectionGrayOpening - { - public: - // typedef unsigned char BinaryType; - typedef itk::Image ImageType; - - CollectionGrayOpening() {} - ~CollectionGrayOpening() {} - /** - * @brief PerformGrayOpening - Opening operation on a specific modality type wihtin the DataCollection. Creates a - * new item. - * @param dataCollection - * @param name - * @param suffix - */ - static void PerformGrayOpening(mitk::DataCollection *dataCollection, std::string name, std::string suffix); - - protected: - private: - // DATA - - // FUNCTIONS - }; -} // end namespace -#endif diff --git a/Modules/TumorInvasionAnalysis/include/mitkDiffusionCollectionReader.h b/Modules/TumorInvasionAnalysis/include/mitkDiffusionCollectionReader.h deleted file mode 100644 index c6cea113a2..0000000000 --- a/Modules/TumorInvasionAnalysis/include/mitkDiffusionCollectionReader.h +++ /dev/null @@ -1,143 +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. - -============================================================================*/ - -#ifndef MITK_DIFFUSIONCOLLECTION_READER_H -#define MITK_DIFFUSIONCOLLECTION_READER_H - -#include "mitkCommon.h" -#include "mitkDataCollection.h" -#include - -// VTK -#include - -namespace mitk { - class MITKTUMORINVASIONANALYSIS_EXPORT DiffusionCollectionReader : public vtkXMLParser - { - public: - - typedef std::vector > FileListType; - - /** - * @brief Build up a mitk::DataCollection from a XML resource - * - **/ - DataCollection::Pointer LoadCollection(const std::string& xmlFileName); - - void AddDataElementIds(std::vector dataElemetIds); - void AddSubColIds(std::vector subColIds); - - void SetDataItemNames(std::vector itemNames); - - void ClearDataElementIds(); - void ClearSubColIds(); - - void Clear(); - - /** - * @brief Build up a mitk::DataCollection from a folder providing suffixes to group the files - * - **/ - static DataCollection::Pointer FolderToCollection(std::string folder, std::vector suffixes,std::vector seriesNames, bool allowGaps); - - /** - * @brief GenerateFileLists Returns a collection of lists with valid files names in a folder - * - * The first suffix entry in the vector is used for the reference images which are put in the first list, - * then the suffixes are interchanged and checked if the file exists; for each suffix a list is returned with filenames, - * if a file is expected but does not exist an empty string "" is added instead. - * - * @param folder - * @param suffixes - * @param allowGaps - * @return - */ - static FileListType GenerateFileLists(std::string folder, std::vector suffixes, bool allowGaps = false); - - /** - * @brief SanitizeFileList Removes all entries that are lacking at least one modality - * @param list - sanitized list - * @return - */ - - static FileListType SanitizeFileList(FileListType list); - - DiffusionCollectionReader(); - ~DiffusionCollectionReader() override; - protected: - - /** - * @brief Derived from XMLReader - **/ - void StartElement (const char* elementName, const char **atts) override; - /** - * @brief Derived from XMLReader - **/ - void EndElement (const char* elementName) override; - - private: - /** - * @brief Derived from XMLReader - **/ - std::string ReadXMLStringAttribut( std::string name, const char** atts); - /** - * @brief Derived from XMLReader - **/ - bool ReadXMLBooleanAttribut( std::string name, const char** atts ); - /** - * @brief Derived from XMLReader - **/ - int ReadXMLIntegerAttribut( std::string name, const char** atts ); - - /** - * @brief m_DataCollection - * Stores a data collection during build of - */ - DataCollection::Pointer m_Collection; - DataCollection::Pointer m_SubCollection; - DataCollection::Pointer m_DataItemCollection; - - /** - * @brief m_SelectedIds - * - * Stores ids which are to be considered during loading, if this is provided all - * all data sets not matching an ID in this list are skipped. - */ - std::vector m_SelectedSubColIds; - - std::vector m_SelectedDataItemIds; - - /** - * @brief m_SelectedDataItemNames - * Lists names of items to be loaded, rest is ignored - */ - - std::vector m_SelectedDataItemNames; - - /** - * @brief m_Ignore - * - * Determines if current sub-collection is ignored - */ - bool m_ColIgnore; - bool m_ItemIgnore; - - /** - * @brief m_BaseDir - * - * Stores Base directory to allow XML links with relative paths - */ - std::string m_BaseDir; - }; -} // namespace mitk - -#endif /* MITK_COLLECTION_READER_H */ diff --git a/Modules/TumorInvasionAnalysis/include/mitkDiffusionCollectionWriter.h b/Modules/TumorInvasionAnalysis/include/mitkDiffusionCollectionWriter.h deleted file mode 100755 index b00751de53..0000000000 --- a/Modules/TumorInvasionAnalysis/include/mitkDiffusionCollectionWriter.h +++ /dev/null @@ -1,77 +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. - -============================================================================*/ - -#ifndef MITK_DIFFUSIONCOLLECTION_WRITER_H -#define MITK_DIFFUSIONCOLLECTION_WRITER_H - -#include "mitkCommon.h" -#include "mitkDataCollection.h" -#include "mitkDiffusionCollectionReader.h" -#include - -namespace mitk { - class MITKTUMORINVASIONANALYSIS_EXPORT DiffusionCollectionWriter - { - public: - - typedef float TensorScalar; - /** - * @brief ExportCollectionToFolder - * - * Creates an XML file and stores all data in the same folder as the xml file (creating sub-folders for sub-collections) - * - * - * Naming Conventions (Neccessary for proper saving of these images): - * DWI - Diffusion Weighted Images - * DTI - Diffusion Tensor Images - * FIB - Fiber Bundles - * - * @param dataCollection - * @param xmlFile - * @param filter - (optional) only items with names contained in this list are written, if list is empty all items are written - * @return - */ - static bool ExportCollectionToFolder(DataCollection* dataCollection, std::string xmlFile , std::vector filter); - - static bool ExportCollectionToFolder(DataCollection* dataCollection, std::string xmlFile); - - /** - * @brief SaveCollection - Stores data collection at original location - * - * Writes the collection back to the files given in the original XML file. - * New data items are stored into the default location, which is relative to the XML file. - * - * If a XML file is provided the files are stored as stated above with the differences that a new XML file is generated and new files are saved - * relative to the newly generated xml. - * - * @param dataCollection - * @param filter - * @param xmlFile - * @return - */ - - static bool SaveCollection(DataCollection* dataCollection, std::vector filter, std::string xmlFile = ""); - - static bool FolderToXml(std::string folder, std::string collectionType, std::string xmlFile, std::vector filter, std::vector seriesNames); - - // GTV last entry in filter list, this item will be made to TARGET - static bool SingleFolderToXml(std::string folder, std::string xmlFile, std::vector filter, std::vector seriesNames, bool longDate = true, int skipUntil = 0, float months = 0); - - protected: - - private: - - static size_t GetIndexForinXMonths(DiffusionCollectionReader::FileListType fileList, float months, size_t curIndex, std::vector filter); - }; -} // namespace mitk - -#endif /* MITK_COLLECTION_WRITER_H */ diff --git a/Modules/TumorInvasionAnalysis/include/mitkTumorInvasionClassification.h b/Modules/TumorInvasionAnalysis/include/mitkTumorInvasionClassification.h deleted file mode 100644 index 5893c0175b..0000000000 --- a/Modules/TumorInvasionAnalysis/include/mitkTumorInvasionClassification.h +++ /dev/null @@ -1,188 +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. - -============================================================================*/ - -#ifndef TumorInvasionAnalysis_H -#define TumorInvasionAnalysis_H - -// MITK -#include "mitkCommon.h" -#include -// DATA -#include -// FORESTS -#include - -namespace mitk -{ - /** - * @brief The TumorInvasionAnalysis class - Classifies Tumor progression using RF and predicts on new cases - * - * Provides a way to learn tumor progression from examples, and predict the growth using random forests. - * - * - * Expected Inputs are DataCollections. The Tumor Segmentations (current extent) are expected to be binary (0 - - * healthy tissue, 1 - tumor tissue), - * likewise the target extent that is to be learnt. - * - */ - class MITKTUMORINVASIONANALYSIS_EXPORT TumorInvasionClassification - { - public: - TumorInvasionClassification(); - ~TumorInvasionClassification() {} - /** - * @brief SelectTrainingSamples - * - * Selects healthy/tumor tissue samples to be included into training. - * \warn This modifies the target data items in the data collection. - * Afterwards the target data is structured as follows: 0 -voxels excluded from training , 1 - healthy sample , 2 - - * "tuning-into-tumor" sample - * - * - * - * @param collection - * @param erodeTrainingMask - Performs erosion on target such that border voxels of tumor region will not be - * included into training - */ - void SelectTrainingSamples(DataCollection *collection, unsigned int mode = 0); - - /** - * @brief PrepareResponseSamples - * - * Selects healthy/tumor tissue samples to be included into training, and weights them to achieve a given ratio. - * \warn This modifies the target data items in the data collection. - * Afterwards the target data is encoded as follows: - * 0 - excluded (e.g. out of brainmask) - * 1 - no involvement (healthy all the time) - * 2 - formerly healthy, now tumor (rezivid) - * 3 - formerly tumor, now necroses (responsive) - */ - void PrepareResponseSamples(DataCollection *collection); - - /** - * @brief LearnProgressionFeatures - * - * - * @param collection - data collection used for training - * @param modalitiesList - modalities (data item names from collection) that are to be used for training - * @param forestSize - number of trees that are trained - * @param treeDepth - maximal depth for a single tree - */ - - void LearnProgressionFeatures(DataCollection *collection, - std::vector modalitiesList, - size_t forestSize = 300, - size_t treeDepth = 10); - - /** - * @brief PredictGrowth - Classify voxels into remaining healthy / turning into tumor - * @param collection - */ - void PredictInvasion(DataCollection *collection, std::vector modalitiesList); - - /** - * @brief SanitizeResults - Performs an Opening Operation on tha data to remove isolated misclassifications - * - * RESULTOPEN - * - * @param collection - */ - void SanitizeResults(DataCollection *collection, std::string resultID = "RESULT"); - - void SetTrainMargin(size_t dil2d, size_t dil3d) - { - m_TargetDil2D = dil2d; - m_TargetDil3D = dil3d; - } - - /** - * @brief SetClassRatio - set ratio of tumor voxels to healthy voxels that is to be used for training - * - * \warn perfect ratio cannot allways be achieved, since by default all tumor voxels are included into training - * (since they ususally are to rare to be skipped) - * - * @param ratio - */ - - void SetClassRatio(ScalarType ratio) { m_ClassRatio = ratio; } - void SetGlobalsStatsFile(std::string fn) { m_GlobalStatsFile = fn; } - /** - * @brief SamplesWeightingActivated If activated a weighted mask for the samples is calculated, weighting samples - * according to their location and ratio - * @param isActive - */ - void SamplesWeightingActivated(bool isActive) { m_WeightSamples = isActive; } - /** - * @brief SetTargetID sets binary mask denoting future tumor area - * @param targetID - */ - void SetTargetID(std::string targetID = "TARGET") { m_TargetID = targetID; } - /** - * @brief SetTumorID sets binary mask denoting current tumor area - * @param tumorID - */ - void SetTumorID(std::string tumorID = "GTV") { m_TumorID = tumorID; } - /** - * @brief SetMaskID sets binary mask denoting area that is evluated/included in training - * @param maskID - */ - void SetMaskID(std::string maskID = "BRAINMASK") { m_MaskID = maskID; } - /** - * @brief SetResultID sets data item name in which prediction results are stored - * @param resultID - */ - void SetResultID(std::string resultID = "RESULT") { m_ResultID = resultID; } - /** - * @brief UseRandomizedTrees - use random splits to build up forest - * @param useRandom - */ - void UseRandomizedTrees(bool useRandom) { m_Randomize = useRandom; } - /** - * @brief DescriptionToLogFile - Append to log file: patient ids and time steps contained in this data collection. - * @param collection - * @param outputFile - */ - void DescriptionToLogFile(DataCollection *collection, std::string outputFile); - - /** - * @brief SaveRandomForest - Saves a trained random forest - * @param filename - */ - void SaveRandomForest(std::string filename); - - /** - * @brief LoadRandomForest - loads a random forest to be used for classification - * @param filename - */ - void LoadRandomForest(std::string); - - protected: - private: - // DATA - mitk::VigraRandomForestClassifier m_Forest; - unsigned int m_TargetDil2D; - unsigned int m_TargetDil3D; - - ScalarType m_ClassRatio; - - std::string m_GlobalStatsFile; - - std::string m_TargetID; - std::string m_TumorID; - std::string m_MaskID; - std::string m_ResultID; - - bool m_Randomize; - bool m_WeightSamples; - }; -} // end namespace -#endif diff --git a/Modules/TumorInvasionAnalysis/src/Classification/mitkTumorInvasionClassification.cpp b/Modules/TumorInvasionAnalysis/src/Classification/mitkTumorInvasionClassification.cpp deleted file mode 100644 index 38e488a6d9..0000000000 --- a/Modules/TumorInvasionAnalysis/src/Classification/mitkTumorInvasionClassification.cpp +++ /dev/null @@ -1,672 +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 "mitkTumorInvasionClassification.h" - -#include "mitkCLUtil.h" -#include "mitkCollectionDilatation.h" -#include "mitkCollectionGrayOpening.h" -#include "mitkDataCollectionImageIterator.h" -#include "mitkDataCollectionUtilities.h" -#include "mitkIOUtil.h" -#include -// To initialize random number generator -#include - -static void EnsureDataImageInCollection(mitk::DataCollection::Pointer collection, - std::string origin, - std::string target) -{ - typedef itk::Image FeatureImage; - - if (collection->HasElement(origin)) - { - mitk::Image::Pointer originImage = dynamic_cast(collection->GetMitkImage(origin).GetPointer()); - FeatureImage::Pointer itkOriginImage = FeatureImage::New(); - mitk::CastToItkImage(originImage, itkOriginImage); - - if (!collection->HasElement(target) && itkOriginImage.IsNotNull()) - { - FeatureImage::Pointer image = FeatureImage::New(); - image->SetRegions(itkOriginImage->GetLargestPossibleRegion()); - image->SetSpacing(itkOriginImage->GetSpacing()); - image->SetOrigin(itkOriginImage->GetOrigin()); - image->SetDirection(itkOriginImage->GetDirection()); - image->Allocate(); - - collection->AddData(dynamic_cast(image.GetPointer()), target, ""); - } - } - for (std::size_t i = 0; i < collection->Size(); ++i) - { - mitk::DataCollection *newCol = dynamic_cast(collection->GetData(i).GetPointer()); - if (newCol != nullptr) - { - EnsureDataImageInCollection(newCol, origin, target); - } - } -} - -mitk::TumorInvasionClassification::TumorInvasionClassification() - : m_TargetID("TARGET"), - m_TumorID("GTV"), - m_MaskID("BRAINMASK"), - m_ResultID("RESULT"), - m_Randomize(false), - m_WeightSamples(false) -{ -} - -void mitk::TumorInvasionClassification::SelectTrainingSamples(mitk::DataCollection *collection, unsigned int mode) -{ - srand(time(nullptr)); - MITK_INFO << "LearnProgressionFeatures: Selecting training voxels."; - switch (mode) - { - case 0: - { - MITK_INFO << " Selection Mode " << mode << " use all tumor voxels, healthy: 50% vicinity / 50% far away"; - - CollectionDilation::DilateBinaryByName(collection, m_TargetID, 2, 0, "EXCLUDE"); - CollectionDilation::ErodeBinaryByName(collection, m_TargetID, 1, 0, "ERODE"); - CollectionDilation::DilateBinaryByName(collection, m_TargetID, m_TargetDil2D, m_TargetDil3D, "TRAIN"); - DataCollectionImageIterator gtvIter(collection, m_TumorID); - DataCollectionImageIterator brainMaskIter(collection, m_MaskID); - DataCollectionImageIterator targetIter(collection, m_TargetID); - DataCollectionImageIterator targetDil(collection, m_TargetID + "TRAIN"); - - // Count Healthy/ Tumor voxels - // i.o. to decide how many of each are taken - unsigned int totalTumor = 0; - unsigned int totalHealthyClose = 0; - unsigned int totalHealthy = 0; - - while (!brainMaskIter.IsAtEnd()) - { - if (brainMaskIter.GetVoxel() != 0) - { - if (targetIter.GetVoxel() == 1 && gtvIter.GetVoxel() == 0) - ++totalTumor; - - if (targetIter.GetVoxel() == 0 && targetDil.GetVoxel() == 1 && gtvIter.GetVoxel() == 0) - ++totalHealthyClose; - - if (targetIter.GetVoxel() == 0 && gtvIter.GetVoxel() == 0 && targetDil.GetVoxel() == 0) - ++totalHealthy; // healthy but not close - } - ++brainMaskIter; - ++targetIter; - ++targetDil; - ++gtvIter; - } - brainMaskIter.ToBegin(); - targetIter.ToBegin(); - targetDil.ToBegin(); - gtvIter.ToBegin(); - // Total of healthy samples that is to be collected - unsigned int targetHealthy = totalTumor * m_ClassRatio; - // Determines which portion of the healthy samples is drawn from the immediate vicinity of the newly grown tumor - ScalarType ratioClose = .5; - - // Compute probabilities thresholds for choosing a close healthy voxel / any healthy voxel - ScalarType thHealthyClose = std::min(1.0, (targetHealthy * ratioClose) / totalHealthyClose); - ScalarType thHealthyAny = std::min(1.0, (targetHealthy * (1.0 - ratioClose)) / totalHealthy); - // Some stats - { - MITK_INFO << "Total # Tumor Voxels " << totalTumor; - MITK_INFO << "Total # Healthy Voxels" << totalHealthy; - MITK_INFO << "Target Ratio " << m_ClassRatio; - MITK_INFO << "Ratio for healthy close: " << thHealthyClose; - MITK_INFO << "Ratio for healthy any other: " << thHealthyAny; - } - - // DEBUG count occurances to compare - unsigned int tumor = 0; - unsigned int healthy = 0; - while (!brainMaskIter.IsAtEnd()) - { - if (brainMaskIter.GetVoxel() != 0) - { - if (targetIter.GetVoxel() == 1) - { // choose tumor voxels for training - if (gtvIter.GetVoxel() == 0) // tumor always - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - ++tumor; - } - else - targetIter.SetVoxel(0); - } - else - { // choose healty tissue voxels for training - ScalarType rndVal = (float)rand() / (float)(RAND_MAX); //(0..1) - if (gtvIter.GetVoxel() == 0 && ((targetDil.GetVoxel() == 1 && rndVal <= thHealthyClose))) - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - ++healthy; - } - else if (((targetDil.GetVoxel() == 0 && rndVal <= thHealthyAny))) - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - ++healthy; - } - else - targetIter.SetVoxel(0); - } - } - else - targetIter.SetVoxel(0); - - ++brainMaskIter; - ++targetIter; - ++gtvIter; - ++targetDil; - } - MITK_INFO << "Training with Samples #Tumor " << tumor << " / healthy # " << healthy; - } - break; - case 2: - { - MITK_INFO << " Selection Mode " << mode << " Weighted with ratio"; - - EnsureDataImageInCollection(collection, m_TumorID, "WEIGHTS"); - - CollectionDilation::DilateBinaryByName(collection, m_TargetID, 1, 0, "EXCLUDE"); - CollectionDilation::ErodeBinaryByName(collection, m_TargetID, 1, 0, "ERODE"); - CollectionDilation::DilateBinaryByName(collection, m_TargetID + "EXCLUDE", m_TargetDil2D, m_TargetDil3D, "TRAIN"); - DataCollectionImageIterator gtvIter(collection, m_TumorID); - DataCollectionImageIterator brainMaskIter(collection, m_MaskID); - DataCollectionImageIterator targetIter(collection, m_TargetID); - DataCollectionImageIterator targetDil(collection, m_TargetID + "EXCLUDETRAIN"); - DataCollectionImageIterator excludeTumorIter(collection, m_TargetID + "ERODE"); - DataCollectionImageIterator excludeHealthyIter(collection, m_TargetID + "EXCLUDE"); - - DataCollectionImageIterator weightsIter(collection, "WEIGHTS"); - - // Count Healthy/ Tumor voxels - // i.o. to decide how many of each are taken - double totalTumor = 0; - double totalHealthyClose = 0; - double totalHealthyNonClose = 0; - double totalHealthy = 0; - - while (!brainMaskIter.IsAtEnd()) - { - if (brainMaskIter.GetVoxel() != 0) - { - if (targetIter.GetVoxel() == 1 && gtvIter.GetVoxel() == 0 && excludeTumorIter.GetVoxel() == 1) - ++totalTumor; - - if (excludeHealthyIter.GetVoxel() == 0 && targetDil.GetVoxel() == 1 && gtvIter.GetVoxel() == 0) - ++totalHealthyClose; - - if (excludeHealthyIter.GetVoxel() == 0 && gtvIter.GetVoxel() == 0 && targetDil.GetVoxel() == 0) - ++totalHealthyNonClose; // healthy but not close - - if (excludeHealthyIter.GetVoxel() == 0 && gtvIter.GetVoxel() == 0 && targetIter.GetVoxel() == 0) - ++totalHealthy; // healthy - } - ++brainMaskIter; - ++targetIter; - ++targetDil; - ++gtvIter; - ++excludeHealthyIter; - ++excludeTumorIter; - } - brainMaskIter.ToBegin(); - targetIter.ToBegin(); - targetDil.ToBegin(); - gtvIter.ToBegin(); - excludeHealthyIter.ToBegin(); - excludeTumorIter.ToBegin(); - - // Compute probabilities thresholds for choosing a close healthy voxel / any healthy voxel - ScalarType wHealthyClose = 10000.0 / totalHealthyClose; - ScalarType wHealthyAny = 5000.0 / totalHealthyNonClose; - ScalarType wTumor = (m_ClassRatio * (10000.0 + 5000.0)) / totalTumor; - - // DEBUG count occurances to compare - double potentialClose = 0; - double selectedClose = 0; - double tumor = 0; - double healthy = 0; - while (!brainMaskIter.IsAtEnd()) - { - weightsIter.SetVoxel(0); - if (brainMaskIter.GetVoxel() != 0) - { - if (targetIter.GetVoxel() == 1) - { // choose tumor voxels for training - if (gtvIter.GetVoxel() == 0 && excludeTumorIter.GetVoxel() == 1) // tumor always - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - weightsIter.SetVoxel(wTumor); - ++tumor; - } - else if (gtvIter.GetVoxel() == 0) - { - weightsIter.SetVoxel(0); //.1); - targetIter.SetVoxel(0); // 2); - } - } - else - { // choose healty tissue voxels for training - if (gtvIter.GetVoxel() == 0 && ((excludeHealthyIter.GetVoxel() == 0 && targetDil.GetVoxel() == 1))) - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - weightsIter.SetVoxel(wHealthyClose); - healthy += wHealthyClose; - } - else if (((targetDil.GetVoxel() == 0 && excludeHealthyIter.GetVoxel() == 0))) - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - weightsIter.SetVoxel(wHealthyAny); - healthy += wHealthyAny; - } - else if ((gtvIter.GetVoxel() == 0 && excludeHealthyIter.GetVoxel() == 1)) - { - targetIter.SetVoxel(0); // brainMaskIter.GetVoxel()+targetIter.GetVoxel()); - weightsIter.SetVoxel(0); //.1); - } - else - { - targetIter.SetVoxel(0); - weightsIter.SetVoxel(0); - } - } - } - else - { - targetIter.SetVoxel(0); - weightsIter.SetVoxel(0); - } - - if (gtvIter.GetVoxel() != 0) - targetIter.SetVoxel(0); - - ++brainMaskIter; - ++targetIter; - ++gtvIter; - ++targetDil; - ++excludeHealthyIter; - ++excludeTumorIter; - ++weightsIter; - } - MITK_INFO << "Training with Samples #Tumor " << tumor << " / healthy # " << healthy; - MITK_INFO << "Potential Close" << potentialClose; - MITK_INFO << "Selected Close" << selectedClose; - } - break; - default: - { - MITK_INFO << " Selection Mode " << mode - << " Exclude voxels in border regions, healthy: 50% vicinity / 50% far away"; - - // weights - ScalarType tumorWeight = 1; - // ScalarType unsureRegion = .25; - ScalarType healthyTissue = 1; - - EnsureDataImageInCollection(collection, m_TumorID, "WEIGHTS"); - - CollectionDilation::DilateBinaryByName(collection, m_TargetID, 1, 0, "EXCLUDE"); - CollectionDilation::ErodeBinaryByName(collection, m_TargetID, 1, 0, "ERODE"); - CollectionDilation::DilateBinaryByName(collection, m_TargetID + "EXCLUDE", m_TargetDil2D, m_TargetDil3D, "TRAIN"); - DataCollectionImageIterator gtvIter(collection, m_TumorID); - DataCollectionImageIterator brainMaskIter(collection, m_MaskID); - DataCollectionImageIterator targetIter(collection, m_TargetID); - DataCollectionImageIterator targetDil(collection, m_TargetID + "EXCLUDETRAIN"); - DataCollectionImageIterator excludeTumorIter(collection, m_TargetID + "ERODE"); - DataCollectionImageIterator excludeHealthyIter(collection, m_TargetID + "EXCLUDE"); - - DataCollectionImageIterator weightsIter(collection, "WEIGHTS"); - - // Count Healthy/ Tumor voxels - // i.o. to decide how many of each are taken - double totalTumor = 0; - double totalHealthyClose = 0; - double totalHealthyNonClose = 0; - double totalHealthy = 0; - - while (!brainMaskIter.IsAtEnd()) - { - if (brainMaskIter.GetVoxel() != 0) - { - if (targetIter.GetVoxel() == 1 && gtvIter.GetVoxel() == 0 && excludeTumorIter.GetVoxel() == 1) - ++totalTumor; - - if (excludeHealthyIter.GetVoxel() == 0 && targetDil.GetVoxel() == 1 && gtvIter.GetVoxel() == 0) - ++totalHealthyClose; - - if (excludeHealthyIter.GetVoxel() == 0 && gtvIter.GetVoxel() == 0 && targetDil.GetVoxel() == 0) - ++totalHealthyNonClose; // healthy but not close - - if (excludeHealthyIter.GetVoxel() == 0 && gtvIter.GetVoxel() == 0 && targetIter.GetVoxel() == 0) - ++totalHealthy; // healthy - } - ++brainMaskIter; - ++targetIter; - ++targetDil; - ++gtvIter; - ++excludeHealthyIter; - ++excludeTumorIter; - } - brainMaskIter.ToBegin(); - targetIter.ToBegin(); - targetDil.ToBegin(); - gtvIter.ToBegin(); - excludeHealthyIter.ToBegin(); - excludeTumorIter.ToBegin(); - - // Total of healthy samples that is to be collected - unsigned int targetHealthy = (tumorWeight / healthyTissue) * totalTumor * m_ClassRatio; - // Determines which portion of the healthy samples is drawn from the immediate vicinity of the newly grown tumor - ScalarType ratioClose = .5; - - // Compute probabilities thresholds for choosing a close healthy voxel / any healthy voxel - ScalarType thHealthyClose = std::min(1.0, ((double)targetHealthy * ratioClose) / totalHealthyClose); - ScalarType thHealthyAny = std::min(1.0, ((double)targetHealthy * (1.0 - ratioClose)) / totalHealthyNonClose); - // Some stats - { - MITK_INFO << "Total Tumor " << totalTumor; - MITK_INFO << "Total healthy " << totalHealthyNonClose; - MITK_INFO << "Total healthy close " << totalHealthyClose; - MITK_INFO << "Total healthy non-close " << totalHealthyNonClose; - MITK_INFO << "Target Ratio " << m_ClassRatio; - - MITK_INFO << "Target Healthy " << targetHealthy; - MITK_INFO << "Probabilty close " << thHealthyClose; - MITK_INFO << "Probabilty any other " << thHealthyAny; - } - - // DEBUG count occurances to compare - double potentialClose = 0; - double selectedClose = 0; - double tumor = 0; - double healthy = 0; - while (!brainMaskIter.IsAtEnd()) - { - weightsIter.SetVoxel(0); - if (brainMaskIter.GetVoxel() != 0) - { - if (targetIter.GetVoxel() == 1) - { // choose tumor voxels for training - if (gtvIter.GetVoxel() == 0 && excludeTumorIter.GetVoxel() == 1) // tumor always - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - weightsIter.SetVoxel(tumorWeight); - ++tumor; - } - else if (gtvIter.GetVoxel() == 0) - { - weightsIter.SetVoxel(0); //.1); - targetIter.SetVoxel(0); // 2); - } - } - else - { // choose healty tissue voxels for training - if (gtvIter.GetVoxel() == 0 && ((excludeHealthyIter.GetVoxel() == 0 && targetDil.GetVoxel() == 1))) - { - if (!m_WeightSamples && ((float)rand() / (float)(RAND_MAX) < thHealthyClose)) - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - weightsIter.SetVoxel(1); - ++healthy; - } - else - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - weightsIter.SetVoxel(thHealthyClose); - healthy += thHealthyClose; - } - } - else if (((targetDil.GetVoxel() == 0 && excludeHealthyIter.GetVoxel() == 0))) - { - if (!m_WeightSamples && ((float)rand() / (float)(RAND_MAX) < thHealthyAny)) - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - weightsIter.SetVoxel(1); - ++healthy; - } - else - { - targetIter.SetVoxel(brainMaskIter.GetVoxel() + targetIter.GetVoxel()); - weightsIter.SetVoxel(thHealthyAny); - healthy += thHealthyAny; - } - } - else if ((gtvIter.GetVoxel() == 0 && excludeHealthyIter.GetVoxel() == 1)) - { - targetIter.SetVoxel(0); // brainMaskIter.GetVoxel()+targetIter.GetVoxel()); - weightsIter.SetVoxel(0); //.1); - } - else - { - targetIter.SetVoxel(0); - weightsIter.SetVoxel(0); - } - - if (gtvIter.GetVoxel() == 0 && ((excludeHealthyIter.GetVoxel() == 0 && targetDil.GetVoxel() == 1))) - { - potentialClose++; - - if ((float)rand() / (float)(RAND_MAX) < thHealthyClose) - selectedClose++; - } - } - } - else - { - targetIter.SetVoxel(0); - weightsIter.SetVoxel(0); - } - - if (gtvIter.GetVoxel() != 0) - targetIter.SetVoxel(0); - - ++brainMaskIter; - ++targetIter; - ++gtvIter; - ++targetDil; - ++excludeHealthyIter; - ++excludeTumorIter; - ++weightsIter; - } - MITK_INFO << "Training with Samples #Tumor " << tumor << " / healthy # " << healthy; - MITK_INFO << "Potential Close" << potentialClose; - MITK_INFO << "Selected Close" << selectedClose; - } - break; - } -} - -void mitk::TumorInvasionClassification::PrepareResponseSamples(mitk::DataCollection *collection) -{ - srand(time(nullptr)); - MITK_INFO << "PrepareResponseSamples: Selecting training voxels."; - - EnsureDataImageInCollection(collection, m_TumorID, "WEIGHTS"); - - CollectionDilation::DilateBinaryByName(collection, m_TargetID, 10, 4, "TRAIN"); - DataCollectionImageIterator gtvIter(collection, m_TumorID); - DataCollectionImageIterator brainMaskIter(collection, m_MaskID); - DataCollectionImageIterator targetIter(collection, m_TargetID); - DataCollectionImageIterator dilIter(collection, m_TargetID + "TRAIN"); - - // Count Non-Involved/Responsive/Rezidiv Voxels - - double nonInvolved = 0; - double responsive = 0; - double rezidiv = 0; - - while (!brainMaskIter.IsAtEnd()) - { - if (brainMaskIter.GetVoxel() != 0 && dilIter.GetVoxel() != 0) - { - if (targetIter.GetVoxel() == 0 && gtvIter.GetVoxel() == 0) - { - targetIter.SetVoxel(1); - ++nonInvolved; - } - - if (targetIter.GetVoxel() == 0 && gtvIter.GetVoxel() == 1) - { - targetIter.SetVoxel(3); - ++responsive; - } - - if (targetIter.GetVoxel() == 1 && gtvIter.GetVoxel() == 0) - { - targetIter.SetVoxel(2); - ++rezidiv; - } - } - else - targetIter.SetVoxel(0); - - ++brainMaskIter; - ++targetIter; - ++gtvIter; - ++dilIter; - } - brainMaskIter.ToBegin(); - targetIter.ToBegin(); - gtvIter.ToBegin(); - dilIter.ToBegin(); - - // weight for groups - - double wNonInvolved = 10000.0 / nonInvolved; - double wResponsive = 10000.0 / responsive; - double wRezidiv = 10000.0 / rezidiv; - - std::cout << "Weights are " << wNonInvolved << "/ " << wResponsive << " / " << wRezidiv << std::endl; - - // Assign weight for each voxel - DataCollectionImageIterator weightsIter(collection, "WEIGHTS"); - - while (!brainMaskIter.IsAtEnd()) - { - if (brainMaskIter.GetVoxel() != 0 && dilIter.GetVoxel() != 0) - { - if (targetIter.GetVoxel() == 1) - weightsIter.SetVoxel(wNonInvolved); - - if (targetIter.GetVoxel() == 2) - weightsIter.SetVoxel(wRezidiv); - - if (targetIter.GetVoxel() == 3) - weightsIter.SetVoxel(wResponsive); - } - - ++dilIter; - ++brainMaskIter; - ++targetIter; - ++weightsIter; - } -} - -void mitk::TumorInvasionClassification::LearnProgressionFeatures(mitk::DataCollection *collection, - std::vector modalitiesList, - size_t forestSize, - size_t treeDepth) -{ - auto trainDataX = mitk::DCUtilities::DC3dDToMatrixXd(collection, modalitiesList, m_TargetID); - auto trainDataY = mitk::DCUtilities::DC3dDToMatrixXi(collection, m_TargetID, m_TargetID); - - if (treeDepth != 0) - m_Forest.SetMaximumTreeDepth(treeDepth); - - m_Forest.SetTreeCount(forestSize); - - if (m_WeightSamples) - { - auto trainDataW = mitk::DCUtilities::DC3dDToMatrixXd(collection, "WEIGHTS", m_TargetID); - m_Forest.SetPointWiseWeight(trainDataW); - m_Forest.UsePointWiseWeight(true); - } - - MITK_INFO << "Start Training:"; - try - { - m_Forest.Train(trainDataX, trainDataY); - } - catch (std::exception &e) - { - MITK_INFO << "Exception while training forest: " << e.what(); - } - std::cout << "Training finished" << std::endl; -} - -void mitk::TumorInvasionClassification::PredictInvasion(mitk::DataCollection *collection, - std::vector modalitiesList) -{ - if (collection != nullptr) - { - MITK_INFO << "Evaluating Forest"; - - auto testDataX = mitk::DCUtilities::DC3dDToMatrixXd(collection, modalitiesList, m_MaskID); - auto testDataNewY = m_Forest.Predict(testDataX); - mitk::DCUtilities::MatrixToDC3d(testDataNewY, collection, m_ResultID, m_MaskID); - - Eigen::MatrixXd Probs = m_Forest.GetPointWiseProbabilities(); - - Eigen::MatrixXd prob0 = Probs.col(0); - Eigen::MatrixXd prob1 = Probs.col(1); - - mitk::DCUtilities::MatrixToDC3d(prob0, collection, "prob0", m_MaskID); - mitk::DCUtilities::MatrixToDC3d(prob1, collection, "prob1", m_MaskID); - if (Probs.cols() >= 3) - { - Eigen::MatrixXd prob2 = Probs.col(2); - mitk::DCUtilities::MatrixToDC3d(prob2, collection, "prob2", m_MaskID); - } - } - else - MITK_ERROR << "TumorInvasionClassification::PredictInvasion - provided collection is nullptr."; -} - -void mitk::TumorInvasionClassification::SanitizeResults(mitk::DataCollection *collection, std::string resultID) -{ - CollectionGrayOpening::PerformGrayOpening(collection, resultID, "OPEN"); -} - -void mitk::TumorInvasionClassification::DescriptionToLogFile(mitk::DataCollection *collection, std::string outputFile) -{ - std::ofstream fileStream; - fileStream.open(outputFile.c_str(), std::ios_base::app); - - fileStream << "Configuration:" << std::endl; - for (size_t patient = 0; patient < collection->Size(); ++patient) - { - DataCollection *dataPatient = dynamic_cast(collection->GetData(patient).GetPointer()); - fileStream << "Name : " << dataPatient->GetName() << " with time steps:" << std::endl; - for (size_t timeStep = 0; timeStep < dataPatient->Size(); ++timeStep) - { - fileStream << dataPatient->IndexToName(timeStep) << "-" << std::endl; - DataCollection *dataTS = dynamic_cast(dataPatient->GetData(timeStep).GetPointer()); - for (size_t ts = 0; ts < dataTS->Size(); ++ts) - fileStream << dataTS->IndexToName(ts) << "-" << std::endl; - } - } -} - -void mitk::TumorInvasionClassification::SaveRandomForest(std::string filename) -{ - mitk::IOUtil::Save(&m_Forest, filename); -} - -void mitk::TumorInvasionClassification::LoadRandomForest(std::string /*filename*/) -{ - // TBD - MITK_ERROR << "not yet implemented ..."; -} diff --git a/Modules/TumorInvasionAnalysis/src/ImageFilters/mitkCollectionDilatation.cpp b/Modules/TumorInvasionAnalysis/src/ImageFilters/mitkCollectionDilatation.cpp deleted file mode 100644 index 9b384be934..0000000000 --- a/Modules/TumorInvasionAnalysis/src/ImageFilters/mitkCollectionDilatation.cpp +++ /dev/null @@ -1,119 +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 "mitkCollectionDilatation.h" - -#include -#include - -#include "itkBinaryBallStructuringElement.h" -#include "itkBinaryDilateImageFilter.h" -#include "itkBinaryErodeImageFilter.h" -#include "itkFlatStructuringElement.h" -#include "itkGrayscaleDilateImageFilter.h" - -void mitk::CollectionDilation::DilateBinaryByName( - mitk::DataCollection *dataCollection, std::string name, unsigned int xy, unsigned int z, std::string suffix) -{ - for (size_t patient = 0; patient < dataCollection->Size(); ++patient) - { - DataCollection *dataPatient = dynamic_cast(dataCollection->GetData(patient).GetPointer()); - if (dataPatient == nullptr) - MITK_ERROR << "DilateBinaryByName - Structure of DataCollection is invalid at patient level. Data inconsistent!"; - - if (dataPatient->Size() == 0) - MITK_ERROR << "Empty Patient Collective. Probably Fatal."; - - for (size_t timeStep = 0; timeStep < dataPatient->Size(); ++timeStep) - { - DataCollection *dataTimeStep = dynamic_cast(dataPatient->GetData(timeStep).GetPointer()); - if (dataTimeStep == nullptr) - MITK_ERROR - << "DilateBinaryByName- Structure of DataCollection is invalid at time step level. Data inconsistent!"; - - BinaryImage::Pointer itkTumorSeed = BinaryImage::New(); - Image *tumorSeed = dynamic_cast(dataTimeStep->GetMitkImage(name).GetPointer()); - if (tumorSeed == nullptr) - MITK_ERROR << "Image " << name << " does not exits. Fatal."; - - CastToItkImage(tumorSeed, itkTumorSeed); - - typedef itk::FlatStructuringElement<3> StructuringElementType; - StructuringElementType::RadiusType elementRadius; - elementRadius.Fill(xy); - elementRadius[2] = z; - - StructuringElementType structuringElement = StructuringElementType::Box(elementRadius); - typedef itk::BinaryDilateImageFilter - BinaryDilateImageFilterType; - - BinaryDilateImageFilterType::Pointer dilateFilter0 = BinaryDilateImageFilterType::New(); - dilateFilter0->SetInput(itkTumorSeed); - dilateFilter0->SetKernel(structuringElement); - dilateFilter0->SetForegroundValue(1); - dilateFilter0->Update(); - - Image::Pointer dil = GrabItkImageMemory(dilateFilter0->GetOutput()); - - dil->SetGeometry(tumorSeed->GetGeometry()); - dataTimeStep->AddData(dil.GetPointer(), name + suffix, "Dilated Binary"); - } - } -} - -void mitk::CollectionDilation::ErodeBinaryByName( - mitk::DataCollection *dataCollection, std::string name, unsigned int xy, unsigned int z, std::string suffix) -{ - for (size_t patient = 0; patient < dataCollection->Size(); ++patient) - { - DataCollection *dataPatient = dynamic_cast(dataCollection->GetData(patient).GetPointer()); - if (dataPatient == nullptr) - MITK_ERROR << "DilateBinaryByName - Structure of DataCollection is invalid at patient level. Data inconsistent!"; - - if (dataPatient->Size() == 0) - MITK_ERROR << "Empty Patient Collective. Probably Fatal."; - - for (size_t timeStep = 0; timeStep < dataPatient->Size(); ++timeStep) - { - DataCollection *dataTimeStep = dynamic_cast(dataPatient->GetData(timeStep).GetPointer()); - if (dataTimeStep == nullptr) - MITK_ERROR - << "DilateBinaryByName- Structure of DataCollection is invalid at time step level. Data inconsistent!"; - - BinaryImage::Pointer itkTumorSeed = BinaryImage::New(); - Image *tumorSeed = dynamic_cast(dataTimeStep->GetMitkImage(name).GetPointer()); - if (tumorSeed == nullptr) - MITK_ERROR << "Image " << name << " does not exits. Fatal."; - - CastToItkImage(tumorSeed, itkTumorSeed); - - typedef itk::FlatStructuringElement<3> StructuringElementType; - StructuringElementType::RadiusType elementRadius; - elementRadius.Fill(xy); - elementRadius[2] = z; - - StructuringElementType structuringElement = StructuringElementType::Box(elementRadius); - - typedef itk::BinaryErodeImageFilter BinaryErodeImageFilterType; - - BinaryErodeImageFilterType::Pointer dilateFilter0 = BinaryErodeImageFilterType::New(); - dilateFilter0->SetInput(itkTumorSeed); - dilateFilter0->SetKernel(structuringElement); - dilateFilter0->SetForegroundValue(1); - dilateFilter0->Update(); - - Image::Pointer dil = GrabItkImageMemory(dilateFilter0->GetOutput()); - - dil->SetGeometry(tumorSeed->GetGeometry()); - dataTimeStep->AddData(dil.GetPointer(), name + suffix, "Dilated Binary"); - } - } -} diff --git a/Modules/TumorInvasionAnalysis/src/ImageFilters/mitkCollectionGrayOpening.cpp b/Modules/TumorInvasionAnalysis/src/ImageFilters/mitkCollectionGrayOpening.cpp deleted file mode 100644 index 4d2811f5c8..0000000000 --- a/Modules/TumorInvasionAnalysis/src/ImageFilters/mitkCollectionGrayOpening.cpp +++ /dev/null @@ -1,74 +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 "mitkCollectionGrayOpening.h" -#include -#include - -#include "itkBinaryBallStructuringElement.h" -#include "itkBinaryDilateImageFilter.h" -#include "itkFlatStructuringElement.h" -#include "itkGrayscaleMorphologicalOpeningImageFilter.h" - -void mitk::CollectionGrayOpening::PerformGrayOpening(mitk::DataCollection *dataCollection, - std::string name, - std::string suffix) -{ - for (size_t patient = 0; patient < dataCollection->Size(); ++patient) - { - DataCollection *dataPatient = dynamic_cast(dataCollection->GetData(patient).GetPointer()); - if (dataPatient == nullptr) - MITK_ERROR << "PerformGrayOpening - Structure of DataCollection is invalid at patient level. Data inconsistent!"; - - if (dataPatient->Size() == 0) - MITK_ERROR << "Empty Patient Collective. Probably Fatal."; - - for (size_t timeStep = 0; timeStep < dataPatient->Size(); ++timeStep) - { - DataCollection *dataTimeStep = dynamic_cast(dataPatient->GetData(timeStep).GetPointer()); - if (dataTimeStep == nullptr) - MITK_ERROR - << "DilateBinaryByName- Structure of DataCollection is invalid at time step level. Data inconsistent!"; - - // BinaryImage::Pointer itkImage = BinaryImage::New(); - ImageType::Pointer itkImage = ImageType::New(); - Image::Pointer tmp = dataTimeStep->GetMitkImage(name).GetPointer(); - if (tmp.IsNull()) - MITK_ERROR << "null"; - CastToItkImage(tmp, itkImage); - if (itkImage.IsNull()) - MITK_ERROR << "Image " << name << " does not exist. Fatal."; - - typedef itk::FlatStructuringElement<3> StructuringElementType; - StructuringElementType::RadiusType elementRadius; - elementRadius.Fill(1); - elementRadius[2] = 0; - StructuringElementType structuringElement = StructuringElementType::Box(elementRadius); - - typedef itk::GrayscaleMorphologicalOpeningImageFilter - DilateImageFilterType; - - DilateImageFilterType::Pointer dilateFilter0 = DilateImageFilterType::New(); - dilateFilter0->SetInput(itkImage); - dilateFilter0->SetKernel(structuringElement); - dilateFilter0->Update(); - - DilateImageFilterType::Pointer dilateFilter1 = DilateImageFilterType::New(); - dilateFilter1->SetInput(dilateFilter0->GetOutput()); - dilateFilter1->SetKernel(structuringElement); - dilateFilter1->Update(); - - Image::Pointer dil = GrabItkImageMemory(dilateFilter1->GetOutput()); - dataTimeStep->AddData(dil.GetPointer(), name + suffix, ""); - } - } -} diff --git a/Modules/TumorInvasionAnalysis/src/ReaderWriter/mitkDiffusionCollectionReader.cpp b/Modules/TumorInvasionAnalysis/src/ReaderWriter/mitkDiffusionCollectionReader.cpp deleted file mode 100644 index 1ba2eb7170..0000000000 --- a/Modules/TumorInvasionAnalysis/src/ReaderWriter/mitkDiffusionCollectionReader.cpp +++ /dev/null @@ -1,402 +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. - -============================================================================*/ -#ifdef _MSC_VER -# pragma warning (disable : 4996) -#endif - -#include "mitkDiffusionCollectionReader.h" -#include - -#include -#include -#include - -#include - -//XML StateMachine Tags -// Objects -const std::string COLLECTION = "col"; -const std::string SUBCOLLECTION = "subcol"; -const std::string DATA = "data"; -const std::string ITEM = "item"; -// Properties -const std::string NAME = "name"; -const std::string ID = "id"; -const std::string FILEPATH = "description"; -const std::string LINK = "link"; - - -static std::string GetName(std::string fileName,std::string suffix) -{ - fileName = QFileInfo(QString::fromStdString(fileName)).fileName().toStdString(); - return fileName.substr(0,fileName.length() -suffix.length()-9); // 8 = date length -} - -static std::string GetDate(std::string fileName,std::string suffix) -{ - fileName = QFileInfo(QString::fromStdString(fileName)).fileName().toStdString(); - fileName = fileName.substr(fileName.length() - suffix.length()-8,8); // 8 = date length - fileName.insert(6,"-"); - fileName.insert(4,"-"); - return fileName; -} - - -mitk::DiffusionCollectionReader::DiffusionCollectionReader() - : m_Collection(nullptr), - m_SubCollection(nullptr), - m_DataItemCollection(nullptr), - m_ColIgnore(false), m_ItemIgnore(false) -{ -} - -mitk::DiffusionCollectionReader::~DiffusionCollectionReader() -{ - this->Clear(); -} - - -/** - * @brief Loads the xml file filename and generates the necessary instances. - **/ -mitk::DataCollection::Pointer mitk::DiffusionCollectionReader::LoadCollection(const std::string& xmlFileName) -{ - QDir fileName = QFileInfo(xmlFileName.c_str()).absoluteDir(); - m_BaseDir = fileName.path().toStdString() + QDir::separator().toLatin1(); - this->SetFileName(xmlFileName.c_str()); - this->Parse(); - if (m_Collection.IsNotNull()) - m_Collection->SetXMLFile(xmlFileName); - return m_Collection; -} - -void mitk::DiffusionCollectionReader::AddDataElementIds(std::vector dataElemetIds) -{ - m_SelectedDataItemIds.insert( m_SelectedDataItemIds.end(), dataElemetIds.begin(), dataElemetIds.end() ); -} - -void mitk::DiffusionCollectionReader::AddSubColIds(std::vector subColIds) -{ - m_SelectedSubColIds.insert( m_SelectedSubColIds.end(), subColIds.begin(), subColIds.end() ); -} - -void mitk::DiffusionCollectionReader::SetDataItemNames(std::vector itemNames) -{ - m_SelectedDataItemNames = itemNames; -} - -void mitk::DiffusionCollectionReader::ClearDataElementIds() -{ - m_SelectedDataItemIds.clear(); -} - -void mitk::DiffusionCollectionReader::ClearSubColIds() -{ - m_SelectedSubColIds.clear(); -} - -void mitk::DiffusionCollectionReader::Clear() -{ - m_DataItemCollection = nullptr; - m_SubCollection = nullptr; - m_Collection = nullptr; -} - -mitk::DataCollection::Pointer mitk::DiffusionCollectionReader::FolderToCollection(std::string folder, std::vector suffixes,std::vector seriesNames, bool allowGaps) -{ - // Parse folder and look up all data, - // after sanitation only fully available groups are included (that is all suffixes are found) - FileListType fileList = SanitizeFileList(GenerateFileLists(folder, suffixes, allowGaps)); - - if (fileList.size() <= 0) - return nullptr; - - DataCollection::Pointer collection = DataCollection::New(); - collection->SetName(GetName(fileList.at(0).at(0),suffixes.at(0))); - - for (unsigned int k=0; k < fileList.at(0).size(); ++k) // all groups have the same amount of items, so looking at 0 is ok. - { - DataCollection::Pointer subCollection = DataCollection::New(); - for (unsigned int i=0; i< suffixes.size(); ++i) - { - std::string fileName = fileList.at(i).at(k); - if (fileName.find(".fib") >= fileName.length()) - { - auto image = IOUtil::Load(fileList.at(i).at(k)); - subCollection->AddData(image.GetPointer(),seriesNames.at(i), fileList.at(i).at(k)); - } - else - { - subCollection->AddData(mitk::IOUtil::Load(fileName).at(0).GetPointer(),seriesNames.at(i), fileList.at(i).at(k)); - } - } - std::string sDate = GetDate(fileList.at(0).at(k),suffixes.at(0)); - collection->AddData(subCollection.GetPointer(),sDate,"--"); - } - return collection; -} - -void mitk::DiffusionCollectionReader::StartElement(const char* elementName, const char **atts) -{ - std::string name(elementName); - - if (name == COLLECTION) - { - m_Collection = DataCollection::New(); - std::string colName = ReadXMLStringAttribut(NAME, atts); - m_Collection->SetName(colName); - } - else if (name == SUBCOLLECTION) - { - m_ColIgnore = false; - m_ItemIgnore = false; - - std::string subColName = ReadXMLStringAttribut(NAME, atts); - std::string subColId = ReadXMLStringAttribut(ID, atts); - - if (m_SelectedSubColIds.size() > 0 && std::find(m_SelectedSubColIds.begin(), m_SelectedSubColIds.end(), subColId) == m_SelectedSubColIds.end() ) - { // a) a selection list is provided AND b) the item is not in the list - m_ColIgnore = true; - return; - } - - // Create subcollection - m_SubCollection = DataCollection::New(); - m_SubCollection->Init(subColName); - } - else if (name == DATA) - { - if (m_ColIgnore) - return; - - std::string dataId = ReadXMLStringAttribut(ID, atts); - if (m_SelectedDataItemIds.size() > 0 && std::find(m_SelectedDataItemIds.begin(), m_SelectedDataItemIds.end(), dataId) == m_SelectedDataItemIds.end() ) - { // a) a selection list is provided AND b) the item is not in the list - m_ItemIgnore = true; - return; - } - m_ItemIgnore = false; - std::string dataName = ReadXMLStringAttribut(NAME, atts); - - m_DataItemCollection = DataCollection::New(); - m_DataItemCollection->Init(dataName); - } - else if (name == ITEM) - { - if (m_ColIgnore || m_ItemIgnore) - return; - - - std::string relativeItemLink = ReadXMLStringAttribut(LINK, atts); - std::string itemLink = m_BaseDir + relativeItemLink; - std::string itemName = ReadXMLStringAttribut(NAME, atts); - - // if item names are provided and name is not in list, do not load it - if (m_SelectedDataItemNames.size() != 0 && std::find(m_SelectedDataItemNames.begin(), m_SelectedDataItemNames.end(), itemName) == m_SelectedDataItemNames.end() ) - return; - - // Populate Sub-Collection - if (itemLink.find(".fib") >= itemLink.length()) - { - auto image = IOUtil::Load(itemLink); - if (image.IsNotNull()) - m_DataItemCollection->AddData(image.GetPointer(),itemName,relativeItemLink); - else - MITK_ERROR << "File could not be loaded: " << itemLink << ". Wihtin Sub-Collection " << m_SubCollection->GetName() << ", within " << m_DataItemCollection->GetName() ; - } - else - m_DataItemCollection->AddData(mitk::IOUtil::Load(itemLink).at(0).GetPointer(),itemName, relativeItemLink); - } - else - MITK_WARN<< "Malformed description ? -- unknown tag: " << name; -} - -void mitk::DiffusionCollectionReader::EndElement(const char* elementName) -{ - std::string name(elementName); - if (name == SUBCOLLECTION) - { - if (m_SubCollection.IsNull()) - return; - if (m_ColIgnore || m_SubCollection->Size() == 0) - return; - - m_Collection->AddData(m_SubCollection.GetPointer(),m_SubCollection->GetName()); - m_SubCollection = DataCollection::New(); - } - if (name == DATA) - { - if (m_DataItemCollection.IsNull()) - return; - if (m_DataItemCollection->Size() == 0) - return; - - m_SubCollection->AddData(m_DataItemCollection.GetPointer(),m_DataItemCollection->GetName()); - m_DataItemCollection = DataCollection::New(); - } -} - -std::string mitk::DiffusionCollectionReader::ReadXMLStringAttribut(std::string name, const char** atts) -{ - if (atts) - { - const char** attsIter = atts; - - while (*attsIter) - { - if (name == *attsIter) - { - attsIter++; - return *attsIter; - } - attsIter++; - attsIter++; - } - } - return std::string(); -} - -bool mitk::DiffusionCollectionReader::ReadXMLBooleanAttribut(std::string name, const char** atts) -{ - std::string s = ReadXMLStringAttribut(name, atts); - std::transform(s.begin(), s.end(), s.begin(), ::toupper); - if (s == "TRUE") - return true; - else - return false; -} - - -int mitk::DiffusionCollectionReader::ReadXMLIntegerAttribut(std::string name, const char** atts) -{ - std::string s = ReadXMLStringAttribut(name, atts); - return atoi(s.c_str()); -} - - - -mitk::DiffusionCollectionReader::FileListType mitk::DiffusionCollectionReader::GenerateFileLists(std::string folder, std::vector suffixes, bool allowGaps) -{ - FileListType fileList; - QString qFolder = QString::fromStdString(folder); - if (!QFileInfo(qFolder).isDir()) - { - MITK_ERROR << "Folder does not exist."; - return fileList; - } - // Add vector for each suffix - for (unsigned int i=0; i< suffixes.size(); ++i) - { - std::vector list; - fileList.push_back(list); - } - - // if gaps are allowed, file names are build up from reference file (first suffix) - // else all lists a file, file by file with regular sorting of the files, - // if one suffix has more/less images than the others loading is aborted - if (allowGaps) - { - QDir parseDir; - parseDir.setFilter(QDir::Files); - parseDir.setPath(qFolder); - QStringList filterMorph; - filterMorph << "*" + QString::fromStdString( suffixes.at(0) ); - parseDir.setNameFilters( filterMorph ); - - QFileInfoList qFileList = parseDir.entryInfoList(); - - // now populate lists with files names, non-existing files will be marked with an empty string - for (int i = 0; i < qFileList.size(); ++i) - { - std::string baseFileName = qFileList.at(i).absoluteFilePath().toStdString(); - fileList.at(0).push_back( baseFileName ); - - //check for different suffixes - for (unsigned int suffNo=1; suffNo < suffixes.size(); ++suffNo) - { - std::string derivedFileName = baseFileName.substr(0,baseFileName.length() -suffixes.at(0).length()) + suffixes.at(suffNo); - - // checking if file exists - if (QFileInfo(QString::fromStdString(derivedFileName)).isFile()) - fileList.at(suffNo).push_back(derivedFileName); - else - fileList.at(suffNo).push_back(""); - } - } - } - else - { - int numberOfFiles=-1; - for (unsigned int i=0; i< suffixes.size(); ++i) - { - QDir parseDir; - parseDir.setFilter(QDir::Files); - parseDir.setPath(qFolder); - QStringList filterMorph; - filterMorph << "*" + QString::fromStdString( suffixes.at(i) ); - parseDir.setNameFilters( filterMorph ); - - QFileInfoList qFileList = parseDir.entryInfoList(); - if (numberOfFiles == -1) - numberOfFiles = qFileList.size(); - - if (numberOfFiles != qFileList.size() ) - { - MITK_ERROR << "Series contain different number of images. Loading aborting."; - fileList.clear(); - break; - } - - for (int fileNo=0; fileNo indexRemoval; - // Parse through all items and check for empty strings, if one occurs mark this index - // for removal. - int modalities = list.size(); - int timeSteps = list.at(0).size(); - MITK_INFO << "Modalities " << modalities; - MITK_INFO << "TimeSteps " << timeSteps; - if (timeSteps == 0) - MITK_ERROR << "No files found. Fatal."; - for (int listIndex = 0 ; listIndex < timeSteps; listIndex++) - { - for (int modalityIndex = 0 ; modalityIndex < modalities; modalityIndex++) - { - if (list.at(modalityIndex).at(listIndex) == "") - { - MITK_INFO << "Marked Index " << listIndex << " for removal."; - indexRemoval.push_back(listIndex); - break; - } - } - } - - - for (int listIndex = indexRemoval.size()-1 ; listIndex >= 0; --listIndex) - { - for (int i = 0 ; i < modalities; i++) - { - list.at(i).erase(list.at(i).begin()+indexRemoval.at(listIndex)) ; - } - } - MITK_INFO << "Time Steps after sanitizing: " << list.at(0).size(); - return list; -} diff --git a/Modules/TumorInvasionAnalysis/src/ReaderWriter/mitkDiffusionCollectionWriter.cpp b/Modules/TumorInvasionAnalysis/src/ReaderWriter/mitkDiffusionCollectionWriter.cpp deleted file mode 100755 index 9a2fbb56b3..0000000000 --- a/Modules/TumorInvasionAnalysis/src/ReaderWriter/mitkDiffusionCollectionWriter.cpp +++ /dev/null @@ -1,460 +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. - -============================================================================*/ -#ifdef _MSC_VER -# pragma warning (disable : 4996) -#endif - -#include "mitkDiffusionCollectionWriter.h" - -#include -#include -#include - -#include "mitkImageCast.h" -#include "mitkTensorImage.h" -#include "itkNrrdImageIO.h" -#include "itkImageFileWriter.h" -#include "mitkCoreObjectFactory.h" - - -#include -#include - -#include - -//XML StateMachine Tags -// Objects -const std::string COLLECTION = "col"; -const std::string SUBCOLLECTION = "subcol"; -const std::string DATA = "data"; -const std::string ITEM = "item"; -// Properties -const std::string NAME = "name"; -const std::string ID = "id"; -const std::string FILEPATH = "filepath"; -const std::string LINK = "link"; - - -static std::string GetName(std::string fileName,std::string suffix, bool longName = false) -{ - fileName = QFileInfo(QString::fromStdString(fileName)).fileName().toStdString(); - if (longName) - return fileName.substr(0,fileName.length() -suffix.length()-11); // 10 = date length - else - return fileName.substr(0,fileName.length() -suffix.length()-9); // 8 = date length -} - -static std::string GetDate(std::string fileName,std::string suffix, bool longName = false) -{ - fileName = QFileInfo(QString::fromStdString(fileName)).fileName().toStdString(); - if (longName) - fileName = fileName.substr(fileName.length() - suffix.length()-10,10); // 8 = date length - else - fileName = fileName.substr(fileName.length() - suffix.length()-8,8); // 8 = date length - if (!longName) - { - fileName.insert(6,"-"); - fileName.insert(4,"-"); - } - return fileName; -} - - - - -bool mitk::DiffusionCollectionWriter::ExportCollectionToFolder(DataCollection *dataCollection, std::string xmlFile, std::vector filter) -{ - // Quick and Dirty: Assumes three level DataCollection - QDir fileName = QFileInfo(xmlFile.c_str()).absoluteDir(); - std::string outputFolder = fileName.path().toStdString() + QDir::separator().toLatin1(); - QDir baseFolder(outputFolder.c_str()); - baseFolder.mkpath(outputFolder.c_str()); - - std::ofstream xmlFileStream; - xmlFileStream.open (xmlFile.c_str()); - xmlFileStream << " \n"; - xmlFileStream << "<" << COLLECTION << " " << NAME << "=\"" << dataCollection->GetName() << "\" >\n"; - unsigned int subColId = 0; - - unsigned int dataId = 0; - - QDir dir(QString::fromStdString(outputFolder)); - for (size_t i = 0 ; i < dataCollection->Size(); ++i) - { - // Write Subcollection tag - xmlFileStream << " <" << SUBCOLLECTION << " " << NAME << "=\"" << dataCollection->IndexToName(i) << "\" " << FILEPATH << "=\"" << dataCollection->GetDataFilePath(i) << "\" id=\"Col" << subColId << "\" >\n"; - // Create Sub-Folder - dir.mkpath(QString::fromStdString(dataCollection->IndexToName(i))); - - // Herein create data folders - DataCollection* subCollections = dynamic_cast (dataCollection->GetData(i).GetPointer()); - if (subCollections == nullptr) - { - MITK_ERROR<< "mitk::DiffusionCollectionWriter::SaveCollectionToFolder: Container is illformed. Aborting"; - return false; - } - - for (size_t d = 0; d < subCollections->Size(); d++ ) - { - // Create Sub Paths - QString subPath = QString::fromStdString(dataCollection->IndexToName(i))+"/"+QString::fromStdString(subCollections->IndexToName(d)); - dir.mkpath(subPath); - xmlFileStream << " <" << DATA << " " << NAME << "=\"" << subCollections->IndexToName(d) << "\" " << FILEPATH << "=\"" << subCollections->GetDataFilePath(d) << "\" id=\"Data" << dataId << "\" >\n"; - - DataCollection* itemCollections = dynamic_cast (subCollections->GetData(d).GetPointer()); - if (itemCollections == nullptr) - { - MITK_ERROR<< "mitk::DiffusionCollectionWriter::SaveCollectionToFolder: Container is illformed. Aborting"; - return false; - } - - for (size_t s = 0; s < itemCollections->Size(); s++) - { - if (filter.size() > 0) - { - bool isSelected = false; - for (size_t f = 0; f < filter.size(); f++) - { - if (filter.at(f) == itemCollections->IndexToName(s) ) - { - isSelected = true; - break; - } - } - if (isSelected == false) - continue; - } - Image* image = dynamic_cast (itemCollections->GetData(s).GetPointer()); - QString fileName = dir.path() + dir.separator() + subPath + dir.separator() + QString::fromStdString(dataCollection->IndexToName(i)) + "_" + QString::fromStdString(subCollections->IndexToName(d)) + "_" + QString::fromStdString(itemCollections->IndexToName(s)); - try - { - if (itemCollections->IndexToName(s) == "DTI" || itemCollections->IndexToName(s) == "DTIFWE") - { - fileName += ".dti"; - IOUtil::Save(image,fileName.toStdString()); - } - else if (itemCollections->IndexToName(s) == "FIB") - { - fileName += ".fib"; - FiberBundle* fib = dynamic_cast (itemCollections->GetData(s).GetPointer()); - IOUtil::Save(fib, fileName.toStdString()); - } - else if (itemCollections->IndexToName(s) == "DWI") - { - fileName += ".dwi"; - IOUtil::Save(image,fileName.toStdString()); - } - else - { - fileName += ".nrrd"; - Image::Pointer image = itemCollections->GetMitkImage(s).GetPointer(); - IOUtil::Save(image,fileName.toStdString()); - } - } - catch( const std::exception& e) - { - MITK_ERROR << "Caught exception: " << e.what(); - } - - std::string relativeFilename = baseFolder.relativeFilePath(fileName).toStdString(); - xmlFileStream << " <" << ITEM << " " << NAME << "=\"" <IndexToName(s) << "\" " << FILEPATH << "=\"" << "\" " << LINK << "=\"" << relativeFilename << "\" />\n"; - } - xmlFileStream << " \n"; - dataId++; - } - - xmlFileStream << " \n"; - subColId++; - } - xmlFileStream << "\n"; - xmlFileStream.flush(); - xmlFileStream.close(); - return true; -} - -bool mitk::DiffusionCollectionWriter::ExportCollectionToFolder(mitk::DataCollection *dataCollection, std::string xmlFile) -{ - std::vector mods; - return ExportCollectionToFolder(dataCollection,xmlFile, mods); -} - -bool mitk::DiffusionCollectionWriter::SaveCollection(mitk::DataCollection *dataCollection, std::vector filter, std::string xmlFile) -{ - QDir origFilename = QFileInfo(dataCollection->GetXMLFile().c_str()).absoluteDir(); - QString originalFolder = origFilename.path() + QDir::separator(); - - if (xmlFile == "") - xmlFile = dataCollection->GetXMLFile(); - - QDir fileName = QFileInfo(xmlFile.c_str()).absoluteDir(); - std::string outputFolder = fileName.path().toStdString() + QDir::separator().toLatin1(); - QDir baseFolder(outputFolder.c_str()); - - std::ofstream xmlFileStream; - xmlFileStream.open (xmlFile.c_str()); - xmlFileStream << " \n"; - xmlFileStream << "<" << COLLECTION << " " << NAME << "=\"" << dataCollection->GetName() << "\" >\n"; - unsigned int subColId = 0; - - unsigned int dataId = 0; - - QDir dir(QString::fromStdString(outputFolder)); - for (size_t i = 0 ; i < dataCollection->Size(); ++i) - { - // Write Subcollection tag - xmlFileStream << " <" << SUBCOLLECTION << " " << NAME << "=\"" << dataCollection->IndexToName(i) << "\" " << FILEPATH << "=\"" << dataCollection->GetDataFilePath(i) << "\" id=\"Col" << subColId << "\" >\n"; - // Create Sub-Folder - dir.mkpath(QString::fromStdString(dataCollection->IndexToName(i))); - - // Herein create data folders - DataCollection* subCollections = dynamic_cast (dataCollection->GetData(i).GetPointer()); - if (subCollections == nullptr) - { - MITK_ERROR<< "mitk::DiffusionCollectionWriter::SaveCollectionToFolder: Container is illformed. Aborting"; - return false; - } - - for (size_t d = 0; d < subCollections->Size(); d++ ) - { - // Create Sub Paths - QString subPath = QString::fromStdString(dataCollection->IndexToName(i))+"/"+QString::fromStdString(subCollections->IndexToName(d)); - dir.mkpath(subPath); - xmlFileStream << " <" << DATA << " " << NAME << "=\"" << subCollections->IndexToName(d) << "\" " << FILEPATH << "=\"" << subCollections->GetDataFilePath(d) << "\" id=\"Data" << dataId << "\" >\n"; - - DataCollection* itemCollections = dynamic_cast (subCollections->GetData(d).GetPointer()); - if (itemCollections == nullptr) - { - MITK_ERROR<< "mitk::DiffusionCollectionWriter::SaveCollectionToFolder: Container is illformed. Aborting"; - return false; - } - - for (size_t s = 0; s < itemCollections->Size(); s++) - { - if (filter.size() > 0) - { - bool isSelected = false; - for (size_t f = 0; f < filter.size(); f++) - { - if (filter.at(f) == itemCollections->IndexToName(s) ) - { - isSelected = true; - break; - } - } - if (isSelected == false) - continue; - } - Image* image = dynamic_cast (itemCollections->GetData(s).GetPointer()); - QString fileName; - bool fullName = false; - if (itemCollections->GetDataFilePath(s) != "") - { - fileName = originalFolder + QString::fromStdString(itemCollections->GetDataFilePath(s)); - fullName = true; - MITK_INFO << "original path: " << itemCollections->GetDataFilePath(s) ; - } - else - fileName = dir.path() + dir.separator() + subPath + dir.separator() + QString::fromStdString(dataCollection->IndexToName(i)) + "_" + QString::fromStdString(subCollections->IndexToName(d)) + "_" + QString::fromStdString(itemCollections->IndexToName(s)); - - try - { - if (itemCollections->IndexToName(s) == "DTI" || itemCollections->IndexToName(s) == "DTIFWE") - { - if (!fullName) - fileName += ".dti"; - IOUtil::Save(image,fileName.toStdString()); - } - else if (itemCollections->IndexToName(s) == "FIB") - { - if (!fullName) - fileName += ".fib"; - FiberBundle* fib = dynamic_cast (itemCollections->GetData(s).GetPointer()); - IOUtil::Save(fib, fileName.toStdString()); - } - else if (itemCollections->IndexToName(s) == "DWI") - { - if (!fullName) - fileName += ".dwi"; - IOUtil::Save(image,fileName.toStdString()); - } - else - { - if (!fullName) - fileName += ".nrrd"; - Image::Pointer image = itemCollections->GetMitkImage(s).GetPointer(); - IOUtil::Save(image,fileName.toStdString()); - } - } - catch( const std::exception& e) - { - MITK_ERROR << "Caught exception: " << e.what(); - } - - std::string relativeFilename =baseFolder.relativeFilePath(fileName).toStdString(); - xmlFileStream << " <" << ITEM << " " << NAME << "=\"" <IndexToName(s) << "\" " << FILEPATH << "=\"" << "\" " << LINK << "=\"" << relativeFilename << "\" />\n"; - } - xmlFileStream << " \n"; - dataId++; - } - - xmlFileStream << " \n"; - subColId++; - } - xmlFileStream << "\n"; - xmlFileStream.flush(); - xmlFileStream.close(); - return true; -} - -bool mitk::DiffusionCollectionWriter::FolderToXml(std::string folder, std::string collectionType, std::string xmlFile, std::vector filter, std::vector seriesNames) -{ - // 1) Parse for folders - - QDir parseDir; - parseDir.setFilter( QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot); - parseDir.setPath(QString::fromStdString(folder)); - - QFileInfoList qFileList = parseDir.entryInfoList(); - - - std::ofstream xmlFileStream; - xmlFileStream.open (xmlFile.c_str()); - xmlFileStream << " \n"; - xmlFileStream << "<" << COLLECTION << " " << NAME << "=\"" << "GEN" << "\" >\n"; - - unsigned int dataId = 0; - - // now populate lists with files names, non-existing files will be marked with an empty string - for (int i = 0; i < qFileList.size(); ++i) - { - // 2) For Each sub folder construct collectionType sub-folder - std::string baseFolder = qFileList.at(i).absoluteFilePath().toStdString() + QDir::separator().toLatin1() + collectionType; - - MITK_INFO << "Processing : " << baseFolder; - if (!QFileInfo(QString::fromStdString(baseFolder)).isDir()) - { - MITK_WARN << "Not a valid folder, skipping."; - continue; - } - - // 3) Parse each sub folder and extend XML file - // Parse folder and look up all data, - // after sanitation only fully available groups are included (that is all suffixes are found) - - DiffusionCollectionReader::FileListType fileList = DiffusionCollectionReader::SanitizeFileList(DiffusionCollectionReader::GenerateFileLists(baseFolder, filter,true)); - if (fileList.size() <= 0 || fileList.at(0).size() <= 0) - continue; - - // Write Subcollection tag - // try to extract date out of filename - std::string name = GetName(fileList.at(0).at(0),filter.at(0)); - xmlFileStream << " <" << SUBCOLLECTION << " " << NAME << "=\"" << name << "\" " << FILEPATH << "=\"\" id=\"Col" << i << "\" >\n"; - - - for (unsigned int k=0; k < fileList.at(0).size(); ++k) // all groups have the same amount of items, so looking at 0 is ok. - { - std::string strDate = GetDate(fileList.at(0).at(k),filter.at(0)); - xmlFileStream << " <" << DATA << " " << NAME << "=\"" << strDate << "\" " << " id=\"Data" << dataId << "\" >\n"; - dataId++; - for (unsigned int i=0; i< filter.size(); ++i) - { - std::string fileName = fileList.at(i).at(k); - xmlFileStream << " <" << ITEM << " " << NAME << "=\"" << seriesNames.at(i) << "\" " << LINK << "=\"" << fileName << "\" />\n"; - } - xmlFileStream << " \n" ; - } - xmlFileStream << " \n"; - } - - xmlFileStream << "\n"; - xmlFileStream.flush(); - xmlFileStream.close(); - - return true; -} - -bool mitk::DiffusionCollectionWriter::SingleFolderToXml(std::string folder, std::string xmlFile, std::vector filter, std::vector seriesNames, bool longDate, int skipUntil, float months) -{ - std::ofstream xmlFileStream; - xmlFileStream.open (xmlFile.c_str()); - xmlFileStream << " \n"; - xmlFileStream << "<" << COLLECTION << " " << NAME << "=\"" << "GEN" << "\" >\n"; - - unsigned int dataId = 0; - - // 1) - // Parse folder and look up all data, - // after sanitation only fully available groups are included (that is all suffixes are found) - - DiffusionCollectionReader::FileListType fileList = DiffusionCollectionReader::SanitizeFileList(DiffusionCollectionReader::GenerateFileLists(folder, filter,true)); - - // Write Subcollection tag - // try to extract date out of filename - std::string name = GetName(fileList.at(0).at(0),filter.at(0),longDate); - xmlFileStream << " <" << SUBCOLLECTION << " " << NAME << "=\"" << name << "\" " << FILEPATH << "=\"\" id=\"Col" << 0 << "\" >\n"; - - - for (unsigned int k=skipUntil; k < fileList.at(0).size(); ++k) // all groups have the same amount of items, so looking at 0 is ok. - { - std::string strDate = GetDate(fileList.at(0).at(k),filter.at(0),true); - xmlFileStream << " <" << DATA << " " << NAME << "=\"" << strDate << "\" " << " id=\"Data" << dataId << "\" >\n"; - dataId++; - for (unsigned int i=0; i< filter.size(); ++i) - { - std::string fileName = fileList.at(i).at(k); - xmlFileStream << " <" << ITEM << " " << NAME << "=\"" << seriesNames.at(i) << "\" " << LINK << "=\"" << fileName << "\" />\n"; - } - - // size_t ind = GetIndexForinXMonths(fileList,months,k,filter); - // xmlFileStream << " <" << ITEM << " " << NAME << "=\"TARGET\" " << LINK << "=\"" << fileList.at(filter.size()-1).at(ind) << "\" />\n"; - - xmlFileStream << " \n" ; - // check if target still exists for next step - if (GetIndexForinXMonths(fileList,months,k+1,filter)== 0) - break; - } - xmlFileStream << " \n"; - - xmlFileStream << "\n"; - xmlFileStream.flush(); - xmlFileStream.close(); - - return true; -} - -size_t mitk::DiffusionCollectionWriter::GetIndexForinXMonths(mitk::DiffusionCollectionReader::FileListType fileList,float months, size_t curIndex,std::vector filter) -{ - std::string strDate0 = GetDate(fileList.at(0).at(curIndex),filter.at(0),true); - - int year0 =std::atoi(strDate0.substr(0,4).c_str()); - int month0 =std::atoi(strDate0.substr(5,2).c_str()); - int day0 = std::atoi(strDate0.substr(8,2).c_str()); - - size_t bestIndex = 0; - int bestFit = 1e5; - - for (size_t i=curIndex+1; i < fileList.at(0).size(); ++i) - { - std::string strDate = GetDate(fileList.at(0).at(i),filter.at(0),true); - int year =std::atoi(strDate.substr(0,4).c_str()); - int month =std::atoi(strDate.substr(5,2).c_str()); - int day = std::atoi(strDate.substr(8,2).c_str()); - - int fit = std::fabs((months * 30 ) - (((year-year0)*360) +((month-month0)*30) + (day-day0))); // days difference from x months - if (fit < bestFit) - { - bestFit = fit; - bestIndex = i; - } - } - return bestIndex; -} diff --git a/Modules/TumorInvasionAnalysis/test/CMakeLists.txt b/Modules/TumorInvasionAnalysis/test/CMakeLists.txt deleted file mode 100644 index 153cd81e2e..0000000000 --- a/Modules/TumorInvasionAnalysis/test/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -MITK_CREATE_MODULE_TESTS() diff --git a/Modules/TumorInvasionAnalysis/test/files.cmake b/Modules/TumorInvasionAnalysis/test/files.cmake deleted file mode 100644 index 138e885252..0000000000 --- a/Modules/TumorInvasionAnalysis/test/files.cmake +++ /dev/null @@ -1,4 +0,0 @@ -set(MODULE_CUSTOM_TESTS - ## Testing the basic classification funtionality - mitkClassificationTest.cpp -) diff --git a/Modules/TumorInvasionAnalysis/test/mitkClassificationTest.cpp b/Modules/TumorInvasionAnalysis/test/mitkClassificationTest.cpp deleted file mode 100644 index 0a85a7e36a..0000000000 --- a/Modules/TumorInvasionAnalysis/test/mitkClassificationTest.cpp +++ /dev/null @@ -1,105 +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. - -============================================================================*/ -#ifdef _MSC_VER -# pragma warning(disable : 4996) -#endif - -#include "mitkTestFixture.h" -#include "mitkTestingMacros.h" - -#include "mitkCompareImageDataFilter.h" -#include "mitkIOUtil.h" - -#include "mitkDataCollection.h" -#include "mitkTumorInvasionClassification.h" -#include "mitkDiffusionCollectionReader.h" -#include "mitkDiffusionCollectionWriter.h" - -#include - -/** - * @brief mitkClassificationTestSuite - * - * Tests mitkDecisionForest, mitkClassifyProgression, mitkDataCollection, mitkDiffusionCollectionReader - * \warn Reference is compared to results computed based on random forests, which might be a source of random test fails - * such sporadic fails do represent total fails, as the result is no longer consitently under the provided margin. - * - */ -class mitkClassificationTestSuite : public mitk::TestFixture -{ - CPPUNIT_TEST_SUITE(mitkClassificationTestSuite); - MITK_TEST(TestClassification); - CPPUNIT_TEST_SUITE_END(); - -public: - /** - * @brief Setup - Always call this method before each Test-case to ensure correct and new intialization of the used - * members for a new test case. (If the members are not used in a test, the method does not need to be called). - */ - void setUp() override {} - void tearDown() override {} - void TestClassification() - { - size_t forestSize = 10; - size_t treeDepth = 2; - - std::string train = GetTestDataFilePath("DiffusionImaging/ProgressionAnalysis/Classification/Train.xml"); - std::string eval = GetTestDataFilePath("DiffusionImaging/ProgressionAnalysis/Classification/Test.xml"); - - std::vector modalities; - - modalities.push_back("MOD0"); - modalities.push_back("MOD1"); - - mitk::DiffusionCollectionReader colReader; - mitk::DataCollection::Pointer collection = colReader.LoadCollection(train); - colReader.Clear(); - // read evaluation collection - - mitk::DataCollection::Pointer evaluation = colReader.LoadCollection(eval); - - mitk::TumorInvasionClassification progression; - - progression.SetClassRatio(1); - progression.SetTrainMargin(4, 0); - progression.SetMaskID("MASK"); - - progression.SelectTrainingSamples(collection); - progression.LearnProgressionFeatures(collection, modalities, forestSize, treeDepth); - - progression.PredictInvasion(evaluation, modalities); - - auto refImage = mitk::IOUtil::Load( - GetTestDataFilePath("DiffusionImaging/ProgressionAnalysis/Classification/TESTING_RESULT.nrrd")); - - mitk::DataCollection *patCol = dynamic_cast(evaluation->GetData(0).GetPointer()); - mitk::DataCollection *subCol = dynamic_cast(patCol->GetData(0).GetPointer()); - mitk::Image::Pointer resultImage = subCol->GetMitkImage("RESULT"); - - // Test result against fixed reference. - // Require more than 90% to be correct. - // 10% margin due to - // 1) unsure classification in transitional regions and - // 2) stochastic training procedure - - // Total number of voxels 2400 -> 10% err -> 240 voxels margin - - mitk::CompareImageDataFilter::Pointer compareFilter = mitk::CompareImageDataFilter::New(); - compareFilter->SetInput(0, refImage.GetPointer()); - compareFilter->SetInput(1, resultImage); - compareFilter->SetTolerance(.1); - compareFilter->Update(); - - MITK_TEST_CONDITION_REQUIRED(compareFilter->GetResult(240), "Compare prediction results to reference image.") - } -}; -MITK_TEST_SUITE_REGISTRATION(mitkClassification) diff --git a/Plugins/PluginList.cmake b/Plugins/PluginList.cmake index 1646d41045..ff2ccda265 100644 --- a/Plugins/PluginList.cmake +++ b/Plugins/PluginList.cmake @@ -1,101 +1,93 @@ # Plug-ins must be ordered according to their dependencies set(MITK_PLUGINS org.blueberry.core.runtime:ON org.blueberry.core.expressions:OFF org.blueberry.core.commands:OFF org.blueberry.core.jobs:OFF org.blueberry.ui.qt:OFF org.blueberry.ui.qt.help:ON org.blueberry.ui.qt.log:ON org.blueberry.ui.qt.objectinspector:OFF - - #org.blueberry.test:ON - #org.blueberry.uitest:ON - - #Testing/org.blueberry.core.runtime.tests:ON - #Testing/org.blueberry.osgi.tests:ON - org.mitk.core.services:ON org.mitk.gui.common:ON org.mitk.planarfigure:ON org.mitk.core.ext:OFF org.mitk.core.jobs:OFF org.mitk.gui.qt.application:ON - org.mitk.gui.qt.coreapplication:OFF org.mitk.gui.qt.ext:OFF org.mitk.gui.qt.extapplication:OFF org.mitk.gui.qt.common:ON org.mitk.gui.qt.stdmultiwidgeteditor:ON org.mitk.gui.qt.mxnmultiwidgeteditor:OFF org.mitk.gui.qt.common.legacy:OFF org.mitk.gui.qt.cmdlinemodules:OFF org.mitk.gui.qt.chartExample:OFF org.mitk.gui.qt.datamanager:ON org.mitk.gui.qt.datamanagerlight:OFF org.mitk.gui.qt.datastorageviewertest:OFF org.mitk.gui.qt.properties:ON org.mitk.gui.qt.basicimageprocessing:OFF org.mitk.gui.qt.dicom:OFF org.mitk.gui.qt.dicominspector:OFF org.mitk.gui.qt.dosevisualization:OFF org.mitk.gui.qt.geometrytools:OFF org.mitk.gui.qt.igtexamples:OFF org.mitk.gui.qt.igttracking:OFF org.mitk.gui.qt.lasercontrol:OFF org.mitk.gui.qt.openigtlink:OFF org.mitk.gui.qt.imagecropper:OFF org.mitk.gui.qt.imagenavigator:ON org.mitk.gui.qt.viewnavigator:OFF org.mitk.gui.qt.materialeditor:OFF org.mitk.gui.qt.measurementtoolbox:OFF org.mitk.gui.qt.moviemaker:OFF org.mitk.gui.qt.pointsetinteraction:OFF org.mitk.gui.qt.pointsetinteractionmultispectrum:OFF org.mitk.gui.qt.python:OFF org.mitk.gui.qt.remeshing:OFF org.mitk.gui.qt.segmentation:OFF org.mitk.gui.qt.aicpregistration:OFF org.mitk.gui.qt.renderwindowmanager:OFF org.mitk.gui.qt.semanticrelations:OFF org.mitk.gui.qt.toftutorial:OFF org.mitk.gui.qt.tofutil:OFF org.mitk.gui.qt.tubegraph:OFF org.mitk.gui.qt.ugvisualization:OFF org.mitk.gui.qt.photoacoustics.pausviewer:OFF org.mitk.gui.qt.photoacoustics.pausmotioncompensation:OFF org.mitk.gui.qt.photoacoustics.imageprocessing:OFF org.mitk.gui.qt.photoacoustics.simulation:OFF org.mitk.gui.qt.photoacoustics.spectralunmixing:OFF org.mitk.gui.qt.ultrasound:OFF org.mitk.gui.qt.volumevisualization:OFF org.mitk.gui.qt.eventrecorder:OFF org.mitk.gui.qt.xnat:OFF org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation:OFF org.mitk.gui.qt.spectrocamrecorder:OFF org.mitk.gui.qt.classificationsegmentation:OFF org.mitk.gui.qt.overlaymanager:OFF org.mitk.gui.qt.igt.app.hummelprotocolmeasurements:OFF org.mitk.gui.qt.multilabelsegmentation:OFF org.mitk.matchpoint.core.helper:OFF org.mitk.gui.qt.matchpoint.algorithm.browser:OFF org.mitk.gui.qt.matchpoint.algorithm.control:OFF org.mitk.gui.qt.matchpoint.mapper:OFF org.mitk.gui.qt.matchpoint.framereg:OFF org.mitk.gui.qt.matchpoint.visualizer:OFF org.mitk.gui.qt.matchpoint.evaluator:OFF org.mitk.gui.qt.matchpoint.manipulator:OFF org.mitk.gui.qt.preprocessing.resampling:OFF org.mitk.gui.qt.radiomics:OFF org.mitk.gui.qt.cest:OFF org.mitk.gui.qt.fit.demo:OFF org.mitk.gui.qt.fit.inspector:OFF org.mitk.gui.qt.fit.genericfitting:OFF org.mitk.gui.qt.pharmacokinetics.mri:OFF org.mitk.gui.qt.pharmacokinetics.pet:OFF org.mitk.gui.qt.pharmacokinetics.simulation:OFF org.mitk.gui.qt.pharmacokinetics.curvedescriptor:OFF org.mitk.gui.qt.pharmacokinetics.concentration.mri:OFF ) diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/CMakeLists.txt b/Plugins/Testing/org.blueberry.core.runtime.tests/CMakeLists.txt deleted file mode 100644 index 4f06c8b200..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -project(org_blueberry_core_runtime_tests) - -mitk_create_plugin( - EXPORT_DIRECTIVE BERRY_RUNTIME_TESTS - TEST_PLUGIN -) - -target_link_libraries(${PROJECT_NAME} optimized CppUnit debug CppUnitd) - -MACRO_TEST_PLUGIN() diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/files.cmake b/Plugins/Testing/org.blueberry.core.runtime.tests/files.cmake deleted file mode 100644 index 904a56991c..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/files.cmake +++ /dev/null @@ -1,30 +0,0 @@ -set(MOC_H_FILES - src/berryCoreRuntimeTestSuite.h - src/berryPluginActivator.h -) - -set(CACHED_RESOURCE_FILES - plugin.xml -) - -set(SRC_CPP_FILES - berryCoreRuntimeTestSuite.cpp - berryPreferencesServiceTest.cpp - berryPreferencesTest.cpp - - berryPluginActivator.cpp -) - -set(INTERNAL_CPP_FILES - -) - -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/Testing/org.blueberry.core.runtime.tests/manifest_headers.cmake b/Plugins/Testing/org.blueberry.core.runtime.tests/manifest_headers.cmake deleted file mode 100644 index 5b1f7b7e14..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/manifest_headers.cmake +++ /dev/null @@ -1,6 +0,0 @@ -set(Plugin-Name "Core Runtime Test Bundle") -set(Plugin-Version "0.9") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.blueberry.test org.blueberry.core.runtime) - diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/plugin.xml b/Plugins/Testing/org.blueberry.core.runtime.tests/plugin.xml deleted file mode 100644 index a788a9f121..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/plugin.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryCoreRuntimeTestSuite.cpp b/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryCoreRuntimeTestSuite.cpp deleted file mode 100644 index 595ff7f254..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryCoreRuntimeTestSuite.cpp +++ /dev/null @@ -1,37 +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 "berryCoreRuntimeTestSuite.h" - -#include "berryPreferencesTest.h" -#include "berryPreferencesServiceTest.h" - -namespace berry { - -CoreRuntimeTestSuite::CoreRuntimeTestSuite(const CoreRuntimeTestSuite& other) -{ - -} - -CoreRuntimeTestSuite::CoreRuntimeTestSuite() -: CppUnit::TestSuite("CoreRuntimeTestSuite") -{ - addTest(PreferencesTest::Suite()); - addTest(PreferencesServiceTest::Suite()); -} - -} diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryCoreRuntimeTestSuite.h b/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryCoreRuntimeTestSuite.h deleted file mode 100644 index 7032be05da..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryCoreRuntimeTestSuite.h +++ /dev/null @@ -1,38 +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. - -============================================================================*/ - - -#ifndef BERRYCORERUNTIMETESTSUITE_H_ -#define BERRYCORERUNTIMETESTSUITE_H_ - -#include - -#include - -Q_DECLARE_INTERFACE(CppUnit::Test, "CppUnit.Test") - -namespace berry { - -class CoreRuntimeTestSuite : public QObject, public CppUnit::TestSuite -{ - Q_OBJECT - Q_INTERFACES(CppUnit::Test) - -public: - - CoreRuntimeTestSuite(); - CoreRuntimeTestSuite(const CoreRuntimeTestSuite& other); -}; - -} - -#endif /* BERRYCORERUNTIMETESTSUITE_H_ */ diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPluginActivator.cpp b/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPluginActivator.cpp deleted file mode 100644 index 4d01f61999..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPluginActivator.cpp +++ /dev/null @@ -1,29 +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 "berryPluginActivator.h" -#include "berryCoreRuntimeTestSuite.h" - -namespace berry { - -void org_blueberry_core_runtime_tests_Activator::start(ctkPluginContext* context) -{ - BERRY_REGISTER_EXTENSION_CLASS(CoreRuntimeTestSuite, context) -} - -void org_blueberry_core_runtime_tests_Activator::stop(ctkPluginContext* context) -{ - Q_UNUSED(context) -} - -} diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPluginActivator.h b/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPluginActivator.h deleted file mode 100644 index 7a5e6ca163..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPluginActivator.h +++ /dev/null @@ -1,40 +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. - -============================================================================*/ - - -#ifndef BERRYPLUGINACTIVATOR_H -#define BERRYPLUGINACTIVATOR_H - -#include -#include - -namespace berry { - -class org_blueberry_core_runtime_tests_Activator : - public QObject, public ctkPluginActivator -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_blueberry_core_runtime_tests") - Q_INTERFACES(ctkPluginActivator) - -public: - - void start(ctkPluginContext* context); - void stop(ctkPluginContext* context); - -}; - -typedef org_blueberry_core_runtime_tests_Activator PluginActivator; - -} - -#endif // BERRYPLUGINACTIVATOR_H diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.cpp b/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.cpp deleted file mode 100644 index ba0dc787f8..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.cpp +++ /dev/null @@ -1,136 +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 "berryPreferencesServiceTest.h" -#include -#include -#include - -#include "berryLog.h" - -#include -#include - -#include "Poco/File.h" -#include "Poco/Path.h" -#include "Poco/AutoPtr.h" - -#include -#include -#include - -using namespace std; - -namespace berry -{ - - PreferencesServiceTest::PreferencesServiceTest(const std::string& testName) - : berry::TestCase(testName) - {} - - CppUnit::Test* PreferencesServiceTest::Suite() - { - CppUnit::TestSuite* suite = new CppUnit::TestSuite("PreferencesServiceTest"); - - CppUnit_addTest(suite, PreferencesServiceTest, TestAll); - return suite; - } - - - void PreferencesServiceTest::TestAll() - { - try - { - IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById(IPreferencesService::ID); - assert(prefService.IsNotNull()); - - /// Test for: IPreferences::GetSystemPreferences() - IPreferences::Pointer sysPrefs = prefService->GetSystemPreferences(); - assert(sysPrefs.IsNotNull()); - - /// Test for: IPreferences::GetUserPreferences(std::string name) - IPreferences::Pointer testUserPrefs = prefService->GetUserPreferences("testUser"); - assert(testUserPrefs.IsNotNull()); - - /// Test for: IPreferences::GetUsers() - std::vector userList = prefService->GetUsers(); - // userList should now contain "testUser" - bool userListContainsTestUser = false; - for (std::vector::iterator it = userList.begin() - ; it != userList.end(); it++) - { - if(*it == "testUser") - { - userListContainsTestUser = true; - break; - } - } - assert(userListContainsTestUser); - - IBerryPreferencesService::Pointer berryPrefService = prefService.Cast(); - // optional test for IBerryPreferencesService - if(berryPrefService.IsNotNull()) - { - /// Test for: IBerryPreferencesService::ExportPreferences(Poco::File f, std::string name="") - - // write general prefs - std::string sysPrefsExportFilePath = Poco::Path::temp() + Poco::Path::separator() + "systemBerryPreferences"; - Poco::File sysPrefsExportFile(sysPrefsExportFilePath); - sysPrefs->PutInt("testNumber", 1); - berryPrefService->ExportPreferences(sysPrefsExportFile); - // assert somethings was written - assert(sysPrefsExportFile.getSize() > 0); - - // write testUser prefs - std::string testUserPrefsExportFilePath = Poco::Path::temp() + Poco::Path::separator() + "testUserBerryPreferences"; - Poco::File testUserPrefsExportFile(testUserPrefsExportFilePath); - testUserPrefs->PutInt("testNumber", 2); - berryPrefService->ExportPreferences(testUserPrefsExportFile, "testUser"); - assert(testUserPrefsExportFile.getSize() > 0); - - /// Test for: IBerryPreferencesService::ImportPreferences(Poco::File f, std::string name="") - - // import general prefs - // change testNumber value - sysPrefs->PutInt("testNumber", 3); - berryPrefService->ImportPreferences(sysPrefsExportFile); - // "testNumber" preference should now again be overwritten with its old value 1 - assert(sysPrefs->GetInt("testNumber", 3) == 1); - - // import testUser prefs - // change testNumber value - testUserPrefs->PutInt("testNumber", 4); - berryPrefService->ImportPreferences(testUserPrefsExportFile, "testUser"); - // "testNumber" preference should now again be overwritten with its old value 2 - assert(testUserPrefs->GetInt("testNumber", 4) == 2); - - // delete files again - sysPrefsExportFile.remove(); - testUserPrefsExportFile.remove(); - } - } - catch (Poco::CreateFileException& e) - { - std::string msg = "Failed to create preferences file: "; - msg.append(e.what()); - this->fail( msg ); - } - catch (std::exception& e) - { - this->fail( e.what() ); - } - catch (...) - { - this->fail( "unknown exception occured" ); - } - } -} diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.h b/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.h deleted file mode 100644 index 286abb9010..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesServiceTest.h +++ /dev/null @@ -1,34 +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. - -============================================================================*/ - - -#ifndef BERRYPREFERENCESSERVICETEST_H_ -#define BERRYPREFERENCESSERVICETEST_H_ - -#include - -namespace berry { - -class PreferencesServiceTest : public berry::TestCase -{ -public: - - static CppUnit::Test* Suite(); - - PreferencesServiceTest(const std::string& testName); - - void TestAll(); -}; - -} - -#endif /* BERRYPREFERENCESSERVICETEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.cpp b/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.cpp deleted file mode 100644 index cecc437691..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.cpp +++ /dev/null @@ -1,173 +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 "berryPreferencesTest.h" - -#include -#include -#include - -#include -#include - -#include "berryLog.h" - -#include "Poco/File.h" -#include "Poco/Path.h" - -#include -#include -#include - -using namespace std; - -namespace berry -{ - - PreferencesTest::PreferencesTest(const std::string& testName) - : berry::TestCase(testName) - {} - - CppUnit::Test* PreferencesTest::Suite() - { - CppUnit::TestSuite* suite = new CppUnit::TestSuite("PreferencesTest"); - - CppUnit_addTest(suite, PreferencesTest, TestAll); - return suite; - } - - // simple class for testing berry changed events - class TestPreferencesChangedListener - { - public: - TestPreferencesChangedListener(IBerryPreferences* _berryPrefNode) : numCalled(0), berryPrefNode(_berryPrefNode) - { - berryPrefNode->OnChanged.AddListener( - berry::MessageDelegate1 ( - this, &TestPreferencesChangedListener::PreferencesChanged ) - ); - }; - - ~TestPreferencesChangedListener() - { - berryPrefNode->OnChanged.RemoveListener( - berry::MessageDelegate1 ( - this, &TestPreferencesChangedListener::PreferencesChanged ) - ); - }; - - void PreferencesChanged(const IBerryPreferences*) - { - ++numCalled; - } - int numCalled; - IBerryPreferences* berryPrefNode; - }; - - void PreferencesTest::TestAll() - { - IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById(IPreferencesService::ID); - assert(prefService.IsNotNull()); - - /// Test for: IPreferences::GetSystemPreferences() - IPreferences::Pointer root = prefService->GetSystemPreferences(); - assert(root.IsNotNull()); - - { - BERRY_INFO << "testing Preferences::Node(), Preferences::NodeExists(), Preferences::Parent(), " - "Preferences::ChildrenNames(), Preferences::RemoveNode()"; - - berry::IPreferences::Pointer editorsNode(0); - editorsNode = root->Node("/editors"); - assert(editorsNode.IsNotNull()); - - assert(editorsNode->NodeExists("/editors")); - - assert(editorsNode->Parent() == root); - - berry::IPreferences::Pointer editorsGeneralNode = root->Node("/editors/general"); - assert(editorsNode->NodeExists("/editors/general")); - - berry::IPreferences::Pointer editorsSyntaxNode = root->Node("/editors/syntax"); - assert(editorsGeneralNode->NodeExists("/editors/syntax")); - - berry::IPreferences::Pointer editorsFontNode = root->Node("/editors/font"); - assert(editorsSyntaxNode->NodeExists("/editors/font")); - - vector childrenNames; - childrenNames.push_back("general"); - childrenNames.push_back("syntax"); - childrenNames.push_back("font"); - assert(editorsNode->ChildrenNames() == childrenNames); - - editorsFontNode->RemoveNode(); - try { - editorsFontNode->Parent(); - failmsg("this should throw a Poco::IllegalStateException"); - } - catch (Poco::IllegalStateException) - { - // expected - } - } - - // testing methods - // Preferences::put*() - // Preferences::get*() - { - BERRY_INFO << "testing Preferences::put*(), Preferences::get*(), OnChanged"; - - assert(root->NodeExists("/editors/general")); - berry::IPreferences::Pointer editorsGeneralNode = root->Node("/editors/general"); - - IBerryPreferences::Pointer berryEditorsGeneralNode = editorsGeneralNode.Cast< IBerryPreferences >(); - assert(berryEditorsGeneralNode.IsNotNull()); - - TestPreferencesChangedListener listener(berryEditorsGeneralNode.GetPointer()); - - std::string strKey = "Bad words";std::string strValue = "badword1 badword2"; - editorsGeneralNode->Put(strKey, strValue); - - assert(listener.numCalled == 1); - assert(editorsGeneralNode->Get(strKey, "") == strValue); - assert(editorsGeneralNode->Get("wrong key", "default value") == "default value"); - - strKey = "Show Line Numbers";bool bValue = true; - editorsGeneralNode->PutBool(strKey, bValue); - assert(listener.numCalled == 2); - assert(editorsGeneralNode->GetBool(strKey, !bValue) == bValue); - - strKey = "backgroundcolor"; strValue = "#00FF00"; - editorsGeneralNode->PutByteArray(strKey, strValue); - assert(listener.numCalled == 3); - assert(editorsGeneralNode->GetByteArray(strKey, "") == strValue); - - strKey = "update time"; double dValue = 1.23; - editorsGeneralNode->PutDouble(strKey, dValue); - assert(editorsGeneralNode->GetDouble(strKey, 0.0) == dValue); - - strKey = "update time float"; float fValue = 1.23f; - editorsGeneralNode->PutFloat(strKey, fValue); - assert(editorsGeneralNode->GetFloat(strKey, 0.0f) == fValue); - - strKey = "Break on column"; int iValue = 80; - editorsGeneralNode->PutInt(strKey, iValue); - assert(editorsGeneralNode->GetInt(strKey, 0) == iValue); - - strKey = "Maximum number of words"; long lValue = 11000000; - editorsGeneralNode->PutLong(strKey, lValue); - assert(editorsGeneralNode->GetLong(strKey, 0) == lValue); - } - - } - -} diff --git a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.h b/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.h deleted file mode 100644 index 7cddaf0d04..0000000000 --- a/Plugins/Testing/org.blueberry.core.runtime.tests/src/berryPreferencesTest.h +++ /dev/null @@ -1,35 +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. - -============================================================================*/ - - -#ifndef BERRYPREFERENCESTEST_H_ -#define BERRYPREFERENCESTEST_H_ - -#include - -namespace berry { - -class PreferencesTest : public berry::TestCase -{ -public: - - PreferencesTest(const std::string& testName); - - static CppUnit::Test* Suite(); - - void TestAll(); - -}; - -} - -#endif /* BERRYPREFERENCESTEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.osgi.tests/CMakeLists.txt b/Plugins/Testing/org.blueberry.osgi.tests/CMakeLists.txt deleted file mode 100755 index a7a9a5798b..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -project(org_blueberry_osgi_tests) - -mitk_create_plugin( - EXPORT_DIRECTIVE BERRY_OSGI_TESTS - TEST_PLUGIN -) - -target_link_libraries(${PROJECT_NAME} optimized CppUnit debug CppUnitd) - -MACRO_TEST_PLUGIN() diff --git a/Plugins/Testing/org.blueberry.osgi.tests/files.cmake b/Plugins/Testing/org.blueberry.osgi.tests/files.cmake deleted file mode 100644 index 197cf50487..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/files.cmake +++ /dev/null @@ -1,31 +0,0 @@ -set(MOC_H_FILES - src/berryOSGiCoreTestSuite.h - src/berryPluginActivator.h -) - -set(CACHED_RESOURCE_FILES - plugin.xml -) - -set(SRC_CPP_FILES - berryMessageTest.cpp - berryObjectTest.cpp - berryOSGiCoreTestSuite.cpp - berryPluginActivator.cpp - berrySmartPointerTest.cpp - berryWeakPointerTest.cpp -) - -set(INTERNAL_CPP_FILES - -) - -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/Testing/org.blueberry.osgi.tests/manifest_headers.cmake b/Plugins/Testing/org.blueberry.osgi.tests/manifest_headers.cmake deleted file mode 100644 index b4779358f4..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/manifest_headers.cmake +++ /dev/null @@ -1,6 +0,0 @@ -set(Plugin-Name "OSGi Test Bundle") -set(Plugin-Version "0.9") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.blueberry.test) - diff --git a/Plugins/Testing/org.blueberry.osgi.tests/plugin.xml b/Plugins/Testing/org.blueberry.osgi.tests/plugin.xml deleted file mode 100644 index a866ea07e1..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/plugin.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryMessageTest.cpp b/Plugins/Testing/org.blueberry.osgi.tests/src/berryMessageTest.cpp deleted file mode 100755 index f0cdb6ac21..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryMessageTest.cpp +++ /dev/null @@ -1,327 +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 "berryMessageTest.h" - -#include -//#include - -#include -#include - -namespace berry -{ - -struct MessageReceiver -{ - bool received; - - MessageReceiver() : received(false) {} - - void PureSignal() { received = true; } - bool PureSignalWithReturn() { received = true; return received; } - - void Message1(int i) { received = (i != 0); } - bool Message1WithReturn(int i) { received = (i != 0); return received; } - - void Message2(int i, float d) { received = (i != 0 && d != 0); } - bool Message2WithReturn(int i, float d) { received = (i != 0 && d!= 0); return received; } - - void Message3(int i, float d, double e) { received = (i != 0 && d != 0 && e != 0); } - bool Message3WithReturn(int i, float d, double e) { received = (i != 0 && d != 0 && e != 0); return received; } - - void Message4(int i, float d, double e, bool b) { received = (i != 0 && d != 0 && e != 0 && b); } - bool Message4WithReturn(int i, float d, double e, bool b) { received = (i != 0 && d != 0 && e != 0 && b); return received; } - -}; - -MessageTest::MessageTest(const std::string& testName) -: TestCase(testName) -{ - -} - -CppUnit::Test* MessageTest::Suite() -{ - CppUnit::TestSuite* suite = new CppUnit::TestSuite("MessageTest"); - - CppUnit_addTest(suite, MessageTest, TestMessage); - CppUnit_addTest(suite, MessageTest, TestMessageWithReturn); - CppUnit_addTest(suite, MessageTest, TestMessage1); - CppUnit_addTest(suite, MessageTest, TestMessage1WithReturn); - CppUnit_addTest(suite, MessageTest, TestMessage2); - CppUnit_addTest(suite, MessageTest, TestMessage2WithReturn); - CppUnit_addTest(suite, MessageTest, TestMessage3); - CppUnit_addTest(suite, MessageTest, TestMessage3WithReturn); - CppUnit_addTest(suite, MessageTest, TestMessage4); - CppUnit_addTest(suite, MessageTest, TestMessage4WithReturn); - - return suite; -} - - void MessageTest::TestMessage() - { - berry::Message<> msg; - - MessageReceiver receiver; - MessageReceiver receiver2; - - typedef berry::MessageDelegate Delegate; - - msg += Delegate(&receiver, &MessageReceiver::PureSignal); - assertEqual(1, (long)msg.GetListeners().size()); - msg += Delegate(&receiver2, &MessageReceiver::PureSignal); - // duplicate entry - msg += Delegate(&receiver, &MessageReceiver::PureSignal); - assertEqual(2, (long)msg.GetListeners().size()); - - msg.Send(); - assert(receiver.received && receiver2.received); - - receiver.received = false; - receiver2.received = false; - msg -= Delegate(&receiver, &MessageReceiver::PureSignal); - assertEqual(1, (long)msg.GetListeners().size()); - - msg.Send(); - assert(receiver.received == false && receiver2.received); - } - - void MessageTest::TestMessageWithReturn() - { - berry::Message msg; - - MessageReceiver receiver; - typedef berry::MessageDelegate Delegate; - msg += Delegate(&receiver, &MessageReceiver::PureSignalWithReturn); - msg(); - assert(receiver.received); - - receiver.received = false; - typedef berry::Message::ListenerList Listeners; - const Listeners& listeners = msg.GetListeners(); - bool valueReturned = false; - for (Listeners::const_iterator iter = listeners.begin(); - iter != listeners.end(); ++iter) - { - valueReturned = (*iter)->Execute(); - if (valueReturned) break; - } - assert(valueReturned); - } - - void MessageTest::TestMessage1() - { - berry::Message1 msg; - - MessageReceiver receiver; - MessageReceiver receiver2; - - typedef berry::MessageDelegate1 Delegate; - - msg += Delegate(&receiver, &MessageReceiver::Message1); - assertEqual(1, (long)msg.GetListeners().size()); - msg += Delegate(&receiver2, &MessageReceiver::Message1); - // duplicate entry - msg += Delegate(&receiver, &MessageReceiver::Message1); - assertEqual(2, (long)msg.GetListeners().size()); - - msg.Send(1); - assert(receiver.received && receiver2.received); - - receiver.received = false; - receiver2.received = false; - msg -= Delegate(&receiver, &MessageReceiver::Message1); - assertEqual(1, (long)msg.GetListeners().size()); - - msg.Send(1); - assert(receiver.received == false && receiver2.received); - } - - void MessageTest::TestMessage1WithReturn() - { - berry::Message1 msg; - - MessageReceiver receiver; - typedef berry::MessageDelegate1 Delegate; - msg += Delegate(&receiver, &MessageReceiver::Message1WithReturn); - msg(1); - assert(receiver.received); - - receiver.received = false; - typedef berry::Message1::ListenerList Listeners; - const Listeners& listeners = msg.GetListeners(); - bool valueReturned = false; - for (Listeners::const_iterator iter = listeners.begin(); - iter != listeners.end(); ++iter) - { - valueReturned = (*iter)->Execute(1); - if (valueReturned) break; - } - assert(valueReturned); - } - - void MessageTest::TestMessage2() - { - berry::Message2 msg; - - MessageReceiver receiver; - MessageReceiver receiver2; - - typedef berry::MessageDelegate2 Delegate; - - msg += Delegate(&receiver, &MessageReceiver::Message2); - assertEqual(1, (long)msg.GetListeners().size()); - msg += Delegate(&receiver2, &MessageReceiver::Message2); - // duplicate entry - msg += Delegate(&receiver, &MessageReceiver::Message2); - assertEqual(2, (long)msg.GetListeners().size()); - - msg.Send(1, 1.0); - assert(receiver.received && receiver2.received); - - receiver.received = false; - receiver2.received = false; - msg -= Delegate(&receiver, &MessageReceiver::Message2); - assertEqual(1, (long)msg.GetListeners().size()); - - msg.Send(1, 1.0); - assert(receiver.received == false && receiver2.received); - } - - void MessageTest::TestMessage2WithReturn() - { - berry::Message2 msg; - - MessageReceiver receiver; - typedef berry::MessageDelegate2 Delegate; - msg += Delegate(&receiver, &MessageReceiver::Message2WithReturn); - msg(1, 2); - assert(receiver.received); - - receiver.received = false; - typedef berry::Message2::ListenerList Listeners; - const Listeners& listeners = msg.GetListeners(); - bool valueReturned = false; - for (Listeners::const_iterator iter = listeners.begin(); - iter != listeners.end(); ++iter) - { - valueReturned = (*iter)->Execute(1, 0.4f); - if (valueReturned) break; - } - assert(valueReturned); - } - - void MessageTest::TestMessage3() - { - berry::Message3 msg; - - MessageReceiver receiver; - MessageReceiver receiver2; - - typedef berry::MessageDelegate3 Delegate; - - msg += Delegate(&receiver, &MessageReceiver::Message3); - assertEqual(1, (long)msg.GetListeners().size()); - msg += Delegate(&receiver2, &MessageReceiver::Message3); - // duplicate entry - msg += Delegate(&receiver, &MessageReceiver::Message3); - assertEqual(2, (long)msg.GetListeners().size()); - - msg.Send(1, 1.0, 2.0); - assert(receiver.received && receiver2.received); - - receiver.received = false; - receiver2.received = false; - msg -= Delegate(&receiver, &MessageReceiver::Message3); - assertEqual(1, (long)msg.GetListeners().size()); - - msg.Send(1, -1.0, 5.0); - assert(receiver.received == false && receiver2.received); - } - - void MessageTest::TestMessage3WithReturn() - { - berry::Message3 msg; - - MessageReceiver receiver; - typedef berry::MessageDelegate3 Delegate; - msg += Delegate(&receiver, &MessageReceiver::Message3WithReturn); - msg(1, -2, 0.2); - assert(receiver.received); - - receiver.received = false; - typedef berry::Message3::ListenerList Listeners; - const Listeners& listeners = msg.GetListeners(); - bool valueReturned = false; - for (Listeners::const_iterator iter = listeners.begin(); - iter != listeners.end(); ++iter) - { - valueReturned = (*iter)->Execute(1, 23.5, -12.2); - if (valueReturned) break; - } - assert(valueReturned); - } - - void MessageTest::TestMessage4() - { - berry::Message4 msg; - - MessageReceiver receiver; - MessageReceiver receiver2; - - typedef berry::MessageDelegate4 Delegate; - - msg += Delegate(&receiver, &MessageReceiver::Message4); - assertEqual(1, (long)msg.GetListeners().size()); - msg += Delegate(&receiver2, &MessageReceiver::Message4); - // duplicate entry - msg += Delegate(&receiver, &MessageReceiver::Message4); - assertEqual(2, (long)msg.GetListeners().size()); - - msg.Send(1, 5.4f, -1.0f, true); - assert(receiver.received && receiver2.received); - - receiver.received = false; - receiver2.received = false; - msg -= Delegate(&receiver, &MessageReceiver::Message4); - assertEqual(1, (long)msg.GetListeners().size()); - - msg.Send(1, 0.2f, 12.0f, true); - assert(receiver.received == false && receiver2.received); - } - - void MessageTest::TestMessage4WithReturn() - { - berry::Message4 msg; - - MessageReceiver receiver; - typedef berry::MessageDelegate4 Delegate; - msg += Delegate(&receiver, &MessageReceiver::Message4WithReturn); - msg(1, 4.1f, -1, true); - assert(receiver.received); - - receiver.received = false; - typedef berry::Message4::ListenerList Listeners; - const Listeners& listeners = msg.GetListeners(); - bool valueReturned = false; - for (Listeners::const_iterator iter = listeners.begin(); - iter != listeners.end(); ++iter) - { - valueReturned = (*iter)->Execute(1, -34.21f, 2, true); - if (valueReturned) break; - } - assert(valueReturned); - } - - -} diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryMessageTest.h b/Plugins/Testing/org.blueberry.osgi.tests/src/berryMessageTest.h deleted file mode 100644 index 9ef394df41..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryMessageTest.h +++ /dev/null @@ -1,44 +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. - -============================================================================*/ - - -#ifndef BERRYMESSAGETEST_H_ -#define BERRYMESSAGETEST_H_ - -#include - -namespace berry { - -class MessageTest : public TestCase { - -public: - - MessageTest(const std::string& testName); - - static CppUnit::Test* Suite(); - - void TestMessage(); - void TestMessageWithReturn(); - void TestMessage1(); - void TestMessage1WithReturn(); - void TestMessage2(); - void TestMessage2WithReturn(); - void TestMessage3(); - void TestMessage3WithReturn(); - void TestMessage4(); - void TestMessage4WithReturn(); - -}; - -} - -#endif /* BERRYMESSAGETEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryOSGiCoreTestSuite.cpp b/Plugins/Testing/org.blueberry.osgi.tests/src/berryOSGiCoreTestSuite.cpp deleted file mode 100644 index 5b9c1cfea5..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryOSGiCoreTestSuite.cpp +++ /dev/null @@ -1,41 +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 "berryOSGiCoreTestSuite.h" - -#include "berryObjectTest.h" -#include "berrySmartPointerTest.h" -#include "berryWeakPointerTest.h" -#include "berryMessageTest.h" - -namespace berry { - -OSGiCoreTestSuite::OSGiCoreTestSuite() -: CppUnit::TestSuite("OSGiCoreTestSuite") -{ - addTest(ObjectTest::Suite()); - addTest(SmartPointerTest::Suite()); - addTest(WeakPointerTest::Suite()); - addTest(MessageTest::Suite()); -} - -OSGiCoreTestSuite::OSGiCoreTestSuite(const OSGiCoreTestSuite& other) -{ - Q_UNUSED(other) -} - -} diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryOSGiCoreTestSuite.h b/Plugins/Testing/org.blueberry.osgi.tests/src/berryOSGiCoreTestSuite.h deleted file mode 100644 index fe203aaf5c..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryOSGiCoreTestSuite.h +++ /dev/null @@ -1,38 +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. - -============================================================================*/ - - -#ifndef BERRYOSGICORETESTSUITE_H_ -#define BERRYOSGICORETESTSUITE_H_ - -#include - -#include - -Q_DECLARE_INTERFACE(CppUnit::Test, "CppUnit.Test") - -namespace berry { - -class OSGiCoreTestSuite : public QObject, public CppUnit::TestSuite -{ - Q_OBJECT - Q_INTERFACES(CppUnit::Test) - -public: - - OSGiCoreTestSuite(); - OSGiCoreTestSuite(const OSGiCoreTestSuite& other); -}; - -} - -#endif /* BERRYOSGICORETESTSUITE_H_ */ diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryObjectTest.cpp b/Plugins/Testing/org.blueberry.osgi.tests/src/berryObjectTest.cpp deleted file mode 100755 index 4c9e0402d4..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryObjectTest.cpp +++ /dev/null @@ -1,109 +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 "berryObjectTest.h" - -#include -#include -#include -//#include - -namespace berry -{ - -class TestObject: public Object -{ -public: - TestObject() : - Object() - { - } -}; - -/** - * used for listening to destroy events - */ -struct ObjectListener -{ - bool m_ObjectDeleted; - - ObjectListener() : - m_ObjectDeleted(false) - { - - } - - void DestroyListener() - { - m_ObjectDeleted = true; - } - -}; - -CppUnit::Test* ObjectTest::Suite() -{ - CppUnit::TestSuite* suite = new CppUnit::TestSuite("ObjectTest"); - - CppUnit_addTest(suite, ObjectTest, TestReferenceCount); - CppUnit_addTest(suite, ObjectTest, TestAddDestroyListener); - CppUnit_addTest(suite, ObjectTest, TestRemoveDestroyListener); - - return suite; -} - -ObjectTest::ObjectTest(const std::string& testName) : - TestCase(testName) -{ - -} - -void ObjectTest::TestReferenceCount() -{ - TestObject* obj = new TestObject(); - assertEqual(obj->GetReferenceCount(), 0); - - obj->Register(); - assertEqual(obj->GetReferenceCount(), 1); - - obj->SetReferenceCount(3); - assertEqual(obj->GetReferenceCount(), 3); - - obj->SetReferenceCount(0); -} - -void ObjectTest::TestAddDestroyListener() -{ - TestObject* obj = new TestObject(); - - ObjectListener objectListener; - - obj->AddDestroyListener(berry::MessageDelegate( - &objectListener, &ObjectListener::DestroyListener)); - delete obj; - assertEqual(true, objectListener.m_ObjectDeleted); -} - -void ObjectTest::TestRemoveDestroyListener() -{ - TestObject* obj = new TestObject(); - - ObjectListener objectListener; - - obj->AddDestroyListener(berry::MessageDelegate( - &objectListener, &ObjectListener::DestroyListener)); - obj->RemoveDestroyListener(berry::MessageDelegate( - &objectListener, &ObjectListener::DestroyListener)); - delete obj; - assertEqual(false, objectListener.m_ObjectDeleted); -} - -} diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryObjectTest.h b/Plugins/Testing/org.blueberry.osgi.tests/src/berryObjectTest.h deleted file mode 100644 index 78cdd44d83..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryObjectTest.h +++ /dev/null @@ -1,36 +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. - -============================================================================*/ - - -#ifndef BERRYOBJECTTEST_H_ -#define BERRYOBJECTTEST_H_ - -#include - -namespace berry { - -class ObjectTest : public TestCase -{ -public: - - static CppUnit::Test* Suite(); - - ObjectTest(const std::string& testName); - - void TestReferenceCount(); - void TestAddDestroyListener(); - void TestRemoveDestroyListener(); -}; - -} - -#endif /* BERRYOBJECTTEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryPluginActivator.cpp b/Plugins/Testing/org.blueberry.osgi.tests/src/berryPluginActivator.cpp deleted file mode 100644 index 56bfcaf1fb..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryPluginActivator.cpp +++ /dev/null @@ -1,31 +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 "berryPluginActivator.h" -#include "berryOSGiCoreTestSuite.h" - -namespace berry { - -void org_blueberry_osgi_tests_Activator::start(ctkPluginContext* context) -{ - Q_UNUSED(context) - - BERRY_REGISTER_EXTENSION_CLASS(OSGiCoreTestSuite, context) -} - -void org_blueberry_osgi_tests_Activator::stop(ctkPluginContext* context) -{ - Q_UNUSED(context) -} - -} diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryPluginActivator.h b/Plugins/Testing/org.blueberry.osgi.tests/src/berryPluginActivator.h deleted file mode 100644 index ff480c83e5..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryPluginActivator.h +++ /dev/null @@ -1,40 +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. - -============================================================================*/ - - -#ifndef BERRYPLUGINACTIVATOR_H -#define BERRYPLUGINACTIVATOR_H - -#include -#include - -namespace berry { - -class org_blueberry_osgi_tests_Activator : - public QObject, public ctkPluginActivator -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_blueberry_osgi_tests") - Q_INTERFACES(ctkPluginActivator) - -public: - - void start(ctkPluginContext* context); - void stop(ctkPluginContext* context); - -}; - -typedef org_blueberry_osgi_tests_Activator PluginActivator; - -} - -#endif // BERRYPLUGINACTIVATOR_H diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berrySmartPointerTest.cpp b/Plugins/Testing/org.blueberry.osgi.tests/src/berrySmartPointerTest.cpp deleted file mode 100755 index 7db7b57055..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berrySmartPointerTest.cpp +++ /dev/null @@ -1,209 +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 "berrySmartPointerTest.h" - -#include -#include - -#include -#include -#include - -#include -//#include - -namespace berry -{ - -class TestObject : public berry::Object -{ -public: - TestObject() : Object(), m_Val(0) {} - TestObject(int value) : m_Val(value) {} - - bool operator==(const Object* o) const - { - if (const TestObject* to = dynamic_cast(o)) - return m_Val == to->m_Val; - - return false; - } - -private: - - int m_Val; -}; - - -SmartPointerTest::SmartPointerTest(const std::string& testName) -: TestCase(testName) -{} - -CppUnit::Test* SmartPointerTest::Suite() -{ - CppUnit::TestSuite* suite = new CppUnit::TestSuite("SmartPointerTest"); - - CppUnit_addTest(suite, SmartPointerTest, TestConstructors); - CppUnit_addTest(suite, SmartPointerTest, TestCasting); - CppUnit_addTest(suite, SmartPointerTest, TestReferenceCounting); - CppUnit_addTest(suite, SmartPointerTest, TestOperators); - - return suite; -} - - - void SmartPointerTest::TestConstructors() - { - { - // standard constructor - berry::SmartPointer testobj; - assertNullPtr(testobj.GetPointer()); - } - - - { - // standard pointer constructor - berry::SmartPointer testobj(new TestObject()); - assertNotNullPtr(testobj.GetPointer()); - assertEqual(1, testobj->GetReferenceCount()); - - // copy constructor - berry::SmartPointer testobj2 = testobj; - assertEqual(testobj.GetPointer(), testobj2.GetPointer()); - assertEqual(2, testobj2->GetReferenceCount()); - } - - { - // WeakPointer constructor - berry::WeakPointer ptr_weak; - try { - berry::SmartPointer testobj(ptr_weak); - failmsg("this should throw a BadWeakPointerException"); - } - catch (BadWeakPointerException ) - { - // expected - } - } - - { - // const_cast template constructor - berry::SmartPointer testobj(new TestObject()); - berry::SmartPointer obj(testobj); - assertNotNullPtr(obj.GetPointer()); - assertEqual(2, obj->GetReferenceCount()); - assert(typeid(*(obj.GetPointer())) == typeid(TestObject)); - } - } - - void SmartPointerTest::TestCasting() - // cast tests - { - berry::SmartPointer obj(new TestObject()); - assertNotNullPtr(obj.GetPointer()); - assertEqual(1, obj->GetReferenceCount()); - - berry::SmartPointer testobj = obj.Cast(); - assertNotNullPtr(testobj.GetPointer()); - assertEqual(2, testobj->GetReferenceCount()); - assertEqual(testobj.GetPointer(), obj.GetPointer()); - } - - void SmartPointerTest::TestReferenceCounting() - // reference count tests - { - berry::SmartPointer obj(new TestObject()); - { - berry::SmartPointer tmpobj = obj; - } - assertEqual(1, obj->GetReferenceCount()); - } - - void SmartPointerTest::TestOperators() - { - // operator tests - { - berry::SmartPointer obj(new TestObject(1)); - berry::SmartPointer testobj(new TestObject(2)); - berry::SmartPointer nullobj; - - // boolean conversions - assert(obj.IsNotNull()); - assert(false == obj.IsNull()); - assert(obj); - assert(false == !obj); - - // != operators - assert(obj != 0); - - try - { - obj != 1; - failmsg("should throw a std::invalid_argument exception"); - } - catch (std::invalid_argument) - { //expectted } - - } - - // operator!=(R) - assert(obj != testobj.GetPointer()); - - // operator!=(const berry::SmartPointer&) - assert(obj != testobj); - - // == operators - // operator==(int) - assert((obj == 0) == false); - try { - obj == 1; - failmsg("should throw a std::invalid_argument exception"); - } - catch (std::invalid_argument) - { // expected } - - } - // operator==(R) - assert((obj == testobj.GetPointer()) == false); - // operator==(R) - assert(obj == obj.GetPointer()); - // operator==(R) - assert((obj == nullobj.GetPointer()) == false); - // operator==(const berry::SmartPointer&) - assert((obj == testobj) == false); - // operator==(const berry::SmartPointer&) - assert(obj == obj); - // operator==(const berry::SmartPointer&) - assert((obj == nullobj) == false); - } - - { - // = operators - berry::SmartPointer obj(new TestObject(1)); - berry::SmartPointer testobj(new TestObject(2)); - - obj = testobj; - // operator=(const berry::SmartPointer&) - assert(obj == testobj); - assertEqual(2, obj->GetReferenceCount()); - - // operator=(Object*) - obj = testobj.GetPointer(); - assert(obj == testobj); - assertEqual(2, obj->GetReferenceCount()); - } - -} - -} diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berrySmartPointerTest.h b/Plugins/Testing/org.blueberry.osgi.tests/src/berrySmartPointerTest.h deleted file mode 100644 index a31b1def1c..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berrySmartPointerTest.h +++ /dev/null @@ -1,38 +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. - -============================================================================*/ - - -#ifndef BERRYSMARTPOINTERTEST_H_ -#define BERRYSMARTPOINTERTEST_H_ - -#include - -namespace berry { - -class SmartPointerTest : public TestCase -{ -public: - - SmartPointerTest(const std::string& testName); - - static CppUnit::Test* Suite(); - - void TestConstructors(); - void TestCasting(); - void TestReferenceCounting(); - void TestOperators(); - -}; - -} - -#endif /* BERRYSMARTPOINTERTEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryWeakPointerTest.cpp b/Plugins/Testing/org.blueberry.osgi.tests/src/berryWeakPointerTest.cpp deleted file mode 100644 index 095cb240ba..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryWeakPointerTest.cpp +++ /dev/null @@ -1,98 +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 -//#include - -#include "berryWeakPointerTest.h" - -#include -#include - -namespace berry -{ - -struct TestObject: public Object -{ - - /** creating a test object in order to test the weakpointer functions */ - - TestObject() - { } - -}; - -WeakPointerTest::WeakPointerTest(const std::string& testName) : - TestCase(testName) -{ - -} - -CppUnit::Test* WeakPointerTest::Suite() -{ - CppUnit::TestSuite* suite = new CppUnit::TestSuite("WeakPointerTest"); - - CppUnit_addTest(suite, WeakPointerTest, TestReferenceCounting); - CppUnit_addTest(suite, WeakPointerTest, TestConstructorAndLock); - CppUnit_addTest(suite, WeakPointerTest, TestOperators); - - return suite; -} - -void WeakPointerTest::TestReferenceCounting() -{ - - SmartPointer ptr_smart(new TestObject()); - - WeakPointer ptr_weak(ptr_smart); - assertEqual(1, ptr_smart->GetReferenceCount()); - - /* Testing the Object reference counter after returning a smartpointer - * to an object, Reference counter should be increased to 2 */ - SmartPointer ptr_smart2(ptr_weak); - assertEqual(2, ptr_smart->GetReferenceCount()); -} - -void WeakPointerTest::TestConstructorAndLock() -{ - SmartPointer* ptr_smart = new SmartPointer ( - new TestObject); - WeakPointer ptr_weak(*ptr_smart); - WeakPointer ptr_weak2(ptr_weak); - { - SmartPointer ptr_smart1(ptr_weak); - SmartPointer ptr_smart2(ptr_weak2); - assertEqual(ptr_smart1.GetPointer(), ptr_smart2.GetPointer()); - } - assertEqual(1, (*ptr_smart)->GetReferenceCount()); - delete ptr_smart; - assert(ptr_weak2.Lock() == 0); -} - -void WeakPointerTest::TestOperators() -{ - SmartPointer ptr_smart(new TestObject); - SmartPointer ptr_smart2(new TestObject); - { - WeakPointer ptr_weak(ptr_smart); - WeakPointer ptr_weak2(ptr_smart2); - ptr_weak = ptr_weak2; - SmartPointer ptr_smart3(ptr_weak2); - SmartPointer ptr_smart4(ptr_weak); - assertEqual(ptr_smart3.GetPointer(), ptr_smart4.GetPointer()); - } -} - -} diff --git a/Plugins/Testing/org.blueberry.osgi.tests/src/berryWeakPointerTest.h b/Plugins/Testing/org.blueberry.osgi.tests/src/berryWeakPointerTest.h deleted file mode 100644 index 49999b0e39..0000000000 --- a/Plugins/Testing/org.blueberry.osgi.tests/src/berryWeakPointerTest.h +++ /dev/null @@ -1,36 +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. - -============================================================================*/ - - -#ifndef BERRYWEAKPOINTERTEST_H_ -#define BERRYWEAKPOINTERTEST_H_ - -#include - -namespace berry { - -class WeakPointerTest : public TestCase -{ -public: - - WeakPointerTest(const std::string& testName); - - static CppUnit::Test* Suite(); - - void TestReferenceCounting(); - void TestConstructorAndLock(); - void TestOperators(); -}; - -} - -#endif /* BERRYWEAKPOINTERTEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/CMakeLists.txt b/Plugins/Testing/org.blueberry.ui.tests/CMakeLists.txt deleted file mode 100644 index f57bb14965..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -project(org_blueberry_ui_tests) - -mitk_create_plugin( - EXPORT_DIRECTIVE BERRY_UI_TESTS - TEST_PLUGIN -) - -target_link_libraries(${PROJECT_NAME} optimized CppUnit debug CppUnitd) - -add_dependencies(${PROJECT_NAME} org_blueberry_ui_qt) - -MACRO_TEST_UIPLUGIN() diff --git a/Plugins/Testing/org.blueberry.ui.tests/documentation/doxygen/modules.dox b/Plugins/Testing/org.blueberry.ui.tests/documentation/doxygen/modules.dox deleted file mode 100644 index 8cbf496b3a..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/documentation/doxygen/modules.dox +++ /dev/null @@ -1,16 +0,0 @@ -/** - \defgroup org_blueberry_ui_tests org.blueberry.ui.tests - \ingroup BlueBerryPlugins - - \brief Describe your plugin here. - -*/ - -/** - \defgroup org_blueberry_ui_tests_internal Internal - \ingroup org_blueberry_ui_tests - - \brief This subcategory includes the internal classes of the org.blueberry.ui.tests plugin. Other - plugins must not rely on these classes. They contain implementation details and their interface - may change at any time. We mean it. -*/ diff --git a/Plugins/Testing/org.blueberry.ui.tests/files.cmake b/Plugins/Testing/org.blueberry.ui.tests/files.cmake deleted file mode 100644 index 2bc694a110..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/files.cmake +++ /dev/null @@ -1,45 +0,0 @@ -set(MOC_H_FILES - src/berryPluginActivator.h - src/berryUiTestSuite.h - - src/api/berryMockViewPart.h - src/api/berrySaveableMockViewPart.h -) - -set(CACHED_RESOURCE_FILES - plugin.xml - icons/view.gif -) - -set(SRC_CPP_FILES - - berryPluginActivator.cpp - berryUiTestSuite.cpp - - # API Tests - api/berryIPageLayoutTest.cpp - api/berryIViewPartTest.cpp - api/berryIWorkbenchPartTest.cpp - api/berryMockSelectionProvider.cpp - api/berryMockViewPart.cpp - api/berryMockWorkbenchPart.cpp - api/berrySaveableMockViewPart.cpp - api/berryUiApiTestSuite.cpp - api/berryXMLMementoTest.cpp - -) - -set(INTERNAL_CPP_FILES - -) - -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/Testing/org.blueberry.ui.tests/icons/view.gif b/Plugins/Testing/org.blueberry.ui.tests/icons/view.gif deleted file mode 100755 index efc77a7f75..0000000000 Binary files a/Plugins/Testing/org.blueberry.ui.tests/icons/view.gif and /dev/null differ diff --git a/Plugins/Testing/org.blueberry.ui.tests/manifest_headers.cmake b/Plugins/Testing/org.blueberry.ui.tests/manifest_headers.cmake deleted file mode 100644 index a62f14f395..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/manifest_headers.cmake +++ /dev/null @@ -1,6 +0,0 @@ -set(Plugin-Name "UI Automated Tests") -set(Plugin-Version "0.9") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.blueberry.uitest) - diff --git a/Plugins/Testing/org.blueberry.ui.tests/plugin.xml b/Plugins/Testing/org.blueberry.ui.tests/plugin.xml deleted file mode 100644 index d3902f6dfc..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/plugin.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIPageLayoutTest.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIPageLayoutTest.cpp deleted file mode 100644 index f7ab8f4ee7..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIPageLayoutTest.cpp +++ /dev/null @@ -1,48 +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 "berryIPageLayoutTest.h" - -#include -#include - -#include - -namespace berry -{ - -IPageLayoutTest::IPageLayoutTest(const std::string& testName) : - UITestCase(testName) -{ - -} - -CppUnit::Test* IPageLayoutTest::Suite() -{ - CppUnit::TestSuite* suite = new CppUnit::TestSuite("IPageLayoutTest"); - - CppUnit_addTest(suite, IPageLayoutTest, TestGetDescriptor); - - return suite; -} - -void IPageLayoutTest::TestGetDescriptor() -{ - this->IgnoreLeakingObjects(); - //this->LeakDetailsOn(); - - EmptyPerspective::SetLastPerspective(""); - OpenTestWindow(EmptyPerspective::PERSP_ID); - assertEqual(EmptyPerspective::PERSP_ID, EmptyPerspective::GetLastPerspective()); -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIPageLayoutTest.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIPageLayoutTest.h deleted file mode 100644 index 6fb416f071..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIPageLayoutTest.h +++ /dev/null @@ -1,44 +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. - -============================================================================*/ - - -#ifndef BERRYIPAGELAYOUTTEST_H_ -#define BERRYIPAGELAYOUTTEST_H_ - -#include - -#include - -namespace berry { - -/** - * Test cases for the IPageLayout API. - * - * @since 3.2 - */ -class IPageLayoutTest : public UITestCase { - -public: - - friend class CppUnit::TestCaller; - - IPageLayoutTest(const std::string& testName); - - static CppUnit::Test* Suite(); - - void TestGetDescriptor(); - -}; - -} - -#endif /* BERRYIPAGELAYOUTTEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIViewPartTest.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIViewPartTest.cpp deleted file mode 100644 index 1ef4c88b2b..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIViewPartTest.cpp +++ /dev/null @@ -1,90 +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 "berryIViewPartTest.h" - -#include "berrySaveableMockViewPart.h" - -#include - -#include - -namespace berry -{ - -IViewPartTest::IViewPartTest(const std::string& testName) : - IWorkbenchPartTest(testName) -{ - -} - -CppUnit::Test* IViewPartTest::Suite() -{ - CppUnit::TestSuite* suite = new CppUnit::TestSuite("IViewPartTest"); - - CppUnit_addTest(suite, IViewPartTest, TestOpenAndCloseSaveNotNeeded); - CppUnit_addTest(suite, IViewPartTest, TestOpenAndClose); - CppUnit_addTest(suite, IViewPartTest, TestOpenAndWindowClose); - - return suite; -} - -void IViewPartTest::TestOpenAndCloseSaveNotNeeded() -{ - this->IgnoreLeakingObjects(); - //this->LeakDetailsOn(); - - CallHistory::Pointer history; - - { - // Open a part. - SaveableMockViewPart::Pointer part = fPage->ShowView( - SaveableMockViewPart::ID).Cast (); - - part->SetDirty(true); - part->SetSaveNeeded(false); - ClosePart(fPage, part); - - history = part->GetCallHistory(); - } - - // TODO: This verifies the 3.0 disposal order. However, there may be a bug here. - // That is, it may be necessary to change this and dispose the contribution items - // after the view's dispose method in order to ensure that the site is never returning - // a disposed contribution item. See bug 94457 for details. - std::vector callOrder; - callOrder.push_back("SetInitializationData"); - callOrder.push_back("Init"); - callOrder.push_back("CreatePartControl"); - callOrder.push_back("SetFocus"); - callOrder.push_back("IsSaveOnCloseNeeded"); - callOrder.push_back("WidgetDisposed"); - //callOrder.push_back("ToolbarContributionItemWidgetDisposed"); - //callOrder.push_back("ToolbarContributionItemDisposed"); - callOrder.push_back("PartDestructor"); - assert(history->VerifyOrder(callOrder)); - // TODO enable assert when saveable support is complete - //assert(history->Contains("DoSave")); -} - -MockWorkbenchPart::Pointer IViewPartTest::OpenPart(IWorkbenchPage::Pointer page) -{ - return page->ShowView(MockViewPart::ID).Cast (); -} - -void IViewPartTest::ClosePart(IWorkbenchPage::Pointer page, - MockWorkbenchPart::Pointer part) -{ - page->HideView(part.Cast ()); -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIViewPartTest.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIViewPartTest.h deleted file mode 100644 index d9cf70d068..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIViewPartTest.h +++ /dev/null @@ -1,68 +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. - -============================================================================*/ - -#ifndef BERRYIVIEWPARTTEST_H_ -#define BERRYIVIEWPARTTEST_H_ - -#include "berryIWorkbenchPartTest.h" - -#include - -namespace berry -{ - -/** - * This is a test for IViewPart. Since IViewPart is an - * interface this test verifies the IViewPart lifecycle rather - * than the implementation. - */ -class IViewPartTest: public IWorkbenchPartTest -{ - -public: - - friend class CppUnit::TestCaller; - - /** - * Constructor for IViewPartTest - */ - IViewPartTest(const std::string& testName); - - static CppUnit::Test* Suite(); - - /** - * Tests that the view is closed without saving if isSaveOnCloseNeeded() - * returns false. This also tests some disposal behaviors specific to - * views: namely, that the contribution items are disposed in the correct - * order with respect to the disposal of the view. - * - * @see ISaveablePart#isSaveOnCloseNeeded() - */ - void TestOpenAndCloseSaveNotNeeded(); - -protected: - - /** - * @see IWorkbenchPartTest#openPart(IWorkbenchPage) - */ - MockWorkbenchPart::Pointer OpenPart(IWorkbenchPage::Pointer page); - - /** - * @see IWorkbenchPartTest#closePart(IWorkbenchPage, MockWorkbenchPart) - */ - void ClosePart(IWorkbenchPage::Pointer page, MockWorkbenchPart::Pointer part); - -}; - -} - -#endif /* BERRYIVIEWPARTTEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIWorkbenchPartTest.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIWorkbenchPartTest.cpp deleted file mode 100644 index 691de05bb3..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIWorkbenchPartTest.cpp +++ /dev/null @@ -1,100 +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 "berryIWorkbenchPartTest.h" - -namespace berry -{ - -void IWorkbenchPartTest::DoSetUp() -{ - UITestCase::DoSetUp(); - fWindow = OpenTestWindow(); - fPage = fWindow->GetActivePage(); -} - -void IWorkbenchPartTest::DoTearDown() -{ - fPage = 0; - fWindow = 0; - UITestCase::DoTearDown(); -} - -IWorkbenchPartTest::IWorkbenchPartTest(const std::string& testName) : - UITestCase(testName) -{ - -} - -void IWorkbenchPartTest::TestOpenAndClose() -{ - this->IgnoreLeakingObjects(); - - CallHistory::Pointer history; - std::vector callOrder; - { - // Open a part. - MockWorkbenchPart::Pointer part = OpenPart(fPage); - assert(part->IsSiteInitialized()); - history = part->GetCallHistory(); - - callOrder.push_back("SetInitializationData"); - callOrder.push_back("Init"); - callOrder.push_back("CreatePartControl"); - callOrder.push_back("SetFocus"); - - assert(history->VerifyOrder(callOrder)); - - // Close the part. - ClosePart(fPage, part); - } - - callOrder.push_back("WidgetDisposed"); - callOrder.push_back("PartDestructor"); - assert(history->VerifyOrder(callOrder)); -} - -void IWorkbenchPartTest::TestOpenAndWindowClose() -{ - this->IgnoreLeakingObjects(); - - CallHistory::Pointer history; - std::vector callOrder; - { - // Open a new window - IWorkbenchWindow::Pointer newWindow = OpenTestWindow(); - - // Open a part. - MockWorkbenchPart::Pointer part = OpenPart(newWindow->GetActivePage()); - assert(part->IsSiteInitialized()); - history = part->GetCallHistory(); - - callOrder.push_back("SetInitializationData"); - callOrder.push_back("Init"); - callOrder.push_back("CreatePartControl"); - callOrder.push_back("SetFocus"); - - assert(history->VerifyOrder(callOrder)); - - // Close the window. - newWindow->Close(); - } - - // The Qt widget for the window is deleted - // asynchronously, so the "WidgetDisposed" - // call may come after the part destructor - //callOrder.push_back("WidgetDisposed"); - callOrder.push_back("PartDestructor"); - assert(history->VerifyOrder(callOrder)); -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIWorkbenchPartTest.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIWorkbenchPartTest.h deleted file mode 100644 index 5ff79c661a..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryIWorkbenchPartTest.h +++ /dev/null @@ -1,65 +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. - -============================================================================*/ - - -#ifndef BERRYIWORKBENCHPARTTEST_H_ -#define BERRYIWORKBENCHPARTTEST_H_ - -#include -#include -#include - -#include "berryMockWorkbenchPart.h" - -namespace berry { - -/** - * This is a test for IWorkbenchPart. Since IWorkbenchPart is an - * interface this test verifies the IWorkbenchPart lifecycle rather - * than the implementation. - */ -class IWorkbenchPartTest : public UITestCase { - -protected: - - IWorkbenchWindow::Pointer fWindow; - IWorkbenchPage::Pointer fPage; - - void DoSetUp(); - void DoTearDown(); - - /** - * Opens a part. Subclasses should override - */ - virtual MockWorkbenchPart::Pointer OpenPart(IWorkbenchPage::Pointer page) = 0; - - /** - * Closes a part. Subclasses should override - */ - virtual void ClosePart(IWorkbenchPage::Pointer page, MockWorkbenchPart::Pointer part) = 0; - -public: - - /** - * Constructor for IActionDelegateTest - */ - IWorkbenchPartTest(const std::string& testName); - - void TestOpenAndClose(); - - void TestOpenAndWindowClose(); - -}; - -} - -#endif /* BERRYIWORKBENCHPARTTEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockSelectionProvider.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockSelectionProvider.cpp deleted file mode 100644 index 5a15443c7e..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockSelectionProvider.cpp +++ /dev/null @@ -1,99 +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 "berryMockSelectionProvider.h" - -namespace berry -{ - -struct EmptyStructuredSelection : public IStructuredSelection -{ - - EmptyStructuredSelection() - : elements(new ContainerType()) - {} - - Object::Pointer GetFirstElement() const - { - return Object::Pointer(0); - } - - iterator Begin() const - { - return elements->begin(); - } - - iterator End() const - { - return elements->end(); - } - - int Size() const - { - return elements->size(); - } - - bool IsEmpty() const - { - return true; - } - - ContainerType::Pointer ToVector() const - { - return elements; - } - -private: - - ContainerType::Pointer elements; -}; - -MockSelectionProvider::MockSelectionProvider() -: emptySelection(new EmptyStructuredSelection()) -{ - -} - -void MockSelectionProvider::FireSelection() -{ - SelectionChangedEvent::Pointer event(new SelectionChangedEvent( - ISelectionProvider::Pointer(this), emptySelection)); - FireSelection(event); -} - -void MockSelectionProvider::FireSelection(SelectionChangedEvent::Pointer event) -{ - listeners.selectionChanged(event); -} - -void MockSelectionProvider::AddSelectionChangedListener( - ISelectionChangedListener::Pointer listener) -{ - listeners.AddListener(listener); -} - -ISelection::ConstPointer MockSelectionProvider::GetSelection() const -{ - return emptySelection; -} - -void MockSelectionProvider::RemoveSelectionChangedListener( - ISelectionChangedListener::Pointer listener) -{ - listeners.RemoveListener(listener); -} - -void MockSelectionProvider::SetSelection(ISelection::Pointer /*selection*/) -{ -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockSelectionProvider.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockSelectionProvider.h deleted file mode 100644 index fe1b1c4473..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockSelectionProvider.h +++ /dev/null @@ -1,70 +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. - -============================================================================*/ - -#ifndef BERRYMOCKSELECTIONPROVIDER_H_ -#define BERRYMOCKSELECTIONPROVIDER_H_ - -#include -#include - -namespace berry -{ - -class MockSelectionProvider: public ISelectionProvider -{ - -private: - - ISelectionChangedListener::Events listeners; - IStructuredSelection::Pointer emptySelection; - -public: - - berryObjectMacro(MockSelectionProvider); - - MockSelectionProvider(); - - /** - * Fires out a selection to all listeners. - */ - void FireSelection(); - - /** - * Fires out a selection to all listeners. - */ - void FireSelection(SelectionChangedEvent::Pointer event); - - /** - * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) - */ - void AddSelectionChangedListener(ISelectionChangedListener::Pointer listener); - - /** - * @see ISelectionProvider#getSelection() - */ - ISelection::ConstPointer GetSelection() const; - - /** - * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) - */ - void RemoveSelectionChangedListener( - ISelectionChangedListener::Pointer listener); - - /** - * @see ISelectionProvider#setSelection(ISelection) - */ - void SetSelection(ISelection::Pointer /*selection*/); -}; - -} - -#endif /* BERRYMOCKSELECTIONPROVIDER_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockViewPart.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockViewPart.cpp deleted file mode 100644 index 1e4403e480..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockViewPart.cpp +++ /dev/null @@ -1,146 +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 "berryMockViewPart.h" - -namespace berry -{ - -const std::string MockViewPart::ID = "org.blueberry.ui.tests.api.MockViewPart"; -const std::string MockViewPart::ID2 = MockViewPart::ID + "2"; -const std::string MockViewPart::ID3 = MockViewPart::ID + "3"; -const std::string MockViewPart::ID4 = MockViewPart::ID + "4"; -const std::string MockViewPart::IDMULT = MockViewPart::ID + "Mult"; -const std::string MockViewPart::NAME = "Mock View 1"; - -MockViewPart::MockViewPart() -{ - -} - -MockViewPart::MockViewPart(const MockViewPart& other) -{ - Q_UNUSED(other) - throw std::runtime_error("Copy constructor not implemented"); -} - -IViewSite::Pointer MockViewPart::GetViewSite() -{ - return GetSite().Cast (); -} - -void MockViewPart::Init(IViewSite::Pointer site, IMemento::Pointer /*memento*/) - throw (PartInitException) -{ - SetSite(site); - callTrace->Add("Init"); - SetSiteInitialized(); - //AddToolbarContributionItem(); -} - -void MockViewPart::CreatePartControl(void* parent) -{ - MockWorkbenchPart::CreatePartControl(parent); - - // Button addAction = new Button(parent, SWT.PUSH); - // addAction.setText("Add Action to Tool Bar"); - // addAction.addSelectionListener(new SelectionAdapter() { - // public void widgetSelected(SelectionEvent e) { - // IActionBars bars = getViewSite().getActionBars(); - // bars.getToolBarManager().add(new DummyAction()); - // bars.updateActionBars(); - // } - // }); - // - // Button removeAction = new Button(parent, SWT.PUSH); - // removeAction.setText("Remove Action from Tool Bar"); - // removeAction.addSelectionListener(new SelectionAdapter() { - // public void widgetSelected(SelectionEvent e) { - // IActionBars bars = getViewSite().getActionBars(); - // IToolBarManager tbm = bars.getToolBarManager(); - // IContributionItem[] items = tbm.getItems(); - // if (items.length > 0) { - // IContributionItem item = items[items.length-1]; - // if (item instanceof ActionContributionItem) { - // if (((ActionContributionItem) item).getAction() instanceof DummyAction) { - // tbm.remove(item); - // bars.updateActionBars(); - // } - // } - // } - // } - // }); -} - -MockViewPart::~MockViewPart() -{ - // // Test for bug 94457: The contribution items must still be in the toolbar manager at the - // // time the part is disposed. (Changing this behavior would be a breaking change for some - // // clients). - // Assert.assertTrue( - // "Contribution items should not be removed from the site until after the part is disposed", - // getViewSite().getActionBars().getToolBarManager().find( - // toolbarItem.getId()) == toolbarItem); -} - -void MockViewPart::ToolbarContributionItemWidgetDisposed() -{ - callTrace->Add("ToolbarContributionItemWidgetDisposed"); -} - -void MockViewPart::ToolbarContributionItemDisposed() -{ - callTrace->Add("ToolbarContributionItemDisposed"); -} - -void MockViewPart::SaveState(IMemento::Pointer /*memento*/) -{ - // do nothing -} - -IWorkbenchPartSite::Pointer MockViewPart::GetSite() const -{ - return MockWorkbenchPart::GetSite(); -} - -std::string MockViewPart::GetPartName() const -{ - return MockWorkbenchPart::GetPartName(); -} - -std::string MockViewPart::GetContentDescription() const -{ - return MockWorkbenchPart::GetContentDescription(); -} - -std::string MockViewPart::GetTitleToolTip() const -{ - return MockWorkbenchPart::GetTitleToolTip(); -} - -std::string MockViewPart::GetPartProperty(const std::string& key) const -{ - return MockWorkbenchPart::GetPartProperty(key); -} - -void MockViewPart::SetPartProperty(const std::string& key, - const std::string& value) -{ - MockWorkbenchPart::SetPartProperty(key, value); -} - -const std::map& MockViewPart::GetPartProperties() const -{ - return MockWorkbenchPart::GetPartProperties(); -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockViewPart.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockViewPart.h deleted file mode 100644 index 5067f2e3ad..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockViewPart.h +++ /dev/null @@ -1,150 +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. - -============================================================================*/ - -#ifndef BERRYMOCKVIEWPART_H_ -#define BERRYMOCKVIEWPART_H_ - -#include "berryMockWorkbenchPart.h" - -#include -#include - - -namespace berry -{ - -class MockViewPart: public QObject, public MockWorkbenchPart, public IViewPart -{ - Q_OBJECT - Q_INTERFACES(berry::IExecutableExtension berry::IViewPart) - -public: - - berryObjectMacro(MockViewPart); - - static const std::string ID; // = "org.blueberry.ui.tests.api.MockViewPart"; - static const std::string ID2; // = ID + "2"; - static const std::string ID3; // = ID + "3"; - static const std::string ID4; // = ID + "4"; - static const std::string IDMULT; // = ID + "Mult"; - static const std::string NAME; // = "Mock View 1"; - - MockViewPart(); - MockViewPart(const MockViewPart& other); - - /** - * @see IViewPart#getViewSite() - */ - IViewSite::Pointer GetViewSite(); - - /** - * @see IViewPart#Init(IViewSite, IMemento) - */ - void Init(IViewSite::Pointer site, IMemento::Pointer /*memento*/) - throw (PartInitException); - - /* (non-Javadoc) - * @see org.eclipse.ui.tests.api.MockWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) - */ - void CreatePartControl(void* parent); - - /* (non-Javadoc) - * @see org.eclipse.ui.tests.api.MockPart#dispose() - */ - ~MockViewPart(); - - void ToolbarContributionItemWidgetDisposed(); - - void ToolbarContributionItemDisposed(); - - /** - * @see IViewPart#saveState(IMemento) - */ - void SaveState(IMemento::Pointer /*memento*/); - - /** - * @see IWorkbenchPart#GetSite() - */ - IWorkbenchPartSite::Pointer GetSite() const; - - /** - * @see IWorkbenchPart#GetTitle() - */ - std::string GetPartName() const; - - std::string GetContentDescription() const; - - /** - * @see IWorkbenchPart#GetTitleToolTip() - */ - std::string GetTitleToolTip() const; - - std::string GetPartProperty(const std::string& key) const; - - void SetPartProperty(const std::string& key, const std::string& value); - - const std::map& GetPartProperties() const; - -private: - - // ContributionItem toolbarItem = new ContributionItem("someId") { - // - // private DisposeListener disposeListener = new DisposeListener() { - // public void widgetDisposed(DisposeEvent e) { - // toolbarContributionItemWidgetDisposed(); - // } - // - // public void fill(ToolBar parent, int index) { - // super.fill(parent, index); - // - // ToolItem item = new ToolItem(parent, index); - // - // item.addDisposeListener(disposeListener); - // item.setImage(WorkbenchImages.getImage(ISharedImages.IMG_DEF_VIEW)); - // } - // - // public void dispose() { - // toolbarContributionItemDisposed(); - // super.dispose(); - // } - // }; - // - // class DummyAction extends Action { - // public DummyAction() { - // setText("Monkey"); - // setImageDescriptor(getViewSite().getWorkbenchWindow() - // .getWorkbench().getSharedImages() - // .getImageDescriptor( - // ISharedImages.IMG_TOOL_DELETE)); - // } - // }; - // - // - // - // void AddToolbarContributionItem() { - // getViewSite().getActionBars().getToolBarManager().add(toolbarItem); - // } - - -protected: - - /* (non-Javadoc) - * @see org.eclipse.ui.tests.api.MockWorkbenchPart#getActionBars() - */ - // IActionBars GetActionBars() { - // return getViewSite().getActionBars(); - // } -}; - -} - -#endif /* BERRYMOCKVIEWPART_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockWorkbenchPart.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockWorkbenchPart.cpp deleted file mode 100644 index 4353c1fd5f..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockWorkbenchPart.cpp +++ /dev/null @@ -1,201 +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 "berryMockWorkbenchPart.h" - -#include -#include -#include -#include -#include -#include - -namespace berry -{ - -MockWorkbenchPart::MockWorkbenchPart() -: titleImage(0), parentWidget(0), - disposeListener(new GuiTk::ControlDestroyedAdapter(this, &MockWorkbenchPart::ControlDestroyed)) -, siteState(false) -{ - callTrace = new CallHistory(); - selectionProvider = new MockSelectionProvider(); -} - -void MockWorkbenchPart::SetSite(IWorkbenchPartSite::Pointer site) -{ - this->site = site; - site->SetSelectionProvider(selectionProvider); -} - -IWorkbenchPartSite::Pointer MockWorkbenchPart::GetSite() const -{ - return site; -} - -std::string MockWorkbenchPart::GetPartName() const -{ - return title; -} - -std::string MockWorkbenchPart::GetContentDescription() const -{ - return title; -} - -std::string MockWorkbenchPart::GetTitleToolTip() const -{ - return title; -} - -CallHistory::Pointer MockWorkbenchPart::GetCallHistory() const -{ - return callTrace; -} - -ISelectionProvider::Pointer MockWorkbenchPart::GetSelectionProvider() -{ - return selectionProvider; -} - -void MockWorkbenchPart::SetInitializationData( - IConfigurationElement::Pointer config, const std::string& /*propertyName*/, - Object::Pointer data) -{ - - callTrace->Add("SetInitializationData"); - - this->config = config; - this->data = data; - - // Icon. - std::string strIcon; - if (config->GetAttribute("icon", strIcon)) - { - ImageDescriptor::Pointer imageDesc = ImageDescriptor::CreateFromFile( - strIcon, config->GetContributor()); - titleImage = imageDesc->CreateImage(); - } - - config->GetAttribute("name", title); -} - -void MockWorkbenchPart::ControlDestroyed(GuiTk::ControlEvent::Pointer) -{ - callTrace->Add("WidgetDisposed"); - parentWidget = 0; -} - -void MockWorkbenchPart::AddPropertyListener( - IPropertyChangeListener::Pointer listener) -{ - propertyEvent.AddListener(listener); -} - -void MockWorkbenchPart::RemovePropertyListener( - IPropertyChangeListener::Pointer listener) -{ - propertyEvent.RemoveListener(listener); -} - -void MockWorkbenchPart::CreatePartControl(void* parent) -{ - callTrace->Add("CreatePartControl"); - - this->parentWidget = parent; - Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(parent, - disposeListener); -} - -MockWorkbenchPart::~MockWorkbenchPart() -{ - callTrace->Add("PartDestructor"); - - if (parentWidget) - { - Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(parentWidget, - disposeListener); - } -} - -void* MockWorkbenchPart::GetTitleImage() const -{ - return titleImage; -} - -void MockWorkbenchPart::SetFocus() -{ - callTrace->Add("SetFocus"); -} - -void MockWorkbenchPart::FireSelection() -{ - selectionProvider->FireSelection(); -} - -bool MockWorkbenchPart::IsSiteInitialized() -{ - return siteState; -} - -void MockWorkbenchPart::SetSiteInitialized() -{ - SetSiteInitialized( - // GetSite()->GetKeyBindingService() != 0 && - (GetSite()->GetPage() != 0) && (GetSite()->GetSelectionProvider() != 0) - && (GetSite()->GetWorkbenchWindow() != 0) // && - // TestActionBars(GetActionBars()) - ); -} - -IConfigurationElement::Pointer MockWorkbenchPart::GetConfig() -{ - return config; -} - -Object::Pointer MockWorkbenchPart::GetData() -{ - return data; -} - -void MockWorkbenchPart::FirePropertyChange(int propertyId) -{ - ObjectInt::Pointer value(new ObjectInt(propertyId)); - PropertyChangeEvent::Pointer event(new PropertyChangeEvent(Object::Pointer( - this), IWorkbenchPartConstants::INTEGER_PROPERTY, value, value)); - propertyEvent.propertyChange(event); -} - -void MockWorkbenchPart::SetSiteInitialized(bool initialized) -{ - siteState = initialized; -} - -std::string MockWorkbenchPart::GetPartProperty(const std::string& key) const -{ - std::map::const_iterator i = properties.find(key); - if (i != properties.end()) return i->second; - return ""; -} - -void MockWorkbenchPart::SetPartProperty(const std::string& key, - const std::string& value) -{ - properties[key] = value; -} - -const std::map& MockWorkbenchPart::GetPartProperties() const -{ - return properties; -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockWorkbenchPart.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockWorkbenchPart.h deleted file mode 100644 index 1884a4ef0b..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryMockWorkbenchPart.h +++ /dev/null @@ -1,191 +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. - -============================================================================*/ - -#ifndef BERRYWORKBENCHMOCKPART_H_ -#define BERRYWORKBENCHMOCKPART_H_ - -#include - -#include "berryMockSelectionProvider.h" - -#include -#include -#include -#include -#include -#include - -namespace berry -{ - -/** - * Base class for mock intro and workbench parts. - * - * @since 3.0 - */ -class MockWorkbenchPart: public virtual IWorkbenchPart, public IExecutableExtension -{ - -public: - - berryObjectMacro(MockWorkbenchPart); - - MockWorkbenchPart(); - - void SetSite(IWorkbenchPartSite::Pointer site); - - IWorkbenchPartSite::Pointer GetSite() const; - - /** - * @see IWorkbenchPart#GetPartName() - */ - std::string GetPartName() const; - - /** - * @see IWorkbenchPart#GetContentDescription() - */ - std::string GetContentDescription() const; - - /** - * @see IWorkbenchPart#getTitleToolTip() - */ - std::string GetTitleToolTip() const; - - CallHistory::Pointer GetCallHistory() const; - - ISelectionProvider::Pointer GetSelectionProvider(); - - void SetInitializationData(IConfigurationElement::Pointer config, - const std::string& /*propertyName*/, Object::Pointer data); - - // This isn't actually part of the part API, but we call this method from a dispose listener - // in order to mark the point in time at which the widgets are disposed - void ControlDestroyed(GuiTk::ControlEvent::Pointer e); - - /** - * @see IWorkbenchPart#addPropertyListener(IPropertyListener) - */ - void AddPropertyListener(IPropertyChangeListener::Pointer listener); - - /** - * @see IWorkbenchPart#removePropertyListener(IPropertyListener) - */ - void RemovePropertyListener(IPropertyChangeListener::Pointer listener); - - std::string GetPartProperty(const std::string& key) const; - - void SetPartProperty(const std::string& key, const std::string& value); - - const std::map& GetPartProperties() const; - - /** - * @see IWorkbenchPart#createPartControl(Composite) - */ - void CreatePartControl(void* parent); - - /** - * @see IWorkbenchPart#dispose() - */ - ~MockWorkbenchPart(); - - /** - * @see IWorkbenchPart#getTitleImage() - */ - void* GetTitleImage() const; - - /** - * @see IWorkbenchPart#setFocus() - */ - void SetFocus(); - - // /** - // * @see IAdaptable#getAdapter(Class) - // */ - // Object::Pointer GetAdapter(Class arg0) { - // return null; - // } - - /** - * Fires a selection out. - */ - void FireSelection(); - - /** - * Gets whether the site was properly initialized in the init method. - */ - bool IsSiteInitialized(); - -protected: - - CallHistory::Pointer callTrace; - - MockSelectionProvider::Pointer selectionProvider; - - // IActionBars GetActionBars() = 0; - - void SetSiteInitialized(); - - IConfigurationElement::Pointer GetConfig(); - - Object::Pointer GetData(); - - /** - * Fires a property change event. - */ - void FirePropertyChange(int propertyId); - - /** - * Sets whether the site was properly initialized in the init method. - */ - void SetSiteInitialized(bool initialized); - -private: - - IConfigurationElement::Pointer config; - - Object::Pointer data; - - void* titleImage; - - void* parentWidget; - - IWorkbenchPartSite::Pointer site; - - std::string title; - - IPropertyChangeListener::Events propertyEvent; - - GuiTk::IControlListener::Pointer disposeListener; - - /** - * boolean to declare whether the site was properly initialized in the init method. - */ - bool siteState; - - // /** - // * @param actionBars - // * @return - // */ - // bool TestActionBars(IActionBars bars) { - // return bars != null && bars.getMenuManager() != null - // && bars.getToolBarManager() != null - // && bars.getStatusLineManager() != null; - // - // } - - std::map properties; - -}; - -} - -#endif /* BERRYWORKBENCHMOCKPART_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berrySaveableMockViewPart.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berrySaveableMockViewPart.cpp deleted file mode 100644 index 585b0aa11f..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berrySaveableMockViewPart.cpp +++ /dev/null @@ -1,109 +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 "berrySaveableMockViewPart.h" - -namespace berry -{ - -const std::string SaveableMockViewPart::ID = - "org.blueberry.ui.tests.api.SaveableMockViewPart"; - -SaveableMockViewPart::SaveableMockViewPart() : - isDirty(false), saveAsAllowed(false), saveNeeded(true) -{ - -} - -SaveableMockViewPart::SaveableMockViewPart(const SaveableMockViewPart& other) -{ - Q_UNUSED(other) - throw std::runtime_error("Copy constructor not implemented"); -} - -void SaveableMockViewPart::CreatePartControl(void* parent) -{ - MockViewPart::CreatePartControl(parent); - - // final Button dirtyToggle = new Button(parent, SWT.CHECK); - // dirtyToggle.setText("Dirty"); - // dirtyToggle.addSelectionListener(new SelectionAdapter() { - // public void widgetSelected(SelectionEvent e) { - // setDirty(dirtyToggle.getSelection()); - // } - // }); - // dirtyToggle.setSelection(isDirty()); - // - // final Button saveNeededToggle = new Button(parent, SWT.CHECK); - // saveNeededToggle.setText("Save on close"); - // saveNeededToggle.addSelectionListener(new SelectionAdapter() { - // public void widgetSelected(SelectionEvent e) { - // setSaveNeeded(saveNeededToggle.getSelection()); - // } - // }); - // saveNeededToggle.setSelection(saveNeeded); - // - // final Button saveAsToggle = new Button(parent, SWT.CHECK); - // saveAsToggle.setText("Save as allowed"); - // saveAsToggle.addSelectionListener(new SelectionAdapter() { - // public void widgetSelected(SelectionEvent e) { - // setSaveAsAllowed(saveAsToggle.getSelection()); - // } - // }); - // saveAsToggle.setSelection(saveAsAllowed); -} - -void SaveableMockViewPart::DoSave(/*IProgressMonitor monitor*/) -{ - callTrace->Add("DoSave"); -} - -void SaveableMockViewPart::DoSaveAs() -{ - callTrace->Add("DoSaveAs"); -} - -bool SaveableMockViewPart::IsDirty() const -{ - callTrace->Add("IsDirty"); - return isDirty; -} - -bool SaveableMockViewPart::IsSaveAsAllowed() const -{ - callTrace->Add("IsSaveAsAllowed"); - return saveAsAllowed; -} - -bool SaveableMockViewPart::IsSaveOnCloseNeeded() const -{ - callTrace->Add("IsSaveOnCloseNeeded"); - return saveNeeded; -} - -void SaveableMockViewPart::SetDirty(bool isDirty) -{ - this->isDirty = isDirty; - FirePropertyChange(ISaveablePart::PROP_DIRTY); -} - -void SaveableMockViewPart::SetSaveAsAllowed(bool isSaveAsAllowed) -{ - this->saveAsAllowed = isSaveAsAllowed; -} - -void SaveableMockViewPart::SetSaveNeeded(bool isSaveOnCloseNeeded) -{ - this->saveNeeded = isSaveOnCloseNeeded; -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berrySaveableMockViewPart.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berrySaveableMockViewPart.h deleted file mode 100644 index 8c03683e5d..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berrySaveableMockViewPart.h +++ /dev/null @@ -1,88 +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. - -============================================================================*/ - -#ifndef BERRYSAVEABLEMOCKVIEWPART_H_ -#define BERRYSAVEABLEMOCKVIEWPART_H_ - -#include "berryMockViewPart.h" - -#include - -namespace berry -{ - -/** - * Mock view part that implements ISaveablePart. - * Used for testing hideView and other view lifecycle on saveable views. - * - * @since 3.0.1 - */ -class SaveableMockViewPart: public MockViewPart, public ISaveablePart -{ - Q_OBJECT - Q_INTERFACES(berry::ISaveablePart) - -public: - - berryObjectMacro(SaveableMockViewPart); - - static const std::string ID; // = "org.blueberry.ui.tests.api.SaveableMockViewPart"; - - SaveableMockViewPart(); - SaveableMockViewPart(const SaveableMockViewPart& other); - - void CreatePartControl(void* parent); - - /* (non-Javadoc) - * @see org.eclipse.ui.ISaveablePart#doSave(org.eclipse.core.runtime.IProgressMonitor) - */ - void DoSave(/*IProgressMonitor monitor*/); - - /* (non-Javadoc) - * @see org.eclipse.ui.ISaveablePart#doSaveAs() - */ - void DoSaveAs(); - - /* (non-Javadoc) - * @see org.eclipse.ui.ISaveablePart#isDirty() - */ - bool IsDirty() const; - - /* (non-Javadoc) - * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed() - */ - bool IsSaveAsAllowed() const; - - /* (non-Javadoc) - * @see org.eclipse.ui.ISaveablePart#isSaveOnCloseNeeded() - */ - bool IsSaveOnCloseNeeded() const; - - void SetDirty(bool isDirty); - - void SetSaveAsAllowed(bool isSaveAsAllowed); - - void SetSaveNeeded(bool isSaveOnCloseNeeded); - -private: - - bool isDirty; - - bool saveAsAllowed; - - bool saveNeeded; - -}; - -} - -#endif /* BERRYSAVEABLEMOCKVIEWPART_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryUiApiTestSuite.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryUiApiTestSuite.cpp deleted file mode 100644 index 2d8a93e9d4..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryUiApiTestSuite.cpp +++ /dev/null @@ -1,29 +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 "berryUiApiTestSuite.h" - -#include "berryXMLMementoTest.h" -#include "berryIPageLayoutTest.h" -#include "berryIViewPartTest.h" - -namespace berry { - -UiApiTestSuite::UiApiTestSuite() -: CppUnit::TestSuite("UiApiTestSuite") -{ - addTest(IPageLayoutTest::Suite()); - addTest(IViewPartTest::Suite()); - addTest(XMLMementoTest::Suite()); -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryUiApiTestSuite.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryUiApiTestSuite.h deleted file mode 100644 index 7ac2f07abe..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryUiApiTestSuite.h +++ /dev/null @@ -1,31 +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. - -============================================================================*/ - - -#ifndef BERRYUIAPITESTSUITE_H_ -#define BERRYUIAPITESTSUITE_H_ - -#include - -namespace berry { - -class UiApiTestSuite : public CppUnit::TestSuite -{ - -public: - - UiApiTestSuite(); -}; - -} - -#endif /* BERRYUIAPITESTSUITE_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryXMLMementoTest.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryXMLMementoTest.cpp deleted file mode 100644 index 593ee46fe8..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryXMLMementoTest.cpp +++ /dev/null @@ -1,749 +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. - -============================================================================*/ - -#define NOMINMAX - -#include "berryXMLMementoTest.h" - -#include -#include -#include -#include -#include - -namespace berry -{ - -struct PutMementoChecker: public XMLMementoTest::MementoChecker -{ - - PutMementoChecker(XMLMementoTest* t) : - mementoTest(t) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - mementoToSerialize->PutTextData("unchanged text data"); - mementoToSerialize->PutString("neverlost", "retained value"); - - IMemento::Pointer aMemento = XMLMemento::CreateWriteRoot("foo"); - mementoTest->FillMemento(aMemento); - - // note that this does not copy the text data: - mementoToSerialize->PutMemento(aMemento); - - // do not check for text data: - mementoTest->CheckMemento(mementoToSerialize, false); - - assertEqual("unchanged text data", mementoToSerialize->GetTextData()); - std::string str; - mementoToSerialize->GetString("neverlost", str); - assertEqual("retained value", str); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - // do not check for text data: - mementoTest->CheckMemento(deserializedMemento, false); - - assertEqual("unchanged text data", deserializedMemento - ->GetTextData()); - std::string str; - deserializedMemento->GetString("neverlost", str); - assertEqual("retained value", str); - } - -private: - - XMLMementoTest* mementoTest; -}; - -struct PutAndGetStringChecker: public XMLMementoTest::MementoChecker -{ - - PutAndGetStringChecker(const std::string& key, const std::string& value) : - key(key), value(value) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - std::string helper; - assertEqual(false, mementoToSerialize->GetString(key, helper)); - mementoToSerialize->PutString(key, value); - mementoToSerialize->GetString(key, helper); - assertEqual(value, helper); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - std::string helper; - deserializedMemento->GetString(key, helper); - assertEqual(value, helper); - } - -private: - const std::string& key; - const std::string& value; -}; - -struct CopyChildChecker: public XMLMementoTest::MementoChecker -{ - - CopyChildChecker(XMLMementoTest* t) : - mementoTest(t) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - IMemento::Pointer child = mementoToSerialize->CreateChild("c", "i"); - mementoTest->FillMemento(child); - IMemento::Pointer copiedChild = mementoToSerialize->CopyChild(child); - assertEqual("i", copiedChild->GetID()); - mementoTest->CheckMemento(copiedChild, true); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - IMemento::Pointer child = deserializedMemento->GetChild("c"); - mementoTest->CheckMemento(child, true); - std::vector children(deserializedMemento->GetChildren( - "c")); - assertEqual(2, (long)children.size()); - assertEqual("i", children[0]->GetID()); - mementoTest->CheckMemento(children[0], true); - assertEqual("i", children[1]->GetID()); - mementoTest->CheckMemento(children[1], true); - } - -private: - - XMLMementoTest* mementoTest; -}; - -struct CreateAndGetChildChecker: public XMLMementoTest::MementoChecker -{ - - CreateAndGetChildChecker() : - type1("type1"), type2("type2"), id("id") - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - // check that nothing is there yet - assertNullPtr(mementoToSerialize->GetChild(type1).GetPointer()); - assertNullPtr(mementoToSerialize->GetChild(type2).GetPointer()); - - // creation without ID - IMemento::Pointer child1 = mementoToSerialize->CreateChild(type1); - assertNotNullPtr(child1.GetPointer()); - assertNotNullPtr(mementoToSerialize->GetChild(type1).GetPointer()); - - // creation with ID - IMemento::Pointer child2 = mementoToSerialize->CreateChild(type2, id); - assertNotNullPtr(child2.GetPointer()); - assertNotNullPtr(mementoToSerialize->GetChild(type2).GetPointer()); - assertEqual(id, child2->GetID()); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - IMemento::Pointer child1 = deserializedMemento->GetChild(type1); - assertNotNullPtr(child1.GetPointer()); - IMemento::Pointer child2 = deserializedMemento->GetChild(type2); - assertNotNullPtr(child2.GetPointer()); - assertEqual(id, child2->GetID()); - } - -private: - - const std::string type1; - const std::string type2; - const std::string id; -}; - -struct GetChildrenChecker: public XMLMementoTest::MementoChecker -{ - - GetChildrenChecker() : - type("type"), id1("id"), id2("id2") - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - // check that nothing is there yet - assertNullPtr(mementoToSerialize->GetChild(type).GetPointer()); - - IMemento::Pointer child1 = mementoToSerialize->CreateChild(type, id1); - assertNotNullPtr(child1.GetPointer()); - assertNotNullPtr(mementoToSerialize->GetChild(type).GetPointer()); - assertEqual(id1, child1->GetID()); - - // second child with the same type - IMemento::Pointer child2 = mementoToSerialize->CreateChild(type, id2); - assertNotNullPtr(child2.GetPointer()); - assertEqual(2, (long)mementoToSerialize->GetChildren(type).size()); - assertEqual(id2, child2->GetID()); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - std::vector children(deserializedMemento->GetChildren( - type)); - assertEqual(2, (long)children.size()); - - // this checks that the order is maintained. - // the spec does not promise this, but clients - // may rely on the current implementation behaviour. - assertEqual(id1, children[0]->GetID()); - assertEqual(id2, children[1]->GetID()); - } - -private: - const std::string type; - const std::string id1; - const std::string id2; -}; - -struct GetIDChecker: public XMLMementoTest::MementoChecker -{ - - GetIDChecker(const std::string& type, const std::string& id) : - type(type), id(id) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - assertNullPtr(mementoToSerialize->GetChild(type).GetPointer()); - IMemento::Pointer child = mementoToSerialize->CreateChild(type, id); - assertEqual(id, child->GetID()); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - IMemento::Pointer child = deserializedMemento->GetChild(type); - assertNotNullPtr(child.GetPointer()); - assertEqual(id, child->GetID()); - } - -private: - - const std::string type; - const std::string id; -}; - -struct PutAndGetFloatChecker: public XMLMementoTest::MementoChecker -{ - - PutAndGetFloatChecker(const std::string& key, double value) : - key(key), value(value) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - double v; - assertEqual(false, mementoToSerialize->GetFloat(key, v)); - mementoToSerialize->PutFloat(key, value); - mementoToSerialize->GetFloat(key, v); - assertEqual(value, v); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - double v; - deserializedMemento->GetFloat(key, v); - assertEqual(value, v); - } - -private: - const std::string key; - const double value; -}; - -struct PutAndGetIntChecker: public XMLMementoTest::MementoChecker -{ - - PutAndGetIntChecker(const std::string& key, const int value) : - key(key), value(value) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - int v; - assertEqual(false, mementoToSerialize->GetInteger(key, v)); - mementoToSerialize->PutInteger(key, value); - mementoToSerialize->GetInteger(key, v); - assertEqual(value, v); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - int v; - deserializedMemento->GetInteger(key, v); - assertEqual(value, v); - } - -private: - const std::string key; - const int value; -}; - -struct PutAndGetTextDataChecker: public XMLMementoTest::MementoChecker -{ - - PutAndGetTextDataChecker(const std::string& data) : - data(data) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - assertEqual("", mementoToSerialize->GetTextData()); - mementoToSerialize->PutTextData(data); - assertEqual(data, mementoToSerialize->GetTextData()); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - assertEqual(data, deserializedMemento->GetTextData()); - } - -private: - const std::string data; -}; - -struct LegalKeysChecker: public XMLMementoTest::MementoChecker -{ - - LegalKeysChecker(const std::string& key) : - key(key) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - std::string v; - assertEqual(false, mementoToSerialize->GetString(key, v)); - try - { - mementoToSerialize->PutString(key, "some string"); - } catch (Poco::RuntimeException& ex) - { - std::cout << "offending key: '" + key + "'" << std::endl; - ex.rethrow(); - } - mementoToSerialize->GetString(key, v); - assertEqual("some string", v); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - std::string v; - deserializedMemento->GetString(key, v); - assertEqual("some string", v); - } - -private: - const std::string key; -}; - -struct PutTextDataWithChildrenChecker: public XMLMementoTest::MementoChecker -{ - - PutTextDataWithChildrenChecker(const std::string& textData) : - textData(textData) - { - } - - void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) - { - mementoToSerialize->CreateChild("type", "id"); - mementoToSerialize->PutTextData(textData); - mementoToSerialize->CreateChild("type", "id"); - mementoToSerialize->CreateChild("type", "id"); - assertEqual(textData, mementoToSerialize->GetTextData()); - } - - void CheckAfterDeserialization(XMLMemento::Pointer deserializedMemento) - { - assertEqual(textData, deserializedMemento->GetTextData()); - } - -private: - const std::string textData; -}; - -const std::string XMLMementoTest::TEST_STRINGS[10] = -{ "value", " value with spaces ", "value.with.many.dots", - "value_with_underscores", "valuewith>greaterthan", - "value&with&ersand", "value\"with\"quote", "value#with#hash", "", }; - -const unsigned int XMLMementoTest::TEST_STRINGS_LENGTH = 10; -/* - * the following cases are for bug 93720 - */ -// "\nvalue\nwith\nnewlines\n", "\tvalue\twith\ttab\t", -// "\rvalue\rwith\rreturn\r", }; - -CppUnit::Test* XMLMementoTest::Suite() -{ - CppUnit::TestSuite* suite = new CppUnit::TestSuite("XMLMementoTest"); - - CppUnit_addTest(suite, XMLMementoTest, TestPutMemento); - CppUnit_addTest(suite, XMLMementoTest, TestPutAndGetString); - CppUnit_addTest(suite, XMLMementoTest, TestCreateReadRootReaderExceptionCases); - CppUnit_addTest(suite, XMLMementoTest, TestCreateReadRootReader); - CppUnit_addTest(suite, XMLMementoTest, TestCreateWriteRoot); - CppUnit_addTest(suite, XMLMementoTest, TestSpacesInRootAreIllegal); - CppUnit_addTest(suite, XMLMementoTest, TestSpacesInKeysAreIllegal); - CppUnit_addTest(suite, XMLMementoTest, TestCopyChild); - CppUnit_addTest(suite, XMLMementoTest, TestCreateAndGetChild); - CppUnit_addTest(suite, XMLMementoTest, TestGetChildren); - CppUnit_addTest(suite, XMLMementoTest, TestGetID); - CppUnit_addTest(suite, XMLMementoTest, TestPutAndGetFloat); - CppUnit_addTest(suite, XMLMementoTest, TestPutAndGetInteger); - CppUnit_addTest(suite, XMLMementoTest, TestPutAndGetTextData); - CppUnit_addTest(suite, XMLMementoTest, TestLegalKeys); - CppUnit_addTest(suite, XMLMementoTest, TestIllegalKeys); - CppUnit_addTest(suite, XMLMementoTest, TestPutTextDataWithChildren); - CppUnit_addTest(suite, XMLMementoTest, TestMementoWithTextContent); - - return suite; -} - -XMLMementoTest::XMLMementoTest(const std::string& testName) : - TestCase(testName) -{ - -} - -void XMLMementoTest::FillMemento(IMemento::Pointer memento) -{ - memento->PutFloat("floatKey", 0.4f); - memento->PutInteger("integerKey", 324765); - memento->PutString("stringKey", "a string"); - memento->PutTextData("some text data"); - memento->CreateChild("child1"); - memento->CreateChild("child2", "child2id1"); - memento->CreateChild("child2", "child2id2"); -} - -void XMLMementoTest::TestPutAndGet(MementoChecker& mementoChecker) - throw (Poco::IOException, WorkbenchException) -{ - XMLMemento::Pointer mementoToSerialize = XMLMemento::CreateWriteRoot( - "XMLMementoTest"); - - mementoChecker.PrepareAndCheckBeforeSerialization(mementoToSerialize); - - std::stringstream writer; - mementoToSerialize->Save(writer); - writer.flush(); - - XMLMemento::Pointer deserializedMemento = XMLMemento::CreateReadRoot(writer); - - mementoChecker.CheckAfterDeserialization(deserializedMemento); -} - -void XMLMementoTest::CheckMemento(IMemento::Pointer memento, - bool checkForTextData) -{ - double floatVal; - memento->GetFloat("floatKey", floatVal); - assertEqualDelta(0.4, floatVal, 0.0001); - - int intVal; - memento->GetInteger("integerKey", intVal); - assertEqual(324765, intVal); - - std::string strVal; - memento->GetString("stringKey", strVal); - assertEqual("a string", strVal); - - if (checkForTextData) - { - assertEqual("some text data", memento->GetTextData()); - } - - IMemento::Pointer child1 = memento->GetChild("child1"); - assertNotNullPtr(child1.GetPointer()); - IMemento::Pointer child2 = memento->GetChild("child2"); - assertNotNullPtr(child2.GetPointer()); - assertEqual("child2id1", child2->GetID()); - std::vector children(memento->GetChildren("child2")); - assertEqual(2, (long)children.size()); - assertEqual("child2id1", children[0]->GetID()); - assertEqual("child2id2", children[1]->GetID()); -} - -void XMLMementoTest::TestPutMemento() throw (WorkbenchException, - Poco::IOException) -{ - PutMementoChecker checker(this); - TestPutAndGet(checker); -} - -void XMLMementoTest::TestPutAndGetString() throw (Poco::IOException, - WorkbenchException) -{ - const std::string key = "key"; - - for (unsigned int i = 0; i < TEST_STRINGS_LENGTH; ++i) - { - const std::string value; - PutAndGetStringChecker checker(key, TEST_STRINGS[i]); - TestPutAndGet(checker); - } -} - -void XMLMementoTest::TestCreateReadRootReaderExceptionCases() -{ - try - { - std::stringstream ss("Invalid format"); - - XMLMemento::CreateReadRoot(ss); - failmsg("should throw WorkbenchException because of invalid format"); - } catch (WorkbenchException e) - { - // expected - } - try - { - std::stringstream ss(""); - XMLMemento::CreateReadRoot(ss); - failmsg("should throw WorkbenchException because there is no element"); - } catch (WorkbenchException e) - { - // expected - } - try - { - std::ifstream file("__123thisshouldnotexist_238waer"); - XMLMemento::CreateReadRoot(file); - failmsg("should throw WorkbenchException because of IOException"); - } catch (WorkbenchException e) - { - // expected - } -} - -void XMLMementoTest::TestCreateReadRootReader() throw (WorkbenchException) -{ - std::stringstream - ss( - "some text data"); - XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss); - assertEqual("some text data", memento->GetTextData()); -} - -void XMLMementoTest::TestCreateWriteRoot() -{ - std::string rootTypes[] = - { "type", "type.with.dots", "type_with_underscores" }; - for (unsigned int i = 0; i < 3; i++) - { - XMLMemento::Pointer memento = XMLMemento::CreateWriteRoot(rootTypes[i]); - assertNotNullPtr(memento.GetPointer()); - } -} - -void XMLMementoTest::TestSpacesInRootAreIllegal() -{ - try - { - XMLMemento::CreateWriteRoot("with space"); - failmsg("should fail"); - } catch (std::exception& /*e*/) - { - // expected - } -} - -void XMLMementoTest::TestSpacesInKeysAreIllegal() -{ - XMLMemento::Pointer memento = XMLMemento::CreateWriteRoot("foo"); - try - { - memento->CreateChild("with space", "bar"); - failmsg("should fail"); - } catch (std::exception& /*e*/) - { - // expected - } - try - { - memento->PutString("with space", "bar"); - failmsg("should fail"); - } catch (std::exception& /*e*/) - { - // expected - } -} - -void XMLMementoTest::TestCopyChild() throw (WorkbenchException, - Poco::IOException) -{ - CopyChildChecker checker(this); - TestPutAndGet(checker); -} - -void XMLMementoTest::TestCreateAndGetChild() throw (WorkbenchException, - Poco::IOException) -{ - CreateAndGetChildChecker checker; - TestPutAndGet(checker); -} - -void XMLMementoTest::TestGetChildren() throw (WorkbenchException, - Poco::IOException) -{ - GetChildrenChecker checker; - TestPutAndGet(checker); -} - -void XMLMementoTest::TestGetID() throw (WorkbenchException, Poco::IOException) -{ - const std::string type = "type"; - - const std::string ids[] = - { "id", "", "id.with.many.dots", "id_with_underscores", "idwith>greaterthan", "id&with&ersand", "id\"with\"quote", - "id#with#hash" }; - - for (unsigned int i = 0; i < 9; i++) - { - GetIDChecker checker(type, ids[i]); - TestPutAndGet(checker); - } -} - -void XMLMementoTest::TestPutAndGetFloat() throw (WorkbenchException, - Poco::IOException) -{ - const std::string key = "key"; - - const double values[] = - { -3.1415, 1, 0, 4554.45235, std::numeric_limits::max(), - std::numeric_limits::min(), - std::numeric_limits::quiet_NaN(), - std::numeric_limits::infinity() }; - - for (unsigned int i = 0; i < 8; i++) - { - PutAndGetFloatChecker checker(key, values[i]); - TestPutAndGet(checker); - } -} - -void XMLMementoTest::TestPutAndGetInteger() throw (WorkbenchException, - Poco::IOException) -{ - const std::string key = "key"; - - const int values[] = - { 36254, 0, 1, -36254, std::numeric_limits::max(), std::numeric_limits< - int>::min() }; - - for (unsigned int i = 0; i < 6; i++) - { - PutAndGetIntChecker checker(key, values[i]); - TestPutAndGet(checker); - } - -} - -void XMLMementoTest::TestPutAndGetTextData() throw (WorkbenchException, - Poco::IOException) -{ - for (unsigned int i = 0; i < TEST_STRINGS_LENGTH; i++) - { - PutAndGetTextDataChecker checker(TEST_STRINGS[i]); - TestPutAndGet(checker); - } -} - -void XMLMementoTest::TestLegalKeys() throw (WorkbenchException, - Poco::IOException) -{ - const std::string legalKeys[] = - { "value", "value.with.many.dots", "value_with_underscores" }; - - for (unsigned int i = 0; i < 3; i++) - { - LegalKeysChecker checker(legalKeys[i]); - TestPutAndGet(checker); - } - -} - -void XMLMementoTest::TestIllegalKeys() throw () -{ - const std::string illegalKeys[] = - { "", " ", " key", "key ", "key key", "\t", "\tkey", "key\t", "key\tkey", - "\n", "\nkey", "key\n", "key\nkey", "keywith>greaterthan", "key&with&ersand", "key#with#hash", - "key\"with\"quote", "\"" }; - - for (unsigned int i = 0; i < 19; i++) - { - XMLMemento::Pointer memento = XMLMemento::CreateWriteRoot("foo"); - try - { - memento->PutString(illegalKeys[i], "some string"); - failmsg("putString with illegal key should fail"); - } catch (std::exception& /*ex*/) - { - // expected - } - } -} - -void XMLMementoTest::TestPutTextDataWithChildren() throw (WorkbenchException, - Poco::IOException) -{ - const std::string textData = - "\n\tThis is\ntext data\n\t\twith newlines and \ttabs\t\n\t "; - PutTextDataWithChildrenChecker checker(textData); - TestPutAndGet(checker); -} - -void XMLMementoTest::TestMementoWithTextContent() -{ - IMemento::Pointer memento = XMLMemento::CreateWriteRoot("root"); - IMemento::Pointer mementoWithChild = XMLMemento::CreateWriteRoot("root"); - IMemento::Pointer child = mementoWithChild->CreateChild("child"); - child->PutTextData("text"); - memento->PutMemento(mementoWithChild); - IMemento::Pointer copiedChild = memento->GetChild("child"); - assertEqual("text", copiedChild->GetTextData()); -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryXMLMementoTest.h b/Plugins/Testing/org.blueberry.ui.tests/src/api/berryXMLMementoTest.h deleted file mode 100644 index 95e97680c9..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/api/berryXMLMementoTest.h +++ /dev/null @@ -1,129 +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. - -============================================================================*/ - -#ifndef BERRYXMLMEMENTOTEST_H_ -#define BERRYXMLMEMENTOTEST_H_ - -#include -#include - -namespace berry -{ - -/** - * Testing XMLMemento - * - */ -class XMLMementoTest: public TestCase -{ - -private: - - static const std::string TEST_STRINGS[10]; - static const unsigned int TEST_STRINGS_LENGTH; - -public: - - static CppUnit::Test* Suite(); - - XMLMementoTest(const std::string& testName); - - /* - * Class under test for XMLMemento createReadRoot(Reader) - */ - void TestCreateReadRootReaderExceptionCases(); - - void TestCreateReadRootReader() throw (WorkbenchException); - - /* - * Class under test for XMLMemento createReadRoot(Reader, String) - */ - // void testCreateReadRootReaderString() { - // // TODO - I don't know how to test this. The method is not called by - // // anyone as of 2005/04/05. - // } - - void TestCreateWriteRoot(); - - void TestSpacesInRootAreIllegal(); - - void TestSpacesInKeysAreIllegal(); - - void TestCopyChild() throw (WorkbenchException, Poco::IOException); - - /** - * Helper method to fill a memento to be checked later by checkMemento. - * - * @param memento - */ - void FillMemento(IMemento::Pointer memento); - - /** - * Helper method to check if the values set by fillMemento are still there. - * The boolean parameter is needed because in some cases - * (IMememento#putMemento), the text data gets lost. - * - * @param memento - * @param checkForTextData - */ - void CheckMemento(IMemento::Pointer memento, bool checkForTextData); - - void TestCreateAndGetChild() throw (WorkbenchException, Poco::IOException); - - void TestGetChildren() throw (WorkbenchException, Poco::IOException); - - void TestGetID() throw (WorkbenchException, Poco::IOException); - - void TestPutAndGetFloat() throw (WorkbenchException, Poco::IOException); - - void TestPutAndGetInteger() throw (WorkbenchException, Poco::IOException); - - void TestPutMemento() throw (WorkbenchException, Poco::IOException); - - void TestPutAndGetString() throw (Poco::IOException, WorkbenchException); - - void TestPutAndGetTextData() throw (WorkbenchException, Poco::IOException); - - void TestLegalKeys() throw (WorkbenchException, Poco::IOException); - - void TestIllegalKeys() throw (); - - void TestPutTextDataWithChildren() throw (WorkbenchException, - Poco::IOException); - - void TestMementoWithTextContent(); - - struct MementoChecker: public CppUnit::TestCase - { - - MementoChecker() : - CppUnit::TestCase("MementoChecker") - { - } - - virtual void PrepareAndCheckBeforeSerialization( - XMLMemento::Pointer mementoToSerialize) = 0; - - virtual void CheckAfterDeserialization( - XMLMemento::Pointer deserializedMemento) = 0; - }; - -private: - - void TestPutAndGet(MementoChecker& mementoChecker) throw (Poco::IOException, - WorkbenchException); - -}; - -} - -#endif /* BERRYXMLMEMENTOTEST_H_ */ diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/berryPluginActivator.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/berryPluginActivator.cpp deleted file mode 100644 index dceb56dca7..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/berryPluginActivator.cpp +++ /dev/null @@ -1,32 +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 "berryPluginActivator.h" -#include "berryUiTestSuite.h" -#include "api/berryMockViewPart.h" -#include "api/berrySaveableMockViewPart.h" - -namespace berry { - -void org_blueberry_ui_tests_Activator::start(ctkPluginContext* context) -{ - BERRY_REGISTER_EXTENSION_CLASS(UiTestSuite, context) - BERRY_REGISTER_EXTENSION_CLASS(MockViewPart, context) - BERRY_REGISTER_EXTENSION_CLASS(SaveableMockViewPart, context) -} - -void org_blueberry_ui_tests_Activator::stop(ctkPluginContext* context) -{ - Q_UNUSED(context) -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/berryPluginActivator.h b/Plugins/Testing/org.blueberry.ui.tests/src/berryPluginActivator.h deleted file mode 100644 index b5fbf8e676..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/berryPluginActivator.h +++ /dev/null @@ -1,40 +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. - -============================================================================*/ - - -#ifndef BERRYPLUGINACTIVATOR_H -#define BERRYPLUGINACTIVATOR_H - -#include -#include - -namespace berry { - -class org_blueberry_ui_tests_Activator : - public QObject, public ctkPluginActivator -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_blueberry_ui_tests") - Q_INTERFACES(ctkPluginActivator) - -public: - - void start(ctkPluginContext* context); - void stop(ctkPluginContext* context); - -}; - -typedef org_blueberry_ui_tests_Activator PluginActivator; - -} - -#endif // BERRYPLUGINACTIVATOR_H diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/berryUiTestSuite.cpp b/Plugins/Testing/org.blueberry.ui.tests/src/berryUiTestSuite.cpp deleted file mode 100644 index a0c700e43f..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/berryUiTestSuite.cpp +++ /dev/null @@ -1,33 +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 "berryUiTestSuite.h" - -#include "api/berryUiApiTestSuite.h" - -#include - -namespace berry { - -UiTestSuite::UiTestSuite() -: CppUnit::TestSuite("UiTestSuite") -{ - addTest(new UiApiTestSuite()); -} - -UiTestSuite::UiTestSuite(const UiTestSuite& other) -{ - Q_UNUSED(other); - throw std::runtime_error("Copy constructor not implemented"); -} - -} diff --git a/Plugins/Testing/org.blueberry.ui.tests/src/berryUiTestSuite.h b/Plugins/Testing/org.blueberry.ui.tests/src/berryUiTestSuite.h deleted file mode 100644 index 653efb08de..0000000000 --- a/Plugins/Testing/org.blueberry.ui.tests/src/berryUiTestSuite.h +++ /dev/null @@ -1,38 +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. - -============================================================================*/ - - -#ifndef BERRYUITESTSUITE_H_ -#define BERRYUITESTSUITE_H_ - -#include - -#include - -Q_DECLARE_INTERFACE(CppUnit::Test, "CppUnit.Test") - -namespace berry { - -class UiTestSuite : public QObject, public CppUnit::TestSuite -{ - Q_OBJECT - Q_INTERFACES(CppUnit::Test) - -public: - - UiTestSuite(); - UiTestSuite(const UiTestSuite& other); -}; - -} - -#endif /* BERRYUITESTSUITE_H_ */ diff --git a/Plugins/org.blueberry.core.runtime/src/berryPlatform.cpp b/Plugins/org.blueberry.core.runtime/src/berryPlatform.cpp index 3224c85951..a30ccd79f3 100644 --- a/Plugins/org.blueberry.core.runtime/src/berryPlatform.cpp +++ b/Plugins/org.blueberry.core.runtime/src/berryPlatform.cpp @@ -1,250 +1,247 @@ /*============================================================================ 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 "berryPlatform.h" #include #include "internal/berryInternalPlatform.h" #include "internal/berryIRuntimeConstants.h" #include namespace berry { const QString Platform::PI_RUNTIME = IRuntimeConstants::PI_RUNTIME(); const int Platform::OS_FREE_BSD = BERRY_OS_FREE_BSD; const int Platform::OS_AIX = BERRY_OS_AIX; const int Platform::OS_HPUX = BERRY_OS_HPUX; const int Platform::OS_TRU64 = BERRY_OS_TRU64; const int Platform::OS_LINUX = BERRY_OS_LINUX; const int Platform::OS_MAC_OS_X = BERRY_OS_MAC_OS_X; const int Platform::OS_NET_BSD = BERRY_OS_NET_BSD; const int Platform::OS_OPEN_BSD = BERRY_OS_OPEN_BSD; const int Platform::OS_IRIX = BERRY_OS_IRIX; const int Platform::OS_SOLARIS = BERRY_OS_SOLARIS; const int Platform::OS_QNX = BERRY_OS_QNX; const int Platform::OS_VXWORKS = BERRY_OS_VXWORKS; const int Platform::OS_CYGWIN = BERRY_OS_CYGWIN; const int Platform::OS_UNKNOWN_UNIX = BERRY_OS_UNKNOWN_UNIX; const int Platform::OS_WINDOWS_NT = BERRY_OS_WINDOWS_NT; const int Platform::OS_WINDOWS_CE = BERRY_OS_WINDOWS_CE; const int Platform::OS_VMS = BERRY_OS_VMS; const int Platform::ARCH_ALPHA = BERRY_ARCH_ALPHA; const int Platform::ARCH_IA32 = BERRY_ARCH_IA32; const int Platform::ARCH_IA64 = BERRY_ARCH_IA64; const int Platform::ARCH_MIPS = BERRY_ARCH_MIPS; const int Platform::ARCH_HPPA = BERRY_ARCH_HPPA; const int Platform::ARCH_PPC = BERRY_ARCH_PPC; const int Platform::ARCH_POWER = BERRY_ARCH_POWER; const int Platform::ARCH_SPARC = BERRY_ARCH_SPARC; const int Platform::ARCH_AMD64 = BERRY_ARCH_AMD64; const int Platform::ARCH_ARM = BERRY_ARCH_ARM; const QString Platform::PROP_QTPLUGIN_PATH = "BlueBerry.qtplugin_path"; const QString Platform::PROP_NEWINSTANCE = "BlueBerry.newInstance"; const QString Platform::PROP_APPLICATION = "BlueBerry.application"; const QString Platform::PROP_PLUGIN_DIRS = "BlueBerry.plugin_dirs"; const QString Platform::PROP_FORCE_PLUGIN_INSTALL = "BlueBerry.forcePlugins"; -const QString Platform::PROP_TESTPLUGIN = "BlueBerry.testplugin"; -const QString Platform::PROP_TESTAPPLICATION = "BlueBerry.testapplication"; - const QString Platform::PROP_IGNOREAPP = "BlueBerry.ignoreApp"; const QString Platform::PROP_XARGS = "xargs"; QDir Platform::GetConfigurationPath() { ctkLocation* location = GetConfigurationLocation(); if (location) { return location->getUrl().toLocalFile(); } return QDir(); } ctkLocation* Platform::GetConfigurationLocation() { return InternalPlatform::GetInstance()->GetConfigurationLocation(); } IAdapterManager* Platform::GetAdapterManager() { return InternalPlatform::GetInstance()->GetAdapterManager(); } IExtensionRegistry *Platform::GetExtensionRegistry() { return InternalPlatform::GetInstance()->GetExtensionRegistry(); } IPreferencesService *Platform::GetPreferencesService() { return InternalPlatform::GetInstance()->GetPreferencesService(); } //PlatformEvents& Platform::GetEvents() //{ // return InternalPlatform::GetInstance()->GetEvents(); //} QDir Platform::GetInstallPath() { ctkLocation* location = GetInstallLocation(); if (location) { return location->getUrl().toLocalFile(); } return QDir(); } ctkLocation* Platform::GetInstallLocation() { return InternalPlatform::GetInstance()->GetInstallLocation(); } QDir Platform::GetInstancePath() { ctkLocation* location = GetInstanceLocation(); if (location) { return location->getUrl().toLocalFile(); } return QDir(); } ctkLocation* Platform::GetInstanceLocation() { return InternalPlatform::GetInstance()->GetInstanceLocation(); } int Platform::GetOS() { return BERRY_OS; } int Platform::GetOSArch() { return BERRY_ARCH; } bool Platform::IsUnix() { #ifdef BERRY_OS_FAMILY_UNIX return true; #else return false; #endif } bool Platform::IsWindows() { #ifdef BERRY_OS_FAMILY_WINDOWS return true; #else return false; #endif } bool Platform::IsBSD() { #ifdef BERRY_OS_FAMILY_BSD return true; #else return false; #endif } bool Platform::IsLinux() { #ifdef BERRY_OS_FAMILY_LINUX return true; #else return false; #endif } bool Platform::IsVMS() { #ifdef BERRY_OS_FAMILY_VMS return true; #else return false; #endif } bool Platform::GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool /*create*/) { statePath = GetStateLocation(plugin); return true; } QDir Platform::GetStateLocation(const QSharedPointer& plugin) { return InternalPlatform::GetInstance()->GetStateLocation(plugin); } QDir Platform::GetUserPath() { ctkLocation* location = GetUserLocation(); if (location) { return location->getUrl().toLocalFile(); } return QDir(); } ctkLocation* Platform::GetUserLocation() { return InternalPlatform::GetInstance()->GetUserLocation(); } bool Platform::IsRunning() { return InternalPlatform::GetInstance()->IsRunning(); } QStringList Platform::GetApplicationArgs() { return InternalPlatform::GetInstance()->GetApplicationArgs(); } QSharedPointer Platform::GetPlugin(const QString& symbolicName) { return InternalPlatform::GetInstance()->GetPlugin(symbolicName); } QList > Platform::GetPlugins(const QString& symbolicName, const QString& version) { return InternalPlatform::GetInstance()->GetPlugins(symbolicName, version); } QVariant berry::Platform::GetDebugOption(const QString& option) { return InternalPlatform::GetInstance()->GetOption(option); } IProduct::Pointer berry::Platform::GetProduct() { return InternalPlatform::GetInstance()->GetProduct(); } } diff --git a/Plugins/org.blueberry.core.runtime/src/berryPlatform.h b/Plugins/org.blueberry.core.runtime/src/berryPlatform.h index f072f5b8ed..548002f7e4 100644 --- a/Plugins/org.blueberry.core.runtime/src/berryPlatform.h +++ b/Plugins/org.blueberry.core.runtime/src/berryPlatform.h @@ -1,495 +1,492 @@ /*============================================================================ 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 BERRY_Platform_INCLUDED #define BERRY_Platform_INCLUDED // // Platform Identification // #define BERRY_OS_FREE_BSD 0x0001 #define BERRY_OS_AIX 0x0002 #define BERRY_OS_HPUX 0x0003 #define BERRY_OS_TRU64 0x0004 #define BERRY_OS_LINUX 0x0005 #define BERRY_OS_MAC_OS_X 0x0006 #define BERRY_OS_NET_BSD 0x0007 #define BERRY_OS_OPEN_BSD 0x0008 #define BERRY_OS_IRIX 0x0009 #define BERRY_OS_SOLARIS 0x000a #define BERRY_OS_QNX 0x000b #define BERRY_OS_VXWORKS 0x000c #define BERRY_OS_CYGWIN 0x000d #define BERRY_OS_UNKNOWN_UNIX 0x00ff #define BERRY_OS_WINDOWS_NT 0x1001 #define BERRY_OS_WINDOWS_CE 0x1011 #define BERRY_OS_VMS 0x2001 #if defined(__FreeBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_FREE_BSD #elif defined(_AIX) || defined(__TOS_AIX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_AIX #elif defined(hpux) || defined(_hpux) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_HPUX #elif defined(__digital__) || defined(__osf__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_TRU64 #elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__TOS_LINUX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_LINUX #elif defined(__APPLE__) || defined(__TOS_MACOS__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_MAC_OS_X #elif defined(__NetBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_NET_BSD #elif defined(__OpenBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_OPEN_BSD #elif defined(sgi) || defined(__sgi) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_IRIX #elif defined(sun) || defined(__sun) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_SOLARIS #elif defined(__QNX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_QNX #elif defined(unix) || defined(__unix) || defined(__unix__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_UNKNOWN_UNIX #elif defined(_WIN32_WCE) #define BERRY_OS_FAMILY_WINDOWS 1 #define BERRY_OS BERRY_OS_WINDOWS_CE #elif defined(_WIN32) || defined(_WIN64) #define BERRY_OS_FAMILY_WINDOWS 1 #define BERRY_OS BERRY_OS_WINDOWS_NT #elif defined(__CYGWIN__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_CYGWIN #elif defined(__VMS) #define BERRY_OS_FAMILY_VMS 1 #define BERRY_OS BERRY_OS_VMS #endif // // Hardware Architecture and Byte Order // #define BERRY_ARCH_ALPHA 0x01 #define BERRY_ARCH_IA32 0x02 #define BERRY_ARCH_IA64 0x03 #define BERRY_ARCH_MIPS 0x04 #define BERRY_ARCH_HPPA 0x05 #define BERRY_ARCH_PPC 0x06 #define BERRY_ARCH_POWER 0x07 #define BERRY_ARCH_SPARC 0x08 #define BERRY_ARCH_AMD64 0x09 #define BERRY_ARCH_ARM 0x0a #if defined(__ALPHA) || defined(__alpha) || defined(__alpha__) || defined(_M_ALPHA) #define BERRY_ARCH BERRY_ARCH_ALPHA #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) #define BERRY_ARCH BERRY_ARCH_IA32 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(_IA64) || defined(__IA64__) || defined(__ia64__) || defined(__ia64) || defined(_M_IA64) #define BERRY_ARCH BERRY_ARCH_IA64 #if defined(hpux) || defined(_hpux) #define BERRY_ARCH_BIG_ENDIAN 1 #else #define BERRY_ARCH_LITTLE_ENDIAN 1 #endif #elif defined(__x86_64__) #define BERRY_ARCH BERRY_ARCH_AMD64 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(_M_X64) #define BERRY_ARCH BERRY_ARCH_AMD64 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(_M_MRX000) #define BERRY_ARCH BERRY_ARCH_MIPS #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__hppa) || defined(__hppa__) #define BERRY_ARCH BERRY_ARCH_HPPA #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__PPC) || defined(__POWERPC__) || defined(__powerpc) || defined(__PPC__) || \ defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC) || defined(_M_PPC) #define BERRY_ARCH BERRY_ARCH_PPC #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(_POWER) || defined(_ARCH_PWR) || defined(_ARCH_PWR2) || defined(_ARCH_PWR3) || \ defined(_ARCH_PWR4) || defined(__THW_RS6000) #define BERRY_ARCH BERRY_ARCH_POWER #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__sparc__) || defined(__sparc) || defined(sparc) #define BERRY_ARCH BERRY_ARCH_SPARC #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__arm__) || defined(__arm) || defined(ARM) || defined(_ARM_) || defined(__ARM__) || defined(_M_ARM) #define BERRY_ARCH BERRY_ARCH_ARM #if defined(__ARMEB__) #define BERRY_ARCH_BIG_ENDIAN 1 #else #define BERRY_ARCH_LITTLE_ENDIAN 1 #endif #endif #include #include #include #include struct ctkLocation; class ctkPlugin; namespace Poco { class Path; } namespace berry { struct IAdapterManager; struct IBundle; struct IExtensionPointService; struct IExtensionRegistry; struct IPreferencesService; struct IProduct; /** * The central class of the BlueBerry Platform Runtime. This class cannot * be instantiated or subclassed by clients; all functionality is provided * by static methods. Features include: *

    *
  • the platform registry of installed plug-ins
  • *
  • the platform adapter manager
  • *
  • the platform log
  • *
*

* Most users don't have to worry about Platform's lifecycle. However, if your * code can call methods of this class when Platform is not running, it becomes * necessary to check {@link #IsRunning()} before making the call. A runtime * exception might be thrown or incorrect result might be returned if a method * from this class is called while Platform is not running. *

*/ class org_blueberry_core_runtime_EXPORT Platform { public: static const QString PI_RUNTIME; static const int OS_FREE_BSD; static const int OS_AIX; static const int OS_HPUX; static const int OS_TRU64; static const int OS_LINUX; static const int OS_MAC_OS_X; static const int OS_NET_BSD; static const int OS_OPEN_BSD; static const int OS_IRIX; static const int OS_SOLARIS; static const int OS_QNX; static const int OS_VXWORKS; static const int OS_CYGWIN; static const int OS_UNKNOWN_UNIX; static const int OS_WINDOWS_NT; static const int OS_WINDOWS_CE; static const int OS_VMS; static const int ARCH_ALPHA; static const int ARCH_IA32; static const int ARCH_IA64; static const int ARCH_MIPS; static const int ARCH_HPPA; static const int ARCH_PPC; static const int ARCH_POWER; static const int ARCH_SPARC; static const int ARCH_AMD64; static const int ARCH_ARM; static const QString PROP_QTPLUGIN_PATH; static const QString PROP_NEWINSTANCE; static const QString PROP_PLUGIN_DIRS; static const QString PROP_FORCE_PLUGIN_INSTALL; static const QString PROP_APPLICATION; static const QString PROP_IGNOREAPP; - static const QString PROP_TESTPLUGIN; - static const QString PROP_TESTAPPLICATION; - static const QString PROP_XARGS; /** * Returns the adapter manager used for extending * IAdaptable objects. * * @return the adapter manager for this platform * @see IAdapterManager */ static IAdapterManager* GetAdapterManager(); /** * Returns the extension registry for this platform. * May return null if the registry has not been created yet. * * @return existing extension registry or null * @see IExtensionRegistry */ static IExtensionRegistry* GetExtensionRegistry(); /** * Return the interface into the preference mechanism. The returned * object can be used for such operations as searching for preference * values across multiple scopes and preference import/export. *

* Clients are also able to acquire the IPreferencesService service via * CTK mechanisms and use it for preference functions. *

* * @return an object to interface into the preference mechanism */ static IPreferencesService* GetPreferencesService(); /** * Returns the product which was selected when running this BlueBerry instance * or null if none * @return the current product or null if none */ static SmartPointer GetProduct(); /** * Returns the identified option. A null QString * is returned if no such option is found. Options are specified * in the general form <plug-in id>/<option-path>. * For example, org.blueberry.core.runtime/debug *

* Clients are also able to acquire the {@link DebugOptions} service * and query it for debug options. *

* @param option the name of the option to lookup * @return the value of the requested debug option or QString::null */ static QVariant GetDebugOption(const QString& option); /** * Returns the path of the configuration information * used to run this instance of the BlueBerry platform. * The configuration area typically * contains the list of plug-ins available for use, various settings * (those shared across different instances of the same configuration) * and any other such data needed by plug-ins. * An empty path is returned if the platform is running without a configuration location. * * @return the location of the platform's configuration data area * @deprecatedSince{2015_05} Use GetConfigurationLocation() instead. */ QT_DEPRECATED static QDir GetConfigurationPath(); /** * Returns the location of the configuration information * used to run this instance of BlueBerry. The configuration area typically * contains the list of plug-ins available for use, various settings * (those shared across different instances of the same configuration) * and any other such data needed by plug-ins. * null is returned if the platform is running without a configuration location. *

* This method is equivalent to acquiring the org.commontk.service.datalocation.Location * service with the property "type" equal to ctkLocation::CONFIGURATION_FILTER. *

* @return the location of the platform's configuration data area or null if none * @see ctkLocation::CONFIGURATION_FILTER */ static ctkLocation* GetConfigurationLocation(); /** * Returns the path of the base installation for the running platform * * @return the location of the platform's installation area or null if none * @deprecatedSince{2015_05} Use GetInstallLocation() instead. */ QT_DEPRECATED static QDir GetInstallPath(); /** * Returns the location of the base installation for the running platform * null is returned if the platform is running without a configuration location. *

* This method is equivalent to acquiring the org.commontk.service.datalocation.Location * service with the property "type" equal to ctkLocation::INSTALL_FILTER. *

* @return the location of the platform's installation area or null if none * @see ctkLocation::INSTALL_FILTER */ static ctkLocation* GetInstallLocation(); /** * Returns the path of the platform's working directory (also known as the instance data area). * An empty path is returned if the platform is running without an instance location. * * @return the location of the platform's instance data area or null if none * @deprecatedSince{2015_05} Use GetInstanceLocation() instead. */ QT_DEPRECATED static QDir GetInstancePath(); /** * Returns the location of the platform's working directory (also known as the instance data area). * null is returned if the platform is running without an instance location. *

* This method is equivalent to acquiring the org.commontk.service.datalocation.Location * service with the property "type" equal to ctkLocation::INSTANCE_FILTER. *

* @return the location of the platform's instance data area or null if none * @see ctkLocation::INSTANCE_FILTER */ static ctkLocation* GetInstanceLocation(); /** * Returns the path in the local file system of the * plug-in state area for the given plug-in. * If the plug-in state area did not exist prior to this call, * it is created. *

* The plug-in state area is a file directory within the * platform's metadata area where a plug-in is free to create files. * The content and structure of this area is defined by the plug-in, * and the particular plug-in is solely responsible for any files * it puts there. It is recommended for plug-in preference settings and * other configuration parameters. *

* * @param plugin the plug-in whose state location is returned * @return a local file system path * TODO Investigate the usage of a service factory * @deprecatedSince{2015_05} Use GetStateLocation instead. */ QT_DEPRECATED static bool GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool create = true); /** * Returns the location in the local file system of the * plug-in state area for the given plug-in. * If the plug-in state area did not exist prior to this call, * it is created. *

* The plug-in state area is a file directory within the * platform's metadata area where a plug-in is free to create files. * The content and structure of this area is defined by the plug-in, * and the particular plug-in is solely responsible for any files * it puts there. It is recommended for plug-in preference settings and * other configuration parameters. *

* * @param plugin the plugin whose state location if returned * @return a local file system path * @throws ctkIllegalStateException if no instance location was specified * @throws RuntimeException if the plug-in state area could not be created. */ static QDir GetStateLocation(const QSharedPointer& plugin); /** * Returns the path of the platform's user data area. The user data area is a location on the system * which is specific to the system's current user. By default it is located relative to the * location given by the System property "user.home". * An empty path is returned if the platform is running without an user location. * * @return the location of the platform's user data area or null if none * @deprecatedSince{2015_05} Use GetUserLocation() instead. */ QT_DEPRECATED static QDir GetUserPath(); /** * Returns the location of the platform's user data area. The user data area is a location on the system * which is specific to the system's current user. By default it is located relative to the * location given by the system property "user.home". * null is returned if the platform is running without an user location. *

* This method is equivalent to acquiring the org.commontk.service.datalocation.Location * service with the property "type" equal to ctkLocation::USER_FILTER. *

* @return the location of the platform's user data area or null if none * @see ctkLocation::USER_FILTER */ static ctkLocation* GetUserLocation(); static int GetOS(); static int GetOSArch(); static bool IsUnix(); static bool IsWindows(); static bool IsBSD(); static bool IsLinux(); static bool IsVMS(); static bool IsRunning(); /** * Returns the applications command line arguments which * have not been consumed by the platform. */ static QStringList GetApplicationArgs(); /** * Returns the resolved plug-in with the specified symbolic name that has the * highest version. If no resolved plug-ins are installed that have the * specified symbolic name then null is returned. *

* Note that clients may want to filter * the results based on the state of the plug-ins. *

* @param symbolicName the symbolic name of the plug-in to be returned. * @return the plug-in that has the specified symbolic name with the * highest version, or null if no plug-in is found. */ static QSharedPointer GetPlugin(const QString& symbolicName); /** * Returns all plug-ins with the specified symbolic name. If no resolved plug-ins * with the specified symbolic name can be found, an empty list is returned. * If the version argument is not null then only the plug-ins that have * the specified symbolic name and a version greater than or equal to the * specified version are returned. The returned plug-ins are ordered in * descending plug-in version order. *

* Note that clients may want to filter * the results based on the state of the plug-ins. *

* @param symbolicName the symbolic name of the plug-ins that are to be returned. * @param version the version that the returned plug-in versions must match, * or QString() if no version matching is to be done. * @return the list of plug-ins with the specified name that match the * specified version and match rule, or null if no plug-ins are found. */ static QList > GetPlugins(const QString& symbolicName, const QString& version = QString()); private: Platform(); }; } // namespace #endif // BERRY_Platform_INCLUDED diff --git a/Plugins/org.blueberry.test/CMakeLists.txt b/Plugins/org.blueberry.test/CMakeLists.txt deleted file mode 100644 index a1fb3b2ae3..0000000000 --- a/Plugins/org.blueberry.test/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -project(org_blueberry_test) - -include_directories(${CppUnit_INCLUDE_DIRS}) - -mitk_create_plugin( - EXPORT_DIRECTIVE BERRY_TEST_EXPORT - EXPORTED_INCLUDE_SUFFIXES src src/harness - NO_INSTALL - ) - -target_link_libraries(${PROJECT_NAME} PRIVATE ${CppUnit_LIBRARIES}) diff --git a/Plugins/org.blueberry.test/documentation/doxygen/modules.dox b/Plugins/org.blueberry.test/documentation/doxygen/modules.dox deleted file mode 100644 index f15b97ba2a..0000000000 --- a/Plugins/org.blueberry.test/documentation/doxygen/modules.dox +++ /dev/null @@ -1,16 +0,0 @@ -/** - \defgroup org_blueberry_test org.blueberry.test - \ingroup BlueBerryPlugins - - \brief Testing infrastructure for running unit tests defined in BlueBerry plug-ins. - -*/ - -/** - \defgroup org_blueberry_test_internal Internal - \ingroup org_blueberry_test - - \brief This subcategory includes the internal classes of the org.blueberry.test plugin. Other - plugins must not rely on these classes. They contain implementation details and their interface - may change at any time. We mean it. -*/ diff --git a/Plugins/org.blueberry.test/files.cmake b/Plugins/org.blueberry.test/files.cmake deleted file mode 100644 index 2021d90c53..0000000000 --- a/Plugins/org.blueberry.test/files.cmake +++ /dev/null @@ -1,35 +0,0 @@ -set(MOC_H_FILES - src/internal/berryPluginActivator.h - - src/berryCoreTestApplication.h -) - -set(CACHED_RESOURCE_FILES - plugin.xml -) - -set(SRC_CPP_FILES - berryCoreTestApplication.cpp - berryBlueBerryTestDriver.cpp - - harness/berryTestCase.cpp - - util/berryCallHistory.cpp -) - -set(INTERNAL_CPP_FILES - berryPluginActivator.cpp - berryTestDescriptor.cpp - berryTestRegistry.cpp -) - -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.blueberry.test/manifest_headers.cmake b/Plugins/org.blueberry.test/manifest_headers.cmake deleted file mode 100644 index 6b5e458b86..0000000000 --- a/Plugins/org.blueberry.test/manifest_headers.cmake +++ /dev/null @@ -1,6 +0,0 @@ -set(Plugin-Name "BlueBerry Automated Testing") -set(Plugin-Version "0.9") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin "org.blueberry.core.runtime") - diff --git a/Plugins/org.blueberry.test/plugin.xml b/Plugins/org.blueberry.test/plugin.xml deleted file mode 100644 index df091b2154..0000000000 --- a/Plugins/org.blueberry.test/plugin.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/Plugins/org.blueberry.test/schema/tests.exsd b/Plugins/org.blueberry.test/schema/tests.exsd deleted file mode 100644 index cb2ca7893e..0000000000 --- a/Plugins/org.blueberry.test/schema/tests.exsd +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - - - - The test extension point allows plugins to contribute unit tests to the BlueBerry Platform. The tests should be written with the help of the Poco CppUnit library. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Following is an example of a test declaration. -<p> - <pre> - <extension id="SampleTestSuite" point="org.blueberry.tests"> - <test id="SampleTest" class="xyz::SampleTest"/> - </extension> - </pre> -</p> - - - - - - - - - Test classes must be a subclass of <code>CppUnit::Test</code>. - - - - - - diff --git a/Plugins/org.blueberry.test/src/berryBlueBerryTestDriver.cpp b/Plugins/org.blueberry.test/src/berryBlueBerryTestDriver.cpp deleted file mode 100644 index c4ec16d8d3..0000000000 --- a/Plugins/org.blueberry.test/src/berryBlueBerryTestDriver.cpp +++ /dev/null @@ -1,91 +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 "berryBlueBerryTestDriver.h" - -#include "internal/berryTestRegistry.h" - -#include "cppunit/TestRunner.h" -#include "cppunit/TestResult.h" -#include "cppunit/TestResultCollector.h" - -namespace berry -{ - -BlueBerryTestDriver::BlueBerryTestDriver( - const QList& descriptors, - bool uitests, - const QString& testName, - bool wait) - : descriptors(descriptors) - , uitests(uitests) - , testName(testName) - , wait(wait) -{ - -} - -int BlueBerryTestDriver::Run() -{ - CppUnit::TestRunner runner; - - unsigned int testCounter = 0; - foreach (const ITestDescriptor::Pointer& descr, descriptors) - { - if (descr->IsUITest() == uitests) - { - CppUnit::Test* test = descr->CreateTest(); - runner.addTest(test); - ++testCounter; - } - } - - if (testCounter == 0) - { - std::cout << "No " << (uitests ? "UI " : "") << "tests registered." - << std::endl; - return 0; - } - - /* - std::vector args; - args.push_back("BlueBerryTestDriver"); - if (testName.empty()) - args.push_back("-all"); - else - args.push_back(testName); - if (wait) - args.push_back("-wait"); - - return runner.run(args) ? 0 : 1; - */ - - CppUnit::TestResult controller; - - CppUnit::TestResultCollector result; - controller.addListener(&result); - - runner.run(controller); - return result.wasSuccessful() ? 0 : 1; -} - -int BlueBerryTestDriver::Run(const QString& pluginId, bool uitests) -{ - TestRegistry testRegistry; - const QList& tests = testRegistry.GetTestsForId( - pluginId); - - BlueBerryTestDriver driver(tests, uitests); - return driver.Run(); -} - -} diff --git a/Plugins/org.blueberry.test/src/berryBlueBerryTestDriver.h b/Plugins/org.blueberry.test/src/berryBlueBerryTestDriver.h deleted file mode 100644 index 361abb6050..0000000000 --- a/Plugins/org.blueberry.test/src/berryBlueBerryTestDriver.h +++ /dev/null @@ -1,49 +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. - -============================================================================*/ - - -#ifndef BERRYBLUEBERRYTESTDRIVER_H_ -#define BERRYBLUEBERRYTESTDRIVER_H_ - -#include - -#include "berryITestDescriptor.h" - -namespace berry -{ - -/** - * A TestDriver for CppUnit that supports running tests inside BlueBerry as well as - * running standalone. - * Example call: TODO - */ -class BERRY_TEST_EXPORT BlueBerryTestDriver -{ -public: - - BlueBerryTestDriver(const QList& descriptors, bool uitests = false, const QString& testName="", bool wait=false); - - int Run(); - - static int Run(const QString& pluginId, bool uitests = false); - -protected: - - QList descriptors; - bool uitests; - QString testName; - bool wait; -}; - -} - -#endif /* BERRYBLUEBERRYTESTDRIVER_H_ */ diff --git a/Plugins/org.blueberry.test/src/berryCoreTestApplication.cpp b/Plugins/org.blueberry.test/src/berryCoreTestApplication.cpp deleted file mode 100644 index fe3e265689..0000000000 --- a/Plugins/org.blueberry.test/src/berryCoreTestApplication.cpp +++ /dev/null @@ -1,51 +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 "berryCoreTestApplication.h" - -#include -#include - -#include "berryBlueBerryTestDriver.h" - -namespace berry { - -CoreTestApplication::CoreTestApplication() -{ - -} - -CoreTestApplication::CoreTestApplication(const CoreTestApplication& other) - : QObject() -{ - Q_UNUSED(other) -} - -int CoreTestApplication::Start() { - std::string testPlugin; - try { - testPlugin = Platform::GetConfiguration().getString(Platform::ARG_TESTPLUGIN.toStdString()); - } - catch (const Poco::NotFoundException& /*e*/) - { - BERRY_ERROR << "You must specify a test plug-in id via " << Platform::ARG_TESTPLUGIN << "="; - return 1; - } - - return BlueBerryTestDriver::Run(QString::fromStdString(testPlugin)); -} - -void CoreTestApplication::Stop() { - -} - -} diff --git a/Plugins/org.blueberry.test/src/berryCoreTestApplication.h b/Plugins/org.blueberry.test/src/berryCoreTestApplication.h deleted file mode 100644 index b2d9cf799a..0000000000 --- a/Plugins/org.blueberry.test/src/berryCoreTestApplication.h +++ /dev/null @@ -1,39 +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. - -============================================================================*/ - - -#ifndef BERRYCORETESTAPPLICATION_H_ -#define BERRYCORETESTAPPLICATION_H_ - -#include - -#include - -namespace berry { - -class CoreTestApplication : public QObject, public IApplication -{ - Q_OBJECT - Q_INTERFACES(berry::IApplication) - -public: - - CoreTestApplication(); - CoreTestApplication(const CoreTestApplication& other); - - int Start(); - void Stop(); -}; - -} - -#endif /* BERRYCORETESTAPPLICATION_H_ */ diff --git a/Plugins/org.blueberry.test/src/berryITestDescriptor.h b/Plugins/org.blueberry.test/src/berryITestDescriptor.h deleted file mode 100644 index f012c9185b..0000000000 --- a/Plugins/org.blueberry.test/src/berryITestDescriptor.h +++ /dev/null @@ -1,38 +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. - -============================================================================*/ - - -#ifndef BERRYITESTDESCRIPTOR_H_ -#define BERRYITESTDESCRIPTOR_H_ - -#include -#include - -#include - -namespace berry { - -struct ITestDescriptor : public Object -{ - berryObjectMacro(berry::ITestDescriptor); - - virtual CppUnit::Test* CreateTest() = 0; - virtual QString GetId() const = 0; - virtual QString GetContributor() const = 0; - virtual QString GetDescription() const = 0; - - virtual bool IsUITest() const = 0; -}; - -} - -#endif /* BERRYITESTDESCRIPTOR_H_ */ diff --git a/Plugins/org.blueberry.test/src/harness/berryTestCase.cpp b/Plugins/org.blueberry.test/src/harness/berryTestCase.cpp deleted file mode 100644 index df3b67d605..0000000000 --- a/Plugins/org.blueberry.test/src/harness/berryTestCase.cpp +++ /dev/null @@ -1,73 +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 "berryTestCase.h" - -#include -#include - -#ifdef BLUEBERRY_DEBUG_SMARTPOINTER -#include -#endif - -#include - -#include - -berry::TestCase::TestCase(const QString& testName) : - CppUnit::TestCase(testName.toStdString()), m_LeakDetails(false), - m_IgnoreLeakage(false) -{ - -} - -void berry::TestCase::LeakDetailsOn() -{ - m_LeakDetails = true; -} - -void berry::TestCase::IgnoreLeakingObjects() -{ - BERRY_WARN << "Ignoring Leaking Objects!!"; - m_IgnoreLeakage = true; -} - -void berry::TestCase::DoSetUp() -{ - -} - -void berry::TestCase::DoTearDown() -{ - -} - -void berry::TestCase::setUp() -{ - CppUnit::TestCase::setUp(); -#ifdef BLUEBERRY_DEBUG_SMARTPOINTER - DebugUtil::ResetObjectSummary(); -#endif - DoSetUp(); -} - -void berry::TestCase::tearDown() -{ - CppUnit::TestCase::tearDown(); - DoTearDown(); -#ifdef BLUEBERRY_DEBUG_SMARTPOINTER - assert(m_IgnoreLeakage || !DebugUtil::PrintObjectSummary(m_LeakDetails)); -#endif - - m_LeakDetails = false; -} - diff --git a/Plugins/org.blueberry.test/src/harness/berryTestCase.h b/Plugins/org.blueberry.test/src/harness/berryTestCase.h deleted file mode 100644 index 8d0d31ed9e..0000000000 --- a/Plugins/org.blueberry.test/src/harness/berryTestCase.h +++ /dev/null @@ -1,80 +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. - -============================================================================*/ - - -#ifndef BERRYTESTCASE_H_ -#define BERRYTESTCASE_H_ - -#include - -#include - -namespace berry { - -class BERRY_TEST_EXPORT TestCase : public CppUnit::TestCase -{ - -public: - - TestCase(const QString& testName); - - /** - * Sets up the fixture, for example, open a network connection. - * This method is called before a test is executed. - * The default implementation does nothing. - * Subclasses may extend. - */ - virtual void DoSetUp(); - - /** - * Tears down the fixture, for example, close a network connection. - * This method is called after a test is executed. - * The default implementation closes all test windows, processing events both before - * and after doing so. - * Subclasses may extend. - */ - virtual void DoTearDown(); - - /** - * Clients should overwrite DoSetUp() instead of this method. - */ - void setUp(); - - /** - * Clients should overwrite DoSetUp() instead of this method. - */ - void tearDown(); - -protected: - - /** - * Call this method in your unit test to enable detailed - * output about leaking berry::Object instances. - */ - void LeakDetailsOn(); - - /** - * Call this method to ignore leaking objects and to continue - * with the unit tests. - */ - void IgnoreLeakingObjects(); - -private: - - bool m_LeakDetails; - bool m_IgnoreLeakage; - -}; - -} - -#endif /* BERRYTESTCASE_H_ */ diff --git a/Plugins/org.blueberry.test/src/internal/berryPluginActivator.cpp b/Plugins/org.blueberry.test/src/internal/berryPluginActivator.cpp deleted file mode 100644 index a68f8131c3..0000000000 --- a/Plugins/org.blueberry.test/src/internal/berryPluginActivator.cpp +++ /dev/null @@ -1,34 +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 "berryPluginActivator.h" -#include "berryMacros.h" -#include "berryCoreTestApplication.h" - -namespace berry { - -org_blueberry_test_Activator::org_blueberry_test_Activator() -{ - -} - -void org_blueberry_test_Activator::start(ctkPluginContext* context) -{ - BERRY_REGISTER_EXTENSION_CLASS(CoreTestApplication, context) -} - -void org_blueberry_test_Activator::stop(ctkPluginContext* context) -{ - Q_UNUSED(context) -} - -} diff --git a/Plugins/org.blueberry.test/src/internal/berryPluginActivator.h b/Plugins/org.blueberry.test/src/internal/berryPluginActivator.h deleted file mode 100644 index fe80c1efeb..0000000000 --- a/Plugins/org.blueberry.test/src/internal/berryPluginActivator.h +++ /dev/null @@ -1,39 +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. - -============================================================================*/ - - -#ifndef BERRYPLUGINACTIVATOR_H -#define BERRYPLUGINACTIVATOR_H - -#include - -namespace berry { - -class org_blueberry_test_Activator : - public QObject, public ctkPluginActivator -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_blueberry_test") - Q_INTERFACES(ctkPluginActivator) - -public: - org_blueberry_test_Activator(); - - void start(ctkPluginContext* context); - void stop(ctkPluginContext* context); -}; - -typedef org_blueberry_test_Activator PluginActivator; - -} - -#endif // BERRYPLUGINACTIVATOR_H diff --git a/Plugins/org.blueberry.test/src/internal/berryTestDescriptor.cpp b/Plugins/org.blueberry.test/src/internal/berryTestDescriptor.cpp deleted file mode 100644 index f405c7c5c8..0000000000 --- a/Plugins/org.blueberry.test/src/internal/berryTestDescriptor.cpp +++ /dev/null @@ -1,64 +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 "berryTestDescriptor.h" -#include "berryTestRegistry.h" -#include "berryIContributor.h" - -#include - -Q_DECLARE_INTERFACE(CppUnit::Test, "CppUnit.Test") - -namespace berry -{ - -TestDescriptor::TestDescriptor(IConfigurationElement::Pointer elem) : - configElem(elem) -{ - -} - -CppUnit::Test* TestDescriptor::CreateTest() -{ - CppUnit::Test* test = configElem->CreateExecutableExtension ( - TestRegistry::ATT_CLASS); - if (test == 0) - { - // Try legacy BlueBerry manifests instead - test = configElem->CreateExecutableExtension ( - TestRegistry::ATT_CLASS); - } - return test; -} - -QString TestDescriptor::GetId() const -{ - return configElem->GetAttribute(TestRegistry::ATT_ID); -} - -QString TestDescriptor::GetContributor() const -{ - return configElem->GetContributor()->GetName(); -} - -QString TestDescriptor::GetDescription() const -{ - return configElem->GetAttribute(TestRegistry::ATT_DESCRIPTION); -} - -bool TestDescriptor::IsUITest() const -{ - QString isUi = configElem->GetAttribute(TestRegistry::ATT_UITEST); - return isUi.compare("true", Qt::CaseInsensitive); -} - -} diff --git a/Plugins/org.blueberry.test/src/internal/berryTestDescriptor.h b/Plugins/org.blueberry.test/src/internal/berryTestDescriptor.h deleted file mode 100644 index 32fa3ca44f..0000000000 --- a/Plugins/org.blueberry.test/src/internal/berryTestDescriptor.h +++ /dev/null @@ -1,45 +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. - -============================================================================*/ - - -#ifndef BERRYTESTDESCRIPTOR_H_ -#define BERRYTESTDESCRIPTOR_H_ - -#include "berryITestDescriptor.h" - -#include - -namespace berry { - -class TestDescriptor : public ITestDescriptor -{ -public: - - berryObjectMacro(TestDescriptor); - - TestDescriptor(IConfigurationElement::Pointer elem); - - CppUnit::Test* CreateTest(); - QString GetId() const; - QString GetContributor() const; - QString GetDescription() const; - - bool IsUITest() const; - -private: - - IConfigurationElement::Pointer configElem; -}; - -} - -#endif /* BERRYTESTDESCRIPTOR_H_ */ diff --git a/Plugins/org.blueberry.test/src/internal/berryTestRegistry.cpp b/Plugins/org.blueberry.test/src/internal/berryTestRegistry.cpp deleted file mode 100644 index f785778a7c..0000000000 --- a/Plugins/org.blueberry.test/src/internal/berryTestRegistry.cpp +++ /dev/null @@ -1,56 +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 "berryTestRegistry.h" -#include "berryTestDescriptor.h" - -#include -#include - -namespace berry -{ - -const QString TestRegistry::TAG_TEST = "test"; -const QString TestRegistry::ATT_ID = "id"; -const QString TestRegistry::ATT_CLASS = "class"; -const QString TestRegistry::ATT_DESCRIPTION = "description"; -const QString TestRegistry::ATT_UITEST = "uitest"; - -TestRegistry::TestRegistry() -{ - QList elements( - Platform::GetExtensionRegistry()->GetConfigurationElementsFor( - "org.blueberry.tests")); - - foreach (const IConfigurationElement::Pointer& configElem, elements) - { - if (configElem->GetName() == TAG_TEST) - { - this->ReadTest(configElem); - } - } -} - -const QList& -TestRegistry::GetTestsForId(const QString& pluginid) -{ - return mapIdToTests[pluginid]; -} - -void TestRegistry::ReadTest(const IConfigurationElement::Pointer& testElem) -{ - ITestDescriptor::Pointer descriptor(new TestDescriptor(testElem)); - Q_ASSERT(!descriptor->GetId().isEmpty()); - mapIdToTests[descriptor->GetContributor()].push_back(descriptor); -} - -} diff --git a/Plugins/org.blueberry.test/src/internal/berryTestRegistry.h b/Plugins/org.blueberry.test/src/internal/berryTestRegistry.h deleted file mode 100644 index 95bccfae0a..0000000000 --- a/Plugins/org.blueberry.test/src/internal/berryTestRegistry.h +++ /dev/null @@ -1,48 +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. - -============================================================================*/ - - -#ifndef BERRYTESTREGISTRY_H_ -#define BERRYTESTREGISTRY_H_ - -#include - -#include "berryITestDescriptor.h" - -namespace berry { - -class TestRegistry -{ -public: - - static const QString TAG_TEST; // = "test" - static const QString ATT_ID; // = "id" - static const QString ATT_CLASS; // = "class" - static const QString ATT_DESCRIPTION; // = "description" - static const QString ATT_UITEST; // = "uitest" - - TestRegistry(); - - const QList& GetTestsForId(const QString& pluginid); - -protected: - - void ReadTest(const IConfigurationElement::Pointer& testElem); - -private: - - QHash > mapIdToTests; -}; - -} - -#endif /* BERRYTESTREGISTRY_H_ */ diff --git a/Plugins/org.blueberry.test/src/util/berryCallHistory.cpp b/Plugins/org.blueberry.test/src/util/berryCallHistory.cpp deleted file mode 100644 index e7a101ddbd..0000000000 --- a/Plugins/org.blueberry.test/src/util/berryCallHistory.cpp +++ /dev/null @@ -1,95 +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 "berryCallHistory.h" - -#include - -namespace berry -{ - -CallHistory::CallHistory(/*Object target*/) -{ - // classType = target.getClass(); -} - -void CallHistory::Add(const std::string& methodName) -{ - TestMethodName(methodName); - methodList.push_back(methodName); -} - -void CallHistory::Clear() -{ - methodList.clear(); -} - -bool CallHistory::VerifyOrder(const std::vector& testNames) const -throw(Poco::InvalidArgumentException) -{ - std::size_t testIndex = 0; - std::size_t testLength = testNames.size(); - if (testLength == 0) - return true; - for (std::size_t nX = 0; nX < methodList.size(); nX++) - { - const std::string& methodName = methodList[nX]; - const std::string& testName = testNames[testIndex]; - TestMethodName(testName); - if (testName == methodName) - ++testIndex; - if (testIndex >= testLength) - return true; - } - return false; -} - -bool CallHistory::Contains(const std::string& methodName) const -{ - TestMethodName(methodName); - return std::find(methodList.begin(), methodList.end(), methodName) != methodList.end(); -} - -bool CallHistory::Contains(const std::vector& methodNames) const -{ - for (std::size_t i = 0; i < methodNames.size(); i++) - { - TestMethodName(methodNames[i]); - if (std::find(methodList.begin(), methodList.end(), methodNames[i]) == methodList.end()) - return false; - } - return true; -} - -bool CallHistory::IsEmpty() const -{ - return methodList.empty(); -} - -void CallHistory::PrintTo(std::ostream& out) const -{ - for (std::size_t i = 0; i < methodList.size(); i++) - out << methodList[i] << std::endl; -} - -void CallHistory::TestMethodName(const std::string&) const -throw(Poco::InvalidArgumentException) -{ -// Method[] methods = classType.getMethods(); -// for (int i = 0; i < methods.length; i++) -// if (methods[i].getName().equals(methodName)) -// return; -// throw new IllegalArgumentException("Target class (" + classType.getName() -// + ") does not contain method: " + methodName); -} - -} diff --git a/Plugins/org.blueberry.test/src/util/berryCallHistory.h b/Plugins/org.blueberry.test/src/util/berryCallHistory.h deleted file mode 100644 index f954ba1cbe..0000000000 --- a/Plugins/org.blueberry.test/src/util/berryCallHistory.h +++ /dev/null @@ -1,131 +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. - -============================================================================*/ - - -#ifndef BERRYCALLHISTORY_H_ -#define BERRYCALLHISTORY_H_ - -#include - -#include -#include - -#include - -#include -#include - -namespace berry { - -/** - * CallHistory is used to record the invocation - * of methods within a target object. This is useful during - * lifecycle testing for an object. - *

- * To use CallHistory .. - *

    - *
  1. Create a CallHistory in the target or pass one in.
  2. - *
  3. Invoke some test scenario.
  4. - *
  5. If a method is called on the target record the invocation - * in the call history
  6. - *
  7. Verify the call history after the test scenario is - * complete.
  8. - *
- *

- * Each CallHistory has a target which is used to - * verify the method names passed to the history. If an invalid - * name is passed an IllegalArgumentException will - * be thrown. - *

- */ -class BERRY_TEST_EXPORT CallHistory : public Object { - -private: - - std::vector methodList; - - // Class classType; - -public: - - berryObjectMacro(CallHistory); - - /** - * Creates a new call history for an object. - * - * @param target the call history target. - */ - CallHistory(/*Object target*/); - - /** - * Adds a method name to the call history. - * - * @param methodName the name of a method - */ - void Add(const std::string& methodName); - - /** - * Clears the call history. - */ - void Clear(); - - /** - * Returns whether a list of methods have been called in - * order. - * - * @param testNames an array of the method names in the order they are expected - * @return true if the methods were called in order - */ - bool VerifyOrder(const std::vector& testNames) const - throw(Poco::InvalidArgumentException); - - /** - * Returns whether a method has been called. - * - * @param methodName a method name - * @return true if the method was called - */ - bool Contains(const std::string& methodName) const ; - - /** - * Returns whether a list of methods were called. - * - * @param methodNames a list of methods - * @return true if the methods were called - */ - bool Contains(const std::vector& methodNames) const; - - /** - * Returns whether the list of methods called is empty. - * - * @return true iff the list of methods is empty - */ - bool IsEmpty() const; - - /** - * Prints the call history to the console. - */ - void PrintTo(std::ostream& out) const; - -private: - - /** - * Throws an exception if the method name is invalid - * for the given target class. - */ - void TestMethodName(const std::string&) const throw(Poco::InvalidArgumentException); - -}; - -} - -#endif /* BERRYCALLHISTORY_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/actions/berryAbstractContributionFactory.h b/Plugins/org.blueberry.ui.qt/src/actions/berryAbstractContributionFactory.h index cdff48a34d..c22feb26b7 100644 --- a/Plugins/org.blueberry.ui.qt/src/actions/berryAbstractContributionFactory.h +++ b/Plugins/org.blueberry.ui.qt/src/actions/berryAbstractContributionFactory.h @@ -1,135 +1,135 @@ /*============================================================================ 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 BERRYABSTRACTCONTRIBUTIONFACTORY_H_ #define BERRYABSTRACTCONTRIBUTIONFACTORY_H_ #include #include namespace berry { struct IServiceLocator; struct IContributionRoot; /** * ContributionFactories are used by the IMenuService to populate - * ContributionManagers. In {@link #createContributionItems(IServiceLocator, IContributionRoot)} + * ContributionManagers. In CreateContributionItems() * you fill in the additions List with {@link IContributionItem} to be inserted at this * factory's location. For example: *

* *

  * AbstractContributionFactory contributions = new AbstractContributionFactory(
  *    "menu:org.eclipse.ui.tests.api.MenuTestHarness?after=additions") {
- *  public void createContributionItems(IMenuService menuService, List additions) {
+ *  public void CreateContributionItems(IMenuService menuService, List additions) {
  *    CommandContributionItem item = new CommandContributionItem(
  *        "org.eclipse.ui.tests.menus.helloWorld",
  *        "org.eclipse.ui.tests.commands.enabledHelloWorld", null, null,
  *        "Say Hello", null);
  *    additions.add(item);
  *    item = new CommandContributionItem(
  *        "org.eclipse.ui.tests.menus.refresh",
  *        "org.eclipse.ui.tests.commands.refreshView", null, null,
  *        "Refresh", null);
  *    menuService.registerVisibleWhen(item, new MyActiveContextExpression(
  *        "org.eclipse.ui.tests.myview.context"));
  *    additions.add(item);
  *  }
  *
  *  public void releaseContributionItems(IMenuService menuService, List items) {
  *    // we have nothing to do
  *  }
  * };
  * IMenuService service = (IMenuService) PlatformUI.getWorkbench().getService(
  *    IMenuService.class);
  * service.addContributionFactory(contributions);
  * 
* *

*

* Only the abstract methods may be implemented. *

* * @see IMenuService * @see MenuManager * @see ToolBarManager */ class BERRY_UI_QT AbstractContributionFactory: public Object { private: QString location; QString namespaze; public: berryObjectMacro(berry::AbstractContributionFactory); /** * The contribution factories must be instantiated with their location, * which which specifies the contributions insertion location. * * @param location * the addition location in Menu API URI format. It must not be * null. * @param namespace * the namespace for this contribution. May be null. * @see #getNamespace() */ AbstractContributionFactory(const QString& location, const QString& namespaze); /** * Return the location as a String. * * @return the location - never null. */ QString GetLocation() const; /** * This factory should create the IContributionItems that it wants to * contribute, and add them to the additions list. The menu service will * call this method at the appropriate time. It should always return new * instances of its contributions in the additions list. *

* This method is not meant to be called by clients. It will be called by * the menu service at the appropriate time. *

* * @param serviceLocator * a service locator that may be used in the construction of * items created by this factory * @param additions * A {@link IContributionRoot} supplied by the framework. It will * never be null. * @see org.eclipse.ui.menus.CommandContributionItem * @see org.eclipse.jface.action.MenuManager */ virtual void CreateContributionItems(IServiceLocator* serviceLocator, const SmartPointer& additions) = 0; /** * Return the namespace for this cache. This corresponds to the plug-in that * is contributing this factory. * * @return the namespace the namespace of this factory */ QString GetNamespace() const; }; } #endif /* BERRYABSTRACTCONTRIBUTIONFACTORY_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h b/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h index 6680aed849..d3f8a174c4 100644 --- a/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h +++ b/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h @@ -1,212 +1,211 @@ /*============================================================================ 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 BERRYCOMMANDCONTRIBUTIONITEM_H_ #define BERRYCOMMANDCONTRIBUTIONITEM_H_ #include "berryContributionItem.h" #include #include namespace berry { struct IMenuService; struct ICommandService; struct ICommandListener; struct IHandlerService; struct IHandler; struct IElementReference; struct IServiceLocator; class CommandEvent; class ParameterizedCommand; class CommandContributionItemParameter; class UIElement; /** - * A contribution item which delegates to a command. It can be used in {@link - * AbstractContributionFactory#CreateContributionItems(IServiceLocator, - * IContributionRoot)}. + * A contribution item which delegates to a command. It can be used in + * berry::AbstractContributionFactory::CreateContributionItems(). *

* It currently supports placement in menus and toolbars. *

*

* This class may be instantiated; it is not intended to be subclassed. *

*/ class BERRY_UI_QT CommandContributionItem : public QObject, public ContributionItem { Q_OBJECT public: /** * Mode bit: Show text on tool items or buttons, even if an image is * present. If this mode bit is not set, text is only shown on tool items if * there is no image present. */ static Modes modes; private: //LocalResourceManager localResourceManager; //Listener menuItemListener; QAction* action; IMenuService* menuService; ICommandService* commandService; IHandlerService* handlerService; //IBindingService bindingService; SmartPointer command; QIcon icon; QString label; QString tooltip; QChar mnemonic; // This is a workaround until key bindings are fully implemented QKeySequence shortcut; SmartPointer elementRef; bool checkedState; Style style; QScopedPointer commandListener; QString dropDownMenuOverride; //IWorkbenchHelpSystem workbenchHelpSystem; QString helpContextId; Modes mode; /** * This is true when the menu contribution's visibleWhen * checkEnabled attribute is true. */ bool visibleEnabled; // items contributed QString contributedLabel; QIcon contributedIcon; SmartPointer serviceLocator; public: /** * Create a CommandContributionItem to place in a ContributionManager. * * @param contributionParameters * parameters necessary to render this contribution item. */ CommandContributionItem( const SmartPointer& contributionParameters); ~CommandContributionItem() override; using ContributionItem::Fill; void Fill(QMenu* parent, QAction* before) override; void Fill(QToolBar* parent, QAction* before) override; void Update() override; void Update(const QString& id) override; bool IsEnabled() const override; bool IsVisible() const override; void UpdateCommandPropertiesInUI(const SmartPointer& commandEvent); private: void SetImages(IServiceLocator* locator, const QString &iconStyle); ICommandListener *GetCommandListener(); void UpdateMenuItem(); void UpdateToolItem(); void UpdateCommandProperties(const SmartPointer commandEvent); bool ShouldRestoreAppearance(const SmartPointer& handler); SmartPointer GetCommand() const; void CreateCommand(const QString& commandId, const QHash& parameters); QString GetToolTipText(const QString& text) const; QString UpdateMnemonic(const QString& s); // void disposeOldImages() { // if (localResourceManager != null) { // localResourceManager.dispose(); // localResourceManager = null; // } // } //SmartPointer GetItemListener(); /** * Determines if the selection was on the dropdown affordance and, if so, * opens the drop down menu (populated using the same id as this item... * * @param event * The SWT.Selection event to be tested * * @return true iff a drop down menu was opened */ //TODO Tool item drop down menu contributions //bool OpenDropDownMenu(SmartPointer event); void SetIcon(const QIcon& icon); void UpdateIcons(); void SetText(const QString& text); void SetChecked(bool checked); void SetToolTip(const QString& text); private slots: void HandleActionDestroyed(); void HandleWidgetSelection(); }; } #endif /* BERRYCOMMANDCONTRIBUTIONITEM_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.h b/Plugins/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.h index d71f7b8f7c..4ce6da062c 100644 --- a/Plugins/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.h +++ b/Plugins/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.h @@ -1,248 +1,248 @@ /*============================================================================ 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 BERRYACTIONBARADVISOR_H_ #define BERRYACTIONBARADVISOR_H_ #include #include class QAction; namespace berry { struct IMenuManager; struct IToolBarManager; struct IStatusLineManager; struct IActionBarConfigurer; struct IMemento; struct IWorkbenchWindow; /** * Public base class for configuring the action bars of a workbench window. *

* An application should declare a subclass of ActionBarAdvisor * and override methods to configure a window's action bars to suit the needs of the * particular application. *

*

* The following advisor methods are called at strategic points in the * workbench's lifecycle (all occur within the dynamic scope of the call - * to {@link PlatformUI#createAndRunWorkbench PlatformUI.createAndRunWorkbench}): + * to berry::PlatformUI::CreateAndRunWorkbench()): *

    - *
  • fillActionBars - called after WorkbenchWindowAdvisor.preWindowOpen + *
  • FillActionBars() - called after berry::WorkbenchWindowAdvisor::PreWindowOpen() * to configure a window's action bars
  • *
*

* - * @see WorkbenchWindowAdvisor#createActionBarAdvisor(IActionBarConfigurer) + * @see berry::WorkbenchWindowAdvisor::CreateActionBarAdvisor() */ class BERRY_UI_QT ActionBarAdvisor : public Object { public: berryObjectMacro(berry::ActionBarAdvisor); enum FillType { /** - * Bit flag for {@link #fillActionBars fillActionBars} indicating that the + * Bit flag for FillActionBars() indicating that the * operation is not filling the action bars of an actual workbench window, * but rather a proxy (used for perspective customization). */ FILL_PROXY = 0x01, /** - * Bit flag for {@link #fillActionBars fillActionBars} indicating that the + * Bit flag for FillActionBars() indicating that the * operation is supposed to fill (or describe) the workbench window's menu * bar. */ FILL_MENU_BAR = 0x02, /** - * Bit flag for {@link #fillActionBars fillActionBars} indicating that the + * Bit flag for FillActionBars() indicating that the * operation is supposed to fill (or describe) the workbench window's cool * bar. */ FILL_TOOL_BAR = 0x04, /** - * Bit flag for {@link #fillActionBars fillActionBars} indicating that the + * Bit flag for FillActionBars() indicating that the * operation is supposed to fill (or describe) the workbench window's status * line. */ FILL_STATUS_LINE = 0x08 }; Q_DECLARE_FLAGS(FillFlags, FillType) public: ~ActionBarAdvisor() override; /** * Creates a new action bar advisor to configure a workbench * window's action bars via the given action bar configurer. * * @param configurer the action bar configurer */ ActionBarAdvisor(const SmartPointer& configurer); /** * Configures the action bars using the given action bar configurer. * Under normal circumstances, flags does not include - * FILL_PROXY, meaning this is a request to fill the action + * #FILL_PROXY, meaning this is a request to fill the action * bars of the corresponding workbench window; the * remaining flags indicate which combination of - * the menu bar (FILL_MENU_BAR), - * the tool bar (FILL_TOOL_BAR), - * and the status line (FILL_STATUS_LINE) are to be filled. + * the menu bar (#FILL_MENU_BAR), + * the tool bar (#FILL_TOOL_BAR), + * and the status line (#FILL_STATUS_LINE) are to be filled. *

- * If flags does include FILL_PROXY, then this + * If flags does include #FILL_PROXY, then this * is a request to describe the actions bars of the given workbench window * (which will already have been filled); * again, the remaining flags indicate which combination of the menu bar, * the tool bar, and the status line are to be described. * The actions included in the proxy action bars can be the same instances * as in the actual window's action bars. *

*

- * This method is called just after {@link WorkbenchWindowAdvisor#PreWindowOpen()}. + * This method is called just after berry::WorkbenchWindowAdvisor::PreWindowOpen(). * Clients must not call this method directly (although super calls are okay). - * The default implementation calls MakeActions if - * FILL_PROXY is specified, then calls FillMenuBar, - * FillToolBar, and FillStatusLine + * The default implementation calls MakeActions() if + * #FILL_PROXY is specified, then calls FillMenuBar(), + * FillToolBar(), and FillStatusLine() * if the corresponding flags are specified. *

*

* Subclasses may override, but it is recommended that they override the * methods mentioned above instead. *

* * @param flags bit mask composed from the constants - * {@link #FILL_MENU_BAR FILL_MENU_BAR}, - * {@link #FILL_TOOL_BAR FILL_TOOL_BAR}, - * {@link #FILL_STATUS_LINE FILL_STATUS_LINE}, - * and {@link #FILL_PROXY FILL_PROXY} + * #FILL_MENU_BAR, + * #FILL_TOOL_BAR, + * #FILL_STATUS_LINE, + * and #FILL_PROXY */ virtual void FillActionBars(FillFlags flags); /** * Saves arbitrary application-specific state information * for this action bar advisor. *

* The default implementation simply returns an OK status. * Subclasses may extend or override. *

* * @param memento the memento in which to save the advisor's state * @return a status object indicating whether the save was successful */ virtual bool SaveState(SmartPointer memento); /** * Restores arbitrary application-specific state information * for this action bar advisor. *

* The default implementation simply returns an OK status. * Subclasses may extend or override. *

* * @param memento the memento from which to restore the advisor's state * @return a status object indicating whether the restore was successful */ public: virtual bool RestoreState(SmartPointer memento); using Object::Register; protected: /** * Returns the action bar configurer. * * @return the action bar configurer */ virtual SmartPointer GetActionBarConfigurer() const; /** * Instantiates the actions used in the fill methods. - * Use {@link #Register(QAction*)} to add it to the list of actions to + * Use Register() to add it to the list of actions to * be disposed when the window is closed. * * @param window the window containing the action bars */ virtual void MakeActions(IWorkbenchWindow* window); /** * Adds the given action to the list of actions to be disposed when the window is closed. * * @param action the action to register, this cannot be null * @param id the unique action id */ virtual void Register(QAction* action, const QString& id); /** * Returns the action with the given id, or null if not found. * * @param id the action id * @return the action with the given id, or null if not found */ virtual QAction* GetAction(const QString& id) const; /** * Fills the menu bar with the main menus for the window. *

* The default implementation does nothing. * Subclasses may override. *

* * @param menuBar the menu manager for the menu bar */ virtual void FillMenuBar(IMenuManager* menuBar); /** * Fills the tool bar with the main toolbars for the window. *

* The default implementation does nothing. * Subclasses may override. *

* * @param toolBar the bar manager */ virtual void FillToolBar(IToolBarManager* toolBar); /** * Fills the status line with the main status line contributions * for the window. *

* The default implementation does nothing. * Subclasses may override. *

* * @param statusLine the status line manager */ virtual void FillStatusLine(IStatusLineManager* statusLine); private: SmartPointer actionBarConfigurer; QHash actions; }; } Q_DECLARE_OPERATORS_FOR_FLAGS(berry::ActionBarAdvisor::FillFlags) #endif /*BERRYACTIONBARADVISOR_H_*/ diff --git a/Plugins/org.blueberry.ui.qt/src/berryIContributionRoot.h b/Plugins/org.blueberry.ui.qt/src/berryIContributionRoot.h index c0834293a7..5b3074227d 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryIContributionRoot.h +++ b/Plugins/org.blueberry.ui.qt/src/berryIContributionRoot.h @@ -1,67 +1,67 @@ /*============================================================================ 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 BERRYICONTRIBUTIONROOT_H #define BERRYICONTRIBUTIONROOT_H #include namespace berry { struct IContributionItem; class Expression; /** * Instances of this interface represent a position in the contribution * hierarchy into which {@link AbstractContributionFactory} instances may insert * elements. Instances of this interface are provided by the platform and this * interface should NOT be implemented by clients. */ struct IContributionRoot : public Object { berryObjectMacro(berry::IContributionRoot); /** * Adds a given contribution item with provided visibility expression and * kill-switch filtering as a direct child of this container. This should be * called for all top-level elements created in - * {@link AbstractContributionFactory#createContributionItems(org.eclipse.ui.services.IServiceLocator, IContributionRoot)} + * berry::AbstractContributionFactory::CreateContributionItems(). * * @param item * the item to add * @param visibleWhen * the visibility expression. May be null. */ virtual void AddContributionItem(const SmartPointer& item, const SmartPointer& visibleWhen) = 0; /** * Registers visibilty for arbitrary {@link IContributionItem} instances * that are NOT direct children of this container. Ie: children of a * {@link IContributionManager} that has been previously registered with a - * call to {{@link #AddContributionItem(IContributionItem, Expression)}. + * call to AddContributionItem(). * * @param item * the item for which to register a visibility clause * @param visibleWhen * the visibility expression. May be null in which * case this method is a no-op. */ virtual void RegisterVisibilityForChild(const SmartPointer& item, const SmartPointer& visibleWhen) = 0; }; } #endif // BERRYICONTRIBUTIONROOT_H diff --git a/Plugins/org.blueberry.ui.qt/src/berryPlatformUI.h b/Plugins/org.blueberry.ui.qt/src/berryPlatformUI.h index 4d19c9355d..ab60ec62dd 100644 --- a/Plugins/org.blueberry.ui.qt/src/berryPlatformUI.h +++ b/Plugins/org.blueberry.ui.qt/src/berryPlatformUI.h @@ -1,170 +1,170 @@ /*============================================================================ 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 BERRYPLATFORMUI_H_ #define BERRYPLATFORMUI_H_ #include #include "berryDisplay.h" #include "application/berryWorkbenchAdvisor.h" #include "testing/berryTestableObject.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * The central class for access to the BlueBerry Platform User Interface. * This class cannot be instantiated; all functionality is provided by * static methods. * * Features provided: *
    *
  • creation of the workbench.
  • *
  • access to the workbench.
  • *
*

* * @see IWorkbench */ class BERRY_UI_QT PlatformUI { public: static QString PLUGIN_ID(); static const QString XP_WORKBENCH; static const QString XP_VIEWS; /** * Return code (value 0) indicating that the workbench terminated normally. * - * @see #CreateAndRunWorkbench + * @see CreateAndRunWorkbench() * @since 3.0 */ static const int RETURN_OK; /** * Return code (value 1) indicating that the workbench was terminated with * a call to IWorkbench.restart. * - * @see #CreateAndRunWorkbench + * @see CreateAndRunWorkbench() * @see IWorkbench#Restart * @since 3.0 */ static const int RETURN_RESTART; /** * Return code (value 2) indicating that the workbench failed to start. * - * @see #CreateAndRunWorkbench + * @see CreateAndRunWorkbench() * @see IWorkbench#Restart * @since 3.0 */ static const int RETURN_UNSTARTABLE; /** * Return code (value 3) indicating that the workbench was terminated with * a call to IWorkbenchConfigurer#emergencyClose. * - * @see #CreateAndRunWorkbench + * @see CreateAndRunWorkbench() * @since 3.0 */ static const int RETURN_EMERGENCY_CLOSE; /** * Creates the workbench and associates it with the given display and workbench * advisor, and runs the workbench UI. This entails processing and dispatching * events until the workbench is closed or restarted. *

* This method is intended to be called by the main class (the "application"). * Fails if the workbench UI has already been created. *

*

* Use {@link #createDisplay createDisplay} to create the display to pass in. *

*

* Note that this method is intended to be called by the application * (org.blueberry.core.boot.IPlatformRunnable). It must be * called exactly once, and early on before anyone else asks * getWorkbench() for the workbench. *

* * @param display the display to be used for all UI interactions with the workbench * @param advisor the application-specific advisor that configures and * specializes the workbench * @return return code {@link #RETURN_OK RETURN_OK} for normal exit; * {@link #RETURN_RESTART RETURN_RESTART} if the workbench was terminated * with a call to {@link IWorkbench#restart IWorkbench.restart}; * {@link #RETURN_UNSTARTABLE RETURN_UNSTARTABLE} if the workbench could * not be started; * {@link #RETURN_EMERGENCY_CLOSE RETURN_EMERGENCY_CLOSE} if the UI quit * because of an emergency; other values reserved for future use */ static int CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor); /** * Creates the Display to be used by the workbench. * It is the caller's responsibility to dispose the resulting Display, * not the workbench's. * * @return the display */ static Display* CreateDisplay(); /** * Returns the workbench. Fails if the workbench has not been created yet. * * @return the workbench. A raw pointer is returned because you normally * should not hold a smart pointer to it (and possibly create reference * cycles) */ static IWorkbench* GetWorkbench(); /** - * Returns whether {@link #createAndRunWorkbench createAndRunWorkbench} has + * Returns whether CreateAndRunWorkbench() has * been called to create the workbench, and the workbench has yet to * terminate. *

* Note that this method may return true while the workbench * is still being initialized, so it may not be safe to call workbench API * methods even if this method returns true. See bug 49316 for details. *

* * @return true if the workbench has been created and is * still running, and false if the workbench has not * yet been created or has completed * @since 3.0 */ static bool IsWorkbenchRunning(); /** * Returns the testable object facade, for use by the test harness. *

* IMPORTANT: This method is only for use by the test harness. * Applications and regular plug-ins should not call this method. *

* * @return the testable object facade * @since 3.0 */ static TestableObject::Pointer GetTestableObject(); private: PlatformUI(); }; } #endif /*BERRYPLATFORMUI_H_*/ diff --git a/Plugins/org.blueberry.ui.qt/src/handlers/berryIHandlerActivation.h b/Plugins/org.blueberry.ui.qt/src/handlers/berryIHandlerActivation.h index d9579d2f46..ee99ce3b1f 100755 --- a/Plugins/org.blueberry.ui.qt/src/handlers/berryIHandlerActivation.h +++ b/Plugins/org.blueberry.ui.qt/src/handlers/berryIHandlerActivation.h @@ -1,100 +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. ============================================================================*/ #ifndef BERRYIHANDLERACTIVATION_H_ #define BERRYIHANDLERACTIVATION_H_ #include "internal/berryIEvaluationResultCache.h" #include namespace berry { struct IHandler; struct IHandlerService; /** *

* A token representing the activation of a handler. This token can later be * used to cancel that activation. Without this token, then handler will only * become inactive if the component in which the handler was activated is * destroyed. *

*

* This interface is not intended to be implemented or extended by clients. *

* * @see org.eclipse.ui.ISources * @see org.eclipse.ui.ISourceProvider */ struct BERRY_UI_QT IHandlerActivation : public virtual IEvaluationResultCache { berryObjectMacro(berry::IHandlerActivation); ~IHandlerActivation() override; /** * The depth at which the root exists. */ static const int ROOT_DEPTH; // = 1; /** * Clears the cached computation of the isActive method, if * any. This method is only intended for internal use. It provides a * mechanism by which ISourceProvider events can invalidate * state on a IHandlerActivation instance. * - * @deprecated Use {@link IEvaluationResultCache#clearResult()} instead. + * @deprecated Use berry::IEvaluationResultCache::clearResult() instead. */ virtual void ClearActive() = 0; /** * Returns the identifier of the command whose handler is being activated. * * @return The command identifier; never null. */ virtual QString GetCommandId() const = 0; /** * Returns the depth at which this activation was created within the * services hierarchy. The root of the hierarchy is at a depth of * 1. This is used as the final tie-breaker in the event * that no other method can be used to determine a winner. * * @return The depth at which the handler was inserted into the services * hierarchy; should be a positive integer. */ virtual int GetDepth() const = 0; /** * Returns the handler that should be activated. * * @return The handler; may be null. */ virtual SmartPointer GetHandler() const = 0; /** * Returns the handler service from which this activation was requested. * This is used to ensure that an activation can only be retracted from the * same service which issued it. * * @return The handler service; never null. */ virtual IHandlerService* GetHandlerService() const = 0; }; } #endif /* BERRYIHANDLERACTIVATION_H_ */ diff --git a/Plugins/org.blueberry.uitest/CMakeLists.txt b/Plugins/org.blueberry.uitest/CMakeLists.txt deleted file mode 100644 index 7f828c370c..0000000000 --- a/Plugins/org.blueberry.uitest/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -project(org_blueberry_uitest) - -include_directories(${CppUnit_INCLUDE_DIRS}) - -mitk_create_plugin( - EXPORT_DIRECTIVE BERRY_UITEST_EXPORT - EXPORTED_INCLUDE_SUFFIXES src src/harness src/util - NO_INSTALL -) - -target_link_libraries(${PROJECT_NAME} PRIVATE ${CppUnit_LIBRARIES}) diff --git a/Plugins/org.blueberry.uitest/documentation/doxygen/modules.dox b/Plugins/org.blueberry.uitest/documentation/doxygen/modules.dox deleted file mode 100644 index 95c905fe9d..0000000000 --- a/Plugins/org.blueberry.uitest/documentation/doxygen/modules.dox +++ /dev/null @@ -1,16 +0,0 @@ -/** - \defgroup org_blueberry_uitest org.blueberry.uitest - \ingroup BlueBerryPlugins - - \brief Testing infrastructure for executing unit tests which require a running workbench. - -*/ - -/** - \defgroup org_blueberry_uitest_internal Internal - \ingroup org_blueberry_uitest - - \brief This subcategory includes the internal classes of the org.blueberry.uitest plugin. Other - plugins must not rely on these classes. They contain implementation details and their interface - may change at any time. We mean it. -*/ diff --git a/Plugins/org.blueberry.uitest/files.cmake b/Plugins/org.blueberry.uitest/files.cmake deleted file mode 100644 index 412fa2378b..0000000000 --- a/Plugins/org.blueberry.uitest/files.cmake +++ /dev/null @@ -1,35 +0,0 @@ -set(MOC_H_FILES - src/internal/berryPluginActivator.h - src/util/berryEmptyPerspective.h - - src/berryUITestApplication.h -) - -set(CACHED_RESOURCE_FILES - plugin.xml -) - -set(SRC_CPP_FILES - berryUITestApplication.cpp - - harness/berryUITestCase.cpp - - util/berryEmptyPerspective.cpp -) - -set(INTERNAL_CPP_FILES - berryPluginActivator.cpp - berryUITestWorkbenchAdvisor.cpp - berryUITestWorkbenchWindowAdvisor.cpp -) - -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.blueberry.uitest/manifest_headers.cmake b/Plugins/org.blueberry.uitest/manifest_headers.cmake deleted file mode 100644 index 01f620b32f..0000000000 --- a/Plugins/org.blueberry.uitest/manifest_headers.cmake +++ /dev/null @@ -1,6 +0,0 @@ -set(Plugin-Name "BlueBerry Automated UI Testing") -set(Plugin-Version "0.9") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.blueberry.test org.blueberry.ui.qt) - diff --git a/Plugins/org.blueberry.uitest/plugin.xml b/Plugins/org.blueberry.uitest/plugin.xml deleted file mode 100644 index b67f1583a8..0000000000 --- a/Plugins/org.blueberry.uitest/plugin.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/Plugins/org.blueberry.uitest/src/berryUITestApplication.cpp b/Plugins/org.blueberry.uitest/src/berryUITestApplication.cpp deleted file mode 100644 index f083a5ea8b..0000000000 --- a/Plugins/org.blueberry.uitest/src/berryUITestApplication.cpp +++ /dev/null @@ -1,191 +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 "berryUITestApplication.h" - -#include -#include -#include -#include -#include - -#include "internal/berryUITestWorkbenchAdvisor.h" - -namespace berry -{ - -class WorkbenchCloseRunnable: public Poco::Runnable -{ -public: - WorkbenchCloseRunnable(IWorkbench* workbench) : - workbench(workbench) - { - } - - void run() - { - workbench->Close(); - } - -private: - IWorkbench* workbench; -}; - -UITestApplication::TestRunnable::TestRunnable(UITestApplication* app, - const QString& testPlugin) : - app(app), testPlugin(testPlugin) -{ -} - -void UITestApplication::TestRunnable::run() -{ - try - { - app->testDriverResult = BlueBerryTestDriver::Run(testPlugin, true); - } - catch (const ctkException& e) - { - qWarning() << e.printStackTrace(); - } - catch (const std::exception& e) - { - qWarning() << e.what(); - } -} - -UITestApplication::UITestApplication() -{ - -} - -int UITestApplication::Start() -{ - // Get the plug-in to test - try - { - testPlugin = QString::fromStdString(Platform::GetConfiguration().getString( - Platform::ARG_TESTPLUGIN.toStdString())); - } catch (const Poco::NotFoundException& /*e*/) - { - BERRY_ERROR << "You must specify a test plug-in id via " - << Platform::ARG_TESTPLUGIN << "="; - return 1; - } - - // Get the application to test - IApplication* application = GetApplication(); - poco_assert(application); - int result = RunApplication(application); - - if (IApplication::EXIT_OK != result) - { - std::cerr << "UITestRunner: Unexpected result from running application " << application << ": " << result << std::endl; - } - return testDriverResult; -} - -void UITestApplication::Stop() -{ - IWorkbench* workbench = PlatformUI::GetWorkbench(); - if (!workbench) - return; - Display* display = workbench->GetDisplay(); - WorkbenchCloseRunnable runnable(workbench); - display->SyncExec(&runnable); -} - -void UITestApplication::RunTests() -{ - TestRunnable runnable(this, testPlugin); - testableObject->TestingStarting(); - testableObject->RunTest(&runnable); - testableObject->TestingFinished(); -} - -IApplication* UITestApplication::GetApplication() -{ - - IExtension::Pointer extension; - /*Platform::GetExtensionPointService()->GetExtension( - Starter::XP_APPLICATIONS, GetApplicationToRun());*/ - - QList extensions( - Platform::GetExtensionRegistry()->GetConfigurationElementsFor(Starter::XP_APPLICATIONS)); - - QString appToRun = GetApplicationToRun(); - QString id; - foreach (const IConfigurationElement::Pointer& configElem, extensions) - { - id = configElem->GetAttribute("id"); - if(id == appToRun) - { - extension = configElem->GetDeclaringExtension(); - break; - } - } - - IApplication* app = 0; - - if (extension) - { - QList elements( - extension->GetConfigurationElements()); - if (!elements.isEmpty()) - { - QList runs( - elements[0]->GetChildren("run")); - if (!runs.isEmpty()) - { - app = runs[0]->CreateExecutableExtension ("class"); - } - } - return app; - } - - return this; -} - -QString UITestApplication::GetApplicationToRun() -{ - - QString testApp; - try - { - testApp = QString::fromStdString(Platform::GetConfiguration().getString( - Platform::ARG_TESTAPPLICATION.toStdString())); - } - catch (const Poco::NotFoundException&) - { - } - - return testApp; -} - -int UITestApplication::RunApplication(IApplication* application) -{ - testableObject = PlatformUI::GetTestableObject(); - testableObject->SetTestHarness(ITestHarness::Pointer(this)); - - if (application == dynamic_cast(this)) - return RunUITestWorkbench(); - - return application->Start(); -} - -int UITestApplication::RunUITestWorkbench() -{ - Display* display = PlatformUI::CreateDisplay(); - UITestWorkbenchAdvisor advisor; - return PlatformUI::CreateAndRunWorkbench(display, &advisor); -} - -} diff --git a/Plugins/org.blueberry.uitest/src/berryUITestApplication.h b/Plugins/org.blueberry.uitest/src/berryUITestApplication.h deleted file mode 100644 index 46cc9bb663..0000000000 --- a/Plugins/org.blueberry.uitest/src/berryUITestApplication.h +++ /dev/null @@ -1,81 +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. - -============================================================================*/ - -#ifndef BERRYUITESTAPPLICATION_H_ -#define BERRYUITESTAPPLICATION_H_ - -#include -#include -#include -#include - -#include - -namespace berry -{ - -class BERRY_UITEST_EXPORT UITestApplication: public QObject, public IApplication, public ITestHarness -{ - Q_OBJECT - Q_INTERFACES(berry::IApplication berry::ITestHarness) - -public: - - UITestApplication(); - - int Start(); - - void Stop(); - - /* - * @see berry#ITestHarness#RunTests() - */ - void RunTests(); - -private: - - TestableObject::Pointer testableObject; - int testDriverResult; - QString testPlugin; - - /* - * return the application to run, or null if not even the default application - * is found. - */ - IApplication* GetApplication(); - - /** - * The -BlueBerry.testApplication argument specifies the application to be run. - * If the argument is not set, an empty string is returned and the UITestApplication - * itself will be started. - */ - QString GetApplicationToRun(); - - int RunApplication(IApplication* application); - - int RunUITestWorkbench(); - - struct TestRunnable: public Poco::Runnable - { - TestRunnable(UITestApplication* app, const QString& testPlugin); - - void run(); - - private: - UITestApplication* app; - QString testPlugin; - }; -}; - -} - -#endif /* BERRYUITESTAPPLICATION_H_ */ diff --git a/Plugins/org.blueberry.uitest/src/harness/berryUITestCase.cpp b/Plugins/org.blueberry.uitest/src/harness/berryUITestCase.cpp deleted file mode 100644 index e95afec4c4..0000000000 --- a/Plugins/org.blueberry.uitest/src/harness/berryUITestCase.cpp +++ /dev/null @@ -1,264 +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 "berryUITestCase.h" - -#include -#include - -#include "util/berryEmptyPerspective.h" - -#ifdef BLUEBERRY_DEBUG_SMARTPOINTER -#include -#endif - -namespace berry -{ - -IAdaptable* UITestCase::GetPageInput() -{ - return 0; -} - -UITestCase::UITestCase(const QString& testName) : - TestCase(testName) -{ - // ErrorDialog.NO_UI = true; - fWorkbench = PlatformUI::GetWorkbench(); -} - -void UITestCase::failexc(const QString& message, const std::exception& e, - long /*lineNumber*/, const QString& /*fileName*/) -{ - //TODO IStatus - // If the exception is a CoreException with a multistatus - // then print out the multistatus so we can see all the info. - // if (e instanceof CoreException) { - // IStatus status = ((CoreException) e).getStatus(); - // write(status, 0); - // } else - // e.printStackTrace(); - CPPUNIT_FAIL(message.toStdString() + ": " + e.what()); -} - -IWorkbenchWindow::Pointer UITestCase::OpenTestWindow() -{ - return OpenTestWindow(EmptyPerspective::PERSP_ID); -} - -IWorkbenchWindow::Pointer UITestCase::OpenTestWindow( - const QString& perspectiveId) -{ - try - { - IWorkbenchWindow::Pointer window = fWorkbench->OpenWorkbenchWindow( - perspectiveId, GetPageInput()); - WaitOnShell(window->GetShell()); - return window; - } catch (const WorkbenchException& e) - { - CPPUNIT_FAIL(e.what()); - return IWorkbenchWindow::Pointer(0); - } -} - -void UITestCase::CloseAllTestWindows() -{ - while (!testWindows.empty()) - { - testWindows.back()->Close(); - testWindows.pop_back(); - } -} - -IWorkbenchPage::Pointer UITestCase::OpenTestPage(const IWorkbenchWindow::Pointer& /*win*/) -{ - // IWorkbenchPage[] pages = openTestPage(win, 1); - // if (pages != null) - // return pages[0]; - // else - return IWorkbenchPage::Pointer(0); -} - -QList UITestCase::OpenTestPage( - const IWorkbenchWindow::Pointer& /*win*/, int /*pageTotal*/) -{ - // try { - // IWorkbenchPage[] pages = new IWorkbenchPage[pageTotal]; - // IAdaptable input = getPageInput(); - // - // for (int i = 0; i < pageTotal; i++) { - // pages[i] = win.openPage(EmptyPerspective.PERSP_ID, input); - // } - // return pages; - // } catch (WorkbenchException e) { - // fail(); - // return null; - // } - return QList(); -} - -void UITestCase::CloseAllPages(const IWorkbenchWindow::Pointer& /*window*/) -{ - // IWorkbenchPage[] pages = window.getPages(); - // for (int i = 0; i < pages.length; i++) - // pages[i].close(); -} - -void UITestCase::Trace(const QString& msg) -{ - qDebug() << msg; -} - -void UITestCase::setUp() -{ - QString name = QString::fromStdString(this->getName()); - Trace("----- " + name); - Trace(name + ": setUp..."); - AddWindowListener(); - berry::TestCase::setUp(); -} - -void UITestCase::DoSetUp() -{ - // do nothing. -} - -void UITestCase::tearDown() -{ - Trace(QString::fromStdString(this->getName()) + ": tearDown...\n"); - RemoveWindowListener(); - berry::TestCase::tearDown(); -} - -void UITestCase::DoTearDown() -{ - ProcessEvents(); - CloseAllTestWindows(); - ProcessEvents(); -} - -void UITestCase::ProcessEvents() -{ - // Display display = PlatformUI.getWorkbench().getDisplay(); - // if (display != null) - // while (display.readAndDispatch()) - // ; -} - -void UITestCase::ManageWindows(bool manage) -{ - windowListener->SetEnabled(manage); -} - -IWorkbench* UITestCase::GetWorkbench() -{ - return fWorkbench; -} - -UITestCase::TestWindowListener::TestWindowListener( - QList& testWindows) - : enabled(true), testWindows(testWindows) -{ -} - -void UITestCase::TestWindowListener::SetEnabled(bool enabled) -{ - this->enabled = enabled; -} - -void UITestCase::TestWindowListener::WindowActivated( - const IWorkbenchWindow::Pointer& /*window*/) -{ - // do nothing -} - -void UITestCase::TestWindowListener::WindowDeactivated( - const IWorkbenchWindow::Pointer& /*window*/) -{ - // do nothing -} - -void UITestCase::TestWindowListener::WindowClosed( - const IWorkbenchWindow::Pointer& window) -{ - if (enabled) - testWindows.removeAll(window); -} - -void UITestCase::TestWindowListener::WindowOpened( - const IWorkbenchWindow::Pointer& window) -{ - if (enabled) - testWindows.push_back(window); -} - -void UITestCase::Indent(std::ostream& output, unsigned int indent) -{ - for (unsigned int i = 0; i < indent; i++) - output << " "; -} - -// void UITestCase::Write(IStatus status, unsigned int indent) { -// PrintStream output = System.out; -// indent(output, indent); -// output.println("Severity: " + status.getSeverity()); -// -// indent(output, indent); -// output.println("Plugin ID: " + status.getPlugin()); -// -// indent(output, indent); -// output.println("Code: " + status.getCode()); -// -// indent(output, indent); -// output.println("Message: " + status.getMessage()); -// -// if (status.getException() != null) { -// indent(output, indent); -// output.print("Exception: "); -// status.getException().printStackTrace(output); -// } -// -// if (status.isMultiStatus()) { -// IStatus[] children = status.getChildren(); -// for (int i = 0; i < children.length; i++) -// write(children[i], indent + 1); -// } -// } - -void UITestCase::AddWindowListener() -{ - windowListener.reset(new TestWindowListener(testWindows)); - fWorkbench->AddWindowListener(windowListener.data()); -} - -void UITestCase::RemoveWindowListener() -{ - if (windowListener) - { - fWorkbench->RemoveWindowListener(windowListener.data()); - } -} - -void UITestCase::WaitOnShell(Shell::Pointer /*shell*/) -{ - - ProcessEvents(); - // long endTime = System.currentTimeMillis() + 5000; - // - // while (shell.getDisplay().getActiveShell() != shell - // && System.currentTimeMillis() < endTime) { - // processEvents(); - // } -} - -} diff --git a/Plugins/org.blueberry.uitest/src/harness/berryUITestCase.h b/Plugins/org.blueberry.uitest/src/harness/berryUITestCase.h deleted file mode 100644 index ef1275ce98..0000000000 --- a/Plugins/org.blueberry.uitest/src/harness/berryUITestCase.h +++ /dev/null @@ -1,206 +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. - -============================================================================*/ - -#ifndef BERRYUITESTCASE_H_ -#define BERRYUITESTCASE_H_ - -#include - -#include -#include -#include - -#include - -#include - -namespace berry -{ - -/** - * UITestCase is a useful super class for most - * UI tests cases. It contains methods to create new windows - * and pages. It will also automatically close the test - * windows when the tearDown method is called. - */ -class BERRY_UITEST_EXPORT UITestCase: public TestCase -{ - -public: - - /** - * Returns the workbench page input to use for newly created windows. - * - * @return the page input to use for newly created windows - * @since 3.1 - */ - static IAdaptable* GetPageInput(); - - UITestCase(const QString& testName); - - /** - * Sets up the fixture, for example, open a network connection. - * This method is called before a test is executed. - * The default implementation does nothing. - * Subclasses may extend. - */ - virtual void DoSetUp(); - - /** - * Tears down the fixture, for example, close a network connection. - * This method is called after a test is executed. - * The default implementation closes all test windows, processing events both before - * and after doing so. - * Subclasses may extend. - */ - virtual void DoTearDown(); - - /** - * Fails the test due to the given throwable. - */ - void failexc(const QString& message, const std::exception& e, - long lineNumber = -1, - const QString& fileName = "unknown"); - - /** - * Open a test window with the empty perspective. - */ - IWorkbenchWindow::Pointer OpenTestWindow(); - - /** - * Open a test window with the provided perspective. - */ - IWorkbenchWindow::Pointer OpenTestWindow(const QString& perspectiveId); - - /** - * Close all test windows. - */ - void CloseAllTestWindows(); - - /** - * Open a test page with the empty perspective in a window. - */ - IWorkbenchPage::Pointer OpenTestPage(const IWorkbenchWindow::Pointer& win); - - /** - * Open "n" test pages with the empty perspective in a window. - */ - QList OpenTestPage( - const IWorkbenchWindow::Pointer& win, int pageTotal); - - /** - * Close all pages within a window. - */ - void CloseAllPages(const IWorkbenchWindow::Pointer& window); - -protected: - - /** - * Outputs a trace message to the trace output device, if enabled. - * By default, trace messages are sent to System.out. - * - * @param msg the trace message - */ - void Trace(const QString& msg); - - /** - * Simple implementation of setUp. Subclasses are prevented - * from overriding this method to maintain logging consistency. - * DoSetUp() should be overriden instead. - */ - void setUp(); - - /** - * Simple implementation of tearDown. Subclasses are prevented - * from overriding this method to maintain logging consistency. - * DoTearDown() should be overriden instead. - */ - void tearDown(); - - static void ProcessEvents(); - - /** - * Set whether the window listener will manage opening and closing of created windows. - */ - void ManageWindows(bool manage); - - /** - * Returns the workbench. - * - * @return the workbench - * @since 3.1 - */ - IWorkbench* GetWorkbench(); - - class TestWindowListener: public IWindowListener - { - - private: - bool enabled; - QList& testWindows; - - public: - - TestWindowListener(QList& testWindows); - - void SetEnabled(bool enabled); - - void WindowActivated(const IWorkbenchWindow::Pointer& window); - - void WindowDeactivated(const IWorkbenchWindow::Pointer& window); - - void WindowClosed(const IWorkbenchWindow::Pointer& window); - - void WindowOpened(const IWorkbenchWindow::Pointer& window); - }; - - IWorkbench* fWorkbench; - -private: - - QList testWindows; - - QScopedPointer windowListener; - - static void Indent(std::ostream& output, unsigned int indent); - - //static void Write(IStatus status, unsigned int indent); - - /** - * Adds a window listener to the workbench to keep track of - * opened test windows. - */ - void AddWindowListener(); - - /** - * Removes the listener added by addWindowListener. - */ - void RemoveWindowListener(); - - /** - * Try and process events until the new shell is the active shell. This may - * never happen, so time out after a suitable period. - * - * @param shell - * the shell to wait on - * @since 3.2 - */ - void WaitOnShell(Shell::Pointer shell); - -}; - -#define failuimsg(msg, exc) \ - (this->failexc(msg, exc, __LINE__, __FILE__)) - -} - -#endif /* BERRYUITESTCASE_H_ */ diff --git a/Plugins/org.blueberry.uitest/src/internal/berryPluginActivator.cpp b/Plugins/org.blueberry.uitest/src/internal/berryPluginActivator.cpp deleted file mode 100644 index 1840dbac6a..0000000000 --- a/Plugins/org.blueberry.uitest/src/internal/berryPluginActivator.cpp +++ /dev/null @@ -1,37 +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 "berryPluginActivator.h" - -#include "berryUITestApplication.h" -#include "util/berryEmptyPerspective.h" - -namespace berry { - -org_blueberry_uitest_Activator::org_blueberry_uitest_Activator() -{ - -} - -void org_blueberry_uitest_Activator::start(ctkPluginContext* context) -{ - BERRY_REGISTER_EXTENSION_CLASS(UITestApplication, context) - BERRY_REGISTER_EXTENSION_CLASS(EmptyPerspective, context) -} - -void org_blueberry_uitest_Activator::stop(ctkPluginContext* context) -{ - Q_UNUSED(context) -} - -} diff --git a/Plugins/org.blueberry.uitest/src/internal/berryPluginActivator.h b/Plugins/org.blueberry.uitest/src/internal/berryPluginActivator.h deleted file mode 100644 index 357ad53b61..0000000000 --- a/Plugins/org.blueberry.uitest/src/internal/berryPluginActivator.h +++ /dev/null @@ -1,39 +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. - -============================================================================*/ - - -#ifndef BERRYPLUGINACTIVATOR_H -#define BERRYPLUGINACTIVATOR_H - -#include - -namespace berry { - -class org_blueberry_uitest_Activator : - public QObject, public ctkPluginActivator -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_blueberry_uitest") - Q_INTERFACES(ctkPluginActivator) - -public: - org_blueberry_uitest_Activator(); - - void start(ctkPluginContext* context); - void stop(ctkPluginContext* context); -}; - -typedef org_blueberry_uitest_Activator PluginActivator; - -} - -#endif // BERRYPLUGINACTIVATOR_H diff --git a/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.cpp b/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.cpp deleted file mode 100644 index 9e90c3af1c..0000000000 --- a/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.cpp +++ /dev/null @@ -1,35 +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 "berryUITestWorkbenchAdvisor.h" -#include "berryUITestWorkbenchWindowAdvisor.h" - -namespace berry -{ - -UITestWorkbenchAdvisor::UITestWorkbenchAdvisor() -{ - -} - -WorkbenchWindowAdvisor* UITestWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( - IWorkbenchWindowConfigurer::Pointer configurer) -{ - return new UITestWorkbenchWindowAdvisor(configurer); -} - -QString UITestWorkbenchAdvisor::GetInitialWindowPerspectiveId() -{ - return QString::null; -} - -} diff --git a/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.h b/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.h deleted file mode 100644 index af8c7791d3..0000000000 --- a/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchAdvisor.h +++ /dev/null @@ -1,37 +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. - -============================================================================*/ - - -#ifndef BERRYUITESTWORKBENCHADVISOR_H_ -#define BERRYUITESTWORKBENCHADVISOR_H_ - -#include - -namespace berry { - -class UITestWorkbenchAdvisor : public WorkbenchAdvisor -{ - -public: - - UITestWorkbenchAdvisor(); - - WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( - IWorkbenchWindowConfigurer::Pointer configurer); - - QString GetInitialWindowPerspectiveId(); - -}; - -} - -#endif /* BERRYUITESTWORKBENCHADVISOR_H_ */ diff --git a/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchWindowAdvisor.cpp b/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchWindowAdvisor.cpp deleted file mode 100644 index 86a2be6874..0000000000 --- a/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchWindowAdvisor.cpp +++ /dev/null @@ -1,25 +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 "berryUITestWorkbenchWindowAdvisor.h" - -#include - -namespace berry { - -UITestWorkbenchWindowAdvisor::UITestWorkbenchWindowAdvisor(const IWorkbenchWindowConfigurer::Pointer& configurer) -: WorkbenchWindowAdvisor(configurer) -{ - -} - -} diff --git a/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchWindowAdvisor.h b/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchWindowAdvisor.h deleted file mode 100644 index 8f347eb145..0000000000 --- a/Plugins/org.blueberry.uitest/src/internal/berryUITestWorkbenchWindowAdvisor.h +++ /dev/null @@ -1,30 +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. - -============================================================================*/ - - -#ifndef BERRYUITESTWORKBENCHWINDOWADVISOR_H_ -#define BERRYUITESTWORKBENCHWINDOWADVISOR_H_ - -#include - -namespace berry { - -class UITestWorkbenchWindowAdvisor : public WorkbenchWindowAdvisor -{ -public: - - UITestWorkbenchWindowAdvisor(const SmartPointer& configurer); -}; - -} - -#endif /* BERRYUITESTWORKBENCHWINDOWADVISOR_H_ */ diff --git a/Plugins/org.blueberry.uitest/src/util/berryEmptyPerspective.cpp b/Plugins/org.blueberry.uitest/src/util/berryEmptyPerspective.cpp deleted file mode 100644 index 49f7d7436d..0000000000 --- a/Plugins/org.blueberry.uitest/src/util/berryEmptyPerspective.cpp +++ /dev/null @@ -1,51 +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 "berryEmptyPerspective.h" - -namespace berry -{ - -QString EmptyPerspective::LastPerspective; -const QString EmptyPerspective::PERSP_ID = - "org.blueberry.uitest.util.EmptyPerspective"; -const QString EmptyPerspective::PERSP_ID2 = - "org.blueberry.uitest.util.EmptyPerspective2"; - -EmptyPerspective::EmptyPerspective() -{ - -} - -EmptyPerspective::EmptyPerspective(const EmptyPerspective& other) - : QObject() -{ - Q_UNUSED(other) -} - -QString EmptyPerspective::GetLastPerspective() -{ - return LastPerspective; -} - -void EmptyPerspective::SetLastPerspective(const QString& perspId) -{ - LastPerspective = perspId; -} - -void EmptyPerspective::CreateInitialLayout(IPageLayout::Pointer layout) -{ - SetLastPerspective(layout->GetDescriptor()->GetId()); - // do no layout, this is the empty perspective -} - -} diff --git a/Plugins/org.blueberry.uitest/src/util/berryEmptyPerspective.h b/Plugins/org.blueberry.uitest/src/util/berryEmptyPerspective.h deleted file mode 100644 index 19b25838c9..0000000000 --- a/Plugins/org.blueberry.uitest/src/util/berryEmptyPerspective.h +++ /dev/null @@ -1,89 +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. - -============================================================================*/ - -#ifndef BERRYEMPTYPERSPECTIVE_H_ -#define BERRYEMPTYPERSPECTIVE_H_ - -#include - -#include - -namespace berry -{ - -/** - * This perspective is used for testing api. It defines an initial - * layout with no parts, just an editor area. - */ -class BERRY_UITEST_EXPORT EmptyPerspective: public QObject, public IPerspectiveFactory -{ - Q_OBJECT - Q_INTERFACES(berry::IPerspectiveFactory) - -private: - - static QString LastPerspective; - -public: - - EmptyPerspective(const EmptyPerspective& other); - - /** - * The perspective id for the empty perspective. - */ - static const QString PERSP_ID; // = "org.blueberry.uitest.util.EmptyPerspective"; - - /** - * The perspective id for the second empty perspective. - */ - static const QString PERSP_ID2; // = "org.blueberry.uitest.util.EmptyPerspective2"; - - - /** - * Returns the descriptor for the perspective last opened using this factory. - * - * @return the descriptor for the perspective last opened using this factory, or null - */ - static QString GetLastPerspective(); - - /** - * Sets the descriptor for the perspective last opened using this factory. - * - * @param persp the descriptor for the perspective last opened using this factory, or null - */ - static void SetLastPerspective(const QString& perspId); - - /** - * Constructs a new Default layout engine. - */ - EmptyPerspective(); - - /** - * Defines the initial layout for a perspective. - * - * Implementors of this method may add additional views to a - * perspective. The perspective already contains an editor folder - * with ID = ILayoutFactory::ID_EDITORS. Add additional views - * to the perspective in reference to the editor folder. - * - * This method is only called when a new perspective is created. If - * an old perspective is restored from a persistence file then - * this method is not called. - * - * @param factory the factory used to add views to the perspective - */ - void CreateInitialLayout(IPageLayout::Pointer layout); -}; - -} - -#endif /* BERRYEMPTYPERSPECTIVE_H_ */ diff --git a/Plugins/org.blueberry.uitest/src/util/berryUITestCaller.h b/Plugins/org.blueberry.uitest/src/util/berryUITestCaller.h deleted file mode 100644 index 39bea30484..0000000000 --- a/Plugins/org.blueberry.uitest/src/util/berryUITestCaller.h +++ /dev/null @@ -1,67 +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. - -============================================================================*/ - - -#ifndef BERRYUITESTCALLER_H_ -#define BERRYUITESTCALLER_H_ - -#include -#include - -#include - -namespace berry { - -template -class UITestCaller: public CppUnit::TestCase -{ - REFERENCEOBJECT (UITestCaller) - - typedef void (Fixture::*TestMethod)(); - -public: - UITestCaller(const std::string& name, TestMethod test): - CppUnit::TestCase(name), - _test(test), - _fixture(new Fixture(name)) - { - } - -protected: - void runTest() - { - (_fixture.get()->*_test)(); - } - - void setUp() - { - _fixture.get()->DoSetUp(); - } - - void tearDown() - { - _fixture.get()->DoTearDown(); - } - -private: - TestMethod _test; - std::unique_ptr _fixture; -}; - - -} // namespace berry - - -#define CppUnit_addUITest(suite, cls, mth) \ - suite->addTest(new berry::UITestCaller(#mth, &cls::mth)) - -#endif /* BERRYUITESTCALLER_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/testing/CMakeLists.txt b/Plugins/org.mitk.gui.qt.common/testing/CMakeLists.txt deleted file mode 100644 index c56ac6d48a..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -project(org_mitk_gui_qt_common_tests) - -mitk_create_plugin( - EXPORT_DIRECTIVE org_mitk_gui_qt_common_tests_EXPORT - EXPORTED_INCLUDE_SUFFIXES src src/api - MODULE_DEPENDS MitkQtWidgets - TEST_PLUGIN -) - -target_link_libraries(${PROJECT_NAME} optimized CppUnit debug CppUnitd) - -MACRO_TEST_UIPLUGIN(${MITK_DEFAULT_SUBPROJECTS}) - diff --git a/Plugins/org.mitk.gui.qt.common/testing/files.cmake b/Plugins/org.mitk.gui.qt.common/testing/files.cmake deleted file mode 100644 index 04afecf423..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/files.cmake +++ /dev/null @@ -1,37 +0,0 @@ -set(MOC_H_FILES - src/QmitkQtCommonTestSuite.h - src/api/QmitkMockFunctionality.h - - src/internal/mitkPluginActivator.h -) - -set(SRC_CPP_FILES - - QmitkQtCommonTestSuite.cpp - - # API Tests - api/QmitkFunctionalityTest.cpp - api/QmitkMockFunctionality.cpp - api/QmitkUiApiTestSuite.cpp - -) - -set(INTERNAL_CPP_FILES - mitkPluginActivator.cpp -) - -set(CPP_FILES ) - -set(RESOURCE_FILES - -# icons/view.gif -) - -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/testing/manifest.cpp b/Plugins/org.mitk.gui.qt.common/testing/manifest.cpp deleted file mode 100644 index 5323237093..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/manifest.cpp +++ /dev/null @@ -1,26 +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 "src/QmitkQtCommonTestSuite.h" - -#include "src/api/QmitkMockFunctionality.h" - -POCO_BEGIN_NAMED_MANIFEST(CppUnitTest, CppUnit::Test) - POCO_EXPORT_CLASS(QmitkQtCommonTestSuite) -POCO_END_MANIFEST - -POCO_BEGIN_NAMED_MANIFEST(berryIViewPart, berry::IViewPart) - POCO_EXPORT_CLASS(QmitkMockFunctionality) -POCO_END_MANIFEST - diff --git a/Plugins/org.mitk.gui.qt.common/testing/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.common/testing/manifest_headers.cmake deleted file mode 100644 index 43e03a0eb8..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/manifest_headers.cmake +++ /dev/null @@ -1,6 +0,0 @@ -set(Plugin-Name "MITK Common GUI Qt Tests") -set(Plugin-Version "0.9") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.blueberry.uitest org.mitk.gui.qt.common) - diff --git a/Plugins/org.mitk.gui.qt.common/testing/plugin.xml b/Plugins/org.mitk.gui.qt.common/testing/plugin.xml deleted file mode 100644 index 2b6d834020..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/plugin.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.cpp deleted file mode 100644 index b134a8221c..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.cpp +++ /dev/null @@ -1,29 +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 "QmitkQtCommonTestSuite.h" - -#include "api/QmitkUiApiTestSuite.h" - -#include - -QmitkQtCommonTestSuite::QmitkQtCommonTestSuite() -: CppUnit::TestSuite("QmitkQtCommonTestSuite") -{ - addTest(new QmitkUiApiTestSuite()); -} - -QmitkQtCommonTestSuite::QmitkQtCommonTestSuite(const QmitkQtCommonTestSuite& other) -{ - Q_UNUSED(other) - throw std::runtime_error("Copy constructor not implemented"); -} diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.h b/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.h deleted file mode 100644 index 86b28a4edc..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/QmitkQtCommonTestSuite.h +++ /dev/null @@ -1,33 +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. - -============================================================================*/ - -#ifndef QMITKQTCOMMONTESTSUITE_H_ -#define QMITKQTCOMMONTESTSUITE_H_ - -#include - -#include - -Q_DECLARE_INTERFACE(CppUnit::Test, "CppUnit.Test") - -class QmitkQtCommonTestSuite : public QObject, public CppUnit::TestSuite -{ - Q_OBJECT - Q_INTERFACES(CppUnit::Test) - -public: - - QmitkQtCommonTestSuite(); - QmitkQtCommonTestSuite(const QmitkQtCommonTestSuite& other); -}; - -#endif /* QMITKQTCOMMONTESTSUITE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.cpp deleted file mode 100644 index 542ac39160..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.cpp +++ /dev/null @@ -1,104 +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 "QmitkFunctionalityTest.h" - -#include -#include - -#include "QmitkMockFunctionality.h" - -QmitkFunctionalityTest::QmitkFunctionalityTest(const std::string& testName) - : berry::UITestCase(testName) -{ - -} - -CppUnit::Test* QmitkFunctionalityTest::Suite() -{ - CppUnit::TestSuite* suite = new CppUnit::TestSuite("QmitkFunctionalityTest"); - - CppUnit_addTest(suite, QmitkFunctionalityTest, TestOpenAndClose); - - return suite; -} - -void QmitkFunctionalityTest::DoSetUp() -{ - UITestCase::DoSetUp(); - fWindow = OpenTestWindow(); - fPage = fWindow->GetActivePage(); -} - -void QmitkFunctionalityTest::DoTearDown() -{ - fPage = 0; - fWindow = 0; - UITestCase::DoTearDown(); -} - -void QmitkFunctionalityTest::TestOpenAndClose() -{ - this->IgnoreLeakingObjects(); - - berry::CallHistory::Pointer history; - std::vector callOrder; - { - // Open a functionality. - QmitkMockFunctionality::Pointer part = fPage->ShowView(QmitkMockFunctionality::ID).Cast (); - history = part->GetCallHistory(); - - //callOrder.push_back("SetInitializationData"); - //callOrder.push_back("Init"); - callOrder.push_back("CreateQtPartControl"); - callOrder.push_back("SetFocus"); - - assert(history->VerifyOrder(callOrder)); - - // Close the part. - fPage->HideView(part.Cast()); - } - - //callOrder.push_back("WidgetDisposed"); - callOrder.push_back("FunctionalityDestructor"); - assert(history->VerifyOrder(callOrder)); -} - -void QmitkFunctionalityTest::TestOpenAndWindowClose() -{ - this->IgnoreLeakingObjects(); - - berry::CallHistory::Pointer history; - std::vector callOrder; - { - // Open a new window - berry::IWorkbenchWindow::Pointer newWindow = OpenTestWindow(); - - // Open a part. - QmitkMockFunctionality::Pointer part = newWindow->GetActivePage()->ShowView(QmitkMockFunctionality::ID).Cast ();; - history = part->GetCallHistory(); - - //callOrder.push_back("SetInitializationData"); - //callOrder.push_back("Init"); - callOrder.push_back("CreateQtPartControl"); - callOrder.push_back("SetFocus"); - - assert(history->VerifyOrder(callOrder)); - - // Close the window. - newWindow->Close(); - } - - //callOrder.push_back("WidgetDisposed"); - callOrder.push_back("FunctionalityDestructor"); - assert(history->VerifyOrder(callOrder)); -} diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.h b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.h deleted file mode 100644 index 66395f8a99..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkFunctionalityTest.h +++ /dev/null @@ -1,52 +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. - -============================================================================*/ - - -#ifndef QMITKFUNCTIONALITYTEST_H_ -#define QMITKFUNCTIONALITYTEST_H_ - -#include - -#include -#include - -#include - -/** - * Test cases for the QmitkFunctionality API. - */ -class QmitkFunctionalityTest : public berry::UITestCase { - -public: - - friend class CppUnit::TestCaller; - - QmitkFunctionalityTest(const std::string& testName); - - static CppUnit::Test* Suite(); - - void TestOpenAndClose(); - void TestOpenAndWindowClose(); - -protected: - - berry::IWorkbenchWindow::Pointer fWindow; - berry::IWorkbenchPage::Pointer fPage; - - void DoSetUp(); - void DoTearDown(); - - -}; - - -#endif /* QMITKFUNCTIONALITYTEST_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.cpp deleted file mode 100644 index 0a2f9b1152..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.cpp +++ /dev/null @@ -1,48 +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 "QmitkMockFunctionality.h" - -const std::string QmitkMockFunctionality::ID = "org.mitk.gui.qt.common.tests.api.MockFunctionality"; - -QmitkMockFunctionality::QmitkMockFunctionality() -: callTrace(new berry::CallHistory()) -{ - -} - -QmitkMockFunctionality::QmitkMockFunctionality(const QmitkMockFunctionality& other) -{ - Q_UNUSED(other) - throw std::runtime_error("Copy constructor not implemented"); -} - -QmitkMockFunctionality::~QmitkMockFunctionality() -{ - callTrace->Add("FunctionalityDestructor"); -} - -berry::CallHistory::Pointer QmitkMockFunctionality::GetCallHistory() const -{ - return callTrace; -} - -void QmitkMockFunctionality::CreateQtPartControl(QWidget* parent) -{ - callTrace->Add("CreateQtPartControl"); -} - -void QmitkMockFunctionality::SetFocus() -{ - QmitkFunctionality::SetFocus(); - callTrace->Add("SetFocus"); -} diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.h b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.h deleted file mode 100644 index f419eaf1d3..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkMockFunctionality.h +++ /dev/null @@ -1,49 +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. - -============================================================================*/ - - -#ifndef QMITKMOCKFUNCTIONALITY_H_ -#define QMITKMOCKFUNCTIONALITY_H_ - -#include - -#include - -class QmitkMockFunctionality : public QmitkFunctionality -{ - Q_OBJECT - -public: - - berryObjectMacro(QmitkMockFunctionality); - - static const std::string ID; // = "org.mitk.gui.qt.common.tests.api.MockFunctionality"; - - QmitkMockFunctionality(); - QmitkMockFunctionality(const QmitkMockFunctionality& other); - - ~QmitkMockFunctionality(); - - berry::CallHistory::Pointer GetCallHistory() const; - - void SetFocus(); - -protected: - - void CreateQtPartControl(QWidget* parent); - -private: - - berry::CallHistory::Pointer callTrace; -}; - -#endif /* QMITKMOCKFUNCTIONALITY_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.cpp deleted file mode 100644 index f35fa6e463..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.cpp +++ /dev/null @@ -1,22 +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 "QmitkUiApiTestSuite.h" - -#include "QmitkFunctionalityTest.h" - -QmitkUiApiTestSuite::QmitkUiApiTestSuite() -: CppUnit::TestSuite("QmitkUiApiTestSuite") -{ - addTest(QmitkFunctionalityTest::Suite()); - -} diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.h b/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.h deleted file mode 100644 index 6791905d4c..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/api/QmitkUiApiTestSuite.h +++ /dev/null @@ -1,27 +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. - -============================================================================*/ - - -#ifndef QMITKUIAPITESTSUITE_H_ -#define QMITKUIAPITESTSUITE_H_ - -#include - -class QmitkUiApiTestSuite : public CppUnit::TestSuite -{ - -public: - - QmitkUiApiTestSuite(); -}; - -#endif /* QMITKUIAPITESTSUITE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.common/testing/src/internal/mitkPluginActivator.cpp deleted file mode 100644 index ca10365e4c..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/internal/mitkPluginActivator.cpp +++ /dev/null @@ -1,30 +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 "mitkPluginActivator.h" -#include "../QmitkQtCommonTestSuite.h" -#include "../api/QmitkMockFunctionality.h" - -namespace mitk { - -void PluginActivator::start(ctkPluginContext* context) -{ - BERRY_REGISTER_EXTENSION_CLASS(QmitkQtCommonTestSuite, context) - BERRY_REGISTER_EXTENSION_CLASS(QmitkMockFunctionality, context) -} - -void PluginActivator::stop(ctkPluginContext* context) -{ - Q_UNUSED(context) -} - -} diff --git a/Plugins/org.mitk.gui.qt.common/testing/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.common/testing/src/internal/mitkPluginActivator.h deleted file mode 100644 index f188e754ae..0000000000 --- a/Plugins/org.mitk.gui.qt.common/testing/src/internal/mitkPluginActivator.h +++ /dev/null @@ -1,35 +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. - -============================================================================*/ -#ifndef MITKPLUGINACTIVATOR_H -#define MITKPLUGINACTIVATOR_H - -#include - -namespace mitk { - -class PluginActivator : - public QObject, public ctkPluginActivator -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_common_tests") - Q_INTERFACES(ctkPluginActivator) - -public: - - void start(ctkPluginContext* context); - void stop(ctkPluginContext* context); - -}; // PluginActivator - -} - -#endif // MITKPLUGINACTIVATOR_H diff --git a/Plugins/org.mitk.gui.qt.coreapplication/CMakeLists.txt b/Plugins/org.mitk.gui.qt.coreapplication/CMakeLists.txt deleted file mode 100644 index 69927c8d5b..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -project(org_mitk_gui_qt_coreapplication) - -mitk_create_plugin( - EXPORT_DIRECTIVE MITK_QT_COREAPP - EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDS MitkQtWidgets - SUBPROJECTS MITK-CoreUI - ) diff --git a/Plugins/org.mitk.gui.qt.coreapplication/documentation/doxygen/modules.dox b/Plugins/org.mitk.gui.qt.coreapplication/documentation/doxygen/modules.dox deleted file mode 100755 index 44df878ed5..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/documentation/doxygen/modules.dox +++ /dev/null @@ -1,17 +0,0 @@ -/** - \defgroup org_mitk_gui_qt_coreapplication org.mitk.gui.qt.coreapplication - \ingroup MITKPlugins - - \brief The CoreApp applictaion plug-in. - - Creates the menu and toolbar entries for the main application window. -*/ - -/** - \defgroup org_mitk_gui_qt_coreapplication_internal Internal - \ingroup org_mitk_gui_qt_coreapplication - - \brief This subcategory includes the internal classes of the org.mitk.gui.qt.coreapplication plugin. Other - plugins must not rely on these classes. They contain implementation details and their interface - may change at any time. We mean it. -*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/files.cmake b/Plugins/org.mitk.gui.qt.coreapplication/files.cmake deleted file mode 100644 index 863322168d..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/files.cmake +++ /dev/null @@ -1,32 +0,0 @@ -set(SRC_CPP_FILES -) - -set(INTERNAL_CPP_FILES - org_mitk_gui_qt_coreapplication_Activator.cpp - QmitkActionBarAdvisor.cpp - QmitkCoreApplication.cpp - QmitkDefaultPerspective.cpp - QmitkWorkbenchAdvisor.cpp - QmitkWorkbenchWindowAdvisor.cpp -) - -set(MOC_H_FILES - src/internal/org_mitk_gui_qt_coreapplication_Activator.h - - src/internal/QmitkCoreApplication.h - src/internal/QmitkDefaultPerspective.h -) - -set(CACHED_RESOURCE_FILES - plugin.xml -) - -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.coreapplication/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.coreapplication/manifest_headers.cmake deleted file mode 100644 index cb1d3dfe7d..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/manifest_headers.cmake +++ /dev/null @@ -1,6 +0,0 @@ -set(Plugin-Name "MITK Qt CoreApp application") -set(Plugin-Version "1.0.0") -set(Plugin-Vendor "German Cancer Research Center (DKFZ)") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.mitk.gui.qt.application) - diff --git a/Plugins/org.mitk.gui.qt.coreapplication/plugin.xml b/Plugins/org.mitk.gui.qt.coreapplication/plugin.xml deleted file mode 100644 index 45d39593a2..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/plugin.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp deleted file mode 100644 index 0cf1e7fd6f..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.cpp +++ /dev/null @@ -1,26 +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 "QmitkActionBarAdvisor.h" - -#include - -QmitkActionBarAdvisor::QmitkActionBarAdvisor(const berry::IActionBarConfigurer::Pointer& configurer) - : berry::ActionBarAdvisor(configurer) -{ - -} - -void QmitkActionBarAdvisor::FillMenuBar(berry::IMenuManager* ) -{ - -} diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h deleted file mode 100644 index 43d30bc909..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkActionBarAdvisor.h +++ /dev/null @@ -1,30 +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. - -============================================================================*/ - -#ifndef QMITKACTIONBARADVISOR_H_ -#define QMITKACTIONBARADVISOR_H_ - -#include - - -class QmitkActionBarAdvisor : public berry::ActionBarAdvisor -{ -public: - - QmitkActionBarAdvisor(const berry::SmartPointer& configurer); - -protected: - - void FillMenuBar(berry::IMenuManager* menuBar) override; -}; - -#endif /*QMITKACTIONBARADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.cpp deleted file mode 100644 index 415eb1f0bb..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.cpp +++ /dev/null @@ -1,39 +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 "QmitkCoreApplication.h" - -#include - -#include "QmitkWorkbenchAdvisor.h" - -QmitkCoreApplication::QmitkCoreApplication() -{ - -} - -QVariant QmitkCoreApplication::Start(berry::IApplicationContext* /*context*/) -{ - QScopedPointer display(berry::PlatformUI::CreateDisplay()); - - QScopedPointer wbAdvisor(new QmitkWorkbenchAdvisor()); - int code = berry::PlatformUI::CreateAndRunWorkbench(display.data(), wbAdvisor.data()); - - // exit the application with an appropriate return code - return code == berry::PlatformUI::RETURN_RESTART - ? EXIT_RESTART : EXIT_OK; -} - -void QmitkCoreApplication::Stop() -{ - -} diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.h deleted file mode 100644 index 879ec77ef1..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkCoreApplication.h +++ /dev/null @@ -1,34 +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. - -============================================================================*/ - -#ifndef QMITKCOREAPPLICATION_H_ -#define QMITKCOREAPPLICATION_H_ - -#include - -#include - - -class QmitkCoreApplication : public QObject, public berry::IApplication -{ - Q_OBJECT - Q_INTERFACES(berry::IApplication) - -public: - - QmitkCoreApplication(); - - QVariant Start(berry::IApplicationContext* context) override; - void Stop() override; -}; - -#endif /*QMITKCOREAPPLICATION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.cpp deleted file mode 100755 index 4e26085903..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.cpp +++ /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 "QmitkDefaultPerspective.h" - -QmitkDefaultPerspective::QmitkDefaultPerspective() -{ - -} - -void QmitkDefaultPerspective::CreateInitialLayout(berry::IPageLayout::Pointer /*layout*/) -{ - -} diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.h deleted file mode 100755 index 7b0acb0242..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkDefaultPerspective.h +++ /dev/null @@ -1,35 +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. - -============================================================================*/ - - -#ifndef QMITKDEFAULTPERSPECTIVE_H_ -#define QMITKDEFAULTPERSPECTIVE_H_ - -#include - -#include - - -struct QmitkDefaultPerspective : public QObject, public berry::IPerspectiveFactory -{ - - QmitkDefaultPerspective(); - - void CreateInitialLayout(berry::IPageLayout::Pointer /*layout*/) override; - -private: - - Q_OBJECT - Q_INTERFACES(berry::IPerspectiveFactory) -}; - -#endif /* QMITKDEFAULTPERSPECTIVE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp deleted file mode 100644 index be05bb4ccf..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.cpp +++ /dev/null @@ -1,41 +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 "QmitkWorkbenchAdvisor.h" - -#include - -#include "QmitkWorkbenchWindowAdvisor.h" - -const QString QmitkWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.coreapp.defaultperspective"; - -void -QmitkWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) -{ - berry::QtWorkbenchAdvisor::Initialize(configurer); - - configurer->SetSaveAndRestore(true); -} - -berry::WorkbenchWindowAdvisor* -QmitkWorkbenchAdvisor::CreateWorkbenchWindowAdvisor( - berry::IWorkbenchWindowConfigurer::Pointer configurer) -{ - return new QmitkWorkbenchWindowAdvisor(configurer); -} - -QString QmitkWorkbenchAdvisor::GetInitialWindowPerspectiveId() -{ - return DEFAULT_PERSPECTIVE_ID; -} - diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h deleted file mode 100644 index 5136c8f281..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchAdvisor.h +++ /dev/null @@ -1,33 +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. - -============================================================================*/ - -#ifndef QMITKWORKBENCHADVISOR_H_ -#define QMITKWORKBENCHADVISOR_H_ - -#include - -class QmitkWorkbenchAdvisor : public berry::QtWorkbenchAdvisor -{ -public: - - static const QString DEFAULT_PERSPECTIVE_ID; // = org.mitk.coreapp.defaultperspective - - void Initialize(berry::IWorkbenchConfigurer::Pointer configurer) override; - - berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( - berry::IWorkbenchWindowConfigurer::Pointer configurer) override; - - QString GetInitialWindowPerspectiveId() override; - -}; - -#endif /*QMITKWORKBENCHADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp deleted file mode 100644 index fd3456a711..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp +++ /dev/null @@ -1,115 +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 "QmitkWorkbenchWindowAdvisor.h" -#include "QmitkActionBarAdvisor.h" - - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -#include - -QmitkWorkbenchWindowAdvisor::QmitkWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer) -: berry::WorkbenchWindowAdvisor(configurer) -, dropTargetListener(new QmitkDefaultDropTargetListener) -{ -} - -berry::ActionBarAdvisor::Pointer -QmitkWorkbenchWindowAdvisor::CreateActionBarAdvisor( - berry::IActionBarConfigurer::Pointer configurer) -{ - berry::ActionBarAdvisor::Pointer actionBarAdvisor(new QmitkActionBarAdvisor(configurer)); - return actionBarAdvisor; -} - -void QmitkWorkbenchWindowAdvisor::PostWindowCreate() -{ - // very bad hack... - berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); - QMainWindow* mainWindow = static_cast(window->GetShell()->GetControl()); - - QMenuBar* menuBar = mainWindow->menuBar(); - - QMenu* fileMenu = menuBar->addMenu("&File"); - - fileMenu->addAction(new QmitkFileOpenAction(window)); - fileMenu->addSeparator(); - fileMenu->addAction(new QmitkFileExitAction(window)); - - berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); - QList viewDescriptors = viewRegistry->GetViews(); - - QMenu* viewMenu = menuBar->addMenu("Show &View"); - - // sort elements (converting vector to map...) - std::map VDMap; - - for (auto iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) - { - if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") - continue; - std::pair p((*iter)->GetLabel(), (*iter)); - VDMap.insert(p); - } - - auto qToolbar = new QToolBar; - - for (auto MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) - { - berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); - //m_ViewActions.push_back(viewAction); - viewMenu->addAction(viewAction); - qToolbar->addAction(viewAction); - } - - mainWindow->addToolBar(qToolbar); - - auto qStatusBar = new QStatusBar(); - - //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar - auto statusBar = new QmitkStatusBar(qStatusBar); - //disabling the SizeGrip in the lower right corner - statusBar->SetSizeGripEnabled(false); - - auto progBar = new QmitkProgressBar(); - qStatusBar->addPermanentWidget(progBar, 0); - progBar->hide(); - mainWindow->setStatusBar(qStatusBar); - - auto memoryIndicator = new QmitkMemoryUsageIndicatorView(); - qStatusBar->addPermanentWidget(memoryIndicator, 0); -} - -void QmitkWorkbenchWindowAdvisor::PreWindowOpen() -{ - this->GetWindowConfigurer()->AddEditorAreaTransfer(QStringList("text/uri-list")); - this->GetWindowConfigurer()->ConfigureEditorAreaDropListener(dropTargetListener.data()); -} diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h deleted file mode 100644 index 91479e6aca..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.h +++ /dev/null @@ -1,38 +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. - -============================================================================*/ - -#ifndef QMITKWORKBENCHWINDOWADVISOR_H_ -#define QMITKWORKBENCHWINDOWADVISOR_H_ - -#include -#include - - -class QmitkWorkbenchWindowAdvisor : public berry::WorkbenchWindowAdvisor -{ -public: - - QmitkWorkbenchWindowAdvisor(berry::SmartPointer configurer); - - berry::SmartPointer CreateActionBarAdvisor( - berry::SmartPointer configurer) override; - - void PostWindowCreate() override; - - void PreWindowOpen() override; - -private: - - QScopedPointer dropTargetListener; -}; - -#endif /*QMITKWORKBENCHWINDOWADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.cpp b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.cpp deleted file mode 100644 index 90ff7b09de..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.cpp +++ /dev/null @@ -1,32 +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 "org_mitk_gui_qt_coreapplication_Activator.h" - -#include "QmitkCoreApplication.h" -#include "QmitkDefaultPerspective.h" - -namespace mitk { - -void org_mitk_gui_qt_coreapplication_Activator::start(ctkPluginContext* context) -{ - BERRY_REGISTER_EXTENSION_CLASS(QmitkCoreApplication, context) - BERRY_REGISTER_EXTENSION_CLASS(QmitkDefaultPerspective, context) -} - -void org_mitk_gui_qt_coreapplication_Activator::stop(ctkPluginContext* context) -{ - Q_UNUSED(context) -} - -} diff --git a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.h b/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.h deleted file mode 100644 index 376927bacb..0000000000 --- a/Plugins/org.mitk.gui.qt.coreapplication/src/internal/org_mitk_gui_qt_coreapplication_Activator.h +++ /dev/null @@ -1,39 +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. - -============================================================================*/ - - -#ifndef MITKPLUGINACTIVATOR_H -#define MITKPLUGINACTIVATOR_H - -#include - -namespace mitk { - -class org_mitk_gui_qt_coreapplication_Activator : - public QObject, public ctkPluginActivator -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_coreapplication") - Q_INTERFACES(ctkPluginActivator) - -public: - - void start(ctkPluginContext* context) override; - void stop(ctkPluginContext* context) override; - -}; // org_mitk_gui_common_Activator - -typedef org_mitk_gui_qt_coreapplication_Activator PluginActivator; - -} - -#endif // MITKPLUGINACTIVATOR_H diff --git a/README.md b/README.md index 9402a64044..ff95bb0ea0 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,93 @@ ![MITK Logo][logo] The [Medical Imaging Interaction Toolkit][mitk] (MITK) is a free open-source software system for development of interactive medical image processing software. MITK combines the [Insight Toolkit][itk] (ITK) and the [Visualization Toolkit][vtk] (VTK) with an application framework. The links below provide high-level and reference documentation targeting different usage scenarios: - Get a [high-level overview][mitk-overview] about MITK with pointers to further documentation - End-users looking for help with MITK applications should read the [MITK User Manual][mitk-usermanual] - Developers contributing to or using MITK, please see the [MITK Developer Manual][mitk-devmanual] as well as the [MITK API Reference][mitk-apiref] See the [MITK homepage][mitk] for details. Supported Platforms ------------------- MITK is a cross-platform C++ toolkit and officially supports: - Windows - Linux - macOS For details, please read the [Supported Platforms][platforms] page. License ------- Copyright (c) [German Cancer Research Center (DKFZ)][dkfz]. All rights reserved. MITK is available as free open-source software under a [3-clause BSD license][license]. Download -------- The MITK source code and binaries for the *MitkWorkbench* application are released regularly according to the [MITK release cycle][release-cycle]. See the [Download][download] page for a list of releases. -The official MITK source code is available in the [MITK Git repository][diffusion]. The Git clone command is +The official MITK source code is available in the [MITK Git repository][phab_repo]. The Git clone command is git clone https://phabricator.mitk.org/source/mitk.git MITK Active development takes place in the MITK master branch and its usage is advised for advanced users only. How to Contribute ----------------- Contributions of all kind are happily accepted. However, to make the contribution process as smooth as possible, please read the [How to contribute to MITK][contribute] page if you plan to contribute to MITK. Build Instructions ------------------ MITK uses [CMake][cmake] to configure a build tree. The following is a crash course about cloning, configuring, and building MITK on a Linux/Unix system: git clone https://phabricator.mitk.org/source/mitk.git MITK mkdir MITK-build cd MITK-build cmake ../MITK make -j4 Read the comprehensive [build instructions][build] page for details. Useful Links ------------ - [Homepage][mitk] - [Download][download] - [Mailing list][mailinglist] - [Issue tracker][bugs] [logo]: https://github.com/MITK/MITK/raw/master/mitk.png [mitk]: http://mitk.org [itk]: https://itk.org [vtk]: https://vtk.org [mitk-overview]: http://docs.mitk.org/nightly/Overview.html [mitk-usermanual]: http://docs.mitk.org/nightly/UserManualPortal.html [mitk-devmanual]: http://docs.mitk.org/nightly/DeveloperManualPortal.html [mitk-apiref]: http://docs.mitk.org/nightly/usergroup0.html [platforms]: http://docs.mitk.org/nightly/SupportedPlatformsPage.html [dkfz]: https://www.dkfz.de [license]: https://github.com/MITK/MITK/blob/master/LICENSE [release-cycle]: http://mitk.org/MitkReleaseCycle [download]: http://mitk.org/Download -[diffusion]: https://phabricator.mitk.org/source/mitk/ +[phab_repo]: https://phabricator.mitk.org/source/mitk/ [contribute]: http://mitk.org/How_to_contribute [cmake]: https://www.cmake.org [build]: http://docs.mitk.org/nightly/BuildInstructionsPage.html [mailinglist]: http://mitk.org/Mailinglist [bugs]: https://phabricator.mitk.org/maniphest/ diff --git a/Utilities/mbilog/mbilogTextDictionary.h b/Utilities/mbilog/mbilogTextDictionary.h index e84e599c81..f02953ec61 100644 --- a/Utilities/mbilog/mbilogTextDictionary.h +++ b/Utilities/mbilog/mbilogTextDictionary.h @@ -1,419 +1,416 @@ /*============================================================================ 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 _MBILOG_TEXTDICTIONARY_H_ #define _MBILOG_TEXTDICTIONARY_H_ namespace mbilog { /** \brief This is a dictionary to replace long names of classes, * modules, etc. to shorter versions in the console output. */ static const char *replace[] = {".cpp", "", ".cxx", "", ".txx", "", ".h", "", ".hpp", "", ".hxx", "", ".c", "", "org.blueberry.", "", "org.mitk.gui.qt.", "", "org.mitk.", "", "qmitk", "", "mitk", "", "berry", "", "itk", "", "vtk", "", "qt", "", "object", "obj", "factory", "fac", "classes", "cls", "plugin", "plg", "widget", "wdgt", "interface", "itf", "service", "svc", "register", "reg", "perspective", "prs", "assessor", "ase", "atrophy", "atr", "bias", "bias", "field", "fld", "multi", "mlt", "contour", "cntr", "tools", "tls", "tool", "tl", "application", "app", "calculate", "calc", "subtract", "sub", "region", "reg", "tumor", "tum", "growing", "grow", "segmentation", "seg", "statistics", "stat", "imaging", "img", "image", "img", - "diffusion", - "dif", "registration", "reg", "navigation", "nav", "generation", "gen", "generator", "gen", "vector", "vec", "gradient", "grad", "flow", "flow", "paint", "pnt", "brush", "brsh", "volumetry", "vol", "volume", "vol", "mapper", "map", "filter", "flt", "surface", "sfc", "point", "pnt", "organ", "org", "multiple", "mlt", "corrector", "cor", "correction", "cor", "batch", "bat", "window", "wnd", "advisor", "adv", "editor", "edt", "material", "mat", "visualization", "vis", "measurement", "mes", "scene", "scn", "serialization", "ser", "deserializer", "dser", "serializer", "ser", "sandbox", "sb", "texture", "tex", "opengl", "ogl", "vessel", "vsl", "value", "val", "analysis", "ana", "patient", "pat", "body", "body", "diagnosis", "diag", "mesh", "mesh", "radial", "rad", "simple", "smp", "algorithms", "alg", "controllers", "con", "control", "con", "interactive", "ia", "interactions", "ia", "processing", "pro", "process", "pro", "rendering", "rnd", "renderer", "rnd", "render", "rnd", "datamanagement", "data", "management", "mng", "manager", "mng", "data", "data", "anatomy", "ana", "neuro", "neo", "automatic", "auto", "optimizer", "opt", "optimize", "opt", "binary", "bin", "liver", "liv", "lymph", "lym", "node", "node", "tree", "tree", "homogeneous", "hmgn", "threshold", "tsh", - // "shapebased", "shp", "based", "bsd", "shape", "shp", "model", "mdl", "extension", "ext", "activator", "act", "dicom", "dicom", "browser", "brwr", "viewer", "view", "view", "view", "finder", "fnd", "indexer", "idx", "index", "idx", "rapid", "rpd", "gui", "gui", "slices", "slc", "slice", "slc", "about", "abt", "interpolator", "inp", "switcher", "swh", "planarfigure", "pfig", "planning", "plan", "planner", "plan", "plane", "pln", "plan", "plan", "label", "lbl", "geometry", "geom", "workbench", "wrkbnc", "common", "com", "resection", "rsc", "translation", "trnsl", "rotation", "rot", "deformation", "dfrm", "shader", "shd", "repository", "rep", "initializer", "init", "dialog", "dlg", "download", "down", "upload", "up", "core", "core", "manual", "man", "leaf", "leaf", "internal", "int", "external", "ext", "platform", "pltfm", "method", "mthd", "pyramidal", "prmdl", "tracking", "trck", "track", "trck", "bspline", "bspl", "spline", "spl", "create", "crt", "erase", "ers", "auto", "auto", "crop", "crop", "file", "file", "io", "io", "2d", "2d", "3d", "3d", ".", "."}; } #endif