Page MenuHomePhabricator

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/Applications/CMakeLists.txt b/Applications/CMakeLists.txt
index 6e731617cb..2f43b4b1fb 100644
--- a/Applications/CMakeLists.txt
+++ b/Applications/CMakeLists.txt
@@ -1,31 +1,31 @@
set(MITK_CPACK_PACKAGE_EXECUTABLES "" CACHE INTERNAL "Collecting windows shortcuts to executables" FORCE)
set(MITK_DIR ${PROJECT_BINARY_DIR})
set(MITK_EXPORTS_FILE_INCLUDED 1)
-if(MITK_USE_Qt5)
+if(MITK_USE_Qt6)
if(MITK_USE_BLUEBERRY)
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 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)
# check if the application is enabled
if(${option_name} OR MITK_BUILD_ALL_APPS)
add_subdirectory(${MITK_APPLICATIONS_EXTENSION_DIR}/${target_dir} ${target_dir})
endif()
endforeach()
endif()
endforeach()
endif()
endif()
diff --git a/CMake/BuildConfigurations/All.cmake b/CMake/BuildConfigurations/All.cmake
index 2e65fd8460..d9f0845fcf 100644
--- a/CMake/BuildConfigurations/All.cmake
+++ b/CMake/BuildConfigurations/All.cmake
@@ -1,44 +1,43 @@
set(MITK_CONFIG_PACKAGES )
set(_apple_package_excludes)
set(_package_excludes
${_apple_package_excludes}
- OpenCL
OpenMP
SYSTEM_Boost
Boost_LIBRARIES
SYSTEM_PYTHON
SUPERBUILD
POLHEMUS_TRACKER
MICROBIRD_TRACKER
MICROBIRD_TRACKER_INCLUDE_DIR
MICROBIRD_TRACKER_LIB
MICRON_TRACKER
OPTITRACK_TRACKER
SPACENAVIGATOR
TOF_KINECT
TOF_KINECTV2
TOF_MESASR4000
TOF_PMDCAMBOARD
TOF_PMDCAMCUBE
TOF_PMDO3
US_TELEMED_SDK
videoInput
)
get_cmake_property(_cache_vars CACHE_VARIABLES)
foreach(_cache_var ${_cache_vars})
string(REGEX REPLACE "MITK_USE_(.+)" "\\1" _package "${_cache_var}")
if(_package AND NOT _package STREQUAL _cache_var)
list(FIND _package_excludes ${_package} _index)
if(_index EQUAL -1)
list(APPEND MITK_CONFIG_PACKAGES ${_package})
endif()
endif()
endforeach()
set(MITK_BUILD_ALL_APPS ON CACHE BOOL "Build all MITK applications" FORCE)
set(MITK_BUILD_ALL_PLUGINS ON CACHE BOOL "Build all MITK plugins" FORCE)
set(MITK_BUILD_EXAMPLES ON CACHE BOOL "Build the MITK examples" FORCE)
set(BLUEBERRY_BUILD_ALL_PLUGINS ON CACHE BOOL "Build all BlueBerry plugins" FORCE)
diff --git a/CMake/BuildConfigurations/Default.cmake b/CMake/BuildConfigurations/Default.cmake
index 7ec36d8732..3467689a6b 100644
--- a/CMake/BuildConfigurations/Default.cmake
+++ b/CMake/BuildConfigurations/Default.cmake
@@ -1,24 +1,24 @@
set(MITK_CONFIG_PACKAGES
ACVD
- Qt5
+ Qt6
BLUEBERRY
)
set(MITK_CONFIG_PLUGINS
org.mitk.gui.qt.mitkworkbench.intro
org.mitk.gui.qt.datamanager
org.mitk.gui.qt.stdmultiwidgeteditor
org.mitk.gui.qt.mxnmultiwidgeteditor
org.mitk.gui.qt.dicombrowser
org.mitk.gui.qt.imagenavigator
org.mitk.gui.qt.measurementtoolbox
org.mitk.gui.qt.properties
org.mitk.gui.qt.segmentation
org.mitk.gui.qt.volumevisualization
org.mitk.gui.qt.moviemaker
org.mitk.gui.qt.pointsetinteraction
org.mitk.gui.qt.remeshing
org.mitk.gui.qt.viewnavigator
org.mitk.gui.qt.imagecropper
org.mitk.gui.qt.pixelvalue
)
diff --git a/CMake/BuildConfigurations/FlowBenchSegmentation.cmake b/CMake/BuildConfigurations/FlowBenchSegmentation.cmake
index 9731309ef7..4e4fc395aa 100644
--- a/CMake/BuildConfigurations/FlowBenchSegmentation.cmake
+++ b/CMake/BuildConfigurations/FlowBenchSegmentation.cmake
@@ -1,13 +1,13 @@
set(MITK_CONFIG_PACKAGES
- Qt5
+ Qt6
BLUEBERRY
)
set(MITK_BUILD_APP_FlowBench ON CACHE BOOL "Build MITK FlowBench" FORCE)
set(MITK_CONFIG_PLUGINS
org.mitk.gui.qt.stdmultiwidgeteditor
org.mitk.gui.qt.imagenavigator
org.mitk.gui.qt.properties
org.mitk.gui.qt.flow.segmentation
)
diff --git a/CMake/BuildConfigurations/Minimal.cmake b/CMake/BuildConfigurations/Minimal.cmake
index 3ad139ab02..65855e9aeb 100644
--- a/CMake/BuildConfigurations/Minimal.cmake
+++ b/CMake/BuildConfigurations/Minimal.cmake
@@ -1,6 +1,6 @@
set(BUILD_TESTING OFF CACHE BOOL "" FORCE)
set(MITK_USE_BLUEBERRY OFF CACHE BOOL "" FORCE)
set(MITK_USE_CTK OFF CACHE BOOL "" FORCE)
-set(MITK_USE_Qt5 OFF CACHE BOOL "" FORCE)
-set(MITK_USE_Qwt OFF CACHE BOOL "" FORCE)
+set(MITK_USE_Qt6 OFF CACHE BOOL "" FORCE)
+set(MITK_USE_Qt6Qwt6 OFF CACHE BOOL "" FORCE)
diff --git a/CMake/BuildConfigurations/mitkNavigationModules.cmake b/CMake/BuildConfigurations/mitkNavigationModules.cmake
index a5eb033617..c1e5993b20 100644
--- a/CMake/BuildConfigurations/mitkNavigationModules.cmake
+++ b/CMake/BuildConfigurations/mitkNavigationModules.cmake
@@ -1,34 +1,34 @@
message(STATUS "Configuring MITK Navigation Modules Build")
set(MITK_CONFIG_PACKAGES
ACVD
- Qt5
+ Qt6
BLUEBERRY
)
# Enable open cv and open igt link, which is a necessary configuration
set(MITK_USE_OpenCV ON CACHE BOOL "MITK Use OpenCV Library" FORCE)
set(MITK_USE_OpenIGTLink ON CACHE BOOL "MITK Use OpenIGTLink Library" FORCE)
# Enable default plugins and the navigation modules
set(MITK_CONFIG_PLUGINS
org.mitk.gui.qt.datamanager
org.mitk.gui.qt.stdmultiwidgeteditor
org.mitk.gui.qt.dicombrowser
org.mitk.gui.qt.imagenavigator
org.mitk.gui.qt.measurementtoolbox
org.mitk.gui.qt.properties
org.mitk.gui.qt.segmentation
org.mitk.gui.qt.volumevisualization
org.mitk.gui.qt.moviemaker
org.mitk.gui.qt.pointsetinteraction
org.mitk.gui.qt.registration
org.mitk.gui.qt.remeshing
org.mitk.gui.qt.viewnavigator
org.mitk.gui.qt.imagecropper
org.mitk.gui.qt.igttracking
org.mitk.gui.qt.openigtlink
org.mitk.gui.qt.ultrasound
org.mitk.gui.qt.tofutil
)
diff --git a/CMake/FindOpenCL.cmake b/CMake/FindOpenCL.cmake
deleted file mode 100644
index 551d768b13..0000000000
--- a/CMake/FindOpenCL.cmake
+++ /dev/null
@@ -1,88 +0,0 @@
-# - Try to find OpenCL
-# This module tries to find an OpenCL implementation on your system. It supports
-# AMD / ATI, Apple and NVIDIA implementations, but should work, too.
-#
-# To set manually the paths, define these environment variables:
-# OpenCL_INCPATH - Include path (e.g. OpenCL_INCPATH=/opt/cuda/4.0/cuda/include)
-# OpenCL_LIBPATH - Library path (e.h. OpenCL_LIBPATH=/usr/lib64/nvidia)
-#
-# Once done this will define
-# OPENCL_FOUND - system has OpenCL
-# OPENCL_INCLUDE_DIRS - the OpenCL include directory
-# OPENCL_LIBRARIES - link these to use OpenCL
-#
-# WIN32 should work, but is untested
-
-FIND_PACKAGE(PackageHandleStandardArgs)
-
-SET (OPENCL_VERSION_STRING "0.1.0")
-SET(OPENCL_VERSION_MAJOR 0)
-SET(OPENCL_VERSION_MINOR 1)
-SET(OPENCL_VERSION_PATCH 0)
-
-IF(APPLE)
-
- FIND_LIBRARY(OPENCL_LIBRARIES OpenCL DOC "OpenCL lib for OSX")
- FIND_PATH(OPENCL_INCLUDE_DIRS OpenCL/cl.h DOC "Include for OpenCL on OSX")
- FIND_PATH(_OPENCL_CPP_INCLUDE_DIRS OpenCL/cl.hpp DOC "Include for OpenCL CPP bindings on OSX")
-
-ELSE()
- IF (WIN32)
-
- FIND_PATH(OPENCL_INCLUDE_DIRS CL/cl.h)
- FIND_PATH(_OPENCL_CPP_INCLUDE_DIRS CL/cl.hpp)
-
- IF(CMAKE_SIZEOF_VOID_P MATCHES "8")
- SET(OPENCL_LIB_DIR "$ENV{ATISTREAMSDKROOT}/lib/x86_64")
- if(NOT IS_DIRECTORY ${OPENCL_LIB_DIR})
- SET(OPENCL_LIB_DIR "$ENV{CUDA_PATH}/lib/x64")
- endif()
- ELSE()
- SET(OPENCL_LIB_DIR "$ENV{ATISTREAMSDKROOT}/lib/x86")
- if(NOT IS_DIRECTORY ${OPENCL_LIB_DIR}) # need to convert path in the cmake style ?
- SET(OPENCL_LIB_DIR "$ENV{CUDA_PATH}/lib/Win32")
- endif()
- ENDIF()
- file(TO_CMAKE_PATH ${OPENCL_LIB_DIR} OPENCL_LIB_DIR)
- GET_FILENAME_COMPONENT(OPENCL_LIB_DIR ${OPENCL_LIB_DIR} ABSOLUTE)
-
- FIND_LIBRARY(OPENCL_LIBRARIES OpenCL.lib PATHS ${OPENCL_LIB_DIR} ENV OpenCL_LIBPATH)
-
- GET_FILENAME_COMPONENT(_OPENCL_INC_CAND ${OPENCL_LIB_DIR}/../../include ABSOLUTE)
-
- # On Win32 search relative to the library
- FIND_PATH(OPENCL_INCLUDE_DIRS CL/cl.h PATHS "${_OPENCL_INC_CAND}" ENV OpenCL_INCPATH)
- FIND_PATH(_OPENCL_CPP_INCLUDE_DIRS CL/cl.hpp PATHS "${_OPENCL_INC_CAND}" ENV OpenCL_INCPATH)
-
- ELSE ()
-
- # Unix style platforms
- FIND_LIBRARY(OPENCL_LIBRARIES libOpenCL.so
- PATHS "/usr/local/cuda/lib64" "/opt/AMDAPP/lib64" ENV LD_LIBRARY_PATH ENV OpenCL_LIBPATH
- )
- GET_FILENAME_COMPONENT(OPENCL_LIB_DIR ${OPENCL_LIBRARIES} PATH)
- GET_FILENAME_COMPONENT(_OPENCL_INC_CAND ${OPENCL_LIB_DIR}/../../include ABSOLUTE)
-
- # The AMD SDK currently does not place its headers
- # in /usr/include, therefore also search relative
- # to the library
- FIND_PATH(OPENCL_INCLUDE_DIRS CL/cl.h PATHS ${_OPENCL_INC_CAND} "/usr/local/cuda/include" "/opt/AMDAPP/include" ENV OpenCL_INCPATH)
- FIND_PATH(_OPENCL_CPP_INCLUDE_DIRS CL/cl.hpp PATHS ${_OPENCL_INC_CAND} "/usr/local/cuda/include" "/opt/AMDAPP/include" ENV OpenCL_INCPATH)
-
- ENDIF ()
-
-ENDIF ()
-
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenCL DEFAULT_MSG OPENCL_LIBRARIES OPENCL_INCLUDE_DIRS)
-
-IF(_OPENCL_CPP_INCLUDE_DIRS)
- SET( OPENCL_HAS_CPP_BINDINGS TRUE )
- LIST( APPEND OPENCL_INCLUDE_DIRS ${_OPENCL_CPP_INCLUDE_DIRS} )
- # This is often the same, so clean up
- LIST( REMOVE_DUPLICATES OPENCL_INCLUDE_DIRS )
-ENDIF()
-
-MARK_AS_ADVANCED(
- OPENCL_INCLUDE_DIRS
- )
-
diff --git a/CMake/MITK.vcxproj.user.in b/CMake/MITK.vcxproj.user.in
deleted file mode 100644
index 68834e306d..0000000000
--- a/CMake/MITK.vcxproj.user.in
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <LocalDebuggerEnvironment>PATH=@MITK_RUNTIME_PATH_REL@;@CUSTOM_RUNTIME_PATH@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\@VS_BUILD_TYPE_REL@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\plugins\@VS_BUILD_TYPE_REL@;%PATH%</LocalDebuggerEnvironment>
- <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'">
- <LocalDebuggerEnvironment>PATH=@MITK_RUNTIME_PATH_RELWITHDEBINFO@;@CUSTOM_RUNTIME_PATH@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\@VS_BUILD_TYPE_RELDEB@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\plugins\@VS_BUILD_TYPE_RELDEB@;%PATH%</LocalDebuggerEnvironment>
- <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <LocalDebuggerEnvironment>PATH=@MITK_RUNTIME_PATH_DEB@;@CUSTOM_RUNTIME_PATH@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\@VS_BUILD_TYPE_DEB@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\plugins\@VS_BUILD_TYPE_DEB@;%PATH%</LocalDebuggerEnvironment>
- <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
- </PropertyGroup>
-
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <LocalDebuggerEnvironment>PATH=@MITK_RUNTIME_PATH_REL@;@CUSTOM_RUNTIME_PATH@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\@VS_BUILD_TYPE_REL@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\plugins\@VS_BUILD_TYPE_REL@;%PATH%</LocalDebuggerEnvironment>
- <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'">
- <LocalDebuggerEnvironment>PATH=@MITK_RUNTIME_PATH_RELWITHDEBINFO@;@CUSTOM_RUNTIME_PATH@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\@VS_BUILD_TYPE_RELDEB@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\plugins\@VS_BUILD_TYPE_RELDEB@;%PATH%</LocalDebuggerEnvironment>
- <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <LocalDebuggerEnvironment>PATH=@MITK_RUNTIME_PATH_DEB@;@CUSTOM_RUNTIME_PATH@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\@VS_BUILD_TYPE_DEB@;@CMAKE_RUNTIME_OUTPUT_DIRECTORY@\plugins\@VS_BUILD_TYPE_DEB@;%PATH%</LocalDebuggerEnvironment>
- <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
- </PropertyGroup>
-</Project>
\ No newline at end of file
diff --git a/CMake/MITKDashboardScript.cmake b/CMake/MITKDashboardScript.cmake
index 6049d0e184..18cf8b514e 100644
--- a/CMake/MITKDashboardScript.cmake
+++ b/CMake/MITKDashboardScript.cmake
@@ -1,196 +1,196 @@
#[============================================================================[
Configuration
]============================================================================]
set(CTEST_CMAKE_GENERATOR
# "Unix Makefiles"
"Visual Studio 16 2019"
)
set(CTEST_CMAKE_GENERATOR_PLATFORM
# "Win32"
"x64"
)
set(CTEST_BUILD_CONFIGURATION
# "Debug"
"Release"
# "MinSizeRel"
# "RelWithDebInfo"
)
set(CTEST_DASHBOARD_MODEL
# "Continuous"
"Experimental"
# "Nightly"
)
# If empty: Default site name is the name of this computer
set(CTEST_SITE
""
)
# If empty: Default build name is automatically generated based on OS,
# compiler, CTEST_BUILD_CONFIGURATION, MITK_BUILD_CONFIGURATION,
# and MITK_BUILD_NAME_SUFFIX
set(CTEST_BUILD_NAME
""
)
set(CTEST_BUILD_FLAGS
# "-j8"
)
# Only appended to automatically generated CTEST_BUILD_NAME
set(MITK_BUILD_NAME_SUFFIX
""
)
set(MITK_CLEAN_SOURCE_DIR
OFF
)
set(MITK_CLEAN_BINARY_DIR
OFF
)
# If empty: Default URL is CTEST_SUBMIT_URL (CTestConfig.cmake)
set(MITK_SUBMIT_URL
"https://cdash.mitk.org/submit.php?project=MITK"
)
set(MITK_AUTH_TOKEN
""
)
set(MITK_BUILD_CONFIGURATION
# "All"
"WorkbenchRelease"
# "Minimal"
)
set(MITK_BUILD_DOCUMENTATION
OFF
)
set(MITK_SUPERBUILD_OPTIONS
# "MITK_WHITELIST:STRING=Minimal"
- "Qt5_DIR:PATH=C:/Qt/5.12.9/msvc2017_64/lib/cmake/Qt5"
+ "Qt6_DIR:PATH=C:/Qt/6.6.1/msvc2019_64/lib/cmake/Qt6"
"MITK_AUTOCLEAN_EXTERNAL_PROJECTS:BOOL=ON"
"MITK_FAST_TESTING:BOOL=ON"
"MITK_XVFB_TESTING:BOOL=OFF"
)
set(MITK_BUILD_OPTIONS
""
)
set(MITK_REPOSITORY
"https://phabricator.mitk.org/source/mitk.git"
)
# Branch name, tag, or commit hash
set(MITK_BRANCH
"develop"
# "master"
)
# Three list items per MITK extension: <name> <URL> <branch>
set(MITK_EXTENSIONS
# "MITK-ProjectTemplate"
# "https://phabricator.mitk.org/source/mitk-projecttemplate.git"
# "master"
# "MITK Diffusion"
# "https://phabricator.mitk.org/source/mitk-diffusion.git"
# "master"
)
#[============================================================================[
Helper functions
]============================================================================]
function(get_temp_directory)
set(temp_directory "${CMAKE_CURRENT_SOURCE_DIR}/temp")
if(NOT EXISTS "${temp_directory}")
file(MAKE_DIRECTORY "${temp_directory}")
elseif(NOT IS_DIRECTORY "${temp_directory}")
message(FATAL_ERROR "Temporary directory location blocked by file \"${temp_directory}\"")
endif()
set(${ARGV0} "${temp_directory}" PARENT_SCOPE)
endfunction()
function(download_file)
cmake_parse_arguments(PARSE_ARGV 0 ARG "QUIET" "URL;OUTPUT_FILE;ERROR_CODE" "")
get_filename_component(output_dir "${ARG_OUTPUT_FILE}" DIRECTORY)
get_filename_component(output_filename "${ARG_OUTPUT_FILE}" NAME)
if(NOT output_dir)
set(output_dir "${CMAKE_CURRENT_SOURCE_DIR}")
endif()
set(output_file "${output_dir}/${output_filename}")
if(NOT ARG_QUIET)
message("Download file\n from: ${ARG_URL}\n to: ${output_file}")
endif()
get_temp_directory(temp_dir)
string(RANDOM random_filename)
while(EXISTS "${temp_dir}/${random_filename}")
string(RANDOM random_filename)
endwhile()
set(temp_output_file "${temp_dir}/${random_filename}")
file(DOWNLOAD "${ARG_URL}" "${temp_output_file}" STATUS status)
list(GET status 0 error_code)
list(GET status 1 error_message)
set(error_message "${error_message} (${error_code})")
if(NOT 0 EQUAL error_code)
if(EXISTS "${temp_output_file}")
file(REMOVE "${temp_output_file}")
endif()
if(NOT ARG_ERROR_CODE)
message(FATAL_ERROR "${error_message}")
elseif(NOT ARG_QUIET)
message(" error: ${error_message}")
endif()
else()
file(RENAME "${temp_output_file}" "${output_file}")
endif()
if(ARG_ERROR_CODE)
set(${ARG_ERROR_CODE} ${error_code} PARENT_SCOPE)
endif()
endfunction()
#[============================================================================[
Download and include actual script
]============================================================================]
include("MITKDashboardScript.local.cmake" OPTIONAL RESULT_VARIABLE found)
if(NOT found)
get_temp_directory(temp_dir)
set(script "${temp_dir}/MITKDashboardScript.cmake")
download_file(
URL "https://raw.githubusercontent.com/MITK/MITK/${MITK_BRANCH}/CMake/MITKDashboardScript.download.cmake"
OUTPUT_FILE "${script}"
)
include("${script}")
endif()
diff --git a/CMake/PackageDepends/MITK_HDF5_Config.cmake b/CMake/PackageDepends/MITK_HDF5_Config.cmake
index 30fe719f4f..b270797942 100644
--- a/CMake/PackageDepends/MITK_HDF5_Config.cmake
+++ b/CMake/PackageDepends/MITK_HDF5_Config.cmake
@@ -1,2 +1 @@
-list(APPEND ALL_INCLUDE_DIRECTORIES ${HDF5_INCLUDE_DIR})
-list(APPEND ALL_LIBRARIES ${HDF5_LIBRARIES})
+list(APPEND ALL_LIBRARIES hdf5_cpp-shared)
diff --git a/CMake/PackageDepends/MITK_OpenCL_Config.cmake b/CMake/PackageDepends/MITK_OpenCL_Config.cmake
deleted file mode 100644
index 8d84d53174..0000000000
--- a/CMake/PackageDepends/MITK_OpenCL_Config.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-list(APPEND ALL_LIBRARIES ${OPENCL_LIBRARIES})
-list(APPEND ALL_INCLUDE_DIRECTORIES ${OPENCL_INCLUDE_DIRS})
-
-# on OS X the linker needs a flag pointing to the OpenCL.framework
-if(APPLE)
- set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -framework OpenCL")
-endif(APPLE)
diff --git a/CMake/PackageDepends/MITK_OpenGL_Config.cmake b/CMake/PackageDepends/MITK_OpenGL_Config.cmake
index 0925ef472b..41e4f41c91 100644
--- a/CMake/PackageDepends/MITK_OpenGL_Config.cmake
+++ b/CMake/PackageDepends/MITK_OpenGL_Config.cmake
@@ -1,3 +1,17 @@
-set(OpenGL_GL_PREFERENCE LEGACY)
-find_package(OpenGL REQUIRED)
-list(APPEND ALL_LIBRARIES OpenGL::GL)
+if(WIN32 OR APPLE OR (DEFINED OpenGL_GL_PREFERENCE AND OpenGL_GL_PREFERENCE STREQUAL LEGACY))
+ find_package(OpenGL REQUIRED)
+ list(APPEND ALL_LIBRARIES OpenGL::GL)
+else()
+ find_package(OpenGL REQUIRED OPTIONAL_COMPONENTS EGL GLX)
+ list(APPEND ALL_LIBRARIES OpenGL::OpenGL)
+
+ if(TARGET OpenGL::EGL)
+ list(APPEND ALL_LIBRARIES OpenGL::EGL)
+ elseif(TARGET OpenGL::GLX)
+ list(APPEND ALL_LIBRARIES OpenGL::GLX)
+ else()
+ set(OpenGL_GL_PREFERENCE LEGACY)
+ find_package(OpenGL REQUIRED)
+ list(APPEND ALL_LIBRARIES OpenGL::GL)
+ endif()
+endif()
diff --git a/CMake/PackageDepends/MITK_Qt5_Config.cmake b/CMake/PackageDepends/MITK_Qt5_Config.cmake
deleted file mode 100644
index cda0e217cd..0000000000
--- a/CMake/PackageDepends/MITK_Qt5_Config.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-find_package(Qt5 COMPONENTS ${Qt5_REQUIRED_COMPONENTS_BY_MODULE} REQUIRED QUIET)
-
-foreach(qt5_component ${Qt5_REQUIRED_COMPONENTS_BY_MODULE})
- list(APPEND ALL_LIBRARIES Qt5::${qt5_component})
-endforeach()
diff --git a/CMake/PackageDepends/MITK_Qt6Qwt6_Config.cmake b/CMake/PackageDepends/MITK_Qt6Qwt6_Config.cmake
new file mode 100644
index 0000000000..a1f22d9b68
--- /dev/null
+++ b/CMake/PackageDepends/MITK_Qt6Qwt6_Config.cmake
@@ -0,0 +1 @@
+set(ALL_LIBRARIES "Qwt::Qwt")
diff --git a/CMake/PackageDepends/MITK_Qt6_Config.cmake b/CMake/PackageDepends/MITK_Qt6_Config.cmake
new file mode 100644
index 0000000000..7b8e70028c
--- /dev/null
+++ b/CMake/PackageDepends/MITK_Qt6_Config.cmake
@@ -0,0 +1,5 @@
+find_package(Qt6 COMPONENTS ${Qt6_REQUIRED_COMPONENTS_BY_MODULE} REQUIRED QUIET)
+
+foreach(qt6_component ${Qt6_REQUIRED_COMPONENTS_BY_MODULE})
+ list(APPEND ALL_LIBRARIES Qt6::${qt6_component})
+endforeach()
diff --git a/CMake/PackageDepends/MITK_Qwt_Config.cmake b/CMake/PackageDepends/MITK_Qwt_Config.cmake
deleted file mode 100644
index a8880d82d9..0000000000
--- a/CMake/PackageDepends/MITK_Qwt_Config.cmake
+++ /dev/null
@@ -1,4 +0,0 @@
-list(APPEND ALL_LIBRARIES ${Qwt_LIBRARIES})
-if(Qwt_INCLUDE_DIRS)
- list(APPEND ALL_INCLUDE_DIRECTORIES ${Qwt_INCLUDE_DIRS})
-endif()
diff --git a/CMake/mitkFunctionConfigureVisualStudioUserProjectFile.cmake b/CMake/mitkFunctionConfigureVisualStudioUserProjectFile.cmake
index 8fc399cff9..2126bf4539 100644
--- a/CMake/mitkFunctionConfigureVisualStudioUserProjectFile.cmake
+++ b/CMake/mitkFunctionConfigureVisualStudioUserProjectFile.cmake
@@ -1,39 +1,42 @@
#!
#! Configure user file for visual studio projects
#!
#! \brief This function will configure a user file for visual studio projects
#!
#! \param NAME (required) Name of the executable
#!
#! \code
#! mitkFunctionConfigureVisualStudioUserProjectFile(
#! NAME MyApp
#! )
#! \endcode
#!
function(mitkFunctionConfigureVisualStudioUserProjectFile)
set(_function_params
NAME # Name of the executable
)
set(_function_multiparams
)
set(_function_options
)
cmake_parse_arguments(VSUPF "${_function_options}" "${_function_params}" "${_function_multiparams}" ${ARGN})
- SET(VS_BUILD_TYPE_DEB debug)
- SET(VS_BUILD_TYPE_REL release)
- SET(VS_BUILD_TYPE_RELDEB relwithdebinfo)
-
- mitkFunctionGetLibrarySearchPaths(MITK_RUNTIME_PATH_DEB ${VS_BUILD_TYPE_DEB} DEBUG)
- mitkFunctionGetLibrarySearchPaths(MITK_RUNTIME_PATH_REL ${VS_BUILD_TYPE_REL} RELEASE)
- mitkFunctionGetLibrarySearchPaths(MITK_RUNTIME_PATH_RELWITHDEBINFO ${VS_BUILD_TYPE_RELDEB} RELWITHDEBINFO)
- CONFIGURE_FILE("${MITK_SOURCE_DIR}/CMake/MITK.vcxproj.user.in" ${CMAKE_CURRENT_BINARY_DIR}/${VSUPF_NAME}.vcxproj.user @ONLY)
+ mitkFunctionGetLibrarySearchPaths(PATH_DEBUG debug DEBUG)
+ mitkFunctionGetLibrarySearchPaths(PATH_RELEASE release RELEASE)
+ mitkFunctionGetLibrarySearchPaths(PATH_RELWITHDEBINFO relwithdebinfo RELWITHDEBINFO)
+ mitkFunctionGetLibrarySearchPaths(PATH_MINSIZEREL minsizerel MINSIZEREL)
+
+ set_target_properties(${VSUPF_NAME} PROPERTIES VS_DEBUGGER_ENVIRONMENT "PATH=\
+$<$<CONFIG:Debug>:${PATH_DEBUG}>\
+$<$<CONFIG:Release>:${PATH_RELEASE}>\
+$<$<CONFIG:RelWithDebInfo>:${PATH_RELWITHDEBINFO}>\
+$<$<CONFIG:MinSizeRel>:${PATH_MINSIZEREL}>\
+$<SEMICOLON>%PATH%")
endfunction()
diff --git a/CMake/mitkFunctionCreateModule.cmake b/CMake/mitkFunctionCreateModule.cmake
index df45e5d1bc..ce0c15267b 100644
--- a/CMake/mitkFunctionCreateModule.cmake
+++ b/CMake/mitkFunctionCreateModule.cmake
@@ -1,647 +1,647 @@
##################################################################
#
# mitk_create_module
#
#! Creates a module for the automatic module dependency system within MITK.
#!
#! Example:
#!
#! \code
#! mitk_create_module(
#! DEPENDS PUBLIC MitkCore
#! PACKAGE_DEPENDS
-#! PRIVATE Qt5|Xml+Networking
+#! PRIVATE Qt6|Xml+Network
#! PUBLIC ITK|Watersheds
#! \endcode
#!
#! The <moduleName> parameter specifies the name of the module which is used
#! to create a logical target name. The parameter is optional in case the
#! MITK_MODULE_NAME_DEFAULTS_TO_DIRECTORY_NAME variable evaluates to TRUE. The
#! module name will then be derived from the directory name in which this
#! function is called.
#!
#! If set, the following variables will be used to validate the module name:
#!
#! MITK_MODULE_NAME_REGEX_MATCH The module name must match this regular expression.
#! MITK_MODULE_NAME_REGEX_NOT_MATCH The module name must not match this regular expression.
#!
#! If the MITK_MODULE_NAME_PREFIX variable is set, the module name will be prefixed
#! with its contents.
#!
#! A modules source files are specified in a separate CMake file usually
#! called files.cmake, located in the module root directory. The
#! mitk_create_module() macro evaluates the following CMake variables
#! from the files.cmake file:
#!
#! - CPP_FILES A list of .cpp files
#! - H_FILES A list of .h files without a corresponding .cpp file
#! - TXX_FILES A list of .txx files
#! - RESOURCE_FILES A list of files (resources) which are embedded into the module
#! - MOC_H_FILES A list of Qt header files which should be processed by the MOC
#! - UI_FILES A list of .ui Qt UI files
#! - QRC_FILES A list of .qrc Qt resource files
#! - DOX_FILES A list of .dox Doxygen files
#!
#! List of variables available after the function is called:
#! - MODULE_NAME
#! - MODULE_TARGET
#! - MODULE_IS_ENABLED
#!
#! \sa mitk_create_executable
#!
#! Parameters (all optional):
#!
#! \param <moduleName> The module name (also used as target name)
#! \param FILES_CMAKE File name of a CMake file setting source list variables
#! (defaults to files.cmake)
#! \param VERSION Module version number, e.g. "1.2.0"
#! \param AUTOLOAD_WITH A module target name identifying the module which will
#! trigger the automatic loading of this module
#! \param DEPRECATED_SINCE Marks this modules as deprecated since <arg>
#! \param DESCRIPTION A description for this module
#!
#! Multi-value Parameters (all optional):
#!
#! \param INCLUDE_DIRS Include directories for this module:
#! \verbatim
#! [[PUBLIC|PRIVATE|INTERFACE] <dir1>...]...
#! \endverbatim
#! The default scope for include directories is PUBLIC.
#! \param DEPENDS List of module dependencies:
#! \verbatim
#! [[PUBLIC|PRIVATE|INTERFACE] <module1>...]...
#! \endverbatim
#! The default scope for module dependencies is PUBLIC.
#! \param PACKAGE_DEPENDS List of public packages dependencies (e.g. Qt, VTK, etc.).
#! Package dependencies have the following syntax:
#! \verbatim
#! [PUBLIC|PRIVATE|INTERFACE] PACKAGE[|COMPONENT1[+COMPONENT2]...]
#! \endverbatim
#! The default scope for package dependencies is PRIVATE.
#! \param ADDITIONAL_LIBS List of additional private libraries linked to this module.
#! The folder containing the library will be added to the global list of library search paths.
#! \param CPP_FILES List of source files for this module. If the list is non-empty,
#! the module does not need to provide a files.cmake file or FILES_CMAKE argument.
#! \param H_FILES List of public header files for this module. It is recommended to use
#! a files.cmake file instead.
#!
#! Options (optional)
#!
#! \param FORCE_STATIC Force building this module as a static library
#! \param GCC_DEFAULT_VISIBILITY Do not use gcc visibility flags - all
#! symbols will be exported
#! \param NO_INIT Do not create CppMicroServices initialization code
#! \param NO_FEATURE_INFO Do not create a feature info by calling add_feature_info()
#! \param WARNINGS_NO_ERRORS Do not treat compiler warnings as errors
#
##################################################################
function(mitk_create_module)
set(_macro_params
VERSION # module version number, e.g. "1.2.0"
EXPORT_DEFINE # export macro name for public symbols of this module (DEPRECATED)
AUTOLOAD_WITH # a module target name identifying the module which will trigger the
# automatic loading of this module
FILES_CMAKE # file name of a CMake file setting source list variables
# (defaults to files.cmake)
DEPRECATED_SINCE # marks this modules as deprecated
DESCRIPTION # a description for this module
)
set(_macro_multiparams
SUBPROJECTS # list of CDash labels (deprecated)
INCLUDE_DIRS # include directories: [PUBLIC|PRIVATE|INTERFACE] <list>
INTERNAL_INCLUDE_DIRS # include dirs internal to this module (DEPRECATED)
DEPENDS # list of modules this module depends on: [PUBLIC|PRIVATE|INTERFACE] <list>
DEPENDS_INTERNAL # list of modules this module internally depends on (DEPRECATED)
PACKAGE_DEPENDS # list of "packages this module depends on (e.g. Qt, VTK, etc.): [PUBLIC|PRIVATE|INTERFACE] <package-list>
TARGET_DEPENDS # list of CMake targets this module should depend on: [PUBLIC|PRIVATE|INTERFACE] <list>
ADDITIONAL_LIBS # list of addidtional private libraries linked to this module.
CPP_FILES # list of cpp files
H_FILES # list of header files: [PUBLIC|PRIVATE] <list>
)
set(_macro_options
FORCE_STATIC # force building this module as a static library
HEADERS_ONLY # this module is a headers-only library
GCC_DEFAULT_VISIBILITY # do not use gcc visibility flags - all symbols will be exported
NO_DEFAULT_INCLUDE_DIRS # do not add default include directories like "include" or "."
NO_INIT # do not create CppMicroServices initialization code
NO_FEATURE_INFO # do not create a feature info by calling add_feature_info()
WARNINGS_NO_ERRORS # do not treat compiler warnings as errors
EXECUTABLE # create an executable; do not use directly, use mitk_create_executable() instead
C_MODULE # compile all source files as C sources
CXX_MODULE # compile all source files as C++ sources
)
cmake_parse_arguments(MODULE "${_macro_options}" "${_macro_params}" "${_macro_multiparams}" ${ARGN})
set(MODULE_NAME ${MODULE_UNPARSED_ARGUMENTS})
# -----------------------------------------------------------------
# Sanity checks
if(NOT MODULE_NAME)
if(MITK_MODULE_NAME_DEFAULTS_TO_DIRECTORY_NAME)
get_filename_component(MODULE_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
else()
message(SEND_ERROR "The module name must not be empty")
endif()
endif()
set(_deprecated_args INTERNAL_INCLUDE_DIRS DEPENDS_INTERNAL EXPORT_DEFINE HEADERS_ONLY)
foreach(_deprecated_arg ${_deprecated_args})
if(MODULE_${_deprecated_arg})
message(WARNING "The ${_deprecated_arg} argument is deprecated")
endif()
endforeach()
set(_module_type module)
set(_Module_type Module)
if(MODULE_EXECUTABLE)
set(_module_type executable)
set(_Module_type Executable)
endif()
if(MITK_MODULE_NAME_REGEX_MATCH)
if(NOT ${MODULE_NAME} MATCHES ${MITK_MODULE_NAME_REGEX_MATCH})
message(SEND_ERROR "The ${_module_type} name \"${MODULE_NAME}\" does not match the regular expression \"${MITK_MODULE_NAME_REGEX_MATCH}\".")
endif()
endif()
if(MITK_MODULE_NAME_REGEX_NOT_MATCH)
if(${MODULE_NAME} MATCHES ${MITK_MODULE_NAME_REGEX_NOT_MATCH})
message(SEND_ERROR "The ${_module_type} name \"${MODULE_NAME}\" must not match the regular expression \"${MITK_MODULE_NAME_REGEX_NOT_MATCH}\".")
endif()
endif()
if(MITK_MODULE_NAME_PREFIX AND NOT MODULE_NAME MATCHES "^${MITK_MODULE_NAME_PREFIX}.*$")
set(MODULE_NAME "${MITK_MODULE_NAME_PREFIX}${MODULE_NAME}")
endif()
if(NOT MODULE_FILES_CMAKE)
set(MODULE_FILES_CMAKE files.cmake)
endif()
if(NOT IS_ABSOLUTE ${MODULE_FILES_CMAKE})
set(MODULE_FILES_CMAKE ${CMAKE_CURRENT_SOURCE_DIR}/${MODULE_FILES_CMAKE})
endif()
# -----------------------------------------------------------------
# Check if module should be build
set(MODULE_TARGET ${MODULE_NAME})
# assume worst case
set(MODULE_IS_ENABLED 0)
# first we check if we have an explicit module build list
if(MITK_MODULES_TO_BUILD)
list(FIND MITK_MODULES_TO_BUILD ${MODULE_NAME} _MOD_INDEX)
if(_MOD_INDEX EQUAL -1)
set(MODULE_IS_EXCLUDED 1)
endif()
endif()
if(NOT MODULE_IS_EXCLUDED)
# first of all we check for the dependencies
_mitk_parse_package_args(${MODULE_PACKAGE_DEPENDS})
mitk_check_module_dependencies(MODULES ${MODULE_DEPENDS}
PACKAGES ${PACKAGE_NAMES}
MISSING_DEPENDENCIES_VAR _MISSING_DEP
PACKAGE_DEPENDENCIES_VAR PACKAGE_NAMES)
if(_MISSING_DEP)
if(MODULE_NO_FEATURE_INFO)
message("${_Module_type} ${MODULE_NAME} won't be built, missing dependency: ${_MISSING_DEP}")
endif()
set(MODULE_IS_ENABLED 0)
else()
foreach(dep ${MODULE_DEPENDS})
if(TARGET ${dep})
get_target_property(AUTLOAD_DEP ${dep} MITK_AUTOLOAD_DIRECTORY)
if (AUTLOAD_DEP)
message(SEND_ERROR "Module \"${MODULE_NAME}\" has an invalid dependency on autoload module \"${dep}\". Check MITK_CREATE_MODULE usage for \"${MODULE_NAME}\".")
endif()
endif()
endforeach(dep)
set(MODULE_IS_ENABLED 1)
# now check for every package if it is enabled. This overlaps a bit with
# MITK_CHECK_MODULE ...
foreach(_package ${PACKAGE_NAMES})
if((DEFINED MITK_USE_${_package}) AND NOT (MITK_USE_${_package}))
message("${_Module_type} ${MODULE_NAME} won't be built. Turn on MITK_USE_${_package} if you want to use it.")
set(MODULE_IS_ENABLED 0)
break()
endif()
endforeach()
endif()
endif()
# -----------------------------------------------------------------
# Start creating the module
if(MODULE_IS_ENABLED)
# clear variables defined in files.cmake
set(RESOURCE_FILES )
set(CPP_FILES )
set(H_FILES )
set(TXX_FILES )
set(DOX_FILES )
set(UI_FILES )
set(MOC_H_FILES )
set(QRC_FILES )
# clear other variables
- set(Q${KITNAME}_GENERATED_CPP )
- set(Q${KITNAME}_GENERATED_MOC_CPP )
- set(Q${KITNAME}_GENERATED_QRC_CPP )
- set(Q${KITNAME}_GENERATED_UI_CPP )
+ set(GENERATED_CPP )
+ set(GENERATED_MOC_CPP )
+ set(GENERATED_QRC_CPP )
+ set(GENERATED_UI_CPP )
# check and set-up auto-loading
if(MODULE_AUTOLOAD_WITH)
if(NOT TARGET "${MODULE_AUTOLOAD_WITH}")
message(SEND_ERROR "The module target \"${MODULE_AUTOLOAD_WITH}\" specified as the auto-loading module for \"${MODULE_NAME}\" does not exist")
endif()
endif()
set(_module_autoload_meta_target "${CMAKE_PROJECT_NAME}-autoload")
# create a meta-target if it does not already exist
if(NOT TARGET ${_module_autoload_meta_target})
add_custom_target(${_module_autoload_meta_target})
set_property(TARGET ${_module_autoload_meta_target} PROPERTY FOLDER "${MITK_ROOT_FOLDER}/Modules/Autoload")
endif()
if(NOT MODULE_EXPORT_DEFINE)
set(MODULE_EXPORT_DEFINE ${MODULE_NAME}_EXPORT)
endif()
if(MITK_GENERATE_MODULE_DOT)
message("MODULEDOTNAME ${MODULE_NAME}")
foreach(dep ${MODULE_DEPENDS})
message("MODULEDOT \"${MODULE_NAME}\" -> \"${dep}\" ; ")
endforeach(dep)
endif(MITK_GENERATE_MODULE_DOT)
if (EXISTS ${MODULE_FILES_CMAKE})
include(${MODULE_FILES_CMAKE})
endif()
if(MODULE_CPP_FILES)
list(APPEND CPP_FILES ${MODULE_CPP_FILES})
endif()
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src")
# Preprend the "src" directory to the cpp file list
set(_cpp_files ${CPP_FILES})
set(CPP_FILES )
foreach(_cpp_file ${_cpp_files})
list(APPEND CPP_FILES "src/${_cpp_file}")
endforeach()
endif()
if(CPP_FILES OR RESOURCE_FILES OR UI_FILES OR MOC_H_FILES OR QRC_FILES)
set(MODULE_HEADERS_ONLY 0)
if(MODULE_C_MODULE)
set_source_files_properties(${CPP_FILES} PROPERTIES LANGUAGE C)
elseif(MODULE_CXX_MODULE)
set_source_files_properties(${CPP_FILES} PROPERTIES LANGUAGE CXX)
endif()
else()
set(MODULE_HEADERS_ONLY 1)
if(MODULE_AUTOLOAD_WITH)
message(SEND_ERROR "A headers only module cannot be auto-loaded")
endif()
endif()
set(module_c_flags )
set(module_c_flags_debug )
set(module_c_flags_release )
set(module_cxx_flags )
set(module_cxx_flags_debug )
set(module_cxx_flags_release )
if(MODULE_GCC_DEFAULT_VISIBILITY OR NOT CMAKE_COMPILER_IS_GNUCXX)
# We only support hidden visibility for gcc for now. Clang still has troubles with
# correctly marking template declarations and explicit template instantiations as exported.
set(CMAKE_CXX_VISIBILITY_PRESET default)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 0)
else()
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
endif()
if(NOT MODULE_WARNINGS_NO_ERRORS)
if(MSVC_VERSION)
mitkFunctionCheckCAndCXXCompilerFlags("/WX" module_c_flags module_cxx_flags)
# this would turn on unused parameter warnings, but unfortunately MSVC cannot
# distinguish yet between internal and external headers so this would be triggered
# a lot by external code. There is support for it on the way so this line could be
# reactivated after https://gitlab.kitware.com/cmake/cmake/issues/17904 has been fixed.
# mitkFunctionCheckCAndCXXCompilerFlags("/w34100" module_c_flags module_cxx_flags)
else()
mitkFunctionCheckCAndCXXCompilerFlags(-Werror module_c_flags module_cxx_flags)
# The flag "c++0x-static-nonintegral-init" has been renamed in newer Clang
# versions to "static-member-init"
#
# Also, older Clang and seemingly all gcc versions do not warn if unknown
# "-no-*" flags are used, so CMake will happily append any -Wno-* flag to the
# command line. This may get confusing if unrelated compiler errors happen and
# the error output then additionally contains errors about unknown flags (which
# is not the case if there were no compile errors).
#
# So instead of using -Wno-* we use -Wno-error=*, which will be properly rejected by
# the compiler and if applicable, prints the specific warning as a real warning and
# not as an error (although -Werror was given).
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=c++0x-static-nonintegral-init" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=static-member-init" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=unknown-warning" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=gnu" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=class-memaccess" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=inconsistent-missing-override" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=deprecated-copy" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=cast-function-type" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=deprecated-declarations" module_c_flags module_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=type-limits" module_c_flags module_cxx_flags)
endif()
endif()
if(MODULE_FORCE_STATIC)
set(_STATIC STATIC)
else()
set(_STATIC )
endif(MODULE_FORCE_STATIC)
if(NOT MODULE_HEADERS_ONLY)
if(NOT MODULE_NO_INIT OR RESOURCE_FILES)
find_package(CppMicroServices QUIET NO_MODULE REQUIRED)
endif()
if(NOT MODULE_NO_INIT)
usFunctionGenerateModuleInit(CPP_FILES)
endif()
set(binary_res_files )
set(source_res_files )
if(RESOURCE_FILES)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/resource")
set(res_dir resource)
elseif(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Resources")
set(res_dir Resources)
else()
message(SEND_ERROR "Resources specified but ${CMAKE_CURRENT_SOURCE_DIR}/resource directory not found.")
endif()
foreach(res_file ${RESOURCE_FILES})
if(EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${res_dir}/${res_file})
list(APPEND binary_res_files "${res_file}")
else()
list(APPEND source_res_files "${res_file}")
endif()
endforeach()
# Add a source level dependencies on resource files
usFunctionGetResourceSource(TARGET ${MODULE_TARGET} OUT CPP_FILES)
endif()
endif()
- if(MITK_USE_Qt5)
+ if(MITK_USE_Qt6)
if(UI_FILES)
- qt5_wrap_ui(Q${KITNAME}_GENERATED_UI_CPP ${UI_FILES})
+ qt_wrap_ui(GENERATED_UI_CPP ${UI_FILES})
endif()
if(MOC_H_FILES)
- qt5_wrap_cpp(Q${KITNAME}_GENERATED_MOC_CPP ${MOC_H_FILES} OPTIONS -DBOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
+ qt_wrap_cpp(GENERATED_MOC_CPP ${MOC_H_FILES} OPTIONS -DBOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
endif()
if(QRC_FILES)
- qt5_add_resources(Q${KITNAME}_GENERATED_QRC_CPP ${QRC_FILES})
+ qt_add_resources(GENERATED_QRC_CPP ${QRC_FILES})
endif()
endif()
- set(Q${KITNAME}_GENERATED_CPP ${Q${KITNAME}_GENERATED_CPP} ${Q${KITNAME}_GENERATED_UI_CPP} ${Q${KITNAME}_GENERATED_MOC_CPP} ${Q${KITNAME}_GENERATED_QRC_CPP})
+ set(GENERATED_CPP ${GENERATED_CPP} ${GENERATED_UI_CPP} ${GENERATED_MOC_CPP} ${GENERATED_QRC_CPP})
mitkFunctionOrganizeSources(
SOURCE ${CPP_FILES}
HEADER ${H_FILES}
TXX ${TXX_FILES}
DOC ${DOX_FILES}
UI ${UI_FILES}
QRC ${QRC_FILES}
- MOC ${Q${KITNAME}_GENERATED_MOC_CPP}
- GEN_QRC ${Q${KITNAME}_GENERATED_QRC_CPP}
- GEN_UI ${Q${KITNAME}_GENERATED_UI_CPP}
+ MOC ${GENERATED_MOC_CPP}
+ GEN_QRC ${GENERATED_QRC_CPP}
+ GEN_UI ${GENERATED_UI_CPP}
)
set(coverage_sources
${CPP_FILES} ${H_FILES} ${GLOBBED__H_FILES} ${CORRESPONDING__H_FILES} ${TXX_FILES}
${TOOL_CPPS} ${TOOL_GUI_CPPS})
# ---------------------------------------------------------------
# Create the actual module target
if(MODULE_HEADERS_ONLY)
add_library(${MODULE_TARGET} INTERFACE)
# INTERFACE_LIBRARY targets may only have whitelisted properties. The property "FOLDER" is not allowed.
# set_property(TARGET ${MODULE_TARGET} PROPERTY FOLDER "${MITK_ROOT_FOLDER}/Modules")
else()
if(MODULE_EXECUTABLE)
if(MITK_SHOW_CONSOLE_WINDOW)
set(_SHOW_CONSOLE_OPTION "")
else()
set(_SHOW_CONSOLE_OPTION WIN32)
endif()
add_executable(${MODULE_TARGET} ${_SHOW_CONSOLE_OPTION}
- ${MODULE_CPP_FILES} ${coverage_sources} ${CPP_FILES_GENERATED} ${Q${KITNAME}_GENERATED_CPP}
+ ${MODULE_CPP_FILES} ${coverage_sources} ${CPP_FILES_GENERATED} ${GENERATED_CPP}
${DOX_FILES} ${UI_FILES} ${QRC_FILES} ${WINDOWS_ICON_RESOURCE_FILE})
if(WIN32)
mitk_add_manifest(${MODULE_TARGET})
endif()
set_property(TARGET ${MODULE_TARGET} PROPERTY FOLDER "${MITK_ROOT_FOLDER}/Modules/Executables")
set(_us_module_name main)
else()
add_library(${MODULE_TARGET} ${_STATIC}
- ${coverage_sources} ${CPP_FILES_GENERATED} ${Q${KITNAME}_GENERATED_CPP}
+ ${coverage_sources} ${CPP_FILES_GENERATED} ${GENERATED_CPP}
${DOX_FILES} ${UI_FILES} ${QRC_FILES})
set_property(TARGET ${MODULE_TARGET} PROPERTY FOLDER "${MITK_ROOT_FOLDER}/Modules")
set(_us_module_name ${MODULE_TARGET})
endif()
# Apply properties to the module target.
target_compile_definitions(${MODULE_TARGET} PRIVATE US_MODULE_NAME=${_us_module_name})
if(MODULE_C_MODULE)
if(module_c_flags)
string(REPLACE " " ";" module_c_flags "${module_c_flags}")
target_compile_options(${MODULE_TARGET} PRIVATE ${module_c_flags})
endif()
if(module_c_flags_debug)
string(REPLACE " " ";" module_c_flags_debug "${module_c_flags_debug}")
target_compile_options(${MODULE_TARGET} PRIVATE $<$<CONFIG:Debug>:${module_c_flags_debug}>)
endif()
if(module_c_flags_release)
string(REPLACE " " ";" module_c_flags_release "${module_c_flags_release}")
target_compile_options(${MODULE_TARGET} PRIVATE $<$<CONFIG:Release>:${module_c_flags_release}>)
endif()
else()
if(module_cxx_flags)
string(REPLACE " " ";" module_cxx_flags "${module_cxx_flags}")
target_compile_options(${MODULE_TARGET} PRIVATE ${module_cxx_flags})
endif()
if(module_cxx_flags_debug)
string(REPLACE " " ";" module_cxx_flags_debug "${module_cxx_flags_debug}")
target_compile_options(${MODULE_TARGET} PRIVATE $<$<CONFIG:Debug>:${module_cxx_flags_debug}>)
endif()
if(module_cxx_flags_release)
string(REPLACE " " ";" module_cxx_flags_release "${module_cxx_flags_release}")
target_compile_options(${MODULE_TARGET} PRIVATE $<$<CONFIG:Release>:${module_cxx_flags_release}>)
endif()
endif()
set_property(TARGET ${MODULE_TARGET} PROPERTY US_MODULE_NAME ${_us_module_name})
# Add additional library search directories to a global property which
# can be evaluated by other CMake macros, e.g. our install scripts.
if(MODULE_ADDITIONAL_LIBS)
target_link_libraries(${MODULE_TARGET} PRIVATE ${MODULE_ADDITIONAL_LIBS})
get_property(_mitk_additional_library_search_paths GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS)
foreach(_lib_filepath ${MODULE_ADDITIONAL_LIBS})
get_filename_component(_search_path "${_lib_filepath}" PATH)
if(_search_path)
list(APPEND _mitk_additional_library_search_paths "${_search_path}")
endif()
endforeach()
if(_mitk_additional_library_search_paths)
list(REMOVE_DUPLICATES _mitk_additional_library_search_paths)
set_property(GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS ${_mitk_additional_library_search_paths})
endif()
endif()
# add the target name to a global property which is used in the top-level
# CMakeLists.txt file to export the target
set_property(GLOBAL APPEND PROPERTY MITK_MODULE_TARGETS ${MODULE_TARGET})
if(MODULE_AUTOLOAD_WITH)
# for auto-loaded modules, adapt the output directory
add_dependencies(${_module_autoload_meta_target} ${MODULE_TARGET})
if(WIN32)
set(_module_output_prop RUNTIME_OUTPUT_DIRECTORY)
else()
set(_module_output_prop LIBRARY_OUTPUT_DIRECTORY)
endif()
set(_module_output_dir ${CMAKE_${_module_output_prop}}/${MODULE_AUTOLOAD_WITH})
get_target_property(_module_is_imported ${MODULE_AUTOLOAD_WITH} IMPORTED)
if(NOT _module_is_imported)
# if the auto-loading module is not imported, get its location
# and put the auto-load module relative to it.
get_target_property(_module_output_dir ${MODULE_AUTOLOAD_WITH} ${_module_output_prop})
set_target_properties(${MODULE_TARGET} PROPERTIES
${_module_output_prop} ${_module_output_dir}/${MODULE_AUTOLOAD_WITH})
else()
set_target_properties(${MODULE_TARGET} PROPERTIES
${_module_output_prop} ${CMAKE_${_module_output_prop}}/${MODULE_AUTOLOAD_WITH})
endif()
set_target_properties(${MODULE_TARGET} PROPERTIES
MITK_AUTOLOAD_DIRECTORY ${MODULE_AUTOLOAD_WITH})
# add the auto-load module name as a property
set_property(TARGET ${MODULE_AUTOLOAD_WITH} APPEND PROPERTY MITK_AUTOLOAD_TARGETS ${MODULE_TARGET})
endif()
if(binary_res_files)
usFunctionAddResources(TARGET ${MODULE_TARGET}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${res_dir}
FILES ${binary_res_files})
endif()
if(source_res_files)
usFunctionAddResources(TARGET ${MODULE_TARGET}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${res_dir}
FILES ${source_res_files})
endif()
if(binary_res_files OR source_res_files)
usFunctionEmbedResources(TARGET ${MODULE_TARGET})
endif()
if(MODULE_DEPRECATED_SINCE)
set_property(TARGET ${MODULE_TARGET} PROPERTY MITK_MODULE_DEPRECATED_SINCE ${MODULE_DEPRECATED_SINCE})
endif()
# create export macros
if (NOT MODULE_EXECUTABLE)
set(_export_macro_name )
if(MITK_LEGACY_EXPORT_MACRO_NAME)
set(_export_macro_names
EXPORT_MACRO_NAME ${MODULE_EXPORT_DEFINE}
NO_EXPORT_MACRO_NAME ${MODULE_NAME}_NO_EXPORT
DEPRECATED_MACRO_NAME ${MODULE_NAME}_DEPRECATED
NO_DEPRECATED_MACRO_NAME ${MODULE_NAME}_NO_DEPRECATED
)
endif()
generate_export_header(${MODULE_NAME}
${_export_macro_names}
EXPORT_FILE_NAME ${MODULE_NAME}Exports.h
)
endif()
target_include_directories(${MODULE_TARGET} PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
endif()
# ---------------------------------------------------------------
# Properties for both header-only and compiled modules
if(MODULE_HEADERS_ONLY)
set(_module_property_type INTERFACE)
else()
set(_module_property_type PUBLIC)
endif()
if(MODULE_TARGET_DEPENDS)
target_link_libraries(${MODULE_TARGET} ${MODULE_TARGET_DEPENDS})
endif()
set(DEPENDS "${MODULE_DEPENDS}")
if(NOT MODULE_NO_INIT AND NOT MODULE_HEADERS_ONLY)
# Add a CppMicroServices dependency implicitly, since it is
# needed for the generated "module initialization" code.
set(DEPENDS "CppMicroServices;${DEPENDS}")
endif()
if(DEPENDS OR MODULE_PACKAGE_DEPENDS)
mitk_use_modules(TARGET ${MODULE_TARGET}
MODULES ${DEPENDS}
PACKAGES ${MODULE_PACKAGE_DEPENDS}
)
endif()
# add include directories
if(MODULE_INTERNAL_INCLUDE_DIRS)
target_include_directories(${MODULE_TARGET} PRIVATE ${MODULE_INTERNAL_INCLUDE_DIRS})
endif()
if(NOT MODULE_NO_DEFAULT_INCLUDE_DIRS)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_include_directories(${MODULE_TARGET} ${_module_property_type} include)
else()
target_include_directories(${MODULE_TARGET} ${_module_property_type} .)
endif()
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_include_directories(${MODULE_TARGET} PRIVATE src)
endif()
endif()
target_include_directories(${MODULE_TARGET} ${_module_property_type} ${MODULE_INCLUDE_DIRS})
endif()
# -----------------------------------------------------------------
# Record missing dependency information
if(_MISSING_DEP)
if(MODULE_DESCRIPTION)
set(MODULE_DESCRIPTION "${MODULE_DESCRIPTION} (missing dependencies: ${_MISSING_DEP})")
else()
set(MODULE_DESCRIPTION "(missing dependencies: ${_MISSING_DEP})")
endif()
endif()
if(NOT MODULE_NO_FEATURE_INFO)
add_feature_info(${MODULE_NAME} MODULE_IS_ENABLED "${MODULE_DESCRIPTION}")
endif()
set(MODULE_NAME ${MODULE_NAME} PARENT_SCOPE)
set(MODULE_TARGET ${MODULE_TARGET} PARENT_SCOPE)
set(MODULE_IS_ENABLED ${MODULE_IS_ENABLED} PARENT_SCOPE)
endfunction()
diff --git a/CMake/mitkFunctionCreatePlugin.cmake b/CMake/mitkFunctionCreatePlugin.cmake
index 8edd95a256..8044c5b978 100644
--- a/CMake/mitkFunctionCreatePlugin.cmake
+++ b/CMake/mitkFunctionCreatePlugin.cmake
@@ -1,357 +1,342 @@
#! \brief Creates a MITK CTK plugin.
#!
#! This function should be called from the plugins CMakeLists.txt file.
#! The target name is available after the macro call as ${PLUGIN_TARGET}
#! to add additional libraries in your CMakeLists.txt. Include paths and link
#! libraries are set depending on the value of the Required-Plugins header
#! in your manifest_headers.cmake file.
#!
#! This function internally calls ctkMacroBuildPlugin() and adds support
#! for Qt Help files and installers.
#!
#! Options:
#! \param TEST_PLUGIN Mark this plug-in as a testing plug-in.
#! \param NO_INSTALL Don't install this plug-in.
#!
#! Parameters:
#!
#! \param EXPORT_DIRECTIVE (required) The export directive to use in the generated
#! <plugin_target>_Exports.h file.
#!
#! Multi-value parameters (all optional):
#!
#! \param EXPORTED_INCLUDE_SUFFIXES A list of sub-directories which should
#! be added to the current source directory. The resulting directories
#! will be available in the set of include directories of depending plug-ins.
#! \param MODULE_DEPENDS (optional) A list of Modules this plug-in depends on.
#! \param PACKAGE_DEPENDS (optional) A list of external packages this plug-in depends on.
#! \param TARGET_DEPENDS (optional) A list of CMake targets this plug-in depends on.
#! \param DOXYGEN_TAGFILES (optional) Which external tag files should be available for the plugin documentation
#! \param MOC_OPTIONS (optional) Additional options to pass to the Qt MOC compiler
#! \param WARNINGS_NO_ERRORS (optional) Do not handle compiler warnings as errors
function(mitk_create_plugin)
# options
set(arg_options
TEST_PLUGIN # Mark this plug-in as a testing plug-in
NO_INSTALL # Don't install this plug-in
- NO_QHP_TRANSFORM
WARNINGS_NO_ERRORS
)
# single value arguments
set(arg_single
EXPORT_DIRECTIVE # (required) TODO: could be generated via CMake as it is done for MITK modules already
)
# multiple value arguments
set(arg_multiple
EXPORTED_INCLUDE_SUFFIXES # (optional) additional public include directories
MODULE_DEPENDS # (optional)
PACKAGE_DEPENDS
TARGET_DEPENDS
DOXYGEN_TAGFILES
MOC_OPTIONS
SUBPROJECTS # deprecated
)
cmake_parse_arguments(_PLUGIN "${arg_options}" "${arg_single}" "${arg_multiple}" ${ARGN})
if(_PLUGIN_TEST_PLUGIN)
set(_PLUGIN_NO_INSTALL 1)
set(is_test_plugin "TEST_PLUGIN")
else()
set(is_test_plugin)
endif()
set(_PLUGIN_MOC_OPTIONS "-DBOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED ${_PLUGIN_MOC_OPTIONS}")
set(PLUGIN_TARGET ${PROJECT_NAME})
mitk_check_module_dependencies(MODULES ${_PLUGIN_MODULE_DEPENDS}
PACKAGES ${_PLUGIN_PACKAGE_DEPENDS}
MISSING_DEPENDENCIES_VAR _missing_deps
MODULE_DEPENDENCIES_VAR _module_deps
PACKAGE_DEPENDENCIES_VAR _package_deps)
if(_missing_deps)
if(NOT MITK_BUILD_ALL_PLUGINS)
message(SEND_ERROR "${PROJECT_NAME} is missing requirements and won't be built. Missing: ${_missing_deps}")
else()
message(STATUS "${PROJECT_NAME} is missing requirements and won't be built. Missing: ${_missing_deps}")
endif()
return()
endif()
foreach(_module_dep ${_PLUGIN_MODULE_DEPENDS})
if(TARGET ${_module_dep})
get_target_property(AUTLOAD_DEP ${_module_dep} MITK_AUTOLOAD_DIRECTORY)
if (AUTLOAD_DEP)
message(SEND_ERROR "Plugin \"${PROJECT_NAME}\" has an invalid dependency on autoload module \"${_module_dep}\". Check MITK_CREATE_PLUGIN usage for \"${PROJECT_NAME}\".")
endif()
endif()
endforeach()
# -------------- All dependencies are resolved ------------------
message(STATUS "Creating CTK plugin ${PROJECT_NAME}")
include(files.cmake)
set(_PLUGIN_CPP_FILES ${CPP_FILES})
set(_PLUGIN_MOC_H_FILES ${MOC_H_FILES})
set(_PLUGIN_UI_FILES ${UI_FILES})
set(_PLUGIN_CACHED_RESOURCE_FILES ${CACHED_RESOURCE_FILES})
set(_PLUGIN_TRANSLATION_FILES ${TRANSLATION_FILES})
set(_PLUGIN_QRC_FILES ${QRC_FILES})
set(_PLUGIN_H_FILES ${H_FILES})
set(_PLUGIN_TXX_FILES ${TXX_FILES})
set(_PLUGIN_DOX_FILES ${DOX_FILES})
set(_PLUGIN_CMAKE_FILES ${CMAKE_FILES} files.cmake)
set(_PLUGIN_FILE_DEPENDENCIES ${FILE_DEPENDENCIES})
if(CTK_PLUGINS_OUTPUT_DIR)
set(_output_dir "${CTK_PLUGINS_OUTPUT_DIR}")
else()
set(_output_dir "")
endif()
# Compute the plugin dependencies
ctkFunctionGetTargetLibraries(_PLUGIN_target_libraries "")
#------------------------------------------------------------#
#------------------ Qt Help support -------------------------#
set(PLUGIN_GENERATED_QCH_FILES )
if(BLUEBERRY_USE_QT_HELP AND
EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/documentation/UserManual")
set(PLUGIN_DOXYGEN_INPUT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/documentation/UserManual")
set(PLUGIN_DOXYGEN_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/documentation/UserManual")
# Create a list of Doxygen tag files from the plug-in dependencies
set(PLUGIN_DOXYGEN_TAGFILES)
foreach(_dep_target ${_PLUGIN_target_libraries})
string(REPLACE _ . _dep ${_dep_target})
get_target_property(_is_imported ${_dep_target} IMPORTED)
if(_is_imported)
get_target_property(_import_loc_debug ${_dep_target} IMPORTED_LOCATION_DEBUG)
get_target_property(_import_loc_release ${_dep_target} IMPORTED_LOCATION_RELEASE)
# There is not necessarily a debug and release build
if(_import_loc_release)
set(_import_loc ${_import_loc_release})
else()
set(_import_loc ${_import_loc_debug})
endif()
get_filename_component(_target_filename "${_import_loc}" NAME)
# on windows there might be a Debug or Release subdirectory
string(REGEX REPLACE "/bin/plugins/(Debug/|Release/)?${_target_filename}" "/Plugins/${_dep}/documentation/UserManual" plugin_tag_dir "${_import_loc}" )
else()
set(plugin_tag_dir "${CMAKE_BINARY_DIR}/Plugins/${_dep}/documentation/UserManual")
endif()
set(_tag_file "${plugin_tag_dir}/${_dep_target}.tag")
if(EXISTS ${_tag_file})
set(PLUGIN_DOXYGEN_TAGFILES "${PLUGIN_DOXYGEN_TAGFILES} \"${_tag_file}=qthelp://${_dep}/bundle/\"")
endif()
endforeach()
if(_PLUGIN_DOXYGEN_TAGFILES)
set(PLUGIN_DOXYGEN_TAGFILES "${PLUGIN_DOXYGEN_TAGFILES} ${_PLUGIN_DOXYGEN_TAGFILES}")
endif()
#message("PLUGIN_DOXYGEN_TAGFILES: ${PLUGIN_DOXYGEN_TAGFILES}")
- if(_PLUGIN_NO_QHP_TRANSFORM)
- set(_use_qhp_xsl 0)
- else()
- set(_use_qhp_xsl 1)
- endif()
- _FUNCTION_CREATE_CTK_QT_COMPRESSED_HELP(PLUGIN_GENERATED_QCH_FILES ${_use_qhp_xsl})
+ _FUNCTION_CREATE_CTK_QT_COMPRESSED_HELP(PLUGIN_GENERATED_QCH_FILES)
list(APPEND _PLUGIN_CACHED_RESOURCE_FILES ${PLUGIN_GENERATED_QCH_FILES})
endif()
#------------------------------------------------------------#
#------------------ Create Plug-in --------------------------#
mitkFunctionOrganizeSources(
SOURCE ${_PLUGIN_CPP_FILES}
HEADER ${_PLUGIN_H_FILES}
TXX ${_PLUGIN_TXX_FILES}
DOC ${_PLUGIN_DOX_FILES}
UI ${_PLUGIN_UI_FILES}
QRC ${_PLUGIN_QRC_FILES} ${_PLUGIN_CACHED_RESOURCE_FILES}
META ${_PLUGIN_META_FILES}
MOC ${MY_MOC_CPP}
GEN_UI ${MY_UI_CPP}
GEN_QRC ${MY_QRC_SRCS}
)
ctkMacroBuildPlugin(
NAME ${PLUGIN_TARGET}
EXPORT_DIRECTIVE ${_PLUGIN_EXPORT_DIRECTIVE}
SRCS ${_PLUGIN_CPP_FILES} ${_PLUGIN_H_FILES} ${CORRESPONDING__H_FILES} ${GLOBBED__H_FILES}
MOC_SRCS ${_PLUGIN_MOC_H_FILES}
MOC_OPTIONS ${_PLUGIN_MOC_OPTIONS}
UI_FORMS ${_PLUGIN_UI_FILES}
EXPORTED_INCLUDE_SUFFIXES ${_PLUGIN_EXPORTED_INCLUDE_SUFFIXES}
RESOURCES ${_PLUGIN_QRC_FILES}
TARGET_LIBRARIES ${_PLUGIN_target_libraries}
CACHED_RESOURCEFILES ${_PLUGIN_CACHED_RESOURCE_FILES}
TRANSLATIONS ${_PLUGIN_TRANSLATION_FILES}
OUTPUT_DIR ${_output_dir}
NO_INSTALL # we install the plug-in ourselves
${is_test_plugin}
)
mitk_use_modules(TARGET ${PLUGIN_TARGET}
MODULES ${_PLUGIN_MODULE_DEPENDS}
PACKAGES ${_PLUGIN_PACKAGE_DEPENDS}
)
if(_PLUGIN_TARGET_DEPENDS)
target_link_libraries(${PLUGIN_TARGET} ${_PLUGIN_TARGET_DEPENDS})
endif()
set_property(TARGET ${PLUGIN_TARGET} APPEND PROPERTY COMPILE_DEFINITIONS US_MODULE_NAME=${PLUGIN_TARGET})
set_property(TARGET ${PLUGIN_TARGET} PROPERTY US_MODULE_NAME ${PLUGIN_TARGET})
if(NOT CMAKE_CURRENT_SOURCE_DIR MATCHES "^${CMAKE_SOURCE_DIR}/.*")
foreach(MITK_EXTENSION_DIR ${MITK_ABSOLUTE_EXTENSION_DIRS})
if("${CMAKE_CURRENT_SOURCE_DIR}/" MATCHES "^${MITK_EXTENSION_DIR}/.*")
get_filename_component(MITK_EXTENSION_ROOT_FOLDER "${MITK_EXTENSION_DIR}" NAME)
set_property(TARGET ${PLUGIN_TARGET} PROPERTY FOLDER "${MITK_EXTENSION_ROOT_FOLDER}/Plugins")
break()
endif()
endforeach()
else()
set_property(TARGET ${PLUGIN_TARGET} PROPERTY FOLDER "${MITK_ROOT_FOLDER}/Plugins")
endif()
set(plugin_c_flags)
set(plugin_cxx_flags)
if(NOT _PLUGIN_WARNINGS_NO_ERRORS)
if(MSVC_VERSION)
mitkFunctionCheckCAndCXXCompilerFlags("/WX" plugin_c_flags plugin_cxx_flags)
else()
mitkFunctionCheckCAndCXXCompilerFlags(-Werror plugin_c_flags plugin_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=c++0x-static-nonintegral-init" plugin_c_flags plugin_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=static-member-init" plugin_c_flags plugin_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=unknown-warning" plugin_c_flags plugin_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=gnu" plugin_c_flags plugin_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=cast-function-type" plugin_c_flags plugin_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=inconsistent-missing-override" plugin_c_flags plugin_cxx_flags)
mitkFunctionCheckCAndCXXCompilerFlags("-Wno-error=deprecated-declarations" plugin_c_flags plugin_cxx_flags)
endif()
endif()
if(plugin_c_flags)
string(REPLACE " " ";" plugin_c_flags "${plugin_c_flags}")
target_compile_options(${PLUGIN_TARGET} PRIVATE ${plugin_c_flags})
endif()
if(plugin_cxx_flags)
string(REPLACE " " ";" plugin_cxx_flags "${plugin_cxx_flags}")
target_compile_options(${PLUGIN_TARGET} PRIVATE ${plugin_cxx_flags})
endif()
if(_PLUGIN_TEST_PLUGIN)
find_package(CppUnit REQUIRED)
target_include_directories(${PLUGIN_TARGET} PRIVATE ${CppUnit_INCLUDE_DIRS})
target_link_libraries(${PLUGIN_TARGET} PRIVATE ${CppUnit_LIBRARIES})
endif()
if(TARGET MitkLog)
target_link_libraries(${PLUGIN_TARGET} PRIVATE MitkLog)
endif()
set(_PLUGIN_META_FILES "${CMAKE_CURRENT_SOURCE_DIR}/manifest_headers.cmake")
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/plugin.xml")
list(APPEND _PLUGIN_META_FILES "${CMAKE_CURRENT_SOURCE_DIR}/plugin.xml")
endif()
set(PLUGIN_TARGET ${PLUGIN_TARGET} PARENT_SCOPE)
#------------------------------------------------------------#
#------------------ Installer support -----------------------#
if(NOT _PLUGIN_NO_INSTALL)
set(install_directories "")
if(NOT MACOSX_BUNDLE_NAMES)
set(install_directories bin/plugins)
else(NOT MACOSX_BUNDLE_NAMES)
foreach(bundle_name ${MACOSX_BUNDLE_NAMES})
list(APPEND install_directories ${bundle_name}.app/Contents/MacOS/plugins)
endforeach(bundle_name)
endif(NOT MACOSX_BUNDLE_NAMES)
foreach(install_subdir ${install_directories})
mitkFunctionInstallCTKPlugin(TARGETS ${PLUGIN_TARGET}
DESTINATION ${install_subdir})
endforeach()
set(_autoload_targets )
foreach(_dependency ${_module_deps})
get_target_property(_dep_autoloads ${_dependency} MITK_AUTOLOAD_TARGETS)
if (_dep_autoloads)
list(APPEND _autoload_targets ${_dep_autoloads})
endif()
endforeach()
# The MITK_AUTOLOAD_TARGETS property is used in the mitkFunctionInstallAutoLoadModules
# macro which expects a list of plug-in targets.
if (_autoload_targets)
list(REMOVE_DUPLICATES _autoload_targets)
set_target_properties(${PLUGIN_TARGET} PROPERTIES MITK_AUTOLOAD_TARGETS "${_autoload_targets}")
endif()
endif()
endfunction()
-function(_FUNCTION_CREATE_CTK_QT_COMPRESSED_HELP qch_file use_xsl)
+function(_FUNCTION_CREATE_CTK_QT_COMPRESSED_HELP qch_file)
set(_manifest_path "${CMAKE_CURRENT_SOURCE_DIR}/manifest_headers.cmake")
if(NOT EXISTS ${_manifest_path})
message(FATAL_ERROR "${_manifest_path} not found")
endif()
include(${_manifest_path})
string(REPLACE "_" "." Plugin-SymbolicName "${PLUGIN_TARGET}")
configure_file(${MITK_SOURCE_DIR}/Documentation/doxygen_plugin_manual.conf.in
${PLUGIN_DOXYGEN_OUTPUT_DIR}/doxygen.conf
)
- set(_qhp_xsl_file "${MITK_SOURCE_DIR}/Documentation/qhp_toc.xsl")
set(_generated_qhp_file "${PLUGIN_DOXYGEN_OUTPUT_DIR}/html/index.qhp")
- set(_transformed_qhp_file "${PLUGIN_DOXYGEN_OUTPUT_DIR}/html/${PLUGIN_TARGET}.qhp")
set(${qch_file} "${CMAKE_CURRENT_BINARY_DIR}/resources/${PLUGIN_TARGET}.qch")
- set(_xsl_command )
- if(use_xsl)
- set(_xsl_command COMMAND ${QT_XMLPATTERNS_EXECUTABLE} ${_qhp_xsl_file} ${_generated_qhp_file} -output ${_transformed_qhp_file})
- endif()
-
file(GLOB _file_dependencies "${PLUGIN_DOXYGEN_INPUT_DIR}/*")
add_custom_command(OUTPUT ${${qch_file}}
# Generate a Qt help project (index.qhp) with doxygen
COMMAND ${DOXYGEN_EXECUTABLE} ${PLUGIN_DOXYGEN_OUTPUT_DIR}/doxygen.conf
- # Use a XSL transformation to get rid of the top-level entry
- ${_xsl_command}
# Generate the final Qt compressed help file (.qch)
- COMMAND ${QT_HELPGENERATOR_EXECUTABLE} ${_transformed_qhp_file} -o ${${qch_file}}
+ COMMAND ${QT_HELPGENERATOR_EXECUTABLE} ${_generated_qhp_file} -o ${${qch_file}}
DEPENDS ${PLUGIN_DOXYGEN_OUTPUT_DIR}/doxygen.conf ${_file_dependencies}
)
#set_source_files_properties(${qch_file} PROPERTIES GENERATED 1)
set(${qch_file} ${${qch_file}} PARENT_SCOPE)
endfunction()
function(MACRO_CREATE_MITK_CTK_PLUGIN)
message(SEND_ERROR "The function MACRO_CREATE_MITK_CTK_PLUGIN was renamed to mitk_create_plugin in MITK 2015.05.")
endfunction()
diff --git a/CMake/mitkFunctionGetLibrarySearchPaths.cmake b/CMake/mitkFunctionGetLibrarySearchPaths.cmake
index a1fe3a86bc..447a729829 100644
--- a/CMake/mitkFunctionGetLibrarySearchPaths.cmake
+++ b/CMake/mitkFunctionGetLibrarySearchPaths.cmake
@@ -1,201 +1,196 @@
#! Helper function that gets all library search paths.
#!
#! Usage:
#!
#! mitkFunctionGetLibrarySearchPaths(search_path intermediate_dir [DEBUG|MINSIZEREL|RELWITHDEBINFO])
#!
#!
#! The function creates the variable ${search_path}. The variable intermediate_dir contains
#! paths that should be added to the search_path but should not be checked for existance,
#! because the are not yet created. The option DEBUG, MINSIZEREL or RELWITHDEBINFO can be used to indicate that
#! not the paths for release configuration are requested but the debug, min size release or "release with debug info"
#! paths.
#!
function(mitkFunctionGetLibrarySearchPaths search_path intermediate_dir)
cmake_parse_arguments(PARSE_ARGV 2 GLS "RELEASE;DEBUG;MINSIZEREL;RELWITHDEBINFO" "" "")
set(_dir_candidates
"${MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY}"
"${MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY}/plugins"
"${MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY}"
"${MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY}/plugins"
)
if(MITK_EXTERNAL_PROJECT_PREFIX)
list(APPEND _dir_candidates
"${MITK_EXTERNAL_PROJECT_PREFIX}/bin"
"${MITK_EXTERNAL_PROJECT_PREFIX}/lib"
)
endif()
- # Determine the Qt5 library installation prefix
- set(_qmake_location )
- if(MITK_USE_Qt5 AND TARGET ${Qt5Core_QMAKE_EXECUTABLE})
- get_property(_qmake_location TARGET ${Qt5Core_QMAKE_EXECUTABLE}
- PROPERTY IMPORT_LOCATION)
- endif()
- if(_qmake_location)
- if(NOT _qt_install_libs)
- if(WIN32)
- execute_process(COMMAND ${_qmake_location} -query QT_INSTALL_BINS
- OUTPUT_VARIABLE _qt_install_libs
- OUTPUT_STRIP_TRAILING_WHITESPACE)
- else()
- execute_process(COMMAND ${_qmake_location} -query QT_INSTALL_LIBS
- OUTPUT_VARIABLE _qt_install_libs
- OUTPUT_STRIP_TRAILING_WHITESPACE)
- endif()
- file(TO_CMAKE_PATH "${_qt_install_libs}" _qt_install_libs)
- set(_qt_install_libs ${_qt_install_libs} CACHE INTERNAL "Qt library installation prefix" FORCE)
- endif()
- if(_qt_install_libs)
- list(APPEND _dir_candidates ${_qt_install_libs})
- endif()
- elseif(MITK_USE_Qt5)
- message(WARNING "The qmake executable could not be found.")
- endif()
-
get_property(_additional_paths GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS)
if(TARGET OpenSSL::SSL)
if(GLS_DEBUG)
get_target_property(_openssl_location OpenSSL::SSL IMPORTED_LOCATION_DEBUG)
else()
get_target_property(_openssl_location OpenSSL::SSL IMPORTED_LOCATION_RELEASE)
endif()
if(_openssl_location)
get_filename_component(_openssl_location ${_openssl_location} DIRECTORY)
set(_openssl_location "${_openssl_location}/../../bin")
if(EXISTS ${_openssl_location})
get_filename_component(_openssl_location ${_openssl_location} ABSOLUTE)
list(APPEND _dir_candidates ${_openssl_location})
endif()
endif()
endif()
if(MITK_USE_HDF5)
FIND_PACKAGE(HDF5 COMPONENTS C HL NO_MODULE REQUIRED shared)
get_target_property(_location hdf5-shared LOCATION)
get_filename_component(_location ${_location} PATH)
list(APPEND _additional_paths ${_location})
# This is a work-around. The hdf5-config.cmake file is not robust enough
# to be included several times via find_pakcage calls.
set(HDF5_LIBRARIES ${HDF5_LIBRARIES} PARENT_SCOPE)
endif()
if(_additional_paths)
list(APPEND _dir_candidates ${_additional_paths})
endif()
# The code below is sub-optimal. It makes assumptions about
# the structure of the build directories, pointed to by
# the *_DIR variables. Instead, we should rely on package
# specific "LIBRARY_DIRS" variables, if they exist.
if(WIN32)
list(APPEND _dir_candidates "${ITK_DIR}/bin")
endif()
if(MITK_USE_MatchPoint)
if(WIN32)
list(APPEND _dir_candidates "${MatchPoint_DIR}/bin")
else()
list(APPEND _dir_candidates "${MatchPoint_DIR}/lib")
endif()
endif()
# If OpenCV is built within the MITK superbuild set the binary directory
# according to the lib path provided by OpenCV.
# In the case where an external OpenCV is provided use the binary directory
# of this OpenCV directory
if(MITK_USE_OpenCV)
if(WIN32)
if (EXISTS ${OpenCV_LIB_PATH})
list(APPEND _dir_candidates "${OpenCV_LIB_PATH}/../bin") # OpenCV is built in superbuild
else()
list(APPEND _dir_candidates "${OpenCV_DIR}/bin") # External OpenCV build is used
endif()
endif()
endif()
if(MITK_USE_Python3)
list(APPEND _dir_candidates "${CTK_DIR}/CMakeExternals/Install/bin")
get_filename_component(_python_dir "${Python3_EXECUTABLE}" DIRECTORY)
list(APPEND _dir_candidates "${_python_dir}")
endif()
if(MITK_USE_TOF_PMDO3 OR MITK_USE_TOF_PMDCAMCUBE OR MITK_USE_TOF_PMDCAMBOARD)
list(APPEND _dir_candidates "${MITK_PMD_SDK_DIR}/plugins" "${MITK_PMD_SDK_DIR}/bin")
endif()
if(MITK_USE_CTK)
list(APPEND _dir_candidates "${CTK_LIBRARY_DIRS}")
foreach(_ctk_library ${CTK_LIBRARIES})
if(${_ctk_library}_LIBRARY_DIRS)
list(APPEND _dir_candidates "${${_ctk_library}_LIBRARY_DIRS}")
endif()
endforeach()
endif()
if(MITK_USE_BLUEBERRY)
if(DEFINED CTK_PLUGIN_RUNTIME_OUTPUT_DIRECTORY)
if(IS_ABSOLUTE "${CTK_PLUGIN_RUNTIME_OUTPUT_DIRECTORY}")
list(APPEND _dir_candidates "${CTK_PLUGIN_RUNTIME_OUTPUT_DIRECTORY}")
else()
list(APPEND _dir_candidates "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${CTK_PLUGIN_RUNTIME_OUTPUT_DIRECTORY}")
endif()
endif()
endif()
if(MITK_LIBRARY_DIRS)
list(APPEND _dir_candidates ${MITK_LIBRARY_DIRS})
endif()
###################################################################
#get the search paths added by the mitkFunctionAddLibrarySearchPath
file(GLOB _additional_path_info_files "${MITK_SUPERBUILD_BINARY_DIR}/MITK-AdditionalLibPaths/*.cmake")
foreach(_additional_path_info_file ${_additional_path_info_files})
get_filename_component(_additional_info_name ${_additional_path_info_file} NAME_WE)
include(${_additional_path_info_file})
if(GLS_DEBUG)
list(APPEND _dir_candidates ${${_additional_info_name}_ADDITIONAL_DEBUG_LIBRARY_SEARCH_PATHS})
elseif(GLS_MINSIZEREL)
list(APPEND _dir_candidates ${${_additional_info_name}_ADDITIONAL_MINSIZEREL_LIBRARY_SEARCH_PATHS})
elseif(GLS_RELWITHDEBINFO)
list(APPEND _dir_candidates ${${_additional_info_name}_ADDITIONAL_RELWITHDEBINFO_LIBRARY_SEARCH_PATHS})
else() #Release
list(APPEND _dir_candidates ${${_additional_info_name}_ADDITIONAL_RELEASE_LIBRARY_SEARCH_PATHS})
endif()
endforeach(_additional_path_info_file ${_additional_path_info_files})
###############################################
#sanitize all candidates and compile final list
list(REMOVE_DUPLICATES _dir_candidates)
set(_search_dirs )
foreach(_dir ${_dir_candidates})
if(EXISTS "${_dir}/${intermediate_dir}")
list(APPEND _search_dirs "${_dir}/${intermediate_dir}")
else()
list(APPEND _search_dirs "${_dir}")
endif()
endforeach()
+ # Determine the Qt6 library installation prefix
+ if(QT_QMAKE_EXECUTABLE)
+ if(NOT _qt_install_libs)
+ if(WIN32)
+ execute_process(COMMAND ${QT_QMAKE_EXECUTABLE} -query QT_INSTALL_BINS
+ OUTPUT_VARIABLE _qt_install_libs
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ else()
+ execute_process(COMMAND ${QT_QMAKE_EXECUTABLE} -query QT_INSTALL_LIBS
+ OUTPUT_VARIABLE _qt_install_libs
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ endif()
+ file(TO_CMAKE_PATH "${_qt_install_libs}" _qt_install_libs)
+ set(_qt_install_libs ${_qt_install_libs} CACHE INTERNAL "Qt library installation prefix" FORCE)
+ endif()
+ if(_qt_install_libs)
+ list(APPEND _search_dirs ${_qt_install_libs})
+ endif()
+ elseif(MITK_USE_Qt6)
+ message(WARNING "The qmake executable could not be found.")
+ endif()
+
# Special handling for "internal" search dirs. The intermediate directory
# might not have been created yet, so we can't check for its existence.
# Hence we just add it for Windows without checking.
set(_internal_search_dirs "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/plugins")
if(WIN32)
foreach(_dir ${_internal_search_dirs})
set(_search_dirs "${_dir}/${intermediate_dir}" ${_search_dirs})
endforeach()
else()
set(_search_dirs ${_internal_search_dirs} ${_search_dirs})
endif()
list(REMOVE_DUPLICATES _search_dirs)
set(${search_path} ${_search_dirs} PARENT_SCOPE)
endfunction()
diff --git a/CMake/mitkFunctionUseModules.cmake b/CMake/mitkFunctionUseModules.cmake
index c1bec4eae5..d2a262f9a8 100644
--- a/CMake/mitkFunctionUseModules.cmake
+++ b/CMake/mitkFunctionUseModules.cmake
@@ -1,169 +1,169 @@
function(_mitk_parse_package_args)
set(package_list ${ARGN})
set(PUBLIC_PACKAGE_NAMES )
set(PRIVATE_PACKAGE_NAMES )
set(INTERFACE_PACKAGE_NAMES )
set(_package_visibility PRIVATE)
foreach(_package ${package_list})
if(_package STREQUAL "PUBLIC" OR _package STREQUAL "PRIVATE" OR _package STREQUAL "INTERFACE")
set(_package_visibility ${_package})
else()
list(APPEND packages ${_package})
set(_package_name )
set(_package_components_list )
string(REPLACE "|" ";" _package_list ${_package})
if("${_package_list}" STREQUAL "${_package}")
set(_package_name ${_package})
else()
list(GET _package_list 0 _package_name)
list(GET _package_list 1 _package_components)
string(REPLACE "+" ";" _package_components_list "${_package_components}")
if(NOT _package_name OR NOT _package_components)
message(SEND_ERROR "PACKAGE argument syntax wrong. ${_package} is not of the form PACKAGE[|COMPONENT1[+COMPONENT2]...]")
endif()
endif()
list(APPEND ${_package_visibility}_PACKAGE_NAMES ${_package_name})
list(APPEND ${_package_visibility}_${_package_name}_REQUIRED_COMPONENTS ${_package_components_list})
endif()
endforeach()
# remove duplicates and set package components in parent scope
foreach(_package_visibility PUBLIC PRIVATE INTERFACE)
foreach(_package_name ${${_package_visibility}_PACKAGE_NAMES})
if(${_package_visibility}_${_package_name}_REQUIRED_COMPONENTS)
list(REMOVE_DUPLICATES ${_package_visibility}_${_package_name}_REQUIRED_COMPONENTS)
endif()
set(${_package_visibility}_${_package_name}_REQUIRED_COMPONENTS ${${_package_visibility}_${_package_name}_REQUIRED_COMPONENTS} PARENT_SCOPE)
endforeach()
endforeach()
set(PUBLIC_PACKAGE_NAMES ${PUBLIC_PACKAGE_NAMES} PARENT_SCOPE)
set(PRIVATE_PACKAGE_NAMES ${PRIVATE_PACKAGE_NAMES} PARENT_SCOPE)
set(INTERFACE_PACKAGE_NAMES ${INTERFACE_PACKAGE_NAMES} PARENT_SCOPE)
set(PACKAGE_NAMES ${PUBLIC_PACKAGE_NAMES} ${PRIVATE_PACKAGE_NAMES} ${INTERFACE_PACKAGE_NAMES} PARENT_SCOPE)
endfunction()
function(_include_package_config pkg_config_file)
# wrap the inclusion of the MITK_<pkg>_Config.cmake file in a
# function to create a scope for its variables; this allows
# multiple inclusions of the file in the parent scope
include(${pkg_config_file})
set(ALL_INCLUDE_DIRECTORIES ${ALL_INCLUDE_DIRECTORIES} PARENT_SCOPE)
set(ALL_LINK_DIRECTORIES ${ALL_LINK_DIRECTORIES} PARENT_SCOPE)
set(ALL_LIBRARIES ${ALL_LIBRARIES} PARENT_SCOPE)
set(ALL_COMPILE_DEFINITIONS ${ALL_COMPILE_DEFINITIONS} PARENT_SCOPE)
set(ALL_COMPILE_OPTIONS ${ALL_COMPILE_OPTIONS} PARENT_SCOPE)
endfunction()
#! This CMake function sets up the necessary include directories,
#! linker dependencies, and compile flags for a given target which
#! depends on a set of MITK modules or packages.
#!
#! A package argument is of the form
#!
#! [PUBLIC|PRIVATE|INTERFACE] PACKAGE[|COMPONENT1[+COMPONENT2]...]
#!
#! where PACKAGE is the package name (e.g. VTK) and components are
#! the names of required package components or libraries.
#!
#! If a dependency is not available, an error is thrown.
function(mitk_use_modules)
set(_macro_params
TARGET # The target name (required)
)
set(_macro_multiparams
MODULES # MITK modules which the given TARGET uses
PACKAGES # MITK packages which the given TARGET uses
)
set(_macro_options )
cmake_parse_arguments(USE "${_macro_options}" "${_macro_params}" "${_macro_multiparams}" ${ARGN})
# Sanity checks
if(NOT USE_TARGET)
message(SEND_ERROR "Required TARGET argument missing.")
elseif(NOT TARGET ${USE_TARGET})
message(SEND_ERROR "The given TARGET argument ${USE_TARGET} is not a valid target")
endif()
set(depends ${USE_MODULES})
set(package_depends ${USE_PACKAGES})
if(depends)
# Iterate over all module dependencies
foreach(dependency ${depends})
if(TARGET ${dependency} AND NOT MODULE_IS_DEPRECATED)
get_target_property(_is_interface_lib ${dependency} TYPE)
if(NOT _is_interface_lib)
get_target_property(_dependency_deprecated_since ${dependency} MITK_MODULE_DEPRECATED_SINCE)
if(_dependency_deprecated_since)
message(WARNING "Module ${dependency} is deprecated since ${_dependency_deprecated_since}")
endif()
endif()
endif()
endforeach()
target_link_libraries(${USE_TARGET} PUBLIC ${depends})
endif()
# Parse package dependencies
if(package_depends)
_mitk_parse_package_args(${package_depends})
- # Some package config files like MITK_Qt5_Config.cmake rely on a
+ # Some package config files like MITK_Qt6_Config.cmake rely on a
# properly set "MODULE_NAME" variable for the current target.
set(MODULE_NAME ${USE_TARGET})
# Read all package information
foreach(_package_visibility INTERFACE PUBLIC PRIVATE)
foreach(_package ${${_package_visibility}_PACKAGE_NAMES})
set(ALL_INCLUDE_DIRECTORIES)
set(ALL_LINK_DIRECTORIES)
set(ALL_LIBRARIES)
set(ALL_COMPILE_DEFINITIONS)
set(ALL_COMPILE_OPTIONS)
set(${_package}_REQUIRED_COMPONENTS_BY_MODULE ${${_package_visibility}_${_package}_REQUIRED_COMPONENTS})
set(_package_found 0)
foreach(dir ${MODULES_PACKAGE_DEPENDS_DIRS})
if((NOT DEFINED MITK_USE_${_package} OR MITK_USE_${_package}) AND EXISTS "${dir}/MITK_${_package}_Config.cmake")
_include_package_config("${dir}/MITK_${_package}_Config.cmake")
set(_package_found 1)
break()
endif()
endforeach()
if(_package_found)
if(ALL_INCLUDE_DIRECTORIES)
list(REMOVE_DUPLICATES ALL_INCLUDE_DIRECTORIES)
target_include_directories(${USE_TARGET} SYSTEM ${_package_visibility} ${ALL_INCLUDE_DIRECTORIES})
endif()
if(ALL_LINK_DIRECTORIES)
list(REMOVE_DUPLICATES ALL_LINK_DIRECTORIES)
target_link_directories(${USE_TARGET} ${_package_visibility} ${ALL_LINK_DIRECTORIES})
endif()
if(ALL_LIBRARIES)
# Don't remove "duplicats" because ALL_LIBRARIES may be of the form:
# "general;bla;debug;blad;general;foo;debug;food"
target_link_libraries(${USE_TARGET} ${_package_visibility} ${ALL_LIBRARIES})
endif()
if(ALL_COMPILE_DEFINITIONS)
list(REMOVE_DUPLICATES ALL_COMPILE_DEFINITIONS)
# Compile definitions are always added "PRIVATE" to avoid multiple definitions
# on the command line due to transitive and direct dependencies adding the
# same definitions.
target_compile_definitions(${USE_TARGET} PRIVATE ${ALL_COMPILE_DEFINITIONS})
endif()
if(ALL_COMPILE_OPTIONS)
list(REMOVE_DUPLICATES ALL_COMPILE_OPTIONS)
target_compile_options(${USE_TARGET} ${_package_visibility} ${ALL_COMPILE_OPTIONS})
endif()
else()
message(SEND_ERROR "Missing package: ${_package}")
endif()
endforeach()
endforeach()
endif()
endfunction()
diff --git a/CMake/mitkInstallRules.cmake b/CMake/mitkInstallRules.cmake
index 062879f3ff..f9a4271830 100644
--- a/CMake/mitkInstallRules.cmake
+++ b/CMake/mitkInstallRules.cmake
@@ -1,177 +1,176 @@
# Install MITK icon and logo
MITK_INSTALL(FILES
"${MITK_SOURCE_DIR}/mitk.ico"
"${MITK_SOURCE_DIR}/mitk.bmp")
# Helper vars
if(WIN32)
set(_prefix "")
set(_ext ".dll")
elseif(UNIX)
set(_prefix "lib")
if(APPLE)
set(_ext ".dylib")
else()
set(_ext ".so")
endif()
endif()
# Install MITK executables including auto-load modules
get_property(_mitk_executable_targets GLOBAL PROPERTY MITK_EXECUTABLE_TARGETS)
if(_mitk_executable_targets)
get_property(_mitk_module_targets GLOBAL PROPERTY MITK_MODULE_TARGETS)
foreach(_mitk_module_target ${_mitk_module_targets})
if(TARGET ${_mitk_module_target})
get_target_property(_mitk_autoload_targets ${_mitk_module_target} MITK_AUTOLOAD_TARGETS)
if (_mitk_autoload_targets)
foreach(_mitk_autoload_target ${_mitk_autoload_targets})
get_target_property(_mitk_autoload_directory ${_mitk_autoload_target} MITK_AUTOLOAD_DIRECTORY)
if (_mitk_autoload_directory)
if(WIN32)
get_target_property(_target_location ${_mitk_autoload_target} RUNTIME_OUTPUT_DIRECTORY)
else()
get_target_property(_target_location ${_mitk_autoload_target} LIBRARY_OUTPUT_DIRECTORY)
endif()
if(NOT CMAKE_CFG_INTDIR STREQUAL ".")
set(_target_location "${_target_location}/Release")
endif()
set(_mitk_autoload_target_filename "${_prefix}${_mitk_autoload_target}${_ext}")
set(_mitk_autoload_target_filepath "${_target_location}/${_mitk_autoload_target_filename}")
set(_install_DESTINATION "${_mitk_autoload_directory}")
MITK_INSTALL(FILES ${_mitk_autoload_target_filepath})
if(UNIX AND NOT APPLE)
install(CODE "file(RPATH_REMOVE FILE \"\${CMAKE_INSTALL_PREFIX}/bin/${_mitk_autoload_directory}/${_mitk_autoload_target_filename}\")")
endif()
endif()
endforeach()
endif()
endif()
endforeach()
set(_install_DESTINATION "")
foreach(_mitk_executable_target ${_mitk_executable_targets})
get_target_property(_no_install ${_mitk_executable_target} NO_INSTALL)
if(_no_install)
continue()
endif()
MITK_INSTALL_TARGETS(EXECUTABLES ${_mitk_executable_target} GLOB_PLUGINS)
if(UNIX AND NOT APPLE)
install(PROGRAMS "${MITK_SOURCE_DIR}/CMake/RunInstalledApp.sh" DESTINATION "." RENAME "${_mitk_executable_target}.sh")
elseif(WIN32)
get_target_property(_win32_exec ${_mitk_executable_target} WIN32_EXECUTABLE)
if(_win32_exec)
install(PROGRAMS "${MITK_SOURCE_DIR}/CMake/RunInstalledWin32App.bat" DESTINATION "." RENAME "${_mitk_executable_target}.bat")
else()
install(PROGRAMS "${MITK_SOURCE_DIR}/CMake/RunInstalledApp.bat" DESTINATION "." RENAME "${_mitk_executable_target}.bat")
endif()
endif()
endforeach()
endif()
# Install PythonQt
if(MITK_USE_Python3 AND PythonQt_DIR)
set(_python_qt_lib "${PythonQt_DIR}/")
if(WIN32)
set(_python_qt_lib "${_python_qt_lib}bin")
else()
set(_python_qt_lib "${_python_qt_lib}lib")
endif()
set(_python_qt_lib "${_python_qt_lib}/${_prefix}PythonQt${_ext}")
MITK_INSTALL(FILES ${_python_qt_lib})
endif()
# Install Qt plugins
-if(MITK_USE_Qt5)
- get_property(_qmake_location TARGET ${Qt5Core_QMAKE_EXECUTABLE} PROPERTY IMPORT_LOCATION)
- get_filename_component(_qmake_path ${_qmake_location} DIRECTORY)
+if(MITK_USE_Qt6)
+ get_filename_component(_qmake_path "${QT_QMAKE_EXECUTABLE}" DIRECTORY)
set(_install_DESTINATION "plugins/sqldrivers")
MITK_INSTALL(FILES "${_qmake_path}/../plugins/sqldrivers/${_prefix}qsqlite${_ext}")
set(_install_DESTINATION "plugins/imageformats")
MITK_INSTALL(FILES "${_qmake_path}/../plugins/imageformats/${_prefix}qsvg${_ext}")
set(_install_DESTINATION "plugins/iconengines")
MITK_INSTALL(FILES "${_qmake_path}/../plugins/iconengines/${_prefix}qsvgicon${_ext}")
# Install platform-specific Qt plugins
set(_install_DESTINATION "plugins/platforms")
if(WIN32)
MITK_INSTALL(FILES "${_qmake_path}/../plugins/platforms/qwindows.dll")
elseif(APPLE)
MITK_INSTALL(FILES "${_qmake_path}/../plugins/platforms/libqcocoa.dylib")
elseif(UNIX)
MITK_INSTALL(FILES "${_qmake_path}/../plugins/platforms/libqxcb.so")
set(_install_DESTINATION "plugins/xcbglintegrations")
MITK_INSTALL(FILES "${_qmake_path}/../plugins/xcbglintegrations/libqxcb-glx-integration.so")
endif()
# Install platform-specific Qt styles
set(_install_DESTINATION "plugins/styles")
if(WIN32)
MITK_INSTALL(FILES "${_qmake_path}/../plugins/styles/qwindowsvistastyle.dll")
elseif(APPLE)
MITK_INSTALL(FILES "${_qmake_path}/../plugins/styles/libqmacstyle.dylib")
endif()
# Install Qt WebEngine
if(APPLE)
set(_install_DESTINATION "../Frameworks/QtWebEngineCore.framework")
get_filename_component(_real_path "${_qmake_path}/../lib/QtWebEngineCore.framework/Helpers" REALPATH)
MITK_INSTALL(DIRECTORY ${_real_path} USE_SOURCE_PERMISSIONS)
# Translations are included in the Resources directory of
# QtWebEngineCore.framework and are installed by default.
else()
set(_install_DESTINATION "")
if(WIN32)
MITK_INSTALL(PROGRAMS "${_qmake_path}/QtWebEngineProcess.exe")
elseif(UNIX)
MITK_INSTALL(PROGRAMS "${_qmake_path}/../libexec/QtWebEngineProcess")
endif()
# make sure resources and translations exist and try system location as well
if(EXISTS "${_qmake_path}/../resources")
MITK_INSTALL(DIRECTORY "${_qmake_path}/../resources")
- elseif(EXISTS "/usr/share/qt5/resources")
- MITK_INSTALL(DIRECTORY "/usr/share/qt5/resources")
+ elseif(EXISTS "/usr/share/qt6/resources")
+ MITK_INSTALL(DIRECTORY "/usr/share/qt6/resources")
else()
message(WARNING "No webengine resources found!")
endif()
set(_install_DESTINATION "translations")
if(EXISTS "${_qmake_path}/../translations/qtwebengine_locales")
MITK_INSTALL(DIRECTORY "${_qmake_path}/../translations/qtwebengine_locales")
- elseif(EXISTS "/usr/share/qt5/translations/qtwebengine_locales")
- MITK_INSTALL(DIRECTORY "/usr/share/qt5/translations/qtwebengine_locales")
+ elseif(EXISTS "/usr/share/qt6/translations/qtwebengine_locales")
+ MITK_INSTALL(DIRECTORY "/usr/share/qt6/translations/qtwebengine_locales")
else()
message(WARNING "No webengine translations found!")
endif()
endif()
endif()
set(_install_DESTINATION "")
# Install MatchPoint binaries that are not auto-detected
if(MITK_USE_MatchPoint)
MITK_INSTALL(DIRECTORY "${MITK_EXTERNAL_PROJECT_PREFIX}/bin/" FILES_MATCHING PATTERN "MapUtilities*")
MITK_INSTALL(DIRECTORY "${MITK_EXTERNAL_PROJECT_PREFIX}/bin/" FILES_MATCHING PATTERN "MapAlgorithms*")
endif()
# IMPORTANT: Restore default install destination! Do not edit this file beyond this line!
set(_install_DESTINATION "")
diff --git a/CMake/mitkMacroInstallHelperApp.cmake b/CMake/mitkMacroInstallHelperApp.cmake
index ddfe252c9c..e27c3db629 100644
--- a/CMake/mitkMacroInstallHelperApp.cmake
+++ b/CMake/mitkMacroInstallHelperApp.cmake
@@ -1,74 +1,74 @@
#! MITK specific cross plattform install macro
#!
#! Usage: MITK_INSTALL_HELPER_APP(target1 [target2] ....)
#!
macro(MITK_INSTALL_HELPER_APP)
cmake_parse_arguments(_install "GLOB_PLUGINS" "" "TARGETS;EXECUTABLES;PLUGINS;LIBRARY_DIRS" ${ARGN})
list(APPEND _install_TARGETS ${_install_DEFAULT_ARGS})
# TODO: how to supply to correct intermediate directory??
# CMAKE_CFG_INTDIR is not expanded to actual values inside the install(CODE "...") macro ...
set(intermediate_dir .)
if(WIN32)
set(intermediate_dir Release)
endif()
mitkFunctionGetLibrarySearchPaths(DIRS ${intermediate_dir})
if(APPLE)
list(APPEND DIRS "/usr/lib")
endif(APPLE)
foreach(_target ${_install_EXECUTABLES})
set(_qt_conf_install_dirs "")
set(_target_locations "")
get_filename_component(_target_name ${_target} NAME)
if(APPLE)
if(NOT MACOSX_BUNDLE_NAMES)
set(_qt_conf_install_dirs bin)
set(_target_locations bin/${_target_name})
install(PROGRAMS ${_target} 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/${_target_name})
list(APPEND _target_locations ${_current_target_location})
install(PROGRAMS ${_target} DESTINATION ${bundle_name}.app/Contents/MacOS/)
endforeach()
endif(NOT MACOSX_BUNDLE_NAMES)
else()
set(_target_location bin/${_target_name})
set(_qt_conf_install_dirs bin)
install(PROGRAMS ${_target} DESTINATION bin)
if(UNIX AND NOT WIN32)
# Remove the rpath from helper applications. We assume that all dependencies
# are installed into the same location as the helper application.
install(CODE "file(RPATH_REMOVE
FILE \"\${CMAKE_INSTALL_PREFIX}/${_target_location}\")")
endif()
endif()
foreach(_target_location ${_target_locations})
_fixup_target()
endforeach(_target_location)
#--------------------------------------------------------------------------------
# install a qt.conf file
# this inserts some cmake code into the install script to write the file
- if(MITK_USE_Qt5)
+ if(MITK_USE_Qt6)
set(_qt_conf_plugin_install_prefix .)
if(APPLE)
set(_qt_conf_plugin_install_prefix ./MacOS)
endif()
foreach(_qt_conf_install_dir ${_qt_conf_install_dirs})
install(CODE "file(WRITE \"\${CMAKE_INSTALL_PREFIX}/${_qt_conf_install_dir}/qt.conf\" \"
[Paths]
Prefix=${_qt_conf_plugin_install_prefix}
\")")
endforeach()
endif()
endforeach()
endmacro(MITK_INSTALL_HELPER_APP)
diff --git a/CMake/mitkMacroInstallTargets.cmake b/CMake/mitkMacroInstallTargets.cmake
index 68ffe8bcba..c20837aae8 100644
--- a/CMake/mitkMacroInstallTargets.cmake
+++ b/CMake/mitkMacroInstallTargets.cmake
@@ -1,71 +1,71 @@
#
# MITK specific cross plattform install macro
#
# Usage: MITK_INSTALL_TARGETS(target1 [target2] ....)
#
macro(MITK_INSTALL_TARGETS)
cmake_parse_arguments(_install "GLOB_PLUGINS" "" "TARGETS;EXECUTABLES;PLUGINS;LIBRARY_DIRS" ${ARGN})
list(APPEND _install_TARGETS ${_install_DEFAULT_ARGS})
# TODO: how to supply the correct intermediate directory??
# CMAKE_CFG_INTDIR is not expanded to actual values inside the install(CODE "...") macro ...
set(intermediate_dir .)
if(WIN32)
set(intermediate_dir Release)
endif()
foreach(_target ${_install_EXECUTABLES})
get_target_property(_is_bundle ${_target} MACOSX_BUNDLE)
set(_qt_conf_install_dirs "")
set(_target_locations "")
if(APPLE)
if(_is_bundle)
set(_target_locations ${_target}.app)
set(${_target_locations}_qt_plugins_install_dir ${_target}.app/Contents/MacOS)
set(_bundle_dest_dir ${_target}.app/Contents/MacOS)
set(_qt_conf_install_dirs ${_target}.app/Contents/Resources)
install(TARGETS ${_target} BUNDLE DESTINATION . )
else()
if(NOT MACOSX_BUNDLE_NAMES)
set(_qt_conf_install_dirs bin)
set(_target_locations bin/${_target})
install(TARGETS ${_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/${_target})
list(APPEND _target_locations ${_current_target_location})
install(TARGETS ${_target} RUNTIME DESTINATION ${bundle_name}.app/Contents/MacOS/)
endforeach()
endif()
endif()
else()
set(_target_locations bin/${_target}${CMAKE_EXECUTABLE_SUFFIX})
set(_qt_conf_install_dirs bin)
install(TARGETS ${_target} RUNTIME DESTINATION bin)
endif()
foreach(_target_location ${_target_locations})
_fixup_target()
endforeach()
#--------------------------------------------------------------------------------
# install a qt.conf file
# this inserts some cmake code into the install script to write the file
- if(MITK_USE_Qt5)
+ if(MITK_USE_Qt6)
set(_qt_conf_plugin_install_prefix .)
if(APPLE)
set(_qt_conf_plugin_install_prefix ./MacOS)
endif()
foreach(_qt_conf_install_dir ${_qt_conf_install_dirs})
install(CODE "file(WRITE \"\${CMAKE_INSTALL_PREFIX}/${_qt_conf_install_dir}/qt.conf\" \"
[Paths]
Prefix=${_qt_conf_plugin_install_prefix}
\")")
endforeach()
endif()
endforeach()
endmacro()
diff --git a/CMakeExternals/ACVD.cmake b/CMakeExternals/ACVD.cmake
index db0876ebc3..a35ba3383c 100644
--- a/CMakeExternals/ACVD.cmake
+++ b/CMakeExternals/ACVD.cmake
@@ -1,50 +1,49 @@
#-----------------------------------------------------------------------------
# ACVD
#-----------------------------------------------------------------------------
if(MITK_USE_ACVD)
# Sanity checks
if(DEFINED ACVD_DIR AND NOT EXISTS ${ACVD_DIR})
message(FATAL_ERROR "ACVD_DIR variable is defined but corresponds to non-existing directory")
endif()
set(proj ACVD)
set(proj_DEPENDENCIES VTK)
set(ACVD_DEPENDS ${proj})
if(NOT DEFINED ACVD_DIR)
set(additional_args )
if(CTEST_USE_LAUNCHERS)
list(APPEND additional_args
"-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake"
)
endif()
ExternalProject_Add(${proj}
LIST_SEPARATOR ${sep}
GIT_REPOSITORY https://github.com/valette/ACVD.git
GIT_TAG 18209c90
CMAKE_GENERATOR ${gen}
CMAKE_GENERATOR_PLATFORM ${gen_platform}
CMAKE_ARGS
${ep_common_args}
${additional_args}
-DUSE_MULTITHREADING:BOOL=ON
-DBUILD_EXAMPLES:BOOL=OFF
- -DQt5_DIR:PATH=${Qt5_DIR}
-DVTK_DIR:PATH=${VTK_DIR}
CMAKE_CACHE_ARGS
${ep_common_cache_args}
CMAKE_CACHE_DEFAULT_ARGS
${ep_common_cache_default_args}
DEPENDS ${proj_DEPENDENCIES}
)
set(ACVD_DIR ${ep_prefix})
mitkFunctionInstallExternalCMakeProject(${proj})
else()
mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}")
endif()
endif()
diff --git a/CMakeExternals/CTK.cmake b/CMakeExternals/CTK.cmake
index 9d845f136b..6c611dd9e2 100644
--- a/CMakeExternals/CTK.cmake
+++ b/CMakeExternals/CTK.cmake
@@ -1,79 +1,79 @@
#-----------------------------------------------------------------------------
# CTK
#-----------------------------------------------------------------------------
if(MITK_USE_CTK)
# Sanity checks
if(DEFINED CTK_DIR AND NOT EXISTS ${CTK_DIR})
message(FATAL_ERROR "CTK_DIR variable is defined but corresponds to non-existing directory")
endif()
set(proj CTK)
set(proj_DEPENDENCIES DCMTK)
set(CTK_DEPENDS ${proj})
if(NOT DEFINED CTK_DIR)
set(ctk_optional_cache_args )
if(CTEST_USE_LAUNCHERS)
list(APPEND ctk_optional_cache_args
"-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake"
)
endif()
FOREACH(type RUNTIME ARCHIVE LIBRARY)
IF(DEFINED CTK_PLUGIN_${type}_OUTPUT_DIRECTORY)
LIST(APPEND mitk_optional_cache_args -DCTK_PLUGIN_${type}_OUTPUT_DIRECTORY:PATH=${CTK_PLUGIN_${type}_OUTPUT_DIRECTORY})
ENDIF()
ENDFOREACH()
mitk_query_custom_ep_vars()
ExternalProject_Add(${proj}
LIST_SEPARATOR ${sep}
GIT_REPOSITORY https://github.com/MITK/CTK.git
GIT_TAG 37aff99226ed936b930b1ef07df046877771ea03 # branch: qt-6
UPDATE_COMMAND ""
INSTALL_COMMAND ""
CMAKE_GENERATOR ${gen}
CMAKE_GENERATOR_PLATFORM ${gen_platform}
CMAKE_ARGS
${ep_common_args}
${ctk_optional_cache_args}
+ "-DQt6_DIR:PATH=${Qt6_DIR}"
# The CTK PluginFramework cannot cope with
# a non-empty CMAKE_DEBUG_POSTFIX for the plugin
# libraries yet.
-DCMAKE_DEBUG_POSTFIX:STRING=
- -DCTK_QT_VERSION:STRING=5
- "-DQt5_DIR=${Qt5_DIR}"
+ -DCTK_QT_VERSION:STRING=6
"-DGIT_EXECUTABLE:FILEPATH=${GIT_EXECUTABLE}"
-DCTK_BUILD_QTDESIGNER_PLUGINS:BOOL=OFF
-DCTK_LIB_PluginFramework:BOOL=ON
-DCTK_LIB_DICOM/Widgets:BOOL=ON
-DCTK_LIB_XNAT/Core:BOOL=ON
-DCTK_PLUGIN_org.commontk.eventadmin:BOOL=ON
-DCTK_PLUGIN_org.commontk.configadmin:BOOL=ON
-DCTK_USE_SYSTEM_DCMTK:BOOL=ON
"-DDCMTK_ROOT:PATH=${ep_prefix}"
${${proj}_CUSTOM_CMAKE_ARGS}
CMAKE_CACHE_ARGS
${ep_common_cache_args}
${${proj}_CUSTOM_CMAKE_CACHE_ARGS}
CMAKE_CACHE_DEFAULT_ARGS
${ep_common_cache_default_args}
${${proj}_CUSTOM_CMAKE_CACHE_DEFAULT_ARGS}
DEPENDS ${proj_DEPENDENCIES}
)
ExternalProject_Get_Property(${proj} binary_dir)
set(CTK_DIR ${binary_dir})
else()
mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}")
endif()
endif()
diff --git a/CMakeExternals/ExternalProjectList.cmake b/CMakeExternals/ExternalProjectList.cmake
index c968205bf8..2ef1d865ed 100644
--- a/CMakeExternals/ExternalProjectList.cmake
+++ b/CMakeExternals/ExternalProjectList.cmake
@@ -1,33 +1,33 @@
mitkFunctionAddExternalProject(NAME Poco ON COMPONENTS Foundation Net Util XML Zip)
mitkFunctionAddExternalProject(NAME DCMTK ON DOC "EXPERIMENTAL, superbuild only: Use DCMTK in MITK")
mitkFunctionAddExternalProject(NAME OpenIGTLink OFF)
mitkFunctionAddExternalProject(NAME tinyxml2 ON ADVANCED)
mitkFunctionAddExternalProject(NAME GDCM ON ADVANCED)
mitkFunctionAddExternalProject(NAME Boost ON NO_CACHE)
mitkFunctionAddExternalProject(NAME Eigen ON DEPENDS Boost ADVANCED DOC "Use the Eigen library")
mitkFunctionAddExternalProject(NAME ANN ON ADVANCED DOC "Use Approximate Nearest Neighbor Library")
mitkFunctionAddExternalProject(NAME CppUnit ON ADVANCED DOC "Use CppUnit for unit tests")
mitkFunctionAddExternalProject(NAME HDF5 ON ADVANCED)
mitkFunctionAddExternalProject(NAME OpenCV OFF)
mitkFunctionAddExternalProject(NAME ITK ON NO_CACHE DEPENDS HDF5)
mitkFunctionAddExternalProject(NAME VTK ON NO_CACHE)
mitkFunctionAddExternalProject(NAME ZLIB OFF ADVANCED)
mitkFunctionAddExternalProject(NAME lz4 ON ADVANCED)
mitkFunctionAddExternalProject(NAME cpprestsdk OFF DEPENDS Boost ZLIB ADVANCED)
mitkFunctionAddExternalProject(NAME ACVD OFF DOC "Use Approximated Centroidal Voronoi Diagrams")
-mitkFunctionAddExternalProject(NAME CTK ON DEPENDS Qt5 DCMTK DOC "Use CTK in MITK")
+mitkFunctionAddExternalProject(NAME CTK ON DEPENDS Qt6 DCMTK DOC "Use CTK in MITK")
mitkFunctionAddExternalProject(NAME DCMQI ON DEPENDS DCMTK ITK DOC "Use dcmqi in MITK")
mitkFunctionAddExternalProject(NAME MatchPoint OFF ADVANCED DEPENDS Boost ITK DOC "Use the MatchPoint translation image registration library")
mitkFunctionAddExternalProject(NAME nlohmann_json ON ADVANCED)
mitkFunctionAddExternalProject(NAME httplib ON DEPENDS ZLIB)
-if(MITK_USE_Qt5)
- mitkFunctionAddExternalProject(NAME Qwt ON ADVANCED DEPENDS Qt5)
+if(MITK_USE_Qt6)
+ mitkFunctionAddExternalProject(NAME Qt6Qwt6 ON ADVANCED DEPENDS Qt6)
endif()
if(UNIX AND NOT APPLE)
mitkFunctionAddExternalProject(NAME PCRE OFF ADVANCED NO_PACKAGE)
mitkFunctionAddExternalProject(NAME SWIG OFF ADVANCED NO_PACKAGE DEPENDS PCRE)
elseif(WIN32)
mitkFunctionAddExternalProject(NAME SWIG OFF ADVANCED NO_PACKAGE)
endif()
diff --git a/CMakeExternals/HDF5.cmake b/CMakeExternals/HDF5.cmake
index bc0d68bba7..b4177d76f3 100644
--- a/CMakeExternals/HDF5.cmake
+++ b/CMakeExternals/HDF5.cmake
@@ -1,59 +1,64 @@
#-----------------------------------------------------------------------------
# HDF5
#-----------------------------------------------------------------------------
if(MITK_USE_HDF5)
# Sanity checks
if(DEFINED HDF5_DIR AND NOT EXISTS ${HDF5_DIR})
message(FATAL_ERROR "HDF5_DIR variable is defined but corresponds to non-existing directory")
endif()
set(proj HDF5)
set(proj_DEPENDENCIES )
set(HDF5_DEPENDS ${proj})
if(NOT DEFINED HDF5_DIR)
set(additional_args )
if(CTEST_USE_LAUNCHERS)
list(APPEND additional_args
"-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake"
)
endif()
# We might build static libs with -DBUILD_SHARED_LIBS=0 but this conflicts with
# the in ITK integrated version! So we need to go the way with dynamic libs. Too
# bad :( This would be fixed by using an external HDF-Installation with ITK/VTK
ExternalProject_Add(${proj}
GIT_REPOSITORY https://github.com/HDFGroup/hdf5.git
- GIT_TAG hdf5-1_8_17
+ GIT_TAG 8b5cac6bc498546efa5639f99bb7dbbc1a2d5d90 # hdf5-1_14_3 (2023-10-28)
CMAKE_GENERATOR ${gen}
CMAKE_GENERATOR_PLATFORM ${gen_platform}
CMAKE_ARGS
${ep_common_args}
${additional_args}
- -DHDF5_BUILD_HL_LIB:BOOL=ON
- -DHDF5_BUILD_CPP_LIB:BOOL=ON
+ -DBUILD_TESTING:BOOL=OFF
-DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
+ -DDEFAULT_API_VERSION:STRING=v18
+ -DHDF5_BUILD_CPP_LIB:BOOL=ON
+ -DHDF5_BUILD_EXAMPLES:BOOL=OFF
+ -DHDF5_BUILD_HL_LIB:BOOL=ON
+ -DHDF5_DISABLE_COMPILER_WARNINGS:BOOL=ON
+ -DHDF5_ENABLE_ALL_WARNINGS:BOOL=OFF
CMAKE_CACHE_ARGS
${ep_common_cache_args}
CMAKE_CACHE_DEFAULT_ARGS
${ep_common_cache_default_args}
DEPENDS ${proj_DEPENDENCIES}
)
ExternalProject_Get_Property(${proj} install_dir)
if(WIN32)
set(HDF5_DIR ${install_dir}/cmake/)
else()
set(HDF5_DIR ${install_dir}/share/cmake)
endif()
else()
mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}")
endif()
endif(MITK_USE_HDF5)
diff --git a/CMakeExternals/OpenCV.cmake b/CMakeExternals/OpenCV.cmake
index 65d61e2f88..1dbc84b7c5 100644
--- a/CMakeExternals/OpenCV.cmake
+++ b/CMakeExternals/OpenCV.cmake
@@ -1,72 +1,72 @@
#-----------------------------------------------------------------------------
# OpenCV
#-----------------------------------------------------------------------------
if(MITK_USE_OpenCV)
# Sanity checks
if(DEFINED OpenCV_DIR AND NOT EXISTS ${OpenCV_DIR})
message(FATAL_ERROR "OpenCV_DIR variable is defined but corresponds to non-existing directory")
endif()
set(proj OpenCV)
set(proj_DEPENDENCIES)
set(OpenCV_DEPENDS ${proj})
if(NOT DEFINED OpenCV_DIR)
set(additional_cmake_args)
if(CTEST_USE_LAUNCHERS)
list(APPEND additional_cmake_args
"-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake"
)
endif()
mitk_query_custom_ep_vars()
ExternalProject_Add(${proj}
GIT_REPOSITORY https://github.com/opencv/opencv.git
- GIT_TAG 4.6.0
+ GIT_TAG 4.9.0
LIST_SEPARATOR ${sep}
CMAKE_GENERATOR ${gen}
CMAKE_GENERATOR_PLATFORM ${gen_platform}
CMAKE_ARGS
${ep_common_args}
-DBUILD_JAVA:BOOL=OFF
-DBUILD_opencv_ts:BOOL=OFF
-DBUILD_PERF_TESTS:BOOL=OFF
-DBUILD_opencv_python3:BOOL=OFF
-DBUILD_opencv_python_bindings_generator:BOOL=OFF
-DBUILD_opencv_python_tests:BOOL=OFF
-DWITH_QT:BOOL=OFF
-DBUILD_TESTS:BOOL=OFF
-DBUILD_DOCS:BOOL=OFF
-DBUILD_EXAMPLES:BOOL=OFF
+ -DOPENCV_PYTHON_SKIP_DETECTION:BOOL=ON
-DWITH_CUDA:BOOL=OFF
-DWITH_VTK:BOOL=OFF
- -DENABLE_CXX11:BOOL=ON
-DWITH_IPP:BOOL=OFF
-DBUILD_IPP_IW:BOOL=OFF
-DENABLE_PRECOMPILED_HEADERS:BOOL=OFF
${additional_cmake_args}
${${proj}_CUSTOM_CMAKE_ARGS}
CMAKE_CACHE_ARGS
${ep_common_cache_args}
${${proj}_CUSTOM_CMAKE_CACHE_ARGS}
CMAKE_CACHE_DEFAULT_ARGS
${ep_common_cache_default_args}
${${proj}_CUSTOM_CMAKE_CACHE_DEFAULT_ARGS}
DEPENDS ${proj_DEPENDENCIES}
)
set(OpenCV_DIR ${ep_prefix})
mitkFunctionInstallExternalCMakeProject(${proj})
else()
mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}")
endif()
endif()
diff --git a/CMakeExternals/PCRE.cmake b/CMakeExternals/PCRE.cmake
index c8a37b69c9..5a70f9b497 100644
--- a/CMakeExternals/PCRE.cmake
+++ b/CMakeExternals/PCRE.cmake
@@ -1,69 +1,69 @@
#--------------------------------------------------------------------------
# PCRE (Perl Compatible Regular Expressions)
#--------------------------------------------------------------------------
if(MITK_USE_PCRE)
if(DEFINED PCRE_DIR AND NOT EXISTS ${PCRE_DIR})
message(FATAL_ERROR "PCRE_DIR variable is defined but corresponds to non-existing directory")
endif()
set(proj PCRE)
set(${proj}_DEPENDENCIES "")
set(${proj}_DEPENDS ${proj})
if(NOT PCRE_DIR)
if(UNIX)
# Some other projects (e.g. Swig) require a pcre-config script which is not
# generated when using the CMake build system.
set(configure_cmd
CONFIGURE_COMMAND <SOURCE_DIR>/./configure
CC=${CMAKE_C_COMPILER}${CMAKE_C_COMPILER_ARG1}
CFLAGS=-fPIC
"CXXFLAGS=-fPIC ${MITK_CXX${MITK_CXX_STANDARD}_FLAG} ${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE}"
"LDFLAGS=${CMAKE_LINKER_FLAGS} ${CMAKE_LINKER_FLAGS_RELEASE} ${_install_rpath_linkflag}"
CXX=${CMAKE_CXX_COMPILER}${CMAKE_CXX_COMPILER_ARG1}
--prefix=<INSTALL_DIR>
--disable-shared
--enable-jit
)
else()
set(additional_cmake_args )
if(CTEST_USE_LAUNCHERS)
list(APPEND additional_cmake_args
"-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake"
)
endif()
set(configure_cmd
CMAKE_GENERATOR ${gen}
CMAKE_GENERATOR_PLATFORM ${gen_platform}
CMAKE_ARGS
${ep_common_args}
${additional_cmake_args}
"-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} -fPIC"
-DBUILD_SHARED_LIBS:BOOL=OFF
-DPCRE_BUILD_PCREGREP:BOOL=OFF
-DPCRE_BUILD_TESTS:BOOL=OFF
-DPCRE_SUPPORT_JIT:BOOL=ON
CMAKE_CACHE_ARGS
${ep_common_cache_args}
CMAKE_CACHE_DEFAULT_ARGS
${ep_common_cache_default_args}
)
endif()
ExternalProject_add(${proj}
LIST_SEPARATOR ${sep}
- URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/pcre-8.35.tar.gz
- URL_MD5 "ed58bcbe54d3b1d59e9f5415ef45ce1c"
+ URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/pcre-8.45.tar.gz
+ URL_MD5 "01b80f8177ab91da63e7e5c5d5dfcb83"
${configure_cmd}
DEPENDS "${${proj}_DEPENDENCIES}"
)
set(PCRE_DIR ${ep_prefix})
else()
mitkMacroEmptyExternalProject(${proj} "${${proj}_DEPENDENCIES}")
endif()
endif()
diff --git a/CMakeExternals/Qwt.cmake b/CMakeExternals/Qt6Qwt6.cmake
similarity index 63%
rename from CMakeExternals/Qwt.cmake
rename to CMakeExternals/Qt6Qwt6.cmake
index 319d941763..b43796b849 100644
--- a/CMakeExternals/Qwt.cmake
+++ b/CMakeExternals/Qt6Qwt6.cmake
@@ -1,57 +1,56 @@
#-----------------------------------------------------------------------------
# Qwt
#-----------------------------------------------------------------------------
-if(MITK_USE_Qwt)
+if(MITK_USE_Qt6Qwt6)
# Sanity checks
-if(DEFINED Qwt_DIR AND NOT EXISTS ${Qwt_DIR})
- message(FATAL_ERROR "Qwt_DIR variable is defined but corresponds to non-existing directory")
+if(DEFINED Qt6Qwt6_DIR AND NOT EXISTS ${Qt6Qwt6_DIR})
+ message(FATAL_ERROR "Qt6Qwt6_DIR variable is defined but corresponds to non-existing directory")
endif()
-set(proj Qwt)
+set(proj Qt6Qwt6)
set(proj_DEPENDENCIES )
set(${proj}_DEPENDS ${proj})
if(NOT DEFINED ${proj}_DIR)
- set(additional_cmake_args
- "-DQt5Svg_DIR:PATH=${Qt5Svg_DIR}"
- "-DQt5OpenGL_DIR:PATH=${Qt5OpenGL_DIR}"
- "-DQt5PrintSupport_DIR:PATH=${Qt5PrintSupport_DIR}"
- "-DQt5Concurrent_DIR:PATH=${Qt5Concurrent_DIR}"
- "-DQt5Designer_DIR:PATH=${Qt5_DIR}Designer"
- )
if(CTEST_USE_LAUNCHERS)
list(APPEND additional_cmake_args
"-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake"
)
endif()
ExternalProject_Add(${proj}
LIST_SEPARATOR ${sep}
GIT_REPOSITORY https://github.com/MITK/Qwt.git
- GIT_TAG v6.2.0-patched
+ GIT_TAG 149ab80d5434bf1702c14886b0e353292a9a1d7e # branch: cmake (synced from https://github.com/MehdiChinoune/qwt)
CMAKE_GENERATOR ${gen}
CMAKE_GENERATOR_PLATFORM ${gen_platform}
CMAKE_ARGS
${ep_common_args}
${additional_cmake_args}
CMAKE_CACHE_ARGS
- -DQWT_BUILD_DESIGNER_PLUGIN:BOOL=OFF
+ "-DQt6_DIR:PATH=${Qt6_DIR}"
+ -DQWT_QT_VERSION_MAJOR:STRING=6
+ -DQWT_DESIGNER:BOOL=OFF
+ -DQWT_OPENGL:BOOL=OFF
+ -DQWT_POLAR:BOOL=OFF
+ -DQWT_SVG:BOOL=OFF
+ -DQWT_WIDGETS:BOOL=OFF
${ep_common_cache_args}
CMAKE_CACHE_DEFAULT_ARGS
${ep_common_cache_default_args}
DEPENDS ${proj_DEPENDENCIES}
)
- set(${proj}_DIR ${ep_prefix})
+ set(${proj}_DIR ${ep_prefix}/lib/cmake/${proj})
mitkFunctionInstallExternalCMakeProject(${proj})
else()
mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}")
endif()
endif()
diff --git a/CMakeExternals/VTK.cmake b/CMakeExternals/VTK.cmake
index b68a539504..4d0f3d0dee 100644
--- a/CMakeExternals/VTK.cmake
+++ b/CMakeExternals/VTK.cmake
@@ -1,88 +1,101 @@
#-----------------------------------------------------------------------------
# VTK
#-----------------------------------------------------------------------------
# Sanity checks
if(DEFINED VTK_DIR AND NOT EXISTS ${VTK_DIR})
message(FATAL_ERROR "VTK_DIR variable is defined but corresponds to non-existing directory")
endif()
set(proj VTK)
set(proj_DEPENDENCIES )
set(VTK_DEPENDS ${proj})
if(NOT DEFINED VTK_DIR)
set(additional_cmake_args )
if(WIN32)
list(APPEND additional_cmake_args
-DCMAKE_CXX_MP_FLAG:BOOL=ON
)
else()
list(APPEND additional_cmake_args
-DVTK_MODULE_USE_EXTERNAL_VTK_freetype:BOOL=ON
)
+
+ if(NOT APPLE)
+ if(NOT DEFINED OpenGL_GL_PREFERENCE OR OpenGL_GL_PREFERENCE STREQUAL GLVND)
+ find_package(OpenGL REQUIRED OPTIONAL_COMPONENTS EGL)
+ if(TARGET OpenGL::EGL)
+ list(APPEND additional_cmake_args "-DVTK_OPENGL_HAS_EGL:BOOL=ON")
+ endif()
+ endif()
+ if(DEFINED OpenGL_GL_PREFERENCE)
+ list(APPEND additional_cmake_args "-DOpenGL_GL_PREFERENCE:STRING=${OpenGL_GL_PREFERENCE}")
+ endif()
+ endif()
+
endif()
# Optionally enable memory leak checks for any objects derived from vtkObject. This
# will force unit tests to fail if they have any of these memory leaks.
option(MITK_VTK_DEBUG_LEAKS OFF)
mark_as_advanced(MITK_VTK_DEBUG_LEAKS)
list(APPEND additional_cmake_args
-DVTK_DEBUG_LEAKS:BOOL=${MITK_VTK_DEBUG_LEAKS}
)
- if(MITK_USE_Qt5)
+ if(MITK_USE_Qt6)
list(APPEND additional_cmake_args
-DVTK_GROUP_ENABLE_Qt:STRING=YES
- -DQt5_DIR:PATH=${Qt5_DIR}
)
endif()
if(CTEST_USE_LAUNCHERS)
list(APPEND additional_cmake_args
"-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake"
)
endif()
mitk_query_custom_ep_vars()
ExternalProject_Add(${proj}
LIST_SEPARATOR ${sep}
- GIT_REPOSITORY https://github.com/Kitware/VTK.git
- GIT_TAG v9.2.6
+ GIT_REPOSITORY https://github.com/MITK/VTK.git
+ GIT_TAG ef49b4f7b240ec62b4a7014fe97858be54fe9157 # v9.3.0-patched
GIT_SUBMODULES ""
CMAKE_GENERATOR ${gen}
CMAKE_GENERATOR_PLATFORM ${gen_platform}
CMAKE_ARGS
${ep_common_args}
- -DOpenGL_GL_PREFERENCE:STRING=LEGACY
+ "-DQt6_DIR:PATH=${Qt6_DIR}"
-DVTK_ENABLE_WRAPPING:BOOL=OFF
-DVTK_LEGACY_REMOVE:BOOL=ON
-DVTK_MODULE_ENABLE_VTK_TestingRendering:STRING=YES
-DVTK_MODULE_ENABLE_VTK_RenderingContextOpenGL2:STRING=YES
-DVTK_MODULE_ENABLE_VTK_RenderingVolumeOpenGL2:STRING=YES
-DVTK_MODULE_ENABLE_VTK_GUISupportQtQuick:STRING=NO
-DVTK_MODULE_ENABLE_VTK_IOIOSS:STRING=NO # See T29633
-DVTK_MODULE_ENABLE_VTK_ioss:STRING=NO # See T29633
- -DVTK_QT_VERSION:STRING=5
+ -DVTK_REPORT_OPENGL_ERRORS:BOOL=OFF
+ -DVTK_QT_VERSION:STRING=6
${additional_cmake_args}
${${proj}_CUSTOM_CMAKE_ARGS}
CMAKE_CACHE_ARGS
${ep_common_cache_args}
${${proj}_CUSTOM_CMAKE_CACHE_ARGS}
CMAKE_CACHE_DEFAULT_ARGS
${ep_common_cache_default_args}
${${proj}_CUSTOM_CMAKE_CACHE_DEFAULT_ARGS}
DEPENDS ${proj_DEPENDENCIES}
)
set(VTK_DIR ${ep_prefix})
mitkFunctionInstallExternalCMakeProject(${proj})
else()
mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}")
endif()
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4a3085768e..579853a65a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,1424 +1,1403 @@
#[[ When increasing the minimum required version, check if Boost_ADDITIONAL_VERSIONS
in CMake/PackageDepends/MITK_Boost_Config.cmake can be removed. See the first
long comment in CMakeExternals/Boost.cmake for details. ]]
set(MITK_CMAKE_MINIMUM_REQUIRED_VERSION 3.18)
cmake_minimum_required(VERSION ${MITK_CMAKE_MINIMUM_REQUIRED_VERSION})
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.19 AND CMAKE_VERSION VERSION_LESS 3.19.2)
message(FATAL_ERROR "\
CMake v${CMAKE_VERSION} is defective [1]. \
Please either downgrade to v3.18 or upgrade to at least v3.19.2.\n\
[1] https://gitlab.kitware.com/cmake/cmake/-/issues/21529")
endif()
#-----------------------------------------------------------------------------
# Policies
#-----------------------------------------------------------------------------
#[[ T28060
https://cmake.org/cmake/help/v3.18/policy/CMP0091.html
https://cmake.org/cmake/help/v3.18/variable/CMAKE_MSVC_RUNTIME_LIBRARY.html
We pass CMP0091 to all external projects as command-line argument:
-DCMAKE_POLICY_DEFAULT_CMP0091:STRING=OLD
]]
cmake_policy(SET CMP0091 OLD)
if(POLICY CMP0135)
cmake_policy(SET CMP0135 NEW) # https://cmake.org/cmake/help/v3.24/policy/CMP0135.html
endif()
#-----------------------------------------------------------------------------
# Superbuild Option - Enabled by default
#-----------------------------------------------------------------------------
option(MITK_USE_SUPERBUILD "Build MITK and the projects it depends on via SuperBuild.cmake." ON)
if(MITK_USE_SUPERBUILD)
project(MITK-superbuild)
set(MITK_SOURCE_DIR ${PROJECT_SOURCE_DIR})
set(MITK_BINARY_DIR ${PROJECT_BINARY_DIR})
else()
project(MITK VERSION 2023.12.99)
include_directories(SYSTEM ${MITK_SUPERBUILD_BINARY_DIR})
endif()
#-----------------------------------------------------------------------------
# MITK Extension Feature
#-----------------------------------------------------------------------------
set(MITK_EXTENSION_DIRS "" CACHE STRING "")
unset(MITK_ABSOLUTE_EXTENSION_DIRS)
foreach(MITK_EXTENSION_DIR ${MITK_EXTENSION_DIRS})
get_filename_component(MITK_ABSOLUTE_EXTENSION_DIR "${MITK_EXTENSION_DIR}" ABSOLUTE)
list(APPEND MITK_ABSOLUTE_EXTENSION_DIRS "${MITK_ABSOLUTE_EXTENSION_DIR}")
endforeach()
set(MITK_DIR_PLUS_EXTENSION_DIRS "${MITK_SOURCE_DIR}" ${MITK_ABSOLUTE_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_ABSOLUTE_EXTENSION_DIRS})
set(MITK_CMAKE_EXTENSION_DIR "${MITK_EXTENSION_DIR}/CMake")
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(CTest)
include(CMakeParseArguments)
include(FindPackageHandleStandardArgs)
# MITK macros
include(mitkFunctionGetGccVersion)
include(mitkFunctionCheckCompilerFlags)
include(mitkFunctionSuppressWarnings) # includes several functions
include(mitkMacroEmptyExternalProject)
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()
if(CMAKE_COMPILER_IS_GNUCXX)
mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION)
else()
set(GCC_VERSION 0)
endif()
set(MITK_CXX_STANDARD 17)
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++<std> flag for targets.
# However, compile flag checks also need to be done with -std=c++<std>.
# The MITK_CXX<std>_FLAG variable is also used for external projects
# build during the MITK super-build.
mitkFunctionCheckCompilerFlags("-std=c++${MITK_CXX_STANDARD}" MITK_CXX${MITK_CXX_STANDARD}_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)
mark_as_advanced(
MITK_XVFB_TESTING
MITK_FAST_TESTING
MITK_BUILD_ALL_APPS
)
#-----------------------------------------------------------------------------
# Set UI testing flags
#-----------------------------------------------------------------------------
if(MITK_XVFB_TESTING)
set(MITK_XVFB_TESTING_COMMAND "xvfb-run" "--auto-servernum" CACHE STRING "Command and options to test through Xvfb")
mark_as_advanced(MITK_XVFB_TESTING_COMMAND)
endif(MITK_XVFB_TESTING)
# -----------------------------------------
# Other options
set(MITK_CUSTOM_REVISION_DESC "" CACHE STRING "Override MITK revision description")
mark_as_advanced(MITK_CUSTOM_REVISION_DESC)
set_property(GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS "")
include(CMakeExternals/ExternalProjectList.cmake)
foreach(MITK_EXTENSION_DIR ${MITK_ABSOLUTE_EXTENSION_DIRS})
set(MITK_CMAKE_EXTERNALS_EXTENSION_DIR "${MITK_EXTENSION_DIR}/CMakeExternals")
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_ABSOLUTE_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)
# -----------------------------------------
# Qt version related variables
-option(MITK_USE_Qt5 "Use Qt 5 library" ON)
-
-if(MITK_USE_Qt5)
- if(WIN32)
- set(MITK_QT5_MINIMUM_VERSION 5.12.9)
- else()
- set(MITK_QT5_MINIMUM_VERSION 5.12)
- endif()
- set(MITK_QT5_COMPONENTS Concurrent OpenGL PrintSupport Script Sql Svg Widgets Xml XmlPatterns WebEngineWidgets UiTools Help LinguistTools)
+option(MITK_USE_Qt6 "Use Qt 6 library" ON)
+
+if(MITK_USE_Qt6)
+ set(MITK_QT6_MINIMUM_VERSION 6.6)
+ set(MITK_QT6_COMPONENTS
+ Concurrent
+ Core
+ Core5Compat
+ CoreTools
+ Designer
+ DesignerComponentsPrivate
+ Gui
+ Help
+ LinguistTools
+ Network
+ OpenGL
+ OpenGLWidgets
+ Qml
+ Sql
+ StateMachine
+ Svg
+ ToolsTools
+ UiTools
+ WebEngineCore
+ WebEngineWidgets
+ Widgets
+ Xml
+ )
if(APPLE)
- list(APPEND MITK_QT5_COMPONENTS DBus)
- elseif(UNIX)
- list(APPEND MITK_QT5_COMPONENTS X11Extras)
+ list(APPEND MITK_QT6_COMPONENTS DBus)
endif()
# Hint at default install locations of Qt
- if(NOT Qt5_DIR)
+ if(NOT Qt6_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 2022)
- list(APPEND _compilers "msvc2019" "msvc2017") # Binary compatible
- elseif (CMAKE_MATCH_0 EQUAL 2019)
- list(APPEND _compilers "msvc2017") # Binary compatible
+ list(APPEND _compilers "msvc2019") # Binary compatible
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()
+ if(APPLE)
+ list(APPEND _compilers macos)
+ endif()
+
foreach(_dir_candidate ${_dir_candidates})
get_filename_component(_dir_candidate ${_dir_candidate} REALPATH)
foreach(_compiler ${_compilers})
- set(_glob_expression "${_dir_candidate}/5.*/${_compiler}")
+ set(_glob_expression "${_dir_candidate}/6.*/${_compiler}")
file(GLOB _hints ${_glob_expression})
list(SORT _hints)
- list(APPEND MITK_QT5_HINTS ${_hints})
+ list(APPEND MITK_QT6_HINTS ${_hints})
endforeach()
endforeach()
endif()
- find_package(Qt5 ${MITK_QT5_MINIMUM_VERSION} COMPONENTS ${MITK_QT5_COMPONENTS} REQUIRED HINTS ${MITK_QT5_HINTS})
+ find_package(Qt6 ${MITK_QT6_MINIMUM_VERSION} COMPONENTS ${MITK_QT6_COMPONENTS} REQUIRED HINTS ${MITK_QT6_HINTS})
+
+ get_target_property(QT_QMAKE_EXECUTABLE Qt6::qmake LOCATION)
+ get_target_property(QT_HELPGENERATOR_EXECUTABLE Qt6::qhelpgenerator LOCATION)
+endif()
+
+if(Qt6_DIR)
+ list(APPEND CMAKE_PREFIX_PATH "${Qt6_DIR}/../../..")
+ list(REMOVE_DUPLICATES CMAKE_PREFIX_PATH)
endif()
# -----------------------------------------
# Custom dependency logic
-if(WIN32 AND Qt5_DIR)
- set(_dir_candidate "${Qt5_DIR}/../../../../../Tools/OpenSSL/Win_x64")
+if(WIN32 AND Qt6_DIR)
+ set(_dir_candidate "${Qt6_DIR}/../../../../../Tools/OpenSSLv3/Win_x64")
get_filename_component(_dir_candidate ${_dir_candidate} ABSOLUTE)
if(EXISTS "${_dir_candidate}")
set(OPENSSL_ROOT_DIR "${_dir_candidate}")
endif()
endif()
-find_package(OpenSSL)
+find_package(OpenSSL 3)
+
+if(NOT OpenSSL_FOUND)
+ find_package(OpenSSL 1.1.1)
+endif()
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 OR MITK_USE_httplib)
if(NOT OpenSSL_FOUND)
set(openssl_message "Could not find OpenSSL (dependency of C++ REST SDK and cpp-httplib).\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 either install Win32 OpenSSL:\n"
" https://slproweb.com/products/Win32OpenSSL.html\n"
"Or use the Qt Maintenance tool to install (recommended):\n"
" Developer and Designer Tools > OpenSSL Toolkit > OpenSSL 64-bit binaries\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)
set(python3_mininum_version 3.11)
else()
set(python3_mininum_version 3.8)
endif()
find_package(Python3 ${python3_mininum_version} REQUIRED COMPONENTS Interpreter Development NumPy)
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<unsigned char>, itk::RGBAPixel<unsigned char>"
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<unsigned char>, itk::RGBAPixel<unsigned char>"
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()
find_package(Git REQUIRED)
#-----------------------------------------------------------------------------
# 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(mitkFunctionAddManifest)
include(mitkFunctionAddCustomModuleTest)
include(mitkFunctionCheckModuleDependencies)
include(mitkFunctionCompileSnippets)
include(mitkFunctionConfigureVisualStudioUserProjectFile)
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(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
#-----------------------------------------------------------------------------
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)
#-----------------------------------------------------------------------------
if(OpenSSL_FOUND AND WIN32)
#[[ On Windows, CMake is able to locate the link libraries for OpenSSL but it
does not look for the corresponding DLLs that we need to copy to our
binary directories and include in packaging.
Setting these paths manually is cumbersome so we try to use a simple
heuristic to automatically set them:
- Based on the link libraries (usually located in a lib folder),
try to find the "../bin" binary directory.
- Use the base file names of the link libraries to find corresponding
DLLs like "<base name>*.dll", that usually are named like
"<base name>-1_1-x64.dll" or similar.
]]
set(openssl_ssl_dll "")
set(openssl_crypto_dll "")
if(OPENSSL_SSL_LIBRARY AND EXISTS "${OPENSSL_SSL_LIBRARY}")
get_filename_component(openssl_bin_dir "${OPENSSL_SSL_LIBRARY}" DIRECTORY)
get_filename_component(openssl_bin_dir "${openssl_bin_dir}" DIRECTORY)
set(openssl_bin_dir "${openssl_bin_dir}/bin")
if(EXISTS "${openssl_bin_dir}")
get_filename_component(openssl_ssl_basename "${OPENSSL_SSL_LIBRARY}" NAME_WE)
file(GLOB openssl_ssl_dll "${openssl_bin_dir}/${openssl_ssl_basename}*.dll")
list(LENGTH openssl_ssl_dll num_findings)
if(num_findings GREATER 1)
set(openssl_ssl_dll "")
endif()
get_filename_component(openssl_crypto_basename "${OPENSSL_CRYPTO_LIBRARY}" NAME_WE)
file(GLOB openssl_crypto_dll "${openssl_bin_dir}/${openssl_crypto_basename}*.dll")
list(LENGTH openssl_crypto_dll num_findings)
if(num_findings GREATER 1)
set(openssl_crypto_dll "")
endif()
endif()
endif()
set(MITK_OPENSSL_SSL_DLL "${openssl_ssl_dll}" CACHE FILEPATH "")
if(DEFINED CACHE{MITK_OPENSSL_SSL_DLL} AND NOT MITK_OPENSSL_SSL_DLL AND openssl_ssl_dll)
set(MITK_OPENSSL_SSL_DLL "${openssl_ssl_dll}" CACHE FILEPATH "" FORCE)
endif()
set(MITK_OPENSSL_CRYPTO_DLL "${openssl_crypto_dll}" CACHE FILEPATH "")
if(DEFINED CACHE{MITK_OPENSSL_CRYPTO_DLL} AND NOT MITK_OPENSSL_CRYPTO_DLL AND openssl_crypto_dll)
set(MITK_OPENSSL_CRYPTO_DLL "${openssl_crypto_dll}" CACHE FILEPATH "" FORCE)
endif()
if(MITK_OPENSSL_SSL_DLL AND EXISTS "${MITK_OPENSSL_SSL_DLL}" AND MITK_OPENSSL_CRYPTO_DLL AND EXISTS "${MITK_OPENSSL_CRYPTO_DLL}")
foreach(config_type ${CMAKE_CONFIGURATION_TYPES})
execute_process(COMMAND "${CMAKE_COMMAND}" -E make_directory "${MITK_BINARY_DIR}/bin/${config_type}")
configure_file("${MITK_OPENSSL_SSL_DLL}" "${MITK_BINARY_DIR}/bin/${config_type}/" COPYONLY)
configure_file("${MITK_OPENSSL_CRYPTO_DLL}" "${MITK_BINARY_DIR}/bin/${config_type}/" COPYONLY)
endforeach()
MITK_INSTALL(FILES
"${MITK_OPENSSL_SSL_DLL}"
"${MITK_OPENSSL_CRYPTO_DLL}"
)
endif()
endif()
# 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 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)
if(NOT MITK_FAST_TESTING)
if(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")
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_CXX${MITK_CXX_STANDARD}_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} -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-deprecated-copy
-Wno-array-bounds
-Wno-cast-function-type
-Wno-maybe-uninitialized
-Wno-error=stringop-overread
-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_ABSOLUTE_EXTENSION_DIRS})
set(MITK_PACKAGE_DEPENDS_EXTENSION_DIR "${MITK_EXTENSION_DIR}/CMake/PackageDepends")
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.74 1.74.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
# <proj>Config.cmake files pointed at by <proj>_DIR variables.
# Otherwise, existing Find<proj>.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<proj>.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)
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()
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()
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_Qt6)
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")
+ if(NOT MITK_USE_Qt6)
+ message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because MITK_USE_Qt6 is OFF.")
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)
# Configuration for the CMake-generated test driver
set(CMAKE_TESTDRIVER_EXTRA_INCLUDES "#include <stdexcept>")
set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN "
try
{")
set(CMAKE_TESTDRIVER_AFTER_TESTMAIN "
}
catch (const std::exception& e)
{
fprintf(stderr, \"%s\\n\", e.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 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_ABSOLUTE_EXTENSION_DIRS})
get_filename_component(MITK_ROOT_FOLDER "${MITK_EXTENSION_DIR}" NAME)
set(MITK_MODULES_EXTENSION_DIR "${MITK_EXTENSION_DIR}/Modules")
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)
set(MITK_DOXYGEN_OUTPUT_DIR "${PROJECT_BINARY_DIR}/Documentation/Doxygen" CACHE PATH
"Output directory for doxygen generated documentation.")
if(MITK_USE_BLUEBERRY)
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_ABSOLUTE_EXTENSION_DIRS})
set(MITK_PLUGINS_EXTENSION_DIR "${MITK_EXTENSION_DIR}/Plugins")
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")
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
#-----------------------------------------------------------------------------
set(MITK_DOXYGEN_ADDITIONAL_INPUT_DIRS)
set(MITK_DOXYGEN_ADDITIONAL_IMAGE_PATHS)
foreach(MITK_EXTENSION_DIR ${MITK_DIR_PLUS_EXTENSION_DIRS})
set(MITK_DOXYGEN_ADDITIONAL_INPUT_DIRS "${MITK_DOXYGEN_ADDITIONAL_INPUT_DIRS} \"${MITK_EXTENSION_DIR}\"")
set(MITK_DOXYGEN_ADDITIONAL_IMAGE_PATHS "${MITK_DOXYGEN_ADDITIONAL_IMAGE_PATHS} \"${MITK_EXTENSION_DIR}\"")
endforeach()
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")
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_ABSOLUTE_EXTENSION_DIRS})
set(MITK_APPLICATIONS_EXTENSION_DIR "${MITK_EXTENSION_DIR}/Applications")
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/CMakeLists.txt b/Documentation/CMakeLists.txt
index 00f7794779..c7583eaad5 100644
--- a/Documentation/CMakeLists.txt
+++ b/Documentation/CMakeLists.txt
@@ -1,128 +1,113 @@
# Different doxygen versions produce significantly different behaviour in the MITK documentation
# especially in regards to the MITK Qt assistant help files and markdown files.
# The HTML documentation is supposed to be build with Doxygen 1.8.7 or newer, the
# Qt assistant QCH files are supposed to be generated with Doxygen 1.8.7 or newer.
# So we check for 1.8.7 here and QCH generation support is checked in
# BlueBerry/CMakeLists.txt
set(supported_doxygen_version "1.8.7")
if(DOXYGEN_VERSION VERSION_LESS ${supported_doxygen_version})
MESSAGE(WARNING "Unsupported doxygen version ${DOXYGEN_VERSION}. The MITK HTML documentation has been tested to work with doxygen ${supported_doxygen_version} or newer.")
endif()
option(USE_DOT "Use dot program for generating graphical class diagrams with doxygen, if available" ON)
option(MITK_DOXYGEN_BUILD_ALWAYS "Always build the MITK documentation when building the default target" OFF)
option(MITK_DOXYGEN_GENERATE_QCH_FILES "Use doxygen to generate Qt compressed help files for MITK docs" OFF)
mark_as_advanced(USE_DOT MITK_DOXYGEN_BUILD_ALWAYS MITK_DOXYGEN_GENERATE_QCH_FILES)
if (MITK_DOXYGEN_GENERATE_QCH_FILES AND DOXYGEN_VERSION VERSION_LESS "1.8.7")
message(WARNING "> Forcing MITK_DOXYGEN_GENERATE_QCH_FILES to OFF because Doxygen version 1.8.7 or newer not found.")
set(MITK_DOXYGEN_GENERATE_QCH_FILES OFF CACHE BOOL "Use doxygen to generate Qt compressed help files for MITK docs" FORCE)
endif()
set(HAVE_DOT "NO")
if(DOXYGEN_DOT_EXECUTABLE AND USE_DOT)
set(HAVE_DOT "YES")
endif()
set(MITK_DOXYGEN_TAGFILE_NAME ${MITK_DOXYGEN_OUTPUT_DIR}/MITK.tag CACHE INTERNAL "MITK Doxygen tag file")
# This is relative to the working directory of the doxygen command
set(MITK_DOXYGEN_STYLESHEET mitk_doxygen_extra.css)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/${MITK_DOXYGEN_STYLESHEET}
${CMAKE_CURRENT_BINARY_DIR}/${MITK_DOXYGEN_STYLESHEET} COPYONLY)
# Create QCH files for MITK and external projects
set(MITK_DOXYGEN_GENERATE_QHP "NO")
if(MITK_DOXYGEN_GENERATE_QCH_FILES)
-
- find_program(QT_HELPGENERATOR_EXECUTABLE
- NAMES qhelpgenerator qhelpgenerator-qt5 qhelpgenerator5
- PATHS ${QT_BINARY_DIR}
- DOC "The location of the the Qt help generator executable"
- NO_DEFAULT_PATH
- )
- mark_as_advanced(QT_HELPGENERATOR_EXECUTABLE)
-
if(NOT QT_HELPGENERATOR_EXECUTABLE)
message(SEND_ERROR "The Qt help generator could not be found. Disabling qch generation")
else()
set(MITK_DOXYGEN_GENERATE_QHP "YES")
endif()
-
- # The name of the generated MITK qch file, relative to the
- # Doxygen HTML output folder
- set(MITK_DOXYGEN_QCH_FILE "${MITK_BINARY_DIR}/MITK-${MITK_REVISION_ID}.qch")
-
- # Generating ITK and VTK docs it not done yet
- #option(MITK_DOXYGEN_GENERATE_VTK_QCH_FILE "Use doxygen to generate a Qt compressed help file for VTK docs" OFF)
- #option(MITK_DOXYGEN_GENERATE_ITK_QCH_FILE "Use doxygen to generate a Qt compressed help file for ITK docs" OFF)
- #mark_as_advanced(MITK_DOXYGEN_GENERATE_VTK_QCH_FILE MITK_DOXYGEN_GENERATE_ITK_QCH_FILE)
-
endif()
+# The name of the generated MITK qch file, relative to the
+# Doxygen HTML output folder
+set(MITK_DOXYGEN_QCH_FILE "${MITK_BINARY_DIR}/MITK-${MITK_REVISION_ID}.qch")
+
# Compile a doxygen input filter for processing CMake scripts
include(mitkFunctionCMakeDoxygenFilterCompile)
mitkFunctionCMakeDoxygenFilterCompile(NAMESPACE "CMake")
# Configure some doxygen options
if(NOT MITK_DOXYGEN_INTERNAL_DOCS)
set(MITK_DOXYGEN_INTERNAL_DOCS "NO")
set(MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS "YES")
set(MITK_DOXYGEN_EXCLUDE_PATTERNS "*_p.* *Private.h */internal/*")
else()
set(MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS "NO")
set(MITK_DOXYGEN_EXCLUDE_PATTERNS "")
endif()
if(NOT MITK_DOXYGEN_GENERATE_TODOLIST)
set(MITK_DOXYGEN_GENERATE_TODOLIST "NO")
endif()
if(NOT MITK_DOXYGEN_GENERATE_BUGLIST)
set(MITK_DOXYGEN_GENERATE_BUGLIST "NO")
endif()
if(NOT MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS)
set(MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS "NO")
endif()
if(NOT MITK_DOXYGEN_UML_LOOK)
set(MITK_DOXYGEN_UML_LOOK "NO")
endif()
if(NOT MITK_DOXYGEN_GENERATE_DEPRECATEDLIST)
set(MITK_DOXYGEN_GENERATE_DEPRECATEDLIST "YES")
endif()
if(NOT DEFINED MITK_DOXYGEN_DOT_NUM_THREADS)
set(MITK_DOXYGEN_DOT_NUM_THREADS 0)
endif()
if(NOT DEFINED US_PLATFORM)
if(UNIX)
if(APPLE)
set(US_PLATFORM "US_PLATFORM_APPLE=1")
else()
set(US_PLATFORM "US_PLATFORM_LINUX=1")
endif()
set(US_PLATFORM "${US_PLATFORM} \\\nUS_PLATFORM_POSIX=1")
else()
set(US_PLATFORM "US_PLATFORM_WINDOWS=1")
endif()
endif()
configure_file(doxygen.conf.in
${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf)
if(MITK_DOXYGEN_BUILD_ALWAYS)
set(_doc_in_all "ALL")
else()
set(_doc_in_all "")
endif()
add_custom_target(doc ${_doc_in_all}
${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
set_property(TARGET doc PROPERTY FOLDER "${MITK_ROOT_FOLDER}/Documentation")
diff --git a/Documentation/Doxygen/2-UserManual/MITKPluginManualsList.dox b/Documentation/Doxygen/2-UserManual/MITKPluginManualsList.dox
index 215faaecb1..615bef9dad 100644
--- a/Documentation/Doxygen/2-UserManual/MITKPluginManualsList.dox
+++ b/Documentation/Doxygen/2-UserManual/MITKPluginManualsList.dox
@@ -1,73 +1,70 @@
/**
\page PluginListPage MITK Plugin Manuals
The plugins and bundles provide much of the extended functionality of MITK. Each encapsulates a solution to a problem and associated features. This way one can easily assemble the necessary capabilites for a workflow without adding a lot of bloat, by combining plugins as needed.
<ul>
<li> \subpage org_mitk_views_basicimageprocessing </li>
<li> \subpage org_mitk_views_datamanager </li>
<li> \subpage org_mitk_editors_dicombrowser </li>
<li> \subpage org_mitk_views_dicominspector </li>
<li> \subpage org_mitk_views_imagecropper </li>
<li> \subpage org_mitk_views_imagenavigator </li>
<li> \subpage org_mitk_views_pixelvalue </li>
<li> \subpage org_blueberry_views_logview </li>
<li> \subpage org_mitk_views_matchpoint_algorithm_browser </li>
<li> \subpage org_mitk_views_matchpoint_algorithm_control </li>
<li> \subpage org_mitk_views_matchpoint_evaluator </li>
<li> \subpage org_mitk_views_matchpoint_framereg </li>
<li> \subpage org_mitk_views_matchpoint_manipulator </li>
<li> \subpage org_mitk_views_matchpoint_mapper </li>
<li> \subpage org_mitk_views_matchpoint_visualizer </li>
<li> \subpage org_mitk_gui_qt_measurementtoolbox
<ul>
<li> \subpage org_mitk_views_measurement </li>
<li> \subpage org_mitk_views_imagestatistics </li>
</ul>
</li>
<li> \subpage org_mitk_views_moviemaker </li>
<li> \subpage org_mitk_views_pointsetinteraction </li>
<li> \subpage org_mitk_views_python </li>
<li> \subpage org_mitk_views_remeshing </li>
<li> \subpage org_mitk_views_screenshotmaker </li>
<li> Segmentation
<ul>
<li> \subpage org_mitk_views_segmentation </li>
<li> \subpage org_mitk_views_segmentationutilities </li>
<li> \subpage org_mitk_views_segmentationtasklist </li>
</ul>
</li>
<li> \subpage org_mitk_editors_stdmultiwidget </li>
<li> \subpage org_mitk_editors_mxnmultiwidget </li>
- <li> \subpage org_mitk_views_deformableclippingplane </li>
<li> \subpage org_mitk_views_viewnavigator </li>
<li> \subpage org_mitk_views_volumevisualization </li>
<li> \subpage org_mitk_views_properties </li>
<li> \subpage org_mitk_gui_qt_flowapplication </li>
<li> \subpage org_mitk_gui_qt_flow_segmentation </li>
<li> \subpage org_mitk_gui_qt_aicpregistration </li>
<li> \subpage org_mitk_gui_qt_cest </li>
<li> \subpage org_mitk_views_pharmacokinetics_concentration_mri </li>
<li> \subpage org_mitk_views_pharmacokinetics_mri </li>
<li> \subpage org_mitk_views_pharmacokinetics_pet </li>
<li> \subpage org_mitk_gui_qt_examples </li>
- <li> \subpage org_mitk_gui_qt_geometrytools </li>
<li> \subpage org_mitk_gui_qt_igtexample </li>
<li> \subpage org_mitk_gui_qt_igttracking </li>
<li> \subpage org_mitk_views_igttrackingsemiautomaticmeasurement </li>
<li> \subpage org_mitk_views_fit_demo </li>
<li> \subpage org_mitk_views_fit_genericfitting </li>
<li> \subpage org_mitk_views_fit_inspector </li>
<li> \subpage org_mitkexamplesopencv </li>
<li> \subpage org_mitk_gui_qt_overlaymanager </li>
<li> \subpage org_mitk_gui_qt_preprocessing_resampling </li>
<li> \subpage org_mitk_views_pharmacokinetics_curvedescriptor </li>
<li> \subpage org_mitk_views_pharmacokinetics_simulation </li>
- <li> \subpage org_surfacematerialeditor </li>
<li> \subpage org_toftutorial </li>
<li> \subpage org_blueberry_ui_qt_objectinspector </li>
<li> \subpage org_mitk_gui_qt_ultrasound </li>
<li> \subpage org_mitk_gui_qt_xnat </li>
</ul>
*/
diff --git a/Documentation/Doxygen/3-DeveloperManual/MITKModuleManualsList.dox b/Documentation/Doxygen/3-DeveloperManual/MITKModuleManualsList.dox
index ca06401761..670861fcdc 100644
--- a/Documentation/Doxygen/3-DeveloperManual/MITKModuleManualsList.dox
+++ b/Documentation/Doxygen/3-DeveloperManual/MITKModuleManualsList.dox
@@ -1,17 +1,16 @@
/**
\page MITKModuleManualsList List of Module Manuals
\li \subpage AnnotationModulePage
\li \subpage ChartModule
\li \subpage IGTConcepts
\li \subpage NavigationGeneralModulePage
\li \subpage IGTTutorialOverview
- \li \subpage MitkOpenCL_Overview
\li \subpage LegacyGLModule
\li \subpage mitkPython_Overview
\li \subpage RESTModule
\li \subpage GeneratingDeviceModulesPage
\li \subpage USModulePage
*/
diff --git a/Documentation/Doxygen/3-DeveloperManual/Starting/GettingToKnow/Tutorial/Step09.dox b/Documentation/Doxygen/3-DeveloperManual/Starting/GettingToKnow/Tutorial/Step09.dox
index be5ba22d77..0d080ceafe 100644
--- a/Documentation/Doxygen/3-DeveloperManual/Starting/GettingToKnow/Tutorial/Step09.dox
+++ b/Documentation/Doxygen/3-DeveloperManual/Starting/GettingToKnow/Tutorial/Step09.dox
@@ -1,75 +1,75 @@
/**
\page Step09Page MITK Tutorial - Step 9: A plug-in
MITK uses a very modular concept to maximize reusability and portability. A MITK application based on the BlueBerry
application framework (for example the MITK Workbench) consists of several bundles (or plug-ins). A bundle can contain
resources and program logic. It can also contribute so-called Views to the main application, which provide a specific
user interface for controlling the bundles functions.
\verbatim
documentation\doxygen\
modules.dox......................... Doxygen file for documenting your plug-in
resources\
icon.png............................ The icon of your plug-in. GIMP or other programs (including your text editor)
can be used to change this
src\internal\
QmitkRegionGrowingView.cpp.......... The most important file, implementing behaviour
QmitkRegionGrowingView.h............ Header file of the functionality
QmitkRegionGrowingViewControls.ui... XML file of the Qt Designer, describes buttons, combo boxes, etc. of your controls
CMakeLists.txt \...................... Build system related files for CMake
files.cmake /
manifest_headers.cmake................ Information about your plug-in
plugin.xml ........................... BlueBerry integration
\endverbatim
If you are not familiar with Qt development, please look into
-<a href="https://doc.qt.io/qt-5/qtdesigner-manual.html">this Qt company page describing .ui files</a>
+<a href="https://doc.qt.io/qt-6/qtdesigner-manual.html">this Qt company page describing .ui files</a>
The C++ files implement a subclass of QmitkAbstractView. In this special case of QmitkRegionGrowing, we added the option to set some seed points and run a region grower. If you are interested in the concrete changes necessary to turn a freshly generated QmitkRegionGrowing into an integrated one:
The plug-in will be build as part of MITK Workbench. Do use it start MITK Workbench an select the region growing view in the view menu.
To add a mitk::PointSet for the seed points:
QmitkRegionGrowingView.h
Add includes and forward declarations:
\snippet QmitkRegionGrowingView.h includes
Add the point set and a pointer to a QmitkPointListWidget as a private member:
\snippet QmitkRegionGrowingView.h members
QmitkRegionGrowingView.cpp
CreateQtPartControl():
\snippet QmitkRegionGrowingView.cpp cpp-createqtpartcontrol
To use the ITK region grower:
QmitkRegionGrowingView.h
Add the private method:
\snippet QmitkRegionGrowingView.h itkimageprocessing
QmitkRegionGrowingView.cpp
Add includes:
\snippet QmitkRegionGrowingView.cpp cpp-includes
DoImageProcessing():
\snippet QmitkRegionGrowingView.cpp cpp-doimageprocessing
And add the new method:
\snippet QmitkRegionGrowingView.cpp cpp-itkimageaccess
Have fun using MITK!
If you meet any difficulties during your first steps, don't hesitate to ask on the MITK mailing list mitk-users@lists.sourceforge.net!
People there are kind and will try to help you.
\ref Step08Page "[Previous step]" \ref Step10Page "[Next Step]" \ref TutorialPage "[Main tutorial page]"
*/
diff --git a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/BuildInstructions.dox b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/BuildInstructions.dox
index 58661d1811..b41dd556cf 100644
--- a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/BuildInstructions.dox
+++ b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/BuildInstructions.dox
@@ -1,232 +1,233 @@
/**
\page BuildInstructionsPage Build Instructions
\tableofcontents
\section BuildInstructions_Introduction Introduction
The CMake-based build system of MITK supports a "superbuild" process,
meaning that it will download, configure, and build all required third-party
libraries (except Qt) automatically. These instructions will show you how to use
the MITK superbuild.
\note This page explains explicitly how to build MITK itself. If you want to
create your own project based on MITK, the process described below is completely
automated. Please see \ref HowToNewProject.
For more advanced users, the last sections explains how to inject custom build
libraries into the superbuild process.
\section BuildInstructions_Prerequisites Prerequisites
You need:
-# <a href="https://git-scm.com/">Git</a> (there are also numerous third-party graphical
clients available). We recommend using Git, but see below for a way how to
get the current source code without using it.
-# <a href="https://cmake.org/">CMake</a> (version \minimumCMakeVersion or higher)
- -# <a href="https://www.qt.io/">Qt</a> \minimumQt5Version if you plan to develop Qt-based
+ -# <a href="https://www.qt.io/">Qt</a> \minimumQt6Version if you plan to develop Qt-based
applications
-# If you are using <b>macOS</b> you need an XCode installation and the
Command Line Tools as it provides the neccessary compilers and SDKs
To build MITK on Linux, install the following packages, e. g. with APT:
\code{.unparsed}
-sudo apt install build-essential doxygen git graphviz libfreetype6-dev libglu1-mesa-dev libssl-dev libtiff5-dev libxcomposite1 libxcursor1 libxdamage-dev libxi-dev libxkbcommon-x11-0 libxt-dev mesa-common-dev
+sudo apt install build-essential doxygen git graphviz libegl-dev libfreetype6-dev libglu1-mesa-dev libopengl-dev libssl-dev libtiff5-dev libxcomposite1 libxcursor-dev libxcb-cursor-dev libxdamage-dev libxi-dev libxkbcommon-dev libxt-dev mesa-common-dev
\endcode
For the optional and experimental (!) Python integration, install NumPy and SimpleITK v1.x, e. g.:
\code{.unparsed}
sudo apt install python3-numpy python3-pip
pip3 install SimpleITK
\endcode
\section BuildInstructions_Qt A note about Qt
As we do not provide Qt in the MITK superbuild you need to install Qt manually.
The Qt Company provides <a href="https://www.qt.io/download/">online installers
for all supported platforms</a>.
We highly recommend to install Qt to the default location of the installer as it will allow MITK to automatically find Qt without any further action needed.
Make sure to also select the following <b>required components</b>:
- - QtWebEngine
- - QtScript
+ - Qt 5 Compatibility Module
+ - Qt State Machines
+ - Qt WebEngine
On Windows, the Qt installer offers a welcome and straight forward way to install <b>OpenSSL</b>.
You find it under the Tools node.
\section BuildInstructions_Get_Source Get a source tree
Since MITK is under active development we recommend to use Git to check out
the latest stable release from the homepage. If you decide to use the most
current nightly release, make sure to get a stable tree: Check the
<a href="https://cdash.mitk.org/index.php?project=MITK">MITK dashboard</a>
before checking out. If the build tree is not clean, you can specify an
older revision for the checkout or get a stable tar ball from
<a href="https://www.mitk.org">www.mitk.org</a>.
To clone MITK's current Git repository do:
\code
git clone https://phabricator.mitk.org/source/mitk.git MITK
\endcode
\section BuildInstructions_Build_With_CMake Build MITK with CMake
Create a new directory for the superbuild binary tree, change to it and call CMake:
In the shell (assuming your current directory is the same as the one where you
issued the git clone command):
\code
mkdir MITK-superbuild
cd MITK-superbuild
ccmake ../MITK
\endcode
If you use <b>Windows</b> or prefer to use the CMake GUI, start the CMake GUI and enter the
location of the source tree and binary tree, choose a suitable generator
and configure the project.
CMake will present you a couple of options, these are the most important ones:
- <tt><b>CMAKE_PREFIX_PATH</b></tt> The path to your Qt installation, e.g., <i>C:/Qt/5.12.9/msvc2017_64</i> or <i>/home/user/Qt/5.12.9/gcc_64</i>
- <tt><b>MITK_USE_BLUEBERRY</b></tt> Build the BlueBerry application framework
- <tt><b>MITK_USE_Boost_LIBRARIES</b></tt> If you need binary Boost libraries,
specify them here.
- <tt><b>MITK_USE_OpenCV</b></tt> Build MITK code which depends on OpenCV (this
will download and build OpenCV 2.4)
- <tt><b>MITK_USE_Python3</b></tt> Enables Python wrapping in MITK. This will also
configure ITK, VTK, and OpenCV (if enabled) to build Python wrappers.
- - <tt><b>MITK_USE_Qt5</b></tt> Build MITK code which depends on Qt 5
+ - <tt><b>MITK_USE_Qt6</b></tt> Build MITK code which depends on Qt 6
If you are satisfied with the configuration of your MITK superbuild, generate
the project files with CMake by pressing "Generate".
<b>Linux</b> and <b>macOS</b> users usually just enter "make" (optionally
supplying the number threads to be used for a parallel build):
\code
make -j6
\endcode
<b>Windows</b> users using Visual Studio can open the generated
<tt>MITK-superbuild.sln</tt> solution file in the <tt>MITK-superbuild</tt>
directory and start the build by building the <tt>BUILD_ALL</tt> project.
\section BuildInstructions_Customize Customize your MITK superbuild
The MITK superbuild configures MITK as well as all external libraries. The
build directories of these libraries, and of MITK itself are located inside
the <tt>MITK-superbuild</tt> directory. For example, the directory layout may
look like:
\code
MITK-superbuild
|- ep "external projects"
|-bin
|-lib
|-include
|-src
|- MITK-build
\endcode
To change the configuration of the MITK build itself, choose the MITK-build directory
as the binary directory in the CMake GUI (not the MITK-superbuild directory).
After generating the project files, build the MITK project by either issuing "make"
in the MITK-build directory (Linux, macOS), or by opening MITK-build/MITK.sln (Windows).
You may also change the configuration of any project configured via the
superbuild process. Make sure to also build the changed project and also the
projects which depend on it.
\section BuildInstructions_Running Running Applications
On Linux, just execute the application you want to run. MITK executables are
located in <tt>MITK-superbuild/MITK-build/bin</tt>
On Windows, the <tt>PATH</tt> environment variable must contain the directories
containing the third-party libraries. This is automatically done from Visual Studio.
For running the applications directly use the generated batch files in the
<tt>MITK-superbuild/MITK-build/bin</tt>.
\section BuildInstructions_Documentation Documentation
If you have the <a href="https://www.doxygen.nl/">Doxygen</a> documentation tool
installed, you get a new project (Visual Studio) or "make" target named "doc".
You can build this to generate the HTML documentation of MITK in the
Documentation/Doxygen directory of your MITK-build binary tree or in the
<tt>MITK_DOXYGEN_OUTPUT_DIR</tt> CMake variable (if specified).
\section BuildInstructions_As_Toolkit Use MITK in your own project (as a toolkit)
To use MITK in your external project, add the CMake command
<code>find_package(MITK REQUIRED)</code> to your CMakeLists.txt and make use of
the CMake macros <code>mitk_create_module()</code> and
<code>mitk_create_executable()</code> provided by MITK.
Here is a very basic example CMakeLists.txt including MITK as a project:
\code
cmake_minimum_required(VERSION 3.18 FATAL_ERROR)
project(MyProject)
find_package(MITK 2023.12 REQUIRED)
add_executable(MyApp main.cpp)
target_link_libraries(MyApp MitkCore)
\endcode
with the main.cpp being
\code
#include <iostream>
#include <mitkLog.h>
int main()
{
MITK_INFO << "Hello world!";
return 0;
}
\endcode
\section BuildInstructions_Advanced_Customization Superbuild customization
You can inject pre-build third-party libraries into the MITK superbuild by
setting certain CMake variables before the first configure step. MITK will
then use these third-party libraries instead of downloading and building them
by itself. Note that you must take care of configuring those libraries with all options
MITK requires.
The variables listed below are provided for injecting third-party libraries.
Their occurrence in the CMake GUI or in ccmake may depend on specific
MITK_USE_* options set to ON. You may also use the variable names below without
the <tt>EXTERNAL_</tt> prefix, for example when providing their values on a
command line call to CMake.
- <tt><b>EXTERNAL_BOOST_ROOT</b></tt> Set this variable to your custom Boost
installation
- <tt><b>EXTERNAL_CTK_DIR</b></tt> Set this variable to your CTK binary tree
(the directory containing the CTKConfig.cmake file)
- <tt><b>EXTERNAL_CableSwig_DIR</b></tt> Set this variable to your CableSwig
binary tree for Python wrapping (the directory containing the
CableSwigConfig.cmake file)
- <tt><b>EXTERNAL_DCMTK_DIR</b></tt> Set this variable to your DCMTK binary
tree (the directory containing the DCMTKConfig.cmake file)
- <tt><b>EXTERNAL_GDCM_DIR</b></tt> Set this variable to your GDCM binary
tree (the directory containing the GDCMConfig.cmake file)
- <tt><b>EXTERNAL_ITK_DIR</b></tt> Set this variable to your ITK binary tree
(the directory containing the ITKConfig.cmake file)
- <tt><b>EXTERNAL_OpenCV_DIR</b></tt> Set this variable to your OpenCV binary
tree (the directory containing the OpenCVConfig.cmake file)
- <tt><b>EXTERNAL_VTK_DIR</b></tt> Set this variable to your VTK binary tree
(the directory containing the VTKConfig.cmake file)
To set CMake options before the first configure step is invoked, supply them
on the command line, i.e.
\code
ccmake -DITK_DIR:PATH=/opt/ITK-release ../MITK
\endcode
*/
diff --git a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/HowToNewProject.dox b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/HowToNewProject.dox
index c2c773f4bc..a73c5243c5 100644
--- a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/HowToNewProject.dox
+++ b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/HowToNewProject.dox
@@ -1,230 +1,230 @@
/**
\page HowToNewProject Creating a new MITK project
\tableofcontents
This page is intended to give a comprehensive guide to setting up your own MITK based
project. It will use the application framework provided by MITK and is probably the
preferred way for most users.
The first part of this document is a tutorial aimed at newcomers to MITK and possibly
%CMake and tries to give as much help as possible on setting up your own project. If
you are looking for more technical information about customizing MITK, the structure
of the superbuild or packaging you might want to read the
\ref HowToNewProjectAdvancedInformation.
If you have set up your MITK project already and want to start developing you could
take a look at \ref TutorialPage.
\section HowToNewProjectGettingStarted Getting Started
Use the <a href="https://github.com/MITK/MITK-ProjectTemplate">MITK project template</a> as an
example-based project template.
\section HowToNewProjectPrerequisites Prerequisites
What ever option you choose, a MITK-based project needs essentially the same
prerequisites as MITK itself. Please see \ref BuildInstructions_Prerequisites for
details.
\note If you use one of the two options above you will \b not \b need to build MITK
yourself. This will be done automatically.
\section HowToNewProjectCreatingSourceDir Preparing your source directory
In order to start developing with MITK, you first have to set up the source directory
for your project.
\subsection HowToNewProjectSourceUsingTemplate Using the MITK Project Template
Download the project as a tarball or zipball and extract it to your desired source
directory.
\note This is a <b>template</b>. You must modify it such that it fits the needs of
your particular project. Especially you should do a global search and replace for
the string "awesome" to rename the template application and plug-in. You may want
to rename some files too.
\section HowToNewProjectGeneratingCMake Generating your binary with CMake
After you have set up your source directory you can proceed to generate your binary
directory using %CMake. Depending on your operating system and preferences you might
want to use "cmake-gui" or "ccmake" (shell). This document assumes you are using
cmake-gui.
<ol>
<li> Start "cmake-gui" and enter your source (e.g. "D:/AwesomeProject") and binary
directory (e.g. "D:/AwesomeProject-superbuild").
<li> Upon first pressing "Configure" you will be prompted to select your generator.
This determines what project files will be generated by %CMake. Set this to the
development tool you are intending to use (e.g. "Visual Studio 2010 64Bit" or
"linux makefiles".
<li> Press "Configure" until no new variables appear and then "Generate". Now all
project files have been generated into your binary directory.
<li> Double-check that the right Qt version is used.
</ol>
Now you are ready to compile your code. Depending on your choice of tool this will
be done differently, we cover two possibilities here.
\subsection HowToNewProjectCompilingLinuxMakefiles Compiling using linux makefiles
<ol>
<li> In the shell, switch to your binary directory.
<li> type "make" and hit enter
</ol>
\subsection HowToNewProjectCompilingVisualStudio Compiling using visual studio
We assume your application is called "AwesomeApp" and your project "AwesomeProject"
and your binary directory is "D:/AwesomeProject-superbuild/". Replace names and
paths accordingly.
<ol>
<li> Close %CMake and open "D:/AwesomeProject-superbuild/AwesomeProject-superbuild.sln".
Your Visual Studio should appear and by pressing F7 you start the compilation.
This will clone the MITK source code, build it, and then start building your own
project.
<li> After the superbuild compilation has finished, close the superbuild solution file and start
the build solution file "D:/AwesomeProject-superbuild/AwesomeProject-build/AwesomeProject.sln"
<li> Set the "AwesomeApp" project as start-up project (right click > "Set as StartUp
Project") and press "F5" to start your MITK AwesomeApp.
</ol>
\note Just opening AwesomeProject.sln from your explorer by double-cliking won`t
allow you to start or debug your application because the required environment
variables would be missing. Use the supplied batch files or set your PATH variable
accordingly.
\section HowToNewProjectAddingMITKFunctionality I want to use some MITK plugin but
it is not available
Due to the sheer number of MITK plugins not every plugin is activated by default.
To activate a specific plugin (again replace paths as needed):
<ol>
<li> Start "cmake-gui" and set the binary directory to
"D:/AwesomeProject-superbuild/MITK-superbuild/MITK-build/", the source will
adjust automatically and you will see new settings appear.
<li> Navigate to the plugin you want to use (e.g. "MITK_BUILD_org.mitk.gui.qt.segmentation")
and tick the checkbox behind it
<li> Press "Configure" until no new variables appear and then "Generate".
<li> Build MITK using your development tool (as in
\ref HowToNewProjectCompilingLinuxMakefiles or \ref HowToNewProjectCompilingVisualStudio
only in the "D:/AwesomeProject-superbuild/MITK-superbuild/MITK-build/" directory )
<li> Start "cmake-gui" and set the binary directory to
"D:/AwesomeProject-superbuild/AwesomeProject-build/", the source will adjust
automatically and you will see new settings appear.
<li> Press "Configure" until no new variables appear and then "Generate".
<li> Build your project
<li> Start your application
</ol>
\note If you want to use an application provided by MITK (e.g. MITK Workbench) you
have to tick the appropriate checkbox as well (in this case MITK_BUILD_APP_Workbench)
and build MITK. Do note, that this application will be located in the bin directory
of the "D:/AwesomeProject-superbuild/MITK-superbuild/MITK-build/" folder.
\section HowToNewProjectAdvancedInformation Information for advanced users
\subsection HowToNewProjectCustomizingMITK Customizing MITK
You can either inject an already build MITK to be used by your project or configure
some MITK options directly in your project's superbuild configuration if MITK is
going to be build inside your project.
\subsection HowToNewProjectCustomizingMITKInjectMITK Inject a MITK build
By setting the \b EXTERNAL_MITK_DIR \b variable in your project's superbuild
%CMake configuration to a MITK build directory (containing the MITKConfig.cmake)
you can skip the MITK build process.
If MITK is the only external project in your project, you might want to disable
the superbuild of your project completely (set <your-proj-name>_USE_SUPERBUILD
to OFF or edit your CMakeLists.txt file to set it to OFF by default) and set
the \b MITK_DIR \b %CMake variable to your MITK build directory.
\subsection HowToNewProjectCustomizingMITKConfigure Configure the MITK superbuild
If MITK is being build inside your project's superbuild process, you can enable
the use of certain third-party libraries inside of MITK. The following variables
control the MITK configuration:
<ul>
<li> \b MITK_USE_BLUEBERRY Enable the use of the BlueBerry application framework
<li> \b MITK_USE_CTK Download, compile, and use CTK in MITK
<li> \b MITK_USE_DCMTK Download, compile, and use DCMTK in MITK
<li> \b MITK_USE_OpenCV Download, compile, and use OpenCV in MITK
<li> \b MITK_USE_Python3 Download and compile 1CableSwig and enable Python
wrapping in ITK, VTK, OpenCV, and MITK
- <li> \b MITK_USE_Qt5 Use the Qt 5 framework in MITK
+ <li> \b MITK_USE_Qt6 Use the Qt 6 framework in MITK
</ul>
You can also inject already build third-party libraries from inside your project's
superbuild in the MITK superbuild by using any of the following %CMake variables:
<ul>
<li> \b MITK_CTK_DIR Reuse a CTK build directory in MITK.
<li> \b MITK_CableSwig_DIR Reuse a 1CableSwig build directory in MITK.
<li> \b MITK_DCMTK_DIR Reuse a DCMKT build directory in MITK.
<li> \b MITK_GDCM_DIR Reuse a GDCM build directory in MITK.
<li> \b MITK_ITK_DIR Reuse a ITK build directory in MITK.
<li> \b MITK_OpenCV_DIR Reuse a OpenCV build directory in MITK.
<li> \b MITK_VTK_DIR Reuse a VTK build directory in MITK.
</ul>
If the corresponding \b MITK_USE_<proj> \b option is set to on, the MITK
superbuild will use the provided build directory instead of building the
project itself.
You can also control the source code location for MITK in your project's
superbuild configuration by using the following %CMake variables:
<ul>
<li> \b MITK_SOURCE_DIR The path to the MITK source directory. If the value
for this variable is non-empty, the variables below are ignored.
<li> \b MITK_GIT_REPOSITORY The Git repository containing the MITK source code.
<li> \b MITK_GIT_TAG The hash id, tag or branch name used for a checkout
from MITK_GIT_REPOSITORY.
</ul>
\subsection HowToNewProjectProjectStructure Project Structure
If you are using the superbuild feature of the generated project (the default),
you might want to familiarise yourself with the layout of your build tree.
The top-level build directory which you specified in %CMake when configuring
your project will contain all the required dependencies.
Suppose we call our project MyProject and the build directory is
"C:\MyProject-superbuild". Then the layout looks something like this:
MyProjectLayout.png The top-level directory contains the source code and the
build directories from the dependencies of your project. In the current case,
the only dependency of MyProject is MITK, which in turn has downloaded and built
its own dependencies (CTK, DCMTK, ITK, etc.). The "real" build tree for your
project is located in MyProject-superbuild/MyProject-build, so point the
%CMake-GUI to this build directory if you want to change the set of enabled
plug-ins for example.
Further, you should open the MyProject.sln solution file (for Visual Studio)
or execute "make" in the MyProject-superbuild/MyProject-build/ directory.
Only for the very first time or if you want to update and newly build the
project's dependencies should you use the project files in the
MyProject-superbuild directory directly.
The same applies for the MyProject-superbuild/MITK-superbuild directory. This
directory contains the MITK superbuild, nested inside your project's superbuild.
If you want to change %CMake options for MITK, use the
MyProject-superbuild/MITK-superbuild/MITK-build build directory.
\imageMacro{HowToNewProject-MyProjectLayout.png,"Layout of MyProject",4.02}
\subsection HowToNewProjectPackaging Packaging
You can create deployable packages of your project
for all supported operating systems my building the PACKAGE target. On Linux,
this will create a tarball, on MacOS a .dmg file, and on Windows a zipball and
an NSIS installer (if NSIS is installed and found).
You can read more about deployment \ref DeploymentPage "here".
*/
diff --git a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/SupportedPlatforms.md b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/SupportedPlatforms.md
index 3d03b00901..c5aee5a224 100644
--- a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/SupportedPlatforms.md
+++ b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/SupportedPlatforms.md
@@ -1,56 +1,56 @@
Supported Platforms {#SupportedPlatformsPage}
===================
MITK is a cross-platform framework that is available for the following platforms:
- Windows
- Linux
- macOS
Supported Platforms Details
---------------------------
The MITK team provides support for the most frequently used platforms and continuously runs testing procedures
to ensure compatibility. Due to the large amount of possible combinations of operating systems and compiler versions,
we divide platform support into two test categories: Tier 1 and Tier 2.
Although MITK may be built on a broader range of platform-compiler combinations, only a subset of these are actively
supported by the MITK development team.
In general, only 64-bit builds are supported.
Tier 1 Platforms
----------------
All Tier 1 platforms are continuously tested by our unit test suite and other internal testing procedures.
Errors or bugs discovered in these platforms are prioritized and corrected as soon as possible.
| Platform | Compilers
| ----------------------------------- | --------------------------------------------------
| Microsoft Windows 10 | Visual Studio 2022
| Linux Ubuntu 22.04 | Default GCC version
| Linux Ubuntu 20.04 | Default GCC version
Tier 2 Platforms
----------------
Tier 2 platforms may or may not be tested on a regular basis. Some Tier 2 platforms are used by individual
members of the MITK development team on a daily basis and some only receive occasional testing. While we
strive to support these platforms, MITK users should note that errors may be present in released versions
as well as in the current master branch.
| Platform | Compilers
| ----------------------------------- | --------------------------------------------------
| Microsoft Windows 11 | Visual Studio 2022
| Microsoft Windows 10 | Visual Studio 2019
-| Apple macOS 13 Ventura | Default Apple Clang version
-| Apple macOS 12 Monterey | Default Apple Clang version
+| Apple macOS Ventura 13 | Default Apple Clang version
+| Apple macOS Monterey 12 | Default Apple Clang version
All platforms not listed above are not officially supported by the MITK team. However, we will happily accept
contributions to improve support for other platforms as long as we have the hardware and capacity for maintenance.
CI Build Clients
----------------
To get an overview of currently tested platforms, see the <a href="https://cdash.mitk.org/index.php?project=MITK">build reports on our CDash site</a>.
diff --git a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/ThirdPartyLibs.dox b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/ThirdPartyLibs.dox
index b96e8c8e25..b688859b3c 100644
--- a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/ThirdPartyLibs.dox
+++ b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/ThirdPartyLibs.dox
@@ -1,111 +1,107 @@
/**
\page thirdpartylibs Third-party libraries
The following third-party libraries can be used with MITK by default and can, in part, be automatically downloaded during superbuild.
\par ACVD
https://www.creatis.insa-lyon.fr/~valette/public/project/acvd/
\par ANN
https://www.cs.umd.edu/~mount/ANN/
\par Boost
https://www.boost.org/
\par C++ REST SDK
https://github.com/Microsoft/cpprestsdk/
\par CppUnit
https://sourceforge.net/projects/cppunit/
\par CTK
https://commontk.org/
\par DCMTK
https://dicom.offis.de/dcmtk
\par Eigen
https://eigen.tuxfamily.org/index.php?title=Main_Page
\par GDCM
https://gdcm.sourceforge.net/
\par HDF5
https://support.hdfgroup.org/HDF5/
\par ITK
https://itk.org/
\par JSON for Modern C++
https://github.com/nlohmann/json
\par lz4
https://github.com/lz4/lz4
\par MatchPoint
https://www.dkfz.de/en/sidt/projects/MatchPoint/info.html
-\par OpenCL
-
-https://www.khronos.org/opencl/
-
\par OpenCV
https://opencv.org/
\par OpenIGTLink
http://openigtlink.org/
\par PCRE
https://www.pcre.org/
\par POCO
https://pocoproject.org/
\par Python
https://www.python.org/
\par Qt
https://www.qt.io/
\par Qwt
https://qwt.sourceforge.io/
\par SWIG
https://www.swig.org/
\par TinyXML-2
https://www.grinninglizard.com/tinyxml2/
\par VTK
https://vtk.org/
\par zlib
https://zlib.net/
For copyright information on any of the above toolkits see the corresponding home page or the corresponding source folder.
*/
diff --git a/Documentation/Doxygen/3-DeveloperManual/Toolkit/ModuleManuals/MITKModuleManualsList.dox b/Documentation/Doxygen/3-DeveloperManual/Toolkit/ModuleManuals/MITKModuleManualsList.dox
index 1891d949b6..3aa31fd1c3 100644
--- a/Documentation/Doxygen/3-DeveloperManual/Toolkit/ModuleManuals/MITKModuleManualsList.dox
+++ b/Documentation/Doxygen/3-DeveloperManual/Toolkit/ModuleManuals/MITKModuleManualsList.dox
@@ -1,35 +1,34 @@
/**
\page MITKModuleManualsListPage MITK Module Manuals
Overview
The modules are shared libraries that provide functionality that can be used by developers.
\subpage MITKModuleManualsList List of Module Manuals
<ul>
<li> \ref AnnotationModulePage
<li> \ref ChartModule
<li> \ref IGTConcepts
<li> \ref NavigationGeneralModulePage
<li> \ref IGTTutorialOverview
- <li> \ref MitkOpenCL_Overview
<li> \ref LegacyGLModule
<li> \ref mitkPython_Overview
<li> \ref RESTModule
<li> \ref GeneratingDeviceModulesPage
<li> \ref USModulePage
</ul>
\subpage MITKModuleManualsListPageAdditionalInformation Additional Information on Certain Modules
<ul>
<li> \ref PlanarPropertiesPage
</ul>
\subpage MITKMigrationGuides Migration Guides
<ul>
<li> \ref GeometryMigration
<li> \ref InteractionMigration
<li> \ref OverlayMigration
</ul>
*/
diff --git a/Documentation/doxygen.conf.in b/Documentation/doxygen.conf.in
index 8f0be3626e..613c132a49 100644
--- a/Documentation/doxygen.conf.in
+++ b/Documentation/doxygen.conf.in
@@ -1,2841 +1,2840 @@
# Doxyfile 1.9.6
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a double hash (##) is considered a comment and is placed in
# front of the TAG it is preceding.
#
# All text after a single hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists, items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (\" \").
#
# Note:
#
# Use doxygen to compare the used configuration file with the template
# configuration file:
# doxygen -x [configFile]
# Use doxygen to compare the used configuration file with the template
# configuration file without replacing the environment variables or CMake type
# replacement variables:
# doxygen -x_noenv [configFile]
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
# This tag specifies the encoding used for all characters in the configuration
# file that follow. The default is UTF-8 which is also the encoding used for all
# text before the first occurrence of this tag. Doxygen uses libiconv (or the
# iconv built into libc) for the transcoding. See
# https://www.gnu.org/software/libiconv/ for the list of possible encodings.
# The default value is: UTF-8.
DOXYFILE_ENCODING = UTF-8
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
# double-quotes, unless you are using Doxywizard) that should identify the
# project for which the documentation is generated. This name is used in the
# title of most generated pages and in a few other places.
# The default value is: My Project.
PROJECT_NAME = "Medical Imaging Interaction Toolkit"
# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER = @MITK_VERSION_STRING@
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
# quick idea about the purpose of the project. Keep the description short.
PROJECT_BRIEF = "Medical Imaging Interaction Toolkit"
# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
# in the documentation. The maximum height of the logo should not exceed 55
# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
# the logo to the output directory.
PROJECT_LOGO =
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = @MITK_DOXYGEN_OUTPUT_DIR@
# If the CREATE_SUBDIRS tag is set to YES then doxygen will create up to 4096
# sub-directories (in 2 levels) under the output directory of each output format
# and will distribute the generated files over these directories. Enabling this
# option can be useful when feeding doxygen a huge amount of source files, where
# putting all generated files in the same directory would otherwise causes
# performance problems for the file system. Adapt CREATE_SUBDIRS_LEVEL to
# control the number of sub-directories.
# The default value is: NO.
CREATE_SUBDIRS = NO
# Controls the number of sub-directories that will be created when
# CREATE_SUBDIRS tag is set to YES. Level 0 represents 16 directories, and every
# level increment doubles the number of directories, resulting in 4096
# directories at level 8 which is the default and also the maximum value. The
# sub-directories are organized in 2 levels, the first level always has a fixed
# number of 16 directories.
# Minimum value: 0, maximum value: 8, default value: 8.
# This tag requires that the tag CREATE_SUBDIRS is set to YES.
CREATE_SUBDIRS_LEVEL = 8
# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
# characters to appear in the names of generated files. If set to NO, non-ASCII
# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
# U+3044.
# The default value is: NO.
ALLOW_UNICODE_NAMES = NO
# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Bulgarian,
# Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, English
# (United States), Esperanto, Farsi (Persian), Finnish, French, German, Greek,
# Hindi, Hungarian, Indonesian, Italian, Japanese, Japanese-en (Japanese with
# English messages), Korean, Korean-en (Korean with English messages), Latvian,
# Lithuanian, Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese,
# Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish,
# Swedish, Turkish, Ukrainian and Vietnamese.
# The default value is: English.
OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
# descriptions after the members that are listed in the file and class
# documentation (similar to Javadoc). Set to NO to disable this.
# The default value is: YES.
BRIEF_MEMBER_DESC = YES
# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
# description of a member or function before the detailed description
#
# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
# The default value is: YES.
REPEAT_BRIEF = YES
# This tag implements a quasi-intelligent brief description abbreviator that is
# used to form the text in various listings. Each string in this list, if found
# as the leading text of the brief description, will be stripped from the text
# and the result, after processing the whole list, is used as the annotated
# text. Otherwise, the brief description is used as-is. If left blank, the
# following values are used ($name is automatically replaced with the name of
# the entity):The $name class, The $name widget, The $name file, is, provides,
# specifies, contains, represents, a, an and the.
ABBREVIATE_BRIEF =
# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# doxygen will generate a detailed section even if there is only a brief
# description.
# The default value is: NO.
ALWAYS_DETAILED_SEC = NO
# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
# inherited members of a class in the documentation of that class as if those
# members were ordinary class members. Constructors, destructors and assignment
# operators of the base classes will not be shown.
# The default value is: NO.
INLINE_INHERITED_MEMB = NO
# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
# before files name in the file list and in the header files. If set to NO the
# shortest path that makes the file name unique will be used
# The default value is: YES.
FULL_PATH_NAMES = NO
# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
# Stripping is only done if one of the specified strings matches the left-hand
# part of the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the path to
# strip.
#
# Note that you can specify absolute paths here, but also relative paths, which
# will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES.
STRIP_FROM_PATH =
# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
# path mentioned in the documentation of a class, which tells the reader which
# header file to include in order to use a class. If left blank only the name of
# the header file containing the class definition is used. Otherwise one should
# specify the list of include paths that are normally passed to the compiler
# using the -I flag.
STRIP_FROM_INC_PATH =
# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
# less readable) file names. This can be useful is your file systems doesn't
# support long names like on DOS, Mac, or CD-ROM.
# The default value is: NO.
SHORT_NAMES = NO
# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
# first line (until the first dot) of a Javadoc-style comment as the brief
# description. If set to NO, the Javadoc-style will behave just like regular Qt-
# style comments (thus requiring an explicit @brief command for a brief
# description.)
# The default value is: NO.
JAVADOC_AUTOBRIEF = NO
# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line
# such as
# /***************
# as being the beginning of a Javadoc-style comment "banner". If set to NO, the
# Javadoc-style will behave just like regular comments and it will not be
# interpreted by doxygen.
# The default value is: NO.
JAVADOC_BANNER = NO
# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
# line (until the first dot) of a Qt-style comment as the brief description. If
# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
# requiring an explicit \brief command for a brief description.)
# The default value is: NO.
QT_AUTOBRIEF = NO
# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
# a brief description. This used to be the default behavior. The new default is
# to treat a multi-line C++ comment block as a detailed description. Set this
# tag to YES if you prefer the old behavior instead.
#
# Note that setting this tag to YES also means that rational rose comments are
# not recognized any more.
# The default value is: NO.
MULTILINE_CPP_IS_BRIEF = NO
# By default Python docstrings are displayed as preformatted text and doxygen's
# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the
# doxygen's special commands can be used and the contents of the docstring
# documentation blocks is shown as doxygen documentation.
# The default value is: YES.
PYTHON_DOCSTRING = YES
# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
# documentation from any documented member that it re-implements.
# The default value is: YES.
INHERIT_DOCS = YES
# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
# page for each member. If set to NO, the documentation of a member will be part
# of the file/class/namespace that contains it.
# The default value is: NO.
SEPARATE_MEMBER_PAGES = NO
# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
# uses this value to replace tabs by spaces in code fragments.
# Minimum value: 1, maximum value: 16, default value: 4.
TAB_SIZE = 8
# This tag can be used to specify a number of aliases that act as commands in
# the documentation. An alias has the form:
# name=value
# For example adding
# "sideeffect=@par Side Effects:^^"
# will allow you to put the command \sideeffect (or @sideeffect) in the
# documentation, which will result in a user-defined paragraph with heading
# "Side Effects:". Note that you cannot put \n's in the value part of an alias
# to insert newlines (in the resulting output). You can put ^^ in the value part
# of an alias to insert a newline as if a physical newline was in the original
# file. When you need a literal { or } or , in the value part of an alias you
# have to escape them by means of a backslash (\), this can lead to conflicts
# with the commands \{ and \} for these it is advised to use the version @{ and
# @} or use a double escape (\\{ and \\})
ALIASES = "FIXME=\par Fix Me's:\n" \
"BlueBerry=\if BLUEBERRY" \
"endBlueBerry=\endif" \
"bundlemainpage{1}=\page \1" \
"embmainpage{1}=\page \1" \
"github{2}=<a href=\"https://github.com/MITK/MITK/blob/master/\1\">\2</a>" \
"deprecatedSince{1}=\xrefitem deprecatedSince\1 \"\" \"Functions deprecated as of \1\" \deprecated (as of \1)" \
"minimumCMakeVersion=@MITK_CMAKE_MINIMUM_REQUIRED_VERSION@" \
- "minimumQt5Version=@MITK_QT5_MINIMUM_VERSION@" \
+ "minimumQt6Version=@MITK_QT6_MINIMUM_VERSION@" \
"imageMacro{3}=\image html \1 \2 \n \image latex \1 \2 width=\3cm" \
"developersguidemainpage{1}=\page \1" \
"usersguidemainpage{1}=\page \1" \
"nondependentPluginLink{3}= \ref \1 \"\3\""
# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
# only. Doxygen will then generate output that is more tailored for C. For
# instance, some of the names that are used will be different. The list of all
# members will be omitted, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_FOR_C = NO
# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
# Python sources only. Doxygen will then generate output that is more tailored
# for that language. For instance, namespaces will be presented as packages,
# qualified scopes will look different, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_JAVA = NO
# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
# sources. Doxygen will then generate output that is tailored for Fortran.
# The default value is: NO.
OPTIMIZE_FOR_FORTRAN = NO
# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
# sources. Doxygen will then generate output that is tailored for VHDL.
# The default value is: NO.
OPTIMIZE_OUTPUT_VHDL = NO
# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice
# sources only. Doxygen will then generate output that is more tailored for that
# language. For instance, namespaces will be presented as modules, types will be
# separated into more groups, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_SLICE = NO
# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given
# extension. Doxygen has a built-in mapping, but you can override or extend it
# using this tag. The format is ext=language, where ext is a file extension, and
# language is one of the parsers supported by doxygen: IDL, Java, JavaScript,
# Csharp (C#), C, C++, Lex, D, PHP, md (Markdown), Objective-C, Python, Slice,
# VHDL, Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:
# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser
# tries to guess whether the code is fixed or free formatted code, this is the
# default for Fortran type files). For instance to make doxygen treat .inc files
# as Fortran files (default is PHP), and .f files as C (default is Fortran),
# use: inc=Fortran f=C.
#
# Note: For files without extension you can use no_extension as a placeholder.
#
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen. When specifying no_extension you should add
# * to the FILE_PATTERNS.
#
# Note see also the list of default file extension mappings.
EXTENSION_MAPPING = cmake=c++
# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable
# documentation. See https://daringfireball.net/projects/markdown/ for details.
# The output of markdown processing is further processed by doxygen, so you can
# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
# case of backward compatibilities issues.
# The default value is: YES.
MARKDOWN_SUPPORT = YES
# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
# to that level are automatically included in the table of contents, even if
# they do not have an id attribute.
# Note: This feature currently applies only to Markdown headings.
# Minimum value: 0, maximum value: 99, default value: 5.
# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
TOC_INCLUDE_HEADINGS = 5
# When enabled doxygen tries to link words that correspond to documented
# classes, or namespaces to their corresponding documentation. Such a link can
# be prevented in individual cases by putting a % sign in front of the word or
# globally by setting AUTOLINK_SUPPORT to NO.
# The default value is: YES.
AUTOLINK_SUPPORT = YES
# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
# to include (a tag file for) the STL sources as input, then you should set this
# tag to YES in order to let doxygen match functions declarations and
# definitions whose arguments contain STL classes (e.g. func(std::string);
# versus func(std::string) {}). This also make the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate.
# The default value is: NO.
BUILTIN_STL_SUPPORT = YES
# If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support.
# The default value is: NO.
CPP_CLI_SUPPORT = NO
# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen
# will parse them like normal C++ but will assume all classes use public instead
# of private inheritance when no explicit protection keyword is present.
# The default value is: NO.
SIP_SUPPORT = NO
# For Microsoft's IDL there are propget and propput attributes to indicate
# getter and setter methods for a property. Setting this option to YES will make
# doxygen to replace the get and set methods by a property in the documentation.
# This will only work if the methods are indeed getting or setting a simple
# type. If this is not the case, or you want to show the methods anyway, you
# should set this option to NO.
# The default value is: YES.
IDL_PROPERTY_SUPPORT = YES
# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
# tag is set to YES then doxygen will reuse the documentation of the first
# member in the group (if any) for the other members of the group. By default
# all members of a group must be documented explicitly.
# The default value is: NO.
DISTRIBUTE_GROUP_DOC = YES
# If one adds a struct or class to a group and this option is enabled, then also
# any nested class or struct is added to the same group. By default this option
# is disabled and one has to add nested compounds explicitly via \ingroup.
# The default value is: NO.
GROUP_NESTED_COMPOUNDS = NO
# Set the SUBGROUPING tag to YES to allow class member groups of the same type
# (for instance a group of public functions) to be put as a subgroup of that
# type (e.g. under the Public Functions section). Set it to NO to prevent
# subgrouping. Alternatively, this can be done per class using the
# \nosubgrouping command.
# The default value is: YES.
SUBGROUPING = YES
# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
# are shown inside the group in which they are included (e.g. using \ingroup)
# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
# and RTF).
#
# Note that this feature does not work in combination with
# SEPARATE_MEMBER_PAGES.
# The default value is: NO.
INLINE_GROUPED_CLASSES = NO
# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
# with only public data fields or simple typedef fields will be shown inline in
# the documentation of the scope in which they are defined (i.e. file,
# namespace, or group documentation), provided this scope is documented. If set
# to NO, structs, classes, and unions are shown on a separate page (for HTML and
# Man pages) or section (for LaTeX and RTF).
# The default value is: NO.
INLINE_SIMPLE_STRUCTS = NO
# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
# enum is documented as struct, union, or enum with the name of the typedef. So
# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
# with name TypeT. When disabled the typedef will appear as a member of a file,
# namespace, or class. And the struct will be named TypeS. This can typically be
# useful for C code in case the coding convention dictates that all compound
# types are typedef'ed and only the typedef is referenced, never the tag name.
# The default value is: NO.
TYPEDEF_HIDES_STRUCT = NO
# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
# cache is used to resolve symbols given their name and scope. Since this can be
# an expensive process and often the same symbol appears multiple times in the
# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
# doxygen will become slower. If the cache is too large, memory is wasted. The
# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
# symbols. At the end of a run doxygen will report the cache usage and suggest
# the optimal cache size from a speed point of view.
# Minimum value: 0, maximum value: 9, default value: 0.
LOOKUP_CACHE_SIZE = 0
# The NUM_PROC_THREADS specifies the number of threads doxygen is allowed to use
# during processing. When set to 0 doxygen will based this on the number of
# cores available in the system. You can set it explicitly to a value larger
# than 0 to get more control over the balance between CPU load and processing
# speed. At this moment only the input processing can be done using multiple
# threads. Since this is still an experimental feature the default is set to 1,
# which effectively disables parallel processing. Please report any issues you
# encounter. Generating dot graphs in parallel is controlled by the
# DOT_NUM_THREADS setting.
# Minimum value: 0, maximum value: 32, default value: 1.
NUM_PROC_THREADS = 1
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
# documentation are documented, even if no documentation was available. Private
# class members and static file members will be hidden unless the
# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
# Note: This will also disable the warnings about undocumented members that are
# normally produced when WARNINGS is set to YES.
# The default value is: NO.
EXTRACT_ALL = YES
# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
# be included in the documentation.
# The default value is: NO.
EXTRACT_PRIVATE = NO
# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual
# methods of a class will be included in the documentation.
# The default value is: NO.
EXTRACT_PRIV_VIRTUAL = NO
# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
# scope will be included in the documentation.
# The default value is: NO.
EXTRACT_PACKAGE = NO
# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
# included in the documentation.
# The default value is: NO.
EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
# locally in source files will be included in the documentation. If set to NO,
# only classes defined in header files are included. Does not have any effect
# for Java sources.
# The default value is: YES.
EXTRACT_LOCAL_CLASSES = @MITK_DOXYGEN_INTERNAL_DOCS@
# This flag is only useful for Objective-C code. If set to YES, local methods,
# which are defined in the implementation section but not in the interface are
# included in the documentation. If set to NO, only methods in the interface are
# included.
# The default value is: NO.
EXTRACT_LOCAL_METHODS = NO
# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base name of
# the file that contains the anonymous namespace. By default anonymous namespace
# are hidden.
# The default value is: NO.
EXTRACT_ANON_NSPACES = NO
# If this flag is set to YES, the name of an unnamed parameter in a declaration
# will be determined by the corresponding definition. By default unnamed
# parameters remain unnamed in the output.
# The default value is: YES.
RESOLVE_UNNAMED_PARAMS = YES
# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
# undocumented members inside documented classes or files. If set to NO these
# members will be included in the various overviews, but no documentation
# section is generated. This option has no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy. If set
# to NO, these classes will be included in the various overviews. This option
# will also hide undocumented C++ concepts if enabled. This option has no effect
# if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_CLASSES = NO
# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
# declarations. If set to NO, these declarations will be included in the
# documentation.
# The default value is: NO.
HIDE_FRIEND_COMPOUNDS = @MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS@
# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
# documentation blocks found inside the body of a function. If set to NO, these
# blocks will be appended to the function's detailed documentation block.
# The default value is: NO.
HIDE_IN_BODY_DOCS = NO
# The INTERNAL_DOCS tag determines if documentation that is typed after a
# \internal command is included. If the tag is set to NO then the documentation
# will be excluded. Set it to YES to include the internal documentation.
# The default value is: NO.
INTERNAL_DOCS = @MITK_DOXYGEN_INTERNAL_DOCS@
# With the correct setting of option CASE_SENSE_NAMES doxygen will better be
# able to match the capabilities of the underlying filesystem. In case the
# filesystem is case sensitive (i.e. it supports files in the same directory
# whose names only differ in casing), the option must be set to YES to properly
# deal with such files in case they appear in the input. For filesystems that
# are not case sensitive the option should be set to NO to properly deal with
# output files written for symbols that only differ in casing, such as for two
# classes, one named CLASS and the other named Class, and to also support
# references to files without having to specify the exact matching casing. On
# Windows (including Cygwin) and MacOS, users should typically set this option
# to NO, whereas on Linux or other Unix flavors it should typically be set to
# YES.
# Possible values are: SYSTEM, NO and YES.
# The default value is: SYSTEM.
CASE_SENSE_NAMES = YES
# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
# their full class and namespace scopes in the documentation. If set to YES, the
# scope will be hidden.
# The default value is: NO.
HIDE_SCOPE_NAMES = NO
# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
# append additional text to a page's title, such as Class Reference. If set to
# YES the compound reference will be hidden.
# The default value is: NO.
HIDE_COMPOUND_REFERENCE= NO
# If the SHOW_HEADERFILE tag is set to YES then the documentation for a class
# will show which file needs to be included to use the class.
# The default value is: YES.
SHOW_HEADERFILE = YES
# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
# the files that are included by a file in the documentation of that file.
# The default value is: YES.
SHOW_INCLUDE_FILES = YES
# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
# grouped member an include statement to the documentation, telling the reader
# which file to include in order to use the member.
# The default value is: NO.
SHOW_GROUPED_MEMB_INC = NO
# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
# files with double quotes in the documentation rather than with sharp brackets.
# The default value is: NO.
FORCE_LOCAL_INCLUDES = NO
# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
# documentation for inline members.
# The default value is: YES.
INLINE_INFO = YES
# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
# (detailed) documentation of file and class members alphabetically by member
# name. If set to NO, the members will appear in declaration order.
# The default value is: YES.
SORT_MEMBER_DOCS = YES
# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
# descriptions of file, namespace and class members alphabetically by member
# name. If set to NO, the members will appear in declaration order. Note that
# this will also influence the order of the classes in the class list.
# The default value is: NO.
SORT_BRIEF_DOCS = NO
# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
# (brief and detailed) documentation of class members so that constructors and
# destructors are listed first. If set to NO the constructors will appear in the
# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
# member documentation.
# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
# detailed member documentation.
# The default value is: NO.
SORT_MEMBERS_CTORS_1ST = NO
# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
# of group names into alphabetical order. If set to NO the group names will
# appear in their defined order.
# The default value is: NO.
SORT_GROUP_NAMES = NO
# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
# fully-qualified names, including namespaces. If set to NO, the class list will
# be sorted only by class name, not including the namespace part.
# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
# Note: This option applies only to the class list, not to the alphabetical
# list.
# The default value is: NO.
SORT_BY_SCOPE_NAME = YES
# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
# type resolution of all parameters of a function it will reject a match between
# the prototype and the implementation of a member function even if there is
# only one candidate or it is obvious which candidate to choose by doing a
# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
# accept a match between prototype and implementation in such cases.
# The default value is: NO.
STRICT_PROTO_MATCHING = NO
# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
# list. This list is created by putting \todo commands in the documentation.
# The default value is: YES.
GENERATE_TODOLIST = @MITK_DOXYGEN_GENERATE_TODOLIST@
# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
# list. This list is created by putting \test commands in the documentation.
# The default value is: YES.
GENERATE_TESTLIST = YES
# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
# list. This list is created by putting \bug commands in the documentation.
# The default value is: YES.
GENERATE_BUGLIST = @MITK_DOXYGEN_GENERATE_BUGLIST@
# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
# the deprecated list. This list is created by putting \deprecated commands in
# the documentation.
# The default value is: YES.
GENERATE_DEPRECATEDLIST= @MITK_DOXYGEN_GENERATE_DEPRECATEDLIST@
# The ENABLED_SECTIONS tag can be used to enable conditional documentation
# sections, marked by \if <section_label> ... \endif and \cond <section_label>
# ... \endcond blocks.
ENABLED_SECTIONS = @MITK_DOXYGEN_ENABLED_SECTIONS@
# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
# initial value of a variable or macro / define can have for it to appear in the
# documentation. If the initializer consists of more lines than specified here
# it will be hidden. Use a value of 0 to hide initializers completely. The
# appearance of the value of individual variables and macros / defines can be
# controlled using \showinitializer or \hideinitializer command in the
# documentation regardless of this setting.
# Minimum value: 0, maximum value: 10000, default value: 30.
MAX_INITIALIZER_LINES = 0
# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
# the bottom of the documentation of classes and structs. If set to YES, the
# list will mention the files that were used to generate the documentation.
# The default value is: YES.
SHOW_USED_FILES = YES
# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
# will remove the Files entry from the Quick Index and from the Folder Tree View
# (if specified).
# The default value is: YES.
SHOW_FILES = YES
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
# page. This will remove the Namespaces entry from the Quick Index and from the
# Folder Tree View (if specified).
# The default value is: YES.
SHOW_NAMESPACES = YES
# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
# the version control system). Doxygen will invoke the program by executing (via
# popen()) the command command input-file, where command is the value of the
# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
# by doxygen. Whatever the program writes to standard output is used as the file
# version. For an example see the documentation.
FILE_VERSION_FILTER =
# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
# by doxygen. The layout file controls the global structure of the generated
# output files in an output format independent way. To create the layout file
# that represents doxygen's defaults, run doxygen with the -l option. You can
# optionally specify a file name after the option, if omitted DoxygenLayout.xml
# will be used as the name of the layout file. See also section "Changing the
# layout of pages" for information.
#
# Note that if you run doxygen from a directory containing a file called
# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
# tag is left empty.
LAYOUT_FILE = @MITK_SOURCE_DIR@/Documentation/MITKDoxygenLayout.xml
# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
# the reference definitions. This must be a list of .bib files. The .bib
# extension is automatically appended if omitted. This requires the bibtex tool
# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.
# For LaTeX the style of the bibliography can be controlled using
# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
# search path. See also \cite for info how to create references.
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
# The QUIET tag can be used to turn on/off the messages that are generated to
# standard output by doxygen. If QUIET is set to YES this implies that the
# messages are off.
# The default value is: NO.
QUIET = YES
# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
# this implies that the warnings are on.
#
# Tip: Turn warnings on while writing the documentation.
# The default value is: YES.
WARNINGS = YES
# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: YES.
WARN_IF_UNDOCUMENTED = YES
# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
# potential errors in the documentation, such as documenting some parameters in
# a documented function twice, or documenting parameters that don't exist or
# using markup commands wrongly.
# The default value is: YES.
WARN_IF_DOC_ERROR = YES
# If WARN_IF_INCOMPLETE_DOC is set to YES, doxygen will warn about incomplete
# function parameter documentation. If set to NO, doxygen will accept that some
# parameters have no documentation without warning.
# The default value is: YES.
WARN_IF_INCOMPLETE_DOC = YES
# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
# are documented, but have no documentation for their parameters or return
# value. If set to NO, doxygen will only warn about wrong parameter
# documentation, but not about the absence of documentation. If EXTRACT_ALL is
# set to YES then this flag will automatically be disabled. See also
# WARN_IF_INCOMPLETE_DOC
# The default value is: NO.
WARN_NO_PARAMDOC = NO
# If WARN_IF_UNDOC_ENUM_VAL option is set to YES, doxygen will warn about
# undocumented enumeration values. If set to NO, doxygen will accept
# undocumented enumeration values. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: NO.
WARN_IF_UNDOC_ENUM_VAL = NO
# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS
# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but
# at the end of the doxygen process doxygen will return with a non-zero status.
# Possible values are: NO, YES and FAIL_ON_WARNINGS.
# The default value is: NO.
WARN_AS_ERROR = NO
# The WARN_FORMAT tag determines the format of the warning messages that doxygen
# can produce. The string should contain the $file, $line, and $text tags, which
# will be replaced by the file and line number from which the warning originated
# and the warning text. Optionally the format may contain $version, which will
# be replaced by the version of the file (if it could be obtained via
# FILE_VERSION_FILTER)
# See also: WARN_LINE_FORMAT
# The default value is: $file:$line: $text.
WARN_FORMAT = "$file:$line: $text"
# In the $text part of the WARN_FORMAT command it is possible that a reference
# to a more specific place is given. To make it easier to jump to this place
# (outside of doxygen) the user can define a custom "cut" / "paste" string.
# Example:
# WARN_LINE_FORMAT = "'vi $file +$line'"
# See also: WARN_FORMAT
# The default value is: at line $line of file $file.
WARN_LINE_FORMAT = "at line $line of file $file"
# The WARN_LOGFILE tag can be used to specify a file to which warning and error
# messages should be written. If left blank the output is written to standard
# error (stderr). In case the file specified cannot be opened for writing the
# warning and error messages are written to standard error. When as file - is
# specified the warning and error messages are written to standard output
# (stdout).
WARN_LOGFILE =
#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------
# The INPUT tag is used to specify the files and/or directories that contain
# documented source files. You may enter file names like myfile.cpp or
# directories like /usr/src/myproject. Separate the files or directories with
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
# Note: If this tag is empty the current directory is searched.
INPUT = "@MITK_SOURCE_DIR@" \
"@MITK_BINARY_DIR@" \
@MITK_DOXYGEN_ADDITIONAL_INPUT_DIRS@
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
# documentation (see:
# https://www.gnu.org/software/libiconv/) for the list of possible encodings.
# See also: INPUT_FILE_ENCODING
# The default value is: UTF-8.
INPUT_ENCODING = UTF-8
# This tag can be used to specify the character encoding of the source files
# that doxygen parses The INPUT_FILE_ENCODING tag can be used to specify
# character encoding on a per file pattern basis. Doxygen will compare the file
# name with each pattern and apply the encoding instead of the default
# INPUT_ENCODING) if there is a match. The character encodings are a list of the
# form: pattern=encoding (like *.php=ISO-8859-1). See cfg_input_encoding
# "INPUT_ENCODING" for further information on supported encodings.
INPUT_FILE_ENCODING =
# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# read by doxygen.
#
# Note the list of default checked file patterns might differ from the list of
# default file extension mappings.
#
# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
# *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php, *.php4, *.php5, *.phtml,
# *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C
# comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd,
# *.vhdl, *.ucf, *.qsf and *.ice.
FILE_PATTERNS = *.h \
*.dox \
*.md
# The RECURSIVE tag can be used to specify whether or not subdirectories should
# be searched for input files as well.
# The default value is: NO.
RECURSIVE = YES
# The EXCLUDE tag can be used to specify files and/or directories that should be
# excluded from the INPUT source files. This way you can easily exclude a
# subdirectory from a directory tree whose root is specified with the INPUT tag.
#
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE = "@MITK_SOURCE_DIR@/Utilities/qtsingleapplication/" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/core/doc/snippets/" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/core/doc/doxygen/standalone/" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/core/test/" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/core/examples/" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/core/src/util/jsoncpp.cpp" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/third_party" \
"@MITK_SOURCE_DIR@/CMake/PackageDepends" \
"@MITK_SOURCE_DIR@/CMakeExternals" \
"@MITK_SOURCE_DIR@/Licenses" \
"@MITK_BINARY_DIR@/Documentation/Doxygen" \
"@MITK_BINARY_DIR@/bin/" \
"@MITK_BINARY_DIR@/PT/" \
"@MITK_BINARY_DIR@/GP/" \
"@MITK_BINARY_DIR@/_CPack_Packages/" \
@MITK_DOXYGEN_ADDITIONAL_EXCLUDE_DIRS@
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
# from the input.
# The default value is: NO.
EXCLUDE_SYMLINKS = NO
# If the value of the INPUT tag contains directories, you can use the
# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
# certain files from those directories.
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/*
EXCLUDE_PATTERNS = README* \
moc_* \
ui_* \
qrc_* \
wrap_* \
Register* \
*/files.cmake \
*/.git/* \
*_p.h \
*Private.* \
*/Internal/* \
*/internal/* \
*/Snippets/* \
*/snippets/* \
*/testing/* \
*/Testing/* \
*/test/* \
*/resource/* \
"@MITK_BINARY_DIR@/*.cmake" \
@MITK_DOXYGEN_EXCLUDE_PATTERNS@
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# ANamespace::AClass, ANamespace::*Test
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/*
EXCLUDE_SYMBOLS =
# The EXAMPLE_PATH tag can be used to specify one or more files or directories
# that contain example code fragments that are included (see the \include
# command).
EXAMPLE_PATH = "@MITK_SOURCE_DIR@/Examples/" \
"@MITK_SOURCE_DIR@/Examples/Tutorial/" \
"@MITK_SOURCE_DIR@/Examples/Plugins/" \
"@MITK_SOURCE_DIR@/Examples/QtFreeRender/" \
"@MITK_SOURCE_DIR@/Modules/Core/" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/core/doc/snippets/" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/core/examples/" \
"@MITK_SOURCE_DIR@/Modules/CppMicroServices/" \
- "@MITK_SOURCE_DIR@/Modules/OpenCL/Documentation/doxygen/snippets/" \
"@MITK_SOURCE_DIR@/Modules/IGT/Tutorial/" \
"@MITK_SOURCE_DIR@/Plugins/org.mitk.gui.common/src/" \
"@MITK_SOURCE_DIR@/Plugins/org.mitk.gui.qt.igtexamples/" \
"@MITK_SOURCE_DIR@/Plugins/org.mitk.gui.qt.igttracking/"
# If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank all
# files are included.
EXAMPLE_PATTERNS =
# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
# searched for input files to be used with the \include or \dontinclude commands
# irrespective of the value of the RECURSIVE tag.
# The default value is: NO.
EXAMPLE_RECURSIVE = YES
# The IMAGE_PATH tag can be used to specify one or more files or directories
# that contain images that are to be included in the documentation (see the
# \image command).
IMAGE_PATH = "@MITK_SOURCE_DIR@/Documentation/Doxygen/" \
"@MITK_SOURCE_DIR@" \
@MITK_DOXYGEN_ADDITIONAL_IMAGE_PATHS@
# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command:
#
# <filter> <input-file>
#
# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
# name of an input file. Doxygen will then use the output that the filter
# program writes to standard output. If FILTER_PATTERNS is specified, this tag
# will be ignored.
#
# Note that the filter must not add or remove lines; it is applied before the
# code is scanned, but not when the output code is generated. If lines are added
# or removed, the anchors will not be placed correctly.
#
# Note that doxygen will use the data processed and written to standard output
# for further processing, therefore nothing else, like debug statements or used
# commands (so in case of a Windows batch file always use @echo OFF), should be
# written to standard output.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# properly processed by doxygen.
INPUT_FILTER =
# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
# basis. Doxygen will compare the file name with each pattern and apply the
# filter if there is a match. The filters are a list of the form: pattern=filter
# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
# patterns match the file name, INPUT_FILTER is applied.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# properly processed by doxygen.
FILTER_PATTERNS = *.cmake=@CMakeDoxygenFilter_EXECUTABLE@
# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER) will also be used to filter the input files that are used for
# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
# The default value is: NO.
FILTER_SOURCE_FILES = NO
# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
# it is also possible to disable source filtering for a specific pattern using
# *.ext= (so without naming a filter).
# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
FILTER_SOURCE_PATTERNS =
# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
# is part of the input, its contents will be placed on the main page
# (index.html). This can be useful if you have a project on for instance GitHub
# and want to reuse the introduction page also for the doxygen output.
USE_MDFILE_AS_MAINPAGE =
# The Fortran standard specifies that for fixed formatted Fortran code all
# characters from position 72 are to be considered as comment. A common
# extension is to allow longer lines before the automatic comment starts. The
# setting FORTRAN_COMMENT_AFTER will also make it possible that longer lines can
# be processed before the automatic comment starts.
# Minimum value: 7, maximum value: 10000, default value: 72.
FORTRAN_COMMENT_AFTER = 72
#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------
# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
# generated. Documented entities will be cross-referenced with these sources.
#
# Note: To get rid of all source code in the generated output, make sure that
# also VERBATIM_HEADERS is set to NO.
# The default value is: NO.
SOURCE_BROWSER = YES
# Setting the INLINE_SOURCES tag to YES will include the body of functions,
# classes and enums directly into the documentation.
# The default value is: NO.
INLINE_SOURCES = NO
# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
# special comment blocks from generated source code fragments. Normal C, C++ and
# Fortran comments will always remain visible.
# The default value is: YES.
STRIP_CODE_COMMENTS = YES
# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
# entity all documented functions referencing it will be listed.
# The default value is: NO.
REFERENCED_BY_RELATION = YES
# If the REFERENCES_RELATION tag is set to YES then for each documented function
# all documented entities called/used by that function will be listed.
# The default value is: NO.
REFERENCES_RELATION = YES
# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
# to YES then the hyperlinks from functions in REFERENCES_RELATION and
# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
# link to the documentation.
# The default value is: YES.
REFERENCES_LINK_SOURCE = YES
# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
# source code will show a tooltip with additional information such as prototype,
# brief description and links to the definition and documentation. Since this
# will make the HTML file larger and loading of large files a bit slower, you
# can opt to disable this feature.
# The default value is: YES.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
SOURCE_TOOLTIPS = YES
# If the USE_HTAGS tag is set to YES then the references to source code will
# point to the HTML generated by the htags(1) tool instead of doxygen built-in
# source browser. The htags tool is part of GNU's global source tagging system
# (see https://www.gnu.org/software/global/global.html). You will need version
# 4.8.6 or higher.
#
# To use it do the following:
# - Install the latest version of global
# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file
# - Make sure the INPUT points to the root of the source tree
# - Run doxygen as normal
#
# Doxygen will invoke htags (and that will in turn invoke gtags), so these
# tools must be available from the command line (i.e. in the search path).
#
# The result: instead of the source browser generated by doxygen, the links to
# source code will now point to the output of htags.
# The default value is: NO.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
USE_HTAGS = NO
# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
# verbatim copy of the header file for each class for which an include is
# specified. Set to NO to disable this.
# See also: Section \class.
# The default value is: YES.
VERBATIM_HEADERS = YES
# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
# clang parser (see:
# http://clang.llvm.org/) for more accurate parsing at the cost of reduced
# performance. This can be particularly helpful with template rich C++ code for
# which doxygen's built-in parser lacks the necessary type information.
# Note: The availability of this option depends on whether or not doxygen was
# generated with the -Duse_libclang=ON option for CMake.
# The default value is: NO.
CLANG_ASSISTED_PARSING = NO
# If the CLANG_ASSISTED_PARSING tag is set to YES and the CLANG_ADD_INC_PATHS
# tag is set to YES then doxygen will add the directory of each input to the
# include path.
# The default value is: YES.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
CLANG_ADD_INC_PATHS = YES
# If clang assisted parsing is enabled you can provide the compiler with command
# line options that you would normally use when invoking the compiler. Note that
# the include paths will already be set by doxygen for the files and directories
# specified with INPUT and INCLUDE_PATH.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
CLANG_OPTIONS =
# If clang assisted parsing is enabled you can provide the clang parser with the
# path to the directory containing a file called compile_commands.json. This
# file is the compilation database (see:
# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the
# options used when the source files were built. This is equivalent to
# specifying the -p option to a clang tool, such as clang-check. These options
# will then be passed to the parser. Any options specified with CLANG_OPTIONS
# will be added as well.
# Note: The availability of this option depends on whether or not doxygen was
# generated with the -Duse_libclang=ON option for CMake.
CLANG_DATABASE_PATH =
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
# compounds will be generated. Enable this if the project contains a lot of
# classes, structs, unions or interfaces.
# The default value is: YES.
ALPHABETICAL_INDEX = YES
# The IGNORE_PREFIX tag can be used to specify a prefix (or a list of prefixes)
# that should be ignored while generating the index headers. The IGNORE_PREFIX
# tag works for classes, function and member names. The entity will be placed in
# the alphabetical list under the first letter of the entity name that remains
# after removing the prefix.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
# The default value is: YES.
GENERATE_HTML = YES
# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_OUTPUT = html
# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
# generated HTML page (for example: .htm, .php, .asp).
# The default value is: .html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FILE_EXTENSION = .html
# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
# each generated HTML page. If the tag is left blank doxygen will generate a
# standard header.
#
# To get valid HTML the header file that includes any scripts and style sheets
# that doxygen needs, which is dependent on the configuration options used (e.g.
# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
# default header using
# doxygen -w html new_header.html new_footer.html new_stylesheet.css
# YourConfigFile
# and then modify the file new_header.html. See also section "Doxygen usage"
# for information on how to generate the default header that doxygen normally
# uses.
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. For a description
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_HEADER =
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
# footer. See HTML_HEADER for more information on how to generate a default
# footer and what special commands can be used inside the footer. See also
# section "Doxygen usage" for information on how to generate the default footer
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FOOTER =
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
# the HTML output. If left blank doxygen will generate a default style sheet.
# See also section "Doxygen usage" for information on how to generate the style
# sheet that doxygen normally uses.
# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
# it is more robust and this tag (HTML_STYLESHEET) will in the future become
# obsolete.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_STYLESHEET =
# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# cascading style sheets that are included after the standard style sheets
# created by doxygen. Using this option one can overrule certain style aspects.
# This is preferred over using HTML_STYLESHEET since it does not replace the
# standard style sheet and is therefore more robust against future updates.
# Doxygen will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list).
# Note: Since the styling of scrollbars can currently not be overruled in
# Webkit/Chromium, the styling will be left out of the default doxygen.css if
# one or more extra stylesheets have been specified. So if scrollbar
# customization is desired it has to be added explicitly. For an example see the
# documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET = @MITK_DOXYGEN_STYLESHEET@
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
# that these files will be copied to the base HTML output directory. Use the
# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_FILES = "@MITK_SOURCE_DIR@/Documentation/Doxygen/mitkLogo.jpg"
# The HTML_COLORSTYLE tag can be used to specify if the generated HTML output
# should be rendered with a dark or light theme.
# Possible values are: LIGHT always generate light mode output, DARK always
# generate dark mode output, AUTO_LIGHT automatically set the mode according to
# the user preference, use light mode if no preference is set (the default),
# AUTO_DARK automatically set the mode according to the user preference, use
# dark mode if no preference is set and TOGGLE allow to user to switch between
# light and dark mode via a button.
# The default value is: AUTO_LIGHT.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE = AUTO_LIGHT
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the style sheet and background images according to
# this color. Hue is specified as an angle on a color-wheel, see
# https://en.wikipedia.org/wiki/Hue for more information. For instance the value
# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
# purple, and 360 is red again.
# Minimum value: 0, maximum value: 359, default value: 220.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_HUE = 220
# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
# in the HTML output. For a value of 0 the output will use gray-scales only. A
# value of 255 will produce the most vivid colors.
# Minimum value: 0, maximum value: 255, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_SAT = 100
# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
# luminance component of the colors in the HTML output. Values below 100
# gradually make the output lighter, whereas values above 100 make the output
# darker. The value divided by 100 is the actual gamma applied, so 80 represents
# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
# change the gamma.
# Minimum value: 40, maximum value: 240, default value: 80.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting this
# to YES can help to show when doxygen was last run and thus if the
# documentation is up to date.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_TIMESTAMP = YES
# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML
# documentation will contain a main index with vertical navigation menus that
# are dynamically created via JavaScript. If disabled, the navigation index will
# consists of multiple levels of tabs that are statically embedded in every HTML
# page. Disable this option to support browsers that do not have JavaScript,
# like the Qt help browser.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_MENUS = YES
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_SECTIONS = @MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS@
# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
# shown in the various tree structured indices initially; the user can expand
# and collapse entries dynamically later on. Doxygen will expand the tree to
# such a level that at most the specified number of entries are visible (unless
# a fully collapsed tree already exceeds this amount). So setting the number of
# entries 1 will produce a full collapsed tree by default. 0 is a special value
# representing an infinite number of entries and will result in a full expanded
# tree by default.
# Minimum value: 0, maximum value: 9999, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_INDEX_NUM_ENTRIES = 100
# If the GENERATE_DOCSET tag is set to YES, additional index files will be
# generated that can be used as input for Apple's Xcode 3 integrated development
# environment (see:
# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To
# create a documentation set, doxygen will generate a Makefile in the HTML
# output directory. Running make will produce the docset in that directory and
# running make install will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy
# genXcode/_index.html for more information.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_DOCSET = NO
# This tag determines the name of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# The default value is: Doxygen generated docs.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDNAME = "Doxygen generated docs"
# This tag determines the URL of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDURL =
# This tag specifies a string that should uniquely identify the documentation
# set bundle. This should be a reverse domain-name style string, e.g.
# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_BUNDLE_ID = org.doxygen.Project
# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
# The default value is: org.doxygen.Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
# The default value is: Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_NAME = Publisher
# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
# on Windows. In the beginning of 2021 Microsoft took the original page, with
# a.o. the download links, offline the HTML help workshop was already many years
# in maintenance mode). You can download the HTML help workshop from the web
# archives at Installation executable (see:
# http://web.archive.org/web/20160201063255/http://download.microsoft.com/downlo
# ad/0/A/9/0A939EF6-E31C-430F-A3DF-DFAE7960D564/htmlhelp.exe).
#
# The HTML Help Workshop contains a compiler that can convert all HTML output
# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
# files are now used as the Windows 98 help format, and will replace the old
# Windows help format (.hlp) on all Windows platforms in the future. Compressed
# HTML files also contain an index, a table of contents, and you can search for
# words in the documentation. The HTML workshop also contains a viewer for
# compressed HTML files.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_HTMLHELP = NO
# The CHM_FILE tag can be used to specify the file name of the resulting .chm
# file. You can add a path in front of the file if the result should not be
# written to the html output directory.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_FILE =
# The HHC_LOCATION tag can be used to specify the location (absolute path
# including file name) of the HTML help compiler (hhc.exe). If non-empty,
# doxygen will try to run the HTML help compiler on the generated index.hhp.
# The file has to be specified with full path.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
HHC_LOCATION =
# The GENERATE_CHI flag controls if a separate .chi index file is generated
# (YES) or that it should be included in the main .chm file (NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
GENERATE_CHI = NO
# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
# and project file content.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_INDEX_ENCODING =
# The BINARY_TOC flag controls whether a binary table of contents is generated
# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
# enables the Previous and Next buttons.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
BINARY_TOC = NO
# The TOC_EXPAND flag can be set to YES to add extra items for group members to
# the table of contents of the HTML help documentation and to the tree view.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
TOC_EXPAND = NO
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
# (.qch) of the generated HTML documentation.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_QHP = @MITK_DOXYGEN_GENERATE_QHP@
# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
# the file name of the resulting .qch file. The path specified is relative to
# the HTML output folder.
# This tag requires that the tag GENERATE_QHP is set to YES.
QCH_FILE = @MITK_DOXYGEN_QCH_FILE@
# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
# Project output. For more information please see Qt Help Project / Namespace
# (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_NAMESPACE = org.mitk
# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
# Help Project output. For more information please see Qt Help Project / Virtual
# Folders (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).
# The default value is: doc.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_VIRTUAL_FOLDER = MITK
# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
# filter to add. For more information please see Qt Help Project / Custom
# Filters (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_NAME =
# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
# custom filter to add. For more information please see Qt Help Project / Custom
# Filters (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_ATTRS =
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_SECT_FILTER_ATTRS =
# The QHG_LOCATION tag can be used to specify the location (absolute path
# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to
# run qhelpgenerator on the generated .qhp file.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHG_LOCATION = @QT_HELPGENERATOR_EXECUTABLE@
# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
# generated, together with the HTML files, they form an Eclipse help plugin. To
# install this plugin and make it available under the help contents menu in
# Eclipse, the contents of the directory containing the HTML and XML files needs
# to be copied into the plugins directory of eclipse. The name of the directory
# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
# After copying Eclipse needs to be restarted before the help appears.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_ECLIPSEHELP = NO
# A unique identifier for the Eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have this
# name. Each documentation set should have its own identifier.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
ECLIPSE_DOC_ID = org.doxygen.Project
# If you want full control over the layout of the generated HTML pages it might
# be necessary to disable the index and replace it with your own. The
# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
# of each HTML page. A value of NO enables the index and the value YES disables
# it. Since the tabs in the index contain the same information as the navigation
# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
DISABLE_INDEX = NO
# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information. If the tag
# value is set to YES, a side panel will be generated containing a tree-like
# index structure (just like the one that is generated for HTML Help). For this
# to work a browser that supports JavaScript, DHTML, CSS and frames is required
# (i.e. any modern browser). Windows users are probably better off using the
# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
# further fine tune the look of the index (see "Fine-tuning the output"). As an
# example, the default style sheet generated by doxygen has an example that
# shows how to put an image at the root of the tree instead of the PROJECT_NAME.
# Since the tree basically has the same information as the tab index, you could
# consider setting DISABLE_INDEX to YES when enabling this option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_TREEVIEW = YES
# When both GENERATE_TREEVIEW and DISABLE_INDEX are set to YES, then the
# FULL_SIDEBAR option determines if the side bar is limited to only the treeview
# area (value NO) or if it should extend to the full height of the window (value
# YES). Setting this to YES gives a layout similar to
# https://docs.readthedocs.io with more room for contents, but less room for the
# project logo, title, and description. If either GENERATE_TREEVIEW or
# DISABLE_INDEX is set to NO, this option has no effect.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
FULL_SIDEBAR = NO
# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
# doxygen will group on one line in the generated HTML documentation.
#
# Note that a value of 0 will completely suppress the enum values from appearing
# in the overview section.
# Minimum value: 0, maximum value: 20, default value: 4.
# This tag requires that the tag GENERATE_HTML is set to YES.
ENUM_VALUES_PER_LINE = 4
# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
# to set the initial width (in pixels) of the frame in which the tree is shown.
# Minimum value: 0, maximum value: 1500, default value: 250.
# This tag requires that the tag GENERATE_HTML is set to YES.
TREEVIEW_WIDTH = 300
# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
# external symbols imported via tag files in a separate window.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
EXT_LINKS_IN_WINDOW = NO
# If the OBFUSCATE_EMAILS tag is set to YES, doxygen will obfuscate email
# addresses.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
OBFUSCATE_EMAILS = YES
# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg
# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see
# https://inkscape.org) to generate formulas as SVG images instead of PNGs for
# the HTML output. These images will generally look nicer at scaled resolutions.
# Possible values are: png (the default) and svg (looks nicer but requires the
# pdf2svg or inkscape tool).
# The default value is: png.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FORMULA_FORMAT = png
# Use this tag to change the font size of LaTeX formulas included as images in
# the HTML documentation. When you change the font size after a successful
# doxygen run you need to manually remove any form_*.png images from the HTML
# output directory to force them to be regenerated.
# Minimum value: 8, maximum value: 50, default value: 10.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_FONTSIZE = 10
# The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands
# to create new LaTeX commands to be used in formulas as building blocks. See
# the section "Including formulas" for details.
FORMULA_MACROFILE =
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
# https://www.mathjax.org) which uses client side JavaScript for the rendering
# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
# installed or if you want to formulas look prettier in the HTML output. When
# enabled you may also need to install MathJax separately and configure the path
# to it using the MATHJAX_RELPATH option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
USE_MATHJAX = YES
# With MATHJAX_VERSION it is possible to specify the MathJax version to be used.
# Note that the different versions of MathJax have different requirements with
# regards to the different settings, so it is possible that also other MathJax
# settings have to be changed when switching between the different MathJax
# versions.
# Possible values are: MathJax_2 and MathJax_3.
# The default value is: MathJax_2.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_VERSION = MathJax_2
# When MathJax is enabled you can set the default output format to be used for
# the MathJax output. For more details about the output format see MathJax
# version 2 (see:
# http://docs.mathjax.org/en/v2.7-latest/output.html) and MathJax version 3
# (see:
# http://docs.mathjax.org/en/latest/web/components/output.html).
# Possible values are: HTML-CSS (which is slower, but has the best
# compatibility. This is the name for Mathjax version 2, for MathJax version 3
# this will be translated into chtml), NativeMML (i.e. MathML. Only supported
# for NathJax 2. For MathJax version 3 chtml will be used instead.), chtml (This
# is the name for Mathjax version 3, for MathJax version 2 this will be
# translated into HTML-CSS) and SVG.
# The default value is: HTML-CSS.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_FORMAT = HTML-CSS
# When MathJax is enabled you need to specify the location relative to the HTML
# output directory using the MATHJAX_RELPATH option. The destination directory
# should contain the MathJax.js script. For instance, if the mathjax directory
# is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
# Content Delivery Network so you can quickly see the result without installing
# MathJax. However, it is strongly recommended to install a local copy of
# MathJax from https://www.mathjax.org before deployment. The default value is:
# - in case of MathJax version 2: https://cdn.jsdelivr.net/npm/mathjax@2
# - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_RELPATH = http://www.mathjax.org/mathjax
# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example
# for MathJax version 2 (see
# https://docs.mathjax.org/en/v2.7-latest/tex.html#tex-and-latex-extensions):
# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
# For example for MathJax version 3 (see
# http://docs.mathjax.org/en/latest/input/tex/extensions/index.html):
# MATHJAX_EXTENSIONS = ams
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_EXTENSIONS =
# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
# of code that will be used on startup of the MathJax code. See the MathJax site
# (see:
# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an
# example see the documentation.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_CODEFILE =
# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
# the HTML output. The underlying search engine uses javascript and DHTML and
# should work on any modern browser. Note that when using HTML help
# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
# there is already a search function so this one should typically be disabled.
# For large projects the javascript based search engine can be slow, then
# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
# search using the keyboard; to jump to the search box use <access key> + S
# (what the <access key> is depends on the OS and browser, but it is typically
# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
# key> to jump into the search results window, the results can be navigated
# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
# the search. The filter options can be selected when the cursor is inside the
# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
# to select a filter and <Enter> or <escape> to activate or cancel the filter
# option.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
SEARCHENGINE = YES
# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
# implemented using a web server instead of a web client using JavaScript. There
# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
# setting. When disabled, doxygen will generate a PHP script for searching and
# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
# and searching needs to be provided by external tools. See the section
# "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
SERVER_BASED_SEARCH = NO
# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
# script for searching. Instead the search results are written to an XML file
# which needs to be processed by an external indexer. Doxygen will invoke an
# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
# search results.
#
# Doxygen ships with an example indexer (doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see:
# https://xapian.org/).
#
# See the section "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH = NO
# The SEARCHENGINE_URL should point to a search engine hosted by a web server
# which will return the search results when EXTERNAL_SEARCH is enabled.
#
# Doxygen ships with an example indexer (doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see:
# https://xapian.org/). See the section "External Indexing and Searching" for
# details.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHENGINE_URL =
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
# search data is written to a file for indexing by an external tool. With the
# SEARCHDATA_FILE tag the name of this file can be specified.
# The default file is: searchdata.xml.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHDATA_FILE = searchdata.xml
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
# projects and redirect the results back to the right project.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH_ID =
# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
# projects other than the one defined by this configuration file, but that are
# all added to the same external search index. Each project needs to have a
# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
# to a relative location where the documentation can be found. The format is:
# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
# The default value is: YES.
GENERATE_LATEX = NO
# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_OUTPUT = latex
# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
# invoked.
#
# Note that when not enabling USE_PDFLATEX the default is latex when enabling
# USE_PDFLATEX the default is pdflatex and when in the later case latex is
# chosen this is overwritten by pdflatex. For specific output languages the
# default can have been set differently, this depends on the implementation of
# the output language.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_CMD_NAME = latex
# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
# index for LaTeX.
# Note: This tag is used in the Makefile / make.bat.
# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file
# (.tex).
# The default file is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
MAKEINDEX_CMD_NAME = makeindex
# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to
# generate index for LaTeX. In case there is no backslash (\) as first character
# it will be automatically added in the LaTeX code.
# Note: This tag is used in the generated output file (.tex).
# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.
# The default value is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_MAKEINDEX_CMD = makeindex
# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
COMPACT_LATEX = NO
# The PAPER_TYPE tag can be used to set the paper type that is used by the
# printer.
# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
# 14 inches) and executive (7.25 x 10.5 inches).
# The default value is: a4.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PAPER_TYPE = a4
# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
# that should be included in the LaTeX output. The package can be specified just
# by its name or with the correct syntax as to be used with the LaTeX
# \usepackage command. To get the times font for instance you can specify :
# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
# To use the option intlimits with the amsmath package you can specify:
# EXTRA_PACKAGES=[intlimits]{amsmath}
# If left blank no extra packages will be included.
# This tag requires that the tag GENERATE_LATEX is set to YES.
EXTRA_PACKAGES = amssymb
# The LATEX_HEADER tag can be used to specify a user-defined LaTeX header for
# the generated LaTeX document. The header should contain everything until the
# first chapter. If it is left blank doxygen will generate a standard header. It
# is highly recommended to start with a default header using
# doxygen -w latex new_header.tex new_footer.tex new_stylesheet.sty
# and then modify the file new_header.tex. See also section "Doxygen usage" for
# information on how to generate the default header that doxygen normally uses.
#
# Note: Only use a user-defined header if you know what you are doing!
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. The following
# commands have a special meaning inside the header (and footer): For a
# description of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HEADER =
# The LATEX_FOOTER tag can be used to specify a user-defined LaTeX footer for
# the generated LaTeX document. The footer should contain everything after the
# last chapter. If it is left blank doxygen will generate a standard footer. See
# LATEX_HEADER for more information on how to generate a default footer and what
# special commands can be used inside the footer. See also section "Doxygen
# usage" for information on how to generate the default footer that doxygen
# normally uses. Note: Only use a user-defined footer if you know what you are
# doing!
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_FOOTER =
# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# LaTeX style sheets that are included after the standard style sheets created
# by doxygen. Using this option one can overrule certain style aspects. Doxygen
# will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list).
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EXTRA_STYLESHEET =
# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the LATEX_OUTPUT output
# directory. Note that the files will be copied as-is; there are no commands or
# markers available.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EXTRA_FILES =
# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
# contain links (just like the HTML output) instead of page references. This
# makes the output suitable for online browsing using a PDF viewer.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PDF_HYPERLINKS = NO
# If the USE_PDFLATEX tag is set to YES, doxygen will use the engine as
# specified with LATEX_CMD_NAME to generate the PDF file directly from the LaTeX
# files. Set this option to YES, to get a higher quality PDF documentation.
#
# See also section LATEX_CMD_NAME for selecting the engine.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
USE_PDFLATEX = NO
# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
# command to the generated LaTeX files. This will instruct LaTeX to keep running
# if errors occur, instead of asking the user for help.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BATCHMODE = NO
# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
# index chapters (such as File Index, Compound Index, etc.) in the output.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HIDE_INDICES = NO
# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
# bibliography, e.g. plainnat, or ieeetr. See
# https://en.wikipedia.org/wiki/BibTeX and \cite for more info.
# The default value is: plain.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BIB_STYLE = plain
# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
# page will contain the date and time when the page was generated. Setting this
# to NO can help when comparing the output of multiple runs.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_TIMESTAMP = NO
# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)
# path from which the emoji images will be read. If a relative path is entered,
# it will be relative to the LATEX_OUTPUT directory. If left blank the
# LATEX_OUTPUT directory will be used.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EMOJI_DIRECTORY =
#---------------------------------------------------------------------------
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
# RTF output is optimized for Word 97 and may not look too pretty with other RTF
# readers/editors.
# The default value is: NO.
GENERATE_RTF = NO
# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: rtf.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_OUTPUT = rtf
# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
COMPACT_RTF = NO
# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
# contain hyperlink fields. The RTF file will contain links (just like the HTML
# output) instead of page references. This makes the output suitable for online
# browsing using Word or some other Word compatible readers that support those
# fields.
#
# Note: WordPad (write) and others do not support links.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_HYPERLINKS = NO
# Load stylesheet definitions from file. Syntax is similar to doxygen's
# configuration file, i.e. a series of assignments. You only have to provide
# replacements, missing definitions are set to their default value.
#
# See also section "Doxygen usage" for information on how to generate the
# default style sheet that doxygen normally uses.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_STYLESHEET_FILE =
# Set optional variables used in the generation of an RTF document. Syntax is
# similar to doxygen's configuration file. A template extensions file can be
# generated using doxygen -e rtf extensionFile.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# Configuration options related to the man page output
#---------------------------------------------------------------------------
# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
# classes and files.
# The default value is: NO.
GENERATE_MAN = NO
# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it. A directory man3 will be created inside the directory specified by
# MAN_OUTPUT.
# The default directory is: man.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_OUTPUT = man
# The MAN_EXTENSION tag determines the extension that is added to the generated
# man pages. In case the manual section does not start with a number, the number
# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
# optional.
# The default value is: .3.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_EXTENSION = .3
# The MAN_SUBDIR tag determines the name of the directory created within
# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
# MAN_EXTENSION with the initial . removed.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_SUBDIR =
# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
# will generate one additional man file for each entity documented in the real
# man page(s). These additional files only source the real man page, but without
# them the man command would be unable to find the correct page.
# The default value is: NO.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_LINKS = NO
#---------------------------------------------------------------------------
# Configuration options related to the XML output
#---------------------------------------------------------------------------
# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
# captures the structure of the code including all documentation.
# The default value is: NO.
GENERATE_XML = NO
# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: xml.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_OUTPUT = xml
# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
# listings (including syntax highlighting and cross-referencing information) to
# the XML output. Note that enabling this will significantly increase the size
# of the XML output.
# The default value is: YES.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_PROGRAMLISTING = YES
# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include
# namespace members in file scope as well, matching the HTML output.
# The default value is: NO.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_NS_MEMB_FILE_SCOPE = NO
#---------------------------------------------------------------------------
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
# that can be used to generate PDF.
# The default value is: NO.
GENERATE_DOCBOOK = NO
# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
# front of it.
# The default directory is: docbook.
# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
DOCBOOK_OUTPUT = docbook
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures
# the structure of the code including all documentation. Note that this feature
# is still experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
# file that captures the structure of the code including all documentation.
#
# Note that this feature is still experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_PERLMOD = NO
# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
# output from the Perl module output.
# The default value is: NO.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_LATEX = NO
# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
# formatted so it can be parsed by a human reader. This is useful if you want to
# understand what is going on. On the other hand, if this tag is set to NO, the
# size of the Perl module output will be much smaller and Perl will parse it
# just the same.
# The default value is: YES.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_PRETTY = YES
# The names of the make variables in the generated doxyrules.make file are
# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
# so different doxyrules.make files included by the same Makefile don't
# overwrite each other's variables.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
# C-preprocessor directives found in the sources and include files.
# The default value is: YES.
ENABLE_PREPROCESSING = YES
# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
# in the source code. If set to NO, only conditional compilation will be
# performed. Macro expansion can be done in a controlled way by setting
# EXPAND_ONLY_PREDEF to YES.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
MACRO_EXPANSION = YES
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
# the macro expansion is limited to the macros specified with the PREDEFINED and
# EXPAND_AS_DEFINED tags.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_ONLY_PREDEF = NO
# If the SEARCH_INCLUDES tag is set to YES, the include files in the
# INCLUDE_PATH will be searched if a #include is found.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SEARCH_INCLUDES = YES
# The INCLUDE_PATH tag can be used to specify one or more directories that
# contain include files that are not input files but should be processed by the
# preprocessor. Note that the INCLUDE_PATH is not recursive, so the setting of
# RECURSIVE has no effect here.
# This tag requires that the tag SEARCH_INCLUDES is set to YES.
INCLUDE_PATH =
# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
# patterns (like *.h and *.hpp) to filter out the header-files in the
# directories. If left blank, the patterns specified with FILE_PATTERNS will be
# used.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
INCLUDE_FILE_PATTERNS =
# The PREDEFINED tag can be used to specify one or more macro names that are
# defined before the preprocessor is started (similar to the -D option of e.g.
# gcc). The argument of the tag is a list of macros of the form: name or
# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
# is assumed. To prevent a macro definition from being undefined via #undef or
# recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
PREDEFINED = itkNotUsed(x)= \
"itkSetMacro(name,type)=virtual void Set##name (type _arg);" \
"itkGetMacro(name,type)=virtual type Get##name ();" \
"itkGetConstMacro(name,type)=virtual type Get##name () const;" \
"itkSetStringMacro(name)=virtual void Set##name (const char* _arg);" \
"itkGetStringMacro(name)=virtual const char* Get##name () const;" \
"itkSetClampMacro(name,type,min,max)=virtual void Set##name (type _arg);" \
"itkSetObjectMacro(name,type)=virtual void Set##name (type* _arg);" \
"itkGetObjectMacro(name,type)=virtual type* Get##name ();" \
"itkSetConstObjectMacro(name,type)=virtual void Set##name ( const type* _arg);" \
"itkGetConstObjectMacro(name,type)=virtual const type* Get##name ();" \
"itkGetConstReferenceMacro(name,type)=virtual const type& Get##name ();" \
"itkGetConstReferenceObjectMacro(name,type)=virtual const type::Pointer& Get##name () const;" \
"itkBooleanMacro(name)=virtual void name##On (); virtual void name##Off ();" \
"itkSetVector2Macro(name,type)=virtual void Set##name (type _arg1, type _arg2) virtual void Set##name (type _arg[2]);" \
"itkGetVector2Macro(name,type)=virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2) const; virtual void Get##name (type _arg[2]) const;" \
"itkSetVector3Macro(name,type)=virtual void Set##name (type _arg1, type _arg2, type _arg3) virtual void Set##name (type _arg[3]);" \
"itkGetVector3Macro(name,type)=virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3) const; virtual void Get##name (type _arg[3]) const;" \
"itkSetVector4Macro(name,type)=virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4) virtual void Set##name (type _arg[4]);" \
"itkGetVector4Macro(name,type)=virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3, type& _arg4) const; virtual void Get##name (type _arg[4]) const;" \
"itkSetVector6Macro(name,type)=virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4, type _arg5, type _arg6) virtual void Set##name (type _arg[6]);" \
"itkGetVector6Macro(name,type)=virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3, type& _arg4, type& _arg5, type& _arg6) const; virtual void Get##name (type _arg[6]) const;" \
"itkSetVectorMacro(name,type,count)=virtual void Set##name(type data[]);" \
"itkGetVectorMacro(name,type,count)=virtual type* Get##name () const;" \
"itkNewMacro(type)=static Pointer New();" \
"itkFactorylessNewMacro(type)=static Pointer New();" \
"itkCloneMacro(type)=Pointer Clone() const;" \
"itkTypeMacro(thisClass,superclass)=virtual const char *GetClassName() const;" \
"itkConceptMacro(name,concept)=enum { name = 0 };" \
"ITK_NUMERIC_LIMITS=std::numeric_limits" \
"ITK_TYPENAME=typename" \
"FEM_ABSTRACT_CLASS(thisClass,parentClass)=public: /** Standard Self typedef.*/ typedef thisClass Self; /** Standard Superclass typedef. */ typedef parentClass Superclass; /** Pointer or SmartPointer to an object. */ typedef Self* Pointer; /** Const pointer or SmartPointer to an object. */ typedef const Self* ConstPointer; private:" \
"FEM_CLASS(thisClass,parentClass)=FEM_ABSTRACT_CLASS(thisClass,parentClass) public: /** Create a new object from the existing one */ virtual Baseclass::Pointer Clone() const; /** Class ID for FEM object factory */ static const int CLID; /** Virtual function to access the class ID */ virtual int ClassID() const { return CLID; /** Object creation in an itk compatible way */ static Self::Pointer New() { return new Self(); } private:" \
FREEVERSION \
ERROR_CHECKING \
HAS_TIFF \
HAS_JPEG \
HAS_NETLIB \
HAS_PNG \
HAS_ZLIB \
HAS_GLUT \
HAS_QT \
VCL_USE_NATIVE_STL=1 \
VCL_USE_NATIVE_COMPLEX=1 \
VCL_HAS_BOOL=1 \
VXL_BIG_ENDIAN=1 \
VXL_LITTLE_ENDIAN=0 \
VNL_DLL_DATA= \
"US_PREPEND_NAMESPACE(x)=us::x" \
"US_BEGIN_NAMESPACE= namespace us {" \
"US_END_NAMESPACE=}" \
"US_BASECLASS_NAME=itk::LightObject" \
US_EXPORT= \
"DEPRECATED(func)=func" \
"mitkSegmentationTaskValueMacro(type, name)=bool Has##name() const; type Get##name() const; void Set##name(const type& value);" \
"mitkSegmentationTaskListValueMacro(type, name)=bool Has##name(size_t index) const; type Get##name(size_t index) const; void SetDefault##name(const type& value);" \
@US_PLATFORM@
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The
# macro definition that is found in the sources will be used. Use the PREDEFINED
# tag if you want to use a different macro definition that overrules the
# definition found in the source code.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_AS_DEFINED =
# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
# remove all references to function-like macros that are alone on a line, have
# an all uppercase name, and do not end with a semicolon. Such function macros
# are typically used for boiler-plate code, and will confuse the parser if not
# removed.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration options related to external references
#---------------------------------------------------------------------------
# The TAGFILES tag can be used to specify one or more tag files. For each tag
# file the location of the external documentation should be added. The format of
# a tag file without this location is as follows:
# TAGFILES = file1 file2 ...
# Adding location for the tag files is done as follows:
# TAGFILES = file1=loc1 "file2 = loc2" ...
# where loc1 and loc2 can be relative or absolute paths or URLs. See the
# section "Linking to external documentation" for more information about the use
# of tag files.
# Note: Each tag file must have a unique name (where the name does NOT include
# the path). If a tag file is not located in the directory in which doxygen is
# run, you must also specify the path to the tagfile here.
TAGFILES =
# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
# tag file that is based on the input files it reads. See section "Linking to
# external documentation" for more information about the usage of tag files.
GENERATE_TAGFILE = @MITK_DOXYGEN_TAGFILE_NAME@
# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
# the class index. If set to NO, only the inherited external classes will be
# listed.
# The default value is: NO.
ALLEXTERNALS = NO
# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
# in the modules index. If set to NO, only the current project's groups will be
# listed.
# The default value is: YES.
EXTERNAL_GROUPS = NO
# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
# the related pages index. If set to NO, only the current project's pages will
# be listed.
# The default value is: YES.
EXTERNAL_PAGES = YES
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
# You can include diagrams made with dia in doxygen documentation. Doxygen will
# then run dia to produce the diagram and insert it in the documentation. The
# DIA_PATH tag allows you to specify the directory where the dia binary resides.
# If left empty dia is assumed to be found in the default search path.
DIA_PATH =
# If set to YES the inheritance and collaboration graphs will hide inheritance
# and usage relations if the target is undocumented or is not a class.
# The default value is: YES.
HIDE_UNDOC_RELATIONS = YES
# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz (see:
# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# Bell Labs. The other options in this section have no effect if this option is
# set to NO
# The default value is: NO.
HAVE_DOT = @HAVE_DOT@
# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
# to run in parallel. When set to 0 doxygen will base this on the number of
# processors available in the system. You can set it explicitly to a value
# larger than 0 to get control over the balance between CPU load and processing
# speed.
# Minimum value: 0, maximum value: 32, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_NUM_THREADS = @MITK_DOXYGEN_DOT_NUM_THREADS@
# DOT_COMMON_ATTR is common attributes for nodes, edges and labels of
# subgraphs. When you want a differently looking font in the dot files that
# doxygen generates you can specify fontname, fontcolor and fontsize attributes.
# For details please see <a href=https://graphviz.org/doc/info/attrs.html>Node,
# Edge and Graph Attributes specification</a> You need to make sure dot is able
# to find the font, which can be done by putting it in a standard location or by
# setting the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
# directory containing the font. Default graphviz fontsize is 14.
# The default value is: fontname=Helvetica,fontsize=10.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_COMMON_ATTR = "fontname=Helvetica,fontsize=10"
# DOT_EDGE_ATTR is concatenated with DOT_COMMON_ATTR. For elegant style you can
# add 'arrowhead=open, arrowtail=open, arrowsize=0.5'. <a
# href=https://graphviz.org/doc/info/arrows.html>Complete documentation about
# arrows shapes.</a>
# The default value is: labelfontname=Helvetica,labelfontsize=10.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_EDGE_ATTR = "labelfontname=Helvetica,labelfontsize=10"
# DOT_NODE_ATTR is concatenated with DOT_COMMON_ATTR. For view without boxes
# around nodes set 'shape=plain' or 'shape=plaintext' <a
# href=https://www.graphviz.org/doc/info/shapes.html>Shapes specification</a>
# The default value is: shape=box,height=0.2,width=0.4.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_NODE_ATTR = "shape=box,height=0.2,width=0.4"
# You can set the path where dot can find font specified with fontname in
# DOT_COMMON_ATTR and others dot attributes.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTPATH =
# If the CLASS_GRAPH tag is set to YES (or GRAPH) then doxygen will generate a
# graph for each documented class showing the direct and indirect inheritance
# relations. In case HAVE_DOT is set as well dot will be used to draw the graph,
# otherwise the built-in generator will be used. If the CLASS_GRAPH tag is set
# to TEXT the direct and indirect inheritance relations will be shown as texts /
# links.
# Possible values are: NO, YES, TEXT and GRAPH.
# The default value is: YES.
CLASS_GRAPH = YES
# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
# graph for each documented class showing the direct and indirect implementation
# dependencies (inheritance, containment, and class references variables) of the
# class with other documented classes.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
COLLABORATION_GRAPH = YES
# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
# groups, showing the direct groups dependencies. See also the chapter Grouping
# in the manual.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GROUP_GRAPHS = YES
# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
# collaboration diagrams in a style similar to the OMG's Unified Modeling
# Language.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
UML_LOOK = @MITK_DOXYGEN_UML_LOOK@
# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
# class node. If there are many fields or methods and many nodes the graph may
# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
# number of items for each type to make the size more manageable. Set this to 0
# for no limit. Note that the threshold may be exceeded by 50% before the limit
# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
# but if the number exceeds 15, the total amount of fields shown is limited to
# 10.
# Minimum value: 0, maximum value: 100, default value: 10.
# This tag requires that the tag UML_LOOK is set to YES.
UML_LIMIT_NUM_FIELDS = 10
# If the DOT_UML_DETAILS tag is set to NO, doxygen will show attributes and
# methods without types and arguments in the UML graphs. If the DOT_UML_DETAILS
# tag is set to YES, doxygen will add type and arguments for attributes and
# methods in the UML graphs. If the DOT_UML_DETAILS tag is set to NONE, doxygen
# will not generate fields with class member information in the UML graphs. The
# class diagrams will look similar to the default class diagrams but using UML
# notation for the relationships.
# Possible values are: NO, YES and NONE.
# The default value is: NO.
# This tag requires that the tag UML_LOOK is set to YES.
DOT_UML_DETAILS = NO
# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters
# to display on a single line. If the actual line length exceeds this threshold
# significantly it will wrapped across multiple lines. Some heuristics are apply
# to avoid ugly line breaks.
# Minimum value: 0, maximum value: 1000, default value: 17.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_WRAP_THRESHOLD = 17
# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
# collaboration graphs will show the relations between templates and their
# instances.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
TEMPLATE_RELATIONS = YES
# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
# YES then doxygen will generate a graph for each documented file showing the
# direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDE_GRAPH = NO
# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
# set to YES then doxygen will generate a graph for each documented file showing
# the direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDED_BY_GRAPH = NO
# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable call graphs for selected
# functions only using the \callgraph command. Disabling a call graph can be
# accomplished by means of the command \hidecallgraph.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALL_GRAPH = NO
# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable caller graphs for selected
# functions only using the \callergraph command. Disabling a caller graph can be
# accomplished by means of the command \hidecallergraph.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALLER_GRAPH = NO
# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
# hierarchy of all classes instead of a textual one.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GRAPHICAL_HIERARCHY = NO
# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
# dependencies a directory has on other directories in a graphical way. The
# dependency relations are determined by the #include relations between the
# files in the directories.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
DIRECTORY_GRAPH = YES
# The DIR_GRAPH_MAX_DEPTH tag can be used to limit the maximum number of levels
# of child directories generated in directory dependency graphs by dot.
# Minimum value: 1, maximum value: 25, default value: 1.
# This tag requires that the tag DIRECTORY_GRAPH is set to YES.
DIR_GRAPH_MAX_DEPTH = 1
# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
# generated by dot. For an explanation of the image formats see the section
# output formats in the documentation of the dot tool (Graphviz (see:
# http://www.graphviz.org/)).
# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
# to make the SVG files visible in IE 9+ (other browsers do not have this
# requirement).
# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,
# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
# png:gdiplus:gdiplus.
# The default value is: png.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_IMAGE_FORMAT = png
# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
# enable generation of interactive SVG images that allow zooming and panning.
#
# Note that this requires a modern browser other than Internet Explorer. Tested
# and working are Firefox, Chrome, Safari, and Opera.
# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
# the SVG files visible. Older versions of IE do not have SVG support.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
INTERACTIVE_SVG = NO
# The DOT_PATH tag can be used to specify the path where the dot tool can be
# found. If left blank, it is assumed the dot tool can be found in the path.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_PATH = @DOXYGEN_DOT_PATH@
# The DOTFILE_DIRS tag can be used to specify one or more directories that
# contain dot files that are included in the documentation (see the \dotfile
# command).
# This tag requires that the tag HAVE_DOT is set to YES.
DOTFILE_DIRS =
# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the \mscfile
# command).
MSCFILE_DIRS =
# The DIAFILE_DIRS tag can be used to specify one or more directories that
# contain dia files that are included in the documentation (see the \diafile
# command).
DIAFILE_DIRS =
# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
# path where java can find the plantuml.jar file or to the filename of jar file
# to be used. If left blank, it is assumed PlantUML is not used or called during
# a preprocessing step. Doxygen will generate a warning when it encounters a
# \startuml command in this case and will not generate output for the diagram.
PLANTUML_JAR_PATH =
# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
# configuration file for plantuml.
PLANTUML_CFG_FILE =
# When using plantuml, the specified paths are searched for files specified by
# the !include statement in a plantuml block.
PLANTUML_INCLUDE_PATH =
# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
# that will be shown in the graph. If the number of nodes in a graph becomes
# larger than this value, doxygen will truncate the graph, which is visualized
# by representing a node as a red box. Note that doxygen if the number of direct
# children of the root node in a graph is already larger than
# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
# Minimum value: 0, maximum value: 10000, default value: 50.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_GRAPH_MAX_NODES = 120
# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
# generated by dot. A depth value of 3 means that only nodes reachable from the
# root by following a path via at most 3 edges will be shown. Nodes that lay
# further from the root node will be omitted. Note that setting this option to 1
# or 2 may greatly reduce the computation time needed for large code bases. Also
# note that the size of a graph can be further restricted by
# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
# Minimum value: 0, maximum value: 1000, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
MAX_DOT_GRAPH_DEPTH = 0
# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
# files in one run (i.e. multiple -o and -T options on the command line). This
# makes dot run faster, but since only newer versions of dot (>1.8.10) support
# this, this feature is disabled by default.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_MULTI_TARGETS = NO
# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
# explaining the meaning of the various boxes and arrows in the dot generated
# graphs.
# Note: This tag requires that UML_LOOK isn't set, i.e. the doxygen internal
# graphical representation for inheritance and collaboration diagrams is used.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GENERATE_LEGEND = YES
# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate
# files that are used to generate the various graphs.
#
# Note: This setting is not only used for dot files but also for msc temporary
# files.
# The default value is: YES.
DOT_CLEANUP = YES
diff --git a/Documentation/doxygen_developers_guide.conf.in b/Documentation/doxygen_developers_guide.conf.in
index 13903e9c89..e611290891 100644
--- a/Documentation/doxygen_developers_guide.conf.in
+++ b/Documentation/doxygen_developers_guide.conf.in
@@ -1,2739 +1,2739 @@
# Doxyfile 1.9.6
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a double hash (##) is considered a comment and is placed in
# front of the TAG it is preceding.
#
# All text after a single hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists, items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (\" \").
#
# Note:
#
# Use doxygen to compare the used configuration file with the template
# configuration file:
# doxygen -x [configFile]
# Use doxygen to compare the used configuration file with the template
# configuration file without replacing the environment variables or CMake type
# replacement variables:
# doxygen -x_noenv [configFile]
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
# This tag specifies the encoding used for all characters in the configuration
# file that follow. The default is UTF-8 which is also the encoding used for all
# text before the first occurrence of this tag. Doxygen uses libiconv (or the
# iconv built into libc) for the transcoding. See
# https://www.gnu.org/software/libiconv/ for the list of possible encodings.
# The default value is: UTF-8.
DOXYFILE_ENCODING = UTF-8
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
# double-quotes, unless you are using Doxywizard) that should identify the
# project for which the documentation is generated. This name is used in the
# title of most generated pages and in a few other places.
# The default value is: My Project.
PROJECT_NAME = MITK
# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER = @MITK_VERSION_STRING@
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
# quick idea about the purpose of the project. Keep the description short.
PROJECT_BRIEF = "Medical Imaging Interaction Toolkit"
# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
# in the documentation. The maximum height of the logo should not exceed 55
# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
# the logo to the output directory.
PROJECT_LOGO =
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = @MITK_DOXYGEN_OUTPUT_DIR@/Guides/Developers_Guide/
# If the CREATE_SUBDIRS tag is set to YES then doxygen will create up to 4096
# sub-directories (in 2 levels) under the output directory of each output format
# and will distribute the generated files over these directories. Enabling this
# option can be useful when feeding doxygen a huge amount of source files, where
# putting all generated files in the same directory would otherwise causes
# performance problems for the file system. Adapt CREATE_SUBDIRS_LEVEL to
# control the number of sub-directories.
# The default value is: NO.
CREATE_SUBDIRS = NO
# Controls the number of sub-directories that will be created when
# CREATE_SUBDIRS tag is set to YES. Level 0 represents 16 directories, and every
# level increment doubles the number of directories, resulting in 4096
# directories at level 8 which is the default and also the maximum value. The
# sub-directories are organized in 2 levels, the first level always has a fixed
# number of 16 directories.
# Minimum value: 0, maximum value: 8, default value: 8.
# This tag requires that the tag CREATE_SUBDIRS is set to YES.
CREATE_SUBDIRS_LEVEL = 8
# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
# characters to appear in the names of generated files. If set to NO, non-ASCII
# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
# U+3044.
# The default value is: NO.
ALLOW_UNICODE_NAMES = NO
# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Bulgarian,
# Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, English
# (United States), Esperanto, Farsi (Persian), Finnish, French, German, Greek,
# Hindi, Hungarian, Indonesian, Italian, Japanese, Japanese-en (Japanese with
# English messages), Korean, Korean-en (Korean with English messages), Latvian,
# Lithuanian, Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese,
# Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish,
# Swedish, Turkish, Ukrainian and Vietnamese.
# The default value is: English.
OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
# descriptions after the members that are listed in the file and class
# documentation (similar to Javadoc). Set to NO to disable this.
# The default value is: YES.
BRIEF_MEMBER_DESC = YES
# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
# description of a member or function before the detailed description
#
# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
# The default value is: YES.
REPEAT_BRIEF = YES
# This tag implements a quasi-intelligent brief description abbreviator that is
# used to form the text in various listings. Each string in this list, if found
# as the leading text of the brief description, will be stripped from the text
# and the result, after processing the whole list, is used as the annotated
# text. Otherwise, the brief description is used as-is. If left blank, the
# following values are used ($name is automatically replaced with the name of
# the entity):The $name class, The $name widget, The $name file, is, provides,
# specifies, contains, represents, a, an and the.
ABBREVIATE_BRIEF =
# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# doxygen will generate a detailed section even if there is only a brief
# description.
# The default value is: NO.
ALWAYS_DETAILED_SEC = NO
# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
# inherited members of a class in the documentation of that class as if those
# members were ordinary class members. Constructors, destructors and assignment
# operators of the base classes will not be shown.
# The default value is: NO.
INLINE_INHERITED_MEMB = NO
# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
# before files name in the file list and in the header files. If set to NO the
# shortest path that makes the file name unique will be used
# The default value is: YES.
FULL_PATH_NAMES = NO
# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
# Stripping is only done if one of the specified strings matches the left-hand
# part of the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the path to
# strip.
#
# Note that you can specify absolute paths here, but also relative paths, which
# will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES.
STRIP_FROM_PATH =
# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
# path mentioned in the documentation of a class, which tells the reader which
# header file to include in order to use a class. If left blank only the name of
# the header file containing the class definition is used. Otherwise one should
# specify the list of include paths that are normally passed to the compiler
# using the -I flag.
STRIP_FROM_INC_PATH =
# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
# less readable) file names. This can be useful is your file systems doesn't
# support long names like on DOS, Mac, or CD-ROM.
# The default value is: NO.
SHORT_NAMES = NO
# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
# first line (until the first dot) of a Javadoc-style comment as the brief
# description. If set to NO, the Javadoc-style will behave just like regular Qt-
# style comments (thus requiring an explicit @brief command for a brief
# description.)
# The default value is: NO.
JAVADOC_AUTOBRIEF = NO
# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line
# such as
# /***************
# as being the beginning of a Javadoc-style comment "banner". If set to NO, the
# Javadoc-style will behave just like regular comments and it will not be
# interpreted by doxygen.
# The default value is: NO.
JAVADOC_BANNER = NO
# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
# line (until the first dot) of a Qt-style comment as the brief description. If
# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
# requiring an explicit \brief command for a brief description.)
# The default value is: NO.
QT_AUTOBRIEF = NO
# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
# a brief description. This used to be the default behavior. The new default is
# to treat a multi-line C++ comment block as a detailed description. Set this
# tag to YES if you prefer the old behavior instead.
#
# Note that setting this tag to YES also means that rational rose comments are
# not recognized any more.
# The default value is: NO.
MULTILINE_CPP_IS_BRIEF = NO
# By default Python docstrings are displayed as preformatted text and doxygen's
# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the
# doxygen's special commands can be used and the contents of the docstring
# documentation blocks is shown as doxygen documentation.
# The default value is: YES.
PYTHON_DOCSTRING = YES
# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
# documentation from any documented member that it re-implements.
# The default value is: YES.
INHERIT_DOCS = YES
# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
# page for each member. If set to NO, the documentation of a member will be part
# of the file/class/namespace that contains it.
# The default value is: NO.
SEPARATE_MEMBER_PAGES = NO
# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
# uses this value to replace tabs by spaces in code fragments.
# Minimum value: 1, maximum value: 16, default value: 4.
TAB_SIZE = 8
# This tag can be used to specify a number of aliases that act as commands in
# the documentation. An alias has the form:
# name=value
# For example adding
# "sideeffect=@par Side Effects:^^"
# will allow you to put the command \sideeffect (or @sideeffect) in the
# documentation, which will result in a user-defined paragraph with heading
# "Side Effects:". Note that you cannot put \n's in the value part of an alias
# to insert newlines (in the resulting output). You can put ^^ in the value part
# of an alias to insert a newline as if a physical newline was in the original
# file. When you need a literal { or } or , in the value part of an alias you
# have to escape them by means of a backslash (\), this can lead to conflicts
# with the commands \{ and \} for these it is advised to use the version @{ and
# @} or use a double escape (\\{ and \\})
ALIASES = "FIXME=\par Fix Me's:\n" \
"BlueBerry=\if BLUEBERRY" \
"endBlueBerry=\endif" \
"bundlemainpage{1}=\page \1" \
"embmainpage{1}=\page \1" \
"github{2}=<a href=\"https://github.com/MITK/MITK/blob/master/\1\">\2</a>" \
"deprecatedSince{1}=\xrefitem deprecatedSince\1 \" Deprecated as of \1\" \"Functions deprecated as of \1\"" \
"minimumCMakeVersion=@MITK_CMAKE_MINIMUM_REQUIRED_VERSION@" \
- "minimumQt5Version=@MITK_QT5_MINIMUM_VERSION@" \
+ "minimumQt6Version=@MITK_QT6_MINIMUM_VERSION@" \
"imageMacro{3}=\image html \1 \2 \n \image latex \1 \2 width=\3cm" \
"developersguidemainpage{1}=\mainpage" \
"usersguidemainpage{1}=\page \1" \
"nondependentPluginLink{3}= \ref \1 \"\3\""
# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
# only. Doxygen will then generate output that is more tailored for C. For
# instance, some of the names that are used will be different. The list of all
# members will be omitted, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_FOR_C = NO
# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
# Python sources only. Doxygen will then generate output that is more tailored
# for that language. For instance, namespaces will be presented as packages,
# qualified scopes will look different, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_JAVA = NO
# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
# sources. Doxygen will then generate output that is tailored for Fortran.
# The default value is: NO.
OPTIMIZE_FOR_FORTRAN = NO
# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
# sources. Doxygen will then generate output that is tailored for VHDL.
# The default value is: NO.
OPTIMIZE_OUTPUT_VHDL = NO
# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice
# sources only. Doxygen will then generate output that is more tailored for that
# language. For instance, namespaces will be presented as modules, types will be
# separated into more groups, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_SLICE = NO
# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given
# extension. Doxygen has a built-in mapping, but you can override or extend it
# using this tag. The format is ext=language, where ext is a file extension, and
# language is one of the parsers supported by doxygen: IDL, Java, JavaScript,
# Csharp (C#), C, C++, Lex, D, PHP, md (Markdown), Objective-C, Python, Slice,
# VHDL, Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:
# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser
# tries to guess whether the code is fixed or free formatted code, this is the
# default for Fortran type files). For instance to make doxygen treat .inc files
# as Fortran files (default is PHP), and .f files as C (default is Fortran),
# use: inc=Fortran f=C.
#
# Note: For files without extension you can use no_extension as a placeholder.
#
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen. When specifying no_extension you should add
# * to the FILE_PATTERNS.
#
# Note see also the list of default file extension mappings.
EXTENSION_MAPPING =
# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable
# documentation. See https://daringfireball.net/projects/markdown/ for details.
# The output of markdown processing is further processed by doxygen, so you can
# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
# case of backward compatibilities issues.
# The default value is: YES.
MARKDOWN_SUPPORT = YES
# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
# to that level are automatically included in the table of contents, even if
# they do not have an id attribute.
# Note: This feature currently applies only to Markdown headings.
# Minimum value: 0, maximum value: 99, default value: 5.
# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
TOC_INCLUDE_HEADINGS = 5
# When enabled doxygen tries to link words that correspond to documented
# classes, or namespaces to their corresponding documentation. Such a link can
# be prevented in individual cases by putting a % sign in front of the word or
# globally by setting AUTOLINK_SUPPORT to NO.
# The default value is: YES.
AUTOLINK_SUPPORT = YES
# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
# to include (a tag file for) the STL sources as input, then you should set this
# tag to YES in order to let doxygen match functions declarations and
# definitions whose arguments contain STL classes (e.g. func(std::string);
# versus func(std::string) {}). This also make the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate.
# The default value is: NO.
BUILTIN_STL_SUPPORT = YES
# If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support.
# The default value is: NO.
CPP_CLI_SUPPORT = NO
# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen
# will parse them like normal C++ but will assume all classes use public instead
# of private inheritance when no explicit protection keyword is present.
# The default value is: NO.
SIP_SUPPORT = NO
# For Microsoft's IDL there are propget and propput attributes to indicate
# getter and setter methods for a property. Setting this option to YES will make
# doxygen to replace the get and set methods by a property in the documentation.
# This will only work if the methods are indeed getting or setting a simple
# type. If this is not the case, or you want to show the methods anyway, you
# should set this option to NO.
# The default value is: YES.
IDL_PROPERTY_SUPPORT = YES
# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
# tag is set to YES then doxygen will reuse the documentation of the first
# member in the group (if any) for the other members of the group. By default
# all members of a group must be documented explicitly.
# The default value is: NO.
DISTRIBUTE_GROUP_DOC = YES
# If one adds a struct or class to a group and this option is enabled, then also
# any nested class or struct is added to the same group. By default this option
# is disabled and one has to add nested compounds explicitly via \ingroup.
# The default value is: NO.
GROUP_NESTED_COMPOUNDS = NO
# Set the SUBGROUPING tag to YES to allow class member groups of the same type
# (for instance a group of public functions) to be put as a subgroup of that
# type (e.g. under the Public Functions section). Set it to NO to prevent
# subgrouping. Alternatively, this can be done per class using the
# \nosubgrouping command.
# The default value is: YES.
SUBGROUPING = YES
# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
# are shown inside the group in which they are included (e.g. using \ingroup)
# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
# and RTF).
#
# Note that this feature does not work in combination with
# SEPARATE_MEMBER_PAGES.
# The default value is: NO.
INLINE_GROUPED_CLASSES = NO
# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
# with only public data fields or simple typedef fields will be shown inline in
# the documentation of the scope in which they are defined (i.e. file,
# namespace, or group documentation), provided this scope is documented. If set
# to NO, structs, classes, and unions are shown on a separate page (for HTML and
# Man pages) or section (for LaTeX and RTF).
# The default value is: NO.
INLINE_SIMPLE_STRUCTS = NO
# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
# enum is documented as struct, union, or enum with the name of the typedef. So
# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
# with name TypeT. When disabled the typedef will appear as a member of a file,
# namespace, or class. And the struct will be named TypeS. This can typically be
# useful for C code in case the coding convention dictates that all compound
# types are typedef'ed and only the typedef is referenced, never the tag name.
# The default value is: NO.
TYPEDEF_HIDES_STRUCT = NO
# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
# cache is used to resolve symbols given their name and scope. Since this can be
# an expensive process and often the same symbol appears multiple times in the
# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
# doxygen will become slower. If the cache is too large, memory is wasted. The
# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
# symbols. At the end of a run doxygen will report the cache usage and suggest
# the optimal cache size from a speed point of view.
# Minimum value: 0, maximum value: 9, default value: 0.
LOOKUP_CACHE_SIZE = 0
# The NUM_PROC_THREADS specifies the number of threads doxygen is allowed to use
# during processing. When set to 0 doxygen will based this on the number of
# cores available in the system. You can set it explicitly to a value larger
# than 0 to get more control over the balance between CPU load and processing
# speed. At this moment only the input processing can be done using multiple
# threads. Since this is still an experimental feature the default is set to 1,
# which effectively disables parallel processing. Please report any issues you
# encounter. Generating dot graphs in parallel is controlled by the
# DOT_NUM_THREADS setting.
# Minimum value: 0, maximum value: 32, default value: 1.
NUM_PROC_THREADS = 1
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
# documentation are documented, even if no documentation was available. Private
# class members and static file members will be hidden unless the
# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
# Note: This will also disable the warnings about undocumented members that are
# normally produced when WARNINGS is set to YES.
# The default value is: NO.
EXTRACT_ALL = YES
# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
# be included in the documentation.
# The default value is: NO.
EXTRACT_PRIVATE = NO
# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual
# methods of a class will be included in the documentation.
# The default value is: NO.
EXTRACT_PRIV_VIRTUAL = NO
# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
# scope will be included in the documentation.
# The default value is: NO.
EXTRACT_PACKAGE = NO
# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
# included in the documentation.
# The default value is: NO.
EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
# locally in source files will be included in the documentation. If set to NO,
# only classes defined in header files are included. Does not have any effect
# for Java sources.
# The default value is: YES.
EXTRACT_LOCAL_CLASSES = @MITK_DOXYGEN_INTERNAL_DOCS@
# This flag is only useful for Objective-C code. If set to YES, local methods,
# which are defined in the implementation section but not in the interface are
# included in the documentation. If set to NO, only methods in the interface are
# included.
# The default value is: NO.
EXTRACT_LOCAL_METHODS = NO
# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base name of
# the file that contains the anonymous namespace. By default anonymous namespace
# are hidden.
# The default value is: NO.
EXTRACT_ANON_NSPACES = NO
# If this flag is set to YES, the name of an unnamed parameter in a declaration
# will be determined by the corresponding definition. By default unnamed
# parameters remain unnamed in the output.
# The default value is: YES.
RESOLVE_UNNAMED_PARAMS = YES
# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
# undocumented members inside documented classes or files. If set to NO these
# members will be included in the various overviews, but no documentation
# section is generated. This option has no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy. If set
# to NO, these classes will be included in the various overviews. This option
# will also hide undocumented C++ concepts if enabled. This option has no effect
# if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_CLASSES = NO
# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
# declarations. If set to NO, these declarations will be included in the
# documentation.
# The default value is: NO.
HIDE_FRIEND_COMPOUNDS = @MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS@
# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
# documentation blocks found inside the body of a function. If set to NO, these
# blocks will be appended to the function's detailed documentation block.
# The default value is: NO.
HIDE_IN_BODY_DOCS = NO
# The INTERNAL_DOCS tag determines if documentation that is typed after a
# \internal command is included. If the tag is set to NO then the documentation
# will be excluded. Set it to YES to include the internal documentation.
# The default value is: NO.
INTERNAL_DOCS = @MITK_DOXYGEN_INTERNAL_DOCS@
# With the correct setting of option CASE_SENSE_NAMES doxygen will better be
# able to match the capabilities of the underlying filesystem. In case the
# filesystem is case sensitive (i.e. it supports files in the same directory
# whose names only differ in casing), the option must be set to YES to properly
# deal with such files in case they appear in the input. For filesystems that
# are not case sensitive the option should be set to NO to properly deal with
# output files written for symbols that only differ in casing, such as for two
# classes, one named CLASS and the other named Class, and to also support
# references to files without having to specify the exact matching casing. On
# Windows (including Cygwin) and MacOS, users should typically set this option
# to NO, whereas on Linux or other Unix flavors it should typically be set to
# YES.
# Possible values are: SYSTEM, NO and YES.
# The default value is: SYSTEM.
CASE_SENSE_NAMES = YES
# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
# their full class and namespace scopes in the documentation. If set to YES, the
# scope will be hidden.
# The default value is: NO.
HIDE_SCOPE_NAMES = NO
# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
# append additional text to a page's title, such as Class Reference. If set to
# YES the compound reference will be hidden.
# The default value is: NO.
HIDE_COMPOUND_REFERENCE= NO
# If the SHOW_HEADERFILE tag is set to YES then the documentation for a class
# will show which file needs to be included to use the class.
# The default value is: YES.
SHOW_HEADERFILE = YES
# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
# the files that are included by a file in the documentation of that file.
# The default value is: YES.
SHOW_INCLUDE_FILES = YES
# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
# grouped member an include statement to the documentation, telling the reader
# which file to include in order to use the member.
# The default value is: NO.
SHOW_GROUPED_MEMB_INC = NO
# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
# files with double quotes in the documentation rather than with sharp brackets.
# The default value is: NO.
FORCE_LOCAL_INCLUDES = NO
# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
# documentation for inline members.
# The default value is: YES.
INLINE_INFO = YES
# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
# (detailed) documentation of file and class members alphabetically by member
# name. If set to NO, the members will appear in declaration order.
# The default value is: YES.
SORT_MEMBER_DOCS = YES
# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
# descriptions of file, namespace and class members alphabetically by member
# name. If set to NO, the members will appear in declaration order. Note that
# this will also influence the order of the classes in the class list.
# The default value is: NO.
SORT_BRIEF_DOCS = NO
# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
# (brief and detailed) documentation of class members so that constructors and
# destructors are listed first. If set to NO the constructors will appear in the
# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
# member documentation.
# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
# detailed member documentation.
# The default value is: NO.
SORT_MEMBERS_CTORS_1ST = NO
# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
# of group names into alphabetical order. If set to NO the group names will
# appear in their defined order.
# The default value is: NO.
SORT_GROUP_NAMES = NO
# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
# fully-qualified names, including namespaces. If set to NO, the class list will
# be sorted only by class name, not including the namespace part.
# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
# Note: This option applies only to the class list, not to the alphabetical
# list.
# The default value is: NO.
SORT_BY_SCOPE_NAME = YES
# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
# type resolution of all parameters of a function it will reject a match between
# the prototype and the implementation of a member function even if there is
# only one candidate or it is obvious which candidate to choose by doing a
# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
# accept a match between prototype and implementation in such cases.
# The default value is: NO.
STRICT_PROTO_MATCHING = NO
# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
# list. This list is created by putting \todo commands in the documentation.
# The default value is: YES.
GENERATE_TODOLIST = @MITK_DOXYGEN_GENERATE_TODOLIST@
# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
# list. This list is created by putting \test commands in the documentation.
# The default value is: YES.
GENERATE_TESTLIST = YES
# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
# list. This list is created by putting \bug commands in the documentation.
# The default value is: YES.
GENERATE_BUGLIST = @MITK_DOXYGEN_GENERATE_BUGLIST@
# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
# the deprecated list. This list is created by putting \deprecated commands in
# the documentation.
# The default value is: YES.
GENERATE_DEPRECATEDLIST= @MITK_DOXYGEN_GENERATE_DEPRECATEDLIST@
# The ENABLED_SECTIONS tag can be used to enable conditional documentation
# sections, marked by \if <section_label> ... \endif and \cond <section_label>
# ... \endcond blocks.
ENABLED_SECTIONS = @MITK_DOXYGEN_ENABLED_SECTIONS@
# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
# initial value of a variable or macro / define can have for it to appear in the
# documentation. If the initializer consists of more lines than specified here
# it will be hidden. Use a value of 0 to hide initializers completely. The
# appearance of the value of individual variables and macros / defines can be
# controlled using \showinitializer or \hideinitializer command in the
# documentation regardless of this setting.
# Minimum value: 0, maximum value: 10000, default value: 30.
MAX_INITIALIZER_LINES = 0
# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
# the bottom of the documentation of classes and structs. If set to YES, the
# list will mention the files that were used to generate the documentation.
# The default value is: YES.
SHOW_USED_FILES = YES
# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
# will remove the Files entry from the Quick Index and from the Folder Tree View
# (if specified).
# The default value is: YES.
SHOW_FILES = NO
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
# page. This will remove the Namespaces entry from the Quick Index and from the
# Folder Tree View (if specified).
# The default value is: YES.
SHOW_NAMESPACES = NO
# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
# the version control system). Doxygen will invoke the program by executing (via
# popen()) the command command input-file, where command is the value of the
# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
# by doxygen. Whatever the program writes to standard output is used as the file
# version. For an example see the documentation.
FILE_VERSION_FILTER =
# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
# by doxygen. The layout file controls the global structure of the generated
# output files in an output format independent way. To create the layout file
# that represents doxygen's defaults, run doxygen with the -l option. You can
# optionally specify a file name after the option, if omitted DoxygenLayout.xml
# will be used as the name of the layout file. See also section "Changing the
# layout of pages" for information.
#
# Note that if you run doxygen from a directory containing a file called
# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
# tag is left empty.
LAYOUT_FILE =
# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
# the reference definitions. This must be a list of .bib files. The .bib
# extension is automatically appended if omitted. This requires the bibtex tool
# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.
# For LaTeX the style of the bibliography can be controlled using
# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
# search path. See also \cite for info how to create references.
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
# The QUIET tag can be used to turn on/off the messages that are generated to
# standard output by doxygen. If QUIET is set to YES this implies that the
# messages are off.
# The default value is: NO.
QUIET = YES
# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
# this implies that the warnings are on.
#
# Tip: Turn warnings on while writing the documentation.
# The default value is: YES.
WARNINGS = YES
# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: YES.
WARN_IF_UNDOCUMENTED = YES
# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
# potential errors in the documentation, such as documenting some parameters in
# a documented function twice, or documenting parameters that don't exist or
# using markup commands wrongly.
# The default value is: YES.
WARN_IF_DOC_ERROR = YES
# If WARN_IF_INCOMPLETE_DOC is set to YES, doxygen will warn about incomplete
# function parameter documentation. If set to NO, doxygen will accept that some
# parameters have no documentation without warning.
# The default value is: YES.
WARN_IF_INCOMPLETE_DOC = YES
# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
# are documented, but have no documentation for their parameters or return
# value. If set to NO, doxygen will only warn about wrong parameter
# documentation, but not about the absence of documentation. If EXTRACT_ALL is
# set to YES then this flag will automatically be disabled. See also
# WARN_IF_INCOMPLETE_DOC
# The default value is: NO.
WARN_NO_PARAMDOC = NO
# If WARN_IF_UNDOC_ENUM_VAL option is set to YES, doxygen will warn about
# undocumented enumeration values. If set to NO, doxygen will accept
# undocumented enumeration values. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: NO.
WARN_IF_UNDOC_ENUM_VAL = NO
# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS
# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but
# at the end of the doxygen process doxygen will return with a non-zero status.
# Possible values are: NO, YES and FAIL_ON_WARNINGS.
# The default value is: NO.
WARN_AS_ERROR = NO
# The WARN_FORMAT tag determines the format of the warning messages that doxygen
# can produce. The string should contain the $file, $line, and $text tags, which
# will be replaced by the file and line number from which the warning originated
# and the warning text. Optionally the format may contain $version, which will
# be replaced by the version of the file (if it could be obtained via
# FILE_VERSION_FILTER)
# See also: WARN_LINE_FORMAT
# The default value is: $file:$line: $text.
WARN_FORMAT = "$file:$line: $text"
# In the $text part of the WARN_FORMAT command it is possible that a reference
# to a more specific place is given. To make it easier to jump to this place
# (outside of doxygen) the user can define a custom "cut" / "paste" string.
# Example:
# WARN_LINE_FORMAT = "'vi $file +$line'"
# See also: WARN_FORMAT
# The default value is: at line $line of file $file.
WARN_LINE_FORMAT = "at line $line of file $file"
# The WARN_LOGFILE tag can be used to specify a file to which warning and error
# messages should be written. If left blank the output is written to standard
# error (stderr). In case the file specified cannot be opened for writing the
# warning and error messages are written to standard error. When as file - is
# specified the warning and error messages are written to standard output
# (stdout).
WARN_LOGFILE =
#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------
# The INPUT tag is used to specify the files and/or directories that contain
# documented source files. You may enter file names like myfile.cpp or
# directories like /usr/src/myproject. Separate the files or directories with
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
# Note: If this tag is empty the current directory is searched.
INPUT = "@MITK_SOURCE_DIR@/Core/Documentation/Doxygen/Concepts/" \
"@MITK_SOURCE_DIR@/Documentation/Doxygen/DeveloperManual/" \
"@MITK_SOURCE_DIR@/Modules/"
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
# documentation (see:
# https://www.gnu.org/software/libiconv/) for the list of possible encodings.
# See also: INPUT_FILE_ENCODING
# The default value is: UTF-8.
INPUT_ENCODING = UTF-8
# This tag can be used to specify the character encoding of the source files
# that doxygen parses The INPUT_FILE_ENCODING tag can be used to specify
# character encoding on a per file pattern basis. Doxygen will compare the file
# name with each pattern and apply the encoding instead of the default
# INPUT_ENCODING) if there is a match. The character encodings are a list of the
# form: pattern=encoding (like *.php=ISO-8859-1). See cfg_input_encoding
# "INPUT_ENCODING" for further information on supported encodings.
INPUT_FILE_ENCODING =
# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# read by doxygen.
#
# Note the list of default checked file patterns might differ from the list of
# default file extension mappings.
#
# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
# *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php, *.php4, *.php5, *.phtml,
# *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C
# comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd,
# *.vhdl, *.ucf, *.qsf and *.ice.
FILE_PATTERNS = *.dox \
*.md
# The RECURSIVE tag can be used to specify whether or not subdirectories should
# be searched for input files as well.
# The default value is: NO.
RECURSIVE = YES
# The EXCLUDE tag can be used to specify files and/or directories that should be
# excluded from the INPUT source files. This way you can easily exclude a
# subdirectory from a directory tree whose root is specified with the INPUT tag.
#
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE =
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
# from the input.
# The default value is: NO.
EXCLUDE_SYMLINKS = NO
# If the value of the INPUT tag contains directories, you can use the
# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
# certain files from those directories.
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/*
EXCLUDE_PATTERNS = modules.dox \
*/Plugins/*/documentation/doxygen/*
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# ANamespace::AClass, ANamespace::*Test
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/*
EXCLUDE_SYMBOLS =
# The EXAMPLE_PATH tag can be used to specify one or more files or directories
# that contain example code fragments that are included (see the \include
# command).
EXAMPLE_PATH =
# If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank all
# files are included.
EXAMPLE_PATTERNS =
# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
# searched for input files to be used with the \include or \dontinclude commands
# irrespective of the value of the RECURSIVE tag.
# The default value is: NO.
EXAMPLE_RECURSIVE = YES
# The IMAGE_PATH tag can be used to specify one or more files or directories
# that contain images that are to be included in the documentation (see the
# \image command).
IMAGE_PATH = "@MITK_SOURCE_DIR@/Core/Documentation/Doxygen/Concepts/" \
"@MITK_SOURCE_DIR@/Documentation/Doxygen/DeveloperManual/" \
"@MITK_SOURCE_DIR@/Modules/"
# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command:
#
# <filter> <input-file>
#
# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
# name of an input file. Doxygen will then use the output that the filter
# program writes to standard output. If FILTER_PATTERNS is specified, this tag
# will be ignored.
#
# Note that the filter must not add or remove lines; it is applied before the
# code is scanned, but not when the output code is generated. If lines are added
# or removed, the anchors will not be placed correctly.
#
# Note that doxygen will use the data processed and written to standard output
# for further processing, therefore nothing else, like debug statements or used
# commands (so in case of a Windows batch file always use @echo OFF), should be
# written to standard output.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# properly processed by doxygen.
INPUT_FILTER =
# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
# basis. Doxygen will compare the file name with each pattern and apply the
# filter if there is a match. The filters are a list of the form: pattern=filter
# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
# patterns match the file name, INPUT_FILTER is applied.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# properly processed by doxygen.
FILTER_PATTERNS = *.cmake=@CMakeDoxygenFilter_EXECUTABLE@
# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER) will also be used to filter the input files that are used for
# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
# The default value is: NO.
FILTER_SOURCE_FILES = NO
# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
# it is also possible to disable source filtering for a specific pattern using
# *.ext= (so without naming a filter).
# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
FILTER_SOURCE_PATTERNS =
# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
# is part of the input, its contents will be placed on the main page
# (index.html). This can be useful if you have a project on for instance GitHub
# and want to reuse the introduction page also for the doxygen output.
USE_MDFILE_AS_MAINPAGE =
# The Fortran standard specifies that for fixed formatted Fortran code all
# characters from position 72 are to be considered as comment. A common
# extension is to allow longer lines before the automatic comment starts. The
# setting FORTRAN_COMMENT_AFTER will also make it possible that longer lines can
# be processed before the automatic comment starts.
# Minimum value: 7, maximum value: 10000, default value: 72.
FORTRAN_COMMENT_AFTER = 72
#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------
# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
# generated. Documented entities will be cross-referenced with these sources.
#
# Note: To get rid of all source code in the generated output, make sure that
# also VERBATIM_HEADERS is set to NO.
# The default value is: NO.
SOURCE_BROWSER = YES
# Setting the INLINE_SOURCES tag to YES will include the body of functions,
# classes and enums directly into the documentation.
# The default value is: NO.
INLINE_SOURCES = NO
# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
# special comment blocks from generated source code fragments. Normal C, C++ and
# Fortran comments will always remain visible.
# The default value is: YES.
STRIP_CODE_COMMENTS = YES
# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
# entity all documented functions referencing it will be listed.
# The default value is: NO.
REFERENCED_BY_RELATION = YES
# If the REFERENCES_RELATION tag is set to YES then for each documented function
# all documented entities called/used by that function will be listed.
# The default value is: NO.
REFERENCES_RELATION = YES
# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
# to YES then the hyperlinks from functions in REFERENCES_RELATION and
# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
# link to the documentation.
# The default value is: YES.
REFERENCES_LINK_SOURCE = YES
# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
# source code will show a tooltip with additional information such as prototype,
# brief description and links to the definition and documentation. Since this
# will make the HTML file larger and loading of large files a bit slower, you
# can opt to disable this feature.
# The default value is: YES.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
SOURCE_TOOLTIPS = YES
# If the USE_HTAGS tag is set to YES then the references to source code will
# point to the HTML generated by the htags(1) tool instead of doxygen built-in
# source browser. The htags tool is part of GNU's global source tagging system
# (see https://www.gnu.org/software/global/global.html). You will need version
# 4.8.6 or higher.
#
# To use it do the following:
# - Install the latest version of global
# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file
# - Make sure the INPUT points to the root of the source tree
# - Run doxygen as normal
#
# Doxygen will invoke htags (and that will in turn invoke gtags), so these
# tools must be available from the command line (i.e. in the search path).
#
# The result: instead of the source browser generated by doxygen, the links to
# source code will now point to the output of htags.
# The default value is: NO.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
USE_HTAGS = NO
# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
# verbatim copy of the header file for each class for which an include is
# specified. Set to NO to disable this.
# See also: Section \class.
# The default value is: YES.
VERBATIM_HEADERS = YES
# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
# clang parser (see:
# http://clang.llvm.org/) for more accurate parsing at the cost of reduced
# performance. This can be particularly helpful with template rich C++ code for
# which doxygen's built-in parser lacks the necessary type information.
# Note: The availability of this option depends on whether or not doxygen was
# generated with the -Duse_libclang=ON option for CMake.
# The default value is: NO.
CLANG_ASSISTED_PARSING = NO
# If the CLANG_ASSISTED_PARSING tag is set to YES and the CLANG_ADD_INC_PATHS
# tag is set to YES then doxygen will add the directory of each input to the
# include path.
# The default value is: YES.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
CLANG_ADD_INC_PATHS = YES
# If clang assisted parsing is enabled you can provide the compiler with command
# line options that you would normally use when invoking the compiler. Note that
# the include paths will already be set by doxygen for the files and directories
# specified with INPUT and INCLUDE_PATH.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
CLANG_OPTIONS =
# If clang assisted parsing is enabled you can provide the clang parser with the
# path to the directory containing a file called compile_commands.json. This
# file is the compilation database (see:
# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the
# options used when the source files were built. This is equivalent to
# specifying the -p option to a clang tool, such as clang-check. These options
# will then be passed to the parser. Any options specified with CLANG_OPTIONS
# will be added as well.
# Note: The availability of this option depends on whether or not doxygen was
# generated with the -Duse_libclang=ON option for CMake.
CLANG_DATABASE_PATH =
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
# compounds will be generated. Enable this if the project contains a lot of
# classes, structs, unions or interfaces.
# The default value is: YES.
ALPHABETICAL_INDEX = YES
# The IGNORE_PREFIX tag can be used to specify a prefix (or a list of prefixes)
# that should be ignored while generating the index headers. The IGNORE_PREFIX
# tag works for classes, function and member names. The entity will be placed in
# the alphabetical list under the first letter of the entity name that remains
# after removing the prefix.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
# The default value is: YES.
GENERATE_HTML = NO
# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_OUTPUT = html
# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
# generated HTML page (for example: .htm, .php, .asp).
# The default value is: .html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FILE_EXTENSION = .html
# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
# each generated HTML page. If the tag is left blank doxygen will generate a
# standard header.
#
# To get valid HTML the header file that includes any scripts and style sheets
# that doxygen needs, which is dependent on the configuration options used (e.g.
# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
# default header using
# doxygen -w html new_header.html new_footer.html new_stylesheet.css
# YourConfigFile
# and then modify the file new_header.html. See also section "Doxygen usage"
# for information on how to generate the default header that doxygen normally
# uses.
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. For a description
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_HEADER =
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
# footer. See HTML_HEADER for more information on how to generate a default
# footer and what special commands can be used inside the footer. See also
# section "Doxygen usage" for information on how to generate the default footer
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FOOTER =
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
# the HTML output. If left blank doxygen will generate a default style sheet.
# See also section "Doxygen usage" for information on how to generate the style
# sheet that doxygen normally uses.
# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
# it is more robust and this tag (HTML_STYLESHEET) will in the future become
# obsolete.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_STYLESHEET =
# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# cascading style sheets that are included after the standard style sheets
# created by doxygen. Using this option one can overrule certain style aspects.
# This is preferred over using HTML_STYLESHEET since it does not replace the
# standard style sheet and is therefore more robust against future updates.
# Doxygen will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list).
# Note: Since the styling of scrollbars can currently not be overruled in
# Webkit/Chromium, the styling will be left out of the default doxygen.css if
# one or more extra stylesheets have been specified. So if scrollbar
# customization is desired it has to be added explicitly. For an example see the
# documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET = @MITK_DOXYGEN_STYLESHEET@
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
# that these files will be copied to the base HTML output directory. Use the
# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_FILES =
# The HTML_COLORSTYLE tag can be used to specify if the generated HTML output
# should be rendered with a dark or light theme.
# Possible values are: LIGHT always generate light mode output, DARK always
# generate dark mode output, AUTO_LIGHT automatically set the mode according to
# the user preference, use light mode if no preference is set (the default),
# AUTO_DARK automatically set the mode according to the user preference, use
# dark mode if no preference is set and TOGGLE allow to user to switch between
# light and dark mode via a button.
# The default value is: AUTO_LIGHT.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE = AUTO_LIGHT
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the style sheet and background images according to
# this color. Hue is specified as an angle on a color-wheel, see
# https://en.wikipedia.org/wiki/Hue for more information. For instance the value
# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
# purple, and 360 is red again.
# Minimum value: 0, maximum value: 359, default value: 220.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_HUE = 220
# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
# in the HTML output. For a value of 0 the output will use gray-scales only. A
# value of 255 will produce the most vivid colors.
# Minimum value: 0, maximum value: 255, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_SAT = 100
# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
# luminance component of the colors in the HTML output. Values below 100
# gradually make the output lighter, whereas values above 100 make the output
# darker. The value divided by 100 is the actual gamma applied, so 80 represents
# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
# change the gamma.
# Minimum value: 40, maximum value: 240, default value: 80.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting this
# to YES can help to show when doxygen was last run and thus if the
# documentation is up to date.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_TIMESTAMP = YES
# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML
# documentation will contain a main index with vertical navigation menus that
# are dynamically created via JavaScript. If disabled, the navigation index will
# consists of multiple levels of tabs that are statically embedded in every HTML
# page. Disable this option to support browsers that do not have JavaScript,
# like the Qt help browser.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_MENUS = YES
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_SECTIONS = @MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS@
# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
# shown in the various tree structured indices initially; the user can expand
# and collapse entries dynamically later on. Doxygen will expand the tree to
# such a level that at most the specified number of entries are visible (unless
# a fully collapsed tree already exceeds this amount). So setting the number of
# entries 1 will produce a full collapsed tree by default. 0 is a special value
# representing an infinite number of entries and will result in a full expanded
# tree by default.
# Minimum value: 0, maximum value: 9999, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_INDEX_NUM_ENTRIES = 100
# If the GENERATE_DOCSET tag is set to YES, additional index files will be
# generated that can be used as input for Apple's Xcode 3 integrated development
# environment (see:
# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To
# create a documentation set, doxygen will generate a Makefile in the HTML
# output directory. Running make will produce the docset in that directory and
# running make install will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy
# genXcode/_index.html for more information.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_DOCSET = NO
# This tag determines the name of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# The default value is: Doxygen generated docs.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDNAME = "Doxygen generated docs"
# This tag determines the URL of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDURL =
# This tag specifies a string that should uniquely identify the documentation
# set bundle. This should be a reverse domain-name style string, e.g.
# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_BUNDLE_ID = org.doxygen.Project
# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
# The default value is: org.doxygen.Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
# The default value is: Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_NAME = Publisher
# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
# on Windows. In the beginning of 2021 Microsoft took the original page, with
# a.o. the download links, offline the HTML help workshop was already many years
# in maintenance mode). You can download the HTML help workshop from the web
# archives at Installation executable (see:
# http://web.archive.org/web/20160201063255/http://download.microsoft.com/downlo
# ad/0/A/9/0A939EF6-E31C-430F-A3DF-DFAE7960D564/htmlhelp.exe).
#
# The HTML Help Workshop contains a compiler that can convert all HTML output
# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
# files are now used as the Windows 98 help format, and will replace the old
# Windows help format (.hlp) on all Windows platforms in the future. Compressed
# HTML files also contain an index, a table of contents, and you can search for
# words in the documentation. The HTML workshop also contains a viewer for
# compressed HTML files.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_HTMLHELP = NO
# The CHM_FILE tag can be used to specify the file name of the resulting .chm
# file. You can add a path in front of the file if the result should not be
# written to the html output directory.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_FILE =
# The HHC_LOCATION tag can be used to specify the location (absolute path
# including file name) of the HTML help compiler (hhc.exe). If non-empty,
# doxygen will try to run the HTML help compiler on the generated index.hhp.
# The file has to be specified with full path.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
HHC_LOCATION =
# The GENERATE_CHI flag controls if a separate .chi index file is generated
# (YES) or that it should be included in the main .chm file (NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
GENERATE_CHI = NO
# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
# and project file content.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_INDEX_ENCODING =
# The BINARY_TOC flag controls whether a binary table of contents is generated
# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
# enables the Previous and Next buttons.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
BINARY_TOC = NO
# The TOC_EXPAND flag can be set to YES to add extra items for group members to
# the table of contents of the HTML help documentation and to the tree view.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
TOC_EXPAND = NO
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
# (.qch) of the generated HTML documentation.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_QHP = @MITK_DOXYGEN_GENERATE_QHP@
# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
# the file name of the resulting .qch file. The path specified is relative to
# the HTML output folder.
# This tag requires that the tag GENERATE_QHP is set to YES.
QCH_FILE = @MITK_DOXYGEN_QCH_FILE@
# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
# Project output. For more information please see Qt Help Project / Namespace
# (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_NAMESPACE = org.mitk
# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
# Help Project output. For more information please see Qt Help Project / Virtual
# Folders (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).
# The default value is: doc.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_VIRTUAL_FOLDER = MITK
# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
# filter to add. For more information please see Qt Help Project / Custom
# Filters (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_NAME =
# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
# custom filter to add. For more information please see Qt Help Project / Custom
# Filters (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_ATTRS =
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_SECT_FILTER_ATTRS =
# The QHG_LOCATION tag can be used to specify the location (absolute path
# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to
# run qhelpgenerator on the generated .qhp file.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHG_LOCATION = @QT_HELPGENERATOR_EXECUTABLE@
# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
# generated, together with the HTML files, they form an Eclipse help plugin. To
# install this plugin and make it available under the help contents menu in
# Eclipse, the contents of the directory containing the HTML and XML files needs
# to be copied into the plugins directory of eclipse. The name of the directory
# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
# After copying Eclipse needs to be restarted before the help appears.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_ECLIPSEHELP = NO
# A unique identifier for the Eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have this
# name. Each documentation set should have its own identifier.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
ECLIPSE_DOC_ID = org.doxygen.Project
# If you want full control over the layout of the generated HTML pages it might
# be necessary to disable the index and replace it with your own. The
# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
# of each HTML page. A value of NO enables the index and the value YES disables
# it. Since the tabs in the index contain the same information as the navigation
# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
DISABLE_INDEX = NO
# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information. If the tag
# value is set to YES, a side panel will be generated containing a tree-like
# index structure (just like the one that is generated for HTML Help). For this
# to work a browser that supports JavaScript, DHTML, CSS and frames is required
# (i.e. any modern browser). Windows users are probably better off using the
# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
# further fine tune the look of the index (see "Fine-tuning the output"). As an
# example, the default style sheet generated by doxygen has an example that
# shows how to put an image at the root of the tree instead of the PROJECT_NAME.
# Since the tree basically has the same information as the tab index, you could
# consider setting DISABLE_INDEX to YES when enabling this option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_TREEVIEW = YES
# When both GENERATE_TREEVIEW and DISABLE_INDEX are set to YES, then the
# FULL_SIDEBAR option determines if the side bar is limited to only the treeview
# area (value NO) or if it should extend to the full height of the window (value
# YES). Setting this to YES gives a layout similar to
# https://docs.readthedocs.io with more room for contents, but less room for the
# project logo, title, and description. If either GENERATE_TREEVIEW or
# DISABLE_INDEX is set to NO, this option has no effect.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
FULL_SIDEBAR = NO
# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
# doxygen will group on one line in the generated HTML documentation.
#
# Note that a value of 0 will completely suppress the enum values from appearing
# in the overview section.
# Minimum value: 0, maximum value: 20, default value: 4.
# This tag requires that the tag GENERATE_HTML is set to YES.
ENUM_VALUES_PER_LINE = 4
# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
# to set the initial width (in pixels) of the frame in which the tree is shown.
# Minimum value: 0, maximum value: 1500, default value: 250.
# This tag requires that the tag GENERATE_HTML is set to YES.
TREEVIEW_WIDTH = 300
# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
# external symbols imported via tag files in a separate window.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
EXT_LINKS_IN_WINDOW = NO
# If the OBFUSCATE_EMAILS tag is set to YES, doxygen will obfuscate email
# addresses.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
OBFUSCATE_EMAILS = YES
# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg
# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see
# https://inkscape.org) to generate formulas as SVG images instead of PNGs for
# the HTML output. These images will generally look nicer at scaled resolutions.
# Possible values are: png (the default) and svg (looks nicer but requires the
# pdf2svg or inkscape tool).
# The default value is: png.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FORMULA_FORMAT = png
# Use this tag to change the font size of LaTeX formulas included as images in
# the HTML documentation. When you change the font size after a successful
# doxygen run you need to manually remove any form_*.png images from the HTML
# output directory to force them to be regenerated.
# Minimum value: 8, maximum value: 50, default value: 10.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_FONTSIZE = 10
# The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands
# to create new LaTeX commands to be used in formulas as building blocks. See
# the section "Including formulas" for details.
FORMULA_MACROFILE =
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
# https://www.mathjax.org) which uses client side JavaScript for the rendering
# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
# installed or if you want to formulas look prettier in the HTML output. When
# enabled you may also need to install MathJax separately and configure the path
# to it using the MATHJAX_RELPATH option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
USE_MATHJAX = NO
# With MATHJAX_VERSION it is possible to specify the MathJax version to be used.
# Note that the different versions of MathJax have different requirements with
# regards to the different settings, so it is possible that also other MathJax
# settings have to be changed when switching between the different MathJax
# versions.
# Possible values are: MathJax_2 and MathJax_3.
# The default value is: MathJax_2.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_VERSION = MathJax_2
# When MathJax is enabled you can set the default output format to be used for
# the MathJax output. For more details about the output format see MathJax
# version 2 (see:
# http://docs.mathjax.org/en/v2.7-latest/output.html) and MathJax version 3
# (see:
# http://docs.mathjax.org/en/latest/web/components/output.html).
# Possible values are: HTML-CSS (which is slower, but has the best
# compatibility. This is the name for Mathjax version 2, for MathJax version 3
# this will be translated into chtml), NativeMML (i.e. MathML. Only supported
# for NathJax 2. For MathJax version 3 chtml will be used instead.), chtml (This
# is the name for Mathjax version 3, for MathJax version 2 this will be
# translated into HTML-CSS) and SVG.
# The default value is: HTML-CSS.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_FORMAT = HTML-CSS
# When MathJax is enabled you need to specify the location relative to the HTML
# output directory using the MATHJAX_RELPATH option. The destination directory
# should contain the MathJax.js script. For instance, if the mathjax directory
# is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
# Content Delivery Network so you can quickly see the result without installing
# MathJax. However, it is strongly recommended to install a local copy of
# MathJax from https://www.mathjax.org before deployment. The default value is:
# - in case of MathJax version 2: https://cdn.jsdelivr.net/npm/mathjax@2
# - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_RELPATH = http://www.mathjax.org/mathjax
# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example
# for MathJax version 2 (see
# https://docs.mathjax.org/en/v2.7-latest/tex.html#tex-and-latex-extensions):
# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
# For example for MathJax version 3 (see
# http://docs.mathjax.org/en/latest/input/tex/extensions/index.html):
# MATHJAX_EXTENSIONS = ams
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_EXTENSIONS =
# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
# of code that will be used on startup of the MathJax code. See the MathJax site
# (see:
# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an
# example see the documentation.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_CODEFILE =
# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
# the HTML output. The underlying search engine uses javascript and DHTML and
# should work on any modern browser. Note that when using HTML help
# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
# there is already a search function so this one should typically be disabled.
# For large projects the javascript based search engine can be slow, then
# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
# search using the keyboard; to jump to the search box use <access key> + S
# (what the <access key> is depends on the OS and browser, but it is typically
# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
# key> to jump into the search results window, the results can be navigated
# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
# the search. The filter options can be selected when the cursor is inside the
# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
# to select a filter and <Enter> or <escape> to activate or cancel the filter
# option.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
SEARCHENGINE = YES
# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
# implemented using a web server instead of a web client using JavaScript. There
# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
# setting. When disabled, doxygen will generate a PHP script for searching and
# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
# and searching needs to be provided by external tools. See the section
# "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
SERVER_BASED_SEARCH = NO
# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
# script for searching. Instead the search results are written to an XML file
# which needs to be processed by an external indexer. Doxygen will invoke an
# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
# search results.
#
# Doxygen ships with an example indexer (doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see:
# https://xapian.org/).
#
# See the section "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH = NO
# The SEARCHENGINE_URL should point to a search engine hosted by a web server
# which will return the search results when EXTERNAL_SEARCH is enabled.
#
# Doxygen ships with an example indexer (doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see:
# https://xapian.org/). See the section "External Indexing and Searching" for
# details.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHENGINE_URL =
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
# search data is written to a file for indexing by an external tool. With the
# SEARCHDATA_FILE tag the name of this file can be specified.
# The default file is: searchdata.xml.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHDATA_FILE = searchdata.xml
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
# projects and redirect the results back to the right project.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH_ID =
# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
# projects other than the one defined by this configuration file, but that are
# all added to the same external search index. Each project needs to have a
# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
# to a relative location where the documentation can be found. The format is:
# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
# The default value is: YES.
GENERATE_LATEX = YES
# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_OUTPUT = latex
# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
# invoked.
#
# Note that when not enabling USE_PDFLATEX the default is latex when enabling
# USE_PDFLATEX the default is pdflatex and when in the later case latex is
# chosen this is overwritten by pdflatex. For specific output languages the
# default can have been set differently, this depends on the implementation of
# the output language.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_CMD_NAME = latex
# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
# index for LaTeX.
# Note: This tag is used in the Makefile / make.bat.
# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file
# (.tex).
# The default file is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
MAKEINDEX_CMD_NAME = makeindex
# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to
# generate index for LaTeX. In case there is no backslash (\) as first character
# it will be automatically added in the LaTeX code.
# Note: This tag is used in the generated output file (.tex).
# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.
# The default value is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_MAKEINDEX_CMD = makeindex
# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
COMPACT_LATEX = NO
# The PAPER_TYPE tag can be used to set the paper type that is used by the
# printer.
# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
# 14 inches) and executive (7.25 x 10.5 inches).
# The default value is: a4.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PAPER_TYPE = a4
# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
# that should be included in the LaTeX output. The package can be specified just
# by its name or with the correct syntax as to be used with the LaTeX
# \usepackage command. To get the times font for instance you can specify :
# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
# To use the option intlimits with the amsmath package you can specify:
# EXTRA_PACKAGES=[intlimits]{amsmath}
# If left blank no extra packages will be included.
# This tag requires that the tag GENERATE_LATEX is set to YES.
EXTRA_PACKAGES = amssymb
# The LATEX_HEADER tag can be used to specify a user-defined LaTeX header for
# the generated LaTeX document. The header should contain everything until the
# first chapter. If it is left blank doxygen will generate a standard header. It
# is highly recommended to start with a default header using
# doxygen -w latex new_header.tex new_footer.tex new_stylesheet.sty
# and then modify the file new_header.tex. See also section "Doxygen usage" for
# information on how to generate the default header that doxygen normally uses.
#
# Note: Only use a user-defined header if you know what you are doing!
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. The following
# commands have a special meaning inside the header (and footer): For a
# description of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HEADER =
# The LATEX_FOOTER tag can be used to specify a user-defined LaTeX footer for
# the generated LaTeX document. The footer should contain everything after the
# last chapter. If it is left blank doxygen will generate a standard footer. See
# LATEX_HEADER for more information on how to generate a default footer and what
# special commands can be used inside the footer. See also section "Doxygen
# usage" for information on how to generate the default footer that doxygen
# normally uses. Note: Only use a user-defined footer if you know what you are
# doing!
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_FOOTER =
# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# LaTeX style sheets that are included after the standard style sheets created
# by doxygen. Using this option one can overrule certain style aspects. Doxygen
# will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list).
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EXTRA_STYLESHEET =
# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the LATEX_OUTPUT output
# directory. Note that the files will be copied as-is; there are no commands or
# markers available.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EXTRA_FILES =
# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
# contain links (just like the HTML output) instead of page references. This
# makes the output suitable for online browsing using a PDF viewer.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PDF_HYPERLINKS = YES
# If the USE_PDFLATEX tag is set to YES, doxygen will use the engine as
# specified with LATEX_CMD_NAME to generate the PDF file directly from the LaTeX
# files. Set this option to YES, to get a higher quality PDF documentation.
#
# See also section LATEX_CMD_NAME for selecting the engine.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
USE_PDFLATEX = YES
# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
# command to the generated LaTeX files. This will instruct LaTeX to keep running
# if errors occur, instead of asking the user for help.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BATCHMODE = YES
# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
# index chapters (such as File Index, Compound Index, etc.) in the output.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HIDE_INDICES = YES
# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
# bibliography, e.g. plainnat, or ieeetr. See
# https://en.wikipedia.org/wiki/BibTeX and \cite for more info.
# The default value is: plain.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BIB_STYLE = plain
# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
# page will contain the date and time when the page was generated. Setting this
# to NO can help when comparing the output of multiple runs.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_TIMESTAMP = NO
# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)
# path from which the emoji images will be read. If a relative path is entered,
# it will be relative to the LATEX_OUTPUT directory. If left blank the
# LATEX_OUTPUT directory will be used.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EMOJI_DIRECTORY =
#---------------------------------------------------------------------------
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
# RTF output is optimized for Word 97 and may not look too pretty with other RTF
# readers/editors.
# The default value is: NO.
GENERATE_RTF = NO
# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: rtf.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_OUTPUT = rtf
# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
COMPACT_RTF = NO
# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
# contain hyperlink fields. The RTF file will contain links (just like the HTML
# output) instead of page references. This makes the output suitable for online
# browsing using Word or some other Word compatible readers that support those
# fields.
#
# Note: WordPad (write) and others do not support links.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_HYPERLINKS = NO
# Load stylesheet definitions from file. Syntax is similar to doxygen's
# configuration file, i.e. a series of assignments. You only have to provide
# replacements, missing definitions are set to their default value.
#
# See also section "Doxygen usage" for information on how to generate the
# default style sheet that doxygen normally uses.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_STYLESHEET_FILE =
# Set optional variables used in the generation of an RTF document. Syntax is
# similar to doxygen's configuration file. A template extensions file can be
# generated using doxygen -e rtf extensionFile.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# Configuration options related to the man page output
#---------------------------------------------------------------------------
# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
# classes and files.
# The default value is: NO.
GENERATE_MAN = NO
# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it. A directory man3 will be created inside the directory specified by
# MAN_OUTPUT.
# The default directory is: man.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_OUTPUT = man
# The MAN_EXTENSION tag determines the extension that is added to the generated
# man pages. In case the manual section does not start with a number, the number
# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
# optional.
# The default value is: .3.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_EXTENSION = .3
# The MAN_SUBDIR tag determines the name of the directory created within
# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
# MAN_EXTENSION with the initial . removed.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_SUBDIR =
# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
# will generate one additional man file for each entity documented in the real
# man page(s). These additional files only source the real man page, but without
# them the man command would be unable to find the correct page.
# The default value is: NO.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_LINKS = NO
#---------------------------------------------------------------------------
# Configuration options related to the XML output
#---------------------------------------------------------------------------
# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
# captures the structure of the code including all documentation.
# The default value is: NO.
GENERATE_XML = NO
# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: xml.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_OUTPUT = xml
# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
# listings (including syntax highlighting and cross-referencing information) to
# the XML output. Note that enabling this will significantly increase the size
# of the XML output.
# The default value is: YES.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_PROGRAMLISTING = YES
# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include
# namespace members in file scope as well, matching the HTML output.
# The default value is: NO.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_NS_MEMB_FILE_SCOPE = NO
#---------------------------------------------------------------------------
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
# that can be used to generate PDF.
# The default value is: NO.
GENERATE_DOCBOOK = NO
# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
# front of it.
# The default directory is: docbook.
# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
DOCBOOK_OUTPUT = docbook
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures
# the structure of the code including all documentation. Note that this feature
# is still experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
# file that captures the structure of the code including all documentation.
#
# Note that this feature is still experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_PERLMOD = NO
# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
# output from the Perl module output.
# The default value is: NO.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_LATEX = NO
# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
# formatted so it can be parsed by a human reader. This is useful if you want to
# understand what is going on. On the other hand, if this tag is set to NO, the
# size of the Perl module output will be much smaller and Perl will parse it
# just the same.
# The default value is: YES.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_PRETTY = YES
# The names of the make variables in the generated doxyrules.make file are
# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
# so different doxyrules.make files included by the same Makefile don't
# overwrite each other's variables.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
# C-preprocessor directives found in the sources and include files.
# The default value is: YES.
ENABLE_PREPROCESSING = YES
# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
# in the source code. If set to NO, only conditional compilation will be
# performed. Macro expansion can be done in a controlled way by setting
# EXPAND_ONLY_PREDEF to YES.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
MACRO_EXPANSION = YES
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
# the macro expansion is limited to the macros specified with the PREDEFINED and
# EXPAND_AS_DEFINED tags.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_ONLY_PREDEF = NO
# If the SEARCH_INCLUDES tag is set to YES, the include files in the
# INCLUDE_PATH will be searched if a #include is found.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SEARCH_INCLUDES = YES
# The INCLUDE_PATH tag can be used to specify one or more directories that
# contain include files that are not input files but should be processed by the
# preprocessor. Note that the INCLUDE_PATH is not recursive, so the setting of
# RECURSIVE has no effect here.
# This tag requires that the tag SEARCH_INCLUDES is set to YES.
INCLUDE_PATH =
# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
# patterns (like *.h and *.hpp) to filter out the header-files in the
# directories. If left blank, the patterns specified with FILE_PATTERNS will be
# used.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
INCLUDE_FILE_PATTERNS =
# The PREDEFINED tag can be used to specify one or more macro names that are
# defined before the preprocessor is started (similar to the -D option of e.g.
# gcc). The argument of the tag is a list of macros of the form: name or
# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
# is assumed. To prevent a macro definition from being undefined via #undef or
# recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
PREDEFINED =
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The
# macro definition that is found in the sources will be used. Use the PREDEFINED
# tag if you want to use a different macro definition that overrules the
# definition found in the source code.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_AS_DEFINED =
# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
# remove all references to function-like macros that are alone on a line, have
# an all uppercase name, and do not end with a semicolon. Such function macros
# are typically used for boiler-plate code, and will confuse the parser if not
# removed.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration options related to external references
#---------------------------------------------------------------------------
# The TAGFILES tag can be used to specify one or more tag files. For each tag
# file the location of the external documentation should be added. The format of
# a tag file without this location is as follows:
# TAGFILES = file1 file2 ...
# Adding location for the tag files is done as follows:
# TAGFILES = file1=loc1 "file2 = loc2" ...
# where loc1 and loc2 can be relative or absolute paths or URLs. See the
# section "Linking to external documentation" for more information about the use
# of tag files.
# Note: Each tag file must have a unique name (where the name does NOT include
# the path). If a tag file is not located in the directory in which doxygen is
# run, you must also specify the path to the tagfile here.
TAGFILES = @BLUEBERRY_DOXYGEN_TAGFILE@
# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
# tag file that is based on the input files it reads. See section "Linking to
# external documentation" for more information about the usage of tag files.
GENERATE_TAGFILE = @MITK_DOXYGEN_TAGFILE_NAME@
# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
# the class index. If set to NO, only the inherited external classes will be
# listed.
# The default value is: NO.
ALLEXTERNALS = NO
# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
# in the modules index. If set to NO, only the current project's groups will be
# listed.
# The default value is: YES.
EXTERNAL_GROUPS = NO
# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
# the related pages index. If set to NO, only the current project's pages will
# be listed.
# The default value is: YES.
EXTERNAL_PAGES = YES
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
# You can include diagrams made with dia in doxygen documentation. Doxygen will
# then run dia to produce the diagram and insert it in the documentation. The
# DIA_PATH tag allows you to specify the directory where the dia binary resides.
# If left empty dia is assumed to be found in the default search path.
DIA_PATH =
# If set to YES the inheritance and collaboration graphs will hide inheritance
# and usage relations if the target is undocumented or is not a class.
# The default value is: YES.
HIDE_UNDOC_RELATIONS = YES
# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz (see:
# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# Bell Labs. The other options in this section have no effect if this option is
# set to NO
# The default value is: NO.
HAVE_DOT = @HAVE_DOT@
# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
# to run in parallel. When set to 0 doxygen will base this on the number of
# processors available in the system. You can set it explicitly to a value
# larger than 0 to get control over the balance between CPU load and processing
# speed.
# Minimum value: 0, maximum value: 32, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_NUM_THREADS = @MITK_DOXYGEN_DOT_NUM_THREADS@
# DOT_COMMON_ATTR is common attributes for nodes, edges and labels of
# subgraphs. When you want a differently looking font in the dot files that
# doxygen generates you can specify fontname, fontcolor and fontsize attributes.
# For details please see <a href=https://graphviz.org/doc/info/attrs.html>Node,
# Edge and Graph Attributes specification</a> You need to make sure dot is able
# to find the font, which can be done by putting it in a standard location or by
# setting the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
# directory containing the font. Default graphviz fontsize is 14.
# The default value is: fontname=Helvetica,fontsize=10.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_COMMON_ATTR = "fontname=Helvetica,fontsize=10"
# DOT_EDGE_ATTR is concatenated with DOT_COMMON_ATTR. For elegant style you can
# add 'arrowhead=open, arrowtail=open, arrowsize=0.5'. <a
# href=https://graphviz.org/doc/info/arrows.html>Complete documentation about
# arrows shapes.</a>
# The default value is: labelfontname=Helvetica,labelfontsize=10.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_EDGE_ATTR = "labelfontname=Helvetica,labelfontsize=10"
# DOT_NODE_ATTR is concatenated with DOT_COMMON_ATTR. For view without boxes
# around nodes set 'shape=plain' or 'shape=plaintext' <a
# href=https://www.graphviz.org/doc/info/shapes.html>Shapes specification</a>
# The default value is: shape=box,height=0.2,width=0.4.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_NODE_ATTR = "shape=box,height=0.2,width=0.4"
# You can set the path where dot can find font specified with fontname in
# DOT_COMMON_ATTR and others dot attributes.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTPATH =
# If the CLASS_GRAPH tag is set to YES (or GRAPH) then doxygen will generate a
# graph for each documented class showing the direct and indirect inheritance
# relations. In case HAVE_DOT is set as well dot will be used to draw the graph,
# otherwise the built-in generator will be used. If the CLASS_GRAPH tag is set
# to TEXT the direct and indirect inheritance relations will be shown as texts /
# links.
# Possible values are: NO, YES, TEXT and GRAPH.
# The default value is: YES.
CLASS_GRAPH = YES
# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
# graph for each documented class showing the direct and indirect implementation
# dependencies (inheritance, containment, and class references variables) of the
# class with other documented classes.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
COLLABORATION_GRAPH = YES
# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
# groups, showing the direct groups dependencies. See also the chapter Grouping
# in the manual.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GROUP_GRAPHS = YES
# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
# collaboration diagrams in a style similar to the OMG's Unified Modeling
# Language.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
UML_LOOK = @MITK_DOXYGEN_UML_LOOK@
# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
# class node. If there are many fields or methods and many nodes the graph may
# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
# number of items for each type to make the size more manageable. Set this to 0
# for no limit. Note that the threshold may be exceeded by 50% before the limit
# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
# but if the number exceeds 15, the total amount of fields shown is limited to
# 10.
# Minimum value: 0, maximum value: 100, default value: 10.
# This tag requires that the tag UML_LOOK is set to YES.
UML_LIMIT_NUM_FIELDS = 10
# If the DOT_UML_DETAILS tag is set to NO, doxygen will show attributes and
# methods without types and arguments in the UML graphs. If the DOT_UML_DETAILS
# tag is set to YES, doxygen will add type and arguments for attributes and
# methods in the UML graphs. If the DOT_UML_DETAILS tag is set to NONE, doxygen
# will not generate fields with class member information in the UML graphs. The
# class diagrams will look similar to the default class diagrams but using UML
# notation for the relationships.
# Possible values are: NO, YES and NONE.
# The default value is: NO.
# This tag requires that the tag UML_LOOK is set to YES.
DOT_UML_DETAILS = NO
# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters
# to display on a single line. If the actual line length exceeds this threshold
# significantly it will wrapped across multiple lines. Some heuristics are apply
# to avoid ugly line breaks.
# Minimum value: 0, maximum value: 1000, default value: 17.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_WRAP_THRESHOLD = 17
# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
# collaboration graphs will show the relations between templates and their
# instances.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
TEMPLATE_RELATIONS = YES
# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
# YES then doxygen will generate a graph for each documented file showing the
# direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDE_GRAPH = NO
# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
# set to YES then doxygen will generate a graph for each documented file showing
# the direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDED_BY_GRAPH = NO
# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable call graphs for selected
# functions only using the \callgraph command. Disabling a call graph can be
# accomplished by means of the command \hidecallgraph.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALL_GRAPH = NO
# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable caller graphs for selected
# functions only using the \callergraph command. Disabling a caller graph can be
# accomplished by means of the command \hidecallergraph.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALLER_GRAPH = NO
# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
# hierarchy of all classes instead of a textual one.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GRAPHICAL_HIERARCHY = NO
# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
# dependencies a directory has on other directories in a graphical way. The
# dependency relations are determined by the #include relations between the
# files in the directories.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
DIRECTORY_GRAPH = YES
# The DIR_GRAPH_MAX_DEPTH tag can be used to limit the maximum number of levels
# of child directories generated in directory dependency graphs by dot.
# Minimum value: 1, maximum value: 25, default value: 1.
# This tag requires that the tag DIRECTORY_GRAPH is set to YES.
DIR_GRAPH_MAX_DEPTH = 1
# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
# generated by dot. For an explanation of the image formats see the section
# output formats in the documentation of the dot tool (Graphviz (see:
# http://www.graphviz.org/)).
# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
# to make the SVG files visible in IE 9+ (other browsers do not have this
# requirement).
# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,
# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
# png:gdiplus:gdiplus.
# The default value is: png.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_IMAGE_FORMAT = png
# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
# enable generation of interactive SVG images that allow zooming and panning.
#
# Note that this requires a modern browser other than Internet Explorer. Tested
# and working are Firefox, Chrome, Safari, and Opera.
# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
# the SVG files visible. Older versions of IE do not have SVG support.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
INTERACTIVE_SVG = NO
# The DOT_PATH tag can be used to specify the path where the dot tool can be
# found. If left blank, it is assumed the dot tool can be found in the path.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_PATH = @DOXYGEN_DOT_PATH@
# The DOTFILE_DIRS tag can be used to specify one or more directories that
# contain dot files that are included in the documentation (see the \dotfile
# command).
# This tag requires that the tag HAVE_DOT is set to YES.
DOTFILE_DIRS =
# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the \mscfile
# command).
MSCFILE_DIRS =
# The DIAFILE_DIRS tag can be used to specify one or more directories that
# contain dia files that are included in the documentation (see the \diafile
# command).
DIAFILE_DIRS =
# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
# path where java can find the plantuml.jar file or to the filename of jar file
# to be used. If left blank, it is assumed PlantUML is not used or called during
# a preprocessing step. Doxygen will generate a warning when it encounters a
# \startuml command in this case and will not generate output for the diagram.
PLANTUML_JAR_PATH =
# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
# configuration file for plantuml.
PLANTUML_CFG_FILE =
# When using plantuml, the specified paths are searched for files specified by
# the !include statement in a plantuml block.
PLANTUML_INCLUDE_PATH =
# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
# that will be shown in the graph. If the number of nodes in a graph becomes
# larger than this value, doxygen will truncate the graph, which is visualized
# by representing a node as a red box. Note that doxygen if the number of direct
# children of the root node in a graph is already larger than
# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
# Minimum value: 0, maximum value: 10000, default value: 50.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_GRAPH_MAX_NODES = 50
# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
# generated by dot. A depth value of 3 means that only nodes reachable from the
# root by following a path via at most 3 edges will be shown. Nodes that lay
# further from the root node will be omitted. Note that setting this option to 1
# or 2 may greatly reduce the computation time needed for large code bases. Also
# note that the size of a graph can be further restricted by
# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
# Minimum value: 0, maximum value: 1000, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
MAX_DOT_GRAPH_DEPTH = 0
# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
# files in one run (i.e. multiple -o and -T options on the command line). This
# makes dot run faster, but since only newer versions of dot (>1.8.10) support
# this, this feature is disabled by default.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_MULTI_TARGETS = NO
# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
# explaining the meaning of the various boxes and arrows in the dot generated
# graphs.
# Note: This tag requires that UML_LOOK isn't set, i.e. the doxygen internal
# graphical representation for inheritance and collaboration diagrams is used.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GENERATE_LEGEND = YES
# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate
# files that are used to generate the various graphs.
#
# Note: This setting is not only used for dot files but also for msc temporary
# files.
# The default value is: YES.
DOT_CLEANUP = YES
diff --git a/Documentation/doxygen_users_guide.conf.in b/Documentation/doxygen_users_guide.conf.in
index b37e0c17ab..ce6a6ed84a 100644
--- a/Documentation/doxygen_users_guide.conf.in
+++ b/Documentation/doxygen_users_guide.conf.in
@@ -1,2737 +1,2737 @@
# Doxyfile 1.9.6
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a double hash (##) is considered a comment and is placed in
# front of the TAG it is preceding.
#
# All text after a single hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists, items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (\" \").
#
# Note:
#
# Use doxygen to compare the used configuration file with the template
# configuration file:
# doxygen -x [configFile]
# Use doxygen to compare the used configuration file with the template
# configuration file without replacing the environment variables or CMake type
# replacement variables:
# doxygen -x_noenv [configFile]
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
# This tag specifies the encoding used for all characters in the configuration
# file that follow. The default is UTF-8 which is also the encoding used for all
# text before the first occurrence of this tag. Doxygen uses libiconv (or the
# iconv built into libc) for the transcoding. See
# https://www.gnu.org/software/libiconv/ for the list of possible encodings.
# The default value is: UTF-8.
DOXYFILE_ENCODING = UTF-8
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
# double-quotes, unless you are using Doxywizard) that should identify the
# project for which the documentation is generated. This name is used in the
# title of most generated pages and in a few other places.
# The default value is: My Project.
PROJECT_NAME = MITK
# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER = @MITK_VERSION_STRING@
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
# quick idea about the purpose of the project. Keep the description short.
PROJECT_BRIEF = "Medical Imaging Interaction Toolkit"
# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
# in the documentation. The maximum height of the logo should not exceed 55
# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
# the logo to the output directory.
PROJECT_LOGO =
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = @MITK_DOXYGEN_OUTPUT_DIR@/Guides/Users_Guide/
# If the CREATE_SUBDIRS tag is set to YES then doxygen will create up to 4096
# sub-directories (in 2 levels) under the output directory of each output format
# and will distribute the generated files over these directories. Enabling this
# option can be useful when feeding doxygen a huge amount of source files, where
# putting all generated files in the same directory would otherwise causes
# performance problems for the file system. Adapt CREATE_SUBDIRS_LEVEL to
# control the number of sub-directories.
# The default value is: NO.
CREATE_SUBDIRS = NO
# Controls the number of sub-directories that will be created when
# CREATE_SUBDIRS tag is set to YES. Level 0 represents 16 directories, and every
# level increment doubles the number of directories, resulting in 4096
# directories at level 8 which is the default and also the maximum value. The
# sub-directories are organized in 2 levels, the first level always has a fixed
# number of 16 directories.
# Minimum value: 0, maximum value: 8, default value: 8.
# This tag requires that the tag CREATE_SUBDIRS is set to YES.
CREATE_SUBDIRS_LEVEL = 8
# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
# characters to appear in the names of generated files. If set to NO, non-ASCII
# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
# U+3044.
# The default value is: NO.
ALLOW_UNICODE_NAMES = NO
# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Bulgarian,
# Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, English
# (United States), Esperanto, Farsi (Persian), Finnish, French, German, Greek,
# Hindi, Hungarian, Indonesian, Italian, Japanese, Japanese-en (Japanese with
# English messages), Korean, Korean-en (Korean with English messages), Latvian,
# Lithuanian, Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese,
# Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish,
# Swedish, Turkish, Ukrainian and Vietnamese.
# The default value is: English.
OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
# descriptions after the members that are listed in the file and class
# documentation (similar to Javadoc). Set to NO to disable this.
# The default value is: YES.
BRIEF_MEMBER_DESC = YES
# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
# description of a member or function before the detailed description
#
# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
# The default value is: YES.
REPEAT_BRIEF = YES
# This tag implements a quasi-intelligent brief description abbreviator that is
# used to form the text in various listings. Each string in this list, if found
# as the leading text of the brief description, will be stripped from the text
# and the result, after processing the whole list, is used as the annotated
# text. Otherwise, the brief description is used as-is. If left blank, the
# following values are used ($name is automatically replaced with the name of
# the entity):The $name class, The $name widget, The $name file, is, provides,
# specifies, contains, represents, a, an and the.
ABBREVIATE_BRIEF =
# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# doxygen will generate a detailed section even if there is only a brief
# description.
# The default value is: NO.
ALWAYS_DETAILED_SEC = NO
# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
# inherited members of a class in the documentation of that class as if those
# members were ordinary class members. Constructors, destructors and assignment
# operators of the base classes will not be shown.
# The default value is: NO.
INLINE_INHERITED_MEMB = NO
# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
# before files name in the file list and in the header files. If set to NO the
# shortest path that makes the file name unique will be used
# The default value is: YES.
FULL_PATH_NAMES = NO
# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
# Stripping is only done if one of the specified strings matches the left-hand
# part of the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the path to
# strip.
#
# Note that you can specify absolute paths here, but also relative paths, which
# will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES.
STRIP_FROM_PATH =
# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
# path mentioned in the documentation of a class, which tells the reader which
# header file to include in order to use a class. If left blank only the name of
# the header file containing the class definition is used. Otherwise one should
# specify the list of include paths that are normally passed to the compiler
# using the -I flag.
STRIP_FROM_INC_PATH =
# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
# less readable) file names. This can be useful is your file systems doesn't
# support long names like on DOS, Mac, or CD-ROM.
# The default value is: NO.
SHORT_NAMES = NO
# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
# first line (until the first dot) of a Javadoc-style comment as the brief
# description. If set to NO, the Javadoc-style will behave just like regular Qt-
# style comments (thus requiring an explicit @brief command for a brief
# description.)
# The default value is: NO.
JAVADOC_AUTOBRIEF = NO
# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line
# such as
# /***************
# as being the beginning of a Javadoc-style comment "banner". If set to NO, the
# Javadoc-style will behave just like regular comments and it will not be
# interpreted by doxygen.
# The default value is: NO.
JAVADOC_BANNER = NO
# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
# line (until the first dot) of a Qt-style comment as the brief description. If
# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
# requiring an explicit \brief command for a brief description.)
# The default value is: NO.
QT_AUTOBRIEF = NO
# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
# a brief description. This used to be the default behavior. The new default is
# to treat a multi-line C++ comment block as a detailed description. Set this
# tag to YES if you prefer the old behavior instead.
#
# Note that setting this tag to YES also means that rational rose comments are
# not recognized any more.
# The default value is: NO.
MULTILINE_CPP_IS_BRIEF = NO
# By default Python docstrings are displayed as preformatted text and doxygen's
# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the
# doxygen's special commands can be used and the contents of the docstring
# documentation blocks is shown as doxygen documentation.
# The default value is: YES.
PYTHON_DOCSTRING = YES
# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
# documentation from any documented member that it re-implements.
# The default value is: YES.
INHERIT_DOCS = YES
# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
# page for each member. If set to NO, the documentation of a member will be part
# of the file/class/namespace that contains it.
# The default value is: NO.
SEPARATE_MEMBER_PAGES = NO
# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
# uses this value to replace tabs by spaces in code fragments.
# Minimum value: 1, maximum value: 16, default value: 4.
TAB_SIZE = 8
# This tag can be used to specify a number of aliases that act as commands in
# the documentation. An alias has the form:
# name=value
# For example adding
# "sideeffect=@par Side Effects:^^"
# will allow you to put the command \sideeffect (or @sideeffect) in the
# documentation, which will result in a user-defined paragraph with heading
# "Side Effects:". Note that you cannot put \n's in the value part of an alias
# to insert newlines (in the resulting output). You can put ^^ in the value part
# of an alias to insert a newline as if a physical newline was in the original
# file. When you need a literal { or } or , in the value part of an alias you
# have to escape them by means of a backslash (\), this can lead to conflicts
# with the commands \{ and \} for these it is advised to use the version @{ and
# @} or use a double escape (\\{ and \\})
ALIASES = "FIXME=\par Fix Me's:\n" \
"BlueBerry=\if BLUEBERRY" \
"endBlueBerry=\endif" \
"bundlemainpage{1}=\page \1" \
"embmainpage{1}=\page \1" \
"github{2}=<a href=\"https://github.com/MITK/MITK/blob/master/\1\">\2</a>" \
"deprecatedSince{1}=\xrefitem deprecatedSince\1 \" Deprecated as of \1\" \"Functions deprecated as of \1\"" \
"minimumCMakeVersion=@MITK_CMAKE_MINIMUM_REQUIRED_VERSION@" \
- "minimumQt5Version=@MITK_QT5_MINIMUM_VERSION@" \
+ "minimumQt6Version=@MITK_QT6_MINIMUM_VERSION@" \
"imageMacro{3}=\image html \1 \2 \n \image latex \1 \2 width=\3cm" \
"developersguidemainpage{1}=\page \1" \
"usersguidemainpage{1}=\mainpage" \
"nondependentPluginLink{3}= \ref \1 \"\3\""
# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
# only. Doxygen will then generate output that is more tailored for C. For
# instance, some of the names that are used will be different. The list of all
# members will be omitted, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_FOR_C = NO
# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
# Python sources only. Doxygen will then generate output that is more tailored
# for that language. For instance, namespaces will be presented as packages,
# qualified scopes will look different, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_JAVA = NO
# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
# sources. Doxygen will then generate output that is tailored for Fortran.
# The default value is: NO.
OPTIMIZE_FOR_FORTRAN = NO
# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
# sources. Doxygen will then generate output that is tailored for VHDL.
# The default value is: NO.
OPTIMIZE_OUTPUT_VHDL = NO
# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice
# sources only. Doxygen will then generate output that is more tailored for that
# language. For instance, namespaces will be presented as modules, types will be
# separated into more groups, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_SLICE = NO
# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given
# extension. Doxygen has a built-in mapping, but you can override or extend it
# using this tag. The format is ext=language, where ext is a file extension, and
# language is one of the parsers supported by doxygen: IDL, Java, JavaScript,
# Csharp (C#), C, C++, Lex, D, PHP, md (Markdown), Objective-C, Python, Slice,
# VHDL, Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:
# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser
# tries to guess whether the code is fixed or free formatted code, this is the
# default for Fortran type files). For instance to make doxygen treat .inc files
# as Fortran files (default is PHP), and .f files as C (default is Fortran),
# use: inc=Fortran f=C.
#
# Note: For files without extension you can use no_extension as a placeholder.
#
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen. When specifying no_extension you should add
# * to the FILE_PATTERNS.
#
# Note see also the list of default file extension mappings.
EXTENSION_MAPPING =
# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable
# documentation. See https://daringfireball.net/projects/markdown/ for details.
# The output of markdown processing is further processed by doxygen, so you can
# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
# case of backward compatibilities issues.
# The default value is: YES.
MARKDOWN_SUPPORT = YES
# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
# to that level are automatically included in the table of contents, even if
# they do not have an id attribute.
# Note: This feature currently applies only to Markdown headings.
# Minimum value: 0, maximum value: 99, default value: 5.
# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
TOC_INCLUDE_HEADINGS = 5
# When enabled doxygen tries to link words that correspond to documented
# classes, or namespaces to their corresponding documentation. Such a link can
# be prevented in individual cases by putting a % sign in front of the word or
# globally by setting AUTOLINK_SUPPORT to NO.
# The default value is: YES.
AUTOLINK_SUPPORT = YES
# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
# to include (a tag file for) the STL sources as input, then you should set this
# tag to YES in order to let doxygen match functions declarations and
# definitions whose arguments contain STL classes (e.g. func(std::string);
# versus func(std::string) {}). This also make the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate.
# The default value is: NO.
BUILTIN_STL_SUPPORT = YES
# If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support.
# The default value is: NO.
CPP_CLI_SUPPORT = NO
# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen
# will parse them like normal C++ but will assume all classes use public instead
# of private inheritance when no explicit protection keyword is present.
# The default value is: NO.
SIP_SUPPORT = NO
# For Microsoft's IDL there are propget and propput attributes to indicate
# getter and setter methods for a property. Setting this option to YES will make
# doxygen to replace the get and set methods by a property in the documentation.
# This will only work if the methods are indeed getting or setting a simple
# type. If this is not the case, or you want to show the methods anyway, you
# should set this option to NO.
# The default value is: YES.
IDL_PROPERTY_SUPPORT = YES
# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
# tag is set to YES then doxygen will reuse the documentation of the first
# member in the group (if any) for the other members of the group. By default
# all members of a group must be documented explicitly.
# The default value is: NO.
DISTRIBUTE_GROUP_DOC = YES
# If one adds a struct or class to a group and this option is enabled, then also
# any nested class or struct is added to the same group. By default this option
# is disabled and one has to add nested compounds explicitly via \ingroup.
# The default value is: NO.
GROUP_NESTED_COMPOUNDS = NO
# Set the SUBGROUPING tag to YES to allow class member groups of the same type
# (for instance a group of public functions) to be put as a subgroup of that
# type (e.g. under the Public Functions section). Set it to NO to prevent
# subgrouping. Alternatively, this can be done per class using the
# \nosubgrouping command.
# The default value is: YES.
SUBGROUPING = YES
# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
# are shown inside the group in which they are included (e.g. using \ingroup)
# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
# and RTF).
#
# Note that this feature does not work in combination with
# SEPARATE_MEMBER_PAGES.
# The default value is: NO.
INLINE_GROUPED_CLASSES = NO
# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
# with only public data fields or simple typedef fields will be shown inline in
# the documentation of the scope in which they are defined (i.e. file,
# namespace, or group documentation), provided this scope is documented. If set
# to NO, structs, classes, and unions are shown on a separate page (for HTML and
# Man pages) or section (for LaTeX and RTF).
# The default value is: NO.
INLINE_SIMPLE_STRUCTS = NO
# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
# enum is documented as struct, union, or enum with the name of the typedef. So
# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
# with name TypeT. When disabled the typedef will appear as a member of a file,
# namespace, or class. And the struct will be named TypeS. This can typically be
# useful for C code in case the coding convention dictates that all compound
# types are typedef'ed and only the typedef is referenced, never the tag name.
# The default value is: NO.
TYPEDEF_HIDES_STRUCT = NO
# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
# cache is used to resolve symbols given their name and scope. Since this can be
# an expensive process and often the same symbol appears multiple times in the
# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
# doxygen will become slower. If the cache is too large, memory is wasted. The
# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
# symbols. At the end of a run doxygen will report the cache usage and suggest
# the optimal cache size from a speed point of view.
# Minimum value: 0, maximum value: 9, default value: 0.
LOOKUP_CACHE_SIZE = 0
# The NUM_PROC_THREADS specifies the number of threads doxygen is allowed to use
# during processing. When set to 0 doxygen will based this on the number of
# cores available in the system. You can set it explicitly to a value larger
# than 0 to get more control over the balance between CPU load and processing
# speed. At this moment only the input processing can be done using multiple
# threads. Since this is still an experimental feature the default is set to 1,
# which effectively disables parallel processing. Please report any issues you
# encounter. Generating dot graphs in parallel is controlled by the
# DOT_NUM_THREADS setting.
# Minimum value: 0, maximum value: 32, default value: 1.
NUM_PROC_THREADS = 1
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
# documentation are documented, even if no documentation was available. Private
# class members and static file members will be hidden unless the
# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
# Note: This will also disable the warnings about undocumented members that are
# normally produced when WARNINGS is set to YES.
# The default value is: NO.
EXTRACT_ALL = YES
# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
# be included in the documentation.
# The default value is: NO.
EXTRACT_PRIVATE = NO
# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual
# methods of a class will be included in the documentation.
# The default value is: NO.
EXTRACT_PRIV_VIRTUAL = NO
# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
# scope will be included in the documentation.
# The default value is: NO.
EXTRACT_PACKAGE = NO
# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
# included in the documentation.
# The default value is: NO.
EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
# locally in source files will be included in the documentation. If set to NO,
# only classes defined in header files are included. Does not have any effect
# for Java sources.
# The default value is: YES.
EXTRACT_LOCAL_CLASSES = @MITK_DOXYGEN_INTERNAL_DOCS@
# This flag is only useful for Objective-C code. If set to YES, local methods,
# which are defined in the implementation section but not in the interface are
# included in the documentation. If set to NO, only methods in the interface are
# included.
# The default value is: NO.
EXTRACT_LOCAL_METHODS = NO
# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base name of
# the file that contains the anonymous namespace. By default anonymous namespace
# are hidden.
# The default value is: NO.
EXTRACT_ANON_NSPACES = NO
# If this flag is set to YES, the name of an unnamed parameter in a declaration
# will be determined by the corresponding definition. By default unnamed
# parameters remain unnamed in the output.
# The default value is: YES.
RESOLVE_UNNAMED_PARAMS = YES
# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
# undocumented members inside documented classes or files. If set to NO these
# members will be included in the various overviews, but no documentation
# section is generated. This option has no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy. If set
# to NO, these classes will be included in the various overviews. This option
# will also hide undocumented C++ concepts if enabled. This option has no effect
# if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_CLASSES = NO
# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
# declarations. If set to NO, these declarations will be included in the
# documentation.
# The default value is: NO.
HIDE_FRIEND_COMPOUNDS = @MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS@
# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
# documentation blocks found inside the body of a function. If set to NO, these
# blocks will be appended to the function's detailed documentation block.
# The default value is: NO.
HIDE_IN_BODY_DOCS = NO
# The INTERNAL_DOCS tag determines if documentation that is typed after a
# \internal command is included. If the tag is set to NO then the documentation
# will be excluded. Set it to YES to include the internal documentation.
# The default value is: NO.
INTERNAL_DOCS = @MITK_DOXYGEN_INTERNAL_DOCS@
# With the correct setting of option CASE_SENSE_NAMES doxygen will better be
# able to match the capabilities of the underlying filesystem. In case the
# filesystem is case sensitive (i.e. it supports files in the same directory
# whose names only differ in casing), the option must be set to YES to properly
# deal with such files in case they appear in the input. For filesystems that
# are not case sensitive the option should be set to NO to properly deal with
# output files written for symbols that only differ in casing, such as for two
# classes, one named CLASS and the other named Class, and to also support
# references to files without having to specify the exact matching casing. On
# Windows (including Cygwin) and MacOS, users should typically set this option
# to NO, whereas on Linux or other Unix flavors it should typically be set to
# YES.
# Possible values are: SYSTEM, NO and YES.
# The default value is: SYSTEM.
CASE_SENSE_NAMES = YES
# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
# their full class and namespace scopes in the documentation. If set to YES, the
# scope will be hidden.
# The default value is: NO.
HIDE_SCOPE_NAMES = NO
# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
# append additional text to a page's title, such as Class Reference. If set to
# YES the compound reference will be hidden.
# The default value is: NO.
HIDE_COMPOUND_REFERENCE= NO
# If the SHOW_HEADERFILE tag is set to YES then the documentation for a class
# will show which file needs to be included to use the class.
# The default value is: YES.
SHOW_HEADERFILE = YES
# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
# the files that are included by a file in the documentation of that file.
# The default value is: YES.
SHOW_INCLUDE_FILES = YES
# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
# grouped member an include statement to the documentation, telling the reader
# which file to include in order to use the member.
# The default value is: NO.
SHOW_GROUPED_MEMB_INC = NO
# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
# files with double quotes in the documentation rather than with sharp brackets.
# The default value is: NO.
FORCE_LOCAL_INCLUDES = NO
# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
# documentation for inline members.
# The default value is: YES.
INLINE_INFO = YES
# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
# (detailed) documentation of file and class members alphabetically by member
# name. If set to NO, the members will appear in declaration order.
# The default value is: YES.
SORT_MEMBER_DOCS = YES
# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
# descriptions of file, namespace and class members alphabetically by member
# name. If set to NO, the members will appear in declaration order. Note that
# this will also influence the order of the classes in the class list.
# The default value is: NO.
SORT_BRIEF_DOCS = NO
# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
# (brief and detailed) documentation of class members so that constructors and
# destructors are listed first. If set to NO the constructors will appear in the
# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
# member documentation.
# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
# detailed member documentation.
# The default value is: NO.
SORT_MEMBERS_CTORS_1ST = NO
# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
# of group names into alphabetical order. If set to NO the group names will
# appear in their defined order.
# The default value is: NO.
SORT_GROUP_NAMES = NO
# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
# fully-qualified names, including namespaces. If set to NO, the class list will
# be sorted only by class name, not including the namespace part.
# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
# Note: This option applies only to the class list, not to the alphabetical
# list.
# The default value is: NO.
SORT_BY_SCOPE_NAME = YES
# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
# type resolution of all parameters of a function it will reject a match between
# the prototype and the implementation of a member function even if there is
# only one candidate or it is obvious which candidate to choose by doing a
# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
# accept a match between prototype and implementation in such cases.
# The default value is: NO.
STRICT_PROTO_MATCHING = NO
# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
# list. This list is created by putting \todo commands in the documentation.
# The default value is: YES.
GENERATE_TODOLIST = @MITK_DOXYGEN_GENERATE_TODOLIST@
# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
# list. This list is created by putting \test commands in the documentation.
# The default value is: YES.
GENERATE_TESTLIST = YES
# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
# list. This list is created by putting \bug commands in the documentation.
# The default value is: YES.
GENERATE_BUGLIST = @MITK_DOXYGEN_GENERATE_BUGLIST@
# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
# the deprecated list. This list is created by putting \deprecated commands in
# the documentation.
# The default value is: YES.
GENERATE_DEPRECATEDLIST= @MITK_DOXYGEN_GENERATE_DEPRECATEDLIST@
# The ENABLED_SECTIONS tag can be used to enable conditional documentation
# sections, marked by \if <section_label> ... \endif and \cond <section_label>
# ... \endcond blocks.
ENABLED_SECTIONS = @MITK_DOXYGEN_ENABLED_SECTIONS@
# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
# initial value of a variable or macro / define can have for it to appear in the
# documentation. If the initializer consists of more lines than specified here
# it will be hidden. Use a value of 0 to hide initializers completely. The
# appearance of the value of individual variables and macros / defines can be
# controlled using \showinitializer or \hideinitializer command in the
# documentation regardless of this setting.
# Minimum value: 0, maximum value: 10000, default value: 30.
MAX_INITIALIZER_LINES = 0
# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
# the bottom of the documentation of classes and structs. If set to YES, the
# list will mention the files that were used to generate the documentation.
# The default value is: YES.
SHOW_USED_FILES = YES
# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
# will remove the Files entry from the Quick Index and from the Folder Tree View
# (if specified).
# The default value is: YES.
SHOW_FILES = YES
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
# page. This will remove the Namespaces entry from the Quick Index and from the
# Folder Tree View (if specified).
# The default value is: YES.
SHOW_NAMESPACES = YES
# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
# the version control system). Doxygen will invoke the program by executing (via
# popen()) the command command input-file, where command is the value of the
# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
# by doxygen. Whatever the program writes to standard output is used as the file
# version. For an example see the documentation.
FILE_VERSION_FILTER =
# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
# by doxygen. The layout file controls the global structure of the generated
# output files in an output format independent way. To create the layout file
# that represents doxygen's defaults, run doxygen with the -l option. You can
# optionally specify a file name after the option, if omitted DoxygenLayout.xml
# will be used as the name of the layout file. See also section "Changing the
# layout of pages" for information.
#
# Note that if you run doxygen from a directory containing a file called
# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
# tag is left empty.
LAYOUT_FILE =
# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
# the reference definitions. This must be a list of .bib files. The .bib
# extension is automatically appended if omitted. This requires the bibtex tool
# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.
# For LaTeX the style of the bibliography can be controlled using
# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
# search path. See also \cite for info how to create references.
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
# The QUIET tag can be used to turn on/off the messages that are generated to
# standard output by doxygen. If QUIET is set to YES this implies that the
# messages are off.
# The default value is: NO.
QUIET = YES
# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
# this implies that the warnings are on.
#
# Tip: Turn warnings on while writing the documentation.
# The default value is: YES.
WARNINGS = YES
# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: YES.
WARN_IF_UNDOCUMENTED = YES
# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
# potential errors in the documentation, such as documenting some parameters in
# a documented function twice, or documenting parameters that don't exist or
# using markup commands wrongly.
# The default value is: YES.
WARN_IF_DOC_ERROR = YES
# If WARN_IF_INCOMPLETE_DOC is set to YES, doxygen will warn about incomplete
# function parameter documentation. If set to NO, doxygen will accept that some
# parameters have no documentation without warning.
# The default value is: YES.
WARN_IF_INCOMPLETE_DOC = YES
# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
# are documented, but have no documentation for their parameters or return
# value. If set to NO, doxygen will only warn about wrong parameter
# documentation, but not about the absence of documentation. If EXTRACT_ALL is
# set to YES then this flag will automatically be disabled. See also
# WARN_IF_INCOMPLETE_DOC
# The default value is: NO.
WARN_NO_PARAMDOC = NO
# If WARN_IF_UNDOC_ENUM_VAL option is set to YES, doxygen will warn about
# undocumented enumeration values. If set to NO, doxygen will accept
# undocumented enumeration values. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: NO.
WARN_IF_UNDOC_ENUM_VAL = NO
# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS
# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but
# at the end of the doxygen process doxygen will return with a non-zero status.
# Possible values are: NO, YES and FAIL_ON_WARNINGS.
# The default value is: NO.
WARN_AS_ERROR = NO
# The WARN_FORMAT tag determines the format of the warning messages that doxygen
# can produce. The string should contain the $file, $line, and $text tags, which
# will be replaced by the file and line number from which the warning originated
# and the warning text. Optionally the format may contain $version, which will
# be replaced by the version of the file (if it could be obtained via
# FILE_VERSION_FILTER)
# See also: WARN_LINE_FORMAT
# The default value is: $file:$line: $text.
WARN_FORMAT = "$file:$line: $text"
# In the $text part of the WARN_FORMAT command it is possible that a reference
# to a more specific place is given. To make it easier to jump to this place
# (outside of doxygen) the user can define a custom "cut" / "paste" string.
# Example:
# WARN_LINE_FORMAT = "'vi $file +$line'"
# See also: WARN_FORMAT
# The default value is: at line $line of file $file.
WARN_LINE_FORMAT = "at line $line of file $file"
# The WARN_LOGFILE tag can be used to specify a file to which warning and error
# messages should be written. If left blank the output is written to standard
# error (stderr). In case the file specified cannot be opened for writing the
# warning and error messages are written to standard error. When as file - is
# specified the warning and error messages are written to standard output
# (stdout).
WARN_LOGFILE =
#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------
# The INPUT tag is used to specify the files and/or directories that contain
# documented source files. You may enter file names like myfile.cpp or
# directories like /usr/src/myproject. Separate the files or directories with
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
# Note: If this tag is empty the current directory is searched.
INPUT = @USERS_GUIDE_INPUT@
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
# documentation (see:
# https://www.gnu.org/software/libiconv/) for the list of possible encodings.
# See also: INPUT_FILE_ENCODING
# The default value is: UTF-8.
INPUT_ENCODING = UTF-8
# This tag can be used to specify the character encoding of the source files
# that doxygen parses The INPUT_FILE_ENCODING tag can be used to specify
# character encoding on a per file pattern basis. Doxygen will compare the file
# name with each pattern and apply the encoding instead of the default
# INPUT_ENCODING) if there is a match. The character encodings are a list of the
# form: pattern=encoding (like *.php=ISO-8859-1). See cfg_input_encoding
# "INPUT_ENCODING" for further information on supported encodings.
INPUT_FILE_ENCODING =
# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# read by doxygen.
#
# Note the list of default checked file patterns might differ from the list of
# default file extension mappings.
#
# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
# *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php, *.php4, *.php5, *.phtml,
# *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C
# comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd,
# *.vhdl, *.ucf, *.qsf and *.ice.
FILE_PATTERNS = *.dox \
*.md
# The RECURSIVE tag can be used to specify whether or not subdirectories should
# be searched for input files as well.
# The default value is: NO.
RECURSIVE = YES
# The EXCLUDE tag can be used to specify files and/or directories that should be
# excluded from the INPUT source files. This way you can easily exclude a
# subdirectory from a directory tree whose root is specified with the INPUT tag.
#
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE =
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
# from the input.
# The default value is: NO.
EXCLUDE_SYMLINKS = NO
# If the value of the INPUT tag contains directories, you can use the
# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
# certain files from those directories.
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/*
EXCLUDE_PATTERNS = modules.dox \
*/Plugins/*/documentation/doxygen/*
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# ANamespace::AClass, ANamespace::*Test
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/*
EXCLUDE_SYMBOLS =
# The EXAMPLE_PATH tag can be used to specify one or more files or directories
# that contain example code fragments that are included (see the \include
# command).
EXAMPLE_PATH =
# If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank all
# files are included.
EXAMPLE_PATTERNS =
# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
# searched for input files to be used with the \include or \dontinclude commands
# irrespective of the value of the RECURSIVE tag.
# The default value is: NO.
EXAMPLE_RECURSIVE = YES
# The IMAGE_PATH tag can be used to specify one or more files or directories
# that contain images that are to be included in the documentation (see the
# \image command).
IMAGE_PATH = "@MITK_SOURCE_DIR@/Documentation/Doxygen/UserManual/" \
"@MITK_SOURCE_DIR@/Plugins/" \
"@MITK_SOURCE_DIR@/Examples/Plugins/"
# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command:
#
# <filter> <input-file>
#
# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
# name of an input file. Doxygen will then use the output that the filter
# program writes to standard output. If FILTER_PATTERNS is specified, this tag
# will be ignored.
#
# Note that the filter must not add or remove lines; it is applied before the
# code is scanned, but not when the output code is generated. If lines are added
# or removed, the anchors will not be placed correctly.
#
# Note that doxygen will use the data processed and written to standard output
# for further processing, therefore nothing else, like debug statements or used
# commands (so in case of a Windows batch file always use @echo OFF), should be
# written to standard output.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# properly processed by doxygen.
INPUT_FILTER =
# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
# basis. Doxygen will compare the file name with each pattern and apply the
# filter if there is a match. The filters are a list of the form: pattern=filter
# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
# patterns match the file name, INPUT_FILTER is applied.
#
# Note that for custom extensions or not directly supported extensions you also
# need to set EXTENSION_MAPPING for the extension otherwise the files are not
# properly processed by doxygen.
FILTER_PATTERNS = *.cmake=@CMakeDoxygenFilter_EXECUTABLE@
# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER) will also be used to filter the input files that are used for
# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
# The default value is: NO.
FILTER_SOURCE_FILES = NO
# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
# it is also possible to disable source filtering for a specific pattern using
# *.ext= (so without naming a filter).
# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
FILTER_SOURCE_PATTERNS =
# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
# is part of the input, its contents will be placed on the main page
# (index.html). This can be useful if you have a project on for instance GitHub
# and want to reuse the introduction page also for the doxygen output.
USE_MDFILE_AS_MAINPAGE =
# The Fortran standard specifies that for fixed formatted Fortran code all
# characters from position 72 are to be considered as comment. A common
# extension is to allow longer lines before the automatic comment starts. The
# setting FORTRAN_COMMENT_AFTER will also make it possible that longer lines can
# be processed before the automatic comment starts.
# Minimum value: 7, maximum value: 10000, default value: 72.
FORTRAN_COMMENT_AFTER = 72
#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------
# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
# generated. Documented entities will be cross-referenced with these sources.
#
# Note: To get rid of all source code in the generated output, make sure that
# also VERBATIM_HEADERS is set to NO.
# The default value is: NO.
SOURCE_BROWSER = YES
# Setting the INLINE_SOURCES tag to YES will include the body of functions,
# classes and enums directly into the documentation.
# The default value is: NO.
INLINE_SOURCES = NO
# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
# special comment blocks from generated source code fragments. Normal C, C++ and
# Fortran comments will always remain visible.
# The default value is: YES.
STRIP_CODE_COMMENTS = YES
# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
# entity all documented functions referencing it will be listed.
# The default value is: NO.
REFERENCED_BY_RELATION = YES
# If the REFERENCES_RELATION tag is set to YES then for each documented function
# all documented entities called/used by that function will be listed.
# The default value is: NO.
REFERENCES_RELATION = YES
# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
# to YES then the hyperlinks from functions in REFERENCES_RELATION and
# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
# link to the documentation.
# The default value is: YES.
REFERENCES_LINK_SOURCE = YES
# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
# source code will show a tooltip with additional information such as prototype,
# brief description and links to the definition and documentation. Since this
# will make the HTML file larger and loading of large files a bit slower, you
# can opt to disable this feature.
# The default value is: YES.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
SOURCE_TOOLTIPS = YES
# If the USE_HTAGS tag is set to YES then the references to source code will
# point to the HTML generated by the htags(1) tool instead of doxygen built-in
# source browser. The htags tool is part of GNU's global source tagging system
# (see https://www.gnu.org/software/global/global.html). You will need version
# 4.8.6 or higher.
#
# To use it do the following:
# - Install the latest version of global
# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file
# - Make sure the INPUT points to the root of the source tree
# - Run doxygen as normal
#
# Doxygen will invoke htags (and that will in turn invoke gtags), so these
# tools must be available from the command line (i.e. in the search path).
#
# The result: instead of the source browser generated by doxygen, the links to
# source code will now point to the output of htags.
# The default value is: NO.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
USE_HTAGS = NO
# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
# verbatim copy of the header file for each class for which an include is
# specified. Set to NO to disable this.
# See also: Section \class.
# The default value is: YES.
VERBATIM_HEADERS = YES
# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
# clang parser (see:
# http://clang.llvm.org/) for more accurate parsing at the cost of reduced
# performance. This can be particularly helpful with template rich C++ code for
# which doxygen's built-in parser lacks the necessary type information.
# Note: The availability of this option depends on whether or not doxygen was
# generated with the -Duse_libclang=ON option for CMake.
# The default value is: NO.
CLANG_ASSISTED_PARSING = NO
# If the CLANG_ASSISTED_PARSING tag is set to YES and the CLANG_ADD_INC_PATHS
# tag is set to YES then doxygen will add the directory of each input to the
# include path.
# The default value is: YES.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
CLANG_ADD_INC_PATHS = YES
# If clang assisted parsing is enabled you can provide the compiler with command
# line options that you would normally use when invoking the compiler. Note that
# the include paths will already be set by doxygen for the files and directories
# specified with INPUT and INCLUDE_PATH.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
CLANG_OPTIONS =
# If clang assisted parsing is enabled you can provide the clang parser with the
# path to the directory containing a file called compile_commands.json. This
# file is the compilation database (see:
# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the
# options used when the source files were built. This is equivalent to
# specifying the -p option to a clang tool, such as clang-check. These options
# will then be passed to the parser. Any options specified with CLANG_OPTIONS
# will be added as well.
# Note: The availability of this option depends on whether or not doxygen was
# generated with the -Duse_libclang=ON option for CMake.
CLANG_DATABASE_PATH =
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
# compounds will be generated. Enable this if the project contains a lot of
# classes, structs, unions or interfaces.
# The default value is: YES.
ALPHABETICAL_INDEX = YES
# The IGNORE_PREFIX tag can be used to specify a prefix (or a list of prefixes)
# that should be ignored while generating the index headers. The IGNORE_PREFIX
# tag works for classes, function and member names. The entity will be placed in
# the alphabetical list under the first letter of the entity name that remains
# after removing the prefix.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
# The default value is: YES.
GENERATE_HTML = NO
# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_OUTPUT = html
# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
# generated HTML page (for example: .htm, .php, .asp).
# The default value is: .html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FILE_EXTENSION = .html
# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
# each generated HTML page. If the tag is left blank doxygen will generate a
# standard header.
#
# To get valid HTML the header file that includes any scripts and style sheets
# that doxygen needs, which is dependent on the configuration options used (e.g.
# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
# default header using
# doxygen -w html new_header.html new_footer.html new_stylesheet.css
# YourConfigFile
# and then modify the file new_header.html. See also section "Doxygen usage"
# for information on how to generate the default header that doxygen normally
# uses.
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. For a description
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_HEADER =
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
# footer. See HTML_HEADER for more information on how to generate a default
# footer and what special commands can be used inside the footer. See also
# section "Doxygen usage" for information on how to generate the default footer
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FOOTER =
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
# the HTML output. If left blank doxygen will generate a default style sheet.
# See also section "Doxygen usage" for information on how to generate the style
# sheet that doxygen normally uses.
# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
# it is more robust and this tag (HTML_STYLESHEET) will in the future become
# obsolete.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_STYLESHEET =
# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# cascading style sheets that are included after the standard style sheets
# created by doxygen. Using this option one can overrule certain style aspects.
# This is preferred over using HTML_STYLESHEET since it does not replace the
# standard style sheet and is therefore more robust against future updates.
# Doxygen will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list).
# Note: Since the styling of scrollbars can currently not be overruled in
# Webkit/Chromium, the styling will be left out of the default doxygen.css if
# one or more extra stylesheets have been specified. So if scrollbar
# customization is desired it has to be added explicitly. For an example see the
# documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET = @MITK_DOXYGEN_STYLESHEET@
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
# that these files will be copied to the base HTML output directory. Use the
# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_FILES =
# The HTML_COLORSTYLE tag can be used to specify if the generated HTML output
# should be rendered with a dark or light theme.
# Possible values are: LIGHT always generate light mode output, DARK always
# generate dark mode output, AUTO_LIGHT automatically set the mode according to
# the user preference, use light mode if no preference is set (the default),
# AUTO_DARK automatically set the mode according to the user preference, use
# dark mode if no preference is set and TOGGLE allow to user to switch between
# light and dark mode via a button.
# The default value is: AUTO_LIGHT.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE = AUTO_LIGHT
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the style sheet and background images according to
# this color. Hue is specified as an angle on a color-wheel, see
# https://en.wikipedia.org/wiki/Hue for more information. For instance the value
# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
# purple, and 360 is red again.
# Minimum value: 0, maximum value: 359, default value: 220.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_HUE = 220
# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
# in the HTML output. For a value of 0 the output will use gray-scales only. A
# value of 255 will produce the most vivid colors.
# Minimum value: 0, maximum value: 255, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_SAT = 100
# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
# luminance component of the colors in the HTML output. Values below 100
# gradually make the output lighter, whereas values above 100 make the output
# darker. The value divided by 100 is the actual gamma applied, so 80 represents
# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
# change the gamma.
# Minimum value: 40, maximum value: 240, default value: 80.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting this
# to YES can help to show when doxygen was last run and thus if the
# documentation is up to date.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_TIMESTAMP = YES
# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML
# documentation will contain a main index with vertical navigation menus that
# are dynamically created via JavaScript. If disabled, the navigation index will
# consists of multiple levels of tabs that are statically embedded in every HTML
# page. Disable this option to support browsers that do not have JavaScript,
# like the Qt help browser.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_MENUS = YES
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_SECTIONS = @MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS@
# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
# shown in the various tree structured indices initially; the user can expand
# and collapse entries dynamically later on. Doxygen will expand the tree to
# such a level that at most the specified number of entries are visible (unless
# a fully collapsed tree already exceeds this amount). So setting the number of
# entries 1 will produce a full collapsed tree by default. 0 is a special value
# representing an infinite number of entries and will result in a full expanded
# tree by default.
# Minimum value: 0, maximum value: 9999, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_INDEX_NUM_ENTRIES = 100
# If the GENERATE_DOCSET tag is set to YES, additional index files will be
# generated that can be used as input for Apple's Xcode 3 integrated development
# environment (see:
# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To
# create a documentation set, doxygen will generate a Makefile in the HTML
# output directory. Running make will produce the docset in that directory and
# running make install will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy
# genXcode/_index.html for more information.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_DOCSET = NO
# This tag determines the name of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# The default value is: Doxygen generated docs.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDNAME = "Doxygen generated docs"
# This tag determines the URL of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDURL =
# This tag specifies a string that should uniquely identify the documentation
# set bundle. This should be a reverse domain-name style string, e.g.
# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_BUNDLE_ID = org.doxygen.Project
# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
# The default value is: org.doxygen.Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
# The default value is: Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_NAME = Publisher
# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
# on Windows. In the beginning of 2021 Microsoft took the original page, with
# a.o. the download links, offline the HTML help workshop was already many years
# in maintenance mode). You can download the HTML help workshop from the web
# archives at Installation executable (see:
# http://web.archive.org/web/20160201063255/http://download.microsoft.com/downlo
# ad/0/A/9/0A939EF6-E31C-430F-A3DF-DFAE7960D564/htmlhelp.exe).
#
# The HTML Help Workshop contains a compiler that can convert all HTML output
# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
# files are now used as the Windows 98 help format, and will replace the old
# Windows help format (.hlp) on all Windows platforms in the future. Compressed
# HTML files also contain an index, a table of contents, and you can search for
# words in the documentation. The HTML workshop also contains a viewer for
# compressed HTML files.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_HTMLHELP = NO
# The CHM_FILE tag can be used to specify the file name of the resulting .chm
# file. You can add a path in front of the file if the result should not be
# written to the html output directory.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_FILE =
# The HHC_LOCATION tag can be used to specify the location (absolute path
# including file name) of the HTML help compiler (hhc.exe). If non-empty,
# doxygen will try to run the HTML help compiler on the generated index.hhp.
# The file has to be specified with full path.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
HHC_LOCATION =
# The GENERATE_CHI flag controls if a separate .chi index file is generated
# (YES) or that it should be included in the main .chm file (NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
GENERATE_CHI = NO
# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
# and project file content.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_INDEX_ENCODING =
# The BINARY_TOC flag controls whether a binary table of contents is generated
# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
# enables the Previous and Next buttons.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
BINARY_TOC = NO
# The TOC_EXPAND flag can be set to YES to add extra items for group members to
# the table of contents of the HTML help documentation and to the tree view.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
TOC_EXPAND = NO
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
# (.qch) of the generated HTML documentation.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_QHP = @MITK_DOXYGEN_GENERATE_QHP@
# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
# the file name of the resulting .qch file. The path specified is relative to
# the HTML output folder.
# This tag requires that the tag GENERATE_QHP is set to YES.
QCH_FILE = @MITK_DOXYGEN_QCH_FILE@
# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
# Project output. For more information please see Qt Help Project / Namespace
# (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_NAMESPACE = org.mitk
# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
# Help Project output. For more information please see Qt Help Project / Virtual
# Folders (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).
# The default value is: doc.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_VIRTUAL_FOLDER = MITK
# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
# filter to add. For more information please see Qt Help Project / Custom
# Filters (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_NAME =
# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
# custom filter to add. For more information please see Qt Help Project / Custom
# Filters (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_ATTRS =
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see:
# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_SECT_FILTER_ATTRS =
# The QHG_LOCATION tag can be used to specify the location (absolute path
# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to
# run qhelpgenerator on the generated .qhp file.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHG_LOCATION = @QT_HELPGENERATOR_EXECUTABLE@
# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
# generated, together with the HTML files, they form an Eclipse help plugin. To
# install this plugin and make it available under the help contents menu in
# Eclipse, the contents of the directory containing the HTML and XML files needs
# to be copied into the plugins directory of eclipse. The name of the directory
# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
# After copying Eclipse needs to be restarted before the help appears.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_ECLIPSEHELP = NO
# A unique identifier for the Eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have this
# name. Each documentation set should have its own identifier.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
ECLIPSE_DOC_ID = org.doxygen.Project
# If you want full control over the layout of the generated HTML pages it might
# be necessary to disable the index and replace it with your own. The
# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
# of each HTML page. A value of NO enables the index and the value YES disables
# it. Since the tabs in the index contain the same information as the navigation
# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
DISABLE_INDEX = NO
# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information. If the tag
# value is set to YES, a side panel will be generated containing a tree-like
# index structure (just like the one that is generated for HTML Help). For this
# to work a browser that supports JavaScript, DHTML, CSS and frames is required
# (i.e. any modern browser). Windows users are probably better off using the
# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
# further fine tune the look of the index (see "Fine-tuning the output"). As an
# example, the default style sheet generated by doxygen has an example that
# shows how to put an image at the root of the tree instead of the PROJECT_NAME.
# Since the tree basically has the same information as the tab index, you could
# consider setting DISABLE_INDEX to YES when enabling this option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_TREEVIEW = YES
# When both GENERATE_TREEVIEW and DISABLE_INDEX are set to YES, then the
# FULL_SIDEBAR option determines if the side bar is limited to only the treeview
# area (value NO) or if it should extend to the full height of the window (value
# YES). Setting this to YES gives a layout similar to
# https://docs.readthedocs.io with more room for contents, but less room for the
# project logo, title, and description. If either GENERATE_TREEVIEW or
# DISABLE_INDEX is set to NO, this option has no effect.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
FULL_SIDEBAR = NO
# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
# doxygen will group on one line in the generated HTML documentation.
#
# Note that a value of 0 will completely suppress the enum values from appearing
# in the overview section.
# Minimum value: 0, maximum value: 20, default value: 4.
# This tag requires that the tag GENERATE_HTML is set to YES.
ENUM_VALUES_PER_LINE = 4
# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
# to set the initial width (in pixels) of the frame in which the tree is shown.
# Minimum value: 0, maximum value: 1500, default value: 250.
# This tag requires that the tag GENERATE_HTML is set to YES.
TREEVIEW_WIDTH = 300
# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
# external symbols imported via tag files in a separate window.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
EXT_LINKS_IN_WINDOW = NO
# If the OBFUSCATE_EMAILS tag is set to YES, doxygen will obfuscate email
# addresses.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
OBFUSCATE_EMAILS = YES
# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg
# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see
# https://inkscape.org) to generate formulas as SVG images instead of PNGs for
# the HTML output. These images will generally look nicer at scaled resolutions.
# Possible values are: png (the default) and svg (looks nicer but requires the
# pdf2svg or inkscape tool).
# The default value is: png.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FORMULA_FORMAT = png
# Use this tag to change the font size of LaTeX formulas included as images in
# the HTML documentation. When you change the font size after a successful
# doxygen run you need to manually remove any form_*.png images from the HTML
# output directory to force them to be regenerated.
# Minimum value: 8, maximum value: 50, default value: 10.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_FONTSIZE = 10
# The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands
# to create new LaTeX commands to be used in formulas as building blocks. See
# the section "Including formulas" for details.
FORMULA_MACROFILE =
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
# https://www.mathjax.org) which uses client side JavaScript for the rendering
# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
# installed or if you want to formulas look prettier in the HTML output. When
# enabled you may also need to install MathJax separately and configure the path
# to it using the MATHJAX_RELPATH option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
USE_MATHJAX = NO
# With MATHJAX_VERSION it is possible to specify the MathJax version to be used.
# Note that the different versions of MathJax have different requirements with
# regards to the different settings, so it is possible that also other MathJax
# settings have to be changed when switching between the different MathJax
# versions.
# Possible values are: MathJax_2 and MathJax_3.
# The default value is: MathJax_2.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_VERSION = MathJax_2
# When MathJax is enabled you can set the default output format to be used for
# the MathJax output. For more details about the output format see MathJax
# version 2 (see:
# http://docs.mathjax.org/en/v2.7-latest/output.html) and MathJax version 3
# (see:
# http://docs.mathjax.org/en/latest/web/components/output.html).
# Possible values are: HTML-CSS (which is slower, but has the best
# compatibility. This is the name for Mathjax version 2, for MathJax version 3
# this will be translated into chtml), NativeMML (i.e. MathML. Only supported
# for NathJax 2. For MathJax version 3 chtml will be used instead.), chtml (This
# is the name for Mathjax version 3, for MathJax version 2 this will be
# translated into HTML-CSS) and SVG.
# The default value is: HTML-CSS.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_FORMAT = HTML-CSS
# When MathJax is enabled you need to specify the location relative to the HTML
# output directory using the MATHJAX_RELPATH option. The destination directory
# should contain the MathJax.js script. For instance, if the mathjax directory
# is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
# Content Delivery Network so you can quickly see the result without installing
# MathJax. However, it is strongly recommended to install a local copy of
# MathJax from https://www.mathjax.org before deployment. The default value is:
# - in case of MathJax version 2: https://cdn.jsdelivr.net/npm/mathjax@2
# - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_RELPATH = http://www.mathjax.org/mathjax
# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example
# for MathJax version 2 (see
# https://docs.mathjax.org/en/v2.7-latest/tex.html#tex-and-latex-extensions):
# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
# For example for MathJax version 3 (see
# http://docs.mathjax.org/en/latest/input/tex/extensions/index.html):
# MATHJAX_EXTENSIONS = ams
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_EXTENSIONS =
# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
# of code that will be used on startup of the MathJax code. See the MathJax site
# (see:
# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an
# example see the documentation.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_CODEFILE =
# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
# the HTML output. The underlying search engine uses javascript and DHTML and
# should work on any modern browser. Note that when using HTML help
# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
# there is already a search function so this one should typically be disabled.
# For large projects the javascript based search engine can be slow, then
# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
# search using the keyboard; to jump to the search box use <access key> + S
# (what the <access key> is depends on the OS and browser, but it is typically
# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
# key> to jump into the search results window, the results can be navigated
# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
# the search. The filter options can be selected when the cursor is inside the
# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
# to select a filter and <Enter> or <escape> to activate or cancel the filter
# option.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
SEARCHENGINE = YES
# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
# implemented using a web server instead of a web client using JavaScript. There
# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
# setting. When disabled, doxygen will generate a PHP script for searching and
# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
# and searching needs to be provided by external tools. See the section
# "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
SERVER_BASED_SEARCH = NO
# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
# script for searching. Instead the search results are written to an XML file
# which needs to be processed by an external indexer. Doxygen will invoke an
# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
# search results.
#
# Doxygen ships with an example indexer (doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see:
# https://xapian.org/).
#
# See the section "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH = NO
# The SEARCHENGINE_URL should point to a search engine hosted by a web server
# which will return the search results when EXTERNAL_SEARCH is enabled.
#
# Doxygen ships with an example indexer (doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see:
# https://xapian.org/). See the section "External Indexing and Searching" for
# details.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHENGINE_URL =
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
# search data is written to a file for indexing by an external tool. With the
# SEARCHDATA_FILE tag the name of this file can be specified.
# The default file is: searchdata.xml.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHDATA_FILE = searchdata.xml
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
# projects and redirect the results back to the right project.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH_ID =
# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
# projects other than the one defined by this configuration file, but that are
# all added to the same external search index. Each project needs to have a
# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
# to a relative location where the documentation can be found. The format is:
# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
# The default value is: YES.
GENERATE_LATEX = YES
# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_OUTPUT = latex
# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
# invoked.
#
# Note that when not enabling USE_PDFLATEX the default is latex when enabling
# USE_PDFLATEX the default is pdflatex and when in the later case latex is
# chosen this is overwritten by pdflatex. For specific output languages the
# default can have been set differently, this depends on the implementation of
# the output language.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_CMD_NAME = latex
# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
# index for LaTeX.
# Note: This tag is used in the Makefile / make.bat.
# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file
# (.tex).
# The default file is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
MAKEINDEX_CMD_NAME = makeindex
# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to
# generate index for LaTeX. In case there is no backslash (\) as first character
# it will be automatically added in the LaTeX code.
# Note: This tag is used in the generated output file (.tex).
# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.
# The default value is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_MAKEINDEX_CMD = makeindex
# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
COMPACT_LATEX = NO
# The PAPER_TYPE tag can be used to set the paper type that is used by the
# printer.
# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
# 14 inches) and executive (7.25 x 10.5 inches).
# The default value is: a4.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PAPER_TYPE = a4
# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
# that should be included in the LaTeX output. The package can be specified just
# by its name or with the correct syntax as to be used with the LaTeX
# \usepackage command. To get the times font for instance you can specify :
# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
# To use the option intlimits with the amsmath package you can specify:
# EXTRA_PACKAGES=[intlimits]{amsmath}
# If left blank no extra packages will be included.
# This tag requires that the tag GENERATE_LATEX is set to YES.
EXTRA_PACKAGES = amssymb
# The LATEX_HEADER tag can be used to specify a user-defined LaTeX header for
# the generated LaTeX document. The header should contain everything until the
# first chapter. If it is left blank doxygen will generate a standard header. It
# is highly recommended to start with a default header using
# doxygen -w latex new_header.tex new_footer.tex new_stylesheet.sty
# and then modify the file new_header.tex. See also section "Doxygen usage" for
# information on how to generate the default header that doxygen normally uses.
#
# Note: Only use a user-defined header if you know what you are doing!
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. The following
# commands have a special meaning inside the header (and footer): For a
# description of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HEADER =
# The LATEX_FOOTER tag can be used to specify a user-defined LaTeX footer for
# the generated LaTeX document. The footer should contain everything after the
# last chapter. If it is left blank doxygen will generate a standard footer. See
# LATEX_HEADER for more information on how to generate a default footer and what
# special commands can be used inside the footer. See also section "Doxygen
# usage" for information on how to generate the default footer that doxygen
# normally uses. Note: Only use a user-defined footer if you know what you are
# doing!
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_FOOTER =
# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
# LaTeX style sheets that are included after the standard style sheets created
# by doxygen. Using this option one can overrule certain style aspects. Doxygen
# will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list).
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EXTRA_STYLESHEET =
# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the LATEX_OUTPUT output
# directory. Note that the files will be copied as-is; there are no commands or
# markers available.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EXTRA_FILES =
# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
# contain links (just like the HTML output) instead of page references. This
# makes the output suitable for online browsing using a PDF viewer.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PDF_HYPERLINKS = YES
# If the USE_PDFLATEX tag is set to YES, doxygen will use the engine as
# specified with LATEX_CMD_NAME to generate the PDF file directly from the LaTeX
# files. Set this option to YES, to get a higher quality PDF documentation.
#
# See also section LATEX_CMD_NAME for selecting the engine.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
USE_PDFLATEX = YES
# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
# command to the generated LaTeX files. This will instruct LaTeX to keep running
# if errors occur, instead of asking the user for help.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BATCHMODE = YES
# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
# index chapters (such as File Index, Compound Index, etc.) in the output.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HIDE_INDICES = NO
# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
# bibliography, e.g. plainnat, or ieeetr. See
# https://en.wikipedia.org/wiki/BibTeX and \cite for more info.
# The default value is: plain.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BIB_STYLE = plain
# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
# page will contain the date and time when the page was generated. Setting this
# to NO can help when comparing the output of multiple runs.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_TIMESTAMP = NO
# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)
# path from which the emoji images will be read. If a relative path is entered,
# it will be relative to the LATEX_OUTPUT directory. If left blank the
# LATEX_OUTPUT directory will be used.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EMOJI_DIRECTORY =
#---------------------------------------------------------------------------
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
# RTF output is optimized for Word 97 and may not look too pretty with other RTF
# readers/editors.
# The default value is: NO.
GENERATE_RTF = NO
# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: rtf.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_OUTPUT = rtf
# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
COMPACT_RTF = NO
# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
# contain hyperlink fields. The RTF file will contain links (just like the HTML
# output) instead of page references. This makes the output suitable for online
# browsing using Word or some other Word compatible readers that support those
# fields.
#
# Note: WordPad (write) and others do not support links.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_HYPERLINKS = NO
# Load stylesheet definitions from file. Syntax is similar to doxygen's
# configuration file, i.e. a series of assignments. You only have to provide
# replacements, missing definitions are set to their default value.
#
# See also section "Doxygen usage" for information on how to generate the
# default style sheet that doxygen normally uses.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_STYLESHEET_FILE =
# Set optional variables used in the generation of an RTF document. Syntax is
# similar to doxygen's configuration file. A template extensions file can be
# generated using doxygen -e rtf extensionFile.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# Configuration options related to the man page output
#---------------------------------------------------------------------------
# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
# classes and files.
# The default value is: NO.
GENERATE_MAN = NO
# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it. A directory man3 will be created inside the directory specified by
# MAN_OUTPUT.
# The default directory is: man.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_OUTPUT = man
# The MAN_EXTENSION tag determines the extension that is added to the generated
# man pages. In case the manual section does not start with a number, the number
# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
# optional.
# The default value is: .3.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_EXTENSION = .3
# The MAN_SUBDIR tag determines the name of the directory created within
# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
# MAN_EXTENSION with the initial . removed.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_SUBDIR =
# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
# will generate one additional man file for each entity documented in the real
# man page(s). These additional files only source the real man page, but without
# them the man command would be unable to find the correct page.
# The default value is: NO.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_LINKS = NO
#---------------------------------------------------------------------------
# Configuration options related to the XML output
#---------------------------------------------------------------------------
# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
# captures the structure of the code including all documentation.
# The default value is: NO.
GENERATE_XML = NO
# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: xml.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_OUTPUT = xml
# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
# listings (including syntax highlighting and cross-referencing information) to
# the XML output. Note that enabling this will significantly increase the size
# of the XML output.
# The default value is: YES.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_PROGRAMLISTING = YES
# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include
# namespace members in file scope as well, matching the HTML output.
# The default value is: NO.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_NS_MEMB_FILE_SCOPE = NO
#---------------------------------------------------------------------------
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
# that can be used to generate PDF.
# The default value is: NO.
GENERATE_DOCBOOK = NO
# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
# front of it.
# The default directory is: docbook.
# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
DOCBOOK_OUTPUT = docbook
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures
# the structure of the code including all documentation. Note that this feature
# is still experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
# file that captures the structure of the code including all documentation.
#
# Note that this feature is still experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_PERLMOD = NO
# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
# output from the Perl module output.
# The default value is: NO.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_LATEX = NO
# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
# formatted so it can be parsed by a human reader. This is useful if you want to
# understand what is going on. On the other hand, if this tag is set to NO, the
# size of the Perl module output will be much smaller and Perl will parse it
# just the same.
# The default value is: YES.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_PRETTY = YES
# The names of the make variables in the generated doxyrules.make file are
# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
# so different doxyrules.make files included by the same Makefile don't
# overwrite each other's variables.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
# C-preprocessor directives found in the sources and include files.
# The default value is: YES.
ENABLE_PREPROCESSING = YES
# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
# in the source code. If set to NO, only conditional compilation will be
# performed. Macro expansion can be done in a controlled way by setting
# EXPAND_ONLY_PREDEF to YES.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
MACRO_EXPANSION = YES
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
# the macro expansion is limited to the macros specified with the PREDEFINED and
# EXPAND_AS_DEFINED tags.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_ONLY_PREDEF = NO
# If the SEARCH_INCLUDES tag is set to YES, the include files in the
# INCLUDE_PATH will be searched if a #include is found.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SEARCH_INCLUDES = YES
# The INCLUDE_PATH tag can be used to specify one or more directories that
# contain include files that are not input files but should be processed by the
# preprocessor. Note that the INCLUDE_PATH is not recursive, so the setting of
# RECURSIVE has no effect here.
# This tag requires that the tag SEARCH_INCLUDES is set to YES.
INCLUDE_PATH =
# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
# patterns (like *.h and *.hpp) to filter out the header-files in the
# directories. If left blank, the patterns specified with FILE_PATTERNS will be
# used.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
INCLUDE_FILE_PATTERNS =
# The PREDEFINED tag can be used to specify one or more macro names that are
# defined before the preprocessor is started (similar to the -D option of e.g.
# gcc). The argument of the tag is a list of macros of the form: name or
# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
# is assumed. To prevent a macro definition from being undefined via #undef or
# recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
PREDEFINED =
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The
# macro definition that is found in the sources will be used. Use the PREDEFINED
# tag if you want to use a different macro definition that overrules the
# definition found in the source code.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_AS_DEFINED =
# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
# remove all references to function-like macros that are alone on a line, have
# an all uppercase name, and do not end with a semicolon. Such function macros
# are typically used for boiler-plate code, and will confuse the parser if not
# removed.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration options related to external references
#---------------------------------------------------------------------------
# The TAGFILES tag can be used to specify one or more tag files. For each tag
# file the location of the external documentation should be added. The format of
# a tag file without this location is as follows:
# TAGFILES = file1 file2 ...
# Adding location for the tag files is done as follows:
# TAGFILES = file1=loc1 "file2 = loc2" ...
# where loc1 and loc2 can be relative or absolute paths or URLs. See the
# section "Linking to external documentation" for more information about the use
# of tag files.
# Note: Each tag file must have a unique name (where the name does NOT include
# the path). If a tag file is not located in the directory in which doxygen is
# run, you must also specify the path to the tagfile here.
TAGFILES = @BLUEBERRY_DOXYGEN_TAGFILE@
# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
# tag file that is based on the input files it reads. See section "Linking to
# external documentation" for more information about the usage of tag files.
GENERATE_TAGFILE = @MITK_DOXYGEN_TAGFILE_NAME@
# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
# the class index. If set to NO, only the inherited external classes will be
# listed.
# The default value is: NO.
ALLEXTERNALS = NO
# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
# in the modules index. If set to NO, only the current project's groups will be
# listed.
# The default value is: YES.
EXTERNAL_GROUPS = NO
# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
# the related pages index. If set to NO, only the current project's pages will
# be listed.
# The default value is: YES.
EXTERNAL_PAGES = YES
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
# You can include diagrams made with dia in doxygen documentation. Doxygen will
# then run dia to produce the diagram and insert it in the documentation. The
# DIA_PATH tag allows you to specify the directory where the dia binary resides.
# If left empty dia is assumed to be found in the default search path.
DIA_PATH =
# If set to YES the inheritance and collaboration graphs will hide inheritance
# and usage relations if the target is undocumented or is not a class.
# The default value is: YES.
HIDE_UNDOC_RELATIONS = YES
# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz (see:
# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# Bell Labs. The other options in this section have no effect if this option is
# set to NO
# The default value is: NO.
HAVE_DOT = @HAVE_DOT@
# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
# to run in parallel. When set to 0 doxygen will base this on the number of
# processors available in the system. You can set it explicitly to a value
# larger than 0 to get control over the balance between CPU load and processing
# speed.
# Minimum value: 0, maximum value: 32, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_NUM_THREADS = @MITK_DOXYGEN_DOT_NUM_THREADS@
# DOT_COMMON_ATTR is common attributes for nodes, edges and labels of
# subgraphs. When you want a differently looking font in the dot files that
# doxygen generates you can specify fontname, fontcolor and fontsize attributes.
# For details please see <a href=https://graphviz.org/doc/info/attrs.html>Node,
# Edge and Graph Attributes specification</a> You need to make sure dot is able
# to find the font, which can be done by putting it in a standard location or by
# setting the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
# directory containing the font. Default graphviz fontsize is 14.
# The default value is: fontname=Helvetica,fontsize=10.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_COMMON_ATTR = "fontname=Helvetica,fontsize=10"
# DOT_EDGE_ATTR is concatenated with DOT_COMMON_ATTR. For elegant style you can
# add 'arrowhead=open, arrowtail=open, arrowsize=0.5'. <a
# href=https://graphviz.org/doc/info/arrows.html>Complete documentation about
# arrows shapes.</a>
# The default value is: labelfontname=Helvetica,labelfontsize=10.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_EDGE_ATTR = "labelfontname=Helvetica,labelfontsize=10"
# DOT_NODE_ATTR is concatenated with DOT_COMMON_ATTR. For view without boxes
# around nodes set 'shape=plain' or 'shape=plaintext' <a
# href=https://www.graphviz.org/doc/info/shapes.html>Shapes specification</a>
# The default value is: shape=box,height=0.2,width=0.4.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_NODE_ATTR = "shape=box,height=0.2,width=0.4"
# You can set the path where dot can find font specified with fontname in
# DOT_COMMON_ATTR and others dot attributes.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTPATH =
# If the CLASS_GRAPH tag is set to YES (or GRAPH) then doxygen will generate a
# graph for each documented class showing the direct and indirect inheritance
# relations. In case HAVE_DOT is set as well dot will be used to draw the graph,
# otherwise the built-in generator will be used. If the CLASS_GRAPH tag is set
# to TEXT the direct and indirect inheritance relations will be shown as texts /
# links.
# Possible values are: NO, YES, TEXT and GRAPH.
# The default value is: YES.
CLASS_GRAPH = YES
# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
# graph for each documented class showing the direct and indirect implementation
# dependencies (inheritance, containment, and class references variables) of the
# class with other documented classes.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
COLLABORATION_GRAPH = YES
# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
# groups, showing the direct groups dependencies. See also the chapter Grouping
# in the manual.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GROUP_GRAPHS = YES
# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
# collaboration diagrams in a style similar to the OMG's Unified Modeling
# Language.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
UML_LOOK = @MITK_DOXYGEN_UML_LOOK@
# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
# class node. If there are many fields or methods and many nodes the graph may
# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
# number of items for each type to make the size more manageable. Set this to 0
# for no limit. Note that the threshold may be exceeded by 50% before the limit
# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
# but if the number exceeds 15, the total amount of fields shown is limited to
# 10.
# Minimum value: 0, maximum value: 100, default value: 10.
# This tag requires that the tag UML_LOOK is set to YES.
UML_LIMIT_NUM_FIELDS = 10
# If the DOT_UML_DETAILS tag is set to NO, doxygen will show attributes and
# methods without types and arguments in the UML graphs. If the DOT_UML_DETAILS
# tag is set to YES, doxygen will add type and arguments for attributes and
# methods in the UML graphs. If the DOT_UML_DETAILS tag is set to NONE, doxygen
# will not generate fields with class member information in the UML graphs. The
# class diagrams will look similar to the default class diagrams but using UML
# notation for the relationships.
# Possible values are: NO, YES and NONE.
# The default value is: NO.
# This tag requires that the tag UML_LOOK is set to YES.
DOT_UML_DETAILS = NO
# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters
# to display on a single line. If the actual line length exceeds this threshold
# significantly it will wrapped across multiple lines. Some heuristics are apply
# to avoid ugly line breaks.
# Minimum value: 0, maximum value: 1000, default value: 17.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_WRAP_THRESHOLD = 17
# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
# collaboration graphs will show the relations between templates and their
# instances.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
TEMPLATE_RELATIONS = YES
# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
# YES then doxygen will generate a graph for each documented file showing the
# direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDE_GRAPH = NO
# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
# set to YES then doxygen will generate a graph for each documented file showing
# the direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDED_BY_GRAPH = NO
# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable call graphs for selected
# functions only using the \callgraph command. Disabling a call graph can be
# accomplished by means of the command \hidecallgraph.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALL_GRAPH = NO
# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable caller graphs for selected
# functions only using the \callergraph command. Disabling a caller graph can be
# accomplished by means of the command \hidecallergraph.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALLER_GRAPH = NO
# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
# hierarchy of all classes instead of a textual one.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GRAPHICAL_HIERARCHY = NO
# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
# dependencies a directory has on other directories in a graphical way. The
# dependency relations are determined by the #include relations between the
# files in the directories.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
DIRECTORY_GRAPH = YES
# The DIR_GRAPH_MAX_DEPTH tag can be used to limit the maximum number of levels
# of child directories generated in directory dependency graphs by dot.
# Minimum value: 1, maximum value: 25, default value: 1.
# This tag requires that the tag DIRECTORY_GRAPH is set to YES.
DIR_GRAPH_MAX_DEPTH = 1
# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
# generated by dot. For an explanation of the image formats see the section
# output formats in the documentation of the dot tool (Graphviz (see:
# http://www.graphviz.org/)).
# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
# to make the SVG files visible in IE 9+ (other browsers do not have this
# requirement).
# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,
# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
# png:gdiplus:gdiplus.
# The default value is: png.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_IMAGE_FORMAT = png
# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
# enable generation of interactive SVG images that allow zooming and panning.
#
# Note that this requires a modern browser other than Internet Explorer. Tested
# and working are Firefox, Chrome, Safari, and Opera.
# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
# the SVG files visible. Older versions of IE do not have SVG support.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
INTERACTIVE_SVG = NO
# The DOT_PATH tag can be used to specify the path where the dot tool can be
# found. If left blank, it is assumed the dot tool can be found in the path.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_PATH = @DOXYGEN_DOT_PATH@
# The DOTFILE_DIRS tag can be used to specify one or more directories that
# contain dot files that are included in the documentation (see the \dotfile
# command).
# This tag requires that the tag HAVE_DOT is set to YES.
DOTFILE_DIRS =
# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the \mscfile
# command).
MSCFILE_DIRS =
# The DIAFILE_DIRS tag can be used to specify one or more directories that
# contain dia files that are included in the documentation (see the \diafile
# command).
DIAFILE_DIRS =
# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
# path where java can find the plantuml.jar file or to the filename of jar file
# to be used. If left blank, it is assumed PlantUML is not used or called during
# a preprocessing step. Doxygen will generate a warning when it encounters a
# \startuml command in this case and will not generate output for the diagram.
PLANTUML_JAR_PATH =
# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
# configuration file for plantuml.
PLANTUML_CFG_FILE =
# When using plantuml, the specified paths are searched for files specified by
# the !include statement in a plantuml block.
PLANTUML_INCLUDE_PATH =
# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
# that will be shown in the graph. If the number of nodes in a graph becomes
# larger than this value, doxygen will truncate the graph, which is visualized
# by representing a node as a red box. Note that doxygen if the number of direct
# children of the root node in a graph is already larger than
# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
# Minimum value: 0, maximum value: 10000, default value: 50.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_GRAPH_MAX_NODES = 50
# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
# generated by dot. A depth value of 3 means that only nodes reachable from the
# root by following a path via at most 3 edges will be shown. Nodes that lay
# further from the root node will be omitted. Note that setting this option to 1
# or 2 may greatly reduce the computation time needed for large code bases. Also
# note that the size of a graph can be further restricted by
# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
# Minimum value: 0, maximum value: 1000, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
MAX_DOT_GRAPH_DEPTH = 0
# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
# files in one run (i.e. multiple -o and -T options on the command line). This
# makes dot run faster, but since only newer versions of dot (>1.8.10) support
# this, this feature is disabled by default.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_MULTI_TARGETS = NO
# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
# explaining the meaning of the various boxes and arrows in the dot generated
# graphs.
# Note: This tag requires that UML_LOOK isn't set, i.e. the doxygen internal
# graphical representation for inheritance and collaboration diagrams is used.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GENERATE_LEGEND = YES
# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate
# files that are used to generate the various graphs.
#
# Note: This setting is not only used for dot files but also for msc temporary
# files.
# The default value is: YES.
DOT_CLEANUP = YES
diff --git a/Examples/BlueBerryExampleLauncher/BlueBerryExampleLauncher.cpp b/Examples/BlueBerryExampleLauncher/BlueBerryExampleLauncher.cpp
index 96cc40d450..1487fa3eca 100644
--- a/Examples/BlueBerryExampleLauncher/BlueBerryExampleLauncher.cpp
+++ b/Examples/BlueBerryExampleLauncher/BlueBerryExampleLauncher.cpp
@@ -1,50 +1,50 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkBaseApplication.h>
#include "BlueBerryExampleLauncherDialog.h"
#include <QFileInfo>
#include <QVariant>
int main(int argc, char **argv)
{
mitk::BaseApplication app(argc, argv);
app.setApplicationName("BlueBerryExampleLauncher");
app.setOrganizationName("DKFZ");
app.initializeQt();
BlueBerryExampleLauncherDialog demoDialog;
QString selectedConfiguration = demoDialog.getDemoConfiguration();
if (selectedConfiguration.isEmpty())
return EXIT_SUCCESS;
app.setProvisioningFilePath(selectedConfiguration);
// We create the application id relying on a convention:
// org.mitk.example.<configuration-name>
QString appId = "org.mitk.example.";
- QStringList appIdTokens = QFileInfo(selectedConfiguration).baseName().toLower().split('_', QString::SkipEmptyParts);
+ QStringList appIdTokens = QFileInfo(selectedConfiguration).baseName().toLower().split('_', Qt::SkipEmptyParts);
appId += appIdTokens.size() > 1 ? appIdTokens.at(1) : appIdTokens.at(0);
// Special cases
if (appId == "org.mitk.example.exampleplugins")
{
appId = "org.mitk.qt.extapplication";
}
app.setProperty(mitk::BaseApplication::PROP_APPLICATION, appId);
return app.run();
}
diff --git a/Examples/BlueBerryExampleLauncher/CMakeLists.txt b/Examples/BlueBerryExampleLauncher/CMakeLists.txt
index 6890323b01..f1a4fcd9f9 100644
--- a/Examples/BlueBerryExampleLauncher/CMakeLists.txt
+++ b/Examples/BlueBerryExampleLauncher/CMakeLists.txt
@@ -1,76 +1,76 @@
project(BlueBerryExampleLauncher)
set(_source_files
BlueBerryExampleLauncher.cpp
BlueBerryExampleLauncherDialog.cpp
)
set(_source_moc_h_files
BlueBerryExampleLauncherDialog.h
)
set(_source_ui_files
BlueBerryExampleLauncherDialog.ui
)
# this is a workaround for Visual Studio. The relative include paths in the generated
# moc files can get very long and can't be resolved by the MSVC compiler.
foreach(_moc_src ${_source_moc_h_files})
- qt5_wrap_cpp(_source_files ${_moc_src} OPTIONS -f${_moc_src})
+ qt_wrap_cpp(_source_files ${_moc_src} OPTIONS -f${_moc_src})
endforeach()
-qt5_wrap_ui(_source_files ${_source_ui_files})
+qt_wrap_ui(_source_files ${_source_ui_files})
include_directories(${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
)
#-----------------------------------------------------------------------------
# Create provisioning files
#-----------------------------------------------------------------------------
set(_plugins_for_all_demos
)
file(GLOB _demo_configurations Configurations/*.cmake)
set(ALL_REQUIRED_PLUGINS ${_plugins_for_all_demos})
foreach(_demo_config_file ${_demo_configurations})
set(REQUIRED_PLUGINS )
set(DESCRIPTION )
include(${_demo_config_file})
get_filename_component(_name ${_demo_config_file} NAME_WE)
mitkFunctionCreateProvisioningFile(FILE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${PROJECT_NAME}_${_name}.provisioning
PLUGINS ${REQUIRED_PLUGINS} ${_plugins_for_all_demos}
NO_INSTALL
)
if(DESCRIPTION)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/BlueBerryExampleDescription.txt
${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${PROJECT_NAME}_${_name}.txt @ONLY)
endif()
list(APPEND ALL_REQUIRED_PLUGINS ${REQUIRED_PLUGINS})
endforeach()
list(REMOVE_DUPLICATES ALL_REQUIRED_PLUGINS)
set(ALL_REQUIRED_PLUGIN_TARGETS )
foreach(req_plugin ${ALL_REQUIRED_PLUGINS})
string(REPLACE "." "_" _plugin_target ${req_plugin})
if(TARGET ${_plugin_target})
list(APPEND ALL_REQUIRED_PLUGIN_TARGETS ${_plugin_target})
endif()
endforeach()
#-----------------------------------------------------------------------------
# Create the example launcher
#-----------------------------------------------------------------------------
mitkFunctionCreateBlueBerryApplication(
NAME ${PROJECT_NAME}
DESCRIPTION "MITK Application Framework Demo"
SOURCES ${_source_files}
# PLUGINS ${ALL_REQUIRED_PLUGIN_TARGETS}
NO_PROVISIONING
NO_INSTALL
)
add_dependencies(${PROJECT_NAME} ${ALL_REQUIRED_PLUGIN_TARGETS})
diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp
index 1f7eabc4db..99777fef44 100644
--- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp
+++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.cpp
@@ -1,161 +1,161 @@
/*============================================================================
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 "QmitkIsoSurface.h"
// MITK headers
#include <mitkManualSegmentationToSurfaceFilter.h>
#include <mitkNodePredicateDataType.h>
#include <mitkSurface.h>
#include <mitkIPreferences.h>
// Qt-GUI headers
#include <QApplication>
#include <QCursor>
#include <QMessageBox>
QmitkIsoSurface::QmitkIsoSurface(QObject * /*parent*/, const char * /*name*/)
: m_Controls(nullptr), m_MitkImage(nullptr), m_SurfaceCounter(0)
{
}
void QmitkIsoSurface::CreateQtPartControl(QWidget *parent)
{
if (!m_Controls)
{
m_Controls = new Ui::QmitkIsoSurfaceControls;
m_Controls->setupUi(parent);
this->CreateConnections();
m_Controls->m_ImageSelector->SetDataStorage(this->GetDataStorage());
m_Controls->m_ImageSelector->SetPredicate(mitk::NodePredicateDataType::New("Image"));
auto* prefs = this->GetPreferences();
if (prefs != nullptr)
m_Controls->thresholdLineEdit->setText(QString::fromStdString(prefs->Get("defaultThreshold", "0")));
}
}
void QmitkIsoSurface::SetFocus()
{
m_Controls->m_ImageSelector->setFocus();
}
void QmitkIsoSurface::CreateConnections()
{
if (m_Controls)
{
connect(m_Controls->m_ImageSelector,
SIGNAL(OnSelectionChanged(const mitk::DataNode *)),
this,
SLOT(ImageSelected(const mitk::DataNode *)));
connect(m_Controls->createSurfacePushButton, SIGNAL(clicked()), this, SLOT(CreateSurface()));
}
}
void QmitkIsoSurface::ImageSelected(const mitk::DataNode *item)
{
// nothing selected (nullptr selection)
if (item == nullptr || item->GetData() == nullptr)
return;
m_MitkImage = dynamic_cast<mitk::Image *>(item->GetData());
}
void QmitkIsoSurface::CreateSurface()
{
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
if (m_MitkImage != nullptr)
{
// Value Gauss
// float gsDev = 1.5;
// Value for DecimatePro
float targetReduction = 0.05;
// ImageToSurface Instance
mitk::DataNode::Pointer node = m_Controls->m_ImageSelector->GetSelectedNode();
mitk::ManualSegmentationToSurfaceFilter::Pointer filter = mitk::ManualSegmentationToSurfaceFilter::New();
if (filter.IsNull())
{
std::cout << "nullptr Pointer for ManualSegmentationToSurfaceFilter" << std::endl;
return;
}
filter->SetInput(m_MitkImage);
filter->SetGaussianStandardDeviation(0.5);
filter->SetUseGaussianImageSmooth(true);
filter->SetThreshold(getThreshold()); // if( Gauss ) --> TH manipulated for vtkMarchingCube
filter->SetTargetReduction(targetReduction);
int numOfPolys = filter->GetOutput()->GetVtkPolyData()->GetNumberOfPolys();
if (numOfPolys > 2000000)
{
QApplication::restoreOverrideCursor();
if (QMessageBox::question(nullptr,
"CAUTION!!!",
"The number of polygons is greater than 2 000 000. If you continue, the program might "
"crash. How do you want to go on?",
"Proceed anyway!",
"Cancel immediately! (maybe you want to insert an other threshold)!",
- QString::null,
+ QString(),
0,
1) == 1)
{
return;
}
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
}
mitk::DataNode::Pointer surfaceNode = mitk::DataNode::New();
surfaceNode->SetData(filter->GetOutput());
int layer = 0;
++m_SurfaceCounter;
std::ostringstream buffer;
buffer << m_SurfaceCounter;
std::string surfaceNodeName = "Surface " + buffer.str();
node->GetIntProperty("layer", layer);
surfaceNode->SetIntProperty("layer", layer + 1);
surfaceNode->SetProperty("Surface", mitk::BoolProperty::New(true));
surfaceNode->SetProperty("name", mitk::StringProperty::New(surfaceNodeName));
this->GetDataStorage()->Add(surfaceNode, node);
// to show surfaceContur
surfaceNode->SetColor(m_RainbowColor.GetNextColor());
surfaceNode->SetVisibility(true);
mitk::IRenderWindowPart *renderPart = this->GetRenderWindowPart();
if (renderPart)
{
renderPart->RequestUpdate();
}
}
QApplication::restoreOverrideCursor();
}
float QmitkIsoSurface::getThreshold()
{
return m_Controls->thresholdLineEdit->text().toFloat();
}
QmitkIsoSurface::~QmitkIsoSurface()
{
auto* prefs = this->GetPreferences();
if (prefs != nullptr)
prefs->Put("defaultThreshold", m_Controls->thresholdLineEdit->text().toStdString());
}
diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/volumetry/QmitkVolumetryView.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/volumetry/QmitkVolumetryView.cpp
index eb2ce45ff9..b5e4aee6f6 100644
--- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/volumetry/QmitkVolumetryView.cpp
+++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/volumetry/QmitkVolumetryView.cpp
@@ -1,252 +1,252 @@
/*============================================================================
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 "QmitkVolumetryView.h"
#include "ui_QmitkVolumetryViewControls.h"
#include "mitkImageStatisticsHolder.h"
#include "mitkVolumeCalculator.h"
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>
#include <QTextStream>
const std::string QmitkVolumetryView::VIEW_ID = "org.mitk.views.volumetry";
QmitkVolumetryView::QmitkVolumetryView() : m_Controls(nullptr), m_ParentWidget(nullptr)
{
}
void QmitkVolumetryView::CreateQtPartControl(QWidget *parent)
{
if (!m_Controls)
{
m_ParentWidget = parent;
// create GUI widgets
m_Controls = new Ui::QmitkVolumetryViewControls;
m_Controls->setupUi(parent);
this->CreateConnections();
}
}
void QmitkVolumetryView::SetFocus()
{
m_Controls->m_CalcButton->setFocus();
}
void QmitkVolumetryView::CreateConnections()
{
if (m_Controls)
{
connect(
(QObject *)(m_Controls->m_ThresholdSlider), SIGNAL(valueChanged(int)), this, SLOT(OnThresholdSliderChanged(int)));
connect((QObject *)(m_Controls->m_CalcButton), SIGNAL(clicked()), this, SLOT(OnCalculateVolume()));
connect((QObject *)(m_Controls->m_TimeSeriesButton), SIGNAL(clicked()), this, SLOT(OnTimeSeriesButtonClicked()));
connect((QObject *)(m_Controls->m_SaveCsvButton), SIGNAL(clicked()), this, SLOT(OnSaveCsvButtonClicked()));
}
}
void QmitkVolumetryView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/,
const QList<mitk::DataNode::Pointer> &nodes)
{
m_SelectedDataNode = nullptr;
if (!nodes.isEmpty() && dynamic_cast<mitk::Image *>(nodes.front()->GetData()))
{
m_SelectedDataNode = nodes.front();
m_ParentWidget->setEnabled(true);
}
if (m_SelectedDataNode.IsExpired() || m_SelectedDataNode == m_OverlayNode)
{
m_SelectedDataNode = nullptr;
m_ParentWidget->setEnabled(false);
return;
}
if (m_OverlayNode)
{
this->GetDataStorage()->Remove(m_OverlayNode);
m_OverlayNode = nullptr;
}
this->CreateOverlayChild();
m_Controls->m_CalcButton->setEnabled(false);
m_Controls->m_TimeSeriesButton->setEnabled(false);
m_Controls->m_SaveCsvButton->setEnabled(false);
m_Controls->m_TextEdit->clear();
mitk::Image *image = dynamic_cast<mitk::Image *>(m_SelectedDataNode.Lock()->GetData());
image->Update();
if (image && image->IsInitialized())
{
if (image->GetDimension() == 4)
{
m_Controls->m_TimeSeriesButton->setEnabled(true);
}
else
{
m_Controls->m_CalcButton->setEnabled(true);
}
int minVal = (int)image->GetStatistics()->GetScalarValue2ndMin();
int maxVal = (int)image->GetStatistics()->GetScalarValueMaxNoRecompute();
if (minVal == maxVal)
--minVal;
m_Controls->m_ThresholdSlider->setMinimum(minVal);
m_Controls->m_ThresholdSlider->setMaximum(maxVal);
m_Controls->m_ThresholdSlider->setEnabled(true);
this->UpdateSlider();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkVolumetryView::OnCalculateVolume()
{
auto selectedDataNode = m_SelectedDataNode.Lock();
if (selectedDataNode.IsNotNull())
{
mitk::Image *image = dynamic_cast<mitk::Image *>(selectedDataNode->GetData());
std::cout << "Dimension:" << image->GetDimension() << std::endl;
std::cout << "Dimension[3]:" << image->GetDimension(3) << std::endl;
mitk::VolumeCalculator::Pointer volCalc = mitk::VolumeCalculator::New();
volCalc->SetImage(image);
volCalc->SetThreshold(m_Controls->m_ThresholdSlider->value());
volCalc->ComputeVolume();
std::stringstream vs;
vs << volCalc->GetVolume() << " ml";
m_Controls->m_Result->setText(vs.str().c_str());
}
}
void QmitkVolumetryView::OnTimeSeriesButtonClicked()
{
auto selectedDataNode = m_SelectedDataNode.Lock();
if (selectedDataNode.IsNotNull())
{
mitk::Image *image = dynamic_cast<mitk::Image *>(selectedDataNode->GetData());
mitk::VolumeCalculator::Pointer volCalc = mitk::VolumeCalculator::New();
volCalc->SetImage(image);
volCalc->SetThreshold(m_Controls->m_ThresholdSlider->value());
volCalc->ComputeVolume();
std::vector<float> volumes = volCalc->GetVolumes();
std::stringstream vs;
int timeStep = 0;
for (auto it = volumes.begin(); it != volumes.end(); it++)
{
vs << timeStep++ << "\t" << *it << std::endl;
}
m_Controls->m_TextEdit->setText(vs.str().c_str());
- m_Controls->m_TextEdit->setTabStopWidth(20);
+ m_Controls->m_TextEdit->setTabStopDistance(20);
m_Controls->m_SaveCsvButton->setEnabled(true);
}
}
const mitk::DataNode *QmitkVolumetryView::GetImageNode() const
{
return m_SelectedDataNode.Lock();
}
void QmitkVolumetryView::UpdateSlider()
{
auto selectedDataNode = m_SelectedDataNode.Lock();
if (selectedDataNode.IsNotNull() && dynamic_cast<mitk::Image *>(selectedDataNode->GetData()))
{
int intSliderValue = (int)m_Controls->m_ThresholdSlider->value();
QString stringSliderValue;
stringSliderValue.setNum(intSliderValue);
m_Controls->m_ThresholdLineEdit->setText(stringSliderValue);
}
}
void QmitkVolumetryView::UpdateSliderLabel()
{
int sliderValue = atoi(m_Controls->m_ThresholdLineEdit->text().toLatin1());
m_Controls->m_ThresholdSlider->setValue(sliderValue);
this->UpdateSlider();
}
void QmitkVolumetryView::OnThresholdSliderChanged(int value)
{
if (m_OverlayNode)
{
m_OverlayNode->SetLevelWindow(mitk::LevelWindow(value, 1));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
this->UpdateSlider();
}
}
void QmitkVolumetryView::CreateOverlayChild()
{
auto selectedDataNode = m_SelectedDataNode.Lock();
if (selectedDataNode.IsNotNull())
{
m_OverlayNode = mitk::DataNode::New();
mitk::StringProperty::Pointer nameProp = mitk::StringProperty::New("volume threshold overlay image");
m_OverlayNode->SetProperty("reslice interpolation", selectedDataNode->GetProperty("reslice interpolation"));
m_OverlayNode->SetProperty("name", nameProp);
m_OverlayNode->SetData(selectedDataNode->GetData());
m_OverlayNode->SetColor(0.0, 1.0, 0.0);
m_OverlayNode->SetOpacity(.25);
int layer = 0;
selectedDataNode->GetIntProperty("layer", layer);
m_OverlayNode->SetIntProperty("layer", layer + 1);
m_OverlayNode->SetLevelWindow(mitk::LevelWindow(m_Controls->m_ThresholdSlider->value(), 1));
this->GetDataStorage()->Add(m_OverlayNode);
}
}
mitk::DataNode *QmitkVolumetryView::GetOverlayNode() const
{
return m_OverlayNode;
}
mitk::Image *QmitkVolumetryView::GetImage() const
{
return dynamic_cast<mitk::Image *>(m_SelectedDataNode.Lock()->GetData());
}
void QmitkVolumetryView::OnSaveCsvButtonClicked()
{
static QString lastSavePath = QDir::homePath();
QString s = QFileDialog::getSaveFileName(this->m_ParentWidget, "Save as..", lastSavePath, "CSV Files (*.csv)");
/*"Save file dialog"
"Choose a filename to save under" );*/
if (!s.isEmpty())
{
lastSavePath = s;
QFile saveFile(s);
if (saveFile.open(QIODevice::WriteOnly))
{
QTextStream stream(&saveFile);
stream << m_Controls->m_TextEdit->toPlainText().replace('\t', ';');
saveFile.close();
}
else
{
// QMessageBox::critical(nullptr,"Save Error!",QString("Saving of CSV failed! Couldn't open output file \"") +
// saveFile + QString("\""),QMessageBox:Ok,QMessageBox::NoButton);
// QMessageBox::critical(nullptr,"Save Error!","Saving of CSV failed! Couldn't open output file \"" + saveFile.name()
// +"\"",QMessageBox::Ok,QMessageBox::NoButton);
}
}
}
diff --git a/Examples/Tutorial/Step4/Step4.cpp b/Examples/Tutorial/Step4/Step4.cpp
index 3861e4d84f..2d6fe9c4c8 100644
--- a/Examples/Tutorial/Step4/Step4.cpp
+++ b/Examples/Tutorial/Step4/Step4.cpp
@@ -1,164 +1,164 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkRegisterClasses.h"
#include "QmitkRenderWindow.h"
#include "QmitkSliceWidget.h"
#include "mitkNodePredicateDataType.h"
#include "mitkProperties.h"
#include "mitkRenderingManager.h"
#include "mitkStandaloneDataStorage.h"
#include <mitkIOUtil.h>
#include <QApplication>
#include <QHBoxLayout>
#include <itksys/SystemTools.hxx>
#include <mitkImage.h>
//##Documentation
//## @brief Use several views to explore data
//##
//## As in Step2 and Step3, load one or more data sets (many image,
//## surface and other formats), but create 3 views on the data.
//## The QmitkRenderWindow is used for displaying a 3D view as in Step3,
//## but without volume-rendering.
//## Furthermore, we create two 2D views for slicing through the data.
//## We use the class QmitkSliceWidget, which is based on the class
//## QmitkRenderWindow, but additionally provides sliders
//## to slice through the data. We create two instances of
//## QmitkSliceWidget, one for axial and one for sagittal slicing.
//## The two slices are also shown at their correct position in 3D as
//## well as intersection-line, each in the other 2D view.
int main(int argc, char *argv[])
{
QApplication qtapplication(argc, argv);
if (argc < 2)
{
fprintf(
stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str());
return 1;
}
// Register Qmitk-dependent global instances
QmitkRegisterClasses();
//*************************************************************************
// Part I: Basic initialization
//*************************************************************************
// Create a DataStorage
mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();
//*************************************************************************
// Part II: Create some data by reading files
//*************************************************************************
int i;
for (i = 1; i < argc; ++i)
{
// For testing
if (strcmp(argv[i], "-testing") == 0)
continue;
//*********************************************************************
// Part III: Put the data into the datastorage
//*********************************************************************
// Load datanode (eg. many image formats, surface formats, etc.)
mitk::IOUtil::Load(argv[i], *ds);
}
//*************************************************************************
// Part IV: Create windows and pass the tree to it
//*************************************************************************
// Create toplevel widget with horizontal layout
QWidget toplevelWidget;
QHBoxLayout layout;
layout.setSpacing(2);
- layout.setMargin(0);
+ layout.setContentsMargins({});
toplevelWidget.setLayout(&layout);
//*************************************************************************
// Part IVa: 3D view
//*************************************************************************
// Create a renderwindow
QmitkRenderWindow renderWindow(&toplevelWidget);
layout.addWidget(&renderWindow);
// Tell the renderwindow which (part of) the datastorage to render
renderWindow.GetRenderer()->SetDataStorage(ds);
// Use it as a 3D view
renderWindow.GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D);
// Reposition the camera to include all visible actors
renderWindow.GetRenderer()->GetVtkRenderer()->ResetCamera();
// *******************************************************
// ****************** START OF NEW PART ******************
// *******************************************************
//*************************************************************************
// Part IVb: 2D view for slicing axially
//*************************************************************************
// Create QmitkSliceWidget, which is based on the class
// QmitkRenderWindow, but additionally provides sliders
QmitkSliceWidget view2(&toplevelWidget);
layout.addWidget(&view2);
view2.SetLevelWindowEnabled(true);
// Tell the QmitkSliceWidget which (part of) the tree to render.
// By default, it slices the data axially
view2.SetDataStorage(ds);
// Get the image from the data storage. A predicate (mitk::NodePredicateBase)
// is used to get only nodes of the type mitk::Image.
mitk::DataStorage::SetOfObjects::ConstPointer rs = ds->GetSubset(mitk::TNodePredicateDataType<mitk::Image>::New());
view2.SetData(rs->Begin(), mitk::AnatomicalPlane::Axial);
// We want to see the position of the slice in 2D and the
// slice itself in 3D: add it to the datastorage!
ds->Add(view2.GetRenderer()->GetCurrentWorldPlaneGeometryNode());
//*************************************************************************
// Part IVc: 2D view for slicing sagittally
//*************************************************************************
// Create QmitkSliceWidget, which is based on the class
// QmitkRenderWindow, but additionally provides sliders
QmitkSliceWidget view3(&toplevelWidget);
layout.addWidget(&view3);
view3.SetDataStorage(ds);
// Tell the QmitkSliceWidget which (part of) the datastorage to render
// and to slice sagittally
view3.SetData(rs->Begin(), mitk::AnatomicalPlane::Sagittal);
// We want to see the position of the slice in 2D and the
// slice itself in 3D: add it to the datastorage!
ds->Add(view3.GetRenderer()->GetCurrentWorldPlaneGeometryNode());
// *******************************************************
// ******************* END OF NEW PART *******************
// *******************************************************
//*************************************************************************
// Part V: Qt-specific initialization
//*************************************************************************
toplevelWidget.show();
return qtapplication.exec();
}
/**
\example Step4.cpp
*/
diff --git a/Examples/Tutorial/Step5/Step5.cpp b/Examples/Tutorial/Step5/Step5.cpp
index addd3361a1..e4b149aef6 100644
--- a/Examples/Tutorial/Step5/Step5.cpp
+++ b/Examples/Tutorial/Step5/Step5.cpp
@@ -1,203 +1,203 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkRegisterClasses.h"
#include "QmitkRenderWindow.h"
#include "QmitkSliceWidget.h"
#include "mitkNodePredicateDataType.h"
#include "mitkProperties.h"
#include "mitkRenderingManager.h"
#include "mitkStandaloneDataStorage.h"
#include "mitkPointSet.h"
// NEW INCLUDE
#include "mitkPointSetDataInteractor.h"
#include <QApplication>
#include <QHBoxLayout>
#include <itksys/SystemTools.hxx>
#include <mitkIOUtil.h>
//##Documentation
//## @brief Interactively add points
//##
//## As in Step4, load one or more data sets (many image,
//## surface and other formats) and create 3 views on the data.
//## Additionally, we want to interactively add points. A node containing
//## a PointSet as data is added to the data tree and a PointSetDataInteractor
//## is associated with the node, which handles the interaction. The
//## @em interaction @em pattern is defined in a state-machine, stored in an
//## external XML file. Thus, we need to load a state-machine
//## The interaction patterns defines the @em events,
//## on which the interactor reacts (e.g., which mouse buttons are used to
//## set a point), the @em transition to the next state (e.g., the initial
//## may be "empty point set") and associated @a actions (e.g., add a point
//## at the position where the mouse-click occured).
int main(int argc, char *argv[])
{
QApplication qtapplication(argc, argv);
if (argc < 2)
{
fprintf(
stderr, "Usage: %s [filename1] [filename2] ...\n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str());
return 1;
}
// Register Qmitk-dependent global instances
QmitkRegisterClasses();
//*************************************************************************
// Part I: Basic initialization
//*************************************************************************
// Create a DataStorage
mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();
//*************************************************************************
// Part II: Create some data by reading files
//*************************************************************************
int i;
for (i = 1; i < argc; ++i)
{
// For testing
if (strcmp(argv[i], "-testing") == 0)
continue;
// Load datanode (eg. many image formats, surface formats, etc.)
mitk::StandaloneDataStorage::SetOfObjects::Pointer dataNodes = mitk::IOUtil::Load(argv[i], *ds);
//*********************************************************************
// Part III: Put the data into the datastorage
//*********************************************************************
// Add the node to the DataStorage
if (dataNodes->empty())
{
fprintf(stderr, "Could not open file %s \n\n", argv[i]);
exit(2);
}
}
//*************************************************************************
// Part V: Create windows and pass the tree to it
//*************************************************************************
// Create toplevel widget with horizontal layout
QWidget toplevelWidget;
QHBoxLayout layout;
layout.setSpacing(2);
- layout.setMargin(0);
+ layout.setContentsMargins({});
toplevelWidget.setLayout(&layout);
//*************************************************************************
// Part Va: 3D view
//*************************************************************************
// Create a renderwindow
QmitkRenderWindow renderWindow(&toplevelWidget);
layout.addWidget(&renderWindow);
// Tell the renderwindow which (part of) the tree to render
renderWindow.GetRenderer()->SetDataStorage(ds);
// Use it as a 3D view
renderWindow.GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D);
// Reposition the camera to include all visible actors
renderWindow.GetRenderer()->GetVtkRenderer()->ResetCamera();
//*************************************************************************
// Part Vb: 2D view for slicing axially
//*************************************************************************
// Create QmitkSliceWidget, which is based on the class
// QmitkRenderWindow, but additionally provides sliders
QmitkSliceWidget view2(&toplevelWidget);
layout.addWidget(&view2);
// Tell the QmitkSliceWidget which (part of) the tree to render.
// By default, it slices the data axially
view2.SetDataStorage(ds);
mitk::DataStorage::SetOfObjects::ConstPointer rs = ds->GetSubset(mitk::TNodePredicateDataType<mitk::Image>::New());
view2.SetData(rs->Begin(), mitk::AnatomicalPlane::Axial);
// We want to see the position of the slice in 2D and the
// slice itself in 3D: add it to the tree!
ds->Add(view2.GetRenderer()->GetCurrentWorldPlaneGeometryNode());
//*************************************************************************
// Part Vc: 2D view for slicing sagittally
//*************************************************************************
// Create QmitkSliceWidget, which is based on the class
// QmitkRenderWindow, but additionally provides sliders
QmitkSliceWidget view3(&toplevelWidget);
layout.addWidget(&view3);
// Tell the QmitkSliceWidget which (part of) the tree to render
// and to slice sagittally
view3.SetDataStorage(ds);
view3.SetData(rs->Begin(), mitk::AnatomicalPlane::Sagittal);
// We want to see the position of the slice in 2D and the
// slice itself in 3D: add it to the tree!
ds->Add(view3.GetRenderer()->GetCurrentWorldPlaneGeometryNode());
// *******************************************************
// ****************** START OF NEW PART ******************
// *******************************************************
//*************************************************************************
// Part VI: For allowing to interactively add points ...
//*************************************************************************
// ATTENTION: It is very important that the renderer already know their DataStorage,
// because registerig DataInteractors with the render windows is done automatically
// and only works if the BaseRenderer and the DataStorage know each other.
// Create PointSet and a node for it
mitk::PointSet::Pointer pointSet = mitk::PointSet::New();
mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();
// Store the point set in the DataNode
pointSetNode->SetData(pointSet);
// Add the node to the tree
ds->Add(pointSetNode);
// Create PointSetDataInteractor
mitk::PointSetDataInteractor::Pointer interactor = mitk::PointSetDataInteractor::New();
// Set the StateMachine pattern that describes the flow of the interactions
interactor->LoadStateMachine("PointSet.xml");
// Set the configuration file, which describes the user interactions that trigger actions
// in this file SHIFT + LeftClick triggers add Point, but by modifying this file,
// it could as well be changes to any other user interaction.
interactor->SetEventConfig("PointSetConfig.xml");
// Assign the pointSetNode to the interactor,
// alternatively one could also add the DataInteractor to the pointSetNode using the SetDataInteractor() method.
interactor->SetDataNode(pointSetNode);
// *******************************************************
// ******************* END OF NEW PART *******************
// *******************************************************
//*************************************************************************
// Part VII: Qt-specific initialization
//*************************************************************************
toplevelWidget.show();
return qtapplication.exec();
}
/**
\example Step5.cpp
*/
diff --git a/Examples/Tutorial/Step6/Step6.cpp b/Examples/Tutorial/Step6/Step6.cpp
index a6bce70bb3..5e7b065aeb 100644
--- a/Examples/Tutorial/Step6/Step6.cpp
+++ b/Examples/Tutorial/Step6/Step6.cpp
@@ -1,233 +1,233 @@
/*============================================================================
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 "Step6.h"
#include "QmitkRenderWindow.h"
#include "QmitkSliceWidget.h"
#include "mitkProperties.h"
#include "mitkRenderingManager.h"
#include "mitkPointSet.h"
#include "mitkPointSetDataInteractor.h"
#include "mitkImageAccessByItk.h"
#include "mitkRenderingManager.h"
#include <mitkIOUtil.h>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QPushButton>
#include <QVBoxLayout>
//##Documentation
//## @brief Start region-grower at interactively added points
Step6::Step6(int argc, char *argv[], QWidget *parent) : QWidget(parent)
{
// load data as in the previous steps; a reference to the first loaded
// image is kept in the member m_FirstImage and used as input for the
// region growing
Load(argc, argv);
}
void Step6::Initialize()
{
// setup the widgets as in the previous steps, but with an additional
// QVBox for a button to start the segmentation
this->SetupWidgets();
// Create controlsParent widget with horizontal layout
QWidget *controlsParent = new QWidget(this);
this->layout()->addWidget(controlsParent);
QHBoxLayout *hlayout = new QHBoxLayout(controlsParent);
hlayout->setSpacing(2);
QLabel *labelThresholdMin = new QLabel("Lower Threshold:", controlsParent);
hlayout->addWidget(labelThresholdMin);
m_LineEditThresholdMin = new QLineEdit("-1000", controlsParent);
hlayout->addWidget(m_LineEditThresholdMin);
QLabel *labelThresholdMax = new QLabel("Upper Threshold:", controlsParent);
hlayout->addWidget(labelThresholdMax);
m_LineEditThresholdMax = new QLineEdit("-400", controlsParent);
hlayout->addWidget(m_LineEditThresholdMax);
// create button to start the segmentation and connect its clicked()
// signal to method StartRegionGrowing
QPushButton *startButton = new QPushButton("start region growing", controlsParent);
hlayout->addWidget(startButton);
connect(startButton, SIGNAL(clicked()), this, SLOT(StartRegionGrowing()));
if (m_FirstImage.IsNull())
startButton->setEnabled(false);
// as in Step5, create PointSet (now as a member m_Seeds) and
// associate a interactor to it
m_Seeds = mitk::PointSet::New();
mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();
pointSetNode->SetData(m_Seeds);
pointSetNode->SetProperty("layer", mitk::IntProperty::New(2));
m_DataStorage->Add(pointSetNode);
// Create PointSetDataInteractor
mitk::PointSetDataInteractor::Pointer interactor = mitk::PointSetDataInteractor::New();
interactor->LoadStateMachine("PointSet.xml");
interactor->SetEventConfig("PointSetConfig.xml");
interactor->SetDataNode(pointSetNode);
}
int Step6::GetThresholdMin()
{
return m_LineEditThresholdMin->text().toInt();
}
int Step6::GetThresholdMax()
{
return m_LineEditThresholdMax->text().toInt();
}
void Step6::StartRegionGrowing()
{
AccessByItk_1(m_FirstImage, RegionGrowing, this);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void Step6::Load(int argc, char *argv[])
{
//*************************************************************************
// Part I: Basic initialization
//*************************************************************************
m_DataStorage = mitk::StandaloneDataStorage::New();
//*************************************************************************
// Part II: Create some data by reading files
//*************************************************************************
int i;
for (i = 1; i < argc; ++i)
{
// For testing
if (strcmp(argv[i], "-testing") == 0)
continue;
// Load datanode (eg. many image formats, surface formats, etc.)
mitk::StandaloneDataStorage::SetOfObjects::Pointer dataNodes = mitk::IOUtil::Load(argv[i], *m_DataStorage);
if (dataNodes->empty())
{
fprintf(stderr, "Could not open file %s \n\n", argv[i]);
exit(2);
}
mitk::Image::Pointer image = dynamic_cast<mitk::Image *>(dataNodes->at(0)->GetData());
if ((m_FirstImage.IsNull()) && (image.IsNotNull()))
m_FirstImage = image;
}
}
void Step6::SetupWidgets()
{
//*************************************************************************
// Part I: Create windows and pass the datastorage to it
//*************************************************************************
// Create toplevel widget with vertical layout
QVBoxLayout *vlayout = new QVBoxLayout(this);
- vlayout->setMargin(0);
+ vlayout->setContentsMargins({});
vlayout->setSpacing(2);
// Create viewParent widget with horizontal layout
QWidget *viewParent = new QWidget(this);
vlayout->addWidget(viewParent);
QHBoxLayout *hlayout = new QHBoxLayout(viewParent);
- hlayout->setMargin(0);
+ hlayout->setContentsMargins({});
hlayout->setSpacing(2);
//*************************************************************************
// Part Ia: 3D view
//*************************************************************************
// Create a renderwindow
QmitkRenderWindow *renderWindow = new QmitkRenderWindow(viewParent);
hlayout->addWidget(renderWindow);
// Tell the renderwindow which (part of) the tree to render
renderWindow->GetRenderer()->SetDataStorage(m_DataStorage);
// Use it as a 3D view
renderWindow->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D);
// Reposition the camera to include all visible actors
renderWindow->GetRenderer()->GetVtkRenderer()->ResetCamera();
//*************************************************************************
// Part Ib: 2D view for slicing axially
//*************************************************************************
// Create QmitkSliceWidget, which is based on the class
// QmitkRenderWindow, but additionally provides sliders
QmitkSliceWidget *view2 = new QmitkSliceWidget(viewParent);
hlayout->addWidget(view2);
// Tell the QmitkSliceWidget which (part of) the tree to render.
// By default, it slices the data axially
view2->SetDataStorage(m_DataStorage);
mitk::DataStorage::SetOfObjects::ConstPointer rs = m_DataStorage->GetAll();
view2->SetData(rs->Begin(), mitk::AnatomicalPlane::Axial);
// We want to see the position of the slice in 2D and the
// slice itself in 3D: add it to the tree!
m_DataStorage->Add(view2->GetRenderer()->GetCurrentWorldPlaneGeometryNode());
//*************************************************************************
// Part Ic: 2D view for slicing sagittally
//*************************************************************************
// Create QmitkSliceWidget, which is based on the class
// QmitkRenderWindow, but additionally provides sliders
QmitkSliceWidget *view3 = new QmitkSliceWidget(viewParent);
hlayout->addWidget(view3);
// Tell the QmitkSliceWidget which (part of) the tree to render
// and to slice sagittally
view3->SetDataStorage(m_DataStorage);
view3->SetData(rs->Begin(), mitk::AnatomicalPlane::Sagittal);
// We want to see the position of the slice in 2D and the
// slice itself in 3D: add it to the tree!
m_DataStorage->Add(view3->GetRenderer()->GetCurrentWorldPlaneGeometryNode());
//*************************************************************************
// Part II: handle updates: To avoid unnecessary updates, we have to
//*************************************************************************
// define when to update. The RenderingManager serves this purpose, and
// each RenderWindow has to be registered to it.
/*mitk::RenderingManager *renderingManager =
mitk::RenderingManager::GetInstance();
renderingManager->AddRenderWindow( renderWindow );
renderingManager->AddRenderWindow( view2->GetRenderWindow() );
renderingManager->AddRenderWindow( view3->GetRenderWindow() );*/
}
/**
\example Step6.cpp
*/
diff --git a/Examples/Tutorial/Step8/Step8.cpp b/Examples/Tutorial/Step8/Step8.cpp
index 2363ed0a48..e300928095 100644
--- a/Examples/Tutorial/Step8/Step8.cpp
+++ b/Examples/Tutorial/Step8/Step8.cpp
@@ -1,76 +1,76 @@
/*============================================================================
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 "Step8.h"
#include "QmitkLevelWindowWidget.h"
#include "QmitkRenderWindow.h"
#include "QmitkStdMultiWidget.h"
#include "mitkRenderingManager.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
//##Documentation
//## @brief As Step6, but with QmitkStdMultiWidget as widget
Step8::Step8(int argc, char *argv[], QWidget *parent) : Step6(argc, argv, parent)
{
}
void Step8::SetupWidgets()
{
//*************************************************************************
// Part I: Create windows and pass the tree to it
//*************************************************************************
// Create toplevel widget with vertical layout
QVBoxLayout *vlayout = new QVBoxLayout(this);
- vlayout->setMargin(0);
+ vlayout->setContentsMargins({});
vlayout->setSpacing(2);
// Create viewParent widget with horizontal layout
QWidget *viewParent = new QWidget(this);
vlayout->addWidget(viewParent);
QHBoxLayout *hlayout = new QHBoxLayout(viewParent);
- hlayout->setMargin(0);
+ hlayout->setContentsMargins({});
//*************************************************************************
// Part Ia: create and initialize QmitkStdMultiWidget
//*************************************************************************
QmitkStdMultiWidget *multiWidget = new QmitkStdMultiWidget(viewParent);
hlayout->addWidget(multiWidget);
// Tell the multiWidget which DataStorage to render
multiWidget->SetDataStorage(m_DataStorage);
// Initialize the multiWidget with the render windows
multiWidget->InitializeMultiWidget();
// Add the displayed views to the DataStorage to see their positions in 2D and 3D
multiWidget->AddPlanesToDataStorage();
//*************************************************************************
// Part Ib: create and initialize LevelWindowWidget
//*************************************************************************
QmitkLevelWindowWidget *levelWindowWidget = new QmitkLevelWindowWidget(viewParent);
hlayout->addWidget(levelWindowWidget);
// Tell the levelWindowWidget which DataStorage to access
levelWindowWidget->SetDataStorage(m_DataStorage);
}
/**
\example Step8.cpp
*/
diff --git a/MITKConfig.cmake.in b/MITKConfig.cmake.in
index 4e7ef7c55b..164a7d82a0 100644
--- a/MITKConfig.cmake.in
+++ b/MITKConfig.cmake.in
@@ -1,314 +1,311 @@
if(CMAKE_VERSION VERSION_LESS @MITK_CMAKE_MINIMUM_REQUIRED_VERSION@)
message(FATAL_ERROR "MITK requires at least CMake Version @MITK_CMAKE_MINIMUM_REQUIRED_VERSION@")
endif()
# The MITK version number
set(MITK_VERSION_MAJOR "@MITK_VERSION_MAJOR@")
set(MITK_VERSION_MINOR "@MITK_VERSION_MINOR@")
set(MITK_VERSION_PATCH "@MITK_VERSION_PATCH@")
set(MITK_VERSION_STRING "@MITK_VERSION_STRING@")
#-----------------------------------------------------------------------------
# C++ language standard
#-----------------------------------------------------------------------------
set(MITK_CXX_STANDARD @MITK_CXX_STANDARD@)
#-----------------------------------------------------------------------------
# Include required CMake scripts
#-----------------------------------------------------------------------------
# Update the CMake module path
set(MITK_CMAKE_MODULE_PATH "@MITK_SOURCE_DIR@/CMake")
list(APPEND CMAKE_MODULE_PATH ${MITK_CMAKE_MODULE_PATH})
# Standard CMake macros
include(CMakeParseArguments)
include(FeatureSummary)
include(FindPackageHandleStandardArgs)
include(GenerateExportHeader)
# Include MITK macros
include(MacroParseArguments)
include(mitkFunctionAddManifest)
include(mitkFunctionAddCustomModuleTest)
include(mitkFunctionCheckMitkCompatibility)
include(mitkFunctionCheckModuleDependencies)
include(mitkFunctionConfigureVisualStudioUserProjectFile)
include(mitkFunctionCreateBlueBerryApplication)
include(mitkFunctionCreateCommandLineApp)
include(mitkFunctionCreateModule)
include(mitkFunctionCreatePlugin)
include(mitkFunctionCreateProvisioningFile)
include(mitkFunctionCreateWindowsBatchScript)
include(mitkFunctionGetLibrarySearchPaths)
include(mitkFunctionInstallAutoLoadModules)
include(mitkFunctionInstallCTKPlugin)
include(mitkFunctionInstallProvisioningFiles)
include(mitkFunctionInstallThirdPartyCTKPlugins)
include(mitkFunctionOrganizeSources)
include(mitkFunctionUseModules)
include(mitkMacroCreateExecutable)
include(mitkMacroCreateModuleTests)
include(mitkMacroFindDependency)
include(mitkMacroGenerateToolsLibrary)
include(mitkMacroGetPMDPlatformString)
include(mitkMacroInstall)
include(mitkMacroInstallHelperApp)
include(mitkMacroInstallTargets)
include(mitkMacroMultiplexPicType)
#-----------------------------------------------------------------------------
# MITK flags and directories
#-----------------------------------------------------------------------------
# MITK compiler flags
set(MITK_C_FLAGS "@MITK_C_FLAGS@")
set(MTTK_C_FLAGS_DEBUG "@MITK_C_FLAGS_DEBUG@")
set(MITK_C_FLAGS_RELEASE "@MITK_C_FLAGS_RELEASE@")
set(MITK_CXX_FLAGS "@MITK_CXX_FLAGS@")
set(MTTK_CXX_FLAGS_DEBUG "@MITK_CXX_FLAGS_DEBUG@")
set(MITK_CXX_FLAGS_RELEASE "@MITK_CXX_FLAGS_RELEASE@")
# MITK linker flags
set(MITK_EXE_LINKER_FLAGS "@MITK_EXE_LINKER_FLAGS@")
set(MITK_SHARED_LINKER_FLAGS "@MITK_SHARED_LINKER_FLAGS@")
set(MITK_MODULE_LINKER_FLAGS "@MITK_MODULE_LINKER_FLAGS@")
# MITK specific directories
set(MITK_SOURCE_DIR "@MITK_SOURCE_DIR@")
set(MITK_BINARY_DIR "@MITK_BINARY_DIR@")
set(MITK_CMAKE_DIR "@MITK_CMAKE_DIR@")
# MITK output directories
set(MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY "@MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY@")
set(MITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY "@MITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY@")
set(MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY "@MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY@")
#-----------------------------------------------------------------------------
# Miscellaneous variables
#-----------------------------------------------------------------------------
# Internal version numbers, used for approximate compatibility checks
# of a MITK development version (non-release).
set(MITK_VERSION_PLUGIN_SYSTEM 2) # dropped legacy BlueBerry plug-in CMake support
set(MITK_DATA_DIR "@MITK_DATA_DIR@")
set(UTILITIES_DIR "@UTILITIES_DIR@")
set(REGISTER_QFUNCTIONALITY_CPP_IN "@REGISTER_QFUNCTIONALITY_CPP_IN@")
set(MITK_DOXYGEN_TAGFILE_NAME "@MITK_DOXYGEN_TAGFILE_NAME@")
set(MITK_LEGACY_EXPORT_MACRO_NAME 1)
set(DCMTK_CMAKE_DEBUG_POSTFIX @DCMTK_CMAKE_DEBUG_POSTFIX@)
# Get the canonical name of the directory to avoid potential case mismatch,
# e.g. in the drive letter on Windows.
get_filename_component(CMAKE_CURRENT_LIST_DIR_REALPATH ${CMAKE_CURRENT_LIST_DIR} REALPATH)
if(CMAKE_CURRENT_LIST_DIR_REALPATH STREQUAL MITK_BINARY_DIR)
set(MITK_EXTERNAL_PROJECT_PREFIX @MITK_EXTERNAL_PROJECT_PREFIX@)
endif()
set(MITK_MODULES_PACKAGE_DEPENDS_DIR "@MITK_MODULES_PACKAGE_DEPENDS_DIR@")
if(MODULES_PACKAGE_DEPENDS_DIRS)
list(APPEND MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR})
list(REMOVE_DUPLICATES MODULES_PACKAGE_DEPENDS_DIRS)
else()
set(MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR})
endif()
#-----------------------------------------------------------------------------
# External dependencies
#-----------------------------------------------------------------------------
list(APPEND CMAKE_PREFIX_PATH "@MITK_EXTERNAL_PROJECT_PREFIX@")
# -----------------------------------------
# Qt variables and dependencies
-set(MITK_USE_Qt5 @MITK_USE_Qt5@)
+set(MITK_USE_Qt6 @MITK_USE_Qt6@)
-if(MITK_USE_Qt5)
- set(MITK_QT5_MINIMUM_VERSION @MITK_QT5_MINIMUM_VERSION@)
- set(MITK_QT5_COMPONENTS @MITK_QT5_COMPONENTS@)
- mitkMacroFindDependency(Qt5 ${MITK_QT5_MINIMUM_VERSION} COMPONENTS ${MITK_QT5_COMPONENTS})
+if(MITK_USE_Qt6)
+ set(MITK_QT6_MINIMUM_VERSION @MITK_QT6_MINIMUM_VERSION@)
+ set(MITK_QT6_COMPONENTS @MITK_QT6_COMPONENTS@)
+ mitkMacroFindDependency(Qt6 ${MITK_QT6_MINIMUM_VERSION} COMPONENTS ${MITK_QT6_COMPONENTS})
endif()
# -----------------------------------------
# Special Python variables
set(MITK_USE_Python3 @MITK_USE_Python3@)
if(MITK_USE_Python3)
set(PYTHON_EXECUTABLE "@PYTHON_EXECUTABLE@" CACHE FILEPATH "")
set(PYTHON_INCLUDE_DIR "@PYTHON_INCLUDE_DIR@" CACHE PATH "")
set(PYTHON_LIBRARY "@PYTHON_LIBRARY@" CACHE FILEPATH "")
set(PYTHON_INCLUDE_DIR2 "@PYTHON_INCLUDE_DIR2@" CACHE PATH "")
mitkMacroFindDependency(Python3 COMPONENTS Interpreter Development NumPy)
endif()
# -----------------------------------------
# Special Boost variables
set(MITK_USE_Boost_LIBRARIES @MITK_USE_Boost_LIBRARIES@)
set(MITK_USE_SYSTEM_Boost @MITK_USE_SYSTEM_Boost@)
set(Boost_ROOT "@Boost_ROOT@" CACHE PATH "")
set(BOOST_LIBRARYDIR "@BOOST_LIBRARYDIR@" CACHE PATH "")
set(Boost_ADDITIONAL_VERSIONS 1.74 1.74.0)
# We need this later for a DCMTK workaround
set(_dcmtk_dir_orig "@DCMTK_DIR@")
# -----------------------------------------
# External dependencies from the superbuild
# or injected from somewhere else via
# <project>_DIR variables.
@MITK_CONFIG_EXTERNAL_PROJECTS@
# Ensure the MITK module path comes first
set(CMAKE_MODULE_PATH ${MITK_CMAKE_MODULE_PATH} ${CMAKE_MODULE_PATH})
# -----------------------------------------
# Special handling for DCMTK
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()
# -----------------------------------------
# Special handling for DCMQI
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()
# -----------------------------------------
# Special handling for Boost
if(MITK_USE_Boost)
link_directories(${Boost_LIBRARY_DIRS})
endif()
# -----------------------------------------
# Special handling for OpenIGTLink
if(MITK_USE_OpenIGTLink)
link_directories(${OpenIGTLink_LIBRARY_DIRS})
endif()
# -----------------------------------------
# Internal project dependencies
set(CppMicroServices_DIR "@CppMicroServices_DIR@")
mitkMacroFindDependency(CppMicroServices)
set(MITK_USE_BLUEBERRY @MITK_USE_BLUEBERRY@)
if(MITK_USE_BLUEBERRY)
set(MITK_PLUGIN_USE_FILE "@MITK_PLUGIN_USE_FILE@")
if(MITK_PLUGIN_USE_FILE)
if(EXISTS "${MITK_PLUGIN_USE_FILE}")
include("${MITK_PLUGIN_USE_FILE}")
endif()
endif()
set(MITK_PLUGIN_PROVISIONING_FILE "@MITK_EXTAPP_PROVISIONING_FILE@")
set(MITK_PROVISIONING_FILES
"${BLUEBERRY_PLUGIN_PROVISIONING_FILE}"
"${MITK_PLUGIN_PROVISIONING_FILE}")
endif()
set(BLUEBERRY_USE_QT_HELP @BLUEBERRY_USE_QT_HELP@)
if(BLUEBERRY_USE_QT_HELP AND DOXYGEN_VERSION VERSION_LESS "1.8.7")
message("Setting BLUEBERRY_USE_QT_HELP to OFF because Doxygen version 1.8.7 or newer not found.")
set(BLUEBERRY_USE_QT_HELP OFF)
endif()
set(BLUEBERRY_QTPLUGIN_PATH "@BLUEBERRY_QTPLUGIN_PATH@")
set(QT_HELPGENERATOR_EXECUTABLE "@QT_HELPGENERATOR_EXECUTABLE@")
set(QT_COLLECTIONGENERATOR_EXECUTABLE "@QT_COLLECTIONGENERATOR_EXECUTABLE@")
-set(QT_ASSISTANT_EXECUTABLE "@QT_ASSISTANT_EXECUTABLE@")
-set(QT_XMLPATTERNS_EXECUTABLE "@QT_XMLPATTERNS_EXECUTABLE@")
-
#-----------------------------------------------------------------------------
# MITK sub-project variables
#-----------------------------------------------------------------------------
# External SDK directories
set(MITK_PMD_SDK_DIR @MITK_PMD_SDK_DIR@)
# MITK ToF use variables
set(MITK_TOF_PMDCAMCUBE_AVAILABLE @MITK_USE_TOF_PMDCAMCUBE@)
if(MITK_TOF_PMDCAMCUBE_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK")
option(MITK_USE_TOF_PMDCAMCUBE "Enable support for PMD Cam Cube" @MITK_USE_TOF_PMDCAMCUBE@)
mark_as_advanced(MITK_USE_TOF_PMDCAMCUBE)
endif()
set(MITK_TOF_PMDCAMBOARD_AVAILABLE @MITK_USE_TOF_PMDCAMBOARD@)
if(MITK_TOF_PMDCAMBOARD_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK")
option(MITK_USE_TOF_PMDCAMBOARD "Enable support for PMD Cam Board" @MITK_USE_TOF_PMDCAMBOARD@)
mark_as_advanced(MITK_USE_TOF_PMDCAMBOARD)
endif()
set(MITK_TOF_PMDO3_AVAILABLE @MITK_USE_TOF_PMDO3@)
if(MITK_TOF_PMDO3_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK")
option(MITK_USE_TOF_PMDO3 "Enable support for PMD =3" @MITK_USE_TOF_PMDO3@)
mark_as_advanced(MITK_USE_TOF_PMDO3)
endif()
set(MITK_TOF_KINECT_AVAILABLE @MITK_USE_TOF_KINECT@)
if(MITK_TOF_KINECT_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK")
option(MITK_USE_TOF_KINECT "Enable support for Kinect" @MITK_USE_TOF_KINECT@)
mark_as_advanced(MITK_USE_TOF_KINECT)
endif()
set(MITK_TOF_MESASR4000_AVAILABLE @MITK_USE_TOF_MESASR4000@)
if(MITK_TOF_MESASR4000_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK")
option(MITK_USE_TOF_MESASR4000 "Enable support for MESA SR4000" @MITK_USE_TOF_MESASR4000@)
mark_as_advanced(MITK_USE_TOF_MESASR4000)
endif()
if(MITK_USE_IGT)
#include("${MITK_DIR}/mitkIGTConfig.cmake")
endif()
#-----------------------------------------------------------------------------
# Import MITK targets and set custom properties
#-----------------------------------------------------------------------------
if(NOT MITK_EXPORTS_FILE_INCLUDED)
if(EXISTS "@MITK_EXPORTS_FILE@")
set(MITK_EXPORTS_FILE_INCLUDED 1)
include("@MITK_EXPORTS_FILE@")
endif()
endif()
# Set properties on exported targets
@MITK_EXPORTED_TARGET_PROPERTIES@
#-----------------------------------------------------------------------------
# Install rules
#-----------------------------------------------------------------------------
# Install rules for ToF libraries loaded at runtime
if(EXISTS "@MITK_BINARY_DIR@/mitkToFHardwareInstallRules.cmake")
include("@MITK_BINARY_DIR@/mitkToFHardwareInstallRules.cmake")
endif()
diff --git a/Modules/AppUtil/CMakeLists.txt b/Modules/AppUtil/CMakeLists.txt
index e306674c8d..6ebace912f 100644
--- a/Modules/AppUtil/CMakeLists.txt
+++ b/Modules/AppUtil/CMakeLists.txt
@@ -1,14 +1,8 @@
-set(qt5_depends Qt5|Widgets+WebEngineCore)
-
-if(UNIX AND NOT APPLE)
- set(qt5_depends "${qt5_depends}+X11Extras")
-endif()
-
mitk_create_module(
PACKAGE_DEPENDS
- PUBLIC CTK|CTKPluginFramework ${qt5_depends} Poco|Util
+ PUBLIC CTK|CTKPluginFramework Qt6|Widgets+WebEngineCore+Quick Poco|Util
PRIVATE VTK|GUISupportQt
DEPENDS
PUBLIC qtsingleapplication
PRIVATE MitkCore
)
diff --git a/Modules/AppUtil/src/QmitkSafeNotify.h b/Modules/AppUtil/src/QmitkSafeNotify.h
index 3b742172ad..2f2228ffc4 100644
--- a/Modules/AppUtil/src/QmitkSafeNotify.h
+++ b/Modules/AppUtil/src/QmitkSafeNotify.h
@@ -1,69 +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 QmitkSafeNotify_h
#define QmitkSafeNotify_h
#include <mitkException.h>
#include <mitkLog.h>
#include <QMessageBox>
template <class A>
bool QmitkSafeNotify(A *app, QObject *receiver, QEvent *event)
{
QString msg;
try
{
return app->A::notify(receiver, event);
}
catch (mitk::Exception &e)
{
msg = QString("MITK Exception:\n\n") + QString("Description: ") + QString(e.GetDescription()) + QString("\n\n") +
QString("Filename: ") + QString(e.GetFile()) + QString("\n\n") + QString("Line: ") +
QString::number(e.GetLine());
}
catch (std::exception &e)
{
msg = e.what();
}
catch (...)
{
msg = "Unknown exception";
}
MITK_ERROR << "An error occurred: " << msg.toStdString();
QMessageBox msgBox;
msgBox.setText("An error occurred. You should save all data and quit the program to prevent possible data loss.");
msgBox.setDetailedText(msg);
msgBox.setIcon(QMessageBox::Critical);
- msgBox.addButton(app->trUtf8("Exit immediately"), QMessageBox::YesRole);
- msgBox.addButton(app->trUtf8("Ignore"), QMessageBox::NoRole);
+ msgBox.addButton("Exit immediately", QMessageBox::YesRole);
+ msgBox.addButton("Ignore", QMessageBox::NoRole);
int ret = msgBox.exec();
switch (ret)
{
case 0:
MITK_ERROR << "The program was closed.";
app->closeAllWindows();
break;
case 1:
MITK_ERROR
<< "The error was ignored by the user. The program may be in a corrupt state and don't behave like expected!";
break;
}
return false;
}
#endif
diff --git a/Modules/AppUtil/src/mitkBaseApplication.cpp b/Modules/AppUtil/src/mitkBaseApplication.cpp
index 6f9e3a72d2..9b96be95c0 100644
--- a/Modules/AppUtil/src/mitkBaseApplication.cpp
+++ b/Modules/AppUtil/src/mitkBaseApplication.cpp
@@ -1,927 +1,926 @@
/*============================================================================
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 <mitkBaseApplication.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkExceptionMacro.h>
#include <mitkLog.h>
#include <mitkProvisioningInfo.h>
#include <QmitkSafeApplication.h>
#include <QmitkSingleApplication.h>
#include <Poco/Util/HelpFormatter.h>
#include <ctkPluginFramework.h>
#include <ctkPluginFramework_global.h>
#include <ctkPluginFrameworkLauncher.h>
#include <usModuleSettings.h>
#include <vtkLogger.h>
#include <vtkOpenGLRenderWindow.h>
#include <QVTKOpenGLNativeWidget.h>
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QRunnable>
#include <QSplashScreen>
#include <QStandardPaths>
#include <QTime>
#include <QWebEngineUrlScheme>
+#include <QQuickWindow>
namespace
{
void outputImportantQtMessage(QtMsgType type, const QMessageLogContext&, const QString& msg)
{
auto message = msg.toStdString();
switch (type)
{
case QtWarningMsg:
MITK_WARN << message;
break;
case QtCriticalMsg:
MITK_ERROR << message;
break;
case QtFatalMsg:
MITK_ERROR << message;
abort();
default:
break;
}
}
void outputQtMessage(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
auto message = msg.toStdString();
switch (type)
{
case QtDebugMsg:
MITK_DEBUG << message;
break;
case QtInfoMsg:
MITK_INFO << message;
break;
case QtWarningMsg:
[[fallthrough]];
case QtCriticalMsg:
[[fallthrough]];
case QtFatalMsg:
outputImportantQtMessage(type, context, msg);
break;
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_XARGS = "xargs";
const QString BaseApplication::ARG_LOG_QT_MESSAGES = "Qt.logMessages";
const QString BaseApplication::ARG_SEGMENTATION_LABELSET_PRESET = "Segmentation.labelSetPreset";
const QString BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS = "Segmentation.labelSuggestions";
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;
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<char*> 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;
bool m_LogQtMessages;
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),
m_LogQtMessages(false)
{
#ifdef Q_OS_MAC
/* On macOS the process serial number is passed as an command line argument (-psn_<NUMBER>)
in certain circumstances. This option causes a Poco exception. We remove it, if present. */
m_Argv_macOS.reserve(argc + 1);
const char psn[] = "-psn";
for (int i = 0; i < argc; ++i)
{
if (0 == strncmp(argv[i], psn, sizeof(psn) - 1))
continue;
m_Argv_macOS.push_back(argv[i]);
}
m_Argv_macOS.push_back(nullptr);
m_Argc = static_cast<decltype(m_Argc)>(m_Argv_macOS.size() - 1);
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 &)
{
if (ARG_LOG_QT_MESSAGES.toStdString() == name)
{
m_LogQtMessages = true;
return;
}
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<std::string> 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 : qAsConst(pluginUrlsToStart))
+ for (const auto& url : std::as_const(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<int>(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<QmitkSingleApplication *>(d->m_QApp)->setSafeMode(safeMode)
: static_cast<QmitkSafeApplication *>(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:
* <MITK-build/bin/MitkWorkbench.provisioning>
* The executable path is:
* <MITK-build/bin/MitkWorkbench.app/Contents/MacOS/MitkWorkbench>
* 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);
+ provFile.setFile(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;
-#ifdef Q_OS_LINUX
+ // Prevent conflicts between native OpenGL applications and QWebEngine
+ QQuickWindow::setGraphicsApi(QSGRendererInterface::Software);
+
+/*#ifdef Q_OS_LINUX
qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--single-process"); // See T29332
-#endif
+#endif*/
// 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(!d->m_LogQtMessages
? outputImportantQtMessage
: outputQtMessage);
QWebEngineUrlScheme qtHelpScheme("qthelp");
qtHelpScheme.setFlags(QWebEngineUrlScheme::LocalScheme | QWebEngineUrlScheme::LocalAccessAllowed);
QWebEngineUrlScheme::registerScheme(qtHelpScheme);
}
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
+ // 3. Load the "default" configuration, which involves parsing
// an optional <executable-name>.ini file and parsing any
// command line arguments
this->loadConfiguration();
- // 5. Add configuration data from the command line and the
+ // 4. Add configuration data from the command line and the
// optional <executable-name>.ini file as CTK plugin
// framework properties.
d->initializeCTKPluginFrameworkProperties(this->config());
- // 6. Initialize splash screen if an image path is provided
+ // 5. 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
+ // 6. Set the custom CTK Plugin Framework storage directory
QString storageDir = this->getCTKFrameworkStorageDir();
if (!storageDir.isEmpty())
{
d->m_FWProps[ctkPluginConstants::FRAMEWORK_STORAGE] = storageDir;
+ if (!(storageDir.endsWith('/') || storageDir.endsWith('\\')))
+ storageDir.append('/');
+
// Initialize core service preferences at the exact same location as their predecessor BlueBerry preferences
mitk::CoreServicePointer preferencesService(mitk::CoreServices::GetPreferencesService());
- preferencesService->InitializeStorage(storageDir.toStdString() + "/data/3/prefs.xml");
+ preferencesService->InitializeStorage(storageDir.toStdString() + "data/3/prefs.xml");
}
- // 8. Set the library search paths and the pre-load library property
+ // 7. 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.
+ // 8. 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
+ // 9. Parse the (optional) provisioning file and set the
// correct framework properties.
d->parseProvisioningFile(this->getProvisioningFilePath());
- // 11. Set the CTK Plugin Framework properties
+ // 10. 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<QtSingleApplication *>(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)
{
vtkLogger::SetStderrVerbosity(vtkLogger::VERBOSITY_WARNING);
vtkOpenGLRenderWindow::SetGlobalMaximumNumberOfMultiSamples(0);
auto defaultFormat = QVTKOpenGLNativeWidget::defaultFormat();
defaultFormat.setSamples(0);
QSurfaceFormat::setDefaultFormat(defaultFormat);
-#ifdef Q_OS_OSX
+#ifdef Q_OS_MACOS
QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
#endif
- QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
-
-#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
-#endif
QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
d->m_QApp = this->getSingleMode()
? static_cast<QCoreApplication*>(new QmitkSingleApplication(d->m_Argc, d->m_Argv, this->getSafeMode()))
: static_cast<QCoreApplication*>(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 : qAsConst(suffixes))
+ for (const auto& suffix : std::as_const(suffixes))
ctkPluginFrameworkLauncher::addSearchPath(appDir.absoluteFilePath(suffix));
}
int BaseApplication::main(const std::vector<std::string> &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<BaseApplication>(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<Impl>(d, &Impl::handleBooleanOption));
options.addOption(newInstanceOption);
Poco::Util::Option cleanOption(ARG_CLEAN.toStdString(), "", "cleans the plugin cache");
cleanOption.callback(Poco::Util::OptionCallback<Impl>(d, &Impl::handleClean));
options.addOption(cleanOption);
Poco::Util::Option productOption(ARG_PRODUCT.toStdString(), "", "the id of the product to be launched");
productOption.argument("<id>").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("<id>").binding(PROP_APPLICATION.toStdString());
options.addOption(appOption);
Poco::Util::Option provOption(ARG_PROVISIONING.toStdString(), "", "the location of a provisioning file");
provOption.argument("<prov file>").binding(ARG_PROVISIONING.toStdString());
options.addOption(provOption);
Poco::Util::Option storageDirOption(ARG_STORAGE_DIR.toStdString(), "", "the location for storing persistent application data");
storageDirOption.argument("<dir>").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<Impl>(d, &Impl::handleBooleanOption));
options.addOption(consoleLogOption);
Poco::Util::Option debugOption(ARG_DEBUG.toStdString(), "", "enable debug mode");
debugOption.argument("<options file>", 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<Impl>(d, &Impl::handleBooleanOption));
options.addOption(forcePluginOption);
Poco::Util::Option preloadLibsOption(ARG_PRELOAD_LIBRARY.toStdString(), "", "preload a library");
preloadLibsOption.argument("<library>")
.repeatable(true)
.callback(Poco::Util::OptionCallback<Impl>(d, &Impl::handlePreloadLibraryOption));
options.addOption(preloadLibsOption);
Poco::Util::Option noRegistryCacheOption(ARG_NO_REGISTRY_CACHE.toStdString(), "", "do not use a cache for the registry");
noRegistryCacheOption.callback(Poco::Util::OptionCallback<Impl>(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<Impl>(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<Impl>(d, &Impl::handleBooleanOption));
options.addOption(registryMultiLanguageOption);
Poco::Util::Option splashScreenOption(ARG_SPLASH_IMAGE.toStdString(), "", "optional picture to use as a splash screen");
splashScreenOption.argument("<filename>").binding(ARG_SPLASH_IMAGE.toStdString());
options.addOption(splashScreenOption);
Poco::Util::Option xargsOption(ARG_XARGS.toStdString(), "", "Extended argument list");
xargsOption.argument("<args>").binding(ARG_XARGS.toStdString());
options.addOption(xargsOption);
Poco::Util::Option logQtMessagesOption(ARG_LOG_QT_MESSAGES.toStdString(), "", "log Qt messages");
logQtMessagesOption.callback(Poco::Util::OptionCallback<Impl>(d, &Impl::handleBooleanOption));
options.addOption(logQtMessagesOption);
Poco::Util::Option labelSetPresetOption(ARG_SEGMENTATION_LABELSET_PRESET.toStdString(), "", "use this label set preset for new segmentations");
labelSetPresetOption.argument("<filename>").binding(ARG_SEGMENTATION_LABELSET_PRESET.toStdString());
options.addOption(labelSetPresetOption);
Poco::Util::Option labelSuggestionsOption(ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), "", "use this list of predefined suggestions for segmentation labels");
labelSuggestionsOption.argument("<filename>").binding(ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString());
options.addOption(labelSuggestionsOption);
Poco::Util::Application::defineOptions(options);
}
QSharedPointer<ctkPluginFramework> 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<QString, QVariant> 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<QtSingleApplication*>(this->getQApplication());
if (nullptr != app)
app->isRunning();
mitkThrow() << "Method not implemented.";
}
void BaseApplication::sendMessage(const QByteArray msg)
{
auto app = dynamic_cast<QtSingleApplication*>(this->getQApplication());
if (nullptr != app)
app->sendMessage(msg);
mitkThrow() << "Method not implemented.";
}
}
diff --git a/Modules/AppUtil/src/mitkProvisioningInfo.cpp b/Modules/AppUtil/src/mitkProvisioningInfo.cpp
index 7ccdb6c8ca..696fe1a621 100644
--- a/Modules/AppUtil/src/mitkProvisioningInfo.cpp
+++ b/Modules/AppUtil/src/mitkProvisioningInfo.cpp
@@ -1,206 +1,207 @@
/*============================================================================
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 "mitkProvisioningInfo.h"
#include <mitkLog.h>
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
+#include <QRegularExpression>
#include <QTextStream>
namespace mitk
{
#ifdef CMAKE_INTDIR
const QString ProvisioningInfo::intermediateOutDir = QString(CMAKE_INTDIR);
#else
const QString ProvisioningInfo::intermediateOutDir = QString();
#endif
ProvisioningInfo::ProvisioningInfo(const QString &file) { this->readProvisioningFile(file); }
- QStringList ProvisioningInfo::getPluginDirs() const { return pluginDirs.toList(); }
+ QStringList ProvisioningInfo::getPluginDirs() const { return pluginDirs.values(); }
QList<QUrl> ProvisioningInfo::getPluginsToInstall() const { return pluginsToInstall; }
QList<QUrl> ProvisioningInfo::getPluginsToStart() const { return pluginsToStart; }
void ProvisioningInfo::readProvisioningFile(const QString &filePath)
{
QFile file(filePath);
file.open(QFile::ReadOnly);
QTextStream fileStream(&file);
- QRegExp sep("\\s+");
+ QRegularExpression sep("\\s+");
QString line;
int count = 1;
do
{
line = fileStream.readLine().trimmed();
if (!line.isEmpty() && !line.startsWith('#'))
{
QString keyword = line.section(sep, 0, 0);
QString value = line.mid(keyword.size()).trimmed();
value = substituteKeywords(value);
if (keyword.isEmpty())
{
MITK_WARN << "Keyword missing in line " << count << " of provisioning file " << filePath.toStdString();
continue;
}
Keyword key = UNKNOWN;
if (keyword.compare("READ", Qt::CaseInsensitive) == 0)
{
key = READ;
}
else if (keyword.compare("INSTALL", Qt::CaseInsensitive) == 0)
{
key = INSTALL;
}
else if (keyword.compare("START", Qt::CaseInsensitive) == 0)
{
key = START;
}
else if (keyword.compare("STOP", Qt::CaseInsensitive) == 0)
{
key = STOP;
}
if (key == UNKNOWN)
{
MITK_WARN << "Keyword " << keyword.toStdString() << " in line " << count << " of provisioning file "
<< filePath.toStdString() << " unknown";
continue;
}
if (value.isEmpty())
{
MITK_WARN << "Value after keyword " << keyword.toStdString() << " missing in line " << count
<< " of provisioning file " << filePath.toStdString();
continue;
}
switch (key)
{
case READ:
{
QUrl readFileUrl(value);
if (!readFileUrl.isValid())
{
MITK_WARN << "The READ URL " << value.toStdString()
<< "is invalid: " << readFileUrl.errorString().toStdString();
break;
}
this->readProvisioningFile(readFileUrl.toLocalFile());
break;
}
case INSTALL:
{
this->addPluginToInstall(value);
break;
}
case START:
{
this->addPluginToStart(value);
break;
}
case STOP:
{
break;
}
case UNKNOWN:
{
break; // error handled above
}
}
}
++count;
} while (!line.isNull());
}
QUrl ProvisioningInfo::addPluginToInstall(const QString &file)
{
QUrl pluginUrl(file);
if (!pluginUrl.isValid())
{
MITK_WARN << "The plugin URL " << file.toStdString() << " is invalid:" << pluginUrl.errorString().toStdString();
return QUrl();
}
QFileInfo fileInfo(pluginUrl.toLocalFile());
if (!fileInfo.exists())
{
QString fileName = fileInfo.fileName();
QString filePath = fileInfo.absolutePath();
if (!intermediateOutDir.isEmpty())
{
// search in the intermediate output dir
QString filePath2 = filePath + "/" + intermediateOutDir;
fileInfo = QFileInfo(filePath2 + "/" + fileName);
if (!fileInfo.exists())
{
MITK_WARN << "The plugin " << fileName.toStdString() << " was not found in " << filePath.toStdString()
<< " or " << filePath2.toStdString();
return QUrl();
}
pluginUrl = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
pluginDirs.insert(fileInfo.canonicalPath());
}
else
{
MITK_WARN << "The plugin " << fileName.toStdString() << " was not found in " << filePath.toStdString();
return QUrl();
}
}
else
{
pluginDirs.insert(fileInfo.canonicalPath());
}
pluginsToInstall.append(pluginUrl);
return pluginUrl;
}
void ProvisioningInfo::addPluginToStart(const QString &file)
{
QUrl pluginUrl = this->addPluginToInstall(file);
if (!pluginUrl.isEmpty())
{
pluginsToStart.append(pluginUrl);
}
}
QString ProvisioningInfo::substituteKeywords(const QString &value) const
{
QString appPath = QCoreApplication::applicationDirPath();
if (appPath.endsWith('/'))
{
appPath.chop(1);
}
#ifdef CMAKE_INTDIR
// Strip the intermediate dir from the application path
QString intDir(CMAKE_INTDIR);
if (appPath.endsWith(intDir))
{
appPath.chop(intDir.size() + 1);
}
#endif
#ifdef _WIN32
if (value.contains("@EXECUTABLE_DIR") && value.contains("blueberry_osgi"))
{
// special case for org_blueberry_osgi in install trees for Windows
return QString(value).replace("@EXECUTABLE_DIR", appPath, Qt::CaseInsensitive).replace("plugins/", "");
}
#endif
return QString(value).replace("@EXECUTABLE_DIR", appPath, Qt::CaseInsensitive);
}
}
diff --git a/Modules/Chart/CMakeLists.txt b/Modules/Chart/CMakeLists.txt
index a1ce1092ec..7f210c921d 100644
--- a/Modules/Chart/CMakeLists.txt
+++ b/Modules/Chart/CMakeLists.txt
@@ -1,4 +1,4 @@
MITK_CREATE_MODULE(
DEPENDS MitkCore
- PACKAGE_DEPENDS PUBLIC Qt5|WebEngineWidgets
+ PACKAGE_DEPENDS PUBLIC Qt6|WebEngineWidgets
)
diff --git a/Modules/Chart/Test/CMakeLists.txt b/Modules/Chart/Test/CMakeLists.txt
index 1bb8b54172..088e42acef 100644
--- a/Modules/Chart/Test/CMakeLists.txt
+++ b/Modules/Chart/Test/CMakeLists.txt
@@ -1,4 +1,4 @@
MITK_CREATE_MODULE_TESTS(
DEPENDS MitkCore MitkChart
- PACKAGE_DEPENDS PUBLIC Qt5|WebEngineWidgets
-)
\ No newline at end of file
+ PACKAGE_DEPENDS PUBLIC Qt6|WebEngineWidgets
+)
diff --git a/Modules/Chart/documentation/mitkChart.dox b/Modules/Chart/documentation/mitkChart.dox
index 52c41353eb..74b5f3ff02 100644
--- a/Modules/Chart/documentation/mitkChart.dox
+++ b/Modules/Chart/documentation/mitkChart.dox
@@ -1,256 +1,256 @@
/**
\page ChartModule Chart Module
\tableofcontents
\section ChartModule_brief Description
The MITK chart module is able to show different types of charts in a widget with customizable labels.
\imageMacro{complexExample.png,"Example chart",10}
\subsection Chart_Technical Technical background
-The module uses the java script library <a href="https://plot.ly/javascript/">plotly</a> to display the chart in a <a href="https://doc.qt.io/qt-5/qwebengineview.html">QWebEngineView</a> (that renders html/js content).
+The module uses the java script library <a href="https://plot.ly/javascript/">plotly</a> to display the chart in a <a href="https://doc.qt.io/qt-6/qwebengineview.html">QWebEngineView</a> (that renders html/js content).
For examples, please visit https://plot.ly/javascript/.
\subsection Chart_GUI GUI
\note Be sure that the dependency to the Chart Module is resolved in the CMakeLists.txt of the plugin: <code>MODULE_DEPENDS MitkChart</code>.
-Open the ui file of the plugin. Then add a widget (we always use the name <code>chartWidget</code> in the following) at the desired position. Change the class of the widget to a user-defined widget (right click &rarr; user defined classes, see https://doc.qt.io/qt-5/designer-using-custom-widgets.html). Set "QWidget" as base class. Set "QmitkChartWidget" as class name and "QmitkChartWidget.h" as include file.
+Open the ui file of the plugin. Then add a widget (we always use the name <code>chartWidget</code> in the following) at the desired position. Change the class of the widget to a user-defined widget (right click &rarr; user defined classes, see https://doc.qt.io/qt-6/designer-using-custom-widgets.html). Set "QWidget" as base class. Set "QmitkChartWidget" as class name and "QmitkChartWidget.h" as include file.
\imageMacro{userDefinedWidget.png,"User defined widget",10}
\subsection Chart_data Data
The most important functionality is to add data to the chartWidget. Either one dimensional or two dimensional data can be used. One-dimensional data has the same interval between values on the x-axis (and no x-axis values) while the two-dimensional data has arbitrary x-axis difference values (and given x-axis values).
An example for one-dimensional data is the temperature for each month of a year: <code>std::vector<double> temperatureHD = {1.8, 3.1, 6.3, 10.2, 14.5, 17.4, 19.4, 18.9, 15.5, 11.2, 5.8, 2.6}</code>. The first entry corresponds (implicitly) to the temperature in january, two second to the temperature in february the last entry to the temperature in december. Thus, the x values have same intervals. The given temperature values are defined as y-axis values.
An example for two-dimensional data is the people living in a city in different years: <code>std::map<double,double> peopleHeidelberg={{1975, 129368 }, { 1985, 134724 },{ 1990, 136796 },{ 2010, 147312 }}.</code>
Thus, the x-values are given as their intervals are different (10 years, 5 years, 10 years). Each x value is connected to an y-value that represents the amount of people (1975 &rarr; 129368, 1985 &rarr; 134724, ...).
Data is added by calling <code>chartWidget->AddData1D(temperatureHD, "Heidelberg")</code> or <code>chartWidget->AddData2D(peopleHeidelberg, "Heidelberg")</code>, where the second argument is a label for the data entry.
\imageMacro{2DDataExample.png,"2D data example: Heidelberg has fewer entries and their x-range (years) is smaller than Freiburg",8}
As the data labels are used as identifier, they have to be unique. This is checked. If non-unique entries are entered, they are made unique by adding numbers. Example:
\code{.cpp}
chartWidget->AddData1D(temperatureHD, "Heidelberg")
chartWidget->AddData1D(temperatureOslo, "Heidelberg")
\endcode
will result in the labels "Heidelberg" and "Heidelberg0", whereas "Heidelberg0" refers to <code>temperatureOslo</code>.
If you want to add more data, just call <code>chartWidget->AddData1D(data, label, chartType)</code> or <code>chartWidget->AddData2D(data, label, chartType)</code> as often as desired. Then, call <code>chartWidget->Show()</code>. The ranges of x- and y-axis are adjusted automatically.
To delete single data entries, call <code>chartWidget->RemoveData(label)</code> and update the chart area with <code>chartWidget->Show()</code>. All data can be cleared by calling <code>chartWidget->Clear()</code>.
\subsection Chart_type Chart type
The default chart type is <code>bar</code>. To use a different type, you have to change it.
Seven chart types are available:
<ul>
<li> <code>bar</code>
<li> <code>line</code>
<li> <code>spline</code>
<li> <code>pie</code>
<li> <code>are</code>
<li> <code>area_spline</code>
<li> <code>scatter</code>
</ul>
See below examples of all types:
\imageMacro{barChartTemperature.png,"Example bar chart",4}
\imageMacro{lineChartTemperature.png,"Example line chart",4}
\imageMacro{splineChartTemperature.png,"Example spline chart",4}
\imageMacro{pieChartExample.png,"Example pie chart",4}
\imageMacro{areaChartTemperature.png,"Example area chart",4}
\imageMacro{areaSplineChartTemperature.png,"Example spline area chart",4}
\imageMacro{scatterChartTemperature.png,"Example scatter chart",4}
Call e.g. <code>chartWidget->SetChartType(label, QmitkChartWidget::ChartType::line)</code> for changing the chart type. Note that it is not directly displayed. To change the chart type for all data entries and display the result, call <code>chartWidget->SetChartTypeForAllDataAndReload(QmitkChartWidget::ChartType::line)</code>.
All chart types except pie chart can be also used mixed (different chart types in the same chart). Pie charts are handled differently. The input data sum is regarded as 100%. The values of all data entries are summed. Example:
\code{.cpp}
chartWidget->AddData1D({5}, "entry1", QmitkChartWidget::ChartType::pie);
chartWidget->AddData1D({2}, "entry2", QmitkChartWidget::ChartType::pie);
chartWidget->AddData1D({3}, "entry3", QmitkChartWidget::ChartType::pie);
\endcode
The pie chart has then entries of 50%, 20% and 30%. Calling <code>chartWidget->AddData1D({5,2,3}, "entry", QmitkChartWidget::ChartType::pie)</code> leads to a pie chart with one class having 100%. Calling
\code{.cpp}
chartWidget->AddData1D({2,2,1}, "entry1", QmitkChartWidget::ChartType::pie);
chartWidget->AddData1D({1,1}, "entry2", QmitkChartWidget::ChartType::pie);
chartWidget->AddData1D({3}, "entry3", QmitkChartWidget::ChartType::pie);
\endcode
leads to the first result again (50%, 20% and 30%) as entries are summed.
\warning pie charts differ significantly from the other chart types. Be aware of the differences.
\subsection Chart_labels Labels
Four labels can be set to custom strings. These are
<ul>
<li> the data labels,
<li> the x-axis label,
<li> the y-axis label and
<li> the title of the chart
</ul>
Data labels provide the name for data legend entries ("Heidelberg" for our 1D data \ref Chart_data as it is the average temperature in Heidelberg) and are given by the second argument of AddData1D and AddData2D. They are also displayed in the legend. An example x-Axis and y-axis label would be <i>month</i> and <i>temperature</i>, respectively.
The data label argument is mandatory. All other labels are optional and empty strings by default.
<code>chartWidget->SetXAxisLabel("month")</code> and <code>chartWidget->SetYAxisLabel("temperature")</code> ensures the labeling of x- and y-Axis in the chart. No labels are defined as default.
<code>chartWidget->SetTitle("temperature chart")</code> adds a title to the chart.
\note The legend position (of data labels) can be set by <code>chartWidget->SetLegendPosition(QmitkChartWidget::LegendPosition::bottom)</code>.
\note To hide the legend, call <code>chartWidget->SetShowLegend(false)</code>.
\subsection Chart_show Displaying the chart
Finally, the chart is displayed by calling <code>chartWidget->Show(bool)</code>. If the optional parameter is set to true, a subchart is shown additionally. That's useful for ensuring the overview if the user wants to zoom in.
\subsection Chart_dataAttributes Changing visualization attributes of data
Besides the chart type, the following attributes of a data entry can be changed:
<ul>
<li>color,
<li>linesyle and
<li>data points shown
</ul>
this is done by referencing the data entry by its label (e.g. "Heidelberg" above): <code>chartWidget->SetColor("Heidelberg", "green")</code>, <code>chartWidget->SetColor("Heidelberg", "#FF4500")</code>, <code>chartWidget->SetLineStyle("Heidelberg", LineStyle::dashed)</code> and <code>chartWidget->SetShowDataPoints(false)</code>.
\note SetShowDataPoints is a global attribute and valid for all data entries due to technical reasons.
Colors are chosen automatically by plotly if not given. However, if some data entries have given colors and some have not, same colors may appear for different data entries. Color can be given as strings (natural names like <i>red</i> or hexadecimal numbers like \c \#FF0000 . For color selection, the following reference is helpful: https://www.w3schools.com/cssref/css_colors.asp)
Line style only can be set if ChartType is <code>QmitkChartWidget::ChartType::line</code>. It is ignored otherwise. Also, if a non-existing label is given, the command is ignored. The default linestyle is <code>LineStyle::solid</code>.
\section Chart_example Example
\subsection Chart_exampleBarChart Bar chart
To create and visualize a bar chart with two data sets, x/y-axis labels and data labels, the following code is used:
\code{.cpp}
std::vector<double> temperatureHD = {1.8, 3.1, 6.3, 10.2, 14.5, 17.4, 19.4, 18.9, 15.5, 11.2, 5.8, 2.6};
std::vector<double> temperatureOslo = {-4.3, -4, -0.2, 4.6, 10.8, 15.2, 16.4, 15.2, 10.8, 6.4, 0.7, -2.8};
chartWidget->AddData1D(temperatureHD, "Heidelberg", QmitkChartWidget::ChartType::bar);
chartWidget->AddData1D(temperatureOslo, "Oslo", QmitkChartWidget::ChartType::bar);
chartWidget->SetXAxisLabel("month");
chartWidget->SetYAxisLabel("temperature");
chartWidget->Show();
\endcode
The order when AddData1D() is called influences the colors of the bars and the order of the shown data. The third argument of <code>chartWidget->AddData1D()</code> is superfluous and only for completeness as <code>QmitkChartWidget::ChartType::bar</code> is the default chart type. After <code>Show()</code> is called, the chart is visualized.
The chart type for all data entries can be changed to spline and directly showed:
\code{.cpp}
chartWidget->SetChartTypeForAllDataAndReload(QmitkChartWidget::ChartType::spline);
\endcode
the equivalent code is:
\code{.cpp}
chartWidget->SetChartType("Heidelberg", QmitkChartWidget::ChartType::spline);
chartWidget->SetChartType("Oslo", QmitkChartWidget::ChartType::spline);
chartWidget->Show();
\endcode
The temperature of another city can be added:
\code{.cpp}
std::vector<double> temperatureRome = {8.1, 8.7, 8.7, 11.6, 18.8, 22.8, 25.4, 25.7, 21.4, 17.6, 12.6, 8.9};
chartWidget->AddData1D(temperatureRome, "Rome");
chartWidget->Show(true);
\endcode
As <code>Show(true)</code> is used, a subchart is shown.
\subsection Chart_examplePieChart Pie chart
A pie chart (the same as in \ref Chart_type ) can be generated with the following code:
\code{.cpp}
chartWidget->AddData1D({5}, "Heidelberg", QmitkChartWidget::ChartType::pie);
chartWidget->AddData1D({3}, "Oslo", QmitkChartWidget::ChartType::pie);
chartWidget->AddData1D({2}, "New York", QmitkChartWidget::ChartType::pie);
chartWidget->Show();
\endcode
\note Only one pie chart at a time can be displayed.
\subsection Chart_exampleMixedChart Mixed chart
Chart types and attributes like colors and line styles can be mixed as seen in the code example below (example result is the chart in \ref ChartModule_brief ):
\code{.cpp}
std::vector<double> temperatureHD = {1.8, 3.1, 6.3, 10.2, 14.5, 17.4, 19.4, 18.9, 15.5, 11.2, 5.8, 2.6};
std::vector<double> temperatureOslo = {-4.3, -4, -0.2, 4.6, 10.8, 15.2, 16.4, 15.2, 10.8, 6.4, 0.7, -2.8};
chartWidget->AddData1D(temperatureHD, "Heidelberg", QmitkChartWidget::ChartType::line);
chartWidget->AddData1D(temperatureOslo, "Oslo", QmitkChartWidget::ChartType::area);
chartWidget->SetColor("Heidelberg", "green");
chartWidget->SetColor("Oslo", "blue");
chartWidget->SetLineStyle("Heidelberg", QmitkChartWidget::LineStyle::dashed);
chartWidget->SetXAxisLabel("month");
chartWidget->SetYAxisLabel("temperature");
chartWidget->Show();
\endcode
\note Pie chart as chart type is an exception. Pie charts can't be displayed with other data entries having other chart types.
\subsection Chart_exampleRemoveData Removing data
Data also can be removed again (using the previous example \ref Chart_exampleMixedChart as base):
\code{.cpp}
chartWidget->RemoveData("Heidelberg");
chartWidget->Show();
\endcode
Only the date entries labeled "Oslo" remain.
Also all data can be removed:
\code{.cpp}
chartWidget->Clear();
chartWidget->Show();
\endcode
The chart is empty now.
\subsection Chart_example2DData Chart with 2D data
A line chart with two-dimensional data is the following example (the same as in \ref Chart_data ):
\code{.cpp}
std::map<double, double> peopleHD = { {1975, 129368 }, { 1985, 134724 },{ 1990, 136796 },{ 2010, 147312 } };
std::map<double, double> peopleFreiburg = { { 1969, 165960 },{ 1973, 174997 },{ 1982, 178545 },{ 2001, 208294 },{ 2015, 222203 } };
chartWidget->AddData2D(peopleHD, "Heidelberg", QmitkChartWidget::ChartType::line);
chartWidget->AddData2D(peopleFreiburg, "Freiburg", QmitkChartWidget::ChartType::line);
chartWidget->SetXAxisLabel("year");
chartWidget->SetYAxisLabel("people");
chartWidget->Show();
\endcode
Hence, 2D data is having the following assignment: year &rarr; people. In the vector peopleHD, four values are defined, in the vector peopleFreiburg, five values are defined. The defined years are different for Heidelberg (1975-2010) than for Freiburg (1969-2015).
\warning mixing AddData2D and AddData1D in a chart is strongly discouraged. It will work, however the visualization may be odd due to implicit and explicit given x values.
\subsection Chart_imageStatistics image statistics plugin
An example of the use of QmitkChartWidget in MITK can be found in the image statistics plugin. The \c chartWidget is named \c m_Controls->m_JSHistogram there.
*/
diff --git a/Modules/Chart/src/QmitkChartWidget.cpp b/Modules/Chart/src/QmitkChartWidget.cpp
index dff85d5543..543dd4dfce 100644
--- a/Modules/Chart/src/QmitkChartWidget.cpp
+++ b/Modules/Chart/src/QmitkChartWidget.cpp
@@ -1,940 +1,940 @@
/*============================================================================
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 <regex>
#include <QGridLayout>
#include <QWebChannel>
#include <QWebEngineSettings>
#include <QWebEngineView>
#include <QmitkChartWidget.h>
#include "mitkExceptionMacro.h"
#include <QmitkChartData.h>
#include <QmitkChartxyData.h>
class CustomPage : public QWebEnginePage
{
public:
CustomPage(QObject *parent = nullptr) : QWebEnginePage(parent) {}
virtual void javaScriptConsoleMessage(JavaScriptConsoleMessageLevel /*level*/,
const QString &message,
int lineNumber,
const QString & /*sourceID*/) override
{
MITK_INFO << "JS > " << lineNumber << ": " << message.toStdString();
}
};
class QmitkChartWidget::Impl final
{
public:
explicit Impl(QWidget *parent);
~Impl();
Impl(const Impl &) = delete;
Impl &operator=(const Impl &) = delete;
void AddData1D(const std::vector<double> &data1D, const std::string &label, QmitkChartWidget::ChartType chartType);
void AddData2D(const std::vector< std::pair<double, double> > &data2D,
const std::string &label,
QmitkChartWidget::ChartType chartType);
void AddChartExampleData(const std::vector< std::pair<double, double> >& data2D,
const std::string& label,
const std::string& type,
const std::string& color,
const std::string& style,
const std::string& pieLabelsData = 0);
void UpdateData1D(const std::vector<double> &data1D, const std::string &label);
void UpdateData2D(const std::vector< std::pair<double, double> > &data2D, const std::string &label);
void UpdateChartExampleData(const std::vector< std::pair<double, double> >& data2D,
const std::string& label,
const std::string& type,
const std::string& color,
const std::string& lineStyle,
const std::string& pieLabelsData = 0);
void RemoveData(const std::string &label);
void UpdateLabel(const std::string &existingLabel, const std::string &newLabel);
QmitkChartxyData* GetDataElementByLabel(const std::string& label) const;
void ClearData();
void SetColor(const std::string &label, const std::string &colorName);
void SetLineStyle(const std::string &label, LineStyle style);
void SetMarkerSymbol(const std::string &label, MarkerSymbol symbol);
void SetYAxisScale(AxisScale scale);
void SetXAxisLabel(const std::string &label);
void SetYAxisLabel(const std::string &label);
void SetPieLabels(const std::vector<std::string> &pieLabels, const std::string &label);
void SetTitle(const std::string &title);
void SetXErrorBars(const std::string &label,
const std::vector<double> &errorPlus,
const std::vector<double> &errorMinus = std::vector<double>());
void SetYErrorBars(const std::string &label,
const std::vector<double> &errorPlus,
const std::vector<double> &errorMinus = std::vector<double>());
std::string GetThemeName() const;
void SetThemeName(ColorTheme style);
void SetLegendPosition(LegendPosition position);
void Show(bool showSubChart);
void SetShowLegend(bool show);
void SetShowErrorBars(bool show);
void SetStackedData(bool stacked);
void SetShowDataPoints(bool showDataPoints = false);
void SetShowSubchart(bool showSubChart);
void SetChartType(const std::string &label, QmitkChartWidget::ChartType chartType);
void SetMinMaxValueXView(double minValueX, double maxValueX);
void SetMinMaxValueYView(double minValueY, double maxValueY);
QList<QVariant> ConvertErrorVectorToQList(const std::vector<double> &error);
QList<QVariant> ConvertVectorToQList(const std::vector<std::string> &vec);
std::string ConvertChartTypeToString(QmitkChartWidget::ChartType chartType) const;
void ClearJavaScriptChart();
void InitializeJavaScriptChart();
void CallJavaScriptFuntion(const QString &command);
QSize sizeHint() const;
void GetImageUrl();
private:
using ChartxyDataVector = std::vector<std::unique_ptr<QmitkChartxyData>>;
std::string GetUniqueLabelName(const QList<QVariant> &labelList, const std::string &label) const;
QList<QVariant> GetDataLabels(const ChartxyDataVector &c3xyData) const;
QWebChannel *m_WebChannel;
QWebEngineView *m_WebEngineView;
QmitkChartData m_C3Data;
ChartxyDataVector m_C3xyData;
std::map<QmitkChartWidget::ChartType, std::string> m_ChartTypeToName;
std::map<QmitkChartWidget::ChartColor, std::string> m_ChartColorToName;
std::map<QmitkChartWidget::ColorTheme, std::string> m_ColorThemeToName;
std::map<QmitkChartWidget::LegendPosition, std::string> m_LegendPositionToName;
std::map<QmitkChartWidget::LineStyle, std::string> m_LineStyleToName;
std::map<QmitkChartWidget::MarkerSymbol, std::string> m_MarkerSymbolToName;
std::map<QmitkChartWidget::AxisScale, std::string> m_AxisScaleToName;
};
QmitkChartWidget::Impl::Impl(QWidget *parent)
: m_WebChannel(new QWebChannel(parent)), m_WebEngineView(new QWebEngineView(parent))
{
// disable context menu for QWebEngineView
m_WebEngineView->setContextMenuPolicy(Qt::NoContextMenu);
m_WebEngineView->setPage(new CustomPage());
// Set the webengineview to an initial empty page. The actual chart will be loaded once the data is calculated.
m_WebEngineView->load(QUrl(QStringLiteral("qrc:///Chart/empty.html")));
m_WebEngineView->page()->setWebChannel(m_WebChannel);
m_WebEngineView->settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, false);
//This is added as a workarround for T28252 (https://phabricator.mitk.org/T28252)
//can be removed if task is properly fixed.
m_WebEngineView->settings()->setAttribute(QWebEngineSettings::ShowScrollBars, false);
connect(m_WebEngineView, SIGNAL(loadFinished(bool)), parent, SLOT(OnLoadFinished(bool)));
auto layout = new QGridLayout(parent);
- layout->setMargin(0);
+ layout->setContentsMargins({});
layout->addWidget(m_WebEngineView);
m_ChartTypeToName.emplace(ChartType::bar, "bar");
m_ChartTypeToName.emplace(ChartType::line, "line");
m_ChartTypeToName.emplace(ChartType::spline, "spline");
m_ChartTypeToName.emplace(ChartType::pie, "pie");
m_ChartTypeToName.emplace(ChartType::area, "area");
m_ChartTypeToName.emplace(ChartType::area_spline, "area-spline");
m_ChartTypeToName.emplace(ChartType::scatter, "scatter");
m_ChartColorToName.emplace(ChartColor::red, "red");
m_ChartColorToName.emplace(ChartColor::orange, "orange");
m_ChartColorToName.emplace(ChartColor::yellow, "yellow");
m_ChartColorToName.emplace(ChartColor::green, "green");
m_ChartColorToName.emplace(ChartColor::blue, "blue");
m_ChartColorToName.emplace(ChartColor::purple, "purple");
m_ChartColorToName.emplace(ChartColor::brown, "brown");
m_ChartColorToName.emplace(ChartColor::magenta, "magenta");
m_ChartColorToName.emplace(ChartColor::tan, "tan");
m_ChartColorToName.emplace(ChartColor::cyan, "cyan");
m_ChartColorToName.emplace(ChartColor::olive, "olive");
m_ChartColorToName.emplace(ChartColor::maroon, "maroon");
m_ChartColorToName.emplace(ChartColor::navy, "navy");
m_ChartColorToName.emplace(ChartColor::aquamarine, "aquamarine");
m_ChartColorToName.emplace(ChartColor::turqouise, "turqouise");
m_ChartColorToName.emplace(ChartColor::silver, "silver");
m_ChartColorToName.emplace(ChartColor::lime, "lime");
m_ChartColorToName.emplace(ChartColor::teal, "teal");
m_ChartColorToName.emplace(ChartColor::indigo, "indigo");
m_ChartColorToName.emplace(ChartColor::violet, "violet");
m_ChartColorToName.emplace(ChartColor::pink, "pink");
m_ChartColorToName.emplace(ChartColor::black, "black");
m_ChartColorToName.emplace(ChartColor::white, "white");
m_ChartColorToName.emplace(ChartColor::grey, "grey");
m_LegendPositionToName.emplace(LegendPosition::bottomMiddle, "bottomMiddle");
m_LegendPositionToName.emplace(LegendPosition::bottomRight, "bottomRight");
m_LegendPositionToName.emplace(LegendPosition::topRight, "topRight");
m_LegendPositionToName.emplace(LegendPosition::topLeft, "topLeft");
m_LegendPositionToName.emplace(LegendPosition::middleRight, "middleRight");
m_LineStyleToName.emplace(LineStyle::solid, "solid");
m_LineStyleToName.emplace(LineStyle::dashed, "dashed");
m_MarkerSymbolToName.emplace(MarkerSymbol::circle, "circle");
m_MarkerSymbolToName.emplace(MarkerSymbol::cross, "cross");
m_MarkerSymbolToName.emplace(MarkerSymbol::diamond, "diamond");
m_MarkerSymbolToName.emplace(MarkerSymbol::pentagon, "pentagon");
m_MarkerSymbolToName.emplace(MarkerSymbol::square, "square");
m_MarkerSymbolToName.emplace(MarkerSymbol::star, "star");
m_MarkerSymbolToName.emplace(MarkerSymbol::x, "x");
m_MarkerSymbolToName.emplace(MarkerSymbol::diamond_tall, "diamond-tall");
m_MarkerSymbolToName.emplace(MarkerSymbol::star_diamond, "star-diamond");
m_MarkerSymbolToName.emplace(MarkerSymbol::star_triangle_up, "star-triangle-up");
m_MarkerSymbolToName.emplace(MarkerSymbol::star_triangle_down, "star-triangle-down");
m_MarkerSymbolToName.emplace(MarkerSymbol::asterisk, "asterisk");
m_MarkerSymbolToName.emplace(MarkerSymbol::cross_thin, "cross-thin");
m_MarkerSymbolToName.emplace(MarkerSymbol::x_thin, "x-thin");
m_AxisScaleToName.emplace(AxisScale::linear, "");
m_AxisScaleToName.emplace(AxisScale::log, "log");
m_ColorThemeToName.emplace(ColorTheme::lightstyle, "light");
m_ColorThemeToName.emplace(ColorTheme::darkstyle, "dark");
}
QmitkChartWidget::Impl::~Impl() {}
std::string QmitkChartWidget::Impl::GetThemeName() const
{
return m_C3Data.GetThemeName().toString().toStdString();
}
std::string CheckForCorrectHex(const std::string &colorName)
{
std::regex rgx("([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})");
std::smatch match;
if (!colorName.empty() && colorName.at(0) != '#' && std::regex_search(colorName.begin(), colorName.end(), match, rgx))
{
return "#" + colorName;
}
else
{
return colorName;
}
}
void QmitkChartWidget::Impl::GetImageUrl()
{
m_C3Data.EmitSignalImageUrl();
}
void QmitkChartWidget::Impl::AddData1D(const std::vector<double> &data1D,
const std::string &label,
QmitkChartWidget::ChartType type)
{
std::vector< std::pair<double, double> > transformedData2D;
unsigned int count = 0;
// transform the 1D data to 2D data
for (const auto &ele : data1D)
{
transformedData2D.emplace_back(count, ele);
count++;
}
AddData2D(transformedData2D, label, type);
}
void QmitkChartWidget::Impl::AddData2D(const std::vector< std::pair<double, double> > &data2D,
const std::string &label,
QmitkChartWidget::ChartType type)
{
const std::string chartTypeName(m_ChartTypeToName.at(type));
auto definedLabels = GetDataLabels(m_C3xyData);
auto uniqueLabel = GetUniqueLabelName(definedLabels, label);
unsigned int sizeOfC3xyData = static_cast<unsigned int>(m_C3xyData.size());
m_C3xyData.push_back(std::make_unique<QmitkChartxyData>(data2D,
QVariant(QString::fromStdString(uniqueLabel)),
QVariant(QString::fromStdString(chartTypeName)),
QVariant(sizeOfC3xyData)));
}
void QmitkChartWidget::Impl::AddChartExampleData(const std::vector< std::pair<double, double> >& data2D,
const std::string& label,
const std::string& type,
const std::string& color,
const std::string& lineStyle,
const std::string& pieLabelsData)
{
auto definedLabels = GetDataLabels(m_C3xyData);
auto uniqueLabel = GetUniqueLabelName(definedLabels, label);
if (type == "scatter")
{
SetShowDataPoints(true);
MITK_INFO << "Enabling data points for all because of scatter plot";
}
unsigned int sizeOfC3xyData = static_cast<unsigned int>(m_C3xyData.size());
std::unique_ptr<QmitkChartxyData> chartData =
std::make_unique<QmitkChartxyData>(
data2D,
QVariant(QString::fromStdString(uniqueLabel)),
QVariant(QString::fromStdString(type)),
QVariant(sizeOfC3xyData));
chartData->SetColor(QVariant(QString::fromStdString(color)));
chartData->SetLineStyle(QVariant(QString::fromStdString(lineStyle)));
if (pieLabelsData != "")
{
std::string pieLabelsDataWorkingString = pieLabelsData;
QList<QVariant> pieLabelsDataList;
while (pieLabelsDataWorkingString.size() != 0)
{
QVariant oneElement = QString::fromStdString(pieLabelsDataWorkingString.substr(0, pieLabelsDataWorkingString.find(";")));
pieLabelsDataList.push_back(oneElement);
if (pieLabelsDataWorkingString.find(";") != std::string::npos)
{
pieLabelsDataWorkingString.erase(0, pieLabelsDataWorkingString.find(";") + 1);
}
else
{
pieLabelsDataWorkingString.erase(pieLabelsDataWorkingString.begin(), pieLabelsDataWorkingString.end());
}
}
chartData->SetPieLabels(pieLabelsDataList);
}
m_C3xyData.push_back(std::move(chartData));
}
void QmitkChartWidget::Impl::UpdateData1D(const std::vector<double> &data1D, const std::string &label)
{
std::vector< std::pair<double, double> > transformedData2D;
unsigned int count = 0;
// transform the 1D data to 2D data
for (const auto &ele : data1D)
{
transformedData2D.emplace_back( count, ele );
count++;
}
UpdateData2D(transformedData2D, label);
}
void QmitkChartWidget::Impl::UpdateData2D(const std::vector< std::pair<double, double> > &data2D, const std::string &label)
{
auto element = GetDataElementByLabel(label);
if (element)
element->SetData(data2D);
}
void QmitkChartWidget::Impl::UpdateChartExampleData(const std::vector< std::pair<double, double> >& data2D,
const std::string& label,
const std::string& type,
const std::string& color,
const std::string& lineStyle,
const std::string& pieLabelsData)
{
UpdateData2D(data2D, label);
auto element = GetDataElementByLabel(label);
if (element)
{
element->SetChartType(QString::fromStdString(type));
element->SetColor(QString::fromStdString(color));
element->SetLineStyle(QString::fromStdString(lineStyle));
if (pieLabelsData != "")
{
std::string pieLabelsDataWorkingString = pieLabelsData;
QList<QVariant> pieLabelsDataList;
while (pieLabelsDataWorkingString.size() != 0)
{
QVariant oneElement = QString::fromStdString(pieLabelsDataWorkingString.substr(0, pieLabelsDataWorkingString.find(";")));
pieLabelsDataList.push_back(oneElement);
if (pieLabelsDataWorkingString.find(";") != std::string::npos)
{
pieLabelsDataWorkingString.erase(0, pieLabelsDataWorkingString.find(";") + 1);
}
else
{
pieLabelsDataWorkingString.erase(pieLabelsDataWorkingString.begin(), pieLabelsDataWorkingString.end());
}
}
element->SetPieLabels(pieLabelsDataList);
}
}
}
void QmitkChartWidget::Impl::RemoveData(const std::string &label)
{
for (ChartxyDataVector::iterator iter = m_C3xyData.begin(); iter != m_C3xyData.end(); ++iter)
{
if ((*iter)->GetLabel().toString().toStdString() == label)
{
m_C3xyData.erase(iter);
return;
}
}
throw std::invalid_argument("Cannot Remove Data because the label does not exist.");
}
void QmitkChartWidget::Impl::ClearData()
{
for (auto &xyData : m_C3xyData)
{
m_WebChannel->deregisterObject(xyData.get());
}
m_C3xyData.clear();
}
void QmitkChartWidget::Impl::UpdateLabel(const std::string &existingLabel, const std::string &newLabel) {
auto element = GetDataElementByLabel(existingLabel);
if (element)
{
auto definedLabels = GetDataLabels(m_C3xyData);
auto uniqueLabel = GetUniqueLabelName(definedLabels, newLabel);
element->SetLabel(QString::fromStdString(uniqueLabel));
}
}
void QmitkChartWidget::Impl::SetColor(const std::string &label, const std::string &colorName)
{
auto element = GetDataElementByLabel(label);
if (element)
{
auto colorChecked = CheckForCorrectHex(colorName);
element->SetColor(QVariant(QString::fromStdString(colorChecked)));
}
}
void QmitkChartWidget::Impl::SetLineStyle(const std::string &label, LineStyle style)
{
auto element = GetDataElementByLabel(label);
const std::string lineStyleName(m_LineStyleToName.at(style));
element->SetLineStyle(QVariant(QString::fromStdString(lineStyleName)));
}
void QmitkChartWidget::Impl::SetMarkerSymbol(const std::string &label, MarkerSymbol symbol)
{
auto element = GetDataElementByLabel(label);
const std::string markerSymbolName(m_MarkerSymbolToName.at(symbol));
element->SetMarkerSymbol(QVariant(QString::fromStdString(markerSymbolName)));
}
void QmitkChartWidget::Impl::SetYAxisScale(AxisScale scale)
{
const std::string axisScaleName(m_AxisScaleToName.at(scale));
m_C3Data.SetYAxisScale(QString::fromStdString(axisScaleName));
}
QmitkChartxyData *QmitkChartWidget::Impl::GetDataElementByLabel(const std::string &label) const
{
for (const auto &qmitkChartxyData : m_C3xyData)
{
if (qmitkChartxyData->GetLabel().toString() == label.c_str())
{
return qmitkChartxyData.get();
}
}
return nullptr;
}
QList<QVariant> QmitkChartWidget::Impl::GetDataLabels(const ChartxyDataVector &c3xyData) const
{
QList<QVariant> dataLabels;
for (auto element = c3xyData.begin(); element != c3xyData.end(); ++element)
{
dataLabels.push_back((*element)->GetLabel());
}
return dataLabels;
}
void QmitkChartWidget::Impl::SetXAxisLabel(const std::string &label)
{
m_C3Data.SetXAxisLabel(QString::fromStdString(label));
}
void QmitkChartWidget::Impl::SetYAxisLabel(const std::string &label)
{
m_C3Data.SetYAxisLabel(QString::fromStdString(label));
}
void QmitkChartWidget::Impl::SetPieLabels(const std::vector<std::string> &pieLabels, const std::string &label)
{
auto element = GetDataElementByLabel(label);
if (element)
{
if (element->GetChartType() == QVariant("pie"))
{
auto dataY = element->GetYData();
element->SetPieLabels(ConvertVectorToQList(pieLabels));
if (static_cast<unsigned>(dataY.size()) != pieLabels.size())
{
MITK_INFO << "data has " << dataY.size() << " entries whereas pie labels have " << pieLabels.size()
<< " entries. Unnamed pie labels automatically get a numerical label.";
}
}
else
{
MITK_INFO << "label" << label << "has chart type " << element->GetChartType().toString().toStdString() << ", but pie is required";
}
}
}
void QmitkChartWidget::Impl::SetTitle(const std::string &title)
{
m_C3Data.SetTitle(QString::fromStdString(title));
}
void QmitkChartWidget::Impl::SetThemeName(QmitkChartWidget::ColorTheme style)
{
const std::string themeName(m_ColorThemeToName.at(style));
m_C3Data.SetThemeName(QString::fromStdString(themeName));
}
void QmitkChartWidget::Impl::SetLegendPosition(QmitkChartWidget::LegendPosition legendPosition)
{
const std::string legendPositionName(m_LegendPositionToName.at(legendPosition));
m_C3Data.SetLegendPosition(QString::fromStdString(legendPositionName));
}
void QmitkChartWidget::Impl::Show(bool showSubChart)
{
if (m_C3xyData.empty())
{
MITK_WARN << "no data available for display in chart";
}
else
{
m_C3Data.SetAppearance(showSubChart, m_C3xyData.front()->GetChartType() == QVariant("pie"));
}
InitializeJavaScriptChart();
}
void QmitkChartWidget::Impl::SetShowLegend(bool show)
{
m_C3Data.SetShowLegend(show);
}
void QmitkChartWidget::Impl::SetStackedData(bool stacked)
{
m_C3Data.SetStackedData(stacked);
}
void QmitkChartWidget::Impl::SetShowErrorBars(bool show)
{
m_C3Data.SetShowErrorBars(show);
}
void QmitkChartWidget::Impl::SetShowDataPoints(bool showDataPoints)
{
if (showDataPoints == true)
{
m_C3Data.SetDataPointSize(6.5);
}
else
{
m_C3Data.SetDataPointSize(0);
}
}
void QmitkChartWidget::Impl::SetShowSubchart(bool showSubChart) {
m_C3Data.SetShowSubchart(showSubChart);
}
void QmitkChartWidget::Impl::SetChartType(const std::string &label, QmitkChartWidget::ChartType chartType)
{
auto element = GetDataElementByLabel(label);
if (element)
{
if (chartType == ChartType::scatter)
{
SetShowDataPoints(true);
MITK_INFO << "Enabling data points for all because of scatter plot";
}
const std::string chartTypeName(m_ChartTypeToName.at(chartType));
element->SetChartType(QVariant(QString::fromStdString(chartTypeName)));
}
}
void QmitkChartWidget::Impl::SetMinMaxValueXView(double minValueX, double maxValueX) {
m_C3Data.SetMinValueXView(minValueX);
m_C3Data.SetMaxValueXView(maxValueX);
}
void QmitkChartWidget::Impl::SetMinMaxValueYView(double minValueY, double maxValueY) {
m_C3Data.SetMinValueYView(minValueY);
m_C3Data.SetMaxValueYView(maxValueY);
}
QList<QVariant> QmitkChartWidget::Impl::ConvertErrorVectorToQList(const std::vector<double> &error)
{
QList<QVariant> errorConverted;
for (const auto &aValue : error)
{
errorConverted.append(aValue);
}
return errorConverted;
}
QList<QVariant> QmitkChartWidget::Impl::ConvertVectorToQList(const std::vector<std::string> &vec)
{
QList<QVariant> vecConverted;
for (const auto &aValue : vec)
{
vecConverted.append(QString::fromStdString(aValue));
}
return vecConverted;
}
void QmitkChartWidget::Impl::SetXErrorBars(const std::string &label,
const std::vector<double> &errorPlus,
const std::vector<double> &errorMinus)
{
auto element = GetDataElementByLabel(label);
if (element)
{
auto errorConvertedPlus = ConvertErrorVectorToQList(errorPlus);
auto errorConvertedMinus = ConvertErrorVectorToQList(errorMinus);
element->SetXErrorDataPlus(errorConvertedPlus);
element->SetXErrorDataMinus(errorConvertedMinus);
}
}
void QmitkChartWidget::Impl::SetYErrorBars(const std::string &label,
const std::vector<double> &errorPlus,
const std::vector<double> &errorMinus)
{
auto element = GetDataElementByLabel(label);
if (element)
{
auto errorConvertedPlus = ConvertErrorVectorToQList(errorPlus);
auto errorConvertedMinus = ConvertErrorVectorToQList(errorMinus);
element->SetYErrorDataPlus(errorConvertedPlus);
element->SetYErrorDataMinus(errorConvertedMinus);
}
}
std::string QmitkChartWidget::Impl::ConvertChartTypeToString(QmitkChartWidget::ChartType chartType) const
{
return m_ChartTypeToName.at(chartType);
}
QSize QmitkChartWidget::Impl::sizeHint() const
{
return QSize(400, 300);
}
void QmitkChartWidget::Impl::CallJavaScriptFuntion(const QString &command)
{
m_WebEngineView->page()->runJavaScript(command);
}
void QmitkChartWidget::Impl::ClearJavaScriptChart()
{
m_WebEngineView->load(QUrl(QStringLiteral("qrc:///Chart/empty.html")));
}
void QmitkChartWidget::Impl::InitializeJavaScriptChart()
{
auto alreadyRegisteredObjects = m_WebChannel->registeredObjects();
auto alreadyRegisteredObjectsValues = alreadyRegisteredObjects.values();
// only register objects that have not been registered yet
if (alreadyRegisteredObjectsValues.indexOf(&m_C3Data) == -1)
{
m_WebChannel->registerObject(QStringLiteral("chartData"), &m_C3Data);
}
unsigned count = 0;
for (auto &xyData : m_C3xyData)
{
// only register objects that have not been registered yet
if (alreadyRegisteredObjectsValues.indexOf(xyData.get()) == -1)
{
QString variableName = "xyData" + QString::number(count);
m_WebChannel->registerObject(variableName, xyData.get());
}
count++;
}
m_WebEngineView->load(QUrl(QStringLiteral("qrc:///Chart/QmitkChartWidget.html")));
}
std::string QmitkChartWidget::Impl::GetUniqueLabelName(const QList<QVariant> &labelList, const std::string &label) const
{
QString currentLabel = QString::fromStdString(label);
int counter = 0;
while (labelList.contains(currentLabel))
{
currentLabel = QString::fromStdString(label + std::to_string(counter));
counter++;
}
return currentLabel.toStdString();
}
QmitkChartWidget::QmitkChartWidget(QWidget *parent) : QWidget(parent), m_Impl(new Impl(this))
{
connect(this, &QmitkChartWidget::PageSuccessfullyLoaded, this, &QmitkChartWidget::OnPageSuccessfullyLoaded);
}
QmitkChartWidget::~QmitkChartWidget() {}
void QmitkChartWidget::SetColor(const std::string &label, const std::string &colorName)
{
m_Impl->SetColor(label, colorName);
}
void QmitkChartWidget::SetLineStyle(const std::string &label, LineStyle style)
{
m_Impl->SetLineStyle(label, style);
}
void QmitkChartWidget::SetMarkerSymbol(const std::string &label, MarkerSymbol symbol)
{
m_Impl->SetMarkerSymbol(label, symbol);
}
void QmitkChartWidget::SetYAxisScale(AxisScale scale)
{
m_Impl->SetYAxisScale(scale);
}
void QmitkChartWidget::AddData1D(const std::vector<double> &data1D, const std::string &label, ChartType type)
{
m_Impl->AddData1D(data1D, label, type);
}
void QmitkChartWidget::AddData2D(const std::vector< std::pair<double, double> >& data2D, const std::string& label, ChartType type)
{
m_Impl->AddData2D(data2D, label, type);
}
void QmitkChartWidget::AddChartExampleData(const std::vector< std::pair<double, double> >& data2D,
const std::string& label,
const std::string& type,
const std::string& color,
const std::string& lineStyle,
const std::string& pieLabelsData)
{
m_Impl->AddChartExampleData(data2D, label, type, color, lineStyle, pieLabelsData);
}
void QmitkChartWidget::UpdateData1D(const std::vector<double> &data1D, const std::string &label)
{
m_Impl->UpdateData1D(data1D, label);
}
void QmitkChartWidget::UpdateData2D(const std::vector< std::pair<double, double> > &data2D, const std::string &label)
{
m_Impl->UpdateData2D(data2D, label);
}
void QmitkChartWidget::UpdateChartExampleData(const std::vector< std::pair<double, double> >& data2D,
const std::string& label,
const std::string& type,
const std::string& color,
const std::string& lineStyle,
const std::string& pieLabelsData)
{
m_Impl->UpdateChartExampleData(data2D, label, type, color, lineStyle, pieLabelsData);
}
void QmitkChartWidget::RemoveData(const std::string &label)
{
m_Impl->RemoveData(label);
}
void QmitkChartWidget::UpdateLabel(const std::string &existingLabel, const std::string &newLabel) {
m_Impl->UpdateLabel(existingLabel, newLabel);
}
QmitkChartxyData* QmitkChartWidget::GetDataElementByLabel(const std::string& label) const
{
return m_Impl->GetDataElementByLabel(label);
}
void QmitkChartWidget::SetXAxisLabel(const std::string &label)
{
m_Impl->SetXAxisLabel(label);
}
void QmitkChartWidget::SetYAxisLabel(const std::string &label)
{
m_Impl->SetYAxisLabel(label);
}
void QmitkChartWidget::SetPieLabels(const std::vector<std::string> &pieLabels, const std::string &label)
{
m_Impl->SetPieLabels(pieLabels, label);
}
void QmitkChartWidget::SetTitle(const std::string &title)
{
m_Impl->SetTitle(title);
}
void QmitkChartWidget::SetShowDataPoints(bool showDataPoints)
{
m_Impl->SetShowDataPoints(showDataPoints);
}
void QmitkChartWidget::SetChartType(const std::string &label, ChartType type)
{
m_Impl->SetChartType(label, type);
}
void QmitkChartWidget::SetXErrorBars(const std::string &label,
const std::vector<double> &errorPlus,
const std::vector<double> &errorMinus)
{
m_Impl->SetXErrorBars(label, errorPlus, errorMinus);
}
void QmitkChartWidget::SetYErrorBars(const std::string &label,
const std::vector<double> &errorPlus,
const std::vector<double> &errorMinus)
{
m_Impl->SetYErrorBars(label, errorPlus, errorMinus);
}
void QmitkChartWidget::SetLegendPosition(LegendPosition position)
{
m_Impl->SetLegendPosition(position);
}
void QmitkChartWidget::SetShowLegend(bool show)
{
m_Impl->SetShowLegend(show);
}
void QmitkChartWidget::SetStackedData(bool stacked)
{
m_Impl->SetStackedData(stacked);
}
void QmitkChartWidget::Show(bool showSubChart)
{
m_Impl->Show(showSubChart);
}
void QmitkChartWidget::Clear()
{
m_Impl->ClearData();
m_Impl->ClearJavaScriptChart();
}
void QmitkChartWidget::OnLoadFinished(bool isLoadSuccessful)
{
if (isLoadSuccessful)
{
emit PageSuccessfullyLoaded();
}
}
void QmitkChartWidget::OnPageSuccessfullyLoaded()
{
auto themeName = m_Impl->GetThemeName();
QString command;
if (themeName == "dark")
{
command = QString("changeTheme('dark')");
}
else
{
command = QString("changeTheme('light')");
}
m_Impl->CallJavaScriptFuntion(command);
}
void QmitkChartWidget::SetTheme(ColorTheme themeEnabled)
{
m_Impl->SetThemeName(themeEnabled);
}
void QmitkChartWidget::SetShowSubchart(bool showSubChart)
{
m_Impl->SetShowSubchart(showSubChart);
}
void QmitkChartWidget::SetShowErrorBars(bool showErrorBars)
{
m_Impl->SetShowErrorBars(showErrorBars);
}
void QmitkChartWidget::SetMinMaxValueXView(double minValueX, double maxValueX)
{
m_Impl->SetMinMaxValueXView(minValueX, maxValueX);
}
void QmitkChartWidget::SetMinMaxValueYView(double minValueY, double maxValueY)
{
m_Impl->SetMinMaxValueYView(minValueY, maxValueY);
}
void QmitkChartWidget::Reload()
{
const QString command = QString("Reload()");
m_Impl->CallJavaScriptFuntion(command);
}
QSize QmitkChartWidget::sizeHint() const
{
return m_Impl->sizeHint();
}
void QmitkChartWidget::SavePlotAsImage()
{
m_Impl->GetImageUrl();
}
diff --git a/Modules/Chart/src/mitkChartExampleTestHelper.cpp b/Modules/Chart/src/mitkChartExampleTestHelper.cpp
index 06bebf4bb2..50e8fed921 100644
--- a/Modules/Chart/src/mitkChartExampleTestHelper.cpp
+++ b/Modules/Chart/src/mitkChartExampleTestHelper.cpp
@@ -1,353 +1,353 @@
/*============================================================================
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 "mitkChartExampleTestHelper.h"
// std includes
#include <string>
std::unique_ptr<QmitkChartxyData> mitk::ChartExampleTestHelper::GetDataOne()
{
auto myDataOne = std::make_unique<QmitkChartxyData>();
std::vector< std::pair<double, double> > data;
for (int i = 0; i < 10; i++)
{
data.emplace_back(i, i);
}
myDataOne->SetData(data);
myDataOne->SetLabel("DataOne");
myDataOne->SetChartType("bar");
myDataOne->SetColor("red");
myDataOne->SetLineStyle("solid");
return myDataOne;
}
std::unique_ptr<QmitkChartxyData> mitk::ChartExampleTestHelper::GetDataTwo()
{
auto myDataTwo = std::make_unique<QmitkChartxyData>();
std::vector< std::pair<double, double> > data;
for (int i = 10; i < 20; i++)
{
data.emplace_back(i, i);
}
myDataTwo->SetData(data);
myDataTwo->SetLabel("DataTwo");
myDataTwo->SetChartType("bar");
myDataTwo->SetColor("green");
myDataTwo->SetLineStyle("solid");
return myDataTwo;
}
std::unique_ptr<QmitkChartxyData> mitk::ChartExampleTestHelper::GetDataThree()
{
auto myDataThree = std::make_unique<QmitkChartxyData>();
std::vector< std::pair<double, double> > data;
for (int i = 20; i < 30; i++)
{
data.emplace_back(i, i);
}
myDataThree->SetData(data);
myDataThree->SetLabel("DataThree");
myDataThree->SetChartType("bar");
myDataThree->SetColor("blue");
myDataThree->SetLineStyle("solid");
return myDataThree;
}
std::unique_ptr<QmitkChartxyData> mitk::ChartExampleTestHelper::GetDataFour()
{
auto myDataFour = std::make_unique<QmitkChartxyData>();
std::vector< std::pair<double, double> > data;
for (int i = 30; i < 40; i++)
{
data.emplace_back(i, i);
}
myDataFour->SetData(data);
myDataFour->SetLabel("DataFour");
myDataFour->SetChartType("bar");
myDataFour->SetColor("yellow");
myDataFour->SetLineStyle("solid");
return myDataFour;
}
std::unique_ptr<QmitkChartxyData> mitk::ChartExampleTestHelper::GetDataFive()
{
auto myDataFive = std::make_unique<QmitkChartxyData>();
std::vector< std::pair<double, double> > data;
for (int i = 40; i < 50; i++)
{
data.emplace_back(i, i);
}
myDataFive->SetData(data);
myDataFive->SetLabel("DataFive");
myDataFive->SetChartType("bar");
myDataFive->SetColor("black");
myDataFive->SetLineStyle("solid");
return myDataFive;
}
QmitkChartWidget::ChartType mitk::ChartExampleTestHelper::ReturnChartTypeByString(std::string chartTypeString)
{
if (chartTypeString == "bar")
{
return QmitkChartWidget::ChartType::bar;
}
if (chartTypeString == "line")
{
return QmitkChartWidget::ChartType::line;
}
if (chartTypeString == "spline")
{
return QmitkChartWidget::ChartType::spline;
}
if (chartTypeString == "pie")
{
return QmitkChartWidget::ChartType::pie;
}
if (chartTypeString == "area")
{
return QmitkChartWidget::ChartType::area;
}
if (chartTypeString == "area_spline")
{
return QmitkChartWidget::ChartType::area_spline;
}
if (chartTypeString == "scatter")
{
return QmitkChartWidget::ChartType::scatter;
}
return QmitkChartWidget::ChartType::bar;
}
QmitkChartWidget::ChartColor mitk::ChartExampleTestHelper::ReturnChartColorByString(std::string chartColorString)
{
if (chartColorString == "red")
{
return QmitkChartWidget::ChartColor::red;
}
if (chartColorString == "orange")
{
return QmitkChartWidget::ChartColor::orange;
}
if (chartColorString == "yellow")
{
return QmitkChartWidget::ChartColor::yellow;
}
if (chartColorString == "green")
{
return QmitkChartWidget::ChartColor::green;
}
if (chartColorString == "blue")
{
return QmitkChartWidget::ChartColor::blue;
}
if (chartColorString == "purple")
{
return QmitkChartWidget::ChartColor::purple;
}
if (chartColorString == "brown")
{
return QmitkChartWidget::ChartColor::brown;
}
if (chartColorString == "magenta")
{
return QmitkChartWidget::ChartColor::magenta;
}
if (chartColorString == "tan")
{
return QmitkChartWidget::ChartColor::tan;
}
if (chartColorString == "cyan")
{
return QmitkChartWidget::ChartColor::cyan;
}
if (chartColorString == "olive")
{
return QmitkChartWidget::ChartColor::olive;
}
if (chartColorString == "maroon")
{
return QmitkChartWidget::ChartColor::maroon;
}
if (chartColorString == "navy")
{
return QmitkChartWidget::ChartColor::navy;
}
if (chartColorString == "aquamarine")
{
return QmitkChartWidget::ChartColor::aquamarine;
}
if (chartColorString == "turqouise")
{
return QmitkChartWidget::ChartColor::turqouise;
}
if (chartColorString == "silver")
{
return QmitkChartWidget::ChartColor::silver;
}
if (chartColorString == "lime")
{
return QmitkChartWidget::ChartColor::lime;
}
if (chartColorString == "teal")
{
return QmitkChartWidget::ChartColor::teal;
}
if (chartColorString == "indigo")
{
return QmitkChartWidget::ChartColor::indigo;
}
if (chartColorString == "violet")
{
return QmitkChartWidget::ChartColor::violet;
}
if (chartColorString == "pink")
{
return QmitkChartWidget::ChartColor::pink;
}
if (chartColorString == "black")
{
return QmitkChartWidget::ChartColor::black;
}
if (chartColorString == "white")
{
return QmitkChartWidget::ChartColor::white;
}
if (chartColorString == "grey")
{
return QmitkChartWidget::ChartColor::grey;
}
return QmitkChartWidget::ChartColor::red;
}
QmitkChartWidget::LineStyle mitk::ChartExampleTestHelper::ReturnChartStyleByString(std::string chartStyleString)
{
if (chartStyleString == "solid")
{
return QmitkChartWidget::LineStyle::solid;
}
if (chartStyleString == "dashed")
{
return QmitkChartWidget::LineStyle::dashed;
}
return QmitkChartWidget::LineStyle::solid;
}
void mitk::ChartExampleTestHelper::Add(int dataSet)
{
std::unique_ptr<QmitkChartxyData> myData;
if (dataSet == 1)
{
myData = mitk::ChartExampleTestHelper::GetDataOne();
}
if (dataSet == 2)
{
myData = mitk::ChartExampleTestHelper::GetDataTwo();
}
if (dataSet == 3)
{
myData = mitk::ChartExampleTestHelper::GetDataThree();
}
if (dataSet == 4)
{
myData = mitk::ChartExampleTestHelper::GetDataFour();
}
if (dataSet == 5)
{
myData = mitk::ChartExampleTestHelper::GetDataFive();
}
std::vector< std::pair<double, double> > data = mitk::ChartExampleTestHelper::ToStdPairList(myData->GetXData(), myData->GetYData());
auto label = myData->GetLabel().toString().toStdString();
auto type = myData->GetChartType().toString().toStdString();
auto color = myData->GetColor().toString().toStdString();
auto style = myData->GetLineStyle().toString().toStdString();
qmitkChartWidget.AddChartExampleData(data, label, type, color, style);
}
std::vector< std::pair<double, double> > mitk::ChartExampleTestHelper::ToStdPairList(QVariantList xData, QVariantList yData)
{
- auto xDataConverted = xData.toVector().toStdVector();
- auto yDataConverted = yData.toVector().toStdVector();
+ std::vector<QVariant> xDataConverted(xData.begin(), xData.end());
+ std::vector<QVariant> yDataConverted(yData.begin(), yData.end());
std::vector< std::pair<double, double> > data;
for (size_t i = 0; i < xDataConverted.size(); i++)
{
data.emplace_back(xDataConverted[i].toDouble(), yDataConverted[i].toDouble());
}
return data;
}
void mitk::ChartExampleTestHelper::ClearMemory()
{
// Clear the vector
qmitkChartWidget.Clear();
}
diff --git a/Modules/Core/include/mitkPlaneGeometryDataToSurfaceFilter.h b/Modules/Core/include/mitkPlaneGeometryDataToSurfaceFilter.h
index 35a6e6b779..6f66b14c63 100644
--- a/Modules/Core/include/mitkPlaneGeometryDataToSurfaceFilter.h
+++ b/Modules/Core/include/mitkPlaneGeometryDataToSurfaceFilter.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 mitkPlaneGeometryDataToSurfaceFilter_h
#define mitkPlaneGeometryDataToSurfaceFilter_h
#include "mitkGeometry3D.h"
#include "mitkSurfaceSource.h"
#include "vtkSystemIncludes.h"
class vtkPlaneSource;
class vtkTransformPolyDataFilter;
class vtkCubeSource;
class vtkTransform;
class vtkPlane;
class vtkCutter;
-class vtkStripper;
class vtkPolyData;
class vtkPPolyDataNormals;
-class vtkTriangleFilter;
class vtkTextureMapToPlane;
class vtkBox;
class vtkClipPolyData;
+class vtkContourTriangulator;
namespace mitk
{
class PlaneGeometryData;
class PlaneGeometryDataToSurfaceFilter;
/** \deprecatedSince{2014_10} This class is deprecated. Please use PlaneGeometryDataToSurfaceFilter instead. */
DEPRECATED(typedef PlaneGeometryDataToSurfaceFilter Geometry2DDataToSurfaceFilter);
/** \brief Superclass of all classes having a PlaneGeometryData as input and
* generating Images as output
*
* Currently implemented for PlaneGeometry and AbstractTransformGeometry.
* Currently, this class does not really have subclasses, but does the job
* for itself. It checks which kind of PlaneGeometry is stored in the
* PlaneGeometryData and - if it knows how - it generates the respective
* Surface. Of course, this has the disadvantage that for any new type of
* PlaneGeometry this class (PlaneGeometryDataToSurfaceFilter) has to be
* changed/extended. The idea is to move the type specific generation code in
* subclasses, and internally (within this class) use a factory to create an
* instance of the required subclass and delegate the surface generation to
* it.
*
* \sa mitk::DeformablePlane
* \todo make extension easier
* \ingroup Process
*/
class MITKCORE_EXPORT PlaneGeometryDataToSurfaceFilter : public SurfaceSource
{
public:
mitkClassMacro(PlaneGeometryDataToSurfaceFilter, SurfaceSource);
itkFactorylessNewMacro(Self);
itkCloneMacro(Self);
void GenerateOutputInformation() override;
void GenerateData() override;
const PlaneGeometryData *GetInput(void);
const PlaneGeometryData *GetInput(unsigned int idx);
virtual void SetInput(const PlaneGeometryData *image);
using itk::ProcessObject::SetInput;
virtual void SetInput(unsigned int index, const PlaneGeometryData *image);
/** \brief If \a true (default), use Geometry3D::GetParametricBounds() to define the resolution in parameter space,
* otherwise use m_XResolution and m_YResolution
*/
itkGetMacro(UseGeometryParametricBounds, bool);
/** \brief If \a true (default), use Geometry3D::GetParametricBounds() to define the resolution in parameter space,
* otherwise use m_XResolution and m_YResolution
*/
itkSetMacro(UseGeometryParametricBounds, bool);
/** \brief Get x-resolution in parameter space
*
* The m_PlaneSource will create this many sub-rectangles
* in x-direction (see vtkPlaneSource::SetXResolution)
* \note Only used, when GetUseGeometryParametricBounds() is \a false, otherwise the
* the x-bounds of Geometry3D::GetParametricBounds() are used.
* \sa m_XResolution
*/
itkGetMacro(XResolution, int);
/** \brief Set x-resolution in parameter space
*
* The m_PlaneSource will create this many sub-rectangles
* in x-direction (see vtkPlaneSource::SetXResolution)
* \note Only used, when GetUseGeometryParametricBounds() is \a false, otherwise the
* the x-bounds of Geometry3D::GetParametricBounds() are used.
* \sa m_XResolution
*/
itkSetMacro(XResolution, int);
/** \brief Get y-resolution in parameter space
*
* The m_PlaneSource will create this many sub-rectangles
* in y-direction (see vtkPlaneSource::SetYResolution)
* \note Only used, when GetUseGeometryParametricBounds() is \a false, otherwise the
* the y-bounds of Geometry3D::GetParametricBounds() are used.
* \sa m_YResolution
*/
itkGetMacro(YResolution, int);
/** \brief Set y-resolution in parameter space
*
* The m_PlaneSource will create this many sub-rectangles
* in y-direction (see vtkPlaneSource::SetYResolution)
* \note Only used, when GetUseGeometryParametricBounds() is \a false, otherwise the
* the y-bounds of Geometry3D::GetParametricBounds() are used.
* \sa m_YResolution
*/
itkSetMacro(YResolution, int);
/** \brief Get whether the Surface is at the origin and placed using the Geometry
*
* Default is \a false, i.e., the transform of the Geometry is the identity, thus
* the points within the Surface are at their final position. Otherwise
* (m_PlaceByGeometry==\a true), the first cornerpoint of the created Surface is
* at the origin and the actual position is determined by the transform of the
* Geometry.
* \sa m_PlaceByGeometry
*/
itkGetConstMacro(PlaceByGeometry, bool);
/** \brief Set whether the Surface is at the origin and placed using the Geometry
*
* Default is \a false, i.e., the transform of the Geometry is the identity, thus
* the points within the Surface are at their final position. Otherwise
* (m_PlaceByGeometry==\a true), the first cornerpoint of the created Surface is
* at the origin and the actual position is determined by the transform of the
* Geometry.
* \sa m_PlaceByGeometry
*/
itkSetMacro(PlaceByGeometry, bool);
itkBooleanMacro(PlaceByGeometry);
itkGetConstMacro(UseBoundingBox, bool);
itkSetMacro(UseBoundingBox, bool);
itkBooleanMacro(UseBoundingBox);
void SetBoundingBox(const BoundingBox *boundingBox);
const BoundingBox *GetBoundingBox() const;
protected:
PlaneGeometryDataToSurfaceFilter();
~PlaneGeometryDataToSurfaceFilter() override;
/** \brief Source to create the vtk-representation of the parameter space rectangle of the PlaneGeometry
*/
vtkPlaneSource *m_PlaneSource;
/** \brief Filter to create the vtk-representation of the PlaneGeometry, which is a
* transformation of the m_PlaneSource
*/
vtkTransformPolyDataFilter *m_VtkTransformPlaneFilter;
/** \brief If \a true, use Geometry3D::GetParametricBounds() to define the resolution in parameter space,
* otherwise use m_XResolution and m_YResolution
*/
bool m_UseGeometryParametricBounds;
/** \brief X-resolution in parameter space
*
* The m_PlaneSource will create this many sub-rectangles
* in x-direction (see vtkPlaneSource::SetXResolution)
* \note Only used, when GetUseGeometryParametricBounds() is \a false, otherwise the
* the x-bounds of Geometry3D::GetParametricBounds() are used.
* \sa m_XResolution
*/
int m_XResolution;
/** \brief Y-resolution in parameter space
*
* The m_PlaneSource will create this many sub-rectangles
* in y-direction (see vtkPlaneSource::SetYResolution)
* \note Only used, when GetUseGeometryParametricBounds() is \a false, otherwise the
* the y-bounds of Geometry3D::GetParametricBounds() are used.
*/
int m_YResolution;
/** \brief Define whether the Surface is at the origin and placed using the Geometry
*
* Default is \a false, i.e., the transform of the Geometry is the identity, thus
* the points within the Surface are at their final position. Otherwise
* (m_PlaceByGeometry==\a true), the first cornerpoint of the created Surface is
* at the origin and the actual position is determined by the transform of the
* Geometry.
*/
bool m_PlaceByGeometry;
bool m_UseBoundingBox;
BoundingBox::ConstPointer m_BoundingBox;
vtkCubeSource *m_CubeSource;
vtkTransform *m_Transform;
vtkTransformPolyDataFilter *m_PolyDataTransformer;
vtkPlane *m_Plane;
vtkCutter *m_PlaneCutter;
- vtkStripper *m_PlaneStripper;
- vtkPolyData *m_PlanePolyData;
+ vtkContourTriangulator *m_ContourTriangulator;
vtkPPolyDataNormals *m_NormalsUpdater;
- vtkTriangleFilter *m_PlaneTriangler;
vtkTextureMapToPlane *m_TextureMapToPlane;
vtkBox *m_Box;
vtkClipPolyData *m_PlaneClipper;
};
} // namespace mitk
#endif
diff --git a/Modules/Core/src/Algorithms/mitkPlaneGeometryDataToSurfaceFilter.cpp b/Modules/Core/src/Algorithms/mitkPlaneGeometryDataToSurfaceFilter.cpp
index 988afe14aa..a7510e655b 100644
--- a/Modules/Core/src/Algorithms/mitkPlaneGeometryDataToSurfaceFilter.cpp
+++ b/Modules/Core/src/Algorithms/mitkPlaneGeometryDataToSurfaceFilter.cpp
@@ -1,391 +1,382 @@
/*============================================================================
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 "mitkPlaneGeometryDataToSurfaceFilter.h"
#include "mitkAbstractTransformGeometry.h"
#include "mitkGeometry3D.h"
#include "mitkPlaneGeometry.h"
#include "mitkPlaneGeometryData.h"
#include "mitkSurface.h"
#include <vtkPlaneSource.h>
#include <vtkPolyData.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkBox.h>
#include <vtkClipPolyData.h>
#include <vtkCubeSource.h>
#include <vtkCutter.h>
#include <vtkGeneralTransform.h>
#include <vtkPPolyDataNormals.h>
#include <vtkPlane.h>
-#include <vtkStripper.h>
#include <vtkTextureMapToPlane.h>
#include <vtkTransform.h>
#include <vtkTransformPolyDataFilter.h>
-#include <vtkTriangleFilter.h>
+#include <vtkContourTriangulator.h>
mitk::PlaneGeometryDataToSurfaceFilter::PlaneGeometryDataToSurfaceFilter()
: m_UseGeometryParametricBounds(true),
m_XResolution(10),
m_YResolution(10),
m_PlaceByGeometry(false),
m_UseBoundingBox(false)
{
m_PlaneSource = vtkPlaneSource::New();
m_Transform = vtkTransform::New();
m_CubeSource = vtkCubeSource::New();
m_PolyDataTransformer = vtkTransformPolyDataFilter::New();
m_Plane = vtkPlane::New();
m_PlaneCutter = vtkCutter::New();
- m_PlaneStripper = vtkStripper::New();
- m_PlanePolyData = vtkPolyData::New();
+ m_ContourTriangulator = vtkContourTriangulator::New();
m_NormalsUpdater = vtkPPolyDataNormals::New();
- m_PlaneTriangler = vtkTriangleFilter::New();
m_TextureMapToPlane = vtkTextureMapToPlane::New();
m_Box = vtkBox::New();
m_PlaneClipper = vtkClipPolyData::New();
m_VtkTransformPlaneFilter = vtkTransformPolyDataFilter::New();
m_VtkTransformPlaneFilter->SetInputConnection(m_PlaneSource->GetOutputPort());
}
mitk::PlaneGeometryDataToSurfaceFilter::~PlaneGeometryDataToSurfaceFilter()
{
m_PlaneSource->Delete();
m_Transform->Delete();
m_CubeSource->Delete();
m_PolyDataTransformer->Delete();
m_Plane->Delete();
m_PlaneCutter->Delete();
- m_PlaneStripper->Delete();
- m_PlanePolyData->Delete();
+ m_ContourTriangulator->Delete();
m_NormalsUpdater->Delete();
- m_PlaneTriangler->Delete();
m_TextureMapToPlane->Delete();
m_Box->Delete();
m_PlaneClipper->Delete();
m_VtkTransformPlaneFilter->Delete();
}
void mitk::PlaneGeometryDataToSurfaceFilter::GenerateOutputInformation()
{
mitk::PlaneGeometryData::ConstPointer input = this->GetInput();
mitk::Surface::Pointer output = this->GetOutput();
if (input.IsNull() || (input->GetPlaneGeometry() == nullptr) || (input->GetPlaneGeometry()->IsValid() == false) ||
(m_UseBoundingBox && (m_BoundingBox.IsNull() || (m_BoundingBox->GetDiagonalLength2() < mitk::eps))))
{
return;
}
Point3D origin;
Point3D right, bottom;
vtkPolyData *planeSurface = nullptr;
// Does the PlaneGeometryData contain an AbstractTransformGeometry?
if (auto *abstractGeometry =
dynamic_cast<AbstractTransformGeometry *>(input->GetPlaneGeometry()))
{
// In the case of an AbstractTransformGeometry (which holds a possibly
// non-rigid transform), we proceed slightly differently: since the
// plane can be arbitrarily deformed, we need to transform it by the
// abstract transform before clipping it. The setup for this is partially
// done in the constructor.
origin = abstractGeometry->GetPlane()->GetOrigin();
right = origin + abstractGeometry->GetPlane()->GetAxisVector(0);
bottom = origin + abstractGeometry->GetPlane()->GetAxisVector(1);
// Define the plane
m_PlaneSource->SetOrigin(origin[0], origin[1], origin[2]);
m_PlaneSource->SetPoint1(right[0], right[1], right[2]);
m_PlaneSource->SetPoint2(bottom[0], bottom[1], bottom[2]);
// Set the plane's resolution (unlike for non-deformable planes, the plane
// grid needs to have a certain resolution so that the deformation has the
// desired effect).
if (m_UseGeometryParametricBounds)
{
m_PlaneSource->SetXResolution((int)abstractGeometry->GetParametricExtent(0));
m_PlaneSource->SetYResolution((int)abstractGeometry->GetParametricExtent(1));
}
else
{
m_PlaneSource->SetXResolution(m_XResolution);
m_PlaneSource->SetYResolution(m_YResolution);
}
if (m_PlaceByGeometry)
{
// Let the output use the input geometry to appropriately transform the
// coordinate system.
mitk::Geometry3D::TransformType *affineTransform = abstractGeometry->GetIndexToWorldTransform();
TimeGeometry *timeGeometry = output->GetTimeGeometry();
BaseGeometry *g3d = timeGeometry->GetGeometryForTimeStep(0);
g3d->SetIndexToWorldTransform(affineTransform);
vtkGeneralTransform *composedResliceTransform = vtkGeneralTransform::New();
composedResliceTransform->Identity();
composedResliceTransform->Concatenate(abstractGeometry->GetVtkTransform()->GetLinearInverse());
composedResliceTransform->Concatenate(abstractGeometry->GetVtkAbstractTransform());
// Use the non-rigid transform for transforming the plane.
m_VtkTransformPlaneFilter->SetTransform(composedResliceTransform);
}
else
{
// Use the non-rigid transform for transforming the plane.
m_VtkTransformPlaneFilter->SetTransform(abstractGeometry->GetVtkAbstractTransform());
}
if (m_UseBoundingBox)
{
mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum();
mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum();
// mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter();
m_Box->SetXMin(boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2]);
m_Box->SetXMax(boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2]);
}
else
{
// Plane will not be clipped
m_Box->SetXMin(-10000.0, -10000.0, -10000.0);
m_Box->SetXMax(10000.0, 10000.0, 10000.0);
}
m_Transform->Identity();
m_Transform->Concatenate(input->GetPlaneGeometry()->GetVtkTransform());
m_Transform->PreMultiply();
m_Box->SetTransform(m_Transform);
m_PlaneClipper->SetInputConnection(m_VtkTransformPlaneFilter->GetOutputPort());
m_PlaneClipper->SetClipFunction(m_Box);
m_PlaneClipper->GenerateClippedOutputOff(); // important to NOT generate normals data for clipped part
m_PlaneClipper->InsideOutOn();
m_PlaneClipper->SetValue(0.0);
m_PlaneClipper->Update();
planeSurface = m_PlaneClipper->GetOutput();
}
// Does the PlaneGeometryData contain a PlaneGeometry?
else if (dynamic_cast<PlaneGeometry *>(input->GetPlaneGeometry()) != nullptr)
{
auto *planeGeometry = dynamic_cast<PlaneGeometry *>(input->GetPlaneGeometry());
if (m_PlaceByGeometry)
{
// Let the output use the input geometry to appropriately transform the
// coordinate system.
mitk::Geometry3D::TransformType *affineTransform = planeGeometry->GetIndexToWorldTransform();
TimeGeometry *timeGeometry = output->GetTimeGeometry();
BaseGeometry *geometrie3d = timeGeometry->GetGeometryForTimeStep(0);
geometrie3d->SetIndexToWorldTransform(affineTransform);
}
if (!m_UseBoundingBox)
{
// We do not have a bounding box, so no clipping is required.
if (m_PlaceByGeometry)
{
// Derive coordinate axes and origin from input geometry extent
origin.Fill(0.0);
FillVector3D(right, planeGeometry->GetExtent(0), 0.0, 0.0);
FillVector3D(bottom, 0.0, planeGeometry->GetExtent(1), 0.0);
}
else
{
// Take the coordinate axes and origin directly from the input geometry.
origin = planeGeometry->GetOrigin();
right = planeGeometry->GetCornerPoint(false, true);
bottom = planeGeometry->GetCornerPoint(true, false);
}
// Since the plane is planar, there is no need to subdivide the grid
// (cf. AbstractTransformGeometry case)
m_PlaneSource->SetXResolution(1);
m_PlaneSource->SetYResolution(1);
m_PlaneSource->SetOrigin(origin[0], origin[1], origin[2]);
m_PlaneSource->SetPoint1(right[0], right[1], right[2]);
m_PlaneSource->SetPoint2(bottom[0], bottom[1], bottom[2]);
m_PlaneSource->Update();
planeSurface = m_PlaneSource->GetOutput();
}
else
{
// Set up a cube with the extent and origin of the bounding box. This
// cube will be clipped by a plane later on. The intersection of the
// cube and the plane will be the surface we are interested in. Note
// that the bounding box needs to be explicitly specified by the user
// of this class, since it is not necessarily clear from the data
// available herein which bounding box to use. In most cases, this
// would be the bounding box of the input geometry's reference
// geometry, but this is not an inevitable requirement.
mitk::BoundingBox::PointType boundingBoxMin = m_BoundingBox->GetMinimum();
mitk::BoundingBox::PointType boundingBoxMax = m_BoundingBox->GetMaximum();
mitk::BoundingBox::PointType boundingBoxCenter = m_BoundingBox->GetCenter();
m_CubeSource->SetXLength(boundingBoxMax[0] - boundingBoxMin[0]);
m_CubeSource->SetYLength(boundingBoxMax[1] - boundingBoxMin[1]);
m_CubeSource->SetZLength(boundingBoxMax[2] - boundingBoxMin[2]);
m_CubeSource->SetCenter(boundingBoxCenter[0], boundingBoxCenter[1], boundingBoxCenter[2]);
// Now we have to transform the cube, so that it will cut our plane
// appropriately. (As can be seen below, the plane corresponds to the
// z-plane in the coordinate system and is *not* transformed.) Therefore,
// we get the inverse of the plane geometry's transform and concatenate
// it with the transform of the reference geometry, if available.
m_Transform->Identity();
m_Transform->Concatenate(planeGeometry->GetVtkTransform()->GetLinearInverse());
const BaseGeometry *referenceGeometry = planeGeometry->GetReferenceGeometry();
if (referenceGeometry)
{
m_Transform->Concatenate(referenceGeometry->GetVtkTransform());
}
// Transform the cube accordingly (s.a.)
m_PolyDataTransformer->SetInputConnection(m_CubeSource->GetOutputPort());
m_PolyDataTransformer->SetTransform(m_Transform);
// Initialize the plane to clip the cube with, as lying on the z-plane
m_Plane->SetOrigin(0.0, 0.0, 0.0);
m_Plane->SetNormal(0.0, 0.0, 1.0);
// Cut the plane with the cube.
m_PlaneCutter->SetInputConnection(m_PolyDataTransformer->GetOutputPort());
+ m_PlaneCutter->GenerateTrianglesOff();
m_PlaneCutter->SetCutFunction(m_Plane);
// The output of the cutter must be converted into appropriate poly data.
- m_PlaneStripper->SetInputConnection(m_PlaneCutter->GetOutputPort());
- m_PlaneStripper->Update();
+ m_ContourTriangulator->SetInputConnection(m_PlaneCutter->GetOutputPort());
+ m_ContourTriangulator->Update();
- if (m_PlaneStripper->GetOutput()->GetNumberOfPoints() < 3)
+ if (m_ContourTriangulator->GetTriangulationError())
{
return;
}
- m_PlanePolyData->SetPoints(m_PlaneStripper->GetOutput()->GetPoints());
- m_PlanePolyData->SetPolys(m_PlaneStripper->GetOutput()->GetLines());
-
- m_PlaneTriangler->SetInputData(m_PlanePolyData);
-
// Get bounds of the resulting surface and use it to generate the texture
// mapping information
- m_PlaneTriangler->Update();
- m_PlaneTriangler->GetOutput()->ComputeBounds();
- double *surfaceBounds = m_PlaneTriangler->GetOutput()->GetBounds();
+ m_ContourTriangulator->Update();
+ m_ContourTriangulator->GetOutput()->ComputeBounds();
+ double *surfaceBounds = m_ContourTriangulator->GetOutput()->GetBounds();
origin[0] = surfaceBounds[0];
origin[1] = surfaceBounds[2];
origin[2] = surfaceBounds[4];
right[0] = surfaceBounds[1];
right[1] = surfaceBounds[2];
right[2] = surfaceBounds[4];
bottom[0] = surfaceBounds[0];
bottom[1] = surfaceBounds[3];
bottom[2] = surfaceBounds[4];
// Now we tell the data how it shall be textured afterwards;
// description see above.
- m_TextureMapToPlane->SetInputConnection(m_PlaneTriangler->GetOutputPort());
+ m_TextureMapToPlane->SetInputConnection(m_ContourTriangulator->GetOutputPort());
m_TextureMapToPlane->AutomaticPlaneGenerationOn();
m_TextureMapToPlane->SetOrigin(origin[0], origin[1], origin[2]);
m_TextureMapToPlane->SetPoint1(right[0], right[1], right[2]);
m_TextureMapToPlane->SetPoint2(bottom[0], bottom[1], bottom[2]);
// Need to call update so that output data and bounds are immediately
// available
m_TextureMapToPlane->Update();
// Return the output of this generation process
planeSurface = dynamic_cast<vtkPolyData *>(m_TextureMapToPlane->GetOutput());
}
}
m_NormalsUpdater->SetInputData(planeSurface);
m_NormalsUpdater->AutoOrientNormalsOn(); // that's the trick! Brings consistency between
// normals direction and front/back faces direction (see bug 1440)
m_NormalsUpdater->ComputePointNormalsOn();
m_NormalsUpdater->Update();
output->SetVtkPolyData(m_NormalsUpdater->GetOutput());
output->CalculateBoundingBox();
}
void mitk::PlaneGeometryDataToSurfaceFilter::GenerateData()
{
mitk::Surface::Pointer output = this->GetOutput();
if (output.IsNull())
return;
if (output->GetVtkPolyData() == nullptr)
return;
// output->GetVtkPolyData()->Update(); //VTK6_TODO vtk pipeline
}
const mitk::PlaneGeometryData *mitk::PlaneGeometryDataToSurfaceFilter::GetInput()
{
if (this->GetNumberOfInputs() < 1)
{
return nullptr;
}
return static_cast<const mitk::PlaneGeometryData *>(this->ProcessObject::GetInput(0));
}
const mitk::PlaneGeometryData *mitk::PlaneGeometryDataToSurfaceFilter::GetInput(unsigned int idx)
{
return static_cast<const mitk::PlaneGeometryData *>(this->ProcessObject::GetInput(idx));
}
void mitk::PlaneGeometryDataToSurfaceFilter::SetInput(const mitk::PlaneGeometryData *input)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(0, const_cast<mitk::PlaneGeometryData *>(input));
}
void mitk::PlaneGeometryDataToSurfaceFilter::SetInput(unsigned int index, const mitk::PlaneGeometryData *input)
{
if (index + 1 > this->GetNumberOfInputs())
{
this->SetNumberOfRequiredInputs(index + 1);
}
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(index, const_cast<mitk::PlaneGeometryData *>(input));
}
void mitk::PlaneGeometryDataToSurfaceFilter::SetBoundingBox(const mitk::BoundingBox *boundingBox)
{
m_BoundingBox = boundingBox;
this->UseBoundingBoxOn();
}
const mitk::BoundingBox *mitk::PlaneGeometryDataToSurfaceFilter::GetBoundingBox() const
{
return m_BoundingBox.GetPointer();
}
diff --git a/Modules/Core/src/IO/mitkXMLPreferencesStorage.cpp b/Modules/Core/src/IO/mitkXMLPreferencesStorage.cpp
index c67a9270b9..3e56b2de4a 100644
--- a/Modules/Core/src/IO/mitkXMLPreferencesStorage.cpp
+++ b/Modules/Core/src/IO/mitkXMLPreferencesStorage.cpp
@@ -1,114 +1,125 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkXMLPreferencesStorage.h"
#include "mitkPreferences.h"
#include <mitkLog.h>
#include <tinyxml2.h>
namespace
{
std::string GetStringAttribute(const tinyxml2::XMLElement* xmlElement, const char* name)
{
const auto* attribute = xmlElement->Attribute(name);
return attribute != nullptr
? attribute
: "";
}
mitk::Preferences* Deserialize(const tinyxml2::XMLElement* xmlPreferenceElement, mitk::Preferences* parentPreferences, mitk::IPreferencesStorage* storage)
{
const std::string name = GetStringAttribute(xmlPreferenceElement, "name");
const auto* xmlPropertyElement = xmlPreferenceElement->FirstChildElement("property");
mitk::Preferences::Properties properties;
while (xmlPropertyElement != nullptr)
{
properties[GetStringAttribute(xmlPropertyElement, "name")] = GetStringAttribute(xmlPropertyElement, "value");
xmlPropertyElement = xmlPropertyElement->NextSiblingElement("property");
}
auto* preferences = new mitk::Preferences(properties, name, parentPreferences, storage);
const auto* xmlPreferenceChildElement = xmlPreferenceElement->FirstChildElement("preferences");
while (xmlPreferenceChildElement != nullptr)
{
Deserialize(xmlPreferenceChildElement, preferences, storage);
xmlPreferenceChildElement = xmlPreferenceChildElement->NextSiblingElement("preferences");
}
return preferences;
}
void Serialize(const mitk::Preferences* preferences, tinyxml2::XMLNode* xmlParentNode)
{
auto* xmlDocument = xmlParentNode->GetDocument();
auto* xmlPreferenceElement = xmlDocument->NewElement("preferences");
xmlPreferenceElement->SetAttribute("name", preferences->Name().c_str());
for (const auto& [name, value] : preferences->GetProperties())
{
auto* xmlPropertyElement = xmlDocument->NewElement("property");
xmlPropertyElement->SetAttribute("name", name.c_str());
xmlPropertyElement->SetAttribute("value", value.c_str());
xmlPreferenceElement->InsertEndChild(xmlPropertyElement);
}
xmlParentNode->InsertEndChild(xmlPreferenceElement);
for (const auto& child : preferences->GetChildren())
Serialize(child.get(), xmlPreferenceElement);
}
}
mitk::XMLPreferencesStorage::XMLPreferencesStorage(const std::filesystem::path& filename)
: IPreferencesStorage(filename)
{
if (std::filesystem::exists(filename))
{
tinyxml2::XMLDocument xmlDocument;
if (xmlDocument.LoadFile(filename.string().c_str()) == tinyxml2::XML_SUCCESS)
{
m_Root.reset(Deserialize(xmlDocument.RootElement(), nullptr, this));
return;
}
else
{
MITK_ERROR << "Could not load preferences from \"" << filename.string() << "\"!";
}
}
+ else
+ {
+ try
+ {
+ std::filesystem::create_directories(filename.parent_path());
+ }
+ catch (const std::exception& e)
+ {
+ MITK_ERROR << "Could not create directories for \"" << filename.string() << "\": " << e.what();
+ }
+ }
m_Root = std::make_unique<Preferences>(Preferences::Properties(), "", nullptr, this);
}
mitk::XMLPreferencesStorage::~XMLPreferencesStorage()
{
}
void mitk::XMLPreferencesStorage::Flush()
{
tinyxml2::XMLDocument xmlDocument;
xmlDocument.InsertEndChild(xmlDocument.NewDeclaration());
Serialize(static_cast<const mitk::Preferences*>(m_Root.get()), &xmlDocument);
if (xmlDocument.SaveFile(m_Filename.string().c_str()) != tinyxml2::XML_SUCCESS)
MITK_ERROR << "Could not save preferences to \"" << m_Filename.string() << "\"!";
}
diff --git a/Modules/DICOMUI/src/QmitkDicomLocalStorageWidget.cpp b/Modules/DICOMUI/src/QmitkDicomLocalStorageWidget.cpp
index 8ee0dae06b..e7197d08ee 100644
--- a/Modules/DICOMUI/src/QmitkDicomLocalStorageWidget.cpp
+++ b/Modules/DICOMUI/src/QmitkDicomLocalStorageWidget.cpp
@@ -1,229 +1,229 @@
/*============================================================================
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.
============================================================================*/
// Qmitk
#include "QmitkDicomLocalStorageWidget.h"
// Qt
#include <QLabel>
#include <QMessageBox>
#include <QProgressDialog>
#include <QVariant>
#include <ctkDICOMIndexer.h>
const std::string QmitkDicomLocalStorageWidget::Widget_ID = "org.mitk.Widgets.QmitkDicomLocalStorageWidget";
QmitkDicomLocalStorageWidget::QmitkDicomLocalStorageWidget(QWidget *parent)
: QWidget(parent), m_LocalIndexer(new ctkDICOMIndexer(parent)), m_Controls(nullptr)
{
CreateQtPartControl(this);
}
QmitkDicomLocalStorageWidget::~QmitkDicomLocalStorageWidget()
{
m_LocalDatabase->closeDatabase();
}
void QmitkDicomLocalStorageWidget::CreateQtPartControl(QWidget *parent)
{
if (!m_Controls)
{
m_Controls = new Ui::QmitkDicomLocalStorageWidgetControls;
m_Controls->setupUi(parent);
connect(m_Controls->deleteButton, SIGNAL(clicked()), this, SLOT(OnDeleteButtonClicked()));
connect(m_Controls->viewInternalDataButton, SIGNAL(clicked()), this, SLOT(OnViewButtonClicked()));
connect(m_Controls->ctkDicomBrowser,
SIGNAL(seriesSelectionChanged(const QStringList &)),
this,
SLOT(OnSeriesSelectionChanged(const QStringList &)));
connect(m_Controls->ctkDicomBrowser,
SIGNAL(seriesSelectionChanged(const QStringList &)),
this,
SLOT(OnSeriesSelectionChanged(const QStringList &)));
connect(
m_Controls->ctkDicomBrowser, SIGNAL(seriesDoubleClicked(const QModelIndex &)), this, SLOT(OnViewButtonClicked()));
connect(m_LocalIndexer, SIGNAL(indexingComplete(int, int, int, int)), this, SIGNAL(SignalFinishedImport()));
m_Controls->ctkDicomBrowser->setTableOrientation(Qt::Vertical);
}
}
void QmitkDicomLocalStorageWidget::OnStartDicomImport(const QString &dicomData)
{
if (m_LocalDatabase->isOpen())
{
m_LocalIndexer->addDirectory(dicomData);
}
}
void QmitkDicomLocalStorageWidget::OnStartDicomImport(const QStringList &dicomData)
{
if (m_LocalDatabase->isOpen())
{
m_LocalIndexer->addListOfFiles( dicomData);
}
}
void QmitkDicomLocalStorageWidget::OnDeleteButtonClicked()
{
if (!this->DeletePatients())
{
if (!this->DeleteStudies())
{
this->DeleteSeries();
}
}
m_Controls->ctkDicomBrowser->updateTableViews();
}
bool QmitkDicomLocalStorageWidget::DeletePatients()
{
auto selectedPatientUIDs = m_Controls->ctkDicomBrowser->currentPatientsSelection();
if (!selectedPatientUIDs.empty())
{
QStringList studyUIDs;
- for (const auto &patientUID : qAsConst(selectedPatientUIDs))
+ for (const auto &patientUID : std::as_const(selectedPatientUIDs))
studyUIDs.append(m_LocalDatabase->studiesForPatient(patientUID));
QStringList seriesUIDs;
for (const auto &studyUID : studyUIDs)
seriesUIDs.append(m_LocalDatabase->seriesForStudy(studyUID));
auto answer = QMessageBox::question(nullptr,
"Delete Patients",
QString("Do you really want to delete %1 %2, containing %3 series in %4 %5?")
.arg(selectedPatientUIDs.count())
.arg(selectedPatientUIDs.count() != 1 ? "patients" : "patient")
.arg(seriesUIDs.count())
.arg(studyUIDs.count())
.arg(studyUIDs.count() != 1 ? "studies" : "study"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (answer == QMessageBox::Yes)
{
- for (const auto &patientUID : qAsConst(selectedPatientUIDs))
+ for (const auto &patientUID : std::as_const(selectedPatientUIDs))
m_LocalDatabase->removePatient(patientUID);
}
return true;
}
return false;
}
bool QmitkDicomLocalStorageWidget::DeleteStudies()
{
auto selectedStudyUIDs = m_Controls->ctkDicomBrowser->currentStudiesSelection();
if (!selectedStudyUIDs.empty())
{
QStringList seriesUIDs;
- for (const auto &studyUID : qAsConst(selectedStudyUIDs))
+ for (const auto &studyUID : std::as_const(selectedStudyUIDs))
seriesUIDs.append(m_LocalDatabase->seriesForStudy(studyUID));
auto answer = QMessageBox::question(nullptr,
"Delete Studies",
QString("Do you really want to delete %1 %2, containing %3 series?")
.arg(selectedStudyUIDs.count())
.arg(selectedStudyUIDs.count() != 1 ? "studies" : "study")
.arg(seriesUIDs.count()),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (answer == QMessageBox::Yes)
{
- for (const auto &studyUID : qAsConst(selectedStudyUIDs))
+ for (const auto &studyUID : std::as_const(selectedStudyUIDs))
m_LocalDatabase->removeStudy(studyUID);
}
return true;
}
return false;
}
bool QmitkDicomLocalStorageWidget::DeleteSeries()
{
auto selectedSeriesUIDs = m_Controls->ctkDicomBrowser->currentSeriesSelection();
if (!selectedSeriesUIDs.empty())
{
auto answer =
QMessageBox::question(nullptr,
"Delete Series",
QString("Do you really want to delete %1 series?").arg(selectedSeriesUIDs.count()),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (answer == QMessageBox::Yes)
{
- for (const auto &seriesUID : qAsConst(selectedSeriesUIDs))
+ for (const auto &seriesUID : std::as_const(selectedSeriesUIDs))
m_LocalDatabase->removeSeries(seriesUID);
}
return true;
}
return false;
}
void QmitkDicomLocalStorageWidget::OnViewButtonClicked()
{
QStringList uids = m_Controls->ctkDicomBrowser->currentSeriesSelection();
QString uid;
foreach (uid, uids)
{
QStringList filesForSeries = m_LocalDatabase->filesForSeries(uid);
QHash<QString, QVariant> eventProperty;
eventProperty.insert("FilesForSeries", filesForSeries);
if (!filesForSeries.isEmpty())
{
QString modality = m_LocalDatabase->fileValue(filesForSeries.at(0), "0008,0060");
eventProperty.insert("Modality", modality);
}
emit SignalDicomToDataManager(eventProperty);
}
}
void QmitkDicomLocalStorageWidget::SetDatabaseDirectory(QString newDatatbaseDirectory)
{
QDir databaseDirecory = QDir(newDatatbaseDirectory);
if (!databaseDirecory.exists())
{
databaseDirecory.mkpath(databaseDirecory.absolutePath());
}
QString newDatatbaseFile = databaseDirecory.absolutePath() + QString("/ctkDICOM.sql");
this->SetDatabase(newDatatbaseFile);
}
void QmitkDicomLocalStorageWidget::SetDatabase(QString databaseFile)
{
m_LocalDatabase = new ctkDICOMDatabase(databaseFile);
m_LocalDatabase->setParent(this);
m_Controls->ctkDicomBrowser->setDICOMDatabase(m_LocalDatabase);
m_LocalIndexer->setDatabase(m_LocalDatabase);
}
void QmitkDicomLocalStorageWidget::OnSeriesSelectionChanged(const QStringList &s)
{
m_Controls->viewInternalDataButton->setEnabled((s.size() != 0));
}
diff --git a/Modules/IGTUI/Qmitk/QmitkAbstractTrackingDeviceWidget.h b/Modules/IGTUI/Qmitk/QmitkAbstractTrackingDeviceWidget.h
index 2c6e072e00..2599f614f4 100644
--- a/Modules/IGTUI/Qmitk/QmitkAbstractTrackingDeviceWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkAbstractTrackingDeviceWidget.h
@@ -1,171 +1,171 @@
/*============================================================================
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 QmitkAbstractTrackingDeviceWidget_h
#define QmitkAbstractTrackingDeviceWidget_h
#include <QWidget>
#include "MitkIGTUIExports.h"
#include "mitkTrackingDevice.h"
#include <mitkIPersistenceService.h>
#include "QmitkTrackingDeviceConfigurationWidgetConnectionWorker.h"
//itk headers
/** Documentation:
* \brief Abstract class to configure a tracking device.
* Inherited widgets should be registered in the Microservice (TrackingDeviceCollectionWidget),
* If done so, they will be included in the QmitkTrackingDeviceConfigurationWidget of the Tracking Toolbox.
*
* - Each implementation of this class must have a method to get a TrackingDevice
* - Each implementation handles itself, if a new TrackingDevice needs to be constructed.
* Attention: In former MITK versions, there was no pure virtual GetTrackingDevice function but a pure virtual ConstructTrackingDevice function.
* You can simply rename these, but you should give it a thought, if each time "Construct" was called, a new device needs to be constructed,
* or if you can store your TrackingDevice in a member variable and return this. Up to you.
* - Please create the UI elements in a function like CreateQtPartControl (e.g. see QmitkVitrualTrackerWidget).
* - You might want to use own buttons etc., please connect them in a private CreateConnections (e.g. see QmitkVitrualTrackerWidget).
* - Due to initialization of qt during autoloading of the IGT module, you constructor should be as slim as possible and only contain a call
* of the QmitkAbstractTrackingDeviceWidget constructor and simple variable initialization.
* - For the initialization, you must write an Iniltialize() function, which must include a call of InitializeSuperclassWidget() and should contain
* calls of your private CreateConnections / CreateQtPartControl (if you implemented these).
* - For integration into the TrackingToolbox, a clone function is needed. Here, a new widget should be created, Initialize() needs to be called,
* and all settings of your widget should be copied.
*
* You can Load and Store previous settings of your GUI elements (e.g. see QmitkNDIPolarisWidget).
* Also, you can add an output textbox to your widget to display information about your device status. It's optional, see e.g. QmitkNDIAuroraWidget.
* Some Devices need the information if drivers are installed on your computer. If this is necessary for your device to avoid crashes,
* please override IsDeviceInstalled. The default return value is true otherwise.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkAbstractTrackingDeviceWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkAbstractTrackingDeviceWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkAbstractTrackingDeviceWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkAbstractTrackingDeviceWidget() override;
/**
* \brief Return pointer to copy of the object.
* Internally use of QmitkUSAbstractCustomWidget::Clone() with additionaly
* setting an internal flag that the object was really cloned.
*/
QmitkAbstractTrackingDeviceWidget* CloneForQt(QWidget* parent = nullptr) const;
/**
* \brief Subclass must implement this method to return a pointer to a copy of the object.
* Please don't forget to call InitializeSuperclassWidget(), CreateQtPartControl and optionally CreateConnections during this function.
*/
virtual void Initialize() = 0;
bool IsInitialized() const { return isInitialized; }
signals:
void ConnectionTested(bool connected, QString output);
protected slots:
void TestConnectionFinished(bool connected, QString output);
/* @brief This method is called when the user presses the button "test connection". The method will then create a temporary tracking device,
* try to open a connection and start tracking. The user can see the result of the connection test on the small output window.
*/
void TestConnection();
private:
/// \brief Creation of the connections. You might implement the same function again in your inherited widget.
void CreateConnections();
protected:
PERSISTENCE_GET_SERVICE_METHOD_MACRO
void InitializeSuperclassWidget();
QmitkTrackingDeviceConfigurationWidgetConnectionWorker* m_TestConnectionWorker;
QThread* m_TestConnectionWorkerThread;
/**
* \brief Subclass must implement this method to return a pointer to a copy of the object.
* Please don't forget to call Initialize() during this function and copy all of your settings.
*/
virtual QmitkAbstractTrackingDeviceWidget* Clone(QWidget* parent = nullptr) const = 0;
public:
/**
* \brief Optional method to add output to a small screen in the trackingToolbox (see QmitkNDIPolarisWidget)
*/
virtual void ResetOutput() {}
/**
* \brief Optional method to add output to a small screen in the trackingToolbox (see QmitkNDIPolarisWidget)
*/
virtual void AddOutput(std::string) {}
virtual mitk::TrackingDevice::Pointer GetTrackingDevice() = 0;
/**
* \brief Optional method to store and load settings of your widget (see QmitkNDIPolarisWidget)
*/
virtual void StoreUISettings() {}
/**
* \brief Optional method to store and load settings of your widget (see QmitkNDIPolarisWidget)
*/
virtual void LoadUISettings() {}
/**
* \brief Optional method to investigate if drivers etc for your device are installed.
* The default value is "true" as most devices don't need this information.
* Others however migth crash, and for these you might implement this function (see QmitkMicronTrackerWidget)
*/
virtual bool IsDeviceInstalled() { return true; }
/**
* \brief This function is called, when in the TrackingToolboxView "Connect" was clicked and the device is successful connected.
* Can e.g. be used to activate options of a tracking device only when it is connected.
*/
virtual void OnConnected(bool) {}
/**
* \brief This function is called, when in the TrackingToolboxView "Disconnect" was clicked and the device is successful disconnected.
* Can e.g. be used to activate/disactivate options of a tracking device.
*/
virtual void OnDisconnected(bool) {}
/**
* \brief This function is called, when in the TrackingToolboxView "Start Tracking" was clicked and the device successfully started tracking.
* Can e.g. be used to activate options of a tracking device only when tracking is started.
*/
virtual void OnStartTracking(bool) {}
/**
* \brief This function is called, when in the TrackingToolboxView "Stop Tracking" was clicked and the device successful stopped tracking.
* Can e.g. be used to activate/disactivate options when device is not tracking.
*/
virtual void OnStopTracking(bool) {}
/**
* \brief This function is called, when anything in the ToolStorage changed, e.g. AddTool or EditTool.
* ServiceListener is connected in the QmitkMITKIGTTrackingToolboxView.
*/
virtual void OnToolStorageChanged() {}
std::string m_ErrorMessage; ///< current problem description
private:
/**
* \warning Don't touch this variable if you don't know what you are doing!
*/
bool isInitialized;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkIGTConnectionWidget.h b/Modules/IGTUI/Qmitk/QmitkIGTConnectionWidget.h
index 8989236910..95c58b665d 100644
--- a/Modules/IGTUI/Qmitk/QmitkIGTConnectionWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkIGTConnectionWidget.h
@@ -1,109 +1,109 @@
/*============================================================================
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 QmitkIGTConnectionWidget_h
#define QmitkIGTConnectionWidget_h
#include <QWidget>
#include "MitkIGTUIExports.h"
#include "ui_QmitkIGTConnectionWidgetControls.h"
#include "mitkDataStorage.h"
#include "mitkNavigationToolStorage.h"
#include "mitkTrackingDevice.h"
#include "mitkTrackingDeviceSource.h"
//itk headers
/** Documentation:
* \brief Simple and fast access to a pre-configured TrackingDeviceSource.
*
* This widget creates a fully configured, connected and started TrackingDeviceSource.
* Clicking "Connect" requires to specify a NavigationToolStorage that holds all tools to be used
* in the application. Corresponding surfaces are added to the DataStorage that has to be set for
* the widget.
*
* Inputs: DataStorage
* Outputs: TrackingDeviceSource, NavigationToolStorage
* Signals: TrackingDeviceConnected, TrackingDeviceDisconnected
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkIGTConnectionWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkIGTConnectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkIGTConnectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkIGTConnectionWidget() override;
/* @return Returns the preconfigured and connected TrackingDeviceSource ready to use in an IGT pipeline.
*/
mitk::TrackingDeviceSource::Pointer GetTrackingDeviceSource();
/*!
\brief Get the NavigationToolStorage holding all tools with corresponding surface objects
*/
mitk::NavigationToolStorage::Pointer GetNavigationToolStorage();
/*!
\brief set DataStorage that is used to put the navigation tools
*/
void SetDataStorage(mitk::DataStorage::Pointer dataStorage);
signals:
/*!
\brief signal emitted when TrackingDevice was successfully connected
*/
void TrackingDeviceConnected();
/*!
\brief signal emitted when TrackingDevice was successfully disconnected
*/
void TrackingDeviceDisconnected();
protected slots:
/*!
\brief Asks the user to specify a tool file and finally connects the TrackingDeviceSource
*/
void OnConnect();
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
/*!
\brief Load NavigationToolStorage from given filename and set according member
\param qFilename file location of the NavigationToolStorage
\return success of load operation (true if load successful, false otherwise) m_ErrorMessage holds the problem description
*/
bool LoadToolfile(QString qFilename);
/*!
\brief Remove the tool nodes currently associated to the tools hold in the NavigationToolStorage from the DataStorage
*/
void RemoveToolNodes();
Ui::QmitkIGTConnectionWidgetControls* m_Controls;
mitk::DataStorage::Pointer m_DataStorage; ///< data storage to put navigation tools
mitk::TrackingDevice::Pointer m_TrackingDevice; ///< tracking device currently connected
mitk::TrackingDeviceSource::Pointer m_TrackingDeviceSource; ///< holds the preconfigured source of the IGT pipeline which is provided by this widget for further processing
mitk::NavigationToolStorage::Pointer m_NavigationToolStorage; ///< holds all navigation tools currently loaded
std::string m_ErrorMessage; ///< current problem description
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkIGTLoggerWidget.h b/Modules/IGTUI/Qmitk/QmitkIGTLoggerWidget.h
index fa678bc0d8..04e8706af0 100644
--- a/Modules/IGTUI/Qmitk/QmitkIGTLoggerWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkIGTLoggerWidget.h
@@ -1,86 +1,86 @@
/*============================================================================
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 QmitkIGTLoggerWidget_h
#define QmitkIGTLoggerWidget_h
//QT headers
#include <QWidget>
//mitk headers
#include "MitkIGTUIExports.h"
#include "mitkNavigationTool.h"
#include <mitkDataStorage.h>
#include "mitkNavigationDataRecorder.h"
//ui header
#include "ui_QmitkIGTLoggerWidgetControls.h"
/** Documentation:
* \brief GUI to access the IGT recorder.
* User can specify the file name where the output shall be stored and
* how long the recording shall be performed.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkIGTLoggerWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkIGTLoggerWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkIGTLoggerWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkIGTLoggerWidget() override;
void SetDataStorage(mitk::DataStorage* dataStorage);
void SetRecorder(mitk::NavigationDataRecorder::Pointer recorder);
signals:
void SignalRecordingStarted();
void SignalRecordingStopped();
protected slots:
void OnChangePressed();
void OnStartRecording(bool recording);
void OnRecording();
void UpdateRecordingTime();
void StopRecording();
void UpdateOutputFileName();
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
void SetDefaultRecordingSettings();
void SetOutputFileName();
Ui::QmitkIGTLoggerWidgetControls* m_Controls;
/** @brief holds the DataStorage */
mitk::DataStorage::Pointer m_DataStorage;
mitk::NavigationDataRecorder::Pointer m_Recorder; ///< records NDs to a XML file
QString m_CmpFilename;
QString m_Dir;
QTimer* m_RecordingTimer;
QString m_MilliSeconds;
QString m_Samples;
bool m_RecordingActivated;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.h b/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.h
index b1ce241385..51109a9365 100644
--- a/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkIGTPlayerWidget.h
@@ -1,246 +1,246 @@
/*============================================================================
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 QmitkIGTPlayerWidget_h
#define QmitkIGTPlayerWidget_h
//QT headers
#include <QWidget>
//mitk headers
#include "MitkIGTUIExports.h"
#include <mitkNavigationTool.h>
#include <mitkNavigationDataPlayer.h>
#include <mitkNavigationDataSequentialPlayer.h>
#include <mitkPointSet.h>
//ui header
#include "ui_QmitkIGTPlayerWidgetControls.h"
/** Documentation:
* \brief GUI to access the IGT Player.
* User must specify the file name where the input xml-file is located. The NavigationDatas from the xml-file can be
* played in normal mode or in PointSet mode.
*
* In normal mode the player updates the NavigationDatas every 100ms (can be changed in SetUpdateRate()) and returns
* them when GetNavigationDatas() is called.
* In PointSet mode the player generates a PointSet with all NavigationDatas from the xml-file. So the playback is
* performed on this ND PointSet.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkIGTPlayerWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
/*!
\brief default constructor
*/
- QmitkIGTPlayerWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkIGTPlayerWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
/*!
\brief default deconstructor
*/
~QmitkIGTPlayerWidget() override;
/*!
\brief Sets the real time player for this player widget
*/
//void SetRealTimePlayer(mitk::NavigationDataPlayer::Pointer player);
/*!
\brief Sets the sequential player for this player widget
*/
//void SetSequentialPlayer(mitk::NavigationDataSequentialPlayer::Pointer player);
/*!
\brief Returns the playing timer of this widget
*/
QTimer* GetPlayingTimer();
/*!
\brief Returns the current playback NavigationDatas from the xml-file
*/
const std::vector<mitk::NavigationData::Pointer> GetNavigationDatas();
/*!
\brief Returns a PointSet of the current NavigationDatas for all recorded tools.
*/
const mitk::PointSet::Pointer GetNavigationDatasPointSet();
/*!
\brief Returns a PointType of the current NavigationData for a specific tool with the given index.
*/
const mitk::PointSet::PointType GetNavigationDataPoint(unsigned int index);
/*!
\brief Sets the update rate of this widget's playing timer
*/
void SetUpdateRate(unsigned int msecs);
/*!
\brief Returns the number of different tools from the current playing stream.
*
* Retuns 0 if playback file is invalid.
*/
unsigned int GetNumberOfTools();
/*!
\brief Stops the playback
*/
void StopPlaying();
/*!
\brief Sets the given tool names list to the trajectory select combobox.
*/
void SetTrajectoryNames(const QStringList toolNames);
/*!
\brief Returns the current resolution value from the resolution spinbox.
*/
int GetResolution();
/*!
\brief Clears all items in the trajectory selection combobox.
*/
void ClearTrajectorySelectCombobox();
/*!
\brief Returns whether spline mode checkbox is selected.
*/
bool IsTrajectoryInSplineMode();
enum PlaybackMode { ///< playback mode enum
RealTimeMode = 1,
SequentialMode = 2
};
PlaybackMode GetCurrentPlaybackMode();
signals:
/*!
\brief This signal is emitted when the player starts the playback.
*/
void SignalPlayingStarted();
/*!
\brief This signal is emitted when the player resumes after a pause.
*/
void SignalPlayingResumed();
/*!
\brief This signal is emitted when the player stops.
*/
void SignalPlayingStopped();
/*!
\brief This signal is emitted when the player is paused.
*/
void SignalPlayingPaused();
/*!
\brief This signal is emitted when the player reaches the end of the playback.
*/
void SignalPlayingEnded();
/*!
\brief This signal is emitted every time the player updated the NavigationDatas.
*/
void SignalPlayerUpdated();
/*!
\brief This signal is emitted if the input file for the replay was changed.
*/
void SignalInputFileChanged();
/*!
\brief This signal is emitted if the index of the current selected trajectory select combobox item changes.
*/
void SignalCurrentTrajectoryChanged(int index);
/*!
\brief This signal is emitted if the spline mode checkbox is toggled or untoggled.
*/
void SignalSplineModeToggled(bool toggled);
protected slots:
/*!
\brief Starts or pauses the playback
*/
void OnPlayButtonClicked(bool toggled);
/*!
\brief Updates the playback data
*/
void OnPlaying();
/*!
\brief Stops the playback
*/
void OnStopPlaying();
/*!
\brief Opens file open dialog for searching the input file
*/
void OnOpenFileButtonPressed();
/*!
\brief Stops the playback
*/
void OnGoToEnd();
/*!
\brief Stops the playback and resets the player to the beginning
*/
void OnGoToBegin();
/*!
\brief Switches widget between realtime and sequential mode
*/
void OnSequencialModeToggled(bool toggled);
/*!
\brief Pauses playback when slider is pressed by user
*/
void OnSliderPressed();
/*!
\brief Moves player position to the position selected with the slider
*/
void OnSliderReleased();
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
/*!
\brief Checks if an imput file with the set filename exists
*/
bool CheckInputFileValid();
/*!
\brief Sets all LCD numbers to 0
*/
void ResetLCDNumbers();
mitk::NavigationDataPlayer::Pointer m_RealTimePlayer; ///< plays NDs from a XML file
mitk::NavigationDataSequentialPlayer::Pointer m_SequentialPlayer;
mitk::NavigationData::TimeStampType m_StartTime; ///< start time of playback needed for time display
unsigned int m_CurrentSequentialPointNumber; ///< current point number
Ui::QmitkIGTPlayerWidgetControls* m_Controls;
QString m_CmpFilename; ///< filename of the input file
QTimer* m_PlayingTimer; ///< update timer
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkInteractiveTransformationWidget.h b/Modules/IGTUI/Qmitk/QmitkInteractiveTransformationWidget.h
index ae6c9993ca..67271ebb01 100644
--- a/Modules/IGTUI/Qmitk/QmitkInteractiveTransformationWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkInteractiveTransformationWidget.h
@@ -1,97 +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 QmitkInteractiveTransformationWidget_h
#define QmitkInteractiveTransformationWidget_h
//QT headers
#include <QDialog>
//Mitk headers
#include "MitkIGTUIExports.h"
#include "mitkVector.h"
#include "mitkGeometry3D.h"
#include "mitkNavigationTool.h"
//ui header
#include "ui_QmitkInteractiveTransformationWidgetControls.h"
/** Documentation:
* \brief An object of this class offers an UI to create a widget to access the advanced tool creation options.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkInteractiveTransformationWidget : public QDialog
{
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkInteractiveTransformationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkInteractiveTransformationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkInteractiveTransformationWidget() override;
/** This tool will be copied to m_ToolToEdit. It will not be changed.
To apply any changes made by this widget, you will need to connect to the signal
EditToolTipFinished(mitk::AffineTransform3D::Pointer toolTip) and set this transfrom
as calibrated tool tip.
We do not directly modify the tool to allow to cancel/exit this widget without doing
any harm.
*/
void SetToolToEdit(const mitk::NavigationTool::Pointer _tool);
/** The sliders and spinboxes will be set to these values.
When clicking "Revert Changes", sliders will be reseted to these values.
*/
void SetDefaultOffset(const mitk::Point3D _defaultValues);
void SetDefaultRotation(const mitk::Quaternion _defaultValues);
protected slots:
void OnZTranslationValueChanged(double v);
void OnYTranslationValueChanged(double v);
void OnXTranslationValueChanged(double v);
void OnZRotationValueChanged(double v);
void OnYRotationValueChanged(double v);
void OnXRotationValueChanged(double v);
void OnResetGeometryToIdentity();
void OnRevertChanges();
void OnApplyManipulatedToolTip();
void OnCancel();
signals:
void EditToolTipFinished(mitk::AffineTransform3D::Pointer toolTip);
protected:
void reject() override;
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
/*! \brief Method performs the rotation.
\param rotateVector New rotation to be combined with geometry. */
void Rotate(mitk::Vector3D rotateVector);
// Member variables
Ui::QmitkInteractiveTransformationWidgetControls* m_Controls;
mitk::NavigationTool::Pointer m_ToolToEdit; ///< \brief this member holds a copy of the tool that should be edited for visualization
mitk::BaseGeometry::Pointer m_Geometry; ///< \brief The geometry that is manipulated
mitk::BaseGeometry::Pointer m_ResetGeometry; ///< \brief Lifeline to reset to the original geometry
private:
void SetValuesToGUI(const mitk::AffineTransform3D::Pointer _defaultValues);
void SetSynchronizedValuesToSliderAndSpinbox(QDoubleSpinBox* _spinbox, QSlider* _slider, double _value);
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkMicronTrackerWidget.h b/Modules/IGTUI/Qmitk/QmitkMicronTrackerWidget.h
index 0dba9f917b..ee6263c3d9 100644
--- a/Modules/IGTUI/Qmitk/QmitkMicronTrackerWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkMicronTrackerWidget.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 QmitkMicronTrackerWidget_h
#define QmitkMicronTrackerWidget_h
#include "ui_QmitkMicronTrackerWidget.h"
#include "QmitkAbstractTrackingDeviceWidget.h"
/** Documentation:
* \brief Implementation of a configuration widget for Micron Tracking Devices.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkMicronTrackerWidget : public QmitkAbstractTrackingDeviceWidget
{
Q_OBJECT // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
public:
static const std::string VIEW_ID;
- QmitkMicronTrackerWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkMicronTrackerWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkMicronTrackerWidget() override;
void Initialize() override;
signals:
protected slots :
/* @brief Opens a file dialog. The users sets the calibration file which location is then stored in the member m_MTCalibrationFile.*/
void SetMTCalibrationFileClicked();
private:
/// \brief Creation of the connections
void CreateConnections();
void CreateQtPartControl(QWidget *parent);
protected:
QmitkMicronTrackerWidget* Clone(QWidget* parent) const override;
std::string m_MTCalibrationFile;
Ui::QmitkMicronTrackerWidget* m_Controls;
public:
void ResetOutput() override;
void AddOutput(std::string s) override;
mitk::TrackingDevice::Pointer GetTrackingDevice() override;
void StoreUISettings() override;
void LoadUISettings() override;
bool IsDeviceInstalled() override;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkNDIAbstractDeviceWidget.h b/Modules/IGTUI/Qmitk/QmitkNDIAbstractDeviceWidget.h
index 0da032751c..48401160c3 100644
--- a/Modules/IGTUI/Qmitk/QmitkNDIAbstractDeviceWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkNDIAbstractDeviceWidget.h
@@ -1,66 +1,66 @@
/*============================================================================
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 QmitkNDIAbstractDeviceWidget_h
#define QmitkNDIAbstractDeviceWidget_h
#include "MitkIGTUIExports.h"
#include "QmitkAbstractTrackingDeviceWidget.h"
#include "QmitkTrackingDeviceConfigurationWidgetScanPortsWorker.h"
/** Documentation:
* \brief Abstract class of a configuration widget for NDI Devices.
* For implementations see NDIAuroraWidget or NDIPolarisWidget.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkNDIAbstractDeviceWidget : public QmitkAbstractTrackingDeviceWidget
{
Q_OBJECT // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
public:
static const std::string VIEW_ID;
- QmitkNDIAbstractDeviceWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkNDIAbstractDeviceWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkNDIAbstractDeviceWidget() override;
void Initialize() override = 0;
void AddOutput(std::string s) override = 0;
signals:
void PortsScanned(int Port, QString result, int PortType);
protected slots:
/* @brief Scans the serial ports automatically for a connected tracking device. If the method finds a device
* it selects the right type and sets the corresponding port in the widget.
*/
void AutoScanPorts();
/** This slot is called when the port scanning is finished. */
void AutoScanPortsFinished(int Port, QString result, int PortType);
private:
/// \brief Creation of the connections
void CreateConnections();
protected:
void InitializeNDIWidget();
QmitkTrackingDeviceConfigurationWidgetScanPortsWorker* m_ScanPortsWorker;
QThread* m_ScanPortsWorkerThread;
virtual void SetPortValueToGUI(int portValue) = 0;
virtual void SetPortTypeToGUI(int portType) = 0;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkNDIAuroraWidget.h b/Modules/IGTUI/Qmitk/QmitkNDIAuroraWidget.h
index c0e402777d..f75ee840cd 100644
--- a/Modules/IGTUI/Qmitk/QmitkNDIAuroraWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkNDIAuroraWidget.h
@@ -1,58 +1,58 @@
/*============================================================================
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 QmitkNDIAuroraWidget_h
#define QmitkNDIAuroraWidget_h
#include "ui_QmitkNDIAuroraWidget.h"
#include "QmitkNDIAbstractDeviceWidget.h"
/** Documentation:
* \brief Implementation of a configuration widget for NDI Aurora Devices.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkNDIAuroraWidget : public QmitkNDIAbstractDeviceWidget
{
Q_OBJECT // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
public:
static const std::string VIEW_ID;
- QmitkNDIAuroraWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkNDIAuroraWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkNDIAuroraWidget() override;
void Initialize() override;
private:
/// \brief Creation of the connections
void CreateConnections();
void CreateQtPartControl(QWidget *parent);
protected:
void ResetOutput() override;
void AddOutput(std::string s) override;
mitk::TrackingDevice::Pointer GetTrackingDevice() override;
void StoreUISettings() override;
void LoadUISettings() override;
void SetPortValueToGUI(int portValue) override;
void SetPortTypeToGUI(int portType) override;
QmitkNDIAuroraWidget* Clone(QWidget* parent) const override;
Ui::QmitkNDIAuroraWidget* m_Controls;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkNDIPolarisWidget.h b/Modules/IGTUI/Qmitk/QmitkNDIPolarisWidget.h
index 5afd1471c4..cb93fe658a 100644
--- a/Modules/IGTUI/Qmitk/QmitkNDIPolarisWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkNDIPolarisWidget.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 QmitkNDIPolarisWidget_h
#define QmitkNDIPolarisWidget_h
#include "ui_QmitkNDIPolarisWidget.h"
#include "QmitkNDIAbstractDeviceWidget.h"
/** Documentation:
* \brief Implementation of a configuration widget for NDI Polaris Devices.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkNDIPolarisWidget : public QmitkNDIAbstractDeviceWidget
{
Q_OBJECT // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
public:
static const std::string VIEW_ID;
- QmitkNDIPolarisWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkNDIPolarisWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkNDIPolarisWidget() override;
void Initialize() override;
signals:
protected slots :
private:
/// \brief Creation of the connections
void CreateConnections();
void CreateQtPartControl(QWidget *parent);
protected:
/** @return Returns the frame rate set in the m_frameRatePolaris ComboBox
*/
mitk::IlluminationActivationRate GetPolarisFrameRate();
Ui::QmitkNDIPolarisWidget* m_Controls;
void SetPortValueToGUI(int portValue) override;
void SetPortTypeToGUI(int portType) override;
QmitkNDIPolarisWidget* Clone(QWidget* parent) const override;
public:
void ResetOutput() override;
void AddOutput(std::string s) override;
mitk::TrackingDevice::Pointer GetTrackingDevice() override;
void StoreUISettings() override;
void LoadUISettings() override;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkNDIToolDelegate.cpp b/Modules/IGTUI/Qmitk/QmitkNDIToolDelegate.cpp
index 68e577301e..f8381fc851 100644
--- a/Modules/IGTUI/Qmitk/QmitkNDIToolDelegate.cpp
+++ b/Modules/IGTUI/Qmitk/QmitkNDIToolDelegate.cpp
@@ -1,210 +1,210 @@
/*============================================================================
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 "QmitkNDIToolDelegate.h"
#include <QStringList>
#include <QComboBox>
#include <QLabel>
#include <QFileDialog>
#include "QmitkEnums.h"
#include "QmitkDataStorageComboBox.h"
#include "QmitkCustomVariants.h"
#include "mitkDataStorage.h"
#include "mitkNodePredicateBase.h"
#include "QmitkDataStorageComboBox.h"
#include "mitkNDIPassiveTool.h"
Q_DECLARE_METATYPE(mitk::NDIPassiveTool*)
QmitkNDIToolDelegate::QmitkNDIToolDelegate(QObject * parent) : QStyledItemDelegate(parent),
m_Types(), m_DataStorage(nullptr), m_Predicate(nullptr), m_TagProperty(nullptr), m_TagPropertyName()
{
}
QWidget* QmitkNDIToolDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (index.isValid() == false)
return QStyledItemDelegate::createEditor(parent, option, index);
switch (index.column())
{
case SROMCol:
{
return new QLabel("", parent);
}
case TypeCol:
{
auto c = new QComboBox(parent);
c->addItems(m_Types);
return c;
}
case NodeCol:
{
return new QmitkDataStorageComboBox(m_DataStorage, m_Predicate, parent);
}
case IndexCol:
case NameCol:
case StatusCol:
default:
return QStyledItemDelegate::createEditor(parent, option, index);
}
}
void QmitkNDIToolDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
if (index.isValid() == false)
return;
switch (index.column())
{
case SROMCol:
{
QLabel* l = qobject_cast<QLabel*>(editor);
if (l->text().isEmpty())
{
QString fileName = index.data(/*mitk::FileNameRole*/).value<QString>();
fileName = QFileDialog::getOpenFileName(editor, "Open SROM file", fileName, "SROM files (*.rom)");
QLabel* l = qobject_cast<QLabel*>(editor);
l->setText(fileName);
}
return;
}
case TypeCol:
{
QString type = index.data(/*mitk::TypeRole*/).value<QString>();
QComboBox* c = qobject_cast<QComboBox*>(editor);
c->setCurrentIndex(c->findText(type));
connect(c, SIGNAL(currentIndexChanged(int)), this, SLOT(ComboBoxCurrentIndexChanged(int)));
return;
}
case NodeCol:
{
mitk::DataNode::Pointer n = index.data(/*mitk::OrganNodeRole*/).value<mitk::DataNode::Pointer>();
if (n.IsNotNull())
{
QmitkDataStorageComboBox* dsc = qobject_cast<QmitkDataStorageComboBox*>(editor);
dsc->setCurrentIndex(dsc->findText(QString::fromStdString(n->GetName())));
connect(dsc, SIGNAL(currentIndexChanged(int)), this, SLOT(ComboBoxCurrentIndexChanged(int)));
}
return;
}
case IndexCol:
case NameCol:
case StatusCol:
default:
QStyledItemDelegate::setEditorData(editor, index);
}
}
void QmitkNDIToolDelegate::setModelData(QWidget *editor, QAbstractItemModel* model, const QModelIndex &index) const
{
if (index.isValid() == false)
return;
switch (index.column())
{
case SROMCol:
{
QLabel* l = qobject_cast<QLabel*>(editor);
//model->setData(index, l->text(), mitk::FileNameRole);
//model->setData(index, l->text(), Qt::DisplayRole); // use for display too
model->setData(index, l->text()); // use for display too
return;
}
case TypeCol:
{
QComboBox* c = qobject_cast<QComboBox*>(editor);
//model->setData(index, c->currentText(), mitk::TypeRole);
model->setData(index, c->currentText(), Qt::DisplayRole);
return;
}
case NodeCol:
{
QmitkDataStorageComboBox* dsc = qobject_cast<QmitkDataStorageComboBox*>(editor);
if (dsc->GetSelectedNode().IsNotNull())
{
- model->setData(index, qVariantFromValue(dsc->GetSelectedNode()), OrganNodeRole);
+ model->setData(index, QVariant::fromValue(dsc->GetSelectedNode()), OrganNodeRole);
//model->setData(index, QString::fromStdString(dsc->GetSelectedNode()->GetName()), Qt::DisplayRole);
model->setData(index, QString::fromStdString(dsc->GetSelectedNode()->GetName()));
if ((m_TagProperty.IsNotNull()) && (m_TagPropertyName.empty() == false)) // tag this node as selected
dsc->GetSelectedNode()->SetProperty(m_TagPropertyName.c_str(), m_TagProperty);
}
}
return;
case IndexCol:
case NameCol:
case StatusCol:
default:
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void QmitkNDIToolDelegate::commitAndCloseEditor()
{
//QWidget* editor = 0;
//if(QPushButton *pushBtn = qobject_cast<QPushButton *>(sender()))
//{
//}
//if(editor)
//{
//emit commitData(editor);
//emit closeEditor(editor);
//}
}
void QmitkNDIToolDelegate::ComboBoxCurrentIndexChanged( int /*index*/ )
{
if(QComboBox *comboBox = qobject_cast<QComboBox *>(sender()))
{
emit commitData(comboBox);
emit closeEditor(comboBox);
}
}
void QmitkNDIToolDelegate::SetTypes( const QStringList& types )
{
m_Types = types;
}
void QmitkNDIToolDelegate::SetDataStorage(mitk::DataStorage* ds)
{
m_DataStorage = ds;
}
void QmitkNDIToolDelegate::SetPredicate(mitk::NodePredicateBase::Pointer p)
{
m_Predicate = p;
}
void QmitkNDIToolDelegate::SetTagProperty(mitk::BaseProperty::Pointer prop)
{
m_TagProperty = prop;
}
void QmitkNDIToolDelegate::SetTagPropertyName( const std::string& name )
{
m_TagPropertyName = name;
}
diff --git a/Modules/IGTUI/Qmitk/QmitkNPOptitrackWidget.h b/Modules/IGTUI/Qmitk/QmitkNPOptitrackWidget.h
index db2f71a53c..21694848e8 100644
--- a/Modules/IGTUI/Qmitk/QmitkNPOptitrackWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkNPOptitrackWidget.h
@@ -1,64 +1,64 @@
/*============================================================================
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 QmitkNPOptitrackWidget_h
#define QmitkNPOptitrackWidget_h
#include "ui_QmitkNPOptitrackWidget.h"
#include "QmitkAbstractTrackingDeviceWidget.h"
/** Documentation:
* \brief Implementation of a configuration widget for NP Optitrack Tracking Devices.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkNPOptitrackWidget : public QmitkAbstractTrackingDeviceWidget
{
Q_OBJECT // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
public:
static const std::string VIEW_ID;
- QmitkNPOptitrackWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkNPOptitrackWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkNPOptitrackWidget() override;
void Initialize() override;
signals:
protected slots :
/* @brief Opens a file dialog. The users sets the calibration file which location is then stored in the member m_OptitrackCalibrationFile.*/
void SetOptitrackCalibrationFileClicked();
private:
/// \brief Creation of the connections
void CreateConnections();
void CreateQtPartControl(QWidget *parent);
protected:
QmitkNPOptitrackWidget* Clone(QWidget* parent) const override;
std::string m_OptitrackCalibrationFile;
Ui::QmitkNPOptitrackWidget* m_Controls;
public:
void ResetOutput() override;
void AddOutput(std::string s) override;
mitk::TrackingDevice::Pointer GetTrackingDevice() override;
bool IsDeviceInstalled() override;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.h b/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.h
index 4b59cc2ff9..7231c8bec2 100644
--- a/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.h
@@ -1,97 +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 QmitkNavigationDataSourceSelectionWidget_h
#define QmitkNavigationDataSourceSelectionWidget_h
//QT headers
#include <QWidget>
//mitk headers
#include "MitkIGTUIExports.h"
#include <mitkNavigationToolStorage.h>
#include <mitkNavigationDataSource.h>
#include <usServiceReference.h>
//ui header
#include "ui_QmitkNavigationDataSourceSelectionWidgetControls.h"
/** Documentation:
* \brief This widget allows the user to select a NavigationDataSource. Tools of this Source are also shown and the user can select one of these tools.
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkNavigationDataSourceSelectionWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkNavigationDataSourceSelectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkNavigationDataSourceSelectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkNavigationDataSourceSelectionWidget() override;
/** @return Returns the currently selected NavigationDataSource. Returns null if no source is selected at the moment. */
mitk::NavigationDataSource::Pointer GetSelectedNavigationDataSource();
/** @return Returns the ID of the currently selected tool. You can get the corresponding NavigationData when calling GetOutput(id)
* on the source object. Returns -1 if there is no tool selected.
*/
int GetSelectedToolID();
/** @return Returns the NavigationTool of the current selected tool if a NavigationToolStorage is available. Returns nullptr if
* there is no storage available or if no tool is selected.
*/
mitk::NavigationTool::Pointer GetSelectedNavigationTool();
/** @return Returns the NavigationToolStorage of the currently selected NavigationDataSource. Returns nullptr if there is no
* source selected or if the source has no NavigationToolStorage assigned.
*/
mitk::NavigationToolStorage::Pointer GetNavigationToolStorageOfSource();
signals:
/** @brief This signal is emitted when a new navigation data source is selected.
* @param n Holds the new selected navigation data source. Is null if the old source is deselected and no new source is selected.
*/
void NavigationDataSourceSelected(mitk::NavigationDataSource::Pointer n);
/** @brief This signal is emitted when a new navigation data tool is selected.
* @param n Holds the new selected navigation tool. Is null if the old source is deselected and no new source is selected.
*/
void NavigationToolSelected(mitk::NavigationTool::Pointer n);
protected slots:
void NavigationDataSourceSelected(us::ServiceReferenceU s);
void NavigationToolSelected(int selection);
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkNavigationDataSourceSelectionWidgetControls* m_Controls;
mitk::NavigationToolStorage::Pointer m_CurrentStorage;
mitk::NavigationDataSource::Pointer m_CurrentSource;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.h b/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.h
index df0e4f290c..766da67cc6 100644
--- a/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkNavigationToolCreationWidget.h
@@ -1,142 +1,142 @@
/*============================================================================
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 QmitkNavigationToolCreationWidget_h
#define QmitkNavigationToolCreationWidget_h
//QT headers
#include <QWidget>
//mitk headers
#include "MitkIGTUIExports.h"
#include <mitkNavigationTool.h>
#include <mitkNavigationToolStorage.h>
#include <mitkNodePredicateDataType.h>
#include "QmitkInteractiveTransformationWidget.h"
#include <QDialog>
//Microservices
#include <usGetModuleContext.h>
#include <usModule.h>
#include <usServiceProperties.h>
#include <usModuleContext.h>
//ui header
#include "ui_QmitkNavigationToolCreationWidget.h"
/** Documentation:
* \brief An object of this class offers an UI to create or modify NavigationTools.
*
* Be sure to call the initialize method before you start the widget
* otherwise some errors might occure.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkNavigationToolCreationWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
/** @brief Initializes the widget.
* @param dataStorage The data storage is needed to offer the possibility to choose surfaces from the data storage for tool visualization.
* @param supposedIdentifier This Identifier is supposed for the user. It is needed because every identifier in a navigation tool storage must be unique and we don't know the others.
* @param supposedName
*/
void Initialize(mitk::DataStorage* dataStorage, const std::string &supposedIdentifier, const std::string &supposedName = "NewTool");
/** @brief This Function will add a new node to the Data Manager with given name to enable a preview of the m_ToolToBeEdited
*/
void ShowToolPreview(std::string _name);
/** @brief Sets the default tracking device type. You may also define if it is changeable or not.*/
void SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable = true);
- QmitkNavigationToolCreationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkNavigationToolCreationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkNavigationToolCreationWidget() override;
/** @brief Sets the default data of all input fields. The default data is used from the default tool which is given as parameter. */
void SetDefaultData(mitk::NavigationTool::Pointer DefaultTool);
/** @return Returns the created tool. Returns nullptr if no tool was created yet. */
mitk::NavigationTool::Pointer GetCreatedTool();
signals:
/** @brief This signal is emitted if the user finished the creation of the tool. */
void NavigationToolFinished();
/** @brief This signal is emitted if the user canceled the creation of the tool. */
void Canceled();
protected slots:
void OnLoadCalibrationFile();
void OnSurfaceUseToggled();
void OnLoadSurface();
void OnEditToolTip();
void OnEditToolTipFinished(mitk::AffineTransform3D::Pointer toolTip);
void OnCancel();
void OnFinished();
void GetValuesFromGuiElements();
private:
//############## private help methods #######################
/** Shows a message box with the given message s. */
void MessageBox(std::string s);
/** Set the tool landmark lists in the UI.*/
void FillUIToolLandmarkLists(mitk::PointSet::Pointer calLandmarks, mitk::PointSet::Pointer regLandmarks);
/** Returns the tool landmark lists from the UI.
* @param[out] calLandmarks Returns a pointer to the calibration landmarks point set.
* @param[out] regLandmarks Returns a pointer to the registration landmarks point set.
*/
void GetUIToolLandmarksLists(mitk::PointSet::Pointer& calLandmarks, mitk::PointSet::Pointer& regLandmarks);
/** Initializes the tool landmark lists in the UI. */
void InitializeUIToolLandmarkLists();
void RefreshTrackingDeviceCollection();
void SetGuiElements();
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkNavigationToolCreationWidgetControls* m_Controls;
/** @brief this pointer holds the tool which is edited. If finished is clicked, it will be copied to the final tool, if it is cancled, it is reseted and not used.
This can be regarded as the clipboard for all changes. */
mitk::NavigationTool::Pointer m_ToolToBeEdited;
/** @brief this pointer holds the tool which is created and returned */
mitk::NavigationTool::Pointer m_FinalTool;
QmitkInteractiveTransformationWidget* m_ToolTransformationWidget;
/** @brief holds the DataStorage */
mitk::DataStorage* m_DataStorage;
/** Hold the data nodes which are needed for the landmark widgets. */
mitk::DataNode::Pointer m_calLandmarkNode, m_regLandmarkNode;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkNavigationToolManagementWidget.h b/Modules/IGTUI/Qmitk/QmitkNavigationToolManagementWidget.h
index 7364498e2d..21d8fc778d 100644
--- a/Modules/IGTUI/Qmitk/QmitkNavigationToolManagementWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkNavigationToolManagementWidget.h
@@ -1,109 +1,109 @@
/*============================================================================
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 QmitkNavigationToolManagementWidget_h
#define QmitkNavigationToolManagementWidget_h
//QT headers
#include <QWidget>
//mitk headers
#include "MitkIGTUIExports.h"
#include "mitkNavigationTool.h"
#include <mitkNavigationToolStorage.h>
//ui header
#include "ui_QmitkNavigationToolManagementWidgetControls.h"
/** Documentation:
* \brief An object of this class offers an UI to manage NavigationTools and
* NavigationToolStorages. This means a user may create, save and load
* single NavigationTools and/or NavigationToolStorages with this widget.
*
* Be sure to call the Initialize-methode before you start the widget
* otherwise some errors might occure.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkNavigationToolManagementWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
/** Initializes the widget. Has to be called before any action, otherwise errors might occur. */
void Initialize(mitk::DataStorage* dataStorage);
/** Loads a storage to the widget. The old storage storage is dropped, so be careful, if the
* storage is not saved somewhere else it might be lost. You might want to ask the user if he
* wants to save the storage to the harddisk before calling this method.
* @param storageToLoad This storage will be loaded and might be modified by the user.
*/
void LoadStorage(mitk::NavigationToolStorage::Pointer storageToLoad);
- QmitkNavigationToolManagementWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkNavigationToolManagementWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkNavigationToolManagementWidget() override;
signals:
/** This signal is emmited if a new storage was added by the widget itself, e.g. because
* a storage was loaded from the harddisk.
* @param newStorage Holds the new storage which was added.
* @param storageName Name of the new storage (e.g. filename)
*/
void NewStorageAdded(mitk::NavigationToolStorage::Pointer newStorage, std::string storageName);
protected slots:
//main widget page:
void OnAddTool();
void OnDeleteTool();
void OnEditTool();
void OnLoadTool();
void OnSaveTool();
void OnMoveToolUp();
void OnMoveToolDown();
void OnLoadStorage();
void OnSaveStorage();
void OnCreateStorage();
void OnToolSelected();
//widget page "add tool":
void OnAddToolCancel();
void OnAddToolSave();
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkNavigationToolManagementWidgetControls* m_Controls;
/** @brief holds the DataStorage */
mitk::DataStorage* m_DataStorage;
/** @brief holds the NavigationToolStorage we are working with. */
mitk::NavigationToolStorage::Pointer m_NavigationToolStorage;
/** @brief shows if we are in edit mode, if not we create new navigation tool objects. */
bool m_edit;
//############## private help methods #######################
void MessageBox(const std::string &s);
void UpdateToolTable();
void DisableStorageControls();
void EnableStorageControls();
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkNavigationToolStorageSelectionWidget.h b/Modules/IGTUI/Qmitk/QmitkNavigationToolStorageSelectionWidget.h
index 7a05db02c4..0bac5b728e 100644
--- a/Modules/IGTUI/Qmitk/QmitkNavigationToolStorageSelectionWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkNavigationToolStorageSelectionWidget.h
@@ -1,78 +1,78 @@
/*============================================================================
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 QmitkNavigationToolStorageSelectionWidget_h
#define QmitkNavigationToolStorageSelectionWidget_h
//QT headers
#include <QWidget>
//mitk headers
#include "MitkIGTUIExports.h"
#include <mitkNavigationToolStorage.h>
#include <mitkNavigationDataSource.h>
#include <usServiceReference.h>
//ui header
#include "ui_QmitkNavigationToolStorageSelectionWidgetControls.h"
/** Documentation:
* \brief This widget allows the user to select a navigation tool storage.
*
* The widget lists all navigation tool storages which are available
* as microservice via the module context.
*
* A signal is emmited whenever the tool selection changes.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkNavigationToolStorageSelectionWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkNavigationToolStorageSelectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkNavigationToolStorageSelectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkNavigationToolStorageSelectionWidget() override;
/** @return Returns the currently selected NavigationToolStorage. Returns null if no storage is selected at the moment. */
mitk::NavigationToolStorage::Pointer GetSelectedNavigationToolStorage();
signals:
/** @brief This signal is emitted when a new navigation tool storage is selected.
* @param storage Holds the new selected navigation tool storage. Is null if the old storage is deselected and no new storage is selected.
*/
void NavigationToolStorageSelected(mitk::NavigationToolStorage::Pointer storage);
protected slots:
void NavigationToolStorageSelected(us::ServiceReferenceU s);
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkNavigationToolStorageSelectionWidgetControls* m_Controls;
mitk::NavigationToolStorage::Pointer m_CurrentStorage;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkOpenIGTLinkWidget.h b/Modules/IGTUI/Qmitk/QmitkOpenIGTLinkWidget.h
index 84eab80655..8dcc066d76 100644
--- a/Modules/IGTUI/Qmitk/QmitkOpenIGTLinkWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkOpenIGTLinkWidget.h
@@ -1,50 +1,50 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkOpenIGTLinkWidget_h
#define QmitkOpenIGTLinkWidget_h
#include "ui_QmitkOpenIGTLinkWidget.h"
#include "QmitkAbstractTrackingDeviceWidget.h"
/** Documentation:
* \brief Implementation of a configuration widget to use an Open IGT Link connection to track any device.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkOpenIGTLinkWidget : public QmitkAbstractTrackingDeviceWidget
{
Q_OBJECT // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
public:
static const std::string VIEW_ID;
- QmitkOpenIGTLinkWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkOpenIGTLinkWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkOpenIGTLinkWidget() override;
void Initialize() override;
signals:
protected slots :
private:
void CreateQtPartControl(QWidget *parent);
protected:
QmitkOpenIGTLinkWidget* Clone(QWidget* parent) const override;
Ui::QmitkOpenIGTLinkWidget* m_Controls;
public:
mitk::TrackingDevice::Pointer GetTrackingDevice() override;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkTrackingDeviceConfigurationWidget.h b/Modules/IGTUI/Qmitk/QmitkTrackingDeviceConfigurationWidget.h
index 235850ef6d..04ce752642 100644
--- a/Modules/IGTUI/Qmitk/QmitkTrackingDeviceConfigurationWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkTrackingDeviceConfigurationWidget.h
@@ -1,131 +1,131 @@
/*============================================================================
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 QmitkTrackingDeviceConfigurationWidget_h
#define QmitkTrackingDeviceConfigurationWidget_h
#include <QWidget>
#include <QThread>
#include "MitkIGTUIExports.h"
#include "ui_QmitkTrackingDeviceConfigurationWidgetControls.h"
#include "mitkTrackingDeviceTypeCollection.h"
#include "mitkTrackingDeviceWidgetCollection.h"
/** Documentation:
* \brief An object of this class offers an UI to configurate
* a tracking device. If the user finished the configuration process and
* a fully configurated tracking device is availiabe the object emits a
* signal "TrackingDeviceConfigurationFinished()". You can then get the
* tracking device by calling the method GetTrackingDevice().
*
* Once the tracking device is configurated there are two ways to reset
* the UI to allow the user for configuring a new device. The method Reset()
* can be called and there is also a button "reset" which can be pressed by
* the user. In both cases a signal "TrackingDeviceConfigurationReseted()"
* is emitted and you may wait for a new configurated tracking device.
*
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkTrackingDeviceConfigurationWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkTrackingDeviceConfigurationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkTrackingDeviceConfigurationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkTrackingDeviceConfigurationWidget() override;
/* @return Returns the current configurated tracking device. If the user didn't finished the
* configuration process or if there is an error during configuration nullptr is returned.
*/
mitk::TrackingDevice::Pointer GetTrackingDevice();
/**
* \brief This function is called, when anything in the ToolStorage changed, e.g. AddTool or EditTool.
* ServiceListener is connected in the QmitkMITKIGTTrackingToolboxView.
*/
void OnToolStorageChanged();
signals:
/* @brief This signal is sent if the tracking device was changed. */
void TrackingDeviceSelectionChanged();
public slots:
/**
* \brief This function is called, when in the TrackingToolboxView "Connect" was clicked and the device is successful connected.
* Can e.g. be used to activate options of a tracking device only when it is connected.
*/
void OnConnected(bool _success);
/**
* \brief This function is called, when in the TrackingToolboxView "Disconnect" was clicked and the device is successful disconnected.
* Can e.g. be used to activate/disactivate options of a tracking device.
*/
void OnDisconnected(bool _success);
/**
* \brief This function is called, when in the TrackingToolboxView "Start Tracking" was clicked and the device successfully started tracking.
* Can e.g. be used to activate options of a tracking device only when tracking is started.
*/
void OnStartTracking(bool _success);
/**
* \brief This function is called, when in the TrackingToolboxView "Stop Tracking" was clicked and the device successful stopped tracking.
* Can e.g. be used to activate/disactivate options when device is not tracking.
*/
void OnStopTracking(bool _success);
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkTrackingDeviceConfigurationWidgetControls* m_Controls;
// key is port name (e.g. "COM1", "/dev/ttyS0"), value will be filled with the type of tracking device at this port
typedef QMap<QString, mitk::TrackingDeviceType> PortDeviceMap;
//######################### internal help methods #######################################
void ResetOutput();
void AddOutput(std::string s);
void StoreUISettings();
void LoadUISettings();
/* @brief This method is called when the user clicks on "Refresh Selection" (m_RefreshTrackingDeviceCollection).
It then sets the correct widget for the selected tracking device.*/
void RefreshTrackingDeviceCollection();
protected slots:
/* @brief This method is called when the user changes the selection of the trackingdevice (m_trackingDeviceChooser).
It then sets the correct widget for the selected tracking device.*/
void TrackingDeviceChanged();
private:
PERSISTENCE_GET_SERVICE_METHOD_MACRO
std::string GetCurrentDeviceName(void) const;
QmitkAbstractTrackingDeviceWidget* GetWidget(const std::string& deviceName) const;
/**
* @brief Mapping of device type identifier and index of the configuration widget in QStackedWidget.
*/
std::map<std::string, int> m_DeviceToWidgetIndexMap;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkTrackingDeviceWidget.h b/Modules/IGTUI/Qmitk/QmitkTrackingDeviceWidget.h
index 4bab5c6cca..104fe84b82 100644
--- a/Modules/IGTUI/Qmitk/QmitkTrackingDeviceWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkTrackingDeviceWidget.h
@@ -1,29 +1,29 @@
/*============================================================================
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 QmitkTrackingDeviceWidget_h
#define QmitkTrackingDeviceWidget_h
#include <QWidget>
#include "MitkIGTUIExports.h"
class MITKIGTUI_EXPORT QmitkTrackingDeviceWidget : public QWidget //MITKIGTUI_EXPORT
{
Q_OBJECT
public:
- QmitkTrackingDeviceWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkTrackingDeviceWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkTrackingDeviceWidget() override;
};
#endif
diff --git a/Modules/IGTUI/Qmitk/QmitkVirtualTrackerWidget.h b/Modules/IGTUI/Qmitk/QmitkVirtualTrackerWidget.h
index 93b77f5fde..2bf6b2362b 100644
--- a/Modules/IGTUI/Qmitk/QmitkVirtualTrackerWidget.h
+++ b/Modules/IGTUI/Qmitk/QmitkVirtualTrackerWidget.h
@@ -1,57 +1,57 @@
/*============================================================================
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 QmitkVirtualTrackerWidget_h
#define QmitkVirtualTrackerWidget_h
#include "ui_QmitkVirtualTrackerWidget.h"
#include "QmitkAbstractTrackingDeviceWidget.h"
/** Documentation:
* \brief Implementation of a configuration widget for a Vitrual Tracking Device.
*
* \ingroup IGTUI
*/
class MITKIGTUI_EXPORT QmitkVirtualTrackerWidget : public QmitkAbstractTrackingDeviceWidget
{
Q_OBJECT // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
public:
static const std::string VIEW_ID;
- QmitkVirtualTrackerWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkVirtualTrackerWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkVirtualTrackerWidget() override;
void Initialize() override;
signals:
protected slots :
/* @brief Enables or disables the Gaussian Noise for the VirtualTrackingDevice dependent on the State of the according Checkbox */
void EnableGaussianNoise();
private:
/// \brief Creation of the connections
void CreateConnections();
void CreateQtPartControl(QWidget *parent);
protected:
QmitkVirtualTrackerWidget* Clone(QWidget* parent) const override;
Ui::QmitkVirtualTrackerWidget* m_Controls;
public:
mitk::TrackingDevice::Pointer GetTrackingDevice() override;
};
#endif
diff --git a/Modules/ImageStatisticsUI/Qmitk/QmitkImageStatisticsTreeModel.cpp b/Modules/ImageStatisticsUI/Qmitk/QmitkImageStatisticsTreeModel.cpp
index 738628cf24..65c86e2024 100644
--- a/Modules/ImageStatisticsUI/Qmitk/QmitkImageStatisticsTreeModel.cpp
+++ b/Modules/ImageStatisticsUI/Qmitk/QmitkImageStatisticsTreeModel.cpp
@@ -1,424 +1,424 @@
/*============================================================================
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 "QmitkImageStatisticsTreeModel.h"
#include "QmitkImageStatisticsTreeItem.h"
#include "mitkImageStatisticsContainerManager.h"
#include "mitkProportionalTimeGeometry.h"
#include "mitkStatisticsToImageRelationRule.h"
#include "mitkStatisticsToMaskRelationRule.h"
#include "QmitkStyleManager.h"
QmitkImageStatisticsTreeModel::QmitkImageStatisticsTreeModel(QObject *parent) : QmitkAbstractDataStorageModel(parent)
{
m_RootItem = new QmitkImageStatisticsTreeItem();
}
QmitkImageStatisticsTreeModel ::~QmitkImageStatisticsTreeModel()
{
// set data storage to nullptr so that the event listener gets removed
this->SetDataStorage(nullptr);
delete m_RootItem;
};
void QmitkImageStatisticsTreeModel::DataStorageChanged()
{
emit beginResetModel();
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
void QmitkImageStatisticsTreeModel::NodePredicateChanged()
{
emit beginResetModel();
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
int QmitkImageStatisticsTreeModel::columnCount(const QModelIndex& /*parent*/) const
{
int columns = m_StatisticNames.size() + 1;
return columns;
}
int QmitkImageStatisticsTreeModel::rowCount(const QModelIndex &parent) const
{
QmitkImageStatisticsTreeItem *parentItem;
if (parent.column() > 0)
return 0;
if (!parent.isValid())
parentItem = m_RootItem;
else
parentItem = static_cast<QmitkImageStatisticsTreeItem *>(parent.internalPointer());
return parentItem->childCount();
}
QVariant QmitkImageStatisticsTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
QmitkImageStatisticsTreeItem* item = static_cast<QmitkImageStatisticsTreeItem*>(index.internalPointer());
if (role == Qt::DisplayRole)
{
return item->data(index.column());
}
else if (role == Qt::DecorationRole && index.column() == 0 && item->isWIP() && item->childCount()==0)
{
return QVariant(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/hourglass-half-solid.svg")));
}
return QVariant();
}
QModelIndex QmitkImageStatisticsTreeModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
QmitkImageStatisticsTreeItem *parentItem;
if (!parent.isValid())
parentItem = m_RootItem;
else
parentItem = static_cast<QmitkImageStatisticsTreeItem *>(parent.internalPointer());
QmitkImageStatisticsTreeItem *childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex QmitkImageStatisticsTreeModel::parent(const QModelIndex &child) const
{
if (!child.isValid())
return QModelIndex();
QmitkImageStatisticsTreeItem *childItem = static_cast<QmitkImageStatisticsTreeItem *>(child.internalPointer());
QmitkImageStatisticsTreeItem *parentItem = childItem->parentItem();
if (parentItem == m_RootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);
}
Qt::ItemFlags QmitkImageStatisticsTreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
- return nullptr;
+ return {};
return QAbstractItemModel::flags(index);
}
QVariant QmitkImageStatisticsTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if ((Qt::DisplayRole == role) && (Qt::Horizontal == orientation))
{
if (section == 0)
{
return m_HeaderFirstColumn;
}
else
{
return QVariant(m_StatisticNames.at(section - 1).c_str());
}
}
return QVariant();
}
void QmitkImageStatisticsTreeModel::SetImageNodes(const std::vector<mitk::DataNode::ConstPointer> &nodes)
{
std::vector<std::pair<mitk::DataNode::ConstPointer, unsigned int>> tempNodes;
for (const auto &node : nodes)
{
auto data = node->GetData();
if (data)
{
auto timeSteps = data->GetTimeSteps();
for (unsigned int i = 0; i < timeSteps; i++)
{
tempNodes.push_back(std::make_pair(node, i));
}
}
}
emit beginResetModel();
m_TimeStepResolvedImageNodes = std::move(tempNodes);
m_ImageNodes = nodes;
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
void QmitkImageStatisticsTreeModel::SetMaskNodes(const std::vector<mitk::DataNode::ConstPointer> &nodes)
{
std::vector<std::pair<mitk::DataNode::ConstPointer, unsigned int>> tempNodes;
for (const auto &node : nodes)
{
auto data = node->GetData();
if (data)
{
auto timeSteps = data->GetTimeSteps();
// special case: apply one mask to each timestep of an 4D image
if (timeSteps == 1 && m_TimeStepResolvedImageNodes.size() > 1)
{
timeSteps = m_TimeStepResolvedImageNodes.size();
}
for (unsigned int i = 0; i < timeSteps; i++)
{
tempNodes.push_back(std::make_pair(node, i));
}
}
}
emit beginResetModel();
m_TimeStepResolvedMaskNodes = std::move(tempNodes);
m_MaskNodes = nodes;
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
void QmitkImageStatisticsTreeModel::Clear()
{
emit beginResetModel();
m_Statistics.clear();
m_ImageNodes.clear();
m_TimeStepResolvedImageNodes.clear();
m_MaskNodes.clear();
m_StatisticNames.clear();
emit endResetModel();
emit modelChanged();
}
void QmitkImageStatisticsTreeModel::SetIgnoreZeroValueVoxel(bool _arg)
{
if (m_IgnoreZeroValueVoxel != _arg)
{
emit beginResetModel();
m_IgnoreZeroValueVoxel = _arg;
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
}
bool QmitkImageStatisticsTreeModel::GetIgnoreZeroValueVoxel() const
{
return this->m_IgnoreZeroValueVoxel;
}
void QmitkImageStatisticsTreeModel::SetHistogramNBins(unsigned int nbins)
{
if (m_HistogramNBins != nbins)
{
emit beginResetModel();
m_HistogramNBins = nbins;
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
}
unsigned int QmitkImageStatisticsTreeModel::GetHistogramNBins() const
{
return this->m_HistogramNBins;
}
void QmitkImageStatisticsTreeModel::UpdateByDataStorage()
{
StatisticsContainerVector newStatistics;
auto datamanager = m_DataStorage.Lock();
if (datamanager.IsNotNull())
{
for (const auto &image : m_ImageNodes)
{
if (m_MaskNodes.empty())
{
auto stats = mitk::ImageStatisticsContainerManager::GetImageStatistics(datamanager, image->GetData(), nullptr, m_IgnoreZeroValueVoxel, m_HistogramNBins, true, false);
if (stats.IsNotNull())
{
newStatistics.emplace_back(stats);
}
}
else
{
for (const auto &mask : m_MaskNodes)
{
auto stats =
mitk::ImageStatisticsContainerManager::GetImageStatistics(datamanager, image->GetData(), mask->GetData(), m_IgnoreZeroValueVoxel, m_HistogramNBins, true, false);
if (stats.IsNotNull())
{
newStatistics.emplace_back(stats);
}
}
}
}
if (!newStatistics.empty())
{
emit dataAvailable();
}
}
{
std::lock_guard<std::mutex> locked(m_Mutex);
m_Statistics = newStatistics;
}
m_StatisticNames = mitk::GetAllStatisticNames(m_Statistics);
BuildHierarchicalModel();
}
void QmitkImageStatisticsTreeModel::BuildHierarchicalModel()
{
// reset old model
delete m_RootItem;
m_RootItem = new QmitkImageStatisticsTreeItem();
bool hasMask = false;
bool hasMultipleTimesteps = false;
std::map<mitk::DataNode::ConstPointer, QmitkImageStatisticsTreeItem *> dataNodeToTreeItem;
for (const auto &statistic : m_Statistics)
{
bool isWIP = statistic->GetProperty(mitk::STATS_GENERATION_STATUS_PROPERTY_NAME.c_str()).IsNotNull();
// get the connected image data node/mask data node
auto imageRule = mitk::StatisticsToImageRelationRule::New();
auto imageOfStatisticsPredicate = imageRule->GetDestinationsDetector(statistic);
auto imageFinding = std::find_if(m_ImageNodes.begin(), m_ImageNodes.end(), [&imageOfStatisticsPredicate](const mitk::DataNode::ConstPointer& testNode) { return imageOfStatisticsPredicate->CheckNode(testNode); });
auto maskRule = mitk::StatisticsToMaskRelationRule::New();
auto maskOfStatisticsPredicate = maskRule->GetDestinationsDetector(statistic);
auto maskFinding = std::find_if(m_MaskNodes.begin(), m_MaskNodes.end(), [&maskOfStatisticsPredicate](const mitk::DataNode::ConstPointer& testNode) { return maskOfStatisticsPredicate->CheckNode(testNode); });
if (imageFinding == m_ImageNodes.end())
{
mitkThrow() << "no image found connected to statistic" << statistic << " Aborting.";
}
auto& image = *imageFinding;
// image: 1. hierarchy level
QmitkImageStatisticsTreeItem *imageItem = nullptr;
auto search = dataNodeToTreeItem.find(image);
// the tree item was created previously
if (search != dataNodeToTreeItem.end())
{
imageItem = search->second;
}
// create the tree item
else
{
QString imageLabel = QString::fromStdString(image->GetName());
if (statistic->GetTimeSteps() == 1 && maskFinding == m_MaskNodes.end())
{
auto statisticsObject = statistic->GetStatisticsForTimeStep(0);
imageItem = new QmitkImageStatisticsTreeItem(statisticsObject, m_StatisticNames, imageLabel, isWIP, m_RootItem);
}
else
{
imageItem = new QmitkImageStatisticsTreeItem(m_StatisticNames, imageLabel, isWIP, m_RootItem);
}
m_RootItem->appendChild(imageItem);
dataNodeToTreeItem.emplace(image, imageItem);
}
// mask: 2. hierarchy level (optional, only if mask exists)
QmitkImageStatisticsTreeItem *lastParent = nullptr;
if (maskFinding != m_MaskNodes.end())
{
auto& mask = *maskFinding;
QString maskLabel = QString::fromStdString(mask->GetName());
QmitkImageStatisticsTreeItem *maskItem;
// add statistical values directly in this hierarchy level
if (statistic->GetTimeSteps() == 1)
{
auto statisticsObject = statistic->GetStatisticsForTimeStep(0);
maskItem = new QmitkImageStatisticsTreeItem(statisticsObject, m_StatisticNames, maskLabel, isWIP, imageItem);
}
else
{
maskItem = new QmitkImageStatisticsTreeItem(m_StatisticNames, maskLabel, isWIP, imageItem);
}
imageItem->appendChild(maskItem);
lastParent = maskItem;
hasMask = true;
}
else
{
lastParent = imageItem;
}
// 3. hierarchy level (optional, only if >1 timestep)
if (statistic->GetTimeSteps() > 1)
{
for (unsigned int i = 0; i < statistic->GetTimeSteps(); i++)
{
QString timeStepLabel = "[" + QString::number(i) + "] " +
QString::number(statistic->GetTimeGeometry()->TimeStepToTimePoint(i)) + " ms";
if (statistic->TimeStepExists(i))
{
auto statisticsItem = new QmitkImageStatisticsTreeItem(
statistic->GetStatisticsForTimeStep(i), m_StatisticNames, timeStepLabel, isWIP, lastParent);
lastParent->appendChild(statisticsItem);
}
}
hasMultipleTimesteps = true;
}
}
QString headerString = "Images";
if (hasMask)
{
headerString += "/Masks";
}
if (hasMultipleTimesteps)
{
headerString += "/Timesteps";
}
m_HeaderFirstColumn = headerString;
}
void QmitkImageStatisticsTreeModel::NodeRemoved(const mitk::DataNode *)
{
emit beginResetModel();
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
void QmitkImageStatisticsTreeModel::NodeAdded(const mitk::DataNode *)
{
emit beginResetModel();
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
void QmitkImageStatisticsTreeModel::NodeChanged(const mitk::DataNode *)
{
emit beginResetModel();
UpdateByDataStorage();
emit endResetModel();
emit modelChanged();
}
diff --git a/Modules/ImageStatisticsUI/Qmitk/QmitkStatisticsModelToStringConverter.cpp b/Modules/ImageStatisticsUI/Qmitk/QmitkStatisticsModelToStringConverter.cpp
index 9ddad668b6..fbcc3f80cd 100644
--- a/Modules/ImageStatisticsUI/Qmitk/QmitkStatisticsModelToStringConverter.cpp
+++ b/Modules/ImageStatisticsUI/Qmitk/QmitkStatisticsModelToStringConverter.cpp
@@ -1,128 +1,128 @@
/*============================================================================
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 "QmitkStatisticsModelToStringConverter.h"
#include "mitkExceptionMacro.h"
QmitkStatisticsModelToStringConverter::QmitkStatisticsModelToStringConverter() {}
void QmitkStatisticsModelToStringConverter::SetModel(QmitkImageStatisticsTreeModel *model)
{
m_statisticsModel = model;
}
void QmitkStatisticsModelToStringConverter::SetRootIndex(QModelIndex rootIndex)
{
m_rootIndex = rootIndex;
}
QString QmitkStatisticsModelToStringConverter::GetString() const
{
if (m_statisticsModel == nullptr)
{
mitkThrow() << "Cannot convert TableModel to String: TableModel is nullptr";
}
QString textData;
int columns = m_statisticsModel->columnCount();
if (m_includeHeaderData)
{
for (int i = 0; i < columns; i++)
{
if (i > 0)
{
textData += m_columnDelimiter;
}
textData += m_statisticsModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
}
textData += m_rowDelimiter;
}
textData += Iterate(m_rootIndex, m_statisticsModel);
return textData;
}
void QmitkStatisticsModelToStringConverter::SetRowDelimiter(QChar rowDelimiter)
{
m_rowDelimiter = rowDelimiter;
}
void QmitkStatisticsModelToStringConverter::SetColumnDelimiter(QChar columnDelimiter)
{
m_columnDelimiter = columnDelimiter;
}
void QmitkStatisticsModelToStringConverter::SetIncludeHeaderData(bool includeHeaderData)
{
m_includeHeaderData = includeHeaderData;
}
QString QmitkStatisticsModelToStringConverter::Iterate(const QModelIndex &index,
const QmitkImageStatisticsTreeModel *model,
QString label) const
{
QString content;
if (model->hasChildren(index))
{
if (index.isValid())
{
label += index.data().toString() + QString(" >> ");
}
auto rows = model->rowCount(index);
for (int r = 0; r < rows; ++r)
{
auto childIndex = model->index(r, 0, index);
if (model->hasChildren(childIndex))
{
content += Iterate(childIndex, model, label);
}
else
{
content += label;
auto cols = model->columnCount(index);
for (int c = 0; c < cols; ++c)
{
if (c > 0)
{
content += m_columnDelimiter;
}
auto columnChildIndex = model->index(r, c, index);
content += Iterate(columnChildIndex, model, label);
}
content += m_rowDelimiter;
}
}
}
else
{
if (index.isValid())
{
auto data = index.data();
- if (static_cast<QMetaType::Type>(data.type()) == QMetaType::Double)
+ if (data.typeId() == QMetaType::Double)
{
content = QString("%L1").arg(data.toDouble(), 0, 'f');
}
else
{
content = data.toString();
}
}
}
return content;
}
diff --git a/Modules/MatchPointRegistration/CMakeLists.txt b/Modules/MatchPointRegistration/CMakeLists.txt
index e2b6e37ba9..9a1df23fcd 100644
--- a/Modules/MatchPointRegistration/CMakeLists.txt
+++ b/Modules/MatchPointRegistration/CMakeLists.txt
@@ -1,36 +1,37 @@
mitk_create_module(
INCLUDE_DIRS
PUBLIC algorithms
PRIVATE src/Helper src/Rendering
DEPENDS MitkCore MitkSceneSerializationBase MitkMultilabel
PACKAGE_DEPENDS
PUBLIC MatchPoint
PRIVATE VTK|ImagingGeneral+ImagingHybrid
)
if(BUILD_TESTING)
add_subdirectory(Testing)
endif()
add_subdirectory(autoload/IO)
add_subdirectory(cmdapps)
if(TARGET ${MODULE_TARGET})
if(MSVC)
- # Warning 4834 leaks into MITK from MatchPoint (remove after MatchPoint is fixed):
- # Discarding return value of function with nodiscard attribute.
- target_compile_options(${MODULE_TARGET} PUBLIC /wd4834)
+ # The following warnings leak into MITK from MatchPoint (remove after MatchPoint is fixed):
+ # - C4828: The file contains a character that is illegal in the current source character set.
+ # - C4834: Discarding return value of function with nodiscard attribute.
+ target_compile_options(${MODULE_TARGET} PUBLIC /wd4828 /wd4834)
endif()
set(ALG_PROFILE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/algorithms)
include(${MatchPoint_SOURCE_DIR}/CMake/mapFunctionCreateAlgorithmProfile.cmake)
file(GLOB ALG_PROFILE_FILES LIST_DIRECTORIES false RELATIVE ${ALG_PROFILE_DIR} "${ALG_PROFILE_DIR}/*.profile")
foreach(profile_file ${ALG_PROFILE_FILES})
get_filename_component(profile_name ${profile_file} NAME_WE)
message(STATUS "Generate MDRA profile ${profile_name} (from ${profile_file})")
CREATE_ALGORITHM_PROFILE(${profile_name} ${ALG_PROFILE_DIR}/${profile_file})
endforeach()
add_subdirectory(deployment)
endif()
diff --git a/Modules/MatchPointRegistrationUI/CMakeLists.txt b/Modules/MatchPointRegistrationUI/CMakeLists.txt
index 85cc6a2e28..df5efef1f2 100644
--- a/Modules/MatchPointRegistrationUI/CMakeLists.txt
+++ b/Modules/MatchPointRegistrationUI/CMakeLists.txt
@@ -1,5 +1,5 @@
MITK_CREATE_MODULE(
INCLUDE_DIRS Common Qmitk
DEPENDS MitkQtWidgets MitkQtWidgetsExt MitkMatchPointRegistration
- PACKAGE_DEPENDS Qt5|Core CTK|CTKWidgets
+ PACKAGE_DEPENDS Qt6|Core CTK|CTKWidgets
)
diff --git a/Modules/MatchPointRegistrationUI/Qmitk/QmitkMapPropertyDelegate.cpp b/Modules/MatchPointRegistrationUI/Qmitk/QmitkMapPropertyDelegate.cpp
index 22b1ab732e..2a194df5f2 100644
--- a/Modules/MatchPointRegistrationUI/Qmitk/QmitkMapPropertyDelegate.cpp
+++ b/Modules/MatchPointRegistrationUI/Qmitk/QmitkMapPropertyDelegate.cpp
@@ -1,270 +1,266 @@
/*============================================================================
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 NOMINMAX
#define NOMINMAX
#endif
#include "QmitkMapPropertyDelegate.h"
#include <QmitkCustomVariants.h>
#include <mitkRenderingManager.h>
#include <QApplication>
#include <QCheckBox>
#include <QColorDialog>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QLabel>
#include <QMessageBox>
#include <QPainter>
#include <QPen>
#include <QPushButton>
#include <QStringList>
#include <bitset>
QmitkMapPropertyDelegate::QmitkMapPropertyDelegate(QObject * /*parent*/)
{
}
void QmitkMapPropertyDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QVariant data = index.data(Qt::DisplayRole);
QString name = data.value<QString>();
QStyledItemDelegate::paint(painter, option, index);
}
QWidget *QmitkMapPropertyDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
QVariant displayData = index.data(Qt::DisplayRole);
QString name = index.model()->data(index.model()->index(index.row(), index.column() - 1)).value<QString>();
if (data.isValid())
{
QWidget *editorWidget = nullptr;
- if (data.type() == QVariant::Int)
+ if (data.typeId() == QMetaType::Int)
{
QSpinBox *spinBox = new QSpinBox(parent);
spinBox->setSingleStep(1);
spinBox->setMinimum(std::numeric_limits<int>::min());
spinBox->setMaximum(std::numeric_limits<int>::max());
editorWidget = spinBox;
}
- // see qt documentation. cast is correct, it would be obsolete if we
- // store doubles
- else if (static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
+ else if (data.typeId() == QMetaType::Float)
{
QDoubleSpinBox *spinBox = new QDoubleSpinBox(parent);
spinBox->setDecimals(5);
spinBox->setSingleStep(0.1);
spinBox->setMinimum(std::numeric_limits<float>::min());
spinBox->setMaximum(std::numeric_limits<float>::max());
editorWidget = spinBox;
}
- else if (data.type() == QVariant::StringList)
+ else if (data.typeId() == QMetaType::QStringList)
{
QStringList entries = data.value<QStringList>();
QComboBox *comboBox = new QComboBox(parent);
comboBox->setEditable(false);
comboBox->addItems(entries);
editorWidget = comboBox;
}
else
{
editorWidget = QStyledItemDelegate::createEditor(parent, option, index);
}
if (editorWidget)
{
// install event filter
editorWidget->installEventFilter(const_cast<QmitkMapPropertyDelegate *>(this));
}
return editorWidget;
}
else
return new QLabel(displayData.toString(), parent);
}
void QmitkMapPropertyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
QVariant displayData = index.data(Qt::DisplayRole);
std::cout << "Set EDITOR DATA : " << data.toDouble() << std::endl;
if (data.isValid())
{
- if (data.type() == QVariant::Int)
+ if (data.typeId() == QMetaType::Int)
{
QSpinBox *spinBox = qobject_cast<QSpinBox *>(editor);
spinBox->setValue(data.toInt());
}
// see qt documentation. cast is correct, it would be obsolete if we
// store doubles
- else if (static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
+ else if (data.typeId() == QMetaType::Float)
{
QDoubleSpinBox *spinBox = qobject_cast<QDoubleSpinBox *>(editor);
spinBox->setValue(data.toDouble());
std::cout << "Set EDITOR DATA : " << spinBox->value() << std::endl;
}
- else if (data.type() == QVariant::StringList)
+ else if (data.typeId() == QMetaType::QStringList)
{
QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
QString displayString = displayData.value<QString>();
comboBox->setCurrentIndex(comboBox->findData(displayString));
}
else
return QStyledItemDelegate::setEditorData(editor, index);
}
}
void QmitkMapPropertyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
QVariant displayData = index.data(Qt::DisplayRole);
if (data.isValid())
{
- if (data.type() == QVariant::Color)
+ if (data.typeId() == QMetaType::QColor)
{
QWidget *colorBtn = qobject_cast<QWidget *>(editor);
- QVariant colorVariant;
- colorVariant.setValue<QColor>(colorBtn->palette().color(QPalette::Button));
+ auto colorVariant = QVariant::fromValue(colorBtn->palette().color(QPalette::Button));
model->setData(index, colorVariant);
}
- else if (data.type() == QVariant::Int)
+ else if (data.typeId() == QMetaType::Int)
{
QSpinBox *spinBox = qobject_cast<QSpinBox *>(editor);
int intValue = spinBox->value();
QVariant intValueVariant;
intValueVariant.setValue<float>(static_cast<float>(intValue));
model->setData(index, intValueVariant);
}
- else if (static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
+ else if (data.typeId() == QMetaType::Float)
{
QDoubleSpinBox *spinBox = qobject_cast<QDoubleSpinBox *>(editor);
double doubleValue = spinBox->value();
std::cout << "SET MODEL DATA << FLOAT : " << doubleValue << std::endl;
QVariant doubleValueVariant;
doubleValueVariant.setValue<float>(static_cast<float>(doubleValue));
std::cout << "SET MODEL DATA << Variant : " << doubleValue << std::endl;
model->setData(index, doubleValueVariant);
}
- else if (data.type() == QVariant::StringList)
+ else if (data.typeId() == QMetaType::QStringList)
{
QString displayData = data.value<QString>();
QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
QString comboBoxValue = comboBox->currentText();
- QVariant comboBoxValueVariant;
- comboBoxValueVariant.setValue<QString>(comboBoxValue);
+ auto comboBoxValueVariant = QVariant::fromValue(comboBoxValue);
model->setData(index, comboBoxValueVariant);
}
else
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void QmitkMapPropertyDelegate::commitAndCloseEditor()
{
QWidget *editor = nullptr;
if (QPushButton *pushBtn = qobject_cast<QPushButton *>(sender()))
{
editor = pushBtn;
}
if (editor)
{
emit commitData(editor);
emit closeEditor(editor);
}
}
void QmitkMapPropertyDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex & /*index*/) const
{
editor->setGeometry(option.rect);
}
void QmitkMapPropertyDelegate::ComboBoxCurrentIndexChanged(int /*index*/)
{
if (QComboBox *comboBox = qobject_cast<QComboBox *>(sender()))
{
emit commitData(comboBox);
emit closeEditor(comboBox);
}
}
void QmitkMapPropertyDelegate::SpinBoxValueChanged(const QString & /*value*/)
{
QAbstractSpinBox *spinBox = nullptr;
if ((spinBox = qobject_cast<QSpinBox *>(sender())) || (spinBox = qobject_cast<QDoubleSpinBox *>(sender())))
{
emit commitData(spinBox);
emit closeEditor(spinBox);
}
}
void QmitkMapPropertyDelegate::showColorDialog()
{
}
bool QmitkMapPropertyDelegate::eventFilter(QObject *o, QEvent *e)
{
// filter all kind of events on our editor widgets
// when certain events occur, repaint all render windows, because rendering relevant properties might have changed
switch (e->type())
{
case QEvent::KeyRelease:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::Wheel:
case QEvent::FocusIn:
{
if (QWidget *editor = dynamic_cast<QWidget *>(o))
{
emit commitData(editor);
}
break;
}
default:
{
break;
}
}
return false;
}
diff --git a/Modules/ModelFitUI/Qmitk/QmitkInitialValuesDelegate.cpp b/Modules/ModelFitUI/Qmitk/QmitkInitialValuesDelegate.cpp
index d70a1cc169..8e0bf7122c 100644
--- a/Modules/ModelFitUI/Qmitk/QmitkInitialValuesDelegate.cpp
+++ b/Modules/ModelFitUI/Qmitk/QmitkInitialValuesDelegate.cpp
@@ -1,113 +1,113 @@
/*============================================================================
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 "QmitkInitialValuesDelegate.h"
#include <mitkModelTraitsInterface.h>
#include <QmitkDataStorageComboBox.h>
#include <QPainter>
#include <QApplication>
#include <QLabel>
#include <QMouseEvent>
#include <QListWidget>
QmitkInitialValuesDelegate::QmitkInitialValuesDelegate(QObject* /*parent*/) : m_Storage(nullptr), m_Predicate(nullptr)
{
}
QWidget* QmitkInitialValuesDelegate::createEditor(QWidget* parent,
const QStyleOptionViewItem& option
, const QModelIndex& index) const
{
QVariant data = index.data(Qt::EditRole);
if (data.isValid())
{
if (valueType(index)==0)
{
return QStyledItemDelegate::createEditor(parent, option, index);
}
else
{
QmitkDataStorageComboBox* box = new QmitkDataStorageComboBox(m_Storage, m_Predicate, parent);
return box;
}
}
else
{
return new QLabel(data.toString(), parent);
}
}
int
QmitkInitialValuesDelegate::
valueType(const QModelIndex& index) const
{
QVariant data = index.data(Qt::UserRole);
return data.toInt();
}
void QmitkInitialValuesDelegate::setEditorData(QWidget* editor,
const QModelIndex& index) const
{
QVariant data = index.data(Qt::EditRole);
if (data.isValid())
{
if (valueType(index) == 0)
{
return QStyledItemDelegate::setEditorData(editor, index);
}
else
{
QmitkDataStorageComboBox* box = qobject_cast<QmitkDataStorageComboBox*>(editor);
mitk::DataNode *node = static_cast<mitk::DataNode*>(data.value<void*>());
auto index = box->Find(node);
box->setCurrentIndex(index);
}
}
}
void QmitkInitialValuesDelegate::setModelData(QWidget* editor, QAbstractItemModel* model
, const QModelIndex& index) const
{
QVariant data = index.data(Qt::EditRole);
if (data.isValid() && valueType(index) == 1)
{
QmitkDataStorageComboBox* box = qobject_cast<QmitkDataStorageComboBox*>(editor);
- QVariant newNode = qVariantFromValue<void*>(static_cast<void*>(box->GetSelectedNode().GetPointer()));
+ QVariant newNode = QVariant::fromValue(static_cast<void*>(box->GetSelectedNode().GetPointer()));
model->setData(index, newNode);
}
else
{
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void QmitkInitialValuesDelegate::
setDataStorage(mitk::DataStorage* storage)
{
this->m_Storage = storage;
};
void QmitkInitialValuesDelegate::
setNodePredicate(mitk::NodePredicateBase* predicate)
{
this->m_Predicate = predicate;
};
diff --git a/Modules/ModuleList.cmake b/Modules/ModuleList.cmake
index b027952284..c2f46614f9 100644
--- a/Modules/ModuleList.cmake
+++ b/Modules/ModuleList.cmake
@@ -1,78 +1,74 @@
# The entries in the mitk_modules list must be
# ordered according to their dependencies.
set(MITK_MODULES
Log
Core
CommandLine
CoreCmdApps
AppUtil
LegacyIO
DataTypesExt
Annotation
LegacyGL
AlgorithmsExt
MapperExt
DICOM
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
US
USUI
DICOMUI
Remeshing
Python
QtPython
Persistence
OpenIGTLinkUI
IGTUI
RT
RTUI
IOExt
XNAT
- TubeGraph
BoundingShape
RenderWindowManagerUI
- SemanticRelations
- SemanticRelationsUI
CEST
BasicImageProcessing
ModelFit
ModelFitUI
Pharmacokinetics
PharmacokineticsUI
DICOMPM
REST
RESTService
DICOMweb
ROI
)
diff --git a/Modules/OpenCL/CMakeLists.txt b/Modules/OpenCL/CMakeLists.txt
deleted file mode 100644
index c782ddf6d0..0000000000
--- a/Modules/OpenCL/CMakeLists.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-if(MITK_USE_OpenCL)
-
- # create the module
- MITK_CREATE_MODULE(
- DEPENDS MitkCore
- PACKAGE_DEPENDS
- PUBLIC OpenCL
- )
-
- add_subdirectory(Testing)
-endif(MITK_USE_OpenCL)
diff --git a/Modules/OpenCL/Documentation/doxygen/MitkOpenCL.dox b/Modules/OpenCL/Documentation/doxygen/MitkOpenCL.dox
deleted file mode 100644
index bbe20e21d7..0000000000
--- a/Modules/OpenCL/Documentation/doxygen/MitkOpenCL.dox
+++ /dev/null
@@ -1,48 +0,0 @@
-
-/**
-
-\page MitkOpenCL_Example Examples
-
-This is a list of available examples:
-- \subpage MitkOpenCL_BinaryThresholdFilter
-
-*/
-
-
-/**
-
-\page MitkOpenCL_Overview OpenCL Module
-
-The MITK OpenCL Module provides a basic class structure to allow usage of OpenCL-accelerated parallel computing.
-
-<h1> Build Instructions </h1>
-
-The MITK OpenCL module needs an OpenCL Device ( most likely a graphics card, but works also on some CPUs ) and the corresponding driver. Furthermore the OpenCL library and the headers are needed. A list of supported hardware is provided by <a href="https://www.khronos.org/conformance/adopters/conformant-products/opencl"> Khronos.org </a>. For the driver and the libraries please look at the support pages of the hardware manufacturer. Quick Links to the most likely of them:
-- <a href="https://developer.nvidia.com/opencl"> NVIDIA OpenCL Page </a>
-- <a href="https://software.intel.com/content/www/us/en/develop/tools/opencl-sdk.html"> Intel OpenCL SDK </a>
-
-To activate the module, you have to activate the CMake option
-
-\verbatim
-MITK_USE_OpenCL
-\endverbatim
-
-The build system tries to find the OpenCL library and the include path automatically. If this attempt failes, you will be prompted to manually specify following variables:
-
-\verbatim
-OPENCL_INCLUDE_DIRS
-OPENCL_LIBRARIES
-\endverbatim
-
-
-
-<h1> Detailed description </h1>
-
-For own implementations, the OpenCL Module allows for building up a filtering pipeline in MITK Style ( see more in \ref PipelineingConceptPage ). The OpenCL filter can be simply connected also to an existing MITK image filtering pipeline since the mitk::OclImageToImageFilter provide a SetInput and GetOutput methods expecting an mitk::Image and returning it respectively.
-
-<h1> Examples </h1>
-
-Here is a list of \subpage MitkOpenCL_Example "examples":
- - \ref MitkOpenCL_BinaryThresholdFilter
-
- */
diff --git a/Modules/OpenCL/Documentation/doxygen/examples/MitkOpenCL_BinaryThresholdFilter.md b/Modules/OpenCL/Documentation/doxygen/examples/MitkOpenCL_BinaryThresholdFilter.md
deleted file mode 100644
index c79cb673e6..0000000000
--- a/Modules/OpenCL/Documentation/doxygen/examples/MitkOpenCL_BinaryThresholdFilter.md
+++ /dev/null
@@ -1,41 +0,0 @@
-Implementing Own OpenCL-based Image Filter {#MitkOpenCL_BinaryThresholdFilter}
-==========================================
-
-This example demonstrates how to implement an image-to-image filter with some computations done on
-an OpenCL device ( most likely a GPU ). This particular example presents a simple threshold filter
-which uses an upper and lower threshold to map the pixel to the specified inside and outside value.
-
-Since the filter we want to implement is an image-to-image filter, we will inherit from the
-mitk::OclImageToImageFilter class.
-
-In the constructor, we set the source file of the filter, in this case is the file located in the default
-directory placed in the module itself. We also se the unique filter id string which serves as an identifier
-for storing and getting the associated program through the OclResourceService.
-
-\snippet mitkOcl-binarythrfilter/main.cpp Create
-
-\snippet mitkOcl-binarythrfilter/main.cpp Initialize
-
-For preparing the execution we call the InitExec method
-provided by the superclass. We also catch exceptions singalising some initialization errors
-
-\snippet mitkOcl-binarythrfilter/main.cpp ExecutePrepare
-
-In this example, the header of the OpenCL-Kernel to be executed is the following
-
-\snippet mitkOcl-binarythrfilter/gpucode.cl GPUHeader
-
-The InitExec methods takes care of initializing the input and output images and their OpenCL counterparts.
-In addition both parameters are passed to the filter and the input data is copied (if necessary).
-If the first initialization part was successfull, we continue by passing in the values for the filter
-specific parameters:
-
-\snippet mitkOcl-binarythrfilter/main.cpp SetKernelArguments
-
-If this passes, we tell the superclass to execute our compiled kernel. The second argument specifies the dimensionality
-of the OpenCL NDRange ( the parallel execution grid ). In this example we use the 3D-Grid:
-
-\snippet mitkOcl-binarythrfilter/main.cpp Execute
-
-Through the last line we signalize that the OpenCL-side data of the output image is modified. This is essential for getting
-the result data when calling GetOutput() afterwards.
diff --git a/Modules/OpenCL/Documentation/doxygen/snippets/mitkOcl-binarythrfilter/main.cpp b/Modules/OpenCL/Documentation/doxygen/snippets/mitkOcl-binarythrfilter/main.cpp
deleted file mode 100644
index a7fddfbb16..0000000000
--- a/Modules/OpenCL/Documentation/doxygen/snippets/mitkOcl-binarythrfilter/main.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 "mitkOclBinaryThresholdImageFilter.h"
-
-mitk::OclBinaryThresholdImageFilter::OclBinaryThresholdImageFilter()
-: m_ckBinaryThreshold( nullptr )
-{
-//! [Create]
- std::string path = "BinaryThresholdFilter.cl";
- this->SetSourceFile( path.c_str() );
- this->m_FilterID = "BinaryThreshold";
-//! [Create]
- this->m_lowerThr = 10;
- this->m_upperThr = 200;
-
- this->m_insideVal = 100;
- this->m_outsideVal = 0;
-}
-
-mitk::OclBinaryThresholdImageFilter::~OclBinaryThresholdImageFilter()
-{
- if ( this->m_ckBinaryThreshold )
- {
- clReleaseKernel( m_ckBinaryThreshold );
- }
-}
-
-void mitk::OclBinaryThresholdImageFilter::Update()
-{
- //Check if context & program available
- if (!this->Initialize())
- {
- // clean-up also the resources
- OpenCLActivator::GetResourceServiceRef()->InvalidateStorage();
- mitkThrow() <<"Filter is not initialized. Cannot update.";
- }
- else{
- // Execute
- this->Execute();
- }
-}
-
-void mitk::OclBinaryThresholdImageFilter::Execute()
-{
- cl_int clErr = 0;
-//! [ExecutePrepare]
- try
- {
- this->InitExec( this->m_ckBinaryThreshold );
- }
- catch( const mitk::Exception& e)
- {
- MITK_ERROR << "Catched exception while initializing filter: " << e.what();
- return;
- }
-//! [ExecutePrepare]
-
- // set kernel arguments
-//! [SetKernelArguments]
- clErr = clSetKernelArg( this->m_ckBinaryThreshold, 2, sizeof(cl_int), &(this->m_lowerThr) );
- clErr |= clSetKernelArg( this->m_ckBinaryThreshold, 3, sizeof(cl_int), &(this->m_upperThr) );
- clErr |= clSetKernelArg( this->m_ckBinaryThreshold, 4, sizeof(cl_int), &(this->m_outsideVal) );
- clErr |= clSetKernelArg( this->m_ckBinaryThreshold, 5, sizeof(cl_int), &(this->m_insideVal) );
- CHECK_OCL_ERR( clErr );
-//! [SetKernelArguments]
-
- // execute the filter on a 3D NDRange
- //! [Execute]
- this->ExecuteKernel( m_ckBinaryThreshold, 3);
-
- // signalize the GPU-side data changed
- m_output->Modified( GPU_DATA );
- //! [Execute]
-
-}
-
-bool mitk::OclBinaryThresholdImageFilter::Initialize()
-{
- bool buildErr = true;
- cl_int clErr = 0;
-//! [Initialize]
- if ( OclFilter::Initialize() )
- {
- this->m_ckBinaryThreshold = clCreateKernel( this->m_clProgram, "ckBinaryThreshold", &clErr);
- buildErr |= CHECK_OCL_ERR( clErr );
- }
-//! [Initialize]
- return (Superclass::IsInitialized() && buildErr );
-}
diff --git a/Modules/OpenCL/Resources/BinaryThresholdFilter.cl b/Modules/OpenCL/Resources/BinaryThresholdFilter.cl
deleted file mode 100644
index 51c3a8978d..0000000000
--- a/Modules/OpenCL/Resources/BinaryThresholdFilter.cl
+++ /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.
-
-============================================================================*/
-
-__kernel void ckBinaryThreshold(
- __read_only image3d_t dSource, // input image
- __global uchar* dDest, // output buffer
- int lowerT, int upperT, int outsideVal, int insideVal // parameters
-)
-{
- // get thread identifier
- unsigned int globalPosX = get_global_id(0);
- unsigned int globalPosY = get_global_id(1);
- unsigned int globalPosZ = get_global_id(2);
-
- // get image width and weight
- const unsigned int uiWidth = get_image_width( dSource );
- const unsigned int uiHeight = get_image_height( dSource );
- const unsigned int uiDepth = get_image_depth( dSource );
-
- // create an image sampler
- const sampler_t defaultSampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST ;
-
- // terminate non-valid threads
- if ( globalPosX < uiWidth && globalPosY < uiHeight && globalPosZ < uiDepth )
- {
- int result = outsideVal;
-
- // get input value
- int4 pixelValue = read_imagei( dSource, defaultSampler, (int4) (globalPosX, globalPosY, globalPosZ, 0 ));
-
- if( (pixelValue.x >= lowerT) && (pixelValue.x <= upperT ) )
- {
- result = insideVal;
- }
-
- // store the result
- dDest[ globalPosZ * uiWidth * uiHeight + globalPosY * uiWidth + globalPosX ] = result;
- }
-
-}
diff --git a/Modules/OpenCL/Testing/CMakeLists.txt b/Modules/OpenCL/Testing/CMakeLists.txt
deleted file mode 100644
index 153cd81e2e..0000000000
--- a/Modules/OpenCL/Testing/CMakeLists.txt
+++ /dev/null
@@ -1 +0,0 @@
-MITK_CREATE_MODULE_TESTS()
diff --git a/Modules/OpenCL/Testing/files.cmake b/Modules/OpenCL/Testing/files.cmake
deleted file mode 100644
index 10dff632d7..0000000000
--- a/Modules/OpenCL/Testing/files.cmake
+++ /dev/null
@@ -1,6 +0,0 @@
-set(MODULE_TESTS
- mitkOclResourceServiceTest.cpp
- mitkOclImageTest.cpp
- mitkOclBinaryThresholdImageFilterTest.cpp
- mitkOclReferenceCountTest.cpp
-)
diff --git a/Modules/OpenCL/Testing/mitkOclBinaryThresholdImageFilterTest.cpp b/Modules/OpenCL/Testing/mitkOclBinaryThresholdImageFilterTest.cpp
deleted file mode 100644
index 413bcb7810..0000000000
--- a/Modules/OpenCL/Testing/mitkOclBinaryThresholdImageFilterTest.cpp
+++ /dev/null
@@ -1,135 +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 <mitkImage.h>
-#include <mitkTestingMacros.h>
-#include <mitkTestFixture.h>
-
-#include <mitkImageGenerator.h>
-#include <mitkImageCast.h>
-
-#include <mitkOclBinaryThresholdImageFilter.h>
-#include <mitkException.h>
-
-//ITK Filter as reference computation
-#include <itkBinaryThresholdImageFilter.h>
-
-class mitkOclBinaryThresholdImageFilterTestSuite : public mitk::TestFixture
-{
-
- CPPUNIT_TEST_SUITE(mitkOclBinaryThresholdImageFilterTestSuite);
- MITK_TEST(SetInput_2DImage_ThrowsException);
- MITK_TEST(GenerateData_3DImage_CompareToReference);
- CPPUNIT_TEST_SUITE_END();
-
-private:
-
- /** Members used inside the different (sub-)tests. All members are initialized via setUp().
- */
- mitk::OclBinaryThresholdImageFilter::Pointer m_oclBinaryFilter;
-
- mitk::Image::Pointer m_Random2DImage;
- mitk::Image::Pointer m_Random3DImage;
- mitk::Image::Pointer m_ReferenceImage;
-
-public:
-
- /**
- * @brief Setup a recorder including a device. Here, we use a player, because in an automatic test
- * hardware is not useful.
- */
- void setUp()
- {
- //Random input images
- m_Random3DImage = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(119, 204, 52, 1, // dimension
- 1.0f, 1.0f, 1.0f, // spacing
- 255, 0); // max, min
-
- m_Random2DImage = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(119, 204, 0, 0, // dimension
- 1.0f, 1.0f, 1.0f, // spacing
- 255, 0); // max, min
- m_oclBinaryFilter = mitk::OclBinaryThresholdImageFilter::New();
- }
-
- void tearDown()
- {
- m_oclBinaryFilter = nullptr;
- }
-
- void SetInput_2DImage_ThrowsException()
- {
- CPPUNIT_ASSERT_THROW( m_oclBinaryFilter->SetInput( m_Random2DImage ), mitk::Exception );
- }
-
- void GenerateData_3DImage_CompareToReference()
- {
- int upperThr = 255;
- int lowerThr = 60;
-
- int outsideVal = 0;
- int insideVal = 100;
-
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
- resources->GetContext(); //todo why do i need to call this before GetMaximumImageSize()?
- if(resources->GetMaximumImageSize(2, CL_MEM_OBJECT_IMAGE3D) == 0)
- {
- //GPU device does not support 3D images. Skip this test.
- MITK_INFO << "Skipping test.";
- return;
- }
-
- try{
-
- m_oclBinaryFilter->SetInput( m_Random3DImage );
- m_oclBinaryFilter->SetUpperThreshold( upperThr );
- m_oclBinaryFilter->SetLowerThreshold( lowerThr );
- m_oclBinaryFilter->SetOutsideValue( outsideVal );
- m_oclBinaryFilter->SetInsideValue( insideVal );
- m_oclBinaryFilter->Update();
-
- mitk::Image::Pointer outputImage = mitk::Image::New();
- outputImage = m_oclBinaryFilter->GetOutput();
-
- // reference computation
- //This is not optimal here, but since we use a random image
- //we cannot know the reference image at this point.
- typedef itk::Image< unsigned char, 3> ImageType;
- typedef itk::BinaryThresholdImageFilter< ImageType, ImageType > ThresholdFilterType;
-
- ImageType::Pointer itkInputImage = ImageType::New();
- CastToItkImage( m_Random3DImage, itkInputImage );
-
- ThresholdFilterType::Pointer refThrFilter = ThresholdFilterType::New();
- refThrFilter->SetInput( itkInputImage );
- refThrFilter->SetLowerThreshold( lowerThr );
- refThrFilter->SetUpperThreshold( upperThr );
- refThrFilter->SetOutsideValue( outsideVal );
- refThrFilter->SetInsideValue( insideVal );
- refThrFilter->Update();
- mitk::Image::Pointer referenceImage = mitk::Image::New();
- mitk::CastToMitkImage(refThrFilter->GetOutput(), referenceImage);
-
- MITK_ASSERT_EQUAL( referenceImage, outputImage,
- "OclBinaryThresholdFilter should be equal to regular itkBinaryThresholdImageFilter.");
- }
- catch(mitk::Exception &e)
- {
- std::string errorMessage = "Caught unexpected exception ";
- errorMessage.append(e.what());
- CPPUNIT_FAIL(errorMessage.c_str());
- }
-
- }
-};
-
-MITK_TEST_SUITE_REGISTRATION(mitkOclBinaryThresholdImageFilter)
diff --git a/Modules/OpenCL/Testing/mitkOclImageTest.cpp b/Modules/OpenCL/Testing/mitkOclImageTest.cpp
deleted file mode 100644
index c1312627af..0000000000
--- a/Modules/OpenCL/Testing/mitkOclImageTest.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 <mitkTestingMacros.h>
-#include <mitkImageGenerator.h>
-#include <mitkOclImage.h>
-
-using namespace mitk;
-
-/**
- This function is testing the mitk::OclImage class.
- */
-int mitkOclImageTest( int /*argc*/, char* /*argv*/[] )
-{
- MITK_TEST_BEGIN("mitkOclImageTest");
-
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- MITK_TEST_CONDITION_REQUIRED( ref != 0, "Got valid ServiceReference" );
-
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
- MITK_TEST_CONDITION_REQUIRED( resources != nullptr, "OpenCL Resource service available." );
-
- cl_context gpuContext = resources->GetContext();
- MITK_TEST_CONDITION_REQUIRED( gpuContext != nullptr, "Got not-null OpenCL context.");
-
- cl_device_id gpuDevice = resources->GetCurrentDevice();
- MITK_TEST_CONDITION_REQUIRED( gpuDevice != nullptr, "Got not-null OpenCL device.");
-
- //create a random image
- mitk::Image::Pointer reference;
- //check if 3D images are supported by the device and initialize image accordingly
- if( resources->GetMaximumImageSize(2, CL_MEM_OBJECT_IMAGE3D) == 0 ) //2D required
- {
- //Create a random reference image
- reference = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(119, 204, 0, 0, // dimension
- 1.0f, 1.0f, 1.0f, // spacing
- 255, 0); // max, min
- }
- else //3D ok
- {
- //Create a random reference image
- reference = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(119, 204, 52, 1, // dimension
- 1.0f, 1.0f, 1.0f, // spacing
- 255, 0); // max, min
- }
- MITK_TEST_CONDITION_REQUIRED( reference.IsNotNull(), "Reference mitk::Image object instantiated.");
-
- mitk::OclImage::Pointer oclTestImage = mitk::OclImage::New();
- oclTestImage->InitializeByMitkImage(reference);
- MITK_TEST_CONDITION_REQUIRED(oclTestImage.IsNotNull(), "oclImage object instantiated.");
-
- // test if oclImage correct initialized
- MITK_TEST_CONDITION( oclTestImage->GetMITKImage() == reference, "oclImage has the correct reference mitk::Image");
- MITK_TEST_CONDITION( (unsigned int)oclTestImage->GetDimension() == reference->GetDimension(), "Same dimensionality.");
-
- cl_int clErr = 0;
- cl_command_queue cmdQueue = clCreateCommandQueue( gpuContext, gpuDevice,
- 0 ,&clErr);
- MITK_TEST_CONDITION_REQUIRED( clErr == CL_SUCCESS, "A command queue was created.");
-
- // Allocate and copy image data to GPU
- try
- {
- oclTestImage->TransferDataToGPU(cmdQueue);
- MITK_TEST_CONDITION( oclTestImage->IsModified(0), "Modified flag for GPU correctly set.");
-
- // check if the created GPU object is valid
- cl_mem gpuImage = oclTestImage->GetGPUImage(cmdQueue);
- MITK_TEST_CONDITION_REQUIRED( gpuImage != nullptr, "oclImage returned a valid GPU memory pointer");
- size_t returned = 0;
- cl_image_format imgFmt;
- clErr = clGetImageInfo( gpuImage, CL_IMAGE_FORMAT, sizeof(cl_image_format),
- (void*) &imgFmt, &returned );
- MITK_TEST_CONDITION( clErr == CL_SUCCESS, "oclImage has created a valid GPU image");
-
- // test for dimensions
- size_t imagesize = 0;
- clErr = clGetImageInfo( gpuImage, CL_IMAGE_WIDTH, sizeof(size_t),
- (void*) &imagesize, &returned );
- MITK_TEST_CONDITION( imagesize == static_cast<size_t>(oclTestImage->GetDimension(0)), "Image width corresponds" );
-
- clErr = clGetImageInfo( gpuImage, CL_IMAGE_HEIGHT, sizeof(size_t),
- (void*) &imagesize, &returned );
- MITK_TEST_CONDITION( imagesize == static_cast<size_t>(oclTestImage->GetDimension(1)), "Image height corresponds" );
-
- clErr = clGetImageInfo( gpuImage, CL_IMAGE_DEPTH, sizeof(size_t),
- (void*) &imagesize, &returned );
- MITK_TEST_CONDITION( imagesize == static_cast<size_t>(oclTestImage->GetDimension(2)), "Image depth corresponds" );
-
- // clean up
- clReleaseCommandQueue( cmdQueue );
- }
- catch(mitk::ImageTypeIsNotSupportedByGPU& e)
- {
- MITK_ERROR << "Caught exception: " << e.what();
- //Image type is not supported -> skip test.
- }
-
- MITK_TEST_END();
-}
diff --git a/Modules/OpenCL/Testing/mitkOclReferenceCountTest.cpp b/Modules/OpenCL/Testing/mitkOclReferenceCountTest.cpp
deleted file mode 100644
index 171a06c9c4..0000000000
--- a/Modules/OpenCL/Testing/mitkOclReferenceCountTest.cpp
+++ /dev/null
@@ -1,83 +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 <mitkTestingMacros.h>
-#include <mitkImageGenerator.h>
-#include <mitkOclBinaryThresholdImageFilter.h>
-
-using namespace mitk;
-
-/**
- This function is testing the OclFilter class and the
- OpenCL resource service. To prevent segmentation faults
- a mutexed reference counter is implemented in the resource service.
- It tracks the number of opencl program references for the corresponding filter
- and delete only the opencl programm if the reference count reaches 0.
- Every new instance of a filter increases the reference count by 1.
- This test runs successfull if the 2 filters are initialized, run
- and deleted without any crash.
- */
-int mitkOclReferenceCountTest( int /*argc*/, char* /*argv*/[] )
-{
- MITK_TEST_BEGIN("mitkOclReferenceCountTest");
-
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
- resources->GetContext(); //todo why do i need to call this before GetMaximumImageSize()?
- if(resources->GetMaximumImageSize(2, CL_MEM_OBJECT_IMAGE3D) == 0)
- {
- //GPU device does not support 3D images. Skip this test.
- MITK_INFO << "Skipping test.";
- return 0;
- }
-
- mitk::Image::Pointer inputImage = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(119, 204, 52, 1, // dimension
- 1.0f, 1.0f, 1.0f, // spacing
- 255, 0); // max, min
- int upperThr = 255;
- int lowerThr = 60;
- int outsideVal = 0;
- int insideVal = 100;
-
- mitk::OclBinaryThresholdImageFilter::Pointer oclFilter1 = mitk::OclBinaryThresholdImageFilter::New();
- oclFilter1->SetInput( inputImage );
- oclFilter1->SetUpperThreshold( upperThr );
- oclFilter1->SetLowerThreshold( lowerThr );
- oclFilter1->SetOutsideValue( outsideVal );
- oclFilter1->SetInsideValue( insideVal );
- oclFilter1->Update();
-
- mitk::Image::Pointer outputImage1 = mitk::Image::New();
- outputImage1 = oclFilter1->GetOutput();
-
- mitk::OclBinaryThresholdImageFilter::Pointer oclFilter2 = mitk::OclBinaryThresholdImageFilter::New();
-
- oclFilter2->SetInput( inputImage );
- oclFilter2->SetUpperThreshold( upperThr );
- oclFilter2->SetLowerThreshold( lowerThr );
- oclFilter2->SetOutsideValue( outsideVal );
- oclFilter2->SetInsideValue( insideVal );
- oclFilter2->Update();
-
- mitk::Image::Pointer outputImage2 = mitk::Image::New();
- outputImage2 = oclFilter2->GetOutput();
-
- // delete filters
- oclFilter1 = nullptr;
- oclFilter2 = nullptr;
-
- // this is only visible if the delete did not cause a segmentation fault
- // it is always true and successfull if the program reaches this state
- MITK_TEST_CONDITION_REQUIRED( true, "2 Filters deleted without a crash -> success ");
-
- MITK_TEST_END();
-}
diff --git a/Modules/OpenCL/Testing/mitkOclResourceServiceTest.cpp b/Modules/OpenCL/Testing/mitkOclResourceServiceTest.cpp
deleted file mode 100644
index 7521f13015..0000000000
--- a/Modules/OpenCL/Testing/mitkOclResourceServiceTest.cpp
+++ /dev/null
@@ -1,103 +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 <mitkTestingMacros.h>
-#include <mitkOclUtils.h>
-#include <mitkOclResourceService.h>
-#include <mitkException.h>
-
-#include <usModuleContext.h>
-#include <usGetModuleContext.h>
-
-using namespace mitk;
-
-/**
- This function is testing the class mitk::OclResourceService.
- */
-int mitkOclResourceServiceTest( int /*argc*/, char* /*argv*/[] )
-{
- MITK_TEST_BEGIN("mitkOclResourceServiceTest");
-
- us::ServiceReference<OclResourceService> ref = us::GetModuleContext()->GetServiceReference<OclResourceService>();
- MITK_TEST_CONDITION_REQUIRED( ref != nullptr, "Resource service available." );
-
- OclResourceService* resources = us::GetModuleContext()->GetService<OclResourceService>(ref);
- MITK_TEST_CONDITION_REQUIRED( resources != nullptr, "Resource service available." );
-
- cl_context first = resources->GetContext();
- MITK_TEST_CONDITION_REQUIRED(first != nullptr, "Got not-null OpenCL context.");
-
- OclResourceService* resources_2 = us::GetModuleContext()->GetService<OclResourceService>(ref);
- MITK_TEST_CONDITION_REQUIRED( resources == resources_2, "Same resource reference the second time." );
-
- cl_context second = resources_2->GetContext();
- MITK_TEST_CONDITION_REQUIRED( first == second, "Both return same context");
-
- // further tests requires for valid context
- if( first )
- {
- cl_image_format testFmt;
- testFmt.image_channel_data_type = CL_FLOAT;
- testFmt.image_channel_order = CL_RGBA;
-
- MITK_TEST_CONDITION( resources->GetIsFormatSupported( &testFmt ), "Checking if format CL_FLOAT / CL_RGBA supported." );
- }
-
- // create test program
- const std::string testProgramSource =
- "__kernel void testKernel( __global uchar* buffer ){ \
- const unsigned int globalPosX = get_global_id(0); \
- buffer[globalPosX] = buffer[globalPosX] + 1;}";
-
- cl_int err = 0;
- size_t progSize = testProgramSource.length();
- const char* progSource = testProgramSource.c_str();
- cl_program testProgram = clCreateProgramWithSource( first, 1, &progSource, &progSize, &err );
-
- MITK_TEST_CONDITION_REQUIRED( err == CL_SUCCESS, "Test program loaded succesfully.");
-
- err = clBuildProgram(testProgram, 0, nullptr, nullptr, nullptr, nullptr);
- MITK_TEST_CONDITION_REQUIRED( err == CL_SUCCESS, "Test program built succesfully.");
-
- resources->InsertProgram( testProgram, "test_program", true);
- MITK_TEST_CONDITION( resources->GetProgram("test_program") == testProgram, "Program correctly stored by ResourceService");
-
- // the manger throws exception when accessing non-existant programs
- MITK_TEST_FOR_EXCEPTION( mitk::Exception, resources->GetProgram("blah"); );
-
- // another test source, this one does not compile
- const std::string testProgramSource_notCompiling =
- "__kernel void testKernel( __global uchar* buffer ){ \
- const unsigned intt globalPosX = get_global_id(0); }";
-
- progSize = testProgramSource_notCompiling.length();
- const char* progSource2 = testProgramSource_notCompiling.c_str();
- cl_program notComp_testProgram = clCreateProgramWithSource( first, 1, &progSource2, &progSize, &err );
-
- // the error in the source code has no influence on loading the program
- MITK_TEST_CONDITION_REQUIRED( err == CL_SUCCESS, "Test program 2 loaded succesfully.");
-
- err = clBuildProgram(notComp_testProgram, 0, nullptr, nullptr, nullptr, nullptr);
- MITK_TEST_CONDITION_REQUIRED( err == CL_BUILD_PROGRAM_FAILURE, "Test program 2 failed to build.");
- std::cout << " --> The (expected) OpenCL Build Error occured : ";// << GetOclErrorString(err);
-
- resources->InsertProgram( notComp_testProgram, "test_program_failed", true);
- MITK_TEST_CONDITION( resources->GetProgram("test_program_failed") == notComp_testProgram, "Program correctly stored by ResourceService");
-
- // calling the InvalidateStorage() will result in removing the _failed test program inserted above
- resources->InvalidateStorage();
-
- // the second test program should no more exist in the storage, hence we await an exception
- MITK_TEST_FOR_EXCEPTION( mitk::Exception, resources->GetProgram("test_program_failed"); );
-
- MITK_TEST_END();
-}
diff --git a/Modules/OpenCL/files.cmake b/Modules/OpenCL/files.cmake
deleted file mode 100644
index c1f158a404..0000000000
--- a/Modules/OpenCL/files.cmake
+++ /dev/null
@@ -1,26 +0,0 @@
-set(CPP_FILES
-# helper classes
- mitkOclUtils.cpp
- mitkOclResourceServiceImpl_Private.cpp
- mitkOclImageFormats.cpp
-
-# module activator
- mitkOpenCLActivator.cpp
-
-# base data and filter objects
- mitkOclBaseData.cpp
- mitkOclImage.cpp
- mitkOclDataSet.cpp
- mitkOclFilter.cpp
- mitkOclImageFilter.cpp
- mitkOclDataSetFilter.cpp
- mitkOclImageToImageFilter.cpp
- mitkOclDataSetToDataSetFilter.cpp
-
-# own filter implementations
- mitkOclBinaryThresholdImageFilter.cpp
-)
-
-set(RESOURCE_FILES
- BinaryThresholdFilter.cl
-)
diff --git a/Modules/OpenCL/mitkOclBaseData.cpp b/Modules/OpenCL/mitkOclBaseData.cpp
deleted file mode 100644
index cb55ab283a..0000000000
--- a/Modules/OpenCL/mitkOclBaseData.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 "mitkOclBaseData.h"
-
-mitk::OclBaseData::OclBaseData()
-: m_BufferSize ( 0 ), m_GPUBuffer( nullptr ), m_CPUBuffer( nullptr )
-{
-}
-
-mitk::OclBaseData::~OclBaseData()
-{
- if (m_GPUBuffer) clReleaseMemObject( m_GPUBuffer );
- if (m_CPUBuffer) free( m_CPUBuffer );
-}
-
-cl_mem mitk::OclBaseData::GetGPUBuffer()
-{
- return this->m_GPUBuffer;
-}
diff --git a/Modules/OpenCL/mitkOclBaseData.h b/Modules/OpenCL/mitkOclBaseData.h
deleted file mode 100644
index 49e5f1c40f..0000000000
--- a/Modules/OpenCL/mitkOclBaseData.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkOclBaseData_h
-#define mitkOclBaseData_h
-
-#include "MitkOpenCLExports.h"
-#include "mitkOclUtils.h"
-
-#include "mitkOpenCL.h"
-
-#include <mitkCommon.h>
-#include <itkObjectFactory.h>
-#include <itkObject.h>
-
-namespace mitk
-{
-
- class MITKOPENCL_EXPORT OclBaseData : public itk::Object
- {
- public:
- mitkClassMacroItkParent(OclBaseData, itk::Object);
-
- /*! \brief Copies the RAM-stored data to GPU-MEM.
- * This method has to be implemented for each data type.
- */
- virtual int TransferDataToGPU(cl_command_queue) = 0;
-
- /*! \brief Copies the in GPU-MEM stored data to RAM
- * This method has to be implemented for each data type.
- */
- virtual void* TransferDataToCPU(cl_command_queue) = 0;
-
- /** \brief Set the modified flag for one of the GPU buffer */
- void GPUModified();
-
- /** \brief Set the modified flag for one of the CPU buffer */
- void CPUModified();
-
-
- /** \brief Get the pointer to the buffer on the device (GPU) */
- virtual cl_mem GetGPUBuffer();
-
- protected:
- /** \brief Default constructor. */
- OclBaseData();
-
- /** \brief Default destructor. */
- virtual ~OclBaseData();
-
- private:
-
- /** \brief Size of the data buffer. CPU size equals GPU size. */
- size_t m_BufferSize;
-
- /** \brief Pointer to the buffer on the device (GPU) */
- cl_mem m_GPUBuffer;
-
- /** \brief Pointer to the buffer on the host (CPU) */
- void* m_CPUBuffer;
- };
-
-}
-
-#endif
diff --git a/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.cpp b/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.cpp
deleted file mode 100644
index 1f750ef5c4..0000000000
--- a/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.cpp
+++ /dev/null
@@ -1,110 +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 "mitkOclBinaryThresholdImageFilter.h"
-#include "usServiceReference.h"
-
-mitk::OclBinaryThresholdImageFilter::OclBinaryThresholdImageFilter()
-: m_ckBinaryThreshold( nullptr )
-{
- this->AddSourceFile("BinaryThresholdFilter.cl");
- this->m_FilterID = "BinaryThreshold";
-
- this->m_LowerThreshold = 10;
- this->m_UpperThreshold = 200;
-
- this->m_InsideValue = 100;
- this->m_OutsideValue = 0;
-}
-
-mitk::OclBinaryThresholdImageFilter::~OclBinaryThresholdImageFilter()
-{
- if ( this->m_ckBinaryThreshold )
- {
- clReleaseKernel( m_ckBinaryThreshold );
- }
-}
-
-void mitk::OclBinaryThresholdImageFilter::Update()
-{
- //Check if context & program available
- if (!this->Initialize())
- {
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
-
- // clean-up also the resources
- resources->InvalidateStorage();
- mitkThrow() <<"Filter is not initialized. Cannot update.";
- }
- else{
- // Execute
- this->Execute();
- }
-}
-
-void mitk::OclBinaryThresholdImageFilter::Execute()
-{
- cl_int clErr = 0;
-
- try
- {
- this->InitExec( this->m_ckBinaryThreshold );
- }
- catch( const mitk::Exception& e)
- {
- MITK_ERROR << "Catched exception while initializing filter: " << e.what();
- return;
- }
-
- // set kernel arguments
- clErr = clSetKernelArg( this->m_ckBinaryThreshold, 2, sizeof(cl_int), &(this->m_LowerThreshold) );
- clErr |= clSetKernelArg( this->m_ckBinaryThreshold, 3, sizeof(cl_int), &(this->m_UpperThreshold) );
- clErr |= clSetKernelArg( this->m_ckBinaryThreshold, 4, sizeof(cl_int), &(this->m_OutsideValue) );
- clErr |= clSetKernelArg( this->m_ckBinaryThreshold, 5, sizeof(cl_int), &(this->m_InsideValue) );
- CHECK_OCL_ERR( clErr );
-
- // execute the filter on a 3D NDRange
- this->ExecuteKernel( m_ckBinaryThreshold, 3);
-
- // signalize the GPU-side data changed
- m_Output->Modified( GPU_DATA );
-}
-
-us::Module *mitk::OclBinaryThresholdImageFilter::GetModule()
-{
- return us::GetModuleContext()->GetModule();
-}
-
-bool mitk::OclBinaryThresholdImageFilter::Initialize()
-{
- bool buildErr = true;
- cl_int clErr = 0;
-
- if ( OclFilter::Initialize() )
- {
- this->m_ckBinaryThreshold = clCreateKernel( this->m_ClProgram, "ckBinaryThreshold", &clErr);
- buildErr |= CHECK_OCL_ERR( clErr );
- }
-
- return (OclFilter::IsInitialized() && buildErr );
-}
-
-void mitk::OclBinaryThresholdImageFilter::SetInput(mitk::Image::Pointer image)
-{
- if(image->GetDimension() != 3)
- {
- mitkThrowException(mitk::Exception) << "Input for " << this->GetNameOfClass() <<
- " is not 3D. The filter only supports 3D. Please change your input.";
- }
- OclImageToImageFilter::SetInput(image);
-}
diff --git a/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.h b/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.h
deleted file mode 100644
index 0488e3fb6f..0000000000
--- a/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.h
+++ /dev/null
@@ -1,121 +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 mitkOclBinaryThresholdImageFilter_h
-#define mitkOclBinaryThresholdImageFilter_h
-
-#include "mitkOclImageToImageFilter.h"
-#include <itkObject.h>
-
-namespace mitk
-{
-class OclImageToImageFilter;
-
-/** Documentation
- *
- * \brief The OclBinaryThresholdImageFilter computes a binary segmentation based on given
- threshold values.
-
- *
- * The filter requires two threshold values ( the upper and the lower threshold ) and two image values ( inside and outside ). The resulting voxel of the segmentation image is assigned the inside value 1 if the image value is between the given thresholds and the outside value otherwise.
- */
-class MITKOPENCL_EXPORT OclBinaryThresholdImageFilter : public OclImageToImageFilter, public itk::Object
-{
-
-public:
- mitkClassMacroItkParent(OclBinaryThresholdImageFilter, itk::Object);
- itkNewMacro(Self);
-
- /**
- * @brief SetInput Set the input image. Only 3D images are supported for now.
- * @param image a 3D image.
- * @throw mitk::Exception if the dimesion is not 3.
- */
- void SetInput(Image::Pointer image);
-
- /** Update the filter */
- void Update();
-
- /** Set the lower threshold
- @param lowerThreshold Threshold value
- */
- void SetLowerThreshold( int lowerThreshold )
- {
- this->m_LowerThreshold = lowerThreshold;
- }
-
- /** Set the upper threshold
- @param upperThreshold Threshold value
- */
- void SetUpperThreshold( int upperThreshold )
- {
- this->m_UpperThreshold = upperThreshold;
- }
-
- /** Set the outside value
-
- @param outsideValue The outside value
- */
- void SetOutsideValue( int outsideValue )
- {
- this->m_OutsideValue = outsideValue;
- }
-
- /** Set the inside value
- @param insideValue The inside value
- */
- void SetInsideValue( int insideValue )
- {
- this->m_InsideValue = insideValue;
- }
-
-protected:
-
- /** Constructor */
- OclBinaryThresholdImageFilter();
-
- /** Destructor */
- virtual ~OclBinaryThresholdImageFilter();
-
- /** Initialize the filter */
- bool Initialize();
-
- void Execute();
-
- mitk::PixelType GetOutputType()
- {
- return mitk::MakeScalarPixelType<unsigned char>();
- }
-
- int GetBytesPerElem()
- {
- return sizeof(unsigned char);
- }
-
- virtual us::Module* GetModule();
-
-private:
- /** The OpenCL kernel for the filter */
- cl_kernel m_ckBinaryThreshold;
-
- int m_LowerThreshold;
-
- int m_UpperThreshold;
-
- int m_InsideValue;
-
- int m_OutsideValue;
-};
-}
-
-
-#endif
diff --git a/Modules/OpenCL/mitkOclDataSet.cpp b/Modules/OpenCL/mitkOclDataSet.cpp
deleted file mode 100644
index 5337a5981d..0000000000
--- a/Modules/OpenCL/mitkOclDataSet.cpp
+++ /dev/null
@@ -1,172 +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 "mitkOclDataSet.h"
-#include "mitkCommon.h"
-#include "mitkLog.h"
-
-#include "mitkOclUtils.h"
-
-#include <fstream>
-
-//#define SHOW_MEM_INFO
-
-mitk::OclDataSet::OclDataSet() : m_gpuBuffer(nullptr), m_context(nullptr), m_bufferSize(0), m_gpuModified(false), m_cpuModified(false),
- m_Data(nullptr), m_BpE(1)
-{
-}
-
-mitk::OclDataSet::~OclDataSet()
-{
- MITK_DEBUG << "OclDataSet Destructor";
-
- //release GMEM Image buffer
- if (m_gpuBuffer) clReleaseMemObject(m_gpuBuffer);
-}
-
-
-cl_mem mitk::OclDataSet::CreateGPUBuffer()
-{
- MITK_DEBUG << "InitializeGPUBuffer call with: BPE=" << m_BpE;
-
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
-
- m_context = resources->GetContext();
-
- int clErr;
- if (m_gpuBuffer) clReleaseMemObject(m_gpuBuffer);
-
- m_gpuBuffer = clCreateBuffer(m_context, CL_MEM_READ_WRITE, m_bufferSize * (size_t)m_BpE, nullptr, &clErr);
-
- #ifdef SHOW_MEM_INFO
- MITK_INFO << "Created GPU Buffer Object of size: " << (size_t)m_BpE * m_bufferSize << " Bytes";
- #endif
-
- CHECK_OCL_ERR(clErr);
-
- if (clErr != CL_SUCCESS)
- mitkThrow() << "openCL Error when creating Buffer";
-
- return m_gpuBuffer;
-}
-
-bool mitk::OclDataSet::IsModified(int _type)
-{
- if (_type) return m_cpuModified;
- else return m_gpuModified;
-}
-
-void mitk::OclDataSet::Modified(int _type)
-{
- // defines... GPU: 0, CPU: 1
- m_cpuModified = _type;
- m_gpuModified = !_type;
-}
-
-int mitk::OclDataSet::TransferDataToGPU(cl_command_queue gpuComQueue)
-{
- cl_int clErr = 0;
-
- // check whether an image present
- if (m_Data == nullptr){
- MITK_ERROR("ocl.DataSet") << "(mitk) No data present!\n";
- return -1;
- }
-
- // there is a need for copy only if RAM-Data newer then GMEM data
- if (m_cpuModified)
- {
- //check the buffer
- if(m_gpuBuffer == nullptr)
- {
- CreateGPUBuffer();
- }
-
- if (m_gpuBuffer != nullptr)
- {
- clErr = clEnqueueWriteBuffer(gpuComQueue, m_gpuBuffer, CL_TRUE, 0, m_bufferSize * (size_t)m_BpE, m_Data, 0, NULL, NULL);
- MITK_DEBUG << "Wrote Data to GPU Buffer Object.";
-
- CHECK_OCL_ERR(clErr);
- m_gpuModified = true;
-
- if (clErr != CL_SUCCESS)
- mitkThrow() << "openCL Error when writing Buffer";
- }
- else
- {
- MITK_ERROR << "No GPU buffer present!";
- }
- }
-
- return clErr;
-}
-
-cl_mem mitk::OclDataSet::GetGPUBuffer()
-{
- // query image object info only if already initialized
- if( this->m_gpuBuffer )
- {
- #ifdef SHOW_MEM_INFO
- cl_int clErr = 0;
- // clGetMemObjectInfo()
- cl_mem_object_type memInfo;
- clErr = clGetMemObjectInfo(this->m_gpuBuffer, CL_MEM_TYPE, sizeof(cl_mem_object_type), &memInfo, nullptr );
- CHECK_OCL_ERR(clErr);
- MITK_DEBUG << "Querying info for object, recieving: " << memInfo;
- #endif
- }
-
- return m_gpuBuffer;
-}
-
-void* mitk::OclDataSet::TransferDataToCPU(cl_command_queue gpuComQueue)
-{
- cl_int clErr = 0;
-
- // if image created on GPU, needs to create mitk::Image
- if( m_gpuBuffer == nullptr ){
- MITK_ERROR("ocl.DataSet") << "(mitk) No buffer present!\n";
- return nullptr;
- }
-
- // check buffersize
- char* data = new char[m_bufferSize * (size_t)m_BpE];
-
- // debug info
- #ifdef SHOW_MEM_INFO
- oclPrintMemObjectInfo( m_gpuBuffer );
- #endif
-
- clErr = clEnqueueReadBuffer( gpuComQueue, m_gpuBuffer, CL_TRUE, 0, m_bufferSize * (size_t)m_BpE, data ,0, nullptr, nullptr);
- CHECK_OCL_ERR(clErr);
-
- if(clErr != CL_SUCCESS)
- mitkThrow() << "openCL Error when reading Output Buffer";
-
- clFlush( gpuComQueue );
- // the cpu data is same as gpu
- this->m_gpuModified = false;
-
- return (void*) data;
-}
-
-void mitk::OclDataSet::SetBufferSize(size_t size)
-{
- m_bufferSize = size;
-}
-
-void mitk::OclDataSet::SetBpE(unsigned short BpE)
-{
- m_BpE = BpE;
-}
diff --git a/Modules/OpenCL/mitkOclDataSet.h b/Modules/OpenCL/mitkOclDataSet.h
deleted file mode 100644
index 8239efdbe3..0000000000
--- a/Modules/OpenCL/mitkOclDataSet.h
+++ /dev/null
@@ -1,130 +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 mitkOclDataSet_h
-#define mitkOclDataSet_h
-
-#define GPU_DATA 0
-#define CPU_DATA 1
-
-#include <mitkImage.h>
-#include "MitkOpenCLExports.h"
-
-#include "mitkOclBaseData.h"
-#include "mitkOpenCLActivator.h"
-
-#include <mitkException.h>
-
-namespace mitk {
-
-/*!
- * \brief Class implementing processing of arbitrary data sets for GPU Image Processing
- *
- * The class holds a pointer to the data stored in RAM and performs an
- * on-demand-copy to the graphics memory. It is the basic data structure for all
- * mitk::oclDataSetToDataSetFilter classes
- */
-class MITKOPENCL_EXPORT OclDataSet : public OclBaseData
-{
-public:
- mitkClassMacro(OclDataSet, OclBaseData);
- itkFactorylessNewMacro(Self);
- itkCloneMacro(Self);
-
- /*! \brief Copies the RAM-stored data to GMEM */
- virtual int TransferDataToGPU(cl_command_queue);
-
- /*! \brief Copies the in GMEM stored data to RAM */
- virtual void* TransferDataToCPU(cl_command_queue);
-
- /*! \brief Returns the pointer to the referenced data */
- void* GetData()
- {
- return m_Data;
- }
-
- /** Returns the pointer to the GPU buffer */
- cl_mem GetGPUBuffer();
-
- /** Create the GPU buffer for image
- *
- */
- cl_mem CreateGPUBuffer();
-
- /** \brief Returns the status of the image buffer
- *
- * @param _type The flag to specify the buffer type ( GPU / CPU )
- */
- bool IsModified(int _type);
-
- using OclBaseData::Modified;
-
- /** \brief Set the modified flag for one of the buffers
- *
- * @param _type The flag to specify the buffer type ( GPU / CPU )
- */
- void Modified(int _type);
-
- /** \brief Initialze the OclDataSet with data. */
- void SetData(void* data)
- {
- this->m_cpuModified = true;
- this->m_gpuModified = false;
- m_Data = data;
- }
-
- /*! \brief returns the amount of elements in the DataSet */
- size_t GetBufferSize() const
- {
- return this->m_bufferSize;
- }
-
- short GetBytesPerElement() const
- {
- return this->m_BpE;
- }
-
- /** @brief Set the amount of elements in buffer*/
- void SetBufferSize(size_t size);
-
- /** @brief Set the DataSet memory Size per Element in Bytes*/
- void SetBpE(unsigned short BpE);
-
-protected:
- /*! \brief Constructor */
- OclDataSet();
-
- /** @brief Destructor */
- virtual ~OclDataSet();
-
- /*! GMEM Image buffer */
- cl_mem m_gpuBuffer;
-
- /*! GPU Context the Buffer was created in, needed for access */
- cl_context m_context;
-
-private:
- /*! GMEM Buffer Size in elements*/
- size_t m_bufferSize;
-
- bool m_gpuModified;
- bool m_cpuModified;
-
- /*! Reference to the data */
- void* m_Data;
-
- /*! Bytes per Element in Buffer*/
- unsigned short m_BpE;
-};
-
-}
-#endif
diff --git a/Modules/OpenCL/mitkOclDataSetFilter.cpp b/Modules/OpenCL/mitkOclDataSetFilter.cpp
deleted file mode 100644
index bc4ab4edfc..0000000000
--- a/Modules/OpenCL/mitkOclDataSetFilter.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 "mitkOclDataSetFilter.h"
-#include "mitkOclFilter.h"
-#include "mitkOclDataSet.h"
-#include "mitkImageReadAccessor.h"
-
-mitk::OclDataSetFilter::OclDataSetFilter()
-{
-}
-
-mitk::OclDataSetFilter::~OclDataSetFilter()
-{
-}
-
-void mitk::OclDataSetFilter::SetInput(mitk::OclDataSet::Pointer DataSet)
-{
- m_Input = DataSet;
-}
-
-void mitk::OclDataSetFilter::SetInput(void* DataSet, unsigned int size, unsigned int BpE)
-{
- m_Input = mitk::OclDataSet::New();
- m_Input->SetData(DataSet);
- m_Input->SetBufferSize(size);
- m_Input->SetBpE(BpE);
- m_CurrentSize = BpE;
-}
-
-void mitk::OclDataSetFilter::SetInput(mitk::Image::Pointer image)
-{
- m_Input = mitk::OclDataSet::New();
- mitk::ImageReadAccessor reader(image);
-
- m_Input->SetData(const_cast<void*>(reader.GetData()));
- m_CurrentSize = (unsigned int)(image->GetPixelType().GetBitsPerComponent() / 8);
- unsigned int elements = image->GetDimension(0) * image->GetDimension(1) * image->GetDimension(2);
-
- m_Input->SetBufferSize(elements);
- m_Input->SetBpE(m_CurrentSize);
-}
diff --git a/Modules/OpenCL/mitkOclDataSetFilter.h b/Modules/OpenCL/mitkOclDataSetFilter.h
deleted file mode 100644
index 9ac247fab0..0000000000
--- a/Modules/OpenCL/mitkOclDataSetFilter.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 mitkOclDataSetFilter_h
-#define mitkOclDataSetFilter_h
-
-#include "mitkOclFilter.h"
-#include "mitkOclDataSet.h"
-
-#define FILTER_UCHAR 0
-#define FILTER_SHORT 1
-
-namespace mitk
-{
-class OclFilter;
-class OclDataSetFilter;
-
- /**
- * \brief The OclDataSetFilter is the topmost class for all filter which take DataSets as input.
- *
- * The input DataSet can be intialized via an oclDataSet or a pointer to the data
- * This makes it possible to create a filter pipeline of GPU-based filters
- * and to bind this part into the CPU (ITK) filter pipeline.
- */
-class MITKOPENCL_EXPORT OclDataSetFilter: public OclFilter
-{
-public:
- /**
- * @brief SetInput SetInput Set the input DataSet (as mitk::OclDataSet).
- * @param DataSet The DataSet in mitk::OclDataSet.
- */
- void SetInput(mitk::OclDataSet::Pointer DataSet);
-
- /**
- * @brief SetInput Set the input DataSet (as a pointer to the data).
- * @param DataSet The DataSet in mitk::OclDataSet.
- * @param size
- * @param BpE
- */
- void SetInput(void* DataSet, unsigned int size, unsigned int BpE);
-
- /**
- * @brief SetInput Set the input DataSet (as mitk::Image).
- * @param image The DataSet in mitk::OclDataSet.
- */
- void SetInput(mitk::Image::Pointer image);
-
-protected:
- OclDataSetFilter();
-
- virtual ~OclDataSetFilter();
-
- /** The input DataSet */
- mitk::OclDataSet::Pointer m_Input;
- unsigned int m_CurrentSize;
-};
-}
-#endif
diff --git a/Modules/OpenCL/mitkOclDataSetToDataSetFilter.cpp b/Modules/OpenCL/mitkOclDataSetToDataSetFilter.cpp
deleted file mode 100644
index 99fffdb4b8..0000000000
--- a/Modules/OpenCL/mitkOclDataSetToDataSetFilter.cpp
+++ /dev/null
@@ -1,124 +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 "mitkOclDataSetToDataSetFilter.h"
-#include "mitkOclDataSet.h"
-
-#include "mitkException.h"
-
-mitk::OclDataSetToDataSetFilter::OclDataSetToDataSetFilter()
-{
- m_Output = mitk::OclDataSet::New();
-}
-
-mitk::OclDataSetToDataSetFilter::~OclDataSetToDataSetFilter()
-{
-}
-
-mitk::OclDataSet::Pointer mitk::OclDataSetToDataSetFilter::GetGPUOutput()
-{
- return this->m_Output;
-}
-
-void* mitk::OclDataSetToDataSetFilter::GetOutput()
-{
- void* pData = m_Output->TransferDataToCPU(m_CommandQue);
- return pData;
-}
-
-int mitk::OclDataSetToDataSetFilter::GetBytesPerElem()
-{
- return this->m_CurrentSizeOutput;
-}
-
-bool mitk::OclDataSetToDataSetFilter::InitExec(cl_kernel ckKernel, unsigned int* dimensions, size_t outputDataSize, unsigned int outputBpE)
-{
- cl_int clErr = 0;
-
- if (m_Input.IsNull())
- mitkThrow() << "Input DataSet is null.";
-
- // get DataSet size once
- const unsigned int uiDataSetWidth = dimensions[0];
- const unsigned int uiDataSetHeight = dimensions[1];
- const unsigned int uiDataSetDepth = dimensions[2];
-
- // compute work sizes
- this->SetWorkingSize(8, uiDataSetWidth, 8, uiDataSetHeight, 8, uiDataSetDepth);
-
- cl_mem clBuffIn = m_Input->GetGPUBuffer();
- cl_mem clBuffOut = m_Output->GetGPUBuffer();
-
- if (!clBuffIn)
- {
- if (m_Input->TransferDataToGPU(m_CommandQue) != CL_SUCCESS)
- {
- mitkThrow() << "Could not create / initialize gpu DataSet.";
- }
-
- clBuffIn = m_Input->GetGPUBuffer();
- }
-
- // output DataSet not initialized or output buffer size changed
- if (!clBuffOut || (size_t)m_Output->GetBufferSize() != outputDataSize)
- {
- MITK_DEBUG << "Create GPU DataSet call " << uiDataSetWidth << "x" << uiDataSetHeight << "x" << uiDataSetDepth;
- MITK_INFO << "Create GPU Buffer of size " << outputDataSize * outputBpE / 1024.f / 1024.f << "MB";
- m_Output->SetBpE(outputBpE);
- m_Output->SetBufferSize(outputDataSize);
- clBuffOut = m_Output->CreateGPUBuffer();
- m_CurrentSizeOutput = outputBpE;
- }
-
- clErr = 0;
- clErr = clSetKernelArg(ckKernel, 0, sizeof(cl_mem), &clBuffIn);
- clErr |= clSetKernelArg(ckKernel, 1, sizeof(cl_mem), &clBuffOut);
- CHECK_OCL_ERR(clErr);
-
- if (clErr != CL_SUCCESS)
- mitkThrow() << "OpenCL Part initialization failed with " << GetOclErrorAsString(clErr);
-
- return(clErr == CL_SUCCESS);
-}
-
-bool mitk::OclDataSetToDataSetFilter::InitExecNoInput(cl_kernel ckKernel, unsigned int* dimensions, size_t outputDataSize, unsigned int outputBpE)
-{
- cl_int clErr = 0;
-
- // get DataSet size once
- const unsigned int uiDataSetWidth = dimensions[0];
- const unsigned int uiDataSetHeight = dimensions[1];
- const unsigned int uiDataSetDepth = dimensions[2];
-
- // compute work sizes
- this->SetWorkingSize(8, uiDataSetWidth, 8, uiDataSetHeight, 8, uiDataSetDepth);
-
- cl_mem clBuffOut = m_Output->GetGPUBuffer();
-
- // output DataSet not initialized or output buffer size changed
- if (!clBuffOut || (size_t)m_Output->GetBufferSize() != outputDataSize)
- {
- MITK_DEBUG << "Create GPU DataSet call " << uiDataSetWidth << "x" << uiDataSetHeight << "x" << uiDataSetDepth;
- m_Output->SetBpE(outputBpE);
- m_Output->SetBufferSize(outputDataSize);
- clBuffOut = m_Output->CreateGPUBuffer();
- m_CurrentSizeOutput = outputBpE;
- }
-
- clErr = clSetKernelArg(ckKernel, 0, sizeof(cl_mem), &clBuffOut);
- CHECK_OCL_ERR(clErr);
-
- if (clErr != CL_SUCCESS)
- mitkThrow() << "OpenCL Part initialization failed with " << GetOclErrorAsString(clErr);
-
- return(clErr == CL_SUCCESS);
-}
diff --git a/Modules/OpenCL/mitkOclDataSetToDataSetFilter.h b/Modules/OpenCL/mitkOclDataSetToDataSetFilter.h
deleted file mode 100644
index d3f22d4c46..0000000000
--- a/Modules/OpenCL/mitkOclDataSetToDataSetFilter.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 mitkOclDataSetToDataSetFilter_h
-#define mitkOclDataSetToDataSetFilter_h
-
-#include "mitkOclDataSetFilter.h"
-
-namespace mitk
-{
-class OclDataSetFilter;
-class OclDataSetToDataSetFilter;
-
-/** @class OclDataSetToDataSetFilter
- * @brief The OclDataSetToDataSetFilter is the base class for all OpenCL DataSet filter generating DataSets.
- */
-class MITKOPENCL_EXPORT OclDataSetToDataSetFilter: public OclDataSetFilter
-{
-public:
- /*!
- * \brief Returns an pointer to the filtered data.
- */
- void* GetOutput();
-
- /*!
- * \brief Returns a pointer to the graphics memory.
- *
- * Use this method when executing two and more filters on the GPU for fast access.
- * This method does not copy the data to RAM. It returns only a pointer.
- */
- mitk::OclDataSet::Pointer GetGPUOutput();
-
-protected:
- /**
- * @brief OclDataSetToDataSetFilter Default constructor.
- */
- OclDataSetToDataSetFilter();
-
- /** @brief Destructor */
- virtual ~OclDataSetToDataSetFilter();
-
- /** Output DataSet */
- mitk::OclDataSet::Pointer m_Output;
-
- /** @brief (Virtual) method Update() to be implemented in derived classes. */
- virtual void Update() = 0;
-
- /**
- * @brief InitExec Initialize the execution
- * @param ckKernel The GPU kernel.
- * @param dimensions
- * @param outputDataSize
- * @param outputBpE
- * @throws mitk::Exception if something goes wrong.
- * @return True for success.
- */
- bool InitExec(cl_kernel ckKernel, unsigned int* dimensions, size_t outputDataSize, unsigned int outputBpE);
-
- bool InitExecNoInput(cl_kernel ckKernel, unsigned int* dimensions, size_t outputDataSize, unsigned int outputBpE);
-
- /** @brief Get the memory size needed for each element */
- virtual int GetBytesPerElem();
-
- unsigned int m_CurrentSizeOutput;
-
-private:
- /** Block dimensions */
- unsigned int m_BlockDims[3];
-};
-}
-#endif
diff --git a/Modules/OpenCL/mitkOclFilter.cpp b/Modules/OpenCL/mitkOclFilter.cpp
deleted file mode 100644
index db9772822d..0000000000
--- a/Modules/OpenCL/mitkOclFilter.cpp
+++ /dev/null
@@ -1,351 +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.
-
-============================================================================*/
-
-//Ocl
-#include "mitkOclFilter.h"
-#include "mitkOclUtils.h"
-#include "mitkOpenCLActivator.h"
-
-
-//Mitk
-#include <mitkLog.h>
-#include <mitkConfig.h>
-
-//usService
-#include "usServiceReference.h"
-#include <usServiceRegistration.h>
-#include <usModuleContext.h>
-#include <usGetModuleContext.h>
-#include <usModule.h>
-#include <usModuleResource.h>
-#include <usModuleResourceStream.h>
-
-//standard library
-#include <thread>
-
-mitk::OclFilter::OclFilter()
- : m_ClCompilerFlags(""),
- m_ClProgram(nullptr),
- m_CommandQue(nullptr),
- m_FilterID("mitkOclFilter"),
- m_Preambel(" "),
- m_Initialized(false)
-{
-}
-
-mitk::OclFilter::OclFilter(const char* filename)
- : m_ClCompilerFlags(""),
- m_ClProgram(nullptr),
- m_CommandQue(nullptr),
- m_FilterID(filename),
- m_Preambel(" "),
- m_Initialized(false)
-{
- m_ClFiles.push_back(filename);
-}
-
-mitk::OclFilter::~OclFilter()
-{
- MITK_DEBUG << "OclFilter Destructor";
-
- // release program
- if (m_ClProgram)
- {
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
-
- // remove program from storage
- resources->RemoveProgram(m_FilterID);
- }
-}
-
-bool mitk::OclFilter::ExecuteKernel( cl_kernel kernel, unsigned int workSizeDim )
-{
- cl_int clErr = 0;
-
- clErr = clEnqueueNDRangeKernel( this->m_CommandQue, kernel, workSizeDim,
- nullptr, this->m_GlobalWorkSize, m_LocalWorkSize, 0, nullptr, nullptr);
-
- CHECK_OCL_ERR( clErr );
-
- return ( clErr == CL_SUCCESS );
-}
-
-bool mitk::OclFilter::ExecuteKernelChunks( cl_kernel kernel, unsigned int workSizeDim, size_t* chunksDim )
-{
- size_t offset[3] ={0, 0, 0};
- cl_int clErr = 0;
-
- if(workSizeDim == 2)
- {
- for(offset[0] = 0; offset[0] < m_GlobalWorkSize[0]; offset[0] += chunksDim[0])
- {
- for(offset[1] = 0; offset[1] < m_GlobalWorkSize[1]; offset[1] += chunksDim[1])
- {
- clErr |= clEnqueueNDRangeKernel(this->m_CommandQue, kernel, workSizeDim,
- offset, chunksDim, m_LocalWorkSize, 0, nullptr, nullptr);
- }
- }
- }
- else if(workSizeDim == 3)
- {
- for(offset[0] = 0; offset[0] < m_GlobalWorkSize[0]; offset[0] += chunksDim[0])
- {
- for(offset[1] = 0; offset[1] < m_GlobalWorkSize[1]; offset[1] += chunksDim[1])
- {
- for(offset[2] = 0; offset[2] < m_GlobalWorkSize[2]; offset[2] += chunksDim[2])
- {
- clErr |= clEnqueueNDRangeKernel( this->m_CommandQue, kernel, workSizeDim,
- offset, chunksDim, m_LocalWorkSize, 0, nullptr, nullptr);
- }
- }
- }
- }
-
- CHECK_OCL_ERR(clErr);
-
- return ( clErr == CL_SUCCESS );
-}
-
-bool mitk::OclFilter::ExecuteKernelChunksInBatches(cl_kernel kernel, unsigned int workSizeDim, size_t* chunksDim, size_t batchSize, int waitTimems)
-{
- size_t offset[3] = { 0, 0, 0 };
- cl_int clErr = 0;
-
- unsigned int currentChunk = 0;
- cl_event* waitFor = new cl_event[batchSize];
-
- if (workSizeDim == 2)
- {
- for (offset[0] = 0; offset[0] < m_GlobalWorkSize[0]; offset[0] += chunksDim[0])
- {
- for (offset[1] = 0; offset[1] < m_GlobalWorkSize[1]; offset[1] += chunksDim[1])
- {
- if (currentChunk % batchSize == 0 && currentChunk != 0)
- {
- clWaitForEvents(batchSize, &waitFor[0]);
- std::this_thread::sleep_for(std::chrono::milliseconds(waitTimems));
- clErr |= clEnqueueNDRangeKernel(this->m_CommandQue, kernel, workSizeDim,
- offset, chunksDim, m_LocalWorkSize, 0, nullptr, &waitFor[0]);
- }
- else
- {
- clErr |= clEnqueueNDRangeKernel(this->m_CommandQue, kernel, workSizeDim,
- offset, chunksDim, m_LocalWorkSize, 0, nullptr, &waitFor[currentChunk % batchSize]);
- }
- currentChunk++;
- }
- }
- }
- else if (workSizeDim == 3)
- {
- for (offset[0] = 0; offset[0] < m_GlobalWorkSize[0]; offset[0] += chunksDim[0])
- {
- for (offset[1] = 0; offset[1] < m_GlobalWorkSize[1]; offset[1] += chunksDim[1])
- {
- for (offset[2] = 0; offset[2] < m_GlobalWorkSize[2]; offset[2] += chunksDim[2])
- {
- if (currentChunk % batchSize == 0 && currentChunk != 0)
- {
- clWaitForEvents(batchSize, &waitFor[0]);
- std::this_thread::sleep_for(std::chrono::milliseconds(waitTimems));
- clErr |= clEnqueueNDRangeKernel(this->m_CommandQue, kernel, workSizeDim,
- offset, chunksDim, m_LocalWorkSize, 0, nullptr, &waitFor[0]);
- }
- else
- {
- clErr |= clEnqueueNDRangeKernel(this->m_CommandQue, kernel, workSizeDim,
- offset, chunksDim, m_LocalWorkSize, 0, nullptr, &waitFor[currentChunk % batchSize]);
- }
- currentChunk++;
- }
- }
- }
- }
- CHECK_OCL_ERR(clErr);
-
- return (clErr == CL_SUCCESS);
-}
-
-
-bool mitk::OclFilter::Initialize()
-{
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
-
- m_CommandQue = resources->GetCommandQueue();
-
- cl_int clErr = 0;
- m_Initialized = CHECK_OCL_ERR(clErr);
-
- if ( m_ClFiles.empty())
- {
- MITK_ERROR<<"No OpenCL Source FILE specified";
- return false;
- }
-
- if (m_ClProgram == nullptr)
- {
- try
- {
- this->m_ClProgram = resources->GetProgram( this->m_FilterID );
- }
- catch(const mitk::Exception& e)
- {
- MITK_INFO << "Program not stored in resource manager, compiling. " << e;
- this->CompileSource();
- }
- }
-
- return m_Initialized;
-}
-
-void mitk::OclFilter::LoadSourceFiles(CStringList &sourceCode, ClSizeList &sourceCodeSize)
-{
- for( CStringList::iterator it = m_ClFiles.begin(); it != m_ClFiles.end(); ++it )
- {
- MITK_DEBUG << "Load file :" << *it;
- us::ModuleResource mdr = GetModule()->GetResource(*it);
-
- if( !mdr.IsValid() )
- MITK_WARN << "Could not load resource: " << mdr.GetName() << " is invalid!";
-
- us::ModuleResourceStream rss(mdr);
-
- // read resource file to a string
- std::istreambuf_iterator<char> eos;
- std::string source(std::istreambuf_iterator<char>(rss), eos);
-
- // add preambel and build up string to compile
- std::string src(m_Preambel);
- src.append("\n");
- src.append(source);
-
- // allocate new char buffer
- char* tmp = new char[src.size() + 1];
- strcpy(tmp,src.c_str());
-
- // add source to list
- sourceCode.push_back((const char*)tmp);
- sourceCodeSize.push_back(src.size());
- }
-}
-
-void mitk::OclFilter::CompileSource()
-{
- // helper variable
- int clErr = 0;
- CStringList sourceCode;
- ClSizeList sourceCodeSize;
-
- if (m_ClFiles.empty())
- {
- MITK_ERROR("ocl.filter") << "No shader source file was set";
- return;
- }
-
- //get a valid opencl context
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
-
- cl_context gpuContext = resources->GetContext();
- // load the program source from file
- LoadSourceFiles(sourceCode, sourceCodeSize);
-
- if ( !sourceCode.empty() )
- {
- // create program from all files in the file list
- m_ClProgram = clCreateProgramWithSource(gpuContext, sourceCode.size(), &sourceCode[0], &sourceCodeSize[0], &clErr);
- CHECK_OCL_ERR(clErr);
-
- // build the source code
- MITK_DEBUG << "Building Program Source";
- std::string compilerOptions = "";
- compilerOptions.append(m_ClCompilerFlags);
-
- MITK_DEBUG("ocl.filter") << "cl compiler flags: " << compilerOptions.c_str();
-
- clErr = clBuildProgram(m_ClProgram, 0, nullptr, compilerOptions.c_str(), nullptr, nullptr);
- CHECK_OCL_ERR(clErr);
-
- // if OpenCL Source build failed
- if (clErr != CL_SUCCESS)
- {
- MITK_ERROR("ocl.filter") << "Failed to build source";
- oclLogBuildInfo(m_ClProgram, resources->GetCurrentDevice() );
- oclLogBinary(m_ClProgram, resources->GetCurrentDevice() );
- m_Initialized = false;
- }
-
- // store the succesfully build program into the program storage provided by the resource service
- resources->InsertProgram(m_ClProgram, m_FilterID, true);
-
- // free the char buffers with the source code
- for( CStringList::iterator it = sourceCode.begin(); it != sourceCode.end(); ++it )
- {
- delete[] *it;
- }
- }
- else
- {
- MITK_ERROR("ocl.filter") << "Could not load from source";
- m_Initialized = false;
- }
-}
-
-void mitk::OclFilter::SetWorkingSize(unsigned int locx, unsigned int dimx, unsigned int locy, unsigned int dimy, unsigned int locz, unsigned int dimz)
-{
- // set the local work size
- this->m_LocalWorkSize[0] = locx;
- this->m_LocalWorkSize[1] = locy;
- this->m_LocalWorkSize[2] = locz;
-
- this->m_GlobalWorkSize[0] = dimx;
- this->m_GlobalWorkSize[1] = dimy;
- this->m_GlobalWorkSize[2] = dimz;
-
- // estimate the global work size
- this->m_GlobalWorkSize[0] = iDivUp( dimx, this->m_LocalWorkSize[0]) * this->m_LocalWorkSize[0];
-
- if ( dimy > 1)
- this->m_GlobalWorkSize[1] = iDivUp( dimy, this->m_LocalWorkSize[1]) * this->m_LocalWorkSize[1];
- if( dimz > 1 )
- this->m_GlobalWorkSize[2] = iDivUp( dimz, this->m_LocalWorkSize[2]) * this->m_LocalWorkSize[2];
-}
-
-void mitk::OclFilter::SetSourcePreambel(const char* preambel)
-{
- this->m_Preambel = preambel;
-}
-
-void mitk::OclFilter::AddSourceFile(const char* filename)
-{
- m_ClFiles.push_back(filename);
-}
-
-void mitk::OclFilter::SetCompilerFlags(const char* flags)
-{
- m_ClCompilerFlags = flags;
-}
-
-
-bool mitk::OclFilter::IsInitialized()
-{
- return m_Initialized;
-}
-
-unsigned long mitk::OclFilter::GetDeviceMemory()
-{
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(GetModuleContext()->GetServiceReference<OclResourceService>());
- auto device = resources->GetCurrentDevice();
- return oclGetGlobalMemSize(device);
-}
diff --git a/Modules/OpenCL/mitkOclFilter.h b/Modules/OpenCL/mitkOclFilter.h
deleted file mode 100644
index 93b6ddf5c0..0000000000
--- a/Modules/OpenCL/mitkOclFilter.h
+++ /dev/null
@@ -1,157 +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 mitkOclFilter_h
-#define mitkOclFilter_h
-
-#include "mitkOclUtils.h"
-#include "mitkCommon.h"
-
-#include <vector>
-#include <usModule.h>
-
-#include <MitkOpenCLExports.h>
-
-namespace mitk
-{
-/**
- @class OclFilter
- @brief Superclass for all OpenCL based filter.
-
- This class takes care of loading and compiling the external GPU program code.
- */
-class MITKOPENCL_EXPORT OclFilter
-{
-public:
- /**
- * @brief Add a source file from the resource files to the
- * OpenCL shader file list. Multiple files can be added to the list.
- *
- * @param filename of the file in the resource system
- */
- void AddSourceFile(const char* filename);
-
- /**
- * @brief Set specific compilerflags to compile the CL source. Default is set to nullptr;
- * example: "-cl-fast-relaxed-math -cl-mad-enable -cl-strict-aliasing"
- *
- * @param flags to the modulefolder that contains the gpuSource
- */
- void SetCompilerFlags(const char* flags);
-
- /**
- * @brief Returns true if the initialization was successfull
- */
- virtual bool IsInitialized();
-
- /**
- * @brief Returns the amount of global memory of the used device in bytes
- */
- virtual unsigned long GetDeviceMemory();
-
- /** @brief Destructor */
- virtual ~OclFilter();
-
-protected:
-
- typedef std::vector<const char*> CStringList;
- typedef std::vector<size_t> ClSizeList;
-
- /** @brief Constructor */
- OclFilter();
-
- /** @brief Constructor ( overloaded ) */
- OclFilter(const char* filename);
-
- /** @brief String that contains the compiler flags */
- const char* m_ClCompilerFlags;
-
- /** @brief The compiled OpenCL program */
- cl_program m_ClProgram;
-
- /** @brief Command queue for the filter */
- cl_command_queue m_CommandQue;
-
- /** @brief Unique ID of the filter, needs to be specified in the constructor of the derived class */
- std::string m_FilterID;
-
- /*! @brief source preambel for e.g. \c \#define commands to be inserted into the OpenCL source */
- const char* m_Preambel;
-
- /** @brief List of sourcefiles that will be compiled for this filter.*/
- CStringList m_ClFiles;
-
- /** @brief status of the filter */
- bool m_Initialized;
-
- /** @brief The local work size fo the filter */
- size_t m_LocalWorkSize[3];
-
- /** @brief The global work size of the filter */
- size_t m_GlobalWorkSize[3];
-
- /** @brief Set the working size for the following OpenCL kernel call */
- void SetWorkingSize(unsigned int locx, unsigned int dimx,
- unsigned int locy = 1, unsigned int dimy = 1,
- unsigned int locz = 1, unsigned int dimz = 1);
-
- /** @brief Execute the given kernel on the OpenCL Index-Space defined by the local and global work sizes
- */
- bool ExecuteKernel( cl_kernel kernel, unsigned int workSizeDim );
-
- /** @brief Execute the given kernel on the OpenCL Index-Space defined by the local and global work sizes, but divide it into chunks of dimension chunksDim
- */
- bool ExecuteKernelChunks( cl_kernel kernel, unsigned int workSizeDim, size_t* chunksDim );
-
- /** @brief Execute the given kernel on the OpenCL Index-Space defined by the local and global work sizes, but divide it into chunks of dimension chunksDim and wait between
- * batches of batchSize chunks a time of waitTimems milliseconds
- */
- bool ExecuteKernelChunksInBatches(cl_kernel kernel, unsigned int workSizeDim, size_t* chunksDim, size_t batchSize, int waitTimems);
- /**
- * \brief Initialize all necessary parts of the filter
- *
- * The Initialize() method creates the command queue and the m_clProgram.
- * The program is either compiled from the given source or taken from the
- * OclResourceManager if the program was compiled already.
- */
- bool Initialize();
-
- /**
- * @brief Compile the program source
- */
- void CompileSource();
-
- /**
- * @brief Add some source code on the beginning of the loaded source
- *
- * In this way, some preprocessor flags for the CL compiler can at the beginning of the filter
- * @param preambel Source preambel for e.g. \c \#define commands to be inserted into the OpenCL source
- */
- void SetSourcePreambel(const char* preambel);
-
- /**
- * @brief Get the Module of the filter. Needs to be implemented by every subclass.
- * The filter will load the OpenCL sourcefiles from this module context.
- */
- virtual us::Module* GetModule() = 0;
-
- /**
- * @brief Helper functions that load sourcefiles from the module context in the Initialize function.
- * @param SourceCodeList holds the sourcecode for every file as string, the SourceCodeSizeList holst the
- * size of every file in bytes.
- * @param SourceCodeSizeList
- */
- void LoadSourceFiles(CStringList &SourceCodeList, ClSizeList &SourceCodeSizeList);
-};
-}
-#endif
diff --git a/Modules/OpenCL/mitkOclImage.cpp b/Modules/OpenCL/mitkOclImage.cpp
deleted file mode 100644
index 31aa963c8d..0000000000
--- a/Modules/OpenCL/mitkOclImage.cpp
+++ /dev/null
@@ -1,359 +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 "mitkOclImage.h"
-#include "mitkImageDataItem.h"
-#include "mitkCommon.h"
-#include "mitkLog.h"
-
-#include "mitkOclUtils.h"
-
-#include <mitkImageReadAccessor.h>
-#include <fstream>
-
-mitk::OclImage::OclImage() : m_gpuImage(nullptr), m_context(nullptr), m_bufferSize(0), m_gpuModified(false), m_cpuModified(false),
- m_Image(nullptr), m_dim(0), m_Dims(nullptr), m_BpE(1), m_formatSupported(false)
-{
-}
-
-mitk::OclImage::~OclImage()
-{
- MITK_INFO << "OclImage Destructor";
-
- //release GMEM Image buffer
- if (m_gpuImage) clReleaseMemObject(m_gpuImage);
-}
-
-
-cl_mem mitk::OclImage::CreateGPUImage(unsigned int _wi, unsigned int _he, unsigned int _de,
- unsigned int _bpp)
-{
- MITK_INFO << "CreateGPUImage call with: BPP=" << _bpp;
-
- this->m_Dims = new unsigned int[MAX_DIMS];
-
- m_Dims[0] = _wi;
- m_Dims[1] = _he;
- m_Dims[2] = _de;
-
- for (unsigned int i=3; i<MAX_DIMS; i++)
- m_Dims[i] = 1;
-
- m_bufferSize = _wi * _he * _de;
-
- m_BpE = _bpp;
-
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
-
- cl_context gpuContext = resources->GetContext();
-
- int clErr;
- m_gpuImage = clCreateBuffer( gpuContext, CL_MEM_READ_WRITE, m_bufferSize * m_BpE, nullptr, &clErr);
-
- CHECK_OCL_ERR(clErr);
-
- return m_gpuImage;
-}
-
-void mitk::OclImage::InitializeByMitkImage(mitk::Image::Pointer _image)
-{
- this->m_Image = _image;
- this->m_cpuModified = true;
- this->m_gpuModified = false;
-
- this->m_gpuImage = nullptr;
-
- // compute the size of the GMEM buffer
- this->m_dim = this->m_Image->GetDimension();
- this->m_Dims = this->m_Image->GetDimensions();
- MITK_INFO << "Image: " << this->m_Dims[0] <<"x"<< this->m_Dims[1] <<"x"<< this->m_Dims[2];
-
- // get the dimensions
- this->m_bufferSize = 1;
- for (unsigned int i=0; i<this->m_dim; i++)
- {
- this->m_bufferSize *= this->m_Dims[i];
- }
-
- // multiply by sizeof(PixelType)
- this->m_BpE = ( this->m_Image->GetPixelType().GetBpe() / 8);
-}
-
-bool mitk::OclImage::IsModified(int _type)
-{
- if (_type) return m_cpuModified;
- else return m_gpuModified;
-}
-
-void mitk::OclImage::Modified(int _type)
-{
- // defines... GPU: 0, CPU: 1
- m_cpuModified = _type;
- m_gpuModified = !_type;
-}
-
-int mitk::OclImage::TransferDataToGPU(cl_command_queue gpuComQueue)
-{
- cl_int clErr = 0;
-
- // check whether an image present
- if (!m_Image->IsInitialized()){
- MITK_ERROR("ocl.Image") << "(mitk) Image not initialized!\n";
- return -1;
- }
-
- // there is a need for copy only if RAM-Data newer then GMEM data
- if (m_cpuModified)
- {
- //check the buffer
- if(m_gpuImage == nullptr)
- {
- clErr = this->AllocateGPUImage();
- }
-
- if (m_Image->IsInitialized() &&
- (clErr == CL_SUCCESS))
- {
- const size_t origin[3] = {0, 0, 0};
- const size_t region[3] = {m_Dims[0], m_Dims[1], m_Dims[2]};
-
- if( this->m_formatSupported )
- {
- mitk::ImageReadAccessor accessor(m_Image);
- clErr = clEnqueueWriteImage( gpuComQueue, m_gpuImage, CL_TRUE, origin, region, 0, 0, accessor.GetData(), 0, nullptr, nullptr);
- }
- else
- {
- MITK_ERROR << "Selected image format currently not supported...";
- }
-
- CHECK_OCL_ERR(clErr);
- }
- m_gpuModified = true;
- }
-
- return clErr;
-}
-
-cl_int mitk::OclImage::AllocateGPUImage()
-{
- cl_int clErr = 0;
-
- us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
- OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
-
- cl_context gpuContext = resources->GetContext();
-
- // initialize both proposed and supported format variables to same value
- this->m_proposedFormat = this->ConvertPixelTypeToOCLFormat();
- this->m_supportedFormat = this->m_proposedFormat;
-
- // test the current format for HW support
- this->m_formatSupported = resources->GetIsFormatSupported( &(this->m_supportedFormat) );
-
- // create an transfer kernel object in case the proposed format is not supported
- if( !(this->m_formatSupported) )
- {
- mitkThrowException(mitk::ImageTypeIsNotSupportedByGPU) << "Original format not supported on the installed graphics card.";
- }
-
-
- _cl_image_desc imageDescriptor;
-
- imageDescriptor.image_width = *(m_Dims);
- imageDescriptor.image_height = *(m_Dims + 1);
- imageDescriptor.image_depth = *(m_Dims + 2);
- imageDescriptor.image_array_size = 0;
- imageDescriptor.image_row_pitch = 0;
- imageDescriptor.image_slice_pitch = 0;
- imageDescriptor.num_mip_levels = 0;
- imageDescriptor.num_samples = 0;
- imageDescriptor.buffer = nullptr;
- // create new buffer
- if( this->m_dim > 2)
- {
- //Create a 3D Image
- imageDescriptor.image_type = CL_MEM_OBJECT_IMAGE3D;
- }
- else
- {
- //Create a 2D Image
- imageDescriptor.image_type = CL_MEM_OBJECT_IMAGE2D;
- }
- m_gpuImage = clCreateImage(gpuContext, CL_MEM_READ_ONLY, &m_supportedFormat, &imageDescriptor, nullptr, &clErr);
-
- CHECK_OCL_ERR(clErr);
-
- return clErr;
-}
-
-cl_mem mitk::OclImage::GetGPUImage(cl_command_queue gpuComQueue)
-{
- // clGetMemObjectInfo()
- cl_mem_object_type memInfo;
- cl_int clErr = 0;
-
- // query image object info only if already initialized
- if( this->m_gpuImage )
- {
- clErr = clGetMemObjectInfo(this->m_gpuImage, CL_MEM_TYPE, sizeof(cl_mem_object_type), &memInfo, nullptr );
- CHECK_OCL_ERR(clErr);
- }
-
- MITK_INFO << "Querying info for object, recieving: " << memInfo;
-
- // test if m_gpuImage CL_MEM_IMAGE_2/3D
- // if not, copy buffer to image
- if (memInfo == CL_MEM_OBJECT_BUFFER)
- {
- MITK_WARN << " Passed oclImage is a buffer-object, creating image";
-
- //hold a copy of the buffer gmem pointer
- cl_mem tempBuffer = this->m_gpuImage;
-
- const size_t origin[3] = {0, 0, 0};
- size_t region[3] = {this->m_Dims[0], this->m_Dims[1], 1};
-
- clErr = this->AllocateGPUImage();
-
- this->m_dim = 3;
-
- //copy last data to the image data
- clErr = clEnqueueCopyBufferToImage( gpuComQueue, tempBuffer, m_gpuImage, 0, origin, region, 0, nullptr, nullptr);
- CHECK_OCL_ERR(clErr);
-
- //release pointer
- clReleaseMemObject(tempBuffer);
- }
- return m_gpuImage;
-}
-
-void mitk::OclImage::SetPixelType(const cl_image_format *_image)
-{
- this->m_proposedFormat.image_channel_data_type = _image->image_channel_data_type;
- this->m_proposedFormat.image_channel_order = _image->image_channel_order;
-}
-
-void* mitk::OclImage::TransferDataToCPU(cl_command_queue gpuComQueue)
-{
- cl_int clErr = 0;
-
- // if image created on GPU, needs to create mitk::Image
- if( m_Image.IsNull() ){
- MITK_INFO << "Image not initialized, creating new one.";
- m_Image = mitk::Image::New();
- }
-
- // check buffersize/image size
- char* data = new char[m_bufferSize * m_BpE];
-
- // debug info
- oclPrintMemObjectInfo( m_gpuImage );
-
- clErr = clEnqueueReadBuffer( gpuComQueue, m_gpuImage, CL_FALSE, 0, m_bufferSize * m_BpE, data ,0, nullptr, nullptr);
- CHECK_OCL_ERR(clErr);
-
- clFlush( gpuComQueue );
- // the cpu data is same as gpu
- this->m_gpuModified = false;
-
- return (void*) data;
-}
-
-cl_image_format mitk::OclImage::ConvertPixelTypeToOCLFormat()
-{
- cl_image_format texFormat;
- //single channel Gray-Valued Images
- texFormat.image_channel_order = CL_R;
-
- MITK_INFO << "Class own value: " << this->m_BpE;
-
- switch ( this->m_BpE )
- {
- case 1:
- texFormat.image_channel_data_type = CL_UNSIGNED_INT8;
- MITK_INFO<< "PixelType: UCHAR => CLFormat: [CL_UNORM_INT8, CL_R]";
- break;
- case 2:
- texFormat.image_channel_data_type = CL_SIGNED_INT16;
- // texFormat.image_channel_order = CL_R;
- MITK_INFO<< "PixelType: SHORT => CLFormat: [CL_SIGNED_INT16, CL_R]";
- break;
- case 4:
- texFormat.image_channel_data_type = CL_FLOAT;
- MITK_INFO<< "Choosing CL_FLOAT";
- break;
- default:
- texFormat.image_channel_data_type = CL_UNORM_INT8;
- texFormat.image_channel_order = CL_RG;
- MITK_INFO<< "Choosing (default) short: 2-Channel UCHAR";
- break;
- }
-
- return texFormat;
-}
-
-int mitk::OclImage::GetDimension(int idx) const
-{
- if (this->m_dim > idx)
- {
- return m_Dims[idx];
- }
- else
- {
- MITK_WARN << "Trying to access non-existing dimension.";
- return 1;
- }
-}
-
-void mitk::OclImage::SetDimensions(unsigned int* Dims)
-{
- m_Dims = Dims;
-}
-
-void mitk::OclImage::SetDimension(unsigned short dim)
-{
- m_dim = dim;
-}
-
-float mitk::OclImage::GetSpacing(int idx)
-{
- if (this->m_dim > idx)
- {
- const mitk::Vector3D imSpacing = m_Image->GetSlicedGeometry()->GetSpacing();
-
- return imSpacing[idx];
- }
- else
- {
- MITK_WARN << "Trying to access non-existing dimension.";
- return 1;
- }
-}
-
-void mitk::OclImage::InitializeMITKImage()
-{
- this->m_Image = mitk::Image::New();
-}
-
-void mitk::OclImage::GetOffset(float* _imOffset) const
-{
- itk::Vector<float, 3> result2;
- result2.Fill(0.0f);
-
- result2 = this->m_Image->GetGeometry()->GetIndexToWorldTransform()->GetOffset();
-
- _imOffset[0] = result2[0];
- _imOffset[1] = result2[1];
- _imOffset[2] = result2[2];
-}
diff --git a/Modules/OpenCL/mitkOclImage.h b/Modules/OpenCL/mitkOclImage.h
deleted file mode 100644
index f42eff6dce..0000000000
--- a/Modules/OpenCL/mitkOclImage.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkOclImage_h
-#define mitkOclImage_h
-
-#define GPU_DATA 0
-#define CPU_DATA 1
-
-#define MAX_DIMS 20
-
-#include <mitkImage.h>
-#include "MitkOpenCLExports.h"
-
-#include "mitkOclBaseData.h"
-#include "mitkOclImageFormats.h"
-#include "mitkOpenCLActivator.h"
-
-#include <mitkException.h>
-
-
-#define SHORT_IM mitk::MakeScalarPixelType<short>()
-#define FLOAT_IM mitk::MakeScalarPixelType<float>()
-
-namespace mitk {
-
-/*!
- * \brief Class implementing the image format for GPU Image Processing
- *
- * The class holds a pointer to the mitk::Image stored in RAM and performs an
- * on-demand-copy to the graphics memory. It is the basic data structure for all
- * mitk::oclImageToImageFilter classes
- * @throw This class may throw an ImageTypeIsNotSupportedByGPU, if the image
- * format is supported by the GPU.
- */
-class MITKOPENCL_EXPORT OclImage : public OclBaseData
-{
-public:
- mitkClassMacro(OclImage, OclBaseData);
- itkFactorylessNewMacro(Self);
- itkCloneMacro(Self);
-
- /*! \brief Copies the RAM-stored data to GMEM */
- virtual int TransferDataToGPU(cl_command_queue);
-
- /*! \brief Copies the in GMEM stored data to RAM */
- virtual void* TransferDataToCPU(cl_command_queue);
-
- /*! \brief Returns the pointer to the referenced mitk::Image */
- Image::Pointer GetMITKImage()
- {
- return m_Image;
- }
-
- /*! \brief Checks whether gpuImage is a valid clImage object
-
- when an oclImage gets created by an image to image filter, the output image is created
- by clCreateBuffer() because it is not in general possible to write to clImage directly
- */
- cl_mem GetGPUImage(cl_command_queue);
-
- /** Returns the pointer to the GPU buffer */
- cl_mem GetGPUBuffer()
- {
- return this->m_gpuImage;
- }
-
- /** Create the GPU buffer for image
- *
- */
- cl_mem CreateGPUImage(unsigned int, unsigned int, unsigned int, unsigned int);
-
- /** \brief Returns the status of the image buffer
- *
- * @param _type The flag to specify the buffer type ( GPU / CPU )
- */
- bool IsModified(int _type);
-
- using OclBaseData::Modified;
- /** \brief Set the modified flag for one of the buffers
- *
- * @param _type The flag to specify the buffer type ( GPU / CPU )
- */
- void Modified(int _type);
-
- /** @brief Initialize the internal variable of type mitk::Image.
- */
- void InitializeMITKImage();
-
- /** \brief Initialze the OclImage with an mitkImage. */
- void InitializeByMitkImage(mitk::Image::Pointer _image);
-
- /*! \brief returns the specified image dimension size */
- int GetDimension(int) const;
-
- /*! \brief returns the dimensionality of the image */
- int GetDimension() const
- {
- return this->m_dim;
- }
-
- /*! \brief returns the pointer to the array of image sizes */
- unsigned int* GetDimensions(){ return this->m_Dims; }
-
- /*! \brief returns the spacing of the image for specified dimension */
- float GetSpacing(int);
-
- /*! \brief Returns the image offset (needed for WorldToIndex Transform */
- void GetOffset(float*) const;
-
- /** @brief Set the pixel type for the image to be used
- */
- void SetPixelType(const cl_image_format*);
-
- short GetBytesPerPixel() const
- {
- return this->m_BpE;
- }
-
- /** @brief Get the currently used pixel type
-
- @returns OpenCL Image Format struct
- */
- const cl_image_format* GetPixelType() const
- {
- return &(this->m_proposedFormat);
- }
-
- /** @brief Set the image dimensions through an unsigned int array */
- void SetDimensions(unsigned int* Dims);
-
- /** @brief Set the dimensionality of the image */
- void SetDimension(unsigned short dim);
-
-protected:
- /*! \brief Constructor */
- OclImage();
-
- /** @brief Destructor */
- virtual ~OclImage();
-
- /*! GMEM Image buffer */
- cl_mem m_gpuImage;
-
- /*! GPU Context the Image Buffer was created in, needed for access */
- cl_context m_context;
-
- /*! GMEM Buffer Size */
- unsigned int m_bufferSize;
-
-private:
-
- cl_image_format ConvertPixelTypeToOCLFormat();
-
- bool m_gpuModified;
- bool m_cpuModified;
-
- /*! Reference to mitk::Image */
- Image::Pointer m_Image;
-
- unsigned short m_dim;
-
- unsigned int* m_Dims;
-
- unsigned short m_BpE;
-
- cl_int AllocateGPUImage();
-
- /** Bool flag to signalize if the proposed format is supported on currend HW.
- For value 'false', the transfer kernel has to be called to fit the data to
- the supported format */
- bool m_formatSupported;
-
- /** Supported format, defined using oclImageFormats */
- cl_image_format m_supportedFormat;
-
- /** Proposed format for image */
- cl_image_format m_proposedFormat;
-};
-
-/**
- * @brief The ImageTypeIsNotSupportedByGPU class specialized exception class for unsupported
- * image formats. If this exception is thrown, try other graphics device.
- */
-class ImageTypeIsNotSupportedByGPU : public Exception
-{
-public:
- mitkExceptionClassMacro(ImageTypeIsNotSupportedByGPU,Exception)
-};
-
-}
-#endif
diff --git a/Modules/OpenCL/mitkOclImageFilter.cpp b/Modules/OpenCL/mitkOclImageFilter.cpp
deleted file mode 100644
index fabd1b473b..0000000000
--- a/Modules/OpenCL/mitkOclImageFilter.cpp
+++ /dev/null
@@ -1,42 +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 "mitkOclImageFilter.h"
-#include "mitkOclFilter.h"
-#include "mitkOclImage.h"
-
-mitk::OclImageFilter::OclImageFilter()
-{
- // set the filter type to default value = SHORT
- this->m_CurrentType = FILTER_SHORT;
-}
-
-mitk::OclImageFilter::~OclImageFilter()
-{
-}
-
-void mitk::OclImageFilter::SetInput(mitk::OclImage::Pointer image)
-{
- m_Input = image;
-}
-
-void mitk::OclImageFilter::SetInput(mitk::Image::Pointer image)
-{
- m_Input = mitk::OclImage::New();
- m_Input->InitializeByMitkImage(image);
-
- // update current size
- MITK_DEBUG << "Current Type was: " << this->m_CurrentType;
- this->m_CurrentType = m_Input->GetBytesPerPixel() - 1;
- MITK_DEBUG << "Current Type is: " << this->m_CurrentType;
-}
-
diff --git a/Modules/OpenCL/mitkOclImageFilter.h b/Modules/OpenCL/mitkOclImageFilter.h
deleted file mode 100644
index 4cdc41f939..0000000000
--- a/Modules/OpenCL/mitkOclImageFilter.h
+++ /dev/null
@@ -1,61 +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 mitkOclImageFilter_h
-#define mitkOclImageFilter_h
-
-#include "mitkOclFilter.h"
-#include "mitkOclImage.h"
-
-#define FILTER_UCHAR 0
-#define FILTER_SHORT 1
-
-namespace mitk
-{
-class OclFilter;
-class OclImageFilter;
-
- /**
- * \brief The OclImageFilter is the topmost class for all filter which take images as input.
- *
- * The input image can be intialized via an oclImage or an mitk::Image.
- * This makes it possible to create a filter pipeline of GPU-based filters
- * and to bind this part into the CPU (ITK) filter pipeline.
- */
-class MITKOPENCL_EXPORT OclImageFilter: public OclFilter
-{
-public:
- /**
- * @brief SetInput SetInput Set the input image (as mitk::OclImage).
- * @param image The image in mitk::OclImage.
- */
- void SetInput(mitk::OclImage::Pointer image);
-
- /**
- * @brief SetInput Set the input image (as mitk::Image).
- * @param image The image in mitk::Image.
- */
- void SetInput(mitk::Image::Pointer image);
-
-protected:
- OclImageFilter();
-
- virtual ~OclImageFilter();
-
- /** The input image */
- mitk::OclImage::Pointer m_Input;
-
- /*! Current (last used) image pixel type */
- short m_CurrentType;
-};
-}
-#endif
diff --git a/Modules/OpenCL/mitkOclImageFormats.cpp b/Modules/OpenCL/mitkOclImageFormats.cpp
deleted file mode 100644
index 89f3a1a002..0000000000
--- a/Modules/OpenCL/mitkOclImageFormats.cpp
+++ /dev/null
@@ -1,261 +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 "mitkOclImageFormats.h"
-
-mitk::OclImageFormats::OclImageFormats()
- :m_Image2DSupport( nullptr ), m_Image3DSupport( nullptr ),
- m_GpuContext( nullptr )
-{
- //todo: what happens here?
- const unsigned int matrixSize = MAX_FORMATS * MAX_DATA_TYPES;
-
- this->m_Image2DSupport = new unsigned char[matrixSize];
- this->m_Image3DSupport = new unsigned char[matrixSize];
-
- for( unsigned int i = 0; i<matrixSize; i++ )
- {
- this->m_Image2DSupport[i] = 0;
- this->m_Image3DSupport[i] = 0;
- }
-}
-
-mitk::OclImageFormats::~OclImageFormats()
-{
-}
-
-void mitk::OclImageFormats::PrintSelf()
-{
- std::stringstream outputstream;
- outputstream << "Values: Read-Write(1) ReadOnly(2) , WriteOnly(4) \n";
- outputstream << "ROWS: [CL_A, CL_R, CL_RA, CL_RG, CL_RGB, CL_RGBA, CL_ARGB, CL_BGRA, CL_LUM, CL_INT] \n";
-
- const unsigned int matrixSize = MAX_FORMATS * MAX_DATA_TYPES;
-
- for( unsigned int i = 0; i<matrixSize; i++ )
- {
- outputstream << (int) this->m_Image2DSupport[i] << ", \t";
- if( (i+1) % MAX_DATA_TYPES == 0 )
- outputstream << " \n";
- }
- outputstream << "========================== \n";
-
- for( unsigned int i = 0; i<matrixSize; i++ )
- {
- outputstream << (int) this->m_Image3DSupport[i] << ", \t";
- if( (i+1) % MAX_DATA_TYPES == 0 )
- outputstream << " \n";
- }
- MITK_INFO << outputstream.str();
-}
-
-unsigned int mitk::OclImageFormats::GetOffset(cl_image_format format)
-{
- //todo: what happens here?
- unsigned int offset = 0;
-
- switch( format.image_channel_order )
- {
- case CL_A:
- break;
- case CL_R:
- offset += 1 * MAX_DATA_TYPES;
- break;
- case CL_RA:
- offset += 2 * MAX_DATA_TYPES;
- break;
- case CL_RG:
- offset += 3 * MAX_DATA_TYPES;
- break;
- case CL_RGB:
- offset += 4 * MAX_DATA_TYPES;
- break;
- case CL_RGBA:
- offset += 5 * MAX_DATA_TYPES;
- break;
- case CL_ARGB:
- offset += 6 * MAX_DATA_TYPES;
- break;
- case CL_BGRA:
- offset += 7 * MAX_DATA_TYPES;
- break;
- case CL_LUMINANCE:
- offset += 8 * MAX_DATA_TYPES;
- break;
- case CL_INTENSITY:
- offset += 9 * MAX_DATA_TYPES;
- break;
- }
-
- switch ( format.image_channel_data_type )
- {
- case CL_SNORM_INT8:
- break;
- case CL_SNORM_INT16:
- offset += 1;
- break;
- case CL_UNORM_INT8:
- offset += 2;
- break;
- case CL_UNORM_INT16:
- offset += 3;
- break;
- case CL_SIGNED_INT8:
- offset += 4;
- break;
- case CL_SIGNED_INT16:
- offset += 5;
- break;
- case CL_SIGNED_INT32:
- offset += 6;
- break;
- case CL_UNSIGNED_INT8:
- offset += 7;
- break;
- case CL_UNSIGNED_INT16:
- offset += 8;
- break;
- case CL_UNSIGNED_INT32:
- offset += 9;
- break;
- case CL_HALF_FLOAT:
- offset += 10;
- break;
- case CL_FLOAT:
- offset += 11;
- break;
- }
-
- return offset;
-}
-
-bool mitk::OclImageFormats::IsFormatSupported(cl_image_format* format)
-{
- bool retVal = false;
-
- // FIXME needs finer subdivision...
- //todo: Comment above???
- if ( this->m_Image2DSupport[ GetOffset(*format)] > 4 )
- retVal = true;
-
- return retVal;
-}
-
-bool mitk::OclImageFormats::GetNearestSupported(cl_image_format *inputformat, cl_image_format *outputformat)
-{
- bool returnValue = false;
-
- // init output format
- outputformat->image_channel_data_type = inputformat->image_channel_data_type;
- outputformat->image_channel_order = inputformat->image_channel_order;
-
- // the input format is supported, just copy the information into out
- if( this->IsFormatSupported(inputformat) )
- {
- returnValue = true;
- }
- else
- {
- // get the 'nearest' format
- // try RGBA first
- //todo: It seems like ONLY RGBA is considered to be near?!? Either code or docu should be adapted.
- cl_image_format test;
- test.image_channel_order = CL_RGBA;
- test.image_channel_data_type = inputformat->image_channel_data_type;
-
- if(this->IsFormatSupported( &test) )
- {
- outputformat->image_channel_order = CL_RGBA;
- }
- }
- return returnValue;
-}
-
-void mitk::OclImageFormats::SetGPUContext(cl_context context)
-{
- this->m_GpuContext = context;
- //collect available formats can now be called
- this->CollectAvailableFormats();
-}
-
-void mitk::OclImageFormats::SortFormats(cl_image_format *formats, cl_uint count, int val, int dims)
-{
- //todo what happens here?
- unsigned char *target = this->m_Image2DSupport;
- if (dims == 3)
- {
- target = this->m_Image3DSupport;
- }
-
- for( unsigned int i=0; i<count; i++)
- {
- // each supported format => +1
- target[ this->GetOffset( formats[i] ) ]+=val;
- }
-}
-
-void mitk::OclImageFormats::CollectAvailableFormats()
-{
- if( this->m_GpuContext == nullptr)
- {
- mitkThrow() << "No GPU context was set! Use SetGPUContext() before calling this method!";
- }
- //todo what happens here?
- const unsigned int entries = 100;
- cl_image_format* formats = new cl_image_format[entries];
-
- cl_uint written = 0;
- cl_int clErr = 0;
-
- // GET formats for R/W, 2D
- clErr = clGetSupportedImageFormats( m_GpuContext, CL_MEM_READ_WRITE, CL_MEM_OBJECT_IMAGE2D, entries, formats, &written);
- CHECK_OCL_ERR( clErr );
-
- this->SortFormats( formats, written, 1 );
-
- // GET formats for R/-, 2D
- written = 0;
- clErr = clGetSupportedImageFormats( m_GpuContext, CL_MEM_READ_ONLY, CL_MEM_OBJECT_IMAGE2D, entries, formats, &written);
- CHECK_OCL_ERR( clErr );
-
- this->SortFormats( formats, written, 2 );
-
- // GET formats for -/W, 2D
- written = 0;
- clErr = clGetSupportedImageFormats( m_GpuContext, CL_MEM_WRITE_ONLY, CL_MEM_OBJECT_IMAGE2D, entries, formats, &written);
- CHECK_OCL_ERR( clErr );
-
- this->SortFormats( formats, written, 4 );
- //-----------------------
-
-
- // GET formats for R/W, 3D
- written = 0;
- clErr = clGetSupportedImageFormats( m_GpuContext, CL_MEM_READ_WRITE, CL_MEM_OBJECT_IMAGE3D, entries, formats, &written);
- CHECK_OCL_ERR( clErr );
-
- this->SortFormats( formats, written, 1, 3 );
-
- // GET formats for R/-, 3D
- written = 0;
- clErr = clGetSupportedImageFormats( m_GpuContext, CL_MEM_READ_ONLY, CL_MEM_OBJECT_IMAGE3D, entries, formats, &written);
- CHECK_OCL_ERR( clErr );
-
- this->SortFormats( formats, written, 2, 3 );
-
- // GET formats for -/W, 3D
- written = 0;
- clErr = clGetSupportedImageFormats( m_GpuContext, CL_MEM_WRITE_ONLY, CL_MEM_OBJECT_IMAGE3D, entries, formats, &written);
- CHECK_OCL_ERR( clErr );
-
- this->SortFormats( formats, written, 4, 3 );
-}
diff --git a/Modules/OpenCL/mitkOclImageFormats.h b/Modules/OpenCL/mitkOclImageFormats.h
deleted file mode 100644
index 08b5a4cd8d..0000000000
--- a/Modules/OpenCL/mitkOclImageFormats.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkOclImageFormats_h
-#define mitkOclImageFormats_h
-
-//mitk
-#include <mitkCommon.h>
-#include <mitkLog.h>
-
-//itk
-#include <itkLightObject.h>
-#include <itkObjectFactory.h>
-
-//ocl
-#include "mitkOclUtils.h"
-#include <MitkOpenCLExports.h>
-
-#define MAX_FORMATS 10
-#define MAX_DATA_TYPES 12
-
-namespace mitk
-{
-
-/**
- @class oclImageFormats
- @brief A class handling the (un)supported OpenCL Image formats.
-
- This class checks whether a format is supported or not and acts accordingly.
- */
-class MITKOPENCL_EXPORT OclImageFormats : public itk::LightObject
-{
-public:
- mitkClassMacroItkParent(OclImageFormats, itk::LightObject);
- itkFactorylessNewMacro(Self);
- itkCloneMacro(Self);
-
- /** @brief Checks if format supported.
- @param format The image format to be checked for support.
- @return True if the parameter is supported.
- */
- bool IsFormatSupported(cl_image_format* format);
-
- /** @brief Finds one supported image format similar to the given format.
-
- In case the input format is supported, the output format will contain the same value.
-
- @param inputformat The (unsupported) image format
- @param outputformat A supported image format
-
- @return True if a supported format was changed.
- */
- bool GetNearestSupported(cl_image_format* inputformat, cl_image_format* outputformat);
-
- /**
- * @brief SetGPUContext Set the GPU context. Must be called before using this class!
- * @param context GPU context in cl format.
- */
- void SetGPUContext( cl_context context );
-
-
-protected:
- /** @brief Get and store all available infos
- * @throw Throws an mitk::Exception if the GPU context was not defined.
- */
- void CollectAvailableFormats();
-
- /**
- * @brief OclImageFormats Constructor
- */
- OclImageFormats();
-
- /** @brief Destructor (default) */
- virtual ~OclImageFormats();
-
-private:
-
- /** @brief Store the given format into the table
- * Todo: what table? Where? Why is it called sort?
- @param formats A pointer to an array of image formats
- Todo: What formats?
- @param count Size of the formats array (i.e. how many formats are to be sorted).
- @param val an intern value to distinguish between read/write/readwrite type
- Todo: what is val?
- @param dim Specifies the target image dimension (default IMAGE_2D).
- */
- void SortFormats( cl_image_format* formats, cl_uint count, int val=1 , int dims = 2);
-
- /** @brief Get the byte offset to the image support fields.
- Todo: What means support field? What is this offset used for? In what unit is it returned?*/
- unsigned int GetOffset( cl_image_format format );
-
- using itk::LightObject::PrintSelf;
- /** @brief Print all supported formats (in a table) for both 2D and 3D IMAGE */
- void PrintSelf();
-
- /** An array to hold the information about IMAGE_2D supported formats. */
- unsigned char* m_Image2DSupport;
-
- /** An array to hold the information about IMAGE_3D supported formats. */
- unsigned char* m_Image3DSupport;
-
- /** the OpenCL context */
- cl_context m_GpuContext;
-};
-
-}
-
-#endif
diff --git a/Modules/OpenCL/mitkOclImageToImageFilter.cpp b/Modules/OpenCL/mitkOclImageToImageFilter.cpp
deleted file mode 100644
index 014a62b45f..0000000000
--- a/Modules/OpenCL/mitkOclImageToImageFilter.cpp
+++ /dev/null
@@ -1,189 +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 "mitkOclImageToImageFilter.h"
-#include "mitkOclImage.h"
-
-#include "mitkException.h"
-
-mitk::OclImageToImageFilter::OclImageToImageFilter()
-{
- m_Output = mitk::OclImage::New();
-}
-
-
-mitk::OclImageToImageFilter::~OclImageToImageFilter()
-{
-}
-
-mitk::OclImage::Pointer mitk::OclImageToImageFilter::GetGPUOutput()
-{
- // initialize some variables
- m_Output->SetPixelType(m_Input->GetPixelType());
-
- // create new image, for passing the essential information to the output
- m_Output->InitializeMITKImage();
-
- const unsigned int dimension = m_Input->GetDimension();
- unsigned int* dimensions = m_Input->GetDimensions();
-
- m_Output->SetDimensions( dimensions );
- m_Output->SetDimension( (unsigned short)dimension );
-
- m_Output->GetMITKImage()->Initialize( this->GetOutputType(), dimension, dimensions);
- const mitk::SlicedGeometry3D::Pointer p_slg = m_Input->GetMITKImage()->GetSlicedGeometry(0);
- m_Output->GetMITKImage()->SetSpacing( p_slg->GetSpacing() );
- m_Output->GetMITKImage()->SetGeometry( m_Input->GetMITKImage()->GetGeometry() );
-
- return this->m_Output;
-
-}
-
-mitk::Image::Pointer mitk::OclImageToImageFilter::GetOutput()
-{
- if (m_Output->IsModified(GPU_DATA))
- {
- void* pData = m_Output->TransferDataToCPU(m_CommandQue);
-
- const unsigned int dimension = m_Input->GetDimension();
- unsigned int* dimensions = m_Input->GetDimensions();
-
- const mitk::SlicedGeometry3D::Pointer p_slg = m_Input->GetMITKImage()->GetSlicedGeometry();
-
- MITK_DEBUG << "Creating new MITK Image.";
-
- m_Output->GetMITKImage()->Initialize( this->GetOutputType(), dimension, dimensions);
- m_Output->GetMITKImage()->SetSpacing( p_slg->GetSpacing());
- m_Output->GetMITKImage()->SetGeometry( m_Input->GetMITKImage()->GetGeometry() );
- m_Output->GetMITKImage()->SetImportVolume( pData, 0, 0, mitk::Image::ReferenceMemory);
- }
-
- MITK_DEBUG << "Image Initialized.";
-
- return m_Output->GetMITKImage();
-}
-
-mitk::PixelType mitk::OclImageToImageFilter::GetOutputType()
-{
- // get the current image format from the input image
- const cl_image_format* currentImFormat = this->m_Input->GetPixelType();
-
- // return the value according to the current channel type
- switch( currentImFormat->image_channel_data_type )
- {
- case CL_UNORM_INT8:
- return mitk::MakeScalarPixelType<unsigned char>();
- case CL_UNSIGNED_INT8:
- return mitk::MakeScalarPixelType<unsigned char>();
- case CL_UNORM_INT16:
- return mitk::MakeScalarPixelType<short>();
- default:
- return mitk::MakeScalarPixelType<short>();
- }
-}
-
-int mitk::OclImageToImageFilter::GetBytesPerElem()
-{
- return (this->m_CurrentType + 1);
-}
-
-bool mitk::OclImageToImageFilter::InitExec(cl_kernel ckKernel)
-{
- cl_int clErr = 0;
-
- if( m_Input.IsNull() )
- mitkThrow() << "Input image is null.";
-
- // get image size once
- const unsigned int uiImageWidth = m_Input->GetDimension(0);
- const unsigned int uiImageHeight = m_Input->GetDimension(1);
- const unsigned int uiImageDepth = m_Input->GetDimension(2);
-
- // compute work sizes
- this->SetWorkingSize( 8, uiImageWidth, 8, uiImageHeight , 8, uiImageDepth );
-
- cl_mem clBuffIn = m_Input->GetGPUImage(this->m_CommandQue);
- cl_mem clBuffOut = m_Output->GetGPUBuffer();
-
- if (!clBuffIn)
- {
- if ( m_Input->TransferDataToGPU(m_CommandQue) != CL_SUCCESS )
- {
- mitkThrow()<< "Could not create / initialize gpu image.";
- }
-
- clBuffIn = m_Input->GetGPUImage(m_CommandQue);
- }
-
- // output image not initialized
- if (!clBuffOut)
- {
- //TODO bpp, or SetImageWidth/Height/...
- MITK_DEBUG << "Create GPU Image call " << uiImageWidth<< "x"<<uiImageHeight<< "x"<<uiImageDepth;
- clBuffOut = m_Output->CreateGPUImage(uiImageWidth, uiImageHeight, uiImageDepth, this->m_CurrentType + 1);
- }
-
- clErr = 0;
- clErr = clSetKernelArg(ckKernel, 0, sizeof(cl_mem), &clBuffIn);
- clErr |= clSetKernelArg(ckKernel, 1, sizeof(cl_mem), &clBuffOut);
- CHECK_OCL_ERR( clErr );
-
- if( clErr != CL_SUCCESS )
- mitkThrow() << "OpenCL Part initialization failed with " << GetOclErrorAsString(clErr);
-
- return( clErr == CL_SUCCESS );
-}
-
- bool mitk::OclImageToImageFilter::InitExec(cl_kernel ckKernel, unsigned int* dimensions)
- {
- cl_int clErr = 0;
-
- if( m_Input.IsNull() )
- mitkThrow() << "Input image is null.";
-
- // get image size once
- const unsigned int uiImageWidth = dimensions[0];
- const unsigned int uiImageHeight = dimensions[1];
- const unsigned int uiImageDepth = dimensions[2]+1;
-
- // compute work sizes
- this->SetWorkingSize( 8, uiImageWidth, 8, uiImageHeight , 8, uiImageDepth );
-
- cl_mem clBuffIn = m_Input->GetGPUImage(this->m_CommandQue);
- cl_mem clBuffOut = m_Output->GetGPUBuffer();
-
- if (!clBuffIn)
- {
- if ( m_Input->TransferDataToGPU(m_CommandQue) != CL_SUCCESS )
- {
- mitkThrow()<< "Could not create / initialize gpu image.";
- }
-
- clBuffIn = m_Input->GetGPUImage(m_CommandQue);
- }
-
- // output image not initialized
- //TODO bpp, or SetImageWidth/Height/...
- MITK_INFO << "Create GPU Image call " << uiImageWidth<< "x"<<uiImageHeight<< "x"<<uiImageDepth;
- clBuffOut = m_Output->CreateGPUImage(uiImageWidth, uiImageHeight, uiImageDepth, this->m_CurrentType + 1);
-
-
- clErr = 0;
- clErr = clSetKernelArg(ckKernel, 0, sizeof(cl_mem), &clBuffIn);
- clErr |= clSetKernelArg(ckKernel, 1, sizeof(cl_mem), &clBuffOut);
- CHECK_OCL_ERR( clErr );
-
- if( clErr != CL_SUCCESS )
- mitkThrow() << "OpenCL Part initialization failed with " << GetOclErrorAsString(clErr);
-
- return( clErr == CL_SUCCESS );
-}
diff --git a/Modules/OpenCL/mitkOclImageToImageFilter.h b/Modules/OpenCL/mitkOclImageToImageFilter.h
deleted file mode 100644
index 9e0af08e72..0000000000
--- a/Modules/OpenCL/mitkOclImageToImageFilter.h
+++ /dev/null
@@ -1,78 +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 mitkOclImageToImageFilter_h
-#define mitkOclImageToImageFilter_h
-
-#include "mitkOclImageFilter.h"
-
-namespace mitk
-{
-class OclImageFilter;
-class OclImageToImageFilter;
-
-/** @class OclImageToImageFilter
- * @brief The OclImageToImageFilter is the base class for all OpenCL image filter generating images.
- */
-class MITKOPENCL_EXPORT OclImageToImageFilter: public OclImageFilter
-{
-public:
- /*!
- * \brief Returns an mitk::Image::Pointer containing the filtered data.
- */
- mitk::Image::Pointer GetOutput();
-
- /*!
- * \brief Returns a pointer to the graphics memory.
- *
- * Use this method when executing two and more filters on the GPU for fast access.
- * This method does not copy the data to RAM. It returns only a pointer.
- */
- mitk::OclImage::Pointer GetGPUOutput();
-
-protected:
- /**
- * @brief OclImageToImageFilter Default constructor.
- */
- OclImageToImageFilter();
-
- /** @brief Destructor */
- virtual ~OclImageToImageFilter();
-
- /** Output Image */
- mitk::OclImage::Pointer m_Output;
-
- /** @brief (Virtual) method Update() to be implemented in derived classes. */
- virtual void Update() = 0;
-
- /** @brief (Virtual) method returning the format in which the output image will be returned */
- virtual mitk::PixelType GetOutputType();
-
- /**
- * @brief InitExec Initialize the execution
- * @param ckKernel The GPU kernel.
- * @throws mitk::Exception if something goes wrong.
- * @return True for success.
- */
- bool InitExec(cl_kernel ckKernel);
- bool InitExec(cl_kernel ckKernel, unsigned int* dimensions);
-
- /** @brief Get the memory size needed for each element */
- virtual int GetBytesPerElem();
-
-private:
- /** Block dimensions */
- unsigned int m_BlockDims[3];
-
-};
-}
-#endif
diff --git a/Modules/OpenCL/mitkOclResourceService.h b/Modules/OpenCL/mitkOclResourceService.h
deleted file mode 100644
index cc4762bbf1..0000000000
--- a/Modules/OpenCL/mitkOclResourceService.h
+++ /dev/null
@@ -1,79 +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 mitkOclResourceService_h
-#define mitkOclResourceService_h
-
-#include <mitkServiceInterface.h>
-
-#include <mitkOpenCL.h>
-
-/**
- * @brief Declaration of the OpenCL Resources micro-service
- *
- * The OclResourceService defines an service interface for providing access to the
- * essential OpenCL-related variables. In addition the service can also store compiled
- * OpenCL Programs in order to avoid multiple compiling of a single program source
- */
-class OclResourceService
-{
-public:
- /** @brief Returns a valid OpenCL Context (if applicable) or nullptr if none present */
- virtual cl_context GetContext() const = 0;
-
- /** @brief Returns a valid cl_command_queue related to the (one) OpenCL context */
- virtual cl_command_queue GetCommandQueue() const = 0;
-
- /** @brief Returns the identifier of an OpenCL device related to the current context */
- virtual cl_device_id GetCurrentDevice() const = 0;
-
- /** @brief Checks if an OpenCL image format passed in is supported on current device */
- virtual bool GetIsFormatSupported( cl_image_format* format ) = 0;
-
- /** @brief Puts the OpenCL Context info in std::cout */
- virtual void PrintContextInfo() const = 0;
-
- /** @brief Insert program into the internal program storage
- *
- * @param program A cl_program object.
- * @param string Text identifier of the inserted program. Used for getting the program.
- * @param flag
- */
- virtual void InsertProgram(cl_program program, std::string string, bool flag) = 0;
-
- /** @brief Get the cl_program by name
- * @param name Text identifier of the program.
- * @throws an mitk::Exception in case the program cannot be found
- */
- virtual cl_program GetProgram(const std::string& name) = 0;
-
- /** @brief Remove all invalid (=do not compile) programs from the internal storage */
- virtual void InvalidateStorage() = 0;
-
- /** @brief Remove given program from storage
- * @param name Text identifier of the program.
- */
- virtual void RemoveProgram(const std::string& name) = 0;
-
- /** @brief Get the maximum size of an image
- *
- * @param dimension (unsigned int) identifier of the image diemsion in {0,1,2}
- * @param image object type, either CL_MEM_OBJECT_IMAGE2D, CL_MEM_OBJECT_IMAGE3D
- */
- virtual unsigned int GetMaximumImageSize(unsigned int dimension, cl_mem_object_type image) = 0;
-
- virtual ~OclResourceService() = 0;
-
-};
-
-MITK_DECLARE_SERVICE_INTERFACE(OclResourceService, "OpenCLResourceService/1.0")
-#endif
diff --git a/Modules/OpenCL/mitkOclResourceServiceImpl_Private.cpp b/Modules/OpenCL/mitkOclResourceServiceImpl_Private.cpp
deleted file mode 100644
index 7de7e51e4d..0000000000
--- a/Modules/OpenCL/mitkOclResourceServiceImpl_Private.cpp
+++ /dev/null
@@ -1,256 +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 "mitkOclResourceServiceImpl_p.h"
-
-OclResourceService::~OclResourceService()
-{
-}
-
-OclResourceServiceImpl::OclResourceServiceImpl()
- : m_ContextCollection(nullptr), m_ProgramStorage()
-{
- m_ProgramStorageMutex = itk::FastMutexLock::New();
-}
-
-OclResourceServiceImpl::~OclResourceServiceImpl()
-{
- // if map non-empty, release all remaining
- if( m_ProgramStorage.size() )
- {
- ProgramMapType::iterator it = m_ProgramStorage.begin();
- while(it != m_ProgramStorage.end() )
- {
- clReleaseProgram( it->second.program );
- m_ProgramStorage.erase( it++ );
- }
- }
-
- if( m_ContextCollection )
- delete m_ContextCollection;
-}
-
-cl_context OclResourceServiceImpl::GetContext() const
-{
- if( m_ContextCollection == nullptr )
- {
- m_ContextCollection = new OclContextCollection();
- }
- else if( !m_ContextCollection->CanProvideContext() )
- {
- return nullptr;
- }
-
- return m_ContextCollection->m_Context;
-}
-
-cl_command_queue OclResourceServiceImpl::GetCommandQueue() const
-{
- // check if queue valid
- cl_context clQueueContext;
-
- // check if there is a context available
- // if not create one
- if( ! m_ContextCollection )
- {
- m_ContextCollection = new OclContextCollection();
- }
-
- cl_int clErr = clGetCommandQueueInfo( m_ContextCollection->m_CommandQueue, CL_QUEUE_CONTEXT, sizeof(clQueueContext), &clQueueContext, nullptr );
- if( clErr != CL_SUCCESS || clQueueContext != m_ContextCollection->m_Context )
- {
- MITK_WARN << "Have no valid command queue. Query returned : " << GetOclErrorAsString( clErr );
- return nullptr;
- }
-
- return m_ContextCollection->m_CommandQueue;
-}
-
-cl_device_id OclResourceServiceImpl::GetCurrentDevice() const
-{
- return m_ContextCollection->m_Devices[0];
-}
-
-bool OclResourceServiceImpl::GetIsFormatSupported(cl_image_format *fmt)
-{
- cl_image_format temp;
- temp.image_channel_data_type = fmt->image_channel_data_type;
- temp.image_channel_order = fmt->image_channel_order;
-
- return (this->m_ContextCollection->m_ImageFormats->GetNearestSupported(&temp, fmt));
-}
-
-void OclResourceServiceImpl::PrintContextInfo() const
-{
- // context and devices available
- if( m_ContextCollection->CanProvideContext() )
- {
- oclPrintDeviceInfo( m_ContextCollection->m_Devices[0] );
- }
-}
-
-void OclResourceServiceImpl::InsertProgram(cl_program _program_in, std::string name, bool forceOverride)
-{
- typedef std::pair < std::string, ProgramData > MapElemPair;
- std::pair< ProgramMapType::iterator, bool> retValue;
-
- ProgramData data;
- data.counter = 1;
- data.program = _program_in;
- data.mutex = itk::FastMutexLock::New();
-
- // program is not stored, insert first instance (count = 1)
- m_ProgramStorageMutex->Lock();
- retValue = m_ProgramStorage.insert( MapElemPair(name, data) );
- m_ProgramStorageMutex->Unlock();
-
- // insertion failed, i.e. a program with same name exists
- if( !retValue.second )
- {
- std::string overrideMsg("");
- if( forceOverride )
- {
- // overwrite old instance
- m_ProgramStorage[name].program = _program_in;
- overrideMsg +=" The old program was overwritten!";
- }
-
- MITK_WARN("OpenCL.ResourceService") << "The program " << name << " already exists." << overrideMsg;
- }
-}
-
-cl_program OclResourceServiceImpl::GetProgram(const std::string &name)
-{
- ProgramMapType::iterator it = m_ProgramStorage.find(name);
-
- if( it != m_ProgramStorage.end() )
- {
- it->second.mutex->Lock();
- // first check if the program was deleted
- // while waiting on the mutex
- if ( it->second.counter == 0 )
- mitkThrow() << "Requested OpenCL Program (" << name <<") not found."
- << "(deleted while waiting on the mutex)";
- // increase the reference counter
- // by one if the program is requestet
- it->second.counter += 1;
- it->second.mutex->Unlock();
-
- // return the cl_program
- return it->second.program;
- }
-
- mitkThrow() << "Requested OpenCL Program (" << name <<") not found.";
-}
-
-void OclResourceServiceImpl::InvalidateStorage()
-{
- // do nothing if no context present, there is also no storage
- if( !m_ContextCollection->CanProvideContext() )
- return;
-
- // query the map
- ProgramMapType::iterator it = m_ProgramStorage.begin();
-
- while(it != m_ProgramStorage.end() )
- {
- // query the program build status
- cl_build_status status;
- unsigned int query = clGetProgramBuildInfo( it->second.program, m_ContextCollection->m_Devices[0], CL_PROGRAM_BUILD_STATUS, sizeof(cl_int), &status, nullptr );
- CHECK_OCL_ERR( query )
-
- MITK_DEBUG << "Quering status for " << it->first << std::endl;
-
- // remove program if no succesfull build
- // we need to pay attention to the increment of the iterator when erasing current element
- if( status != CL_BUILD_SUCCESS )
- {
- MITK_DEBUG << " +-- Build failed " << std::endl;
- m_ProgramStorage.erase( it++ );
- }
- else
- {
- ++it;
- }
- }
-}
-
-void OclResourceServiceImpl::RemoveProgram(const std::string& name)
-{
- ProgramMapType::iterator it = m_ProgramStorage.find(name);
- cl_int status = 0;
- cl_program program = nullptr;
-
- if( it != m_ProgramStorage.end() )
- {
- it->second.mutex->Lock();
- // decrease reference by one
- it->second.counter -= 1;
- it->second.mutex->Unlock();
-
- // remove from the storage
- if( it->second.counter == 0 )
- {
- program = it->second.program;
-
- m_ProgramStorageMutex->Lock();
- m_ProgramStorage.erase(it);
- m_ProgramStorageMutex->Unlock();
- }
-
- // delete the program
- if( program )
- {
- status = clReleaseProgram(program);
- CHECK_OCL_ERR( status );
- }
- }
- else
- {
- MITK_WARN("OpenCL.ResourceService") << "Program name [" <<name <<"] passed for deletion not found.";
- }
-}
-
-unsigned int OclResourceServiceImpl::GetMaximumImageSize(unsigned int dimension, cl_mem_object_type _imagetype)
-{
- if( ! m_ContextCollection->CanProvideContext() )
- return 0;
-
- size_t retValue = 0;
-
- switch(dimension)
- {
- case 0:
- if ( _imagetype == CL_MEM_OBJECT_IMAGE2D)
- clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof( size_t ), &retValue, nullptr );
- else
- clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof( size_t ), &retValue, nullptr );
-
- break;
- case 1:
- if ( _imagetype == CL_MEM_OBJECT_IMAGE2D)
- clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof( size_t ), &retValue, nullptr );
- else
- clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof( size_t ), &retValue, nullptr );
- break;
- case 2:
- if ( _imagetype == CL_MEM_OBJECT_IMAGE3D)
- clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof( size_t ), &retValue, nullptr);
- break;
- default:
- MITK_WARN << "Could not recieve info. Desired dimension or object type does not exist. ";
- break;
- }
-
- return retValue;
-}
-
diff --git a/Modules/OpenCL/mitkOclResourceServiceImpl_p.h b/Modules/OpenCL/mitkOclResourceServiceImpl_p.h
deleted file mode 100644
index f95707f0c5..0000000000
--- a/Modules/OpenCL/mitkOclResourceServiceImpl_p.h
+++ /dev/null
@@ -1,182 +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 mitkOclResourceServiceImpl_p_h
-#define mitkOclResourceServiceImpl_p_h
-
-#include <map>
-
-//Micro Services
-#include <usModuleActivator.h>
-#include <usModuleContext.h>
-#include <usGetModuleContext.h>
-#include <usServiceProperties.h>
-
-//ocl
-#include "mitkOclResourceService.h"
-#include "mitkOclUtils.h"
-#include "mitkOclImageFormats.h"
-
-#include <itkFastMutexLock.h>
-
-US_USE_NAMESPACE
-
-//todo add docu!
-
-/** @struct OclContextCollection
- * @brief An capsulation of all OpenCL context related variables needed for the OclResourceService implementation
- *
- * The struct gets created on first call to GetContext in the OclResourceService and attepts to initialize all
- * relevant parts, i.e. the context itself, the device and the command queue
- */
-struct OclContextCollection{
-public:
- OclContextCollection()
- : m_Context(nullptr), m_Devices(nullptr), m_CreateContextFailed(false)
- {
- cl_int clErr = 0;
- size_t szParmDataBytes;
- cl_platform_id cpPlatform;
- cl_device_id m_cdDevice;
-
- try{
- clErr = oclGetPlatformID( &cpPlatform);
- CHECK_OCL_ERR( clErr );
-
- clErr = clGetDeviceIDs( cpPlatform, CL_DEVICE_TYPE_GPU, 1, &m_cdDevice, nullptr);
- CHECK_OCL_ERR( clErr );
-
- this->m_Context = clCreateContext( 0, 1, &m_cdDevice, nullptr, nullptr, &clErr);
- m_CreateContextFailed = (clErr != CL_SUCCESS);
-
- // get the info size
- clErr = clGetContextInfo(m_Context, CL_CONTEXT_DEVICES, 0,nullptr, &szParmDataBytes );
- this->m_Devices = (cl_device_id*) malloc(szParmDataBytes);
-
- // get device info
- clErr = clGetContextInfo(m_Context, CL_CONTEXT_DEVICES, szParmDataBytes, m_Devices, nullptr);
- CHECK_OCL_ERR( clErr );
-
- // create command queue
- m_CommandQueue = clCreateCommandQueue(m_Context, m_Devices[0], 0, &clErr);
- CHECK_OCL_ERR( clErr );
-
- this->PrintContextInfo( );
-
- // collect available image formats for current context
- this->m_ImageFormats = mitk::OclImageFormats::New();
- this->m_ImageFormats->SetGPUContext(m_Context);
- }
- catch( std::exception& e)
- {
- MITK_ERROR("OpenCL.ResourceService") << "Exception while creating context: \n" << e.what();
- }
- }
-
- ~OclContextCollection()
- {
- // if devices were allocated, delete
- if(m_Devices)
- {
- // TODO: Available first in OpenCL 1.2 : query the device for CL_PLATFORM_VERSION
- // through clGetPlatformInfo
- // clReleaseDevice(m_Devices[0]);
-
- delete [] m_Devices;
- }
-
- // if context was created release it
- if( m_Context )
- clReleaseContext( this->m_Context );
- }
-
- bool CanProvideContext() const
- {
- return ( m_Context != nullptr && !m_CreateContextFailed );
- }
-
- void PrintContextInfo() const
- {
- if( m_Devices )
- {
- oclPrintDeviceInfo( m_Devices[0] );
- }
- }
-
- /** The context */
- cl_context m_Context;
-
- /** Available OpenCL devices */
- cl_device_id* m_Devices;
-
- /** Class for handling (un)supported GPU image formats **/
- mitk::OclImageFormats::Pointer m_ImageFormats;
-
- /** The command queue*/
- cl_command_queue m_CommandQueue;
-
- bool m_CreateContextFailed;
-};
-
-class OclResourceServiceImpl
- : public OclResourceService
-{
-
-private:
- // define programmdata private class
- struct ProgramData
- {
- int counter;
- cl_program program;
- itk::FastMutexLock::Pointer mutex;
- ProgramData() :counter(1), program(nullptr)
- {}
- };
-
- typedef std::map< std::string, ProgramData > ProgramMapType;
- //typedef std::map< std::string, std::pair< int, cl_program> > ProgramMapType;
-
- mutable OclContextCollection* m_ContextCollection;
-
- /** Map containing all available (allready compiled) OpenCL Programs */
- ProgramMapType m_ProgramStorage;
- /** mutex for manipulating the program storage */
- itk::FastMutexLock::Pointer m_ProgramStorageMutex;
-
-public:
-
- OclResourceServiceImpl();
-
- ~OclResourceServiceImpl();
-
- cl_context GetContext() const;
-
- cl_command_queue GetCommandQueue() const;
-
- cl_device_id GetCurrentDevice() const;
-
- bool GetIsFormatSupported(cl_image_format *);
-
- void PrintContextInfo() const;
-
- void InsertProgram(cl_program _program_in, std::string name, bool forceOverride=true);
-
- cl_program GetProgram(const std::string&name);
-
- void InvalidateStorage();
-
- void RemoveProgram(const std::string&name);
-
- unsigned int GetMaximumImageSize(unsigned int dimension, cl_mem_object_type _imagetype);
-};
-
-#endif
diff --git a/Modules/OpenCL/mitkOclUtils.cpp b/Modules/OpenCL/mitkOclUtils.cpp
deleted file mode 100644
index c12b659173..0000000000
--- a/Modules/OpenCL/mitkOclUtils.cpp
+++ /dev/null
@@ -1,579 +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 "mitkOclUtils.h"
-#include "mitkLog.h"
-#include <cstdio>
-#include <cstring>
-
-
-unsigned int iDivUp(unsigned int dividend, unsigned int divisor){
- return (dividend % divisor == 0) ? (dividend / divisor) : (dividend / divisor + 1);
-}
-
-cl_int oclGetPlatformID(cl_platform_id* selectedPlatform)
-{
- cl_uint num_platforms = 0;
- cl_platform_id* clPlatformIDs;
- cl_int ciErrNum = 0;
-
- ciErrNum = clGetPlatformIDs( 0, nullptr, &num_platforms);
- if ( ciErrNum != CL_SUCCESS)
- {
- MITK_ERROR<<" Error " << ciErrNum << " in clGetPlatformIDs() \n";
- throw std::bad_exception();
- }
- else
- {
- clPlatformIDs = new cl_platform_id[num_platforms];
-
- ciErrNum = clGetPlatformIDs( num_platforms, clPlatformIDs, nullptr);
- if(ciErrNum == CL_SUCCESS)
- {
- *selectedPlatform = clPlatformIDs[0];
- }
- }
-
- return CL_SUCCESS;
-
-}
-
-void oclPrintMemObjectInfo(cl_mem memobj)
-{
- cl_int clErr = 0;
-
- MITK_INFO << "Examining cl_mem object: " << memobj
- << "\n------------------\n";
-
- // CL_MEM_TYPE
- cl_mem_object_type objtype;
- clErr = clGetMemObjectInfo( memobj, CL_MEM_TYPE, sizeof(cl_mem_object_type),&objtype, nullptr);
- CHECK_OCL_ERR( clErr );
-
- switch(objtype)
- {
- case CL_MEM_OBJECT_BUFFER:
- MITK_INFO << "CL_MEM_TYPE \t" << "BUFFER_OBJ" << "\n";
- break;
- case CL_MEM_OBJECT_IMAGE2D:
- MITK_INFO << "CL_MEM_TYPE \t" << "2D IMAGE" << "\n";
- break;
- case CL_MEM_OBJECT_IMAGE3D:
- MITK_INFO << "CL_MEM_TYPE \t" << "3D IMAGE" << "\n";
- break;
- default:
- MITK_INFO << "CL_MEM_TYPE \t" << "[could not resolve]" << "\n";
- break;
- }
-
- // CL_MEM_FLAGS
- cl_mem_flags flags;
- clErr = clGetMemObjectInfo( memobj, CL_MEM_FLAGS, sizeof(cl_mem_flags),&flags, nullptr);
- CHECK_OCL_ERR( clErr );
-
- switch(flags)
- {
- case CL_MEM_READ_ONLY:
- MITK_INFO << "CL_MEM_FLAGS \t" << "CL_MEM_READ_ONLY" << "\n";
- break;
- case CL_MEM_WRITE_ONLY:
- MITK_INFO << "CL_MEM_FLAGS \t" << "CL_MEM_WRITE_ONLY" << "\n";
- break;
- case CL_MEM_READ_WRITE:
- MITK_INFO << "CL_MEM_FLAGS \t" << "CL_MEM_READ_WRITE" << "\n";
- break;
- default:
- MITK_INFO << "CL_MEM_FLAGS \t" << "not resolved, " << flags << "\n";
- break;
- }
-
- // get CL_MEM_SIZE
- size_t memsize;
- clErr = clGetMemObjectInfo( memobj, CL_MEM_SIZE, sizeof(memsize),&memsize, nullptr);
- CHECK_OCL_ERR( clErr );
-
- MITK_INFO << "CL_MEM_SIZE \t" << memsize << "\n";
-
- // get CL_MEM_HOST_PTR
- float *hostptr;
- clErr = clGetMemObjectInfo( memobj, CL_MEM_HOST_PTR, sizeof(void*), (void*) &hostptr, nullptr);
- CHECK_OCL_ERR( clErr );
-
- MITK_INFO << "CL_MEM_HOST_PTR \t" << hostptr << "\n";
-
- // get CL_CONTEXT
- cl_context gpuctxt;
- clErr = clGetMemObjectInfo( memobj, CL_MEM_CONTEXT, sizeof(cl_context), &gpuctxt, nullptr);
- CHECK_OCL_ERR( clErr );
-
- MITK_INFO << "CL_CONTEXT \t\t" << gpuctxt << "\n";
-
- // get CL_MEM_REFERENCE_COUNT
- cl_uint refs;
- clErr = clGetMemObjectInfo( memobj, CL_MEM_REFERENCE_COUNT, sizeof(cl_uint), &refs, nullptr);
- CHECK_OCL_ERR(clErr);
-
- MITK_INFO << "CL_REF_COUNT \t" << refs << "\n";
-
- MITK_INFO << "================== \n" << std::endl;
-}
-
-void oclPrintDeviceInfo(cl_device_id device)
-{
- char device_string[1024];
-
- clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_string), &device_string, nullptr);
- MITK_INFO("ocl.log")<< " Device : " << device_string;
-
- // CL_DEVICE_INFO
- cl_device_type type;
- clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(type), &type, nullptr);
- if( type & CL_DEVICE_TYPE_CPU )
- MITK_INFO("ocl.log")<<" CL_DEVICE_TYPE: CL_DEVICE_TYPE_CPU";
- if( type & CL_DEVICE_TYPE_GPU )
- MITK_INFO("ocl.log")<<" CL_DEVICE_TYPE: CL_DEVICE_TYPE_GPU";
- if( type & CL_DEVICE_TYPE_ACCELERATOR )
- MITK_INFO("ocl.log")<<" CL_DEVICE_TYPE: CL_DEVICE_TYPE_ACCELERATOR";
- if( type & CL_DEVICE_TYPE_DEFAULT )
- MITK_INFO("ocl.log")<<" CL_DEVICE_TYPE: CL_DEVICE_TYPE_DEFAULT";
-
- // CL_DEVICE_MAX_COMPUTE_UNITS
- cl_uint compute_units;
- clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(compute_units), &compute_units, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_MAX_COMPUTE_UNITS:" << compute_units;
-
- // CL_DEVICE_MAX_WORK_GROUP_SIZE
- size_t workitem_size[3];
- clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(workitem_size), &workitem_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_MAX_WORK_ITEM_SIZES:\t"<< workitem_size[0]<< workitem_size[1]<< workitem_size[2];
-
- // CL_DEVICE_MAX_WORK_GROUP_SIZE
- size_t workgroup_size;
- clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(workgroup_size), &workgroup_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_MAX_WORK_GROUP_SIZE:" << workgroup_size;
-
- // CL_DEVICE_MAX_CLOCK_FREQUENCY
- cl_uint clock_frequency;
- clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(clock_frequency), &clock_frequency, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_MAX_CLOCK_FREQUENCY:"<< clock_frequency / 1000;
-
- // CL_DEVICE_IMAGE_SUPPORT
- cl_bool image_support;
- clGetDeviceInfo(device, CL_DEVICE_IMAGE_SUPPORT, sizeof(image_support), &image_support, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_IMAGE_SUPPORT:\t" << image_support;
-
- // CL_DEVICE_GLOBAL_MEM_SIZE
- cl_ulong mem_size;
- clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(mem_size), &mem_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_GLOBAL_MEM_SIZE:\t\t"<<(unsigned int)(mem_size / (1024 * 1024))<<"Mbytes";
-
- // CL_DEVICE_LOCAL_MEM_SIZE
- clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(mem_size), &mem_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_LOCAL_MEM_SIZE:\t\t"<< (unsigned int)(mem_size / (1024)) <<"KByte\n";
-
- // CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE
- clGetDeviceInfo(device, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE, sizeof(mem_size), &mem_size, nullptr);
- MITK_INFO("ocl.log") << " CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE:\t\t" << (unsigned int)(mem_size / (1024)) << "KByte";
-
- //check for image support properties
- clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof(workgroup_size), &workgroup_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_IMAGE2D_MAX_WIDTH:\t" << workgroup_size;
-
- clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof(workgroup_size), &workgroup_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_IMAGE2D_MAX_HEIGHT:\t" << workgroup_size;
-
- clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof(workgroup_size), &workgroup_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_IMAGE3D_MAX_WIDTH:\t" << workgroup_size;
-
- clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof(workgroup_size), &workgroup_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_IMAGE3D_MAX_HEIGHT:\t" << workgroup_size;
-
- clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof(workgroup_size), &workgroup_size, nullptr);
- MITK_INFO("ocl.log")<<" CL_DEVICE_IMAGE3D_MAX_DEPTH:\t" << workgroup_size;
-
-
- // CL_DEVICE_QUEUE_PROPERTIES
- cl_command_queue_properties queue_properties;
- clGetDeviceInfo(device, CL_DEVICE_QUEUE_PROPERTIES, sizeof(queue_properties), &queue_properties, nullptr);
- if( queue_properties & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE )
- MITK_INFO("ocl.log")<<" CL_DEVICE_QUEUE_PROPERTIES:\t\t"<< "CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE";
- if( queue_properties & CL_QUEUE_PROFILING_ENABLE )
- MITK_INFO("ocl.log")<<" CL_DEVICE_QUEUE_PROPERTIES:\t\t"<< "CL_QUEUE_PROFILING_ENABLE";
-
-}
-
-cl_ulong oclGetGlobalMemSize(cl_device_id device)
-{
- cl_ulong mem_size;
- clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(mem_size), &mem_size, nullptr);
- return mem_size;
-}
-
-std::string GetOclErrorAsString( int _clErr )
-{
- std::string returnString("unkown error number: "+std::to_string(_clErr)+" \n");
-
- switch(_clErr)
- {
- case CL_SUCCESS:
- returnString = "CL_SUCCESS\n";
- break;
- case CL_DEVICE_NOT_FOUND:
- returnString = "CL_DEVICE_NOT_FOUND\n";
- break;
- case CL_DEVICE_NOT_AVAILABLE:
- returnString = "CL_DEVICE_NOT_AVAILABLE\n";
- break;
- /*case CL_DEVICE_COMPILER_NOT_AVAILABLE:
- returnString = "CL_DEVICE_COMPILER_NOT_AVAILABLE\n";
- break; */
- case CL_MEM_OBJECT_ALLOCATION_FAILURE :
- returnString = "CL_MEM_OBJECT_ALLOCATION_FAILURE\n";
- break;
- case CL_OUT_OF_RESOURCES:
- returnString = "CL_OUT_OF_RESOURCES\n";
- break;
- case CL_OUT_OF_HOST_MEMORY:
- returnString = "CL_OUT_OF_HOST_MEMORY\n";
- break;
- case CL_PROFILING_INFO_NOT_AVAILABLE:
- returnString = "CL_PROFILING_INFO_NOT_AVAILABLE\n";
- break;
- case CL_MEM_COPY_OVERLAP:
- returnString = "CL_MEM_COPY_OVERLAP\n";
- break;
- case CL_IMAGE_FORMAT_MISMATCH:
- returnString = "CL_IMAGE_FORMAT_MISMATCH\n";
- break;
- case CL_IMAGE_FORMAT_NOT_SUPPORTED:
- returnString = "CL_IMAGE_FORMAT_NOT_SUPPORTED\n";
- break;
- case CL_BUILD_PROGRAM_FAILURE:
- returnString = "CL_BUILD_PROGRAM_FAILURE\n";
- break;
- case CL_MAP_FAILURE:
- returnString = "CL_MAP_FAILURE\n";
- break;
- case CL_INVALID_VALUE:
- returnString = "CL_INVALID_VALUE\n";
- break;
- case CL_INVALID_DEVICE_TYPE:
- returnString = "CL_INVALID_DEVICE_TYPE\n";
- break;
- case CL_INVALID_PLATFORM:
- returnString = "CL_INVALID_PLATFORM\n";
- break;
- case CL_INVALID_DEVICE:
- returnString = "CL_INVALID_DEVICE\n";
- break;
- case CL_INVALID_CONTEXT :
- returnString = "CL_INVALID_CONTEXT\n";
- break;
- case CL_INVALID_QUEUE_PROPERTIES:
- returnString = "CL_INVALID_QUEUE_PROPERTIES\n";
- break;
- case CL_INVALID_COMMAND_QUEUE:
- returnString = "CL_INVALID_COMMAND_QUEUE\n";
- break;
- case CL_INVALID_HOST_PTR:
- returnString = "CL_INVALID_HOST_PTR\n";
- break;
- case CL_INVALID_MEM_OBJECT:
- returnString = "CL_INVALID_MEM_OBJECT\n";
- break;
- case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:
- returnString = "CL_INVALID_IMAGE_FORMAT_DESCRIPTOR\n";
- break;
- case CL_INVALID_IMAGE_SIZE:
- returnString = "CL_INVALID_IMAGE_SIZE\n";
- break;
- case CL_INVALID_SAMPLER :
- returnString = "CL_INVALID_SAMPLER\n";
- break;
- case CL_INVALID_BINARY:
- returnString = "CL_INVALID_BINARY\n";
- break;
- case CL_INVALID_BUILD_OPTIONS:
- returnString = "CL_INVALID_BUILD_OPTIONS\n";
- break;
- case CL_INVALID_PROGRAM:
- returnString = "CL_INVALID_PROGRAM\n";
- break;
- case CL_INVALID_PROGRAM_EXECUTABLE:
- returnString = "CL_INVALID_PROGRAM_EXECUTABLE\n";
- break;
- case CL_INVALID_KERNEL_NAME:
- returnString = "CL_INVALID_KERNEL_NAME\n";
- break;
- case CL_INVALID_KERNEL_DEFINITION:
- returnString = "CL_INVALID_KERNEL_DEFINITION\n";
- break;
- case CL_INVALID_KERNEL :
- returnString = "CL_INVALID_KERNEL\n";
- break;
- case CL_INVALID_ARG_INDEX :
- returnString = "CL_INVALID_ARG_INDEX\n";
- break;
- case CL_INVALID_ARG_VALUE :
- returnString = "CL_INVALID_ARG_VALUE\n";
- break;
- case CL_INVALID_ARG_SIZE :
- returnString = "CL_INVALID_ARG_SIZE\n";
- break;
- case CL_INVALID_KERNEL_ARGS :
- returnString = "CL_INVALID_KERNEL_ARGS\n";
- break;
- case CL_INVALID_WORK_DIMENSION:
- returnString = "CL_INVALID_WORK_DIMENSION\n";
- break;
- case CL_INVALID_WORK_GROUP_SIZE:
- returnString = "CL_INVALID_WORK_GROUP_SIZE\n";
- break;
- case CL_INVALID_WORK_ITEM_SIZE:
- returnString = "CL_INVALID_WORK_ITEM_SIZE\n";
- break;
- case CL_INVALID_GLOBAL_OFFSET:
- returnString = "CL_INVALID_GLOBAL_OFFSET\n";
- break;
- case CL_INVALID_EVENT_WAIT_LIST:
- returnString = "CL_INVALID_EVENT_WAIT_LIST\n";
- break;
- case CL_INVALID_EVENT:
- returnString = "CL_INVALID_EVENT\n";
- break;
- case CL_INVALID_OPERATION:
- returnString = "CL_INVALID_OPERATION\n";
- break;
- case CL_INVALID_GL_OBJECT:
- returnString = "CL_INVALID_GL_OBJECT\n";
- break;
- case CL_INVALID_BUFFER_SIZE :
- returnString = "CL_INVALID_BUFFER_SIZE\n";
- break;
- case CL_INVALID_MIP_LEVEL :
- returnString = "CL_INVALID_MIP_LEVEL\n";
- break;
- default:
- break;
- }
-
- return returnString;
-}
-
-void GetOclError(int _clErr)
-{
- if(_clErr == CL_SUCCESS)
- MITK_WARN << "Called GetOclErr() with no error value: [CL_SUCCESS]";
- else
- MITK_ERROR << GetOclErrorAsString(_clErr);
-}
-
-bool oclCheckError(int _err, const char* filepath, int lineno)
-{
- if (_err)
- {
- MITK_ERROR<< "OpenCL Error at " << filepath <<":"<< lineno;
- GetOclError(_err);
-
- return 0;
- }
-
- return 1;
-}
-
-void GetSupportedImageFormats(cl_context _context, cl_mem_object_type _type)
-{
- const unsigned int entries = 500;
- cl_image_format* formats = new cl_image_format[entries];
-
- cl_uint _written = 0;
-
- // OpenCL constant to catch error IDs
- cl_int ciErr1;
- // Get list of supported image formats for READ_ONLY access
- ciErr1 = clGetSupportedImageFormats( _context, CL_MEM_READ_ONLY, _type, entries, formats, &_written);
- CHECK_OCL_ERR(ciErr1);
-
- MITK_INFO << "Supported Image Formats, Image: CL_MEM_READ_ONLY \n";
-
- for (unsigned int i=0; i<_written; i++)
- {
- MITK_INFO<< "ChannelType: " << GetImageTypeAsString(formats[i].image_channel_data_type) << "| ChannelOrder: "<< GetImageTypeAsString(formats[i].image_channel_order) <<"\n";
- }
-
- _written = 0;
-
- // Get list of supported image formats for READ_WRITE access
- ciErr1 = clGetSupportedImageFormats( _context, CL_MEM_READ_WRITE, _type, entries, formats, &_written);
- CHECK_OCL_ERR(ciErr1);
-
- MITK_INFO << "Supported Image Formats, Image: CL_MEM_READ_WRITE (found: " << _written <<") \n";
-
- for (unsigned int i=0; i<_written; i++)
- {
- MITK_INFO<< "ChannelType: " << GetImageTypeAsString(formats[i].image_channel_data_type) << "| ChannelOrder: "<< GetImageTypeAsString(formats[i].image_channel_order) <<"\n";
- }
-
- _written = 0;
-
- // Get list of supported image formats for WRITE_ONLY access
- ciErr1 = clGetSupportedImageFormats( _context, CL_MEM_WRITE_ONLY, _type, entries, formats, &_written);
- CHECK_OCL_ERR(ciErr1);
-
- MITK_INFO << "Supported Image Formats, Image: CL_MEM_WRITE_ONLY (found: " << _written <<") \n";
-
- for (unsigned int i=0; i<_written; i++)
- {
- MITK_INFO<< "ChannelType: " << GetImageTypeAsString(formats[i].image_channel_data_type) << "| ChannelOrder: "<< GetImageTypeAsString(formats[i].image_channel_order) <<"\n";
- }
-}
-
-std::string GetImageTypeAsString( const unsigned int _in)
-{
- switch(_in)
- {
- case CL_R:
- return "CL_R ";
- break;
- case CL_A:
- return "CL_A ";
- break;
- case CL_RG:
- return "CL_RG ";
- break;
- case CL_RA:
- return "CL_RA ";
- break;
- case CL_RGB:
- return "CL_RGB ";
- break;
- case CL_RGBA:
- return "CL_RGBA ";
- break;
- case CL_BGRA:
- return "CL_BGRA ";
- break;
- case CL_ARGB:
- return "CL_ARGB ";
- break;
- case CL_INTENSITY:
- return "CL_INTENSITY ";
- break;
- case CL_LUMINANCE:
- return "CL_LUMINANCE ";
- break;
- case CL_SNORM_INT8:
- return "CL_SNORM_INT8 ";
- break;
- case CL_SNORM_INT16:
- return "CL_SNORM_INT16 ";
- break;
- case CL_UNORM_INT8:
- return "CL_UNORM_INT8 ";
- break;
- case CL_UNORM_INT16:
- return "CL_UNORM_INT16 ";
- break;
- case CL_UNORM_SHORT_565:
- return "CL_UNORM_SHORT_565 ";
- break;
- case CL_UNORM_SHORT_555:
- return "CL_UNORM_SHORT_555 ";
- break;
- case CL_UNORM_INT_101010:
- return "CL_UNORM_INT_101010 ";
- break;
- case CL_SIGNED_INT8:
- return "CL_SIGNED_INT8 ";
- break;
- case CL_SIGNED_INT16:
- return "CL_SIGNED_INT16 ";
- break;
- case CL_SIGNED_INT32:
- return "CL_SIGNED_INT32 ";
- break;
- case CL_UNSIGNED_INT8:
- return "CL_UNSIGNED_INT8 ";
- break;
- case CL_UNSIGNED_INT16:
- return "CL_UNSIGNED_INT16 ";
- break;
- case CL_UNSIGNED_INT32:
- return "CL_UNSIGNED_INT32 ";
- break;
- case CL_HALF_FLOAT:
- return "CL_HALF_FLOAT ";
- break;
- case CL_FLOAT:
- return "CL_FLOAT ";
- break;
- default:
- return "--";
- break;
- }
-}
-
-
-
-void oclLogBinary(cl_program clProg, cl_device_id clDev)
-{
- // Grab the number of devices associated with the program
- cl_uint num_devices;
- clGetProgramInfo(clProg, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint), &num_devices, nullptr);
-
- // Grab the device ids
- cl_device_id* devices = (cl_device_id*) malloc(num_devices * sizeof(cl_device_id));
- clGetProgramInfo(clProg, CL_PROGRAM_DEVICES, num_devices * sizeof(cl_device_id), devices, 0);
-
- // Grab the sizes of the binaries
- size_t* binary_sizes = (size_t*)malloc(num_devices * sizeof(size_t));
- clGetProgramInfo(clProg, CL_PROGRAM_BINARY_SIZES, num_devices * sizeof(size_t), binary_sizes, nullptr);
-
- // Now get the binaries
- char** ptx_code = (char**)malloc(num_devices * sizeof(char*));
- for( unsigned int i=0; i<num_devices; ++i)
- {
- ptx_code[i] = (char*)malloc(binary_sizes[i]);
- }
- clGetProgramInfo(clProg, CL_PROGRAM_BINARIES, 0, ptx_code, nullptr);
-
- // Find the index of the device of interest
- unsigned int idx = 0;
- while((idx < num_devices) && (devices[idx] != clDev))
- {
- ++idx;
- }
-
- // If the index is associated, log the result
- if( idx < num_devices )
- {
- MITK_INFO<< "\n ---------------- \n Program Binary: \n -----------------------\n";
- MITK_INFO<< ptx_code[idx];
- }
-
- free( devices );
- free( binary_sizes );
- for(unsigned int i=0; i<num_devices; ++i)
- {
- free(ptx_code[i]);
- }
- free( ptx_code );
-}
-
-void oclLogBuildInfo(cl_program clProg, cl_device_id clDev)
-{
- char cBuildLog[10240];
-
- clGetProgramBuildInfo(clProg, clDev, CL_PROGRAM_BUILD_LOG, sizeof(cBuildLog), cBuildLog, nullptr);
- MITK_INFO<< "\n Program Build Log: \n -----------------------\n";
- MITK_INFO<< cBuildLog;
-}
diff --git a/Modules/OpenCL/mitkOclUtils.h b/Modules/OpenCL/mitkOclUtils.h
deleted file mode 100644
index 1c5d221389..0000000000
--- a/Modules/OpenCL/mitkOclUtils.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkOclUtils_h
-#define mitkOclUtils_h
-
-#include "mitkOpenCL.h"
-
-#include <string>
-#include <MitkOpenCLExports.h>
-
-#define CHECK_OCL_ERR(_er) oclCheckError(_er, __FILE__, __LINE__);
-
-/**
- @brief Method to estimate an integer quotient C from given dividend and divisor higher or equal to
- the corresponding floating quotient
-
- If the divisor is a factor of the dividend, the dividend/divisor is an integer value and is returned. If not,
- the nearest higher integer is returned. So it holds for the return value C that C * divisor is equal or greater then
- the dividend. In OpenCL context useful for estimating the local/global working dimension of a NDRange so that all
- image data is covered by the parallelisation scheme.
- */
-MITKOPENCL_EXPORT unsigned int iDivUp(unsigned int dividend, unsigned int divisor);
-
-/**
- @brief Returns the name of an OpenCL Error as a string
-
- Most of the OpenCL Methods ( cl<NAME> ) return an integer error code. This method translates the
- error value given as parameter to the corresponding error name. For example the value -30 will be translated
- to CL_INVALID_VALUE
- */
-MITKOPENCL_EXPORT std::string GetOclErrorAsString( int _clErr );
-
-/**
- @brief Checks whether the given value corresponds to an OpenCL Error value and prints this message out as MITK_ERROR if yes
- */
-MITKOPENCL_EXPORT void GetOclError(int _clErr);
-
-/**
- @brief Returns a platform ID of an OpenCL-capable GPU, or throws an exception
-*/
-MITKOPENCL_EXPORT cl_int oclGetPlatformID(cl_platform_id* selectedPlatform);
-
-/*! \brief Prints out the essential support information about current device */
-MITKOPENCL_EXPORT void oclPrintDeviceInfo(cl_device_id);
-
-/*! \brief Returns the Global memory size of the current device */
-MITKOPENCL_EXPORT cl_ulong oclGetGlobalMemSize(cl_device_id device);
-
-/*! @brief Prints the available memory info about the given object to std::cout
- */
-MITKOPENCL_EXPORT void oclPrintMemObjectInfo( cl_mem memobj);
-
-/*! \brief Checks the given code for errors and produces a std::cout output if
- the _err does not equal CL_SUCCESS. The output includes also the filename and the line
- number of the method call.
- */
-MITKOPENCL_EXPORT bool oclCheckError(int _err, const char*, int);
-
-/*! \brief Logs the GPU Program binary code
-
-@param clProg: the OpenCL Program to log
-@param clDev: the OpenCL-capable device the program was tried to be compiled for
-*/
-MITKOPENCL_EXPORT void oclLogBinary(cl_program clProg, cl_device_id clDev);
-
-/*! \brief Shows the OpenCL-Program build info, called if clBuildProgram != CL_SUCCES
-
-@param clProg: the OpenCL Program to log
-@param clDev: the OpenCL-capable device the program was tried to be compiled for
-*/
-MITKOPENCL_EXPORT void oclLogBuildInfo(cl_program clProg, cl_device_id clDev);
-
-/** \brief Print out all supported image formats for given image type
-
- @param _type the image type ( CL_MEM_OBJECT_2D or CL_MEM_OBJECT_3D )
- @param _context the OpenCL context to be examined
- */
-MITKOPENCL_EXPORT void GetSupportedImageFormats(cl_context _context, cl_mem_object_type _type);
-
-/**
- @brief Translates the internal image type identifier to a human readable description string
-*/
-MITKOPENCL_EXPORT std::string GetImageTypeAsString( const unsigned int _in);
-
-#endif
diff --git a/Modules/OpenCL/mitkOpenCLActivator.cpp b/Modules/OpenCL/mitkOpenCLActivator.cpp
deleted file mode 100644
index 3ea84f430d..0000000000
--- a/Modules/OpenCL/mitkOpenCLActivator.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 "mitkOpenCLActivator.h"
-
-void OpenCLActivator::Load(us::ModuleContext *context)
-{
- // generate context
- m_ResourceService.reset(new OclResourceServiceImpl);
- us::ServiceProperties props;
-
- context->RegisterService<OclResourceService>(m_ResourceService.get(), props);
-}
-
-void OpenCLActivator::Unload(us::ModuleContext *)
-{
- m_ResourceService.release();
-}
-
-US_EXPORT_MODULE_ACTIVATOR(OpenCLActivator )
diff --git a/Modules/OpenCL/mitkOpenCLActivator.h b/Modules/OpenCL/mitkOpenCLActivator.h
deleted file mode 100644
index 8500ca3eb4..0000000000
--- a/Modules/OpenCL/mitkOpenCLActivator.h
+++ /dev/null
@@ -1,50 +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 mitkOpenCLActivator_h
-#define mitkOpenCLActivator_h
-
-#include "mitkOclResourceServiceImpl_p.h"
-
-#include <usModuleActivator.h>
-#include <usModuleContext.h>
-#include <usGetModuleContext.h>
-#include <usServiceProperties.h>
-
-#include <set>
-#include <algorithm>
-#include <memory>
-
-/**
- * @class OpenCLActivator
- *
- * @brief Custom activator for the OpenCL Module in order to register
- * and provide the OclResourceService
- */
-class US_ABI_LOCAL OpenCLActivator : public us::ModuleActivator
-{
-private:
-
- std::unique_ptr<OclResourceServiceImpl> m_ResourceService;
-
-public:
- /** @brief Load module context */
- void Load(us::ModuleContext *context);
-
- /** @brief Unload module context */
- void Unload(us::ModuleContext* );
-
-};
-
-
-
-#endif
diff --git a/Modules/OpenCVVideoSupport/CMakeLists.txt b/Modules/OpenCVVideoSupport/CMakeLists.txt
index 10db853b78..f56e7b8b91 100644
--- a/Modules/OpenCVVideoSupport/CMakeLists.txt
+++ b/Modules/OpenCVVideoSupport/CMakeLists.txt
@@ -1,24 +1,24 @@
set(dependencies OpenCV|videoio+calib3d)
# adding option for videoinput library on windows (for directshow based frame grabbing)
if(WIN32 AND MITK_USE_OpenCV)
option(MITK_USE_videoInput "Use videoInput (DirectShow wrapper) library" OFF)
endif()
if(MITK_USE_videoInput)
list(APPEND dependencies videoInput)
endif()
mitk_create_module(
INCLUDE_DIRS Commands
DEPENDS MitkAlgorithmsExt
PACKAGE_DEPENDS PUBLIC ${dependencies}
)
if(MODULE_IS_ENABLED)
- if(MITK_USE_Qt5)
+ if(MITK_USE_Qt6)
add_subdirectory(UI)
endif()
endif()
add_subdirectory(Testing)
diff --git a/Modules/OpenCVVideoSupport/UI/QmitkOpenCVVideoControls.h b/Modules/OpenCVVideoSupport/UI/QmitkOpenCVVideoControls.h
index d70660f536..6ec5d32614 100644
--- a/Modules/OpenCVVideoSupport/UI/QmitkOpenCVVideoControls.h
+++ b/Modules/OpenCVVideoSupport/UI/QmitkOpenCVVideoControls.h
@@ -1,117 +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 QmitkOpenCVVideoControls_h
#define QmitkOpenCVVideoControls_h
#include <ui_QmitkOpenCVVideoControls.h>
#include <MitkOpenCVVideoSupportUIExports.h>
#include <mitkPropertyListReplacedObserver.h>
#include <opencv2/core.hpp>
#include <opencv2/core/types_c.h>
class QmitkRenderWindow;
class QmitkVideoBackground;
namespace mitk
{
class VideoSource;
class OpenCVVideoSource;
}
class QmitkOpenCVVideoControlsPrivate;
///
/// \brief Offers widgets to play/pause/stop a video on a certain render window with
/// the use of an !initialized! QmitkVideoBackground. The QmitkVideoBackground should
/// contain an OpenCVVideoSource is then owned by this widget (and deleted)
///
class MITKOPENCVVIDEOSUPPORTUI_EXPORT QmitkOpenCVVideoControls : public QWidget, public mitk::PropertyListReplacedObserver
{
Q_OBJECT
public:
///
/// Construct the widget with the given render window and the given preset values
///
QmitkOpenCVVideoControls(QmitkVideoBackground* _VideoBackground, QmitkRenderWindow* _RenderWindow
- , QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ , QWidget* parent = nullptr, Qt::WindowFlags f = {});
///
/// call reset if video playback is enabled here
///
~QmitkOpenCVVideoControls() override;
///
/// sets the render window for this video player
///
void SetRenderWindow(QmitkRenderWindow* _RenderWindow);
///
/// returns the current render window
///
QmitkRenderWindow* GetRenderWindow() const;
///
/// sets the qmitkvideobackground for this
///
void SetVideoBackground(QmitkVideoBackground* _VideoBackground);
///
/// returns the current QmitkVideoBackground
///
QmitkVideoBackground* GetVideoBackground() const;
///
/// calls FromPropertyList
///
void AfterPropertyListReplaced(const std::string& id, mitk::PropertyList* propertyList) override;
signals:
///
/// When playback is started this informs when a new frame was grabbed
///
void NewOpenCVFrameAvailable(const IplImage*);
protected slots:
void on_UseGrabbingDeviceButton_clicked(bool checked = false);
void on_UseVideoFileButton_clicked(bool checked = false);
void on_VideoProgressSlider_sliderPressed();
void on_VideoProgressSlider_sliderReleased();
void on_VideoProgressSlider_valueChanged(int value);
void on_RepeatVideoButton_clicked(bool checked = false);
void on_PlayButton_clicked(bool checked = false);
void on_StopButton_clicked(bool checked = false);
void Play();
void Stop();
void Reset();
void IsPlaying(bool paused);
void QObjectDestroyed(QObject * obj = nullptr);
void NewFrameAvailable(mitk::VideoSource* videoSource);
void EndOfVideoSourceReached(mitk::VideoSource* videoSource);
protected:
QmitkVideoBackground* m_VideoBackground;
QmitkRenderWindow* m_RenderWindow;
mitk::OpenCVVideoSource* m_VideoSource;
Ui::QmitkOpenCVVideoControls* m_Controls;
bool m_SliderCurrentlyMoved;
private:
friend class QmitkOpenCVVideoControlsPrivate;
QScopedPointer<QmitkOpenCVVideoControlsPrivate> d;
};
#endif
diff --git a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceCommandWidget.h b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceCommandWidget.h
index 0d83ba48c6..0e9c4f6528 100644
--- a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceCommandWidget.h
+++ b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceCommandWidget.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 QmitkIGTLDeviceCommandWidget_h
#define QmitkIGTLDeviceCommandWidget_h
//QT headers
#include <QWidget>
#include <QTimer>
//mitk headers
#include "MitkOpenIGTLinkUIExports.h"
#include "mitkIGTLDeviceSource.h"
#include "mitkIGTLClient.h"
#include "mitkDataStorage.h"
//itk
#include <itkCommand.h>
//ui header
#include "ui_QmitkIGTLDeviceCommandWidgetControls.h"
/** Documentation:
* \brief An object of this class offers an UI to send OpenIGTLink commands.
*
*
* \ingroup OpenIGTLinkUI
*/
class MITKOPENIGTLINKUI_EXPORT QmitkIGTLDeviceCommandWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
/**
* \brief Initializes the widget with the given device.
*
* The old device is
* dropped, so be careful, if the source is not saved somewhere else it might
* be lost. You might want to ask the user if he wants to save the changes
* before calling this method.
* \param device The widget will be initialized corresponding to the state of
* this device.
*/
void Initialize(mitk::IGTLDevice::Pointer device);
- QmitkIGTLDeviceCommandWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkIGTLDeviceCommandWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkIGTLDeviceCommandWidget() override;
protected slots:
void OnCommandChanged(const QString& curCommand);
void OnSendCommand();
///**
//* \brief Is called when the current device received a message
//*/
//void OnMessageReceived();
///**
//* \brief Is called when the current device received a command
//*/
//void OnCommandReceived();
/**
* \brief Is called when the current device lost a connection to one of its
* sockets
*/
void OnLostConnection();
/**
* \brief Is called when the current device connected to another device
*/
void OnNewConnection();
/**
* \brief Adapts the GUI to the state of the device
*/
void AdaptGUIToState();
signals:
/**
* \brief used for thread seperation, the worker thread must not call AdaptGUIToState directly
* QT signals are thread safe and seperate the threads
*/
void AdaptGUIToStateSignal();
protected:
/**
* \brief Calls AdaptGUIToState()
*/
void OnDeviceStateChanged();
/// \brief Fills the commands combo box with available commands
void FillCommandsComboBox();
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkIGTLDeviceCommandWidgetControls* m_Controls;
/** @brief holds the OpenIGTLink device */
mitk::IGTLDevice::Pointer m_IGTLDevice;
igtl::MessageBase::Pointer m_CurrentCommand;
/** @brief flag to indicate if the IGTL device is a client or a server */
bool m_IsClient;
unsigned long m_MessageReceivedObserverTag;
unsigned long m_CommandReceivedObserverTag;
unsigned long m_LostConnectionObserverTag;
unsigned long m_NewConnectionObserverTag;
unsigned long m_StateModifiedObserverTag;
//############## private help methods #######################
void DisableSourceControls();
void EnableSourceControls();
};
#endif
diff --git a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSetupConnectionWidget.cpp b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSetupConnectionWidget.cpp
index 11cdc1a0c0..96431b93c8 100644
--- a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSetupConnectionWidget.cpp
+++ b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSetupConnectionWidget.cpp
@@ -1,436 +1,436 @@
/*============================================================================
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 "QmitkIGTLDeviceSetupConnectionWidget.h"
//mitk headers
#include <mitkSurface.h>
#include <mitkIGTLDeviceSource.h>
#include <mitkDataStorage.h>
#include <mitkIGTLMessageFactory.h>
//qt headers
#include <qfiledialog.h>
#include <qinputdialog.h>
#include <qmessagebox.h>
#include <qscrollbar.h>
//igtl
#include <igtlStringMessage.h>
#include <igtlBindMessage.h>
#include <igtlQuaternionTrackingDataMessage.h>
#include <igtlTrackingDataMessage.h>
//poco headers
#include <Poco/Path.h>
-#include <QRegExpValidator>
+#include <QRegularExpressionValidator>
const std::string QmitkIGTLDeviceSetupConnectionWidget::VIEW_ID =
"org.mitk.views.igtldevicesetupconnectionwidget";
QmitkIGTLDeviceSetupConnectionWidget::QmitkIGTLDeviceSetupConnectionWidget(
QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f), m_IsClient(false)
{
m_Controls = nullptr;
this->m_IGTLDevice = nullptr;
CreateQtPartControl(this);
m_NumSentFramesSinceLastUpdate = 0;
m_NumReceivedFramesSinceLastUpdate = 0;
}
QmitkIGTLDeviceSetupConnectionWidget::~QmitkIGTLDeviceSetupConnectionWidget()
{
this->RemoveObserver();
}
void QmitkIGTLDeviceSetupConnectionWidget::RemoveObserver()
{
if (this->m_IGTLDevice.IsNotNull())
{
this->m_IGTLDevice->RemoveObserver(m_MessageReceivedObserverTag);
this->m_IGTLDevice->RemoveObserver(m_MessageSentObserverTag);
this->m_IGTLDevice->RemoveObserver(m_CommandReceivedObserverTag);
this->m_IGTLDevice->RemoveObserver(m_LostConnectionObserverTag);
this->m_IGTLDevice->RemoveObserver(m_NewConnectionObserverTag);
this->m_IGTLDevice->RemoveObserver(m_StateModifiedObserverTag);
}
}
void QmitkIGTLDeviceSetupConnectionWidget::CreateQtPartControl(QWidget *parent)
{
if (!m_Controls)
{
// create GUI widgets
m_Controls = new Ui::QmitkIGTLDeviceSetupConnectionWidgetControls;
// setup GUI widgets
m_Controls->setupUi(parent);
}
// set the validator for the ip edit box (values must be between 0 and 255 and
// there are four of them, seperated with a point
- QRegExpValidator *v = new QRegExpValidator(this);
- QRegExp rx("((1{0,1}[0-9]{0,2}|2[0-4]{1,1}[0-9]{1,1}|25[0-5]{1,1})\\.){3,3}(1{0,1}[0-9]{0,2}|2[0-4]{1,1}[0-9]{1,1}|25[0-5]{1,1})");
- v->setRegExp(rx);
+ auto v = new QRegularExpressionValidator(this);
+ QRegularExpression rx("((1{0,1}[0-9]{0,2}|2[0-4]{1,1}[0-9]{1,1}|25[0-5]{1,1})\\.){3,3}(1{0,1}[0-9]{0,2}|2[0-4]{1,1}[0-9]{1,1}|25[0-5]{1,1})");
+ v->setRegularExpression(rx);
m_Controls->editIP->setValidator(v);
// set the validator for the port edit box (values must be between 1 and 65535)
m_Controls->editPort->setValidator(new QIntValidator(1, 65535, this));
m_FPSCalculationTimer.start(1000);
//connect slots with signals
CreateConnections();
}
void QmitkIGTLDeviceSetupConnectionWidget::CreateConnections()
{
if (m_Controls)
{
// connect the widget items with the methods
connect(m_Controls->butConnect, SIGNAL(clicked()),
this, SLOT(OnConnect()));
connect(m_Controls->editPort, SIGNAL(editingFinished()),
this, SLOT(OnPortChanged()));
connect(m_Controls->editIP, SIGNAL(editingFinished()),
this, SLOT(OnHostnameChanged()));
connect(m_Controls->bufferInMsgCheckBox, SIGNAL(stateChanged(int)),
this, SLOT(OnBufferIncomingMessages(int)));
connect(m_Controls->bufferOutMsgCheckBox, SIGNAL(stateChanged(int)),
this, SLOT(OnBufferOutgoingMessages(int)));
connect(&m_FPSCalculationTimer, SIGNAL(timeout()),
this, SLOT(OnUpdateFPSLabel()));
connect(m_Controls->logMessageDetailsCheckBox, SIGNAL(clicked()),
this, SLOT(OnLogMessageDetailsCheckBoxClicked()));
}
//this is used for thread seperation, otherwise the worker thread would change the ui elements
//which would cause an exception
connect(this, SIGNAL(AdaptGUIToStateSignal()), this, SLOT(AdaptGUIToState()));
}
void QmitkIGTLDeviceSetupConnectionWidget::OnDeviceStateChanged()
{
emit AdaptGUIToStateSignal();
}
void QmitkIGTLDeviceSetupConnectionWidget::AdaptGUIToState()
{
//check the validity of the device
if (this->m_IGTLDevice.IsNull())
{
return;
}
//check the state of the device
mitk::IGTLDevice::IGTLDeviceState state = this->m_IGTLDevice->GetState();
switch (state) {
case mitk::IGTLDevice::Setup:
if (!m_IsClient)
{
m_Controls->butConnect->setText("Go Online");
this->m_Controls->editIP->setEnabled(false);
}
else
{
m_Controls->butConnect->setText("Connect");
this->m_Controls->editIP->setEnabled(true);
}
this->m_Controls->editPort->setEnabled(true);
this->m_Controls->logMessageStatusCheckBox->setChecked(false);
this->m_Controls->logMessageDetailsCheckBox->setChecked(false);
this->m_Controls->logMessageStatusCheckBox->setEnabled(false);
this->m_Controls->logMessageDetailsCheckBox->setEnabled(false);
this->m_Controls->bufferInMsgCheckBox->setEnabled(false);
this->m_Controls->bufferOutMsgCheckBox->setEnabled(false);
this->m_Controls->butConnect->setEnabled(true);
this->m_Controls->fpsInLabel->setEnabled(false);
this->m_Controls->fpsOutLabel->setEnabled(false);
this->m_Controls->fpsInDescrLabel->setEnabled(false);
this->m_Controls->fpsOutDescrLabel->setEnabled(false);
if( this->m_IGTLDevice.IsNotNull() )
{
this->m_IGTLDevice->SetLogMessages(false);
}
break;
case mitk::IGTLDevice::Ready:
if (m_IsClient)
{
this->m_Controls->butConnect->setText("Disconnect");
}
else
{
this->m_Controls->butConnect->setText("Go Offline");
}
this->m_Controls->editIP->setEnabled(false);
this->m_Controls->editPort->setEnabled(false);
this->m_Controls->logMessageStatusCheckBox->setEnabled(true);
this->m_Controls->logMessageDetailsCheckBox->setEnabled(true);
this->m_Controls->bufferInMsgCheckBox->setEnabled(true);
this->m_Controls->bufferOutMsgCheckBox->setEnabled(true);
this->m_Controls->butConnect->setEnabled(true);
this->m_Controls->fpsInLabel->setEnabled(true);
this->m_Controls->fpsOutLabel->setEnabled(true);
this->m_Controls->fpsInDescrLabel->setEnabled(true);
this->m_Controls->fpsOutDescrLabel->setEnabled(true);
break;
case mitk::IGTLDevice::Running:
if (m_IsClient)
{
this->m_Controls->butConnect->setText("Disconnect");
}
else
{
this->m_Controls->butConnect->setText("Go Offline");
}
this->m_Controls->editIP->setEnabled(false);
this->m_Controls->editPort->setEnabled(false);
this->m_Controls->logMessageStatusCheckBox->setEnabled(true);
this->m_Controls->logMessageDetailsCheckBox->setEnabled(true);
this->m_Controls->bufferInMsgCheckBox->setEnabled(true);
this->m_Controls->bufferOutMsgCheckBox->setEnabled(true);
this->m_Controls->butConnect->setEnabled(true);
this->m_Controls->fpsInLabel->setEnabled(true);
this->m_Controls->fpsOutLabel->setEnabled(true);
this->m_Controls->fpsInDescrLabel->setEnabled(true);
this->m_Controls->fpsOutDescrLabel->setEnabled(true);
break;
default:
mitkThrow() << "Invalid Device State";
break;
}
}
void QmitkIGTLDeviceSetupConnectionWidget::Initialize(
mitk::IGTLDevice::Pointer device)
{
//reset the GUI
DisableSourceControls();
//reset the observers
this->RemoveObserver();
if (device.IsNotNull())
{
this->m_IGTLDevice = device;
//check if the device is a server or a client
if (dynamic_cast<mitk::IGTLClient*>(
this->m_IGTLDevice.GetPointer()) == nullptr)
{
m_IsClient = false;
}
else
{
m_IsClient = true;
}
this->AdaptGUIToState();
typedef itk::SimpleMemberCommand< QmitkIGTLDeviceSetupConnectionWidget > CurCommandType;
CurCommandType::Pointer messageSentCommand = CurCommandType::New();
messageSentCommand->SetCallbackFunction(
this, &QmitkIGTLDeviceSetupConnectionWidget::OnMessageSent);
this->m_MessageSentObserverTag = this->m_IGTLDevice->AddObserver(
mitk::MessageSentEvent(), messageSentCommand);
CurCommandType::Pointer messageReceivedCommand = CurCommandType::New();
messageReceivedCommand->SetCallbackFunction(
this, &QmitkIGTLDeviceSetupConnectionWidget::OnMessageReceived);
this->m_MessageReceivedObserverTag = this->m_IGTLDevice->AddObserver(
mitk::MessageReceivedEvent(), messageReceivedCommand);
CurCommandType::Pointer commandReceivedCommand = CurCommandType::New();
commandReceivedCommand->SetCallbackFunction(
this, &QmitkIGTLDeviceSetupConnectionWidget::OnCommandReceived);
this->m_CommandReceivedObserverTag = this->m_IGTLDevice->AddObserver(
mitk::CommandReceivedEvent(), commandReceivedCommand);
CurCommandType::Pointer connectionLostCommand = CurCommandType::New();
connectionLostCommand->SetCallbackFunction(
this, &QmitkIGTLDeviceSetupConnectionWidget::OnLostConnection);
this->m_LostConnectionObserverTag = this->m_IGTLDevice->AddObserver(
mitk::LostConnectionEvent(), connectionLostCommand);
CurCommandType::Pointer newConnectionCommand = CurCommandType::New();
newConnectionCommand->SetCallbackFunction(
this, &QmitkIGTLDeviceSetupConnectionWidget::OnNewConnection);
this->m_NewConnectionObserverTag = this->m_IGTLDevice->AddObserver(
mitk::NewClientConnectionEvent(), newConnectionCommand);
CurCommandType::Pointer stateModifiedCommand = CurCommandType::New();
stateModifiedCommand->SetCallbackFunction(
this, &QmitkIGTLDeviceSetupConnectionWidget::OnDeviceStateChanged);
this->m_StateModifiedObserverTag = this->m_IGTLDevice->AddObserver(
itk::ModifiedEvent(), stateModifiedCommand);
OnBufferIncomingMessages(m_Controls->bufferInMsgCheckBox->isChecked());
OnBufferOutgoingMessages(m_Controls->bufferOutMsgCheckBox->isChecked());
}
else
{
m_IGTLDevice = nullptr;
}
}
void QmitkIGTLDeviceSetupConnectionWidget::DisableSourceControls()
{
m_Controls->editIP->setEnabled(false);
m_Controls->editPort->setEnabled(false);
m_Controls->butConnect->setEnabled(false);
m_Controls->bufferInMsgCheckBox->setEnabled(false);
m_Controls->bufferOutMsgCheckBox->setEnabled(false);
this->m_Controls->logMessageStatusCheckBox->setChecked(false);
this->m_Controls->logMessageDetailsCheckBox->setChecked(false);
this->m_Controls->logMessageStatusCheckBox->setEnabled(false);
this->m_Controls->logMessageDetailsCheckBox->setEnabled(false);
if( this->m_IGTLDevice.IsNotNull() )
{
this->m_IGTLDevice->SetLogMessages(false);
}
}
void QmitkIGTLDeviceSetupConnectionWidget::OnConnect()
{
if (m_IGTLDevice->GetState() == mitk::IGTLDevice::Setup)
{
QString port = m_Controls->editPort->text();
m_IGTLDevice->SetPortNumber(port.toInt());
std::string hostname = m_Controls->editIP->text().toStdString();
m_IGTLDevice->SetHostname(hostname);
//connect with the other OpenIGTLink device => changes the state from Setup
//to Ready
if (m_IGTLDevice->OpenConnection())
{
//starts the communication thread => changes the state from Ready to
//Running
if (m_IGTLDevice->StartCommunication())
{
if (this->m_IsClient)
{
MITK_INFO("IGTLDeviceSourceManagementWidget")
<< "Successfully connected to " << hostname
<< " on port " << port.toStdString();
}
}
else
{
MITK_ERROR("QmitkIGTLDeviceSetupConnectionWidget") <<
"Could not start a communication with the"
"server because the client is in the wrong state";
}
}
else
{
MITK_ERROR("QmitkIGTLDeviceSetupConnectionWidget") <<
"Could not connect to the server. "
"Please check the hostname and port.";
}
}
else if (m_IGTLDevice->GetState() == mitk::IGTLDevice::Ready || m_IGTLDevice->GetState() == mitk::IGTLDevice::Running)
{
m_IGTLDevice->CloseConnection();
MITK_INFO("QmitkIGTLDeviceSetupConnectionWidget") << "Closed connection";
}
else
{
mitkThrow() << "Invalid state of IGTLDevice";
}
this->AdaptGUIToState();
}
void QmitkIGTLDeviceSetupConnectionWidget::OnPortChanged()
{
}
void QmitkIGTLDeviceSetupConnectionWidget::OnHostnameChanged()
{
}
void QmitkIGTLDeviceSetupConnectionWidget::OnLostConnection()
{
emit AdaptGUIToStateSignal();
}
void QmitkIGTLDeviceSetupConnectionWidget::OnNewConnection()
{
emit AdaptGUIToStateSignal();
}
void QmitkIGTLDeviceSetupConnectionWidget::OnMessageReceived()
{
if( this->m_Controls->logMessageStatusCheckBox->isChecked() )
{
MITK_INFO("IGTLDeviceSetupConnectionWidget") << "Received a message.";
}
m_NumReceivedFramesSinceLastUpdate++;
}
void QmitkIGTLDeviceSetupConnectionWidget::OnMessageSent()
{
if( this->m_Controls->logMessageStatusCheckBox->isChecked() )
{
MITK_INFO("IGTLDeviceSetupConnectionWidget") << "Sent a message.";
}
m_NumSentFramesSinceLastUpdate++;
}
void QmitkIGTLDeviceSetupConnectionWidget::OnCommandReceived()
{
if( this->m_Controls->logMessageStatusCheckBox->isChecked() )
{
MITK_INFO("IGTLDeviceSetupConnectionWidget") << "Received a command.";
}
}
void QmitkIGTLDeviceSetupConnectionWidget::OnBufferIncomingMessages(int state)
{
if (this->m_IGTLDevice.IsNotNull())
{
this->m_IGTLDevice->EnableNoBufferingMode(
this->m_IGTLDevice->GetMessageQueue(), (bool)state);
}
}
void QmitkIGTLDeviceSetupConnectionWidget::OnBufferOutgoingMessages(int state)
{
if (this->m_IGTLDevice.IsNotNull())
{
this->m_IGTLDevice->EnableNoBufferingMode(
this->m_IGTLDevice->GetMessageQueue(), (bool)state);
}
}
void QmitkIGTLDeviceSetupConnectionWidget::OnUpdateFPSLabel()
{
double fpsIn = m_NumReceivedFramesSinceLastUpdate / 1.0;
double fpsOut = m_NumSentFramesSinceLastUpdate / 1.0;
this->m_Controls->fpsInLabel->setText(QString::number(fpsIn));
this->m_Controls->fpsOutLabel->setText(QString::number(fpsOut));
m_NumReceivedFramesSinceLastUpdate = 0;
m_NumSentFramesSinceLastUpdate = 0;
}
void QmitkIGTLDeviceSetupConnectionWidget::OnLogMessageDetailsCheckBoxClicked()
{
if( this->m_IGTLDevice.IsNull() )
{
MITK_WARN << "Logging information not passed down to Message Provider.";
return;
}
else
{
this->m_IGTLDevice->SetLogMessages( this->m_Controls->logMessageDetailsCheckBox->isChecked() );
}
}
diff --git a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSetupConnectionWidget.h b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSetupConnectionWidget.h
index fa4042610c..b9b5e37d91 100644
--- a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSetupConnectionWidget.h
+++ b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSetupConnectionWidget.h
@@ -1,181 +1,181 @@
/*============================================================================
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 QmitkIGTLDeviceSetupConnectionWidget_h
#define QmitkIGTLDeviceSetupConnectionWidget_h
//QT headers
#include <QWidget>
#include <QTimer>
//mitk headers
#include "MitkOpenIGTLinkUIExports.h"
#include "mitkIGTLDeviceSource.h"
#include "mitkIGTLClient.h"
#include "mitkDataStorage.h"
//itk
#include <itkCommand.h>
//ui header
#include "ui_QmitkIGTLDeviceSetupConnectionWidgetControls.h"
/** Documentation:
* \brief An object of this class offers an UI to setup the connection of an
* OpenIGTLink device.
*
*
* \ingroup OpenIGTLinkUI
*/
class MITKOPENIGTLINKUI_EXPORT QmitkIGTLDeviceSetupConnectionWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
/**
* \brief Initializes the widget with the given device.
*
* The old device is
* dropped, so be careful, if the source is not saved somewhere else it might
* be lost. You might want to ask the user if he wants to save the changes
* before calling this method.
* \param device The widget will be initialized corresponding to the state of
* this device.
*/
void Initialize(mitk::IGTLDevice::Pointer device);
- QmitkIGTLDeviceSetupConnectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkIGTLDeviceSetupConnectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkIGTLDeviceSetupConnectionWidget() override;
// /**
// * \brief Is called when the current device received a message
// */
// void OnMessageReceived(itk::Object* caller, const itk::EventObject&);
// /**
// * \brief Is called when the current device received a command
// */
// void OnCommandReceived(itk::Object* caller, const itk::EventObject&);
/**
* \brief Is called when the current device lost a connection to one of its
* sockets
*/
void OnLostConnection();
/**
* \brief Is called when the current device connected to another device
*/
void OnNewConnection();
/**
* \brief Is called when the current device received a message
*/
void OnMessageReceived();
/**
* \brief Is called when the current device received a message
*/
void OnMessageSent();
/**
* \brief Is called when the current device received a command
*/
void OnCommandReceived();
protected slots:
void OnConnect();
void OnPortChanged();
void OnHostnameChanged();
void OnUpdateFPSLabel();
/**
* \brief Enables/Disables the detailed logging of incoming/outgoing messages
*/
void OnLogMessageDetailsCheckBoxClicked();
/**
* \brief Enables/Disables the buffering of incoming messages
*/
void OnBufferIncomingMessages(int state);
/**
* \brief Enables/Disables the buffering of outgoing messages
*
* This can be necessary when the data is faster produced then sent
*/
void OnBufferOutgoingMessages(int state);
/**
* \brief Adapts the GUI to the state of the device
*/
void AdaptGUIToState();
signals:
/**
* \brief used for thread seperation, the worker thread must not call AdaptGUIToState directly.
* QT signals are thread safe and seperate the threads
*/
void AdaptGUIToStateSignal();
protected:
/**
* \brief Calls AdaptGUIToState()
*/
void OnDeviceStateChanged();
/** \brief Creation of the connections */
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkIGTLDeviceSetupConnectionWidgetControls* m_Controls;
/** @brief holds the OpenIGTLink device */
mitk::IGTLDevice::Pointer m_IGTLDevice;
/** @brief flag to indicate if the IGTL device is a client or a server */
bool m_IsClient;
unsigned long m_MessageSentObserverTag;
unsigned long m_MessageReceivedObserverTag;
unsigned long m_CommandReceivedObserverTag;
unsigned long m_LostConnectionObserverTag;
unsigned long m_NewConnectionObserverTag;
unsigned long m_StateModifiedObserverTag;
/** @brief the number of received frames (messages) since the last fps calculation update
*
* This counter is incremented every time a message is received. When the timer
* m_FPSCalculationTimer is fired it is reset to 0 and the number is used to calculate the FPS
*/
unsigned int m_NumReceivedFramesSinceLastUpdate;
/** @brief the number of sent frames (messages) since the last fps calculation update
*
* This counter is incremented every time a message is sent. When the timer
* m_FPSCalculationTimer is fired it is reset to 0 and the number is used to calculate the FPS
*/
unsigned int m_NumSentFramesSinceLastUpdate;
/** @brief the timer used to calculate the frames per second */
QTimer m_FPSCalculationTimer;
//############## private help methods #######################
void DisableSourceControls();
// void EnableSourceControls();
void RemoveObserver();
};
#endif
diff --git a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSourceManagementWidget.h b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSourceManagementWidget.h
index fac4b78a4e..ca20793121 100644
--- a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSourceManagementWidget.h
+++ b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSourceManagementWidget.h
@@ -1,128 +1,128 @@
/*============================================================================
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 QmitkIGTLDeviceSourceManagementWidget_h
#define QmitkIGTLDeviceSourceManagementWidget_h
//QT headers
#include <QWidget>
#include <QTimer>
//mitk headers
#include "MitkOpenIGTLinkUIExports.h"
#include "mitkIGTLDeviceSource.h"
#include "mitkIGTLClient.h"
#include "mitkDataStorage.h"
//itk
#include <itkCommand.h>
//ui header
#include "ui_QmitkIGTLDeviceSourceManagementWidgetControls.h"
/** Documentation:
* \brief An object of this class offers an UI to manage OpenIGTLink Device
* Sources and OpenIGTLink Devices.
*
*
* \ingroup OpenIGTLinkUI
*/
class MITKOPENIGTLINKUI_EXPORT QmitkIGTLDeviceSourceManagementWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
/** Loads a source to the widget. The old source is dropped, so be careful,
* if the source is not saved somewhere else it might be lost. You might
* want to ask the user if he wants to save the changes before calling this
* method.
* @param sourceToLoad This source will be loaded and might be modified
* by the user.
*/
void LoadSource(mitk::IGTLDeviceSource::Pointer sourceToLoad);
- QmitkIGTLDeviceSourceManagementWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkIGTLDeviceSourceManagementWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkIGTLDeviceSourceManagementWidget() override;
protected slots:
void OnSendMessage();
/**
* \brief Is called when the current device received a message
*/
void OnMessageReceived();
/**
* \brief Is called when the current device received a command
*/
void OnCommandReceived();
/**
* \brief Is called when the current device lost a connection to one of its
* sockets
*/
void OnLostConnection();
/**
* \brief Is called when the current device connected to another device
*/
void OnNewConnection();
/**
* \brief Adapts the GUI to the state of the device
*/
void AdaptGUIToState();
signals:
/**
* \brief used for thread seperation, the worker thread must not call AdaptGUIToState directly
* QT signals are thread safe and seperate the threads
*/
void AdaptGUIToStateSignal();
protected:
/**
* \brief Calls AdaptGUIToState()
*/
void OnDeviceStateChanged();
/// \brief Fills the commands combo box with available commands
void FillCommandsComboBox();
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkIGTLDeviceSourceManagementWidgetControls* m_Controls;
/** @brief holds the OpenIGTLink device */
mitk::IGTLDevice::Pointer m_IGTLDevice;
/** @brief holds the IGTLDeviceSource we are working with. */
mitk::IGTLDeviceSource::Pointer m_IGTLDeviceSource;
/** @brief flag to indicate if the IGTL device is a client or a server */
bool m_IsClient;
unsigned long m_MessageReceivedObserverTag;
unsigned long m_CommandReceivedObserverTag;
unsigned long m_LostConnectionObserverTag;
unsigned long m_NewConnectionObserverTag;
unsigned long m_StateModifiedObserverTag;
//############## private help methods #######################
void DisableSourceControls();
};
#endif
diff --git a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSourceSelectionWidget.h b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSourceSelectionWidget.h
index 4a108603ac..a035d90af2 100644
--- a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSourceSelectionWidget.h
+++ b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLDeviceSourceSelectionWidget.h
@@ -1,80 +1,80 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkIGTLDeviceSourceSelectionWidget_h
#define QmitkIGTLDeviceSourceSelectionWidget_h
//QT headers
#include <QWidget>
//mitk headers
#include "MitkOpenIGTLinkUIExports.h"
#include "mitkIGTLDeviceSource.h"
//#include <mitkNavigationToolStorage.h>
//#include <mitkNavigationDataSource.h>
#include <usServiceReference.h>
//ui header
#include "ui_QmitkIGTLDeviceSourceSelectionWidgetControls.h"
/** Documentation:
* \brief This widget allows the user to select a OpenIGTLink device source.
*
* The widget lists all OpenIGTLink device sources which are available
* as microservice via the module context.
*
* A signal is emmited whenever the device selection changes.
*
* \ingroup OpenIGTLinkUI
*/
class MITKOPENIGTLINKUI_EXPORT QmitkIGTLDeviceSourceSelectionWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkIGTLDeviceSourceSelectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkIGTLDeviceSourceSelectionWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkIGTLDeviceSourceSelectionWidget() override;
/** @return Returns the currently selected OpenIGTLink device source.
* Returns null if no source is selected at the moment. */
mitk::IGTLDeviceSource::Pointer GetSelectedIGTLDeviceSource();
signals:
/** @brief This signal is emitted when a new OpenIGTLink device source is
* selected.
* @param source Holds the new selected OpenIGTLink device source. Is null
* if the old source is deselected and no new source is selected.
*/
void IGTLDeviceSourceSelected(mitk::IGTLDeviceSource::Pointer source);
protected slots:
void IGTLDeviceSourceSelected(us::ServiceReferenceU s);
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkIGTLDeviceSourceSelectionWidgetControls* m_Controls;
mitk::IGTLDeviceSource::Pointer m_CurrentIGTLDeviceSource;
};
#endif
diff --git a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLMessageSourceSelectionWidget.h b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLMessageSourceSelectionWidget.h
index fda2d1aed6..be3c2df916 100644
--- a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLMessageSourceSelectionWidget.h
+++ b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLMessageSourceSelectionWidget.h
@@ -1,97 +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 QmitkIGTLMessageSourceSelectionWidget_h
#define QmitkIGTLMessageSourceSelectionWidget_h
//QT headers
#include <QWidget>
//mitk headers
#include "MitkOpenIGTLinkUIExports.h"
#include "mitkIGTLMessageSource.h"
//us
#include <usServiceReference.h>
//ui header
#include "ui_QmitkIGTLMessageSourceSelectionWidgetControls.h"
/** Documentation:
* \brief This widget allows the user to select a OpenIGTLink message source.
*
* The widget lists all OpenIGTLink message sources which are available
* as microservice via the module context.
*
* A signal is emmited whenever the selection changes.
*
* \ingroup OpenIGTLinkUI
*/
class MITKOPENIGTLINKUI_EXPORT QmitkIGTLMessageSourceSelectionWidget :
public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
QmitkIGTLMessageSourceSelectionWidget(QWidget* parent = nullptr,
- Qt::WindowFlags f = nullptr);
+ Qt::WindowFlags f = {});
~QmitkIGTLMessageSourceSelectionWidget() override;
/** @return Returns the currently selected OpenIGTLink message source.
* Returns null if no source is selected at the moment. */
mitk::IGTLMessageSource::Pointer GetSelectedIGTLMessageSource();
/** @brief Automatically selects the first available OpenIGTLink message source
* of the messageSourceSelectionWidget as message source and assigns it to the
* class member m_CurrentIGTLMessageSource.
* If there is no OpenIGTLink message source available, a nullptr will be assigned
* to the m_CurrentIGTLMessageSource. It is important to call this method whenever
* a new OpenIGTLink client connects to the active OpenIGTLink server. Otherwise,
* the connection between PLUS and MITK or between Slicer and MITK won't work
* automatically.
*
* @return The pointer to the automatically selected message source. This might
* be a nullptr, if there is no message source available.
*/
mitk::IGTLMessageSource::Pointer AutoSelectFirstIGTLMessageSource();
signals:
/** @brief This signal is emitted when a new OpenIGTLink message source is
* selected.
* @param source Holds the new selected OpenIGTLink device source. Is null
* if the old source is deselected and no new source is selected.
*/
void IGTLMessageSourceSelected(mitk::IGTLMessageSource::Pointer source);
protected slots:
void IGTLMessageSourceSelected(us::ServiceReferenceU s);
protected:
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkIGTLMessageSourceSelectionWidgetControls* m_Controls;
mitk::IGTLMessageSource::Pointer m_CurrentIGTLMessageSource;
};
#endif
diff --git a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLStreamingManagementWidget.h b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLStreamingManagementWidget.h
index f28898beb2..4b249b0be2 100644
--- a/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLStreamingManagementWidget.h
+++ b/Modules/OpenIGTLinkUI/Qmitk/QmitkIGTLStreamingManagementWidget.h
@@ -1,167 +1,167 @@
/*============================================================================
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 QmitkIGTLStreamingManagementWidget_h
#define QmitkIGTLStreamingManagementWidget_h
//QT headers
#include <QWidget>
#include <QTimer>
//mitk headers
#include "MitkOpenIGTLinkUIExports.h"
#include "mitkIGTLMessageProvider.h"
#include "mitkIGTLClient.h"
#include "mitkDataStorage.h"
//itk
#include <itkCommand.h>
//ui header
#include "ui_QmitkIGTLStreamingManagementWidgetControls.h"
/** Documentation:
* \brief An object of this class offers an UI to manage the streaming of
* message sources.
*
*
* \ingroup OpenIGTLinkUI
*/
class MITKOPENIGTLINKUI_EXPORT QmitkIGTLStreamingManagementWidget : public QWidget
{
Q_OBJECT
public:
static const std::string VIEW_ID;
/** Loads a provider to the widget. The old source is dropped, so be careful,
* if the source is not saved somewhere else it might be lost. You might
* want to ask the user if he wants to save the changes before calling this
* method.
* @param provider This provider will be loaded and might be modified
* by the user.
*/
void LoadSource(mitk::IGTLMessageProvider::Pointer provider);
- QmitkIGTLStreamingManagementWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkIGTLStreamingManagementWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
~QmitkIGTLStreamingManagementWidget() override;
protected slots:
void OnStartStreaming();
void OnStopStreaming();
void OnStreamingTimerTimeout();
/** \brief Is called when a new source is selected.
* @param source the newly selected source
*/
void SourceSelected(mitk::IGTLMessageSource::Pointer source);
/**
* \brief Adapts the GUI to the state of the device
*/
void AdaptGUIToState();
/**
* \brief selects the current source and adapts the GUI according to the selection
*/
void SelectSourceAndAdaptGUI();
signals:
/**
* \brief used for thread seperation, the worker thread must not call AdaptGUIToState directly.
* QT signals are thread safe and seperate the threads
*/
void AdaptGUIToStateSignal();
/**
* \brief used for thread seperation, the worker thread must not call SelectSourceAndAdaptGUI
* directly.
* QT signals are thread safe and seperate the threads
*/
void SelectSourceAndAdaptGUISignal();
protected:
/**
* \brief Is called when the current device received a message
*/
void OnMessageReceived();
/**
* \brief Is called when the current device received a command
*/
void OnCommandReceived();
/**
* \brief Is called when the current device lost a connection to one of its
* sockets
*/
void OnLostConnection();
/**
* \brief Is called when the current device connected to another device
*/
void OnNewConnection();
/**
* \brief Is called when provider requests the start of the streaming timer
*/
void OnStartStreamingTimer();
/**
* \brief Is called when provider requests the stop of the streaming timer
*/
void OnStopStreamingTimer();
/**
* \brief Calls AdaptGUIToState()
*/
void OnDeviceStateChanged();
/// \brief Fills the commands combo box with available commands
void FillCommandsComboBox();
/// \brief Creation of the connections
virtual void CreateConnections();
virtual void CreateQtPartControl(QWidget *parent);
Ui::QmitkIGTLStreamingManagementWidgetControls* m_Controls;
/** @brief holds the OpenIGTLink device */
mitk::IGTLDevice::Pointer m_IGTLDevice;
/** @brief holds the IGTL Message Provider that will send the stream */
mitk::IGTLMessageProvider::Pointer m_IGTLMsgProvider;
/** @brief holds the IGTLDeviceSource we are working with. */
mitk::IGTLMessageSource::Pointer m_IGTLMsgSource;
/** @brief flag to indicate if the IGTL device is a client or a server */
bool m_IsClient;
/** @brief the streaming timer that periodically calls the update method of the provider */
QTimer m_StreamingTimer;
unsigned long m_MessageReceivedObserverTag;
unsigned long m_CommandReceivedObserverTag;
unsigned long m_LostConnectionObserverTag;
unsigned long m_NewConnectionObserverTag;
unsigned long m_StateModifiedObserverTag;
unsigned long m_StartStreamingTimerObserverTag;
unsigned long m_StopStreamingTimerObserverTag;
//############## private help methods #######################
void DisableSourceControls();
void RemoveObserver();
};
#endif
diff --git a/Modules/Python/autoload/PythonService/CMakeLists.txt b/Modules/Python/autoload/PythonService/CMakeLists.txt
index 15f1384ec9..dbf1b33bf4 100644
--- a/Modules/Python/autoload/PythonService/CMakeLists.txt
+++ b/Modules/Python/autoload/PythonService/CMakeLists.txt
@@ -1,17 +1,17 @@
mitkFunctionCheckCompilerFlags("-Wno-cpp" CMAKE_CXX_FLAGS)
if(CTKScriptingPythonCore_INCLUDE_DIRS AND CTKScriptingPythonWidgets_INCLUDE_DIRS)
mitk_create_module(PythonService
INCLUDE_DIRS
PRIVATE src/PythonService
DEPENDS PUBLIC MitkPython
PACKAGE_DEPENDS
- PUBLIC Qt5|Widgets CTK|CTKScriptingPythonCore+CTKScriptingPythonWidgets
+ PUBLIC Qt6|Widgets CTK|CTKScriptingPythonCore+CTKScriptingPythonWidgets
PRIVATE Python3|NumPy
AUTOLOAD_WITH MitkPython
)
endif()
if(TARGET ${MODULE_TARGET})
configure_file(PythonPath.h.in "${CMAKE_CURRENT_BINARY_DIR}/PythonPath.h" @ONLY)
endif()
diff --git a/Modules/Python/documentation/mitkPython.dox b/Modules/Python/documentation/mitkPython.dox
index ce19e8112b..3aa0dc6657 100644
--- a/Modules/Python/documentation/mitkPython.dox
+++ b/Modules/Python/documentation/mitkPython.dox
@@ -1,47 +1,47 @@
/**
\page mitkPython_Overview Python Module
\section python_sec1 Brief description
The MITK Python Module provides a service class to interactively run python code (passed as C++ strings) and
evaluate the results. Furthermore the service class offers means to convert an MITK Image to an ITK/OpenCV image in their wrapped python environment.
<strong>Thus, one can process MITK images with Python Code from the OpenCV and ITK wrapping system</strong>.
Furthermore one can convert an mitk::Surface to a vtkPolyData in its Python environment.<br />
Under the hood, the MITK build system takes care that the wrapping build process for SimpleITK/VTK/OpenCV is correctly initiated and all paths are correctly set within MITK code.
To use the features of the different toolkits make sure they are enabled during the superbuild process.
\section python_sec2 Build Instructions
-Have a look at \ref python_sec3 on how to build MITK-Python with Qt5.
+Have a look at \ref python_sec3 on how to build MITK-Python with Qt6.
The following CMake build options are available:
<ul>
<li> MITK_USE_Python3
</ul>
\subsection python_ssec1 MITK_USE_Python3
MITK_USE_Python3 enables the python wrapping in MITK. When the option is activated
the build of the additional dependency SimpleITK is also enabled. The default behaviour is to use the python runtime from the system is used.
Only Python 3.x is supported.
The user can also specify it's own runtime by modifying the variables added by the
FindPythonLib.cmake script. <strong>Note:</strong> A Python runtime with numpy is needed to use the MITK Python wrapping.
When using this options all additional libraries installed in the python runtime will be available within the MITK-Python console.
\section python_sec3 Suported Data Types
The following data types in MITK are supported in the MITK Python Wrapping:
<ul>
<li> Image
<li> Surface
</ul>
\subsection python_ssec4 Image
Mitk Images can be transferred to python. The images are copied in-memory and
transferred as a numpy array to Python and vice versa. The MITK python wrapping creates a SimpleITK image
using the numpy array with the properties of the MITK Image. Two dimensional images
can also be transferred as an OpenCV image to python.
\subsection python_ssec5 Surface
Surfaces within mitk can be transferred as a vtkPolyData Object to Python.
The surfaces are fully memory mapped. When changing a python wrapped surface
the original object is also modified on the C++ side of MITK.
*/
diff --git a/Modules/QtOverlays/QmitkOverlayContainerWidget.h b/Modules/QtOverlays/QmitkOverlayContainerWidget.h
index 8165d3ccab..aad0d194fb 100644
--- a/Modules/QtOverlays/QmitkOverlayContainerWidget.h
+++ b/Modules/QtOverlays/QmitkOverlayContainerWidget.h
@@ -1,48 +1,48 @@
/*============================================================================
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 QmitkOverlayContainerWidget_h
#define QmitkOverlayContainerWidget_h
// Qt
#include <QWidget>
#include <MitkQtOverlaysExports.h>
/**
* \class QmitkOverlayContainerWidget
* \brief Widget that overrides the paintEvent method to correctly display
* the Qt based overlays when using the system-environment variable
* QT_DEVIDE_PIXEL_RATIO.
*/
class MITKQTOVERLAYS_EXPORT QmitkOverlayContainerWidget : public QWidget
{
public:
/**
* @brief Default Constructor
**/
- QmitkOverlayContainerWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkOverlayContainerWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
/**
* @brief Default Destructor
**/
~QmitkOverlayContainerWidget() override;
protected:
/**
* @brief overridden version of paintEvent that correctly clears its canvas before painting.
**/
void paintEvent(QPaintEvent *event) override;
};
#endif
diff --git a/Modules/QtOverlays/QmitkTextOverlay.cpp b/Modules/QtOverlays/QmitkTextOverlay.cpp
index ebdd4d7005..512e849693 100644
--- a/Modules/QtOverlays/QmitkTextOverlay.cpp
+++ b/Modules/QtOverlays/QmitkTextOverlay.cpp
@@ -1,159 +1,159 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkTextOverlay.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkPropertyList.h"
#include <itkCommand.h>
QmitkTextOverlay::QmitkTextOverlay(const char *id) : QmitkOverlay(id), m_ObservedProperty(nullptr), m_ObserverTag(0)
{
m_Widget = m_Label = new QLabel();
QmitkOverlay::AddDropShadow(m_Widget);
}
QmitkTextOverlay::~QmitkTextOverlay()
{
m_PropertyList->GetProperty(m_Id)->RemoveObserver(m_ObserverTag);
}
void QmitkTextOverlay::GenerateData(mitk::PropertyList::Pointer pl)
{
if (pl.IsNull())
return;
m_PropertyList = pl;
if (m_PropertyList.IsNotNull())
{
this->SetupCallback(m_PropertyList->GetProperty(m_Id));
this->UpdateFontProperties(pl);
this->UpdateDisplayedTextFromProperties();
}
else
{
MITK_ERROR << "invalid propList";
}
}
void QmitkTextOverlay::UpdateDisplayedTextFromProperties()
{
std::string text;
if (m_PropertyList.IsNull() || !m_PropertyList->GetStringProperty(m_Id, text))
{
MITK_DEBUG << "Property " << m_Id << " could not be found";
}
if (text != m_Label->text().toStdString())
{
m_Label->setText(text.c_str());
m_Label->repaint();
}
}
void QmitkTextOverlay::UpdateFontProperties(mitk::PropertyList::Pointer pl)
{
if (pl.IsNull())
return;
mitk::PropertyList::Pointer propertyList = pl;
QPalette palette = QPalette();
QFont font = QFont();
// get the desired color of the textOverlays
mitk::ColorProperty::Pointer colorProp =
dynamic_cast<mitk::ColorProperty *>(propertyList->GetProperty("overlay.color"));
if (colorProp.IsNull())
{
colorProp = mitk::ColorProperty::New(127.0, 196.0, 232.0);
}
mitk::Color color = colorProp->GetColor();
- palette.setColor(QPalette::Foreground, QColor(color[0], color[1], color[2], 255));
+ palette.setColor(QPalette::WindowText, QColor(color[0], color[1], color[2], 255));
palette.setColor(QPalette::Window, Qt::transparent);
m_Label->setPalette(palette);
// get the desired opacity of the overlays
// mitk::FloatProperty::Pointer opacityProperty =
// dynamic_cast<mitk::FloatProperty*>( propertyList->GetProperty( "overlay.opacity" ) );
// if ( opacityProperty.IsNull() )
//{
// m_Label->setWindowOpacity( 1 );
//}
// else
//{
// m_Label->setWindowOpacity( opacityProperty->GetValue() );
//}
// set the desired font-size of the overlays
int fontSize = 0;
if (!propertyList->GetIntProperty("overlay.fontSize", fontSize))
{
fontSize = 9;
}
font.setPointSize(fontSize);
bool useKerning = false;
if (!propertyList->GetBoolProperty("overlay.kerning", useKerning))
{
useKerning = true;
}
font.setKerning(useKerning);
std::string fontFamily = "";
if (!propertyList->GetStringProperty("overlay.fontFamily", fontFamily))
{
fontFamily = "Verdana";
}
font.setFamily(QString(fontFamily.c_str()));
m_Label->setFont(font);
}
void QmitkTextOverlay::SetupCallback(mitk::BaseProperty::Pointer prop)
{
if (m_ObservedProperty != prop && m_ObserverTag == 0)
{
if (prop.IsNotNull())
{
if (m_ObservedProperty.IsNotNull())
{
m_ObservedProperty->RemoveObserver(m_ObserverTag);
}
typedef itk::SimpleMemberCommand<QmitkTextOverlay> MemberCommandType;
MemberCommandType::Pointer propModifiedCommand;
propModifiedCommand = MemberCommandType::New();
propModifiedCommand->SetCallbackFunction(this, &QmitkTextOverlay::UpdateDisplayedTextFromProperties);
m_ObserverTag = prop->AddObserver(itk::ModifiedEvent(), propModifiedCommand);
}
m_ObservedProperty = prop;
}
else
{
MITK_DEBUG << "invalid property";
}
}
QSize QmitkTextOverlay::GetNeededSize()
{
QFont font = m_Label->font();
QFontMetrics fm(font);
return fm.size(Qt::TextSingleLine, m_Label->text());
}
diff --git a/Modules/QtPython/CMakeLists.txt b/Modules/QtPython/CMakeLists.txt
index c22ed5a8db..5eb9c46d4e 100644
--- a/Modules/QtPython/CMakeLists.txt
+++ b/Modules/QtPython/CMakeLists.txt
@@ -1,15 +1,15 @@
if(MITK_USE_Python3)
mitkFunctionCheckCompilerFlags("/wd4273" CMAKE_CXX_FLAGS)
if(CTKScriptingPythonCore_INCLUDE_DIRS AND CTKScriptingPythonWidgets_INCLUDE_DIRS)
mitk_create_module(
DEPENDS MitkCore MitkQtWidgets MitkPython
PACKAGE_DEPENDS
- PUBLIC Qt5|Widgets CTK|CTKScriptingPythonCore+CTKScriptingPythonWidgets
+ PUBLIC Qt6|Widgets CTK|CTKScriptingPythonCore+CTKScriptingPythonWidgets
)
endif()
if(BUILD_TESTING AND TARGET ${MODULE_TARGET})
add_subdirectory(Testing)
endif()
endif()
diff --git a/Modules/QtPython/Testing/CMakeLists.txt b/Modules/QtPython/Testing/CMakeLists.txt
index e9cde47bc8..9b997160ff 100644
--- a/Modules/QtPython/Testing/CMakeLists.txt
+++ b/Modules/QtPython/Testing/CMakeLists.txt
@@ -1,19 +1,19 @@
set(package_deps PACKAGE_DEPENDS PRIVATE)
MITK_CREATE_MODULE_TESTS(${package_deps})
if(UNIX AND NOT APPLE)
#[[ The PythonQt library (dependency of MitkQtPython module) depends on Qt
libraries without absolute paths. Use LD_LIBRARY_PATH as workaround.
See T26955. ]]
if(TARGET ${TESTDRIVER})
- get_target_property(ld_library_path Qt5::Core IMPORTED_LOCATION_RELEASE)
+ get_target_property(ld_library_path Qt6::Core IMPORTED_LOCATION_RELEASE)
get_filename_component(ld_library_path "${ld_library_path}" DIRECTORY)
add_test(
NAME mitkPythonTest
COMMAND ${CMAKE_COMMAND} -E env "LD_LIBRARY_PATH=${ld_library_path}"
${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTDRIVER} mitkPythonTest
)
endif()
endif()
diff --git a/Modules/QtWidgets/CMakeLists.txt b/Modules/QtWidgets/CMakeLists.txt
index 8d685ebd5c..9a160b1e60 100644
--- a/Modules/QtWidgets/CMakeLists.txt
+++ b/Modules/QtWidgets/CMakeLists.txt
@@ -1,9 +1,9 @@
MITK_CREATE_MODULE(
INCLUDE_DIRS PRIVATE resource # for xpm includes
DEPENDS MitkPlanarFigure MitkAnnotation
PACKAGE_DEPENDS
- PUBLIC VTK|GUISupportQt+RenderingQt Qt5|Widgets+OpenGL+Core CTK|CTKWidgets
+ PUBLIC VTK|GUISupportQt+RenderingQt Qt6|Widgets+OpenGL+Core CTK|CTKWidgets
PRIVATE nlohmann_json
)
add_subdirectory(test)
diff --git a/Modules/QtWidgets/include/QmitkAbstractMultiWidget.h b/Modules/QtWidgets/include/QmitkAbstractMultiWidget.h
index 1b927645c3..93377e60de 100644
--- a/Modules/QtWidgets/include/QmitkAbstractMultiWidget.h
+++ b/Modules/QtWidgets/include/QmitkAbstractMultiWidget.h
@@ -1,191 +1,191 @@
/*============================================================================
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 QmitkAbstractMultiWidget_h
#define QmitkAbstractMultiWidget_h
// mitk qt widgets module
#include "MitkQtWidgetsExports.h"
// mitk core
#include <mitkBaseRenderer.h>
#include <mitkDisplayActionEventHandler.h>
#include <mitkInteractionSchemeSwitcher.h>
#include <mitkPoint.h>
// qt
#include <QWidget>
// c++
#include <map>
#include <memory>
class QmitkMultiWidgetLayoutManager;
class QmitkRenderWindow;
class QmitkRenderWindowWidget;
namespace mitk
{
class DataStorage;
class InteractionEventHandler;
}
/**
* @brief The 'QmitkAbstractMultiWidget' is a 'QWidget' that can be subclassed to display multiple render windows at once.
* Render windows can dynamically be added and removed to change the layout of the multi widget.
* A subclass of this multi widget can be used inside a 'QmitkAbstractMultiWidgetEditor'.
*
* The class uses the 'DisplayActionEventBroadcast' and 'DisplayActionEventHandler' classes to
* load a state machine and set an event configuration.
*
* Using the 'Synchronize' function the user can enable or disable the synchronization of display action events.
* See 'DisplayActionEventFunctions'-class for the different synchronized and non-synchronized functions used.
*/
class MITKQTWIDGETS_EXPORT QmitkAbstractMultiWidget : public QWidget
{
Q_OBJECT
public:
using RenderWindowWidgetPointer = std::shared_ptr<QmitkRenderWindowWidget>;
using RenderWindowWidgetMap = std::map<QString, std::shared_ptr<QmitkRenderWindowWidget>>;
using RenderWindowHash = QHash<QString, QmitkRenderWindow*>;
QmitkAbstractMultiWidget(QWidget* parent = 0,
- Qt::WindowFlags f = 0,
+ Qt::WindowFlags f = {},
const QString& multiWidgetName = "multiwidget");
virtual ~QmitkAbstractMultiWidget();
virtual void InitializeMultiWidget() = 0;
virtual void MultiWidgetOpened() { }
virtual void MultiWidgetClosed() { }
virtual void SetDataStorage(mitk::DataStorage* dataStorage);
mitk::DataStorage* GetDataStorage() const;
int GetRowCount() const;
int GetColumnCount() const;
virtual void SetLayout(int row, int column);
virtual void Synchronize(bool) { };
virtual void SetInteractionScheme(mitk::InteractionSchemeSwitcher::InteractionScheme scheme);
mitk::InteractionEventHandler* GetInteractionEventHandler();
void SetDisplayActionEventHandler(std::unique_ptr<mitk::DisplayActionEventHandler> displayActionEventHandler);
mitk::DisplayActionEventHandler* GetDisplayActionEventHandler();
RenderWindowWidgetMap GetRenderWindowWidgets() const;
RenderWindowWidgetMap Get2DRenderWindowWidgets() const;
RenderWindowWidgetMap Get3DRenderWindowWidgets() const;
RenderWindowWidgetPointer GetRenderWindowWidget(int row, int column) const;
RenderWindowWidgetPointer GetRenderWindowWidget(const QString& widgetName) const;
RenderWindowWidgetPointer GetRenderWindowWidget(const QmitkRenderWindow* renderWindow) const;
RenderWindowHash GetRenderWindows() const;
QmitkRenderWindow* GetRenderWindow(int row, int column) const;
virtual QmitkRenderWindow* GetRenderWindow(const QString& widgetName) const;
virtual QmitkRenderWindow* GetRenderWindow(const mitk::AnatomicalPlane& orientation) const = 0;
virtual void SetActiveRenderWindowWidget(RenderWindowWidgetPointer activeRenderWindowWidget);
RenderWindowWidgetPointer GetActiveRenderWindowWidget() const;
RenderWindowWidgetPointer GetFirstRenderWindowWidget() const;
RenderWindowWidgetPointer GetLastRenderWindowWidget() const;
virtual QString GetNameFromIndex(int row, int column) const;
virtual QString GetNameFromIndex(size_t index) const;
unsigned int GetNumberOfRenderWindowWidgets() const;
void RequestUpdate(const QString& widgetName);
void RequestUpdateAll();
void ForceImmediateUpdate(const QString& widgetName);
void ForceImmediateUpdateAll();
/**
* @brief Initialize the render windows of the concrete multi widget to the given geometry.
*
* The concrete implementation is subclass-specific, no default implementation is provided here.
*
* @param geometry The geometry to be used to initialize / update the
* render window's time and slice navigation controller.
* @param resetCamera If true, the camera and crosshair will be reset to the default view (centered, no zoom).
* If false, the current crosshair position and the camera zoom will be stored and reset
* after the reference geometry has been updated.
*/
virtual void InitializeViews(const mitk::TimeGeometry* geometry, bool resetCamera) = 0;
/**
* @brief Define the reference geometry for interaction withing a render window.
*
* The concrete implementation is subclass-specific, no default implementation is provided here.
*
* @param referenceGeometry The interaction reference geometry for the base renderer of the concrete multi widget.
* For more details, see 'BaseRenderer::SetInteractionReferenceGeometry'.
*/
virtual void SetInteractionReferenceGeometry(const mitk::TimeGeometry* referenceGeometry) = 0;
/**
* @brief Returns true if the render windows are coupled; false if not.
*
* Render windows are coupled if the slice navigation controller of the render windows
* are connected which means that always the same geometry is used for the render windows.
*/
virtual bool HasCoupledRenderWindows() const = 0;
virtual void SetSelectedPosition(const mitk::Point3D& newPosition, const QString& widgetName) = 0;
virtual const mitk::Point3D GetSelectedPosition(const QString& widgetName) const = 0;
virtual void SetCrosshairVisibility(bool visible) = 0;
virtual bool GetCrosshairVisibility() const = 0;
virtual void SetCrosshairGap(unsigned int gapSize) = 0;
virtual void ResetCrosshair() = 0;
virtual void SetWidgetPlaneMode(int mode) = 0;
virtual void ActivateMenuWidget(bool state);
virtual bool IsMenuWidgetEnabled() const;
QmitkMultiWidgetLayoutManager* GetMultiWidgetLayoutManager() const;
signals:
void ActiveRenderWindowChanged();
private slots:
void OnFocusChanged(itk::Object*, const itk::EventObject& event);
protected:
virtual void AddRenderWindowWidget(const QString& widgetName, RenderWindowWidgetPointer renderWindowWidget);
virtual void RemoveRenderWindowWidget();
private:
/**
* @brief This function will be called by the function 'SetLayout' and
* can be implemented and customized in the subclasses.
*/
virtual void SetLayoutImpl() = 0;
/**
* @brief This function will be called by the function 'SetInteractionScheme' and
* can be implemented and customized in the subclasses.
*/
virtual void SetInteractionSchemeImpl() = 0;
struct Impl;
std::unique_ptr<Impl> m_Impl;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkIOUtil.h b/Modules/QtWidgets/include/QmitkIOUtil.h
index 2baa1cc464..47ca03ac63 100644
--- a/Modules/QtWidgets/include/QmitkIOUtil.h
+++ b/Modules/QtWidgets/include/QmitkIOUtil.h
@@ -1,238 +1,237 @@
/*============================================================================
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 QmitkIOUtil_h
#define QmitkIOUtil_h
#include "MitkQtWidgetsExports.h"
// std
#include <string>
// mitk includes
#include <mitkBaseData.h>
#include <mitkCommon.h>
#include <mitkDataNode.h>
#include <mitkFileWriterWithInformation.h>
#include <mitkIOUtil.h>
#include <mitkImage.h>
#include <mitkPointSet.h>
#include <mitkSurface.h>
// Qt
#include <QList>
#include <QPair>
#include <QScopedPointer>
#include <QString>
class QWidget;
class QString;
-class QStringList;
namespace mitk
{
class DataStorage;
class MimeType;
struct IFileReader;
}
/**
* @brief QmitkIOUtil Provides static helper methods to open and save files with Qt dialogs.
*/
class MITKQTWIDGETS_EXPORT QmitkIOUtil : public mitk::IOUtil
{
public:
class MITKQTWIDGETS_EXPORT SaveFilter
{
public:
static mitk::MimeType ALL_MIMETYPE();
SaveFilter(const SaveFilter &other);
SaveFilter(const SaveInfo &saveInfo);
SaveFilter &operator=(const SaveFilter &other);
std::vector<mitk::MimeType> GetMimeTypes() const;
QString GetFilterForMimeType(const std::string &mimeType) const;
mitk::MimeType GetMimeTypeForFilter(const QString &filter) const;
QString GetDefaultFilter() const;
QString GetDefaultExtension() const;
mitk::MimeType GetDefaultMimeType() const;
QString ToString() const;
int Size() const;
bool IsEmpty() const;
bool ContainsMimeType(const std::string &mimeType);
private:
struct Impl;
QScopedPointer<Impl> d;
};
/**
* @brief GetFilterString
* @return
*/
static QString GetFileOpenFilterString();
/**
* @brief Loads the specified files
*
* This methods tries to load all specified files and pop-ups dialog boxes if further
* user input is required (e.g. ambiguous mime-types or reader options).
*
* If the provided DataStorage is not nullptr, some files will be added to it automatically,
* dependeing on the IFileReader used.
*
* @param paths
* @param parent
* @return A list of BaseData instances which have not already been added to the data storage.
*/
static QList<mitk::BaseData::Pointer> Load(const QStringList &paths, QWidget *parent = nullptr);
static mitk::DataStorage::SetOfObjects::Pointer Load(const QStringList &paths,
mitk::DataStorage &storage,
QWidget *parent = nullptr);
static QList<mitk::BaseData::Pointer> Load(const QString &path, QWidget *parent = nullptr);
static mitk::DataStorage::SetOfObjects::Pointer Load(const QString &path,
mitk::DataStorage &storage,
QWidget *parent = nullptr);
using mitk::IOUtil::Load;
static QString Save(const mitk::BaseData *data,
const QString &defaultBaseName,
const QString &defaultPath = QString(),
QWidget *parent = nullptr,
bool setPathProperty = false);
/**
* @brief Save a list of BaseData objects using a "File Save Dialog".
*
* For each element in the \c data vector, the following algorithm is
* used to find a IFileWriter instance for writing the BaseData object.
*
* First, the user is prompted to select file names for each BaseData object. This
* is equivalent to choosing a specific mime-type, either by selecting a filter
* in the save dialog or by explicitly providing a file name extension:
* <ol>
* <li>Get a list of registered IFileWriter objects for the current BaseData object.
* If no writers are found, a message box displays a warning and
* the process starts from the beginning for the next BaseData object.</li>
* <li>A QFileDialog for prompting the user to select a file name is opened.
* The mime-type associated with each IFileWriter object is used to create
* a filter for file name extensions.
* The best IFileWriter (see FileWriterSelector) for the current BaseData object
* defines the default file name suffix via its associated mime-type. If the
* file name is empty (the user cancelled the dialog), the remaining
* BaseData objects are skipped.
* <li>The file name is matched against valid mime-types. The first mime-type
* which accepts the file name is associated with the current BaseData object.
* If no mime-type accepts the supplied file name and the file already
* exists, the process starts from the beginning with the next BaseData object.
* Otherwise, if the selected filter is the special "all" filter and the
* file name does not contain periods (which may or may not mark the start of
* a file extension), the current BaseData object is associated with the
* default mime-type. If the selected filter is not the special "all" filter,
* the mime-type for this filter is associated with the current BaseData object.
* The default extension of the associated mime-type is then appended to the
* supplied file name.
* <li>The selected/derived file name and associated mime-type is stored in a list
* and the process starts from the beginning for the next BaseData object.</li>
* </ol>
*
* In the second phase, each BaseData object is saved to disk using the specified
* file name and mime-type, according to the following procedure:
* <ol>
* <li>If multiple IFileWriter objects are compatible with the current base data
* object or if the single compatible IFileWriter provides configuration
* options, a dialog window containing a list of IFileWriter objects and
* configurable options is displayed. If the dialog is cancelled by the user,
* neither the current nor the remaining base data objects are saved to disk.
* If the user previously in this phase enabled the "remember options" checkbox
* of the dialog, then the dialog is not shown for base data objects with the
* same data type and associated mime-type if the file writer instance reports
* a higher or equal confidence level for the current base data object.</li>
* <li>The selected writer (either the only available one or the user selected one)
* is used to write the base data object to disk. On failure, an error is
* reported and the second phase continues with the next base data object.</li>
* </ol>
*
* @param data
* @param defaultBaseNames
* @param defaultPath
* @param parent
* @param setPathProperty
* @return
*/
static QStringList Save(const std::vector<const mitk::BaseData *> &data,
const QStringList &defaultBaseNames,
const QString &defaultPath = QString(),
QWidget *parent = nullptr,
bool setPathProperty = false);
using mitk::IOUtil::Save;
/**
* @brief SaveBaseDataWithDialog Convenience method to save any data with a Qt dialog.
* @param data BaseData holding the data you wish to save.
* @param fileName The file name where to save the data (including path and extension).
* @param parent An optional QWidget as parent. If no parent is supplied, the QFileDialog can occur anywhere on the
* screen.
* @deprecatedSince{2014_10} Use Save() instead.
*/
DEPRECATED(static void SaveBaseDataWithDialog(mitk::BaseData *data, std::string fileName, QWidget *parent = nullptr));
/**
* @brief SaveSurfaceWithDialog Convenience method to save a surface with a Qt dialog.
* @param surface The surface to save.
* @param fileName The file name where to save the data (including path and extension).
* @param parent An optional QWidget as parent. If no parent is supplied, the QFileDialog can occur anywhere on the
* screen.
* @deprecatedSince{2014_10} Use Save() instead.
*/
DEPRECATED(static void SaveSurfaceWithDialog(mitk::Surface::Pointer surface,
std::string fileName = "",
QWidget *parent = nullptr));
/**
* @brief SaveImageWithDialog Convenience method to save an image with a Qt dialog.
* @param image The image to save.
* @param fileName The file name where to save the data (including path and extension).
* @param parent An optional QWidget as parent. If no parent is supplied, the QFileDialog can occur anywhere on the
* screen.
* @deprecatedSince{2014_10} Use Save() instead.
*/
DEPRECATED(static void SaveImageWithDialog(mitk::Image::Pointer image,
std::string fileName = "",
QWidget *parent = nullptr));
/**
* @brief SavePointSetWithDialog Convenience method to save a pointset with a Qt dialog.
* @param pointset The pointset to save.
* @param fileName The file name where to save the data (including path and extension).
* @param parent An optional QWidget as parent. If no parent is supplied, the QFileDialog can occur anywhere on the
* screen.
* @deprecatedSince{2014_10} Use Save() instead.
*/
DEPRECATED(static void SavePointSetWithDialog(mitk::PointSet::Pointer pointset,
std::string fileName = "",
QWidget *parent = nullptr));
private:
struct Impl;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkLevelWindowPresetDefinitionDialog.h b/Modules/QtWidgets/include/QmitkLevelWindowPresetDefinitionDialog.h
index eb432cfb6c..c16c98ade2 100644
--- a/Modules/QtWidgets/include/QmitkLevelWindowPresetDefinitionDialog.h
+++ b/Modules/QtWidgets/include/QmitkLevelWindowPresetDefinitionDialog.h
@@ -1,101 +1,101 @@
/*============================================================================
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 QmitkLevelWindowPresetDefinitionDialog_h
#define QmitkLevelWindowPresetDefinitionDialog_h
#include <MitkQtWidgetsExports.h>
#include "ui_QmitkLevelWindowPresetDefinition.h"
#include <QDialog>
#include <QSortFilterProxyModel>
#include <map>
#include <string>
/// \ingroup QmitkModule
class MITKQTWIDGETS_EXPORT QmitkLevelWindowPresetDefinitionDialog : public QDialog,
public Ui::QmitkLevelWindowPresetDefinition
{
Q_OBJECT
public:
- QmitkLevelWindowPresetDefinitionDialog(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkLevelWindowPresetDefinitionDialog(QWidget *parent = nullptr, Qt::WindowFlags f = {});
~QmitkLevelWindowPresetDefinitionDialog() override;
void setPresets(std::map<std::string, double> &level,
std::map<std::string, double> &window,
QString initLevel,
QString initWindow);
std::map<std::string, double> getLevelPresets();
std::map<std::string, double> getWindowPresets();
protected slots:
void addPreset();
void removePreset();
void changePreset();
void ListViewSelectionChanged(const QItemSelection &, const QItemSelection &);
void sortPresets(int index);
protected:
class PresetTableModel : public QAbstractTableModel
{
public:
struct Entry
{
std::string name;
double level;
double window;
Entry(const std::string &n, double l, double w) : name(n), level(l), window(w) {}
};
PresetTableModel(std::map<std::string, double> &levels,
std::map<std::string, double> &windows,
QObject *parent = nullptr);
int rowCount(const QModelIndex &) const override;
int columnCount(const QModelIndex &) const override;
QVariant data(const QModelIndex &index, int) const override;
QVariant headerData(int section, Qt::Orientation orientation, int) const override;
void addPreset(std::string &name, double level, double window);
void removePreset(const QModelIndex &);
void changePreset(int row, std::string &name, double level, double window);
void getLevels(std::map<std::string, double> &levels);
void getWindows(std::map<std::string, double> &windows);
bool contains(std::string &name);
Entry getPreset(const QModelIndex &) const;
private:
std::vector<Entry> m_Entries;
};
void resizeEvent(QResizeEvent *event) override;
void showEvent(QShowEvent *event) override;
void resizeColumns();
PresetTableModel *m_TableModel;
QSortFilterProxyModel m_SortModel;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkLevelWindowRangeChangeDialog.h b/Modules/QtWidgets/include/QmitkLevelWindowRangeChangeDialog.h
index 54d9f0aac5..58bb9a7ba1 100644
--- a/Modules/QtWidgets/include/QmitkLevelWindowRangeChangeDialog.h
+++ b/Modules/QtWidgets/include/QmitkLevelWindowRangeChangeDialog.h
@@ -1,43 +1,43 @@
/*============================================================================
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 QmitkLevelWindowRangeChangeDialog_h
#define QmitkLevelWindowRangeChangeDialog_h
#include <MitkQtWidgetsExports.h>
#include "ui_QmitkLevelWindowRangeChange.h"
#include <QDialog>
/// \ingroup QmitkModule
class MITKQTWIDGETS_EXPORT QmitkLevelWindowRangeChangeDialog : public QDialog, public Ui::QmitkLevelWindowRangeChange
{
Q_OBJECT
public:
- QmitkLevelWindowRangeChangeDialog(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkLevelWindowRangeChangeDialog(QWidget *parent = nullptr, Qt::WindowFlags f = {});
double getLowerLimit();
double getUpperLimit();
void setLowerLimit(double rangeMin);
void setUpperLimit(double rangeMax);
protected slots:
void inputValidator();
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkLevelWindowWidget.h b/Modules/QtWidgets/include/QmitkLevelWindowWidget.h
index 1dce4bebdc..a4f879a8bb 100644
--- a/Modules/QtWidgets/include/QmitkLevelWindowWidget.h
+++ b/Modules/QtWidgets/include/QmitkLevelWindowWidget.h
@@ -1,49 +1,49 @@
/*============================================================================
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 QmitkLevelWindowWidget_h
#define QmitkLevelWindowWidget_h
#include <MitkQtWidgetsExports.h>
#include <mitkLevelWindowManager.h>
#include <QWidget>
// Forward declarations
namespace Ui
{
class QmitkLevelWindow;
}
/// \ingroup QmitkModule
class MITKQTWIDGETS_EXPORT QmitkLevelWindowWidget : public QWidget
{
Q_OBJECT
public:
- QmitkLevelWindowWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkLevelWindowWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
~QmitkLevelWindowWidget() override;
mitk::LevelWindowManager *GetManager();
public slots:
void SetDataStorage(mitk::DataStorage *ds);
protected:
// unsigned long m_ObserverTag;
mitk::LevelWindowManager::Pointer m_Manager;
private:
// GUI controls of this plugin
Ui::QmitkLevelWindow* ui;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkLevelWindowWidgetContextMenu.h b/Modules/QtWidgets/include/QmitkLevelWindowWidgetContextMenu.h
index 614fe26fcb..cb847c209d 100644
--- a/Modules/QtWidgets/include/QmitkLevelWindowWidgetContextMenu.h
+++ b/Modules/QtWidgets/include/QmitkLevelWindowWidgetContextMenu.h
@@ -1,117 +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 QmitkLevelWindowWidgetContextMenu_h
#define QmitkLevelWindowWidgetContextMenu_h
#include <MitkQtWidgetsExports.h>
#include <QMenu>
#include <mitkLevelWindowManager.h>
#include <mitkLevelWindowPreset.h>
/**
* \ingroup QmitkModule
* \brief Provides a contextmenu for Level/Window functionality.
*
* Either creates
* a new contextmenu with standard functions or adds Level/Window standard
* functions to an predefined contextmenu.
*/
class MITKQTWIDGETS_EXPORT QmitkLevelWindowWidgetContextMenu : public QWidget
{
Q_OBJECT
public:
/// constructor
- QmitkLevelWindowWidgetContextMenu(QWidget *parent, Qt::WindowFlags f = nullptr);
+ QmitkLevelWindowWidgetContextMenu(QWidget *parent, Qt::WindowFlags f = {});
~QmitkLevelWindowWidgetContextMenu() override;
/*!
* data structure which reads and writes presets defined in a XML-file
*/
mitk::LevelWindowPreset *m_LevelWindowPreset;
/*!
* data structure which stores the values manipulated
* by a QmitkLevelWindowWidgetContextMenu
*/
mitk::LevelWindow m_LevelWindow;
/// submenu with all presets for contextmenu
QMenu *m_PresetSubmenu;
/// submenu with all images for contextmenu
QMenu *m_ImageSubmenu;
/// pointer to the object which manages all Level/Window changes on images and holds the LevelWindowProperty
/// of the current image
mitk::LevelWindowManager *m_Manager;
/// map to hold all image-properties, one can get the image which is selected in the contextmenu
/// with the QAction representing the image for the contextmenu
std::map<QAction *, mitk::LevelWindowProperty::Pointer> m_Images;
/*!
* returns the contextmenu with standard functions for Level/Window
*
* input is a prefilled contextmenu to which standard functions will be added
*/
void GetContextMenu(QMenu *contextMenu);
/// returns the contextmenu with standard functions for Level/Window
void GetContextMenu();
/// lets this object know about the LevelWindowManager to get all images and tell about changes
void SetLevelWindowManager(mitk::LevelWindowManager *levelWindowManager);
protected:
QAction *m_PresetAction;
QAction *m_AutoTopmostAction;
QAction *m_SelectedImagesAction;
protected Q_SLOTS:
/// sets level and window value of the current image to the values defined for the selected preset
void OnSetPreset(const QAction *presetAction);
/// calls the mitkLevelWindow SetAuto method with guessByCentralSlice false, so that the greyvalues from whole image
/// will be considered
void OnUseOptimizedLevelWindow();
/// calls the mitkLevelWindow SetToImageRange method, so that the greyvalues from whole image will be used
void OnUseAllGreyvaluesFromImage();
/// sets the level window slider to be fixed
void OnSetFixed();
/// adds a new Preset for presets-contextmenu
void OnAddPreset();
/// resets the current images Level/Window to its default values
void OnSetDefaultLevelWindow();
/// resets the current images scalerange to its default values
void OnSetDefaultScaleRange();
/// changes the current images scalerange
void OnChangeScaleRange();
/// sets the selected image or the topmost layer image to the new current image
void OnSetImage(QAction *imageAction);
/// sets the window to its maximum Size to fit the scalerange
void OnSetMaximumWindow();
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkLineEditLevelWindowWidget.h b/Modules/QtWidgets/include/QmitkLineEditLevelWindowWidget.h
index fdf365fe51..b271875b19 100644
--- a/Modules/QtWidgets/include/QmitkLineEditLevelWindowWidget.h
+++ b/Modules/QtWidgets/include/QmitkLineEditLevelWindowWidget.h
@@ -1,93 +1,93 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkLineEditLevelWindowWidget_h
#define QmitkLineEditLevelWindowWidget_h
#include <MitkQtWidgetsExports.h>
// mitk core
#include <mitkLevelWindowManager.h>
// qt
#include <QWidget>
class QmitkLevelWindowWidgetContextMenu;
class QLineEdit;
/**
* \ingroup QmitkModule
* \brief Provides a widget with two lineedit fields, one to change the
* window value of the current image and one to change the level value of
* the current image.
*/
class MITKQTWIDGETS_EXPORT QmitkLineEditLevelWindowWidget : public QWidget
{
Q_OBJECT
public:
/// constructor
- QmitkLineEditLevelWindowWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkLineEditLevelWindowWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
/// destructor
~QmitkLineEditLevelWindowWidget() override;
/// inputfield for level value
QLineEdit *m_LevelInput;
/// inputfield for window value
QLineEdit *m_WindowInput;
/*!
* data structure which stores the values manipulated
* by a QmitkLineEditLevelWindowWidget
*/
mitk::LevelWindow m_LevelWindow;
/// manager who is responsible to collect and deliver changes on Level/Window
mitk::LevelWindowManager::Pointer m_Manager;
/// sets the manager who is responsible to collect and deliver changes on Level/Window
void SetLevelWindowManager(mitk::LevelWindowManager *levelWindowManager);
/// sets the DataStorage which holds all image-nodes
void SetDataStorage(mitk::DataStorage *ds);
/// returns the manager who is responsible to collect and deliver changes on Level/Window
mitk::LevelWindowManager *GetManager();
private:
/// creates the contextmenu for this widget from class QmitkLevelWindowWidgetContextMenu
void contextMenuEvent(QContextMenuEvent *) override;
/// change notifications from the mitkLevelWindowManager
void OnPropertyModified(const itk::EventObject &e);
public Q_SLOTS:
/** @brief Read the levelInput and change level and slider when the button "ENTER" was pressed
* in the windowInput-LineEdit.
*/
void SetLevelValue();
/** @brief Read the windowInput and change window and slider when the button "ENTER" was pressed
* in the windowInput-LineEdit.
*/
void SetWindowValue();
protected:
unsigned long m_ObserverTag;
bool m_IsObserverTagSet;
QmitkLevelWindowWidgetContextMenu *m_Contextmenu;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkMxNMultiWidget.h b/Modules/QtWidgets/include/QmitkMxNMultiWidget.h
index 9ae1bc0ab7..92d5e7a7b5 100644
--- a/Modules/QtWidgets/include/QmitkMxNMultiWidget.h
+++ b/Modules/QtWidgets/include/QmitkMxNMultiWidget.h
@@ -1,131 +1,131 @@
/*============================================================================
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 QmitkMxNMultiWidget_h
#define QmitkMxNMultiWidget_h
#include "MitkQtWidgetsExports.h"
// qt widgets module
#include "QmitkAbstractMultiWidget.h"
#include <QmitkSynchronizedNodeSelectionWidget.h>
#include <QmitkSynchronizedWidgetConnector.h>
#include <nlohmann/json.hpp>
class QSplitter;
/**
* @brief The 'QmitkMxNMultiWidget' is a 'QmitkAbstractMultiWidget' that is used to display multiple render windows at once.
* Render windows can dynamically be added and removed to change the layout of the multi widget. This
* is done by using the 'SetLayout'-function to define a layout. This will automatically add or remove
* the appropriate number of render window widgets.
*/
class MITKQTWIDGETS_EXPORT QmitkMxNMultiWidget : public QmitkAbstractMultiWidget
{
Q_OBJECT
public:
QmitkMxNMultiWidget(QWidget* parent = nullptr,
- Qt::WindowFlags f = 0,
+ Qt::WindowFlags f = {},
const QString& multiWidgetName = "mxn");
~QmitkMxNMultiWidget();
void InitializeMultiWidget() override;
void Synchronize(bool synchronized) override;
QmitkRenderWindow* GetRenderWindow(const QString& widgetName) const override;
QmitkRenderWindow* GetRenderWindow(const mitk::AnatomicalPlane& orientation) const override;
void SetActiveRenderWindowWidget(RenderWindowWidgetPointer activeRenderWindowWidget) override;
/**
* @brief Initialize the active render windows of the MxNMultiWidget to the given geometry.
*
* @param geometry The geometry to be used to initialize / update the
* active render window's time and slice navigation controller.
* @param resetCamera If true, the camera and crosshair will be reset to the default view (centered, no zoom).
* If false, the current crosshair position and the camera zoom will be stored and reset
* after the reference geometry has been updated.
*/
void InitializeViews(const mitk::TimeGeometry* geometry, bool resetCamera) override;
/**
* @brief Forward the given time geometry to all base renderers, so that they can store it as their
* interaction reference geometry.
* This will update the alignment status of the reference geometry for each base renderer.
* For more details, see 'BaseRenderer::SetInteractionReferenceGeometry'.
* Overridem from 'QmitkAbstractMultiWidget'.
*/
void SetInteractionReferenceGeometry(const mitk::TimeGeometry* referenceGeometry) override;
/**
* @brief Returns true if the render windows are coupled; false if not.
*
* For the MxNMultiWidget the render windows are typically decoupled.
*/
bool HasCoupledRenderWindows() const override;
void SetSelectedPosition(const mitk::Point3D& newPosition, const QString& widgetName) override;
const mitk::Point3D GetSelectedPosition(const QString& widgetName) const override;
void SetCrosshairVisibility(bool visible) override;
bool GetCrosshairVisibility() const override;
void SetCrosshairGap(unsigned int gapSize) override;
void ResetCrosshair() override;
void SetWidgetPlaneMode(int userMode) override;
mitk::SliceNavigationController* GetTimeNavigationController();
void EnableCrosshair();
void DisableCrosshair();
public Q_SLOTS:
// mouse events
void wheelEvent(QWheelEvent* e) override;
void mousePressEvent(QMouseEvent* e) override;
void moveEvent(QMoveEvent* e) override;
void LoadLayout(const nlohmann::json* jsonData);
void SaveLayout(std::ostream* outStream);
Q_SIGNALS:
void WheelMoved(QWheelEvent *);
void Moved();
void UpdateUtilityWidgetViewPlanes();
void LayoutChanged();
private:
void SetLayoutImpl() override;
void SetInteractionSchemeImpl() override { }
QmitkAbstractMultiWidget::RenderWindowWidgetPointer CreateRenderWindowWidget();
void SetInitialSelection();
void ToggleSynchronization(QmitkSynchronizedNodeSelectionWidget* synchronizedWidget);
static nlohmann::json BuildJSONFromLayout(const QSplitter* splitter);
QSplitter* BuildLayoutFromJSON(const nlohmann::json* jsonData, unsigned int* windowCounter, QSplitter* parentSplitter = nullptr);
std::unique_ptr<QmitkSynchronizedWidgetConnector> m_SynchronizedWidgetConnector;
bool m_CrosshairVisibility;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkNodeDetailsDialog.h b/Modules/QtWidgets/include/QmitkNodeDetailsDialog.h
index 855ba32b18..15dea093b2 100644
--- a/Modules/QtWidgets/include/QmitkNodeDetailsDialog.h
+++ b/Modules/QtWidgets/include/QmitkNodeDetailsDialog.h
@@ -1,56 +1,56 @@
/*============================================================================
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 QmitkNodeDetailsDialog_h
#define QmitkNodeDetailsDialog_h
#include <mitkDataNode.h>
#include <QDialog>
#include <MitkQtWidgetsExports.h>
class QLineEdit;
class QTextBrowser;
class MITKQTWIDGETS_EXPORT QmitkNodeDetailsDialog : public QDialog
{
Q_OBJECT
public:
- QmitkNodeDetailsDialog(const QList<mitk::DataNode::ConstPointer>& nodes, QWidget* parent = nullptr, Qt::WindowFlags flags = nullptr);
- QmitkNodeDetailsDialog(const QList<mitk::DataNode::Pointer>& nodes, QWidget* parent = nullptr, Qt::WindowFlags flags = nullptr);
+ QmitkNodeDetailsDialog(const QList<mitk::DataNode::ConstPointer>& nodes, QWidget* parent = nullptr, Qt::WindowFlags flags = {});
+ QmitkNodeDetailsDialog(const QList<mitk::DataNode::Pointer>& nodes, QWidget* parent = nullptr, Qt::WindowFlags flags = {});
public Q_SLOTS:
void OnSelectionChanged(const mitk::DataNode*);
void OnSearchButtonClicked(bool checked = false);
void OnCancelButtonClicked(bool checked = false);
void KeyWordTextChanged(const QString& text);
protected:
bool eventFilter(QObject* obj, QEvent* event) override;
protected:
QLineEdit* m_KeyWord;
QPushButton* m_SearchButton;
QTextBrowser* m_TextBrowser;
private:
void InitWidgets(const QList<mitk::DataNode::ConstPointer>& nodes);
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkPropertiesTableEditor.h b/Modules/QtWidgets/include/QmitkPropertiesTableEditor.h
index f5987c51fd..0d41d566c7 100644
--- a/Modules/QtWidgets/include/QmitkPropertiesTableEditor.h
+++ b/Modules/QtWidgets/include/QmitkPropertiesTableEditor.h
@@ -1,86 +1,86 @@
/*============================================================================
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 QmitkPropertiesTableEditor_h
#define QmitkPropertiesTableEditor_h
#include <MitkQtWidgetsExports.h>
/// Own includes.
#include "mitkDataNode.h"
/// Toolkit includes.
#include <QWidget>
/// Forward declarations.
class QmitkPropertiesTableModel;
class QTableView;
class QLineEdit;
/**
* \ingroup QmitkModule
* \brief Combines a QTableView along with a QmitkPropertiesTableModel to a reusable
* Property Editor component.
*
* \see QmitkPropertyDelegate
*/
class MITKQTWIDGETS_EXPORT QmitkPropertiesTableEditor : public QWidget
{
Q_OBJECT
public:
///
/// Constructs a new QmitkDataStorageTableModel
/// and sets the DataNode for this TableModel.
- QmitkPropertiesTableEditor(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr, mitk::DataNode::Pointer _Node = nullptr);
+ QmitkPropertiesTableEditor(QWidget *parent = nullptr, Qt::WindowFlags f = {}, mitk::DataNode::Pointer _Node = nullptr);
///
/// Standard dtor. Nothing to do here.
~QmitkPropertiesTableEditor() override;
///
/// Convenience method. Sets the property list in the model.
///
void SetPropertyList(mitk::PropertyList::Pointer _List);
///
/// Get the model.
///
QmitkPropertiesTableModel *getModel() const;
QTableView *getTable() const;
protected slots:
void PropertyFilterKeyWordTextChanged(const QString &text);
protected:
///
/// Initialise empty GUI.
///
virtual void init();
///
/// The table view that renders the property list.
///
QTableView *m_NodePropertiesTableView;
///
/// A text field in which the user can enter a filter keyword for the properties. Only properties containing with this
/// keyword
/// will be selected.
///
QLineEdit *m_TxtPropertyFilterKeyWord;
///
/// The property list table model.
///
QmitkPropertiesTableModel *m_Model;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkPropertyItemDelegate.h b/Modules/QtWidgets/include/QmitkPropertyItemDelegate.h
index cd18a319a8..c0d2ffa4f2 100644
--- a/Modules/QtWidgets/include/QmitkPropertyItemDelegate.h
+++ b/Modules/QtWidgets/include/QmitkPropertyItemDelegate.h
@@ -1,93 +1,93 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkPropertyItemDelegate_h
#define QmitkPropertyItemDelegate_h
#include <MitkQtWidgetsExports.h>
#include <QListView>
#include <QStyledItemDelegate>
#include <mitkPropertyList.h>
#include <mitkWeakPointer.h>
class QComboBox;
class QLineEdit;
class QToolButton;
class QResizeEvent;
class QmitkColorWidget : public QWidget
{
Q_OBJECT
public:
explicit QmitkColorWidget(QWidget *parent = nullptr);
~QmitkColorWidget() override;
QColor GetColor() const;
void SetColor(QColor color);
signals:
void ColorPicked();
private slots:
void OnButtonClicked();
void OnLineEditEditingFinished();
private:
QColor m_Color;
QLineEdit *m_LineEdit;
QToolButton *m_Button;
};
class QmitkComboBoxListView : public QListView
{
Q_OBJECT
public:
explicit QmitkComboBoxListView(QComboBox *comboBox = nullptr);
~QmitkComboBoxListView() override;
protected:
void paintEvent(QPaintEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
- QStyleOptionViewItem viewOptions() const override;
+ void initViewItemOption(QStyleOptionViewItem *option) const override;
private:
QComboBox *m_ComboBox;
};
class MITKQTWIDGETS_EXPORT QmitkPropertyItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit QmitkPropertyItemDelegate(QObject *parent = nullptr);
~QmitkPropertyItemDelegate() override;
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
void setEditorData(QWidget *editor, const QModelIndex &index) const override;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override;
void SetPropertyList(mitk::PropertyList *propertyList);
private slots:
void OnComboBoxCurrentIndexChanged(int index);
void OnSpinBoxEditingFinished();
void OnColorPicked();
private:
std::string GetPropertyName(const QModelIndex &index) const;
mitk::WeakPointer<mitk::PropertyList> m_PropertyList;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkRenderWindow.h b/Modules/QtWidgets/include/QmitkRenderWindow.h
index 8194a8ddc0..2aa0b9e4b7 100644
--- a/Modules/QtWidgets/include/QmitkRenderWindow.h
+++ b/Modules/QtWidgets/include/QmitkRenderWindow.h
@@ -1,165 +1,165 @@
/*============================================================================
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 QmitkRenderWindow_h
#define QmitkRenderWindow_h
#include "mitkRenderWindowBase.h"
#include "QmitkRenderWindowMenu.h"
#include <MitkQtWidgetsExports.h>
#include <vtkGenericOpenGLRenderWindow.h>
#include <QVTKOpenGLNativeWidget.h>
#include "mitkBaseRenderer.h"
#include "mitkInteractionEventConst.h"
#include <QmitkButtonOverlayWidget.h>
class QDragEnterEvent;
class QDropEvent;
class QInputEvent;
class QMouseEvent;
/**
* \ingroup QmitkModule
* \brief MITK implementation of the QVTKWidget
*/
class MITKQTWIDGETS_EXPORT QmitkRenderWindow : public QVTKOpenGLNativeWidget, public mitk::RenderWindowBase
{
Q_OBJECT
public:
QmitkRenderWindow(
QWidget *parent = nullptr,
const QString &name = "unnamed renderwindow",
mitk::VtkPropRenderer *renderer = nullptr);
~QmitkRenderWindow() override;
/**
* \brief Whether Qt events should be passed to parent (default: true)
*
* With introduction of the QVTKWidget the behaviour regarding Qt events changed.
* QVTKWidget "accepts" Qt events like mouse clicks (i.e. set an "accepted" flag).
* When this flag is set, Qt fininshed handling of this event -- otherwise it is
* reached through to the widget's parent.
*
* This reaching through to the parent was implicitly required by QmitkMaterialWidget / QmitkMaterialShowCase.
*
* The default behaviour of QmitkRenderWindow is now to clear the "accepted" flag
* of Qt events after they were handled by QVTKWidget. This way parents can also
* handle events.
*
* If you don't want this behaviour, call SetResendQtEvents(true) on your render window.
*/
virtual void SetResendQtEvents(bool resend);
// Set Layout Index to define the Layout Type
void SetLayoutIndex(QmitkRenderWindowMenu::LayoutIndex layoutIndex);
// Get Layout Index to define the Layout Type
QmitkRenderWindowMenu::LayoutIndex GetLayoutIndex();
// MenuWidget need to update the Layout Design List when Layout had changed
void UpdateLayoutDesignList(QmitkRenderWindowMenu::LayoutDesign layoutDesign);
void UpdateCrosshairVisibility(bool);
void UpdateCrosshairRotationMode(int);
// Activate or Deactivate MenuWidget.
void ActivateMenuWidget(bool state);
bool GetActivateMenuWidgetFlag() { return m_MenuWidgetActivated; }
void ShowOverlayMessage(bool show);
// Get it from the QVTKWidget parent
vtkRenderWindow *GetVtkRenderWindow() override { return this->renderWindow(); }
vtkRenderWindowInteractor *GetVtkRenderWindowInteractor() override { return nullptr; }
protected:
// catch-all event handler
bool event(QEvent *e) override;
// overloaded move handler
void moveEvent(QMoveEvent *event) override;
// overloaded show handler
void showEvent(QShowEvent *event) override;
// overloaded enter handler
- void enterEvent(QEvent *) override;
+ void enterEvent(QEnterEvent *) override;
// overloaded leave handler
void leaveEvent(QEvent *) override;
// Overloaded resize handler, see decs in QVTKOpenGLWidget.
// Basically, we have to ensure the VTK rendering is updated for each change in window size.
void resizeGL(int w, int h) override;
/// \brief Simply says we accept the event type.
void dragEnterEvent(QDragEnterEvent *event) override;
/// \brief If the dropped type is application/x-mitk-datanodes we process the request by converting to mitk::DataNode
/// pointers and emitting the NodesDropped signal.
void dropEvent(QDropEvent *event) override;
Q_SIGNALS:
void LayoutDesignChanged(QmitkRenderWindowMenu::LayoutDesign);
void ResetView();
void ResetGeometry();
void CrosshairRotationModeChanged(int);
void CrosshairVisibilityChanged(bool);
void moved();
/// \brief Emits a signal to say that this window has had the following nodes dropped on it.
void NodesDropped(QmitkRenderWindow *thisWindow, std::vector<mitk::DataNode *> nodes);
private Q_SLOTS:
void DeferredHideMenu();
private:
// Helper Functions to Convert Qt-Events to Mitk-Events
mitk::Point2D GetMousePosition(QMouseEvent *me) const;
mitk::Point2D GetMousePosition(QWheelEvent *we) const;
mitk::InteractionEvent::MouseButtons GetEventButton(QMouseEvent *me) const;
mitk::InteractionEvent::MouseButtons GetButtonState(QMouseEvent *me) const;
mitk::InteractionEvent::ModifierKeys GetModifiers(QInputEvent *me) const;
mitk::InteractionEvent::MouseButtons GetButtonState(QWheelEvent *we) const;
std::string GetKeyLetter(QKeyEvent *ke) const;
int GetDelta(QWheelEvent *we) const;
void UpdateStatusBar(mitk::Point2D pointerPositionOnScreen);
bool m_ResendQtEvents;
QmitkRenderWindowMenu *m_MenuWidget;
bool m_MenuWidgetActivated;
QmitkRenderWindowMenu::LayoutIndex m_LayoutIndex;
vtkSmartPointer<vtkGenericOpenGLRenderWindow> m_InternalRenderWindow;
QmitkButtonOverlayWidget* m_GeometryViolationWarningOverlay;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkRenderWindowMenu.h b/Modules/QtWidgets/include/QmitkRenderWindowMenu.h
index a887f21441..e0e6e49f10 100644
--- a/Modules/QtWidgets/include/QmitkRenderWindowMenu.h
+++ b/Modules/QtWidgets/include/QmitkRenderWindowMenu.h
@@ -1,194 +1,194 @@
/*============================================================================
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 QmitkRenderWindowMenu_h
#define QmitkRenderWindowMenu_h
// mitk qtwidgets module
#include "MitkQtWidgetsExports.h"
#include "QmitkMultiWidgetLayoutManager.h"
// mitk core
#include <mitkBaseRenderer.h>
// qt
#include <QAction>
#include <QEvent>
#include <QLabel>
#include <QMenuBar>
#include <QPushButton>
#include <QTimer>
#include <QToolButton>
#include <QWidget>
/**
* \ingroup QmitkModule
* \brief The QmitkRenderWindowMenu is a popup Widget which shows
* up when the mouse cursor enter a QmitkRenderWindow.
* The Menu Widget is located in the right top corner of each
* RenderWindow. It includes different settings. For example
* the layout design can be changed with the setting button. Switching
* between full-screen mode and layout design can be done
* with the full-screen button.
* The popup Widget can be deactivated with ActivateMenuWidget(false) in
* QmitkRenderWindow.
*
* \sa QmitkRenderWindow
*
*/
class MITKQTWIDGETS_EXPORT QmitkRenderWindowMenu : public QWidget
{
Q_OBJECT
public:
using LayoutIndex = mitk::AnatomicalPlane;
using LayoutDesign = QmitkMultiWidgetLayoutManager::LayoutDesign;
QmitkRenderWindowMenu(QWidget *parent = nullptr,
- Qt::WindowFlags f = nullptr,
+ Qt::WindowFlags f = {},
mitk::BaseRenderer *b = nullptr);
~QmitkRenderWindowMenu() override;
/*! Return visibility of settings menu. The menu is connected with m_SettingsButton and includes
layout direction (axial, coronal .. ) and layout design (standard layout, 2D images top,
3D bottom ... ). */
bool GetSettingsMenuVisibilty()
{
if (m_LayoutActionsMenu == nullptr)
return false;
else
return m_LayoutActionsMenu->isVisible();
}
/*! Set layout index. Defines layout direction (axial, coronal, sagittal or threeD) of the parent. */
void SetLayoutIndex(LayoutIndex layoutIndex);
/*! Return layout direction of parent (axial, coronal, sagittal or threeD) */
LayoutIndex GetLayoutIndex() { return m_Layout; }
/*! Update list of layout design (standard layout, 2D images top, 3D bottom ..). Set action of current layout design
to disable and all other to enable. */
void UpdateLayoutDesignList(LayoutDesign layoutDesign);
void UpdateCrosshairVisibility(bool visible);
void UpdateCrosshairRotationMode(int mode);
/*! Move menu widget to correct position (right upper corner). E.g. it is necessary when the full-screen mode
is activated.*/
void MoveWidgetToCorrectPos();
void ShowMenu();
void HideMenu();
protected:
/*! Reimplemented from QWidget. The paint event is a request to repaint all or part of a widget.*/
void paintEvent(QPaintEvent *event) override;
void CreateMenuWidget();
/*! Create settings menu which contains layout direction and the different layout designs. */
void CreateSettingsWidget();
/*! Change Icon of full-screen button depending on full-screen mode. */
void ChangeFullScreenIcon();
Q_SIGNALS:
void ResetView(); // == "global reinit"
void CrosshairVisibilityChanged(bool);
// \brief int parameters are enum from QmitkStdMultiWidget
void CrosshairRotationModeChanged(int);
/*! emit signal, when layout design changed by the setting menu.*/
void LayoutDesignChanged(LayoutDesign layoutDesign);
protected Q_SLOTS:
/// this function is continuously called by a timer
/// to do the auto rotation
void AutoRotateNextStep();
/// this function is invoked when the auto-rotate action
/// is clicked
void OnAutoRotationActionTriggered();
void OnTSNumChanged(int);
void OnCrosshairMenuAboutToShow();
void OnCrosshairVisibilityChanged(bool);
void OnCrosshairRotationModeSelected(QAction *);
/*! slot for activating/deactivating the full-screen mode. The slot is connected to the clicked() event of
m_FullScreenButton.
Activating the full-screen maximize the current widget, deactivating restore If layout design changed by the settings
menu, the full-Screen mode is automatically switched to false. */
void OnFullScreenButton(bool checked);
/*! Slot for opening setting menu. The slot is connected to the clicked() event of m_SettingsButton.
The settings menu includes different layout directions (axial, coronal, sagittal and 3D) as well all layout design
(standard layout, 2D images top, 3D bottom ..)*/
void OnLayoutDesignButton(bool checked);
void OnSetLayout(LayoutDesign layoutDesign);
protected:
QToolButton* m_CrosshairModeButton;
QToolButton* m_FullScreenButton;
QToolButton* m_LayoutDesignButton;
QMenu* m_LayoutActionsMenu;
QAction* m_DefaultLayoutAction;
QAction* m_All2DTop3DBottomLayoutAction;
QAction* m_All2DLeft3DRightLayoutAction;
QAction* m_OneBigLayoutAction;
QAction* m_Only2DHorizontalLayoutAction;
QAction* m_Only2DVerticalLayoutAction;
QAction* m_OneTop3DBottomLayoutAction;
QAction* m_OneLeft3DRightLayoutAction;
QAction* m_AllHorizontalLayoutAction;
QAction* m_AllVerticalLayoutAction;
QAction* m_RemoveOneLayoutAction;
QLabel *m_TSLabel;
QMenu *m_CrosshairMenu;
/*! Flag if full-screen mode is activated or deactivated. */
bool m_FullScreenMode;
private:
mitk::BaseRenderer::Pointer m_Renderer;
QTimer* m_AutoRotationTimer;
QWidget *m_Parent;
//memory because mode is set to default for slice num = 1
static unsigned int m_DefaultThickMode;
int m_CrosshairRotationMode;
bool m_CrosshairVisibility;
LayoutIndex m_Layout;
LayoutDesign m_LayoutDesign;
LayoutDesign m_OldLayoutDesign;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkServiceListWidget.h b/Modules/QtWidgets/include/QmitkServiceListWidget.h
index 54d4194dfb..ba70714b54 100644
--- a/Modules/QtWidgets/include/QmitkServiceListWidget.h
+++ b/Modules/QtWidgets/include/QmitkServiceListWidget.h
@@ -1,288 +1,288 @@
/*============================================================================
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 QmitkServiceListWidget_h
#define QmitkServiceListWidget_h
#include "MitkQtWidgetsExports.h"
#include "ui_QmitkServiceListWidgetControls.h"
#include <vector>
// QT headers
#include <QListWidgetItem>
#include <QWidget>
// Microservices
#include "mitkServiceInterface.h"
#include "usModuleContext.h"
#include "usServiceEvent.h"
#include "usServiceReference.h"
/**
* \ingroup QmitkModule
*
* \brief This widget provides abstraction for the handling of MicroServices.
*
* Place one in your Plugin and set it to look for a certain interface.
* One can also specify a filter and / or a property to use for captioning of
* the services. It also offers functionality to signal
* ServiceEvents and to return the actual classes, so only a minimum of
* interaction with the MicroserviceInterface is required.
* To get started, just put it in your Plugin or Widget, call the Initialize
* Method and optionally connect it's signals.
* As QT limits templating possibilities, events only throw ServiceReferences.
* You can manually dereference them using TranslateServiceReference()
*/
class MITKQTWIDGETS_EXPORT QmitkServiceListWidget : public QWidget
{
// this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
private:
us::ModuleContext *m_Context;
/** \brief a filter to further narrow down the list of results*/
std::string m_Filter;
/** \brief The name of the ServiceInterface that this class should list */
std::string m_Interface;
/** \brief The name of the ServiceProperty that will be displayed in the list to represent the service */
std::string m_NamingProperty;
/** \brief Determines if the first entry of the list should be selected automatically if no entry was selected before
* (default false). */
bool m_AutomaticallySelectFirstEntry;
public:
static const std::string VIEW_ID;
- QmitkServiceListWidget(QWidget *p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkServiceListWidget(QWidget *p = nullptr, Qt::WindowFlags f1 = {});
~QmitkServiceListWidget() override;
/** \brief Set if the first entry of the list should be selected automatically if no entry was selected before. */
void SetAutomaticallySelectFirstEntry(bool automaticallySelectFirstEntry);
/** \brief This method is part of the widget an needs not to be called separately. */
virtual void CreateQtPartControl(QWidget *parent);
/** \brief This method is part of the widget an needs not to be called separately. (Creation of the connections of
* main and control widget.)*/
virtual void CreateConnections();
/**
* \brief Will return true, if a service is currently selected and false otherwise.
*
* Call this before requesting service references to avoid invalid ServiceReferences.
*/
bool GetIsServiceSelected();
/**
* \brief Returns the currently selected Service as a ServiceReference.
*
* If no Service is selected, the result will probably be a bad pointer. call GetIsServiceSelected()
* beforehand to avoid this
*/
us::ServiceReferenceU GetSelectedServiceReference();
/**
* @return Returns all service references that are displayed in this widget.
*/
std::vector<us::ServiceReferenceU> GetAllServiceReferences();
/**
* \brief Use this function to return the all listed services as a class directly.
*
* Make sure you pass the appropriate type, or else this call will fail.
* Usually, you will pass the class itself, not the SmartPointer, but the function returns a pointer.
*/
template <class T>
std::vector<T *> GetAllServices()
{
// if (this->m_Controls->m_ServiceList->currentRow()==-1) return nullptr;
std::vector<us::ServiceReferenceU> refs = GetAllServiceReferences();
std::vector<T *> result;
for (std::size_t i = 0; i < refs.size(); i++)
{
result.push_back(m_Context->GetService(us::ServiceReference<T>(refs[i])));
}
return result;
}
/**
* \brief Use this function to return the currently selected service as a class directly.
*
* Make sure you pass the appropriate type, or else this call will fail.
* Usually, you will pass the class itself, not the SmartPointer, but the function returns a pointer. Example:
* \verbatim mitk::USDevice::Pointer device = GetSelectedService<mitk::USDevice>(); \endverbatim
* @return Returns the current selected device. Returns nullptr if no device is selected.
*/
template <class T>
T *GetSelectedService()
{
if (this->m_Controls->m_ServiceList->currentRow() == -1)
return nullptr;
us::ServiceReferenceU ref = GetServiceForListItem(this->m_Controls->m_ServiceList->currentItem());
return (m_Context->GetService(us::ServiceReference<T>(ref)));
}
/**
* \brief Initializes the Widget with essential parameters.
*
* The string filter is an LDAP parsable String, compare mitk::ModuleContext for examples on filtering.
* Pass class T to tell the widget which class it should filter for - only services of this class will be listed.
* NamingProperty is a property that will be used to caption the Items in the list. If no filter is supplied, all
* matching interfaces are shown. If no namingProperty is supplied, the interfaceName will be used to caption Items in
the list.
* For example, this Initialization will filter for all USDevices that are set to active. The USDevice's model will be
used to display it in the list:
* \verbatim
std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" +
"org.mitk.services.UltrasoundDevice)(IsActive=true))";
m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(mitk::USDevice::GetPropertyKeys().US_PROPKEY_NAME
,filter);
* \endverbatim
*/
template <class T>
void Initialize(const std::string &namingProperty = static_cast<std::string>(""),
const std::string &filter = static_cast<std::string>(""))
{
std::string interfaceName(us_service_interface_iid<T>());
m_Interface = interfaceName;
InitPrivate(namingProperty, filter);
}
/**
* \brief Translates a serviceReference to a class of the given type.
*
* Use this to translate the signal's parameters. To adhere to the MicroService contract,
* only ServiceReferences stemming from the same widget should be used as parameters for this method.
* \verbatim mitk::USDevice::Pointer device = TranslateReference<mitk::USDevice>(myDeviceReference); \endverbatim
*/
template <class T>
T *TranslateReference(const us::ServiceReferenceU &reference)
{
return m_Context->GetService(us::ServiceReference<T>(reference));
}
/**
*\brief This Function listens to ServiceRegistry changes and updates the list of services accordingly.
*
* The user of this widget does not need to call this method, it is instead used to recieve events from the module
*registry.
*/
void OnServiceEvent(const us::ServiceEvent event);
signals:
/**
*\brief Emitted when a new Service matching the filter is being registered.
*
* Be careful if you use a filter:
* If a device does not match the filter when registering, but modifies it's properties later to match the filter,
* then the first signal you will see this device in will be ServiceModified.
*/
void ServiceRegistered(us::ServiceReferenceU);
/**
*\brief Emitted directly before a Service matching the filter is being unregistered.
*/
void ServiceUnregistering(us::ServiceReferenceU);
/**
*\brief Emitted when a Service matching the filter changes it's properties, or when a service that formerly not
*matched the filter
* changed it's properties and now matches the filter.
*/
void ServiceModified(us::ServiceReferenceU);
/**
*\brief Emitted when a Service matching the filter changes it's properties,
*
* and the new properties make it fall trough the filter. This effectively means that
* the widget will not track the service anymore. Usually, the Service should still be useable though
*/
void ServiceModifiedEndMatch(us::ServiceReferenceU);
/**
*\brief Emitted if the user selects a Service from the list.
*
* If no service is selected, an invalid serviceReference is returned. The user can easily check for this.
* if (serviceReference) will evaluate to false, if the reference is invalid and true if valid.
*/
void ServiceSelectionChanged(us::ServiceReferenceU);
public slots:
protected slots:
/**
\brief Called, when the selection in the list of Services changes.
*/
void OnServiceSelectionChanged();
protected:
Ui::QmitkServiceListWidgetControls *m_Controls; ///< member holding the UI elements of this widget
/**
* \brief Internal structure used to link ServiceReferences to their QListWidgetItems
*/
struct ServiceListLink
{
us::ServiceReferenceU service;
QListWidgetItem *item;
};
/**
* \brief Finishes initialization after Initialize has been called.
*
* This function assumes that m_Interface is set correctly (Which Initialize does).
*/
void InitPrivate(const std::string &namingProperty, const std::string &filter);
/**
* \brief Contains a list of currently active services and their entires in the list. This is wiped with every
* ServiceRegistryEvent.
*/
std::vector<ServiceListLink> m_ListContent;
/**
* \brief Constructs a ListItem from the given service, displays it, and locally stores the service.
*/
QListWidgetItem *AddServiceToList(const us::ServiceReferenceU &serviceRef);
/**
* \brief Removes the given service from the list and cleans up. Returns true if successful, false if service was not
* found.
*/
bool RemoveServiceFromList(const us::ServiceReferenceU &serviceRef);
/**
* \brief Changes list entry of given service to match the changed service properties.
* \return true if successful, false if service was not found
*/
bool ChangeServiceOnList(const us::ServiceReferenceU &serviceRef);
/**
* \brief Returns the serviceReference corresponding to the given ListEntry or an invalid one if none was found (will
* evaluate to false in bool expressions).
*/
us::ServiceReferenceU GetServiceForListItem(QListWidgetItem *item);
/**
* \brief Returns a list of ServiceReferences matching the filter criteria by querying the service registry.
*/
std::vector<us::ServiceReferenceU> GetAllRegisteredServices();
/**
* \brief Gets string from the naming property of the service.
* \return caption string for given us::ServiceReferenceU
*/
QString CreateCaptionForService(const us::ServiceReferenceU &serviceRef);
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkSliceNavigationWidget.h b/Modules/QtWidgets/include/QmitkSliceNavigationWidget.h
index c1ca2879f0..a0a5611819 100644
--- a/Modules/QtWidgets/include/QmitkSliceNavigationWidget.h
+++ b/Modules/QtWidgets/include/QmitkSliceNavigationWidget.h
@@ -1,151 +1,151 @@
/*============================================================================
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 QmitkSliceNavigationWidget_h
#define QmitkSliceNavigationWidget_h
#include "MitkQtWidgetsExports.h"
#include "ui_QmitkSliceNavigationWidget.h"
#include <mitkStepper.h>
#include <QString>
#include <QWidget>
class MITKQTWIDGETS_EXPORT QmitkSliceNavigationWidget : public QWidget, public Ui::QmitkSliceNavigationWidget
{
Q_OBJECT
public:
- QmitkSliceNavigationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkSliceNavigationWidget(QWidget* parent = nullptr, Qt::WindowFlags f = {});
/**
* \brief Convert the passed value to a QString representation.
*
* If the value exceeds a certain maximum, "INF" (for "infinity") is displayed
* instead.
*/
QString ClippedValueToString(float value);
QString GetLabelUnit();
QString GetMinValueLabel();
QString GetMaxValueLabel();
int GetPos();
bool GetInverseDirection() const;
bool GetInvertedControls() const;
public slots:
/**
* \brief Update the slider with the recent changes applied to the navigation widget.
*
* Intended to be called via event mechanism, e.g. if the connected
* mitk::Stepper is modified.
*/
void Refetch();
/**
* \brief Set the stepper that should be represented and modified.
*
*/
void SetStepper(mitk::Stepper* stepper);
/**
* \brief Enable / disable displaying of the minimum and maximum labels
*/
void ShowLabels(bool show);
/**
* \brief Enable / disable displaying of the unit label (range will be displayed
* without unit if enabled).
*/
void ShowLabelUnit(bool show);
void SetPos(int val);
void SetInverseDirection(bool inverseDirection);
void SetInvertedControls(bool invertedControls);
protected slots:
/**
* \brief React on changes of the slider.
*
* The position of the stepper (class member) is set according to the
* current slider value.
* This will also update the value labels.
*/
void SliderChanged(double);
/**
* \brief React on changes of the spinbox.
*
* The position of the stepper (class member) is set according to the
* current spinbox value.
* This will also update the value labels.
*/
void SpinBoxChanged(double);
/**
* \brief Set label values for the range minimum and maximum.
*
* Displayed as labels to the left and the right of the slider, if enabled.
*/
void SetLabelValues(float min, float max);
/**
* \brief Enable / disable labels for the range minimum or maximum.
*
* Displayed as labels to the left and the right of the slider, if enabled.
*/
void SetLabelValuesValid(bool minValid, bool maxValid);
/**
* \brief Set the range unit (e.g. mm or ms).
*
* Displayed below the range labels, if enabled.
*/
void SetLabelUnit(const char* unit);
/**
* \brief Configure slider with labels according to range and unit settings.
*/
void SetLabels();
protected:
mitk::Stepper::Pointer m_Stepper;
bool m_InRefetch;
QString m_LabelUnit;
bool m_HasLabelUnit;
bool m_MaxValueValid;
bool m_MinValueValid;
bool m_HasLabels;
float m_MinValue;
float m_MaxValue;
bool m_InverseDirection;
bool m_InvertedControls;
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkSliderLevelWindowWidget.h b/Modules/QtWidgets/include/QmitkSliderLevelWindowWidget.h
index 7ed574ba4e..cc726fe505 100644
--- a/Modules/QtWidgets/include/QmitkSliderLevelWindowWidget.h
+++ b/Modules/QtWidgets/include/QmitkSliderLevelWindowWidget.h
@@ -1,188 +1,188 @@
/*============================================================================
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 QmitkSliderLevelWindowWidget_h
#define QmitkSliderLevelWindowWidget_h
#include <MitkQtWidgetsExports.h>
#include <QWidget>
#include <mitkLevelWindowManager.h>
class QmitkLevelWindowWidgetContextMenu;
/**
* \ingroup QmitkModule
*
* \brief Provides a widget with a slider to change the level and
* window value of the current image.
*
* This documentation actually refers to the QmitkLevelWindowWidget
* and is only put in this class due to technical issues (should be
* moved later).
*
* The QmitkLevelWindowWidget is a kind of container for a
* QmitkSliderLevelWindowWidget (this is the cyan bar above the text
* input fields) and a QmitkLineEditLevelWindowWidget (with two text
* input fields). It holds a reference to a mitk::LevelWindowManager
* variable, which keeps the LevelWindowProperty of the currently
* selected image. Level/Window is manipulated by the text inputs and
* the Slider to adjust brightness/contrast of a single image. All
* changes on the slider or in the text input fields affect the current
* image by giving new values to LevelWindowManager. LevelWindowManager
* then sends a signal to tell other listeners about changes.
*
* Which image is changed is determined by mitkLevelWindowManager. If
* m_AutoTopMost is true, always the topmost image in data tree (layer
* property) is affected by changes. The image which is affected by
* changes can also be changed by QmitkLevelWindowWidgetContextMenu,
* the context menu for QmitkSliderLevelWindowWidget and
* QmitkLineEditLevelWindowWidget. There you have the possibility to
* set a certain image or always the topmost image in the data tree
* (layer property) to be affected by changes.
*
* The internal mitk::LevelWindow variable contains a range that is
* valid for a given image. It should not be possible to move the
* level/window parameters outside this range. The range can be changed
* and reset to its default values by QmitkLevelWindowWidgetContextMenu,
* the context menu for QmitkSliderLevelWindowWidget and
* QmitkLineEditLevelWindowWidget.
*
* Now for the behaviour of the text inputs: The upper one contains the
* value of the level (brightness), the lower one shows the window (contrast).
*
* The behaviour of the cyan bar is more obvious: the scale in the
* background shows the valid range. The cyan bar in front displays the
* currently selected level/window setting. You can change the level by
* dragging the bar with the left mouse button or clicking somewhere inside
* the scalerange with the left mouse button. The window is changed by
* moving the mouse on the upper or lower bound of the bar until the cursor
* becomes an vertical double-arrowed symbol. Then you can change the
* windowsize by clicking the left mouse button and move the mouse upwards
* or downwards. The bar becomes greater upwards as well as downwards. If
* you want to change the size of the window in only one direction you
* have to press the CTRL-key while doing the same as mentioned above.
* This information is also presented by a tooltip text when moving the
* mouse on the upper or lower bound of the bar.
*/
class MITKQTWIDGETS_EXPORT QmitkSliderLevelWindowWidget : public QWidget
{
Q_OBJECT
public:
/// constructor
- QmitkSliderLevelWindowWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkSliderLevelWindowWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
/// destructor
~QmitkSliderLevelWindowWidget() override;
/// sets the manager who is responsible to collect and deliver changes on Level/Window
void SetLevelWindowManager(mitk::LevelWindowManager *levelWindowManager);
/// sets the DataStorage which holds all image-nodes
void SetDataStorage(mitk::DataStorage *ds);
/// returns the manager who is responsible to collect and deliver changes on Level/Window
mitk::LevelWindowManager *GetManager();
mitk::LevelWindow m_LevelWindow;
/// manager who is responsible to collect and deliver changes on Level/Window
mitk::LevelWindowManager::Pointer m_Manager;
private:
/// creates the context menu for this widget from class QmitkLevelWindowWidgetContextMenu
void contextMenuEvent(QContextMenuEvent *) override;
/// change notifications from the mitkLevelWindowManager
void OnPropertyModified(const itk::EventObject &e);
protected:
/// recalculate the size and position of the slider bar
virtual void Update();
/*!
* helper for drawing the component
*/
QRect m_Rect;
/*!
* helper for drawing the component
*/
QPoint m_StartPos;
bool m_Resize;
bool m_Bottom;
bool m_MouseDown;
bool m_Leftbutton;
bool m_CtrlPressed;
int m_MoveHeight;
bool m_ScaleVisible;
QRect m_LowerBound;
QRect m_UpperBound;
unsigned long m_ObserverTag;
bool m_IsObserverTagSet;
QFont m_Font;
/*!
* data structure which creates the context menu for QmitkLineEditLevelWindowWidget
*/
QmitkLevelWindowWidgetContextMenu *m_Contextmenu;
/*!
* repaint the slider and the scale
*/
void paintEvent(QPaintEvent *e) override;
/*!
* method implements the component behavior
*
* checks if cursor is on upper or lower bound of slider bar and changes cursor symbol
*
* checks if left mouse button is pressed and if CTRL is pressed and changes sliderbar in move-direction accordingly
*/
void mouseMoveEvent(QMouseEvent *mouseEvent) override;
- void enterEvent(QEvent *event) override;
+ void enterEvent(QEnterEvent *event) override;
/*!
* registers events when a mousebutton is pressed
*
* if leftbutton is pressed m_Leftbutton is set to true
*
* also checks if CTRL is pressed and sets the bool variable m_CtrlPressed
*/
void mousePressEvent(QMouseEvent *mouseEvent) override;
/*!
* sets the variable m_MouseDown to false
*/
void mouseReleaseEvent(QMouseEvent *mouseEvent) override;
/*!
* causes an update of the sliderbar when resizing the window
*/
void resizeEvent(QResizeEvent *event) override;
protected Q_SLOTS:
/** @brief Hide the scale if "Hide Scale" is selected in the context menu
*/
void HideScale();
/** @brief Shows the scale if "Show Scale" is selected in the context menu
*/
void ShowScale();
};
#endif
diff --git a/Modules/QtWidgets/include/QmitkStdMultiWidget.h b/Modules/QtWidgets/include/QmitkStdMultiWidget.h
index 9c6f0e34d0..69c746f10e 100644
--- a/Modules/QtWidgets/include/QmitkStdMultiWidget.h
+++ b/Modules/QtWidgets/include/QmitkStdMultiWidget.h
@@ -1,173 +1,173 @@
/*============================================================================
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 QmitkStdMultiWidget_h
#define QmitkStdMultiWidget_h
// qt widgets module
#include "MitkQtWidgetsExports.h"
#include "QmitkAbstractMultiWidget.h"
/**
* @brief The 'QmitkStdMultiWidget' is a 'QmitkAbstractMultiWidget' that is used to display multiple render windows at once.
* Render windows are predefined in a 2x2 design with 3 different 2D view planes and a 3D render window.
*/
class MITKQTWIDGETS_EXPORT QmitkStdMultiWidget : public QmitkAbstractMultiWidget
{
Q_OBJECT
public:
QmitkStdMultiWidget(
QWidget *parent = nullptr,
- Qt::WindowFlags f = nullptr,
+ Qt::WindowFlags f = {},
const QString &name = "stdmulti");
~QmitkStdMultiWidget() override;
virtual void InitializeMultiWidget() override;
virtual QmitkRenderWindow* GetRenderWindow(const QString& widgetName) const override;
virtual QmitkRenderWindow* GetRenderWindow(const mitk::AnatomicalPlane& orientation) const override;
/**
* @brief Initialize all render windows of the StdMultiWidget to the given geometry.
* Overridem from 'QmitkAbstractMultiWidget'.
*
* @param geometry The geometry to be used to initialize / update all
* render window's time and slice navigation controller.
* @param resetCamera If true, the camera and crosshair will be reset to the default view (centered, no zoom).
* If false, the current crosshair position and the camera zoom will be stored and reset
* after the reference geometry has been updated.
*/
void InitializeViews(const mitk::TimeGeometry* geometry, bool resetCamera) override;
/**
* @brief Not implemented in this class.
* Overridem from 'QmitkAbstractMultiWidget'.
*/
void SetInteractionReferenceGeometry(const mitk::TimeGeometry* referenceGeometry) override;
/**
* @brief Returns true if the render windows are coupled; false if not.
*
* For the StdMultiWidget the render windows are typically coupled.
*/
bool HasCoupledRenderWindows() const override;
virtual void SetSelectedPosition(const mitk::Point3D& newPosition, const QString& widgetName) override;
virtual const mitk::Point3D GetSelectedPosition(const QString& widgetName) const override;
virtual void SetCrosshairVisibility(bool) override;
virtual bool GetCrosshairVisibility() const override;
void SetCrosshairGap(unsigned int gapSize) override;
virtual void ResetCrosshair() override;
virtual void SetWidgetPlaneMode(int mode) override;
void AddPlanesToDataStorage();
void RemovePlanesFromDataStorage();
/**
* @brief Convenience method to get a render window widget.
* @param number of the widget (0-3)
* @return The render window widget
*/
QmitkRenderWindow* GetRenderWindow(unsigned int number) const;
QmitkRenderWindow* GetRenderWindow1() const;
QmitkRenderWindow* GetRenderWindow2() const;
QmitkRenderWindow* GetRenderWindow3() const;
QmitkRenderWindow* GetRenderWindow4() const;
/**
* @brief Convenience method to get a widget plane.
* @param number of the widget plane (1-3)
* @return The widget plane as data node
*/
mitk::DataNode::Pointer GetWidgetPlane(unsigned int number) const;
mitk::DataNode::Pointer GetWidgetPlane1() const;
mitk::DataNode::Pointer GetWidgetPlane2() const;
mitk::DataNode::Pointer GetWidgetPlane3() const;
/**
* @brief SetDecorationColor Set the color of the decoration of the 4 widgets.
*
* This is used to color the frame of the renderwindow and the corner annatation.
* For the first 3 widgets, this color is a property of the helper object nodes
* which contain the respective plane geometry. For widget 4, this is a member,
* since there is no data node for this widget.
*/
void SetDecorationColor(unsigned int widgetNumber, mitk::Color color);
/**
* @brief GetDecorationColorForWidget Get the color for annotation, crosshair and rectangle.
* @param widgetNumber Number of the renderwindow (0-3).
* @return Color in mitk format.
*/
mitk::Color GetDecorationColor(unsigned int widgetNumber);
public Q_SLOTS:
// mouse events
virtual void mousePressEvent(QMouseEvent*) override;
virtual void moveEvent(QMoveEvent* e) override;
virtual void wheelEvent(QWheelEvent* e) override;
void Fit();
void AddDisplayPlaneSubTree();
void EnsureDisplayContainsPoint(mitk::BaseRenderer *renderer, const mitk::Point3D &p);
void SetWidgetPlaneVisibility(const char *widgetName, bool visible, mitk::BaseRenderer *renderer = nullptr);
void SetWidgetPlanesVisibility(bool visible, mitk::BaseRenderer *renderer = nullptr);
Q_SIGNALS:
void NotifyCrosshairVisibilityChanged(bool visible);
void NotifyCrosshairRotationModeChanged(int mode);
void WheelMoved(QWheelEvent *);
void Moved();
private:
virtual void SetLayoutImpl() override;
virtual void SetInteractionSchemeImpl() override { }
void CreateRenderWindowWidgets();
/**
* @brief The 3 helper objects which contain the plane geometry.
*/
mitk::DataNode::Pointer m_PlaneNode1;
mitk::DataNode::Pointer m_PlaneNode2;
mitk::DataNode::Pointer m_PlaneNode3;
/**
* @brief m_ParentNodeForGeometryPlanes This helper object is added to the datastorage
* and contains the 3 planes for displaying the image geometry (crosshair and 3D planes).
*/
mitk::DataNode::Pointer m_ParentNodeForGeometryPlanes;
/**
* @brief m_DecorationColorWidget4 color for annotation and rectangle of widget 4.
*
* For other widgets1-3, the color is a property of the respective data node.
* There is no node for widget 4, hence, we need an extra member.
*/
mitk::Color m_DecorationColorWidget4;
};
#endif
diff --git a/Modules/QtWidgets/src/QmitkAbstractNodeSelectionWidget.cpp b/Modules/QtWidgets/src/QmitkAbstractNodeSelectionWidget.cpp
index acc64021c6..52e3f98ac5 100644
--- a/Modules/QtWidgets/src/QmitkAbstractNodeSelectionWidget.cpp
+++ b/Modules/QtWidgets/src/QmitkAbstractNodeSelectionWidget.cpp
@@ -1,426 +1,426 @@
/*============================================================================
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 "QmitkAbstractNodeSelectionWidget.h"
#include "QmitkModelViewSelectionConnector.h"
QmitkAbstractNodeSelectionWidget::QmitkAbstractNodeSelectionWidget(QWidget* parent)
: QWidget(parent)
, m_InvalidInfo("Error. Select data.")
, m_EmptyInfo("Empty. Make a selection.")
, m_PopUpTitel("Select a data node")
, m_PopUpHint("")
, m_IsOptional(false)
, m_SelectOnlyVisibleNodes(true)
, m_DataStorageDeletedTag(0)
, m_LastEmissionAllowance(true)
, m_RecursionGuard(false)
{
}
QmitkAbstractNodeSelectionWidget::~QmitkAbstractNodeSelectionWidget()
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNotNull())
{
// remove Listener for the data storage itself
dataStorage->RemoveObserver(m_DataStorageDeletedTag);
// remove "add node listener" from data storage
dataStorage->AddNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// remove "remove node listener" from data storage
dataStorage->RemoveNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
for (auto& node : m_CurrentInternalSelection)
{
this->RemoveNodeObserver(node);
}
}
QmitkAbstractNodeSelectionWidget::NodeList QmitkAbstractNodeSelectionWidget::GetSelectedNodes() const
{
return this->CompileEmitSelection();
}
QmitkAbstractNodeSelectionWidget::ConstNodeStdVector QmitkAbstractNodeSelectionWidget::GetSelectedNodesStdVector() const
{
auto result = this->GetSelectedNodes();
return ConstNodeStdVector(result.begin(), result.end());
}
void QmitkAbstractNodeSelectionWidget::SetDataStorage(mitk::DataStorage* dataStorage)
{
if (m_DataStorage == dataStorage)
{
return;
}
auto oldStorage = m_DataStorage.Lock();
if (oldStorage.IsNotNull())
{
// remove Listener for the data storage itself
oldStorage->RemoveObserver(m_DataStorageDeletedTag);
// remove "add node listener" from old data storage
oldStorage->AddNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// remove "remove node listener" from old data storage
oldStorage->RemoveNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
m_DataStorage = dataStorage;
auto newStorage = m_DataStorage.Lock();
if (newStorage.IsNotNull())
{
// add Listener for the data storage itself
auto command = itk::SimpleMemberCommand<QmitkAbstractNodeSelectionWidget>::New();
command->SetCallbackFunction(this, &QmitkAbstractNodeSelectionWidget::SetDataStorageDeleted);
m_DataStorageDeletedTag = newStorage->AddObserver(itk::DeleteEvent(), command);
// add "add node listener" for new data storage
newStorage->AddNodeEvent.AddListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// add remove node listener for new data storage
newStorage->RemoveNodeEvent.AddListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
this->OnDataStorageChanged();
this->HandleChangeOfInternalSelection({});
}
void QmitkAbstractNodeSelectionWidget::SetNodePredicate(const mitk::NodePredicateBase* nodePredicate)
{
if (m_NodePredicate != nodePredicate)
{
m_NodePredicate = nodePredicate;
this->OnNodePredicateChanged();
NodeList newInternalNodes;
for (auto& node : m_CurrentInternalSelection)
{
if (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node))
{
newInternalNodes.append(node);
}
}
if (!m_SelectOnlyVisibleNodes)
{
for (auto& node : m_CurrentExternalSelection)
{
if (!newInternalNodes.contains(node) && (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node)))
{
newInternalNodes.append(node);
}
}
}
this->HandleChangeOfInternalSelection(newInternalNodes);
}
}
void QmitkAbstractNodeSelectionWidget::HandleChangeOfInternalSelection(NodeList newInternalSelection)
{
if (!EqualNodeSelections(m_CurrentInternalSelection, newInternalSelection))
{
this->ReviseSelectionChanged(m_CurrentInternalSelection, newInternalSelection);
this->SetCurrentInternalSelection(newInternalSelection);
this->OnInternalSelectionChanged();
auto newEmission = this->CompileEmitSelection();
this->EmitSelection(newEmission);
this->UpdateInfo();
}
}
void QmitkAbstractNodeSelectionWidget::SetCurrentSelection(NodeList selectedNodes)
{
if (!m_RecursionGuard)
{
m_CurrentExternalSelection = selectedNodes;
auto dataStorage = m_DataStorage.Lock();
NodeList newInternalSelection;
- for (const auto &node : qAsConst(selectedNodes))
+ for (const auto &node : std::as_const(selectedNodes))
{
if (dataStorage.IsNotNull() && dataStorage->Exists(node) && (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node)))
{
newInternalSelection.append(node);
}
}
this->HandleChangeOfInternalSelection(newInternalSelection);
}
}
const mitk::NodePredicateBase* QmitkAbstractNodeSelectionWidget::GetNodePredicate() const
{
return m_NodePredicate;
}
QString QmitkAbstractNodeSelectionWidget::GetInvalidInfo() const
{
return m_InvalidInfo;
}
QString QmitkAbstractNodeSelectionWidget::GetEmptyInfo() const
{
return m_EmptyInfo;
}
QString QmitkAbstractNodeSelectionWidget::GetPopUpTitel() const
{
return m_PopUpTitel;
}
QString QmitkAbstractNodeSelectionWidget::GetPopUpHint() const
{
return m_PopUpHint;
}
bool QmitkAbstractNodeSelectionWidget::GetSelectionIsOptional() const
{
return m_IsOptional;
}
bool QmitkAbstractNodeSelectionWidget::GetSelectOnlyVisibleNodes() const
{
return m_SelectOnlyVisibleNodes;
}
void QmitkAbstractNodeSelectionWidget::SetSelectOnlyVisibleNodes(bool selectOnlyVisibleNodes)
{
if (m_SelectOnlyVisibleNodes != selectOnlyVisibleNodes)
{
m_SelectOnlyVisibleNodes = selectOnlyVisibleNodes;
auto newEmission = this->CompileEmitSelection();
this->EmitSelection(newEmission);
}
}
void QmitkAbstractNodeSelectionWidget::SetInvalidInfo(QString info)
{
m_InvalidInfo = info;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetEmptyInfo(QString info)
{
m_EmptyInfo = info;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetPopUpTitel(QString info)
{
m_PopUpTitel = info;
}
void QmitkAbstractNodeSelectionWidget::SetPopUpHint(QString info)
{
m_PopUpHint = info;
}
void QmitkAbstractNodeSelectionWidget::SetSelectionIsOptional(bool isOptional)
{
m_IsOptional = isOptional;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetDataStorageDeleted()
{
this->OnDataStorageChanged();
this->HandleChangeOfInternalSelection({});
}
void QmitkAbstractNodeSelectionWidget::ReviseSelectionChanged(const NodeList& /*oldInternalSelection*/, NodeList& /*newInternalSelection*/)
{
}
bool QmitkAbstractNodeSelectionWidget::AllowEmissionOfSelection(const NodeList& /*emissionCandidates*/) const
{
return true;
}
void QmitkAbstractNodeSelectionWidget::EmitSelection(const NodeList& emissionCandidates)
{
m_LastEmissionAllowance = this->AllowEmissionOfSelection(emissionCandidates);
if (m_LastEmissionAllowance && !EqualNodeSelections(m_LastEmission, emissionCandidates))
{
m_RecursionGuard = true;
emit CurrentSelectionChanged(emissionCandidates);
m_RecursionGuard = false;
m_LastEmission = emissionCandidates;
}
}
void QmitkAbstractNodeSelectionWidget::SetCurrentInternalSelection(NodeList selectedNodes)
{
for (auto& node : m_CurrentInternalSelection)
{
this->RemoveNodeObserver(node);
}
m_CurrentInternalSelection = selectedNodes;
for (auto& node : m_CurrentInternalSelection)
{
this->AddNodeObserver(node);
}
}
const QmitkAbstractNodeSelectionWidget::NodeList& QmitkAbstractNodeSelectionWidget::GetCurrentInternalSelection() const
{
return m_CurrentInternalSelection;
}
const QmitkAbstractNodeSelectionWidget::NodeList& QmitkAbstractNodeSelectionWidget::GetCurrentExternalSelection() const
{
return m_CurrentExternalSelection;
}
void QmitkAbstractNodeSelectionWidget::OnNodePredicateChanged()
{
}
void QmitkAbstractNodeSelectionWidget::OnDataStorageChanged()
{
}
void QmitkAbstractNodeSelectionWidget::OnInternalSelectionChanged()
{
}
void QmitkAbstractNodeSelectionWidget::NodeAddedToStorage(const mitk::DataNode* node)
{
this->OnNodeAddedToStorage(node);
}
void QmitkAbstractNodeSelectionWidget::OnNodeAddedToStorage(const mitk::DataNode* /*node*/)
{
}
void QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage(const mitk::DataNode* node)
{
this->OnNodeRemovedFromStorage(node);
this->RemoveNodeFromSelection(node);
}
void QmitkAbstractNodeSelectionWidget::OnNodeRemovedFromStorage(const mitk::DataNode* /*node*/)
{
}
void QmitkAbstractNodeSelectionWidget::OnNodeModified(const itk::Object* caller, const itk::EventObject& event)
{
if (itk::ModifiedEvent().CheckEvent(&event))
{
auto node = dynamic_cast<const mitk::DataNode*>(caller);
if (node)
{
if (m_NodePredicate.IsNotNull() && !m_NodePredicate->CheckNode(node))
{
this->RemoveNodeFromSelection(node);
}
else
{
auto oldAllowance = m_LastEmissionAllowance;
auto newEmission = this->CompileEmitSelection();
auto nonConstNode = const_cast<mitk::DataNode*>(node);
if (newEmission.contains(nonConstNode) && (oldAllowance != this->AllowEmissionOfSelection(newEmission)))
{
this->EmitSelection(newEmission);
this->UpdateInfo();
}
}
}
}
}
QmitkAbstractNodeSelectionWidget::NodeList QmitkAbstractNodeSelectionWidget::CompileEmitSelection() const
{
NodeList result = m_CurrentInternalSelection;
if (!m_SelectOnlyVisibleNodes)
{
for (const auto &node : m_CurrentExternalSelection)
{
if (!result.contains(node) && m_NodePredicate.IsNotNull() && !m_NodePredicate->CheckNode(node))
{
result.append(node);
}
}
}
return result;
}
void QmitkAbstractNodeSelectionWidget::RemoveNodeFromSelection(const mitk::DataNode* node)
{
auto newSelection = m_CurrentInternalSelection;
auto finding = std::find(std::begin(newSelection), std::end(newSelection), node);
if (finding != std::end(newSelection))
{
newSelection.erase(finding);
this->HandleChangeOfInternalSelection(newSelection);
}
}
void QmitkAbstractNodeSelectionWidget::AddNodeObserver(mitk::DataNode* node)
{
if (node)
{
auto modifiedCommand = itk::MemberCommand<QmitkAbstractNodeSelectionWidget>::New();
modifiedCommand->SetCallbackFunction(this, &QmitkAbstractNodeSelectionWidget::OnNodeModified);
auto nodeModifiedObserverTag = node->AddObserver(itk::ModifiedEvent(), modifiedCommand);
m_NodeObserverTags.insert(std::make_pair(node, nodeModifiedObserverTag));
}
}
void QmitkAbstractNodeSelectionWidget::RemoveNodeObserver(mitk::DataNode* node)
{
if (node)
{
auto finding = m_NodeObserverTags.find(node);
if (finding != std::end(m_NodeObserverTags))
{
node->RemoveObserver(finding->second);
}
else
{
MITK_ERROR << "Selection widget is in a wrong state. A node should be removed from the internal selection but seems to have no observer. Node:" << node;
}
m_NodeObserverTags.erase(node);
}
}
diff --git a/Modules/QtWidgets/src/QmitkDataStorageFavoriteNodesInspector.cpp b/Modules/QtWidgets/src/QmitkDataStorageFavoriteNodesInspector.cpp
index 271e19c06d..80adde42ae 100644
--- a/Modules/QtWidgets/src/QmitkDataStorageFavoriteNodesInspector.cpp
+++ b/Modules/QtWidgets/src/QmitkDataStorageFavoriteNodesInspector.cpp
@@ -1,55 +1,55 @@
/*============================================================================
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 <QmitkDataStorageFavoriteNodesInspector.h>
#include "QmitkDataStorageDefaultListModel.h"
#include "mitkNodePredicateAnd.h"
#include "QPushButton"
#include "QmitkStyleManager.h"
QmitkDataStorageFavoriteNodesInspector::QmitkDataStorageFavoriteNodesInspector(QWidget* parent/* = nullptr*/)
: QmitkDataStorageListInspector(parent)
{
auto favoriteNodesButton = new QPushButton(parent);
QmitkDataStorageListInspector::m_Controls.verticalLayout->addWidget(favoriteNodesButton, 0, Qt::AlignRight);
favoriteNodesButton->setIcon(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/favorite_remove.svg")));
favoriteNodesButton->setIconSize(QSize(24, 24));
favoriteNodesButton->setToolTip("Remove selected nodes as favorite");
m_FavoriteNodeSelectionPredicate = mitk::NodePredicateProperty::New("org.mitk.selection.favorite", mitk::BoolProperty::New(true));
m_NodePredicate = m_FavoriteNodeSelectionPredicate;
connect(favoriteNodesButton, &QPushButton::clicked, this, &QmitkDataStorageFavoriteNodesInspector::OnFavoriteNodesButtonClicked);
}
void QmitkDataStorageFavoriteNodesInspector::SetNodePredicate(const mitk::NodePredicateBase* nodePredicate)
{
mitk::NodePredicateAnd::Pointer combinedPredicate = mitk::NodePredicateAnd::New();
combinedPredicate->AddPredicate(m_FavoriteNodeSelectionPredicate);
combinedPredicate->AddPredicate(nodePredicate);
QmitkDataStorageListInspector::SetNodePredicate(combinedPredicate);
}
void QmitkDataStorageFavoriteNodesInspector::OnFavoriteNodesButtonClicked()
{
auto selectedNodes = GetSelectedNodes();
- for (auto node : qAsConst(selectedNodes))
+ for (auto node : std::as_const(selectedNodes))
{
node->SetBoolProperty("org.mitk.selection.favorite", false);
}
}
diff --git a/Modules/QtWidgets/src/QmitkDnDDataNodeWidget.cpp b/Modules/QtWidgets/src/QmitkDnDDataNodeWidget.cpp
index 2b48e0e411..4481fcc6b8 100644
--- a/Modules/QtWidgets/src/QmitkDnDDataNodeWidget.cpp
+++ b/Modules/QtWidgets/src/QmitkDnDDataNodeWidget.cpp
@@ -1,69 +1,70 @@
/*============================================================================
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 <QmitkDnDDataNodeWidget.h>
// mitk qt widgets module
#include "QmitkMimeTypes.h"
// qt
#include <QMimeData>
#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QDropEvent>
QmitkDnDDataNodeWidget::QmitkDnDDataNodeWidget(QWidget* parent /*= nullptr*/)
: QFrame(parent)
{
this->setAcceptDrops(true);
}
QmitkDnDDataNodeWidget::~QmitkDnDDataNodeWidget()
{
// nothing here
}
void QmitkDnDDataNodeWidget::dragEnterEvent(QDragEnterEvent* event)
{
if (this != event->source())
{
event->acceptProposedAction();
}
else
{
event->ignore();
}
}
void QmitkDnDDataNodeWidget::dragMoveEvent(QDragMoveEvent* event)
{
if (event->mimeData()->hasFormat(QmitkMimeTypes::DataNodePtrs))
{
event->acceptProposedAction();
}
else
{
event->ignore();
}
}
void QmitkDnDDataNodeWidget::dropEvent(QDropEvent* event)
{
QList<mitk::DataNode*> dataNodeList = QmitkMimeTypes::ToDataNodePtrList(event->mimeData());
if (!dataNodeList.empty())
{
- emit NodesDropped(dataNodeList.toVector().toStdVector());
+ std::vector<mitk::DataNode*> nodes(dataNodeList.begin(), dataNodeList.end());
+ emit NodesDropped(nodes);
}
event->acceptProposedAction();
}
diff --git a/Modules/QtWidgets/src/QmitkIOUtil.cpp b/Modules/QtWidgets/src/QmitkIOUtil.cpp
index 053a231c77..e8f59fc640 100644
--- a/Modules/QtWidgets/src/QmitkIOUtil.cpp
+++ b/Modules/QtWidgets/src/QmitkIOUtil.cpp
@@ -1,586 +1,587 @@
/*============================================================================
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 "QmitkIOUtil.h"
#include "mitkCoreServices.h"
#include "mitkCustomMimeType.h"
#include "mitkFileReaderRegistry.h"
#include "mitkFileWriterRegistry.h"
#include "mitkIMimeTypeProvider.h"
#include "mitkMimeType.h"
#include <mitkCoreObjectFactory.h>
#include <mitkIOUtil.h>
#include "QmitkFileReaderOptionsDialog.h"
#include "QmitkFileWriterOptionsDialog.h"
// QT
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QSet>
#include <QString>
+#include <QStringList>
// ITK
#include <itksys/SystemTools.hxx>
#include <algorithm>
struct QmitkIOUtil::Impl
{
struct ReaderOptionsDialogFunctor : public ReaderOptionsFunctorBase
{
bool operator()(LoadInfo &loadInfo) const override
{
QmitkFileReaderOptionsDialog dialog(loadInfo);
if (dialog.exec() == QDialog::Accepted)
{
return !dialog.ReuseOptions();
}
else
{
loadInfo.m_Cancel = true;
return true;
}
}
};
struct WriterOptionsDialogFunctor : public WriterOptionsFunctorBase
{
bool operator()(SaveInfo &saveInfo) const override
{
QmitkFileWriterOptionsDialog dialog(saveInfo);
if (dialog.exec() == QDialog::Accepted)
{
return !dialog.ReuseOptions();
}
else
{
saveInfo.m_Cancel = true;
return true;
}
}
};
//! Filename characters that are not valid - depending on the platform (Windows, Posix)
static QString s_InvalidFilenameCharacters;
//! Return 'true' when:
//! - the specified filename contains characters not accepted by the file system (see s_InvalidFilenameCharacters)
//! - filename starts or ends in space characters
//!
//! This test is not exhaustive but just excluding the most common problems.
static bool IsIllegalFilename(const QString &fullFilename)
{
QFileInfo fi(fullFilename);
auto filename = fi.fileName();
- for (const auto &ch : qAsConst(s_InvalidFilenameCharacters))
+ for (const auto &ch : std::as_const(s_InvalidFilenameCharacters))
{
if (filename.contains(ch))
{
return true;
}
}
if (filename.startsWith(' ') || filename.endsWith(' '))
{
return true;
}
return false;
}
}; // Impl
#if defined(_WIN32) || defined(_WIN64)
QString QmitkIOUtil::Impl::s_InvalidFilenameCharacters = "<>:\"/\\|?*";
#else
QString QmitkIOUtil::Impl::s_InvalidFilenameCharacters = "/";
#endif
struct MimeTypeComparison
{
MimeTypeComparison(const std::string &mimeTypeName) : m_Name(mimeTypeName) {}
bool operator()(const mitk::MimeType &mimeType) const { return mimeType.GetName() == m_Name; }
const std::string m_Name;
};
QString QmitkIOUtil::GetFileOpenFilterString()
{
QString filters;
mitk::CoreServicePointer<mitk::IMimeTypeProvider> mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider());
std::vector<std::string> categories = mimeTypeProvider->GetCategories();
for (std::vector<std::string>::iterator cat = categories.begin(); cat != categories.end(); ++cat)
{
QSet<QString> filterExtensions;
std::vector<mitk::MimeType> mimeTypes = mimeTypeProvider->GetMimeTypesForCategory(*cat);
for (std::vector<mitk::MimeType>::iterator mt = mimeTypes.begin(); mt != mimeTypes.end(); ++mt)
{
std::vector<std::string> extensions = mt->GetExtensions();
for (std::vector<std::string>::iterator ext = extensions.begin(); ext != extensions.end(); ++ext)
{
filterExtensions << QString::fromStdString(*ext);
}
}
QString filter = QString::fromStdString(*cat) + " (";
foreach (const QString &extension, filterExtensions)
{
filter += "*." + extension + " ";
}
filter = filter.replace(filter.size() - 1, 1, ')');
filters += ";;" + filter;
}
filters.prepend("All (*)");
return filters;
}
QList<mitk::BaseData::Pointer> QmitkIOUtil::Load(const QStringList &paths, QWidget *parent)
{
std::vector<LoadInfo> loadInfos;
foreach (const QString &file, paths)
{
loadInfos.push_back(LoadInfo(file.toLocal8Bit().constData()));
}
Impl::ReaderOptionsDialogFunctor optionsCallback;
std::string errMsg = Load(loadInfos, nullptr, nullptr, &optionsCallback);
if (!errMsg.empty())
{
QMessageBox::warning(parent, "Error reading files", QString::fromStdString(errMsg));
mitkThrow() << errMsg;
}
QList<mitk::BaseData::Pointer> qResult;
for (std::vector<LoadInfo>::const_iterator iter = loadInfos.begin(), iterEnd = loadInfos.end(); iter != iterEnd;
++iter)
{
for (const auto &elem : iter->m_Output)
{
qResult << elem;
}
}
return qResult;
}
mitk::DataStorage::SetOfObjects::Pointer QmitkIOUtil::Load(const QStringList &paths,
mitk::DataStorage &storage,
QWidget *parent)
{
std::vector<LoadInfo> loadInfos;
foreach (const QString &file, paths)
{
loadInfos.push_back(LoadInfo(file.toLocal8Bit().constData()));
}
mitk::DataStorage::SetOfObjects::Pointer nodeResult = mitk::DataStorage::SetOfObjects::New();
Impl::ReaderOptionsDialogFunctor optionsCallback;
std::string errMsg = Load(loadInfos, nodeResult, &storage, &optionsCallback);
if (!errMsg.empty())
{
QMessageBox::warning(parent, "Error reading files", QString::fromStdString(errMsg));
}
return nodeResult;
}
QList<mitk::BaseData::Pointer> QmitkIOUtil::Load(const QString &path, QWidget *parent)
{
QStringList paths;
paths << path;
return Load(paths, parent);
}
mitk::DataStorage::SetOfObjects::Pointer QmitkIOUtil::Load(const QString &path,
mitk::DataStorage &storage,
QWidget *parent)
{
QStringList paths;
paths << path;
return Load(paths, storage, parent);
}
QString QmitkIOUtil::Save(const mitk::BaseData *data,
const QString &defaultBaseName,
const QString &defaultPath,
QWidget *parent,
bool setPathProperty)
{
std::vector<const mitk::BaseData *> dataVector;
dataVector.push_back(data);
QStringList defaultBaseNames;
defaultBaseNames.push_back(defaultBaseName);
return Save(dataVector, defaultBaseNames, defaultPath, parent, setPathProperty).back();
}
QStringList QmitkIOUtil::Save(const std::vector<const mitk::BaseData *> &data,
const QStringList &defaultBaseNames,
const QString &defaultPath,
QWidget *parent,
bool setPathProperty)
{
QStringList fileNames;
QString currentPath = defaultPath;
std::vector<SaveInfo> saveInfos;
int counter = 0;
for (std::vector<const mitk::BaseData *>::const_iterator dataIter = data.begin(), dataIterEnd = data.end();
dataIter != dataIterEnd;
++dataIter, ++counter)
{
SaveInfo saveInfo(*dataIter, mitk::MimeType(), std::string());
SaveFilter filters(saveInfo);
// If there is only the "__all__" filter string, it means there is no writer for this base data
if (filters.Size() < 2)
{
QMessageBox::warning(
parent,
"Saving not possible",
QString("No writer available for type \"%1\"").arg(QString::fromStdString((*dataIter)->GetNameOfClass())));
continue;
}
// Construct a default path and file name
QString filterString = filters.ToString();
QString selectedFilter = filters.GetDefaultFilter();
QString fileName = currentPath;
QString dialogTitle = "Save " + QString::fromStdString((*dataIter)->GetNameOfClass());
if (counter < defaultBaseNames.size())
{
dialogTitle += " \"" + defaultBaseNames[counter] + "\"";
fileName += QDir::separator() + defaultBaseNames[counter];
// We do not append an extension to the file name by default. The extension
// is chosen by the user by either selecting a filter or writing the
// extension in the file name himself (in the file save dialog).
/*
QString defaultExt = filters.GetDefaultExtension();
if (!defaultExt.isEmpty())
{
fileName += "." + defaultExt;
}
*/
}
// Ask the user for a file name
QString nextName = QFileDialog::getSaveFileName(parent, dialogTitle, fileName, filterString, &selectedFilter);
if (Impl::IsIllegalFilename(nextName))
{
QMessageBox::warning(
parent,
"Saving not possible",
QString("File \"%2\" contains invalid characters.\n\nPlease avoid any of \"%1\"")
- .arg(Impl::s_InvalidFilenameCharacters.split("", QString::SkipEmptyParts).join(" "))
+ .arg(Impl::s_InvalidFilenameCharacters.split("", Qt::SkipEmptyParts).join(" "))
.arg(nextName));
continue;
}
if (nextName.isEmpty())
{
// We stop asking for further file names, but we still save the
// data where the user already confirmed the save dialog.
break;
}
fileName = nextName;
std::string stdFileName = fileName.toLocal8Bit().constData();
QFileInfo fileInfo(fileName);
currentPath = fileInfo.absolutePath();
QString suffix = fileInfo.completeSuffix();
mitk::MimeType filterMimeType = filters.GetMimeTypeForFilter(selectedFilter);
mitk::MimeType selectedMimeType;
if (fileInfo.exists() && !fileInfo.isFile())
{
QMessageBox::warning(parent, "Saving not possible", QString("The path \"%1\" is not a file").arg(fileName));
continue;
}
// Theoretically, the user could have entered an extension that does not match the selected filter
// The extension then has prioritry over the filter
// Check if one of the available mime-types match the filename
std::vector<mitk::MimeType> filterMimeTypes = filters.GetMimeTypes();
for (std::vector<mitk::MimeType>::const_iterator mimeTypeIter = filterMimeTypes.begin(),
mimeTypeIterEnd = filterMimeTypes.end();
mimeTypeIter != mimeTypeIterEnd;
++mimeTypeIter)
{
if (mimeTypeIter->MatchesExtension(stdFileName))
{
selectedMimeType = *mimeTypeIter;
break;
}
}
if (!selectedMimeType.IsValid())
{
// The file name either does not contain an extension or the
// extension is unknown.
// If the file already exists, we stop here because we are unable
// to (over)write the file without adding a custom suffix. If the file
// does not exist, we add the default extension from the currently
// selected filter. If the "All" filter was selected, we only add the
// default extensions if the file name itself does not already contain
// an extension.
if (!fileInfo.exists())
{
if (filterMimeType == SaveFilter::ALL_MIMETYPE())
{
if (suffix.isEmpty())
{
// Use the highest ranked mime-type from the list
selectedMimeType = filters.GetDefaultMimeType();
}
}
else
{
selectedMimeType = filterMimeType;
}
if (selectedMimeType.IsValid())
{
suffix = QString::fromStdString(selectedMimeType.GetExtensions().front());
fileName += "." + suffix;
stdFileName = fileName.toLocal8Bit().constData();
// We changed the file name (added a suffix) so ask in case
// the file aready exists.
fileInfo = QFileInfo(fileName);
if (fileInfo.exists())
{
if (!fileInfo.isFile())
{
QMessageBox::warning(
parent, "Saving not possible", QString("The path \"%1\" is not a file").arg(fileName));
continue;
}
if (QMessageBox::question(
parent,
"Replace File",
QString("A file named \"%1\" already exists. Do you want to replace it?").arg(fileName)) ==
QMessageBox::No)
{
continue;
}
}
}
}
}
if (!selectedMimeType.IsValid())
{
// The extension/filename is not valid (no mime-type found), bail out
QMessageBox::warning(
parent, "Saving not possible", QString("No mime-type available which can handle \"%1\".").arg(fileName));
continue;
}
if (!QFileInfo(fileInfo.absolutePath()).isWritable())
{
QMessageBox::warning(parent, "Saving not possible", QString("The path \"%1\" is not writable").arg(fileName));
continue;
}
fileNames.push_back(fileName);
saveInfo.m_Path = stdFileName;
saveInfo.m_MimeType = selectedMimeType;
// pre-select the best writer for the chosen mime-type
saveInfo.m_WriterSelector.Select(selectedMimeType.GetName());
saveInfos.push_back(saveInfo);
}
if (!saveInfos.empty())
{
Impl::WriterOptionsDialogFunctor optionsCallback;
std::string errMsg = Save(saveInfos, &optionsCallback, setPathProperty);
if (!errMsg.empty())
{
QMessageBox::warning(parent, "Error writing files", QString::fromStdString(errMsg));
mitkThrow() << errMsg;
}
}
return fileNames;
}
void QmitkIOUtil::SaveBaseDataWithDialog(mitk::BaseData *data, std::string fileName, QWidget * /*parent*/)
{
Save(data, fileName);
}
void QmitkIOUtil::SaveSurfaceWithDialog(mitk::Surface::Pointer surface, std::string fileName, QWidget * /*parent*/)
{
Save(surface, fileName);
}
void QmitkIOUtil::SaveImageWithDialog(mitk::Image::Pointer image, std::string fileName, QWidget * /*parent*/)
{
Save(image, fileName);
}
void QmitkIOUtil::SavePointSetWithDialog(mitk::PointSet::Pointer pointset, std::string fileName, QWidget * /*parent*/)
{
Save(pointset, fileName);
}
struct QmitkIOUtil::SaveFilter::Impl
{
Impl(const mitk::IOUtil::SaveInfo &saveInfo) : m_SaveInfo(saveInfo)
{
// Add an artifical filter for "All"
m_MimeTypes.push_back(ALL_MIMETYPE());
m_FilterStrings.push_back("All (*.*)");
// Get all writers and their mime types for the given base data type
// (this is sorted already)
std::vector<mitk::MimeType> mimeTypes = saveInfo.m_WriterSelector.GetMimeTypes();
for (std::vector<mitk::MimeType>::const_reverse_iterator iter = mimeTypes.rbegin(), iterEnd = mimeTypes.rend();
iter != iterEnd;
++iter)
{
QList<QString> filterExtensions;
mitk::MimeType mimeType = *iter;
std::vector<std::string> extensions = mimeType.GetExtensions();
for (auto &extension : extensions)
{
filterExtensions << QString::fromStdString(extension);
}
if (m_DefaultExtension.isEmpty())
{
m_DefaultExtension = QString::fromStdString(extensions.front());
}
QString filter = QString::fromStdString(mimeType.GetComment()) + " (";
foreach (const QString &extension, filterExtensions)
{
filter += "*." + extension + " ";
}
filter = filter.replace(filter.size() - 1, 1, ')');
m_MimeTypes.push_back(mimeType);
m_FilterStrings.push_back(filter);
}
}
const mitk::IOUtil::SaveInfo m_SaveInfo;
std::vector<mitk::MimeType> m_MimeTypes;
QStringList m_FilterStrings;
QString m_DefaultExtension;
};
mitk::MimeType QmitkIOUtil::SaveFilter::ALL_MIMETYPE()
{
static mitk::CustomMimeType allMimeType(std::string("__all__"));
return mitk::MimeType(allMimeType, -1, -1);
}
QmitkIOUtil::SaveFilter::SaveFilter(const QmitkIOUtil::SaveFilter &other) : d(new Impl(*other.d))
{
}
QmitkIOUtil::SaveFilter::SaveFilter(const SaveInfo &saveInfo) : d(new Impl(saveInfo))
{
}
QmitkIOUtil::SaveFilter &QmitkIOUtil::SaveFilter::operator=(const QmitkIOUtil::SaveFilter &other)
{
d.reset(new Impl(*other.d));
return *this;
}
std::vector<mitk::MimeType> QmitkIOUtil::SaveFilter::GetMimeTypes() const
{
return d->m_MimeTypes;
}
QString QmitkIOUtil::SaveFilter::GetFilterForMimeType(const std::string &mimeType) const
{
std::vector<mitk::MimeType>::const_iterator iter =
std::find_if(d->m_MimeTypes.begin(), d->m_MimeTypes.end(), MimeTypeComparison(mimeType));
if (iter == d->m_MimeTypes.end())
{
return QString();
}
int index = static_cast<int>(iter - d->m_MimeTypes.begin());
if (index < 0 || index >= d->m_FilterStrings.size())
{
return QString();
}
return d->m_FilterStrings[index];
}
mitk::MimeType QmitkIOUtil::SaveFilter::GetMimeTypeForFilter(const QString &filter) const
{
int index = d->m_FilterStrings.indexOf(filter);
if (index < 0)
{
return mitk::MimeType();
}
return d->m_MimeTypes[index];
}
QString QmitkIOUtil::SaveFilter::GetDefaultFilter() const
{
if (d->m_FilterStrings.size() > 1)
{
return d->m_FilterStrings.at(1);
}
else if (d->m_FilterStrings.size() > 0)
{
return d->m_FilterStrings.front();
}
return QString();
}
QString QmitkIOUtil::SaveFilter::GetDefaultExtension() const
{
return d->m_DefaultExtension;
}
mitk::MimeType QmitkIOUtil::SaveFilter::GetDefaultMimeType() const
{
if (d->m_MimeTypes.size() > 1)
{
return d->m_MimeTypes.at(1);
}
else if (d->m_MimeTypes.size() > 0)
{
return d->m_MimeTypes.front();
}
return mitk::MimeType();
}
QString QmitkIOUtil::SaveFilter::ToString() const
{
return d->m_FilterStrings.join(";;");
}
int QmitkIOUtil::SaveFilter::Size() const
{
return d->m_FilterStrings.size();
}
bool QmitkIOUtil::SaveFilter::IsEmpty() const
{
return d->m_FilterStrings.isEmpty();
}
bool QmitkIOUtil::SaveFilter::ContainsMimeType(const std::string &mimeType)
{
return std::find_if(d->m_MimeTypes.begin(), d->m_MimeTypes.end(), MimeTypeComparison(mimeType)) !=
d->m_MimeTypes.end();
}
diff --git a/Modules/QtWidgets/src/QmitkLineEditLevelWindowWidget.cpp b/Modules/QtWidgets/src/QmitkLineEditLevelWindowWidget.cpp
index e11dcbfb6a..29223cadf2 100644
--- a/Modules/QtWidgets/src/QmitkLineEditLevelWindowWidget.cpp
+++ b/Modules/QtWidgets/src/QmitkLineEditLevelWindowWidget.cpp
@@ -1,168 +1,168 @@
/*============================================================================
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 "QmitkLineEditLevelWindowWidget.h"
// mitk core
#include <mitkRenderingManager.h>
// mitk qt widgets
#include <QmitkLevelWindowWidgetContextMenu.h>
// qt
#include <QLayout>
#include <QLineEdit>
#include <QValidator>
// itk
#include <itkCommand.h>
// c++
#include <limits>
#include <sstream>
QmitkLineEditLevelWindowWidget::QmitkLineEditLevelWindowWidget(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f)
{
m_Manager = mitk::LevelWindowManager::New();
itk::ReceptorMemberCommand<QmitkLineEditLevelWindowWidget>::Pointer command =
itk::ReceptorMemberCommand<QmitkLineEditLevelWindowWidget>::New();
command->SetCallbackFunction(this, &QmitkLineEditLevelWindowWidget::OnPropertyModified);
m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command);
m_IsObserverTagSet = true;
m_Contextmenu = new QmitkLevelWindowWidgetContextMenu(this);
auto layout = new QVBoxLayout(this);
- layout->setMargin(0);
+ layout->setContentsMargins({});
layout->setSpacing(0);
m_LevelInput = new QLineEdit(this);
m_LevelInput->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred));
m_LevelInput->setToolTip("Edit this field to change the center of the levelwindow.");
m_WindowInput = new QLineEdit(this);
m_WindowInput->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred));
m_WindowInput->setToolTip(
"Edit this field to change the span of the levelwindow. This number describes the whole span around the center.");
layout->addWidget(m_LevelInput);
layout->addWidget(m_WindowInput);
// signals and slots connections
connect(m_LevelInput, SIGNAL(editingFinished()), this, SLOT(SetLevelValue()));
connect(m_WindowInput, SIGNAL(editingFinished()), this, SLOT(SetWindowValue()));
// Validator for both LineEdit-widgets, to limit the valid input-range to int.
QValidator *validatorWindowInput = new QDoubleValidator(0, std::numeric_limits<double>::max(), 2, this);
m_WindowInput->setValidator(validatorWindowInput);
this->hide();
}
QmitkLineEditLevelWindowWidget::~QmitkLineEditLevelWindowWidget()
{
if (m_IsObserverTagSet)
{
m_Manager->RemoveObserver(m_ObserverTag);
m_IsObserverTagSet = false;
}
}
void QmitkLineEditLevelWindowWidget::OnPropertyModified(const itk::EventObject &)
{
try
{
m_LevelWindow = m_Manager->GetLevelWindow();
QString level;
QString window;
if (m_LevelWindow.IsFloatingValues())
{
std::stringstream ssLevel;
std::stringstream ssWindow;
ssLevel << std::setprecision(3) << m_LevelWindow.GetLevel();
ssWindow << std::setprecision(3) << m_LevelWindow.GetWindow();
level = ssLevel.str().c_str();
window = ssWindow.str().c_str();
}
else
{
level.setNum((int)(m_LevelWindow.GetLevel()));
window.setNum((int)(m_LevelWindow.GetWindow()));
}
m_LevelInput->setText(level);
m_WindowInput->setText(window);
m_LevelInput->setEnabled(!m_LevelWindow.IsFixed());
m_WindowInput->setEnabled(!m_LevelWindow.IsFixed());
this->show();
}
catch (...)
{
try
{
this->hide();
}
catch (...)
{
}
}
}
void QmitkLineEditLevelWindowWidget::SetLevelWindowManager(mitk::LevelWindowManager *levelWindowManager)
{
if (m_IsObserverTagSet)
{
m_Manager->RemoveObserver(m_ObserverTag);
m_IsObserverTagSet = false;
}
m_Manager = levelWindowManager;
if (m_Manager.IsNotNull())
{
itk::ReceptorMemberCommand<QmitkLineEditLevelWindowWidget>::Pointer command =
itk::ReceptorMemberCommand<QmitkLineEditLevelWindowWidget>::New();
command->SetCallbackFunction(this, &QmitkLineEditLevelWindowWidget::OnPropertyModified);
m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command);
m_IsObserverTagSet = true;
}
}
void QmitkLineEditLevelWindowWidget::SetDataStorage(mitk::DataStorage *ds)
{
m_Manager->SetDataStorage(ds);
}
void QmitkLineEditLevelWindowWidget::SetLevelValue()
{
double level = m_LevelInput->text().toDouble();
m_LevelWindow.SetLevelWindow(level, m_LevelWindow.GetWindow());
m_Manager->SetLevelWindow(m_LevelWindow);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkLineEditLevelWindowWidget::SetWindowValue()
{
double window = m_WindowInput->text().toDouble();
m_LevelWindow.SetLevelWindow(m_LevelWindow.GetLevel(), window);
m_Manager->SetLevelWindow(m_LevelWindow);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkLineEditLevelWindowWidget::contextMenuEvent(QContextMenuEvent *)
{
m_Contextmenu->SetLevelWindowManager(m_Manager.GetPointer());
m_Contextmenu->GetContextMenu();
}
mitk::LevelWindowManager *QmitkLineEditLevelWindowWidget::GetManager()
{
return m_Manager.GetPointer();
}
diff --git a/Modules/QtWidgets/src/QmitkModelViewSelectionConnector.cpp b/Modules/QtWidgets/src/QmitkModelViewSelectionConnector.cpp
index a52e840471..a30399c0e5 100644
--- a/Modules/QtWidgets/src/QmitkModelViewSelectionConnector.cpp
+++ b/Modules/QtWidgets/src/QmitkModelViewSelectionConnector.cpp
@@ -1,185 +1,185 @@
/*============================================================================
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 gui qt common plugin
#include "QmitkModelViewSelectionConnector.h"
// qt widgets module
#include "QmitkCustomVariants.h"
#include "QmitkEnums.h"
QmitkModelViewSelectionConnector::QmitkModelViewSelectionConnector()
: m_Model(nullptr)
, m_View(nullptr)
, m_SelectOnlyVisibleNodes(false)
{
// nothing here
}
void QmitkModelViewSelectionConnector::SetView(QAbstractItemView* view)
{
if (nullptr != m_View)
{
disconnect(m_View->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(ChangeModelSelection(const QItemSelection&, const QItemSelection&)));
}
// reset model-view pair and check for valid function argument
m_View = nullptr;
if (nullptr == view)
{
mitkThrow() << "Invalid item view. To use the model-view selection connector please specify a valid 'QAbstractItemView'.";
}
auto storageModel = dynamic_cast<QmitkAbstractDataStorageModel*>(view->model());
if (storageModel == nullptr)
{
mitkThrow() << "Invalid data model. To use the model-view selection connector please set a valid 'QmitkAbstractDataStorageModel' for the given item view.";
}
// a valid item view and a valid data model was found
m_View = view;
m_Model = storageModel;
connect(m_View->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), SLOT(ChangeModelSelection(const QItemSelection&, const QItemSelection&)));
}
void QmitkModelViewSelectionConnector::SetSelectOnlyVisibleNodes(bool selectOnlyVisibleNodes)
{
m_SelectOnlyVisibleNodes = selectOnlyVisibleNodes;
}
void QmitkModelViewSelectionConnector::SetCurrentSelection(QList<mitk::DataNode::Pointer> selectedNodes)
{
if (nullptr == m_Model || nullptr == m_View)
{
return;
}
// filter input nodes and return the modified input node list
QList<mitk::DataNode::Pointer> filteredNodes = FilterNodeList(selectedNodes);
bool equal = EqualNodeSelections(this->GetInternalSelectedNodes(), filteredNodes);
if (equal)
{
return;
}
if (!m_SelectOnlyVisibleNodes)
{
// store the unmodified selection
m_NonVisibleSelection = selectedNodes;
// remove the nodes in the original selection that are already contained in the filtered input node list
// this will keep the selection of the original nodes that are not presented by the current view unmodified, but allows to change the selection of the filtered nodes
// later, the nodes of the 'm_NonVisibleSelection' member have to be added again to the list of selected (filtered) nodes, if a selection is sent from the current view (see 'ModelSelectionChanged')
auto lambda = [&filteredNodes](mitk::DataNode::Pointer original) { return filteredNodes.contains(original); };
m_NonVisibleSelection.erase(std::remove_if(m_NonVisibleSelection.begin(), m_NonVisibleSelection.end(), lambda), m_NonVisibleSelection.end());
}
// create new selection by retrieving the corresponding indices of the (filtered) nodes
QItemSelection newCurrentSelection;
- for (const auto& node : qAsConst(filteredNodes))
+ for (const auto& node : std::as_const(filteredNodes))
{
QModelIndexList matched = m_Model->match(m_Model->index(0, 0), QmitkDataNodeRole, QVariant::fromValue<mitk::DataNode::Pointer>(node), 1, Qt::MatchRecursive);
if (!matched.empty())
{
newCurrentSelection.select(matched.front(), matched.front());
}
}
m_View->selectionModel()->select(newCurrentSelection, QItemSelectionModel::ClearAndSelect);
}
void QmitkModelViewSelectionConnector::ChangeModelSelection(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/)
{
emit CurrentSelectionChanged(GetSelectedNodes());
}
bool QmitkModelViewSelectionConnector::GetSelectOnlyVisibleNodes() const
{
return m_SelectOnlyVisibleNodes;
}
QList<mitk::DataNode::Pointer> QmitkModelViewSelectionConnector::GetSelectedNodes() const
{
auto nodes = GetInternalSelectedNodes();
if (!m_SelectOnlyVisibleNodes)
{
// add the non-visible nodes from the original selection
nodes.append(m_NonVisibleSelection);
}
return nodes;
}
QList<mitk::DataNode::Pointer> QmitkModelViewSelectionConnector::GetInternalSelectedNodes() const
{
if (nullptr == m_Model || nullptr == m_View)
{
return QList<mitk::DataNode::Pointer>();
}
QList<mitk::DataNode::Pointer> nodes;
QModelIndexList selectedIndexes = m_View->selectionModel()->selectedIndexes();
- for (const auto& index : qAsConst(selectedIndexes))
+ for (const auto& index : std::as_const(selectedIndexes))
{
QVariant qvariantDataNode = m_Model->data(index, QmitkDataNodeRole);
if (qvariantDataNode.canConvert<mitk::DataNode::Pointer>())
{
nodes.push_back(qvariantDataNode.value<mitk::DataNode::Pointer>());
}
}
return nodes;
}
QList<mitk::DataNode::Pointer> QmitkModelViewSelectionConnector::FilterNodeList(const QList<mitk::DataNode::Pointer>& nodes) const
{
if (nodes.isEmpty())
{
return QList<mitk::DataNode::Pointer>();
}
if (nullptr == m_Model)
{
return nodes;
}
auto nodePredicate = m_Model->GetNodePredicate();
if (nullptr == nodePredicate)
{
// no filter set
return nodes;
}
QList<mitk::DataNode::Pointer> result;
for (const auto& node : nodes)
{
if (true == nodePredicate->CheckNode(node))
{
result.push_back(node);
}
}
return result;
}
bool MITKQTWIDGETS_EXPORT EqualNodeSelections(const QList<mitk::DataNode::Pointer>& selection1, const QList<mitk::DataNode::Pointer>& selection2)
{
if (selection1.size() == selection2.size())
{
// lambda to compare node pointer inside both lists
auto lambda = [](mitk::DataNode::Pointer lhs, mitk::DataNode::Pointer rhs) { return lhs == rhs; };
return std::is_permutation(selection1.begin(), selection1.end(), selection2.begin(), selection2.end(), lambda);
}
return false;
}
diff --git a/Modules/QtWidgets/src/QmitkMultiWidgetLayoutManager.cpp b/Modules/QtWidgets/src/QmitkMultiWidgetLayoutManager.cpp
index 96b441e343..51bf4daa58 100644
--- a/Modules/QtWidgets/src/QmitkMultiWidgetLayoutManager.cpp
+++ b/Modules/QtWidgets/src/QmitkMultiWidgetLayoutManager.cpp
@@ -1,541 +1,541 @@
/*============================================================================
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 "QmitkMultiWidgetLayoutManager.h"
#include <mitkLog.h>
#include <QmitkAbstractMultiWidget.h>
#include <QmitkRenderWindow.h>
#include <QmitkRenderWindowWidget.h>
// qt
#include <QHBoxLayout>
#include <qsplitter.h>
QmitkMultiWidgetLayoutManager::QmitkMultiWidgetLayoutManager(QmitkAbstractMultiWidget* multiwidget)
: QObject(multiwidget)
, m_MultiWidget(multiwidget)
, m_CurrentRenderWindowWidget(nullptr)
{
// nothing here
}
void QmitkMultiWidgetLayoutManager::SetLayoutDesign(LayoutDesign layoutDesign)
{
if (nullptr == m_MultiWidget)
{
return;
}
// retrieve the render window name from the sending render window
auto renderWindow = dynamic_cast<QmitkRenderWindow*>(QObject::sender());
m_CurrentRenderWindowWidget = m_MultiWidget->GetRenderWindowWidget(renderWindow).get();
switch (layoutDesign)
{
case LayoutDesign::DEFAULT:
{
SetDefaultLayout();
break;
}
case LayoutDesign::ALL_2D_TOP_3D_BOTTOM:
{
SetAll2DTop3DBottomLayout();
break;
}
case LayoutDesign::ALL_2D_LEFT_3D_RIGHT:
{
SetAll2DLeft3DRightLayout();
break;
}
case LayoutDesign::ONE_BIG:
{
SetOneBigLayout();
break;
}
case LayoutDesign::ONLY_2D_HORIZONTAL:
{
SetOnly2DHorizontalLayout();
break;
}
case LayoutDesign::ONLY_2D_VERTICAL:
{
SetOnly2DVerticalLayout();
break;
}
case LayoutDesign::ONE_TOP_3D_BOTTOM:
{
SetOneTop3DBottomLayout();
break;
}
case LayoutDesign::ONE_LEFT_3D_RIGHT:
{
SetOneLeft3DRightLayout();
break;
}
case LayoutDesign::ALL_HORIZONTAL:
{
SetAllHorizontalLayout();
break;
}
case LayoutDesign::ALL_VERTICAL:
{
SetAllVerticalLayout();
break;
}
case LayoutDesign::REMOVE_ONE:
{
RemoveOneLayout();
break;
}
case LayoutDesign::NONE:
{
break;
}
};
}
void QmitkMultiWidgetLayoutManager::SetCurrentRenderWindowWidget(QmitkRenderWindowWidget* renderWindowWidget)
{
m_CurrentRenderWindowWidget = renderWindowWidget;
}
void QmitkMultiWidgetLayoutManager::SetDefaultLayout()
{
MITK_DEBUG << "Set default layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(Qt::Vertical, m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
QList<int> splitterSizeRow;
for (int row = 0; row < m_MultiWidget->GetRowCount(); ++row)
{
splitterSizeRow.push_back(1000);
QList<int> splitterSizeColumn;
auto splitter = new QSplitter(mainSplit);
for (int column = 0; column < m_MultiWidget->GetColumnCount(); ++column)
{
splitterSizeColumn.push_back(1000);
auto renderWindowWidget = m_MultiWidget->GetRenderWindowWidget(row, column);
splitter->addWidget(renderWindowWidget.get());
renderWindowWidget->show();
}
splitter->setSizes(splitterSizeColumn);
}
mainSplit->setSizes(splitterSizeRow);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::DEFAULT);
}
}
void QmitkMultiWidgetLayoutManager::SetAll2DTop3DBottomLayout()
{
MITK_DEBUG << "Set all 2D top and 3D bottom layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(Qt::Vertical, m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
auto subSplit2D = new QSplitter(mainSplit);
QList<int> splitterSize;
auto all2DRenderWindowWidgets = m_MultiWidget->Get2DRenderWindowWidgets();
for (const auto& renderWindowWidget : all2DRenderWindowWidgets)
{
subSplit2D->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
subSplit2D->setSizes(splitterSize);
auto subSplit3D = new QSplitter(mainSplit);
splitterSize.clear();
auto all3DRenderWindowWidgets = m_MultiWidget->Get3DRenderWindowWidgets();
for (const auto& renderWindowWidget : all3DRenderWindowWidgets)
{
subSplit3D->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
subSplit3D->setSizes(splitterSize);
// set size for main splitter
splitterSize.clear();
splitterSize.push_back(600);
splitterSize.push_back(1000);
mainSplit->setSizes(splitterSize);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ALL_2D_TOP_3D_BOTTOM);
}
}
void QmitkMultiWidgetLayoutManager::SetAll2DLeft3DRightLayout()
{
MITK_DEBUG << "Set all 2D left and 3D right layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
auto subSplit2D = new QSplitter(Qt::Vertical, mainSplit);
QList<int> splitterSize;
auto all2DRenderWindowWidgets = m_MultiWidget->Get2DRenderWindowWidgets();
for (const auto& renderWindowWidget : all2DRenderWindowWidgets)
{
subSplit2D->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
subSplit2D->setSizes(splitterSize);
auto subSplit3D = new QSplitter(mainSplit);
splitterSize.clear();
auto all3DRenderWindowWidgets = m_MultiWidget->Get3DRenderWindowWidgets();
for (const auto& renderWindowWidget : all3DRenderWindowWidgets)
{
subSplit3D->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
subSplit3D->setSizes(splitterSize);
// set size for main splitter
splitterSize.clear();
splitterSize.push_back(600);
splitterSize.push_back(1000);
mainSplit->setSizes(splitterSize);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ALL_2D_LEFT_3D_RIGHT);
}
}
void QmitkMultiWidgetLayoutManager::SetOneBigLayout()
{
MITK_DEBUG << "Set single 2D layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
mainSplit->addWidget(m_CurrentRenderWindowWidget);
m_CurrentRenderWindowWidget->show();
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ONE_BIG);
}
}
void QmitkMultiWidgetLayoutManager::SetOnly2DHorizontalLayout()
{
MITK_DEBUG << "Set only 2D layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
QList<int> splitterSize;
auto all2DRenderWindowWidgets = m_MultiWidget->Get2DRenderWindowWidgets();
for (const auto& renderWindowWidget : all2DRenderWindowWidgets)
{
mainSplit->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
mainSplit->setSizes(splitterSize);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ONLY_2D_HORIZONTAL);
}
}
void QmitkMultiWidgetLayoutManager::SetOnly2DVerticalLayout()
{
MITK_DEBUG << "Set only 2D layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(Qt::Vertical, m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
QList<int> splitterSize;
auto all2DRenderWindowWidgets = m_MultiWidget->Get2DRenderWindowWidgets();
for (const auto& renderWindowWidget : all2DRenderWindowWidgets)
{
mainSplit->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
mainSplit->setSizes(splitterSize);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ONLY_2D_VERTICAL);
}
}
void QmitkMultiWidgetLayoutManager::SetOneTop3DBottomLayout()
{
MITK_DEBUG << "Set one top and all 3D bottom layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(Qt::Vertical, m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
mainSplit->addWidget(m_CurrentRenderWindowWidget);
m_CurrentRenderWindowWidget->show();
auto subSplit3D = new QSplitter(mainSplit);
QList<int> splitterSize;
auto all3DRenderWindowWidgets = m_MultiWidget->Get3DRenderWindowWidgets();
for (const auto& renderWindowWidget : all3DRenderWindowWidgets)
{
subSplit3D->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
subSplit3D->setSizes(splitterSize);
// set size for main splitter
splitterSize.clear();
splitterSize.push_back(1000);
splitterSize.push_back(1000);
mainSplit->setSizes(splitterSize);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ONE_TOP_3D_BOTTOM);
}
}
void QmitkMultiWidgetLayoutManager::SetOneLeft3DRightLayout()
{
MITK_DEBUG << "Set one left and all 3D right layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
mainSplit->addWidget(m_CurrentRenderWindowWidget);
m_CurrentRenderWindowWidget->show();
auto subSplit3D = new QSplitter(Qt::Vertical, mainSplit);
QList<int> splitterSize;
auto all3DRenderWindowWidgets = m_MultiWidget->Get3DRenderWindowWidgets();
for (const auto& renderWindowWidget : all3DRenderWindowWidgets)
{
subSplit3D->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
subSplit3D->setSizes(splitterSize);
// set size for main splitter
splitterSize.clear();
splitterSize.push_back(1000);
splitterSize.push_back(1000);
mainSplit->setSizes(splitterSize);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ONE_LEFT_3D_RIGHT);
}
}
void QmitkMultiWidgetLayoutManager::SetAllHorizontalLayout()
{
MITK_DEBUG << "Set all horizontal layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
QList<int> splitterSize;
auto allRenderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets();
for (const auto& renderWindowWidget : allRenderWindowWidgets)
{
if (nullptr != renderWindowWidget.second)
{
mainSplit->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
}
// set size for main splitter
mainSplit->setSizes(splitterSize);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ALL_HORIZONTAL);
}
}
void QmitkMultiWidgetLayoutManager::SetAllVerticalLayout()
{
MITK_DEBUG << "Set all vertical layout";
m_MultiWidget->ActivateMenuWidget(false);
delete m_MultiWidget->layout();
auto hBoxLayout = new QHBoxLayout(m_MultiWidget);
hBoxLayout->setContentsMargins(0, 0, 0, 0);
m_MultiWidget->setLayout(hBoxLayout);
- hBoxLayout->setMargin(0);
+ hBoxLayout->setContentsMargins({});
auto mainSplit = new QSplitter(Qt::Vertical, m_MultiWidget);
hBoxLayout->addWidget(mainSplit);
QList<int> splitterSize;
auto allRenderWindowWidgets = m_MultiWidget->GetRenderWindowWidgets();
for (const auto& renderWindowWidget : allRenderWindowWidgets)
{
mainSplit->addWidget(renderWindowWidget.second.get());
renderWindowWidget.second->show();
splitterSize.push_back(1000);
}
// set size for splitter
mainSplit->setSizes(splitterSize);
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::ALL_VERTICAL);
}
}
void QmitkMultiWidgetLayoutManager::RemoveOneLayout()
{
MITK_DEBUG << "Remove single render window";
m_MultiWidget->ActivateMenuWidget(false);
m_CurrentRenderWindowWidget->hide();
m_MultiWidget->ActivateMenuWidget(true);
auto allRenderWindows = m_MultiWidget->GetRenderWindows();
for (auto& renderWindow : allRenderWindows)
{
renderWindow->UpdateLayoutDesignList(LayoutDesign::NONE);
}
}
diff --git a/Modules/QtWidgets/src/QmitkMultiWidgetLayoutSelectionWidget.cpp b/Modules/QtWidgets/src/QmitkMultiWidgetLayoutSelectionWidget.cpp
index 1f80c59170..d7c6dc070f 100644
--- a/Modules/QtWidgets/src/QmitkMultiWidgetLayoutSelectionWidget.cpp
+++ b/Modules/QtWidgets/src/QmitkMultiWidgetLayoutSelectionWidget.cpp
@@ -1,138 +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.
============================================================================*/
#include "QmitkMultiWidgetLayoutSelectionWidget.h"
#include <QFileDialog>
#include <usGetModuleContext.h>
#include <usModuleContext.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>
QmitkMultiWidgetLayoutSelectionWidget::QmitkMultiWidgetLayoutSelectionWidget(QWidget* parent/* = 0*/)
: QWidget(parent)
{
Init();
}
void QmitkMultiWidgetLayoutSelectionWidget::Init()
{
ui.setupUi(this);
auto stylesheet = "QTableWidget::item{background-color: white;}\nQTableWidget::item:selected{background-color: #1C97EA;}";
ui.tableWidget->setStyleSheet(stylesheet);
connect(ui.tableWidget, &QTableWidget::itemSelectionChanged, this, &QmitkMultiWidgetLayoutSelectionWidget::OnTableItemSelectionChanged);
connect(ui.setLayoutPushButton, &QPushButton::clicked, this, &QmitkMultiWidgetLayoutSelectionWidget::OnSetLayoutButtonClicked);
connect(ui.loadLayoutPushButton, &QPushButton::clicked, this, &QmitkMultiWidgetLayoutSelectionWidget::OnLoadLayoutButtonClicked);
connect(ui.saveLayoutPushButton, &QPushButton::clicked, this, &QmitkMultiWidgetLayoutSelectionWidget::OnSaveLayoutButtonClicked);
connect(ui.selectDefaultLayoutComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &QmitkMultiWidgetLayoutSelectionWidget::OnLayoutPresetSelected);
ui.selectDefaultLayoutComboBox->addItem("Select a layout preset");
auto presetResources = us::GetModuleContext()->GetModule()->FindResources("/", "mxnLayout_*.json", false);
for (const auto& resource : presetResources)
{
us::ModuleResourceStream jsonStream(resource);
auto data = nlohmann::json::parse(jsonStream);
auto resourceName = data["name"].get<std::string>();
ui.selectDefaultLayoutComboBox->addItem(QString::fromStdString(resourceName));
m_PresetMap[ui.selectDefaultLayoutComboBox->count() - 1] = data;
}
}
void QmitkMultiWidgetLayoutSelectionWidget::OnTableItemSelectionChanged()
{
QItemSelectionModel* selectionModel = ui.tableWidget->selectionModel();
int row = 0;
int column = 0;
QModelIndexList indices = selectionModel->selectedIndexes();
if (indices.size() > 0)
{
row = indices[0].row();
column = indices[0].column();
QModelIndex topLeft = ui.tableWidget->model()->index(0, 0, QModelIndex());
QModelIndex bottomRight = ui.tableWidget->model()->index(row, column, QModelIndex());
QItemSelection cellSelection;
cellSelection.select(topLeft, bottomRight);
selectionModel->select(cellSelection, QItemSelectionModel::Select);
}
}
void QmitkMultiWidgetLayoutSelectionWidget::OnSetLayoutButtonClicked()
{
int row = 0;
int column = 0;
QModelIndexList indices = ui.tableWidget->selectionModel()->selectedIndexes();
if (indices.size() > 0)
{
// find largest row and column
- for (const auto& modelIndex : qAsConst(indices))
+ for (const auto& modelIndex : std::as_const(indices))
{
if (modelIndex.row() > row)
{
row = modelIndex.row();
}
if (modelIndex.column() > column)
{
column = modelIndex.column();
}
}
close();
emit LayoutSet(row+1, column+1);
}
ui.selectDefaultLayoutComboBox->setCurrentIndex(0);
}
void QmitkMultiWidgetLayoutSelectionWidget::OnSaveLayoutButtonClicked()
{
QString filename = QFileDialog::getSaveFileName(nullptr, "Select where to save the current layout", "", "MITK Window Layout (*.json)");
if (filename.isEmpty())
return;
QString fileExt(".json");
if (!filename.endsWith(fileExt))
filename += fileExt;
auto outStream = std::ofstream(filename.toStdString());
emit SaveLayout(&outStream);
}
void QmitkMultiWidgetLayoutSelectionWidget::OnLoadLayoutButtonClicked()
{
QString filename = QFileDialog::getOpenFileName(nullptr, "Load a layout file", "", "MITK Window Layouts (*.json)");
if (filename.isEmpty())
return;
ui.selectDefaultLayoutComboBox->setCurrentIndex(0);
std::ifstream f(filename.toStdString());
auto jsonData = nlohmann::json::parse(f);
emit LoadLayout(&jsonData);
}
void QmitkMultiWidgetLayoutSelectionWidget::OnLayoutPresetSelected(int index)
{
if (index == 0)
{
// First entry is only for description
return;
}
auto jsonData = m_PresetMap[index];
close();
emit LoadLayout(&jsonData);
}
diff --git a/Modules/QtWidgets/src/QmitkNodeSelectionDialog.cpp b/Modules/QtWidgets/src/QmitkNodeSelectionDialog.cpp
index 514b9d35c1..5fa811fefc 100644
--- a/Modules/QtWidgets/src/QmitkNodeSelectionDialog.cpp
+++ b/Modules/QtWidgets/src/QmitkNodeSelectionDialog.cpp
@@ -1,296 +1,296 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkNodeSelectionDialog.h"
#include <QmitkStyleManager.h>
#include <mitkDataStorageInspectorGenerator.h>
#include <QmitkNodeSelectionPreferenceHelper.h>
#include <QmitkDataStorageSelectionHistoryInspector.h>
#include <QmitkDataStorageFavoriteNodesInspector.h>
#include <string>
#include <map>
QmitkNodeSelectionDialog::QmitkNodeSelectionDialog(QWidget* parent, QString title, QString hint)
: QDialog(parent)
, m_NodePredicate(nullptr)
, m_SelectOnlyVisibleNodes(false)
, m_SelectedNodes(NodeList())
, m_SelectionMode(QAbstractItemView::SingleSelection)
{
m_Controls.setupUi(this);
m_CheckFunction = [](const NodeList &) { return ""; };
auto providers = mitk::DataStorageInspectorGenerator::GetProviders();
auto visibleProviders = mitk::GetVisibleDataStorageInspectors();
auto preferredID = mitk::GetPreferredDataStorageInspector();
if (visibleProviders.empty())
{
MITK_DEBUG << "No presets for visible node selection inspectors available. Use fallback (show all available inspectors)";
unsigned int order = 0;
for (const auto &proIter : providers)
{
visibleProviders.insert(std::make_pair(order, proIter.first));
++order;
}
}
int preferredIndex = 0;
bool preferredFound = false;
for (const auto &proIter : visibleProviders)
{
auto finding = providers.find(proIter.second);
if (finding != providers.end())
{
if (finding->second->GetInspectorID() != QmitkDataStorageFavoriteNodesInspector::INSPECTOR_ID() && finding->second->GetInspectorID() != QmitkDataStorageSelectionHistoryInspector::INSPECTOR_ID())
{
auto provider = finding->second;
this->AddPanel(provider, preferredID, preferredFound, preferredIndex);
}
}
else
{
MITK_DEBUG << "No provider registered for inspector that is defined as visible in the preferences. Illegal inspector ID: " << proIter.second;
}
}
if (mitk::GetShowFavoritesInspector())
{
auto favoritesPorvider = mitk::DataStorageInspectorGenerator::GetProvider(QmitkDataStorageFavoriteNodesInspector::INSPECTOR_ID());
if (favoritesPorvider != nullptr)
{
this->AddPanel(favoritesPorvider, preferredID, preferredFound, preferredIndex);
}
}
if (mitk::GetShowHistoryInspector())
{
auto historyPorvider = mitk::DataStorageInspectorGenerator::GetProvider(QmitkDataStorageSelectionHistoryInspector::INSPECTOR_ID());
if (historyPorvider != nullptr)
{
this->AddPanel(historyPorvider, preferredID, preferredFound, preferredIndex);
}
}
m_Controls.tabWidget->setCurrentIndex(preferredIndex);
this->setWindowTitle(title);
this->setToolTip(hint);
m_Controls.hint->setText(hint);
m_Controls.hint->setVisible(!hint.isEmpty());
if(hint.isEmpty())
{
m_Controls.layoutHint->setContentsMargins(0, 0, 0, 0);
}
else
{
m_Controls.layoutHint->setContentsMargins(6, 6, 6, 6);
}
this->SetErrorText("");
m_Controls.btnAddToFav->setIcon(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/favorite_add.svg")));
connect(m_Controls.btnAddToFav, &QPushButton::clicked, this, &QmitkNodeSelectionDialog::OnFavoriteNodesButtonClicked);
connect(m_Controls.buttonBox, &QDialogButtonBox::accepted, this, &QmitkNodeSelectionDialog::OnOK);
connect(m_Controls.buttonBox, &QDialogButtonBox::rejected, this, &QmitkNodeSelectionDialog::OnCancel);
}
void QmitkNodeSelectionDialog::SetDataStorage(mitk::DataStorage* dataStorage)
{
if (m_DataStorage != dataStorage)
{
m_DataStorage = dataStorage;
auto lockedDataStorage = m_DataStorage.Lock();
if (lockedDataStorage.IsNotNull())
{
for (auto panel : m_Panels)
{
panel->SetDataStorage(lockedDataStorage);
}
}
}
}
void QmitkNodeSelectionDialog::SetNodePredicate(const mitk::NodePredicateBase* nodePredicate)
{
if (m_NodePredicate != nodePredicate)
{
m_NodePredicate = nodePredicate;
for (auto panel : m_Panels)
{
panel->SetNodePredicate(m_NodePredicate);
}
}
}
const mitk::NodePredicateBase* QmitkNodeSelectionDialog::GetNodePredicate() const
{
return m_NodePredicate;
}
QmitkNodeSelectionDialog::NodeList QmitkNodeSelectionDialog::GetSelectedNodes() const
{
return m_SelectedNodes;
}
void QmitkNodeSelectionDialog::SetSelectionCheckFunction(const SelectionCheckFunctionType &checkFunction)
{
m_CheckFunction = checkFunction;
auto checkResponse = m_CheckFunction(m_SelectedNodes);
SetErrorText(checkResponse);
m_Controls.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(checkResponse.empty());
}
void QmitkNodeSelectionDialog::SetErrorText(const std::string& checkResponse)
{
m_Controls.error->setText(QString::fromStdString(checkResponse));
m_Controls.error->setVisible(!checkResponse.empty());
if (checkResponse.empty())
{
m_Controls.layoutError->setContentsMargins(0, 0, 0, 0);
}
else
{
m_Controls.layoutError->setContentsMargins(6, 6, 6, 6);
}
}
bool QmitkNodeSelectionDialog::GetSelectOnlyVisibleNodes() const
{
return m_SelectOnlyVisibleNodes;
}
void QmitkNodeSelectionDialog::SetSelectionMode(SelectionMode mode)
{
m_SelectionMode = mode;
for (auto panel : m_Panels)
{
panel->SetSelectionMode(mode);
}
}
QmitkNodeSelectionDialog::SelectionMode QmitkNodeSelectionDialog::GetSelectionMode() const
{
return m_SelectionMode;
}
void QmitkNodeSelectionDialog::SetSelectOnlyVisibleNodes(bool selectOnlyVisibleNodes)
{
if (m_SelectOnlyVisibleNodes != selectOnlyVisibleNodes)
{
m_SelectOnlyVisibleNodes = selectOnlyVisibleNodes;
for (auto panel : m_Panels)
{
panel->SetSelectOnlyVisibleNodes(m_SelectOnlyVisibleNodes);
}
}
}
void QmitkNodeSelectionDialog::SetCurrentSelection(NodeList selectedNodes)
{
m_SelectedNodes = selectedNodes;
auto checkResponse = m_CheckFunction(m_SelectedNodes);
SetErrorText(checkResponse);
m_Controls.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(checkResponse.empty());
for (auto panel : m_Panels)
{
panel->SetCurrentSelection(selectedNodes);
}
}
void QmitkNodeSelectionDialog::OnSelectionChanged(NodeList selectedNodes)
{
SetCurrentSelection(selectedNodes);
emit CurrentSelectionChanged(selectedNodes);
}
void QmitkNodeSelectionDialog::OnFavoriteNodesButtonClicked()
{
- for (auto node : qAsConst(m_SelectedNodes))
+ for (auto node : std::as_const(m_SelectedNodes))
{
node->SetBoolProperty("org.mitk.selection.favorite", true);
}
}
void QmitkNodeSelectionDialog::OnOK()
{
- for (const auto &node : qAsConst(m_SelectedNodes))
+ for (const auto &node : std::as_const(m_SelectedNodes))
{
QmitkDataStorageSelectionHistoryInspector::AddNodeToHistory(node);
}
this->accept();
}
void QmitkNodeSelectionDialog::OnCancel()
{
this->reject();
}
void QmitkNodeSelectionDialog::AddPanel(const mitk::IDataStorageInspectorProvider * provider, const mitk::IDataStorageInspectorProvider::InspectorIDType& preferredID, bool &preferredFound, int &preferredIndex)
{
auto inspector = provider->CreateInspector();
QString name = QString::fromStdString(provider->GetInspectorDisplayName());
QString desc = QString::fromStdString(provider->GetInspectorDescription());
inspector->setParent(this);
inspector->SetSelectionMode(m_SelectionMode);
auto tabPanel = new QWidget();
tabPanel->setObjectName(QString("tab_") + name);
tabPanel->setToolTip(desc);
auto verticalLayout = new QVBoxLayout(tabPanel);
verticalLayout->setSpacing(0);
verticalLayout->setContentsMargins(0, 0, 0, 0);
verticalLayout->addWidget(inspector);
auto panelPos = m_Controls.tabWidget->insertTab(m_Controls.tabWidget->count(), tabPanel, name);
auto icon = provider->GetInspectorIcon();
if (!icon.isNull())
{
m_Controls.tabWidget->setTabIcon(panelPos, icon);
}
m_Panels.push_back(inspector);
connect(inspector, &QmitkAbstractDataStorageInspector::CurrentSelectionChanged, this, &QmitkNodeSelectionDialog::OnSelectionChanged);
connect(inspector->GetView(), &QAbstractItemView::doubleClicked, this, &QmitkNodeSelectionDialog::OnDoubleClicked);
preferredFound = preferredFound || provider->GetInspectorID() == preferredID;
if (!preferredFound)
{
++preferredIndex;
}
}
void QmitkNodeSelectionDialog::OnDoubleClicked(const QModelIndex& /*index*/)
{
const auto isOK = m_Controls.buttonBox->button(QDialogButtonBox::Ok)->isEnabled();
if (!m_SelectedNodes.empty() && isOK)
{
this->OnOK();
}
}
diff --git a/Modules/QtWidgets/src/QmitkPropertiesTableEditor.cpp b/Modules/QtWidgets/src/QmitkPropertiesTableEditor.cpp
index bbaca03d47..3d870a56ec 100644
--- a/Modules/QtWidgets/src/QmitkPropertiesTableEditor.cpp
+++ b/Modules/QtWidgets/src/QmitkPropertiesTableEditor.cpp
@@ -1,112 +1,112 @@
/*============================================================================
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 "QmitkPropertiesTableEditor.h"
#include "QmitkPropertiesTableModel.h"
#include "QmitkPropertyDelegate.h"
#include "mitkBaseRenderer.h"
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QTableView>
#include <QVBoxLayout>
#include <vtkRenderWindow.h>
QmitkPropertiesTableEditor::QmitkPropertiesTableEditor(QWidget *parent,
Qt::WindowFlags f,
mitk::DataNode::Pointer /*_Node*/)
: QWidget(parent, f), m_NodePropertiesTableView(nullptr), m_Model(nullptr)
{
// set up empty gui elements
this->init();
// set up model
m_Model = new QmitkPropertiesTableModel(m_NodePropertiesTableView, nullptr);
m_NodePropertiesTableView->setModel(m_Model);
}
QmitkPropertiesTableEditor::~QmitkPropertiesTableEditor()
{
}
void QmitkPropertiesTableEditor::SetPropertyList(mitk::PropertyList::Pointer _List)
{
if (_List.IsNotNull())
{
m_Model->SetPropertyList(_List);
m_NodePropertiesTableView->resizeColumnsToContents();
m_NodePropertiesTableView->resizeRowsToContents();
m_NodePropertiesTableView->horizontalHeader()->setStretchLastSection(true);
m_NodePropertiesTableView->setEditTriggers(QAbstractItemView::CurrentChanged);
}
else
{
m_Model->SetPropertyList(nullptr);
}
}
QmitkPropertiesTableModel *QmitkPropertiesTableEditor::getModel() const
{
return m_Model;
}
void QmitkPropertiesTableEditor::init()
{
// read/ dim
QVBoxLayout *_NodePropertiesLayout = new QVBoxLayout;
QWidget *_PropertyFilterKeyWordPane = new QWidget(QWidget::parentWidget());
QHBoxLayout *_PropertyFilterKeyWordLayout = new QHBoxLayout;
QLabel *_LabelPropertyFilterKeyWord = new QLabel("Filter: ", _PropertyFilterKeyWordPane);
m_TxtPropertyFilterKeyWord = new QLineEdit(_PropertyFilterKeyWordPane);
m_NodePropertiesTableView = new QTableView(QWidget::parentWidget());
// write
setLayout(_NodePropertiesLayout);
_PropertyFilterKeyWordPane->setLayout(_PropertyFilterKeyWordLayout);
- _PropertyFilterKeyWordLayout->setMargin(0);
+ _PropertyFilterKeyWordLayout->setContentsMargins({});
_PropertyFilterKeyWordLayout->addWidget(_LabelPropertyFilterKeyWord);
_PropertyFilterKeyWordLayout->addWidget(m_TxtPropertyFilterKeyWord);
- _NodePropertiesLayout->setMargin(0);
+ _NodePropertiesLayout->setContentsMargins({});
_NodePropertiesLayout->addWidget(_PropertyFilterKeyWordPane);
_NodePropertiesLayout->addWidget(m_NodePropertiesTableView);
m_NodePropertiesTableView->setSelectionMode(QAbstractItemView::SingleSelection);
m_NodePropertiesTableView->setSelectionBehavior(QAbstractItemView::SelectItems);
m_NodePropertiesTableView->verticalHeader()->hide();
m_NodePropertiesTableView->setItemDelegate(new QmitkPropertyDelegate(this));
m_NodePropertiesTableView->setAlternatingRowColors(true);
m_NodePropertiesTableView->setSortingEnabled(true);
m_NodePropertiesTableView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
QObject::connect(m_TxtPropertyFilterKeyWord,
SIGNAL(textChanged(const QString &)),
this,
SLOT(PropertyFilterKeyWordTextChanged(const QString &)));
}
void QmitkPropertiesTableEditor::PropertyFilterKeyWordTextChanged(const QString & /*text*/)
{
m_Model->SetFilterPropertiesKeyWord(m_TxtPropertyFilterKeyWord->text().toStdString());
}
QTableView *QmitkPropertiesTableEditor::getTable() const
{
return m_NodePropertiesTableView;
}
diff --git a/Modules/QtWidgets/src/QmitkPropertiesTableModel.cpp b/Modules/QtWidgets/src/QmitkPropertiesTableModel.cpp
index 5fd79e13bf..65fe3ad56b 100644
--- a/Modules/QtWidgets/src/QmitkPropertiesTableModel.cpp
+++ b/Modules/QtWidgets/src/QmitkPropertiesTableModel.cpp
@@ -1,530 +1,530 @@
/*============================================================================
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 "QmitkPropertiesTableModel.h"
//# Own includes
#include "QmitkCustomVariants.h"
#include "mitkColorProperty.h"
#include "mitkEnumerationProperty.h"
#include "mitkProperties.h"
#include "mitkRenderingManager.h"
#include "mitkStringProperty.h"
//# Toolkit includes
#include <QBrush>
#include <QColor>
#include <QStringList>
#include <itkCommand.h>
//# PUBLIC CTORS,DTOR
QmitkPropertiesTableModel::QmitkPropertiesTableModel(QObject *parent, mitk::PropertyList::Pointer _PropertyList)
: QAbstractTableModel(parent),
m_PropertyList(nullptr),
m_BlockEvents(false),
m_SortDescending(false),
m_FilterKeyWord("")
{
this->SetPropertyList(_PropertyList);
}
QmitkPropertiesTableModel::~QmitkPropertiesTableModel()
{
// remove all event listeners by setting the property list to 0
this->SetPropertyList(nullptr);
}
//# PUBLIC GETTER
mitk::PropertyList::Pointer QmitkPropertiesTableModel::GetPropertyList() const
{
return m_PropertyList.Lock();
}
Qt::ItemFlags QmitkPropertiesTableModel::flags(const QModelIndex &index) const
{
// no editing so far, return default (enabled, selectable)
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (index.column() == PROPERTY_VALUE_COLUMN)
{
// there are also read only property items -> do not allow editing them
if (index.data(Qt::EditRole).isValid())
flags |= Qt::ItemIsEditable;
if (index.data(Qt::CheckStateRole).isValid())
flags |= Qt::ItemIsUserCheckable;
}
return flags;
}
QVariant QmitkPropertiesTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal)
{
switch (section)
{
case PROPERTY_NAME_COLUMN:
return tr("Name");
case PROPERTY_VALUE_COLUMN:
return tr("Value");
default:
return QVariant();
}
}
return QVariant();
}
QVariant QmitkPropertiesTableModel::data(const QModelIndex &index, int role) const
{
// empty data by default
QVariant data;
if (!index.isValid() || m_SelectedProperties.empty() || index.row() > (int)(m_SelectedProperties.size() - 1))
return data;
// the properties name
if (index.column() == PROPERTY_NAME_COLUMN)
{
if (role == Qt::DisplayRole)
data = QString::fromStdString(m_SelectedProperties[index.row()].first);
}
// the real properties value
else if (index.column() == PROPERTY_VALUE_COLUMN)
{
mitk::BaseProperty *baseProp = m_SelectedProperties[index.row()].second;
if (const mitk::ColorProperty *colorProp = dynamic_cast<const mitk::ColorProperty *>(baseProp))
{
mitk::Color col = colorProp->GetColor();
QColor qcol((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255), (int)(col.GetBlue() * 255));
if (role == Qt::DisplayRole)
- data.setValue<QColor>(qcol);
+ data.setValue(qcol);
else if (role == Qt::EditRole)
- data.setValue<QColor>(qcol);
+ data.setValue(qcol);
}
else if (mitk::BoolProperty *boolProp = dynamic_cast<mitk::BoolProperty *>(baseProp))
{
if (role == Qt::CheckStateRole)
data = boolProp->GetValue() ? Qt::Checked : Qt::Unchecked;
}
else if (mitk::StringProperty *stringProp = dynamic_cast<mitk::StringProperty *>(baseProp))
{
if (role == Qt::DisplayRole)
data.setValue<QString>(QString::fromStdString(stringProp->GetValue()));
else if (role == Qt::EditRole)
data.setValue<QString>(QString::fromStdString(stringProp->GetValue()));
}
else if (mitk::IntProperty *intProp = dynamic_cast<mitk::IntProperty *>(baseProp))
{
if (role == Qt::DisplayRole)
data.setValue<int>(intProp->GetValue());
else if (role == Qt::EditRole)
data.setValue<int>(intProp->GetValue());
}
else if (mitk::FloatProperty *floatProp = dynamic_cast<mitk::FloatProperty *>(baseProp))
{
if (role == Qt::DisplayRole)
data.setValue<float>(floatProp->GetValue());
else if (role == Qt::EditRole)
data.setValue<float>(floatProp->GetValue());
}
else if (mitk::EnumerationProperty *enumerationProp = dynamic_cast<mitk::EnumerationProperty *>(baseProp))
{
if (role == Qt::DisplayRole)
data.setValue<QString>(QString::fromStdString(baseProp->GetValueAsString()));
else if (role == Qt::EditRole)
{
QStringList values;
for (auto it = enumerationProp->Begin(); it != enumerationProp->End(); it++)
{
values << QString::fromStdString(it->second);
}
- data.setValue<QStringList>(values);
+ data.setValue(values);
}
}
else
{
if (role == Qt::DisplayRole)
- data.setValue<QString>(QString::fromStdString(m_SelectedProperties[index.row()].second->GetValueAsString()));
+ data.setValue(QString::fromStdString(m_SelectedProperties[index.row()].second->GetValueAsString()));
}
}
return data;
}
int QmitkPropertiesTableModel::rowCount(const QModelIndex & /*parent*/) const
{
// return the number of properties in the properties list.
return m_SelectedProperties.size();
}
int QmitkPropertiesTableModel::columnCount(const QModelIndex & /*parent*/) const
{
return 2;
}
//# PUBLIC SETTER
void QmitkPropertiesTableModel::SetPropertyList(mitk::PropertyList *_PropertyList)
{
// if propertylist really changed
if (m_PropertyList != _PropertyList)
{
auto propertyList = m_PropertyList.Lock();
// Remove delete listener if there was a propertylist before
if (propertyList.IsNotNull())
propertyList->RemoveObserver(m_PropertyListDeleteObserverTag);
// set new list
m_PropertyList = _PropertyList;
propertyList = m_PropertyList.Lock();
if (propertyList.IsNotNull())
{
auto command = itk::SimpleMemberCommand<QmitkPropertiesTableModel>::New();
command->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyListDelete);
m_PropertyListDeleteObserverTag = propertyList->AddObserver(itk::DeleteEvent(), command);
}
this->Reset();
}
}
void QmitkPropertiesTableModel::PropertyListDelete()
{
if (!m_BlockEvents)
{
m_BlockEvents = true;
this->Reset();
m_BlockEvents = false;
}
}
void QmitkPropertiesTableModel::PropertyModified(const itk::Object *caller, const itk::EventObject & /*event*/)
{
if (!m_BlockEvents)
{
m_BlockEvents = true;
int row = this->FindProperty(dynamic_cast<const mitk::BaseProperty *>(caller));
QModelIndex indexOfChangedProperty = index(row, 1);
emit dataChanged(indexOfChangedProperty, indexOfChangedProperty);
m_BlockEvents = false;
}
}
void QmitkPropertiesTableModel::PropertyDelete(const itk::Object *caller, const itk::EventObject & /*event*/)
{
if (!m_BlockEvents)
{
m_BlockEvents = true;
int row = this->FindProperty(dynamic_cast<const mitk::BaseProperty *>(caller));
if (row >= 0)
this->Reset();
m_BlockEvents = false;
}
}
bool QmitkPropertiesTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
// TODO: check 'role' condition
if (index.isValid() && !m_SelectedProperties.empty() && index.row() < (int)(m_SelectedProperties.size()) &&
(role == Qt::EditRole || role == Qt::CheckStateRole))
{
// block all events now!
m_BlockEvents = true;
auto propertyList = m_PropertyList.Lock();
// the properties name
if (index.column() == PROPERTY_VALUE_COLUMN)
{
mitk::BaseProperty *baseProp = m_SelectedProperties[index.row()].second;
if (mitk::ColorProperty *colorProp = dynamic_cast<mitk::ColorProperty *>(baseProp))
{
QColor qcolor = value.value<QColor>();
if (!qcolor.isValid())
return false;
mitk::Color col = colorProp->GetColor();
col.SetRed(qcolor.red() / 255.0);
col.SetGreen(qcolor.green() / 255.0);
col.SetBlue(qcolor.blue() / 255.0);
colorProp->SetColor(col);
propertyList->InvokeEvent(itk::ModifiedEvent());
propertyList->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::BoolProperty *boolProp = dynamic_cast<mitk::BoolProperty *>(baseProp))
{
boolProp->SetValue(value.toInt() == Qt::Checked ? true : false);
propertyList->InvokeEvent(itk::ModifiedEvent());
propertyList->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::StringProperty *stringProp = dynamic_cast<mitk::StringProperty *>(baseProp))
{
stringProp->SetValue((value.value<QString>()).toStdString());
propertyList->InvokeEvent(itk::ModifiedEvent());
propertyList->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::IntProperty *intProp = dynamic_cast<mitk::IntProperty *>(baseProp))
{
int intValue = value.value<int>();
if (intValue != intProp->GetValue())
{
intProp->SetValue(intValue);
propertyList->InvokeEvent(itk::ModifiedEvent());
propertyList->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
else if (mitk::FloatProperty *floatProp = dynamic_cast<mitk::FloatProperty *>(baseProp))
{
float floatValue = value.value<float>();
if (floatValue != floatProp->GetValue())
{
floatProp->SetValue(floatValue);
propertyList->InvokeEvent(itk::ModifiedEvent());
propertyList->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
else if (mitk::EnumerationProperty *enumerationProp = dynamic_cast<mitk::EnumerationProperty *>(baseProp))
{
std::string activatedItem = value.value<QString>().toStdString();
if (activatedItem != enumerationProp->GetValueAsString())
{
if (enumerationProp->IsValidEnumerationValue(activatedItem))
{
enumerationProp->SetValue(activatedItem);
propertyList->InvokeEvent(itk::ModifiedEvent());
propertyList->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
}
}
// property was changed by us, now we can accept property changes triggered by someone else
m_BlockEvents = false;
emit dataChanged(index, index);
return true;
}
return false;
}
void QmitkPropertiesTableModel::sort(int column, Qt::SortOrder order /*= Qt::AscendingOrder */)
{
bool sortDescending = (order == Qt::DescendingOrder) ? true : false;
// do not sort twice !!! (dont know why, but qt calls this func twice. STUPID!)
if (sortDescending != m_SortDescending)
{
m_SortDescending = sortDescending;
PropertyDataSetCompareFunction::CompareCriteria _CompareCriteria = PropertyDataSetCompareFunction::CompareByName;
PropertyDataSetCompareFunction::CompareOperator _CompareOperator =
m_SortDescending ? PropertyDataSetCompareFunction::Greater : PropertyDataSetCompareFunction::Less;
if (column == PROPERTY_VALUE_COLUMN)
_CompareCriteria = PropertyDataSetCompareFunction::CompareByValue;
PropertyDataSetCompareFunction compareFunc(_CompareCriteria, _CompareOperator);
std::sort(m_SelectedProperties.begin(), m_SelectedProperties.end(), compareFunc);
QAbstractTableModel::beginResetModel();
QAbstractTableModel::endResetModel();
}
}
//# PROTECTED GETTER
int QmitkPropertiesTableModel::FindProperty(const mitk::BaseProperty *_Property) const
{
int row = -1;
if (_Property)
{
// search for property that changed and emit datachanged on the corresponding ModelIndex
std::vector<PropertyDataSet>::const_iterator propertyIterator;
for (propertyIterator = m_SelectedProperties.begin(); propertyIterator != m_SelectedProperties.end();
propertyIterator++)
{
if (propertyIterator->second == _Property)
break;
}
if (propertyIterator != m_SelectedProperties.end())
row = std::distance(m_SelectedProperties.begin(), propertyIterator);
}
return row;
}
//# PROTECTED SETTER
void QmitkPropertiesTableModel::AddSelectedProperty(PropertyDataSet &_PropertyDataSet)
{
// subscribe for modified event
itk::MemberCommand<QmitkPropertiesTableModel>::Pointer _PropertyDataSetModifiedCommand =
itk::MemberCommand<QmitkPropertiesTableModel>::New();
_PropertyDataSetModifiedCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyModified);
m_PropertyModifiedObserverTags.push_back(
_PropertyDataSet.second->AddObserver(itk::ModifiedEvent(), _PropertyDataSetModifiedCommand));
// subscribe for delete event
itk::MemberCommand<QmitkPropertiesTableModel>::Pointer _PropertyDataSetDeleteCommand =
itk::MemberCommand<QmitkPropertiesTableModel>::New();
_PropertyDataSetDeleteCommand->SetCallbackFunction(this, &QmitkPropertiesTableModel::PropertyDelete);
m_PropertyDeleteObserverTags.push_back(
_PropertyDataSet.second->AddObserver(itk::DeleteEvent(), _PropertyDataSetDeleteCommand));
// add to the selection
m_SelectedProperties.push_back(_PropertyDataSet);
}
void QmitkPropertiesTableModel::RemoveSelectedProperty(unsigned int _Index)
{
PropertyDataSet &_PropertyDataSet = m_SelectedProperties.at(_Index);
// remove modified event listener
_PropertyDataSet.second->RemoveObserver(m_PropertyModifiedObserverTags[_Index]);
m_PropertyModifiedObserverTags.erase(m_PropertyModifiedObserverTags.begin() + _Index);
// remove delete event listener
_PropertyDataSet.second->RemoveObserver(m_PropertyDeleteObserverTags[_Index]);
m_PropertyDeleteObserverTags.erase(m_PropertyDeleteObserverTags.begin() + _Index);
// remove from selection
m_SelectedProperties.erase(m_SelectedProperties.begin() + _Index);
}
void QmitkPropertiesTableModel::Reset()
{
// remove all selected properties
while (!m_SelectedProperties.empty())
{
this->RemoveSelectedProperty(m_SelectedProperties.size() - 1);
}
std::vector<PropertyDataSet> allPredicates;
auto propertyList = m_PropertyList.Lock();
if (propertyList.IsNotNull())
{
// first of all: collect all properties from the list
for (auto it = propertyList->GetMap()->begin(); it != propertyList->GetMap()->end(); it++)
{
allPredicates.push_back(*it); //% TODO
}
}
// make a subselection if a keyword is specified
if (!m_FilterKeyWord.empty())
{
std::vector<PropertyDataSet> subSelection;
for (auto it = allPredicates.begin(); it != allPredicates.end(); it++)
{
// add this to the selection if it is matched by the keyword
if ((*it).first.find(m_FilterKeyWord) != std::string::npos)
subSelection.push_back((*it));
}
allPredicates.clear();
allPredicates = subSelection;
}
PropertyDataSet tmpPropertyDataSet;
// add all selected now to the Model
for (auto it = allPredicates.begin(); it != allPredicates.end(); it++)
{
tmpPropertyDataSet = *it;
this->AddSelectedProperty(tmpPropertyDataSet);
}
// sort the list as indicated by m_SortDescending
this->sort(m_SortDescending);
// model was resetted
QAbstractTableModel::beginResetModel();
QAbstractTableModel::endResetModel();
}
void QmitkPropertiesTableModel::SetFilterPropertiesKeyWord(std::string _FilterKeyWord)
{
m_FilterKeyWord = _FilterKeyWord;
this->Reset();
}
QmitkPropertiesTableModel::PropertyDataSetCompareFunction::PropertyDataSetCompareFunction(
CompareCriteria _CompareCriteria, CompareOperator _CompareOperator)
: m_CompareCriteria(_CompareCriteria), m_CompareOperator(_CompareOperator)
{
}
bool QmitkPropertiesTableModel::PropertyDataSetCompareFunction::operator()(const PropertyDataSet &_Left,
const PropertyDataSet &_Right) const
{
switch (m_CompareCriteria)
{
case CompareByValue:
if (m_CompareOperator == Less)
return (_Left.second->GetValueAsString() < _Right.second->GetValueAsString());
else
return (_Left.second->GetValueAsString() > _Right.second->GetValueAsString());
break;
// CompareByName:
default:
if (m_CompareOperator == Less)
return (_Left.first < _Right.first);
else
return (_Left.first > _Right.first);
break;
}
}
QmitkPropertiesTableModel::PropertyListElementFilterFunction::PropertyListElementFilterFunction(
const std::string &_FilterKeyWord)
: m_FilterKeyWord(_FilterKeyWord)
{
}
bool QmitkPropertiesTableModel::PropertyListElementFilterFunction::operator()(const PropertyDataSet &_Elem) const
{
if (m_FilterKeyWord.empty())
return true;
return (_Elem.first.find(m_FilterKeyWord) == 0);
}
diff --git a/Modules/QtWidgets/src/QmitkPropertyDelegate.cpp b/Modules/QtWidgets/src/QmitkPropertyDelegate.cpp
index 991f374238..2c309928a8 100644
--- a/Modules/QtWidgets/src/QmitkPropertyDelegate.cpp
+++ b/Modules/QtWidgets/src/QmitkPropertyDelegate.cpp
@@ -1,320 +1,319 @@
/*============================================================================
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 NOMINMAX
#define NOMINMAX
#endif
#include "QmitkPropertyDelegate.h"
#include "QmitkCustomVariants.h"
#include "mitkRenderingManager.h"
#include <QApplication>
#include <QCheckBox>
#include <QColorDialog>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QLabel>
#include <QMessageBox>
#include <QPainter>
#include <QPen>
#include <QPushButton>
#include <QStringList>
#include <bitset>
QmitkPropertyDelegate::QmitkPropertyDelegate(QObject * /*parent*/)
{
}
void QmitkPropertyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QVariant data = index.data(Qt::DisplayRole);
QString name = data.value<QString>();
- if (index.column() == 1 && data.type() == QVariant::Color)
+ if (index.column() == 1 && data.typeId() == QMetaType::QColor)
{
QColor qcol = data.value<QColor>();
painter->save();
painter->fillRect(option.rect, qcol);
QRect rect = option.rect;
rect.setWidth(rect.width() - 1);
rect.setHeight(rect.height() - 1);
QPen pen;
pen.setWidth(1);
painter->setPen(pen);
painter->drawRect(rect);
painter->restore();
}
else
{
QStyledItemDelegate::paint(painter, option, index);
}
}
QWidget *QmitkPropertyDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
QVariant displayData = index.data(Qt::DisplayRole);
QString name = index.model()->data(index.model()->index(index.row(), index.column() - 1)).value<QString>();
if (data.isValid())
{
QWidget *editorWidget = nullptr;
- if (data.type() == QVariant::Color)
+ if (data.typeId() == QMetaType::QColor)
{
auto colorBtn = new QPushButton(parent);
QColor color = data.value<QColor>();
QColor result = QColorDialog::getColor(color);
if (result.isValid())
{
QPalette palette = colorBtn->palette();
palette.setColor(QPalette::Button, result);
colorBtn->setPalette(palette);
colorBtn->setStyleSheet(
QString("background-color: %1;foreground-color: %1; border-style: none;").arg(result.name()));
}
// QColorDialog closed by 'Cancel' button, use the old property color
else
{
QPalette palette = colorBtn->palette();
palette.setColor(QPalette::Button, color);
colorBtn->setPalette(palette);
colorBtn->setStyleSheet(
QString("background-color: %1;foreground-color: %1; border-style: none;").arg(color.name()));
}
connect(colorBtn, SIGNAL(pressed()), this, SLOT(commitAndCloseEditor()));
editorWidget = colorBtn;
}
- else if (data.type() == QVariant::Int)
+ else if (data.typeId() == QMetaType::Int)
{
auto spinBox = new QSpinBox(parent);
spinBox->setSingleStep(1);
spinBox->setMinimum(std::numeric_limits<int>::min());
spinBox->setMaximum(std::numeric_limits<int>::max());
editorWidget = spinBox;
}
- // see qt documentation. cast is correct, it would be obsolete if we
- // store doubles
- else if (static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
+
+ else if (data.typeId() == QMetaType::Float)
{
auto spinBox = new QDoubleSpinBox(parent);
spinBox->setDecimals(2);
spinBox->setSingleStep(0.1);
if (name == "opacity")
{
spinBox->setMinimum(0.0);
spinBox->setMaximum(1.0);
}
else
{
spinBox->setMinimum(std::numeric_limits<float>::min());
spinBox->setMaximum(std::numeric_limits<float>::max());
}
editorWidget = spinBox;
}
- else if (data.type() == QVariant::StringList)
+ else if (data.typeId() == QMetaType::QStringList)
{
QStringList entries = data.value<QStringList>();
auto comboBox = new QComboBox(parent);
comboBox->setEditable(false);
comboBox->addItems(entries);
editorWidget = comboBox;
}
else
{
editorWidget = QStyledItemDelegate::createEditor(parent, option, index);
}
if (editorWidget)
{
// install event filter
editorWidget->installEventFilter(const_cast<QmitkPropertyDelegate *>(this));
}
return editorWidget;
}
else
return new QLabel(displayData.toString(), parent);
}
void QmitkPropertyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
QVariant displayData = index.data(Qt::DisplayRole);
if (data.isValid())
{
- if (data.type() == QVariant::Int)
+ if (data.typeId() == QMetaType::Int)
{
QSpinBox *spinBox = qobject_cast<QSpinBox *>(editor);
spinBox->setValue(data.toInt());
}
// see qt documentation. cast is correct, it would be obsolete if we
// store doubles
- else if (static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
+ else if (data.typeId() == QMetaType::Float)
{
QDoubleSpinBox *spinBox = qobject_cast<QDoubleSpinBox *>(editor);
spinBox->setValue(data.toDouble());
}
- else if (data.type() == QVariant::StringList)
+ else if (data.typeId() == QMetaType::QStringList)
{
QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
QString displayString = displayData.value<QString>();
comboBox->setCurrentIndex(comboBox->findData(displayString));
}
else
return QStyledItemDelegate::setEditorData(editor, index);
}
}
void QmitkPropertyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
QVariant displayData = index.data(Qt::DisplayRole);
if (data.isValid())
{
- if (data.type() == QVariant::Color)
+ if (data.typeId() == QMetaType::QColor)
{
QWidget *colorBtn = qobject_cast<QWidget *>(editor);
QVariant colorVariant;
- colorVariant.setValue<QColor>(colorBtn->palette().color(QPalette::Button));
+ colorVariant.setValue(colorBtn->palette().color(QPalette::Button));
model->setData(index, colorVariant);
}
- else if (data.type() == QVariant::Int)
+ else if (data.typeId() == QMetaType::Int)
{
QSpinBox *spinBox = qobject_cast<QSpinBox *>(editor);
int intValue = spinBox->value();
QVariant intValueVariant;
intValueVariant.setValue<float>(static_cast<float>(intValue));
model->setData(index, intValueVariant);
}
- else if (static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
+ else if (data.typeId() == QMetaType::Float)
{
QDoubleSpinBox *spinBox = qobject_cast<QDoubleSpinBox *>(editor);
double doubleValue = spinBox->value();
QVariant doubleValueVariant;
doubleValueVariant.setValue<float>(static_cast<float>(doubleValue));
model->setData(index, doubleValueVariant);
}
- else if (data.type() == QVariant::StringList)
+ else if (data.typeId() == QMetaType::QStringList)
{
QString displayData = data.value<QString>();
QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
QString comboBoxValue = comboBox->currentText();
QVariant comboBoxValueVariant;
- comboBoxValueVariant.setValue<QString>(comboBoxValue);
+ comboBoxValueVariant.setValue(comboBoxValue);
model->setData(index, comboBoxValueVariant);
}
else
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void QmitkPropertyDelegate::commitAndCloseEditor()
{
QWidget *editor = nullptr;
if (QPushButton *pushBtn = qobject_cast<QPushButton *>(sender()))
{
editor = pushBtn;
}
if (editor)
{
emit commitData(editor);
emit closeEditor(editor);
}
}
void QmitkPropertyDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex & /*index*/) const
{
editor->setGeometry(option.rect);
}
void QmitkPropertyDelegate::ComboBoxCurrentIndexChanged(int /*index*/)
{
if (QComboBox *comboBox = qobject_cast<QComboBox *>(sender()))
{
emit commitData(comboBox);
emit closeEditor(comboBox);
}
}
void QmitkPropertyDelegate::SpinBoxValueChanged(const QString & /*value*/)
{
QAbstractSpinBox *spinBox = nullptr;
if ((spinBox = qobject_cast<QSpinBox *>(sender())) || (spinBox = qobject_cast<QDoubleSpinBox *>(sender())))
{
emit commitData(spinBox);
emit closeEditor(spinBox);
}
}
void QmitkPropertyDelegate::showColorDialog()
{
}
bool QmitkPropertyDelegate::eventFilter(QObject *o, QEvent *e)
{
// filter all kind of events on our editor widgets
// when certain events occur, repaint all render windows, because rendering relevant properties might have changed
switch (e->type())
{
case QEvent::KeyRelease:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::Wheel:
case QEvent::FocusIn:
{
if (QWidget *editor = dynamic_cast<QWidget *>(o))
{
emit commitData(editor);
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
break;
}
default:
{
break;
}
}
return false;
}
diff --git a/Modules/QtWidgets/src/QmitkPropertyItemDelegate.cpp b/Modules/QtWidgets/src/QmitkPropertyItemDelegate.cpp
index 9eae1448e9..544b7690a2 100644
--- a/Modules/QtWidgets/src/QmitkPropertyItemDelegate.cpp
+++ b/Modules/QtWidgets/src/QmitkPropertyItemDelegate.cpp
@@ -1,382 +1,380 @@
/*============================================================================
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 "QmitkPropertyItemDelegate.h"
#include "QmitkPropertyItemModel.h"
#include <QApplication>
#include <QColorDialog>
#include <QComboBox>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPaintEvent>
#include <QPainter>
#include <QSpinBox>
#include <QToolButton>
#include <algorithm>
#include <mitkBaseProperty.h>
#include <mitkCoreServices.h>
#include <mitkFloatPropertyExtension.h>
#include <mitkIPropertyExtensions.h>
#include <mitkIntPropertyExtension.h>
QmitkColorWidget::QmitkColorWidget(QWidget *parent)
: QWidget(parent), m_LineEdit(new QLineEdit), m_Button(new QToolButton)
{
m_LineEdit->setText(m_Color.name());
m_Button->setText("...");
QHBoxLayout *layout = new QHBoxLayout;
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
layout->addWidget(m_LineEdit);
layout->addWidget(m_Button);
this->setFocusProxy(m_LineEdit);
this->setLayout(layout);
connect(m_LineEdit, SIGNAL(editingFinished()), this, SLOT(OnLineEditEditingFinished()));
connect(m_Button, SIGNAL(clicked()), this, SLOT(OnButtonClicked()));
}
QmitkColorWidget::~QmitkColorWidget()
{
}
QColor QmitkColorWidget::GetColor() const
{
return m_Color;
}
void QmitkColorWidget::SetColor(QColor color)
{
m_Color = color;
m_LineEdit->setText(color.name());
}
void QmitkColorWidget::OnLineEditEditingFinished()
{
- if (!QColor::isValidColor(m_LineEdit->text()))
+ if (!QColor::isValidColorName(m_LineEdit->text()))
m_LineEdit->setText("#000000");
- m_Color.setNamedColor(m_LineEdit->text());
+ m_Color = QColor::fromString(m_LineEdit->text());
}
void QmitkColorWidget::OnButtonClicked()
{
QColor color = QColorDialog::getColor(m_Color, QApplication::activeWindow());
if (color.isValid())
{
this->SetColor(color);
emit ColorPicked();
}
}
QmitkComboBoxListView::QmitkComboBoxListView(QComboBox *comboBox) : m_ComboBox(comboBox)
{
}
QmitkComboBoxListView::~QmitkComboBoxListView()
{
}
void QmitkComboBoxListView::paintEvent(QPaintEvent *event)
{
if (m_ComboBox != nullptr)
{
QStyleOptionComboBox option;
option.initFrom(m_ComboBox);
option.editable = m_ComboBox->isEditable();
if (m_ComboBox->style()->styleHint(QStyle::SH_ComboBox_Popup, &option, m_ComboBox))
{
QStyleOptionMenuItem menuOption;
menuOption.initFrom(this);
menuOption.palette = this->palette();
menuOption.state = QStyle::State_None;
menuOption.checkType = QStyleOptionMenuItem::NotCheckable;
menuOption.menuRect = event->rect();
menuOption.maxIconWidth = 0;
- menuOption.tabWidth = 0;
QPainter painter(this->viewport());
m_ComboBox->style()->drawControl(QStyle::CE_MenuEmptyArea, &menuOption, &painter, this);
}
}
QListView::paintEvent(event);
}
void QmitkComboBoxListView::resizeEvent(QResizeEvent *event)
{
int width = this->viewport()->width();
int height = this->contentsSize().height();
this->resizeContents(width, height);
QListView::resizeEvent(event);
}
-QStyleOptionViewItem QmitkComboBoxListView::viewOptions() const
+void QmitkComboBoxListView::initViewItemOption(QStyleOptionViewItem* option) const
{
- QStyleOptionViewItem option = QListView::viewOptions();
- option.showDecorationSelected = true;
+ QListView::initViewItemOption(option);
- if (m_ComboBox != nullptr)
- option.font = m_ComboBox->font();
+ option->showDecorationSelected = true;
- return option;
+ if (m_ComboBox != nullptr)
+ option->font = m_ComboBox->font();
}
class PropertyEqualTo
{
public:
PropertyEqualTo(const mitk::BaseProperty *property) : m_Property(property) {}
bool operator()(const mitk::PropertyList::PropertyMapElementType &pair) const
{
return pair.second.GetPointer() == m_Property;
}
private:
const mitk::BaseProperty *m_Property;
};
QmitkPropertyItemDelegate::QmitkPropertyItemDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
}
QmitkPropertyItemDelegate::~QmitkPropertyItemDelegate()
{
}
QWidget *QmitkPropertyItemDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
if (data.isValid())
{
- if (data.type() == QVariant::Int)
+ if (data.typeId() == QMetaType::Int)
{
QSpinBox *spinBox = new QSpinBox(parent);
mitk::CoreServicePointer<mitk::IPropertyExtensions> extensions(mitk::CoreServices::GetPropertyExtensions());
std::string name = this->GetPropertyName(index);
if (!name.empty() && extensions->HasExtension(name))
{
mitk::IntPropertyExtension::Pointer extension =
dynamic_cast<mitk::IntPropertyExtension *>(extensions->GetExtension(name).GetPointer());
if (extension.IsNotNull())
{
spinBox->setMinimum(extension->GetMinimum());
spinBox->setMaximum(extension->GetMaximum());
spinBox->setSingleStep(extension->GetSingleStep());
}
}
connect(spinBox, SIGNAL(editingFinished()), this, SLOT(OnSpinBoxEditingFinished()));
return spinBox;
}
- if (data.type() == QVariant::Double || static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
+ if (data.typeId() == QMetaType::Double || data.typeId() == QMetaType::Float)
{
QDoubleSpinBox *spinBox = new QDoubleSpinBox(parent);
mitk::CoreServicePointer<mitk::IPropertyExtensions> extensions(mitk::CoreServices::GetPropertyExtensions());
std::string name = this->GetPropertyName(index);
if (!name.empty() && extensions->HasExtension(name))
{
mitk::FloatPropertyExtension::Pointer extension =
dynamic_cast<mitk::FloatPropertyExtension *>(extensions->GetExtension(name).GetPointer());
if (extension.IsNotNull())
{
spinBox->setMinimum(extension->GetMinimum());
spinBox->setMaximum(extension->GetMaximum());
spinBox->setSingleStep(extension->GetSingleStep());
spinBox->setDecimals(extension->GetDecimals());
}
}
else
{
spinBox->setSingleStep(0.1);
spinBox->setDecimals(4);
}
if (name == "opacity") // TODO
{
spinBox->setMinimum(0.0);
spinBox->setMaximum(1.0);
}
connect(spinBox, SIGNAL(editingFinished()), this, SLOT(OnSpinBoxEditingFinished()));
return spinBox;
}
- if (data.type() == QVariant::StringList)
+ if (data.typeId() == QMetaType::QStringList)
{
QComboBox *comboBox = new QComboBox(parent);
comboBox->setView(new QmitkComboBoxListView(comboBox));
comboBox->addItems(data.toStringList());
connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnComboBoxCurrentIndexChanged(int)));
return comboBox;
}
- if (data.type() == QVariant::Color)
+ if (data.typeId() == QMetaType::QColor)
{
QmitkColorWidget *colorWidget = new QmitkColorWidget(parent);
connect(colorWidget, SIGNAL(ColorPicked()), this, SLOT(OnColorPicked()));
return colorWidget;
}
}
return QStyledItemDelegate::createEditor(parent, option, index);
}
std::string QmitkPropertyItemDelegate::GetPropertyName(const QModelIndex &index) const
{
auto propertyList = m_PropertyList.Lock();
if (propertyList.IsNotNull())
{
mitk::BaseProperty *property =
reinterpret_cast<mitk::BaseProperty *>(index.data(mitk::PropertyRole).value<void *>());
const mitk::PropertyList::PropertyMap *propertyMap = propertyList->GetMap();
mitk::PropertyList::PropertyMap::const_iterator it =
std::find_if(propertyMap->begin(), propertyMap->end(), PropertyEqualTo(property));
if (it != propertyMap->end())
return it->first;
}
return "";
}
void QmitkPropertyItemDelegate::OnComboBoxCurrentIndexChanged(int)
{
QComboBox *comboBox = qobject_cast<QComboBox *>(sender());
emit commitData(comboBox);
emit closeEditor(comboBox);
}
void QmitkPropertyItemDelegate::OnSpinBoxEditingFinished()
{
QAbstractSpinBox *spinBox = qobject_cast<QAbstractSpinBox *>(sender());
emit commitData(spinBox);
emit closeEditor(spinBox);
}
void QmitkPropertyItemDelegate::OnColorPicked()
{
QmitkColorWidget *colorWidget = qobject_cast<QmitkColorWidget *>(sender());
emit commitData(colorWidget);
emit closeEditor(colorWidget);
}
void QmitkPropertyItemDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QVariant data = index.data();
- if (index.column() == 1 && data.type() == QVariant::Color)
+ if (index.column() == 1 && data.typeId() == QMetaType::QColor)
{
painter->fillRect(option.rect, data.value<QColor>());
return;
}
QStyledItemDelegate::paint(painter, option, index);
}
void QmitkPropertyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
if (!data.isValid())
return;
- if (data.type() == QVariant::StringList)
+ if (data.typeId() == QMetaType::QStringList)
{
QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
comboBox->setCurrentIndex(comboBox->findText(index.data().toString()));
}
- if (data.type() == QVariant::Color)
+ if (data.typeId() == QMetaType::QColor)
{
QmitkColorWidget *colorWidget = qobject_cast<QmitkColorWidget *>(editor);
colorWidget->SetColor(data.value<QColor>());
}
else
{
QStyledItemDelegate::setEditorData(editor, index);
}
}
void QmitkPropertyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QVariant data = index.data(Qt::EditRole);
if (!data.isValid())
return;
- if (data.type() == QVariant::Int)
+ if (data.typeId() == QMetaType::Int)
{
QSpinBox *spinBox = qobject_cast<QSpinBox *>(editor);
model->setData(index, spinBox->value());
}
- else if (data.type() == QVariant::Double)
+ else if (data.typeId() == QMetaType::Double)
{
QDoubleSpinBox *spinBox = qobject_cast<QDoubleSpinBox *>(editor);
model->setData(index, spinBox->value());
}
- else if (static_cast<QMetaType::Type>(data.type()) == QMetaType::Float)
+ else if (data.typeId() == QMetaType::Float)
{
QDoubleSpinBox *spinBox = qobject_cast<QDoubleSpinBox *>(editor);
model->setData(index, static_cast<float>(spinBox->value()));
}
- else if (data.type() == QVariant::StringList)
+ else if (data.typeId() == QMetaType::QStringList)
{
QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
model->setData(index, comboBox->currentText());
}
- else if (data.type() == QVariant::Color)
+ else if (data.typeId() == QMetaType::QColor)
{
QmitkColorWidget *colorWidget = qobject_cast<QmitkColorWidget *>(editor);
model->setData(index, colorWidget->GetColor());
}
else
{
QStyledItemDelegate::setModelData(editor, model, index);
}
}
void QmitkPropertyItemDelegate::SetPropertyList(mitk::PropertyList *propertyList)
{
if (m_PropertyList != propertyList)
m_PropertyList = propertyList;
}
diff --git a/Modules/QtWidgets/src/QmitkPropertyItemModel.cpp b/Modules/QtWidgets/src/QmitkPropertyItemModel.cpp
index 10514fbe2a..22a464abba 100644
--- a/Modules/QtWidgets/src/QmitkPropertyItemModel.cpp
+++ b/Modules/QtWidgets/src/QmitkPropertyItemModel.cpp
@@ -1,478 +1,478 @@
/*============================================================================
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 "QmitkPropertyItemModel.h"
#include "QmitkPropertyItem.h"
#include <QColor>
#include <mitkColorProperty.h>
#include <mitkEnumerationProperty.h>
#include <mitkIPropertyAliases.h>
#include <mitkIPropertyFilters.h>
#include <mitkProperties.h>
#include <mitkRenderingManager.h>
#include <mitkStringProperty.h>
namespace
{
QColor MitkToQt(const mitk::Color& color)
{
return QColor(color.GetRed() * 255, color.GetGreen() * 255, color.GetBlue() * 255);
}
mitk::BaseProperty* GetBaseProperty(const QVariant& data)
{
return data.isValid() ? reinterpret_cast<mitk::BaseProperty*>(data.value<void*>()) : nullptr;
}
mitk::Color QtToMitk(const QColor& color)
{
mitk::Color mitkColor;
mitkColor.SetRed(color.red() / 255.0f);
mitkColor.SetGreen(color.green() / 255.0f);
mitkColor.SetBlue(color.blue() / 255.0f);
return mitkColor;
}
}
class PropertyEqualTo
{
public:
PropertyEqualTo(const mitk::BaseProperty *property) : m_Property(property) {}
bool operator()(const mitk::PropertyList::PropertyMapElementType &pair) const
{
return pair.second.GetPointer() == m_Property;
}
private:
const mitk::BaseProperty *m_Property;
};
QmitkPropertyItemModel::QmitkPropertyItemModel(QObject *parent)
: QAbstractItemModel(parent),
m_PropertyAliases(mitk::CoreServices::GetPropertyAliases()),
m_PropertyFilters(mitk::CoreServices::GetPropertyFilters())
{
this->CreateRootItem();
}
QmitkPropertyItemModel::~QmitkPropertyItemModel()
{
this->SetNewPropertyList(nullptr);
}
int QmitkPropertyItemModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return static_cast<QmitkPropertyItem *>(parent.internalPointer())->GetColumnCount();
else
return m_RootItem->GetColumnCount();
}
void QmitkPropertyItemModel::CreateRootItem()
{
QList<QVariant> rootData;
rootData << "Property"
<< "Value";
m_RootItem.reset(new QmitkPropertyItem(rootData));
this->beginResetModel();
this->endResetModel();
}
QVariant QmitkPropertyItemModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
mitk::BaseProperty *property =
index.column() == 1 ? GetBaseProperty(static_cast<QmitkPropertyItem *>(index.internalPointer())->GetData(1)) : nullptr;
if (role == Qt::DisplayRole)
{
if (index.column() == 0)
{
return static_cast<QmitkPropertyItem *>(index.internalPointer())->GetData(0);
}
else if (index.column() == 1 && property != nullptr)
{
if (auto colorProperty = dynamic_cast<mitk::ColorProperty *>(property))
return MitkToQt(colorProperty->GetValue());
else if (dynamic_cast<mitk::BoolProperty *>(property) == nullptr)
return QString::fromStdString(property->GetValueAsString());
}
}
else if (index.column() == 1 && property != nullptr)
{
if (role == Qt::CheckStateRole)
{
if (auto boolProperty = dynamic_cast<mitk::BoolProperty *>(property))
return boolProperty->GetValue() ? Qt::Checked : Qt::Unchecked;
}
else if (role == Qt::EditRole)
{
if (dynamic_cast<mitk::StringProperty *>(property) != nullptr)
{
return QString::fromStdString(property->GetValueAsString());
}
else if (auto intProperty = dynamic_cast<mitk::IntProperty *>(property))
{
return intProperty->GetValue();
}
else if (auto floatProperty = dynamic_cast<mitk::FloatProperty *>(property))
{
return floatProperty->GetValue();
}
else if (auto doubleProperty = dynamic_cast<mitk::DoubleProperty *>(property))
{
return doubleProperty->GetValue();
}
else if (auto enumProperty = dynamic_cast<mitk::EnumerationProperty *>(property))
{
QStringList values;
for (mitk::EnumerationProperty::EnumConstIterator it = enumProperty->Begin(); it != enumProperty->End(); it++)
values << QString::fromStdString(it->second);
return values;
}
else if (auto colorProperty = dynamic_cast<mitk::ColorProperty *>(property))
{
return MitkToQt(colorProperty->GetValue());
}
}
else if (role == mitk::PropertyRole)
{
return QVariant::fromValue<void *>(property);
}
}
return QVariant();
}
QModelIndex QmitkPropertyItemModel::FindProperty(const mitk::BaseProperty *property)
{
if (property == nullptr)
return QModelIndex();
auto propertyList = m_PropertyList.Lock();
if (propertyList.IsNull())
return QModelIndex();
auto propertyMap = propertyList->GetMap();
auto it = std::find_if(propertyMap->begin(), propertyMap->end(), PropertyEqualTo(property));
if (it == propertyMap->end())
return QModelIndex();
QString name = QString::fromStdString(it->first);
if (!name.contains('.'))
{
QModelIndexList item = this->match(index(0, 0), Qt::DisplayRole, name, 1, Qt::MatchExactly);
if (!item.empty())
return item[0];
}
else
{
QStringList names = name.split('.');
QModelIndexList items =
this->match(index(0, 0), Qt::DisplayRole, names.last(), -1, Qt::MatchRecursive | Qt::MatchExactly);
- for (auto item : qAsConst(items))
+ for (auto item : std::as_const(items))
{
QModelIndex candidate = item;
for (int i = names.length() - 1; i != 0; --i)
{
QModelIndex parent = item.parent();
if (parent.parent() == QModelIndex())
{
if (parent.data() != names.first())
break;
return candidate;
}
if (parent.data() != names[i - 1])
break;
item = parent;
}
}
}
return QModelIndex();
}
Qt::ItemFlags QmitkPropertyItemModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (index.column() == 1)
{
if (index.data(Qt::EditRole).isValid())
flags |= Qt::ItemIsEditable;
if (index.data(Qt::CheckStateRole).isValid())
flags |= Qt::ItemIsUserCheckable;
}
return flags;
}
mitk::PropertyList *QmitkPropertyItemModel::GetPropertyList() const
{
return m_PropertyList.Lock().GetPointer();
}
QVariant QmitkPropertyItemModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return m_RootItem->GetData(section);
return QVariant();
}
QModelIndex QmitkPropertyItemModel::index(int row, int column, const QModelIndex &parent) const
{
if (!this->hasIndex(row, column, parent))
return QModelIndex();
QmitkPropertyItem *parentItem =
parent.isValid() ? static_cast<QmitkPropertyItem *>(parent.internalPointer()) : m_RootItem.get();
QmitkPropertyItem *childItem = parentItem->GetChild(row);
return childItem != nullptr ? this->createIndex(row, column, childItem) : QModelIndex();
}
void QmitkPropertyItemModel::OnPropertyListModified()
{
this->SetNewPropertyList(m_PropertyList.Lock());
}
void QmitkPropertyItemModel::OnPropertyListDeleted()
{
this->CreateRootItem();
}
void QmitkPropertyItemModel::OnPropertyModified(const itk::Object *property, const itk::EventObject &)
{
QModelIndex index = this->FindProperty(static_cast<const mitk::BaseProperty *>(property));
if (index != QModelIndex())
emit dataChanged(index, index);
}
QModelIndex QmitkPropertyItemModel::parent(const QModelIndex &child) const
{
if (!child.isValid())
return QModelIndex();
QmitkPropertyItem *parentItem = static_cast<QmitkPropertyItem *>(child.internalPointer())->GetParent();
if (parentItem == m_RootItem.get())
return QModelIndex();
return this->createIndex(parentItem->GetRow(), 0, parentItem);
}
int QmitkPropertyItemModel::rowCount(const QModelIndex &parent) const
{
if (parent.column() > 0)
return 0;
QmitkPropertyItem *parentItem =
parent.isValid() ? static_cast<QmitkPropertyItem *>(parent.internalPointer()) : m_RootItem.get();
return parentItem->GetChildCount();
}
bool QmitkPropertyItemModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid() || index.column() != 1 || (role != Qt::EditRole && role != Qt::CheckStateRole))
return false;
mitk::BaseProperty *property = GetBaseProperty(static_cast<QmitkPropertyItem *>(index.internalPointer())->GetData(1));
if (property == nullptr)
return false;
if (mitk::BoolProperty *boolProperty = dynamic_cast<mitk::BoolProperty *>(property))
{
boolProperty->SetValue(value.toInt() == Qt::Checked ? true : false);
}
else if (mitk::StringProperty *stringProperty = dynamic_cast<mitk::StringProperty *>(property))
{
stringProperty->SetValue(value.toString().toStdString());
}
else if (mitk::IntProperty *intProperty = dynamic_cast<mitk::IntProperty *>(property))
{
intProperty->SetValue(value.toInt());
}
else if (mitk::FloatProperty *floatProperty = dynamic_cast<mitk::FloatProperty *>(property))
{
floatProperty->SetValue(value.toFloat());
}
else if (mitk::DoubleProperty *doubleProperty = dynamic_cast<mitk::DoubleProperty *>(property))
{
doubleProperty->SetValue(value.toDouble());
}
else if (mitk::EnumerationProperty *enumProperty = dynamic_cast<mitk::EnumerationProperty *>(property))
{
std::string selection = value.toString().toStdString();
if (selection != enumProperty->GetValueAsString() && enumProperty->IsValidEnumerationValue(selection))
enumProperty->SetValue(selection);
}
else if (mitk::ColorProperty *colorProperty = dynamic_cast<mitk::ColorProperty *>(property))
{
colorProperty->SetValue(QtToMitk(value.value<QColor>()));
}
auto propertyList = m_PropertyList.Lock();
propertyList->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
return true;
}
void QmitkPropertyItemModel::SetNewPropertyList(mitk::PropertyList *newPropertyList)
{
typedef mitk::PropertyList::PropertyMap PropertyMap;
this->beginResetModel();
auto propertyList = m_PropertyList.Lock();
if (propertyList.IsNotNull())
{
propertyList->RemoveObserver(m_PropertyListDeletedTag);
propertyList->RemoveObserver(m_PropertyListModifiedTag);
const PropertyMap *propertyMap = propertyList->GetMap();
for (PropertyMap::const_iterator propertyIt = propertyMap->begin(); propertyIt != propertyMap->end(); ++propertyIt)
{
std::map<std::string, unsigned long>::const_iterator tagIt = m_PropertyModifiedTags.find(propertyIt->first);
if (tagIt != m_PropertyModifiedTags.end())
propertyIt->second->RemoveObserver(tagIt->second);
tagIt = m_PropertyDeletedTags.find(propertyIt->first);
if (tagIt != m_PropertyDeletedTags.end())
propertyIt->second->RemoveObserver(tagIt->second);
}
m_PropertyModifiedTags.clear();
m_PropertyDeletedTags.clear();
}
m_PropertyList = newPropertyList;
propertyList = m_PropertyList.Lock();
if (propertyList.IsNotNull())
{
auto onPropertyListModified = itk::SimpleMemberCommand<QmitkPropertyItemModel>::New();
onPropertyListModified->SetCallbackFunction(this, &QmitkPropertyItemModel::OnPropertyListModified);
m_PropertyListModifiedTag = propertyList->AddObserver(itk::ModifiedEvent(), onPropertyListModified);
auto onPropertyListDeleted = itk::SimpleMemberCommand<QmitkPropertyItemModel>::New();
onPropertyListDeleted->SetCallbackFunction(this, &QmitkPropertyItemModel::OnPropertyListDeleted);
m_PropertyListDeletedTag = propertyList->AddObserver(itk::DeleteEvent(), onPropertyListDeleted);
auto modifiedCommand = itk::MemberCommand<QmitkPropertyItemModel>::New();
modifiedCommand->SetCallbackFunction(this, &QmitkPropertyItemModel::OnPropertyModified);
const PropertyMap *propertyMap = m_PropertyList.Lock()->GetMap();
for (PropertyMap::const_iterator it = propertyMap->begin(); it != propertyMap->end(); ++it)
m_PropertyModifiedTags.insert(
std::make_pair(it->first, it->second->AddObserver(itk::ModifiedEvent(), modifiedCommand)));
}
this->CreateRootItem();
propertyList = m_PropertyList.Lock();
if (propertyList.IsNotNull() && !propertyList->IsEmpty())
{
mitk::PropertyList::PropertyMap filteredProperties;
bool filterProperties = false;
if (m_PropertyFilters->HasFilter() || m_PropertyFilters->HasFilter(m_ClassName.toStdString()))
{
filteredProperties = m_PropertyFilters->ApplyFilter(*propertyList->GetMap(), m_ClassName.toStdString());
filterProperties = true;
}
const mitk::PropertyList::PropertyMap *propertyMap =
!filterProperties ? propertyList->GetMap() : &filteredProperties;
mitk::PropertyList::PropertyMap::const_iterator end = propertyMap->end();
for (mitk::PropertyList::PropertyMap::const_iterator iter = propertyMap->begin(); iter != end; ++iter)
{
std::vector<std::string> aliases;
aliases = m_PropertyAliases->GetAliases(iter->first, m_ClassName.toStdString());
if (aliases.empty() && !m_ClassName.isEmpty())
aliases = m_PropertyAliases->GetAliases(iter->first);
if (aliases.empty())
{
QList<QVariant> data;
data << QString::fromStdString(iter->first)
<< QVariant::fromValue((reinterpret_cast<void *>(iter->second.GetPointer())));
m_RootItem->AppendChild(new QmitkPropertyItem(data));
}
else
{
std::vector<std::string>::const_iterator end = aliases.end();
for (std::vector<std::string>::const_iterator aliasIter = aliases.begin(); aliasIter != end; ++aliasIter)
{
QList<QVariant> data;
data << QString::fromStdString(*aliasIter)
<< QVariant::fromValue((reinterpret_cast<void *>(iter->second.GetPointer())));
m_RootItem->AppendChild(new QmitkPropertyItem(data));
}
}
}
}
this->endResetModel();
}
void QmitkPropertyItemModel::SetPropertyList(mitk::PropertyList *propertyList, const QString &className)
{
if (m_PropertyList != propertyList)
{
m_ClassName = className;
this->SetNewPropertyList(propertyList);
}
}
void QmitkPropertyItemModel::Update()
{
this->SetNewPropertyList(m_PropertyList.Lock());
}
diff --git a/Modules/QtWidgets/src/QmitkRenderWindow.cpp b/Modules/QtWidgets/src/QmitkRenderWindow.cpp
index 601981ce79..669bf58cbe 100644
--- a/Modules/QtWidgets/src/QmitkRenderWindow.cpp
+++ b/Modules/QtWidgets/src/QmitkRenderWindow.cpp
@@ -1,515 +1,518 @@
/*============================================================================
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 "QmitkRenderWindow.h"
#include "mitkInteractionKeyEvent.h"
#include "mitkInternalEvent.h"
#include "mitkMouseDoubleClickEvent.h"
#include "mitkMouseMoveEvent.h"
#include "mitkMousePressEvent.h"
#include "mitkMouseReleaseEvent.h"
#include "mitkMouseWheelEvent.h"
#include <mitkStatusBar.h>
#include <QCursor>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QResizeEvent>
#include <QSurfaceFormat>
#include <QTimer>
#include <QWheelEvent>
#include <QWindow>
#include <QmitkMimeTypes.h>
#include <QmitkRenderWindowMenu.h>
#include <QmitkStyleManager.h>
QmitkRenderWindow::QmitkRenderWindow(QWidget *parent, const QString &name, mitk::VtkPropRenderer *)
: QVTKOpenGLNativeWidget(parent)
, m_ResendQtEvents(true)
, m_MenuWidget(nullptr)
, m_MenuWidgetActivated(false)
, m_LayoutIndex(QmitkRenderWindowMenu::LayoutIndex::Axial)
, m_GeometryViolationWarningOverlay(nullptr)
{
m_InternalRenderWindow = vtkSmartPointer<vtkGenericOpenGLRenderWindow>::New();
m_InternalRenderWindow->SetMultiSamples(0);
m_InternalRenderWindow->SetAlphaBitPlanes(0);
setRenderWindow(m_InternalRenderWindow);
Initialize(name.toStdString().c_str());
setFocusPolicy(Qt::StrongFocus);
setMouseTracking(true);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setSizePolicy(sizePolicy);
// setup overlay widget to show a warning message with a button
m_GeometryViolationWarningOverlay = new QmitkButtonOverlayWidget(this);
m_GeometryViolationWarningOverlay->setVisible(false);
m_GeometryViolationWarningOverlay->SetOverlayText(
QStringLiteral("<font color=\"red\"><p style=\"text-align:center\">Interaction is not possible because the "
"render window geometry<br>does not match the interaction reference geometry.</p></center></font>"));
m_GeometryViolationWarningOverlay->SetButtonText("Reset geometry");
m_GeometryViolationWarningOverlay->SetButtonIcon(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/reset.svg")));
connect(m_GeometryViolationWarningOverlay, &QmitkButtonOverlayWidget::Clicked,
this, &QmitkRenderWindow::ResetGeometry);
}
QmitkRenderWindow::~QmitkRenderWindow()
{
Destroy(); // Destroy mitkRenderWindowBase
}
void QmitkRenderWindow::SetResendQtEvents(bool resend)
{
m_ResendQtEvents = resend;
}
void QmitkRenderWindow::SetLayoutIndex(QmitkRenderWindowMenu::LayoutIndex layoutIndex)
{
m_LayoutIndex = layoutIndex;
if (nullptr != m_MenuWidget)
{
m_MenuWidget->SetLayoutIndex(layoutIndex);
}
}
QmitkRenderWindowMenu::LayoutIndex QmitkRenderWindow::GetLayoutIndex()
{
if (nullptr != m_MenuWidget)
{
return m_MenuWidget->GetLayoutIndex();
}
else
{
return QmitkRenderWindowMenu::LayoutIndex::Axial;
}
}
void QmitkRenderWindow::UpdateLayoutDesignList(QmitkRenderWindowMenu::LayoutDesign layoutDesign)
{
if (nullptr != m_MenuWidget)
{
m_MenuWidget->UpdateLayoutDesignList(layoutDesign);
}
}
void QmitkRenderWindow::UpdateCrosshairVisibility(bool visible)
{
m_MenuWidget->UpdateCrosshairVisibility(visible);
}
void QmitkRenderWindow::UpdateCrosshairRotationMode(int mode)
{
m_MenuWidget->UpdateCrosshairRotationMode(mode);
}
void QmitkRenderWindow::ActivateMenuWidget(bool state)
{
if (nullptr == m_MenuWidget)
{
- m_MenuWidget = new QmitkRenderWindowMenu(this, nullptr, m_Renderer);
+ m_MenuWidget = new QmitkRenderWindowMenu(this, {}, m_Renderer);
m_MenuWidget->SetLayoutIndex(m_LayoutIndex);
}
if (m_MenuWidgetActivated == state)
{
// no new state; nothing to do
return;
}
m_MenuWidgetActivated = state;
if (m_MenuWidgetActivated)
{
connect(m_MenuWidget, &QmitkRenderWindowMenu::LayoutDesignChanged, this, &QmitkRenderWindow::LayoutDesignChanged);
connect(m_MenuWidget, &QmitkRenderWindowMenu::ResetView, this, &QmitkRenderWindow::ResetView);
connect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairVisibilityChanged, this, &QmitkRenderWindow::CrosshairVisibilityChanged);
connect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairRotationModeChanged, this, &QmitkRenderWindow::CrosshairRotationModeChanged);
}
else
{
disconnect(m_MenuWidget, &QmitkRenderWindowMenu::LayoutDesignChanged, this, &QmitkRenderWindow::LayoutDesignChanged);
disconnect(m_MenuWidget, &QmitkRenderWindowMenu::ResetView, this, &QmitkRenderWindow::ResetView);
disconnect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairVisibilityChanged, this, &QmitkRenderWindow::CrosshairVisibilityChanged);
disconnect(m_MenuWidget, &QmitkRenderWindowMenu::CrosshairRotationModeChanged, this, &QmitkRenderWindow::CrosshairRotationModeChanged);
m_MenuWidget->hide();
}
}
void QmitkRenderWindow::ShowOverlayMessage(bool show)
{
m_GeometryViolationWarningOverlay->setVisible(show);
}
void QmitkRenderWindow::moveEvent(QMoveEvent *event)
{
QVTKOpenGLNativeWidget::moveEvent(event);
// after a move the overlays need to be positioned
emit moved();
}
void QmitkRenderWindow::showEvent(QShowEvent *event)
{
QVTKOpenGLNativeWidget::showEvent(event);
// this singleshot is necessary to have the overlays positioned correctly after initial show
// simple call of moved() is no use here!!
QTimer::singleShot(0, this, SIGNAL(moved()));
}
bool QmitkRenderWindow::event(QEvent* e)
{
mitk::InteractionEvent::Pointer mitkEvent = nullptr;
mitk::Point2D mousePosition;
bool updateStatusBar = false;
switch (e->type())
{
case QEvent::MouseMove:
{
auto me = static_cast<QMouseEvent *>(e);
mousePosition = this->GetMousePosition(me);
mitkEvent = mitk::MouseMoveEvent::New(m_Renderer, mousePosition, GetButtonState(me), GetModifiers(me));
updateStatusBar = true;
break;
}
case QEvent::MouseButtonPress:
{
auto me = static_cast<QMouseEvent *>(e);
mitkEvent = mitk::MousePressEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me));
break;
}
case QEvent::MouseButtonRelease:
{
auto me = static_cast<QMouseEvent *>(e);
mitkEvent = mitk::MouseReleaseEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me));
break;
}
case QEvent::MouseButtonDblClick:
{
auto me = static_cast<QMouseEvent *>(e);
mitkEvent = mitk::MouseDoubleClickEvent::New( m_Renderer, GetMousePosition(me), GetButtonState(me), GetModifiers(me), GetEventButton(me));
break;
}
case QEvent::Wheel:
{
auto we = static_cast<QWheelEvent *>(e);
mousePosition = this->GetMousePosition(we);
mitkEvent = mitk::MouseWheelEvent::New(m_Renderer, mousePosition, GetButtonState(we), GetModifiers(we), GetDelta(we));
updateStatusBar = true;
break;
}
case QEvent::KeyPress:
{
auto ke = static_cast<QKeyEvent*>(e);
mitkEvent = mitk::InteractionKeyEvent::New(m_Renderer, GetKeyLetter(ke), GetModifiers(ke));
break;
}
case QEvent::Resize:
{
if (nullptr != m_MenuWidget)
m_MenuWidget->MoveWidgetToCorrectPos();
}
default:
{
break;
}
}
if (mitkEvent != nullptr)
{
if (this->HandleEvent(mitkEvent.GetPointer())) {
return m_ResendQtEvents ? false : true;
}
}
if (updateStatusBar)
{
this->UpdateStatusBar(mousePosition);
}
return QVTKOpenGLNativeWidget::event(e);
}
-void QmitkRenderWindow::enterEvent(QEvent *e)
+void QmitkRenderWindow::enterEvent(QEnterEvent *e)
{
auto* baseRenderer = mitk::BaseRenderer::GetInstance(this->GetVtkRenderWindow());
this->ShowOverlayMessage(!baseRenderer->GetReferenceGeometryAligned());
if (nullptr != m_MenuWidget)
m_MenuWidget->ShowMenu();
QVTKOpenGLNativeWidget::enterEvent(e);
}
void QmitkRenderWindow::leaveEvent(QEvent *e)
{
auto statusBar = mitk::StatusBar::GetInstance();
statusBar->DisplayGreyValueText("");
this->ShowOverlayMessage(false);
if (nullptr != m_MenuWidget)
m_MenuWidget->HideMenu();
QVTKOpenGLNativeWidget::leaveEvent(e);
}
void QmitkRenderWindow::resizeGL(int w, int h)
{
QVTKOpenGLNativeWidget::resizeGL(w, h);
mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(renderWindow());
}
void QmitkRenderWindow::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-mitk-datanodes"))
{
event->accept();
}
}
void QmitkRenderWindow::dropEvent(QDropEvent *event)
{
QList<mitk::DataNode *> dataNodeList = QmitkMimeTypes::ToDataNodePtrList(event->mimeData());
if (!dataNodeList.empty())
{
- emit NodesDropped(this, dataNodeList.toVector().toStdVector());
+ std::vector dataNodes(dataNodeList.begin(), dataNodeList.end());
+ emit NodesDropped(this, dataNodes);
}
}
void QmitkRenderWindow::DeferredHideMenu()
{
MITK_DEBUG << "QmitkRenderWindow::DeferredHideMenu";
if (nullptr != m_MenuWidget)
{
m_MenuWidget->HideMenu();
}
}
mitk::Point2D QmitkRenderWindow::GetMousePosition(QMouseEvent *me) const
{
mitk::Point2D point;
const auto scale = this->devicePixelRatioF();
- point[0] = me->x()*scale;
+ const auto position = me->position();
+ point[0] = position.x()*scale;
// We need to convert the y component, as the display and vtk have other definitions for the y direction
- point[1] = m_Renderer->GetSizeY() - me->y()*scale;
+ point[1] = m_Renderer->GetSizeY() - position.y()*scale;
return point;
}
mitk::Point2D QmitkRenderWindow::GetMousePosition(QWheelEvent *we) const
{
mitk::Point2D point;
const auto scale = this->devicePixelRatioF();
- point[0] = we->x()*scale;
+ const auto position = we->position();
+ point[0] = position.x()*scale;
// We need to convert the y component, as the display and vtk have other definitions for the y direction
- point[1] = m_Renderer->GetSizeY() - we->y()*scale;
+ point[1] = m_Renderer->GetSizeY() - position.y()*scale;
return point;
}
mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetEventButton(QMouseEvent *me) const
{
mitk::InteractionEvent::MouseButtons eventButton;
switch (me->button())
{
case Qt::LeftButton:
eventButton = mitk::InteractionEvent::LeftMouseButton;
break;
case Qt::RightButton:
eventButton = mitk::InteractionEvent::RightMouseButton;
break;
- case Qt::MidButton:
+ case Qt::MiddleButton:
eventButton = mitk::InteractionEvent::MiddleMouseButton;
break;
default:
eventButton = mitk::InteractionEvent::NoButton;
break;
}
return eventButton;
}
mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetButtonState(QMouseEvent *me) const
{
mitk::InteractionEvent::MouseButtons buttonState = mitk::InteractionEvent::NoButton;
if (me->buttons() & Qt::LeftButton)
{
buttonState = buttonState | mitk::InteractionEvent::LeftMouseButton;
}
if (me->buttons() & Qt::RightButton)
{
buttonState = buttonState | mitk::InteractionEvent::RightMouseButton;
}
- if (me->buttons() & Qt::MidButton)
+ if (me->buttons() & Qt::MiddleButton)
{
buttonState = buttonState | mitk::InteractionEvent::MiddleMouseButton;
}
return buttonState;
}
mitk::InteractionEvent::ModifierKeys QmitkRenderWindow::GetModifiers(QInputEvent *me) const
{
mitk::InteractionEvent::ModifierKeys modifiers = mitk::InteractionEvent::NoKey;
if (me->modifiers() & Qt::ALT)
{
modifiers = modifiers | mitk::InteractionEvent::AltKey;
}
if (me->modifiers() & Qt::CTRL)
{
modifiers = modifiers | mitk::InteractionEvent::ControlKey;
}
if (me->modifiers() & Qt::SHIFT)
{
modifiers = modifiers | mitk::InteractionEvent::ShiftKey;
}
return modifiers;
}
mitk::InteractionEvent::MouseButtons QmitkRenderWindow::GetButtonState(QWheelEvent *we) const
{
mitk::InteractionEvent::MouseButtons buttonState = mitk::InteractionEvent::NoButton;
if (we->buttons() & Qt::LeftButton)
{
buttonState = buttonState | mitk::InteractionEvent::LeftMouseButton;
}
if (we->buttons() & Qt::RightButton)
{
buttonState = buttonState | mitk::InteractionEvent::RightMouseButton;
}
- if (we->buttons() & Qt::MidButton)
+ if (we->buttons() & Qt::MiddleButton)
{
buttonState = buttonState | mitk::InteractionEvent::MiddleMouseButton;
}
return buttonState;
}
std::string QmitkRenderWindow::GetKeyLetter(QKeyEvent *ke) const
{
// Converting Qt Key Event to string element.
std::string key = "";
int tkey = ke->key();
if (tkey < 128)
{ // standard ascii letter
key = (char)toupper(tkey);
}
else
{ // special keys
switch (tkey)
{
case Qt::Key_Return:
key = mitk::InteractionEvent::KeyReturn;
break;
case Qt::Key_Enter:
key = mitk::InteractionEvent::KeyEnter;
break;
case Qt::Key_Escape:
key = mitk::InteractionEvent::KeyEsc;
break;
case Qt::Key_Delete:
key = mitk::InteractionEvent::KeyDelete;
break;
case Qt::Key_Up:
key = mitk::InteractionEvent::KeyArrowUp;
break;
case Qt::Key_Down:
key = mitk::InteractionEvent::KeyArrowDown;
break;
case Qt::Key_Left:
key = mitk::InteractionEvent::KeyArrowLeft;
break;
case Qt::Key_Right:
key = mitk::InteractionEvent::KeyArrowRight;
break;
case Qt::Key_F1:
key = mitk::InteractionEvent::KeyF1;
break;
case Qt::Key_F2:
key = mitk::InteractionEvent::KeyF2;
break;
case Qt::Key_F3:
key = mitk::InteractionEvent::KeyF3;
break;
case Qt::Key_F4:
key = mitk::InteractionEvent::KeyF4;
break;
case Qt::Key_F5:
key = mitk::InteractionEvent::KeyF5;
break;
case Qt::Key_F6:
key = mitk::InteractionEvent::KeyF6;
break;
case Qt::Key_F7:
key = mitk::InteractionEvent::KeyF7;
break;
case Qt::Key_F8:
key = mitk::InteractionEvent::KeyF8;
break;
case Qt::Key_F9:
key = mitk::InteractionEvent::KeyF9;
break;
case Qt::Key_F10:
key = mitk::InteractionEvent::KeyF10;
break;
case Qt::Key_F11:
key = mitk::InteractionEvent::KeyF11;
break;
case Qt::Key_F12:
key = mitk::InteractionEvent::KeyF12;
break;
case Qt::Key_End:
key = mitk::InteractionEvent::KeyEnd;
break;
case Qt::Key_Home:
key = mitk::InteractionEvent::KeyPos1;
break;
case Qt::Key_Insert:
key = mitk::InteractionEvent::KeyInsert;
break;
case Qt::Key_PageDown:
key = mitk::InteractionEvent::KeyPageDown;
break;
case Qt::Key_PageUp:
key = mitk::InteractionEvent::KeyPageUp;
break;
case Qt::Key_Space:
key = mitk::InteractionEvent::KeySpace;
break;
}
}
return key;
}
int QmitkRenderWindow::GetDelta(QWheelEvent *we) const
{
- return we->delta();
+ return we->angleDelta().y();
}
void QmitkRenderWindow::UpdateStatusBar(mitk::Point2D pointerPositionOnScreen)
{
mitk::Point3D worldPosition;
m_Renderer->ForceImmediateUpdate();
m_Renderer->DisplayToWorld(pointerPositionOnScreen, worldPosition);
auto statusBar = mitk::StatusBar::GetInstance();
statusBar->DisplayRendererInfo(worldPosition, m_Renderer->GetTime());
}
diff --git a/Modules/QtWidgets/src/QmitkRenderWindowDataNodeTableModel.cpp b/Modules/QtWidgets/src/QmitkRenderWindowDataNodeTableModel.cpp
index a4c6cb67ae..c389e3e529 100644
--- a/Modules/QtWidgets/src/QmitkRenderWindowDataNodeTableModel.cpp
+++ b/Modules/QtWidgets/src/QmitkRenderWindowDataNodeTableModel.cpp
@@ -1,370 +1,372 @@
/*============================================================================
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 "QmitkRenderWindowDataNodeTableModel.h"
// mitk core
#include <mitkRenderingManager.h>
// qt widgets module
#include <QmitkCustomVariants.h>
#include <QmitkEnums.h>
#include <QmitkMimeTypes.h>
#include <QmitkNodeDescriptorManager.h>
#include <QmitkStyleManager.h>
#include <QIcon>
+#include <QIODevice>
+
#include <itkCommand.h>
QmitkRenderWindowDataNodeTableModel::QmitkRenderWindowDataNodeTableModel(QObject* parent /*= nullptr*/)
: QAbstractItemModel(parent)
{
m_RenderWindowLayerController = std::make_unique<mitk::RenderWindowLayerController>();
m_VisibleIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/visible.svg"));
m_InvisibleIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/invisible.svg"));
m_ArrowIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/reset.svg"));
m_TimesIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/times.svg"));
}
void QmitkRenderWindowDataNodeTableModel::UpdateModelData()
{
auto baseRenderer = m_BaseRenderer.Lock();
auto greaterThan = [&baseRenderer](const mitk::DataNode* dataNodeLeft, const mitk::DataNode* dataNodeRight)
{
int layerLeft = -1;
int layerRight = -1;
bool layerLeftFound = dataNodeLeft->GetIntProperty("layer", layerLeft, baseRenderer);
bool layerRightFound = dataNodeRight->GetIntProperty("layer", layerRight, baseRenderer);
if (layerLeftFound && layerRightFound)
{
return layerLeft > layerRight;
}
return true;
};
// sort node selection
beginResetModel();
std::sort(m_CurrentSelection.begin(), m_CurrentSelection.end(), greaterThan);
endResetModel();
emit ModelUpdated();
}
void QmitkRenderWindowDataNodeTableModel::SetDataStorage(mitk::DataStorage* dataStorage)
{
m_RenderWindowLayerController->SetDataStorage(dataStorage);
}
void QmitkRenderWindowDataNodeTableModel::SetCurrentRenderer(mitk::BaseRenderer* baseRenderer)
{
if (m_BaseRenderer == baseRenderer)
{
// resetting the same base renderer does nothing
return;
}
m_BaseRenderer = baseRenderer;
// update the model, since a new base renderer could have set the relevant node-properties differently
this->UpdateModelData();
}
mitk::BaseRenderer::Pointer QmitkRenderWindowDataNodeTableModel::GetCurrentRenderer() const
{
return m_BaseRenderer.Lock();
}
void QmitkRenderWindowDataNodeTableModel::SetCurrentSelection(NodeList selectedNodes)
{
m_CurrentSelection = selectedNodes;
// update the model: sort the current internal selection
this->UpdateModelData();
}
QmitkRenderWindowDataNodeTableModel::NodeList QmitkRenderWindowDataNodeTableModel::GetCurrentSelection() const
{
return m_CurrentSelection;
}
QModelIndex QmitkRenderWindowDataNodeTableModel::index(int row, int column, const QModelIndex& parent /*= QModelIndex()*/) const
{
bool hasIndex = this->hasIndex(row, column, parent);
if (hasIndex)
{
return this->createIndex(row, column);
}
return QModelIndex();
}
QModelIndex QmitkRenderWindowDataNodeTableModel::parent(const QModelIndex& /*child*/) const
{
return QModelIndex();
}
int QmitkRenderWindowDataNodeTableModel::rowCount(const QModelIndex& parent /*= QModelIndex()*/) const
{
if (parent.isValid())
{
return 0;
}
return static_cast<int>(m_CurrentSelection.size());
}
int QmitkRenderWindowDataNodeTableModel::columnCount(const QModelIndex& parent /*= QModelIndex()*/) const
{
if (parent.isValid())
{
return 0;
}
return 4;
}
Qt::ItemFlags QmitkRenderWindowDataNodeTableModel::flags(const QModelIndex &index) const
{
if (this != index.model())
{
return Qt::NoItemFlags;
}
if (index.isValid())
{
if (index.column() == 0)
{
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable |
Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
}
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
}
else
{
return Qt::ItemIsDropEnabled;
}
}
QVariant QmitkRenderWindowDataNodeTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || this != index.model())
{
return QVariant();
}
if (index.row() < 0 || index.row() >= static_cast<int>(m_CurrentSelection.size()))
{
return QVariant();
}
mitk::DataNode* dataNode = m_CurrentSelection.at(index.row());
if (role == QmitkDataNodeRole)
{
return QVariant::fromValue<mitk::DataNode::Pointer>(mitk::DataNode::Pointer(dataNode));
}
if (role == QmitkDataNodeRawPointerRole)
{
return QVariant::fromValue<mitk::DataNode*>(dataNode);
}
if (index.column() == 0) // data node information column
{
QString nodeName = QString::fromStdString(dataNode->GetName());
if (nodeName.isEmpty())
{
nodeName = "unnamed";
}
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
return nodeName;
}
if (role == Qt::ToolTipRole)
{
return QVariant("Name of the data node.");
}
if (role == Qt::DecorationRole)
{
QmitkNodeDescriptor* nodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(dataNode);
return QVariant(nodeDescriptor->GetIcon(dataNode));
}
}
if (index.column() == 1) // node visibility column
{
if (role == Qt::DecorationRole)
{
auto baseRenderer = m_BaseRenderer.Lock();
bool visibility = false;
dataNode->GetVisibility(visibility, baseRenderer);
return visibility ? QVariant(m_VisibleIcon) : QVariant(m_InvisibleIcon);
}
if (role == Qt::EditRole)
{
auto baseRenderer = m_BaseRenderer.Lock();
bool visibility = false;
dataNode->GetVisibility(visibility, baseRenderer);
return QVariant(visibility);
}
}
if (index.column() == 2) // reset geometry column
{
if (role == Qt::DecorationRole)
{
return QVariant(m_ArrowIcon);
}
}
if (index.column() == 3) // remove node column
{
if (role == Qt::DecorationRole)
{
return QVariant(m_TimesIcon);
}
}
return QVariant();
}
bool QmitkRenderWindowDataNodeTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid() || this != index.model())
{
return false;
}
if (index.row() < 0 || index.row() >= static_cast<int>(m_CurrentSelection.size()))
{
return false;
}
mitk::DataNode* dataNode = m_CurrentSelection.at(index.row());
if (index.column() == 0) // data node information column
{
if (role == Qt::EditRole && !value.toString().isEmpty())
{
dataNode->SetName(value.toString().toStdString());
emit dataChanged(index, index);
return true;
}
}
if (index.column() == 1) // data node visibility column
{
if (role == Qt::EditRole)
{
auto baseRenderer = m_BaseRenderer.Lock();
bool visibility = value.toBool();
dataNode->SetVisibility(visibility, baseRenderer);
if (baseRenderer.IsNotNull())
{
// Explicitly request an update since a renderer-specific property change does not mark the node as modified.
// see https://phabricator.mitk.org/T22322
mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow());
}
emit dataChanged(index, index);
return true;
}
}
return false;
}
Qt::DropActions QmitkRenderWindowDataNodeTableModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
Qt::DropActions QmitkRenderWindowDataNodeTableModel::supportedDragActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
QStringList QmitkRenderWindowDataNodeTableModel::mimeTypes() const
{
QStringList types = QAbstractItemModel::mimeTypes();
types << QmitkMimeTypes::DataNodePtrs;
return types;
}
QMimeData* QmitkRenderWindowDataNodeTableModel::mimeData(const QModelIndexList& indexes) const
{
QMimeData* mimeData = new QMimeData();
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
for (const auto& index : indexes)
{
if (index.isValid())
{
auto dataNode = data(index, QmitkDataNodeRawPointerRole).value<mitk::DataNode*>();
stream << reinterpret_cast<quintptr>(dataNode);
}
}
mimeData->setData(QmitkMimeTypes::DataNodePtrs, encodedData);
return mimeData;
}
bool QmitkRenderWindowDataNodeTableModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int /*row*/, int /*column*/, const QModelIndex& parent)
{
if (action == Qt::IgnoreAction)
{
return true;
}
if (!data->hasFormat(QmitkMimeTypes::DataNodePtrs))
{
return false;
}
if (parent.isValid())
{
auto baseRenderer = m_BaseRenderer.Lock();
int layer = -1;
auto dataNode = this->data(parent, QmitkDataNodeRawPointerRole).value<mitk::DataNode*>();
if (nullptr != dataNode)
{
dataNode->GetIntProperty("layer", layer, baseRenderer);
}
auto dataNodeList = QmitkMimeTypes::ToDataNodePtrList(data);
- for (const auto& dataNode : qAsConst(dataNodeList))
+ for (const auto& dataNode : std::as_const(dataNodeList))
{
m_RenderWindowLayerController->MoveNodeToPosition(dataNode, layer, baseRenderer);
}
this->UpdateModelData();
return true;
}
return false;
}
diff --git a/Modules/QtWidgets/src/QmitkRenderWindowDataStorageTreeModel.cpp b/Modules/QtWidgets/src/QmitkRenderWindowDataStorageTreeModel.cpp
index cebc96e009..6e71ca65b5 100644
--- a/Modules/QtWidgets/src/QmitkRenderWindowDataStorageTreeModel.cpp
+++ b/Modules/QtWidgets/src/QmitkRenderWindowDataStorageTreeModel.cpp
@@ -1,606 +1,608 @@
/*============================================================================
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.
============================================================================*/
// render window manager UI module
#include "QmitkRenderWindowDataStorageTreeModel.h"
#include <QmitkDataStorageTreeModelInternalItem.h>
// qt widgets module
#include "QmitkCustomVariants.h"
#include "QmitkEnums.h"
#include "QmitkMimeTypes.h"
#include "QmitkNodeDescriptorManager.h"
+#include <QIODevice>
+
QmitkRenderWindowDataStorageTreeModel::QmitkRenderWindowDataStorageTreeModel(QObject* parent /*= nullptr*/)
: QmitkAbstractDataStorageModel(parent)
, m_Root(nullptr)
{
m_RenderWindowLayerController = std::make_unique<mitk::RenderWindowLayerController>();
ResetTree();
}
void QmitkRenderWindowDataStorageTreeModel::DataStorageChanged()
{
m_RenderWindowLayerController->SetDataStorage(m_DataStorage.Lock());
ResetTree();
UpdateModelData();
}
void QmitkRenderWindowDataStorageTreeModel::NodePredicateChanged()
{
ResetTree();
UpdateModelData();
}
void QmitkRenderWindowDataStorageTreeModel::NodeAdded(const mitk::DataNode* node)
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNull())
{
return;
}
if (m_NodePredicate.IsNotNull())
{
if (m_NodePredicate->CheckNode(node))
{
AddNodeInternal(node, baseRenderer);
}
}
}
void QmitkRenderWindowDataStorageTreeModel::NodeChanged(const mitk::DataNode* node)
{
auto item = m_Root->Find(node);
if (nullptr != item)
{
auto parentItem = item->GetParent();
// as the root node should not be removed one should always have a parent item
if (nullptr == parentItem)
{
return;
}
auto index = createIndex(item->GetIndex(), 0, item);
emit dataChanged(index, index);
}
}
void QmitkRenderWindowDataStorageTreeModel::NodeRemoved(const mitk::DataNode* node)
{
RemoveNodeInternal(node);
}
QModelIndex QmitkRenderWindowDataStorageTreeModel::index(int row, int column, const QModelIndex& parent) const
{
auto item = GetItemByIndex(parent);
if (nullptr != item)
{
item = item->GetChild(row);
}
if (nullptr == item)
{
return QModelIndex();
}
return createIndex(row, column, item);
}
QModelIndex QmitkRenderWindowDataStorageTreeModel::parent(const QModelIndex& parent) const
{
auto item = GetItemByIndex(parent);
if (nullptr != item)
{
item = item->GetParent();
}
if(nullptr == item)
{
return QModelIndex();
}
if (item == m_Root)
{
return QModelIndex();
}
return createIndex(item->GetIndex(), 0, item);
}
int QmitkRenderWindowDataStorageTreeModel::rowCount(const QModelIndex& parent /*= QModelIndex()*/) const
{
auto item = GetItemByIndex(parent);
if (nullptr == item)
{
return 0;
}
return item->GetChildCount();
}
int QmitkRenderWindowDataStorageTreeModel::columnCount(const QModelIndex&/* parent = QModelIndex()*/) const
{
if (0 == m_Root->GetChildCount())
{
// no items stored, no need to display columns
return 0;
}
return 1;
}
QVariant QmitkRenderWindowDataStorageTreeModel::data(const QModelIndex& index, int role) const
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNull())
{
return QVariant();
}
if (!index.isValid() || this != index.model())
{
return QVariant();
}
auto item = GetItemByIndex(index);
if (nullptr == item)
{
return QVariant();
}
auto dataNode = item->GetDataNode();
if (nullptr == dataNode)
{
return QVariant();
}
if (Qt::CheckStateRole == role)
{
bool visibility = false;
dataNode->GetVisibility(visibility, baseRenderer);
if (visibility)
{
return Qt::Checked;
}
else
{
return Qt::Unchecked;
}
}
else if (Qt::DisplayRole == role)
{
return QVariant(QString::fromStdString(dataNode->GetName()));
}
else if (Qt::ToolTipRole == role)
{
return QVariant("Name of the data node.");
}
else if (Qt::DecorationRole == role)
{
QmitkNodeDescriptor* nodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(dataNode);
return nodeDescriptor->GetIcon(dataNode);
}
else if (Qt::UserRole == role || QmitkDataNodeRawPointerRole == role)
{
// user role always returns a reference to the data node,
// which can be used to modify the data node in the data storage
return QVariant::fromValue<mitk::DataNode*>(dataNode);
}
else if (QmitkDataNodeRole == role)
{
return QVariant::fromValue<mitk::DataNode::Pointer>(mitk::DataNode::Pointer(dataNode));
}
return QVariant();
}
bool QmitkRenderWindowDataStorageTreeModel::setData(const QModelIndex& index, const QVariant& value, int role /*= Qt::EditRole*/)
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNull())
{
return false;
}
if (!index.isValid() || this != index.model())
{
return false;
}
auto item = GetItemByIndex(index);
if (nullptr == item)
{
return false;
}
auto dataNode = item->GetDataNode();
if (nullptr == dataNode)
{
return false;
}
if (Qt::EditRole == role && !value.toString().isEmpty())
{
dataNode->SetName(value.toString().toStdString().c_str());
emit dataChanged(index, index);
return true;
}
if (Qt::CheckStateRole == role)
{
Qt::CheckState newCheckState = static_cast<Qt::CheckState>(value.toInt());
bool isVisible = newCheckState;
dataNode->SetVisibility(isVisible, baseRenderer);
emit dataChanged(index, index);
mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow());
return true;
}
return false;
}
Qt::ItemFlags QmitkRenderWindowDataStorageTreeModel::flags(const QModelIndex& index) const
{
if (this != index.model())
{
return Qt::NoItemFlags;
}
if (!index.isValid())
{
return Qt::ItemIsDropEnabled;
}
auto item = GetItemByIndex(index);
if (nullptr == item)
{
return Qt::NoItemFlags;
}
const auto dataNode = item->GetDataNode();
if (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(dataNode))
{
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
}
return Qt::NoItemFlags;
}
Qt::DropActions QmitkRenderWindowDataStorageTreeModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
Qt::DropActions QmitkRenderWindowDataStorageTreeModel::supportedDragActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
QStringList QmitkRenderWindowDataStorageTreeModel::mimeTypes() const
{
QStringList types = QAbstractItemModel::mimeTypes();
types << QmitkMimeTypes::DataNodePtrs;
return types;
}
QMimeData* QmitkRenderWindowDataStorageTreeModel::mimeData(const QModelIndexList& indexes) const
{
QMimeData* mimeData = new QMimeData();
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
for (const auto& index : indexes)
{
if (index.isValid())
{
auto dataNode = data(index, QmitkDataNodeRawPointerRole).value<mitk::DataNode*>();
stream << reinterpret_cast<quintptr>(dataNode);
}
}
mimeData->setData(QmitkMimeTypes::DataNodePtrs, encodedData);
return mimeData;
}
bool QmitkRenderWindowDataStorageTreeModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int /*row*/, int /*column*/, const QModelIndex& parent)
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNull())
{
return false;
}
if (action == Qt::IgnoreAction)
{
return true;
}
if (!data->hasFormat(QmitkMimeTypes::DataNodePtrs))
{
return false;
}
if (!parent.isValid())
{
return false;
}
int layer = -1;
auto dataNode = this->data(parent, QmitkDataNodeRawPointerRole).value<mitk::DataNode*>();
if (nullptr != dataNode)
{
dataNode->GetIntProperty("layer", layer, baseRenderer);
}
auto dataNodeList = QmitkMimeTypes::ToDataNodePtrList(data);
- for (const auto& dataNode : qAsConst(dataNodeList))
+ for (const auto& dataNode : std::as_const(dataNodeList))
{
m_RenderWindowLayerController->MoveNodeToPosition(dataNode, layer, baseRenderer);
}
ResetTree();
UpdateModelData();
AdjustLayerProperty();
return true;
}
void QmitkRenderWindowDataStorageTreeModel::SetControlledRenderer(mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer)
{
ResetTree();
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNull())
{
return;
}
for (const auto& renderer : controlledRenderer)
{
if (nullptr == renderer)
{
continue;
}
auto allDataNodes = dataStorage->GetAll();
for (const auto& dataNode : *allDataNodes)
{
// add the node to each render window
mitk::RenderWindowLayerUtilities::SetRenderWindowProperties(dataNode, renderer);
}
}
}
void QmitkRenderWindowDataStorageTreeModel::SetCurrentRenderer(mitk::BaseRenderer* baseRenderer)
{
if (m_BaseRenderer == baseRenderer)
{
return;
}
// base renderer changed
// reset tree to build a new renderer-specific item hierarchy
m_BaseRenderer = baseRenderer;
ResetTree();
UpdateModelData();
}
mitk::BaseRenderer::Pointer QmitkRenderWindowDataStorageTreeModel::GetCurrentRenderer() const
{
return m_BaseRenderer.Lock();
}
void QmitkRenderWindowDataStorageTreeModel::ResetTree()
{
beginResetModel();
if (nullptr != m_Root)
{
m_Root->Delete();
}
mitk::DataNode::Pointer rootDataNode = mitk::DataNode::New();
rootDataNode->SetName("Data Storage");
m_Root = new QmitkDataStorageTreeModelInternalItem(rootDataNode);
endResetModel();
}
void QmitkRenderWindowDataStorageTreeModel::UpdateModelData()
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNotNull())
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNotNull())
{
auto allDataNodes = dataStorage->GetAll();
for (const auto& dataNode : *allDataNodes)
{
// add the node to each render window
mitk::RenderWindowLayerUtilities::SetRenderWindowProperties(dataNode, baseRenderer);
}
if (m_NodePredicate.IsNotNull())
{
auto filteredDataNodes = dataStorage->GetSubset(m_NodePredicate);
for (const auto& dataNode : *filteredDataNodes)
{
AddNodeInternal(dataNode, baseRenderer);
}
}
}
}
}
void QmitkRenderWindowDataStorageTreeModel::AdjustLayerProperty()
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNull())
{
return;
}
std::vector<QmitkDataStorageTreeModelInternalItem*> treeAsVector;
TreeToVector(m_Root, treeAsVector);
int i = treeAsVector.size() - 1;
for (auto it = treeAsVector.begin(); it != treeAsVector.end(); ++it)
{
auto dataNode = (*it)->GetDataNode();
dataNode->SetIntProperty("layer", i, baseRenderer);
--i;
}
}
void QmitkRenderWindowDataStorageTreeModel::TreeToVector(QmitkDataStorageTreeModelInternalItem* parent, std::vector<QmitkDataStorageTreeModelInternalItem*>& treeAsVector) const
{
QmitkDataStorageTreeModelInternalItem* item;
for (int i = 0; i < parent->GetChildCount(); ++i)
{
item = parent->GetChild(i);
TreeToVector(item, treeAsVector);
treeAsVector.push_back(item);
}
}
void QmitkRenderWindowDataStorageTreeModel::AddNodeInternal(const mitk::DataNode* dataNode, const mitk::BaseRenderer* renderer)
{
if (nullptr == dataNode
|| m_DataStorage.IsExpired()
|| nullptr != m_Root->Find(dataNode))
{
return;
}
// find out if we have a root node
auto parentItem = m_Root;
QModelIndex index;
auto parentDataNode = GetParentNode(dataNode);
if (nullptr != parentDataNode) // no top level data node
{
parentItem = m_Root->Find(parentDataNode);
if (nullptr == parentItem)
{
// parent node not contained in the tree; add it
NodeAdded(parentDataNode);
parentItem = m_Root->Find(parentDataNode);
if (nullptr == parentItem)
{
// could not find and add the parent tree; abort
return;
}
}
// get the index of this parent with the help of the grand parent
index = createIndex(parentItem->GetIndex(), 0, parentItem);
}
int firstRowWithASiblingBelow = 0;
int nodeLayer = -1;
dataNode->GetIntProperty("layer", nodeLayer, renderer);
for (const auto& siblingItem : parentItem->GetChildren())
{
int siblingLayer = -1;
auto siblingNode = siblingItem->GetDataNode();
if (nullptr != siblingNode)
{
siblingNode->GetIntProperty("layer", siblingLayer, renderer);
}
if (nodeLayer > siblingLayer)
{
break;
}
++firstRowWithASiblingBelow;
}
beginInsertRows(index, firstRowWithASiblingBelow, firstRowWithASiblingBelow);
auto newNode = new QmitkDataStorageTreeModelInternalItem(const_cast<mitk::DataNode*>(dataNode));
parentItem->InsertChild(newNode, firstRowWithASiblingBelow);
endInsertRows();
}
void QmitkRenderWindowDataStorageTreeModel::RemoveNodeInternal(const mitk::DataNode* dataNode)
{
if (nullptr == dataNode
|| nullptr == m_Root)
{
return;
}
auto item = m_Root->Find(dataNode);
if (nullptr == item)
{
return;
}
auto parentItem = item->GetParent();
auto parentIndex = GetIndexByItem(parentItem);
auto children = item->GetChildren();
beginRemoveRows(parentIndex, item->GetIndex(), item->GetIndex());
parentItem->RemoveChild(item);
delete item;
endRemoveRows();
if (!children.empty())
{
// rebuild tree because children could not be at the top level
ResetTree();
UpdateModelData();
}
}
mitk::DataNode* QmitkRenderWindowDataStorageTreeModel::GetParentNode(const mitk::DataNode* node) const
{
mitk::DataNode* dataNode = nullptr;
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNull())
{
return dataNode;
}
auto sources = dataStorage->GetSources(node);
if (sources->empty())
{
return dataNode;
}
return sources->front();
}
QmitkDataStorageTreeModelInternalItem* QmitkRenderWindowDataStorageTreeModel::GetItemByIndex(const QModelIndex& index) const
{
if (index.isValid())
{
return static_cast<QmitkDataStorageTreeModelInternalItem*>(index.internalPointer());
}
return m_Root;
}
QModelIndex QmitkRenderWindowDataStorageTreeModel::GetIndexByItem(QmitkDataStorageTreeModelInternalItem* item) const
{
if (item == m_Root)
{
return QModelIndex();
}
return createIndex(item->GetIndex(), 0, item);
}
diff --git a/Modules/QtWidgets/src/QmitkRenderWindowMenu.cpp b/Modules/QtWidgets/src/QmitkRenderWindowMenu.cpp
index 0ea68a3046..7582a388a3 100644
--- a/Modules/QtWidgets/src/QmitkRenderWindowMenu.cpp
+++ b/Modules/QtWidgets/src/QmitkRenderWindowMenu.cpp
@@ -1,578 +1,579 @@
/*============================================================================
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 "QmitkRenderWindowMenu.h"
// mitk core
#include "mitkProperties.h"
#include "mitkResliceMethodProperty.h"
// qt
+#include <QActionGroup>
#include <QHBoxLayout>
#include <QPainter>
#include <QSize>
#include <QSpacerItem>
#include <QSlider>
#include <QGroupBox>
#include <QLine>
#include <QRadioButton>
#include <QWidgetAction>
//#include"iconClose.xpm"
#include "iconCrosshairMode.xpm"
#include "iconFullScreen.xpm"
//#include"iconHoriSplit.xpm"
#include "iconSettings.xpm"
//#include"iconVertiSplit.xpm"
#include "iconLeaveFullScreen.xpm"
// c++
#include <cmath>
unsigned int QmitkRenderWindowMenu::m_DefaultThickMode(1);
QmitkRenderWindowMenu::QmitkRenderWindowMenu(QWidget* parent,
Qt::WindowFlags flags,
mitk::BaseRenderer* baseRenderer)
: QWidget(parent, flags)
, m_LayoutActionsMenu(nullptr)
, m_CrosshairMenu(nullptr)
, m_FullScreenMode(false)
, m_Renderer(baseRenderer)
, m_Parent(parent)
, m_CrosshairRotationMode(0)
, m_CrosshairVisibility(true)
, m_Layout(LayoutIndex::Axial)
, m_LayoutDesign(LayoutDesign::DEFAULT)
, m_OldLayoutDesign(LayoutDesign::DEFAULT)
{
CreateMenuWidget();
setMinimumWidth(61); // DIRTY.. If you add or remove a button, you need to change the size.
setMaximumWidth(61);
setAutoFillBackground(true);
this->hide();
m_AutoRotationTimer = new QTimer(this);
m_AutoRotationTimer->setInterval(75);
connect(m_AutoRotationTimer, &QTimer::timeout, this, &QmitkRenderWindowMenu::AutoRotateNextStep);
connect(m_Parent, &QObject::destroyed, this, &QmitkRenderWindowMenu::deleteLater);
}
QmitkRenderWindowMenu::~QmitkRenderWindowMenu()
{
if (m_AutoRotationTimer->isActive())
{
m_AutoRotationTimer->stop();
}
}
void QmitkRenderWindowMenu::SetLayoutIndex(LayoutIndex layoutIndex)
{
m_Layout = layoutIndex;
}
void QmitkRenderWindowMenu::UpdateLayoutDesignList(LayoutDesign layoutDesign)
{
m_LayoutDesign = layoutDesign;
if (nullptr == m_LayoutActionsMenu)
{
CreateSettingsWidget();
}
m_DefaultLayoutAction->setEnabled(true);
m_All2DTop3DBottomLayoutAction->setEnabled(true);
m_All2DLeft3DRightLayoutAction->setEnabled(true);
m_OneBigLayoutAction->setEnabled(true);
m_Only2DHorizontalLayoutAction->setEnabled(true);
m_Only2DVerticalLayoutAction->setEnabled(true);
m_OneTop3DBottomLayoutAction->setEnabled(true);
m_OneLeft3DRightLayoutAction->setEnabled(true);
m_AllHorizontalLayoutAction->setEnabled(true);
m_AllVerticalLayoutAction->setEnabled(true);
m_RemoveOneLayoutAction->setEnabled(true);
switch (m_LayoutDesign)
{
case LayoutDesign::DEFAULT:
{
m_DefaultLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ALL_2D_TOP_3D_BOTTOM:
{
m_All2DTop3DBottomLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ALL_2D_LEFT_3D_RIGHT:
{
m_All2DLeft3DRightLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ONE_BIG:
{
m_OneBigLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ONLY_2D_HORIZONTAL:
{
m_Only2DHorizontalLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ONLY_2D_VERTICAL:
{
m_Only2DVerticalLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ONE_TOP_3D_BOTTOM:
{
m_OneTop3DBottomLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ONE_LEFT_3D_RIGHT:
{
m_OneLeft3DRightLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ALL_HORIZONTAL:
{
m_AllHorizontalLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::ALL_VERTICAL:
{
m_AllVerticalLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::REMOVE_ONE:
{
m_RemoveOneLayoutAction->setEnabled(false);
break;
}
case LayoutDesign::NONE:
{
break;
}
}
}
void QmitkRenderWindowMenu::UpdateCrosshairVisibility(bool visible)
{
m_CrosshairVisibility = visible;
}
void QmitkRenderWindowMenu::UpdateCrosshairRotationMode(int mode)
{
m_CrosshairRotationMode = mode;
}
void QmitkRenderWindowMenu::MoveWidgetToCorrectPos()
{
int moveX = floor(static_cast<double>(this->m_Parent->width()) - static_cast<double>(this->width()) - 4.0);
this->move(moveX, 3);
auto cursorPos = this->mapFromGlobal(QCursor::pos());
if (cursorPos.x() < 0 || cursorPos.x() >= this->width() ||
cursorPos.y() < 0 || cursorPos.y() >= this->height())
{
this->HideMenu();
}
else
{
this->ShowMenu();
}
}
void QmitkRenderWindowMenu::ShowMenu()
{
MITK_DEBUG << "menu showMenu";
this->show();
this->raise();
}
void QmitkRenderWindowMenu::HideMenu()
{
MITK_DEBUG << "menu hideEvent";
this->hide();
}
void QmitkRenderWindowMenu::paintEvent(QPaintEvent * /*e*/)
{
QPainter painter(this);
QColor semiTransparentColor = Qt::black;
semiTransparentColor.setAlpha(255);
painter.fillRect(rect(), semiTransparentColor);
}
void QmitkRenderWindowMenu::CreateMenuWidget()
{
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setAlignment(Qt::AlignRight);
layout->setContentsMargins(1, 1, 1, 1);
QSize size(13, 13);
m_CrosshairMenu = new QMenu(this);
connect(m_CrosshairMenu, &QMenu::aboutToShow, this, &QmitkRenderWindowMenu::OnCrosshairMenuAboutToShow);
m_CrosshairModeButton = new QToolButton(this);
m_CrosshairModeButton->setMaximumSize(15, 15);
m_CrosshairModeButton->setIconSize(size);
m_CrosshairModeButton->setMenu(m_CrosshairMenu);
m_CrosshairModeButton->setIcon(QIcon(QPixmap(iconCrosshairMode_xpm)));
m_CrosshairModeButton->setPopupMode(QToolButton::InstantPopup);
m_CrosshairModeButton->setStyleSheet("QToolButton::menu-indicator { image: none; }");
m_CrosshairModeButton->setAutoRaise(true);
layout->addWidget(m_CrosshairModeButton);
m_FullScreenButton = new QToolButton(this);
m_FullScreenButton->setMaximumSize(15, 15);
m_FullScreenButton->setIconSize(size);
m_FullScreenButton->setIcon(QIcon(QPixmap(iconFullScreen_xpm)));
m_FullScreenButton->setAutoRaise(true);
layout->addWidget(m_FullScreenButton);
m_LayoutDesignButton = new QToolButton(this);
m_LayoutDesignButton->setMaximumSize(15, 15);
m_LayoutDesignButton->setIconSize(size);
m_LayoutDesignButton->setIcon(QIcon(QPixmap(iconSettings_xpm)));
m_LayoutDesignButton->setAutoRaise(true);
layout->addWidget(m_LayoutDesignButton);
connect(m_FullScreenButton, &QToolButton::clicked, this, &QmitkRenderWindowMenu::OnFullScreenButton);
connect(m_LayoutDesignButton, &QToolButton::clicked, this, &QmitkRenderWindowMenu::OnLayoutDesignButton);
}
void QmitkRenderWindowMenu::CreateSettingsWidget()
{
m_LayoutActionsMenu = new QMenu(this);
m_DefaultLayoutAction = new QAction("Standard layout", m_LayoutActionsMenu);
m_DefaultLayoutAction->setDisabled(true);
m_All2DTop3DBottomLayoutAction = new QAction("All 2D top, 3D bottom", m_LayoutActionsMenu);
m_All2DTop3DBottomLayoutAction->setDisabled(false);
m_All2DLeft3DRightLayoutAction = new QAction("All 2D left, 3D right", m_LayoutActionsMenu);
m_All2DLeft3DRightLayoutAction->setDisabled(false);
m_OneBigLayoutAction = new QAction("This big", m_LayoutActionsMenu);
m_OneBigLayoutAction->setDisabled(false);
m_Only2DHorizontalLayoutAction = new QAction("Only 2D horizontal", m_LayoutActionsMenu);
m_Only2DHorizontalLayoutAction->setDisabled(false);
m_Only2DVerticalLayoutAction = new QAction("Only 2D vertical", m_LayoutActionsMenu);
m_Only2DVerticalLayoutAction->setDisabled(false);
m_OneTop3DBottomLayoutAction = new QAction("This top, 3D bottom", m_LayoutActionsMenu);
m_OneTop3DBottomLayoutAction->setDisabled(false);
m_OneLeft3DRightLayoutAction = new QAction("This left, 3D right", m_LayoutActionsMenu);
m_OneLeft3DRightLayoutAction->setDisabled(false);
m_AllHorizontalLayoutAction = new QAction("All horizontal", m_LayoutActionsMenu);
m_AllHorizontalLayoutAction->setDisabled(false);
m_AllVerticalLayoutAction = new QAction("All vertical", m_LayoutActionsMenu);
m_AllVerticalLayoutAction->setDisabled(false);
m_RemoveOneLayoutAction = new QAction("Remove this", m_LayoutActionsMenu);
m_RemoveOneLayoutAction->setDisabled(false);
m_LayoutActionsMenu->addAction(m_DefaultLayoutAction);
m_LayoutActionsMenu->addAction(m_All2DTop3DBottomLayoutAction);
m_LayoutActionsMenu->addAction(m_All2DLeft3DRightLayoutAction);
m_LayoutActionsMenu->addAction(m_OneBigLayoutAction);
m_LayoutActionsMenu->addAction(m_Only2DHorizontalLayoutAction);
m_LayoutActionsMenu->addAction(m_Only2DVerticalLayoutAction);
m_LayoutActionsMenu->addAction(m_OneTop3DBottomLayoutAction);
m_LayoutActionsMenu->addAction(m_OneLeft3DRightLayoutAction);
m_LayoutActionsMenu->addAction(m_AllHorizontalLayoutAction);
m_LayoutActionsMenu->addAction(m_AllVerticalLayoutAction);
m_LayoutActionsMenu->addAction(m_RemoveOneLayoutAction);
m_LayoutActionsMenu->setVisible(false);
connect(m_DefaultLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::DEFAULT); });
connect(m_All2DTop3DBottomLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ALL_2D_TOP_3D_BOTTOM); });
connect(m_All2DLeft3DRightLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ALL_2D_LEFT_3D_RIGHT); });
connect(m_OneBigLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ONE_BIG); });
connect(m_Only2DHorizontalLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ONLY_2D_HORIZONTAL); });
connect(m_Only2DVerticalLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ONLY_2D_VERTICAL); });
connect(m_OneTop3DBottomLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ONE_TOP_3D_BOTTOM); });
connect(m_OneLeft3DRightLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ONE_LEFT_3D_RIGHT); });
connect(m_AllHorizontalLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ALL_HORIZONTAL); });
connect(m_AllVerticalLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::ALL_VERTICAL); });
connect(m_RemoveOneLayoutAction, &QAction::triggered, [this]() { this->OnSetLayout(LayoutDesign::REMOVE_ONE); });
}
void QmitkRenderWindowMenu::ChangeFullScreenIcon()
{
m_FullScreenButton->setIcon(m_FullScreenMode ? QPixmap(iconLeaveFullScreen_xpm) : QPixmap(iconFullScreen_xpm));
}
void QmitkRenderWindowMenu::AutoRotateNextStep()
{
if (m_Renderer->GetCameraRotationController())
{
m_Renderer->GetCameraRotationController()->GetStepper()->Next();
}
}
void QmitkRenderWindowMenu::OnAutoRotationActionTriggered()
{
if (m_AutoRotationTimer->isActive())
{
m_AutoRotationTimer->stop();
m_Renderer->GetCameraRotationController()->GetStepper()->PingPongOff();
}
else
{
m_Renderer->GetCameraRotationController()->GetStepper()->PingPongOn();
m_AutoRotationTimer->start();
}
}
void QmitkRenderWindowMenu::OnTSNumChanged(int num)
{
MITK_DEBUG << "Thickslices num: " << num << " on renderer " << m_Renderer.GetPointer();
if (m_Renderer.IsNotNull())
{
unsigned int thickSlicesMode = 0;
// determine the state of the thick-slice mode
mitk::ResliceMethodProperty *resliceMethodEnumProperty = nullptr;
if(m_Renderer->GetCurrentWorldPlaneGeometryNode()->GetProperty(resliceMethodEnumProperty, "reslice.thickslices") && resliceMethodEnumProperty)
{
thickSlicesMode = resliceMethodEnumProperty->GetValueAsId();
if(thickSlicesMode!=0)
m_DefaultThickMode = thickSlicesMode;
}
if(thickSlicesMode==0 && num>0) //default mode only for single slices
{
thickSlicesMode = m_DefaultThickMode; //mip default
m_Renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices.showarea",
mitk::BoolProperty::New(true));
}
if(num<1)
{
thickSlicesMode = 0;
m_Renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices.showarea",
mitk::BoolProperty::New(false));
}
m_Renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices",
mitk::ResliceMethodProperty::New(thickSlicesMode));
m_Renderer->GetCurrentWorldPlaneGeometryNode()->SetProperty("reslice.thickslices.num",
mitk::IntProperty::New(num));
m_TSLabel->setText(QString::number(num * 2 + 1));
m_Renderer->SendUpdateSlice();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkRenderWindowMenu::OnCrosshairMenuAboutToShow()
{
QMenu *crosshairModesMenu = m_CrosshairMenu;
crosshairModesMenu->clear();
QAction *resetViewAction = new QAction(crosshairModesMenu);
resetViewAction->setText("Reset view");
crosshairModesMenu->addAction(resetViewAction);
connect(resetViewAction, &QAction::triggered, this, &QmitkRenderWindowMenu::ResetView);
// Show hide crosshairs
{
QAction *showHideCrosshairVisibilityAction = new QAction(crosshairModesMenu);
showHideCrosshairVisibilityAction->setText("Show crosshair");
showHideCrosshairVisibilityAction->setCheckable(true);
showHideCrosshairVisibilityAction->setChecked(m_CrosshairVisibility);
crosshairModesMenu->addAction(showHideCrosshairVisibilityAction);
connect(showHideCrosshairVisibilityAction, &QAction::toggled, this, &QmitkRenderWindowMenu::OnCrosshairVisibilityChanged);
}
// Rotation mode
{
QAction *rotationGroupSeparator = new QAction(crosshairModesMenu);
rotationGroupSeparator->setSeparator(true);
rotationGroupSeparator->setText("Rotation mode");
crosshairModesMenu->addAction(rotationGroupSeparator);
QActionGroup *rotationModeActionGroup = new QActionGroup(crosshairModesMenu);
rotationModeActionGroup->setExclusive(true);
QAction *noCrosshairRotation = new QAction(crosshairModesMenu);
noCrosshairRotation->setActionGroup(rotationModeActionGroup);
noCrosshairRotation->setText("No crosshair rotation");
noCrosshairRotation->setCheckable(true);
noCrosshairRotation->setChecked(m_CrosshairRotationMode == 0);
noCrosshairRotation->setData(0);
crosshairModesMenu->addAction(noCrosshairRotation);
QAction *singleCrosshairRotation = new QAction(crosshairModesMenu);
singleCrosshairRotation->setActionGroup(rotationModeActionGroup);
singleCrosshairRotation->setText("Crosshair rotation");
singleCrosshairRotation->setCheckable(true);
singleCrosshairRotation->setChecked(m_CrosshairRotationMode == 1);
singleCrosshairRotation->setData(1);
crosshairModesMenu->addAction(singleCrosshairRotation);
QAction *coupledCrosshairRotation = new QAction(crosshairModesMenu);
coupledCrosshairRotation->setActionGroup(rotationModeActionGroup);
coupledCrosshairRotation->setText("Coupled crosshair rotation");
coupledCrosshairRotation->setCheckable(true);
coupledCrosshairRotation->setChecked(m_CrosshairRotationMode == 2);
coupledCrosshairRotation->setData(2);
crosshairModesMenu->addAction(coupledCrosshairRotation);
QAction *swivelMode = new QAction(crosshairModesMenu);
swivelMode->setActionGroup(rotationModeActionGroup);
swivelMode->setText("Swivel mode");
swivelMode->setCheckable(true);
swivelMode->setChecked(m_CrosshairRotationMode == 3);
swivelMode->setData(3);
crosshairModesMenu->addAction(swivelMode);
connect(rotationModeActionGroup, &QActionGroup::triggered, this, &QmitkRenderWindowMenu::OnCrosshairRotationModeSelected);
}
// auto rotation support
if (m_Renderer.IsNotNull() && m_Renderer->GetMapperID() == mitk::BaseRenderer::Standard3D)
{
QAction *autoRotationGroupSeparator = new QAction(crosshairModesMenu);
autoRotationGroupSeparator->setSeparator(true);
crosshairModesMenu->addAction(autoRotationGroupSeparator);
QAction *autoRotationAction = crosshairModesMenu->addAction("Auto Rotation");
autoRotationAction->setCheckable(true);
autoRotationAction->setChecked(m_AutoRotationTimer->isActive());
connect(autoRotationAction, &QAction::triggered, this, &QmitkRenderWindowMenu::OnAutoRotationActionTriggered);
}
// Thickslices support
if (m_Renderer.IsNotNull() && m_Renderer->GetMapperID() == mitk::BaseRenderer::Standard2D)
{
QAction *thickSlicesGroupSeparator = new QAction(crosshairModesMenu);
thickSlicesGroupSeparator->setSeparator(true);
thickSlicesGroupSeparator->setText("ThickSlices mode");
crosshairModesMenu->addAction(thickSlicesGroupSeparator);
QActionGroup *thickSlicesActionGroup = new QActionGroup(crosshairModesMenu);
thickSlicesActionGroup->setExclusive(true);
int currentMode = 0;
{
mitk::ResliceMethodProperty::Pointer m = dynamic_cast<mitk::ResliceMethodProperty *>(
m_Renderer->GetCurrentWorldPlaneGeometryNode()->GetProperty("reslice.thickslices"));
if (m.IsNotNull())
currentMode = m->GetValueAsId();
}
int currentNum = 1;
{
mitk::IntProperty::Pointer m = dynamic_cast<mitk::IntProperty *>(
m_Renderer->GetCurrentWorldPlaneGeometryNode()->GetProperty("reslice.thickslices.num"));
if (m.IsNotNull())
{
currentNum = m->GetValue();
}
}
if (currentMode == 0)
currentNum = 0;
QSlider *m_TSSlider = new QSlider(crosshairModesMenu);
m_TSSlider->setMinimum(0);
m_TSSlider->setMaximum(50);
m_TSSlider->setValue(currentNum);
m_TSSlider->setOrientation(Qt::Horizontal);
connect(m_TSSlider, &QSlider::valueChanged, this, &QmitkRenderWindowMenu::OnTSNumChanged);
QHBoxLayout *tsLayout = new QHBoxLayout;
tsLayout->setContentsMargins(4, 4, 4, 4);
tsLayout->addWidget(new QLabel("TS: "));
tsLayout->addWidget(m_TSSlider);
tsLayout->addWidget(m_TSLabel = new QLabel(QString::number(currentNum * 2 + 1), this));
QWidget *tsWidget = new QWidget;
tsWidget->setLayout(tsLayout);
QWidgetAction *m_TSSliderAction = new QWidgetAction(crosshairModesMenu);
m_TSSliderAction->setDefaultWidget(tsWidget);
crosshairModesMenu->addAction(m_TSSliderAction);
}
}
void QmitkRenderWindowMenu::OnCrosshairVisibilityChanged(bool visible)
{
UpdateCrosshairVisibility(visible);
emit CrosshairVisibilityChanged(m_CrosshairVisibility);
}
void QmitkRenderWindowMenu::OnCrosshairRotationModeSelected(QAction *action)
{
UpdateCrosshairRotationMode(action->data().toInt());
emit CrosshairRotationModeChanged(m_CrosshairRotationMode);
}
void QmitkRenderWindowMenu::OnFullScreenButton(bool /*checked*/)
{
if (!m_FullScreenMode)
{
m_FullScreenMode = true;
m_OldLayoutDesign = m_LayoutDesign;
emit LayoutDesignChanged(LayoutDesign::ONE_BIG);
}
else
{
m_FullScreenMode = false;
emit LayoutDesignChanged(m_OldLayoutDesign);
}
MoveWidgetToCorrectPos();
ChangeFullScreenIcon();
ShowMenu();
}
void QmitkRenderWindowMenu::OnLayoutDesignButton(bool /*checked*/)
{
if (nullptr == m_LayoutActionsMenu)
{
CreateSettingsWidget();
}
QPoint point = mapToGlobal(m_LayoutDesignButton->geometry().topLeft());
m_LayoutActionsMenu->setVisible(true);
m_LayoutActionsMenu->exec(point);
}
void QmitkRenderWindowMenu::OnSetLayout(LayoutDesign layoutDesign)
{
m_FullScreenMode = false;
ChangeFullScreenIcon();
m_LayoutDesign = layoutDesign;
emit LayoutDesignChanged(m_LayoutDesign);
ShowMenu();
}
diff --git a/Modules/QtWidgets/src/QmitkRenderWindowUtilityWidget.cpp b/Modules/QtWidgets/src/QmitkRenderWindowUtilityWidget.cpp
index 4a950fb941..4934c397d3 100644
--- a/Modules/QtWidgets/src/QmitkRenderWindowUtilityWidget.cpp
+++ b/Modules/QtWidgets/src/QmitkRenderWindowUtilityWidget.cpp
@@ -1,185 +1,185 @@
/*============================================================================
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 "QmitkRenderWindowUtilityWidget.h"
#include <QWidgetAction>
// mitk core
#include <mitkDataStorage.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateProperty.h>
// mitk qt widgets
#include <QmitkRenderWindow.h>
#include <QmitkStyleManager.h>
// itk
#include <itkSpatialOrientationAdapter.h>
QmitkRenderWindowUtilityWidget::QmitkRenderWindowUtilityWidget(
QWidget* parent/* = nullptr */,
QmitkRenderWindow* renderWindow/* = nullptr */,
mitk::DataStorage* dataStorage/* = nullptr */)
: m_NodeSelectionWidget(nullptr)
, m_SliceNavigationWidget(nullptr)
, m_StepperAdapter(nullptr)
, m_ViewDirectionSelector(nullptr)
{
this->setParent(parent);
auto layout = new QHBoxLayout(this);
- layout->setMargin(0);
+ layout->setContentsMargins({});
mitk::NodePredicateAnd::Pointer noHelperObjects = mitk::NodePredicateAnd::New();
noHelperObjects->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object")));
noHelperObjects->AddPredicate(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("hidden object")));
m_BaseRenderer = mitk::BaseRenderer::GetInstance(renderWindow->GetVtkRenderWindow());
m_NodeSelectionWidget = new QmitkSynchronizedNodeSelectionWidget(parent);
m_NodeSelectionWidget->SetBaseRenderer(m_BaseRenderer);
m_NodeSelectionWidget->SetDataStorage(dataStorage);
m_NodeSelectionWidget->SetNodePredicate(noHelperObjects);
auto menuBar = new QMenuBar(this);
menuBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
menuBar->setNativeMenuBar(false);
auto dataMenu = menuBar->addMenu("Data");
QWidgetAction* dataAction = new QWidgetAction(dataMenu);
dataAction->setDefaultWidget(m_NodeSelectionWidget);
dataMenu->addAction(dataAction);
layout->addWidget(menuBar);
auto* synchPushButton = new QPushButton(this);
auto* synchIcon = new QIcon();
auto synchronizeSvg = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/lock.svg"));
auto desynchronizeSvg = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/unlock.svg"));
synchIcon->addPixmap(synchronizeSvg.pixmap(64), QIcon::Normal, QIcon::On);
synchIcon->addPixmap(desynchronizeSvg.pixmap(64), QIcon::Normal, QIcon::Off);
synchPushButton->setIcon(*synchIcon);
synchPushButton->setToolTip("Synchronize / desynchronize data management");
synchPushButton->setCheckable(true);
synchPushButton->setChecked(true);
connect(synchPushButton, &QPushButton::clicked,
this, &QmitkRenderWindowUtilityWidget::ToggleSynchronization);
layout->addWidget(synchPushButton);
auto* sliceNavigationController = m_BaseRenderer->GetSliceNavigationController();
m_SliceNavigationWidget = new QmitkSliceNavigationWidget(this);
m_StepperAdapter =
new QmitkStepperAdapter(m_SliceNavigationWidget, sliceNavigationController->GetStepper());
layout->addWidget(m_SliceNavigationWidget);
mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer{ m_BaseRenderer };
m_RenderWindowViewDirectionController = std::make_unique<mitk::RenderWindowViewDirectionController>();
m_RenderWindowViewDirectionController->SetControlledRenderer(controlledRenderer);
m_RenderWindowViewDirectionController->SetDataStorage(dataStorage);
m_ViewDirectionSelector = new QComboBox(this);
QStringList viewDirections{ "axial", "coronal", "sagittal"};
m_ViewDirectionSelector->insertItems(0, viewDirections);
m_ViewDirectionSelector->setMinimumContentsLength(12);
connect(m_ViewDirectionSelector, &QComboBox::currentTextChanged, this, &QmitkRenderWindowUtilityWidget::ChangeViewDirection);
UpdateViewPlaneSelection();
layout->addWidget(m_ViewDirectionSelector);
// finally add observer, after all relevant objects have been created / initialized
sliceNavigationController->ConnectGeometrySendEvent(this);
}
QmitkRenderWindowUtilityWidget::~QmitkRenderWindowUtilityWidget()
{
}
void QmitkRenderWindowUtilityWidget::ToggleSynchronization(bool synchronized)
{
m_NodeSelectionWidget->SetSynchronized(synchronized);
emit SynchronizationToggled(m_NodeSelectionWidget);
}
void QmitkRenderWindowUtilityWidget::SetGeometry(const itk::EventObject& event)
{
if (!mitk::SliceNavigationController::GeometrySendEvent(nullptr, 0).CheckEvent(&event))
{
return;
}
const auto* sliceNavigationController = m_BaseRenderer->GetSliceNavigationController();
auto viewDirection = sliceNavigationController->GetViewDirection();
unsigned int axis = 0;
switch (viewDirection)
{
case mitk::AnatomicalPlane::Original:
return;
case mitk::AnatomicalPlane::Axial:
{
axis = 2;
break;
}
case mitk::AnatomicalPlane::Coronal:
{
axis = 1;
break;
}
case mitk::AnatomicalPlane::Sagittal:
{
axis = 0;
break;
}
}
const auto* inputTimeGeometry = sliceNavigationController->GetInputWorldTimeGeometry();
const mitk::BaseGeometry* rendererGeometry = m_BaseRenderer->GetCurrentWorldGeometry();
mitk::TimeStepType timeStep = sliceNavigationController->GetStepper()->GetPos();
mitk::BaseGeometry::ConstPointer geometry = inputTimeGeometry->GetGeometryForTimeStep(timeStep);
if (geometry == nullptr)
return;
mitk::AffineTransform3D::MatrixType matrix = geometry->GetIndexToWorldTransform()->GetMatrix();
matrix.GetVnlMatrix().normalize_columns();
mitk::AffineTransform3D::MatrixType::InternalMatrixType inverseMatrix = matrix.GetInverse();
int dominantAxis = itk::Function::Max3(inverseMatrix[0][axis], inverseMatrix[1][axis], inverseMatrix[2][axis]);
bool referenceGeometryAxisInverted = inverseMatrix[dominantAxis][axis] < 0;
bool rendererZAxisInverted = rendererGeometry->GetAxisVector(2)[axis] < 0;
m_SliceNavigationWidget->SetInverseDirection(referenceGeometryAxisInverted != rendererZAxisInverted);
}
void QmitkRenderWindowUtilityWidget::ChangeViewDirection(const QString& viewDirection)
{
m_RenderWindowViewDirectionController->SetViewDirectionOfRenderer(viewDirection.toStdString());
}
void QmitkRenderWindowUtilityWidget::UpdateViewPlaneSelection()
{
const auto sliceNavigationController = m_BaseRenderer->GetSliceNavigationController();
const auto viewDirection = sliceNavigationController->GetDefaultViewDirection();
switch (viewDirection)
{
case mitk::AnatomicalPlane::Axial:
m_ViewDirectionSelector->setCurrentIndex(0);
break;
case mitk::AnatomicalPlane::Coronal:
m_ViewDirectionSelector->setCurrentIndex(1);
break;
case mitk::AnatomicalPlane::Sagittal:
m_ViewDirectionSelector->setCurrentIndex(2);
break;
default:
break;
}
}
diff --git a/Modules/QtWidgets/src/QmitkRenderWindowWidget.cpp b/Modules/QtWidgets/src/QmitkRenderWindowWidget.cpp
index 29325720d7..8c7d54c727 100644
--- a/Modules/QtWidgets/src/QmitkRenderWindowWidget.cpp
+++ b/Modules/QtWidgets/src/QmitkRenderWindowWidget.cpp
@@ -1,322 +1,322 @@
/*============================================================================
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 "QmitkRenderWindowWidget.h"
// vtk
#include <vtkCornerAnnotation.h>
#include <vtkTextProperty.h>
QmitkRenderWindowWidget::QmitkRenderWindowWidget(QWidget* parent/* = nullptr*/,
const QString& widgetName/* = ""*/,
mitk::DataStorage* dataStorage/* = nullptr*/)
: QFrame(parent)
, m_WidgetName(widgetName)
, m_DataStorage(dataStorage)
, m_RenderWindow(nullptr)
, m_CrosshairManager(nullptr)
{
this->InitializeGUI();
}
QmitkRenderWindowWidget::~QmitkRenderWindowWidget()
{
auto sliceNavigationController = this->GetSliceNavigationController();
if (nullptr != sliceNavigationController)
{
sliceNavigationController->SetCrosshairEvent.RemoveListener(
mitk::MessageDelegate1<QmitkRenderWindowWidget, const mitk::Point3D &>(
this, &QmitkRenderWindowWidget::SetCrosshairPosition));
}
this->DisableCrosshair();
}
void QmitkRenderWindowWidget::SetDataStorage(mitk::DataStorage* dataStorage)
{
if (dataStorage == m_DataStorage)
{
return;
}
m_DataStorage = dataStorage;
if (nullptr != m_RenderWindow)
{
mitk::BaseRenderer::GetInstance(m_RenderWindow->renderWindow())->SetDataStorage(dataStorage);
}
}
mitk::SliceNavigationController* QmitkRenderWindowWidget::GetSliceNavigationController() const
{
return m_RenderWindow->GetSliceNavigationController();
}
void QmitkRenderWindowWidget::RequestUpdate()
{
mitk::RenderingManager::GetInstance()->RequestUpdate(m_RenderWindow->renderWindow());
}
void QmitkRenderWindowWidget::ForceImmediateUpdate()
{
mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(m_RenderWindow->renderWindow());
}
void QmitkRenderWindowWidget::AddUtilityWidget(QWidget* utilityWidget)
{
m_Layout->insertWidget(0, utilityWidget);
}
void QmitkRenderWindowWidget::SetGradientBackgroundColors(const mitk::Color& upper, const mitk::Color& lower)
{
vtkRenderer* vtkRenderer = m_RenderWindow->GetRenderer()->GetVtkRenderer();
if (nullptr == vtkRenderer)
{
return;
}
m_GradientBackgroundColors.first = upper;
m_GradientBackgroundColors.second = lower;
vtkRenderer->SetBackground(lower[0], lower[1], lower[2]);
vtkRenderer->SetBackground2(upper[0], upper[1], upper[2]);
ShowGradientBackground(true);
}
void QmitkRenderWindowWidget::ShowGradientBackground(bool show)
{
m_RenderWindow->GetRenderer()->GetVtkRenderer()->SetGradientBackground(show);
}
bool QmitkRenderWindowWidget::IsGradientBackgroundOn() const
{
return m_RenderWindow->GetRenderer()->GetVtkRenderer()->GetGradientBackground();
}
void QmitkRenderWindowWidget::SetDecorationColor(const mitk::Color& color)
{
m_DecorationColor = color;
m_CornerAnnotation->GetTextProperty()->SetColor(m_DecorationColor[0], m_DecorationColor[1], m_DecorationColor[2]);
QColor hexColor(m_DecorationColor[0] * 255, m_DecorationColor[1] * 255, m_DecorationColor[2] * 255);
setStyleSheet("QmitkRenderWindowWidget { border: 2px solid " + hexColor.name(QColor::HexRgb) + "; }");
}
void QmitkRenderWindowWidget::ShowColoredRectangle(bool show)
{
if (show)
{
setFrameStyle(QFrame::Box | QFrame::Plain);
}
else
{
setFrameStyle(NoFrame);
}
}
bool QmitkRenderWindowWidget::IsColoredRectangleVisible() const
{
return frameStyle() > 0;
}
void QmitkRenderWindowWidget::ShowCornerAnnotation(bool show)
{
m_CornerAnnotation->SetVisibility(show);
}
bool QmitkRenderWindowWidget::IsCornerAnnotationVisible() const
{
return m_CornerAnnotation->GetVisibility() > 0;
}
void QmitkRenderWindowWidget::SetCornerAnnotationText(const std::string& cornerAnnotation)
{
m_CornerAnnotation->SetText(0, cornerAnnotation.c_str());
}
std::string QmitkRenderWindowWidget::GetCornerAnnotationText() const
{
return std::string(m_CornerAnnotation->GetText(0));
}
bool QmitkRenderWindowWidget::IsRenderWindowMenuActivated() const
{
return m_RenderWindow->GetActivateMenuWidgetFlag();
}
void QmitkRenderWindowWidget::SetCrosshairVisibility(bool visible)
{
m_CrosshairManager->SetCrosshairVisibility(visible, m_RenderWindow->GetRenderer());
this->RequestUpdate();
}
bool QmitkRenderWindowWidget::GetCrosshairVisibility()
{
return m_CrosshairManager->GetCrosshairVisibility(m_RenderWindow->GetRenderer());
}
void QmitkRenderWindowWidget::SetCrosshairGap(unsigned int gapSize)
{
m_CrosshairManager->SetCrosshairGap(gapSize);
}
void QmitkRenderWindowWidget::EnableCrosshair()
{
m_CrosshairManager->AddCrosshairNodeToDataStorage(m_DataStorage);
}
void QmitkRenderWindowWidget::DisableCrosshair()
{
m_CrosshairManager->RemoveCrosshairNodeFromDataStorage(m_DataStorage);
}
void QmitkRenderWindowWidget::InitializeGUI()
{
m_Layout = new QVBoxLayout(this);
- m_Layout->setMargin(0);
+ m_Layout->setContentsMargins({});
setLayout(m_Layout);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setContentsMargins(0, 0, 0, 0);
if (nullptr == m_DataStorage)
{
return;
}
mitk::RenderingManager::GetInstance()->SetDataStorage(m_DataStorage);
// create render window for this render window widget
m_RenderWindow = new QmitkRenderWindow(this, m_WidgetName, nullptr);
m_RenderWindow->SetLayoutIndex(mitk::AnatomicalPlane::Sagittal);
connect(m_RenderWindow, &QmitkRenderWindow::ResetGeometry,
this, &QmitkRenderWindowWidget::OnResetGeometry);
auto* sliceNavigationController = this->GetSliceNavigationController();
sliceNavigationController->SetDefaultViewDirection(mitk::AnatomicalPlane::Sagittal);
m_Layout->addWidget(m_RenderWindow);
// set colors and corner annotation
InitializeDecorations();
// use crosshair manager
m_CrosshairManager = mitk::CrosshairManager::New(m_RenderWindow->GetRenderer());
sliceNavigationController->SetCrosshairEvent.AddListener(
mitk::MessageDelegate1<QmitkRenderWindowWidget, const mitk::Point3D &>(
this, &QmitkRenderWindowWidget::SetCrosshairPosition));
// finally add observer, after all relevant objects have been created / initialized
sliceNavigationController->ConnectGeometrySendEvent(this);
sliceNavigationController->ConnectGeometrySliceEvent(this);
mitk::TimeGeometry::ConstPointer timeGeometry = m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll());
mitk::RenderingManager::GetInstance()->InitializeView(m_RenderWindow->GetVtkRenderWindow(), timeGeometry);
}
void QmitkRenderWindowWidget::InitializeDecorations()
{
vtkRenderer* vtkRenderer = m_RenderWindow->GetRenderer()->GetVtkRenderer();
if (nullptr == vtkRenderer)
{
return;
}
// initialize background color gradients
float black[3] = { 0.0f, 0.0f, 0.0f };
SetGradientBackgroundColors(black, black);
// initialize annotation text and decoration color
setFrameStyle(QFrame::Box | QFrame::Plain);
m_CornerAnnotation = vtkSmartPointer<vtkCornerAnnotation>::New();
m_CornerAnnotation->SetText(0, "Sagittal");
m_CornerAnnotation->SetMaximumFontSize(12);
if (0 == vtkRenderer->HasViewProp(m_CornerAnnotation))
{
vtkRenderer->AddViewProp(m_CornerAnnotation);
}
float white[3] = { 1.0f, 1.0f, 1.0f };
SetDecorationColor(mitk::Color(white));
}
void QmitkRenderWindowWidget::SetCrosshairPosition(const mitk::Point3D& newPosition)
{
m_CrosshairManager->SetCrosshairPosition(newPosition);
this->RequestUpdate();
}
mitk::Point3D QmitkRenderWindowWidget::GetCrosshairPosition() const
{
return m_CrosshairManager->GetCrosshairPosition();
}
void QmitkRenderWindowWidget::SetGeometry(const itk::EventObject& event)
{
if (!mitk::SliceNavigationController::GeometrySendEvent(nullptr, 0).CheckEvent(&event))
{
return;
}
const auto* planeGeometry = this->GetSliceNavigationController()->GetCurrentPlaneGeometry();
if (nullptr == planeGeometry)
{
mitkThrow() << "No valid plane geometry set. Render window is in an invalid state.";
}
return SetCrosshairPosition(planeGeometry->GetCenter());
}
void QmitkRenderWindowWidget::SetGeometrySlice(const itk::EventObject& event)
{
if (!mitk::SliceNavigationController::GeometrySliceEvent(nullptr, 0).CheckEvent(&event))
{
return;
}
const auto* sliceNavigationController = this->GetSliceNavigationController();
m_CrosshairManager->UpdateCrosshairPosition(sliceNavigationController);
}
void QmitkRenderWindowWidget::OnResetGeometry()
{
const auto* baseRenderer = mitk::BaseRenderer::GetInstance(m_RenderWindow->GetVtkRenderWindow());
const auto* interactionReferenceGeometry = baseRenderer->GetInteractionReferenceGeometry();
this->ResetGeometry(interactionReferenceGeometry);
m_RenderWindow->ShowOverlayMessage(false);
}
void QmitkRenderWindowWidget::ResetGeometry(const mitk::TimeGeometry* referenceGeometry)
{
if (nullptr == referenceGeometry)
{
return;
}
mitk::TimeStepType imageTimeStep = 0;
// store the current position to set it again later, if the camera should not be reset
mitk::Point3D currentPosition = this->GetCrosshairPosition();
// store the current time step to set it again later, if the camera should not be reset
auto* renderingManager = mitk::RenderingManager::GetInstance();
const mitk::TimePointType currentTimePoint = renderingManager->GetTimeNavigationController()->GetSelectedTimePoint();
if (referenceGeometry->IsValidTimePoint(currentTimePoint))
{
imageTimeStep = referenceGeometry->TimePointToTimeStep(currentTimePoint);
}
const auto* baseRenderer = mitk::BaseRenderer::GetInstance(m_RenderWindow->renderWindow());
renderingManager->InitializeView(baseRenderer->GetRenderWindow(), referenceGeometry, false);
// reset position and time step
this->GetSliceNavigationController()->SelectSliceByPoint(currentPosition);
renderingManager->GetTimeNavigationController()->GetStepper()->SetPos(imageTimeStep);
}
diff --git a/Modules/QtWidgets/src/QmitkSliderLevelWindowWidget.cpp b/Modules/QtWidgets/src/QmitkSliderLevelWindowWidget.cpp
index ef8fb9e4d0..2f4bbf0926 100644
--- a/Modules/QtWidgets/src/QmitkSliderLevelWindowWidget.cpp
+++ b/Modules/QtWidgets/src/QmitkSliderLevelWindowWidget.cpp
@@ -1,550 +1,550 @@
/*============================================================================
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 <QmitkSliderLevelWindowWidget.h>
// mitk core
#include <mitkRenderingManager.h>
// mitk qt widgets
#include <QmitkLevelWindowWidgetContextMenu.h>
// qt
#include <QCursor>
#include <QMouseEvent>
#include <QPainter>
#include <QToolTip>
// itk
#include <itkCommand.h>
// c++
#include <cmath>
QmitkSliderLevelWindowWidget::QmitkSliderLevelWindowWidget(QWidget *parent, Qt::WindowFlags f)
: QWidget(parent, f)
{
m_Manager = mitk::LevelWindowManager::New();
itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::Pointer command =
itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::New();
command->SetCallbackFunction(this, &QmitkSliderLevelWindowWidget::OnPropertyModified);
m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command);
m_IsObserverTagSet = true;
setMouseTracking(true);
m_Resize = false;
m_Bottom = false;
m_CtrlPressed = false;
m_MouseDown = false;
m_Font.setPointSize(6);
m_MoveHeight = height() - 25;
m_ScaleVisible = true;
m_Contextmenu = new QmitkLevelWindowWidgetContextMenu(this);
this->hide();
Update();
}
QmitkSliderLevelWindowWidget::~QmitkSliderLevelWindowWidget()
{
if (m_IsObserverTagSet)
{
m_Manager->RemoveObserver(m_ObserverTag);
m_IsObserverTagSet = false;
}
}
void QmitkSliderLevelWindowWidget::SetLevelWindowManager(mitk::LevelWindowManager *levelWindowManager)
{
if (m_IsObserverTagSet)
{
m_Manager->RemoveObserver(m_ObserverTag);
m_IsObserverTagSet = false;
}
m_Manager = levelWindowManager;
if (m_Manager.IsNotNull())
{
itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::Pointer command =
itk::ReceptorMemberCommand<QmitkSliderLevelWindowWidget>::New();
command->SetCallbackFunction(this, &QmitkSliderLevelWindowWidget::OnPropertyModified);
m_ObserverTag = m_Manager->AddObserver(itk::ModifiedEvent(), command);
m_IsObserverTagSet = true;
}
}
void QmitkSliderLevelWindowWidget::OnPropertyModified(const itk::EventObject &)
{
try
{
m_LevelWindow = m_Manager->GetLevelWindow();
this->show();
Update();
}
catch (...)
{
try
{
this->hide();
}
catch (...)
{
}
}
}
void QmitkSliderLevelWindowWidget::paintEvent(QPaintEvent *itkNotUsed(e))
{
QPixmap pm(width(), height());
pm.fill(this->palette().color(this->backgroundRole()));
QPainter painter(&pm);
painter.setFont(m_Font);
painter.setPen(this->palette().color(this->foregroundRole()));
QColor c(51, 153, 204);
- QColor cl = c.light();
- QColor cd = c.dark();
+ QColor cl = c.lighter();
+ QColor cd = c.darker();
painter.setBrush(c);
painter.drawRect(m_Rect);
mitk::ScalarType mr = m_LevelWindow.GetRange();
float smallestLevelableValue = 1e-9;
//This check is needed as safe guard. LevelWindow is refactored to only deduce finite ranges
//from images, but old scene serialization may contain infinite ranges that overwrite the new
//business logic. This roots in two many "jobs" LevelWindow" is used for; see also T24962.
//Until LevelWindow and this widget is refactored the check was the minimal invasive fix.
if (!std::isfinite(mr))
{
mr = m_LevelWindow.GetWindow();
}
// avoiding a division by 0 while still enabling small level windows
if (mr < smallestLevelableValue)
mr = smallestLevelableValue;
mitk::ScalarType fact = m_MoveHeight / mr;
// begin draw scale
if (m_ScaleVisible)
{
mitk::ScalarType minRange = m_LevelWindow.GetRangeMin();
mitk::ScalarType maxRange = m_LevelWindow.GetRangeMax();
//This check is needed as safe guard. LevelWindow is refactored to only deduce finite ranges
//from images, but old scene serialization may contain infinite ranges that overwrite the new
//business logic. This roots in two many "jobs" LevelWindow" is used for; see also T24962.
//Until LevelWindow and this widget is refactored the check was the minimal invasive fix.
if (!std::isfinite(minRange))
{
minRange = m_LevelWindow.GetLowerWindowBound();
}
//This check is needed as safe guard. LevelWindow is refactored to only deduce finite ranges
//from images, but old scene serialization may contain infinite ranges that overwrite the new
//business logic. This roots in two many "jobs" LevelWindow" is used for; see also T24962.
//Until LevelWindow and this widget is refactored the check was the minimal invasive fix.
if (!std::isfinite(maxRange))
{
maxRange = m_LevelWindow.GetUpperWindowBound();
}
int yValue = m_MoveHeight + static_cast<int>(minRange * fact);
QString s = " 0";
if (minRange < 0 && maxRange > 0)
{
painter.drawLine(5, yValue, 15, yValue);
painter.drawText(21, yValue + 3, s);
}
int count = 1;
int k = 5;
bool enoughSpace = false;
bool enoughSpace2 = false;
double dStepSize = pow(10, floor(log10(mr / 100)) + 1);
for (int i = m_MoveHeight + static_cast<int>(minRange * fact); i < m_MoveHeight;) // negative
{
if (-count * dStepSize < minRange)
{
break;
}
yValue = m_MoveHeight + static_cast<int>((minRange + count * dStepSize) * fact);
s = QString::number(-count * dStepSize);
if (count % k && ((dStepSize * fact) > 2.5))
{
painter.drawLine(8, yValue, 12, yValue);
enoughSpace = true;
}
else if (!(count % k))
{
if ((k * dStepSize * fact) > 7)
{
painter.drawLine(5, yValue, 15, yValue);
painter.drawText(21, yValue + 3, s);
enoughSpace2 = true;
}
else
{
k += 5;
}
}
if (enoughSpace)
{
i = yValue;
count++;
}
else if (enoughSpace2)
{
i = yValue;
count += k;
}
else
{
i = yValue;
count = k;
}
}
count = 1;
k = 5;
enoughSpace = false;
enoughSpace2 = false;
for (int i = m_MoveHeight + static_cast<int>(minRange * fact); i >= 0;)
{
if (count * dStepSize > maxRange)
{
break;
}
yValue = m_MoveHeight + static_cast<int>((minRange - count * dStepSize) * fact);
s = QString::number(count * dStepSize);
if (count % k && ((dStepSize * fact) > 2.5))
{
if (!(minRange > 0 && (count * dStepSize) < minRange))
painter.drawLine(8, yValue, 12, yValue);
enoughSpace = true;
}
else if (!(count % k))
{
if ((k * dStepSize * fact) > 7)
{
if (!(minRange > 0 && (count * dStepSize) < minRange))
{
painter.drawLine(5, yValue, 15, yValue);
painter.drawText(21, yValue + 3, s);
}
enoughSpace2 = true;
}
else
{
k += 5;
}
}
if (enoughSpace)
{
i = yValue;
count++;
}
else if (enoughSpace2)
{
i = yValue;
count += k;
}
else
{
i = yValue;
count = k;
}
}
}
// end draw scale
painter.setPen(cl);
painter.drawLine(m_Rect.topLeft(), m_Rect.topRight());
painter.drawLine(m_Rect.topLeft(), m_Rect.bottomLeft());
painter.setPen(cd);
painter.drawLine(m_Rect.topRight(), m_Rect.bottomRight());
painter.drawLine(m_Rect.bottomRight(), m_Rect.bottomLeft());
painter.end();
QPainter p(this);
p.drawPixmap(0, 0, pm);
}
void QmitkSliderLevelWindowWidget::mouseMoveEvent(QMouseEvent *mouseEvent)
{
if (!mouseEvent)
return;
if (m_LevelWindow.IsFixed())
return;
if (!m_MouseDown)
{
if (mouseEvent->pos().y() >= 0 && mouseEvent->pos().y() <= (m_Rect.topLeft().y() + 3))
{
setCursor(Qt::SizeVerCursor);
m_UpperBound.setRect(m_Rect.topLeft().x(), m_Rect.topLeft().y() - 3, 17, 7);
this->setToolTip("Ctrl + left click to change only upper bound");
m_Resize = true;
}
else if (mouseEvent->pos().y() >= (m_Rect.bottomLeft().y() - 3))
{
setCursor(Qt::SizeVerCursor);
m_LowerBound.setRect(m_Rect.bottomLeft().x(), m_Rect.bottomLeft().y() - 3, 17, 7);
this->setToolTip("Ctrl + left click to change only lower bound");
m_Resize = true;
m_Bottom = true;
}
else
{
setCursor(Qt::ArrowCursor);
this->setToolTip("Left click and mouse move to adjust the slider");
m_Resize = false;
m_Bottom = false;
}
}
else
{
mitk::ScalarType fact = m_MoveHeight / m_LevelWindow.GetRange();
if (m_Leftbutton)
{
if (m_Resize && !m_CtrlPressed)
{
mitk::ScalarType diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0)
return;
mitk::ScalarType value;
if (m_Bottom)
value = m_LevelWindow.GetWindow() + ((2 * diff));
else
value = m_LevelWindow.GetWindow() - ((2 * diff));
if (value < 0)
value = 0;
m_LevelWindow.SetLevelWindow(m_LevelWindow.GetLevel(), value);
}
else if (m_Resize && m_CtrlPressed)
{
if (!m_Bottom)
{
mitk::ScalarType diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0)
return;
mitk::ScalarType value;
value = m_LevelWindow.GetWindow() - ((diff));
if (value < 0)
value = 0;
mitk::ScalarType oldWindow;
mitk::ScalarType oldLevel;
mitk::ScalarType newLevel;
oldWindow = m_LevelWindow.GetWindow();
oldLevel = m_LevelWindow.GetLevel();
newLevel = oldLevel + (value - oldWindow) / 2;
if (!((newLevel + value / 2) > m_LevelWindow.GetRangeMax()))
m_LevelWindow.SetLevelWindow(newLevel, value);
}
else
{
mitk::ScalarType diff = (mouseEvent->pos().y()) / fact;
diff -= (m_StartPos.y()) / fact;
m_StartPos = mouseEvent->pos();
if (diff == 0)
return;
mitk::ScalarType value;
value = m_LevelWindow.GetWindow() + ((diff));
if (value < 0)
value = 0;
mitk::ScalarType oldWindow;
mitk::ScalarType oldLevel;
mitk::ScalarType newLevel;
oldWindow = m_LevelWindow.GetWindow();
oldLevel = m_LevelWindow.GetLevel();
newLevel = oldLevel - (value - oldWindow) / 2;
if (!((newLevel - value / 2) < m_LevelWindow.GetRangeMin()))
m_LevelWindow.SetLevelWindow(newLevel, value);
}
}
else
{
const mitk::ScalarType minv = m_LevelWindow.GetRangeMin();
const mitk::ScalarType level = (m_MoveHeight - mouseEvent->pos().y()) / fact + minv;
mitk::ScalarType diff = (mouseEvent->pos().x()) / fact;
diff -= (m_StartPos.x()) / fact;
m_StartPos = mouseEvent->pos();
mitk::ScalarType window;
if (m_Bottom)
window = m_LevelWindow.GetWindow() + ((2 * diff));
else
window = m_LevelWindow.GetWindow() - ((2 * diff));
if (window < 0)
window = 0;
m_LevelWindow.SetLevelWindow(level, window);
}
m_Manager->SetLevelWindow(m_LevelWindow);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
}
-void QmitkSliderLevelWindowWidget::enterEvent(QEvent * /*event*/)
+void QmitkSliderLevelWindowWidget::enterEvent(QEnterEvent * /*event*/)
{
- QPoint p = QCursor::pos();
- p = this->mapFromGlobal(p);
- QMouseEvent ev(QEvent::MouseMove, p, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
+ const auto pos = QCursor::pos();
+ const auto localPos = this->mapFromGlobal(pos);
+ QMouseEvent ev(QEvent::MouseMove, localPos, pos, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
this->mouseMoveEvent(&ev);
}
void QmitkSliderLevelWindowWidget::mousePressEvent(QMouseEvent *mouseEvent)
{
if (m_LevelWindow.IsFixed())
return;
m_MouseDown = true;
m_StartPos = mouseEvent->pos();
if (mouseEvent->button() == Qt::LeftButton)
{
if (mouseEvent->modifiers() == Qt::ControlModifier || mouseEvent->modifiers() == Qt::ShiftModifier)
{
m_CtrlPressed = true;
}
else
{
m_CtrlPressed = false;
}
m_Leftbutton = true;
}
else
m_Leftbutton = false;
mouseMoveEvent(mouseEvent);
}
void QmitkSliderLevelWindowWidget::resizeEvent(QResizeEvent *event)
{
m_MoveHeight = event->size().height() - 25;
Update();
}
void QmitkSliderLevelWindowWidget::mouseReleaseEvent(QMouseEvent *)
{
if (m_LevelWindow.IsFixed())
return;
m_MouseDown = false;
}
void QmitkSliderLevelWindowWidget::Update()
{
int rectWidth;
if (m_ScaleVisible)
{
rectWidth = 17;
setMinimumSize(QSize(50, 50));
setMaximumSize(QSize(50, 2000));
setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding));
}
else
{
rectWidth = 26;
setMinimumSize(QSize(40, 50));
setMaximumSize(QSize(50, 2000));
setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding));
}
mitk::ScalarType mr = m_LevelWindow.GetRange();
if (mr < 1e-9)
mr = 1e-9;
mitk::ScalarType fact = m_MoveHeight / mr;
mitk::ScalarType rectHeight = m_LevelWindow.GetWindow() * fact;
if (rectHeight < 15)
rectHeight = 15;
if (m_LevelWindow.GetLowerWindowBound() < 0)
m_Rect.setRect(2,
static_cast<int>(m_MoveHeight - (m_LevelWindow.GetUpperWindowBound() - m_LevelWindow.GetRangeMin()) * fact),
rectWidth,
static_cast<int>(rectHeight));
else
m_Rect.setRect(2,
static_cast<int>(m_MoveHeight - (m_LevelWindow.GetUpperWindowBound() - m_LevelWindow.GetRangeMin()) * fact),
rectWidth,
static_cast<int>(rectHeight));
QWidget::repaint();
}
void QmitkSliderLevelWindowWidget::contextMenuEvent(QContextMenuEvent *)
{
m_Contextmenu->SetLevelWindowManager(m_Manager.GetPointer());
auto contextMenu = new QMenu(this);
Q_CHECK_PTR(contextMenu);
if (m_ScaleVisible)
contextMenu->addAction(tr("Hide Scale"), this, SLOT(HideScale()));
else
contextMenu->addAction(tr("Show Scale"), this, SLOT(ShowScale()));
contextMenu->addSeparator();
m_Contextmenu->GetContextMenu(contextMenu);
// Fix: Bug #13327 we need to reset the m_MouseDown value
// otherwise the cursor is not correctly restored afterwards
m_MouseDown = false;
}
void QmitkSliderLevelWindowWidget::HideScale()
{
m_ScaleVisible = false;
Update();
}
void QmitkSliderLevelWindowWidget::ShowScale()
{
m_ScaleVisible = true;
Update();
}
void QmitkSliderLevelWindowWidget::SetDataStorage(mitk::DataStorage *ds)
{
m_Manager->SetDataStorage(ds);
}
mitk::LevelWindowManager *QmitkSliderLevelWindowWidget::GetManager()
{
return m_Manager.GetPointer();
}
diff --git a/Modules/QtWidgetsExt/CMakeLists.txt b/Modules/QtWidgetsExt/CMakeLists.txt
index 9609183729..6c00e6f843 100644
--- a/Modules/QtWidgetsExt/CMakeLists.txt
+++ b/Modules/QtWidgetsExt/CMakeLists.txt
@@ -1,18 +1,18 @@
MITK_CREATE_MODULE(
DEPENDS MitkAlgorithmsExt MitkQtWidgets PRIVATE MitkSceneSerializationBase
PACKAGE_DEPENDS
- PUBLIC Qwt CTK|CTKWidgets
- PRIVATE Qt5|Concurrent+Svg+Xml VTK|IOImage
+ PUBLIC Qt6Qwt6 CTK|CTKWidgets
+ PRIVATE Qt6|Concurrent+Svg+Xml VTK|IOImage
)
if (TARGET ${MODULE_TARGET} AND MSVC)
#[[ Compiler warnings/errors because of QList, resp. Qwt on Visual Studio 2022 version 17.8:
'stdext::checked_array_iterator<const T *>': warning STL4043: stdext::checked_array_iterator,
stdext::unchecked_array_iterator, and related factory functions are non-Standard extensions
and will be removed in the future. std::span (since C++20) and gsl::span can be used instead.
You can define _SILENCE_STDEXT_ARR_ITERS_DEPRECATION_WARNING or _SILENCE_ALL_MS_EXT_DEPRECATION_WARNINGS
to suppress this warning.
]]
target_compile_definitions(${MODULE_TARGET} PUBLIC _SILENCE_STDEXT_ARR_ITERS_DEPRECATION_WARNING)
endif()
diff --git a/Modules/QtWidgetsExt/include/QmitkBoundingObjectWidget.h b/Modules/QtWidgetsExt/include/QmitkBoundingObjectWidget.h
index 5c98cc9b28..cbb86b29af 100644
--- a/Modules/QtWidgetsExt/include/QmitkBoundingObjectWidget.h
+++ b/Modules/QtWidgetsExt/include/QmitkBoundingObjectWidget.h
@@ -1,85 +1,85 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkBoundingObjectWidget_h
#define QmitkBoundingObjectWidget_h
// includes
#include "MitkQtWidgetsExtExports.h"
#include <QComboBox>
#include <QPushButton>
#include <QTreeWidget>
#include <mitkBoundingObject.h>
#include <mitkBoundingObjectGroup.h>
#include <mitkDataNode.h>
#include <mitkDataStorage.h>
#include <qwidget.h>
class MITKQTWIDGETSEXT_EXPORT QmitkBoundingObjectWidget : public QWidget
{
Q_OBJECT
public:
- QmitkBoundingObjectWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkBoundingObjectWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
~QmitkBoundingObjectWidget() override;
void SetDataStorage(mitk::DataStorage *dataStorage);
mitk::DataStorage *GetDataStorage();
mitk::BoundingObject::Pointer GetSelectedBoundingObject();
mitk::DataNode::Pointer GetSelectedBoundingObjectNode();
mitk::DataNode::Pointer GetAllBoundingObjects();
void setEnabled(bool flag);
void OnBoundingObjectModified(const itk::EventObject &e);
void RemoveAllItems();
signals:
// signal when bo has changed
void BoundingObjectsChanged();
protected slots:
void CreateBoundingObject(int type);
void OnDelButtonClicked();
void SelectionChanged();
void OnItemDoubleClicked(QTreeWidgetItem *item, int col);
void OnItemDataChanged(QTreeWidgetItem *item, int col);
protected:
void AddItem(mitk::DataNode *node);
void RemoveItem();
mitk::DataStorage *m_DataStorage;
QTreeWidget *m_TreeWidget;
QComboBox *m_addComboBox;
QPushButton *m_DelButton;
QPushButton *m_SaveButton;
QPushButton *m_LoadButton;
QTreeWidgetItem *m_lastSelectedItem;
unsigned long m_lastAffineObserver;
typedef std::map<QTreeWidgetItem *, mitk::DataNode *> ItemNodeMapType;
ItemNodeMapType m_ItemNodeMap;
unsigned int m_BoundingObjectCounter;
enum BoundingObjectType
{
CUBOID,
CONE,
ELLIPSOID,
CYLINDER,
};
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkColorTransferFunctionCanvas.h b/Modules/QtWidgetsExt/include/QmitkColorTransferFunctionCanvas.h
index 59d0d0af06..1d5a8023ee 100755
--- a/Modules/QtWidgetsExt/include/QmitkColorTransferFunctionCanvas.h
+++ b/Modules/QtWidgetsExt/include/QmitkColorTransferFunctionCanvas.h
@@ -1,94 +1,94 @@
/*============================================================================
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 QmitkColorTransferFunctionCanvas_h
#define QmitkColorTransferFunctionCanvas_h
#include "MitkQtWidgetsExtExports.h"
#include "QmitkTransferFunctionCanvas.h"
#include <vtkColorTransferFunction.h>
class MITKQTWIDGETSEXT_EXPORT QmitkColorTransferFunctionCanvas : public QmitkTransferFunctionCanvas
{
Q_OBJECT
public:
- QmitkColorTransferFunctionCanvas(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkColorTransferFunctionCanvas(QWidget *parent = nullptr, Qt::WindowFlags f = {});
void paintEvent(QPaintEvent *e) override;
int GetNearHandle(int x, int y, unsigned int maxSquaredDistance = 32) override;
void SetTitle(const QString &title);
void SetColorTransferFunction(vtkColorTransferFunction *colorTransferFunction)
{
this->m_ColorTransferFunction = colorTransferFunction;
this->SetMin(colorTransferFunction->GetRange()[0]);
this->SetMax(colorTransferFunction->GetRange()[1]);
setEnabled(true);
update();
}
int AddFunctionPoint(double x, double) override
{
return m_ColorTransferFunction->AddRGBPoint(x,
m_ColorTransferFunction->GetRedValue(x),
m_ColorTransferFunction->GetGreenValue(x),
m_ColorTransferFunction->GetBlueValue(x));
}
void RemoveFunctionPoint(double x) override
{
int old_size = GetFunctionSize();
m_ColorTransferFunction->RemovePoint(x);
if (GetFunctionSize() + 1 != old_size)
{
std::cout << "old/new size" << old_size << "/" << GetFunctionSize() << std::endl;
std::cout << "called with x=" << x << std::endl;
}
}
double GetFunctionX(int index) override { return m_ColorTransferFunction->GetDataPointer()[index * 4]; }
int GetFunctionSize() override { return m_ColorTransferFunction->GetSize(); }
void DoubleClickOnHandle(int handle) override;
void MoveFunctionPoint(int index, std::pair<double, double> pos) override;
void AddRGB(double x, double r, double g, double b);
double GetFunctionMax() { return m_ColorTransferFunction->GetRange()[1]; }
double GetFunctionMin() { return m_ColorTransferFunction->GetRange()[0]; }
double GetFunctionRange()
{
double range;
if ((m_ColorTransferFunction->GetRange()[0]) == 0)
{
range = m_ColorTransferFunction->GetRange()[1];
return range;
}
else
{
range = (m_ColorTransferFunction->GetRange()[1]) - (m_ColorTransferFunction->GetRange()[0]);
return range;
}
}
void RemoveAllFunctionPoints()
{
m_ColorTransferFunction->AddRGBSegment(this->GetFunctionMin(), 1, 0, 0, this->GetFunctionMax(), 1, 1, 0);
}
double GetFunctionY(int) override { return 0.0; }
protected:
vtkColorTransferFunction *m_ColorTransferFunction;
QString m_Title;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkCrossWidget.h b/Modules/QtWidgetsExt/include/QmitkCrossWidget.h
index 81a6ebcb08..ab6d22be4b 100644
--- a/Modules/QtWidgetsExt/include/QmitkCrossWidget.h
+++ b/Modules/QtWidgetsExt/include/QmitkCrossWidget.h
@@ -1,47 +1,47 @@
/*============================================================================
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 QmitkCrossWidget_h
#define QmitkCrossWidget_h
#include "MitkQtWidgetsExtExports.h"
#include <QLabel>
#include <mitkCommon.h>
class MITKQTWIDGETSEXT_EXPORT QmitkCrossWidget : public QLabel
{
Q_OBJECT
public:
- QmitkCrossWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkCrossWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
void mousePressEvent(QMouseEvent *mouseEvent) override;
void mouseMoveEvent(QMouseEvent *mouseEvent) override;
void mouseReleaseEvent(QMouseEvent *mouseEvent) override;
signals:
void SignalDeltaMove(int, int);
protected:
// fix for bug 3378 - setPos() causes an app crash on macOS
#ifdef __APPLE__
void ResetMousePosition(int, int){};
#else
void ResetMousePosition(int xpos, int ypos) { QCursor::setPos(xpos, ypos); };
#endif
int lastX, lastY;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkEditPointDialog.h b/Modules/QtWidgetsExt/include/QmitkEditPointDialog.h
index 7845d08fed..8adbad3a13 100644
--- a/Modules/QtWidgetsExt/include/QmitkEditPointDialog.h
+++ b/Modules/QtWidgetsExt/include/QmitkEditPointDialog.h
@@ -1,44 +1,44 @@
/*============================================================================
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 QmitkEditPointDialog_h
#define QmitkEditPointDialog_h
#include "MitkQtWidgetsExtExports.h"
#include <QDialog>
#include <mitkPointSet.h>
struct QmitkEditPointDialogData;
/*!
* \brief A dialog for editing points directly (coordinates) via TextEdits
*
*/
class MITKQTWIDGETSEXT_EXPORT QmitkEditPointDialog : public QDialog
{
Q_OBJECT
public:
- QmitkEditPointDialog(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkEditPointDialog(QWidget *parent = nullptr, Qt::WindowFlags f = {});
~QmitkEditPointDialog() override;
void SetPoint(mitk::PointSet *_PointSet, mitk::PointSet::PointIdentifier _PointId, int timestep = 0);
protected slots:
void OnOkButtonClicked(bool);
protected:
QmitkEditPointDialogData *d;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkFileChooser.h b/Modules/QtWidgetsExt/include/QmitkFileChooser.h
index af3d854bb1..17e8ef219f 100644
--- a/Modules/QtWidgetsExt/include/QmitkFileChooser.h
+++ b/Modules/QtWidgetsExt/include/QmitkFileChooser.h
@@ -1,114 +1,114 @@
/*============================================================================
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 QmitkFileChooser_h
#define QmitkFileChooser_h
#include "MitkQtWidgetsExtExports.h"
#include <QWidget>
class QPushButton;
class QLineEdit;
///
/// \brief Convenience Widget showing a line edit with the path of
/// a file or directory and a button which invokes a file choose dialog
///
/// Various methods are given to influence the behaviour or presentation
///
class MITKQTWIDGETSEXT_EXPORT QmitkFileChooser : public QWidget
{
Q_OBJECT
public:
///
/// standard ctor, init values to defaults (see methods for values)
///
- explicit QmitkFileChooser(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ explicit QmitkFileChooser(QWidget *parent = nullptr, Qt::WindowFlags f = {});
///
/// determines whether the button "Select file" is shown on the left
/// underneath the line edit, default=false (=is shown in a vertical layout)
///
void SetHorizotalLayout(bool horizontalLayout);
///
/// determines whether the selection must be a directory
/// default=false
///
void SetSelectDir(bool selectDir);
///
/// determines whether the file/directory mustexist
/// default=true
///
void SetFileMustExist(bool fileMustExist);
///
/// sets the file input, default=""
///
void SetFile(const std::string &file);
///
/// sets a file pattern to be selected, default=""
///
void SetFilePattern(const std::string &filepattern);
///
/// sets whether the user can edit the input, default=false
///
void SetReadOnly(bool ReadOnly);
///
/// returns whether the selected file/directory exists
///
bool IsValidFile() const;
///
/// returns the currently set file (an absolute path)
///
virtual std::string GetFile() const;
signals:
///
/// emitted when the input changed programatically or by the user
///
void NewFileSelected(const std::string &);
protected slots:
///
/// show dialog here
///
virtual void OnSelectFileClicked(bool /*checked=false*/);
///
/// check for valid here
///
virtual void OnFileEditingFinished();
protected:
///
/// \see SetSelectDir()
///
bool m_SelectDir;
///
/// \see SetFileMustExist()
///
bool m_FileMustExist;
///
/// \see SetFilePattern()
///
QString m_FilePattern;
///
/// the select file button
///
QPushButton *m_SelectFile;
///
/// the line edit to show the current file
///
QLineEdit *m_File;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkHistogram.h b/Modules/QtWidgetsExt/include/QmitkHistogram.h
index 77128944ce..b2baf5861d 100644
--- a/Modules/QtWidgetsExt/include/QmitkHistogram.h
+++ b/Modules/QtWidgetsExt/include/QmitkHistogram.h
@@ -1,58 +1,58 @@
/*============================================================================
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 QmitkHistogram_h
#define QmitkHistogram_h
#include <qcolor.h>
#include <qglobal.h>
#include <qwt_plot_item.h>
#include <qwt_series_data.h>
#include <qwt_text.h>
/**
\brief Used to create a histogram that can be shown in a Qwt Plot.
See QmitkHistogramWidget for an example of its usage.
*/
class QmitkHistogram : public QwtPlotItem
{
public:
- explicit QmitkHistogram(const QString &title = QString::null);
+ explicit QmitkHistogram(const QString &title = QString());
explicit QmitkHistogram(const QwtText &title);
~QmitkHistogram() override;
void setData(const QwtIntervalSeriesData &data);
const QwtIntervalSeriesData &data() const;
void setColor(const QColor &);
QColor color() const;
QRectF boundingRect() const override;
void draw(QPainter *, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &) const override;
void setBaseline(double reference);
double baseline() const;
protected:
virtual void drawBar(QPainter *, Qt::Orientation o, const QRect &) const;
private:
void init();
class HistogramData;
HistogramData *m_Data;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkPiecewiseFunctionCanvas.h b/Modules/QtWidgetsExt/include/QmitkPiecewiseFunctionCanvas.h
index 9eb399edb3..ed010daa13 100755
--- a/Modules/QtWidgetsExt/include/QmitkPiecewiseFunctionCanvas.h
+++ b/Modules/QtWidgetsExt/include/QmitkPiecewiseFunctionCanvas.h
@@ -1,99 +1,99 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkPiecewiseFunctionCanvas_h
#define QmitkPiecewiseFunctionCanvas_h
#include "MitkQtWidgetsExtExports.h"
#include "QmitkTransferFunctionCanvas.h"
#include <vtkPiecewiseFunction.h>
class MITKQTWIDGETSEXT_EXPORT QmitkPiecewiseFunctionCanvas : public QmitkTransferFunctionCanvas
{
Q_OBJECT
public:
- QmitkPiecewiseFunctionCanvas(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkPiecewiseFunctionCanvas(QWidget *parent = nullptr, Qt::WindowFlags f = {});
void paintEvent(QPaintEvent *e) override;
void SetTitle(const QString &title);
int GetNearHandle(int x, int y, unsigned int maxSquaredDistance = 32) override;
void SetPiecewiseFunction(vtkPiecewiseFunction *piecewiseFunction)
{
this->m_PiecewiseFunction = piecewiseFunction;
this->SetMin(m_PiecewiseFunction->GetRange()[0]);
this->SetMax(m_PiecewiseFunction->GetRange()[1]);
setEnabled(true);
update();
}
int AddFunctionPoint(double x, double val) override { return m_PiecewiseFunction->AddPoint(x, val); }
void RemoveFunctionPoint(double x) override
{
int old_size = GetFunctionSize();
m_PiecewiseFunction->RemovePoint(x);
if (GetFunctionSize() + 1 != old_size)
{
std::cout << "old/new size" << old_size << "/" << GetFunctionSize() << std::endl;
std::cout << "called with x=" << x << std::endl;
}
}
double GetFunctionX(int index) override { return m_PiecewiseFunction->GetDataPointer()[index * 2]; }
double GetFunctionY(int index) override
{
return m_PiecewiseFunction->GetValue(m_PiecewiseFunction->GetDataPointer()[index * 2]);
}
int GetFunctionSize() override { return m_PiecewiseFunction->GetSize(); }
void DoubleClickOnHandle(int) override {}
void MoveFunctionPoint(int index, std::pair<double, double> pos) override;
double GetFunctionMax() { return m_PiecewiseFunction->GetRange()[1]; }
double GetFunctionMin() { return m_PiecewiseFunction->GetRange()[0]; }
double GetFunctionRange()
{
double range;
if ((m_PiecewiseFunction->GetRange()[0]) < 0)
{
range = (m_PiecewiseFunction->GetRange()[1]) - (m_PiecewiseFunction->GetRange()[0]);
return range;
}
else
{
range = m_PiecewiseFunction->GetRange()[1];
return range;
}
}
void RemoveAllFunctionPoints()
{
m_PiecewiseFunction->AddSegment(this->GetFunctionMin(), 0, this->GetFunctionMax(), 1);
m_PiecewiseFunction->AddPoint(0.0, 0.0);
}
void ResetGO()
{ // Gradient Opacity
m_PiecewiseFunction->AddSegment(this->GetFunctionMin(), 0, 0, 1);
m_PiecewiseFunction->AddSegment(0, 1, ((this->GetFunctionRange()) * 0.125), 1);
m_PiecewiseFunction->AddSegment(((this->GetFunctionRange()) * 0.125), 1, ((this->GetFunctionRange()) * 0.2), 1);
m_PiecewiseFunction->AddSegment(((this->GetFunctionRange()) * 0.2), 1, ((this->GetFunctionRange()) * 0.25), 1);
}
protected:
vtkPiecewiseFunction *m_PiecewiseFunction;
QString m_Title;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkPlotWidget.h b/Modules/QtWidgetsExt/include/QmitkPlotWidget.h
index 5e21395d03..3fac00fd64 100644
--- a/Modules/QtWidgetsExt/include/QmitkPlotWidget.h
+++ b/Modules/QtWidgetsExt/include/QmitkPlotWidget.h
@@ -1,301 +1,301 @@
/*============================================================================
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 QmitkPlotWidget_h
#define QmitkPlotWidget_h
#include "MitkQtWidgetsExtExports.h"
#include "mitkCommon.h"
#include <qwidget.h>
#include <qwt_legend.h>
#include <qwt_plot.h>
#include <qwt_plot_curve.h>
#include <qwt_plot_intervalcurve.h>
#include <qwt_symbol.h>
#include <qwt_text.h>
#include <tuple>
#include <vector>
/**
* Provides a convenient interface for plotting curves using qwt.
* Designed for qwt version 5.2.1.
* Can be used with a QmitkPlotDialog, which provides a "Close" button.
* @see QmitkPlotDialog
*
* To plot data do the following:
* 1. Create two QmitkPlotWidget::DataVector Objects and fill them
* with corresponding x/y values. DataVectors are simple stl-vectors
* of type std::vector<double>. Please note that the xValues
* vector and the yValues vector MUST have the same size.
* 2. Instantiate the widget for example like that:
* QmitkPlotWidget* widget = new QmitkPlotWidget( this, "widget" );
* widget->SetAxisTitle( QwtPlot::xBottom, "My x asis [mm]" );
* widget->SetAxisTitle( QwtPlot::yLeft, "My y axis [mm]" );
* int curveId = widget->InsertCurve( "My sophisticated data" );
* widget->SetCurveData( curveId, xValues, yValues );
* widget->SetCurvePen( curveId, QPen( red ) );
* widget->SetCurveTitle( curveId, "My curve description" );
* widget->Replot();
* 3. You can modify the behavior of the plot by directly referencing
* the QwtPlot instance using the method GetPlot().
* @see QwtPlot
* @deprecatedSince{2018_04} Use QmitkChartWidget instead
*/
class MITKQTWIDGETSEXT_EXPORT QmitkPlotWidget
: public QWidget
{
private:
Q_OBJECT
public:
/**
* represents the data type used for scalar values stored
* in data arrays. This type is provided by qwt and may not
* be changed.
*/
typedef double ScalarType;
/**
* This type may be used to store a set of scalar values
* representing either x or y coordinates of the data
* points that should be rendered.
*/
typedef std::vector<ScalarType> DataVector;
/**
* convenience type used to store pairs representing x/y coordinates
* that should be rendered as a curve by the plot widget
*/
typedef std::vector<std::pair<double, double>> XYDataVector;
/**
* Standard qt constructor
*/
QmitkPlotWidget(QWidget *parent = nullptr,
const char *title = nullptr,
const char *name = nullptr,
- Qt::WindowFlags f = nullptr);
+ Qt::WindowFlags f = {});
/**
* Virtual destructor
*/
~QmitkPlotWidget() override;
/**
* Returns the instance of the plot-widget. This may be used
* to modify any detail of the appearance of the plot.
*/
QwtPlot *GetPlot();
/**
* Set the title using (formatted) QwtText object
*/
void SetPlotTitle(const QwtText &qwt_title);
/**
* Set plain text title, using default formatting
*/
void SetPlotTitle(const char *title);
/**
* Inserts a new curve into the plot-window.
* @param title the name of the curve
* @param color
* @returns the id of the curve. Use this id to
* refer to the curve, if you want to modify or add data.
*/
unsigned int InsertCurve(const char *title, QColor color = QColor(Qt::black));
/**
* Sets the title of the given axis. For the set of available axes
* @see QwtPlot::Axis.
* @param axis the axis for which the description should be set.
* @param title the name of the axis.
*/
void SetAxisTitle(int axis, const char *title);
/**
* Sets the data for a previously added curve. Data is provided as two vectors of double.
* The first vector represents the x coordinates, the second vector represents the y coordinates.
* @param curveId the id of the curve for which data should be added.
* @param xValues the x coordinates of the points that define the curve
* @param yValues the y coordinates of the points that define the curve
* @returns whether data was added successfully or not
*/
bool SetCurveData(unsigned int curveId, const DataVector &xValues, const DataVector &yValues);
/**
* @brief Sets the data with errors for a previously added curve.
*
* @param curveId the id of the curve for which data should be added.
* @param xValues the x coordinates of the points that define the curve
* @param yValues the y coordinates of the points that define the curve
* @param yLowerError the magnitude (>0) of the error in the lesser direction of y
* @param yUpperError the magnitude (>0) of the error in the larger direction of y
* @returns whether data was added successfully or not
*/
bool SetCurveData(unsigned int curveId,
const DataVector &xValues,
const DataVector &yValues,
const DataVector &yLowerError,
const DataVector &yUpperError);
/**
* @brief Sets the data with errors for a previously added curve.
*
* @param curveId the id of the curve for which data should be added.
* @param xValues the x coordinates of the points that define the curve
* @param yValues the y coordinates of the points that define the curve
* @param xLowerError the magnitude (>0) of the error in the lesser direction of x
* @param xUpperError the magnitude (>0) of the error in the larger direction of x
* @param yLowerError the magnitude (>0) of the error in the lesser direction of y
* @param yUpperError the magnitude (>0) of the error in the larger direction of y
* @returns whether data was added successfully or not
*/
bool SetCurveData(unsigned int curveId,
const DataVector &xValues,
const DataVector &yValues,
const DataVector &xLowerError,
const DataVector &xUpperError,
const DataVector &yLowerError,
const DataVector &yUpperError);
/**
* Sets the data for a previously added curve. Data is provided as a vectors of pairs.
* The pairs represent x/y coordinates of the points that define the curve.
* @param curveId the id of the curve for which data should be added.
* @param data the coordinates of the points that define the curve
* @returns whether data was added successfully or not
*/
bool SetCurveData(unsigned int curveId, const XYDataVector &data);
/**
* Defines how a curve should be drawn. For drawing a curve, a QPen is used.
* @param curveId the id of the curve for which appearance should be changed
* @param pen a QPen (@see QPen) defining the line style
*/
void SetCurvePen(unsigned int curveId, const QPen &pen);
/**
* Assign a brush, which defines the fill pattern of shapes drawn by a QPainter.
* In case of brush.style() != QBrush::NoBrush and * style() != QwtPlotCurve::Sticks
* the area between the curve and the baseline will be filled.
* In case !brush.color().isValid() the area will be filled by pen.color().
* The fill algorithm simply connects the first and the last curve point to the
* baseline. So the curve data has to be sorted (ascending or descending).
* @param curveId the id of the curve for which appearance should be changed
* @param brush a QBrush (@see QBrush) defining the line style
*/
void SetCurveBrush(unsigned int curveId, const QBrush &brush);
/**
* Sets the style how the line is drawn for the curve; like, plain line,
* or with the data points marked with a symbol;
* @param curveId
* @param style A QwtPlotCurve::CurveStyle
*/
void SetCurveStyle(unsigned int curveId, const QwtPlotCurve::CurveStyle style);
/**
* Sets the style data points are drawn for the curve; like, a line,
* or dots;
* @param curveId
* @param symbol A QwtSymbol
*/
void SetCurveSymbol(unsigned int curveId, QwtSymbol *symbol);
void SetCurveAntialiasingOn(unsigned int curveId);
void SetCurveAntialiasingOff(unsigned int curveId);
/**
* Sets the title of the given curve. The title will be shown in the legend of
* the QwtPlot.
* @param curveId the id of the curve for which the title should be set
* @param title the description of the curve that will be shown in the legend.
*/
void SetCurveTitle(unsigned int curveId, const char *title);
/**
* Defines how a curves errors should be drawn. For drawing a QPen is used.
* @param curveId the id of the curve for which error appearance should be changed
* @param pen a QPen (@see QPen) defining the line style
*/
void SetErrorPen(unsigned int curveId, const QPen &pen);
/**
* Defines the style of errors, symbols or as a curve.
* @param curveId the id of the curve for which error appearance should be changed
* @param drawSmybols true - draw symbols, false - draw curve
*/
void SetErrorStyleSymbols(unsigned int curveId, bool drawSmybols);
/**
* Sets the legend of the plot
*
*/
void SetLegend(QwtLegend *legend, QwtPlot::LegendPosition pos = QwtPlot::RightLegend, double ratio = -1);
/**
* Set a curve's legend attribute
* @param curveId the id of the curve
* @param attribute the legend attribute to be set
*/
void SetLegendAttribute(unsigned int curveId, const QwtPlotCurve::LegendAttribute &attribute);
/**
* Triggers a replot of the curve. Replot should be called once after
* setting new data.
*/
void Replot();
/**
* Resets the plot into an empty state
*/
void Clear();
protected:
/**
* Converts the given values into a raw double* array.
* A new array is allocated via new and must be deleted[] by the caller.
*/
double *ConvertToRawArray(const DataVector &values);
/**
* Converts the given values into a raw double* array.
* A new array is allocated via new and must be deleted[] by the caller.
* @param values the x/y values to convert to an array
* @param component defines if the x values (0) or the y values(1) should
* be converted. Other values than 0 and 1 will not be accepted.
*/
double *ConvertToRawArray(const XYDataVector &values, unsigned int component);
/**
* Adds an error interval curve.
*
* All errors should be absolutes. The magnitude will be used.
*
* @param curveId Which curve should the error curve be added to
* @param lessError Error in the negative direction (value - lessError)
* @param moreError Error in the positive direction (value + lessError)
* @param isXError Should the error bars be drawn horizontally
*/
bool AddErrorIntervalCurve(unsigned int curveId,
const DataVector &lessError,
const DataVector &moreError,
bool isXError);
QwtPlot *m_Plot;
std::vector<std::tuple<QwtPlotCurve *, QwtPlotIntervalCurve *, QwtPlotIntervalCurve *>> m_PlotCurveVector;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkPrimitiveMovieNavigatorWidget.h b/Modules/QtWidgetsExt/include/QmitkPrimitiveMovieNavigatorWidget.h
index d18d750cee..f72e247a20 100755
--- a/Modules/QtWidgetsExt/include/QmitkPrimitiveMovieNavigatorWidget.h
+++ b/Modules/QtWidgetsExt/include/QmitkPrimitiveMovieNavigatorWidget.h
@@ -1,50 +1,50 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkPrimitiveMovieNavigatorWidget_h
#define QmitkPrimitiveMovieNavigatorWidget_h
#include "MitkQtWidgetsExtExports.h"
#include <QTimer>
#include <QWidget>
#include <ui_QmitkPrimitiveMovieNavigatorWidget.h>
class MITKQTWIDGETSEXT_EXPORT QmitkPrimitiveMovieNavigatorWidget : public QWidget
{
Q_OBJECT
public:
- QmitkPrimitiveMovieNavigatorWidget(QWidget *parent = nullptr, Qt::WindowFlags fl = nullptr);
+ QmitkPrimitiveMovieNavigatorWidget(QWidget *parent = nullptr, Qt::WindowFlags fl = {});
~QmitkPrimitiveMovieNavigatorWidget() override;
virtual int getTimerInterval();
public slots:
virtual void Refetch();
virtual void SetStepper(mitk::Stepper *stepper);
virtual void goButton_clicked();
virtual void stopButton_clicked();
virtual void spinBoxValueChanged(int value);
virtual void setTimerInterval(int timerIntervalInMS);
protected:
Ui::QmitkPrimitiveMovieNavigator m_Controls;
mitk::Stepper::Pointer m_Stepper;
bool m_InRefetch;
QTimer *m_Timer;
int m_TimerIntervalInMS;
private slots:
virtual void next();
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkSliceWidget.h b/Modules/QtWidgetsExt/include/QmitkSliceWidget.h
index 1b831fee0e..5e4332b74b 100644
--- a/Modules/QtWidgetsExt/include/QmitkSliceWidget.h
+++ b/Modules/QtWidgetsExt/include/QmitkSliceWidget.h
@@ -1,91 +1,91 @@
/*============================================================================
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 QmitkSliceWidget_h
#define QmitkSliceWidget_h
#include "MitkQtWidgetsExtExports.h"
#include "ui_QmitkSliceWidget.h"
#include "QmitkRenderWindow.h"
#include "mitkDataStorage.h"
#include "mitkSliceNavigationController.h"
#include "QmitkSliceNavigationWidget.h"
#include "mitkSlicedGeometry3D.h"
#include "mitkStandaloneDataStorage.h"
#include <QWidget>
class MITKQTWIDGETSEXT_EXPORT QmitkSliceWidget : public QWidget, public Ui::QmitkSliceWidgetUi
{
Q_OBJECT
public:
- QmitkSliceWidget(QWidget *parent = nullptr, const char *name = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkSliceWidget(QWidget *parent = nullptr, const char *name = nullptr, Qt::WindowFlags f = {});
mitk::VtkPropRenderer *GetRenderer();
QFrame *GetSelectionFrame();
void UpdateGL();
void mousePressEvent(QMouseEvent *e) override;
void setPopUpEnabled(bool b);
void SetDataStorage(mitk::StandaloneDataStorage::Pointer storage);
mitk::StandaloneDataStorage *GetDataStorage();
QmitkSliceNavigationWidget* GetSliceNavigationWidget();
bool IsLevelWindowEnabled();
QmitkRenderWindow *GetRenderWindow();
mitk::SliceNavigationController *GetSliceNavigationController() const;
mitk::CameraRotationController *GetCameraRotationController() const;
mitk::BaseController *GetController() const;
public slots:
void SetData(mitk::DataStorage::SetOfObjects::ConstIterator it);
void SetData(mitk::DataStorage::SetOfObjects::ConstIterator it, mitk::AnatomicalPlane view);
void SetData(mitk::DataNode::Pointer node);
void SetData(mitk::DataNode::Pointer node, mitk::AnatomicalPlane view);
void InitWidget(mitk::AnatomicalPlane viewDirection);
void wheelEvent(QWheelEvent *e) override;
void ChangeView(QAction *val);
void SetLevelWindowEnabled(bool enable);
protected:
QmitkRenderWindow *m_RenderWindow;
mitk::AnatomicalPlane m_View;
private:
bool popUpEnabled;
mitk::VtkPropRenderer::Pointer m_Renderer;
mitk::SlicedGeometry3D::Pointer m_SlicedGeometry;
mitk::StandaloneDataStorage::Pointer m_DataStorage;
QMenu *popUp;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkStandardViews.h b/Modules/QtWidgetsExt/include/QmitkStandardViews.h
index af6871553f..34db3b9760 100644
--- a/Modules/QtWidgetsExt/include/QmitkStandardViews.h
+++ b/Modules/QtWidgetsExt/include/QmitkStandardViews.h
@@ -1,51 +1,51 @@
/*============================================================================
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 QmitkStandardViews_h
#define QmitkStandardViews_h
#include "MitkQtWidgetsExtExports.h"
#include "mitkCameraController.h"
#include "mitkCommon.h"
#include <QWidget>
class QClickableLabel;
class vtkRenderWindow;
class MITKQTWIDGETSEXT_EXPORT QmitkStandardViews : public QWidget
{
Q_OBJECT
public:
- QmitkStandardViews(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkStandardViews(QWidget *parent = nullptr, Qt::WindowFlags f = {});
~QmitkStandardViews() override;
void SetCameraController(mitk::CameraController *controller);
void SetCameraControllerFromRenderWindow(vtkRenderWindow *window);
signals:
void StandardViewDefined(mitk::CameraController::StandardView view);
protected slots:
void hotspotClicked(const QString &s);
protected:
QClickableLabel *m_ClickablePicture;
mitk::CameraController::Pointer m_CameraController;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkStringPropertyOnDemandEdit.h b/Modules/QtWidgetsExt/include/QmitkStringPropertyOnDemandEdit.h
index 03522d7224..7bcc247d2c 100644
--- a/Modules/QtWidgetsExt/include/QmitkStringPropertyOnDemandEdit.h
+++ b/Modules/QtWidgetsExt/include/QmitkStringPropertyOnDemandEdit.h
@@ -1,57 +1,57 @@
/*============================================================================
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 QmitkStringPropertyOnDemandEdit_h
#define QmitkStringPropertyOnDemandEdit_h
#include "MitkQtWidgetsExtExports.h"
#include <QLabel>
#include <QLayout>
#include <mitkPropertyObserver.h>
#include <mitkStringProperty.h>
class MITKQTWIDGETSEXT_EXPORT QClickableLabel2 : public QLabel
{
Q_OBJECT
signals:
void clicked();
public:
- QClickableLabel2(QWidget *parent, Qt::WindowFlags f = nullptr) : QLabel(parent, f) {}
+ QClickableLabel2(QWidget *parent, Qt::WindowFlags f = {}) : QLabel(parent, f) {}
void mouseReleaseEvent(QMouseEvent *) override { emit clicked(); }
};
/// @ingroup Widgets
class MITKQTWIDGETSEXT_EXPORT QmitkStringPropertyOnDemandEdit : public QFrame, public mitk::PropertyEditor
{
Q_OBJECT
public:
QmitkStringPropertyOnDemandEdit(mitk::StringProperty *, QWidget *parent);
~QmitkStringPropertyOnDemandEdit() override;
protected:
void PropertyChanged() override;
void PropertyRemoved() override;
mitk::StringProperty *m_StringProperty;
QHBoxLayout *m_layout;
QLabel *m_label;
QClickableLabel2 *m_toolbutton;
protected slots:
void onToolButtonClicked();
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkTransferFunctionCanvas.h b/Modules/QtWidgetsExt/include/QmitkTransferFunctionCanvas.h
index ae4ad01d58..d7a0c91175 100755
--- a/Modules/QtWidgetsExt/include/QmitkTransferFunctionCanvas.h
+++ b/Modules/QtWidgetsExt/include/QmitkTransferFunctionCanvas.h
@@ -1,131 +1,131 @@
/*============================================================================
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 QmitkTransferFunctionCanvas_h
#define QmitkTransferFunctionCanvas_h
#include "MitkQtWidgetsExtExports.h"
#include <mitkRenderingManager.h>
#include <mitkSimpleHistogram.h>
#include <QLineEdit>
#include <QWidget>
class MITKQTWIDGETSEXT_EXPORT QmitkTransferFunctionCanvas : public QWidget
{
Q_OBJECT
public:
- QmitkTransferFunctionCanvas(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkTransferFunctionCanvas(QWidget *parent = nullptr, Qt::WindowFlags f = {});
mitk::SimpleHistogram *GetHistogram() { return m_Histogram; }
void SetHistogram(mitk::SimpleHistogram *histogram) { m_Histogram = histogram; }
double GetMin() { return m_Min; }
void SetMin(double min)
{
this->m_Min = min;
SetLower(min);
}
double GetMax() { return m_Max; }
void SetMax(double max)
{
this->m_Max = max;
SetUpper(max);
}
double GetLower() { return m_Lower; }
void SetLower(double lower) { this->m_Lower = lower; }
double GetUpper() { return m_Upper; }
void SetUpper(double upper) { this->m_Upper = upper; }
void mousePressEvent(QMouseEvent *mouseEvent) override;
void paintEvent(QPaintEvent *e) override;
virtual void DoubleClickOnHandle(int handle) = 0;
void mouseMoveEvent(QMouseEvent *mouseEvent) override;
void mouseReleaseEvent(QMouseEvent *mouseEvent) override;
void mouseDoubleClickEvent(QMouseEvent *mouseEvent) override;
void PaintHistogram(QPainter &p);
virtual int GetNearHandle(int x, int y, unsigned int maxSquaredDistance = 32) = 0;
virtual int AddFunctionPoint(double x, double val) = 0;
virtual void RemoveFunctionPoint(double x) = 0;
virtual void MoveFunctionPoint(int index, std::pair<double, double> pos) = 0;
virtual double GetFunctionX(int index) = 0;
virtual double GetFunctionY(int index) = 0;
virtual int GetFunctionSize() = 0;
int m_GrabbedHandle;
double m_Lower, m_Upper, m_Min, m_Max;
std::pair<int, int> FunctionToCanvas(std::pair<double, double>);
std::pair<double, double> CanvasToFunction(std::pair<int, int>);
mitk::SimpleHistogram *m_Histogram;
void keyPressEvent(QKeyEvent *e) override;
void SetImmediateUpdate(bool state);
std::pair<double, double> ValidateCoord(std::pair<double, double> x)
{
double max = m_Histogram->GetMax();
double min = m_Histogram->GetMin();
if (x.first < min)
x.first = min;
if (x.first > max)
x.first = max;
if (x.second < 0)
x.second = 0;
if (x.second > 1)
x.second = 1;
return x;
}
void SetX(float x)
{
if (m_GrabbedHandle != -1)
{
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair(x, GetFunctionY(m_GrabbedHandle))));
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void SetY(float y)
{
if (m_GrabbedHandle != -1)
{
this->MoveFunctionPoint(m_GrabbedHandle, ValidateCoord(std::make_pair(GetFunctionX(m_GrabbedHandle), y)));
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void SetQLineEdits(QLineEdit *xEdit, QLineEdit *yEdit)
{
m_XEdit = xEdit;
m_YEdit = yEdit;
m_LineEditAvailable = true;
}
protected:
bool m_ImmediateUpdate;
float m_Range;
bool m_LineEditAvailable;
QLineEdit *m_XEdit;
QLineEdit *m_YEdit;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkTransferFunctionGeneratorWidget.h b/Modules/QtWidgetsExt/include/QmitkTransferFunctionGeneratorWidget.h
index aae0e4a99c..222ec09e66 100644
--- a/Modules/QtWidgetsExt/include/QmitkTransferFunctionGeneratorWidget.h
+++ b/Modules/QtWidgetsExt/include/QmitkTransferFunctionGeneratorWidget.h
@@ -1,80 +1,80 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkTransferFunctionGeneratorWidget_h
#define QmitkTransferFunctionGeneratorWidget_h
#include "MitkQtWidgetsExtExports.h"
#include "ui_QmitkTransferFunctionGeneratorWidget.h"
#include <mitkCommon.h>
#include <QWidget>
#include <mitkDataNode.h>
#include <mitkTransferFunctionProperty.h>
class MITKQTWIDGETSEXT_EXPORT QmitkTransferFunctionGeneratorWidget : public QWidget,
public Ui::QmitkTransferFunctionGeneratorWidget
{
Q_OBJECT
public:
- QmitkTransferFunctionGeneratorWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkTransferFunctionGeneratorWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
~QmitkTransferFunctionGeneratorWidget() override;
void SetDataNode(mitk::DataNode *node, mitk::TimeStepType timestep = 0);
int AddPreset(const QString &presetName);
void SetPresetsTabEnabled(bool enable);
void SetThresholdTabEnabled(bool enable);
void SetBellTabEnabled(bool enable);
public slots:
void OnSavePreset();
void OnLoadPreset();
void OnDeltaLevelWindow(int dx, int dy);
void OnDeltaThreshold(int dx, int dy);
signals:
void SignalTransferFunctionModeChanged(int);
void SignalUpdateCanvas();
protected slots:
void OnPreset(int mode);
protected:
mitk::TransferFunctionProperty::Pointer tfpToChange;
double histoMinimum;
double histoMaximum;
double thPos;
double thDelta;
double deltaScale;
double deltaMax;
double deltaMin;
const mitk::Image::HistogramType *histoGramm;
QString presetFileName;
double ScaleDelta(int d) const;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/QmitkTransferFunctionWidget.h b/Modules/QtWidgetsExt/include/QmitkTransferFunctionWidget.h
index 7daa54a4d3..a24e0a331b 100755
--- a/Modules/QtWidgetsExt/include/QmitkTransferFunctionWidget.h
+++ b/Modules/QtWidgetsExt/include/QmitkTransferFunctionWidget.h
@@ -1,79 +1,79 @@
/*============================================================================
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 QmitkTransferFunctionWidget_h
#define QmitkTransferFunctionWidget_h
#include "MitkQtWidgetsExtExports.h"
#include "ui_QmitkTransferFunctionWidget.h"
#include <mitkCommon.h>
#include <QWidget>
#include <mitkDataNode.h>
#include <mitkTransferFunctionProperty.h>
#include <QPushButton>
#include <QSlider>
#include <QmitkTransferFunctionWidget.h>
namespace mitk
{
class BaseRenderer;
}
class MITKQTWIDGETSEXT_EXPORT QmitkTransferFunctionWidget : public QWidget, public Ui::QmitkTransferFunctionWidget
{
Q_OBJECT
public:
- QmitkTransferFunctionWidget(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkTransferFunctionWidget(QWidget *parent = nullptr, Qt::WindowFlags f = {});
~QmitkTransferFunctionWidget() override;
void SetDataNode(mitk::DataNode *node, mitk::TimeStepType timestep = 0, const mitk::BaseRenderer *renderer = nullptr);
void SetScalarLabel(const QString &scalarLabel);
void ShowScalarOpacityFunction(bool show);
void ShowColorFunction(bool show);
void ShowGradientOpacityFunction(bool show);
void SetScalarOpacityFunctionEnabled(bool enable);
void SetColorFunctionEnabled(bool enable);
void SetGradientOpacityFunctionEnabled(bool enable);
public slots:
void SetXValueScalar(const QString text);
void SetYValueScalar(const QString text);
void SetXValueGradient(const QString text);
void SetYValueGradient(const QString text);
void SetXValueColor(const QString text);
void OnUpdateCanvas();
void UpdateRanges();
void OnResetSlider();
void OnSpanChanged(int lower, int upper);
protected:
mitk::TransferFunctionProperty::Pointer tfpToChange;
int m_RangeSliderMin;
int m_RangeSliderMax;
mitk::SimpleHistogramCache histogramCache;
};
#endif
diff --git a/Modules/QtWidgetsExt/include/qclickablelabel.h b/Modules/QtWidgetsExt/include/qclickablelabel.h
index 1afe7791c9..aae696823a 100644
--- a/Modules/QtWidgetsExt/include/qclickablelabel.h
+++ b/Modules/QtWidgetsExt/include/qclickablelabel.h
@@ -1,68 +1,68 @@
/*============================================================================
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 qclickablelabelhincluded
#define qclickablelabelhincluded
#include "MitkQtWidgetsExtExports.h"
#include <QLabel>
#include <map>
#include <vector>
#include "mitkCommon.h"
/**
\brief A QLabel with multiple hotspots, that can be clicked
Specially useful in connection with a pixmap.
Stretched images should be avoided, because the hotspots will not be adjusted in any way.
*/
class MITKQTWIDGETSEXT_EXPORT QClickableLabel : public QLabel
{
Q_OBJECT
public:
- QClickableLabel(QWidget *parent, Qt::WindowFlags f = nullptr);
- QClickableLabel(const QString &text, QWidget *parent, Qt::WindowFlags f = nullptr);
+ QClickableLabel(QWidget *parent, Qt::WindowFlags f = {});
+ QClickableLabel(const QString &text, QWidget *parent, Qt::WindowFlags f = {});
~QClickableLabel() override;
void AddHotspot(const QString &name, const QRect position);
void RemoveHotspot(const QString &name);
void RemoveHotspot(unsigned int hotspotIndex);
void RemoveAllHotspots();
signals:
void mousePressed(const QString &hotspotName);
void mousePressed(unsigned int hotspotIndex);
void mouseReleased(const QString &hotspotName);
void mouseReleased(unsigned int hotspotIndex);
protected:
void mousePressEvent(QMouseEvent *e) override;
void mouseReleaseEvent(QMouseEvent *e) override;
/// returns index == m_Hotspots.size() if nothing is hit
unsigned int matchingRect(const QPoint &p);
typedef std::vector<QRect> RectVectorType;
RectVectorType m_Hotspots;
typedef std::map<QString, unsigned int> NameToIndexMapType;
typedef std::map<unsigned int, QString> IndexToNameMapType;
NameToIndexMapType m_HotspotIndexForName;
IndexToNameMapType m_HotspotNameForIndex;
};
#endif
diff --git a/Modules/QtWidgetsExt/src/QmitkBoundingObjectWidget.cpp b/Modules/QtWidgetsExt/src/QmitkBoundingObjectWidget.cpp
index 2044658851..8195ef1e7c 100644
--- a/Modules/QtWidgetsExt/src/QmitkBoundingObjectWidget.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkBoundingObjectWidget.cpp
@@ -1,442 +1,442 @@
/*============================================================================
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 "QmitkBoundingObjectWidget.h"
#include <mitkCone.h>
#include <mitkCuboid.h>
#include <mitkCylinder.h>
#include <mitkEllipsoid.h>
#include <mitkLine.h>
#include <mitkNodePredicateProperty.h>
#include <mitkPlaneGeometry.h>
#include <QBoxLayout>
#include <QCheckBox>
#include <QInputDialog>
#include <QPushButton>
#include <QStringList>
#include <mitkAffineBaseDataInteractor3D.h>
// micro services
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
QmitkBoundingObjectWidget::QmitkBoundingObjectWidget(QWidget *parent, Qt::WindowFlags f)
: QWidget(parent, f),
m_DataStorage(nullptr),
m_lastSelectedItem(nullptr),
m_lastAffineObserver(0),
m_ItemNodeMap(),
m_BoundingObjectCounter(1)
{
QBoxLayout *mainLayout = new QVBoxLayout(this);
QHBoxLayout *buttonLayout = new QHBoxLayout();
QStringList boList;
boList << tr("add") << tr("cube") << tr("cone") << tr("ellipse") << tr("cylinder");
m_addComboBox = new QComboBox();
m_addComboBox->addItems(boList);
m_addComboBox->setItemIcon(1, QIcon(":/QmitkWidgetsExt/btnCube.xpm"));
m_addComboBox->setItemIcon(2, QIcon(":/QmitkWidgetsExt/btnPyramid.xpm"));
m_addComboBox->setItemIcon(3, QIcon(":/QmitkWidgetsExt/btnEllipsoid.xpm"));
m_addComboBox->setItemIcon(4, QIcon(":/QmitkWidgetsExt/btnCylinder.xpm"));
buttonLayout->addWidget(m_addComboBox);
m_DelButton = new QPushButton("del");
buttonLayout->addWidget(m_DelButton);
m_SaveButton = new QPushButton("save");
buttonLayout->addWidget(m_SaveButton);
m_SaveButton->setEnabled(false);
m_LoadButton = new QPushButton("load");
buttonLayout->addWidget(m_LoadButton);
m_LoadButton->setEnabled(false);
m_TreeWidget = new QTreeWidget(this);
m_TreeWidget->setColumnCount(3);
QStringList sList;
sList << tr("name") << tr("inverted") << tr("visible");
m_TreeWidget->setHeaderLabels(sList);
m_TreeWidget->setColumnWidth(0, 250);
m_TreeWidget->setColumnWidth(1, 50);
m_TreeWidget->setColumnWidth(2, 50);
m_TreeWidget->setAutoScroll(true);
m_TreeWidget->setSelectionMode(QAbstractItemView::SingleSelection);
mainLayout->addWidget(m_TreeWidget);
mainLayout->addLayout(buttonLayout);
connect(m_addComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(CreateBoundingObject(int)));
connect(m_TreeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(SelectionChanged()));
connect(m_DelButton, SIGNAL(clicked()), this, SLOT(OnDelButtonClicked()));
connect(m_TreeWidget,
SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
this,
SLOT(OnItemDoubleClicked(QTreeWidgetItem *, int)));
connect(
m_TreeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(OnItemDataChanged(QTreeWidgetItem *, int)));
}
QmitkBoundingObjectWidget::~QmitkBoundingObjectWidget()
{
}
void QmitkBoundingObjectWidget::setEnabled(bool flag)
{
ItemNodeMapType::iterator it = m_ItemNodeMap.begin();
while (it != m_ItemNodeMap.end())
{
mitk::DataNode *node = it->second;
QTreeWidgetItem *item = it->first;
if (flag)
node->SetVisibility(item->checkState(2));
else
node->SetVisibility(flag);
++it;
}
QWidget::setEnabled(flag);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkBoundingObjectWidget::SelectionChanged()
{
QList<QTreeWidgetItem *> selectedItems = m_TreeWidget->selectedItems();
if (selectedItems.size() < 1)
return;
QTreeWidgetItem *selectedItem = selectedItems.first();
if (selectedItem == m_lastSelectedItem)
return;
if (m_lastSelectedItem != nullptr)
{
m_TreeWidget->closePersistentEditor(m_lastSelectedItem, 0);
ItemNodeMapType::iterator it = m_ItemNodeMap.find(m_lastSelectedItem);
if (it != m_ItemNodeMap.end())
{
mitk::DataNode *last_node = it->second;
// remove observer
last_node->RemoveObserver(m_lastAffineObserver);
last_node->SetDataInteractor(nullptr);
}
}
ItemNodeMapType::iterator it = m_ItemNodeMap.find(selectedItem);
if (it == m_ItemNodeMap.end())
return;
mitk::DataNode *new_node = it->second;
mitk::AffineBaseDataInteractor3D::Pointer affineDataInteractor = mitk::AffineBaseDataInteractor3D::New();
affineDataInteractor->LoadStateMachine("AffineInteraction3D.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
affineDataInteractor->SetEventConfig("AffineConfig.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
affineDataInteractor->SetDataNode(new_node);
new_node->SetBoolProperty("pickable", true);
// create observer for node
itk::ReceptorMemberCommand<QmitkBoundingObjectWidget>::Pointer command =
itk::ReceptorMemberCommand<QmitkBoundingObjectWidget>::New();
command->SetCallbackFunction(this, &QmitkBoundingObjectWidget::OnBoundingObjectModified);
m_lastAffineObserver = new_node->AddObserver(mitk::AffineInteractionEvent(), command);
m_lastSelectedItem = selectedItem;
}
void QmitkBoundingObjectWidget::AddItem(mitk::DataNode *node)
{
mitk::BoundingObject *boundingObject;
boundingObject = dynamic_cast<mitk::BoundingObject *>(node->GetData());
std::string name;
node->GetStringProperty("name", name);
if (boundingObject)
{
QTreeWidgetItem *item = new QTreeWidgetItem();
item->setData(0, Qt::EditRole, QString::fromLocal8Bit(name.c_str()));
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
// checkbox for positive flag
item->setData(1, Qt::CheckStateRole, tr(""));
item->setCheckState(1, Qt::Unchecked);
// checkbox for visibleflag
item->setData(2, Qt::CheckStateRole, tr(""));
item->setCheckState(2, Qt::Checked);
m_TreeWidget->addTopLevelItem(item);
m_ItemNodeMap.insert(std::make_pair(item, node));
m_TreeWidget->selectAll();
QList<QTreeWidgetItem *> items = m_TreeWidget->selectedItems();
for (int i = 0; i < items.size(); i++)
{
- m_TreeWidget->setItemSelected(items.at(i), false);
+ items.at(i)->setSelected(false);
}
- m_TreeWidget->setItemSelected(item, true);
+ item->setSelected(true);
}
else
MITK_ERROR << name << " is not a bounding object or does not exist in data storage" << endl;
}
void QmitkBoundingObjectWidget::OnItemDoubleClicked(QTreeWidgetItem *item, int col)
{
if (col == 0)
{
m_TreeWidget->openPersistentEditor(item, col);
}
}
void QmitkBoundingObjectWidget::OnItemDataChanged(QTreeWidgetItem *item, int col)
{
if (m_ItemNodeMap.size() < 1)
return;
ItemNodeMapType::iterator it = m_ItemNodeMap.find(item);
if (it == m_ItemNodeMap.end())
return;
mitk::DataNode *node = it->second;
// name
if (col == 0)
{
m_TreeWidget->closePersistentEditor(item, col);
node->SetName(item->text(0).toLocal8Bit().data());
}
// positive
else if (col == 1)
{
mitk::BoundingObject *boundingObject = dynamic_cast<mitk::BoundingObject *>(node->GetData());
if (boundingObject)
boundingObject->SetPositive(!(item->checkState(1)));
emit BoundingObjectsChanged();
}
// visible
else if (col == 2)
{
node->SetVisibility(item->checkState(2));
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkBoundingObjectWidget::RemoveItem()
{
// selection mode is set to single selection, so there should not be more than one selected item
QList<QTreeWidgetItem *> selectedItems = m_TreeWidget->selectedItems();
QTreeWidgetItem *item = selectedItems.first();
QString str = item->text(0);
ItemNodeMapType::iterator it = m_ItemNodeMap.find(item);
if (it == m_ItemNodeMap.end())
return;
mitk::DataNode *node = it->second;
mitk::BoundingObject *boundingObject;
if (node)
{
boundingObject = dynamic_cast<mitk::BoundingObject *>(node->GetData());
if (boundingObject)
{
// delete item;
m_TreeWidget->takeTopLevelItem(m_TreeWidget->indexOfTopLevelItem(item));
m_ItemNodeMap.erase(m_ItemNodeMap.find(item));
m_DataStorage->Remove(node);
}
}
}
void QmitkBoundingObjectWidget::RemoveAllItems()
{
ItemNodeMapType::iterator it = m_ItemNodeMap.begin();
while (it != m_ItemNodeMap.end())
{
m_TreeWidget->takeTopLevelItem(m_TreeWidget->indexOfTopLevelItem(it->first));
m_ItemNodeMap.erase(m_ItemNodeMap.find(it->first));
++it;
}
m_BoundingObjectCounter = 1;
}
mitk::BoundingObject::Pointer QmitkBoundingObjectWidget::GetSelectedBoundingObject()
{
mitk::BoundingObject *boundingObject;
mitk::DataNode *node = this->GetSelectedBoundingObjectNode();
if (node)
{
boundingObject = dynamic_cast<mitk::BoundingObject *>(node->GetData());
if (boundingObject)
return boundingObject;
}
return nullptr;
}
void QmitkBoundingObjectWidget::SetDataStorage(mitk::DataStorage *dataStorage)
{
m_DataStorage = dataStorage;
}
mitk::DataStorage *QmitkBoundingObjectWidget::GetDataStorage()
{
return m_DataStorage;
}
void QmitkBoundingObjectWidget::OnDelButtonClicked()
{
RemoveItem();
}
void QmitkBoundingObjectWidget::CreateBoundingObject(int type)
{
// get cross position
mitk::Point3D pos;
mitk::RenderingManager::RenderWindowVector windows =
mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows();
// hopefully we have the renderwindows in the "normal" order
const mitk::PlaneGeometry *plane1 =
mitk::BaseRenderer::GetInstance(windows.at(0))->GetSliceNavigationController()->GetCurrentPlaneGeometry();
const mitk::PlaneGeometry *plane2 =
mitk::BaseRenderer::GetInstance(windows.at(1))->GetSliceNavigationController()->GetCurrentPlaneGeometry();
const mitk::PlaneGeometry *plane3 =
mitk::BaseRenderer::GetInstance(windows.at(2))->GetSliceNavigationController()->GetCurrentPlaneGeometry();
mitk::Line3D line;
if ((plane1 != nullptr) && (plane2 != nullptr) && (plane1->IntersectionLine(plane2, line)))
{
if (!((plane3 != nullptr) && (plane3->IntersectionPoint(line, pos))))
{
return;
}
}
if (type != 0)
{
mitk::BoundingObject::Pointer boundingObject;
QString name;
name.setNum(m_BoundingObjectCounter);
switch (type - 1)
{
case CUBOID:
boundingObject = mitk::Cuboid::New();
name.prepend("Cube_");
break;
case CONE:
boundingObject = mitk::Cone::New();
name.prepend("Cone_");
break;
case ELLIPSOID:
boundingObject = mitk::Ellipsoid::New();
name.prepend("Ellipse_");
break;
case CYLINDER:
boundingObject = mitk::Cylinder::New();
name.prepend("Cylinder_");
break;
default:
return;
break;
}
m_BoundingObjectCounter++;
m_addComboBox->setCurrentIndex(0);
// set initial size
mitk::Vector3D size;
size.Fill(10);
boundingObject->GetGeometry()->SetSpacing(size);
boundingObject->GetGeometry()->Translate(pos.GetVectorFromOrigin());
boundingObject->GetTimeGeometry()->Update();
// create node
mitk::DataNode::Pointer node = mitk::DataNode::New();
node->SetData(boundingObject);
node->SetProperty("name", mitk::StringProperty::New(name.toLocal8Bit().data()));
node->SetProperty("color", mitk::ColorProperty::New(0.0, 0.0, 1.0));
node->SetProperty("opacity", mitk::FloatProperty::New(0.7));
node->SetProperty("bounding object", mitk::BoolProperty::New(true));
node->SetProperty("helper object", mitk::BoolProperty::New(true));
m_DataStorage->Add(node);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
emit BoundingObjectsChanged();
AddItem(node);
}
}
mitk::DataNode::Pointer QmitkBoundingObjectWidget::GetAllBoundingObjects()
{
mitk::DataNode::Pointer boundingObjectGroupNode = mitk::DataNode::New();
mitk::BoundingObjectGroup::Pointer boundingObjectGroup = mitk::BoundingObjectGroup::New();
boundingObjectGroup->SetCSGMode(mitk::BoundingObjectGroup::Union);
mitk::NodePredicateProperty::Pointer prop =
mitk::NodePredicateProperty::New("bounding object", mitk::BoolProperty::New(true));
mitk::DataStorage::SetOfObjects::ConstPointer allBO = m_DataStorage->GetSubset(prop);
for (mitk::DataStorage::SetOfObjects::const_iterator it = allBO->begin(); it != allBO->end(); ++it)
{
mitk::DataNode::Pointer node = *it;
mitk::BoundingObject::Pointer boundingObject = dynamic_cast<mitk::BoundingObject *>(node->GetData());
if (boundingObject)
boundingObjectGroup->AddBoundingObject(boundingObject);
}
boundingObjectGroupNode->SetData(boundingObjectGroup);
if (boundingObjectGroup->GetCount() > 0)
return boundingObjectGroupNode;
return nullptr;
}
mitk::DataNode::Pointer QmitkBoundingObjectWidget::GetSelectedBoundingObjectNode()
{
QList<QTreeWidgetItem *> selectedItems = m_TreeWidget->selectedItems();
if (selectedItems.size() < 1)
return nullptr;
QTreeWidgetItem *item = selectedItems.first();
mitk::DataNode *node = m_ItemNodeMap.find(item)->second;
return node;
}
void QmitkBoundingObjectWidget::OnBoundingObjectModified(const itk::EventObject &)
{
emit BoundingObjectsChanged();
}
diff --git a/Modules/QtWidgetsExt/src/QmitkColorPropertyEditor.cpp b/Modules/QtWidgetsExt/src/QmitkColorPropertyEditor.cpp
index 254c1afea4..dd4d4e1d08 100644
--- a/Modules/QtWidgetsExt/src/QmitkColorPropertyEditor.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkColorPropertyEditor.cpp
@@ -1,279 +1,271 @@
/*============================================================================
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 "QmitkColorPropertyEditor.h"
#include <QApplication>
#include <QCloseEvent>
-#include <QDesktopWidget>
#include <QLayout>
#include <QMouseEvent>
#include <QPainter>
#include <mitkRenderingManager.h>
//----- QmitkPopupColorChooser ---------------------------------------------------------
QmitkPopupColorChooser::QmitkPopupColorChooser(QWidget *parent, unsigned int steps, unsigned int size)
: QFrame(parent, Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Tool | Qt::X11BypassWindowManagerHint),
my_parent(parent)
{
setSteps(steps);
setLineWidth(2);
setMouseTracking(true);
setFrameStyle(QFrame::Panel | QFrame::Raised);
setLineWidth(1);
ensurePolished();
resize(size, size);
hide();
}
QmitkPopupColorChooser::~QmitkPopupColorChooser()
{
}
void QmitkPopupColorChooser::setSteps(int steps)
{
m_Steps = steps;
m_Steps2 = m_Steps / 2;
m_HStep = 360 / m_Steps;
m_SStep = 512 / m_Steps;
m_VStep = 512 / m_Steps;
}
void QmitkPopupColorChooser::keyReleaseEvent(QKeyEvent *)
{
emit colorSelected(m_OriginalColor);
close();
}
void QmitkPopupColorChooser::mouseMoveEvent(QMouseEvent *e)
{
double x(e->pos().x());
double y(e->pos().y());
x /= width();
if (x >= 0.0)
{
x = (int)(x * (float)(m_Steps - 1)) / (float)(m_Steps - 1);
if (x > 1.0)
x = 1.0;
if (x < 0.0)
x = 0.0;
}
y /= height();
if (y >= 1.0)
y = 0.9;
if (y < 0.0)
y = 0.0;
y = (int)(y * (float)m_Steps) / (float)m_Steps;
m_H = static_cast<int>(y * 359.0);
if (x >= 0.5)
{
m_S = static_cast<int>((1.0 - x) * 511.0);
if (m_S > 255)
m_S = 255;
m_V = 255;
}
else
{
m_S = 255;
if (x < 0.0)
m_V = 0;
else
{
m_V = static_cast<int>(x * 511.0 + 511.0 / (float)(m_Steps - 1));
if (m_V > 255)
m_V = 255;
}
}
QColor color;
color.setHsv(m_H, m_S, m_V);
emit colorSelected(color);
}
void QmitkPopupColorChooser::mouseReleaseEvent(QMouseEvent *)
{
close();
}
void QmitkPopupColorChooser::closeEvent(QCloseEvent *e)
{
e->accept();
releaseKeyboard();
releaseMouse();
if (!m_popupParent)
return;
// remember that we (as a popup) might recieve the mouse release
// event instead of the popupParent. This is due to the fact that
// the popupParent popped us up in its mousePressEvent handler. To
// avoid the button remaining in pressed state we simply send a
// faked mouse button release event to it.
// Maleike: parent should not pop us on MouseRelease!
QMouseEvent me(QEvent::MouseButtonRelease, QPoint(0, 0), QPoint(0, 0), Qt::LeftButton, Qt::NoButton, Qt::NoModifier);
QApplication::sendEvent(m_popupParent, &me);
}
void QmitkPopupColorChooser::popup(QWidget *parent, const QPoint &point, const mitk::Color *color)
{
m_popupParent = parent;
if (m_popupParent)
{
QPoint newPos;
if (color)
{
QColor qcolor((int)((*color)[0] * 255.0), (int)((*color)[1] * 255.0), (int)((*color)[2] * 255.0));
int h, s, v;
qcolor.getHsv(&h, &s, &v);
if (h == -1) // set by Qt if color is achromatic ( but this widget does not display grays )
h = 10; // red
int x, y;
float cellwidth = (float)width() / (float)(m_Steps);
if (s > v) // restrict to the colors we can display
{ // left side, ramp from v = 255/m_Steps to v = 255
s = 255;
x = (int)((((float)v / 255.0) * ((float)m_Steps2) - 1.0) * cellwidth + cellwidth / 2);
}
else
{
v = 255;
x = (int)(((1.0 - ((float)s / 255.0)) * ((float)m_Steps2)) * cellwidth + cellwidth / 2
+
width() / 2);
}
y = (int)((float)h / 360.0 * (float)m_Steps * cellwidth);
m_OriginalColor.setHsv(h, s, v);
// move to color
newPos.setX(point.x() - x);
newPos.setY(point.y() - y);
}
else
{
// center widget
m_OriginalColor.setHsv(-1, 0, 0);
newPos.setX(point.x() - width() / 2);
newPos.setY(point.y() - height() / 2);
}
move(m_popupParent->mapToGlobal(newPos));
}
show();
raise();
grabMouse();
grabKeyboard();
}
void QmitkPopupColorChooser::paintEvent(QPaintEvent *)
{
QPainter painter(this);
drawGradient(&painter);
}
void QmitkPopupColorChooser::drawGradient(QPainter *p)
{
p->setWindow(0, 0, m_Steps - 1, m_Steps); // defines coordinate system
p->setPen(Qt::NoPen);
QColor c;
for (unsigned int h = 0; h < m_Steps; ++h)
{
for (unsigned int v = 1; v < m_Steps2; ++v)
{
c.setHsv(h * m_HStep, 255, v * m_VStep); // rainbow effect
p->setBrush(c); // solid fill with color c
p->drawRect(v - 1, h, m_Steps2, m_Steps); // draw the rectangle
}
for (unsigned int s = 0; s < m_Steps2; ++s)
{
c.setHsv(h * m_HStep, 255 - s * m_SStep, 255); // rainbow effect
p->setBrush(c); // solid fill with color c
p->drawRect(m_Steps2 + s - 1, h, m_Steps2, m_Steps); // draw the rectangle
}
}
}
//----- QmitkColorPropertyEditor --------------------------------------------------
// initialization of static pointer to color picker widget
QmitkPopupColorChooser *QmitkColorPropertyEditor::colorChooser = nullptr;
int QmitkColorPropertyEditor::colorChooserRefCount = 0;
QmitkColorPropertyEditor::QmitkColorPropertyEditor(const mitk::ColorProperty *property, QWidget *parent)
: QmitkColorPropertyView(property, parent)
{
- // our popup belongs to the whole screen, so it could be drawn outside the toplevel window's borders
- int scr;
- if (QApplication::desktop()->isVirtualDesktop())
- scr = QApplication::desktop()->screenNumber(parent->mapToGlobal(pos()));
- else
- scr = QApplication::desktop()->screenNumber(parent);
-
if (colorChooserRefCount == 0)
{
- colorChooser = new QmitkPopupColorChooser(QApplication::desktop()->screen(scr), 50);
+ colorChooser = new QmitkPopupColorChooser(nullptr, 50);
}
++colorChooserRefCount;
}
QmitkColorPropertyEditor::~QmitkColorPropertyEditor()
{
--colorChooserRefCount;
if (!colorChooserRefCount)
{
delete colorChooser;
colorChooser = nullptr;
}
}
void QmitkColorPropertyEditor::mousePressEvent(QMouseEvent *e)
{
connect(colorChooser, SIGNAL(colorSelected(QColor)), this, SLOT(onColorSelected(QColor)));
if (m_ColorProperty)
{
colorChooser->popup(this, e->pos(), &(m_ColorProperty->GetColor()));
}
}
void QmitkColorPropertyEditor::mouseReleaseEvent(QMouseEvent *)
{
disconnect(colorChooser, SIGNAL(colorSelected(QColor)), this, SLOT(onColorSelected(QColor)));
}
void QmitkColorPropertyEditor::onColorSelected(QColor c)
{
if (m_ColorProperty)
{
int r, g, b;
c.getRgb(&r, &g, &b);
const_cast<mitk::ColorProperty *>(m_ColorProperty)->SetColor(r / 255.0, g / 255.0, b / 255.0);
m_ColorProperty->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
diff --git a/Modules/QtWidgetsExt/src/QmitkColorPropertyView.cpp b/Modules/QtWidgetsExt/src/QmitkColorPropertyView.cpp
index 95789bc8e4..62407ef96a 100644
--- a/Modules/QtWidgetsExt/src/QmitkColorPropertyView.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkColorPropertyView.cpp
@@ -1,51 +1,51 @@
/*============================================================================
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 "QmitkColorPropertyView.h"
#include <QPixmap>
#define ROUND_P(x) ((int)((x) + 0.5))
QmitkColorPropertyView::QmitkColorPropertyView(const mitk::ColorProperty *property, QWidget *parent)
: QLabel(parent), PropertyView(property), m_ColorProperty(property)
{
setText(" "); // two spaces for some minimun height
setMinimumSize(15, 15);
PropertyChanged();
m_WidgetPalette = QWidget::palette();
QWidget::setPalette(m_WidgetPalette);
QWidget::setAutoFillBackground(true);
}
QmitkColorPropertyView::~QmitkColorPropertyView()
{
}
void QmitkColorPropertyView::PropertyChanged()
{
if (m_Property)
DisplayColor();
}
void QmitkColorPropertyView::PropertyRemoved()
{
m_Property = nullptr;
m_ColorProperty = nullptr;
}
void QmitkColorPropertyView::DisplayColor()
{
const mitk::Color &tmp_col(m_ColorProperty->GetColor());
QColor color(ROUND_P(tmp_col[0] * 255.0), ROUND_P(tmp_col[1] * 255.0), ROUND_P(tmp_col[2] * 255.0));
- m_WidgetPalette.setColor(QPalette::Background, color);
+ m_WidgetPalette.setColor(QPalette::Window, color);
}
diff --git a/Modules/QtWidgetsExt/src/QmitkColorTransferFunctionCanvas.cpp b/Modules/QtWidgetsExt/src/QmitkColorTransferFunctionCanvas.cpp
index f0b9626bba..8c60514684 100755
--- a/Modules/QtWidgetsExt/src/QmitkColorTransferFunctionCanvas.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkColorTransferFunctionCanvas.cpp
@@ -1,152 +1,152 @@
/*============================================================================
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 "QmitkColorTransferFunctionCanvas.h"
#include <QColorDialog>
#include <QLineEdit>
#include <QPainter>
QmitkColorTransferFunctionCanvas::QmitkColorTransferFunctionCanvas(QWidget *parent, Qt::WindowFlags f)
: QmitkTransferFunctionCanvas(parent, f), m_ColorTransferFunction(nullptr)
{
// used for drawing a border
setContentsMargins(1, 1, 1, 1);
}
void QmitkColorTransferFunctionCanvas::SetTitle(const QString &title)
{
m_Title = title;
}
void QmitkColorTransferFunctionCanvas::paintEvent(QPaintEvent *)
{
QPainter painter(this);
// Render gray background
QRect contentsRect = this->contentsRect();
painter.setPen(Qt::gray);
painter.drawRect(0, 0, contentsRect.width() + 1, contentsRect.height() + 1);
if (!this->isEnabled())
return;
if (m_ColorTransferFunction)
{
for (int x = contentsRect.x(); x < contentsRect.x() + contentsRect.width(); x++)
{
double xVal = m_Min + ((float)x) / contentsRect.width() * (m_Max - m_Min);
QColor col((int)(m_ColorTransferFunction->GetRedValue(xVal) * 255),
(int)(m_ColorTransferFunction->GetGreenValue(xVal) * 255),
(int)(m_ColorTransferFunction->GetBlueValue(xVal) * 255));
painter.setPen(col);
painter.drawLine(x, 1, x, contentsRect.height());
}
}
// paint title
if (m_Title.size() > 0)
{
painter.setPen(Qt::black);
painter.drawText(QPoint(11, 21), m_Title);
painter.setPen(Qt::white);
painter.drawText(QPoint(10, 20), m_Title);
}
// paint min and max
QString qs_min = QString::number(m_Min);
QString qs_max = QString::number(m_Max);
QRect qr_min = painter.fontMetrics().boundingRect(qs_min);
QRect qr_max = painter.fontMetrics().boundingRect(qs_max);
int y, x;
y = this->contentsRect().height() - qr_min.height() + 5;
x = 10;
painter.setPen(Qt::black);
painter.drawText(QPoint(x + 1, y + 1), qs_min);
painter.setPen(Qt::white);
painter.drawText(QPoint(x, y), qs_min);
y = this->contentsRect().height() - qr_max.height() + 5;
x = this->contentsRect().width() - qr_max.width() - 6;
painter.setPen(Qt::black);
painter.drawText(QPoint(x, y + 1), qs_max);
painter.setPen(Qt::white);
painter.drawText(QPoint(x, y), qs_max);
if (m_ColorTransferFunction)
{
// now paint the handles
painter.setBrush(Qt::black);
painter.setPen(Qt::black);
for (int i = 0; i < this->GetFunctionSize(); i++)
{
int handleHeight = (i == m_GrabbedHandle) ? (int)(contentsRect.height() / 1.5) : contentsRect.height() / 2;
int handleWidth = (i == m_GrabbedHandle) ? 6 : 4;
std::pair<int, int> point = this->FunctionToCanvas(std::make_pair(GetFunctionX(i), 0.0f));
int y = height() / 2;
- painter.drawRoundRect(point.first - handleWidth / 2, y - handleHeight / 2, handleWidth, handleHeight, 50, 50);
+ painter.drawRoundedRect(point.first - handleWidth / 2, y - handleHeight / 2, handleWidth, handleHeight, 50, 50);
if (i == m_GrabbedHandle && m_LineEditAvailable)
{
int xCursor = m_XEdit->cursorPosition();
m_XEdit->setText(QString::number(GetFunctionX(m_GrabbedHandle), 'g', 4));
m_XEdit->setCursorPosition(xCursor);
}
}
}
}
int QmitkColorTransferFunctionCanvas::GetNearHandle(int x, int, unsigned int maxSquaredDistance)
{
for (int i = 0; i < this->GetFunctionSize(); i++)
{
std::pair<int, int> point = this->FunctionToCanvas(std::make_pair(GetFunctionX(i), (double)0.0));
if ((unsigned int)((point.first - x) * (point.first - x)) < maxSquaredDistance)
{
return i;
}
}
return -1;
}
void QmitkColorTransferFunctionCanvas::DoubleClickOnHandle(int handle)
{
double xVal = GetFunctionX(handle);
QColor col((int)(m_ColorTransferFunction->GetRedValue(xVal) * 255),
(int)(m_ColorTransferFunction->GetGreenValue(xVal) * 255),
(int)(m_ColorTransferFunction->GetBlueValue(xVal) * 255));
QColor result = QColorDialog::getColor(col);
if (result.isValid())
{
m_ColorTransferFunction->AddRGBPoint(xVal, result.red() / 255.0, result.green() / 255.0, result.blue() / 255.0);
this->update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkColorTransferFunctionCanvas::MoveFunctionPoint(int index, std::pair<double, double> pos)
{
double color[3];
m_ColorTransferFunction->GetColor(GetFunctionX(index), color);
RemoveFunctionPoint(GetFunctionX(index));
m_ColorTransferFunction->AddRGBPoint(pos.first, color[0], color[1], color[2]);
}
void QmitkColorTransferFunctionCanvas::AddRGB(double x, double r, double g, double b)
{
m_ColorTransferFunction->AddRGBPoint(x, r, g, b);
}
diff --git a/Modules/QtWidgetsExt/src/QmitkGnuplotWidget.cpp b/Modules/QtWidgetsExt/src/QmitkGnuplotWidget.cpp
index 76527b197d..d7dce8f540 100644
--- a/Modules/QtWidgetsExt/src/QmitkGnuplotWidget.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkGnuplotWidget.cpp
@@ -1,217 +1,217 @@
/*============================================================================
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 "QmitkGnuplotWidget.h"
#include <QClipboard>
#include <QContextMenuEvent>
#include <QMenu>
#include <ui_QmitkGnuplotWidget.h>
QmitkGnuplotWidget::QmitkGnuplotWidget(QWidget *parent)
: QWidget(parent),
m_Ui(new Ui::QmitkGnuplotWidget),
m_ContextMenu(nullptr),
m_CopyPlotAction(nullptr),
m_CopyScriptAction(nullptr),
m_Process(new QProcess(this))
{
m_Ui->setupUi(this);
connect(
m_Process, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(OnProcessStateChanged(QProcess::ProcessState)));
connect(m_Process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(OnProcessError(QProcess::ProcessError)));
connect(
m_Process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(OnProcessFinished(int, QProcess::ExitStatus)));
this->CreateContextMenu();
}
QmitkGnuplotWidget::~QmitkGnuplotWidget()
{
}
void QmitkGnuplotWidget::CreateContextMenu()
{
m_CopyPlotAction = new QAction("Copy &Plot", this);
connect(m_CopyPlotAction, SIGNAL(triggered()), this, SLOT(OnCopyPlot()));
m_CopyScriptAction = new QAction("Copy &Script", this);
connect(m_CopyScriptAction, SIGNAL(triggered()), this, SLOT(OnCopyScript()));
m_ContextMenu = new QMenu(this);
m_ContextMenu->addActions(QList<QAction *>() << m_CopyPlotAction << m_CopyScriptAction);
}
void QmitkGnuplotWidget::contextMenuEvent(QContextMenuEvent *event)
{
- const QPixmap *plot = m_Ui->label->pixmap();
+ auto plot = m_Ui->label->pixmap();
- m_CopyPlotAction->setEnabled(plot != nullptr && !plot->isNull());
+ m_CopyPlotAction->setEnabled(!plot.isNull());
m_CopyScriptAction->setEnabled(!m_Commands.empty());
m_ContextMenu->popup(event->globalPos());
event->accept();
}
void QmitkGnuplotWidget::OnCopyPlot()
{
- const QPixmap *plot = m_Ui->label->pixmap();
+ auto plot = m_Ui->label->pixmap();
- if (plot != nullptr && !plot->isNull())
- QApplication::clipboard()->setPixmap(*plot);
+ if (!plot.isNull())
+ QApplication::clipboard()->setPixmap(plot);
}
void QmitkGnuplotWidget::OnCopyScript()
{
if (m_Commands.empty())
return;
QString script = this->CreateSetTermCommand();
Q_FOREACH (const QString &command, m_Commands)
{
script += command + "\n";
}
QApplication::clipboard()->setText(script);
}
void QmitkGnuplotWidget::resizeEvent(QResizeEvent *)
{
m_ModifiedTime.Modified();
if (m_Process->isOpen() || m_Commands.isEmpty() || m_GnuplotPath.isEmpty())
return;
this->Update();
}
QString QmitkGnuplotWidget::GetGnuplotPath() const
{
return m_GnuplotPath;
}
void QmitkGnuplotWidget::SetGnuplotPath(const QString &path)
{
m_GnuplotPath = path;
m_ModifiedTime.Modified();
}
QStringList QmitkGnuplotWidget::GetCommands() const
{
return m_Commands;
}
void QmitkGnuplotWidget::SetCommands(const QStringList &commands)
{
m_Commands = commands;
m_ModifiedTime.Modified();
}
void QmitkGnuplotWidget::Update()
{
if (m_UpdateTime < m_ModifiedTime)
m_Process->start(m_GnuplotPath, QStringList() << "-");
}
QSize QmitkGnuplotWidget::sizeHint() const
{
return QSize(400, 300);
}
QString QmitkGnuplotWidget::CreateSetTermCommand() const
{
return QString("set term pngcairo size %1,%2 enhanced font '%3,%4'\n")
.arg(this->width())
.arg(this->height())
.arg(this->font().family())
.arg(this->font().pointSize());
}
void QmitkGnuplotWidget::OnProcessStateChanged(QProcess::ProcessState state)
{
if (state == QProcess::Running)
{
m_UpdateTime = m_ModifiedTime;
m_Process->write(this->CreateSetTermCommand().toLatin1());
Q_FOREACH (const QString &command, m_Commands)
{
m_Process->write(QString("%1\n").arg(command).toLatin1());
}
m_Process->write("exit\n");
m_Process->closeWriteChannel();
}
}
void QmitkGnuplotWidget::OnProcessError(QProcess::ProcessError error)
{
switch (error)
{
case QProcess::FailedToStart:
m_Ui->label->setText("Gnuplot failed to start!");
break;
case QProcess::Crashed:
m_Ui->label->setText("Gnuplot crashed!");
break;
case QProcess::Timedout:
m_Ui->label->setText("Gnuplot timed out!");
break;
case QProcess::WriteError:
m_Ui->label->setText("Could not write to gnuplot!");
break;
case QProcess::ReadError:
m_Ui->label->setText("Could not read from gnuplot!");
break;
default:
m_Ui->label->setText("An unknown error occurred!");
break;
}
}
void QmitkGnuplotWidget::OnProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
bool needUpdate = false;
if (exitStatus != QProcess::CrashExit)
{
if (exitCode == 0)
{
if (m_UpdateTime < m_ModifiedTime)
{
needUpdate = true;
}
else
{
m_Ui->label->setPixmap(QPixmap::fromImage(QImage::fromData(m_Process->readAllStandardOutput(), "PNG")));
}
}
else
{
m_Ui->label->setText(QString("Gnuplot exit code: %1!").arg(exitCode));
}
}
m_Process->close();
if (needUpdate)
this->Update();
}
diff --git a/Modules/QtWidgetsExt/src/QmitkHistogram.cpp b/Modules/QtWidgetsExt/src/QmitkHistogram.cpp
index c2a7db8f5b..be0e9bfc8b 100644
--- a/Modules/QtWidgetsExt/src/QmitkHistogram.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkHistogram.cpp
@@ -1,179 +1,179 @@
/*============================================================================
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 <qpainter.h>
#include <qwt_painter.h>
#include <qwt_plot.h>
#include <qwt_scale_map.h>
#include "QmitkHistogram.h"
class QmitkHistogram::HistogramData
{
public:
QwtIntervalSeriesData data;
QColor color;
double reference;
};
QmitkHistogram::QmitkHistogram(const QwtText &title) : QwtPlotItem(title)
{
init();
}
QmitkHistogram::QmitkHistogram(const QString &title) : QwtPlotItem(QwtText(title))
{
init();
}
QmitkHistogram::~QmitkHistogram()
{
delete m_Data;
}
void QmitkHistogram::init()
{
m_Data = new HistogramData();
m_Data->reference = 0.0;
setItemAttribute(QwtPlotItem::AutoScale, true);
setItemAttribute(QwtPlotItem::Legend, true);
setZ(20.0);
}
void QmitkHistogram::setBaseline(double reference)
{
if (m_Data->reference != reference)
{
m_Data->reference = reference;
itemChanged();
}
}
double QmitkHistogram::baseline() const
{
return m_Data->reference;
}
void QmitkHistogram::setData(const QwtIntervalSeriesData &data)
{
m_Data->data.setSamples(data.samples());
itemChanged();
}
const QwtIntervalSeriesData &QmitkHistogram::data() const
{
return m_Data->data;
}
void QmitkHistogram::setColor(const QColor &color)
{
if (m_Data->color != color)
{
m_Data->color = color;
itemChanged();
}
}
QColor QmitkHistogram::color() const
{
return m_Data->color;
}
QRectF QmitkHistogram::boundingRect() const
{
QRectF rect = m_Data->data.boundingRect();
if (!rect.isValid())
return rect;
if (rect.bottom() < m_Data->reference)
rect.setBottom(m_Data->reference);
else if (rect.top() > m_Data->reference)
rect.setTop(m_Data->reference);
return rect;
}
void QmitkHistogram::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &) const
{
const QwtIntervalSeriesData &iData = m_Data->data;
painter->setPen(QPen(m_Data->color));
const int y0 = yMap.transform(baseline());
for (int i = 0; i < (int)iData.size(); i++)
{
const int y2 = yMap.transform(iData.sample(i).value);
if (y2 == y0)
continue;
int x1 = xMap.transform(iData.sample(i).interval.minValue());
int x2 = xMap.transform(iData.sample(i).interval.maxValue());
if (x1 > x2)
qSwap(x1, x2);
if (i < (int)iData.size() - 2)
{
const int xx1 = xMap.transform(iData.sample(i + 1).interval.minValue());
const int xx2 = xMap.transform(iData.sample(i + 1).interval.maxValue());
if (x2 == qMin(xx1, xx2))
{
const int yy2 = yMap.transform(iData.sample(i + 1).value);
if (yy2 != y0 && ((yy2 < y0 && y2 < y0) || (yy2 > y0 && y2 > y0)))
{
// One pixel distance between neighbored bars
x2--;
}
}
}
drawBar(painter, Qt::Vertical, QRect(x1, y0, x2 - x1, y2 - y0));
}
}
void QmitkHistogram::drawBar(QPainter *painter, Qt::Orientation, const QRect &rect) const
{
painter->save();
const QColor color(painter->pen().color());
const QRect r = rect.normalized();
const int factor = 125;
- const QColor light(color.light(factor));
- const QColor dark(color.dark(factor));
+ const QColor light(color.lighter(factor));
+ const QColor dark(color.darker(factor));
painter->setBrush(color);
painter->setPen(Qt::NoPen);
QwtPainter::drawRect(painter, r.x() + 1, r.y() + 1, r.width() - 2, r.height() - 2);
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(light, 2));
QwtPainter::drawLine(painter, r.left() + 1, r.top() + 2, r.right() + 1, r.top() + 2);
painter->setPen(QPen(dark, 2));
QwtPainter::drawLine(painter, r.left() + 1, r.bottom(), r.right() + 1, r.bottom());
painter->setPen(QPen(light, 1));
QwtPainter::drawLine(painter, r.left(), r.top() + 1, r.left(), r.bottom());
QwtPainter::drawLine(painter, r.left() + 1, r.top() + 2, r.left() + 1, r.bottom() - 1);
painter->setPen(QPen(dark, 1));
QwtPainter::drawLine(painter, r.right() + 1, r.top() + 1, r.right() + 1, r.bottom());
QwtPainter::drawLine(painter, r.right(), r.top() + 2, r.right(), r.bottom() - 1);
painter->restore();
}
diff --git a/Modules/QtWidgetsExt/src/QmitkHotkeyLineEdit.cpp b/Modules/QtWidgetsExt/src/QmitkHotkeyLineEdit.cpp
index f15f2c3b18..110228df8b 100644
--- a/Modules/QtWidgetsExt/src/QmitkHotkeyLineEdit.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkHotkeyLineEdit.cpp
@@ -1,97 +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.
============================================================================*/
#include "QmitkHotkeyLineEdit.h"
#include <QGridLayout>
#include <QKeyEvent>
#include <QLabel>
#include <QPushButton>
const std::string QmitkHotkeyLineEdit::TOOLTIP = "Press any key (combination)";
QmitkHotkeyLineEdit::QmitkHotkeyLineEdit(QWidget* parent /*= nullptr*/)
: QLineEdit(parent)
{
Init();
}
QmitkHotkeyLineEdit::QmitkHotkeyLineEdit(const QKeySequence& qKeySequence, QWidget* parent /*= nullptr*/)
: QLineEdit(parent)
{
Init();
SetKeySequence(qKeySequence);
}
QmitkHotkeyLineEdit::QmitkHotkeyLineEdit(const QString& qKeySequenceAsString, QWidget* parent /*= nullptr*/)
: QLineEdit(parent)
{
Init();
SetKeySequence(qKeySequenceAsString);
}
void QmitkHotkeyLineEdit::Init()
{
setToolTip(QString::fromStdString(QmitkHotkeyLineEdit::TOOLTIP));
setReadOnly(true);
connect(this, &QLineEdit::textChanged, this, &QmitkHotkeyLineEdit::LineEditTextChanged);
}
void QmitkHotkeyLineEdit::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_unknown)
{
return;
}
else if (event->key() == Qt::Key_Escape)
{
m_KeySequence = QKeySequence();
}
else
{
- m_KeySequence = QKeySequence(event->modifiers() + event->key());
+ m_KeySequence = QKeySequence(event->modifiers() | event->key());
}
SetKeySequence(m_KeySequence);
}
void QmitkHotkeyLineEdit::SetKeySequence(const QKeySequence& qKeySequence)
{
setText(qKeySequence.toString());
}
void QmitkHotkeyLineEdit::SetKeySequence(const QString& qKeySequenceAsString)
{
SetKeySequence(QKeySequence(qKeySequenceAsString));
}
QKeySequence QmitkHotkeyLineEdit::GetKeySequence()
{
return m_KeySequence;
}
QString QmitkHotkeyLineEdit::GetKeySequenceAsString()
{
return m_KeySequence.toString();
}
bool QmitkHotkeyLineEdit::Matches(QKeyEvent* event)
{
- QKeySequence keySequence = QKeySequence(event->modifiers() + event->key());
+ QKeySequence keySequence = QKeySequence(event->modifiers() | event->key());
return keySequence == m_KeySequence;
}
void QmitkHotkeyLineEdit::LineEditTextChanged(const QString& text)
{
m_KeySequence = QKeySequence(text.toUpper());
}
diff --git a/Modules/QtWidgetsExt/src/QmitkNumberPropertyView.cpp b/Modules/QtWidgetsExt/src/QmitkNumberPropertyView.cpp
index 17bb2e4466..679126aa90 100644
--- a/Modules/QtWidgetsExt/src/QmitkNumberPropertyView.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkNumberPropertyView.cpp
@@ -1,138 +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.
============================================================================*/
#include "QmitkNumberPropertyView.h"
#include <QTextStream>
#define DT_SHORT 1
#define DT_INT 2
#define DT_FLOAT 3
#define DT_DOUBLE 4
QmitkNumberPropertyView::QmitkNumberPropertyView(const mitk::IntProperty *property, QWidget *parent)
: QLabel(parent), PropertyView(property), m_IntProperty(property), m_DataType(DT_INT)
{
initialize();
}
QmitkNumberPropertyView::QmitkNumberPropertyView(const mitk::FloatProperty *property, QWidget *parent)
: QLabel(parent), PropertyView(property), m_FloatProperty(property), m_DataType(DT_FLOAT)
{
initialize();
}
QmitkNumberPropertyView::QmitkNumberPropertyView(const mitk::DoubleProperty *property, QWidget *parent)
: QLabel(parent), PropertyView(property), m_DoubleProperty(property), m_DataType(DT_DOUBLE)
{
initialize();
}
QmitkNumberPropertyView::~QmitkNumberPropertyView()
{
}
void QmitkNumberPropertyView::initialize()
{ // only to be called from constructors
m_Suffix = "";
m_DisplayFactor = 1.0;
setDecimalPlaces(2);
}
short QmitkNumberPropertyView::decimalPlaces() const
{
return m_DecimalPlaces;
}
void QmitkNumberPropertyView::setDecimalPlaces(short places)
{
m_DecimalPlaces = places;
DisplayNumber();
}
QString QmitkNumberPropertyView::suffix() const
{
- if (m_Suffix == "")
- return QString::null;
- else
- return m_Suffix;
+ return m_Suffix;
}
void QmitkNumberPropertyView::setSuffix(const QString &suffix)
{
m_Suffix = suffix;
DisplayNumber();
}
bool QmitkNumberPropertyView::showPercent() const
{
return m_DisplayFactor == 100.0;
}
void QmitkNumberPropertyView::setShowPercent(bool show)
{
if (show)
{
m_DisplayFactor = 100.0;
setSuffix("%");
}
else
{
m_DisplayFactor = 1.0;
setSuffix("");
}
}
void QmitkNumberPropertyView::PropertyChanged()
{
if (m_Property)
DisplayNumber();
}
void QmitkNumberPropertyView::PropertyRemoved()
{
m_Property = nullptr;
setText("n/a");
}
void QmitkNumberPropertyView::DisplayNumber()
{
QString displayedText;
QTextStream stream(&displayedText);
stream.setRealNumberPrecision(m_DecimalPlaces);
switch (m_DataType)
{
case DT_INT:
{
int i = m_IntProperty->GetValue();
stream << (i * m_DisplayFactor);
break;
}
case DT_FLOAT:
{
float f = m_FloatProperty->GetValue();
stream << (f * m_DisplayFactor);
break;
}
case DT_DOUBLE:
{
double d = m_DoubleProperty->GetValue();
stream << (d * m_DisplayFactor);
break;
}
default:
break;
}
setText(displayedText);
}
diff --git a/Modules/QtWidgetsExt/src/QmitkPointListView.cpp b/Modules/QtWidgetsExt/src/QmitkPointListView.cpp
index cf25972d78..3d3ec8c652 100644
--- a/Modules/QtWidgetsExt/src/QmitkPointListView.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkPointListView.cpp
@@ -1,336 +1,336 @@
/*============================================================================
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 "QmitkPointListView.h"
#include <QmitkEditPointDialog.h>
#include <QmitkPointListModel.h>
#include <QmitkRenderWindow.h>
#include <QmitkAbstractMultiWidget.h>
#include <mitkRenderingManager.h>
#include <QKeyEvent>
#include <QMenu>
#include <QMessageBox>
#include <QPalette>
#include <QTimer>
QmitkPointListView::QmitkPointListView(QWidget *parent)
: QListView(parent),
m_PointListModel(new QmitkPointListModel()),
m_SelfCall(false),
m_showFading(false),
m_MultiWidget(nullptr)
{
QListView::setAlternatingRowColors(true);
QListView::setSelectionBehavior(QAbstractItemView::SelectItems);
QListView::setSelectionMode(QAbstractItemView::SingleSelection);
QListView::setModel(m_PointListModel);
QString tooltip = QString("Use the F2/F3 keys to move a point up/down, the Del key to remove a point\nand the mouse "
"wheel to change the timestep.\n\nTimeStep:\t%1")
.arg(0);
QListView::setToolTip(tooltip);
this->setContextMenuPolicy(Qt::CustomContextMenu);
this->setMinimumHeight(40);
this->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
connect(m_PointListModel, SIGNAL(SignalUpdateSelection()), this, SLOT(OnPointSetSelectionChanged()));
connect(this, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(OnPointDoubleClicked(const QModelIndex &)));
connect(QListView::selectionModel(),
SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
this,
SLOT(OnListViewSelectionChanged(const QItemSelection &, const QItemSelection &)));
// T28213: Every single action in the context menu is either not implemented or working. Implement/fix or remove in future.
// connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));
}
QmitkPointListView::~QmitkPointListView()
{
delete m_PointListModel;
}
void QmitkPointListView::SetPointSetNode(mitk::DataNode *pointSetNode)
{
m_PointListModel->SetPointSetNode(pointSetNode);
}
const mitk::PointSet *QmitkPointListView::GetPointSet() const
{
return m_PointListModel->GetPointSet();
}
void QmitkPointListView::SetMultiWidget(QmitkAbstractMultiWidget* multiWidget)
{
m_MultiWidget = multiWidget;
if (nullptr != m_MultiWidget)
{
for (const auto& renderWindow : m_MultiWidget->GetRenderWindows().values())
{
AddSliceNavigationController(renderWindow->GetSliceNavigationController());
}
}
}
QmitkAbstractMultiWidget* QmitkPointListView::GetMultiWidget() const
{
return m_MultiWidget;
}
void QmitkPointListView::OnPointDoubleClicked(const QModelIndex &index)
{
mitk::PointSet::PointType p;
mitk::PointSet::PointIdentifier id;
m_PointListModel->GetPointForModelIndex(index, p, id);
QmitkEditPointDialog _EditPointDialog(this);
_EditPointDialog.SetPoint(m_PointListModel->GetPointSet(), id, m_PointListModel->GetTimeStep());
_EditPointDialog.exec();
}
void QmitkPointListView::OnPointSetSelectionChanged()
{
const mitk::PointSet *pointSet = m_PointListModel->GetPointSet();
if (pointSet == nullptr)
return;
// update this view's selection status as a result to changes in the point set data structure
m_SelfCall = true;
int timeStep = m_PointListModel->GetTimeStep();
if (pointSet->GetNumberOfSelected(timeStep) > 1)
{
MITK_ERROR << "Point set has multiple selected points. This view is not designed for more than one selected point.";
}
int selectedIndex = pointSet->SearchSelectedPoint(timeStep);
if (selectedIndex == -1) // no selected point is found
{
m_SelfCall = false;
return;
}
QModelIndex index;
bool modelIndexOkay = m_PointListModel->GetModelIndexForPointID(selectedIndex, index);
if (modelIndexOkay == true)
QListView::selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
emit SignalPointSelectionChanged();
m_SelfCall = false;
}
void QmitkPointListView::OnListViewSelectionChanged(const QItemSelection &selected,
const QItemSelection & /*deselected*/)
{
if (m_SelfCall)
return;
mitk::PointSet *pointSet = const_cast<mitk::PointSet *>(m_PointListModel->GetPointSet());
if (pointSet == nullptr)
return;
// (take care that this widget doesn't react to self-induced changes by setting m_SelfCall)
m_SelfCall = true;
// update selection of all points in pointset: select the one(s) that are selected in the view, deselect all others
QModelIndexList selectedIndexes = selected.indexes();
// only call setSelectInfo on a point set with 'selected = true' if you deselcted the other entries
int indexToSelect = -1;
for (mitk::PointSet::PointsContainer::Iterator it =
pointSet->GetPointSet(m_PointListModel->GetTimeStep())->GetPoints()->Begin();
it != pointSet->GetPointSet(m_PointListModel->GetTimeStep())->GetPoints()->End();
++it)
{
QModelIndex index;
if (m_PointListModel->GetModelIndexForPointID(it->Index(), index))
{
if (selectedIndexes.indexOf(index) != -1) // index is found in the selected indices list
{
indexToSelect = it->Index();
}
else
{
pointSet->SetSelectInfo(it->Index(), false, m_PointListModel->GetTimeStep());
}
}
}
// force selection of only one index after deselecting the others
if (indexToSelect > -1) {
pointSet->SetSelectInfo(indexToSelect, true, m_PointListModel->GetTimeStep());
mitk::Point3D p = pointSet->GetPoint(indexToSelect, m_PointListModel->GetTimeStep());
for (auto snc : m_Sncs)
snc->SelectSliceByPoint(p);
}
m_SelfCall = false;
emit SignalPointSelectionChanged();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkPointListView::keyPressEvent(QKeyEvent *e)
{
if (m_PointListModel == nullptr)
return;
int key = e->key();
switch (key)
{
case Qt::Key_F2:
m_PointListModel->MoveSelectedPointUp();
break;
case Qt::Key_F3:
m_PointListModel->MoveSelectedPointDown();
break;
case Qt::Key_Delete:
m_PointListModel->RemoveSelectedPoint();
break;
default:
break;
}
}
void QmitkPointListView::wheelEvent(QWheelEvent *event)
{
if (!m_PointListModel || !m_PointListModel->GetPointSet() ||
(int)(m_PointListModel->GetPointSet()->GetTimeSteps()) == 1)
return;
- int whe = event->delta();
+ int whe = event->angleDelta().y();
mitk::PointSet::Pointer ps = dynamic_cast<mitk::PointSet *>(m_PointListModel->GetPointSet());
unsigned int numberOfTS = ps->GetTimeSteps();
if (numberOfTS == 1)
return;
int currentTS = this->m_PointListModel->GetTimeStep();
if (whe > 0)
{
if ((currentTS + 1 >= (int)numberOfTS))
return;
this->m_PointListModel->SetTimeStep(++currentTS);
}
else
{
if ((currentTS <= 0))
return;
this->m_PointListModel->SetTimeStep(--currentTS);
}
QString tooltip = QString("Use the F2/F3 keys to move a point up/down, the Del key to remove a point\nand the mouse "
"wheel to change the timestep.\n\nTimeStep:\t%1")
.arg(currentTS);
this->setToolTip(tooltip);
emit SignalTimeStepChanged(currentTS);
}
void QmitkPointListView::ctxMenu(const QPoint &pos)
{
QMenu *menu = new QMenu;
// add Fading check
QAction *showFading = new QAction(this);
showFading->setCheckable(false); // TODO: reset when fading is working
showFading->setEnabled(false); // TODO: reset when fading is working
showFading->setText("Fade TimeStep");
connect(showFading, SIGNAL(triggered(bool)), this, SLOT(SetFading(bool)));
menu->addAction(showFading);
// add Clear action
QAction *clearList = new QAction(this);
clearList->setText("Clear List");
connect(clearList, SIGNAL(triggered()), this, SLOT(ClearPointList()));
menu->addAction(clearList);
// add Clear TimeStep action
QAction *clearTS = new QAction(this);
clearTS->setText("Clear current time step");
connect(clearTS, SIGNAL(triggered()), this, SLOT(ClearPointListTS()));
menu->addAction(clearTS);
menu->exec(this->mapToGlobal(pos));
}
void QmitkPointListView::SetFading(bool onOff)
{
m_showFading = onOff;
}
void QmitkPointListView::ClearPointList()
{
if (!m_PointListModel->GetPointSet())
return;
mitk::PointSet::Pointer curPS = m_PointListModel->GetPointSet();
if (curPS->GetSize() == 0)
return;
switch (QMessageBox::question(this,
tr("Clear Points"),
tr("Remove all points from the displayed list?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No))
{
case QMessageBox::Yes:
{
mitk::PointSet::PointsIterator it;
mitk::PointSet::PointsContainer *curPsPoints;
while (!curPS->IsEmptyTimeStep(0))
{
curPsPoints = curPS->GetPointSet()->GetPoints();
it = curPsPoints->Begin();
curPS->SetSelectInfo(it->Index(), true);
m_PointListModel->RemoveSelectedPoint();
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
break;
}
case QMessageBox::No:
default:
break;
}
}
void QmitkPointListView::ClearPointListTS()
{
}
void QmitkPointListView::AddSliceNavigationController(mitk::SliceNavigationController *snc)
{
if (snc == nullptr)
return;
m_Sncs.insert(snc);
}
void QmitkPointListView::RemoveSliceNavigationController(mitk::SliceNavigationController *snc)
{
if (snc == nullptr)
return;
m_Sncs.erase(snc);
}
diff --git a/Modules/QtWidgetsExt/src/QmitkSliceWidget.cpp b/Modules/QtWidgetsExt/src/QmitkSliceWidget.cpp
index 7cfbb790eb..c3ec916a01 100644
--- a/Modules/QtWidgetsExt/src/QmitkSliceWidget.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkSliceWidget.cpp
@@ -1,266 +1,266 @@
/*============================================================================
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 "QmitkSliceWidget.h"
#include "QmitkStepperAdapter.h"
#include "mitkCameraController.h"
#include "mitkImage.h"
#include "mitkNodePredicateDataType.h"
#include <QMenu>
#include <QMouseEvent>
#include <mitkCameraController.h>
#include <mitkProportionalTimeGeometry.h>
QmitkSliceWidget::QmitkSliceWidget(QWidget *parent, const char *name, Qt::WindowFlags f) : QWidget(parent, f)
{
this->setupUi(this);
if (name != nullptr)
this->setObjectName(name);
popUp = new QMenu(this);
popUp->addAction("Axial");
popUp->addAction("Coronal");
popUp->addAction("Sagittal");
QObject::connect(popUp, SIGNAL(triggered(QAction *)), this, SLOT(ChangeView(QAction *)));
setPopUpEnabled(false);
m_SlicedGeometry = nullptr;
m_View = mitk::AnatomicalPlane::Axial;
QHBoxLayout *hlayout = new QHBoxLayout(container);
- hlayout->setMargin(0);
+ hlayout->setContentsMargins({});
// create widget
QString composedName("QmitkSliceWidget::");
if (!this->objectName().isEmpty())
composedName += this->objectName();
else
composedName += "QmitkGLWidget";
m_RenderWindow = new QmitkRenderWindow(container, composedName);
m_Renderer = m_RenderWindow->GetRenderer();
hlayout->addWidget(m_RenderWindow);
new QmitkStepperAdapter(sliceNavigationWidget, m_RenderWindow->GetSliceNavigationController()->GetStepper());
SetLevelWindowEnabled(true);
}
mitk::VtkPropRenderer *QmitkSliceWidget::GetRenderer()
{
return m_Renderer;
}
QFrame *QmitkSliceWidget::GetSelectionFrame()
{
return SelectionFrame;
}
void QmitkSliceWidget::SetDataStorage(mitk::StandaloneDataStorage::Pointer storage)
{
m_DataStorage = storage;
m_Renderer->SetDataStorage(m_DataStorage);
}
mitk::StandaloneDataStorage *QmitkSliceWidget::GetDataStorage()
{
return m_DataStorage;
}
void QmitkSliceWidget::SetData(mitk::DataStorage::SetOfObjects::ConstIterator it)
{
SetData(it->Value(), m_View);
}
void QmitkSliceWidget::SetData(mitk::DataStorage::SetOfObjects::ConstIterator it,
mitk::AnatomicalPlane view)
{
SetData(it->Value(), view);
}
void QmitkSliceWidget::SetData(mitk::DataNode::Pointer node)
{
try
{
if (m_DataStorage.IsNotNull())
{
m_DataStorage->Add(node);
}
}
catch (...)
{
}
SetData(node, m_View);
}
void QmitkSliceWidget::SetData(mitk::DataNode::Pointer node, mitk::AnatomicalPlane view)
{
mitk::Image::Pointer image = dynamic_cast<mitk::Image *>(node->GetData());
if (image.IsNull())
{
MITK_WARN << "QmitkSliceWidget data is not an image!";
return;
}
m_SlicedGeometry = image->GetSlicedGeometry();
this->InitWidget(view);
}
void QmitkSliceWidget::InitWidget(mitk::AnatomicalPlane view)
{
m_View = view;
mitk::SliceNavigationController *controller = m_RenderWindow->GetSliceNavigationController();
if (view == mitk::AnatomicalPlane::Axial)
{
controller->SetViewDirection(mitk::AnatomicalPlane::Axial);
}
else if (view == mitk::AnatomicalPlane::Coronal)
{
controller->SetViewDirection(mitk::AnatomicalPlane::Coronal);
}
// init sagittal view for all other cases ('original' is covered here as well)
else
{
controller->SetViewDirection(mitk::AnatomicalPlane::Sagittal);
}
if (m_SlicedGeometry.IsNull())
{
return;
}
mitk::BaseGeometry::Pointer geometry = static_cast<mitk::BaseGeometry *>(m_SlicedGeometry->Clone().GetPointer());
const mitk::BoundingBox::Pointer boundingbox = m_DataStorage->ComputeVisibleBoundingBox(GetRenderer(), nullptr);
if (boundingbox->GetPoints()->Size() > 0)
{
// let's see if we have data with a limited live-span ...
mitk::TimeBounds timebounds = m_DataStorage->ComputeTimeBounds(GetRenderer(), nullptr);
mitk::ProportionalTimeGeometry::Pointer timeGeometry = mitk::ProportionalTimeGeometry::New();
timeGeometry->Initialize(geometry, 1);
{
timeGeometry->SetFirstTimePoint(timebounds[0]);
timeGeometry->SetStepDuration(1.0);
}
if (timeGeometry->GetBoundingBoxInWorld()->GetDiagonalLength2() >= mitk::eps)
{
controller->SetInputWorldTimeGeometry(timeGeometry);
controller->Update();
}
}
GetRenderer()->GetCameraController()->Fit();
mitk::RenderingManager::GetInstance()->RequestUpdate(GetRenderer()->GetRenderWindow());
}
void QmitkSliceWidget::UpdateGL()
{
GetRenderer()->GetCameraController()->Fit();
mitk::RenderingManager::GetInstance()->RequestUpdate(GetRenderer()->GetRenderWindow());
}
void QmitkSliceWidget::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::RightButton && popUpEnabled)
{
popUp->popup(QCursor::pos());
}
}
void QmitkSliceWidget::wheelEvent(QWheelEvent *e)
{
int val = sliceNavigationWidget->GetPos();
- if (e->orientation() * e->delta() > 0)
+ if (e->angleDelta().y() > 0)
{
sliceNavigationWidget->SetPos(val + 1);
}
else
{
if (val > 0)
sliceNavigationWidget->SetPos(val - 1);
}
}
void QmitkSliceWidget::ChangeView(QAction *val)
{
if (val->text() == "Axial")
{
InitWidget(mitk::AnatomicalPlane::Axial);
}
else if (val->text() == "Coronal")
{
InitWidget(mitk::AnatomicalPlane::Coronal);
}
else if (val->text() == "Sagittal")
{
InitWidget(mitk::AnatomicalPlane::Sagittal);
}
}
void QmitkSliceWidget::setPopUpEnabled(bool b)
{
popUpEnabled = b;
}
QmitkSliceNavigationWidget* QmitkSliceWidget::GetSliceNavigationWidget()
{
return sliceNavigationWidget;
}
void QmitkSliceWidget::SetLevelWindowEnabled(bool enable)
{
levelWindow->setEnabled(enable);
if (!enable)
{
levelWindow->setMinimumWidth(0);
levelWindow->setMaximumWidth(0);
}
else
{
levelWindow->setMinimumWidth(28);
levelWindow->setMaximumWidth(28);
}
}
bool QmitkSliceWidget::IsLevelWindowEnabled()
{
return levelWindow->isEnabled();
}
QmitkRenderWindow *QmitkSliceWidget::GetRenderWindow()
{
return m_RenderWindow;
}
mitk::SliceNavigationController *QmitkSliceWidget::GetSliceNavigationController() const
{
return m_RenderWindow->GetSliceNavigationController();
}
mitk::CameraRotationController *QmitkSliceWidget::GetCameraRotationController() const
{
return m_RenderWindow->GetCameraRotationController();
}
mitk::BaseController *QmitkSliceWidget::GetController() const
{
return m_RenderWindow->GetController();
}
diff --git a/Modules/QtWidgetsExt/src/QmitkStringPropertyOnDemandEdit.cpp b/Modules/QtWidgetsExt/src/QmitkStringPropertyOnDemandEdit.cpp
index 1a20f6a3e4..01f60032ba 100644
--- a/Modules/QtWidgetsExt/src/QmitkStringPropertyOnDemandEdit.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkStringPropertyOnDemandEdit.cpp
@@ -1,74 +1,74 @@
/*============================================================================
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 "QmitkStringPropertyOnDemandEdit.h"
#include <QInputDialog>
QmitkStringPropertyOnDemandEdit::QmitkStringPropertyOnDemandEdit(mitk::StringProperty *property, QWidget *parent)
: QFrame(parent), PropertyEditor(property), m_StringProperty(property)
{
setFrameStyle(QFrame::NoFrame);
setLineWidth(0);
// create HBoxLayout with two buttons
m_layout = new QHBoxLayout(this);
- m_layout->setMargin(0);
+ m_layout->setContentsMargins({});
m_label = new QLabel(this);
m_layout->addWidget(m_label);
m_toolbutton = new QClickableLabel2(this);
m_toolbutton->setText("...");
m_layout->addWidget(m_toolbutton);
m_layout->addStretch(10);
connect(m_toolbutton, SIGNAL(clicked()), this, SLOT(onToolButtonClicked()));
ensurePolished();
adjustSize();
PropertyChanged();
}
QmitkStringPropertyOnDemandEdit::~QmitkStringPropertyOnDemandEdit()
{
}
void QmitkStringPropertyOnDemandEdit::PropertyChanged()
{
if (m_Property)
m_label->setText(m_StringProperty->GetValue());
}
void QmitkStringPropertyOnDemandEdit::PropertyRemoved()
{
m_Property = nullptr;
m_StringProperty = nullptr;
m_label->setText("n/a");
}
void QmitkStringPropertyOnDemandEdit::onToolButtonClicked()
{
bool ok(false);
QString newText = QInputDialog::getText(
this, "Change text", "You can change the displayed text here", QLineEdit::Normal, m_label->text(), &ok);
if (ok)
{
BeginModifyProperty(); // deregister from events
m_StringProperty->SetValue(newText.toStdString());
m_label->setText(newText);
EndModifyProperty(); // again register for events
}
}
diff --git a/Modules/QtWidgetsExt/src/QmitkTransferFunctionCanvas.cpp b/Modules/QtWidgetsExt/src/QmitkTransferFunctionCanvas.cpp
index b71f2fb889..7e68f1c758 100755
--- a/Modules/QtWidgetsExt/src/QmitkTransferFunctionCanvas.cpp
+++ b/Modules/QtWidgetsExt/src/QmitkTransferFunctionCanvas.cpp
@@ -1,232 +1,234 @@
/*============================================================================
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 "QmitkTransferFunctionCanvas.h"
#include <itkObject.h>
#include <QColorDialog>
#include <QMouseEvent>
#include <QPainter>
QmitkTransferFunctionCanvas::QmitkTransferFunctionCanvas(QWidget *parent, Qt::WindowFlags f)
: QWidget(parent, f),
m_GrabbedHandle(-1),
m_Lower(0.0),
m_Upper(1.0),
m_Min(0.0),
m_Max(1.0),
m_Histogram(nullptr),
m_ImmediateUpdate(false),
m_Range(0.0f),
m_LineEditAvailable(false),
m_XEdit(nullptr),
m_YEdit(nullptr)
{
setEnabled(false);
setFocusPolicy(Qt::ClickFocus);
}
void QmitkTransferFunctionCanvas::paintEvent(QPaintEvent *ev)
{
QWidget::paintEvent(ev);
}
std::pair<int, int> QmitkTransferFunctionCanvas::FunctionToCanvas(std::pair<double, double> functionPoint)
{
return std::make_pair(
(int)((functionPoint.first - m_Lower) / (m_Upper - m_Lower) * contentsRect().width()) + contentsRect().x(),
(int)(contentsRect().height() * (1 - functionPoint.second)) + contentsRect().y());
}
std::pair<double, double> QmitkTransferFunctionCanvas::CanvasToFunction(std::pair<int, int> canvasPoint)
{
return std::make_pair(
(canvasPoint.first - contentsRect().x()) * (m_Upper - m_Lower) / contentsRect().width() + m_Lower,
1.0 - (double)(canvasPoint.second - contentsRect().y()) / contentsRect().height());
}
void QmitkTransferFunctionCanvas::mouseDoubleClickEvent(QMouseEvent *mouseEvent)
{
int nearHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());
if (nearHandle != -1)
{
this->DoubleClickOnHandle(nearHandle);
}
}
/** returns index of a near handle or -1 if none is near
*/
int QmitkTransferFunctionCanvas::GetNearHandle(int, int, unsigned int)
{
return -1;
}
void QmitkTransferFunctionCanvas::mousePressEvent(QMouseEvent *mouseEvent)
{
if (m_LineEditAvailable)
{
m_XEdit->clear();
if (m_YEdit)
m_YEdit->clear();
}
- m_GrabbedHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());
+ const auto pos = mouseEvent->position().toPoint();
+ m_GrabbedHandle = GetNearHandle(pos.x(), pos.y());
if ((mouseEvent->button() & Qt::LeftButton) && m_GrabbedHandle == -1)
{
- this->AddFunctionPoint(this->CanvasToFunction(std::make_pair(mouseEvent->pos().x(), mouseEvent->pos().y())).first,
- this->CanvasToFunction(std::make_pair(mouseEvent->x(), mouseEvent->y())).second);
- m_GrabbedHandle = GetNearHandle(mouseEvent->pos().x(), mouseEvent->pos().y());
+ auto [x, value] = this->CanvasToFunction(std::make_pair(pos.x(), pos.y()));
+ this->AddFunctionPoint(x, value);
+ m_GrabbedHandle = GetNearHandle(pos.x(), pos.y());
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if ((mouseEvent->button() & Qt::RightButton) && m_GrabbedHandle != -1 && this->GetFunctionSize() > 1)
{
this->RemoveFunctionPoint(this->GetFunctionX(m_GrabbedHandle));
m_GrabbedHandle = -1;
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
update();
}
void QmitkTransferFunctionCanvas::mouseMoveEvent(QMouseEvent *mouseEvent)
{
if (m_GrabbedHandle != -1)
{
- std::pair<double, double> newPos = this->CanvasToFunction(std::make_pair(mouseEvent->x(), mouseEvent->y()));
+ const auto pos = mouseEvent->position().toPoint();
+ std::pair<double, double> newPos = this->CanvasToFunction(std::make_pair(pos.x(), pos.y()));
// X Clamping
{
// Check with predecessor
if (m_GrabbedHandle > 0)
if (newPos.first <= this->GetFunctionX(m_GrabbedHandle - 1))
newPos.first = this->GetFunctionX(m_GrabbedHandle);
// Check with sucessor
if (m_GrabbedHandle < this->GetFunctionSize() - 1)
if (newPos.first >= this->GetFunctionX(m_GrabbedHandle + 1))
newPos.first = this->GetFunctionX(m_GrabbedHandle);
// Clamping to histogramm
if (newPos.first < m_Min)
newPos.first = m_Min;
else if (newPos.first > m_Max)
newPos.first = m_Max;
}
// Y Clamping
{
if (newPos.second < 0.0)
newPos.second = 0.0;
else if (newPos.second > 1.0)
newPos.second = 1.0;
}
// Move selected point
this->MoveFunctionPoint(m_GrabbedHandle, newPos);
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkTransferFunctionCanvas::mouseReleaseEvent(QMouseEvent *)
{
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkTransferFunctionCanvas::PaintHistogram(QPainter &p)
{
if (m_Histogram)
{
p.save();
p.setPen(Qt::gray);
int displayWidth = contentsRect().width();
int displayHeight = contentsRect().height();
double windowLeft = m_Lower;
double windowRight = m_Upper;
double step = (windowRight - windowLeft) / double(displayWidth);
double pos = windowLeft;
for (int x = 0; x < displayWidth; x++)
{
double left = pos;
double right = pos + step;
float height = m_Histogram->GetRelativeBin(left, right);
if (height >= 0)
p.drawLine(x, displayHeight * (1 - height), x, displayHeight);
pos += step;
}
p.restore();
}
}
void QmitkTransferFunctionCanvas::keyPressEvent(QKeyEvent *e)
{
if (m_GrabbedHandle == -1)
return;
switch (e->key())
{
case Qt::Key_Delete:
if (this->GetFunctionSize() > 1)
{
this->RemoveFunctionPoint(GetFunctionX(m_GrabbedHandle));
m_GrabbedHandle = -1;
}
break;
case Qt::Key_Left:
this->MoveFunctionPoint(
m_GrabbedHandle,
ValidateCoord(std::make_pair(GetFunctionX(m_GrabbedHandle) - 1, GetFunctionY(m_GrabbedHandle))));
break;
case Qt::Key_Right:
this->MoveFunctionPoint(
m_GrabbedHandle,
ValidateCoord(std::make_pair(GetFunctionX(m_GrabbedHandle) + 1, GetFunctionY(m_GrabbedHandle))));
break;
case Qt::Key_Up:
this->MoveFunctionPoint(
m_GrabbedHandle,
ValidateCoord(std::make_pair(GetFunctionX(m_GrabbedHandle), GetFunctionY(m_GrabbedHandle) + 0.001)));
break;
case Qt::Key_Down:
this->MoveFunctionPoint(
m_GrabbedHandle,
ValidateCoord(std::make_pair(GetFunctionX(m_GrabbedHandle), GetFunctionY(m_GrabbedHandle) - 0.001)));
break;
}
update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
// Update immediatly while changing the transfer function
void QmitkTransferFunctionCanvas::SetImmediateUpdate(bool state)
{
m_ImmediateUpdate = state;
}
diff --git a/Modules/REST/documentation/REST.dox b/Modules/REST/documentation/REST.dox
index 3743001a47..93cfd5a122 100644
--- a/Modules/REST/documentation/REST.dox
+++ b/Modules/REST/documentation/REST.dox
@@ -1,194 +1,194 @@
/**
\page RESTModule REST Module
\tableofcontents
\section REST_brief Description
The MITK REST Module is able to manage REST requests. The main class is the RESTManager.
It is a MicroServices which can be accessed via
\code{.cpp}
auto *context = us::GetModuleContext();
auto managerRef = context->GetServiceReference<IRESTManager>();
if (managerRef)
{
auto managerService = context->GetService(managerRef);
if (managerService)
{
//call the function you need from the service
}
}
\endcode
\subsection REST_Technical Technical background
The module uses the <a href="https://github.com/Microsoft/cpprestsdk">Microsoft C++ REST SDK</a> for REST mechanisms as well as JSON convertion and asynchronic programming.
\section Use_REST How to use the REST Module
You can use the REST module from two different perspectives in MITK:
<ol>
<li> The Server view (receive requests from clients)
<li> The Client view (send requests to servers)
</ol>
The following sections will give you an introduction on how to use which of those roles:
\subsection Server_Use Use from a Server perspective
To act as a server, you need to implement the <code>IRESTObserver</code>, which has a <code>Notify()</code> method that has to be implemented.
In this <code>Notify()</code> method you specify how you want to react to incoming requests and with which data you want to respond to the requests.
You can then start listening for requests from clients as shown below:
\code{.cpp}
auto *context = us::GetModuleContext();
auto managerRef = context->GetServiceReference<IRESTManager>();
if (managerRef)
{
auto managerService = context->GetService(managerRef);
if (managerService)
{
managerService->ReceiveRequests(uri /*specify your uri which you want to receive requests for*/, this);
}
}
\endcode
If a client sends a request, the Notify method is called and a response is sent. By now, only GET-requests from clients are supported.
If you want to stop listening for requests you can do this by calling
\code{.cpp}
auto *context = us::GetModuleContext();
auto managerRef = context->GetServiceReference<IRESTManager>();
if (managerRef)
{
auto managerService = context->GetService(managerRef);
if (managerService)
{
managerService->HandleDeleteObserver(this, uri);
}
}
\endcode
You don't have to specify a uri in the HandleDeleteObserver method, if you only call <code>managerService->HandleDeleteObserver(this);</code>, all uris you receive requests for are deleted and you aren't listening to any requests anymore.
\subsection Client_Use Use from a Client perspective
The following example shows how to send requests from a client perspective:
\code{.cpp}
//Get the microservice
auto *context = us::ModuleRegistry::GetModule(1)->GetModuleContext();
auto managerRef = context->GetServiceReference<mitk::IRESTManager>();
if (managerRef)
{
auto managerService = context->GetService(managerRef);
if (managerService)
{
//Call the send request method which starts the actual request
managerService
->SendRequest(U("https://jsonplaceholder.typicode.com/posts/1"))
.then([=](pplx::task<web::json::value> resultTask)/*It is important to use task-based continuation*/ {
try
{
//Get the result of the request
//This will throw an exception if the ascendent task threw an exception (e.g. invalid URI)
web::json::value result = resultTask.get();
//Do something with the result (e.g. convert it to a QString to update an UI element)
utility::string_t stringT = result.to_string();
std::string stringStd(stringT.begin(), stringT.end());
QString stringQ = QString::fromStdString(stringStd);
//Note: if you want to update your UI, do this by using signals and slots.
//The UI can't be updated from a Thread different to the Qt main thread
emit UpdateLabel(stringQ);
}
catch (const mitk::Exception &exception)
{
//Exceptions from ascendent tasks are catched here
MITK_ERROR << exception.what();
return;
}
});
}
}
\endcode
The steps you need to make are the following:
<ol>
<li> Get the microservice. You can get the microservice via the module context. If you want to use the microservice within a plug-in, you need to get the module context from the <code>us::ModuleRegistry</code>.
<li> Call the <code>SendRequest</code> method. This will start the request itself and is performed asynchronously. As soon as the response is sent by the server, the <code>.then(...)</code> block is executed.
<li> Choose parameters for <code>.then(...)</code> block. For exception handling, it is important to choose <code>pplx::task<web::json::value> </code>. This is a task-based continuation.
For more information, visit https://docs.microsoft.com/en-us/cpp/parallel/concrt/exception-handling-in-the-concurrency-runtime?view=vs-2017.
<li> Get the result of the request. You can get the JSON-value of the result by callint <code>.get()</code>. At this point, an exception is thrown if something in the previous tasks threw an exception.
<li> Do something with the result.
\note If you want to modify GUI elements within the <code>.then(...)</code> block, you need to do this by using signals and slots because GUI elements can only be modified by th Qt Main Thread.
- For more information, visit https://doc.qt.io/Qt-5/thread-basics.html#gui-thread-and-worker-thread
+ For more information, visit https://doc.qt.io/qt-6/thread-basics.html#gui-thread-and-worker-thread
<li> Exception handling. Here you can define the behaviour if an exception is thrown, exceptions from ascendent tasks are also catched here.
</ol>
Code, which is followed by this codeblock shown above will be performed asynchronously while waiting for the result.
Besides Get-Requests, you can also perform Put or Post requests by specifying a <code>RequestType</code> in the <code>SendRequest</code> method.
The following example shows, how you can perform multiple tasks, encapsulated to one joined task. The steps are based on the example for one request and only the specific steps for encapsulation are described.
\code{.cpp}
//Get the microservice
//Get microservice
auto *context = us::ModuleRegistry::GetModule(1)->GetModuleContext();
auto managerRef = context->GetServiceReference<mitk::IRESTManager>();
if (managerRef)
{
auto managerService = context->GetService(managerRef);
if (managerService)
{
//Create multiple tasks e.g. as shown below
std::vector<pplx::task<void>> tasks;
for (int i = 0; i < 20; i++)
{
pplx::task<void> singleTask = managerService->SendRequest(L"https://jsonplaceholder.typicode.com/posts/1")
.then([=](pplx::task<web::json::value> resultTask) {
//Do something when a single task is done
try
{
resultTask.get();
emit UpdateProgressBar();
}
catch (const mitk::Exception &exception)
{
MITK_ERROR << exception.what();
return;
}
});
tasks.emplace_back(singleTask);
}
//Create a joinTask which includes all tasks you've created
auto joinTask = pplx::when_all(begin(tasks), end(tasks));
//Run asynchonously
joinTask.then([=](pplx::task<void> resultTask) {
//Do something when all tasks are finished
try
{
resultTask.get();
emit UpdateLabel("All tasks finished");
}
catch (const mitk::Exception &exception)
{
MITK_ERROR << exception.what();
return;
}
});
}
\endcode
The steps you need to make are the following:
<ol>
<li> Get the microservice. See example above.
<li> Create multiple tasks. In this example, 20 identical tasks are created and are saved into a vector. In general, it is possible to place any tasks in that vector.
<li> Do something when a single task is done. Here, an action is performed if a single tasks is finished. In this example, a progress bar is loaded by a specific number of percent.
<li> Create a joinTask. Here, all small tasks are encapsulated in one big task.
<li> Run joinTask asynchonously. The <code>then(...)</code> of the joinTask is performed when all single tasks are finished.
<li> Do something when all tasks are finished. The handling of the end of a joinTask is equivalent to the end of a single tasks.
</ol>
*/
diff --git a/Modules/RTUI/CMakeLists.txt b/Modules/RTUI/CMakeLists.txt
index 148b6682b9..ce48fc3157 100644
--- a/Modules/RTUI/CMakeLists.txt
+++ b/Modules/RTUI/CMakeLists.txt
@@ -1,7 +1,7 @@
MITK_CREATE_MODULE(
INCLUDE_DIRS Qmitk Helper
DEPENDS MitkRT
PACKAGE_DEPENDS
- PUBLIC Qt5|Widgets
+ PUBLIC Qt6|Widgets
PRIVATE CTK|CTKWidgets
)
diff --git a/Modules/RenderWindowManagerUI/CMakeLists.txt b/Modules/RenderWindowManagerUI/CMakeLists.txt
index 01d4a01d6d..a0fd130a47 100644
--- a/Modules/RenderWindowManagerUI/CMakeLists.txt
+++ b/Modules/RenderWindowManagerUI/CMakeLists.txt
@@ -1,4 +1,4 @@
MITK_CREATE_MODULE(
DEPENDS MitkQtWidgets
- PACKAGE_DEPENDS PUBLIC Qt5|Core
+ PACKAGE_DEPENDS PUBLIC Qt6|Core
)
diff --git a/Modules/RenderWindowManagerUI/src/QmitkRenderWindowDataStorageInspector.cpp b/Modules/RenderWindowManagerUI/src/QmitkRenderWindowDataStorageInspector.cpp
index f489241706..738ba84f87 100644
--- a/Modules/RenderWindowManagerUI/src/QmitkRenderWindowDataStorageInspector.cpp
+++ b/Modules/RenderWindowManagerUI/src/QmitkRenderWindowDataStorageInspector.cpp
@@ -1,142 +1,142 @@
/*============================================================================
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.
============================================================================*/
// render window manager UI module
#include "QmitkRenderWindowDataStorageInspector.h"
#include "QmitkCustomVariants.h"
// mitk core
#include <mitkBaseRenderer.h>
// qt
#include <QSignalMapper>
QmitkRenderWindowDataStorageInspector::QmitkRenderWindowDataStorageInspector(QWidget* parent /*=nullptr*/)
: QmitkAbstractDataStorageInspector(parent)
{
m_Controls.setupUi(this);
// initialize the render window layer controller and the render window view direction controller
m_RenderWindowLayerController = std::make_unique<mitk::RenderWindowLayerController>();
m_RenderWindowViewDirectionController = std::make_unique<mitk::RenderWindowViewDirectionController>();
m_StorageModel = std::make_unique<QmitkRenderWindowDataStorageTreeModel>(this);
m_Controls.renderWindowTreeView->setModel(m_StorageModel.get());
m_Controls.renderWindowTreeView->setHeaderHidden(true);
m_Controls.renderWindowTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_Controls.renderWindowTreeView->setSelectionBehavior(QAbstractItemView::SelectRows);
m_Controls.renderWindowTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_Controls.renderWindowTreeView->setAlternatingRowColors(true);
m_Controls.renderWindowTreeView->setDragEnabled(true);
m_Controls.renderWindowTreeView->setDropIndicatorShown(true);
m_Controls.renderWindowTreeView->setAcceptDrops(true);
m_Controls.renderWindowTreeView->setContextMenuPolicy(Qt::CustomContextMenu);
SetUpConnections();
}
QAbstractItemView* QmitkRenderWindowDataStorageInspector::GetView()
{
return m_Controls.renderWindowTreeView;
}
const QAbstractItemView* QmitkRenderWindowDataStorageInspector::GetView() const
{
return m_Controls.renderWindowTreeView;
}
void QmitkRenderWindowDataStorageInspector::SetSelectionMode(SelectionMode mode)
{
m_Controls.renderWindowTreeView->setSelectionMode(mode);
}
QmitkRenderWindowDataStorageInspector::SelectionMode QmitkRenderWindowDataStorageInspector::GetSelectionMode() const
{
return m_Controls.renderWindowTreeView->selectionMode();
}
void QmitkRenderWindowDataStorageInspector::Initialize()
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNull())
return;
m_StorageModel->SetDataStorage(dataStorage);
m_StorageModel->SetNodePredicate(m_NodePredicate);
m_RenderWindowLayerController->SetDataStorage(dataStorage);
m_RenderWindowViewDirectionController->SetDataStorage(dataStorage);
m_Connector->SetView(m_Controls.renderWindowTreeView);
}
void QmitkRenderWindowDataStorageInspector::SetUpConnections()
{
connect(m_StorageModel.get(), &QAbstractItemModel::rowsInserted, this, &QmitkRenderWindowDataStorageInspector::ModelRowsInserted);
QSignalMapper* changeViewDirectionSignalMapper = new QSignalMapper(this);
changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonAxial, QString("axial"));
changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonCoronal, QString("coronal"));
changeViewDirectionSignalMapper->setMapping(m_Controls.radioButtonSagittal, QString("sagittal"));
changeViewDirectionSignalMapper->setMapping(m_Controls.radioButton3D, QString("3D"));
- connect(changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)(const QString&)>(&QSignalMapper::mapped), this, &QmitkRenderWindowDataStorageInspector::ChangeViewDirection);
+ connect(changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)(const QString&)>(&QSignalMapper::mappedString), this, &QmitkRenderWindowDataStorageInspector::ChangeViewDirection);
connect(m_Controls.radioButtonAxial, &QRadioButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map));
connect(m_Controls.radioButtonCoronal, &QRadioButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map));
connect(m_Controls.radioButtonSagittal, &QRadioButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map));
connect(m_Controls.radioButton3D, &QRadioButton::clicked, changeViewDirectionSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map));
}
void QmitkRenderWindowDataStorageInspector::SetControlledRenderer(mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer)
{
m_StorageModel->SetControlledRenderer(controlledRenderer);
m_RenderWindowViewDirectionController->SetControlledRenderer(controlledRenderer);
}
void QmitkRenderWindowDataStorageInspector::SetActiveRenderWindow(const QString& renderWindowId)
{
mitk::BaseRenderer* selectedRenderer = mitk::BaseRenderer::GetByName(renderWindowId.toStdString());
if (nullptr == selectedRenderer)
{
return;
}
m_StorageModel->SetCurrentRenderer(selectedRenderer);
mitk::AnatomicalPlane viewDirection = selectedRenderer->GetSliceNavigationController()->GetDefaultViewDirection();
switch (viewDirection)
{
case mitk::AnatomicalPlane::Axial:
m_Controls.radioButtonAxial->setChecked(true);
break;
case mitk::AnatomicalPlane::Coronal:
m_Controls.radioButtonCoronal->setChecked(true);
break;
case mitk::AnatomicalPlane::Sagittal:
m_Controls.radioButtonSagittal->setChecked(true);
break;
default:
break;
}
}
void QmitkRenderWindowDataStorageInspector::ModelRowsInserted(const QModelIndex& parent, int /*start*/, int /*end*/)
{
m_Controls.renderWindowTreeView->setExpanded(parent, true);
}
void QmitkRenderWindowDataStorageInspector::ChangeViewDirection(const QString& viewDirection)
{
m_RenderWindowViewDirectionController->SetViewDirectionOfRenderer(viewDirection.toStdString(), m_StorageModel->GetCurrentRenderer());
}
diff --git a/Modules/RenderWindowManagerUI/src/QmitkRenderWindowDataStorageListModel.cpp b/Modules/RenderWindowManagerUI/src/QmitkRenderWindowDataStorageListModel.cpp
index efba98a992..0859779c25 100644
--- a/Modules/RenderWindowManagerUI/src/QmitkRenderWindowDataStorageListModel.cpp
+++ b/Modules/RenderWindowManagerUI/src/QmitkRenderWindowDataStorageListModel.cpp
@@ -1,350 +1,352 @@
/*============================================================================
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.
============================================================================*/
// render window manager UI module
#include "QmitkRenderWindowDataStorageListModel.h"
// qt widgets module
#include "QmitkCustomVariants.h"
#include "QmitkEnums.h"
#include "QmitkMimeTypes.h"
#include "QmitkNodeDescriptorManager.h"
+#include <QIODevice>
+
QmitkRenderWindowDataStorageListModel::QmitkRenderWindowDataStorageListModel(QObject* parent /*= nullptr*/)
: QmitkAbstractDataStorageModel(parent)
{
m_RenderWindowLayerController = std::make_unique<mitk::RenderWindowLayerController>();
}
void QmitkRenderWindowDataStorageListModel::DataStorageChanged()
{
m_RenderWindowLayerController->SetDataStorage(m_DataStorage.Lock());
UpdateModelData();
}
void QmitkRenderWindowDataStorageListModel::NodePredicateChanged()
{
UpdateModelData();
}
void QmitkRenderWindowDataStorageListModel::NodeAdded(const mitk::DataNode* node)
{
// add a node to each render window specific list (or to a global list initially)
AddDataNodeToAllRenderer(const_cast<mitk::DataNode*>(node));
UpdateModelData();
}
void QmitkRenderWindowDataStorageListModel::NodeChanged(const mitk::DataNode* /*node*/)
{
// nothing here, since the "'NodeChanged'-event is currently sent far too often
}
void QmitkRenderWindowDataStorageListModel::NodeRemoved(const mitk::DataNode* /*node*/)
{
// update model data to create a new list without the removed data node
UpdateModelData();
}
QModelIndex QmitkRenderWindowDataStorageListModel::index(int row, int column, const QModelIndex& parent) const
{
bool hasIndex = this->hasIndex(row, column, parent);
if (hasIndex)
{
return this->createIndex(row, column);
}
return QModelIndex();
}
QModelIndex QmitkRenderWindowDataStorageListModel::parent(const QModelIndex& /*child*/) const
{
return QModelIndex();
}
int QmitkRenderWindowDataStorageListModel::rowCount(const QModelIndex& parent /*= QModelIndex()*/) const
{
if (parent.isValid())
{
return 0;
}
return static_cast<int>(m_LayerStack.size());
}
int QmitkRenderWindowDataStorageListModel::columnCount(const QModelIndex& parent /*= QModelIndex()*/) const
{
if (parent.isValid())
{
return 0;
}
return 1;
}
QVariant QmitkRenderWindowDataStorageListModel::data(const QModelIndex& index, int role) const
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNull())
{
return QVariant();
}
if (!index.isValid() || this != index.model())
{
return QVariant();
}
if (index.row() < 0 || index.row() >= static_cast<int>(m_LayerStack.size()))
{
return QVariant();
}
mitk::RenderWindowLayerUtilities::LayerStack::const_iterator layerStackIt = m_LayerStack.begin();
std::advance(layerStackIt, index.row());
mitk::DataNode* dataNode = layerStackIt->second;
if (Qt::CheckStateRole == role)
{
bool visibility = false;
dataNode->GetVisibility(visibility, baseRenderer);
if (visibility)
{
return Qt::Checked;
}
else
{
return Qt::Unchecked;
}
}
else if (Qt::DisplayRole == role)
{
return QVariant(QString::fromStdString(dataNode->GetName()));
}
else if (Qt::ToolTipRole == role)
{
return QVariant("Name of the data node.");
}
else if (Qt::DecorationRole == role)
{
QmitkNodeDescriptor* nodeDescriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(dataNode);
return nodeDescriptor->GetIcon(dataNode);
}
else if (Qt::UserRole == role || QmitkDataNodeRawPointerRole == role)
{
// user role always returns a reference to the data node,
// which can be used to modify the data node in the data storage
return QVariant::fromValue<mitk::DataNode*>(dataNode);
}
else if (QmitkDataNodeRole == role)
{
return QVariant::fromValue<mitk::DataNode::Pointer>(mitk::DataNode::Pointer(dataNode));
}
return QVariant();
}
bool QmitkRenderWindowDataStorageListModel::setData(const QModelIndex& index, const QVariant& value, int role /*= Qt::EditRole*/)
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNull())
{
return false;
}
if (!index.isValid() || this != index.model())
{
return false;
}
if (index.row() < 0 || index.row() >= static_cast<int>(m_LayerStack.size()))
{
return false;
}
mitk::RenderWindowLayerUtilities::LayerStack::const_iterator layerStackIt = m_LayerStack.begin();
std::advance(layerStackIt, index.row());
mitk::DataNode* dataNode = layerStackIt->second;
if (Qt::CheckStateRole == role)
{
Qt::CheckState newCheckState = static_cast<Qt::CheckState>(value.toInt());
bool isVisible = newCheckState;
dataNode->SetVisibility(isVisible, baseRenderer);
emit dataChanged(index, index);
mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow());
return true;
}
return false;
}
Qt::ItemFlags QmitkRenderWindowDataStorageListModel::flags(const QModelIndex &index) const
{
if (this != index.model())
{
return Qt::NoItemFlags;
}
if (!index.isValid())
{
return Qt::ItemIsDropEnabled;
}
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
}
Qt::DropActions QmitkRenderWindowDataStorageListModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
Qt::DropActions QmitkRenderWindowDataStorageListModel::supportedDragActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
QStringList QmitkRenderWindowDataStorageListModel::mimeTypes() const
{
QStringList types = QAbstractItemModel::mimeTypes();
types << QmitkMimeTypes::DataNodePtrs;
return types;
}
QMimeData* QmitkRenderWindowDataStorageListModel::mimeData(const QModelIndexList& indexes) const
{
QMimeData* mimeData = new QMimeData();
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
for (const auto& index : indexes)
{
if (index.isValid())
{
auto dataNode = data(index, QmitkDataNodeRawPointerRole).value<mitk::DataNode*>();
stream << reinterpret_cast<quintptr>(dataNode);
}
}
mimeData->setData(QmitkMimeTypes::DataNodePtrs, encodedData);
return mimeData;
}
bool QmitkRenderWindowDataStorageListModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int /*row*/, int column, const QModelIndex& parent)
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNull())
{
return false;
}
if (action == Qt::IgnoreAction)
{
return true;
}
if (!data->hasFormat(QmitkMimeTypes::DataNodePtrs))
{
return false;
}
if (column > 0)
{
return false;
}
if (parent.isValid())
{
int layer = -1;
auto dataNode = this->data(parent, QmitkDataNodeRawPointerRole).value<mitk::DataNode*>();
if (nullptr != dataNode)
{
dataNode->GetIntProperty("layer", layer, baseRenderer);
}
auto dataNodeList = QmitkMimeTypes::ToDataNodePtrList(data);
- for (const auto& dataNode : qAsConst(dataNodeList))
+ for (const auto& dataNode : std::as_const(dataNodeList))
{
m_RenderWindowLayerController->MoveNodeToPosition(dataNode, layer, baseRenderer);
}
UpdateModelData();
return true;
}
return false;
}
void QmitkRenderWindowDataStorageListModel::SetControlledRenderer(mitk::RenderWindowLayerUtilities::RendererVector /*controlledRenderer*/)
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNotNull())
{
mitk::DataStorage::SetOfObjects::ConstPointer allDataNodes = dataStorage->GetAll();
for (mitk::DataStorage::SetOfObjects::ConstIterator it = allDataNodes->Begin(); it != allDataNodes->End(); ++it)
{
mitk::DataNode::Pointer dataNode = it->Value();
if (dataNode.IsNull())
{
continue;
}
AddDataNodeToAllRenderer(dataNode);
}
}
}
void QmitkRenderWindowDataStorageListModel::SetCurrentRenderer(mitk::BaseRenderer* baseRenderer)
{
if (m_BaseRenderer == baseRenderer)
{
return;
}
m_BaseRenderer = baseRenderer;
if (!m_BaseRenderer.IsExpired())
{
UpdateModelData();
}
}
mitk::BaseRenderer::Pointer QmitkRenderWindowDataStorageListModel::GetCurrentRenderer() const
{
return m_BaseRenderer.Lock();
}
void QmitkRenderWindowDataStorageListModel::AddDataNodeToAllRenderer(mitk::DataNode* dataNode)
{
m_RenderWindowLayerController->InsertLayerNode(dataNode);
}
void QmitkRenderWindowDataStorageListModel::UpdateModelData()
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNotNull())
{
auto baseRenderer = m_BaseRenderer.Lock();
if (baseRenderer.IsNotNull())
{
// update the model, so that it will be filled with the nodes of the new data storage
beginResetModel();
// get the current layer stack of the given base renderer
m_LayerStack = mitk::RenderWindowLayerUtilities::GetLayerStack(dataStorage, baseRenderer);
endResetModel();
}
}
}
diff --git a/Modules/Segmentation/Interactions/mitkSegmentAnythingTool.h b/Modules/Segmentation/Interactions/mitkSegmentAnythingTool.h
index a200b2c09b..5385dca185 100644
--- a/Modules/Segmentation/Interactions/mitkSegmentAnythingTool.h
+++ b/Modules/Segmentation/Interactions/mitkSegmentAnythingTool.h
@@ -1,217 +1,216 @@
/*============================================================================
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 mitkSegmentAnythingTool_h
#define mitkSegmentAnythingTool_h
#include "mitkSegWithPreviewTool.h"
#include "mitkPointSet.h"
#include "mitkProcessExecutor.h"
#include "mitkSegmentAnythingPythonService.h"
#include <MitkSegmentationExports.h>
#include <itkImage.h>
#include <mitkLevelWindow.h>
namespace us
{
class ModuleResource;
}
namespace mitk
{
/**
\brief Segment Anything Model interactive 2D tool class.
\ingroup ToolManagerEtAl
\sa mitk::Tool
\sa QmitkInteractiveSegmentation
*/
class MITKSEGMENTATION_EXPORT SegmentAnythingTool : public SegWithPreviewTool
{
public:
mitkClassMacro(SegmentAnythingTool, SegWithPreviewTool);
itkFactorylessNewMacro(Self);
itkCloneMacro(Self);
const char **GetXPM() const override;
const char *GetName() const override;
us::ModuleResource GetIconResource() const override;
void Activated() override;
void Deactivated() override;
/**
* @brief Clears all picks and updates the preview.
*/
void ClearPicks();
/**
* @brief Checks if any point exists in the either
* of the pointsets
*
* @return bool
*/
bool HasPicks() const;
itkSetMacro(MitkTempDir, std::string);
itkGetConstMacro(MitkTempDir, std::string);
itkSetMacro(PythonPath, std::string);
itkGetConstMacro(PythonPath, std::string);
itkSetMacro(ModelType, std::string);
itkGetConstMacro(ModelType, std::string);
itkSetMacro(CheckpointPath, std::string);
itkGetConstMacro(CheckpointPath, std::string);
itkSetMacro(GpuId, int);
itkGetConstMacro(GpuId, int);
itkSetMacro(TimeOutLimit, long);
itkGetConstMacro(TimeOutLimit, long);
itkSetMacro(IsReady, bool);
itkGetConstMacro(IsReady, bool);
itkBooleanMacro(IsReady);
/**
* @brief Initializes python service and
* starts async python daemon of SegmentAnything model.
*
*/
void InitSAMPythonProcess();
/**
* @brief Checks if Python daemon is ready to accept inputs.
*
* @return bool
*/
bool IsPythonReady() const;
Message1<const std::string&> SAMStatusMessageEvent;
protected:
SegmentAnythingTool();
~SegmentAnythingTool() = default;
void ConnectActionsAndFunctions() override;
/*
* @brief Add positive seed point action of StateMachine pattern
*/
virtual void OnAddPositivePoint(StateMachineAction*, InteractionEvent *interactionEvent);
/*
* @brief Add negative seed point action of StateMachine pattern
*/
virtual void OnAddNegativePoint(StateMachineAction*, InteractionEvent *interactionEvent);
/*
* @brief Delete action of StateMachine pattern. The function deletes positive or negative points in
the reverse order of creation. This is done by finding & deleting the Point having the highest
PointIdentifier value from either of the PointSets m_PointSetPositive & m_PointSetNegative.
*/
virtual void OnDelete(StateMachineAction*, InteractionEvent*);
/*
* @brief Clear all seed points and call UpdatePreview to reset the segmentation Preview
*/
void ClearSeeds();
/**
* @brief Overriden method from the tool manager to execute the segmentation
* Implementation:
* 1. Creates Hash for input image from current plane geometry.
* 2. Transfers image pointer to python service along with the hash code.
* 3. Creates seed points as CSV string & transfers to python service
* 3. Retrieves resulting segmentation Image pointer from python service and sets to previewImage.
*
* @param inputAtTimeStep
* @param oldSegAtTimeStep
* @param previewImage
* @param timeStep
*/
void DoUpdatePreview(const Image *inputAtTimeStep, const Image *oldSegAtTimeStep, LabelSetImage *previewImage, TimeStepType timeStep) override;
/**
* @brief Get the Points from positive and negative pointsets as std::vector.
*
- * @param baseGeometry of Image
* @return std::vector<std::pair<mitk::Point2D, std::string>>
*/
std::vector<std::pair<mitk::Point2D, std::string>> GetPointsAsVector(const mitk::BaseGeometry*);
/**
* @brief Get the Points from positive and negative pointsets as csv string.
*
* @param baseGeometry
* @return std::stringstream
*/
std::stringstream GetPointsAsCSVString(const mitk::BaseGeometry *baseGeometry);
/**
* @brief Get the Hash For Current Plane from current working plane geometry.
*
* @return std::string
*/
std::string GetHashForCurrentPlane(const mitk::LevelWindow&);
/**
* @brief Emits message to connected Listnerers.
*
*/
void EmitSAMStatusMessageEvent(const std::string&);
/**
* @brief Cleans up segmentation preview and clears all seeds.
*
*/
void ConfirmCleanUp() override;
/**
* @brief Applies ITK IntensityWindowing Filter to input image;
*
*/
template <typename TPixel, unsigned int VImageDimension>
void ITKWindowing(const itk::Image<TPixel, VImageDimension>*, mitk::Image*, ScalarType, ScalarType);
private:
/**
* @brief Convert 3D world coordinates to 2D indices.
*
* @param baseGeometry
* @param mitk::Point3D
* @return mitk::Point2D
*/
static mitk::Point2D Get2DIndicesfrom3DWorld(const mitk::BaseGeometry*, const mitk::Point3D&);
std::string m_MitkTempDir;
std::string m_PythonPath;
std::string m_ModelType;
std::string m_CheckpointPath;
int m_GpuId = 0;
PointSet::Pointer m_PointSetPositive;
PointSet::Pointer m_PointSetNegative;
DataNode::Pointer m_PointSetNodePositive;
DataNode::Pointer m_PointSetNodeNegative;
bool m_IsGenerateEmbeddings = true;
bool m_IsReady = false;
int m_PointSetCount = 0;
long m_TimeOutLimit = -1;
std::unique_ptr<SegmentAnythingPythonService> m_PythonService;
const Label::PixelType MASK_VALUE = 1;
};
} // namespace
#endif
diff --git a/Modules/SegmentationUI/CMakeLists.txt b/Modules/SegmentationUI/CMakeLists.txt
index 794aee58ab..47693a265e 100644
--- a/Modules/SegmentationUI/CMakeLists.txt
+++ b/Modules/SegmentationUI/CMakeLists.txt
@@ -1,9 +1,9 @@
MITK_CREATE_MODULE (
INCLUDE_DIRS Qmitk SegmentationUtilities
DEPENDS MitkSegmentation MitkQtWidgetsExt
- PACKAGE_DEPENDS PRIVATE CTK|CTKWidgets nlohmann_json
+ PACKAGE_DEPENDS PRIVATE CTK|CTKWidgets Qt6|Concurrent nlohmann_json
)
if(BUILD_TESTING)
add_subdirectory(test)
-endif()
\ No newline at end of file
+endif()
diff --git a/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.cpp b/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.cpp
index e4968b6769..8da907bbec 100644
--- a/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.cpp
+++ b/Modules/SegmentationUI/Qmitk/QmitkEditableContourToolGUIBase.cpp
@@ -1,122 +1,109 @@
/*============================================================================
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 <QmitkEditableContourToolGUIBase.h>
#include <ui_QmitkEditableContourToolGUIControls.h>
#include <QButtonGroup>
#include <mitkEditableContourTool.h>
QmitkEditableContourToolGUIBase::QmitkEditableContourToolGUIBase()
: QmitkToolGUI(),
m_Controls(new Ui::QmitkEditableContourToolGUIControls),
m_ModeButtonGroup(new QButtonGroup(this))
{
m_Controls->setupUi(this);
m_Controls->m_ConfirmButton->hide();
m_Controls->m_AddMode->hide();
m_Controls->m_SubtractMode->hide();
m_Controls->m_ClearButton->hide();
m_Controls->m_Information->hide();
m_ModeButtonGroup->addButton(m_Controls->m_AddMode, static_cast<int>(Mode::Add));
m_ModeButtonGroup->addButton(m_Controls->m_SubtractMode, static_cast<int>(Mode::Subtract));
-#if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0))
- auto onModeToggled = [this](QAbstractButton* button) {
- Mode mode = button == m_Controls->m_AddMode
- ? Mode::Add
- : Mode::Subtract;
-
- this->OnModeToggled(mode);
- };
-
- connect(m_ModeButtonGroup, QOverload<QAbstractButton*>::of(&QButtonGroup::buttonClicked), onModeToggled);
-#else
connect(m_ModeButtonGroup, &QButtonGroup::idClicked, [this](int id) { this->OnModeToggled(static_cast<Mode>(id)); });
-#endif
-
connect(this, &Self::NewToolAssociated, this, &Self::OnNewToolAssociated);
connect(m_Controls->m_AutoCheck, &QCheckBox::toggled, this, &Self::OnAutoConfirm);
connect(m_Controls->m_ConfirmButton, &QPushButton::clicked, this, &Self::OnConfirmSegmentation);
connect(m_Controls->m_ClearButton, &QPushButton::clicked, this, &Self::OnClearContour);
connect(m_Controls->m_InformationCheckBox, &QCheckBox::toggled, this, &Self::OnShowInformation);
}
QmitkEditableContourToolGUIBase::~QmitkEditableContourToolGUIBase()
{
}
void QmitkEditableContourToolGUIBase::OnNewToolAssociated(mitk::Tool* tool)
{
m_NewTool = dynamic_cast<mitk::EditableContourTool*>(tool);
if (m_NewTool.IsNull())
mitkThrow() << "Tool is in an invalid state. QmitkEditableContourToolGUIBase needs tools based on EditableContourTool.";
const auto autoConfirm = m_NewTool->GetAutoConfirm();
m_Controls->m_AutoCheck->setChecked(autoConfirm);
const auto mode = m_NewTool->GetAddMode()
? Mode::Add
: Mode::Subtract;
m_ModeButtonGroup->button(static_cast<int>(mode))->setChecked(true);
this->OnAutoConfirm(autoConfirm);
this->OnModeToggled(mode);
}
void QmitkEditableContourToolGUIBase::OnAutoConfirm(bool on)
{
m_Controls->m_ConfirmButton->setVisible(!on);
m_Controls->m_ClearButton->setVisible(!on);
m_Controls->m_AddMode->setVisible(!on);
m_Controls->m_SubtractMode->setVisible(!on);
if (on)
m_Controls->m_AddMode->setChecked(true);
if (m_NewTool.IsNotNull())
{
if (on && m_NewTool->IsEditingContour())
this->OnConfirmSegmentation();
m_NewTool->SetAutoConfirm(on);
m_NewTool->SetAddMode(m_Controls->m_AddMode->isChecked());
}
}
void QmitkEditableContourToolGUIBase::OnModeToggled(Mode mode)
{
if (m_NewTool.IsNotNull())
m_NewTool->SetAddMode(Mode::Add == mode);
}
void QmitkEditableContourToolGUIBase::OnConfirmSegmentation()
{
if (m_NewTool.IsNotNull())
m_NewTool->ConfirmSegmentation();
}
void QmitkEditableContourToolGUIBase::OnClearContour()
{
if (m_NewTool.IsNotNull())
m_NewTool->ClearContour();
}
void QmitkEditableContourToolGUIBase::OnShowInformation(bool on)
{
m_Controls->m_Information->setVisible(on);
}
diff --git a/Modules/SegmentationUI/Qmitk/QmitkMultiLabelInspector.cpp b/Modules/SegmentationUI/Qmitk/QmitkMultiLabelInspector.cpp
index 2b2002ec07..0f4565a621 100644
--- a/Modules/SegmentationUI/Qmitk/QmitkMultiLabelInspector.cpp
+++ b/Modules/SegmentationUI/Qmitk/QmitkMultiLabelInspector.cpp
@@ -1,1139 +1,1139 @@
/*============================================================================
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 <QmitkMultiLabelInspector.h>
// mitk
#include <mitkRenderingManager.h>
#include <mitkLabelSetImageHelper.h>
#include <mitkDICOMSegmentationPropertyHelper.h>
// Qmitk
#include <QmitkMultiLabelTreeModel.h>
#include <QmitkLabelColorItemDelegate.h>
#include <QmitkLabelToggleItemDelegate.h>
#include <QmitkStyleManager.h>
// Qt
#include <QMenu>
#include <QLabel>
#include <QWidgetAction>
#include <QMessageBox>
#include <ui_QmitkMultiLabelInspectorControls.h>
QmitkMultiLabelInspector::QmitkMultiLabelInspector(QWidget* parent/* = nullptr*/)
: QWidget(parent), m_Controls(new Ui::QmitkMultiLabelInspector)
{
m_Controls->setupUi(this);
m_Model = new QmitkMultiLabelTreeModel(this);
m_Controls->view->setModel(m_Model);
m_ColorItemDelegate = new QmitkLabelColorItemDelegate(this);
auto visibleIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/visible.svg"));
auto invisibleIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/invisible.svg"));
m_VisibilityItemDelegate = new QmitkLabelToggleItemDelegate(visibleIcon, invisibleIcon, this);
auto lockIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/lock.svg"));
auto unlockIcon = QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/unlock.svg"));
m_LockItemDelegate = new QmitkLabelToggleItemDelegate(lockIcon, unlockIcon, this);
auto* view = this->m_Controls->view;
view->setItemDelegateForColumn(1, m_LockItemDelegate);
view->setItemDelegateForColumn(2, m_ColorItemDelegate);
view->setItemDelegateForColumn(3, m_VisibilityItemDelegate);
auto* header = view->header();
header->setSectionResizeMode(0,QHeaderView::Stretch);
header->setSectionResizeMode(1, QHeaderView::ResizeToContents);
header->setSectionResizeMode(2, QHeaderView::ResizeToContents);
header->setSectionResizeMode(3, QHeaderView::ResizeToContents);
view->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_Model, &QAbstractItemModel::modelReset, this, &QmitkMultiLabelInspector::OnModelReset);
connect(view->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), SLOT(OnChangeModelSelection(const QItemSelection&, const QItemSelection&)));
connect(view, &QAbstractItemView::customContextMenuRequested, this, &QmitkMultiLabelInspector::OnContextMenuRequested);
connect(view, &QAbstractItemView::doubleClicked, this, &QmitkMultiLabelInspector::OnItemDoubleClicked);
}
QmitkMultiLabelInspector::~QmitkMultiLabelInspector()
{
delete m_Controls;
}
void QmitkMultiLabelInspector::Initialize()
{
m_LastValidSelectedLabels = {};
m_ModelManipulationOngoing = false;
m_Model->SetSegmentation(m_Segmentation);
m_Controls->view->expandAll();
m_LastValidSelectedLabels = {};
//in singel selection mode, if at least one label exist select the first label of the mode.
if (m_Segmentation.IsNotNull() && !this->GetMultiSelectionMode() && m_Segmentation->GetTotalNumberOfLabels() > 0)
{
auto firstIndex = m_Model->FirstLabelInstanceIndex(QModelIndex());
auto labelVariant = firstIndex.data(QmitkMultiLabelTreeModel::ItemModelRole::LabelInstanceValueRole);
if (labelVariant.isValid())
{
this->SetSelectedLabel(labelVariant.value<LabelValueType>());
m_Controls->view->selectionModel()->setCurrentIndex(firstIndex, QItemSelectionModel::NoUpdate);
}
}
}
void QmitkMultiLabelInspector::SetMultiSelectionMode(bool multiMode)
{
m_Controls->view->setSelectionMode(multiMode
? QAbstractItemView::SelectionMode::MultiSelection
: QAbstractItemView::SelectionMode::SingleSelection);
}
bool QmitkMultiLabelInspector::GetMultiSelectionMode() const
{
return QAbstractItemView::SelectionMode::MultiSelection == m_Controls->view->selectionMode();
}
void QmitkMultiLabelInspector::SetAllowVisibilityModification(bool visibilityMod)
{
m_AllowVisibilityModification = visibilityMod;
this->m_Model->SetAllowVisibilityModification(visibilityMod);
}
void QmitkMultiLabelInspector::SetAllowLabelModification(bool labelMod)
{
m_AllowLabelModification = labelMod;
}
bool QmitkMultiLabelInspector::GetAllowVisibilityModification() const
{
return m_AllowVisibilityModification;
}
void QmitkMultiLabelInspector::SetAllowLockModification(bool lockMod)
{
m_AllowLockModification = lockMod;
this->m_Model->SetAllowLockModification(lockMod);
}
bool QmitkMultiLabelInspector::GetAllowLockModification() const
{
return m_AllowLockModification;
}
bool QmitkMultiLabelInspector::GetAllowLabelModification() const
{
return m_AllowLabelModification;
}
void QmitkMultiLabelInspector::SetDefaultLabelNaming(bool defaultLabelNaming)
{
m_DefaultLabelNaming = defaultLabelNaming;
}
void QmitkMultiLabelInspector::SetMultiLabelSegmentation(mitk::LabelSetImage* segmentation)
{
if (segmentation != m_Segmentation)
{
m_Segmentation = segmentation;
this->Initialize();
}
}
bool QmitkMultiLabelInspector::GetModelManipulationOngoing() const
{
return m_ModelManipulationOngoing;
}
void QmitkMultiLabelInspector::OnModelReset()
{
m_LastValidSelectedLabels = {};
m_ModelManipulationOngoing = false;
}
bool EqualLabelSelections(const QmitkMultiLabelInspector::LabelValueVectorType& selection1, const QmitkMultiLabelInspector::LabelValueVectorType& selection2)
{
if (selection1.size() == selection2.size())
{
// lambda to compare node pointer inside both lists
return std::is_permutation(selection1.begin(), selection1.end(), selection2.begin());
}
return false;
}
void QmitkMultiLabelInspector::SetSelectedLabels(const LabelValueVectorType& selectedLabels)
{
if (EqualLabelSelections(this->GetSelectedLabels(), selectedLabels))
{
return;
}
this->UpdateSelectionModel(selectedLabels);
m_LastValidSelectedLabels = selectedLabels;
}
void QmitkMultiLabelInspector::UpdateSelectionModel(const LabelValueVectorType& selectedLabels)
{
// create new selection by retrieving the corresponding indices of the labels
QItemSelection newCurrentSelection;
for (const auto& labelID : selectedLabels)
{
QModelIndexList matched = m_Model->match(m_Model->index(0, 0), QmitkMultiLabelTreeModel::ItemModelRole::LabelInstanceValueRole, QVariant(labelID), 1, Qt::MatchRecursive);
if (!matched.empty())
{
newCurrentSelection.select(matched.front(), matched.front());
}
}
m_Controls->view->selectionModel()->select(newCurrentSelection, QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Current);
}
void QmitkMultiLabelInspector::SetSelectedLabel(mitk::LabelSetImage::LabelValueType selectedLabel)
{
this->SetSelectedLabels({ selectedLabel });
}
QmitkMultiLabelInspector::LabelValueVectorType QmitkMultiLabelInspector::GetSelectedLabelsFromSelectionModel() const
{
LabelValueVectorType result;
QModelIndexList selectedIndexes = m_Controls->view->selectionModel()->selectedIndexes();
- for (const auto& index : qAsConst(selectedIndexes))
+ for (const auto& index : std::as_const(selectedIndexes))
{
QVariant qvariantDataNode = m_Model->data(index, QmitkMultiLabelTreeModel::ItemModelRole::LabelInstanceValueRole);
if (qvariantDataNode.canConvert<mitk::LabelSetImage::LabelValueType>())
{
result.push_back(qvariantDataNode.value<mitk::LabelSetImage::LabelValueType>());
}
}
return result;
}
QmitkMultiLabelInspector::LabelValueVectorType QmitkMultiLabelInspector::GetSelectedLabels() const
{
return m_LastValidSelectedLabels;
}
mitk::Label* QmitkMultiLabelInspector::GetFirstSelectedLabelObject() const
{
if (m_LastValidSelectedLabels.empty() || m_Segmentation.IsNull())
return nullptr;
return m_Segmentation->GetLabel(m_LastValidSelectedLabels.front());
}
void QmitkMultiLabelInspector::OnChangeModelSelection(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/)
{
if (!m_ModelManipulationOngoing)
{
auto internalSelection = GetSelectedLabelsFromSelectionModel();
if (internalSelection.empty())
{
//empty selections are not allowed by UI interactions, there should always be at least on label selected.
//but selections are e.g. also cleared if the model is updated (e.g. due to addition of labels)
UpdateSelectionModel(m_LastValidSelectedLabels);
}
else
{
m_LastValidSelectedLabels = internalSelection;
emit CurrentSelectionChanged(GetSelectedLabels());
}
}
}
void QmitkMultiLabelInspector::WaitCursorOn() const
{
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
}
void QmitkMultiLabelInspector::WaitCursorOff() const
{
this->RestoreOverrideCursor();
}
void QmitkMultiLabelInspector::RestoreOverrideCursor() const
{
QApplication::restoreOverrideCursor();
}
mitk::Label* QmitkMultiLabelInspector::GetCurrentLabel() const
{
auto currentIndex = this->m_Controls->view->currentIndex();
auto labelVariant = currentIndex.data(QmitkMultiLabelTreeModel::ItemModelRole::LabelDataRole);
mitk::Label::Pointer currentIndexLabel = nullptr;
if (labelVariant.isValid())
{
auto uncastedLabel = labelVariant.value<void*>();
currentIndexLabel = static_cast<mitk::Label*>(uncastedLabel);
}
return currentIndexLabel;
}
QmitkMultiLabelInspector::IndexLevelType QmitkMultiLabelInspector::GetCurrentLevelType() const
{
auto currentIndex = this->m_Controls->view->currentIndex();
auto labelInstanceVariant = currentIndex.data(QmitkMultiLabelTreeModel::ItemModelRole::LabelInstanceDataRole);
auto labelVariant = currentIndex.data(QmitkMultiLabelTreeModel::ItemModelRole::LabelDataRole);
if (labelInstanceVariant.isValid() )
{
return IndexLevelType::LabelInstance;
}
else if (labelVariant.isValid())
{
return IndexLevelType::LabelClass;
}
return IndexLevelType::Group;
}
QmitkMultiLabelInspector::LabelValueVectorType QmitkMultiLabelInspector::GetCurrentlyAffactedLabelInstances() const
{
auto currentIndex = m_Controls->view->currentIndex();
return m_Model->GetLabelsInSubTree(currentIndex);
}
QmitkMultiLabelInspector::LabelValueVectorType QmitkMultiLabelInspector::GetLabelInstancesOfSelectedFirstLabel() const
{
if (m_Segmentation.IsNull())
return {};
if (this->GetSelectedLabels().empty())
return {};
const auto index = m_Model->indexOfLabel(this->GetSelectedLabels().front());
return m_Model->GetLabelInstancesOfSameLabelClass(index);
}
mitk::Label* QmitkMultiLabelInspector::AddNewLabelInstanceInternal(mitk::Label* templateLabel)
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of AddNewLabelInstance.";
if (nullptr == templateLabel)
mitkThrow() << "QmitkMultiLabelInspector is in an invalid state. AddNewLabelInstanceInternal was called with a non existing label as template";
auto groupID = m_Segmentation->GetGroupIndexOfLabel(templateLabel->GetValue());
auto group = m_Segmentation->GetLabelSet(groupID);
m_ModelManipulationOngoing = true;
auto newLabel = group->AddLabel(templateLabel, true);
m_ModelManipulationOngoing = false;
this->SetSelectedLabel(newLabel->GetValue());
auto index = m_Model->indexOfLabel(newLabel->GetValue());
if (index.isValid())
{
m_Controls->view->expand(index.parent());
}
else
{
mitkThrow() << "Segmentation or QmitkMultiLabelTreeModel is in an invalid state. Label is not present in the model after adding it to the segmentation. Label value: " << newLabel->GetValue();
}
emit ModelUpdated();
return newLabel;
}
mitk::Label* QmitkMultiLabelInspector::AddNewLabelInstance()
{
auto currentLabel = this->GetFirstSelectedLabelObject();
if (nullptr == currentLabel)
return nullptr;
return this->AddNewLabelInstanceInternal(currentLabel);
}
mitk::Label* QmitkMultiLabelInspector::AddNewLabelInternal(const mitk::LabelSetImage::GroupIndexType& containingGroup)
{
auto newLabel = mitk::LabelSetImageHelper::CreateNewLabel(m_Segmentation);
if (!m_DefaultLabelNaming)
emit LabelRenameRequested(newLabel, false);
auto group = m_Segmentation->GetLabelSet(containingGroup);
m_ModelManipulationOngoing = true;
group->AddLabel(newLabel, false);
m_ModelManipulationOngoing = false;
this->SetSelectedLabel(newLabel->GetValue());
auto index = m_Model->indexOfLabel(newLabel->GetValue());
if (!index.isValid())
mitkThrow() << "Segmentation or QmitkMultiLabelTreeModel is in an invalid state. Label is not present in the "
"model after adding it to the segmentation. Label value: " << newLabel->GetValue();
m_Controls->view->expand(index.parent());
emit ModelUpdated();
return newLabel;
}
mitk::Label* QmitkMultiLabelInspector::AddNewLabel()
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of AddNewLabel.";
if (m_Segmentation.IsNull())
{
return nullptr;
}
auto currentLabel = this->GetFirstSelectedLabelObject();
mitk::LabelSetImage::GroupIndexType groupID = nullptr != currentLabel
? m_Segmentation->GetGroupIndexOfLabel(currentLabel->GetValue())
: 0;
return AddNewLabelInternal(groupID);
}
void QmitkMultiLabelInspector::DeleteLabelInstance()
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of DeleteLabelInstance.";
if (m_Segmentation.IsNull())
return;
auto label = this->GetFirstSelectedLabelObject();
if (nullptr == label)
return;
auto index = m_Model->indexOfLabel(label->GetValue());
auto instanceName = index.data(Qt::DisplayRole);
auto question = "Do you really want to delete label instance \"" + instanceName.toString() + "\"?";
auto answer = QMessageBox::question(this, QString("Delete label instances"), question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
if (answer == QMessageBox::Yes)
this->DeleteLabelInternal({ label->GetValue() });
}
void QmitkMultiLabelInspector::DeleteLabel()
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of DeleteLabel.";
if (m_Segmentation.IsNull())
return;
const auto label = this->GetFirstSelectedLabelObject();
if (nullptr == label)
return;
const auto relevantLabels = this->GetLabelInstancesOfSelectedFirstLabel();
if (relevantLabels.empty())
return;
auto question = "Do you really want to delete label \"" + QString::fromStdString(label->GetName());
question = relevantLabels.size()==1 ? question + "\"?" : question + "\" with all "+QString::number(relevantLabels.size()) +" instances?";
auto answer = QMessageBox::question(this, QString("Delete label"), question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
if (answer == QMessageBox::Yes)
this->DeleteLabelInternal(relevantLabels);
}
void QmitkMultiLabelInspector::DeleteLabelInternal(const LabelValueVectorType& labelValues)
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of DeleteLabelInternal.";
if (m_Segmentation.IsNull())
{
return;
}
QVariant nextLabelVariant;
this->WaitCursorOn();
m_ModelManipulationOngoing = true;
for (auto labelValue : labelValues)
{
if (labelValue == labelValues.back())
{
auto currentIndex = m_Model->indexOfLabel(labelValue);
auto nextIndex = m_Model->ClosestLabelInstanceIndex(currentIndex);
nextLabelVariant = nextIndex.data(QmitkMultiLabelTreeModel::ItemModelRole::LabelInstanceValueRole);
}
m_Segmentation->RemoveLabel(labelValue);
}
m_ModelManipulationOngoing = false;
this->WaitCursorOff();
if (nextLabelVariant.isValid())
{
auto newLabelValue = nextLabelVariant.value<LabelValueType>();
this->SetSelectedLabel(newLabelValue);
auto index = m_Model->indexOfLabel(newLabelValue); //we have to get index again, because it could have changed due to remove operation.
if (index.isValid())
{
m_Controls->view->expand(index.parent());
}
else
{
mitkThrow() << "Segmentation or QmitkMultiLabelTreeModel is in an invalid state. Label is not present in the model after adding it to the segmentation. Label value: " << newLabelValue;
}
}
else
{
this->SetSelectedLabels({});
}
emit ModelUpdated();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
mitk::Label* QmitkMultiLabelInspector::AddNewGroup()
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of AddNewLabel.";
if (m_Segmentation.IsNull())
{
return nullptr;
}
mitk::LabelSetImage::GroupIndexType groupID = 0;
mitk::Label* newLabel = nullptr;
m_ModelManipulationOngoing = true;
try
{
this->WaitCursorOn();
groupID = m_Segmentation->AddLayer();
this->WaitCursorOff();
newLabel = this->AddNewLabelInternal(groupID);
}
catch (mitk::Exception& e)
{
this->WaitCursorOff();
m_ModelManipulationOngoing = false;
MITK_ERROR << "Exception caught: " << e.GetDescription();
QMessageBox::information(this, "Add group", "Could not add a new group. See error log for details.");
}
m_ModelManipulationOngoing = false;
emit ModelUpdated();
return newLabel;
}
void QmitkMultiLabelInspector::RemoveGroupInternal(const mitk::LabelSetImage::GroupIndexType& groupID)
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of RemoveLabel.";
if (m_Segmentation.IsNull())
return;
if (m_Segmentation->GetNumberOfLayers() < 2)
return;
auto currentIndex = m_Model->indexOfGroup(groupID);
auto nextIndex = m_Model->ClosestLabelInstanceIndex(currentIndex);
auto labelVariant = nextIndex.data(QmitkMultiLabelTreeModel::ItemModelRole::LabelInstanceValueRole);
try
{
this->WaitCursorOn();
m_ModelManipulationOngoing = true;
m_Segmentation->RemoveGroup(groupID);
m_ModelManipulationOngoing = false;
this->WaitCursorOff();
}
catch (mitk::Exception& e)
{
m_ModelManipulationOngoing = false;
this->WaitCursorOff();
MITK_ERROR << "Exception caught: " << e.GetDescription();
QMessageBox::information(this, "Delete group", "Could not delete the currently active group. See error log for details.");
return;
}
if (labelVariant.isValid())
{
auto newLabelValue = labelVariant.value<LabelValueType>();
this->SetSelectedLabel(newLabelValue);
auto index = m_Model->indexOfLabel(newLabelValue); //we have to get index again, because it could have changed due to remove operation.
if (index.isValid())
{
m_Controls->view->expand(index.parent());
}
else
{
mitkThrow() << "Segmentation or QmitkMultiLabelTreeModel is in an invalid state. Label is not present in the model after adding it to the segmentation. Label value: " << newLabelValue;
}
}
else
{
this->SetSelectedLabels({});
}
emit ModelUpdated();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkMultiLabelInspector::RemoveGroup()
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of RemoveLabel.";
if (m_Segmentation.IsNull())
return;
if (m_Segmentation->GetNumberOfLayers() < 2)
{
QMessageBox::information(this, "Delete group", "Cannot delete last remaining group. A segmentation must contain at least a single group.");
return;
}
const auto* selectedLabel = this->GetFirstSelectedLabelObject();
if (selectedLabel == nullptr)
return;
const auto group = m_Segmentation->GetGroupIndexOfLabel(selectedLabel->GetValue());
auto question = QStringLiteral("Do you really want to delete group %1 including all of its labels?").arg(group);
auto answer = QMessageBox::question(this, QStringLiteral("Delete group %1").arg(group), question, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (answer != QMessageBox::Yes)
return;
this->RemoveGroupInternal(group);
}
void QmitkMultiLabelInspector::OnDeleteGroup()
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of RemoveLabel.";
if (m_Segmentation.IsNull())
return;
auto currentIndex = this->m_Controls->view->currentIndex();
auto groupIDVariant = currentIndex.data(QmitkMultiLabelTreeModel::ItemModelRole::GroupIDRole);
if (groupIDVariant.isValid())
{
auto groupID = groupIDVariant.value<mitk::LabelSetImage::GroupIndexType>();
auto question = QStringLiteral("Do you really want to delete group %1 including all of its labels?").arg(groupID);
auto answer = QMessageBox::question(this, QString("Delete group %1").arg(groupID), question, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (answer != QMessageBox::Yes)
return;
this->RemoveGroupInternal(groupID);
}
};
void QmitkMultiLabelInspector::OnContextMenuRequested(const QPoint& /*pos*/)
{
if (m_Segmentation.IsNull() || !this->isEnabled())
return;
const auto indexLevel = this->GetCurrentLevelType();
if (IndexLevelType::Group == indexLevel)
{
QMenu* menu = new QMenu(this);
if (m_AllowLabelModification)
{
QAction* addInstanceAction = new QAction(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/icon_label_add.svg")), "&Add label", this);
QObject::connect(addInstanceAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnAddLabel);
menu->addAction(addInstanceAction);
if (m_Segmentation->GetNumberOfLayers() > 1)
{
QAction* removeAction = new QAction(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/icon_group_delete.svg")), "Delete group", this);
QObject::connect(removeAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnDeleteGroup);
menu->addAction(removeAction);
}
}
if (m_AllowLockModification)
{
menu->addSeparator();
QAction* lockAllAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/lock.svg")), "Lock group", this);
QObject::connect(lockAllAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnLockAffectedLabels);
menu->addAction(lockAllAction);
QAction* unlockAllAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/unlock.svg")), "Unlock group", this);
QObject::connect(unlockAllAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnUnlockAffectedLabels);
menu->addAction(unlockAllAction);
}
if (m_AllowVisibilityModification)
{
menu->addSeparator();
QAction* viewAllAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/visible.svg")), "Show group", this);
QObject::connect(viewAllAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnSetAffectedLabelsVisible);
menu->addAction(viewAllAction);
QAction* hideAllAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/invisible.svg")), "Hide group", this);
QObject::connect(hideAllAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnSetAffectedLabelsInvisible);
menu->addAction(hideAllAction);
menu->addSeparator();
auto opacityAction = this->CreateOpacityAction();
if (nullptr != opacityAction)
menu->addAction(opacityAction);
}
menu->popup(QCursor::pos());
}
else if (IndexLevelType::LabelClass == indexLevel)
{
QMenu* menu = new QMenu(this);
if (m_AllowLabelModification)
{
QAction* addInstanceAction = new QAction(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/icon_label_add_instance.svg")), "Add label instance", this);
QObject::connect(addInstanceAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnAddLabelInstance);
menu->addAction(addInstanceAction);
QAction* renameAction = new QAction(QIcon(":/Qmitk/RenameLabel.png"), "&Rename label", this);
QObject::connect(renameAction, SIGNAL(triggered(bool)), this, SLOT(OnRenameLabel(bool)));
menu->addAction(renameAction);
QAction* removeAction = new QAction(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/icon_label_delete.svg")), "&Delete label", this);
QObject::connect(removeAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnDeleteAffectedLabel);
menu->addAction(removeAction);
}
if (m_AllowLockModification)
{
menu->addSeparator();
QAction* lockAllAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/lock.svg")), "Lock label instances", this);
QObject::connect(lockAllAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnLockAffectedLabels);
menu->addAction(lockAllAction);
QAction* unlockAllAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/unlock.svg")), "Unlock label instances", this);
QObject::connect(unlockAllAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnUnlockAffectedLabels);
menu->addAction(unlockAllAction);
}
if (m_AllowVisibilityModification)
{
menu->addSeparator();
QAction* viewAllAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/visible.svg")), "Show label instances", this);
QObject::connect(viewAllAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnSetAffectedLabelsVisible);
menu->addAction(viewAllAction);
QAction* hideAllAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/invisible.svg")), "Hide label instances", this);
QObject::connect(hideAllAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnSetAffectedLabelsInvisible);
menu->addAction(hideAllAction);
menu->addSeparator();
auto opacityAction = this->CreateOpacityAction();
if (nullptr!=opacityAction)
menu->addAction(opacityAction);
}
menu->popup(QCursor::pos());
}
else
{
auto selectedLabelValues = this->GetSelectedLabels();
if (selectedLabelValues.empty())
return;
QMenu* menu = new QMenu(this);
if (this->GetMultiSelectionMode() && selectedLabelValues.size() > 1)
{
QAction* mergeAction = new QAction(QIcon(":/Qmitk/MergeLabels.png"), "Merge selection on current label", this);
QObject::connect(mergeAction, SIGNAL(triggered(bool)), this, SLOT(OnMergeLabels(bool)));
menu->addAction(mergeAction);
QAction* removeLabelsAction = new QAction(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/icon_label_delete_instance.svg")), "&Delete selected labels", this);
QObject::connect(removeLabelsAction, SIGNAL(triggered(bool)), this, SLOT(OnDeleteLabels(bool)));
menu->addAction(removeLabelsAction);
QAction* clearLabelsAction = new QAction(QIcon(":/Qmitk/EraseLabel.png"), "&Clear selected labels", this);
QObject::connect(clearLabelsAction, SIGNAL(triggered(bool)), this, SLOT(OnClearLabels(bool)));
menu->addAction(clearLabelsAction);
}
else
{
if (m_AllowLabelModification)
{
QAction* addInstanceAction = new QAction(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/icon_label_add_instance.svg")), "&Add label instance", this);
QObject::connect(addInstanceAction, &QAction::triggered, this, &QmitkMultiLabelInspector::OnAddLabelInstance);
menu->addAction(addInstanceAction);
const auto selectedLabelIndex = m_Model->indexOfLabel(selectedLabelValues.front());
if (m_Model->GetLabelInstancesOfSameLabelClass(selectedLabelIndex).size() > 1) // Only labels that actually appear as instance (having additional instances)
{
QAction* renameAction = new QAction(QIcon(":/Qmitk/RenameLabel.png"), "&Rename label instance", this);
QObject::connect(renameAction, SIGNAL(triggered(bool)), this, SLOT(OnRenameLabel(bool)));
menu->addAction(renameAction);
QAction* removeInstanceAction = new QAction(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/icon_label_delete_instance.svg")), "&Delete label instance", this);
QObject::connect(removeInstanceAction, &QAction::triggered, this, &QmitkMultiLabelInspector::DeleteLabelInstance);
menu->addAction(removeInstanceAction);
}
else
{
QAction* renameAction = new QAction(QIcon(":/Qmitk/RenameLabel.png"), "&Rename label", this);
QObject::connect(renameAction, SIGNAL(triggered(bool)), this, SLOT(OnRenameLabel(bool)));
menu->addAction(renameAction);
}
QAction* removeLabelAction = new QAction(QmitkStyleManager::ThemeIcon(QStringLiteral(":/Qmitk/icon_label_delete.svg")), "Delete &label", this);
QObject::connect(removeLabelAction, &QAction::triggered, this, &QmitkMultiLabelInspector::DeleteLabel);
menu->addAction(removeLabelAction);
QAction* clearAction = new QAction(QIcon(":/Qmitk/EraseLabel.png"), "&Clear content", this);
QObject::connect(clearAction, SIGNAL(triggered(bool)), this, SLOT(OnClearLabel(bool)));
menu->addAction(clearAction);
}
if (m_AllowVisibilityModification)
{
menu->addSeparator();
QAction* viewOnlyAction = new QAction(QmitkStyleManager::ThemeIcon(QLatin1String(":/Qmitk/visible.svg")), "Hide everything in group but this", this);
QObject::connect(viewOnlyAction, SIGNAL(triggered(bool)), this, SLOT(OnSetOnlyActiveLabelVisible(bool)));
menu->addAction(viewOnlyAction);
menu->addSeparator();
auto opacityAction = this->CreateOpacityAction();
if (nullptr != opacityAction)
menu->addAction(opacityAction);
}
}
menu->popup(QCursor::pos());
}
}
QWidgetAction* QmitkMultiLabelInspector::CreateOpacityAction()
{
auto relevantLabelValues = this->GetCurrentlyAffactedLabelInstances();
std::vector<mitk::Label*> relevantLabels;
if (!relevantLabelValues.empty())
{
//we assume here that all affacted label belong to one group.
auto groupID = m_Segmentation->GetGroupIndexOfLabel(relevantLabelValues.front());
auto group = m_Segmentation->GetLabelSet(groupID);
for (auto value : relevantLabelValues)
{
auto label = this->m_Segmentation->GetLabel(value);
if (nullptr == label)
mitkThrow() << "Invalid state. Internal model returned a label value that does not exist in segmentation. Invalid value:" << value;
relevantLabels.emplace_back(label);
}
auto* opacitySlider = new QSlider;
opacitySlider->setMinimum(0);
opacitySlider->setMaximum(100);
opacitySlider->setOrientation(Qt::Horizontal);
auto opacity = relevantLabels.front()->GetOpacity();
opacitySlider->setValue(static_cast<int>(opacity * 100));
auto segmentation = m_Segmentation;
QObject::connect(opacitySlider, &QSlider::valueChanged, this, [segmentation, relevantLabels, group](const int value)
{
auto opacity = static_cast<float>(value) / 100.0f;
for (auto label : relevantLabels)
{
label->SetOpacity(opacity);
group->UpdateLookupTable(label->GetValue());
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
);
QLabel* opacityLabel = new QLabel("Opacity: ");
QVBoxLayout* opacityWidgetLayout = new QVBoxLayout;
opacityWidgetLayout->setContentsMargins(4, 4, 4, 4);
opacityWidgetLayout->addWidget(opacityLabel);
opacityWidgetLayout->addWidget(opacitySlider);
QWidget* opacityWidget = new QWidget;
opacityWidget->setLayout(opacityWidgetLayout);
QWidgetAction* opacityAction = new QWidgetAction(this);
opacityAction->setDefaultWidget(opacityWidget);
return opacityAction;
}
return nullptr;
}
void QmitkMultiLabelInspector::OnClearLabels(bool /*value*/)
{
QString question = "Do you really want to clear the selected labels?";
QMessageBox::StandardButton answerButton = QMessageBox::question(
this, "Clear selected labels", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
if (answerButton == QMessageBox::Yes)
{
this->WaitCursorOn();
m_Segmentation->EraseLabels(this->GetSelectedLabels());
this->WaitCursorOff();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkMultiLabelInspector::OnDeleteAffectedLabel()
{
if (!m_AllowLabelModification)
mitkThrow() << "QmitkMultiLabelInspector is configured incorrectly. Set AllowLabelModification to true to allow the usage of RemoveLabel.";
if (m_Segmentation.IsNull())
{
return;
}
auto affectedLabels = GetCurrentlyAffactedLabelInstances();
auto currentLabel = m_Segmentation->GetLabel(affectedLabels.front());
QString question = "Do you really want to delete all instances of label \"" + QString::fromStdString(currentLabel->GetName()) + "\"?";
QMessageBox::StandardButton answerButton =
QMessageBox::question(this, "Delete label", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
if (answerButton == QMessageBox::Yes)
{
this->DeleteLabelInternal(affectedLabels);
}
}
void QmitkMultiLabelInspector::OnDeleteLabels(bool /*value*/)
{
QString question = "Do you really want to remove the selected labels?";
QMessageBox::StandardButton answerButton = QMessageBox::question(
this, "Remove selected labels", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
if (answerButton == QMessageBox::Yes)
{
this->WaitCursorOn();
m_Segmentation->RemoveLabels(this->GetSelectedLabels());
this->WaitCursorOff();
}
}
void QmitkMultiLabelInspector::OnMergeLabels(bool /*value*/)
{
auto currentLabel = GetCurrentLabel();
QString question = "Do you really want to merge selected labels into \"" + QString::fromStdString(currentLabel->GetName())+"\"?";
QMessageBox::StandardButton answerButton = QMessageBox::question(
this, "Merge selected label", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
if (answerButton == QMessageBox::Yes)
{
this->WaitCursorOn();
m_Segmentation->MergeLabels(currentLabel->GetValue(), this->GetSelectedLabels(), m_Segmentation->GetActiveLayer());
this->WaitCursorOff();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkMultiLabelInspector::OnAddLabel()
{
auto currentIndex = this->m_Controls->view->currentIndex();
auto groupIDVariant = currentIndex.data(QmitkMultiLabelTreeModel::ItemModelRole::GroupIDRole);
if (groupIDVariant.isValid())
{
auto groupID = groupIDVariant.value<mitk::LabelSetImage::GroupIndexType>();
this->AddNewLabelInternal(groupID);
}
}
void QmitkMultiLabelInspector::OnAddLabelInstance()
{
auto currentLabel = this->GetCurrentLabel();
if (nullptr == currentLabel)
return;
this->AddNewLabelInstanceInternal(currentLabel);
}
void QmitkMultiLabelInspector::OnClearLabel(bool /*value*/)
{
auto currentLabel = GetFirstSelectedLabelObject();
QString question = "Do you really want to clear the contents of label \"" + QString::fromStdString(currentLabel->GetName())+"\"?";
QMessageBox::StandardButton answerButton =
QMessageBox::question(this, "Clear label", question, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
if (answerButton == QMessageBox::Yes)
{
this->WaitCursorOn();
m_Segmentation->EraseLabel(currentLabel->GetValue());
this->WaitCursorOff();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkMultiLabelInspector::OnRenameLabel(bool /*value*/)
{
auto relevantLabelValues = this->GetCurrentlyAffactedLabelInstances();
auto currentLabel = this->GetCurrentLabel();
emit LabelRenameRequested(currentLabel, true);
//we assume here that all affacted label belong to one group.
auto groupID = m_Segmentation->GetGroupIndexOfLabel(currentLabel->GetValue());
auto group = m_Segmentation->GetLabelSet(groupID);
for (auto value : relevantLabelValues)
{
if (value != currentLabel->GetValue())
{
auto label = this->m_Segmentation->GetLabel(value);
if (nullptr == label)
mitkThrow() << "Invalid state. Internal model returned a label value that does not exist in segmentation. Invalid value:" << value;
label->SetName(currentLabel->GetName());
label->SetColor(currentLabel->GetColor());
group->UpdateLookupTable(label->GetValue());
mitk::DICOMSegmentationPropertyHelper::SetDICOMSegmentProperties(label);
}
}
emit ModelUpdated();
}
void QmitkMultiLabelInspector::SetLockOfAffectedLabels(bool locked) const
{
auto relevantLabelValues = this->GetCurrentlyAffactedLabelInstances();
if (!relevantLabelValues.empty())
{
for (auto value : relevantLabelValues)
{
auto label = this->m_Segmentation->GetLabel(value);
if (nullptr == label)
mitkThrow() << "Invalid state. Internal model returned a label value that does not exist in segmentation. Invalid value:" << value;
label->SetLocked(locked);
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkMultiLabelInspector::OnUnlockAffectedLabels()
{
this->SetLockOfAffectedLabels(false);
}
void QmitkMultiLabelInspector::OnLockAffectedLabels()
{
this->SetLockOfAffectedLabels(true);
}
void QmitkMultiLabelInspector::SetVisibilityOfAffectedLabels(bool visible) const
{
auto relevantLabelValues = this->GetCurrentlyAffactedLabelInstances();
if (!relevantLabelValues.empty())
{
//we assume here that all affacted label belong to one group.
auto groupID = m_Segmentation->GetGroupIndexOfLabel(relevantLabelValues.front());
auto group = m_Segmentation->GetLabelSet(groupID);
for (auto value : relevantLabelValues)
{
auto label = this->m_Segmentation->GetLabel(value);
if (nullptr == label)
mitkThrow() << "Invalid state. Internal model returned a label value that does not exist in segmentation. Invalid value:" << value;
label->SetVisible(visible);
group->UpdateLookupTable(label->GetValue());
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
void QmitkMultiLabelInspector::OnSetAffectedLabelsVisible()
{
this->SetVisibilityOfAffectedLabels(true);
}
void QmitkMultiLabelInspector::OnSetAffectedLabelsInvisible()
{
this->SetVisibilityOfAffectedLabels(false);
}
void QmitkMultiLabelInspector::OnSetOnlyActiveLabelVisible(bool /*value*/)
{
auto currentLabel = GetFirstSelectedLabelObject();
const auto labelID = currentLabel->GetValue();
auto groupID = m_Segmentation->GetGroupIndexOfLabel(currentLabel->GetValue());
auto group = m_Segmentation->GetLabelSet(groupID);
group->SetAllLabelsVisible(false);
currentLabel->SetVisible(true);
group->UpdateLookupTable(labelID);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
this->PrepareGoToLabel(labelID);
}
void QmitkMultiLabelInspector::OnItemDoubleClicked(const QModelIndex& index)
{
if (!index.isValid()) return;
if (index.column() > 0) return;
auto labelVariant = index.data(QmitkMultiLabelTreeModel::ItemModelRole::LabelInstanceValueRole);
if (!labelVariant.isValid()) return;
const auto labelID = labelVariant.value<mitk::Label::PixelType>();
if (QApplication::queryKeyboardModifiers().testFlag(Qt::AltModifier))
{
this->OnRenameLabel(false);
return;
}
this->PrepareGoToLabel(labelID);
}
void QmitkMultiLabelInspector::PrepareGoToLabel(mitk::Label::PixelType labelID) const
{
this->WaitCursorOn();
m_Segmentation->UpdateCenterOfMass(labelID);
const auto currentLabel = m_Segmentation->GetLabel(labelID);
const mitk::Point3D& pos = currentLabel->GetCenterOfMassCoordinates();
this->WaitCursorOff();
if (pos.GetVnlVector().max_value() > 0.0)
{
emit GoToLabel(currentLabel->GetValue(), pos);
}
}
diff --git a/Modules/SegmentationUI/Qmitk/QmitkSetupVirtualEnvUtil.cpp b/Modules/SegmentationUI/Qmitk/QmitkSetupVirtualEnvUtil.cpp
index 326bbc522f..b871e15128 100644
--- a/Modules/SegmentationUI/Qmitk/QmitkSetupVirtualEnvUtil.cpp
+++ b/Modules/SegmentationUI/Qmitk/QmitkSetupVirtualEnvUtil.cpp
@@ -1,274 +1,238 @@
/*============================================================================
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.s
============================================================================*/
#include "QmitkSetupVirtualEnvUtil.h"
#include "mitkLog.h"
#include <QStandardPaths>
#include <itkCommand.h>
#include <regex>
-#include <sstream>
#include <QDir>
#include <QApplication>
-#include <mutex>
+#include <QProcess>
+#include <QStringDecoder>
QmitkSetupVirtualEnvUtil::QmitkSetupVirtualEnvUtil()
{
m_BaseDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QDir::separator() +
qApp->organizationName() + QDir::separator();
}
QmitkSetupVirtualEnvUtil::QmitkSetupVirtualEnvUtil(const QString &baseDir)
{
m_BaseDir = baseDir;
}
QString& QmitkSetupVirtualEnvUtil::GetBaseDir()
{
return m_BaseDir;
}
QString QmitkSetupVirtualEnvUtil::GetVirtualEnvPath()
{
return m_venvPath;
}
QString& QmitkSetupVirtualEnvUtil::GetSystemPythonPath()
{
return m_SysPythonPath;
}
QString& QmitkSetupVirtualEnvUtil::GetPythonPath()
{
return m_PythonPath;
}
QString& QmitkSetupVirtualEnvUtil::GetPipPath()
{
return m_PipPath;
}
void QmitkSetupVirtualEnvUtil::SetVirtualEnvPath(const QString &path)
{
m_venvPath = path;
}
void QmitkSetupVirtualEnvUtil::SetPipPath(const QString &path)
{
m_PipPath = path;
}
void QmitkSetupVirtualEnvUtil::SetPythonPath(const QString &path)
{
if (this->IsPythonPath(path))
{
m_PythonPath = path;
}
else
{
MITK_INFO << "Python was not detected in " + path.toStdString();
}
}
void QmitkSetupVirtualEnvUtil::SetSystemPythonPath(const QString &path)
{
if (this->IsPythonPath(path))
{
m_SysPythonPath = path;
}
else
{
MITK_INFO << "Python was not detected in " + path.toStdString();
}
}
void QmitkSetupVirtualEnvUtil::PrintProcessEvent(itk::Object * /*pCaller*/, const itk::EventObject &e, void *)
{
std::string testCOUT;
std::string testCERR;
const auto *pEvent = dynamic_cast<const mitk::ExternalProcessStdOutEvent *>(&e);
if (pEvent)
{
testCOUT = testCOUT + pEvent->GetOutput();
MITK_INFO << testCOUT;
}
const auto *pErrEvent = dynamic_cast<const mitk::ExternalProcessStdErrEvent *>(&e);
if (pErrEvent)
{
testCERR = testCERR + pErrEvent->GetOutput();
MITK_ERROR << testCERR;
}
}
void QmitkSetupVirtualEnvUtil::InstallPytorch(const std::string &workingDir,
void (*callback)(itk::Object *, const itk::EventObject &, void *))
{
mitk::ProcessExecutor::ArgumentListType args;
auto spExec = mitk::ProcessExecutor::New();
auto spCommand = itk::CStyleCommand::New();
spCommand->SetCallback(callback);
spExec->AddObserver(mitk::ExternalProcessOutputEvent(), spCommand);
args.push_back("-m");
args.push_back("pip");
args.push_back("install");
args.push_back("light-the-torch==0.7.5");
spExec->Execute(workingDir, "python", args);
PipInstall("torch==2.0.0", workingDir, callback, "ltt");
PipInstall("torchvision==0.15.0", workingDir, callback, "ltt");
}
void QmitkSetupVirtualEnvUtil::InstallPytorch()
{
this->InstallPytorch(GetPythonPath().toStdString(), &PrintProcessEvent);
}
void QmitkSetupVirtualEnvUtil::PipInstall(const std::string &library,
const std::string &workingDir,
void (*callback)(itk::Object *, const itk::EventObject &, void *),
const std::string &command)
{
mitk::ProcessExecutor::ArgumentListType args;
auto spExec = mitk::ProcessExecutor::New();
auto spCommand = itk::CStyleCommand::New();
spCommand->SetCallback(callback);
spExec->AddObserver(mitk::ExternalProcessOutputEvent(), spCommand);
args.push_back("install");
args.push_back(library);
spExec->Execute(workingDir, command, args);
}
void QmitkSetupVirtualEnvUtil::PipInstall(const std::string &library,
void (*callback)(itk::Object*, const itk::EventObject&, void*),
const std::string& command)
{
this->PipInstall(library, this->GetPipPath().toStdString(), callback, command);
}
void QmitkSetupVirtualEnvUtil::ExecutePython(const std::string &pythonCode,
const std::string &workingDir,
void (*callback)(itk::Object *, const itk::EventObject &, void *),
const std::string &command)
{
mitk::ProcessExecutor::ArgumentListType args;
auto spExec = mitk::ProcessExecutor::New();
auto spCommand = itk::CStyleCommand::New();
spCommand->SetCallback(callback);
spExec->AddObserver(mitk::ExternalProcessOutputEvent(), spCommand);
args.push_back("-c");
args.push_back(pythonCode);
spExec->Execute(workingDir, command, args);
}
void QmitkSetupVirtualEnvUtil::ExecutePython(const std::string &args,
void (*callback)(itk::Object *, const itk::EventObject &, void *),
const std::string &command)
{
this->ExecutePython(args, this->GetPythonPath().toStdString(), callback, command);
}
bool QmitkSetupVirtualEnvUtil::IsPythonPath(const QString &pythonPath)
{
QString fullPath = pythonPath;
bool isExists =
#ifdef _WIN32
QFile::exists(fullPath + QDir::separator() + QString("python.exe"));
#else
QFile::exists(fullPath + QDir::separator() + QString("python3"));
#endif
return isExists;
}
-namespace
-{
- std::mutex mutex;
- std::string pyVersionCaptured;
-
- void CapturePyVersion(itk::Object * /*pCaller*/, const itk::EventObject &e, void *)
- {
- std::string testCOUT;
- const auto *pEvent = dynamic_cast<const mitk::ExternalProcessStdOutEvent *>(&e);
- if (pEvent)
- {
- pyVersionCaptured = pEvent->GetOutput();
- }
- }
-
- std::vector<int> SplitVersionString(const std::string& version)
- {
- std::vector<int> splits;
- std::string part;
- std::istringstream tokenStream(version);
- while (std::getline(tokenStream, part, '.'))
- {
- splits.push_back(std::stoi(part));
- }
- return splits;
- }
-
- bool IsSupported(const std::string& version, const std::string& low, const std::string& high)
- {
- std::vector<int> inHandVersion = SplitVersionString(version);
- std::vector<int> targetLowVersion = SplitVersionString(low);
- std::vector<int> targetHighVersion = SplitVersionString(high);
- if (inHandVersion.size() > 1 && targetLowVersion.size() > 1 && targetHighVersion.size() > 1)
- { // comparing second part of the version
- return (inHandVersion[1] > targetLowVersion[1] && inHandVersion[1] < targetHighVersion[1]);
- }
- return false;
- }
-}
-
std::pair<QString, QString> QmitkSetupVirtualEnvUtil::GetExactPythonPath(const QString &pyEnv)
{
QString fullPath = pyEnv;
bool pythonDoesExist = false;
bool isSupportedVersion = false;
#ifdef _WIN32
const std::string PYTHON_EXE = "python.exe";
// check if python exist in given folder.
pythonDoesExist = QFile::exists(fullPath + QDir::separator() + QString::fromStdString(PYTHON_EXE));
if (!pythonDoesExist && // check if in Scripts already, if not go there
!(fullPath.endsWith("Scripts", Qt::CaseInsensitive) || fullPath.endsWith("Scripts/", Qt::CaseInsensitive)))
{
fullPath += QDir::separator() + QString("Scripts");
pythonDoesExist = QFile::exists(fullPath + QDir::separator() + QString("python.exe"));
}
#else
const std::string PYTHON_EXE = "python3";
pythonDoesExist = QFile::exists(fullPath + QDir::separator() + QString::fromStdString(PYTHON_EXE));
if (!pythonDoesExist &&
!(fullPath.endsWith("bin", Qt::CaseInsensitive) || fullPath.endsWith("bin/", Qt::CaseInsensitive)))
{
fullPath += QDir::separator() + QString("bin");
pythonDoesExist = QFile::exists(fullPath + QDir::separator() + QString("python3"));
}
#endif
std::pair<QString, QString> pythonPath;
if (pythonDoesExist)
{
- ::mutex.lock();
- std::regex sanitizer(R"([^3\.(\d+)])");
- mitk::ProcessExecutor::ArgumentListType args;
- auto spExec = mitk::ProcessExecutor::New();
- auto spCommand = itk::CStyleCommand::New();
- spCommand->SetCallback(&::CapturePyVersion);
- spExec->AddObserver(mitk::ExternalProcessOutputEvent(), spCommand);
- args.push_back("--version");
- spExec->Execute(fullPath.toStdString(), PYTHON_EXE, args);
- std::string pyVersionNumber = std::regex_replace(::pyVersionCaptured, sanitizer, "");
- isSupportedVersion = ::IsSupported(pyVersionNumber, "3.8", "3.13");
- pythonPath.second = QString::fromStdString(pyVersionNumber);
- ::mutex.unlock();
+ std::regex sanitizer(R"(3\.(\d+))");
+ QProcess pyProcess;
+ pyProcess.start(fullPath + QDir::separator() + QString::fromStdString(PYTHON_EXE),
+ QStringList() << "--version",
+ QProcess::ReadOnly);
+ if (pyProcess.waitForFinished())
+ {
+ auto pyVersionCaptured = QString(QStringDecoder(QStringDecoder::Utf8)(pyProcess.readAllStandardOutput())).toStdString();
+ std::smatch match; // Expecting "Python 3.xx.xx" or "Python 3.xx"
+ if (std::regex_search(pyVersionCaptured, match, sanitizer) && !match.empty())
+ {
+ std::string pyVersionNumber = match[0];
+ int pySubVersion = std::stoi(match[1]);
+ isSupportedVersion = (pySubVersion > 8) ? (pySubVersion < 13) : false;
+ pythonPath.second = QString::fromStdString(pyVersionNumber);
+ }
+ }
}
pythonPath.first = pythonDoesExist &&isSupportedVersion ? fullPath : "";
return pythonPath;
}
diff --git a/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.cpp b/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.cpp
index 912b186306..9feec73c51 100644
--- a/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.cpp
+++ b/Modules/SegmentationUI/Qmitk/QmitkSlicesInterpolator.cpp
@@ -1,2039 +1,2039 @@
/*============================================================================
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 "QmitkSlicesInterpolator.h"
#include "QmitkRenderWindow.h"
#include "QmitkRenderWindowWidget.h"
#include "mitkApplyDiffImageOperation.h"
#include "mitkColorProperty.h"
#include "mitkCoreObjectFactory.h"
#include "mitkDiffImageApplier.h"
#include "mitkInteractionConst.h"
#include "mitkLevelWindowProperty.h"
#include "mitkOperationEvent.h"
#include "mitkProgressBar.h"
#include "mitkProperties.h"
#include "mitkRenderingManager.h"
#include "mitkSegTool2D.h"
#include "mitkSliceNavigationController.h"
#include "mitkSurfaceToImageFilter.h"
#include <mitkTimeNavigationController.h>
#include "mitkToolManager.h"
#include "mitkUndoController.h"
#include <mitkExtractSliceFilter.h>
#include <mitkPlanarCircle.h>
#include <mitkImageReadAccessor.h>
#include <mitkImageTimeSelector.h>
#include <mitkImageWriteAccessor.h>
#include <mitkPlaneProposer.h>
#include <mitkUnstructuredGridClusteringFilter.h>
#include <mitkVtkImageOverwrite.h>
#include <mitkShapeBasedInterpolationAlgorithm.h>
#include <itkCommand.h>
#include <mitkImageToContourFilter.h>
#include <mitkImagePixelReadAccessor.h>
// Includes for the merge operation
#include "mitkImageToContourFilter.h"
#include <mitkLabelSetImage.h>
#include <QCheckBox>
#include <QCursor>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <vtkDoubleArray.h>
#include <vtkFieldData.h>
#include <vtkPolyVertex.h>
#include <vtkUnstructuredGrid.h>
#include <vtkPolyData.h>
#include <array>
#include <atomic>
#include <thread>
#include <vector>
namespace
{
template <typename T = mitk::BaseData>
itk::SmartPointer<T> GetData(const mitk::DataNode* dataNode)
{
return nullptr != dataNode
? dynamic_cast<T*>(dataNode->GetData())
: nullptr;
}
}
float SURFACE_COLOR_RGB[3] = {0.49f, 1.0f, 0.16f};
const QmitkSlicesInterpolator::ActionToSliceDimensionMapType QmitkSlicesInterpolator::CreateActionToSlicer(const QList<QmitkRenderWindow*>& windows)
{
std::map<QAction *, mitk::SliceNavigationController *> actionToSliceDimension;
for (auto* window : windows)
{
std::string windowName;
auto renderWindowWidget = dynamic_cast<QmitkRenderWindowWidget*>(window->parentWidget());
if (renderWindowWidget)
{
windowName = renderWindowWidget->GetCornerAnnotationText();
}
else
{
windowName = window->GetRenderer()->GetName();
}
auto slicer = window->GetSliceNavigationController();
actionToSliceDimension[new QAction(QString::fromStdString(windowName), nullptr)] = slicer;
}
return actionToSliceDimension;
}
// Check whether the given contours are coplanar
bool AreContoursCoplanar(mitk::SurfaceInterpolationController::ContourPositionInformation leftHandSide,
mitk::SurfaceInterpolationController::ContourPositionInformation rightHandSide)
{
// Here we check two things:
// 1. Whether the normals of both contours are at least parallel
// 2. Whether both contours lie in the same plane
// Check for coplanarity:
// a. Span a vector between two points one from each contour
// b. Calculate dot product for the vector and one of the normals
// c. If the dot is zero the two vectors are orthogonal and the contours are coplanar
double vec[3];
vec[0] = leftHandSide.ContourPoint[0] - rightHandSide.ContourPoint[0];
vec[1] = leftHandSide.ContourPoint[1] - rightHandSide.ContourPoint[1];
vec[2] = leftHandSide.ContourPoint[2] - rightHandSide.ContourPoint[2];
double n[3];
n[0] = rightHandSide.ContourNormal[0];
n[1] = rightHandSide.ContourNormal[1];
n[2] = rightHandSide.ContourNormal[2];
double dot = vtkMath::Dot(n, vec);
double n2[3];
n2[0] = leftHandSide.ContourNormal[0];
n2[1] = leftHandSide.ContourNormal[1];
n2[2] = leftHandSide.ContourNormal[2];
// The normals of both contours have to be parallel but not of the same orientation
double lengthLHS = leftHandSide.ContourNormal.GetNorm();
double lengthRHS = rightHandSide.ContourNormal.GetNorm();
double dot2 = vtkMath::Dot(n, n2);
bool contoursParallel = mitk::Equal(fabs(lengthLHS * lengthRHS), fabs(dot2), 0.001);
if (mitk::Equal(dot, 0.0, 0.001) && contoursParallel)
return true;
else
return false;
}
mitk::Image::Pointer ExtractSliceFromImage(mitk::Image* image,
const mitk::PlaneGeometry * contourPlane,
unsigned int timeStep)
{
vtkSmartPointer<mitkVtkImageOverwrite> reslice = vtkSmartPointer<mitkVtkImageOverwrite>::New();
// set to false to extract a slice
reslice->SetOverwriteMode(false);
reslice->Modified();
mitk::ExtractSliceFilter::Pointer extractor = mitk::ExtractSliceFilter::New(reslice);
extractor->SetInput(image);
extractor->SetTimeStep(timeStep);
extractor->SetWorldGeometry(contourPlane);
extractor->SetVtkOutputRequest(false);
extractor->SetResliceTransformByGeometry(image->GetTimeGeometry()->GetGeometryForTimeStep(timeStep));
extractor->Update();
mitk::Image::Pointer slice = extractor->GetOutput();
return slice;
}
template <unsigned int VImageDimension = 3>
std::vector<mitk::Label::PixelType> GetPixelValuesPresentInImage(mitk::LabelSetImage* labelSetImage)
{
std::vector<mitk::Label::PixelType> pixelsPresent;
mitk::ImagePixelReadAccessor<mitk::LabelSet::PixelType, VImageDimension> readAccessor(labelSetImage);
std::size_t numberOfPixels = 1;
for (size_t dim = 0; dim < VImageDimension; ++dim)
numberOfPixels *= static_cast<std::size_t>(readAccessor.GetDimension(dim));
auto src = readAccessor.GetData();
for (std::size_t i = 0; i < numberOfPixels; ++i)
{
mitk::Label::PixelType pixelVal = *(src + i);
if ( (std::find(pixelsPresent.begin(), pixelsPresent.end(), pixelVal) == pixelsPresent.end()) && (pixelVal != mitk::LabelSetImage::UnlabeledValue) )
pixelsPresent.push_back(pixelVal);
}
return pixelsPresent;
}
template <unsigned int VImageDimension = 3>
ModifyLabelActionTrigerred ModifyLabelProcessing(mitk::LabelSetImage* labelSetImage,
mitk::SurfaceInterpolationController::Pointer surfaceInterpolator,
unsigned int timePoint)
{
auto currentLayerID = labelSetImage->GetActiveLayer();
auto numTimeSteps = labelSetImage->GetTimeSteps();
ModifyLabelActionTrigerred actionTriggered = ModifyLabelActionTrigerred::Null;
auto* currentContourList = surfaceInterpolator->GetContours(timePoint, currentLayerID);
while (nullptr == currentContourList)
{
surfaceInterpolator->OnAddLayer();
currentContourList = surfaceInterpolator->GetContours(timePoint, currentLayerID);
}
mitk::LabelSetImage::Pointer labelSetImage2 = labelSetImage->Clone();
mitk::ImagePixelReadAccessor<mitk::LabelSet::PixelType, VImageDimension> readAccessor(labelSetImage2.GetPointer());
for (auto& contour : *currentContourList)
{
mitk::Label::PixelType contourPixelValue;
itk::Index<3> itkIndex;
labelSetImage2->GetGeometry()->WorldToIndex(contour.ContourPoint, itkIndex);
if (VImageDimension == 4)
{
itk::Index<VImageDimension> time3DIndex;
for (size_t i = 0; i < itkIndex.size(); ++i)
time3DIndex[i] = itkIndex[i];
time3DIndex[3] = timePoint;
contourPixelValue = readAccessor.GetPixelByIndexSafe(time3DIndex);
}
else if (VImageDimension == 3)
{
itk::Index<VImageDimension> geomIndex;
for (size_t i = 0; i < itkIndex.size(); ++i)
geomIndex[i] = itkIndex[i];
contourPixelValue = readAccessor.GetPixelByIndexSafe(geomIndex);
}
if (contour.LabelValue != contourPixelValue)
{
if (contourPixelValue == 0) // Erase label
{
for (size_t t = 0; t < numTimeSteps; ++t)
surfaceInterpolator->RemoveContours(contour.LabelValue, t, currentLayerID);
actionTriggered = ModifyLabelActionTrigerred::Erase;
}
else
{
contour.LabelValue = contourPixelValue;
actionTriggered = ModifyLabelActionTrigerred::Merge;
}
}
}
return actionTriggered;
}
QmitkSlicesInterpolator::QmitkSlicesInterpolator(QWidget *parent, const char * /*name*/)
: QWidget(parent),
m_Interpolator(mitk::SegmentationInterpolationController::New()),
m_SurfaceInterpolator(mitk::SurfaceInterpolationController::GetInstance()),
m_ToolManager(nullptr),
m_Initialized(false),
m_LastSNC(nullptr),
m_LastSliceIndex(0),
m_2DInterpolationEnabled(false),
m_3DInterpolationEnabled(false),
m_PreviousActiveLabelValue(0),
m_CurrentActiveLabelValue(0),
m_PreviousLayerIndex(0),
m_CurrentLayerIndex(0),
m_FirstRun(true)
{
m_GroupBoxEnableExclusiveInterpolationMode = new QGroupBox("Interpolation", this);
QVBoxLayout *vboxLayout = new QVBoxLayout(m_GroupBoxEnableExclusiveInterpolationMode);
m_EdgeDetector = mitk::FeatureBasedEdgeDetectionFilter::New();
m_PointScorer = mitk::PointCloudScoringFilter::New();
m_CmbInterpolation = new QComboBox(m_GroupBoxEnableExclusiveInterpolationMode);
m_CmbInterpolation->addItem("Disabled");
m_CmbInterpolation->addItem("2-Dimensional");
m_CmbInterpolation->addItem("3-Dimensional");
vboxLayout->addWidget(m_CmbInterpolation);
m_BtnApply2D = new QPushButton("Confirm for single slice", m_GroupBoxEnableExclusiveInterpolationMode);
vboxLayout->addWidget(m_BtnApply2D);
m_BtnApplyForAllSlices2D = new QPushButton("Confirm for all slices", m_GroupBoxEnableExclusiveInterpolationMode);
vboxLayout->addWidget(m_BtnApplyForAllSlices2D);
m_BtnApply3D = new QPushButton("Confirm", m_GroupBoxEnableExclusiveInterpolationMode);
vboxLayout->addWidget(m_BtnApply3D);
// T28261
// m_BtnSuggestPlane = new QPushButton("Suggest a plane", m_GroupBoxEnableExclusiveInterpolationMode);
// vboxLayout->addWidget(m_BtnSuggestPlane);
m_BtnReinit3DInterpolation = new QPushButton("Reinit Interpolation", m_GroupBoxEnableExclusiveInterpolationMode);
vboxLayout->addWidget(m_BtnReinit3DInterpolation);
m_ChkShowPositionNodes = new QCheckBox("Show Position Nodes", m_GroupBoxEnableExclusiveInterpolationMode);
vboxLayout->addWidget(m_ChkShowPositionNodes);
this->HideAllInterpolationControls();
connect(m_CmbInterpolation, SIGNAL(currentIndexChanged(int)), this, SLOT(OnInterpolationMethodChanged(int)));
connect(m_BtnApply2D, SIGNAL(clicked()), this, SLOT(OnAcceptInterpolationClicked()));
connect(m_BtnApplyForAllSlices2D, SIGNAL(clicked()), this, SLOT(OnAcceptAllInterpolationsClicked()));
connect(m_BtnApply3D, SIGNAL(clicked()), this, SLOT(OnAccept3DInterpolationClicked()));
connect(m_BtnReinit3DInterpolation, SIGNAL(clicked()), this, SLOT(OnReinit3DInterpolation()));
connect(m_ChkShowPositionNodes, SIGNAL(toggled(bool)), this, SLOT(OnShowMarkers(bool)));
connect(m_ChkShowPositionNodes, SIGNAL(toggled(bool)), this, SIGNAL(SignalShowMarkerNodes(bool)));
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(m_GroupBoxEnableExclusiveInterpolationMode);
this->setLayout(layout);
itk::ReceptorMemberCommand<QmitkSlicesInterpolator>::Pointer command =
itk::ReceptorMemberCommand<QmitkSlicesInterpolator>::New();
command->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnInterpolationInfoChanged);
InterpolationInfoChangedObserverTag = m_Interpolator->AddObserver(itk::ModifiedEvent(), command);
itk::ReceptorMemberCommand<QmitkSlicesInterpolator>::Pointer command2 =
itk::ReceptorMemberCommand<QmitkSlicesInterpolator>::New();
command2->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnSurfaceInterpolationInfoChanged);
SurfaceInterpolationInfoChangedObserverTag = m_SurfaceInterpolator->AddObserver(itk::ModifiedEvent(), command2);
auto command3 = itk::ReceptorMemberCommand<QmitkSlicesInterpolator>::New();
command3->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnInterpolationAborted);
InterpolationAbortedObserverTag = m_Interpolator->AddObserver(itk::AbortEvent(), command3);
// feedback node and its visualization properties
m_FeedbackNode = mitk::DataNode::New();
mitk::CoreObjectFactory::GetInstance()->SetDefaultProperties(m_FeedbackNode);
m_FeedbackNode->SetProperty("binary", mitk::BoolProperty::New(true));
m_FeedbackNode->SetProperty("outline binary", mitk::BoolProperty::New(true));
m_FeedbackNode->SetProperty("color", mitk::ColorProperty::New(255.0, 255.0, 0.0));
m_FeedbackNode->SetProperty("texture interpolation", mitk::BoolProperty::New(false));
m_FeedbackNode->SetProperty("layer", mitk::IntProperty::New(20));
m_FeedbackNode->SetProperty("levelwindow", mitk::LevelWindowProperty::New(mitk::LevelWindow(0, 1)));
m_FeedbackNode->SetProperty("name", mitk::StringProperty::New("Interpolation feedback"));
m_FeedbackNode->SetProperty("opacity", mitk::FloatProperty::New(0.8));
m_FeedbackNode->SetProperty("helper object", mitk::BoolProperty::New(true));
m_InterpolatedSurfaceNode = mitk::DataNode::New();
m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(SURFACE_COLOR_RGB));
m_InterpolatedSurfaceNode->SetProperty("name", mitk::StringProperty::New("Surface Interpolation feedback"));
m_InterpolatedSurfaceNode->SetProperty("opacity", mitk::FloatProperty::New(0.5));
m_InterpolatedSurfaceNode->SetProperty("line width", mitk::FloatProperty::New(4.0f));
m_InterpolatedSurfaceNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
m_InterpolatedSurfaceNode->SetProperty("helper object", mitk::BoolProperty::New(true));
m_InterpolatedSurfaceNode->SetVisibility(false);
m_3DContourNode = mitk::DataNode::New();
m_3DContourNode->SetProperty("color", mitk::ColorProperty::New(0.0, 0.0, 0.0));
m_3DContourNode->SetProperty("hidden object", mitk::BoolProperty::New(true));
m_3DContourNode->SetProperty("name", mitk::StringProperty::New("Drawn Contours"));
m_3DContourNode->SetProperty("material.representation", mitk::VtkRepresentationProperty::New(VTK_WIREFRAME));
m_3DContourNode->SetProperty("material.wireframeLineWidth", mitk::FloatProperty::New(2.0f));
m_3DContourNode->SetProperty("3DContourContainer", mitk::BoolProperty::New(true));
m_3DContourNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
m_3DContourNode->SetVisibility(false);
QWidget::setContentsMargins(0, 0, 0, 0);
if (QWidget::layout() != nullptr)
{
QWidget::layout()->setContentsMargins(0, 0, 0, 0);
}
// For running 3D Interpolation in background
// create a QFuture and a QFutureWatcher
connect(&m_Watcher, SIGNAL(started()), this, SLOT(StartUpdateInterpolationTimer()));
connect(&m_Watcher, SIGNAL(finished()), this, SLOT(OnSurfaceInterpolationFinished()));
connect(&m_Watcher, SIGNAL(finished()), this, SLOT(StopUpdateInterpolationTimer()));
m_Timer = new QTimer(this);
connect(m_Timer, SIGNAL(timeout()), this, SLOT(ChangeSurfaceColor()));
}
void QmitkSlicesInterpolator::SetDataStorage(mitk::DataStorage::Pointer storage)
{
if (m_DataStorage == storage)
{
return;
}
if (m_DataStorage.IsNotNull())
{
m_DataStorage->RemoveNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkSlicesInterpolator, const mitk::DataNode*>(this, &QmitkSlicesInterpolator::NodeRemoved)
);
}
m_DataStorage = storage;
m_SurfaceInterpolator->SetDataStorage(storage);
if (m_DataStorage.IsNotNull())
{
m_DataStorage->RemoveNodeEvent.AddListener(
mitk::MessageDelegate1<QmitkSlicesInterpolator, const mitk::DataNode*>(this, &QmitkSlicesInterpolator::NodeRemoved)
);
}
}
mitk::DataStorage *QmitkSlicesInterpolator::GetDataStorage()
{
if (m_DataStorage.IsNotNull())
{
return m_DataStorage;
}
else
{
return nullptr;
}
}
void QmitkSlicesInterpolator::InitializeWindow(QmitkRenderWindow* window)
{
auto slicer = window->GetSliceNavigationController();
if (slicer == nullptr)
{
MITK_WARN << "Tried setting up interpolation for a render window that does not have a slice navigation controller set";
return;
}
// Has to be initialized
m_LastSNC = slicer;
itk::MemberCommand<QmitkSlicesInterpolator>::Pointer deleteCommand =
itk::MemberCommand<QmitkSlicesInterpolator>::New();
deleteCommand->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnSliceNavigationControllerDeleted);
m_ControllerToDeleteObserverTag[slicer] = slicer->AddObserver(itk::DeleteEvent(), deleteCommand);
itk::MemberCommand<QmitkSlicesInterpolator>::Pointer sliceChangedCommand =
itk::MemberCommand<QmitkSlicesInterpolator>::New();
sliceChangedCommand->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnSliceChanged);
m_ControllerToSliceObserverTag[slicer] = slicer->AddObserver(mitk::SliceNavigationController::GeometrySliceEvent(nullptr, 0), sliceChangedCommand);
}
void QmitkSlicesInterpolator::Initialize(mitk::ToolManager *toolManager,
const QList<QmitkRenderWindow*>& windows)
{
Q_ASSERT(!windows.empty());
if (m_Initialized)
{
// remove old observers
this->Uninitialize();
}
m_ToolManager = toolManager;
if (m_ToolManager)
{
// set enabled only if a segmentation is selected
mitk::DataNode *node = m_ToolManager->GetWorkingData(0);
QWidget::setEnabled(node != nullptr);
// react whenever the set of selected segmentation changes
m_ToolManager->WorkingDataChanged +=
mitk::MessageDelegate<QmitkSlicesInterpolator>(this, &QmitkSlicesInterpolator::OnToolManagerWorkingDataModified);
m_ToolManager->ReferenceDataChanged += mitk::MessageDelegate<QmitkSlicesInterpolator>(
this, &QmitkSlicesInterpolator::OnToolManagerReferenceDataModified);
auto* timeNavigationController = mitk::RenderingManager::GetInstance()->GetTimeNavigationController();
itk::MemberCommand<QmitkSlicesInterpolator>::Pointer timeChangedCommand =
itk::MemberCommand<QmitkSlicesInterpolator>::New();
timeChangedCommand->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnTimeChanged);
m_ControllerToTimeObserverTag =
timeNavigationController->AddObserver(mitk::TimeNavigationController::TimeEvent(0), timeChangedCommand);
m_TimePoint = timeNavigationController->GetSelectedTimePoint();
// connect to the slice navigation controller. after each change, call the interpolator
for (auto* window : windows)
{
this->InitializeWindow(window);
}
m_ActionToSlicerMap = CreateActionToSlicer(windows);
}
m_Initialized = true;
}
void QmitkSlicesInterpolator::Uninitialize()
{
if (m_ToolManager.IsNotNull())
{
m_ToolManager->WorkingDataChanged -=
mitk::MessageDelegate<QmitkSlicesInterpolator>(this, &QmitkSlicesInterpolator::OnToolManagerWorkingDataModified);
m_ToolManager->ReferenceDataChanged -= mitk::MessageDelegate<QmitkSlicesInterpolator>(
this, &QmitkSlicesInterpolator::OnToolManagerReferenceDataModified);
}
auto* timeNavigationController = mitk::RenderingManager::GetInstance()->GetTimeNavigationController();
timeNavigationController->RemoveObserver(m_ControllerToTimeObserverTag);
for (auto* slicer : m_ControllerToSliceObserverTag.keys())
{
slicer->RemoveObserver(m_ControllerToDeleteObserverTag.take(slicer));
slicer->RemoveObserver(m_ControllerToSliceObserverTag.take(slicer));
}
this->ClearSegmentationObservers();
m_ActionToSlicerMap.clear();
m_ToolManager = nullptr;
m_Initialized = false;
}
QmitkSlicesInterpolator::~QmitkSlicesInterpolator()
{
if (m_Initialized)
{
// remove old observers
this->Uninitialize();
}
WaitForFutures();
if (m_DataStorage.IsNotNull())
{
m_DataStorage->RemoveNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkSlicesInterpolator, const mitk::DataNode*>(this, &QmitkSlicesInterpolator::NodeRemoved)
);
if (m_DataStorage->Exists(m_3DContourNode))
m_DataStorage->Remove(m_3DContourNode);
if (m_DataStorage->Exists(m_InterpolatedSurfaceNode))
m_DataStorage->Remove(m_InterpolatedSurfaceNode);
}
// remove observer
m_Interpolator->RemoveObserver(InterpolationAbortedObserverTag);
m_Interpolator->RemoveObserver(InterpolationInfoChangedObserverTag);
m_SurfaceInterpolator->RemoveObserver(SurfaceInterpolationInfoChangedObserverTag);
m_SurfaceInterpolator->UnsetSelectedImage();
delete m_Timer;
}
/**
External enableization...
*/
void QmitkSlicesInterpolator::setEnabled(bool enable)
{
QWidget::setEnabled(enable);
// Set the gui elements of the different interpolation modi enabled
if (enable)
{
if (m_2DInterpolationEnabled)
{
this->Show2DInterpolationControls(true);
m_Interpolator->Activate2DInterpolation(true);
}
else if (m_3DInterpolationEnabled)
{
this->Show3DInterpolationControls(true);
this->Show3DInterpolationResult(true);
}
}
// Set all gui elements of the interpolation disabled
else
{
this->HideAllInterpolationControls();
this->Show3DInterpolationResult(false);
}
}
void QmitkSlicesInterpolator::On2DInterpolationEnabled(bool status)
{
OnInterpolationActivated(status);
m_Interpolator->Activate2DInterpolation(status);
}
void QmitkSlicesInterpolator::On3DInterpolationEnabled(bool status)
{
On3DInterpolationActivated(status);
}
void QmitkSlicesInterpolator::OnInterpolationDisabled(bool status)
{
if (status)
{
OnInterpolationActivated(!status);
On3DInterpolationActivated(!status);
this->Show3DInterpolationResult(false);
}
}
void QmitkSlicesInterpolator::HideAllInterpolationControls()
{
this->Show2DInterpolationControls(false);
this->Show3DInterpolationControls(false);
}
void QmitkSlicesInterpolator::Show2DInterpolationControls(bool show)
{
m_BtnApply2D->setVisible(show);
m_BtnApplyForAllSlices2D->setVisible(show);
}
void QmitkSlicesInterpolator::Show3DInterpolationControls(bool show)
{
m_BtnApply3D->setVisible(show);
// T28261
// m_BtnSuggestPlane->setVisible(show);
m_ChkShowPositionNodes->setVisible(show);
m_BtnReinit3DInterpolation->setVisible(show);
}
void QmitkSlicesInterpolator::OnInterpolationMethodChanged(int index)
{
switch (index)
{
case 0: // Disabled
m_GroupBoxEnableExclusiveInterpolationMode->setTitle("Interpolation");
this->HideAllInterpolationControls();
this->OnInterpolationActivated(false);
this->On3DInterpolationActivated(false);
this->Show3DInterpolationResult(false);
m_Interpolator->Activate2DInterpolation(false);
break;
case 1: // 2D
m_GroupBoxEnableExclusiveInterpolationMode->setTitle("Interpolation (Enabled)");
this->HideAllInterpolationControls();
this->Show2DInterpolationControls(true);
this->OnInterpolationActivated(true);
this->On3DInterpolationActivated(false);
this->Show3DInterpolationResult(false);
m_Interpolator->Activate2DInterpolation(true);
break;
case 2: // 3D
m_GroupBoxEnableExclusiveInterpolationMode->setTitle("Interpolation (Enabled)");
this->HideAllInterpolationControls();
this->Show3DInterpolationControls(true);
this->OnInterpolationActivated(false);
this->On3DInterpolationActivated(true);
m_Interpolator->Activate2DInterpolation(false);
break;
default:
MITK_ERROR << "Unknown interpolation method!";
m_CmbInterpolation->setCurrentIndex(0);
break;
}
}
void QmitkSlicesInterpolator::OnShowMarkers(bool state)
{
mitk::DataStorage::SetOfObjects::ConstPointer allContourMarkers =
m_DataStorage->GetSubset(mitk::NodePredicateProperty::New("isContourMarker", mitk::BoolProperty::New(true)));
for (mitk::DataStorage::SetOfObjects::ConstIterator it = allContourMarkers->Begin(); it != allContourMarkers->End();
++it)
{
it->Value()->SetProperty("helper object", mitk::BoolProperty::New(!state));
}
}
void QmitkSlicesInterpolator::OnToolManagerWorkingDataModified()
{
this->ClearSegmentationObservers();
if (m_ToolManager->GetWorkingData(0) != nullptr)
{
m_Segmentation = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData());
auto labelSetImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());
m_BtnReinit3DInterpolation->setEnabled(true);
try {
if (m_SegmentationObserverTags.find(labelSetImage) == m_SegmentationObserverTags.end())
{
auto command2 = itk::MemberCommand<QmitkSlicesInterpolator>::New();
command2->SetCallbackFunction(this, &QmitkSlicesInterpolator::OnModifyLabelChanged);
auto workingImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());
m_SegmentationObserverTags[workingImage] = workingImage->AddObserver(itk::ModifiedEvent(), command2);
}
}
catch (const std::exception& e)
{
MITK_ERROR << "Error casting node data to LabelSetImage\n";
}
}
else
{
// If no workingdata is set, remove the interpolation feedback
this->GetDataStorage()->Remove(m_FeedbackNode);
m_FeedbackNode->SetData(nullptr);
this->GetDataStorage()->Remove(m_3DContourNode);
m_3DContourNode->SetData(nullptr);
this->GetDataStorage()->Remove(m_InterpolatedSurfaceNode);
m_InterpolatedSurfaceNode->SetData(nullptr);
m_BtnReinit3DInterpolation->setEnabled(false);
m_CmbInterpolation->setCurrentIndex(0);
return;
}
// Updating the current selected segmentation for the 3D interpolation
this->SetCurrentContourListID();
if (m_2DInterpolationEnabled)
{
OnInterpolationActivated(true); // re-initialize if needed
}
}
void QmitkSlicesInterpolator::OnToolManagerReferenceDataModified()
{
}
void QmitkSlicesInterpolator::OnTimeChanged(itk::Object *sender, const itk::EventObject &e)
{
if (!dynamic_cast<const mitk::TimeNavigationController::TimeEvent*>(&e))
{
return;
}
const auto* timeNavigationController = dynamic_cast<mitk::TimeNavigationController*>(sender);
if (nullptr == timeNavigationController)
{
return;
}
m_TimePoint = timeNavigationController->GetSelectedTimePoint();
if (m_Watcher.isRunning())
m_Watcher.waitForFinished();
if (m_TimePoint != m_SurfaceInterpolator->GetCurrentTimePoint())
{
m_SurfaceInterpolator->SetCurrentTimePoint(m_TimePoint);
if (m_3DInterpolationEnabled)
{
m_3DContourNode->SetData(nullptr);
m_InterpolatedSurfaceNode->SetData(nullptr);
}
m_SurfaceInterpolator->Modified();
}
if (nullptr == m_LastSNC)
{
return;
}
if (TranslateAndInterpolateChangedSlice(m_LastSNC->GetCreatedWorldGeometry()))
{
m_LastSNC->GetRenderer()->RequestUpdate();
}
}
void QmitkSlicesInterpolator::OnSliceChanged(itk::Object *sender, const itk::EventObject &e)
{
if (!dynamic_cast<const mitk::SliceNavigationController::GeometrySliceEvent*>(&e))
{
return;
}
auto sliceNavigationController = dynamic_cast<mitk::SliceNavigationController*>(sender);
if (nullptr == sliceNavigationController)
{
return;
}
if(m_2DInterpolationEnabled)
{
this->On2DInterpolationEnabled(m_2DInterpolationEnabled);
}
if (TranslateAndInterpolateChangedSlice(e, sliceNavigationController))
{
sliceNavigationController->GetRenderer()->RequestUpdate();
}
}
bool QmitkSlicesInterpolator::TranslateAndInterpolateChangedSlice(const itk::EventObject& e,
mitk::SliceNavigationController* sliceNavigationController)
{
const mitk::SliceNavigationController::GeometrySliceEvent* event =
dynamic_cast<const mitk::SliceNavigationController::GeometrySliceEvent*>(&e);
mitk::TimeGeometry* timeGeometry = event->GetTimeGeometry();
m_LastSNC = sliceNavigationController;
return this->TranslateAndInterpolateChangedSlice(timeGeometry);
}
bool QmitkSlicesInterpolator::TranslateAndInterpolateChangedSlice(const mitk::TimeGeometry* timeGeometry)
{
if (!m_2DInterpolationEnabled)
{
return false;
}
if (nullptr == timeGeometry)
{
return false;
}
if (!timeGeometry->IsValidTimePoint(m_TimePoint))
{
return false;
}
mitk::SlicedGeometry3D* slicedGeometry =
dynamic_cast<mitk::SlicedGeometry3D*>(timeGeometry->GetGeometryForTimePoint(m_TimePoint).GetPointer());
if (nullptr == slicedGeometry)
{
return false;
}
mitk::PlaneGeometry* plane = dynamic_cast<mitk::PlaneGeometry*>(slicedGeometry->GetPlaneGeometry(m_LastSNC->GetStepper()->GetPos()));
if (nullptr == plane)
{
return false;
}
this->Interpolate(plane);
return true;
}
void QmitkSlicesInterpolator::OnLayerChanged()
{
auto* workingNode = m_ToolManager->GetWorkingData(0);
if (workingNode != nullptr)
{
m_3DContourNode->SetData(nullptr);
this->Show3DInterpolationResult(false);
}
if (m_3DInterpolationEnabled)
{
m_SurfaceInterpolator->Modified();
}
if (m_2DInterpolationEnabled)
{
m_FeedbackNode->SetData(nullptr);
this->OnInterpolationActivated(true);
m_LastSNC->SendSlice();
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
this->UpdateVisibleSuggestion();
}
void QmitkSlicesInterpolator::Interpolate(mitk::PlaneGeometry *plane)
{
if (nullptr == m_ToolManager)
{
return;
}
mitk::DataNode* node = m_ToolManager->GetWorkingData(0);
if (nullptr == node)
{
return;
}
m_Segmentation = dynamic_cast<mitk::Image*>(node->GetData());
if (nullptr == m_Segmentation)
{
return;
}
if (!m_Segmentation->GetTimeGeometry()->IsValidTimePoint(m_TimePoint))
{
MITK_WARN << "Cannot interpolate WorkingImage. Passed time point is not within the time bounds of WorkingImage. "
"Time point: "
<< m_TimePoint;
return;
}
const auto timeStep = m_Segmentation->GetTimeGeometry()->TimePointToTimeStep(m_TimePoint);
int clickedSliceDimension = -1;
int clickedSliceIndex = -1;
// calculate real slice position, i.e. slice of the image
mitk::SegTool2D::DetermineAffectedImageSlice(m_Segmentation, plane, clickedSliceDimension, clickedSliceIndex);
mitk::Image::Pointer interpolation =
m_Interpolator->Interpolate(clickedSliceDimension, clickedSliceIndex, plane, timeStep);
m_FeedbackNode->SetData(interpolation);
// maybe just have a variable that stores the active label color.
if (m_ToolManager)
{
auto* workingNode = m_ToolManager->GetWorkingData(0);
if (workingNode != nullptr)
{
auto* activeLabel = dynamic_cast<mitk::LabelSetImage*>(workingNode->GetData())->GetActiveLabelSet()->GetActiveLabel();
if (nullptr != activeLabel)
{
auto activeColor = activeLabel->GetColor();
m_FeedbackNode->SetProperty("color", mitk::ColorProperty::New(activeColor));
}
}
}
m_LastSliceIndex = clickedSliceIndex;
}
void QmitkSlicesInterpolator::OnSurfaceInterpolationFinished()
{
mitk::Surface::Pointer interpolatedSurface = m_SurfaceInterpolator->GetInterpolationResult();
mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0);
mitk::PlaneGeometry::Pointer slicingPlane = mitk::PlaneGeometry::New();
mitk::Vector3D slicingPlaneNormalVector;
FillVector3D(slicingPlaneNormalVector,0.0,1.0,0.0);
mitk::Point3D origin;
FillVector3D(origin, 0.0, 0.0, 0.0);
slicingPlane->InitializePlane(origin, slicingPlaneNormalVector);
if (interpolatedSurface.IsNotNull() && workingNode)
{
m_BtnApply3D->setEnabled(true);
// T28261
// m_BtnSuggestPlane->setEnabled(true);
m_InterpolatedSurfaceNode->SetData(interpolatedSurface);
m_3DContourNode->SetData(m_SurfaceInterpolator->GetContoursAsSurface());
this->Show3DInterpolationResult(true);
if (!m_DataStorage->Exists(m_InterpolatedSurfaceNode))
{
m_DataStorage->Add(m_InterpolatedSurfaceNode);
}
}
else if (interpolatedSurface.IsNull())
{
m_BtnApply3D->setEnabled(false);
// T28261
// m_BtnSuggestPlane->setEnabled(false);
if (m_DataStorage->Exists(m_InterpolatedSurfaceNode))
{
this->Show3DInterpolationResult(false);
}
}
m_BtnReinit3DInterpolation->setEnabled(true);
for (auto* slicer : m_ControllerToSliceObserverTag.keys())
{
slicer->GetRenderer()->RequestUpdate();
}
m_SurfaceInterpolator->ReinitializeInterpolation();
}
void QmitkSlicesInterpolator::OnAcceptInterpolationClicked()
{
auto* workingNode = m_ToolManager->GetWorkingData(0);
auto* planeGeometry = m_LastSNC->GetCurrentPlaneGeometry();
auto* interpolatedPreview = dynamic_cast<mitk::Image*>(m_FeedbackNode->GetData());
if (nullptr == workingNode || nullptr == interpolatedPreview)
return;
auto* segmentationImage = dynamic_cast<mitk::LabelSetImage*>(workingNode->GetData());
if (nullptr == segmentationImage)
return;
if (!segmentationImage->GetTimeGeometry()->IsValidTimePoint(m_TimePoint))
{
MITK_WARN << "Cannot accept interpolation. Time point selected by SliceNavigationController is not within the "
"time bounds of segmentation. Time point: "
<< m_TimePoint;
return;
}
const auto timeStep = segmentationImage->GetTimeGeometry()->TimePointToTimeStep(m_TimePoint);
auto interpolatedSlice = mitk::SegTool2D::GetAffectedImageSliceAs2DImage(planeGeometry, segmentationImage, timeStep)->Clone();
auto labelSet = segmentationImage->GetActiveLabelSet();
auto activeValue = labelSet->GetActiveLabel()->GetValue();
mitk::TransferLabelContentAtTimeStep(
interpolatedPreview,
interpolatedSlice,
labelSet,
timeStep,
0,
mitk::LabelSetImage::UnlabeledValue,
false,
{ {0, mitk::LabelSetImage::UnlabeledValue}, {1, activeValue} }
);
mitk::SegTool2D::WriteBackSegmentationResult(workingNode, planeGeometry, interpolatedSlice, timeStep);
m_FeedbackNode->SetData(nullptr);
}
void QmitkSlicesInterpolator::AcceptAllInterpolations(mitk::SliceNavigationController *slicer)
{
/*
* What exactly is done here:
* 1. We create an empty diff image for the current segmentation
* 2. All interpolated slices are written into the diff image
* 3. Then the diffimage is applied to the original segmentation
*/
if (m_Segmentation)
{
mitk::Image::Pointer segmentation3D = m_Segmentation;
unsigned int timeStep = 0;
if (4 == m_Segmentation->GetDimension())
{
const auto* geometry = m_Segmentation->GetTimeGeometry();
if (!geometry->IsValidTimePoint(m_TimePoint))
{
MITK_WARN << "Cannot accept all interpolations. Time point selected by passed SliceNavigationController is not "
"within the time bounds of segmentation. Time point: "
<< m_TimePoint;
return;
}
mitk::Image::Pointer activeLabelImage;
try
{
auto labelSetImage = dynamic_cast<mitk::LabelSetImage *>(m_Segmentation);
activeLabelImage = labelSetImage->CreateLabelMask(labelSetImage->GetActiveLabelSet()->GetActiveLabel()->GetValue(), true, 0);
}
catch (const std::exception& e)
{
MITK_ERROR << e.what() << " | NO LABELSETIMAGE IN WORKING NODE\n";
}
m_Interpolator->SetSegmentationVolume(activeLabelImage);
timeStep = geometry->TimePointToTimeStep(m_TimePoint);
auto timeSelector = mitk::ImageTimeSelector::New();
timeSelector->SetInput(m_Segmentation);
timeSelector->SetTimeNr(timeStep);
timeSelector->Update();
segmentation3D = timeSelector->GetOutput();
}
// Create an empty diff image for the undo operation
auto diffImage = mitk::Image::New();
diffImage->Initialize(segmentation3D);
// Create scope for ImageWriteAccessor so that the accessor is destroyed right after use
{
mitk::ImageWriteAccessor accessor(diffImage);
// Set all pixels to zero
auto pixelType = mitk::MakeScalarPixelType<mitk::Tool::DefaultSegmentationDataType>();
// For legacy purpose support former pixel type of segmentations (before multilabel)
if (itk::IOComponentEnum::UCHAR == m_Segmentation->GetImageDescriptor()->GetChannelDescriptor().GetPixelType().GetComponentType())
pixelType = mitk::MakeScalarPixelType<unsigned char>();
memset(accessor.GetData(), 0, pixelType.GetSize() * diffImage->GetDimension(0) * diffImage->GetDimension(1) * diffImage->GetDimension(2));
}
// Since we need to shift the plane it must be clone so that the original plane isn't altered
auto slicedGeometry = m_Segmentation->GetSlicedGeometry();
auto planeGeometry = slicer->GetCurrentPlaneGeometry()->Clone();
int sliceDimension = -1;
int sliceIndex = -1;
mitk::SegTool2D::DetermineAffectedImageSlice(m_Segmentation, planeGeometry, sliceDimension, sliceIndex);
const auto numSlices = m_Segmentation->GetDimension(sliceDimension);
mitk::ProgressBar::GetInstance()->AddStepsToDo(numSlices);
std::atomic_uint totalChangedSlices;
// Reuse interpolation algorithm instance for each slice to cache boundary calculations
auto algorithm = mitk::ShapeBasedInterpolationAlgorithm::New();
// Distribute slice interpolations to multiple threads
const auto numThreads = std::min(std::thread::hardware_concurrency(), numSlices);
// const auto numThreads = 1;
std::vector<std::vector<unsigned int>> sliceIndices(numThreads);
for (std::remove_const_t<decltype(numSlices)> sliceIndex = 0; sliceIndex < numSlices; ++sliceIndex)
sliceIndices[sliceIndex % numThreads].push_back(sliceIndex);
std::vector<std::thread> threads;
threads.reserve(numThreads);
// This lambda will be executed by the threads
auto interpolate = [=, &interpolator = m_Interpolator, &totalChangedSlices](unsigned int threadIndex)
{
auto clonedPlaneGeometry = planeGeometry->Clone();
auto origin = clonedPlaneGeometry->GetOrigin();
// Go through the sliced indices
for (auto sliceIndex : sliceIndices[threadIndex])
{
slicedGeometry->WorldToIndex(origin, origin);
origin[sliceDimension] = sliceIndex;
slicedGeometry->IndexToWorld(origin, origin);
clonedPlaneGeometry->SetOrigin(origin);
auto interpolation = interpolator->Interpolate(sliceDimension, sliceIndex, clonedPlaneGeometry, timeStep, algorithm);
if (interpolation.IsNotNull())
{
// Setting up the reslicing pipeline which allows us to write the interpolation results back into the image volume
auto reslicer = vtkSmartPointer<mitkVtkImageOverwrite>::New();
// Set overwrite mode to true to write back to the image volume
reslicer->SetInputSlice(interpolation->GetSliceData()->GetVtkImageAccessor(interpolation)->GetVtkImageData());
reslicer->SetOverwriteMode(true);
reslicer->Modified();
auto diffSliceWriter = mitk::ExtractSliceFilter::New(reslicer);
diffSliceWriter->SetInput(diffImage);
diffSliceWriter->SetTimeStep(0);
diffSliceWriter->SetWorldGeometry(clonedPlaneGeometry);
diffSliceWriter->SetVtkOutputRequest(true);
diffSliceWriter->SetResliceTransformByGeometry(diffImage->GetTimeGeometry()->GetGeometryForTimeStep(0));
diffSliceWriter->Modified();
diffSliceWriter->Update();
++totalChangedSlices;
}
mitk::ProgressBar::GetInstance()->Progress();
}
};
m_Interpolator->EnableSliceImageCache();
// Do the interpolation here.
for (size_t threadIndex = 0; threadIndex < numThreads; ++threadIndex)
{
interpolate(threadIndex);
}
m_Interpolator->DisableSliceImageCache();
const mitk::Label::PixelType newDestinationLabel = dynamic_cast<mitk::LabelSetImage *>(m_Segmentation)->GetActiveLabelSet()->GetActiveLabel()->GetValue();
// Do and Undo Operations
if (totalChangedSlices > 0)
{
// Create do/undo operations
auto* doOp = new mitk::ApplyDiffImageOperation(mitk::OpTEST, m_Segmentation, diffImage, timeStep);
auto* undoOp = new mitk::ApplyDiffImageOperation(mitk::OpTEST, m_Segmentation, diffImage, timeStep);
undoOp->SetFactor(-1.0);
auto comment = "Confirm all interpolations (" + std::to_string(totalChangedSlices) + ")";
auto* undoStackItem = new mitk::OperationEvent(mitk::DiffImageApplier::GetInstanceForUndo(), doOp, undoOp, comment);
mitk::OperationEvent::IncCurrGroupEventId();
mitk::OperationEvent::IncCurrObjectEventId();
mitk::UndoController::GetCurrentUndoModel()->SetOperationEvent(undoStackItem);
mitk::DiffImageApplier::GetInstanceForUndo()->SetDestinationLabel(newDestinationLabel);
// Apply the changes to the original image
mitk::DiffImageApplier::GetInstanceForUndo()->ExecuteOperation(doOp);
}
m_FeedbackNode->SetData(nullptr);
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkSlicesInterpolator::FinishInterpolation(mitk::SliceNavigationController *slicer)
{
// this redirect is for calling from outside
if (slicer == nullptr)
OnAcceptAllInterpolationsClicked();
else
AcceptAllInterpolations(slicer);
}
void QmitkSlicesInterpolator::OnAcceptAllInterpolationsClicked()
{
QMenu orientationPopup(this);
for (auto it = m_ActionToSlicerMap.begin(); it != m_ActionToSlicerMap.end(); ++it)
{
orientationPopup.addAction(it->first);
}
connect(&orientationPopup, SIGNAL(triggered(QAction *)), this, SLOT(OnAcceptAllPopupActivated(QAction *)));
orientationPopup.exec(QCursor::pos());
}
void QmitkSlicesInterpolator::OnAccept3DInterpolationClicked()
{
auto referenceImage = GetData<mitk::Image>(m_ToolManager->GetReferenceData(0));
auto* segmentationDataNode = m_ToolManager->GetWorkingData(0);
auto labelSetImage = dynamic_cast<mitk::LabelSetImage*>(segmentationDataNode->GetData());
auto activeLabelColor = labelSetImage->GetActiveLabelSet()->GetActiveLabel()->GetColor();
std::string activeLabelName = labelSetImage->GetActiveLabelSet()->GetActiveLabel()->GetName();
auto segmentation = GetData<mitk::Image>(segmentationDataNode);
if (referenceImage.IsNull() || segmentation.IsNull())
return;
const auto* segmentationGeometry = segmentation->GetTimeGeometry();
if (!referenceImage->GetTimeGeometry()->IsValidTimePoint(m_TimePoint) ||
!segmentationGeometry->IsValidTimePoint(m_TimePoint))
{
MITK_WARN << "Cannot accept interpolation. Current time point is not within the time bounds of the patient image and segmentation.";
return;
}
auto interpolatedSurface = GetData<mitk::Surface>(m_InterpolatedSurfaceNode);
if (interpolatedSurface.IsNull())
return;
auto surfaceToImageFilter = mitk::SurfaceToImageFilter::New();
surfaceToImageFilter->SetImage(referenceImage);
surfaceToImageFilter->SetMakeOutputBinary(true);
surfaceToImageFilter->SetUShortBinaryPixelType(itk::IOComponentEnum::USHORT == segmentation->GetPixelType().GetComponentType());
surfaceToImageFilter->SetInput(interpolatedSurface);
surfaceToImageFilter->Update();
mitk::Image::Pointer interpolatedSegmentation = surfaceToImageFilter->GetOutput();
auto timeStep = segmentationGeometry->TimePointToTimeStep(m_TimePoint);
const mitk::Label::PixelType newDestinationLabel = labelSetImage->GetActiveLabelSet()->GetActiveLabel()->GetValue();
TransferLabelContentAtTimeStep(
interpolatedSegmentation,
labelSetImage,
labelSetImage->GetActiveLabelSet(),
timeStep,
0,
0,
false,
{{1, newDestinationLabel}},
mitk::MultiLabelSegmentation::MergeStyle::Merge,
mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
this->Show3DInterpolationResult(false);
std::string name = segmentationDataNode->GetName() + " 3D-interpolation - " + activeLabelName;
mitk::TimeBounds timeBounds;
if (1 < interpolatedSurface->GetTimeSteps())
{
name += "_t" + std::to_string(timeStep);
auto* polyData = vtkPolyData::New();
polyData->DeepCopy(interpolatedSurface->GetVtkPolyData(timeStep));
auto surface = mitk::Surface::New();
surface->SetVtkPolyData(polyData);
interpolatedSurface = surface;
timeBounds = segmentationGeometry->GetTimeBounds(timeStep);
}
else
{
timeBounds = segmentationGeometry->GetTimeBounds(0);
}
auto* surfaceGeometry = static_cast<mitk::ProportionalTimeGeometry*>(interpolatedSurface->GetTimeGeometry());
surfaceGeometry->SetFirstTimePoint(timeBounds[0]);
surfaceGeometry->SetStepDuration(timeBounds[1] - timeBounds[0]);
// Typical file formats for surfaces do not save any time-related information. As a workaround at least for MITK scene files, we have the
// possibility to seralize this information as properties.
interpolatedSurface->SetProperty("ProportionalTimeGeometry.FirstTimePoint", mitk::FloatProperty::New(surfaceGeometry->GetFirstTimePoint()));
interpolatedSurface->SetProperty("ProportionalTimeGeometry.StepDuration", mitk::FloatProperty::New(surfaceGeometry->GetStepDuration()));
auto interpolatedSurfaceDataNode = mitk::DataNode::New();
interpolatedSurfaceDataNode->SetData(interpolatedSurface);
interpolatedSurfaceDataNode->SetName(name);
interpolatedSurfaceDataNode->SetOpacity(0.7f);
interpolatedSurfaceDataNode->SetColor(activeLabelColor);
m_DataStorage->Add(interpolatedSurfaceDataNode, segmentationDataNode);
}
void QmitkSlicesInterpolator::OnReinit3DInterpolation()
{
// Step 1. Load from the isContourPlaneGeometry nodes the contourNodes.
mitk::NodePredicateProperty::Pointer pred =
mitk::NodePredicateProperty::New("isContourPlaneGeometry", mitk::BoolProperty::New(true));
mitk::DataStorage::SetOfObjects::ConstPointer contourNodes =
m_DataStorage->GetDerivations(m_ToolManager->GetWorkingData(0), pred);
if (contourNodes->Size() != 0)
{
std::vector<const mitk::PlaneGeometry*> contourPlanes;
std::vector<mitk::Surface::Pointer> contourList;
if (m_ToolManager->GetWorkingData(0) != nullptr)
{
try
{
auto labelSetImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());
auto activeLayerID = labelSetImage->GetActiveLayer();
if (!labelSetImage->GetTimeGeometry()->IsValidTimePoint(m_TimePoint))
{
MITK_ERROR << "Invalid time point requested for interpolation pipeline.";
return;
}
// Adding layer, label and timeStep information for the contourNodes.
for (auto it = contourNodes->Begin(); it != contourNodes->End(); ++it)
{
auto contourNode = it->Value();
auto layerID = dynamic_cast<mitk::UIntProperty *>(contourNode->GetProperty("layerID"))->GetValue();
auto labelID = dynamic_cast<mitk::UShortProperty *>(contourNode->GetProperty("labelID"))->GetValue();
auto timeStep = dynamic_cast<mitk::IntProperty *>(contourNode->GetProperty("timeStep"))->GetValue();
auto px = dynamic_cast<mitk::DoubleProperty *>(contourNode->GetProperty("px"))->GetValue();
auto py = dynamic_cast<mitk::DoubleProperty *>(contourNode->GetProperty("py"))->GetValue();
auto pz = dynamic_cast<mitk::DoubleProperty *>(contourNode->GetProperty("pz"))->GetValue();
// auto layerImage = labelSetImage->GetLayerImage(layerID);
auto planeGeometry = dynamic_cast<mitk::PlanarFigure *>(contourNode->GetData())->GetPlaneGeometry();
labelSetImage->SetActiveLayer(layerID);
auto sliceImage = ExtractSliceFromImage(labelSetImage, planeGeometry, timeStep);
labelSetImage->SetActiveLayer(activeLayerID);
mitk::ImageToContourFilter::Pointer contourExtractor = mitk::ImageToContourFilter::New();
contourExtractor->SetInput(sliceImage);
contourExtractor->SetContourValue(labelID);
contourExtractor->Update();
mitk::Surface::Pointer contour = contourExtractor->GetOutput();
if (contour->GetVtkPolyData()->GetNumberOfPoints() == 0)
continue;
vtkSmartPointer<vtkIntArray> intArray = vtkSmartPointer<vtkIntArray>::New();
intArray->InsertNextValue(labelID);
intArray->InsertNextValue(layerID);
intArray->InsertNextValue(timeStep);
contour->GetVtkPolyData()->GetFieldData()->AddArray(intArray);
vtkSmartPointer<vtkDoubleArray> doubleArray = vtkSmartPointer<vtkDoubleArray>::New();
doubleArray->InsertNextValue(px);
doubleArray->InsertNextValue(py);
doubleArray->InsertNextValue(pz);
contour->GetVtkPolyData()->GetFieldData()->AddArray(doubleArray);
contour->DisconnectPipeline();
contourList.push_back(contour);
contourPlanes.push_back(planeGeometry);
}
labelSetImage->SetActiveLayer(activeLayerID);
// size_t activeLayer = labelSetImage->GetActiveLayer();
for (size_t l = 0; l < labelSetImage->GetNumberOfLayers(); ++l)
{
this->OnAddLabelSetConnection(l);
}
// labelSetImage->SetActiveLayer(activeLayer);
m_SurfaceInterpolator->CompleteReinitialization(contourList, contourPlanes);
}
catch(const std::exception& e)
{
MITK_ERROR << "Exception thrown casting toolmanager working data to labelsetImage";
}
}
}
else
{
m_BtnApply3D->setEnabled(false);
QMessageBox errorInfo;
errorInfo.setWindowTitle("Reinitialize surface interpolation");
errorInfo.setIcon(QMessageBox::Information);
errorInfo.setText("No contours available for the selected segmentation!");
errorInfo.exec();
}
}
void QmitkSlicesInterpolator::OnAcceptAllPopupActivated(QAction *action)
{
try
{
auto iter = m_ActionToSlicerMap.find(action);
if (iter != m_ActionToSlicerMap.end())
{
mitk::SliceNavigationController *slicer = iter->second;
this->AcceptAllInterpolations(slicer);
}
}
catch (...)
{
/* Showing message box with possible memory error */
QMessageBox errorInfo;
errorInfo.setWindowTitle("Interpolation Process");
errorInfo.setIcon(QMessageBox::Critical);
errorInfo.setText("An error occurred during interpolation. Possible cause: Not enough memory!");
errorInfo.exec();
// additional error message on std::cerr
std::cerr << "Ill construction in " __FILE__ " l. " << __LINE__ << std::endl;
}
}
void QmitkSlicesInterpolator::OnInterpolationActivated(bool on)
{
m_2DInterpolationEnabled = on;
try
{
if (m_DataStorage.IsNotNull())
{
if (on && !m_DataStorage->Exists(m_FeedbackNode))
{
m_DataStorage->Add(m_FeedbackNode);
}
}
}
catch (...)
{
// don't care (double add/remove)
}
if (m_ToolManager)
{
mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0);
mitk::DataNode *referenceNode = m_ToolManager->GetReferenceData(0);
QWidget::setEnabled(workingNode != nullptr);
m_BtnApply2D->setEnabled(on);
m_FeedbackNode->SetVisibility(on);
if (!on)
{
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
return;
}
if (workingNode)
{
auto labelSetImage = dynamic_cast<mitk::LabelSetImage *>(workingNode->GetData());
if (nullptr == labelSetImage)
{
MITK_ERROR << "NO LABELSETIMAGE IN WORKING NODE\n";
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
return;
}
auto* activeLabel = labelSetImage->GetActiveLabelSet()->GetActiveLabel();
auto* segmentation = dynamic_cast<mitk::Image*>(workingNode->GetData());
if (nullptr != activeLabel && nullptr != segmentation)
{
auto activeLabelImage = labelSetImage->CreateLabelMask(activeLabel->GetValue(), true, 0);
m_Interpolator->SetSegmentationVolume(activeLabelImage);
if (referenceNode)
{
mitk::Image *referenceImage = dynamic_cast<mitk::Image *>(referenceNode->GetData());
m_Interpolator->SetReferenceVolume(referenceImage); // may be nullptr
}
}
}
}
this->UpdateVisibleSuggestion();
}
void QmitkSlicesInterpolator::Run3DInterpolation()
{
m_SurfaceInterpolator->Interpolate();
}
void QmitkSlicesInterpolator::StartUpdateInterpolationTimer()
{
m_Timer->start(500);
}
void QmitkSlicesInterpolator::StopUpdateInterpolationTimer()
{
if(m_ToolManager)
{
auto* workingNode = m_ToolManager->GetWorkingData(0);
auto activeColor = dynamic_cast<mitk::LabelSetImage*>(workingNode->GetData())->GetActiveLabelSet()->GetActiveLabel()->GetColor();
m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(activeColor));
m_3DContourNode->SetProperty("color", mitk::ColorProperty::New(activeColor));
}
m_Timer->stop();
}
void QmitkSlicesInterpolator::ChangeSurfaceColor()
{
float currentColor[3];
m_InterpolatedSurfaceNode->GetColor(currentColor);
m_InterpolatedSurfaceNode->SetProperty("color", mitk::ColorProperty::New(SURFACE_COLOR_RGB));
m_InterpolatedSurfaceNode->Update();
mitk::RenderingManager::GetInstance()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_3DWINDOWS);
}
void QmitkSlicesInterpolator::PrepareInputsFor3DInterpolation()
{
if (m_DataStorage.IsNotNull() && m_ToolManager && m_3DInterpolationEnabled)
{
auto *workingNode = m_ToolManager->GetWorkingData(0);
if (workingNode != nullptr)
{
int ret = QMessageBox::Yes;
if (m_SurfaceInterpolator->EstimatePortionOfNeededMemory() > 0.5)
{
QMessageBox msgBox;
msgBox.setText("Due to short handed system memory the 3D interpolation may be very slow!");
msgBox.setInformativeText("Are you sure you want to activate the 3D interpolation?");
msgBox.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
ret = msgBox.exec();
}
auto labelSetImage = dynamic_cast<mitk::LabelSetImage*>(workingNode->GetData());
auto activeLabel = labelSetImage->GetActiveLabelSet()->GetActiveLabel()->GetValue();
m_SurfaceInterpolator->AddActiveLabelContoursForInterpolation(activeLabel);
if (m_Watcher.isRunning())
m_Watcher.waitForFinished();
if (ret == QMessageBox::Yes)
{
// Maybe set the segmentation node here
- m_Future = QtConcurrent::run(this, &QmitkSlicesInterpolator::Run3DInterpolation);
+ m_Future = QtConcurrent::run(&QmitkSlicesInterpolator::Run3DInterpolation, this);
m_Watcher.setFuture(m_Future);
}
else
{
m_CmbInterpolation->setCurrentIndex(0);
}
}
else
{
QWidget::setEnabled(false);
m_ChkShowPositionNodes->setEnabled(m_3DInterpolationEnabled);
}
}
if (!m_3DInterpolationEnabled)
{
this->Show3DInterpolationResult(false);
m_BtnApply3D->setEnabled(m_3DInterpolationEnabled);
// T28261
// m_BtnSuggestPlane->setEnabled(m_3DInterpolationEnabled);
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkSlicesInterpolator::On3DInterpolationActivated(bool on)
{
m_3DInterpolationEnabled = on;
try
{
// this->PrepareInputsFor3DInterpolation();
m_SurfaceInterpolator->Modified();
}
catch (...)
{
MITK_ERROR << "Error with 3D surface interpolation!";
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkSlicesInterpolator::EnableInterpolation(bool on)
{
// only to be called from the outside world
// just a redirection to OnInterpolationActivated
OnInterpolationActivated(on);
}
void QmitkSlicesInterpolator::Enable3DInterpolation(bool on)
{
// only to be called from the outside world
// just a redirection to OnInterpolationActivated
this->On3DInterpolationActivated(on);
}
void QmitkSlicesInterpolator::UpdateVisibleSuggestion()
{
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkSlicesInterpolator::OnInterpolationInfoChanged(const itk::EventObject & /*e*/)
{
// something (e.g. undo) changed the interpolation info, we should refresh our display
this->UpdateVisibleSuggestion();
}
void QmitkSlicesInterpolator::OnInterpolationAborted(const itk::EventObject& /*e*/)
{
m_CmbInterpolation->setCurrentIndex(0);
m_FeedbackNode->SetData(nullptr);
}
void QmitkSlicesInterpolator::OnSurfaceInterpolationInfoChanged(const itk::EventObject & /*e*/)
{
if (m_Watcher.isRunning())
m_Watcher.waitForFinished();
if (m_3DInterpolationEnabled)
{
m_3DContourNode->SetData(nullptr);
m_InterpolatedSurfaceNode->SetData(nullptr);
auto* workingNode = m_ToolManager->GetWorkingData(0);
if (workingNode == nullptr)
return;
auto* labelSetImage = dynamic_cast<mitk::LabelSetImage*>(workingNode->GetData());
auto* label = labelSetImage->GetActiveLabelSet()->GetActiveLabel();
if (label == nullptr)
return;
m_SurfaceInterpolator->AddActiveLabelContoursForInterpolation(label->GetValue());
- m_Future = QtConcurrent::run(this, &QmitkSlicesInterpolator::Run3DInterpolation);
+ m_Future = QtConcurrent::run(&QmitkSlicesInterpolator::Run3DInterpolation, this);
m_Watcher.setFuture(m_Future);
}
}
void QmitkSlicesInterpolator::SetCurrentContourListID()
{
// New ContourList = hide current interpolation
Show3DInterpolationResult(false);
if (m_DataStorage.IsNotNull() && m_ToolManager && m_LastSNC)
{
mitk::DataNode *workingNode = m_ToolManager->GetWorkingData(0);
try{
auto labelSetImage = dynamic_cast<mitk::LabelSetImage *>(workingNode->GetData());
for (size_t layerID = 0; layerID < labelSetImage->GetNumberOfLayers(); ++layerID)
{
this->OnAddLabelSetConnection(layerID);
}
}
catch (std::exception &e)
{
MITK_ERROR << e.what() << "\n";
}
if (workingNode)
{
QWidget::setEnabled(true);
// In case the time is not valid use 0 to access the time geometry of the working node
unsigned int time_position = 0;
if (!workingNode->GetData()->GetTimeGeometry()->IsValidTimePoint(m_TimePoint))
{
MITK_WARN << "Cannot accept interpolation. Time point selected by SliceNavigationController is not within the time bounds of WorkingImage. Time point: " << m_TimePoint;
return;
}
// Sets up the surface interpolator to accept
time_position = workingNode->GetData()->GetTimeGeometry()->TimePointToTimeStep(m_TimePoint);
mitk::Vector3D spacing = workingNode->GetData()->GetGeometry(time_position)->GetSpacing();
double minSpacing = 100;
double maxSpacing = 0;
for (int i = 0; i < 3; i++)
{
if (spacing[i] < minSpacing)
{
minSpacing = spacing[i];
}
if (spacing[i] > maxSpacing)
{
maxSpacing = spacing[i];
}
}
m_SurfaceInterpolator->SetMaxSpacing(maxSpacing);
m_SurfaceInterpolator->SetMinSpacing(minSpacing);
m_SurfaceInterpolator->SetDistanceImageVolume(50000);
mitk::Image::Pointer segmentationImage;
segmentationImage = dynamic_cast<mitk::Image *>(workingNode->GetData());
m_SurfaceInterpolator->SetCurrentInterpolationSession(segmentationImage);
m_SurfaceInterpolator->SetCurrentTimePoint(m_TimePoint);
}
else
{
QWidget::setEnabled(false);
}
}
}
void QmitkSlicesInterpolator::Show3DInterpolationResult(bool status)
{
if (m_InterpolatedSurfaceNode.IsNotNull())
m_InterpolatedSurfaceNode->SetVisibility(status);
if (m_3DContourNode.IsNotNull())
{
auto allRenderWindows = mitk::BaseRenderer::GetAll3DRenderWindows();
for (auto mapit = allRenderWindows.begin(); mapit != allRenderWindows.end(); ++mapit)
{
m_3DContourNode->SetVisibility(status, mapit->second);
}
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
void QmitkSlicesInterpolator::OnActiveLabelChanged(mitk::Label::PixelType)
{
m_3DContourNode->SetData(nullptr);
m_FeedbackNode->SetData(nullptr);
m_InterpolatedSurfaceNode->SetData(nullptr);
if (m_Watcher.isRunning())
m_Watcher.waitForFinished();
if (m_3DInterpolationEnabled)
{
m_SurfaceInterpolator->Modified();
}
if (m_2DInterpolationEnabled)
{
m_FeedbackNode->SetData(nullptr);
this->OnInterpolationActivated(true);
m_LastSNC->SendSlice();
}
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
this->UpdateVisibleSuggestion();
}
void QmitkSlicesInterpolator::CheckSupportedImageDimension()
{
if (m_ToolManager->GetWorkingData(0))
{
m_Segmentation = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData());
if (m_3DInterpolationEnabled && m_Segmentation && ((m_Segmentation->GetDimension() != 3) || (m_Segmentation->GetDimension() != 4)) )
{
QMessageBox info;
info.setWindowTitle("3D Interpolation Process");
info.setIcon(QMessageBox::Information);
info.setText("3D Interpolation is only supported for 3D/4D images at the moment!");
info.exec();
m_CmbInterpolation->setCurrentIndex(0);
}
}
}
void QmitkSlicesInterpolator::OnSliceNavigationControllerDeleted(const itk::Object *sender,
const itk::EventObject & /*e*/)
{
// Don't know how to avoid const_cast here?!
mitk::SliceNavigationController *slicer =
dynamic_cast<mitk::SliceNavigationController *>(const_cast<itk::Object *>(sender));
if (slicer)
{
m_ControllerToSliceObserverTag.remove(slicer);
m_ControllerToDeleteObserverTag.remove(slicer);
}
}
void QmitkSlicesInterpolator::WaitForFutures()
{
if (m_Watcher.isRunning())
{
m_Watcher.waitForFinished();
}
if (m_PlaneWatcher.isRunning())
{
m_PlaneWatcher.waitForFinished();
}
}
void QmitkSlicesInterpolator::NodeRemoved(const mitk::DataNode* node)
{
if ((m_ToolManager && m_ToolManager->GetWorkingData(0) == node) ||
node == m_3DContourNode ||
node == m_FeedbackNode ||
node == m_InterpolatedSurfaceNode)
{
WaitForFutures();
}
}
void QmitkSlicesInterpolator::OnAddLabelSetConnection(unsigned int layerID)
{
if (m_ToolManager->GetWorkingData(0) != nullptr)
{
try
{
auto workingImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());
auto labelSet = workingImage->GetLabelSet(layerID);
labelSet->RemoveLabelEvent += mitk::MessageDelegate1<QmitkSlicesInterpolator, mitk::Label::PixelType>(
this, &QmitkSlicesInterpolator::OnRemoveLabel);
labelSet->ActiveLabelEvent += mitk::MessageDelegate1<QmitkSlicesInterpolator,mitk::Label::PixelType>(
this, &QmitkSlicesInterpolator::OnActiveLabelChanged);
workingImage->AfterChangeLayerEvent += mitk::MessageDelegate<QmitkSlicesInterpolator>(
this, &QmitkSlicesInterpolator::OnLayerChanged);
m_SurfaceInterpolator->AddLabelSetConnection(layerID);
}
catch(const std::exception& e)
{
MITK_ERROR << e.what() << '\n';
}
}
}
void QmitkSlicesInterpolator::OnAddLabelSetConnection()
{
if (m_ToolManager->GetWorkingData(0) != nullptr)
{
try
{
auto workingImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());
workingImage->GetActiveLabelSet()->RemoveLabelEvent += mitk::MessageDelegate1<QmitkSlicesInterpolator, mitk::Label::PixelType>(
this, &QmitkSlicesInterpolator::OnRemoveLabel);
workingImage->GetActiveLabelSet()->ActiveLabelEvent += mitk::MessageDelegate1<QmitkSlicesInterpolator,mitk::Label::PixelType>(
this, &QmitkSlicesInterpolator::OnActiveLabelChanged);
workingImage->AfterChangeLayerEvent += mitk::MessageDelegate<QmitkSlicesInterpolator>(
this, &QmitkSlicesInterpolator::OnLayerChanged);
m_SurfaceInterpolator->AddLabelSetConnection();
}
catch(const std::exception& e)
{
MITK_ERROR << e.what() << '\n';
}
}
}
void QmitkSlicesInterpolator::OnRemoveLabelSetConnection(mitk::LabelSetImage* labelSetImage, unsigned int layerID)
{
size_t previousLayerID = labelSetImage->GetActiveLayer();
labelSetImage->SetActiveLayer(layerID);
labelSetImage->GetActiveLabelSet()->RemoveLabelEvent -= mitk::MessageDelegate1<QmitkSlicesInterpolator, mitk::Label::PixelType>(
this, &QmitkSlicesInterpolator::OnRemoveLabel);
labelSetImage->GetActiveLabelSet()->ActiveLabelEvent -= mitk::MessageDelegate1<QmitkSlicesInterpolator,mitk::Label::PixelType>(
this, &QmitkSlicesInterpolator::OnActiveLabelChanged);
labelSetImage->AfterChangeLayerEvent -= mitk::MessageDelegate<QmitkSlicesInterpolator>(
this, &QmitkSlicesInterpolator::OnLayerChanged);
m_SurfaceInterpolator->RemoveLabelSetConnection(labelSetImage, layerID);
labelSetImage->SetActiveLayer(previousLayerID);
}
void QmitkSlicesInterpolator::OnRemoveLabelSetConnection()
{
if (m_ToolManager->GetWorkingData(0) != nullptr)
{
try
{
auto workingImage = dynamic_cast<mitk::LabelSetImage*>(m_ToolManager->GetWorkingData(0)->GetData());
workingImage->GetActiveLabelSet()->RemoveLabelEvent -= mitk::MessageDelegate1<QmitkSlicesInterpolator, mitk::Label::PixelType>(
this, &QmitkSlicesInterpolator::OnRemoveLabel);
workingImage->GetActiveLabelSet()->ActiveLabelEvent -= mitk::MessageDelegate1<QmitkSlicesInterpolator,mitk::Label::PixelType>(
this, &QmitkSlicesInterpolator::OnActiveLabelChanged);
workingImage->AfterChangeLayerEvent -= mitk::MessageDelegate<QmitkSlicesInterpolator>(
this, &QmitkSlicesInterpolator::OnLayerChanged);
}
catch(const std::exception& e)
{
MITK_ERROR << e.what() << '\n';
}
}
}
void QmitkSlicesInterpolator::OnRemoveLabel(mitk::Label::PixelType /*removedLabelValue*/)
{
if (m_ToolManager->GetWorkingData(0) != nullptr)
{
try
{
auto labelSetImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());
auto currentLayerID = labelSetImage->GetActiveLayer();
auto numTimeSteps = labelSetImage->GetTimeGeometry()->CountTimeSteps();
for (size_t t = 0; t < numTimeSteps; ++t)
{
m_SurfaceInterpolator->RemoveContours(m_PreviousActiveLabelValue,t,currentLayerID);
}
}
catch(const std::exception& e)
{
MITK_ERROR << "Bad cast error for labelSetImage";
}
}
}
void QmitkSlicesInterpolator::OnModifyLabelChanged(const itk::Object *caller,
const itk::EventObject & /*event*/)
{
auto *tempImage = dynamic_cast<mitk::LabelSetImage *>(const_cast<itk::Object *>(caller) ) ;
if( tempImage == nullptr)
{
MITK_ERROR << "Unable to cast caller to LabelSetImage.";
return;
}
ModifyLabelActionTrigerred actionTriggered = ModifyLabelActionTrigerred::Null;
if(m_ToolManager->GetWorkingData(0) != nullptr)
{
auto labelSetImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());
if (labelSetImage == tempImage)
{
if (!labelSetImage->GetTimeGeometry()->IsValidTimePoint(m_TimePoint))
{
MITK_ERROR << "Invalid time point requested for interpolation pipeline.";
return;
}
auto timeStep = labelSetImage->GetTimeGeometry()->TimePointToTimeStep(m_TimePoint);
auto numLayersInCurrentSegmentation = m_SurfaceInterpolator->GetNumberOfLayersInCurrentSegmentation();
// This handles the add layer or remove layer operation.
if (labelSetImage->GetNumberOfLayers() != numLayersInCurrentSegmentation)
{
bool addLayer = (labelSetImage->GetNumberOfLayers() == (numLayersInCurrentSegmentation +1) );
bool removeLayer = (labelSetImage->GetNumberOfLayers() == (numLayersInCurrentSegmentation - 1) );
m_SurfaceInterpolator->SetNumberOfLayersInCurrentSegmentation(labelSetImage->GetNumberOfLayers());
if (addLayer)
{
m_SurfaceInterpolator->OnAddLayer();
this->OnAddLabelSetConnection();
}
if (removeLayer)
{
m_SurfaceInterpolator->OnRemoveLayer();
}
return;
}
// Get the pixels present in the image.
// This portion of the code deals with the merge and erase labels operations.
auto imageDimension = labelSetImage->GetDimension();
if (imageDimension == 4)
{
actionTriggered = ModifyLabelProcessing<4>(labelSetImage, m_SurfaceInterpolator, timeStep);
}
else
{
actionTriggered = ModifyLabelProcessing<3>(labelSetImage, m_SurfaceInterpolator, timeStep);
}
if (actionTriggered == ModifyLabelActionTrigerred::Erase)
{
m_InterpolatedSurfaceNode->SetData(nullptr);
}
auto currentLayerID = labelSetImage->GetActiveLayer();
if (actionTriggered == ModifyLabelActionTrigerred::Merge)
{
this->MergeContours(timeStep, currentLayerID);
m_SurfaceInterpolator->Modified();
}
}
}
}
void QmitkSlicesInterpolator::MergeContours(unsigned int timeStep,
unsigned int layerID)
{
auto* contours = m_SurfaceInterpolator->GetContours(timeStep, layerID);
if (nullptr == contours)
return;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
for (size_t i = 0; i < contours->size(); ++i)
{
for (size_t j = i+1; j < contours->size(); ++j)
{
// And Labels are the same and Layers are the same.
bool areContoursCoplanar = AreContoursCoplanar((*contours)[i], (*contours)[j]);
if ( areContoursCoplanar && ((*contours)[i].LabelValue == (*contours)[j].LabelValue) )
{
// Update the contour by re-extracting the slice from the corresponding plane.
mitk::Image::Pointer slice = ExtractSliceFromImage(m_Segmentation, (*contours)[i].Plane, timeStep);
mitk::ImageToContourFilter::Pointer contourExtractor = mitk::ImageToContourFilter::New();
contourExtractor->SetInput(slice);
contourExtractor->SetContourValue((*contours)[i].LabelValue);
contourExtractor->Update();
mitk::Surface::Pointer contour = contourExtractor->GetOutput();
(*contours)[i].Contour = contour;
// Update the interior point of the contour
(*contours)[i].ContourPoint = m_SurfaceInterpolator->ComputeInteriorPointOfContour((*contours)[i],dynamic_cast<mitk::LabelSetImage *>(m_Segmentation));
// Setting the contour polygon data to an empty vtkPolyData,
// as source label is empty after merge operation.
(*contours)[j].Contour->SetVtkPolyData(vtkSmartPointer<vtkPolyData>::New());
}
}
}
auto segmentationNode = m_SurfaceInterpolator->GetSegmentationImageNode();
if (segmentationNode == nullptr)
{
MITK_ERROR << "segmentation Image Node not found\n";
}
auto isContourPlaneGeometry = mitk::NodePredicateProperty::New("isContourPlaneGeometry", mitk::BoolProperty::New(true));
mitk::DataStorage::SetOfObjects::ConstPointer contourNodes =
m_DataStorage->GetDerivations(segmentationNode, isContourPlaneGeometry);
// Remove empty contour nodes.
auto isContourEmpty = [] (const mitk::SurfaceInterpolationController::ContourPositionInformation& contour)
{
return (contour.Contour->GetVtkPolyData()->GetNumberOfPoints() == 0);
};
auto it = std::remove_if((*contours).begin(), (*contours).end(), isContourEmpty);
(*contours).erase(it, (*contours).end());
}
void QmitkSlicesInterpolator::ClearSegmentationObservers()
{
auto dataIter = m_SegmentationObserverTags.begin();
while (dataIter != m_SegmentationObserverTags.end())
{
auto labelSetImage = (*dataIter).first;
labelSetImage->RemoveObserver((*dataIter).second);
for (size_t layerID = 0; layerID < labelSetImage->GetNumberOfLayers(); ++layerID)
{
this->OnRemoveLabelSetConnection(labelSetImage, layerID);
}
++dataIter;
}
m_SegmentationObserverTags.clear();
}
diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolGUI.h b/Modules/SegmentationUI/Qmitk/QmitkToolGUI.h
index 25aa1ff9aa..f47df87bc5 100644
--- a/Modules/SegmentationUI/Qmitk/QmitkToolGUI.h
+++ b/Modules/SegmentationUI/Qmitk/QmitkToolGUI.h
@@ -1,62 +1,59 @@
/*============================================================================
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 QmitkToolGUI_h
#define QmitkToolGUI_h
#include <MitkSegmentationUIExports.h>
#include <qwidget.h>
#include "mitkCommon.h"
#include "mitkTool.h"
/**
\brief Base class for GUIs belonging to mitk::Tool classes.
\ingroup org_mitk_gui_qt_interactivesegmentation
Created through ITK object factory. TODO May be changed to a toolkit specific way later?
Last contributor: $Author$
*/
class MITKSEGMENTATIONUI_EXPORT QmitkToolGUI : public QWidget, public itk::Object
{
Q_OBJECT
public:
mitkClassMacroItkParent(QmitkToolGUI, itk::Object);
void SetTool(mitk::Tool *tool);
// just make sure ITK won't take care of anything (especially not destruction)
void Register() const override;
void UnRegister() const ITK_NOEXCEPT ITK_OVERRIDE;
void SetReferenceCount(int) override;
~QmitkToolGUI() override;
signals:
-
void NewToolAssociated(mitk::Tool *);
-public slots:
-
-protected slots:
-
protected:
+ QmitkToolGUI() = default;
+
mitk::Tool::Pointer m_Tool;
virtual void BusyStateChanged(bool){};
};
#endif
diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolGUIArea.h b/Modules/SegmentationUI/Qmitk/QmitkToolGUIArea.h
index 491aba8371..6fd79905ff 100644
--- a/Modules/SegmentationUI/Qmitk/QmitkToolGUIArea.h
+++ b/Modules/SegmentationUI/Qmitk/QmitkToolGUIArea.h
@@ -1,46 +1,46 @@
/*============================================================================
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 QmitkToolGUIArea_h
#define QmitkToolGUIArea_h
#include "mitkCommon.h"
#include <MitkSegmentationUIExports.h>
#include <qwidget.h>
/**
\brief Dummy class for putting into a GUI (mainly using Qt Designer).
This class is nothing more than a QWidget. It is good for use with QmitkToolSelectionBox as a place to display GUIs
for active tools.
Last contributor: $Author$
*/
class MITKSEGMENTATIONUI_EXPORT QmitkToolGUIArea : public QWidget
{
Q_OBJECT
public:
- QmitkToolGUIArea(QWidget *parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkToolGUIArea(QWidget *parent = nullptr, Qt::WindowFlags f = {});
~QmitkToolGUIArea() override;
signals:
public slots:
protected slots:
protected:
};
#endif
diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp
index 96f5bf2fbd..995433d58e 100755
--- a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp
+++ b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp
@@ -1,622 +1,623 @@
/*============================================================================
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 MBILOG_ENABLE_DEBUG 1
#include <QmitkStyleManager.h>
#include "QmitkToolSelectionBox.h"
#include "QmitkToolGUI.h"
#include "mitkBaseRenderer.h"
#include <QList>
-#include <qapplication.h>
-#include <qlayout.h>
-#include <qmessagebox.h>
-#include <qtoolbutton.h>
-#include <qtooltip.h>
+#include <QApplication>
+#include <QLayout>
+#include <QMessageBox>
+#include <QToolButton>
+#include <QToolTip>
+#include <QRegularExpression>
#include <queue>
#include "usModuleResource.h"
#include "usModuleResourceStream.h"
#include "mitkToolManagerProvider.h"
QmitkToolSelectionBox::QmitkToolSelectionBox(QWidget *parent, mitk::DataStorage *)
: QWidget(parent),
m_SelfCall(false),
m_DisplayedGroups("default"),
m_LayoutColumns(2),
m_ShowNames(true),
m_GenerateAccelerators(false),
m_ToolGUIWidget(nullptr),
m_LastToolGUI(nullptr),
m_ToolButtonGroup(nullptr),
m_ButtonLayout(nullptr)
{
QFont currentFont = QWidget::font();
currentFont.setBold(true);
QWidget::setFont(currentFont);
m_ToolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager();
// QButtonGroup
m_ToolButtonGroup = new QButtonGroup(this);
// some features of QButtonGroup
m_ToolButtonGroup->setExclusive(false); // mutually exclusive toggle buttons
RecreateButtons();
QWidget::setContentsMargins(0, 0, 0, 0);
if (layout() != nullptr)
{
layout()->setContentsMargins(0, 0, 0, 0);
}
// reactions to signals
- connect(m_ToolButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(toolButtonClicked(int)));
+ connect(m_ToolButtonGroup, &QButtonGroup::idClicked, this, &QmitkToolSelectionBox::toolButtonClicked);
// reactions to ToolManager events
m_ToolManager->ActiveToolChanged +=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerToolModified);
m_ToolManager->ReferenceDataChanged +=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified);
m_ToolManager->WorkingDataChanged +=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified);
// show active tool
SetOrUnsetButtonForActiveTool();
QWidget::setEnabled(false);
}
QmitkToolSelectionBox::~QmitkToolSelectionBox()
{
m_ToolManager->ActiveToolChanged -=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerToolModified);
m_ToolManager->ReferenceDataChanged -=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified);
m_ToolManager->WorkingDataChanged -=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified);
}
mitk::ToolManager *QmitkToolSelectionBox::GetToolManager()
{
return m_ToolManager;
}
void QmitkToolSelectionBox::SetToolManager(
mitk::ToolManager &newManager) // no nullptr pointer allowed here, a manager is required
{
// say bye to the old manager
m_ToolManager->ActiveToolChanged -=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerToolModified);
m_ToolManager->ReferenceDataChanged -=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified);
m_ToolManager->WorkingDataChanged -=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified);
if (QWidget::isEnabled())
{
m_ToolManager->UnregisterClient();
}
m_ToolManager = &newManager;
RecreateButtons();
// greet the new one
m_ToolManager->ActiveToolChanged +=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerToolModified);
m_ToolManager->ReferenceDataChanged +=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified);
m_ToolManager->WorkingDataChanged +=
mitk::MessageDelegate<QmitkToolSelectionBox>(this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified);
if (QWidget::isEnabled())
{
m_ToolManager->RegisterClient();
}
// ask the new one what the situation is like
SetOrUnsetButtonForActiveTool();
}
void QmitkToolSelectionBox::toolButtonClicked(int id)
{
if (!QWidget::isEnabled())
return; // this method could be triggered from the constructor, when we are still disabled
MITK_DEBUG << "toolButtonClicked(" << id << "): id translates to tool ID " << m_ToolIDForButtonID[id];
QToolButton *toolButton = dynamic_cast<QToolButton *>(m_ToolButtonGroup->buttons().at(id));
if (toolButton)
{
if ((m_ButtonIDForToolID.find(m_ToolManager->GetActiveToolID()) !=
m_ButtonIDForToolID.end()) // if we have this tool in our box
&&
(m_ButtonIDForToolID[m_ToolManager->GetActiveToolID()] ==
id)) // the tool corresponding to this button is already active
{
// disable this button, disable all tools
toolButton->setChecked(false);
m_ToolManager->ActivateTool(-1); // disable everything
}
else
{
// enable the corresponding tool
m_SelfCall = true;
m_ToolManager->ActivateTool(m_ToolIDForButtonID[id]);
m_SelfCall = false;
}
}
}
void QmitkToolSelectionBox::OnToolManagerToolModified()
{
SetOrUnsetButtonForActiveTool();
}
void QmitkToolSelectionBox::SetOrUnsetButtonForActiveTool()
{
// we want to emit a signal in any case, whether we selected ourselves or somebody else changes "our" tool manager.
// --> emit before check on m_SelfCall
int id = m_ToolManager->GetActiveToolID();
// don't emit signal for shape model tools
bool emitSignal = true;
mitk::Tool *tool = m_ToolManager->GetActiveTool();
if (tool && std::string(tool->GetGroup()) == "organ_segmentation")
emitSignal = false;
if (emitSignal)
emit ToolSelected(id);
// delete old GUI (if any)
if (m_LastToolGUI && m_ToolGUIWidget)
{
if (m_ToolGUIWidget->layout())
{
m_ToolGUIWidget->layout()->removeWidget(m_LastToolGUI);
}
m_LastToolGUI->setParent(nullptr);
delete m_LastToolGUI; // will hopefully notify parent and layouts
m_LastToolGUI = nullptr;
QLayout *layout = m_ToolGUIWidget->layout();
if (layout)
{
layout->activate();
}
}
QToolButton *toolButton(nullptr);
if (m_ButtonIDForToolID.find(id) != m_ButtonIDForToolID.end()) // if this tool is in our box
{
toolButton = dynamic_cast<QToolButton *>(m_ToolButtonGroup->buttons().at(m_ButtonIDForToolID[id]));
}
if (toolButton)
{
// mmueller
// uncheck all other buttons
QAbstractButton *tmpBtn = nullptr;
for (int i = 0; i < m_ToolButtonGroup->buttons().size(); ++i)
{
tmpBtn = m_ToolButtonGroup->buttons().at(i);
if (tmpBtn != toolButton)
dynamic_cast<QToolButton *>(tmpBtn)->setChecked(false);
}
toolButton->setChecked(true);
if (m_ToolGUIWidget && tool)
{
// create and reparent new GUI (if any)
itk::Object::Pointer possibleGUI = tool->GetGUI("Qmitk", "GUI").GetPointer(); // prefix and postfix
if (possibleGUI.IsNull())
possibleGUI = tool->GetGUI("", "GUI").GetPointer();
QmitkToolGUI *gui = dynamic_cast<QmitkToolGUI *>(possibleGUI.GetPointer());
//!
m_LastToolGUI = gui;
if (gui)
{
gui->SetTool(tool);
gui->setParent(m_ToolGUIWidget);
gui->move(gui->geometry().topLeft());
gui->show();
QLayout *layout = m_ToolGUIWidget->layout();
if (!layout)
{
layout = new QVBoxLayout(m_ToolGUIWidget);
}
if (layout)
{
layout->addWidget(gui);
layout->activate();
}
}
}
}
else
{
// disable all buttons
QToolButton *selectedToolButton = dynamic_cast<QToolButton *>(m_ToolButtonGroup->checkedButton());
if (selectedToolButton)
{
selectedToolButton->setChecked(false);
}
}
}
void QmitkToolSelectionBox::OnToolManagerReferenceDataModified()
{
if (m_SelfCall)
return;
MITK_DEBUG << "OnToolManagerReferenceDataModified()";
this->UpdateButtonsEnabledState();
}
void QmitkToolSelectionBox::OnToolManagerWorkingDataModified()
{
if (m_SelfCall)
return;
MITK_DEBUG << "OnToolManagerWorkingDataModified()";
this->UpdateButtonsEnabledState();
}
void QmitkToolSelectionBox::setEnabled(bool enable)
{
if (QWidget::isEnabled() == enable)
return;
QWidget::setEnabled(enable);
if (enable)
{
m_ToolManager->RegisterClient();
auto id = m_ToolManager->GetActiveToolID();
emit ToolSelected(id);
}
else
{
m_ToolManager->ActivateTool(-1);
m_ToolManager->UnregisterClient();
emit ToolSelected(-1);
}
}
void QmitkToolSelectionBox::UpdateButtonsEnabledState()
{
auto buttons = m_ToolButtonGroup->buttons();
const auto refDataNode = m_ToolManager->GetReferenceData(0);
const mitk::BaseData* refData = nullptr;
if (nullptr != refDataNode)
{
refData = refDataNode->GetData();
}
const auto workingDataNode = m_ToolManager->GetWorkingData(0);
const mitk::BaseData* workingData = nullptr;
if (nullptr != workingDataNode)
{
workingData = workingDataNode->GetData();
}
- for (const auto& button : qAsConst(buttons))
+ for (const auto& button : std::as_const(buttons))
{
const auto buttonID = m_ToolButtonGroup->id(button);
const auto toolID = m_ToolIDForButtonID[buttonID];
const auto tool = m_ToolManager->GetToolById(toolID);
button->setEnabled(tool->CanHandle(refData, workingData));
}
}
void QmitkToolSelectionBox::RecreateButtons()
{
if (m_ToolManager.IsNull())
return;
QList<QAbstractButton *> l = m_ToolButtonGroup->buttons();
// remove all buttons that are there
QList<QAbstractButton *>::iterator it;
QAbstractButton *btn;
for (it = l.begin(); it != l.end(); ++it)
{
btn = *it;
m_ToolButtonGroup->removeButton(btn);
delete btn;
}
mitk::ToolManager::ToolVectorTypeConst allPossibleTools = m_ToolManager->GetTools();
mitk::ToolManager::ToolVectorTypeConst allTools;
typedef std::pair<std::string::size_type, const mitk::Tool *> SortPairType;
typedef std::priority_queue<SortPairType> SortedToolQueueType;
SortedToolQueueType toolPositions;
// clear and sort all tools
// step one: find name/group of all tools in m_DisplayedGroups string. remember these positions for all tools.
for (mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allPossibleTools.begin();
iter != allPossibleTools.end();
++iter)
{
const mitk::Tool *tool = *iter;
std::string::size_type namePos = m_DisplayedGroups.find(std::string("'") + tool->GetName() + "'");
std::string::size_type groupPos = m_DisplayedGroups.find(std::string("'") + tool->GetGroup() + "'");
if (!m_DisplayedGroups.empty() && namePos == std::string::npos && groupPos == std::string::npos)
continue; // skip
if (m_DisplayedGroups.empty() && std::string(tool->GetName()).length() > 0)
{
namePos = static_cast<std::string::size_type>(tool->GetName()[0]);
}
SortPairType thisPair = std::make_pair(namePos < groupPos ? namePos : groupPos, *iter);
toolPositions.push(thisPair);
}
// step two: sort tools according to previously found positions in m_DisplayedGroups
MITK_DEBUG << "Sorting order of tools (lower number --> earlier in button group)";
while (!toolPositions.empty())
{
SortPairType thisPair = toolPositions.top();
MITK_DEBUG << "Position " << thisPair.first << " : " << thisPair.second->GetName();
allTools.push_back(thisPair.second);
toolPositions.pop();
}
std::reverse(allTools.begin(), allTools.end());
MITK_DEBUG << "Sorted tools:";
for (mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allTools.begin(); iter != allTools.end(); ++iter)
{
MITK_DEBUG << (*iter)->GetName();
}
if (m_ButtonLayout == nullptr)
m_ButtonLayout = new QGridLayout;
int row(0);
int column(-1);
int currentButtonID(0);
m_ButtonIDForToolID.clear();
m_ToolIDForButtonID.clear();
QToolButton *button = nullptr;
MITK_DEBUG << "Creating buttons for tools";
// fill group box with buttons
for (mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allTools.begin(); iter != allTools.end(); ++iter)
{
const mitk::Tool *tool = *iter;
int currentToolID(m_ToolManager->GetToolID(tool));
++column;
// new line if we are at the maximum columns
if (column == m_LayoutColumns)
{
++row;
column = 0;
}
button = new QToolButton;
button->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum));
// add new button to the group
MITK_DEBUG << "Adding button with ID " << currentToolID;
m_ToolButtonGroup->addButton(button, currentButtonID);
// ... and to the layout
MITK_DEBUG << "Adding button in row/column " << row << "/" << column;
m_ButtonLayout->addWidget(button, row, column);
if (m_LayoutColumns == 1)
{
button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
}
else
{
button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
}
button->setCheckable(true);
if (currentToolID == m_ToolManager->GetActiveToolID())
button->setChecked(true);
QString label;
if (m_GenerateAccelerators)
{
label += "&";
}
label += tool->GetName();
QString tooltip = tool->GetName();
MITK_DEBUG << tool->GetName() << ", " << label.toLocal8Bit().constData() << ", '"
<< tooltip.toLocal8Bit().constData();
if (m_ShowNames)
{
button->setText(label); // a label
button->setToolTip(tooltip);
QFont currentFont = button->font();
currentFont.setBold(false);
button->setFont(currentFont);
}
us::ModuleResource iconResource = tool->GetIconResource();
if (!iconResource.IsValid())
{
button->setIcon(QIcon(QPixmap(tool->GetXPM())));
}
else
{
auto isSVG = "svg" == iconResource.GetSuffix();
auto openmode = isSVG ? std::ios_base::in : std::ios_base::binary;
us::ModuleResourceStream resourceStream(iconResource, openmode);
resourceStream.seekg(0, std::ios::end);
std::ios::pos_type length = resourceStream.tellg();
resourceStream.seekg(0, std::ios::beg);
char *data = new char[length];
resourceStream.read(data, length);
if (isSVG)
{
button->setIcon(QmitkStyleManager::ThemeIcon(QByteArray::fromRawData(data, length)));
}
else
{
QPixmap pixmap;
pixmap.loadFromData(QByteArray::fromRawData(data, length));
button->setIcon(QIcon(pixmap));
}
delete[] data;
if (m_ShowNames)
{
if (m_LayoutColumns == 1)
button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
else
button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
button->setIconSize(QSize(24, 24));
}
else
{
button->setToolButtonStyle(Qt::ToolButtonIconOnly);
button->setIconSize(QSize(32, 32));
button->setToolTip(tooltip);
}
}
if (m_GenerateAccelerators)
{
QString firstLetter = QString(tool->GetName());
firstLetter.truncate(1);
button->setShortcut(
firstLetter); // a keyboard shortcut (just the first letter of the given name w/o any CTRL or something)
}
m_ButtonIDForToolID[currentToolID] = currentButtonID;
m_ToolIDForButtonID[currentButtonID] = currentToolID;
MITK_DEBUG << "m_ButtonIDForToolID[" << currentToolID << "] == " << currentButtonID;
MITK_DEBUG << "m_ToolIDForButtonID[" << currentButtonID << "] == " << currentToolID;
tool->GUIProcessEventsMessage += mitk::MessageDelegate<QmitkToolSelectionBox>(
this, &QmitkToolSelectionBox::OnToolGUIProcessEventsMessage); // will never add a listener twice, so we don't have
// to check here
tool->ErrorMessage += mitk::MessageDelegate1<QmitkToolSelectionBox, std::string>(
this,
&QmitkToolSelectionBox::OnToolErrorMessage); // will never add a listener twice, so we don't have to check here
tool->GeneralMessage +=
mitk::MessageDelegate1<QmitkToolSelectionBox, std::string>(this, &QmitkToolSelectionBox::OnGeneralToolMessage);
++currentButtonID;
}
// setting grid layout for this groupbox
this->setLayout(m_ButtonLayout);
this->UpdateButtonsEnabledState();
// this->update();
}
void QmitkToolSelectionBox::OnToolGUIProcessEventsMessage()
{
qApp->processEvents();
}
void QmitkToolSelectionBox::OnToolErrorMessage(std::string s)
{
QMessageBox::critical(
- this, "MITK", QString(s.c_str()), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
+ this, "MITK", QString(s.c_str()), QMessageBox::Ok | QMessageBox::NoButton, QMessageBox::NoButton);
}
void QmitkToolSelectionBox::OnGeneralToolMessage(std::string s)
{
QMessageBox::information(
- this, "MITK", QString(s.c_str()), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
+ this, "MITK", QString(s.c_str()), QMessageBox::Ok | QMessageBox::NoButton, QMessageBox::NoButton);
}
void QmitkToolSelectionBox::SetDisplayedToolGroups(const std::string &toolGroups)
{
if (m_DisplayedGroups != toolGroups)
{
QString q_DisplayedGroups = toolGroups.c_str();
// quote all unquoted single words
- q_DisplayedGroups = q_DisplayedGroups.replace(QRegExp("\\b(\\w+)\\b|'([^']+)'"), "'\\1\\2'");
+ q_DisplayedGroups = q_DisplayedGroups.replace(QRegularExpression("\\b(\\w+)\\b|'([^']+)'"), "'\\1\\2'");
MITK_DEBUG << "m_DisplayedGroups was \"" << toolGroups << "\"";
m_DisplayedGroups = q_DisplayedGroups.toLocal8Bit().constData();
MITK_DEBUG << "m_DisplayedGroups is \"" << m_DisplayedGroups << "\"";
RecreateButtons();
SetOrUnsetButtonForActiveTool();
}
}
void QmitkToolSelectionBox::SetLayoutColumns(int columns)
{
if (columns > 0 && columns != m_LayoutColumns)
{
m_LayoutColumns = columns;
RecreateButtons();
}
}
void QmitkToolSelectionBox::SetShowNames(bool show)
{
if (show != m_ShowNames)
{
m_ShowNames = show;
RecreateButtons();
}
}
void QmitkToolSelectionBox::SetGenerateAccelerators(bool accel)
{
if (accel != m_GenerateAccelerators)
{
m_GenerateAccelerators = accel;
RecreateButtons();
}
}
void QmitkToolSelectionBox::SetToolGUIArea(QWidget *parentWidget)
{
m_ToolGUIWidget = parentWidget;
}
diff --git a/Modules/SegmentationUI/Qmitk/QmitkTotalSegmentatorToolGUI.cpp b/Modules/SegmentationUI/Qmitk/QmitkTotalSegmentatorToolGUI.cpp
index a78bef468a..2d2bdb4f75 100644
--- a/Modules/SegmentationUI/Qmitk/QmitkTotalSegmentatorToolGUI.cpp
+++ b/Modules/SegmentationUI/Qmitk/QmitkTotalSegmentatorToolGUI.cpp
@@ -1,497 +1,497 @@
/*============================================================================
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 "QmitkTotalSegmentatorToolGUI.h"
#include "mitkProcessExecutor.h"
#include "mitkTotalSegmentatorTool.h"
#include <QApplication>
#include <QDir>
#include <QDirIterator>
#include <QFileDialog>
#include <QIcon>
#include <QmitkStyleManager.h>
#include <QMessageBox>
MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitkTotalSegmentatorToolGUI, "")
QmitkTotalSegmentatorToolGUI::QmitkTotalSegmentatorToolGUI()
: QmitkMultiLabelSegWithPreviewToolGUIBase(), m_SuperclassEnableConfirmSegBtnFnc(m_EnableConfirmSegBtnFnc)
{
// Nvidia-smi command returning zero doesn't always imply lack of GPUs.
// Pytorch uses its own libraries to communicate to the GPUs. Hence, only a warning can be given.
if (m_GpuLoader.GetGPUCount() == 0)
{
std::string warning = "WARNING: No GPUs were detected on your machine. The TotalSegmentator tool can be very slow.";
this->ShowErrorMessage(warning);
}
m_EnableConfirmSegBtnFnc = [this](bool enabled)
{ return !m_FirstPreviewComputation ? m_SuperclassEnableConfirmSegBtnFnc(enabled) : false; };
}
void QmitkTotalSegmentatorToolGUI::ConnectNewTool(mitk::SegWithPreviewTool *newTool)
{
Superclass::ConnectNewTool(newTool);
m_FirstPreviewComputation = true;
}
void QmitkTotalSegmentatorToolGUI::InitializeUI(QBoxLayout *mainLayout)
{
m_Controls.setupUi(this);
#ifndef _WIN32
m_Controls.sysPythonComboBox->addItem("/usr/bin");
#endif
this->AutoParsePythonPaths();
m_Controls.sysPythonComboBox->addItem("Select");
m_Controls.sysPythonComboBox->setCurrentIndex(0);
m_Controls.pythonEnvComboBox->addItem("Select");
m_Controls.pythonEnvComboBox->setDuplicatesEnabled(false);
m_Controls.pythonEnvComboBox->setDisabled(true);
m_Controls.previewButton->setDisabled(true);
m_Controls.statusLabel->setTextFormat(Qt::RichText);
m_Controls.subtaskComboBox->addItems(VALID_TASKS);
QString welcomeText;
this->SetGPUInfo();
if (m_GpuLoader.GetGPUCount() != 0)
{
welcomeText = "<b>STATUS: </b><i>Welcome to TotalSegmentator tool. You're in luck: " +
QString::number(m_GpuLoader.GetGPUCount()) + " GPU(s) were detected.</i>";
}
else
{
welcomeText = "<b>STATUS: </b><i>Welcome to TotalSegmentator tool. Sorry, " +
QString::number(m_GpuLoader.GetGPUCount()) + " GPUs were detected.</i>";
}
connect(m_Controls.previewButton, SIGNAL(clicked()), this, SLOT(OnPreviewBtnClicked()));
connect(m_Controls.clearButton, SIGNAL(clicked()), this, SLOT(OnClearInstall()));
connect(m_Controls.installButton, SIGNAL(clicked()), this, SLOT(OnInstallBtnClicked()));
connect(m_Controls.overrideBox, SIGNAL(stateChanged(int)), this, SLOT(OnOverrideChecked(int)));
connect(m_Controls.pythonEnvComboBox,
QOverload<int>::of(&QComboBox::activated),
[=](int index) { OnPythonPathChanged(m_Controls.pythonEnvComboBox->itemText(index)); });
connect(m_Controls.sysPythonComboBox,
QOverload<int>::of(&QComboBox::activated),
[=](int index) { OnSystemPythonChanged(m_Controls.sysPythonComboBox->itemText(index)); });
QString lastSelectedPyEnv = m_Settings.value("TotalSeg/LastCustomPythonPath").toString();
if (!lastSelectedPyEnv.isEmpty() && lastSelectedPyEnv!= "Select")
{
m_Controls.pythonEnvComboBox->insertItem(0, lastSelectedPyEnv);
}
const QString storageDir = m_Installer.GetVirtualEnvPath();
m_IsInstalled = this->IsTotalSegmentatorInstalled(storageDir);
if (m_IsInstalled)
{
m_PythonPath = QmitkSetupVirtualEnvUtil::GetExactPythonPath(storageDir).first;
m_Installer.SetVirtualEnvPath(m_PythonPath);
this->EnableAll(m_IsInstalled);
welcomeText += " TotalSegmentator is already found installed.";
}
else
{
welcomeText += " TotalSegmentator is not installed. Please click on \"Install TotalSegmentator\" above.";
}
this->WriteStatusMessage(welcomeText);
QIcon deleteIcon =
QmitkStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/edit-delete.svg"));
QIcon arrowIcon =
QmitkStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/tango/scalable/actions/media-playback-start.svg"));
m_Controls.clearButton->setIcon(deleteIcon);
m_Controls.previewButton->setIcon(arrowIcon);
mainLayout->addLayout(m_Controls.verticalLayout);
Superclass::InitializeUI(mainLayout);
}
void QmitkTotalSegmentatorToolGUI::SetGPUInfo()
{
std::vector<QmitkGPUSpec> specs = m_GpuLoader.GetAllGPUSpecs();
for (const QmitkGPUSpec &gpuSpec : specs)
{
m_Controls.gpuComboBox->addItem(QString::number(gpuSpec.id) + ": " + gpuSpec.name + " (" + gpuSpec.memory + ")");
}
if (specs.empty())
{
m_Controls.gpuComboBox->setEditable(true);
m_Controls.gpuComboBox->addItem(QString::number(0));
m_Controls.gpuComboBox->setValidator(new QIntValidator(0, 999, this));
}
}
unsigned int QmitkTotalSegmentatorToolGUI::FetchSelectedGPUFromUI() const
{
QString gpuInfo = m_Controls.gpuComboBox->currentText();
if (m_GpuLoader.GetGPUCount() == 0)
{
return static_cast<unsigned int>(gpuInfo.toInt());
}
else
{
- QString gpuId = gpuInfo.split(":", QString::SplitBehavior::SkipEmptyParts).first();
+ QString gpuId = gpuInfo.split(":", Qt::SkipEmptyParts).first();
return static_cast<unsigned int>(gpuId.toInt());
}
}
void QmitkTotalSegmentatorToolGUI::EnableAll(bool isEnable)
{
m_Controls.previewButton->setEnabled(isEnable);
m_Controls.subtaskComboBox->setEnabled(isEnable);
m_Controls.installButton->setEnabled((!isEnable));
}
void QmitkTotalSegmentatorToolGUI::OnInstallBtnClicked()
{
bool isInstalled = false;
const auto [path, version] = OnSystemPythonChanged(m_Controls.sysPythonComboBox->currentText());
if (path.isEmpty())
{
this->WriteErrorMessage("<b>ERROR: </b>Couldn't find compatible Python.");
return;
}
// check if python 3.12 and ask for confirmation
if (version.startsWith("3.12") &&
QMessageBox::No == QMessageBox::question(
nullptr,
"Installing TotalSegmentator",
QString("WARNING: This is an unsupported version of Python that may not work. "
"We recommend using a supported Python version between 3.9 and 3.11.\n\n"
"Continue anyway?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No))
{
return;
}
this->WriteStatusMessage("<b>STATUS: </b>Installing TotalSegmentator...");
m_Installer.SetSystemPythonPath(path);
isInstalled = m_Installer.SetupVirtualEnv(m_Installer.VENV_NAME);
if (isInstalled)
{
m_PythonPath = QmitkSetupVirtualEnvUtil::GetExactPythonPath(m_Installer.GetVirtualEnvPath()).first;
this->WriteStatusMessage("<b>STATUS: </b>Successfully installed TotalSegmentator.");
}
else
{
this->WriteErrorMessage("<b>ERROR: </b>Couldn't install TotalSegmentator.");
}
this->EnableAll(isInstalled);
}
void QmitkTotalSegmentatorToolGUI::OnPreviewBtnClicked()
{
auto tool = this->GetConnectedToolAs<mitk::TotalSegmentatorTool>();
if (nullptr == tool)
{
return;
}
try
{
m_Controls.previewButton->setEnabled(false);
qApp->processEvents();
if (!this->IsTotalSegmentatorInstalled(m_PythonPath))
{
throw std::runtime_error(WARNING_TOTALSEG_NOT_FOUND);
}
bool isFast = m_Controls.fastBox->isChecked();
QString subTask = m_Controls.subtaskComboBox->currentText();
if (subTask != VALID_TASKS[0])
{
isFast = true;
}
tool->SetPythonPath(m_PythonPath.toStdString());
tool->SetGpuId(FetchSelectedGPUFromUI());
tool->SetFast(isFast);
tool->SetSubTask(subTask.toStdString());
this->WriteStatusMessage(QString("<b>STATUS: </b><i>Starting Segmentation task... This might take a while.</i>"));
tool->UpdatePreview();
m_Controls.previewButton->setEnabled(true);
m_FirstPreviewComputation = false;
}
catch (const std::exception &e)
{
std::stringstream errorMsg;
errorMsg << "<b>STATUS: </b>Error while processing parameters for TotalSegmentator segmentation. Reason: "
<< e.what();
this->ShowErrorMessage(errorMsg.str());
this->WriteErrorMessage(QString::fromStdString(errorMsg.str()));
m_Controls.previewButton->setEnabled(true);
return;
}
catch (...)
{
std::string errorMsg = "Unkown error occured while generation TotalSegmentator segmentation.";
this->ShowErrorMessage(errorMsg);
m_Controls.previewButton->setEnabled(true);
return;
}
this->SetLabelSetPreview(tool->GetPreviewSegmentation());
this->ActualizePreviewLabelVisibility();
this->WriteStatusMessage("<b>STATUS: </b><i>Segmentation task finished successfully.</i>");
QString pythonPathTextItem = m_Controls.pythonEnvComboBox->currentText();
if (!pythonPathTextItem.isEmpty() && pythonPathTextItem != "Select") // only cache if the prediction ended without errors.
{
QString lastSelectedPyEnv = m_Settings.value("TotalSeg/LastCustomPythonPath").toString();
if (lastSelectedPyEnv != pythonPathTextItem)
{
m_Settings.setValue("TotalSeg/LastCustomPythonPath", pythonPathTextItem);
}
}
}
void QmitkTotalSegmentatorToolGUI::ShowErrorMessage(const std::string &message, QMessageBox::Icon icon)
{
this->setCursor(Qt::ArrowCursor);
QMessageBox *messageBox = new QMessageBox(icon, nullptr, message.c_str());
messageBox->exec();
delete messageBox;
MITK_WARN << message;
}
void QmitkTotalSegmentatorToolGUI::WriteStatusMessage(const QString &message)
{
m_Controls.statusLabel->setText(message);
m_Controls.statusLabel->setStyleSheet("font-weight: bold; color: white");
qApp->processEvents();
}
void QmitkTotalSegmentatorToolGUI::WriteErrorMessage(const QString &message)
{
m_Controls.statusLabel->setText(message);
m_Controls.statusLabel->setStyleSheet("font-weight: bold; color: red");
qApp->processEvents();
}
bool QmitkTotalSegmentatorToolGUI::IsTotalSegmentatorInstalled(const QString &pythonPath)
{
QString fullPath = pythonPath;
bool isPythonExists = false, isExists = false;
#ifdef _WIN32
isPythonExists = QFile::exists(fullPath + QDir::separator() + QString("python.exe"));
if (!(fullPath.endsWith("Scripts", Qt::CaseInsensitive) || fullPath.endsWith("Scripts/", Qt::CaseInsensitive)))
{
fullPath += QDir::separator() + QString("Scripts");
isPythonExists =
(!isPythonExists) ? QFile::exists(fullPath + QDir::separator() + QString("python.exe")) : isPythonExists;
}
isExists = QFile::exists(fullPath + QDir::separator() + QString("TotalSegmentator.exe")) && isPythonExists;
#else
isPythonExists = QFile::exists(fullPath + QDir::separator() + QString("python3"));
if (!(fullPath.endsWith("bin", Qt::CaseInsensitive) || fullPath.endsWith("bin/", Qt::CaseInsensitive)))
{
fullPath += QDir::separator() + QString("bin");
isPythonExists =
(!isPythonExists) ? QFile::exists(fullPath + QDir::separator() + QString("python3")) : isPythonExists;
}
isExists = QFile::exists(fullPath + QDir::separator() + QString("TotalSegmentator")) && isPythonExists;
#endif
return isExists;
}
void QmitkTotalSegmentatorToolGUI::AutoParsePythonPaths()
{
QString homeDir = QDir::homePath();
std::vector<QString> searchDirs;
#ifdef _WIN32
searchDirs.push_back(QString("C:") + QDir::separator() + QString("ProgramData") + QDir::separator() +
QString("anaconda3"));
#else
// Add search locations for possible standard python paths here
searchDirs.push_back(homeDir + QDir::separator() + "environments");
searchDirs.push_back(homeDir + QDir::separator() + "anaconda3");
searchDirs.push_back(homeDir + QDir::separator() + "miniconda3");
searchDirs.push_back(homeDir + QDir::separator() + "opt" + QDir::separator() + "miniconda3");
searchDirs.push_back(homeDir + QDir::separator() + "opt" + QDir::separator() + "anaconda3");
#endif
for (QString searchDir : searchDirs)
{
if (searchDir.endsWith("anaconda3", Qt::CaseInsensitive))
{
if (QDir(searchDir).exists())
{
m_Controls.sysPythonComboBox->addItem("(base): " + searchDir);
searchDir.append((QDir::separator() + QString("envs")));
}
}
for (QDirIterator subIt(searchDir, QDir::AllDirs, QDirIterator::NoIteratorFlags); subIt.hasNext();)
{
subIt.next();
QString envName = subIt.fileName();
if (!envName.startsWith('.')) // Filter out irrelevent hidden folders, if any.
{
m_Controls.pythonEnvComboBox->addItem("(" + envName + "): " + subIt.filePath());
}
}
}
}
std::pair<QString, QString> QmitkTotalSegmentatorToolGUI::OnSystemPythonChanged(const QString &pyEnv)
{
std::pair<QString, QString> pyPath;
if (pyEnv == QString("Select"))
{
m_Controls.previewButton->setDisabled(true);
QString path =
QFileDialog::getExistingDirectory(m_Controls.sysPythonComboBox->parentWidget(), "Python Path", "dir");
if (!path.isEmpty())
{
this->OnSystemPythonChanged(path); // recall same function for new path validation
bool oldState = m_Controls.sysPythonComboBox->blockSignals(true); // block signal firing while inserting item
m_Controls.sysPythonComboBox->insertItem(0, path);
m_Controls.sysPythonComboBox->setCurrentIndex(0);
m_Controls.sysPythonComboBox->blockSignals(
oldState); // unblock signal firing after inserting item. Remove this after Qt6 migration
}
}
else
{
QString uiPyPath = this->GetPythonPathFromUI(pyEnv);
pyPath = QmitkSetupVirtualEnvUtil::GetExactPythonPath(uiPyPath);
}
return pyPath;
}
void QmitkTotalSegmentatorToolGUI::OnPythonPathChanged(const QString &pyEnv)
{
if (pyEnv == QString("Select"))
{
m_Controls.previewButton->setDisabled(true);
QString path =
QFileDialog::getExistingDirectory(m_Controls.pythonEnvComboBox->parentWidget(), "Python Path", "dir");
if (!path.isEmpty())
{
this->OnPythonPathChanged(path); // recall same function for new path validation
bool oldState = m_Controls.pythonEnvComboBox->blockSignals(true); // block signal firing while inserting item
m_Controls.pythonEnvComboBox->insertItem(0, path);
m_Controls.pythonEnvComboBox->setCurrentIndex(0);
m_Controls.pythonEnvComboBox->blockSignals(
oldState); // unblock signal firing after inserting item. Remove this after Qt6 migration
}
}
else if (!this->IsTotalSegmentatorInstalled(this->GetPythonPathFromUI(pyEnv)))
{
this->ShowErrorMessage(WARNING_TOTALSEG_NOT_FOUND);
m_Controls.previewButton->setDisabled(true);
}
else
{// Show positive status meeage
m_Controls.previewButton->setDisabled(false);
QString uiPyPath = this->GetPythonPathFromUI(pyEnv);
m_PythonPath = QmitkSetupVirtualEnvUtil::GetExactPythonPath(uiPyPath).first;
}
}
QString QmitkTotalSegmentatorToolGUI::GetPythonPathFromUI(const QString &pyUI) const
{
QString fullPath = pyUI;
if (-1 != fullPath.indexOf(")"))
{
fullPath = fullPath.mid(fullPath.indexOf(")") + 2);
}
return fullPath.simplified();
}
void QmitkTotalSegmentatorToolGUI::OnOverrideChecked(int state)
{
bool isEnabled = false;
if (state == Qt::Checked)
{
isEnabled = true;
m_Controls.previewButton->setDisabled(true);
m_PythonPath.clear();
}
else
{
m_PythonPath.clear();
m_Controls.previewButton->setDisabled(true);
if (m_IsInstalled)
{
const QString pythonPath = m_Installer.GetVirtualEnvPath();
auto pathObject = QmitkSetupVirtualEnvUtil::GetExactPythonPath(pythonPath);
m_PythonPath = pathObject.first;
this->EnableAll(m_IsInstalled);
}
}
m_Controls.pythonEnvComboBox->setEnabled(isEnabled);
}
void QmitkTotalSegmentatorToolGUI::OnClearInstall()
{
QDir folderPath(m_Installer.GetVirtualEnvPath());
if (folderPath.removeRecursively())
{
m_Controls.installButton->setEnabled(true);
m_IsInstalled = false;
if (!m_Controls.overrideBox->isChecked())
{
m_Controls.previewButton->setEnabled(false);
}
}
else
{
MITK_ERROR
<< "The virtual environment couldn't be removed. Please check if you have the required access privileges or, some other process is accessing the folders.";
}
}
bool QmitkTotalSegmentatorToolInstaller::SetupVirtualEnv(const QString& venvName)
{
if (GetSystemPythonPath().isEmpty())
{
return false;
}
QDir folderPath(GetBaseDir());
folderPath.mkdir(venvName);
if (!folderPath.cd(venvName))
{
return false; // Check if directory creation was successful.
}
mitk::ProcessExecutor::ArgumentListType args;
auto spExec = mitk::ProcessExecutor::New();
auto spCommand = itk::CStyleCommand::New();
spCommand->SetCallback(&PrintProcessEvent);
spExec->AddObserver(mitk::ExternalProcessOutputEvent(), spCommand);
args.push_back("-m");
args.push_back("venv");
args.push_back(venvName.toStdString());
#ifdef _WIN32
QString pythonFile = GetSystemPythonPath() + QDir::separator() + "python.exe";
QString pythonExeFolder = "Scripts";
#else
QString pythonFile = GetSystemPythonPath() + QDir::separator() + "python3";
QString pythonExeFolder = "bin";
#endif
spExec->Execute(GetBaseDir().toStdString(), pythonFile.toStdString(), args); // Setup local virtual environment
if (folderPath.cd(pythonExeFolder))
{
this->SetPythonPath(folderPath.absolutePath());
this->SetPipPath(folderPath.absolutePath());
this->InstallPytorch();
for (auto &package : PACKAGES)
{
this->PipInstall(package.toStdString(), &PrintProcessEvent);
}
std::string pythonCode; // python syntax to check if torch is installed with CUDA.
pythonCode.append("import torch;");
pythonCode.append("print('Pytorch was installed with CUDA') if torch.cuda.is_available() else print('PyTorch was "
"installed WITHOUT CUDA');");
this->ExecutePython(pythonCode, &PrintProcessEvent);
return true;
}
return false;
}
QString QmitkTotalSegmentatorToolInstaller::GetVirtualEnvPath()
{
return STORAGE_DIR + VENV_NAME;
}
diff --git a/Modules/SegmentationUI/Qmitk/QmitknnUNetToolGUI.cpp b/Modules/SegmentationUI/Qmitk/QmitknnUNetToolGUI.cpp
index 6e449c5a4e..b39262f9ad 100644
--- a/Modules/SegmentationUI/Qmitk/QmitknnUNetToolGUI.cpp
+++ b/Modules/SegmentationUI/Qmitk/QmitknnUNetToolGUI.cpp
@@ -1,1197 +1,1197 @@
/*============================================================================
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 "QmitknnUNetToolGUI.h"
#include "mitkProcessExecutor.h"
#include "mitknnUnetTool.h"
#include <mitkTimeNavigationController.h>
#include <QApplication>
#include <QDir>
#include <QDirIterator>
#include <QIcon>
#include <QmitkStyleManager.h>
#include <QmitknnUNetEnsembleLayout.h>
#include <QtGlobal>
#include <algorithm>
#include <ctkCollapsibleGroupBox.h>
#include <itksys/SystemTools.hxx>
#include <nlohmann/json.hpp>
#include <mitkIOUtil.h>
MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitknnUNetToolGUI, "")
QmitknnUNetToolGUI::QmitknnUNetToolGUI() : QmitkMultiLabelSegWithPreviewToolGUIBase(), m_SuperclassEnableConfirmSegBtnFnc(m_EnableConfirmSegBtnFnc)
{
// Nvidia-smi command returning zero doesn't always imply lack of GPUs.
// Pytorch uses its own libraries to communicate to the GPUs. Hence, only a warning can be given.
if (m_GpuLoader.GetGPUCount() == 0)
{
std::string warning = "WARNING: No GPUs were detected on your machine. The nnUNet tool might not work.";
this->ShowErrorMessage(warning);
}
// define predicates for multi modal data selection combobox
auto imageType = mitk::TNodePredicateDataType<mitk::Image>::New();
auto labelSetImageType = mitk::NodePredicateNot::New(mitk::TNodePredicateDataType<mitk::LabelSetImage>::New());
m_MultiModalPredicate = mitk::NodePredicateAnd::New(imageType, labelSetImageType).GetPointer();
m_nnUNetThread = new QThread(this);
m_Worker = new nnUNetDownloadWorker;
m_Worker->moveToThread(m_nnUNetThread);
m_EnableConfirmSegBtnFnc = [this](bool enabled)
{
return !m_FirstPreviewComputation ? m_SuperclassEnableConfirmSegBtnFnc(enabled) : false;
};
}
QmitknnUNetToolGUI::~QmitknnUNetToolGUI()
{
m_nnUNetThread->quit();
m_nnUNetThread->wait();
}
void QmitknnUNetToolGUI::ConnectNewTool(mitk::SegWithPreviewTool *newTool)
{
Superclass::ConnectNewTool(newTool);
newTool->IsTimePointChangeAwareOff();
m_FirstPreviewComputation = true;
}
void QmitknnUNetToolGUI::InitializeUI(QBoxLayout *mainLayout)
{
m_Controls.setupUi(this);
#ifndef _WIN32
m_Controls.pythonEnvComboBox->addItem("/usr/bin");
#endif
m_Controls.pythonEnvComboBox->addItem("Select");
AutoParsePythonPaths();
SetGPUInfo();
connect(m_Controls.previewButton, SIGNAL(clicked()), this, SLOT(OnPreviewRequested()));
connect(m_Controls.modeldirectoryBox,
SIGNAL(directoryChanged(const QString &)),
this,
SLOT(OnDirectoryChanged(const QString &)));
connect(
m_Controls.modelBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(OnModelChanged(const QString &)));
connect(m_Controls.taskBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(OnTaskChanged(const QString &)));
connect(
m_Controls.plannerBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(OnTrainerChanged(const QString &)));
connect(m_Controls.multiModalBox, SIGNAL(stateChanged(int)), this, SLOT(OnCheckBoxChanged(int)));
connect(m_Controls.pythonEnvComboBox,
#if QT_VERSION >= 0x050F00 // 5.15
SIGNAL(textActivated(const QString &)),
#elif QT_VERSION >= 0x050C00 // 5.12
SIGNAL(currentTextChanged(const QString &)),
#endif
this,
SLOT(OnPythonPathChanged(const QString &)));
connect(m_Controls.refreshdirectoryBox, SIGNAL(clicked()), this, SLOT(OnRefreshPresssed()));
connect(m_Controls.clearCacheButton, SIGNAL(clicked()), this, SLOT(OnClearCachePressed()));
connect(m_Controls.startDownloadButton, SIGNAL(clicked()), this, SLOT(OnDownloadModel()));
connect(m_Controls.stopDownloadButton, SIGNAL(clicked()), this, SLOT(OnStopDownload()));
// Qthreads
qRegisterMetaType<mitk::ProcessExecutor::Pointer>();
qRegisterMetaType<mitk::ProcessExecutor::ArgumentListType>();
connect(this, &QmitknnUNetToolGUI::Operate, m_Worker, &nnUNetDownloadWorker::DoWork);
connect(m_Worker, &nnUNetDownloadWorker::Exit, this, &QmitknnUNetToolGUI::OnDownloadWorkerExit);
connect(m_nnUNetThread, &QThread::finished, m_Worker, &QObject::deleteLater);
m_Controls.multiModalValueLabel->setStyleSheet("font-weight: bold; color: white");
m_Controls.multiModalValueLabel->setVisible(false);
m_Controls.requiredModalitiesLabel->setVisible(false);
m_Controls.stopDownloadButton->setVisible(false);
m_Controls.previewButton->setEnabled(false);
QIcon refreshIcon =
QmitkStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/view-refresh.svg"));
m_Controls.refreshdirectoryBox->setIcon(refreshIcon);
QIcon dirIcon =
QmitkStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/document-open.svg"));
m_Controls.modeldirectoryBox->setIcon(dirIcon);
m_Controls.refreshdirectoryBox->setEnabled(true);
QIcon stopIcon =
QmitkStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/status/dialog-error.svg"));
m_Controls.stopDownloadButton->setIcon(stopIcon);
m_Controls.statusLabel->setTextFormat(Qt::RichText);
if (m_GpuLoader.GetGPUCount() != 0)
{
WriteStatusMessage(QString("<b>STATUS: </b><i>Welcome to nnUNet. " + QString::number(m_GpuLoader.GetGPUCount()) +
" GPUs were detected.</i>"));
}
else
{
WriteErrorMessage(QString("<b>STATUS: </b><i>Welcome to nnUNet. " + QString::number(m_GpuLoader.GetGPUCount()) +
" GPUs were detected.</i>"));
}
mainLayout->addLayout(m_Controls.verticalLayout);
Superclass::InitializeUI(mainLayout);
m_UI_ROWS = m_Controls.advancedSettingsLayout->rowCount(); // Must do. Row count is correct only here.
this->DisableEverything();
QString lastSelectedPyEnv = m_Settings.value("nnUNet/LastPythonPath").toString();
m_Controls.pythonEnvComboBox->setCurrentText(lastSelectedPyEnv);
}
void QmitknnUNetToolGUI::EnableWidgets(bool enabled)
{
Superclass::EnableWidgets(enabled);
}
void QmitknnUNetToolGUI::ClearAllModalities()
{
m_Controls.multiModalBox->setChecked(false);
this->ClearAllModalLabels();
}
void QmitknnUNetToolGUI::ClearAllModalLabels()
{
for (auto modalLabel : m_ModalLabels)
{
delete modalLabel; // delete the layout item
m_ModalLabels.pop_back();
}
m_Controls.advancedSettingsLayout->update();
}
void QmitknnUNetToolGUI::DisableEverything()
{
m_Controls.modeldirectoryBox->setEnabled(false);
m_Controls.refreshdirectoryBox->setEnabled(false);
m_Controls.previewButton->setEnabled(false);
m_Controls.multiModalValueLabel->setVisible(false);
m_Controls.multiModalBox->setEnabled(false);
this->ClearAllComboBoxes();
this->ClearAllModalities();
}
void QmitknnUNetToolGUI::ClearAllComboBoxes()
{
m_Controls.modelBox->clear();
m_Controls.taskBox->clear();
m_Controls.foldBox->clear();
m_Controls.trainerBox->clear();
m_Controls.plannerBox->clear();
for (auto &layout : m_EnsembleParams)
{
layout->modelBox->clear();
layout->trainerBox->clear();
layout->plannerBox->clear();
layout->foldBox->clear();
}
}
std::vector<mitk::Image::ConstPointer> QmitknnUNetToolGUI::FetchMultiModalImagesFromUI()
{
std::vector<mitk::Image::ConstPointer> modals;
if (m_Controls.multiModalBox->isChecked() && !m_Modalities.empty())
{
std::set<std::string> nodeNames; // set container for keeping names of all nodes to check if they are added twice.
for (QmitkSingleNodeSelectionWidget *modality : m_Modalities)
{
mitk::DataNode::Pointer node = modality->GetSelectedNode();
if (nodeNames.find(node->GetName()) == nodeNames.end())
{
modals.push_back(dynamic_cast<const mitk::Image *>(node->GetData()));
nodeNames.insert(node->GetName());
}
else
{
throw std::runtime_error("Same modality is selected more than once. Please change your selection.");
break;
}
}
}
return modals;
}
bool QmitknnUNetToolGUI::IsNNUNetInstalled(const QString &pythonPath)
{
QString fullPath = pythonPath;
#ifdef _WIN32
if (!(fullPath.endsWith("Scripts", Qt::CaseInsensitive) || fullPath.endsWith("Scripts/", Qt::CaseInsensitive)))
{
fullPath += QDir::separator() + QString("Scripts");
}
#else
if (!(fullPath.endsWith("bin", Qt::CaseInsensitive) || fullPath.endsWith("bin/", Qt::CaseInsensitive)))
{
fullPath += QDir::separator() + QString("bin");
}
#endif
fullPath = fullPath.mid(fullPath.indexOf(" ") + 1);
bool isExists = QFile::exists(fullPath + QDir::separator() + QString("nnUNet_predict")) &&
QFile::exists(fullPath + QDir::separator() + QString("python3"));
return isExists;
}
void QmitknnUNetToolGUI::ShowErrorMessage(const std::string &message, QMessageBox::Icon icon)
{
this->setCursor(Qt::ArrowCursor);
QMessageBox *messageBox = new QMessageBox(icon, nullptr, message.c_str());
messageBox->exec();
delete messageBox;
MITK_WARN << message;
}
void QmitknnUNetToolGUI::WriteStatusMessage(const QString &message)
{
m_Controls.statusLabel->setText(message);
m_Controls.statusLabel->setStyleSheet("font-weight: bold; color: white");
}
void QmitknnUNetToolGUI::WriteErrorMessage(const QString &message)
{
m_Controls.statusLabel->setText(message);
m_Controls.statusLabel->setStyleSheet("font-weight: bold; color: red");
}
void QmitknnUNetToolGUI::ProcessEnsembleModelsParams(mitk::nnUNetTool::Pointer tool)
{
if (m_EnsembleParams[0]->modelBox->currentText() == m_EnsembleParams[1]->modelBox->currentText())
{
throw std::runtime_error("Both models you have selected for ensembling are the same.");
}
QString taskName = m_Controls.taskBox->currentText();
bool isPPJson = m_Controls.postProcessingCheckBox->isChecked();
std::vector<mitk::ModelParams> requestQ;
QString ppDirFolderNamePart1 = "ensemble_";
QStringList ppDirFolderNameParts;
for (auto &layout : m_EnsembleParams)
{
QStringList ppDirFolderName;
QString modelName = layout->modelBox->currentText();
ppDirFolderName << modelName;
ppDirFolderName << "__";
QString trainer = layout->trainerBox->currentText();
ppDirFolderName << trainer;
ppDirFolderName << "__";
QString planId = layout->plannerBox->currentText();
ppDirFolderName << planId;
if (!this->IsModelExists(modelName, taskName, QString(trainer + "__" + planId)))
{
std::string errorMsg = "The configuration " + modelName.toStdString() +
" you have selected doesn't exist. Check your Results Folder again.";
throw std::runtime_error(errorMsg);
}
std::vector<std::string> testfold = FetchSelectedFoldsFromUI(layout->foldBox);
mitk::ModelParams modelObject = MapToRequest(modelName, taskName, trainer, planId, testfold);
requestQ.push_back(modelObject);
ppDirFolderNameParts << ppDirFolderName.join(QString(""));
}
tool->EnsembleOn();
if (isPPJson)
{
QString ppJsonFilePossibility1 = QDir::cleanPath(
m_ParentFolder->getResultsFolder() + QDir::separator() + "nnUNet" + QDir::separator() + "ensembles" +
QDir::separator() + taskName + QDir::separator() + ppDirFolderNamePart1 + ppDirFolderNameParts.first() + "--" +
ppDirFolderNameParts.last() + QDir::separator() + "postprocessing.json");
QString ppJsonFilePossibility2 = QDir::cleanPath(
m_ParentFolder->getResultsFolder() + QDir::separator() + "nnUNet" + QDir::separator() + "ensembles" +
QDir::separator() + taskName + QDir::separator() + ppDirFolderNamePart1 + ppDirFolderNameParts.last() + "--" +
ppDirFolderNameParts.first() + QDir::separator() + "postprocessing.json");
if (QFile(ppJsonFilePossibility1).exists())
{
tool->SetPostProcessingJsonDirectory(ppJsonFilePossibility1.toStdString());
const QString statusMsg = "<i>Post Processing JSON file found: </i>" + ppJsonFilePossibility1;
this->WriteStatusMessage(statusMsg);
}
else if (QFile(ppJsonFilePossibility2).exists())
{
tool->SetPostProcessingJsonDirectory(ppJsonFilePossibility2.toStdString());
const QString statusMsg = "<i>Post Processing JSON file found:</i>" + ppJsonFilePossibility2;
this->WriteStatusMessage(statusMsg);
}
else
{
std::string errorMsg =
"No post processing file was found for the selected ensemble combination. Continuing anyway...";
this->ShowErrorMessage(errorMsg);
}
}
tool->m_ParamQ.clear();
tool->m_ParamQ = requestQ;
}
void QmitknnUNetToolGUI::ProcessModelParams(mitk::nnUNetTool::Pointer tool)
{
tool->EnsembleOff();
std::vector<mitk::ModelParams> requestQ;
QString modelName = m_Controls.modelBox->currentText();
QString taskName = m_Controls.taskBox->currentText();
QString trainer = m_Controls.trainerBox->currentText();
QString planId = m_Controls.plannerBox->currentText();
std::vector<std::string> fetchedFolds = this->FetchSelectedFoldsFromUI(m_Controls.foldBox);
mitk::ModelParams modelObject = MapToRequest(modelName, taskName, trainer, planId, fetchedFolds);
requestQ.push_back(modelObject);
tool->m_ParamQ.clear();
tool->m_ParamQ = requestQ;
}
bool QmitknnUNetToolGUI::IsModelExists(const QString &modelName, const QString &taskName, const QString &trainerPlanner)
{
QString modelSearchPath =
QDir::cleanPath(m_ParentFolder->getResultsFolder() + QDir::separator() + "nnUNet" + QDir::separator() + modelName +
QDir::separator() + taskName + QDir::separator() + trainerPlanner);
if (QDir(modelSearchPath).exists())
{
return true;
}
return false;
}
void QmitknnUNetToolGUI::CheckAllInCheckableComboBox(ctkCheckableComboBox *foldBox)
{
// Recalling all added items to check-mark it.
const QAbstractItemModel *qaim = foldBox->checkableModel();
auto rows = qaim->rowCount();
for (std::remove_const_t<decltype(rows)> i = 0; i < rows; ++i)
{
const QModelIndex mi = qaim->index(i, 0);
foldBox->setCheckState(mi, Qt::Checked);
}
}
std::pair<QStringList, QStringList> QmitknnUNetToolGUI::ExtractTrainerPlannerFromString(QStringList trainerPlanners)
{
QString splitterString = "__";
QStringList trainers, planners;
for (const auto &trainerPlanner : trainerPlanners)
{
- trainers << trainerPlanner.split(splitterString, QString::SplitBehavior::SkipEmptyParts).first();
- planners << trainerPlanner.split(splitterString, QString::SplitBehavior::SkipEmptyParts).last();
+ trainers << trainerPlanner.split(splitterString, Qt::SkipEmptyParts).first();
+ planners << trainerPlanner.split(splitterString, Qt::SkipEmptyParts).last();
}
trainers.removeDuplicates();
planners.removeDuplicates();
return std::make_pair(trainers, planners);
}
std::vector<std::string> QmitknnUNetToolGUI::FetchSelectedFoldsFromUI(ctkCheckableComboBox *foldBox)
{
std::vector<std::string> folds;
if (foldBox->noneChecked())
{
this->CheckAllInCheckableComboBox(foldBox);
}
QModelIndexList foldList = foldBox->checkedIndexes();
for (const auto &index : foldList)
{
QString foldQString = foldBox->itemText(index.row());
if(foldQString != "dummy_element_that_nobody_can_see")
{
- foldQString = foldQString.split("_", QString::SplitBehavior::SkipEmptyParts).last();
+ foldQString = foldQString.split("_", Qt::SkipEmptyParts).last();
folds.push_back(foldQString.toStdString());
}
else
{
throw std::runtime_error("Folds are not recognized. Please check if your nnUNet results folder structure is legitimate");
}
}
return folds;
}
void QmitknnUNetToolGUI::UpdateCacheCountOnUI()
{
QString cacheText = m_CACHE_COUNT_BASE_LABEL + QString::number(m_Cache.size());
m_Controls.cacheCountLabel->setText(cacheText);
}
void QmitknnUNetToolGUI::AddToCache(size_t &hashKey, mitk::LabelSetImage::ConstPointer mlPreview)
{
nnUNetCache *newCacheObj = new nnUNetCache;
newCacheObj->m_SegCache = mlPreview;
m_Cache.insert(hashKey, newCacheObj);
MITK_INFO << "New hash: " << hashKey << " " << newCacheObj->m_SegCache.GetPointer();
this->UpdateCacheCountOnUI();
}
void QmitknnUNetToolGUI::SetGPUInfo()
{
std::vector<QmitkGPUSpec> specs = m_GpuLoader.GetAllGPUSpecs();
for (const QmitkGPUSpec &gpuSpec : specs)
{
m_Controls.gpuComboBox->addItem(QString::number(gpuSpec.id) + ": " + gpuSpec.name + " (" + gpuSpec.memory + ")");
}
if (specs.empty())
{
m_Controls.gpuComboBox->setEditable(true);
m_Controls.gpuComboBox->addItem(QString::number(0));
m_Controls.gpuComboBox->setValidator(new QIntValidator(0, 999, this));
}
}
unsigned int QmitknnUNetToolGUI::FetchSelectedGPUFromUI()
{
QString gpuInfo = m_Controls.gpuComboBox->currentText();
if (m_GpuLoader.GetGPUCount() == 0)
{
return static_cast<unsigned int>(gpuInfo.toInt());
}
else
{
- QString gpuId = gpuInfo.split(":", QString::SplitBehavior::SkipEmptyParts).first();
+ QString gpuId = gpuInfo.split(":", Qt::SkipEmptyParts).first();
return static_cast<unsigned int>(gpuId.toInt());
}
}
QString QmitknnUNetToolGUI::FetchResultsFolderFromEnv()
{
const char *pathVal = itksys::SystemTools::GetEnv("RESULTS_FOLDER");
QString retVal;
if (pathVal)
{
retVal = QString::fromUtf8(pathVal);
}
else
{
retVal = m_Settings.value("nnUNet/LastRESULTS_FOLDERPath").toString();
}
return retVal;
}
void QmitknnUNetToolGUI::DumpJSONfromPickle(const QString &picklePath)
{
const QString pickleFile = picklePath + QDir::separator() + m_PICKLE_FILENAME;
const QString jsonFile = picklePath + QDir::separator() + m_MITK_EXPORT_JSON_FILENAME;
if (!QFile::exists(jsonFile))
{
mitk::ProcessExecutor::Pointer spExec = mitk::ProcessExecutor::New();
mitk::ProcessExecutor::ArgumentListType args;
args.push_back("-c");
std::string pythonCode; // python syntax to parse plans.pkl file and export as Json file.
pythonCode.append("import pickle;");
pythonCode.append("import json;");
pythonCode.append("loaded_pickle = pickle.load(open('");
pythonCode.append(pickleFile.toStdString());
pythonCode.append("','rb'));");
pythonCode.append("modal_dict = {key: loaded_pickle[key] for key in loaded_pickle.keys() if key in "
"['modalities','num_modalities']};");
pythonCode.append("json.dump(modal_dict, open('");
pythonCode.append(jsonFile.toStdString());
pythonCode.append("', 'w'))");
args.push_back(pythonCode);
try
{
spExec->Execute(m_PythonPath.toStdString(), "python3", args);
}
catch (const mitk::Exception &e)
{
MITK_ERROR << "Pickle parsing FAILED!" << e.GetDescription();
this->WriteStatusMessage(
"Parsing failed in backend. Multiple Modalities will now have to be manually entered by the user.");
}
}
}
void QmitknnUNetToolGUI::ExportAvailableModelsAsJSON(const QString &resultsFolder)
{
const QString jsonPath = resultsFolder + QDir::separator() + m_AVAILABLE_MODELS_JSON_FILENAME;
if (!QFile::exists(jsonPath))
{
auto spExec = mitk::ProcessExecutor::New();
mitk::ProcessExecutor::ArgumentListType args;
args.push_back("--export");
args.push_back(resultsFolder.toStdString());
try
{
spExec->Execute(m_PythonPath.toStdString(), "nnUNet_print_available_pretrained_models", args);
}
catch (const mitk::Exception &e)
{
MITK_ERROR << "Exporting information FAILED." << e.GetDescription();
this->WriteStatusMessage("Exporting information FAILED.");
}
}
}
void QmitknnUNetToolGUI::DisplayMultiModalInfoFromJSON(const QString &jsonPath)
{
std::ifstream file(jsonPath.toStdString());
if (file.is_open())
{
auto jsonObj = nlohmann::json::parse(file, nullptr, false);
if (jsonObj.is_discarded() || !jsonObj.is_object())
{
MITK_ERROR << "Could not parse \"" << jsonPath.toStdString() << "\" as JSON object!";
return;
}
auto num_mods = jsonObj["num_modalities"].get<int>();
this->ClearAllModalLabels();
if (num_mods > 1)
{
m_Controls.multiModalBox->setChecked(true);
m_Controls.multiModalBox->setEnabled(false);
m_Controls.multiModalValueLabel->setText(QString::number(num_mods));
OnModalitiesNumberChanged(num_mods);
m_Controls.advancedSettingsLayout->update();
auto obj = jsonObj["modalities"];
int count = 0;
for (const auto &value : obj)
{
QLabel *label = new QLabel(QString::fromStdString("<i>" + value.get<std::string>() + "</i>"), this);
m_ModalLabels.push_back(label);
m_Controls.advancedSettingsLayout->addWidget(label, m_UI_ROWS + 1 + count, 0);
count++;
}
m_Controls.advancedSettingsLayout->update();
}
else
{
m_Controls.multiModalBox->setChecked(false);
}
}
}
void QmitknnUNetToolGUI::FillAvailableModelsInfoFromJSON(const QString &jsonPath)
{
std::ifstream file(jsonPath.toStdString());
if (file.is_open() && m_Controls.availableBox->count() < 1)
{
auto jsonObj = nlohmann::json::parse(file, nullptr, false);
if (jsonObj.is_discarded() || !jsonObj.is_object())
{
MITK_ERROR << "Could not parse \"" << jsonPath.toStdString() << "\" as JSON object!";
return;
}
for (const auto &obj : jsonObj.items())
{
m_Controls.availableBox->addItem(QString::fromStdString(obj.key()));
}
}
}
mitk::ModelParams QmitknnUNetToolGUI::MapToRequest(const QString &modelName,
const QString &taskName,
const QString &trainer,
const QString &planId,
const std::vector<std::string> &folds)
{
mitk::ModelParams requestObject;
requestObject.model = modelName.toStdString();
requestObject.trainer = trainer.toStdString();
requestObject.planId = planId.toStdString();
requestObject.task = taskName.toStdString();
requestObject.folds = folds;
mitk::nnUNetTool::Pointer tool = this->GetConnectedToolAs<mitk::nnUNetTool>();
requestObject.inputName = tool->GetRefNode()->GetName();
requestObject.timeStamp =
std::to_string(mitk::RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimePoint());
return requestObject;
}
void QmitknnUNetToolGUI::SetComboBoxToNone(ctkCheckableComboBox* comboBox)
{
comboBox->clear();
comboBox->addItem("dummy_element_that_nobody_can_see");
qobject_cast<QListView *>(comboBox->view())->setRowHidden(0, true); // For the cosmetic purpose of showing "None" on the combobox.
}
/* ---------------------SLOTS---------------------------------------*/
void QmitknnUNetToolGUI::OnPreviewRequested()
{
mitk::nnUNetTool::Pointer tool = this->GetConnectedToolAs<mitk::nnUNetTool>();
if (nullptr != tool)
{
QString pythonPathTextItem = "";
try
{
size_t hashKey(0);
m_Controls.previewButton->setEnabled(false); // To prevent misclicked back2back prediction.
qApp->processEvents();
tool->PredictOn(); // purposefully placed to make tool->GetMTime different than before.
QString modelName = m_Controls.modelBox->currentText();
if (modelName.startsWith("ensemble", Qt::CaseInsensitive))
{
this->ProcessEnsembleModelsParams(tool);
}
else
{
this->ProcessModelParams(tool);
}
pythonPathTextItem = m_Controls.pythonEnvComboBox->currentText();
QString pythonPath = m_PythonPath;
if (!this->IsNNUNetInstalled(pythonPath))
{
throw std::runtime_error("nnUNet is not detected in the selected python environment. Please select a valid "
"python environment or install nnUNet.");
}
tool->SetPythonPath(pythonPath.toStdString());
tool->SetModelDirectory(m_ParentFolder->getResultsFolder().toStdString());
// checkboxes
tool->SetMirror(m_Controls.mirrorBox->isChecked());
tool->SetMixedPrecision(m_Controls.mixedPrecisionBox->isChecked());
tool->SetNoPip(false);
bool doCache = m_Controls.enableCachingCheckBox->isChecked();
// Spinboxes
tool->SetGpuId(FetchSelectedGPUFromUI());
// Multi-Modal
tool->MultiModalOff();
if (m_Controls.multiModalBox->isChecked())
{
tool->m_OtherModalPaths.clear();
tool->m_OtherModalPaths = FetchMultiModalImagesFromUI();
tool->MultiModalOn();
}
if (doCache)
{
hashKey = nnUNetCache::GetUniqueHash(tool->m_ParamQ);
if (m_Cache.contains(hashKey))
{
tool->PredictOff(); // purposefully placed to make tool->GetMTime different than before.
}
}
if (tool->GetPredict())
{
tool->m_InputBuffer = nullptr;
this->WriteStatusMessage(
QString("<b>STATUS: </b><i>Starting Segmentation task... This might take a while.</i>"));
tool->UpdatePreview();
if (nullptr == tool->GetOutputBuffer())
{
this->SegmentationProcessFailed();
}
else
{
this->SegmentationResultHandler(tool);
if (doCache)
{
this->AddToCache(hashKey, tool->GetOutputBuffer());
}
tool->ClearOutputBuffer();
}
tool->PredictOff(); // purposefully placed to make tool->GetMTime different than before.
}
else
{
MITK_INFO << "won't do segmentation. Key found: " << QString::number(hashKey).toStdString();
if (m_Cache.contains(hashKey))
{
nnUNetCache *cacheObject = m_Cache[hashKey];
MITK_INFO << "fetched pointer " << cacheObject->m_SegCache.GetPointer();
tool->SetOutputBuffer(const_cast<mitk::LabelSetImage *>(cacheObject->m_SegCache.GetPointer()));
this->SegmentationResultHandler(tool, true);
}
}
m_Controls.previewButton->setEnabled(true);
}
catch (const std::exception &e)
{
std::stringstream errorMsg;
errorMsg << "<b>STATUS: </b>Error while processing parameters for nnUNet segmentation. Reason: " << e.what();
this->ShowErrorMessage(errorMsg.str());
this->WriteErrorMessage(QString::fromStdString(errorMsg.str()));
m_Controls.previewButton->setEnabled(true);
tool->PredictOff();
return;
}
catch (...)
{
std::string errorMsg = "Unkown error occured while generation nnUNet segmentation.";
this->ShowErrorMessage(errorMsg);
m_Controls.previewButton->setEnabled(true);
tool->PredictOff();
return;
}
if (!pythonPathTextItem.isEmpty())
{ // only cache if the prediction ended without errors.
m_Settings.setValue("nnUNet/LastPythonPath", pythonPathTextItem);
}
}
}
void QmitknnUNetToolGUI::OnRefreshPresssed()
{
const QString resultsFolder = m_Controls.modeldirectoryBox->directory();
this->OnDirectoryChanged(resultsFolder);
}
void QmitknnUNetToolGUI::OnDirectoryChanged(const QString &resultsFolder)
{
m_IsResultsFolderValid = false;
m_Controls.previewButton->setEnabled(false);
this->ClearAllComboBoxes();
this->ClearAllModalities();
m_ParentFolder = std::make_shared<QmitknnUNetFolderParser>(resultsFolder);
auto tasks = m_ParentFolder->getAllTasks<QStringList>();
tasks.removeDuplicates();
std::for_each(tasks.begin(), tasks.end(), [this](QString task) { m_Controls.taskBox->addItem(task); });
m_Settings.setValue("nnUNet/LastRESULTS_FOLDERPath", resultsFolder);
}
void QmitknnUNetToolGUI::OnModelChanged(const QString &model)
{
if (model.isEmpty())
{
return;
}
this->ClearAllModalities();
auto selectedTask = m_Controls.taskBox->currentText();
ctkComboBox *box = qobject_cast<ctkComboBox *>(sender());
if (box == m_Controls.modelBox)
{
if (model == m_VALID_MODELS.last())
{
m_Controls.trainerBox->setVisible(false);
m_Controls.trainerLabel->setVisible(false);
m_Controls.plannerBox->setVisible(false);
m_Controls.plannerLabel->setVisible(false);
m_Controls.foldBox->setVisible(false);
m_Controls.foldLabel->setVisible(false);
m_Controls.previewButton->setEnabled(false);
this->ShowEnsembleLayout(true);
auto models = m_ParentFolder->getModelsForTask<QStringList>(m_Controls.taskBox->currentText());
models.removeDuplicates();
models.removeOne(m_VALID_MODELS.last());
for (auto &layout : m_EnsembleParams)
{
layout->modelBox->clear();
layout->trainerBox->clear();
layout->plannerBox->clear();
std::for_each(models.begin(),
models.end(),
[&layout, this](QString model)
{
if (m_VALID_MODELS.contains(model, Qt::CaseInsensitive))
layout->modelBox->addItem(model);
});
}
}
else
{
m_Controls.trainerBox->setVisible(true);
m_Controls.trainerLabel->setVisible(true);
m_Controls.plannerBox->setVisible(true);
m_Controls.plannerLabel->setVisible(true);
m_Controls.foldBox->setVisible(true);
m_Controls.foldLabel->setVisible(true);
m_Controls.previewButton->setEnabled(false);
this->ShowEnsembleLayout(false);
m_Controls.trainerBox->clear();
m_Controls.plannerBox->clear();
auto trainerPlanners = m_ParentFolder->getTrainerPlannersForTask<QStringList>(selectedTask, model);
if(trainerPlanners.isEmpty())
{
this->ShowErrorMessage("No plans.pkl found for "+model.toStdString()+". Check your directory or download the task again.");
this->SetComboBoxToNone(m_Controls.foldBox);
return;
}
QStringList trainers, planners;
std::tie(trainers, planners) = ExtractTrainerPlannerFromString(trainerPlanners);
std::for_each(
trainers.begin(), trainers.end(), [this](QString trainer) { m_Controls.trainerBox->addItem(trainer); });
std::for_each(
planners.begin(), planners.end(), [this](QString planner) { m_Controls.plannerBox->addItem(planner); });
}
}
else if (!m_EnsembleParams.empty())
{
m_Controls.previewButton->setEnabled(false);
for (auto &layout : m_EnsembleParams)
{
if (box == layout->modelBox)
{
layout->trainerBox->clear();
layout->plannerBox->clear();
auto trainerPlanners = m_ParentFolder->getTrainerPlannersForTask<QStringList>(selectedTask, model);
if(trainerPlanners.isEmpty())
{
this->ShowErrorMessage("No plans.pkl found for "+model.toStdString()+". Check your directory or download the task again.");
this->SetComboBoxToNone(layout->foldBox);
return;
}
QStringList trainers, planners;
std::tie(trainers, planners) = ExtractTrainerPlannerFromString(trainerPlanners);
std::for_each(trainers.begin(),
trainers.end(),
[&layout](const QString &trainer) { layout->trainerBox->addItem(trainer); });
std::for_each(planners.begin(),
planners.end(),
[&layout](const QString &planner) { layout->plannerBox->addItem(planner); });
break;
}
}
}
}
void QmitknnUNetToolGUI::OnTaskChanged(const QString &task)
{
if (task.isEmpty())
{
return;
}
m_Controls.modelBox->clear();
auto models = m_ParentFolder->getModelsForTask<QStringList>(task);
models.removeDuplicates();
if (!models.contains(m_VALID_MODELS.last(), Qt::CaseInsensitive))
{
models << m_VALID_MODELS.last(); // add ensemble even if folder doesn't exist
}
std::for_each(models.begin(),
models.end(),
[this](QString model)
{
if (m_VALID_MODELS.contains(model, Qt::CaseInsensitive))
m_Controls.modelBox->addItem(model);
});
}
void QmitknnUNetToolGUI::OnTrainerChanged(const QString &plannerSelected)
{
if (plannerSelected.isEmpty())
{
return;
}
m_IsResultsFolderValid = false;
QString parentPath;
auto *box = qobject_cast<ctkComboBox *>(sender());
if (box == m_Controls.plannerBox)
{
m_Controls.foldBox->clear();
auto selectedTrainer = m_Controls.trainerBox->currentText();
auto selectedTask = m_Controls.taskBox->currentText();
auto selectedModel = m_Controls.modelBox->currentText();
auto folds = m_ParentFolder->getFoldsForTrainerPlanner<QStringList>(
selectedTrainer, plannerSelected, selectedTask, selectedModel);
if(folds.isEmpty())
{
this->ShowErrorMessage("No valid folds found. Check your directory or download the task again.");
this->SetComboBoxToNone(m_Controls.foldBox);
return;
}
std::for_each(folds.begin(),
folds.end(),
[this](QString fold)
{
if (fold.startsWith("fold_", Qt::CaseInsensitive)) // imposed by nnUNet
m_Controls.foldBox->addItem(fold);
});
if (m_Controls.foldBox->count() != 0)
{
m_IsResultsFolderValid = true;
this->CheckAllInCheckableComboBox(m_Controls.foldBox);
auto tempPath = QStringList() << m_ParentFolder->getResultsFolder() << "nnUNet" << selectedModel << selectedTask
<< QString("%1__%2").arg(selectedTrainer, plannerSelected);
parentPath = QDir::cleanPath(tempPath.join(QDir::separator()));
}
}
else if (!m_EnsembleParams.empty())
{
for (auto &layout : m_EnsembleParams)
{
if (box == layout->plannerBox)
{
layout->foldBox->clear();
auto selectedTrainer = layout->trainerBox->currentText();
auto selectedTask = m_Controls.taskBox->currentText();
auto selectedModel = layout->modelBox->currentText();
auto folds = m_ParentFolder->getFoldsForTrainerPlanner<QStringList>(
selectedTrainer, plannerSelected, selectedTask, selectedModel);
if(folds.isEmpty())
{
this->ShowErrorMessage("No valid folds found. Check your directory.");
this->SetComboBoxToNone(layout->foldBox);
return;
}
std::for_each(folds.begin(),
folds.end(),
[&layout](const QString &fold)
{
if (fold.startsWith("fold_", Qt::CaseInsensitive)) // imposed by nnUNet
layout->foldBox->addItem(fold);
});
if (layout->foldBox->count() != 0)
{
this->CheckAllInCheckableComboBox(layout->foldBox);
m_IsResultsFolderValid = true;
auto tempPath = QStringList() << m_ParentFolder->getResultsFolder() << "nnUNet" << selectedModel
<< selectedTask << QString("%1__%2").arg(selectedTrainer, plannerSelected);
parentPath = QDir::cleanPath(tempPath.join(QDir::separator()));
}
break;
}
}
}
if (m_IsResultsFolderValid)
{
m_Controls.previewButton->setEnabled(true);
const QString mitkJsonFile = parentPath + QDir::separator() + m_MITK_EXPORT_JSON_FILENAME;
this->DumpJSONfromPickle(parentPath);
if (QFile::exists(mitkJsonFile))
{
this->DisplayMultiModalInfoFromJSON(mitkJsonFile);
}
}
}
void QmitknnUNetToolGUI::OnPythonPathChanged(const QString &pyEnv)
{
if (pyEnv == QString("Select"))
{
QString path =
QFileDialog::getExistingDirectory(m_Controls.pythonEnvComboBox->parentWidget(), "Python Path", "dir");
if (!path.isEmpty())
{
this->OnPythonPathChanged(path); // recall same function for new path validation
m_Controls.pythonEnvComboBox->insertItem(0, path);
m_Controls.pythonEnvComboBox->setCurrentIndex(0);
}
}
else if (!this->IsNNUNetInstalled(pyEnv))
{
std::string warning =
"WARNING: nnUNet is not detected on the Python environment you selected. Please select another "
"environment or create one. For more info refer https://github.com/MIC-DKFZ/nnUNet";
this->ShowErrorMessage(warning);
this->DisableEverything();
m_Controls.availableBox->clear();
}
else
{
m_Controls.modeldirectoryBox->setEnabled(true);
m_Controls.refreshdirectoryBox->setEnabled(true);
m_Controls.multiModalBox->setEnabled(true);
QString setVal = this->FetchResultsFolderFromEnv();
if (!setVal.isEmpty())
{
m_Controls.modeldirectoryBox->setDirectory(setVal);
}
this->OnRefreshPresssed();
m_PythonPath = pyEnv.mid(pyEnv.indexOf(" ") + 1);
#ifdef _WIN32
if (!(m_PythonPath.endsWith("Scripts", Qt::CaseInsensitive) || m_PythonPath.endsWith("Scripts/", Qt::CaseInsensitive)))
{
m_PythonPath += QDir::separator() + QString("Scripts");
}
#else
if (!(m_PythonPath.endsWith("bin", Qt::CaseInsensitive) || m_PythonPath.endsWith("bin/", Qt::CaseInsensitive)))
{
m_PythonPath += QDir::separator() + QString("bin");
}
#endif
// Export available model info as json and fill them for Download
QString tempPath = QString::fromStdString(mitk::IOUtil::GetTempPath());
this->ExportAvailableModelsAsJSON(tempPath);
const QString jsonPath = tempPath + QDir::separator() + m_AVAILABLE_MODELS_JSON_FILENAME;
if (QFile::exists(jsonPath))
{
this->FillAvailableModelsInfoFromJSON(jsonPath);
}
}
}
void QmitknnUNetToolGUI::OnCheckBoxChanged(int state)
{
bool visibility = false;
if (state == Qt::Checked)
{
visibility = true;
}
ctkCheckBox *box = qobject_cast<ctkCheckBox *>(sender());
if (box != nullptr)
{
if (box->objectName() == QString("multiModalBox"))
{
m_Controls.requiredModalitiesLabel->setVisible(visibility);
m_Controls.multiModalValueLabel->setVisible(visibility);
if (!visibility)
{
this->OnModalitiesNumberChanged(0);
m_Controls.multiModalValueLabel->setText("0");
this->ClearAllModalLabels();
}
}
}
}
void QmitknnUNetToolGUI::OnModalitiesNumberChanged(int num)
{
while (num > static_cast<int>(m_Modalities.size()))
{
QmitkSingleNodeSelectionWidget *multiModalBox = new QmitkSingleNodeSelectionWidget(this);
mitk::nnUNetTool::Pointer tool = this->GetConnectedToolAs<mitk::nnUNetTool>();
multiModalBox->SetDataStorage(tool->GetDataStorage());
multiModalBox->SetInvalidInfo("Select corresponding modalities");
multiModalBox->SetNodePredicate(m_MultiModalPredicate);
multiModalBox->setObjectName(QString("multiModal_" + QString::number(m_Modalities.size() + 1)));
m_Controls.advancedSettingsLayout->addWidget(multiModalBox, m_UI_ROWS + m_Modalities.size() + 1, 1, 1, 3);
m_Modalities.push_back(multiModalBox);
}
while (num < static_cast<int>(m_Modalities.size()) && !m_Modalities.empty())
{
QmitkSingleNodeSelectionWidget *child = m_Modalities.back();
delete child; // delete the layout item
m_Modalities.pop_back();
}
m_Controls.advancedSettingsLayout->update();
}
void QmitknnUNetToolGUI::AutoParsePythonPaths()
{
QString homeDir = QDir::homePath();
std::vector<QString> searchDirs;
#ifdef _WIN32
searchDirs.push_back(QString("C:") + QDir::separator() + QString("ProgramData") + QDir::separator() +
QString("anaconda3"));
#else
// Add search locations for possible standard python paths here
searchDirs.push_back(homeDir + QDir::separator() + "environments");
searchDirs.push_back(homeDir + QDir::separator() + "anaconda3");
searchDirs.push_back(homeDir + QDir::separator() + "miniconda3");
searchDirs.push_back(homeDir + QDir::separator() + "opt" + QDir::separator() + "miniconda3");
searchDirs.push_back(homeDir + QDir::separator() + "opt" + QDir::separator() + "anaconda3");
#endif
for (QString searchDir : searchDirs)
{
if (searchDir.endsWith("anaconda3", Qt::CaseInsensitive))
{
if (QDir(searchDir).exists())
{
m_Controls.pythonEnvComboBox->insertItem(0, "(base): " + searchDir);
searchDir.append((QDir::separator() + QString("envs")));
}
}
for (QDirIterator subIt(searchDir, QDir::AllDirs, QDirIterator::NoIteratorFlags); subIt.hasNext();)
{
subIt.next();
QString envName = subIt.fileName();
if (!envName.startsWith('.')) // Filter out irrelevent hidden folders, if any.
{
m_Controls.pythonEnvComboBox->insertItem(0, "(" + envName + "): " + subIt.filePath());
}
}
}
m_Controls.pythonEnvComboBox->setCurrentIndex(-1);
}
void QmitknnUNetToolGUI::SegmentationProcessFailed()
{
this->WriteErrorMessage(
"<b>STATUS: </b><i>Error in the segmentation process. <br>No resulting segmentation can be loaded.</i>");
this->setCursor(Qt::ArrowCursor);
std::stringstream stream;
stream << "Error in the segmentation process. No resulting segmentation can be loaded.";
this->ShowErrorMessage(stream.str());
}
void QmitknnUNetToolGUI::SegmentationResultHandler(mitk::nnUNetTool *tool, bool forceRender)
{
if (forceRender)
{
tool->RenderOutputBuffer();
}
m_FirstPreviewComputation = false;
this->SetLabelSetPreview(tool->GetPreviewSegmentation());
this->WriteStatusMessage("<b>STATUS: </b><i>Segmentation task finished successfully.</i>");
this->ActualizePreviewLabelVisibility();
}
void QmitknnUNetToolGUI::ShowEnsembleLayout(bool visible)
{
if (m_EnsembleParams.empty())
{
ctkCollapsibleGroupBox *groupBoxModel1 = new ctkCollapsibleGroupBox(this);
auto lay1 = std::make_unique<QmitknnUNetTaskParamsUITemplate>(groupBoxModel1);
groupBoxModel1->setObjectName(QString::fromUtf8("model_1_Box"));
groupBoxModel1->setTitle(QString::fromUtf8("Model 1"));
groupBoxModel1->setMinimumSize(QSize(0, 0));
groupBoxModel1->setCollapsedHeight(5);
groupBoxModel1->setCollapsed(false);
groupBoxModel1->setFlat(true);
groupBoxModel1->setAlignment(Qt::AlignRight);
m_Controls.advancedSettingsLayout->addWidget(groupBoxModel1, 5, 0, 1, 2);
connect(lay1->modelBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(OnModelChanged(const QString &)));
connect(
lay1->plannerBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(OnTrainerChanged(const QString &)));
m_EnsembleParams.push_back(std::move(lay1));
ctkCollapsibleGroupBox *groupBoxModel2 = new ctkCollapsibleGroupBox(this);
auto lay2 = std::make_unique<QmitknnUNetTaskParamsUITemplate>(groupBoxModel2);
groupBoxModel2->setObjectName(QString::fromUtf8("model_2_Box"));
groupBoxModel2->setTitle(QString::fromUtf8("Model 2"));
groupBoxModel2->setMinimumSize(QSize(0, 0));
groupBoxModel2->setCollapsedHeight(5);
groupBoxModel2->setCollapsed(false);
groupBoxModel2->setFlat(true);
groupBoxModel2->setAlignment(Qt::AlignLeft);
m_Controls.advancedSettingsLayout->addWidget(groupBoxModel2, 5, 2, 1, 2);
connect(lay2->modelBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(OnModelChanged(const QString &)));
connect(
lay2->plannerBox, SIGNAL(currentTextChanged(const QString &)), this, SLOT(OnTrainerChanged(const QString &)));
m_EnsembleParams.push_back(std::move(lay2));
}
for (auto &layout : m_EnsembleParams)
{
layout->setVisible(visible);
}
}
void QmitknnUNetToolGUI::OnDownloadModel()
{
auto selectedTask = m_Controls.availableBox->currentText();
if(!selectedTask.isEmpty())
{
auto spExec = mitk::ProcessExecutor::New();
mitk::ProcessExecutor::ArgumentListType args;
args.push_back(selectedTask.toStdString());
this->WriteStatusMessage(
"Downloading the requested task in to the selected Results Folder. This might take some time "
"depending on your internet connection...");
m_Processes["DOWNLOAD"] = spExec;
if (!m_nnUNetThread->isRunning())
{
MITK_DEBUG << "Starting thread...";
m_nnUNetThread->start();
}
QString resultsFolder = m_ParentFolder->getResultsFolder();
emit Operate(resultsFolder, m_PythonPath, spExec, args);
m_Controls.stopDownloadButton->setVisible(true);
m_Controls.startDownloadButton->setVisible(false);
}
}
void QmitknnUNetToolGUI::OnDownloadWorkerExit(const bool isSuccess, const QString message)
{
if (isSuccess)
{
this->WriteStatusMessage(message + QString(" Click Refresh Results Folder to use the new Task."));
}
else
{
MITK_ERROR << "Download FAILED! " << message.toStdString();
this->WriteStatusMessage(QString("Download failed. Check your internet connection. " + message));
}
m_Controls.stopDownloadButton->setVisible(false);
m_Controls.startDownloadButton->setVisible(true);
}
void QmitknnUNetToolGUI::OnStopDownload()
{
mitk::ProcessExecutor::Pointer spExec = m_Processes["DOWNLOAD"];
spExec->KillProcess();
this->WriteStatusMessage("Download Killed by the user.");
m_Controls.stopDownloadButton->setVisible(false);
m_Controls.startDownloadButton->setVisible(true);
}
void QmitknnUNetToolGUI::OnClearCachePressed()
{
m_Cache.clear();
this->UpdateCacheCountOnUI();
}
diff --git a/Modules/SegmentationUI/SegmentationUtilities/QmitkContourModelToImageWidget.cpp b/Modules/SegmentationUI/SegmentationUtilities/QmitkContourModelToImageWidget.cpp
index 97327e8cab..42b465fe46 100644
--- a/Modules/SegmentationUI/SegmentationUtilities/QmitkContourModelToImageWidget.cpp
+++ b/Modules/SegmentationUI/SegmentationUtilities/QmitkContourModelToImageWidget.cpp
@@ -1,258 +1,258 @@
/*============================================================================
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 "QmitkContourModelToImageWidget.h"
#include <ui_QmitkContourModelToImageWidgetControls.h>
#include <mitkDataStorage.h>
#include <mitkImage.h>
#include <mitkContourModelSet.h>
#include <mitkContourModelSetToImageFilter.h>
#include <mitkLabelSetImage.h>
#include <mitkRenderingManager.h>
#include <mitkTimeNavigationController.h>
#include <QtConcurrentRun>
#include <QFuture>
#include <QFutureWatcher>
#include <qmessagebox.h>
static const char* const HelpText = "Select a image and a contour(set)";
class QmitkContourModelToImageWidgetPrivate
{
public:
QmitkContourModelToImageWidgetPrivate();
~QmitkContourModelToImageWidgetPrivate();
/** @brief Check if selections is valid. */
void SelectionControl( unsigned int index, const mitk::DataNode* selection);
/** @brief Enable buttons if data selection is valid. */
void EnableButtons(bool enable = true);
/** @brief Does the actual contour filling */
mitk::LabelSetImage::Pointer FillContourModelSetIntoImage(mitk::Image *image, mitk::ContourModelSet *contourSet, mitk::TimePointType timePoint);
Ui::QmitkContourModelToImageWidgetControls m_Controls;
QFutureWatcher<mitk::LabelSetImage::Pointer> m_Watcher;
};
QmitkContourModelToImageWidgetPrivate::QmitkContourModelToImageWidgetPrivate()
{
}
QmitkContourModelToImageWidgetPrivate::~QmitkContourModelToImageWidgetPrivate()
{
}
void QmitkContourModelToImageWidgetPrivate::EnableButtons(bool enable)
{
m_Controls.btnProcess->setEnabled(enable);
}
void QmitkContourModelToImageWidgetPrivate::SelectionControl(unsigned int index, const mitk::DataNode* /*selection*/)
{
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(index);
dataSelectionWidget->SetHelpText("");
this->EnableButtons();
}
mitk::LabelSetImage::Pointer QmitkContourModelToImageWidgetPrivate::FillContourModelSetIntoImage(mitk::Image* image, mitk::ContourModelSet* contourSet, mitk::TimePointType timePoint)
{
// Use mitk::ContourModelSetToImageFilter to fill the ContourModelSet into the image
mitk::ContourModelSetToImageFilter::Pointer contourFiller = mitk::ContourModelSetToImageFilter::New();
auto timeStep = image->GetTimeGeometry()->TimePointToTimeStep(timePoint);
contourFiller->SetTimeStep(timeStep);
contourFiller->SetImage(image);
contourFiller->SetInput(contourSet);
contourFiller->MakeOutputBinaryOn();
try
{
contourFiller->Update();
}
catch (const std::exception & e)
{
MITK_ERROR << "Error while converting contour model. "<< e.what();
}
catch (...)
{
MITK_ERROR << "Unknown error while converting contour model.";
}
if (nullptr == contourFiller->GetOutput())
{
MITK_ERROR<<"Could not write the selected contours into the image!";
}
auto result = mitk::LabelSetImage::New();
result->InitializeByLabeledImage(contourFiller->GetOutput());
return result;
}
void QmitkContourModelToImageWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection)
{
Q_D(QmitkContourModelToImageWidget);
QmitkDataSelectionWidget* dataSelectionWidget = d->m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node0 = dataSelectionWidget->GetSelection(0);
mitk::DataNode::Pointer node1 = dataSelectionWidget->GetSelection(1);
if (node0.IsNull() || node1.IsNull() )
{
d->EnableButtons(false);
dataSelectionWidget->SetHelpText(HelpText);
}
else
{
d->SelectionControl(index, selection);
}
}
void QmitkContourModelToImageWidget::OnProcessingFinished()
{
// Called when processing finished
// Adding the result to the data storage
Q_D(QmitkContourModelToImageWidget);
// Adding the result to the data storage
auto result = d->m_Watcher.result();
if (result.IsNotNull())
{
QmitkDataSelectionWidget* dataSelectionWidget = d->m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer imageNode = dataSelectionWidget->GetSelection(0);
mitk::DataNode::Pointer contourNode = dataSelectionWidget->GetSelection(1);
mitk::DataNode::Pointer filled = mitk::DataNode::New();
std::stringstream stream;
stream << imageNode->GetName();
stream << "_";
stream << contourNode->GetName();
filled->SetName(stream.str());
filled->SetData(result);
auto dataStorage = dataSelectionWidget->GetDataStorage();
if (dataStorage.IsNull())
{
std::string exception = "Cannot add result to the data storage. Data storage invalid.";
MITK_ERROR << "Error filling contours into an image: " << exception;
QMessageBox::information(nullptr, "Error filling contours into an image", QString::fromStdString(exception));
}
dataStorage->Add(filled, imageNode);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else
{
MITK_ERROR<<"Error filling contours into an image!";
}
d->EnableButtons();
}
void QmitkContourModelToImageWidget::OnProcessPressed()
{
Q_D(QmitkContourModelToImageWidget);
QmitkDataSelectionWidget* dataSelectionWidget = d->m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer imageNode = dataSelectionWidget->GetSelection(0);
mitk::DataNode::Pointer contourNode = dataSelectionWidget->GetSelection(1);
// Check if data nodes are valid
if(imageNode.IsNull() || contourNode.IsNull() )
{
MITK_ERROR << "Selection does not contain valid data";
QMessageBox::information( this, "Contour To Image",
"Selection does not contain valid data, please select a binary image and a contour(set)",
QMessageBox::Ok );
d->m_Controls.btnProcess->setEnabled(false);
return;
}
mitk::Image::Pointer image = static_cast<mitk::Image*>(imageNode->GetData());
// Check if the image is valid
if (image.IsNull())
{
MITK_ERROR<<"Error writing contours into image! Invalid image data selected!";
return;
}
const mitk::TimePointType timePoint = mitk::RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimePoint();
if (!image->GetTimeGeometry()->IsValidTimePoint(timePoint))
{
MITK_ERROR << "Error writing contours into image! Currently selected time point is not supported by selected image data.";
return;
}
// Check if the selected contours are valid
mitk::ContourModelSet::Pointer contourSet;
mitk::ContourModel::Pointer contour = dynamic_cast<mitk::ContourModel*>(contourNode->GetData());
if (contour.IsNotNull())
{
contourSet = mitk::ContourModelSet::New();
contourSet->AddContourModel(contour);
}
else
{
contourSet = static_cast<mitk::ContourModelSet*>(contourNode->GetData());
if (contourSet.IsNull())
{
MITK_ERROR<<"Error writing contours into binary image! Invalid contour data selected!";
return;
}
}
//Disable Buttons during calculation and initialize Progressbar
d->EnableButtons(false);
// Start the computation in a background thread
- QFuture< mitk::LabelSetImage::Pointer > future = QtConcurrent::run(d, &QmitkContourModelToImageWidgetPrivate::FillContourModelSetIntoImage, image, contourSet, timePoint);
+ auto future = QtConcurrent::run(&QmitkContourModelToImageWidgetPrivate::FillContourModelSetIntoImage, d, image, contourSet, timePoint);
d->m_Watcher.setFuture(future);
}
QmitkContourModelToImageWidget::QmitkContourModelToImageWidget(mitk::DataStorage* dataStorage, QWidget* parent)
: QWidget(parent)
, d_ptr(new QmitkContourModelToImageWidgetPrivate())
{
Q_D(QmitkContourModelToImageWidget);
// Set up UI
d->m_Controls.setupUi(this);
d->m_Controls.dataSelectionWidget->SetDataStorage(dataStorage);
d->m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::ImageAndSegmentationPredicate);
d->m_Controls.dataSelectionWidget->AddDataSelection(QmitkDataSelectionWidget::ContourModelPredicate);
d->m_Controls.dataSelectionWidget->SetHelpText(HelpText);
d->EnableButtons(false);
// Create connections
connect (d->m_Controls.btnProcess, SIGNAL(pressed()), this, SLOT(OnProcessPressed()));
connect(d->m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)),
this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*)));
connect(&d->m_Watcher, SIGNAL(finished()), this, SLOT(OnProcessingFinished()));
if( d->m_Controls.dataSelectionWidget->GetSelection(0).IsNotNull() &&
d->m_Controls.dataSelectionWidget->GetSelection(1).IsNotNull() )
{
OnSelectionChanged(0, d->m_Controls.dataSelectionWidget->GetSelection(0));
}
}
QmitkContourModelToImageWidget::~QmitkContourModelToImageWidget()
{
}
diff --git a/Modules/SemanticRelations/CMakeLists.txt b/Modules/SemanticRelations/CMakeLists.txt
deleted file mode 100644
index f4c3c2d50f..0000000000
--- a/Modules/SemanticRelations/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-MITK_CREATE_MODULE(
- DEPENDS MitkSceneSerializationBase MitkDICOM MitkMultilabel MitkPersistence MitkImageStatisticsUI
-)
-
-if(BUILD_TESTING)
- ADD_SUBDIRECTORY(Test)
-endif(BUILD_TESTING)
diff --git a/Modules/SemanticRelations/Test/CMakeLists.txt b/Modules/SemanticRelations/Test/CMakeLists.txt
deleted file mode 100644
index 153cd81e2e..0000000000
--- a/Modules/SemanticRelations/Test/CMakeLists.txt
+++ /dev/null
@@ -1 +0,0 @@
-MITK_CREATE_MODULE_TESTS()
diff --git a/Modules/SemanticRelations/Test/files.cmake b/Modules/SemanticRelations/Test/files.cmake
deleted file mode 100644
index 3e491291c0..0000000000
--- a/Modules/SemanticRelations/Test/files.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-set(MODULE_TESTS
- mitkSemanticRelationsTest.cpp
-)
-
-set(CPP_FILES
- mitkSemanticRelationsTestHelper.cpp
-)
diff --git a/Modules/SemanticRelations/Test/mitkSemanticRelationsTest.cpp b/Modules/SemanticRelations/Test/mitkSemanticRelationsTest.cpp
deleted file mode 100644
index 70ff2f25e6..0000000000
--- a/Modules/SemanticRelations/Test/mitkSemanticRelationsTest.cpp
+++ /dev/null
@@ -1,947 +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 semantic relations
-#include "mitkSemanticRelationException.h"
-#include "mitkSemanticRelationsInference.h"
-#include "mitkSemanticRelationsIntegration.h"
-#include "mitkSemanticRelationsDataStorageAccess.h"
-#include "mitkRelationStorage.h"
-#include "mitkControlPointManager.h"
-#include "mitkDICOMHelper.h"
-#include "mitkLesionManager.h"
-#include "mitkSemanticRelationsTestHelper.h"
-#include "mitkUIDGeneratorBoost.h"
-
-// mitk core
-#include <mitkStandaloneDataStorage.h>
-#include <mitkTestFixture.h>
-#include <mitkTestingMacros.h>
-#include <mitkPropertyNameHelper.h>
-
-// mitk persistence
-#include <mitkPersistenceService.h>
-
-class mitkSemanticRelationsTestSuite : public mitk::TestFixture
-{
- CPPUNIT_TEST_SUITE(mitkSemanticRelationsTestSuite);
- MITK_TEST(IntegrationTest);
- MITK_TEST(InferenceTest);
- MITK_TEST(DataStorageAccessTest);
- MITK_TEST(RemoveAndUnlinkTest);
- MITK_TEST(LesionAndControlPointTest);
- CPPUNIT_TEST_SUITE_END();
-
-private:
-
- mitk::DataStorage::Pointer m_DataStorage;
-
-public:
-
- void setUp() override
- {
- mitk::PersistenceService::LoadModule();
- m_DataStorage = mitk::StandaloneDataStorage::New();
- }
-
- void tearDown() override
- {
- // clear semantic relations storage
- mitk::SemanticRelationsTestHelper::ClearRelationStorage();
- }
-
- //////////////////////////////////////////////////////////////////////////
- // SPECIFIC TEST GROUPS
- //////////////////////////////////////////////////////////////////////////
- void IntegrationTest()
- {
- MITK_INFO << "=== IntegrationTest start ===";
- AddNewData();
- ExaminationPeriod();
- SegmentationAndLesion();
- InvalidData();
- MITK_INFO << "=== IntegrationTest end ===";
- }
-
- void InferenceTest()
- {
- MITK_INFO << "=== InferenceTest start ===";
- CombinedQueries();
- InstanceExistences();
- MITK_INFO << "=== InferenceTest end ===";
- }
-
- void DataStorageAccessTest()
- {
- MITK_INFO << "=== DataStorageAccessTest start ===";
- DataStorageAccess();
- MITK_INFO << "=== DataStorageAccessTest end ===";
- }
-
- void RemoveAndUnlinkTest()
- {
- MITK_INFO << "=== RemoveAndUnlinkTest start ===";
- CPRemoveAndUnlink();
- LesionRemoveAndUnlink();
- RemoveImagesAndSegmentation();
- MITK_INFO << "=== RemoveAndUnlinkTest end ===";
- }
-
- void LesionAndControlPointTest()
- {
- MITK_INFO << "=== LesionAndControlPointTest start ===";
- LesionDataTest();
- LesionOverwriteTest();
- MITK_INFO << "=== LesionAndControlPointTest end ===";
- }
-
- //////////////////////////////////////////////////////////////////////////
- // SPECIFIC TESTS
- //////////////////////////////////////////////////////////////////////////
- // IntegrationTest
- void AddNewData()
- {
- MITK_INFO << "=== AddNewData";
-
- // load data
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
-
- auto image = mitk::SemanticRelationsTestHelper::GetPatientOneCTImage();
- m_DataStorage->Add(image);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", image.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", image->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(image);
-
- // start test
- auto allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- CPPUNIT_ASSERT_MESSAGE("CaseID not correctly stored", allCaseIDs.front() == "Patient1");
- auto caseID = allCaseIDs.front();
-
- // test control point
- auto allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One control point should be stored", allControlPoints.size() == 1);
-
- auto controlPointOfImage = mitk::SemanticRelationsInference::GetControlPointOfImage(image);
- mitk::SemanticTypes::ControlPoint controlPointToCompare;
- controlPointToCompare.date = boost::gregorian::date(2019, 01, 01);
- CPPUNIT_ASSERT_MESSAGE("Control point not correctly stored", controlPointOfImage.date == controlPointToCompare.date);
-
- // test information type
- auto allInformationTypes = mitk::RelationStorage::GetAllInformationTypesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One information type should be stored", allInformationTypes.size() == 1);
-
- auto informationType = mitk::SemanticRelationsInference::GetInformationTypeOfImage(image);
- CPPUNIT_ASSERT_MESSAGE("Information type not correctly stored", informationType == "CT");
-
- semanticRelationsIntegration.SetInformationType(image, "MR");
- informationType = mitk::SemanticRelationsInference::GetInformationTypeOfImage(image);
- CPPUNIT_ASSERT_MESSAGE("Information type not correctly stored", informationType == "MR");
- }
-
- void ExaminationPeriod()
- {
- MITK_INFO << "=== ExaminationPeriod";
-
- // load data
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
-
- auto MRImage = mitk::SemanticRelationsTestHelper::GetPatientOneMRImage();
- m_DataStorage->Add(MRImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", MRImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", MRImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(MRImage);
-
- // start test
- auto allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- CPPUNIT_ASSERT_MESSAGE("One CaseID should be stored", allCaseIDs.size() == 1);
- auto caseID = allCaseIDs.front();
-
- auto allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One control point should be stored", allControlPoints.size() == 1);
-
- auto controlPointOfImage = mitk::SemanticRelationsInference::GetControlPointOfImage(MRImage);
- mitk::SemanticTypes::ControlPoint controlPoint;
- controlPoint.date = boost::gregorian::date(2019, 01, 01);
- CPPUNIT_ASSERT_MESSAGE("Control point not correctly stored", controlPointOfImage.date == controlPoint.date);
-
- auto allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One examination period should be stored", allExaminationPeriods.size() == 1);
-
- auto allImageIDs = mitk::RelationStorage::GetAllImageIDsOfControlPoint(caseID, controlPointOfImage);
- CPPUNIT_ASSERT_MESSAGE("Two images should reference the same control point", allImageIDs.size() == 2);
-
- // add additional control point to the same examination period
- // load data
- auto CTImage = mitk::SemanticRelationsTestHelper::GetPatientOneOtherCTImage();
- m_DataStorage->Add(CTImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", CTImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", CTImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(CTImage);
-
- // start test
- allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two control points should be stored", allControlPoints.size() == 2);
-
- allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One examination period should be stored", allExaminationPeriods.size() == 1);
-
- // modify control point to create new examination period
- // current control point is 2019, 01, 31
- // new control point should exceed threshold (30 days) and create new examination period
- // new control point is 2019, 02, 01
- controlPoint.UID = mitk::UIDGeneratorBoost::GenerateUID();
- controlPoint.date = boost::gregorian::date(2019, 02, 01);
- semanticRelationsIntegration.UnlinkImageFromControlPoint(CTImage);
- semanticRelationsIntegration.SetControlPointOfImage(CTImage, controlPoint);
-
- allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two control points should be stored", allControlPoints.size() == 2);
-
- allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two examination periods should be stored", allExaminationPeriods.size() == 2);
-
- auto examinationPeriod = allExaminationPeriods.front();
- CPPUNIT_ASSERT_MESSAGE("Examination period name should be 'New examination period'", examinationPeriod.name == "New examination period");
-
- examinationPeriod.name = "ExaminationPeriod_01";
- semanticRelationsIntegration.RenameExaminationPeriod(caseID, examinationPeriod);
-
- examinationPeriod = mitk::FindFittingExaminationPeriod(MRImage);
- CPPUNIT_ASSERT_MESSAGE("Examination period name should be 'ExaminationPeriod_01'", examinationPeriod.name == "ExaminationPeriod_01");
-
- examinationPeriod = mitk::FindFittingExaminationPeriod(CTImage);
- CPPUNIT_ASSERT_MESSAGE("Examination period name should be 'New examination period'", examinationPeriod.name == "New examination period");
-
- // modify control point to remove examination period and create new one before the first one
- controlPoint.UID = mitk::UIDGeneratorBoost::GenerateUID();
- controlPoint.date = boost::gregorian::date(2018, 01, 01);
- semanticRelationsIntegration.UnlinkImageFromControlPoint(CTImage);
- semanticRelationsIntegration.SetControlPointOfImage(CTImage, controlPoint);
-
- allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Examination period name should be 'ExaminationPeriod_01'", allExaminationPeriods.front().name == "ExaminationPeriod_01");
- CPPUNIT_ASSERT_MESSAGE("Examination period name should be 'New examination period'", allExaminationPeriods.back().name == "New examination period");
-
- mitk::SortAllExaminationPeriods(caseID, allExaminationPeriods);
- CPPUNIT_ASSERT_MESSAGE("Examination period name should be 'New examination period'", allExaminationPeriods.front().name == "New examination period");
- CPPUNIT_ASSERT_MESSAGE("Examination period name should be 'ExaminationPeriod_01'", allExaminationPeriods.back().name == "ExaminationPeriod_01");
- CPPUNIT_ASSERT_MESSAGE("Two examination periods should be stored", allExaminationPeriods.size() == 2);
- }
-
- void SegmentationAndLesion()
- {
- MITK_INFO << "=== SegmentationAndLesion";
-
- // load data
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
-
- // Patient2
- auto image = mitk::SemanticRelationsTestHelper::GetPatientTwoPETImage();
- m_DataStorage->Add(image);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", image.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", image->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(image);
-
- auto segmentation = mitk::SemanticRelationsTestHelper::GetPatientTwoSegmentation();
- m_DataStorage->Add(segmentation, image);
- CPPUNIT_ASSERT_MESSAGE("Not a valid segmentation data node", segmentation.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Segmentation data is empty", segmentation->GetData() != nullptr);
- semanticRelationsIntegration.AddSegmentation(segmentation, image);
-
- // start test
- auto allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- CPPUNIT_ASSERT_MESSAGE("Two CaseIDs should be stored", allCaseIDs.size() == 2);
-
- // test lesion (add and link)
- auto lesion = mitk::GenerateNewLesion();
- semanticRelationsIntegration.AddLesionAndLinkSegmentation(segmentation, lesion);
-
- auto representedLesion = mitk::SemanticRelationsInference::GetLesionOfSegmentation(segmentation);
- CPPUNIT_ASSERT_MESSAGE("Represented lesion should be the only stored lesion", lesion.UID == representedLesion.UID);
- }
-
- void InvalidData()
- {
- MITK_INFO << "=== InvalidData";
-
- // TEST INVALID CASE ID
- std::string caseID = "invalidID";
- auto allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No lesion should be stored, given a non-existing CaseID", allLesions.size() == 0);
-
- auto allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No control point should be stored, given a non-existing CaseID", allControlPoints.size() == 0);
-
- auto allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No examination periods should be stored, given a non-existing CaseID", allExaminationPeriods.size() == 0);
-
- auto allInformationTypes = mitk::RelationStorage::GetAllInformationTypesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No information type should be stored, given a non-existing CaseID", allInformationTypes.size() == 0);
-
- auto allImageIDsOfCase = mitk::RelationStorage::GetAllImageIDsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No image ID should be stored, given a non-existing CaseID", allControlPoints.size() == 0);
-
- bool instanceExists = mitk::RelationStorage::InstanceExists(caseID);
- CPPUNIT_ASSERT_MESSAGE("CaseID should not exist", !instanceExists);
-
- // TEST INVALID DATE
- mitk::DataNode::Pointer invalidDateImage = mitk::SemanticRelationsTestHelper::GetInvalidDate();
- m_DataStorage->Add(invalidDateImage);
-
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", invalidDateImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", invalidDateImage->GetData() != nullptr);
-
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: AddImage",
- semanticRelationsIntegration.AddImage(invalidDateImage),
- mitk::SemanticRelationException);
-
- auto controlPointOfImage = mitk::SemanticRelationsInference::GetControlPointOfImage(invalidDateImage);
- CPPUNIT_ASSERT_MESSAGE("No control point should be stored for an invalid DICOM date", controlPointOfImage.UID.empty());
-
- // set invalid date format for current image
- // 0x0008, 0x0022 (AcquisitionDate), should be 20180101
- invalidDateImage->GetData()->SetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0022).c_str(),
- mitk::StringProperty::New("201811"));
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: GenerateControlPoint",
- mitk::GenerateControlPoint(invalidDateImage),
- mitk::SemanticRelationException);
-
- // set valid date format for current image and add image again (only control point should be updated)
- // 0x0008, 0x0022 (AcquisitionDate), should be 20180101
- invalidDateImage->GetData()->SetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0022).c_str(),
- mitk::StringProperty::New("20180101"));
- semanticRelationsIntegration.AddImage(invalidDateImage);
-
- controlPointOfImage = mitk::SemanticRelationsInference::GetControlPointOfImage(invalidDateImage);
- mitk::SemanticTypes::ControlPoint controlPointToCompare;
- controlPointToCompare.date = boost::gregorian::date(2018, 01, 01);
- CPPUNIT_ASSERT_MESSAGE("Control point not correctly stored", controlPointOfImage.date == controlPointToCompare.date);
-
- // TEST INVALID MODALITY
- mitk::DataNode::Pointer invalidModalityImage = mitk::SemanticRelationsTestHelper::GetInvalidModality();
- m_DataStorage->Add(invalidModalityImage);
-
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", invalidModalityImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", invalidModalityImage->GetData() != nullptr);
-
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: AddImage",
- semanticRelationsIntegration.AddImage(invalidModalityImage),
- mitk::SemanticRelationException);
-
- auto informationTypeOfImage = mitk::SemanticRelationsInference::GetInformationTypeOfImage(invalidModalityImage);
- CPPUNIT_ASSERT_MESSAGE("No information type should be stored for an invalid DICOM date", informationTypeOfImage.empty());
-
- // set valid modality for current image and add image again
- // 0x0008, 0x0060 (Modality), should be CT
- invalidModalityImage->GetData()->SetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0060).c_str(),
- mitk::StringProperty::New("CT"));
- semanticRelationsIntegration.AddImage(invalidModalityImage);
-
- auto informationType = mitk::SemanticRelationsInference::GetInformationTypeOfImage(invalidModalityImage);
- CPPUNIT_ASSERT_MESSAGE("Information type not correctly stored", informationType == "CT");
-
- // TEST INVALID ID
- mitk::DataNode::Pointer invalidIDImage = mitk::SemanticRelationsTestHelper::GetInvalidID();
- m_DataStorage->Add(invalidIDImage);
-
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", invalidModalityImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", invalidModalityImage->GetData() != nullptr);
-
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: AddImage",
- semanticRelationsIntegration.AddImage(invalidIDImage),
- mitk::SemanticRelationException);
-
- // set valid ID for current image and add image again
- // 0x0020, 0x000e (SeriesInstanceUID)
- auto generatedUID = mitk::UIDGeneratorBoost::GenerateUID();
- invalidIDImage->GetData()->SetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0020, 0x000e).c_str(),
- mitk::StringProperty::New(generatedUID));
- semanticRelationsIntegration.AddImage(invalidIDImage);
-
- auto IDFromNode = mitk::GetIDFromDataNode(invalidIDImage);
- CPPUNIT_ASSERT_MESSAGE("ID not correctly stored", IDFromNode == generatedUID);
-
- // TEST INVALID CASE ID
- mitk::DataNode::Pointer invalidCaseIDImage = mitk::SemanticRelationsTestHelper::GetInvalidCaseID();
- m_DataStorage->Add(invalidCaseIDImage);
-
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", invalidModalityImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", invalidModalityImage->GetData() != nullptr);
-
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: AddImage",
- semanticRelationsIntegration.AddImage(invalidCaseIDImage),
- mitk::SemanticRelationException);
-
- // set valid case ID for current image and add image again
- // 0x0010, 0x0010 (PatientName)
- invalidCaseIDImage->GetData()->SetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0010, 0x0010).c_str(),
- mitk::StringProperty::New("Patient7"));
- semanticRelationsIntegration.AddImage(invalidCaseIDImage);
-
- auto caseIDFromNode = mitk::GetCaseIDFromDataNode(invalidCaseIDImage);
- CPPUNIT_ASSERT_MESSAGE("Case ID not correctly stored", caseIDFromNode == "Patient7");
- }
-
- // InferenceTest
- void CombinedQueries()
- {
- MITK_INFO << "=== CombinedQueries";
-
- // add image with segmentation and lesion
- auto image = mitk::SemanticRelationsTestHelper::GetPatientTwoPETImage();
- m_DataStorage->Add(image);
-
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", image.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", image->GetData() != nullptr);
-
- auto segmentation = mitk::SemanticRelationsTestHelper::GetPatientTwoSegmentation();
- m_DataStorage->Add(segmentation, image);
-
- CPPUNIT_ASSERT_MESSAGE("Not a valid segmentation data node", segmentation.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Segmentation data is empty", segmentation->GetData() != nullptr);
-
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- semanticRelationsIntegration.AddImage(image);
- semanticRelationsIntegration.AddSegmentation(segmentation, image);
-
- auto caseID = mitk::GetCaseIDFromDataNode(image);
-
- auto lesion = mitk::GenerateNewLesion();
- semanticRelationsIntegration.AddLesionAndLinkSegmentation(segmentation, lesion);
-
- auto allLesionsOfImage = mitk::SemanticRelationsInference::GetAllLesionsOfImage(image);
- CPPUNIT_ASSERT_MESSAGE("One lesion should be stored", allLesionsOfImage.size() == 1);
-
- auto controlPoint = mitk::SemanticRelationsInference::GetControlPointOfImage(image);
- auto allLesionsOfControlPoint = mitk::SemanticRelationsInference::GetAllLesionsOfControlPoint(caseID, controlPoint);
- CPPUNIT_ASSERT_MESSAGE("Lesions should be the same", (allLesionsOfImage.size() == allLesionsOfControlPoint.size())
- && (allLesionsOfImage.front().UID == allLesionsOfControlPoint.front().UID));
-
- auto allImageIDsOfLesion = mitk::SemanticRelationsInference::GetAllImageIDsOfLesion(caseID, allLesionsOfControlPoint.front());
- CPPUNIT_ASSERT_MESSAGE("Image IDs should be the same", (allImageIDsOfLesion.size() == 1)
- && (allImageIDsOfLesion.front() == mitk::GetIDFromDataNode(image)));
-
- auto allControlPointsOfLesion = mitk::SemanticRelationsInference::GetAllControlPointsOfLesion(caseID, allLesionsOfImage.front());
- CPPUNIT_ASSERT_MESSAGE("Control points should be the same", (allControlPointsOfLesion.size() == 1)
- && (allControlPointsOfLesion.front().date == controlPoint.date));
-
- auto informationType = mitk::SemanticRelationsInference::GetInformationTypeOfImage(image);
- auto allLesionsOfInformationType = mitk::SemanticRelationsInference::GetAllLesionsOfInformationType(caseID, informationType);
- CPPUNIT_ASSERT_MESSAGE("Lesions should be the same", (allLesionsOfImage.size() == allLesionsOfInformationType.size())
- && (allLesionsOfImage.front().UID == allLesionsOfInformationType.front().UID));
-
- auto allControlPointsOfInformationType = mitk::SemanticRelationsInference::GetAllControlPointsOfInformationType(caseID, informationType);
- CPPUNIT_ASSERT_MESSAGE("Control points should be the same", (allControlPointsOfLesion.size() == 1)
- && (allControlPointsOfLesion.front().date == controlPoint.date));
-
- auto allInformationTypesOfControlPoint = mitk::SemanticRelationsInference::GetAllInformationTypesOfControlPoint(caseID, controlPoint);
- CPPUNIT_ASSERT_MESSAGE("Information types should be the same", (allInformationTypesOfControlPoint.size() == 1)
- && (allInformationTypesOfControlPoint.front() == informationType));
-
- auto allSpecificLesions = mitk::SemanticRelationsInference::GetAllSpecificLesions(caseID, controlPoint, informationType);
- CPPUNIT_ASSERT_MESSAGE("Lesions should be the same", (allLesionsOfImage.size() == allSpecificLesions.size())
- && (allLesionsOfImage.front().UID == allSpecificLesions.front().UID));
- }
-
- void InstanceExistences()
- {
- MITK_INFO << "=== InstanceExistences";
-
- mitk::SemanticRelationsDataStorageAccess semanticRelationsDataStorageAccess(m_DataStorage);
- auto allSegmentationsOfCase = semanticRelationsDataStorageAccess.GetAllSegmentationsOfCase("Patient2");
- CPPUNIT_ASSERT_MESSAGE("One segmentation should be stored", allSegmentationsOfCase.size() == 1);
-
- auto segmentation = allSegmentationsOfCase.front();
- CPPUNIT_ASSERT_MESSAGE("Not a valid segmentation data node", segmentation.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Segmentation data is empty", segmentation->GetData() != nullptr);
-
- bool valid = mitk::SemanticRelationsInference::IsRepresentingALesion(segmentation);
- CPPUNIT_ASSERT_MESSAGE("Segmentation node should represent a lesion", valid);
-
- auto caseID = "Patient2";
- valid = mitk::SemanticRelationsInference::IsRepresentingALesion(caseID, mitk::GetIDFromDataNode(segmentation));
- CPPUNIT_ASSERT_MESSAGE("Segmentation (via ID) should represent a lesion", valid);
-
- auto allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One lesion should be stored", allLesions.size() == 1);
-
- auto lesion = allLesions.front();
- valid = mitk::SemanticRelationsInference::IsLesionPresent(lesion, segmentation);
- CPPUNIT_ASSERT_MESSAGE("Lesion should be present on segmentation", valid);
-
- auto allImagesOfCase = semanticRelationsDataStorageAccess.GetAllImagesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One image should be stored", allImagesOfCase.size() == 1);
-
- auto image = allImagesOfCase.front();
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", image.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", image->GetData() != nullptr);
-
- valid = mitk::SemanticRelationsInference::IsLesionPresent(lesion, image);
- CPPUNIT_ASSERT_MESSAGE("Lesion should be present on image", valid);
-
- valid = mitk::SemanticRelationsInference::IsLesionPresentOnImage(caseID, lesion, mitk::GetIDFromDataNode(image));
- CPPUNIT_ASSERT_MESSAGE("Lesion should be present on segmentation", valid);
-
- valid = mitk::SemanticRelationsInference::IsLesionPresentOnSegmentation(caseID, lesion, mitk::GetIDFromDataNode(segmentation));
- CPPUNIT_ASSERT_MESSAGE("Lesion should be present on image", valid);
-
- auto controlPoint = mitk::SemanticRelationsInference::GetControlPointOfImage(image);
- valid = mitk::SemanticRelationsInference::IsLesionPresentAtControlPoint(caseID, lesion, controlPoint);
- CPPUNIT_ASSERT_MESSAGE("Lesion should be present at control point", valid);
-
- controlPoint.date = boost::gregorian::date(2019, 01, 01);
- valid = mitk::SemanticRelationsInference::IsLesionPresentAtControlPoint(caseID, lesion, controlPoint);
- CPPUNIT_ASSERT_MESSAGE("No lesion should be present at control point", !valid);
-
- valid = mitk::SemanticRelationsInference::InstanceExists(image);
- CPPUNIT_ASSERT_MESSAGE("Image should exist", valid);
-
- valid = mitk::SemanticRelationsInference::InstanceExists(segmentation);
- CPPUNIT_ASSERT_MESSAGE("Segmentation should exist", valid);
-
- valid = mitk::SemanticRelationsInference::InstanceExists(caseID, lesion);
- CPPUNIT_ASSERT_MESSAGE("Lesion should exist", valid);
-
- auto emptyLesion = mitk::GenerateNewLesion("ExampleLesionClass");
- valid = mitk::SemanticRelationsInference::InstanceExists(caseID, emptyLesion);
- CPPUNIT_ASSERT_MESSAGE("Lesion should not exist", !valid);
-
- auto newControlPoint = mitk::SemanticTypes::ControlPoint();
- valid = mitk::SemanticRelationsInference::InstanceExists(caseID, newControlPoint);
- CPPUNIT_ASSERT_MESSAGE("Control point should not exist for this case", !valid);
-
- valid = mitk::SemanticRelationsInference::InstanceExists(caseID, controlPoint);
- CPPUNIT_ASSERT_MESSAGE("Control point should exist for this case", valid);
-
- auto allExaminationPeriod = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One examination period should be stored", allExaminationPeriod.size() == 1);
- auto examinationPeriod = allExaminationPeriod.front();
-
- valid = mitk::SemanticRelationsInference::InstanceExists(caseID, examinationPeriod);
- CPPUNIT_ASSERT_MESSAGE("Examination period should exist for this case", valid);
-
- auto informationType = mitk::SemanticRelationsInference::GetInformationTypeOfImage(image);
- valid = mitk::SemanticRelationsInference::InstanceExists(caseID, informationType);
- CPPUNIT_ASSERT_MESSAGE("Control point should exist for this case", valid);
-
- valid = mitk::SemanticRelationsInference::InstanceExists(caseID, "CT");
- CPPUNIT_ASSERT_MESSAGE("Control point should not exist for this case", !valid);
-
- valid = mitk::SemanticRelationsInference::SpecificImageExists(caseID, lesion, informationType);
- CPPUNIT_ASSERT_MESSAGE("Specific image should exist for this case", valid);
-
- valid = mitk::SemanticRelationsInference::SpecificImageExists(caseID, lesion, controlPoint);
- CPPUNIT_ASSERT_MESSAGE("Specific image should exist for this case", valid);
-
- valid = mitk::SemanticRelationsInference::SpecificImageExists(caseID, informationType, controlPoint);
- CPPUNIT_ASSERT_MESSAGE("Specific image should exist for this case", valid);
- }
-
- // DataStorageAccessTest
- void DataStorageAccess()
- {
- MITK_INFO << "=== DataStorageAccess";
-
- // load data
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
-
- // Patient1
- auto CTImage = mitk::SemanticRelationsTestHelper::GetPatientOneCTImage();
- m_DataStorage->Add(CTImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", CTImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", CTImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(CTImage);
-
- auto MRImage = mitk::SemanticRelationsTestHelper::GetPatientOneMRImage();
- m_DataStorage->Add(MRImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", MRImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", MRImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(MRImage);
-
- auto otherCTImage = mitk::SemanticRelationsTestHelper::GetPatientOneOtherCTImage();
- m_DataStorage->Add(otherCTImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", otherCTImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", otherCTImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(otherCTImage);
-
- // Patient2
- auto PETImage = mitk::SemanticRelationsTestHelper::GetPatientTwoPETImage();
- m_DataStorage->Add(PETImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", PETImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", PETImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(PETImage);
-
- auto PETSegmentation = mitk::SemanticRelationsTestHelper::GetPatientTwoSegmentation();
- m_DataStorage->Add(PETSegmentation, PETImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid segmentation data node", PETSegmentation.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Segmentation data is empty", PETSegmentation->GetData() != nullptr);
- semanticRelationsIntegration.AddSegmentation(PETSegmentation, PETImage);
-
- auto lesion = mitk::GenerateNewLesion();
- semanticRelationsIntegration.AddLesionAndLinkSegmentation(PETSegmentation, lesion);
-
- // start test
- mitk::SemanticRelationsDataStorageAccess semanticRelationsDataStorageAccess(m_DataStorage);
-
- auto caseID = "Patient1";
- auto allSegmentationsOfCase = semanticRelationsDataStorageAccess.GetAllSegmentationsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No segmentation should be stored", allSegmentationsOfCase.size() == 0);
-
- auto allImagesOfCase = semanticRelationsDataStorageAccess.GetAllImagesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Three images should be stored", allImagesOfCase.size() == 3);
-
- auto allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No lesion should be stored", allLesions.size() == 0);
-
- auto emptyLesion = mitk::GenerateNewLesion("ExampleLesionClass");
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: GetAllSegmentationsOfLesion",
- semanticRelationsDataStorageAccess.GetAllSegmentationsOfLesion(caseID, emptyLesion),
- mitk::SemanticRelationException);
-
- auto examinationPeriod = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One examination period should be stored", examinationPeriod.size() == 1);
- auto allSpecificImages = semanticRelationsDataStorageAccess.GetAllSpecificImages(caseID, "CT", examinationPeriod.front());
- CPPUNIT_ASSERT_MESSAGE("Two CT images should be stored", allSpecificImages.size() == 2);
-
- caseID = "Patient2";
- allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One lesion should be stored", allLesions.size() == 1);
-
- lesion = allLesions.front();
- auto allSegmentationsOfLesion = semanticRelationsDataStorageAccess.GetAllSegmentationsOfLesion(caseID, lesion);
- CPPUNIT_ASSERT_MESSAGE("One segmentation should be stored", allSegmentationsOfLesion.size() == 1);
-
- auto allImagesOfLesion = semanticRelationsDataStorageAccess.GetAllImagesOfLesion(caseID, lesion);
- CPPUNIT_ASSERT_MESSAGE("One image should be stored", allImagesOfLesion.size() == 1);
-
- auto allControlPointsOfLesion = mitk::SemanticRelationsInference::GetAllControlPointsOfLesion(caseID, lesion);
- CPPUNIT_ASSERT_MESSAGE("One control point should be stored", allControlPointsOfLesion.size() == 1);
- auto controlPoint = allControlPointsOfLesion.front();
-
- allSpecificImages = semanticRelationsDataStorageAccess.GetAllSpecificImages(caseID, controlPoint, "PT");
- CPPUNIT_ASSERT_MESSAGE("One image should be stored", allSpecificImages.size() == 1);
-
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: GetAllSpecificImages",
- semanticRelationsDataStorageAccess.GetAllSpecificImages(caseID, controlPoint, "CT"),
- mitk::SemanticRelationException);
-
- auto allSpecificSegmentations = semanticRelationsDataStorageAccess.GetAllSpecificSegmentations(caseID, controlPoint, "PT");
- CPPUNIT_ASSERT_MESSAGE("One segmentation should be stored", allSpecificSegmentations.size() == 1);
-
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: GetAllSpecificSegmentations",
- semanticRelationsDataStorageAccess.GetAllSpecificSegmentations(caseID, controlPoint, "MR"),
- mitk::SemanticRelationException);
-
- auto specificSegmentation = semanticRelationsDataStorageAccess.GetSpecificSegmentation(caseID, controlPoint, "PT", lesion);
- CPPUNIT_ASSERT_MESSAGE("One segmentation should be stored", specificSegmentation == PETSegmentation);
-
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: GetAllSpecificSegmentations",
- semanticRelationsDataStorageAccess.GetSpecificSegmentation(caseID, controlPoint, "CT", lesion),
- mitk::SemanticRelationException);
- }
-
- // RemoveAndUnlinkTest
- void CPRemoveAndUnlink()
- {
- MITK_INFO << "=== RemoveAndUnlink";
-
- // load data
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
-
- auto CTImage = mitk::SemanticRelationsTestHelper::GetPatientThreeCTImage();
- m_DataStorage->Add(CTImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", CTImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", CTImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(CTImage);
-
- auto MRImage = mitk::SemanticRelationsTestHelper::GetPatientThreeMRImage();
- m_DataStorage->Add(MRImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", MRImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", MRImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(MRImage);
-
- // start test
- auto allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- CPPUNIT_ASSERT_MESSAGE("One CaseID should be stored", allCaseIDs.size() == 1);
-
- auto caseID = allCaseIDs.front();
- CPPUNIT_ASSERT_MESSAGE("CaseID should be Patient3", caseID == "Patient3");
-
- auto allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One examination period should be sored", allExaminationPeriods.size() == 1);
-
- auto allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two control points should be stored", allControlPoints.size() == 2);
-
- // control points
- auto CTControlPoint = mitk::SemanticRelationsInference::GetControlPointOfImage(CTImage);
- semanticRelationsIntegration.UnlinkImageFromControlPoint(CTImage);
-
- allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One examination period should be stored", allExaminationPeriods.size() == 1);
-
- allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One control point should be stored since one has been removed", allControlPoints.size() == 1);
-
- CTControlPoint = mitk::SemanticRelationsInference::GetControlPointOfImage(CTImage);
- CPPUNIT_ASSERT_MESSAGE("Control point should be removed", CTControlPoint.UID.empty());
-
- CTControlPoint = mitk::GenerateControlPoint(CTImage);
- semanticRelationsIntegration.SetControlPointOfImage(CTImage, CTControlPoint);
-
- allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One examination period should be sored", allExaminationPeriods.size() == 1);
-
- allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two control points should be stored", allControlPoints.size() == 2);
-
- mitk::SemanticTypes::ControlPoint newCTControlPoint;
- newCTControlPoint.UID = mitk::UIDGeneratorBoost::GenerateUID();
- newCTControlPoint.date = boost::gregorian::date(2019, 03, 01);
- semanticRelationsIntegration.SetControlPointOfImage(CTImage, newCTControlPoint);
-
- allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One examination period should be sored", allExaminationPeriods.size() == 1);
-
- allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two control points should be stored", allControlPoints.size() == 2);
-
- newCTControlPoint.UID = mitk::UIDGeneratorBoost::GenerateUID();
- newCTControlPoint.date = boost::gregorian::date(2019, 01, 01);
- semanticRelationsIntegration.SetControlPointOfImage(CTImage, newCTControlPoint);
-
- allExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two examination periods should be stored", allExaminationPeriods.size() == 2);
-
- allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two control points should be stored", allControlPoints.size() == 2);
- }
-
- void LesionRemoveAndUnlink()
- {
- MITK_INFO << "=== LesionRemoveAndUnlink";
-
- // load data
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- mitk::SemanticRelationsDataStorageAccess semanticRelationsDataStorageAccess(m_DataStorage);
-
- auto allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- CPPUNIT_ASSERT_MESSAGE("One CaseID should be stored", allCaseIDs.size() == 1);
- auto caseID = allCaseIDs.front();
-
- auto allImages = semanticRelationsDataStorageAccess.GetAllImagesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two images should be stored", allImages.size() == 2);
-
- auto allCTImageIDs = mitk::RelationStorage::GetAllImageIDsOfInformationType(caseID, "CT");
- CPPUNIT_ASSERT_MESSAGE("One image should be stored", allCTImageIDs.size() == 1);
-
- auto allMRImageIDs = mitk::RelationStorage::GetAllImageIDsOfInformationType(caseID, "MR");
- CPPUNIT_ASSERT_MESSAGE("One image should be stored", allMRImageIDs.size() == 1);
-
- mitk::DataNode::Pointer CTImage;
- mitk::DataNode::Pointer MRImage;
- for (const auto& image : allImages)
- {
- auto imageID = mitk::GetIDFromDataNode(image);
- if (imageID == allCTImageIDs.front())
- {
- CTImage = image;
- }
- else if (imageID == allMRImageIDs.front())
- {
- MRImage = image;
- }
- }
-
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", CTImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", CTImage->GetData() != nullptr);
-
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", MRImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", MRImage->GetData() != nullptr);
-
- auto CTSegmentation = mitk::SemanticRelationsTestHelper::GetPatientThreeCTSegmentation();
- m_DataStorage->Add(CTSegmentation, CTImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid segmentation data node", CTSegmentation.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Segmentation data is empty", CTSegmentation->GetData() != nullptr);
- semanticRelationsIntegration.AddSegmentation(CTSegmentation, CTImage);
-
- auto MRSegmentation = mitk::SemanticRelationsTestHelper::GetPatientThreeMRSegmentation();
- m_DataStorage->Add(MRSegmentation, MRImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid segmentation data node", MRSegmentation.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Segmentation data is empty", MRSegmentation->GetData() != nullptr);
- semanticRelationsIntegration.AddSegmentation(MRSegmentation, MRImage);
-
- auto newLesion = mitk::GenerateNewLesion();
- semanticRelationsIntegration.AddLesionAndLinkSegmentation(CTSegmentation, newLesion);
- newLesion = mitk::GenerateNewLesion();
- semanticRelationsIntegration.AddLesionAndLinkSegmentation(MRSegmentation, newLesion);
-
- // start test
- auto allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two lesions should be stored", allLesions.size() == 2);
-
- auto MRLesion = mitk::SemanticRelationsInference::GetLesionOfSegmentation(MRSegmentation);
- semanticRelationsIntegration.UnlinkSegmentationFromLesion(MRSegmentation);
-
- allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two lesions should be stored", allLesions.size() == 2);
-
- auto emptyLesion = mitk::SemanticRelationsInference::GetLesionOfSegmentation(MRSegmentation);
- CPPUNIT_ASSERT_MESSAGE("Lesion should be removed", emptyLesion.UID.empty());
-
- semanticRelationsIntegration.LinkSegmentationToLesion(MRSegmentation, MRLesion);
- allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two lesions should be stored", allLesions.size() == 2);
-
- auto CTLesion = mitk::SemanticRelationsInference::GetLesionOfSegmentation(CTSegmentation);
- CPPUNIT_ASSERT_THROW_MESSAGE("Semantic relation exception not thrown: RemoveLesion",
- semanticRelationsIntegration.RemoveLesion(caseID, CTLesion),
- mitk::SemanticRelationException);
-
- semanticRelationsIntegration.UnlinkSegmentationFromLesion(CTSegmentation);
- semanticRelationsIntegration.RemoveLesion(caseID, CTLesion);
-
- allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One lesions should be stored since one has been removed", allLesions.size() == 1);
-
- CTLesion = mitk::SemanticRelationsInference::GetLesionOfSegmentation(CTSegmentation);
- CPPUNIT_ASSERT_MESSAGE("Lesion should be removed", CTLesion.UID.empty());
- }
-
- void RemoveImagesAndSegmentation()
- {
- MITK_INFO << "=== RemoveImagesAndSegmentation";
-
- // load data
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- mitk::SemanticRelationsDataStorageAccess semanticRelationsDataStorageAccess(m_DataStorage);
-
- auto allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- CPPUNIT_ASSERT_MESSAGE("One CaseID should be stored", allCaseIDs.size() == 1);
- auto caseID = allCaseIDs.front();
-
- auto allImages = semanticRelationsDataStorageAccess.GetAllImagesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two images should be stored", allImages.size() == 2);
-
- auto allSegmentations = semanticRelationsDataStorageAccess.GetAllSegmentationsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("Two segmentations should be stored", allSegmentations.size() == 2);
-
- for (const auto& image : allImages)
- {
- semanticRelationsIntegration.RemoveImage(image);
- }
-
- for (const auto& segmentation : allSegmentations)
- {
- semanticRelationsIntegration.RemoveSegmentation(segmentation);
- }
-
- allImages = semanticRelationsDataStorageAccess.GetAllImagesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No images should be stored", allImages.size() == 0);
-
- allSegmentations = semanticRelationsDataStorageAccess.GetAllSegmentationsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No segmentations should be stored", allSegmentations.size() == 0);
-
- auto allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No control point should be stored", allControlPoints.size() == 0);
-
- auto allInformationTypes = mitk::RelationStorage::GetAllInformationTypesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("No information type should be stored", allInformationTypes.size() == 0);
-
- auto allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One lesions should be stored", allLesions.size() == 1);
- }
-
- // LesionAndControlPointTest
- void LesionDataTest()
- {
- MITK_INFO << "=== LesionDataTest";
-
- // load data
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
-
- // CT image
- auto CTImage = mitk::SemanticRelationsTestHelper::GetPatientThreeCTImage();
- m_DataStorage->Add(CTImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", CTImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", CTImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(CTImage);
-
- // MR image
- auto MRImage = mitk::SemanticRelationsTestHelper::GetPatientThreeMRImage();
- m_DataStorage->Add(MRImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid image data node", MRImage.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Image data is empty", MRImage->GetData() != nullptr);
- semanticRelationsIntegration.AddImage(MRImage);
-
- auto segmentation = mitk::SemanticRelationsTestHelper::GetPatientThreeMRSegmentation();
- m_DataStorage->Add(segmentation, MRImage);
- CPPUNIT_ASSERT_MESSAGE("Not a valid segmentation data node", segmentation.IsNotNull());
- CPPUNIT_ASSERT_MESSAGE("Segmentation data is empty", segmentation->GetData() != nullptr);
- semanticRelationsIntegration.AddSegmentation(segmentation, MRImage);
-
- auto lesion = mitk::GenerateNewLesion();
- semanticRelationsIntegration.AddLesionAndLinkSegmentation(segmentation, lesion);
-
- auto caseID = "Patient3";
- auto allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One lesions should be stored", allLesions.size() == 1);
-
- lesion = allLesions.front();
- mitk::LesionData lesionData(lesion);
- mitk::ComputeLesionPresence(lesionData, caseID);
-
- auto lesionByUID = mitk::GetLesionByUID(caseID, lesion.UID);
- mitk::LesionData lesionByUIDData;
- lesionByUIDData.SetLesion(lesionByUID);
- mitk::ComputeLesionPresence(lesionByUIDData, caseID);
-
- CPPUNIT_ASSERT_MESSAGE("Lesions should be equal", lesion.UID == lesionByUID.UID && lesionData.GetLesionUID() == lesionByUIDData.GetLesionUID());
- CPPUNIT_ASSERT_MESSAGE("Lesion names should be equal", lesion.name == lesionByUID.name && lesionData.GetLesionName() == lesionByUIDData.GetLesionName());
- CPPUNIT_ASSERT_MESSAGE("Lesion classes should be equal", lesion.lesionClass.UID == lesionByUID.lesionClass.UID);
- CPPUNIT_ASSERT_MESSAGE("Lesion presences should be equal", lesionData.GetLesionPresence() == lesionByUIDData.GetLesionPresence());
- CPPUNIT_ASSERT_MESSAGE("Lesion presence should be 'false' and 'true'", lesionData.GetLesionPresence()[0] == false && lesionData.GetLesionPresence()[1] == true);
- }
-
- void LesionOverwriteTest()
- {
- MITK_INFO << "=== LesionOverwriteTest";
-
- auto caseID = "Patient3";
- auto allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One lesions should be stored", allLesions.size() == 1);
-
- auto lesion = allLesions.front();
- CPPUNIT_ASSERT_MESSAGE("Lesion name should be 'New lesion'", lesion.name == "New lesion");
- CPPUNIT_ASSERT_MESSAGE("Lesion class type should be empty", lesion.lesionClass.classType == "");
-
- lesion.name = "Lesion_01";
- lesion.lesionClass.classType = "Class_01";
-
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- semanticRelationsIntegration.OverwriteLesion(caseID, lesion);
-
- CPPUNIT_ASSERT_MESSAGE("Lesion name should be 'Lesion_01'", lesion.name == "Lesion_01");
-
- auto foundLesionClass = mitk::FindExistingLesionClass(caseID, "Class_01");
- CPPUNIT_ASSERT_MESSAGE("Lesion class type should be 'Class_01'", foundLesionClass.classType == "Class_01");
-
- allLesions = mitk::RelationStorage::GetAllLesionsOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One lesions should be stored", allLesions.size() == 1);
-
- auto allLesionClasses = mitk::SemanticRelationsInference::GetAllLesionClassesOfCase(caseID);
- CPPUNIT_ASSERT_MESSAGE("One lesion class should be stored", allLesionClasses.size() == 1);
- }
-};
-
-MITK_TEST_SUITE_REGISTRATION(mitkSemanticRelations)
diff --git a/Modules/SemanticRelations/Test/mitkSemanticRelationsTestHelper.cpp b/Modules/SemanticRelations/Test/mitkSemanticRelationsTestHelper.cpp
deleted file mode 100644
index e81fac00df..0000000000
--- a/Modules/SemanticRelations/Test/mitkSemanticRelationsTestHelper.cpp
+++ /dev/null
@@ -1,331 +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 "mitkSemanticRelationsTestHelper.h"
-
-// mitk semantic relations
-#include "mitkDICOMHelper.h"
-#include "mitkRelationStorage.h"
-#include "mitkUIDGeneratorBoost.h"
-
-// mitk core
-#include <mitkImage.h>
-#include <mitkIPersistenceService.h>
-#include <mitkTemporoSpatialStringProperty.h>
-
-// mitk multilabel
-#include <mitkLabelSetImage.h>
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientOneCTImage()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient1"));
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20190101"));
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("CT"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientOneMRImage()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient1"));
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20190101"));
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("MR"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientOneOtherCTImage()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient1"));
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20190131"));
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("CT"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientTwoPETImage()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient2"));
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20180101"));
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("PT"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientTwoSegmentation()
-{
- // create new empty segmentation
- LabelSetImage::Pointer segmentation = LabelSetImage::New();
-
- // set properties of segmentation (base data)
- segmentation->SetProperty(GetCaseIDDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New("Patient2"));
- segmentation->SetProperty(GetNodeIDDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New(UIDGeneratorBoost::GenerateUID()));
- segmentation->SetProperty(GetDateDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New("20180101"));
- // segmentation modality is 'SEG'
-
- // create new data node and add segmentation as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(segmentation);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientThreeCTImage()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient3"));
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20190201"));
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("CT"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientThreeCTSegmentation()
-{
- // create new empty segmentation
- LabelSetImage::Pointer segmentation = LabelSetImage::New();
-
- // set properties of segmentation (base data)
- segmentation->SetProperty(GetCaseIDDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New("Patient3"));
- segmentation->SetProperty(GetNodeIDDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New(UIDGeneratorBoost::GenerateUID()));
- segmentation->SetProperty(GetDateDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New("20190201"));
- // segmentation modality is 'SEG'
-
- // create new data node and add segmentation as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(segmentation);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientThreeMRImage()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient3"));
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20190215"));
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("MR"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetPatientThreeMRSegmentation()
-{
- // create new empty segmentation
- LabelSetImage::Pointer segmentation = LabelSetImage::New();
-
- // set properties of segmentation (base data)
- segmentation->SetProperty(GetCaseIDDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New("Patient3"));
- segmentation->SetProperty(GetNodeIDDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New(UIDGeneratorBoost::GenerateUID()));
- segmentation->SetProperty(GetDateDICOMProperty().c_str(),
- TemporoSpatialStringProperty::New("20190215"));
- // segmentation modality is 'SEG'
-
- // create new data node and add segmentation as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(segmentation);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetInvalidDate()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient4"));
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
-
- // no DICOM information for Date
-
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("CT"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetInvalidModality()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient5"));
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20180101"));
-
- // no DICOM information for Modality
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetInvalidID()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- image->SetProperty(GetCaseIDDICOMProperty().c_str(),
- StringProperty::New("Patient6"));
-
- // no DICOM information for NodeID
-
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20180101"));
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("CT"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsTestHelper::GetInvalidCaseID()
-{
- // create new empty image
- Image::Pointer image = Image::New();
-
- // set properties of image (base data)
- // no DICOM information for CaseID
-
- image->SetProperty(GetNodeIDDICOMProperty().c_str(),
- StringProperty::New(UIDGeneratorBoost::GenerateUID()));
- image->SetProperty(GetDateDICOMProperty().c_str(),
- StringProperty::New("20180101"));
- image->SetProperty(GetModalityDICOMProperty().c_str(),
- StringProperty::New("CT"));
-
- // create new data node and add image as base data
- DataNode::Pointer dataNode = DataNode::New();
- dataNode->SetData(image);
-
- return dataNode;
-}
-
-void mitk::SemanticRelationsTestHelper::ClearRelationStorage()
-{
- // access the storage
- PERSISTENCE_GET_SERVICE_MACRO
- if (nullptr == persistenceService)
- {
- MITK_DEBUG << "Persistence service could not be loaded";
- return;
- }
-
- auto allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- for (auto& caseID : allCaseIDs)
- {
- persistenceService->RemovePropertyList(caseID);
- }
-
- std::string listIdentifier("caseIDs");
- persistenceService->RemovePropertyList(listIdentifier);
-}
diff --git a/Modules/SemanticRelations/Test/mitkSemanticRelationsTestHelper.h b/Modules/SemanticRelations/Test/mitkSemanticRelationsTestHelper.h
deleted file mode 100644
index 64dd853f0b..0000000000
--- a/Modules/SemanticRelations/Test/mitkSemanticRelationsTestHelper.h
+++ /dev/null
@@ -1,71 +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 mitkSemanticRelationsTestHelper_h
-#define mitkSemanticRelationsTestHelper_h
-
-#include <mitkDataNode.h>
-
-namespace mitk
-{
- namespace SemanticRelationsTestHelper
- {
- //////////////////////////////////////////////////////////////////////////
- // VALID DATA NODES
- //////////////////////////////////////////////////////////////////////////
- DataNode::Pointer GetPatientOneCTImage();
-
- DataNode::Pointer GetPatientOneMRImage();
-
- DataNode::Pointer GetPatientOneOtherCTImage();
-
- DataNode::Pointer GetPatientTwoPETImage();
-
- DataNode::Pointer GetPatientTwoSegmentation();
-
- DataNode::Pointer GetPatientThreeCTImage();
-
- DataNode::Pointer GetPatientThreeCTSegmentation();
-
- DataNode::Pointer GetPatientThreeMRImage();
-
- DataNode::Pointer GetPatientThreeMRSegmentation();
-
- //////////////////////////////////////////////////////////////////////////
- // INVALID DATA NODES
- //////////////////////////////////////////////////////////////////////////
- /**
- * @brief Date is 0x0008, 0x0022 (AcquisitionDate)
- */
- DataNode::Pointer GetInvalidDate();
- /**
- * @brief Modality is 0x0008, 0x0060(Modality)
- */
- DataNode::Pointer GetInvalidModality();
- /**
- * @brief ID is 0x0020, 0x000e (SeriesInstanceUID)
- */
- DataNode::Pointer GetInvalidID();
- /**
- * @brief CaseID is 0x0010, 0x0010 (PatientName)
- */
- DataNode::Pointer GetInvalidCaseID();
-
- //////////////////////////////////////////////////////////////////////////
- // AUXILIARY FUNCTIONS
- //////////////////////////////////////////////////////////////////////////
- void ClearRelationStorage();
-
- } // end SemanticRelationsTestHelper
-} // end mitk
-
-#endif
diff --git a/Modules/SemanticRelations/files.cmake b/Modules/SemanticRelations/files.cmake
deleted file mode 100644
index b5e1bddd7a..0000000000
--- a/Modules/SemanticRelations/files.cmake
+++ /dev/null
@@ -1,14 +0,0 @@
-file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*")
-
-set(CPP_FILES
- mitkControlPointManager.cpp
- mitkDICOMHelper.cpp
- mitkLesionData.cpp
- mitkLesionManager.cpp
- mitkNodePredicates.cpp
- mitkRelationStorage.cpp
- mitkSemanticRelationsDataStorageAccess.cpp
- mitkSemanticRelationsInference.cpp
- mitkSemanticRelationsIntegration.cpp
- mitkUIDGeneratorBoost.cpp
-)
diff --git a/Modules/SemanticRelations/include/mitkControlPointManager.h b/Modules/SemanticRelations/include/mitkControlPointManager.h
deleted file mode 100644
index bf3def64bc..0000000000
--- a/Modules/SemanticRelations/include/mitkControlPointManager.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkControlPointManager_h
-#define mitkControlPointManager_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// semantic relations module
-#include "mitkSemanticTypes.h"
-
-// mitk core
-#include <mitkDataNode.h>
-
-namespace mitk
-{
- /**
- * @brief Provides helper functions that are needed to work with control points.
- *
- * These functions help to generate new control points, check for overlapping / containing control points or provide functionality
- * to find a fitting control point or even extend an already existing control point.
- */
- /**
- * @brief Generates a control point from a given data node.
- * The date is extracted from the data node by using the 'DICOMHelper::GetDICOMDateFromDataNode'-function.
- *
- * @param datanode A data node pointer, whose date should be included in the newly generated control point.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPoint GenerateControlPoint(const mitk::DataNode* datanode);
- /**
- * @brief Find and return a whole control point including its date given a specific control point UID.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPointUID The control point UID as string.
- *
- * @return The control point with its UID and the date.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPoint GetControlPointByUID(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& controlPointUID);
- /**
- * @brief Returns an already existing control point from the given vector of control points. This existing control point has the
- * the same date (year, month, day) as the given single control point.
- * If no existing control point can be found an empty control point is returned.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint The control point to check for existence.
- *
- * @return The existing control point.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPoint FindExistingControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Returns an already existing close control point from the given vector of control points. This closest control point has a
- * date that is within a certain distance-in-days to the given control point.
- * If no closest control point can be found within the distance threshold an empty control point is returned.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint The control point to check for distance.
- *
- * @return The closest control point.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPoint FindClosestControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Returns the examination period to which the given control point belongs.
- * Each examination point holds a vector of control point UIDs so that the UID of the given control point can be compared against the UIDs of the vector.
- * An empty examination period is returned if,
- * - the given vector of examination periods is empty
- * - the examination periods do not contain any control point UIDs
- * - the UID of the given control point is not contained in any examination period
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint The control point of which the examination period should be found.
- *
- * @return The examination period that contains the given control point.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ExaminationPeriod FindContainingExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Return the examination period to which the given data node belongs.
- * The control point is used to find an already existing or the closest control point in the semantic relations storage.
- * If such a control point is found, the 'FindClosestControlPoint'-function with this control point as an argument is used
- * to actually find the corresponding examination period.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint The control point of which the examination period should be found.
- *
- * @return The examination period that fits the given data node.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ExaminationPeriod FindFittingExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Return the examination period to which the given data node belongs.
- * The DICOM date of the data node is used to find an already existing or the closest control point in the semantic relations storage.
- * If such a control point is found, the 'FindFittingExaminationPeriod'-function with this control point as an argument is used
- * to actually find the corresponding examination period.
- *
- * @param dataNode A data node pointer, whose date should be included in the newly generated control point.
- *
- * @return The examination period that contains the given data node.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ExaminationPeriod FindFittingExaminationPeriod(const DataNode* dataNode);
- /**
- * @brief Sort the given vector of examination periods.
- * Each examination period has a vector of control point UIDs (stored in chronological order).
- * The examination periods can be sorted by comparing the first control points of the examination periods.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param allExaminationPeriods The examination periods to sort.
- */
- MITKSEMANTICRELATIONS_EXPORT void SortAllExaminationPeriods(const SemanticTypes::CaseID& caseID, SemanticTypes::ExaminationPeriodVector& allExaminationPeriods);
-
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkDICOMHelper.h b/Modules/SemanticRelations/include/mitkDICOMHelper.h
deleted file mode 100644
index 656ba88ca5..0000000000
--- a/Modules/SemanticRelations/include/mitkDICOMHelper.h
+++ /dev/null
@@ -1,126 +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 mitkDICOMHelper_h
-#define mitkDICOMHelper_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// semantic relations module
-#include "mitkSemanticTypes.h"
-
-// mitk core
-#include <mitkDataNode.h>
-#include <mitkDICOMTagPath.h>
-
-// c++
-#include <string>
-
-/*
-* @brief Provides helper functions to convert DICOM Tag information.
-*
-* In order to identify the patient of an image or segmentation or to set the control point of DICOM data,
-* these functions are used to retrieve the DICOM tags from the given data nodes and convert them into semantic types
-* that can be used by the SemanticRelations class.
-*/
-namespace mitk
-{
- /**
- * @brief Creates a property name for a DICOM tag.
- * The tag is "0x0010, 0x0010" (PatientName)
- */
- MITKSEMANTICRELATIONS_EXPORT std::string GetCaseIDDICOMProperty();
- /**
- * @brief Creates a property name for a DICOM tag.
- * The tag is "0x0020, 0x000e" (SeriesInstanceUID)
- */
- MITKSEMANTICRELATIONS_EXPORT std::string GetNodeIDDICOMProperty();
- /**
- * @brief Creates a property name for a DICOM tag.
- * The tag is "0x0008, 0x0022" (AcquisitionDate)
- */
- MITKSEMANTICRELATIONS_EXPORT std::string GetDateDICOMProperty();
- /**
- * @brief Creates a property name for a DICOM tag.
- * The tag is "0x0008, 0x0060" (Modality)
- */
- MITKSEMANTICRELATIONS_EXPORT std::string GetModalityDICOMProperty();
- /*
- * @brief Extracts a specific DICOM tag from the node's base data
- * and returns the tag as a string. This tag string is used as an identifier for the patient (case).
- *
- * @pre The given data node or the node's base data has to be valid (!nullptr).
- * @pre The node's base data has to have the specific DICOM Tag property set.
- * @throw mitk::Exception if the given data node, the node's base data or the extracted DICOM tag are invalid (==nullptr).
- *
- * @par dataNode The data node, of which the DICOM tag should be extracted.
- *
- * @return The extracted DICOM tag as string.
- * An empty string, if the DICOM tag can not be extracted (i.e. the data node or
- * the underlying base data is invalid or the DICOM tag does not exist for the given data node).
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::CaseID GetCaseIDFromDataNode(const mitk::DataNode* dataNode);
- /*
- * @brief Extracts a specific DICOM tag (currently "0x0020, 0x000e": SeriesInstanceUID) from the node's base data
- * and returns the tag as a string. This tag string is used as an identifier for the image instance.
- *
- * @pre The given data node or the node's base data has to be valid (!nullptr).
- * @pre The node's base data has to have the "0x0020, 0x000e" DICOM Tag property set.
- * @throw mitk::Exception if the given data node, the node's base data or the extracted DICOM tag are invalid (==nullptr).
- *
- * @par dataNode The data node, of which the DICOM tag should be extracted.
- *
- * @return The extracted DICOM tag as string.
- * An empty string, if the DICOM tag can not be extracted (i.e. the data node or
- * the underlying base data is invalid or the DICOM tag does not exist for the given data node).
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ID GetIDFromDataNode(const mitk::DataNode* dataNode);
- /*
- * @brief Extracts a specific DICOM tag (currently "0x0008, 0x0022": AcquisitionDate) from the node's base data
- * and returns the tag as a control point.
- *
- * @pre The given data node or the node's base data has to be valid (!nullptr).
- * @pre The node's base data has to have the "0x0008, 0x0022" DICOM Tag property set.
- * @throw mitk::Exception if the given data node, the node's base data or the extracted DICOM tag are invalid (==nullptr).
- *
- * @par dataNode The data node, of which the DICOM tag should be extracted.
- *
- * @return The extracted DICOM tag as control point.
- * An empty control point, if the DICOM tag can not be extracted (i.e. the data node or
- * the underlying base data is invalid or the DICOM tag does not exist for the given data node).
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPoint GetDICOMDateFromDataNode(const mitk::DataNode* dataNode);
- /**
- * @brief Extracts a specific DICOM tag from the node's base data and returns the tag as a information type (a string).
- *
- * @pre The given data node or the node's base data has to be valid (!nullptr).
- * @pre The node's base data has to have the "0x0008, 0x0060" DICOM Tag property set.
- * @throw mitk::Exception if the given data node, the node's base data or the extracted DICOM tag are invalid (==nullptr).
- *
- * @par dataNode The data node, of which the DICOM tag should be extracted.
- *
- * @return The extracted DICOM tag as information type (a string).
- * An empty information type, if the DICOM tag can not be extracted (i.e. the data node or
- * the underlying base data is invalid or the DICOM tag does not exist for the given data node).
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::InformationType GetDICOMModalityFromDataNode(const mitk::DataNode* dataNode);
- /*
- * @brief Removes leading and trailing whitespace from the given string.
- *
- * @par identifier The value of a DICOM tag.
- *
- * @return The trimmed DICOM tag
- */
- MITKSEMANTICRELATIONS_EXPORT std::string TrimDICOM(const std::string& identifier);
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkISemanticRelationsObservable.h b/Modules/SemanticRelations/include/mitkISemanticRelationsObservable.h
deleted file mode 100644
index e25acef445..0000000000
--- a/Modules/SemanticRelations/include/mitkISemanticRelationsObservable.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkISemanticRelationsObservable_h
-#define mitkISemanticRelationsObservable_h
-
-#include "mitkISemanticRelationsObserver.h"
-
-namespace mitk
-{
- /*
- * @brief This interface declares three functions each observable subject has to implement
- * in order to be observed in the 'Observer pattern' sense.
- * The concrete observable class has to store its observer.
- */
- class ISemanticRelationsObservable
- {
- public:
- /*
- * @brief Adds the given concrete observer to a container that holds all currently registered observer.
- *
- * @param observer The concrete observer to register.
- */
- virtual void AddObserver(ISemanticRelationsObserver* observer) = 0;
- /*
- * @brief Removes the given concrete observer from the container that holds all currently registered observer.
- *
- * @param observer The concrete observer to unregister.
- */
- virtual void RemoveObserver(ISemanticRelationsObserver* observer) = 0;
- /*
- * @brief Updates all concrete observer in the container that holds all currently registered observer.
- * The caseID can be used to only update the observer, if the caseID fulfills a certain condition.
- *
- * @param caseID A caseID that identifies the currently active patient / case.
- */
- virtual void NotifyObserver(const SemanticTypes::CaseID& caseID) const = 0;
-
- }; // class ISemanticRelationsObservable
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkISemanticRelationsObserver.h b/Modules/SemanticRelations/include/mitkISemanticRelationsObserver.h
deleted file mode 100644
index b45f890bfe..0000000000
--- a/Modules/SemanticRelations/include/mitkISemanticRelationsObserver.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 mitkISemanticRelationsObserver_h
-#define mitkISemanticRelationsObserver_h
-
-#include "mitkSemanticTypes.h"
-
-namespace mitk
-{
- /*
- * @brief This interface declares a functions each observer has to implement
- * in order to be notified in the 'Observer pattern' sense.
- */
- class ISemanticRelationsObserver
- {
- public:
- /*
- * @brief Updates the concrete observer.
- * The caseID can be used to get access to a certain patient (case),
- * whose data should be used for updating.
- *
- * @param caseID The current case ID to identify the currently active patient / case.
- */
- virtual void Update(const mitk::SemanticTypes::CaseID& caseID) = 0;
-
- }; // class ISemanticRelationsObserver
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkLesionData.h b/Modules/SemanticRelations/include/mitkLesionData.h
deleted file mode 100644
index b9c00cda7d..0000000000
--- a/Modules/SemanticRelations/include/mitkLesionData.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkLesionData_h
-#define mitkLesionData_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// mitk semantic relations module
-#include "mitkSemanticTypes.h"
-
-// c++
-#include <vector>
-
-namespace mitk
-{
- /**
- * @brief This class holds the data of each lesion in the lesion tree view.
- * The data is the lesion itself with its UID, name and lesion class
- * as well as two vectors for
- * - lesion presence: bool value for each control-point
- * inside the semantic relations storage
- * - lesion volume: double value for each control-point - information type pair
- * inside the semantic relations storage
- *
- */
- class MITKSEMANTICRELATIONS_EXPORT LesionData
- {
- public:
- /**
- * @brief sets the data members to their initial values
- */
- LesionData(const SemanticTypes::Lesion& lesion = SemanticTypes::Lesion());
-
- SemanticTypes::Lesion GetLesion() const { return m_Lesion; };
- SemanticTypes::ID GetLesionUID() const { return m_Lesion.UID; }
- std::string GetLesionName() const { return m_Lesion.name; }
-
- const std::vector<bool>& GetLesionPresence() const { return m_LesionPresence; };
- const std::vector<double>& GetLesionVolume() const { return m_LesionVolume; };
-
- void SetLesion(const SemanticTypes::Lesion& lesion);
- void SetLesionPresence(const std::vector<bool>& lesionPresence);
- void SetLesionVolume(const std::vector<double>& lesionVolume);
-
- private:
-
- SemanticTypes::Lesion m_Lesion;
- std::vector<bool> m_LesionPresence;
- std::vector<double> m_LesionVolume;
-
- };
-} // end namespace
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkLesionManager.h b/Modules/SemanticRelations/include/mitkLesionManager.h
deleted file mode 100644
index 24a92dc1e0..0000000000
--- a/Modules/SemanticRelations/include/mitkLesionManager.h
+++ /dev/null
@@ -1,71 +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 mitkLesionManager_h
-#define mitkLesionManager_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// semantic relations module
-#include "mitkLesionData.h"
-
-/*
-* @brief Provides helper functions that are needed to work with lesions.
-*
-* These functions help to generate new lesions, check for existing lesions or provide functionality
-* to generate new and find existing lesion class types.
-*/
-namespace mitk
-{
- typedef std::vector<SemanticTypes::LesionClass> LesionClassVector;
-
- /**
- * @brief Generate a new lesion and lesion class with UIDs and the given string as lesion class type.
- *
- * @param lesionClassType The lesion class type as string. Default parameter is "".
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::Lesion GenerateNewLesion(const std::string& lesionClassType = "");
- /**
- * @brief Generate a new lesion class with UID and the given string as lesion class type.
- *
- * @param lesionClassType The lesion class type as string. Default parameter is "".
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::LesionClass GenerateNewLesionClass(const std::string& lesionClassType = "");
- /**
- * @brief Find and return a whole lesion including its lesion class given a specific lesion UID.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesionUID The lesion UID as string.
- *
- * @return The lesion with its UID and the lesion class.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::Lesion GetLesionByUID(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& lesionUID);
- /**
- * @brief Find and return the whole lesion class including its UID given a specific lesion class type.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesionClassType The lesion class type as string.
- *
- * @return The lesion class with its UID and the class type.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::LesionClass FindExistingLesionClass(const SemanticTypes::CaseID& caseID, const std::string& lesionClassType);
- /**
- * @brief Compute and store lesion presence for all available control points and information types.
- *
- * @param lesionData The lesion data that holds the lesion and will hold the additional lesion data.
- * @param caseID The current case ID.
- */
- MITKSEMANTICRELATIONS_EXPORT void ComputeLesionPresence(LesionData& lesionData, const SemanticTypes::CaseID& caseID);
-
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkNodePredicates.h b/Modules/SemanticRelations/include/mitkNodePredicates.h
deleted file mode 100644
index f9ef91c869..0000000000
--- a/Modules/SemanticRelations/include/mitkNodePredicates.h
+++ /dev/null
@@ -1,43 +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 mitkNodePredicates_h
-#define mitkNodePredicates_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// mitk core
-#include <mitkNodePredicateAnd.h>
-
-namespace mitk
-{
- namespace NodePredicates
- {
- /*
- * @brief Helper function to get a node predicate that can be used to filter images.
- *
- * The images are of type 'mitk::Image' but must not be 'helper objects' or 'segmentation nodes'.
- * For the definition of 'segmentation nodes' see 'GetSegmentationPredicate'.
- */
- MITKSEMANTICRELATIONS_EXPORT NodePredicateAnd::Pointer GetImagePredicate();
- /*
- * @brief Helper function to get a node predicate that can be used to filter segmentations.
- *
- * The segmentations are of type 'mitk::LabelSetImage' or nodes that have their 'binary' property set to true.
- * Segmentations must not be 'helper objects'.
- */
- MITKSEMANTICRELATIONS_EXPORT NodePredicateAnd::Pointer GetSegmentationPredicate();
-
- } // namespace NodePredicates
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkRelationStorage.h b/Modules/SemanticRelations/include/mitkRelationStorage.h
deleted file mode 100644
index f3a580e6bf..0000000000
--- a/Modules/SemanticRelations/include/mitkRelationStorage.h
+++ /dev/null
@@ -1,79 +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 mitkRelationStorage_h
-#define mitkRelationStorage_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// semantic relations module
-#include "mitkSemanticTypes.h"
-
-namespace mitk
-{
- namespace RelationStorage
- {
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::LesionVector GetAllLesionsOfCase(const SemanticTypes::CaseID& caseID);
- SemanticTypes::Lesion GetLesionOfSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID);
-
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPointVector GetAllControlPointsOfCase(const SemanticTypes::CaseID& caseID);
- SemanticTypes::ControlPoint GetControlPointOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID);
-
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ExaminationPeriodVector GetAllExaminationPeriodsOfCase(const SemanticTypes::CaseID& caseID);
-
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::InformationTypeVector GetAllInformationTypesOfCase(const SemanticTypes::CaseID& caseID);
- SemanticTypes::InformationType GetInformationTypeOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID);
-
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::IDVector GetAllImageIDsOfCase(const SemanticTypes::CaseID& caseID);
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::IDVector GetAllImageIDsOfControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::IDVector GetAllImageIDsOfInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType);
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::IDVector GetAllSegmentationIDsOfCase(const SemanticTypes::CaseID& caseID);
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::IDVector GetAllSegmentationIDsOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID);
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::IDVector GetAllSegmentationIDsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
-
- SemanticTypes::ID GetImageIDOfSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID);
-
- MITKSEMANTICRELATIONS_EXPORT std::vector<SemanticTypes::CaseID> GetAllCaseIDs();
- MITKSEMANTICRELATIONS_EXPORT bool InstanceExists(const SemanticTypes::CaseID& caseID);
-
- void AddCase(const SemanticTypes::CaseID& caseID);
- void AddImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID);
- void RemoveImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID);
- void AddSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID, const SemanticTypes::ID& parentID);
- void RemoveSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID);
-
- void AddLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- void OverwriteLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- void LinkSegmentationToLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID, const SemanticTypes::Lesion& lesion);
- void UnlinkSegmentationFromLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID);
- void RemoveLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- void RemoveLesionClass(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& lesionClassID);
-
- void AddControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- void LinkImageToControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID, const SemanticTypes::ControlPoint& controlPoint);
- void UnlinkImageFromControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID);
- void RemoveControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
-
- void AddExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- MITKSEMANTICRELATIONS_EXPORT void RenameExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- void AddControlPointToExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- void RemoveControlPointFromExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- void RemoveExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod);
-
- void AddInformationTypeToImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID, const SemanticTypes::InformationType& informationType);
- void RemoveInformationTypeFromImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID);
- void RemoveInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType);
-
- } // namespace RelationStorage
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkSemanticRelationException.h b/Modules/SemanticRelations/include/mitkSemanticRelationException.h
deleted file mode 100644
index b091f90d27..0000000000
--- a/Modules/SemanticRelations/include/mitkSemanticRelationException.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 mitkSemanticRelationException_h
-#define mitkSemanticRelationException_h
-
-// mitk core
-#include <mitkExceptionMacro.h>
-
-namespace mitk
-{
- class SemanticRelationException : public Exception
- {
-
- public:
-
- mitkExceptionClassMacro(SemanticRelationException, Exception);
-
- };
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkSemanticRelationsDataStorageAccess.h b/Modules/SemanticRelations/include/mitkSemanticRelationsDataStorageAccess.h
deleted file mode 100644
index 6060ebec5d..0000000000
--- a/Modules/SemanticRelations/include/mitkSemanticRelationsDataStorageAccess.h
+++ /dev/null
@@ -1,184 +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 mitkSemanticRelationsDataStorageAccess_h
-#define mitkSemanticRelationsDataStorageAccess_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// semantic relations module
-#include "mitkSemanticTypes.h"
-
-// mitk core
-#include <mitkDataStorage.h>
-#include <mitkWeakPointer.h>
-
-namespace mitk
-{
- /**
- * @brief The API provides functions to query and manipulate image relations and instances,
- * that are helpful during follow-up examination, like control-points (time period),
- * types of the images or lesions that may be visible on multiple images.
- *
- * The class is able to generate IDs from given data nodes using DICOM information.
- * These IDs are used to identify the corresponding instances of a specific case.
- * The case can also be directly identified by the given case ID.
- *
- * In order for most functions to work the case ID has to be used as a parameter.
- * If not, these functions do nothing.
- */
- class MITKSEMANTICRELATIONS_EXPORT SemanticRelationsDataStorageAccess
- {
- public:
-
- using DataNodeVector = std::vector<DataNode::Pointer>;
-
- SemanticRelationsDataStorageAccess(DataStorage* dataStorage);
-
- /************************************************************************/
- /* functions to get instances / attributes */
- /************************************************************************/
- /**
- * @brief Return a vector of all segmentations that are currently available for the given case.
- * The segmentations may be connected / not connected to a lesion of the case.
- * If no segmentations are stored for the current case, an empty vector is returned.
- *
- * @pre The data storage member has to be valid (!nullptr).
- * @throw SemanticRelationException, if the data storage member is invalid (==nullptr).
- *
- * @param caseID The current case identifier is defined by the given string.
- *
- * @return A vector of data nodes representing segmentations.
- */
- DataNodeVector GetAllSegmentationsOfCase(const SemanticTypes::CaseID& caseID) const;
- /**
- * @brief Return a vector of all segmentations that define the given lesion. These segmentations don't have to be linked to the same image.
- * If the lesion is not referred to by any segmentation, an empty vector is returned.
- *
- * @pre The data storage member has to be valid (!nullptr).
- * @throw SemanticRelationException, if the data storage member is invalid (==nullptr).
- * @pre The UID of the lesion has to exist for a lesion instance.
- * @throw SemanticRelationException, if UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- *
- * @return A vector of data nodes representing segmentations that define the given lesion.
- */
- DataNodeVector GetAllSegmentationsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) const;
- /**
- * @brief Return a vector of all images that are currently available for the given case.
- *
- * @pre The data storage member has to be valid (!nullptr).
- * @throw SemanticRelationException, if the data storage member is invalid (==nullptr).
- *
- * @param caseID The current case identifier is defined by the given string.
- *
- * @return A vector of data nodes representing images.
- */
- DataNodeVector GetAllImagesOfCase(const SemanticTypes::CaseID& caseID) const;
- /**
- * @brief Return a vector of all images that are specified by the given vector of image IDs.
- *
- * @pre The data storage member has to be valid (!nullptr).
- * @throw SemanticRelationException, if the data storage member is invalid (==nullptr).
- *
- * @param imageIDs A vector of image IDs that represent the images in the data storage.
- *
- * @return A vector of data nodes representing images.
- */
- DataNodeVector GetAllImagesByID(const SemanticTypes::IDVector& imageIDs) const;
- /**
- * @brief Return a vector of all images that are connected to those segmentations that are linked to the given lesion.
- * If the lesion is not referred to by any segmentation, an empty vector is returned.
- *
- * @pre The UID of the lesion has to exist for a lesion instance.
- * @throw SemanticRelationException, if UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- *
- * @return A vector of data nodes representing images on which the lesions are visible.
- */
- DataNodeVector GetAllImagesOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) const;
- /**
- * @brief Return a vector of all image nodes that are defined with the given control point and the given information type.
- *
- * @pre The UID of the control point has to exist for a control point instance.
- * The information type has to exist for the given case (and is therefore used by at least one data node).
- * @throw SemanticRelationException, if the UID of the control point does not exist for a control point instance (this can be checked via 'InstanceExists') or
- * if the information type is not used by any data node (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint A control point with a UID that identifies the corresponding control point instance.
- * @param informationType An information type that identifies the corresponding information type instance.
- *
- * @return A vector of image nodes that are defined with the given control point and the given information type.
- */
- DataNodeVector GetAllSpecificImages(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType) const;
- /**
- * @brief Return a vector of all image nodes that are defined with the given information type and the given examination period.
- * The function uses the 'SemanticRelationsInference::GetAllImageIDsOfExaminationPeriod'-function to retrieve the imageIDs of the examination period and
- * then compares the information type of all these images against the given information type.
- *
- * @param caseID
- * @param informationType An information type that identifies the corresponding information type instance.
- * @param examinationPeriod An examination period that identifies the corresponding examination period instance.
- *
- * @return A vector of image nodes that are defined with the given information type with the given control point.
- */
- DataNodeVector GetAllSpecificImages(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType, const SemanticTypes::ExaminationPeriod& examinationPeriod) const;
- /**
- * @brief Return a vector of all segmentation nodes that are defined with the given control point and the given information type.
- * The function uses the 'GetAllSpecificImages'-function to retrieve the specific images and then searches for the derived nodes (segmentation child nodes).
- *
- * @pre The UID of the control point has to exist for a control point instance.
- * The information type has to exist for the given case (and is therefore used by at least one data node).
- * @throw SemanticRelationException, if the UID of the control point does not exist for a control point instance (this can be checked via 'InstanceExists') or
- * if the information type is not used by any data node (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint A control point with a UID that identifies the corresponding control point instance.
- * @param informationType An information type that identifies the corresponding information type instance.
- *
- * @return A vector of segmentation nodes that are defined with the given control point and the given information type.
- */
- DataNodeVector GetAllSpecificSegmentations(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType) const;
- /**
- * @brief Return the single segmentation node that is defined with the given information type, the given control point and is representing the given lesion.
- * The function uses the 'GetAllSpecificSegmentations'-function to retrieve the specific segmentations and then checks for the represented lesion.
- *
- * @pre The UID of the control point has to exist for a control point instance.
- * The information type has to exist for the given case (and is therefore used by at least one data node).
- * The lesion has to exist for the given case.
- * @throw SemanticRelationException, if the UID of the control point does not exist for a control point instance (this can be checked via 'InstanceExists') or
- * if the information type is not used by any data node (this can be checked via 'InstanceExists') or
- * if the lesion does not exist for the given case (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint A control point with a UID that identifies the corresponding control point instance.
- * @param informationType An information type that identifies the corresponding information type instance.
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- *
- * @return A single segmentation node that is defined with the given information type, the given control point and is representing the given lesion.
- */
- DataNode::Pointer GetSpecificSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint,
- const SemanticTypes::InformationType& informationType, const SemanticTypes::Lesion& lesion) const;
-
- private:
-
- WeakPointer<DataStorage> m_DataStorage;
-
- };
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkSemanticRelationsInference.h b/Modules/SemanticRelations/include/mitkSemanticRelationsInference.h
deleted file mode 100644
index 67bcf40b3d..0000000000
--- a/Modules/SemanticRelations/include/mitkSemanticRelationsInference.h
+++ /dev/null
@@ -1,347 +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 mitkSemanticRelationsInference_h
-#define mitkSemanticRelationsInference_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// semantic relations module
-#include "mitkSemanticTypes.h"
-
-// mitk core
-#include <mitkDataNode.h>
-
-namespace mitk
-{
- /**
- * @brief The API provides functions to query image relations and instances
- * that are helpful during follow-up examination, like control-points (time period),
- * types of the images or lesions that may be visible on multiple images.
- *
- * The class is able to generate IDs from given data nodes using DICOM information.
- * These IDs are used to identify the corresponding instances of a specific case.
- * The case can also be directly identified by the given case ID.
- *
- * In order for most functions to work the case ID has to be used as a parameter.
- * If not, these functions do nothing.
- */
- namespace SemanticRelationsInference
- {
-
- /************************************************************************/
- /* functions to get instances / attributes */
- /************************************************************************/
- /**
- * @brief Return a vector of lesion classes that are currently available for the given case.
- *
- * @param caseID The current case identifier is defined by the given string.
- *
- * @return A vector of lesion classes.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::LesionClassVector GetAllLesionClassesOfCase(const SemanticTypes::CaseID& caseID);
- /**
- * @brief Return the lesion that is defined by the given segmentation.
- *
- * @pre The given segmentation data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given segmentation is invalid (==nullptr).
- * @pre The segmentation data node has to represent a lesion. If not, the retrieved lesion will be empty, which leads to an exception.
- * @throw SemanticRelationException, if the segmentation does not represent an existing lesion (this can be checked via 'IsRepresentingALesion').
- *
- * @param segmentationNode The segmentation identifier is extracted from the given data node.
- *
- * @return The represented lesion.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::Lesion GetLesionOfSegmentation(const DataNode* segmentationNode);
- /**
- * @brief Returns a vector of all lesions that are currently available for the current case and are connected to the given image (via a segmentation).
- * If no lesions are stored for the current case, an empty vector is returned. If no segmentations are
- * connected with the image node, no lesions for the specific image will be found and an empty vector is returned.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- *
- * @param imageNode The current case identifier is extracted from the given data node, which contains DICOM information about the case.
- *
- * @return A vector of lesions.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::LesionVector GetAllLesionsOfImage(const DataNode* imageNode);
- /**
- * @brief Returns a vector of all lesions that are valid for the given case, given a specific control point.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint A specific control point which has to be available at a returned (found) lesion:
- * Only those lesions are returned for which the image of the associated segmentation is linked to the given control point.
- * If the control point instance does not exist, an empty vector is returned.
- *
- * @return A vector of lesions.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::LesionVector GetAllLesionsOfControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Returns a vector of all lesions that are valid for the given case, given a specific information type.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param informationType A specific information type which has to be available at a returned (found) lesion:
- * Only those lesions are returned for which the image of the associated segmentation is of the given information type.
- * If the information type instance does not exist, an empty vector is returned.
- *
- * @return A vector of lesions.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::LesionVector GetAllLesionsOfInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType);
- /**
- * @brief Returns a vector of all lesions that are valid for the given case, given a specific control point and a specific information type.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint A specific control point which has to be available at a returned (found) lesion:
- * Only those lesions are returned for which the image of the associated segmentation is linked to the given control point.
- * If the control point instance does not exist, an empty vector is returned.
- * @param informationType A specific information type which has to be available at a returned (found) lesion:
- * Only those lesions are returned for which the image of the associated segmentation is of the given information type.
- * If the information type instance does not exist, an empty vector is returned.
- *
- * @return A vector of lesions.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::LesionVector GetAllSpecificLesions(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType);
- /**
- * @brief Check if the given segmentation refers to an existing lesion instance.
- * This function can be used before calling 'GetRepresentedLesion' in order to avoid a possible exception.
- *
- * @param segmentationNode The segmentation identifier is extracted from the given data node.
- *
- * @return True, if the segmentation refers to an existing lesion; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool IsRepresentingALesion(const DataNode* segmentationNode);
- /**
- * @brief Check if the segmentation identified by the given segmentation ID refers to an existing lesion instance.
- * This function can be used before calling 'GetRepresentedLesion' in order to avoid a possible exception.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param segmentationID The segmentation node identifier is defined by the given string.
- *
- * @return True, if the segmentation refers to an existing lesion; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool IsRepresentingALesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID);
- /**
- * @brief Check if the given lesion is present on the given data node.
- * The function receives the case- and the node-ID from the DICOM tags of the node itself.
- * It uses node predicates to decide if the node is an image or a segmentation node.
- *
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- * @param dataNode A data node to check.
- *
- * @return True, if the lesion is present on the data node; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool IsLesionPresent(const SemanticTypes::Lesion& lesion, const DataNode* dataNode);
- /**
- * @brief Check if the given lesion is related to the image identified by the given image ID.
- * Each lesion is represented by a segmentation which is connected to its parent image.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- * @param imageID The image node identifier is defined by the given string.
- *
- * @return True, if the lesion is related to image identified by the given image ID; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool IsLesionPresentOnImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::ID& imageID);
- /**
- * @brief Check if the given lesion is present on the segmentation identified by the given segmentation ID.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- * @param segmentationID The segmentation node identifier is defined by the given string.
- *
- * @return True, if the lesion is present on the segmentation identified by the given segmentation ID; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool IsLesionPresentOnSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::ID& segmentationID);
- /**
- * @brief Check if the given lesion is present at the given control point.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- * @param controlPoint A control point with a UID that identifies the corresponding control point instance.
- *
- * @return True, if the lesion is present at the given control point; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool IsLesionPresentAtControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Check if the given data node exists in the relation storage.
- * The function receives the case- and the node-ID from the DICOM tags of the node itself.
- * It uses node predicates to decide if the node is an image or a segmentation node and searches
- * through the corresponding relations.
- *
- * @param dataNode A data node to check.
- *
- * @return True, if the data node exists; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool InstanceExists(const DataNode* dataNode);
- /**
- * @brief Check if the given lesion instance exists.
- * This function can be used before calling 'AddLesionInstance' in order to avoid a possible exception.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- *
- * @return True, if the lesion instance exists; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool InstanceExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- /**
- * @brief Return a vector of all image IDs that identify images that are related to the given lesion.
- * Each lesion is represented by a segmentation which is connected to its parent image.
- * If the lesion is not represented by any segmentation, an empty vector is returned.
- *
- * @pre The UID of the lesion has to exist for a lesion instance.
- * @throw SemanticRelationException, if UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A lesion with a UID that identifies the corresponding lesion instance.
- *
- * @return A vector of IDs identifying images that are related to the given lesion.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::IDVector GetAllImageIDsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- /**
- * @brief Return a vector of all image IDs that identify images that are related to the given examination period.
- * If the examination period is not used by and image, an empty vector is returned.
- *
- * @pre The UID of the examination period has to exist for an examination period instance.
- * @throw SemanticRelationException, if UID of the examination period does not exist for an examination period instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param examinationPeriod An examination period with a UID that identifies the corresponding examination period instance.
- *
- * @return A vector of IDs identifying images that are related to the given examination period.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::IDVector GetAllImageIDsOfExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- /**
- * @brief Return the control point of a data node.
- * If the data node is not linked to a control point or the data node refers to a non-existing control point,
- * a control point with an empty UID is returned.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- *
- * @param dataNode The current case identifier is extracted from the given data node, which contains DICOM information about the case.
- *
- * @return The control point of the given data node.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPoint GetControlPointOfImage(const DataNode* dataNode);
- /**
- * @brief Return a vector of all control points that are valid for the given case, given a specific lesion
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A specific lesion which has to be available at a returned (found) control point:
- * Only those control points are returned for which an associated data has a segmentation that references the given lesion.
- * If the lesion does not exists, an empty vector is returned.
- *
- * @return A vector of control points.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPointVector GetAllControlPointsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- /**
- * @brief Return a vector of all control points that are valid for the given case, given a specific information type.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param informationType A specific information type which has to be available at a returned (found) control point:
- * Only those control points are returned for which an associated data has the given information type.
- * If the information type instance does not exists, an empty vector is returned.
- *
- * @return A vector of control points.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::ControlPointVector GetAllControlPointsOfInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType);
- /**
- * @brief Check if the given control point instance exists.
- * This function can be used before adding, linking and unlinking control points to avoid a possible exception.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint A control point with a UID that identifies the corresponding control point instance.
- *
- * @return True, if the control point instance exists; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool InstanceExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Check if the given examination period instance exists.
- * This function can be used before calling 'AddExaminationPeriod' in order to avoid a possible exception.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param examinationPeriod An examination period with a UID that identifies the corresponding examination period instance.
- *
- * @return True, if the examination period instance exists; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool InstanceExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- /**
- * @brief Return the information type of the given image.
- * If the image does not contain any information type, an empty information type is returned.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- *
- * @param imageNode The current case identifier is extracted from the given data node, which contains DICOM information about the case.
- *
- * @return The information type of the given data node.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::InformationType GetInformationTypeOfImage(const DataNode* imageNode);
- /**
- * @brief Return a vector of all information types that are valid for the given case, given a specific control point.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint A specific control point which has to be available at a returned (found) information type:
- * Only those information types are returned for which an associated data is linked to the given control point.
- * If the control point instance does not exist, an empty vector is returned.
- *
- * @return A vector of information types.
- */
- MITKSEMANTICRELATIONS_EXPORT SemanticTypes::InformationTypeVector GetAllInformationTypesOfControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Check if the given information type exists.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param informationType An information type.
- *
- * @return True, if the information type exists; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool InstanceExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType);
- /**
- * @brief Determine if the given information type contains images, which are connected to segmentations that represent the given lesion.
- * If the lesion or the information type are not correctly stored, the function returns false.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A Lesion with a UID that identifies the corresponding lesion instance.
- * @param informationType An information type that identifies the corresponding information type instance.
- *
- * @return True, if the given information type contains data that is related to the given lesion; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool SpecificImageExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::InformationType& informationType);
- /**
- * @brief Determine if the given control point contains images, which are connected to segmentations that represent the given lesion.
- * If the lesion or the control point are not correctly stored, the function returns false.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion A Lesion with a UID that identifies the corresponding lesion instance.
- * @param controlPoint A control point with a UID that identifies the corresponding control point instance.
- *
- * @return True, if the given control point contains data that is related to the given lesion; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool SpecificImageExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Determine if the given control point contains images, which refer to the given information type.
- * If the information type or the control point are not correctly stored, the function returns false.
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param informationType An information type that identifies the corresponding information type instance.
- * @param controlPoint A control point with a UID that identifies the corresponding control point instance.
- *
- * @return True, if the given control point contains data that is related to the given information type; false otherwise.
- */
- MITKSEMANTICRELATIONS_EXPORT bool SpecificImageExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType, const SemanticTypes::ControlPoint& controlPoint);
-
- } // namespace SemanticRelationsInference
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkSemanticRelationsIntegration.h b/Modules/SemanticRelations/include/mitkSemanticRelationsIntegration.h
deleted file mode 100644
index 71ee0d4721..0000000000
--- a/Modules/SemanticRelations/include/mitkSemanticRelationsIntegration.h
+++ /dev/null
@@ -1,322 +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 mitkSemanticRelationsIntegration_h
-#define mitkSemanticRelationsIntegration_h
-
-#include <MitkSemanticRelationsExports.h>
-
-// semantic relations module
-#include "mitkISemanticRelationsObservable.h"
-#include "mitkISemanticRelationsObserver.h"
-#include "mitkSemanticTypes.h"
-
-// mitk core
-#include <mitkDataNode.h>
-
-namespace mitk
-{
- /**
- * @brief The API provides functions to manipulate image relations and instances
- * that are helpful during follow-up examination, like control-points (time period),
- * types of the images or lesions that may be visible on multiple images.
- *
- * The class is able to generate IDs from given data nodes using DICOM information.
- * These IDs are used to identify the corresponding instances of a specific case.
- * The case can also be directly identified by the given case ID.
- *
- * In order for most functions to work the case ID has to be used as a parameter.
- * If not, these functions do nothing.
- *
- * The class implements the ISemanticRelationsObservable interface to allow observers to
- * be informed about changes in the semantic relation storage.
- */
- class MITKSEMANTICRELATIONS_EXPORT SemanticRelationsIntegration : public ISemanticRelationsObservable
- {
- public:
-
- /************************************************************************/
- /* functions to implement the observer pattern */
- /************************************************************************/
- /**
- * @brief Adds the given concrete observer to the vector that holds all currently registered observer.
- * If the observer is already registered, it will not be added to the observer vector.
- *
- * @param observer The concrete observer to register.
- */
- void AddObserver(ISemanticRelationsObserver* observer) override;
- /**
- * @brief Removes the given concrete observer from the vector that holds all currently registered observer.
- *
- * @param observer The concrete observer to unregister.
- */
- void RemoveObserver(ISemanticRelationsObserver* observer) override;
-
- virtual ~SemanticRelationsIntegration() {}
-
- /************************************************************************/
- /* functions to add / remove instances / attributes */
- /************************************************************************/
- /**
- * @brief Add the given image to the set of already existing images.
- * The date is extracted from the DICOM data of the image node and is compared to already existing control points in the semantic relations model.
- * The function tries to find a fitting control point or to extend an already existing control point, if the extracted control point is close to
- * any other, already existing control point.
- * Finally, the image is linked to the correct control point.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- *
- * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node.
- */
- void AddImage(const DataNode* imageNode);
- /**
- * @brief Remove the given image from the set of already existing images.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- *
- * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node.
- */
- void RemoveImage(const DataNode* imageNode);
- /**
- * @brief Add a newly created lesion to the set of already existing lesions - with no connection to a specific image / segmentation of the case data.
- *
- * @pre The UID of the lesion must not already exist for a lesion instance.
- * @throw SemanticRelationException, it the UID of the lesion already exists for a lesion instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion The lesion instance to add.
- */
- void AddLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- /**
- * @brief Overwrite an already existing lesion instance (this may be useful to overwrite the lesion with a different lesion class).
- *
- * @pre The UID of the lesion has to exist for a lesion instance.
- * @throw SemanticRelationException, if the UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion The lesion instance that overwrites an existing lesion.
- */
- void OverwriteLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- /**
- * @brief Add a newly created lesion to the set of already existing lesions. The lesion is added and a reference to
- * the lesion is added to the segmentation. If the segmentation is already linked to a lesion, the
- * old linkage is overwritten (this can be checked via 'IsRepresentingALesion').
- *
- * @pre The given segmentation data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given segmentation data node is invalid (==nullptr).
- * @pre The UID of the lesion must not already exist for a lesion instance.
- * @throw SemanticRelationException, if the UID of the lesion already exists for a lesion instance (this can be checked via 'InstanceExists').
- *
- * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node.
- * @param lesion The lesion instance to add and link.
- */
- void AddLesionAndLinkSegmentation(const DataNode* segmentationNode, const SemanticTypes::Lesion& lesion);
- /**
- * @brief Remove the given lesion from the set of already existing lesions.
- *
- * @pre The UID of the lesion has to exist for a lesion instance.
- * @throw SemanticRelationException, if the UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists').
- * @pre The function needs to assure that no segmentation is still representing (linked to) this lesion.
- * @throw SemanticRelationException, if the lesion instance to remove is still linked to by any segmentation (this can be checked via 'GetAllSegmentationsOfLesion').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param lesion The lesion instance to remove.
- */
- void RemoveLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion);
- /**
- * @brief Add a segmentation instance to the set of already existing segmentations - with no connection to a specific lesion.
- *
- * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node.
- * @param parentNode The node identifier of the parent node is extracted from the given parent data node.
- */
- void AddSegmentation(const DataNode* segmentationNode, const DataNode* parentNode);
- /**
- * @brief Link the given segmentation instance to an an already existing lesion instance. If the segmentation is already linked to a lesion instance, the
- * old linkage is overwritten (this can be checked via 'IsRepresentingALesion').
- *
- * @pre The given segmentation data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given segmentation data node is invalid (==nullptr).
- * @pre The UID of the lesion has to exist for a lesion instance.
- * @throw SemanticRelationException, if the UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists').
- *
- * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node.
- * @param lesion The lesion instance to link.
- */
- void LinkSegmentationToLesion(const DataNode* segmentationNode, const SemanticTypes::Lesion& lesion);
- /**
- * @brief Unlink the given segmentation instance from the linked lesion instance.
- * The lesion may stay unlinked to any segmentation.
- *
- * @pre The given segmentation data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given segmentation data node is invalid (==nullptr).
- *
- * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node.
- */
- void UnlinkSegmentationFromLesion(const DataNode* segmentationNode);
- /**
- * @brief Remove the given segmentation from the set of already existing segmentations.
- *
- * @pre The given segmentation data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given segmentation data node is invalid (==nullptr).
- *
- * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node.
- */
- void RemoveSegmentation(const DataNode* segmentationNode);
- /**
- * @brief Set the control point for the given image.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- *
- * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node.
- * @param controlPoint The control point instance which is used for the given image.
- */
- void SetControlPointOfImage(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint);
- /**
- * @brief Add a newly created control point to the set of already existing control points. A reference to the control point is added to the given image.
- * This function combines adding a control point and linking it, since a control point with no associated data is not allowed.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- * @pre The UID of the control point must not already exist for a control point instance.
- * @throw SemanticRelationException, if the UID of the control point already exists for a control point instance (this can be checked via 'InstanceExists').
- * @pre The given control point must not already be contained in an existing control point interval.
- * @throw SemanticRelationException, if the given control point is already contained in an existing control point interval (this can be checked via 'CheckContainingControlPoint').
- * @pre The given control point must contain the date of the given image data node (if parameter 'checkConsistence = true').
- * @throw SemanticRelationException, if the given control point does not contain the date of the given image data node and 'checkConsistence = true' (this can be checked via 'ControlPointManager::InsideControlPoint').
- *
- * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node.
- * @param controlPoint The control point instance to add. For a newly added control point always has "startDate = endDate".
- * @param checkConsistence If true, the function checks, whether the date of the image data node actually lies inside the control point to link.
- */
- void AddControlPointAndLinkImage(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint, bool checkConsistence = true);
- /**
- * @brief Link the given image to an already existing control point.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- * @pre The UID of the control point has to exist for a control point instance.
- * @throw SemanticRelationException, if the UID of the control point does not exists for a control point instance (this can be checked via 'InstanceExists').
- * @pre The given control point must contain the date of the given image data node (if parameter 'checkConsistence = true').
- * @throw SemanticRelationException, if the given control point does not contain the date of the given image data node and 'checkConsistence = true' (this can be checked via 'ControlPointManager::InsideControlPoint').
- *
- * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node.
- * @param controlPoint The control point instance to link.
- * @param checkConsistence If true, the function checks, whether the date of the image data node actually lies inside the control point to link.
- */
- void LinkImageToControlPoint(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint, bool checkConsistence = true);
- /**
- * @brief Unlink the given image from the linked control point.
- * If an image is unlinked from a control point, the function needs to check whether the control point is still linked to any other image:
- * - if not, the control point instance will be removed (has to be removed since a control point with no associated image is not allowed).
- * - if so, the function has to make sure that the control point instance is shortened to its minimum time period (e.g. moving the end point to an earlier date).
- *
- * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node.
- */
- void UnlinkImageFromControlPoint(const DataNode* imageNode);
- /**
- * @brief Add an examination period instance to the set of already existing examination periods - with no connection to a specific control point.
- *
- * @pre The UID of the examination period must not already exist for an examination period instance.
- * @throw SemanticRelationException, if the UID of the examination period already exists for a examination period instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param examinationPeriod The examination period to add.
- */
- void AddExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- /**
- * @brief Rename an already existing examination period instance.
- *
- * @pre The UID of the examination period has to exist for an examination period instance.
- * @throw SemanticRelationException, if the UID of the examination period does not exist for an examination period instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param examinationPeriod The examination period instance that renames an existing examination period.
- */
- void RenameExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- /**
- * @brief Add a control point to the vector of control point UIDs of an existing examination period.
- *
- * @pre The UID of the control point has to exist for a control point instance.
- * @throw SemanticRelationException, if the UID of the control point does not exists for a control point instance (this can be checked via 'InstanceExists').
- * @pre The UID of the examination period must not already exist for an examination period instance.
- * @throw SemanticRelationException, if the UID of the examination period already exists for a examination period instance (this can be checked via 'InstanceExists').
- *
- * @param caseID The current case identifier is defined by the given string.
- * @param controlPoint The control point instance to add to the examination period.
- * @param examinationPeriod The examination period to which the control point should be added.
- */
- void AddControlPointToExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod);
- /**
- * @brief Set (and possibly overwrite) the information type of the given image.
- * An already associated information type might be removed if is not referenced by any other image:
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- * @post If the information type instance did not exist before, it is now added.
- *
- * @param imageNode The current case identifier is extracted from the given image data node, which contains DICOM information about the case.
- * @param informationType An information type that identifies the corresponding information type instance.
- */
- void SetInformationType(const DataNode* imageNode, const SemanticTypes::InformationType& informationType);
- /**
- * @brief Set the information type of the given image.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- * @post If the information type instance did not exist before, it is now added.
- *
- * @param imageNode The current case identifier is extracted from the given image data node, which contains DICOM information about the case.
- * @param informationType An information type that identifies the corresponding information type instance.
- */
- void AddInformationTypeToImage(const DataNode* imageNode, const SemanticTypes::InformationType& informationType);
- /**
- * @brief Remove the information type of the given image.
- * If the information type is removed, the function needs to check whether the information type is referenced by any other image:
- * - if not, the information type instance can be removed (has to be removed since an information type with no associated image is not allowed).
- * - if so, the information type is just removed from the given image.
- *
- * @pre The given image data node has to be valid (!nullptr).
- * @throw SemanticRelationException, if the given image data node is invalid (==nullptr).
- *
- * @param imageNode The current case identifier is extracted from the given image data node, which contains DICOM information about the case.
- */
- void RemoveInformationTypeFromImage(const DataNode* imageNode);
-
- private:
- /**
- * @brief A vector that stores the currently registered observer of this observable subject.
- */
- static std::vector<mitk::ISemanticRelationsObserver*> m_ObserverVector;
- /**
- * @brief The class notifies (updates) the observer with a given case ID.
- * The view's caseID was set before in the GUI. The parts of the view that observe changes in the semantic relations are only updated,
- * if the given case ID is equal to the observer's current caseID and thus the observer currently shows the semantic information of the given case.
- *
- * @param caseID The caseID that identifies the currently active patient / case.
- */
- void NotifyObserver(const mitk::SemanticTypes::CaseID& caseID) const override;
- /**
- * @brief Remove all control points from the storage that are not referenced by any image anymore.
- * This might happen if an image has been removed (and unlinked from the corresponding control point)
- * or if the user sets a new control point for an image manually in the GUI.
- *
- * @param caseID The current case identifier is defined by the given string.
- */
- void ClearControlPoints(const SemanticTypes::CaseID& caseID);
-
- };
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkSemanticTypes.h b/Modules/SemanticRelations/include/mitkSemanticTypes.h
deleted file mode 100644
index 4a1cc4dd68..0000000000
--- a/Modules/SemanticRelations/include/mitkSemanticTypes.h
+++ /dev/null
@@ -1,125 +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 mitkSemanticTypes_h
-#define mitkSemanticTypes_h
-
-#define BOOST_DATE_TIME_NO_LIB
-#if defined(BOOST_ALL_DYN_LINK)
-#undef BOOST_ALL_DYN_LINK
-#endif
-
-// boost
-#include <boost/date_time/gregorian/gregorian.hpp>
-
-// c++
-#include <set>
-#include <tuple>
-#include <vector>
-
-namespace mitk
-{
- namespace SemanticTypes
- {
- using ID = std::string;
- using CaseID = std::string;
- using InformationType = std::string;
-
- /*
- * @brief The concept of a control point.
- */
- struct ControlPoint
- {
- ID UID;
- boost::gregorian::date date;
-
- ControlPoint()
- {
- date = boost::gregorian::date(boost::gregorian::min_date_time);
- }
-
- // less comparison to sort containers of control points
- bool operator<(const ControlPoint& other) const
- {
- return date < other.date;
- }
-
- std::string ToString() const
- {
- std::stringstream controlPointAsString;
- if (date.is_not_a_date())
- {
- return "";
- }
-
- controlPointAsString << std::to_string(date.year()) << "-"
- << std::setfill('0') << std::setw(2) << std::to_string(date.month()) << "-"
- << std::setfill('0') << std::setw(2) << std::to_string(date.day());
-
- return controlPointAsString.str();
- }
-
- void SetDateFromString(const std::string& dateAsString)
- {
- date = boost::gregorian::from_undelimited_string(dateAsString);
- }
-
- int DistanceInDays(const ControlPoint& other) const
- {
- boost::gregorian::date_duration duration = date - other.date;
- return std::abs(duration.days());
- }
- };
-
- /**
- * @brief The concept of an examination period.
- * An examination period holds a vector of control point UIDs.
- * The semantic relation storage stores the UIDs such that
- * the represented control points are in chronological order.
- */
- struct ExaminationPeriod
- {
- ID UID;
- std::string name = "";
- std::vector<ID> controlPointUIDs;
- };
-
- /*
- * @brief The concept of a lesion class.
- */
- struct LesionClass
- {
- ID UID;
- std::string classType = "";
- };
-
- /*
- * @brief The concept of a lesion.
- */
- struct Lesion
- {
- ID UID;
- std::string name = "";
- LesionClass lesionClass;
- };
-
- using IDVector = std::vector<ID>;
- using LesionVector = std::vector<Lesion>;
- using LesionClassVector = std::vector<LesionClass>;
- using ControlPointVector = std::vector<ControlPoint>;
- using ExaminationPeriodVector = std::vector<ExaminationPeriod>;
- using InformationTypeVector = std::vector<InformationType>;
-
- } // namespace SemanticTypes
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/include/mitkUIDGeneratorBoost.h b/Modules/SemanticRelations/include/mitkUIDGeneratorBoost.h
deleted file mode 100644
index 9902e96bd6..0000000000
--- a/Modules/SemanticRelations/include/mitkUIDGeneratorBoost.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*============================================================================
-
-The Medical Imaging Interaction Toolkit (MITK)
-
-Copyright (c) German Cancer Research Center (DKFZ)
-All rights reserved.
-
-Use of this source code is governed by a 3-clause BSD license that can be
-found in the LICENSE file.
-
-============================================================================*/
-
-#ifndef mitkUIDGeneratorBoost_h
-#define mitkUIDGeneratorBoost_h
-
-#include <MitkSemanticRelationsExports.h>
-
-#include <iostream>
-
-namespace mitk
-{
- namespace UIDGeneratorBoost
- {
- MITKSEMANTICRELATIONS_EXPORT std::string GenerateUID();
- } // namespace UIDGeneratorBoost
-} // namespace mitk
-
-#endif
diff --git a/Modules/SemanticRelations/src/mitkControlPointManager.cpp b/Modules/SemanticRelations/src/mitkControlPointManager.cpp
deleted file mode 100644
index 2f31f63a27..0000000000
--- a/Modules/SemanticRelations/src/mitkControlPointManager.cpp
+++ /dev/null
@@ -1,224 +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.
-
-============================================================================*/
-
-// semantic relations module
-#include "mitkControlPointManager.h"
-#include "mitkDICOMHelper.h"
-#include "mitkRelationStorage.h"
-#include "mitkSemanticRelationException.h"
-#include "mitkUIDGeneratorBoost.h"
-
-// mitk core
-#include <mitkPropertyNameHelper.h>
-
-mitk::SemanticTypes::ControlPoint mitk::GenerateControlPoint(const DataNode* datanode)
-{
- SemanticTypes::ControlPoint controlPoint;
- try
- {
- controlPoint = GetDICOMDateFromDataNode(datanode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot generate a control point from the DICOM tag of the given data node.";
- }
-
- controlPoint.UID = UIDGeneratorBoost::GenerateUID();
- return controlPoint;
-}
-
-mitk::SemanticTypes::ControlPoint mitk::GetControlPointByUID(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& controlPointUID)
-{
- auto lambda = [&controlPointUID](const SemanticTypes::ControlPoint& currentControlPoint)
- {
- return currentControlPoint.UID == controlPointUID;
- };
-
- SemanticTypes::ControlPointVector allControlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
- const auto existingControlPoint = std::find_if(allControlPoints.begin(), allControlPoints.end(), lambda);
-
- mitk::SemanticTypes::ControlPoint controlPoint;
- if (existingControlPoint != allControlPoints.end())
- {
- controlPoint = *existingControlPoint;
- }
-
- return controlPoint;
-}
-
-mitk::SemanticTypes::ControlPoint mitk::FindExistingControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::ControlPointVector allControlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
- for (const auto& currentControlPoint : allControlPoints)
- {
- if (controlPoint.date == currentControlPoint.date)
- {
- return currentControlPoint;
- }
- }
-
- return SemanticTypes::ControlPoint();
-}
-
-mitk::SemanticTypes::ControlPoint mitk::FindClosestControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::ControlPointVector allControlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
- if (allControlPoints.empty())
- {
- return SemanticTypes::ControlPoint();
- }
-
- // sort the vector of control points for easier lookup
- std::sort(allControlPoints.begin(), allControlPoints.end());
- // new control point does not match an existing control point
- // check if the control point is close to an already existing control point
- SemanticTypes::ControlPointVector::const_iterator it;
- for (it = allControlPoints.begin(); it != allControlPoints.end(); ++it)
- {
- if (controlPoint.date < it->date)
- {
- break;
- }
- }
-
- SemanticTypes::ControlPoint nextControlPoint;
- SemanticTypes::ControlPoint previousControlPoint;
- if (it == allControlPoints.begin())
- {
- // new date is smaller ("older") than the smallest already existing control point
- nextControlPoint = *it;
- }
- else if (it != allControlPoints.end())
- {
- // new date is greater ("newer") than an already existing control point,
- // but smaller ("older") than another already existing control point
- nextControlPoint = *it;
- previousControlPoint = *(--it);
- }
- else
- {
- // new date is greater ("newer") than the greatest already existing control point
- previousControlPoint = *(--it);
- }
-
- // test distance to next and previous time period
- double distanceToNextExaminationPeriod = nextControlPoint.DistanceInDays(controlPoint);
- double distanceToPreviousExaminationPeriod = previousControlPoint.DistanceInDays(controlPoint);
-
- SemanticTypes::ControlPoint closestControlPoint;
- int closestDistanceInDays = 0;
- if (distanceToNextExaminationPeriod < distanceToPreviousExaminationPeriod)
- {
- // control point is closer to the next control point
- closestControlPoint = nextControlPoint;
- closestDistanceInDays = distanceToNextExaminationPeriod;
- }
- else
- {
- // control point is closer to the previous control point
- closestControlPoint = previousControlPoint;
- closestDistanceInDays = distanceToPreviousExaminationPeriod;
- }
-
- int THRESHOLD_DISTANCE_IN_DAYS = 30;
- if (closestDistanceInDays <= THRESHOLD_DISTANCE_IN_DAYS)
- {
- return closestControlPoint;
- }
-
- return SemanticTypes::ControlPoint();
-}
-
-mitk::SemanticTypes::ExaminationPeriod mitk::FindContainingExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::ExaminationPeriodVector allExaminationPeriods = RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
- for (const auto& examinationPeriod : allExaminationPeriods)
- {
- for (const auto& UID : examinationPeriod.controlPointUIDs)
- {
- if (controlPoint.UID == UID)
- {
- return examinationPeriod;
- }
- }
- }
-
- return SemanticTypes::ExaminationPeriod();
-}
-
-mitk::SemanticTypes::ExaminationPeriod mitk::FindFittingExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::ExaminationPeriod specificExaminationPeriod;
- SemanticTypes::ControlPoint specificControlPoint;
- // find the closest control point
- SemanticTypes::ControlPoint existingControlPoint = FindExistingControlPoint(caseID, controlPoint);
- if (!existingControlPoint.UID.empty())
- {
- specificControlPoint = existingControlPoint;
- }
- else
- {
- auto closestControlPoint = FindClosestControlPoint(caseID, controlPoint);
- if (!closestControlPoint.UID.empty())
- {
- specificControlPoint = closestControlPoint;
- }
- }
-
- // find the containing examination period
- return FindContainingExaminationPeriod(caseID, specificControlPoint);
-}
-
-mitk::SemanticTypes::ExaminationPeriod mitk::FindFittingExaminationPeriod(const DataNode* dataNode)
-{
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ControlPoint controlPoint;
- try
- {
- caseID = GetCaseIDFromDataNode(dataNode);
- controlPoint = GetDICOMDateFromDataNode(dataNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot find an examination period.";
- }
-
- return FindFittingExaminationPeriod(caseID, controlPoint);
-}
-
-void mitk::SortAllExaminationPeriods(const SemanticTypes::CaseID& caseID, SemanticTypes::ExaminationPeriodVector& allExaminationPeriods)
-{
- SemanticTypes::ControlPointVector controlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
- // sort the vector of control points for the timeline
- std::sort(controlPoints.begin(), controlPoints.end());
-
- auto lambda = [&caseID](const SemanticTypes::ExaminationPeriod& leftExaminationPeriod, const SemanticTypes::ExaminationPeriod& rightExaminationPeriod)
- {
- if (leftExaminationPeriod.controlPointUIDs.empty())
- {
- return true;
- }
-
- if (rightExaminationPeriod.controlPointUIDs.empty())
- {
- return false;
- }
- const auto leftUID = leftExaminationPeriod.controlPointUIDs.front();
- const auto rightUID = rightExaminationPeriod.controlPointUIDs.front();
- const auto& leftControlPoint = GetControlPointByUID(caseID, leftUID);
- const auto& rightControlPoint = GetControlPointByUID(caseID, rightUID);
-
- return leftControlPoint.date < rightControlPoint.date;
- };
-
- std::sort(allExaminationPeriods.begin(), allExaminationPeriods.end(), lambda);
-}
diff --git a/Modules/SemanticRelations/src/mitkDICOMHelper.cpp b/Modules/SemanticRelations/src/mitkDICOMHelper.cpp
deleted file mode 100644
index 726dd9159c..0000000000
--- a/Modules/SemanticRelations/src/mitkDICOMHelper.cpp
+++ /dev/null
@@ -1,186 +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.
-
-============================================================================*/
-
-// semantic relations module
-#include "mitkDICOMHelper.h"
-#include "mitkSemanticRelationException.h"
-#include "mitkUIDGeneratorBoost.h"
-
-// mitk core
-#include <mitkPropertyNameHelper.h>
-
-// c++
-#include <algorithm>
-
-mitk::SemanticTypes::ControlPoint GetControlPointFromString(const std::string& dateAsString)
-{
- // date expected to be YYYYMMDD (8 characters)
- if (dateAsString.size() != 8)
- {
- // string does not represent a DICOM date
- mitkThrowException(mitk::SemanticRelationException) << "Not a valid DICOM date format.";
- }
-
- mitk::SemanticTypes::ControlPoint controlPoint;
- controlPoint.SetDateFromString(dateAsString);
-
- return controlPoint;
-}
-
-std::string mitk::GetCaseIDDICOMProperty()
-{
- // extract suitable DICOM tag to use as the case id
- // two alternatives can be used:
- // - DICOM tag "0x0010, 0x0010" is PatientName
- // - DICOM tag "0x0010, 0x0020" is PatientID
- // in the current implementation the PatientName (0x0010, 0x0010) is used
- return GeneratePropertyNameForDICOMTag(0x0010, 0x0010);
-}
-
-std::string mitk::GetNodeIDDICOMProperty()
-{
- // extract suitable DICOM tag to use as the data node id
- // DICOM tag "0x0020, 0x000e" is SeriesInstanceUID
- return GeneratePropertyNameForDICOMTag(0x0020, 0x000e);
-}
-
-std::string mitk::GetDateDICOMProperty()
-{
- // extract suitable DICOM tag to use as the data node id
- // DICOM tag "0x0008, 0x0022" is AcquisitionDate
- return GeneratePropertyNameForDICOMTag(0x0008, 0x0022);
-}
-
-std::string mitk::GetModalityDICOMProperty()
-{
- // extract suitable DICOM tag to use as the information type
- // DICOM tag "0x0008, 0x0060" is Modality
- return GeneratePropertyNameForDICOMTag(0x0008, 0x0060);
-}
-
-mitk::SemanticTypes::CaseID mitk::GetCaseIDFromDataNode(const DataNode* dataNode)
-{
- if (nullptr == dataNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data node.";
- }
-
- BaseData* baseData = dataNode->GetData();
- if (nullptr == baseData)
- {
- mitkThrowException(SemanticRelationException) << "No valid base data.";
- }
-
- BaseProperty* dicomTag = baseData->GetProperty(GetCaseIDDICOMProperty().c_str());
- if (nullptr == dicomTag)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid DICOM property.";
- }
-
- std::string dicomTagAsString = dicomTag->GetValueAsString();
- return dicomTagAsString;
-}
-
-mitk::SemanticTypes::ID mitk::GetIDFromDataNode(const DataNode* dataNode)
-{
- if (nullptr == dataNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data node.";
- }
-
- BaseData* baseData = dataNode->GetData();
- if (nullptr == baseData)
- {
- mitkThrowException(SemanticRelationException) << "No valid base data.";
- }
-
- BaseProperty* dicomTag = baseData->GetProperty(GetNodeIDDICOMProperty().c_str());
- if (nullptr == dicomTag)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid DICOM property.";
- }
- std::string dicomTagAsString = dicomTag->GetValueAsString();
- return dicomTagAsString;
-}
-
-mitk::SemanticTypes::ControlPoint mitk::GetDICOMDateFromDataNode(const DataNode* dataNode)
-{
- if (nullptr == dataNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data node.";
- }
-
- BaseData* baseData = dataNode->GetData();
- if (nullptr == baseData)
- {
- mitkThrowException(SemanticRelationException) << "No valid base data.";
- }
-
- BaseProperty* acquisitionDateProperty = baseData->GetProperty(GetDateDICOMProperty().c_str());
- if (nullptr == acquisitionDateProperty)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid DICOM property.";
- }
- std::string acquisitionDateAsString = acquisitionDateProperty->GetValueAsString();
-
- SemanticTypes::ControlPoint controlPoint;
- try
- {
- controlPoint = GetControlPointFromString(acquisitionDateAsString);
- }
- catch (SemanticRelationException &e)
- {
- mitkReThrow(e) << "Cannot retrieve a valid DICOM date.";
- }
-
- return controlPoint;
-}
-
-mitk::SemanticTypes::InformationType mitk::GetDICOMModalityFromDataNode(const DataNode* dataNode)
-{
- if (nullptr == dataNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data node.";
- }
-
- BaseData* baseData = dataNode->GetData();
- if (nullptr == baseData)
- {
- mitkThrowException(SemanticRelationException) << "No valid base data.";
- }
-
- BaseProperty* dicomTag = baseData->GetProperty(GetModalityDICOMProperty().c_str());
- if (nullptr == dicomTag)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid DICOM property.";
- }
- std::string dicomTagAsString = dicomTag->GetValueAsString();
- return dicomTagAsString;
-}
-
-std::string mitk::TrimDICOM(const std::string& identifier)
-{
- if (identifier.empty())
- {
- return identifier;
- }
-
- // leading whitespace
- std::size_t first = identifier.find_first_not_of(' ');
- if (std::string::npos == first)
- {
- return "";
- }
- // trailing whitespace
- std::size_t last = identifier.find_last_not_of(' ');
- return identifier.substr(first, last - first + 1);
-}
diff --git a/Modules/SemanticRelations/src/mitkLesionData.cpp b/Modules/SemanticRelations/src/mitkLesionData.cpp
deleted file mode 100644
index 103bfc9675..0000000000
--- a/Modules/SemanticRelations/src/mitkLesionData.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.
-
-============================================================================*/
-
-// semantic relations module
-#include "mitkLesionData.h"
-
-mitk::LesionData::LesionData(const SemanticTypes::Lesion& lesion/* = SemanticTypes::Lesion()*/)
-{
- m_Lesion = lesion;
-}
-
-void mitk::LesionData::SetLesion(const SemanticTypes::Lesion& lesion)
-{
- m_Lesion = lesion;
-}
-
-void mitk::LesionData::SetLesionPresence(const std::vector<bool>& lesionPresence)
-{
- m_LesionPresence = lesionPresence;
-}
-
-void mitk::LesionData::SetLesionVolume(const std::vector<double>& lesionVolume)
-{
- m_LesionVolume = lesionVolume;
-}
diff --git a/Modules/SemanticRelations/src/mitkLesionManager.cpp b/Modules/SemanticRelations/src/mitkLesionManager.cpp
deleted file mode 100644
index 725dbfaf6c..0000000000
--- a/Modules/SemanticRelations/src/mitkLesionManager.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.
-
-============================================================================*/
-
-// semantic relations module
-#include "mitkLesionManager.h"
-#include "mitkRelationStorage.h"
-#include "mitkSemanticRelationException.h"
-#include "mitkSemanticRelationsInference.h"
-#include "mitkUIDGeneratorBoost.h"
-
-mitk::SemanticTypes::Lesion mitk::GenerateNewLesion(const std::string& lesionClassType/* = ""*/)
-{
- SemanticTypes::Lesion lesion;
- lesion.UID = UIDGeneratorBoost::GenerateUID();
- lesion.name = "New lesion";
- lesion.lesionClass = GenerateNewLesionClass(lesionClassType);
-
- return lesion;
-}
-
-mitk::SemanticTypes::LesionClass mitk::GenerateNewLesionClass(const std::string& lesionClassType/* = ""*/)
-{
- SemanticTypes::LesionClass lesionClass;
- lesionClass.UID = UIDGeneratorBoost::GenerateUID();
- lesionClass.classType = lesionClassType;
-
- return lesionClass;
-}
-
-mitk::SemanticTypes::Lesion mitk::GetLesionByUID(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& lesionUID)
-{
- auto lambda = [&lesionUID](const SemanticTypes::Lesion& currentLesion)
- {
- return currentLesion.UID == lesionUID;
- };
-
- SemanticTypes::LesionVector allLesions = RelationStorage::GetAllLesionsOfCase(caseID);
- const auto existingLesion = std::find_if(allLesions.begin(), allLesions.end(), lambda);
-
- SemanticTypes::Lesion lesion;
- if (existingLesion != allLesions.end())
- {
- lesion = *existingLesion;
- }
-
- return lesion;
-}
-
-mitk::SemanticTypes::LesionClass mitk::FindExistingLesionClass(const SemanticTypes::CaseID& caseID, const std::string& lesionClassType)
-{
- auto lambda = [&lesionClassType](const SemanticTypes::LesionClass& currentLesionClass)
- {
- return currentLesionClass.classType == lesionClassType;
- };
-
- SemanticTypes::LesionClassVector allLesionClasses = SemanticRelationsInference::GetAllLesionClassesOfCase(caseID);
- const auto existingLesionClass = std::find_if(allLesionClasses.begin(), allLesionClasses.end(), lambda);
-
- SemanticTypes::LesionClass lesionClass;
- if (existingLesionClass != allLesionClasses.end())
- {
- lesionClass = *existingLesionClass;
- }
-
- return lesionClass;
-}
-
-void mitk::ComputeLesionPresence(LesionData& lesionData, const SemanticTypes::CaseID& caseID)
-{
- std::vector<bool> lesionPresence;
- auto lesion = lesionData.GetLesion();
- bool presence = false;
- auto controlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
- // sort the vector of control points for the timeline
- std::sort(controlPoints.begin(), controlPoints.end());
- for (const auto& controlPoint : controlPoints)
- {
- try
- {
- presence = SemanticRelationsInference::IsLesionPresentAtControlPoint(caseID, lesion, controlPoint);
- }
- catch (SemanticRelationException&)
- {
- presence = false;
- }
-
- lesionPresence.push_back(presence);
- }
-
- lesionData.SetLesionPresence(lesionPresence);
-}
diff --git a/Modules/SemanticRelations/src/mitkNodePredicates.cpp b/Modules/SemanticRelations/src/mitkNodePredicates.cpp
deleted file mode 100644
index 7d92b9e9f6..0000000000
--- a/Modules/SemanticRelations/src/mitkNodePredicates.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 "mitkNodePredicates.h"
-
-// mitk core
-#include <mitkNodePredicateDataType.h>
-#include <mitkNodePredicateNot.h>
-#include <mitkNodePredicateOr.h>
-#include <mitkNodePredicateProperty.h>
-
-// multi label module
-#include <mitkLabelSetImage.h>
-
-mitk::NodePredicateAnd::Pointer mitk::NodePredicates::GetImagePredicate()
-{
- TNodePredicateDataType<Image>::Pointer isImage = TNodePredicateDataType<Image>::New();
-
- NodePredicateOr::Pointer validImages = NodePredicateOr::New();
- validImages->AddPredicate(isImage);
-
- NodePredicateAnd::Pointer imagePredicate = NodePredicateAnd::New();
- imagePredicate->AddPredicate(validImages);
- imagePredicate->AddPredicate(NodePredicateNot::New(GetSegmentationPredicate()));
- imagePredicate->AddPredicate(NodePredicateNot::New(NodePredicateProperty::New("helper object")));
-
- return imagePredicate;
-}
-
-mitk::NodePredicateAnd::Pointer mitk::NodePredicates::GetSegmentationPredicate()
-{
- NodePredicateAnd::Pointer segmentationPredicate = NodePredicateAnd::New();
-
- NodePredicateProperty::Pointer isBinary = NodePredicateProperty::New("binary", BoolProperty::New(true));
- TNodePredicateDataType<LabelSetImage>::Pointer isLabelSetImage = TNodePredicateDataType<LabelSetImage>::New();
- NodePredicateOr::Pointer allSegmentations = NodePredicateOr::New(isBinary, isLabelSetImage);
-
- segmentationPredicate->AddPredicate(allSegmentations);
- segmentationPredicate->AddPredicate(NodePredicateNot::New(NodePredicateProperty::New("helper object")));
-
- return segmentationPredicate;
-}
diff --git a/Modules/SemanticRelations/src/mitkRelationStorage.cpp b/Modules/SemanticRelations/src/mitkRelationStorage.cpp
deleted file mode 100644
index e8c49818aa..0000000000
--- a/Modules/SemanticRelations/src/mitkRelationStorage.cpp
+++ /dev/null
@@ -1,1567 +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 "mitkRelationStorage.h"
-
-// semantic relations module
-#include "mitkDICOMHelper.h"
-
-// multi label module
-#include <mitkLabelSetImage.h>
-
-// mitk core
-#include <mitkIPersistenceService.h>
-#include <mitkVectorProperty.h>
-
-// c++
-#include <algorithm>
-#include <iostream>
-
-namespace
-{
- std::vector<mitk::SemanticTypes::CaseID> GetCaseIDs()
- {
- PERSISTENCE_GET_SERVICE_MACRO
- if (nullptr == persistenceService)
- {
- MITK_DEBUG << "Persistence service could not be loaded";
- return std::vector<mitk::SemanticTypes::CaseID>();
- }
- // the property list is valid for a certain scenario and contains all the case IDs of the radiological user's MITK session
- std::string listIdentifier = "caseIDs";
- mitk::PropertyList::Pointer propertyList = persistenceService->GetPropertyList(listIdentifier);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << listIdentifier << " for the current MITK workbench / session.";
- return std::vector<mitk::SemanticTypes::CaseID>();
- }
- // retrieve a vector property that contains all case IDs
- mitk::VectorProperty<std::string>* caseIDsVectorProperty = dynamic_cast<mitk::VectorProperty<std::string>*>(propertyList->GetProperty(listIdentifier));
- if (nullptr == caseIDsVectorProperty)
- {
- MITK_DEBUG << "Could not find the property " << listIdentifier << " for the " << listIdentifier << " property list.";
- return std::vector<mitk::SemanticTypes::CaseID>();
- }
-
- return caseIDsVectorProperty->GetValue();
- }
-
- bool CaseIDExists(const mitk::SemanticTypes::CaseID& caseID)
- {
- auto allCaseIDs = GetCaseIDs();
- auto existingCase = std::find(allCaseIDs.begin(), allCaseIDs.end(), caseID);
- if (existingCase == allCaseIDs.end())
- {
- return false;
- }
-
- return true;
- }
-
- mitk::PropertyList::Pointer GetStorageData(const mitk::SemanticTypes::CaseID& caseID)
- {
- // access the storage
- PERSISTENCE_GET_SERVICE_MACRO
- if (nullptr == persistenceService)
- {
- MITK_DEBUG << "Persistence service could not be loaded";
- return nullptr;
- }
-
- // The persistence service may create a new property list with the given ID, if no property list is found.
- // Since we don't want to return a new property list but rather inform the user that the given case
- // is not a valid, stored case, we will return nullptr in that case.
- if (CaseIDExists(caseID))
- {
- // the property list is valid for a whole case and contains all the properties for the current case
- return persistenceService->GetPropertyList(const_cast<mitk::SemanticTypes::CaseID&>(caseID));
- }
-
- return nullptr;
- }
-
- mitk::SemanticTypes::Lesion GenerateLesion(const mitk::SemanticTypes::CaseID& caseID, const mitk::SemanticTypes::ID& lesionID)
- {
- mitk::PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return mitk::SemanticTypes::Lesion();
- }
-
- mitk::VectorProperty<std::string>* lesionDataProperty = dynamic_cast<mitk::VectorProperty<std::string>*>(propertyList->GetProperty(lesionID));
- if (nullptr == lesionDataProperty)
- {
- MITK_DEBUG << "Lesion " << lesionID << " not found. Lesion can not be retrieved.";
- return mitk::SemanticTypes::Lesion();
- }
-
- std::vector<std::string> lesionData = lesionDataProperty->GetValue();
- // a lesion date has to have exactly two values (the name of the lesion and the UID of the lesion class)
- if (lesionData.size() != 2)
- {
- MITK_DEBUG << "Incorrect lesion data storage. Not two (2) strings of the lesion name and the lesion UID are stored.";
- return mitk::SemanticTypes::Lesion();
- }
-
- // the lesion class ID is stored as the second property
- std::string lesionClassID = lesionData[1];
- mitk::StringProperty* lesionClassProperty = dynamic_cast<mitk::StringProperty*>(propertyList->GetProperty(lesionClassID));
- if (nullptr != lesionClassProperty)
- {
- mitk::SemanticTypes::LesionClass generatedLesionClass;
- generatedLesionClass.UID = lesionClassID;
- generatedLesionClass.classType = lesionClassProperty->GetValue();
-
- mitk::SemanticTypes::Lesion generatedLesion;
- generatedLesion.UID = lesionID;
- generatedLesion.name = lesionData[0];
- generatedLesion.lesionClass = generatedLesionClass;
-
- return generatedLesion;
- }
-
- MITK_DEBUG << "Incorrect lesion class storage. Lesion " << lesionID << " can not be retrieved.";
- return mitk::SemanticTypes::Lesion();
- }
-
- mitk::SemanticTypes::ControlPoint GenerateControlpoint(const mitk::SemanticTypes::CaseID& caseID, const mitk::SemanticTypes::ID& controlPointUID)
- {
- mitk::PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return mitk::SemanticTypes::ControlPoint();
- }
-
- // retrieve a vector property that contains the integer values of the date of a control point (0. year 1. month 2. day)
- mitk::VectorProperty<int>* controlPointVectorProperty = dynamic_cast<mitk::VectorProperty<int>*>(propertyList->GetProperty(controlPointUID));
- if (nullptr == controlPointVectorProperty)
- {
- MITK_DEBUG << "Could not find the control point " << controlPointUID << " in the storage.";
- return mitk::SemanticTypes::ControlPoint();
- }
-
- std::vector<int> controlPointVectorPropertyValue = controlPointVectorProperty->GetValue();
- // a control point has to have exactly three integer values (year, month and day)
- if (controlPointVectorPropertyValue.size() != 3)
- {
- MITK_DEBUG << "Incorrect control point storage. Not three (3) values of the date are stored.";
- return mitk::SemanticTypes::ControlPoint();
- }
-
- // set the values of the control point
- mitk::SemanticTypes::ControlPoint generatedControlPoint;
- generatedControlPoint.UID = controlPointUID;
- generatedControlPoint.date = boost::gregorian::date(controlPointVectorPropertyValue[0],
- controlPointVectorPropertyValue[1],
- controlPointVectorPropertyValue[2]);
-
- return generatedControlPoint;
- }
-}
-
-mitk::SemanticTypes::LesionVector mitk::RelationStorage::GetAllLesionsOfCase(const SemanticTypes::CaseID& caseID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::LesionVector();
- }
- // retrieve a vector property that contains the valid lesion-IDs for the current case
- VectorProperty<std::string>* lesionsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions"));
- if (nullptr == lesionsVectorProperty)
- {
- MITK_DEBUG << "Could not find any lesion in the storage.";
- return SemanticTypes::LesionVector();
- }
-
- std::vector<std::string> lesionsVectorPropertyValue = lesionsVectorProperty->GetValue();
- SemanticTypes::LesionVector allLesionsOfCase;
- for (const auto& lesionID : lesionsVectorPropertyValue)
- {
- SemanticTypes::Lesion generatedLesion = GenerateLesion(caseID, lesionID);
- if (!generatedLesion.UID.empty())
- {
- allLesionsOfCase.push_back(generatedLesion);
- }
- }
-
- return allLesionsOfCase;
-}
-
-mitk::SemanticTypes::Lesion mitk::RelationStorage::GetLesionOfSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::Lesion();
- }
-
- // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID)
- VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID));
- if (nullptr == segmentationVectorProperty)
- {
- MITK_DEBUG << "Could not find the segmentation " << segmentationID << " in the storage.";
- return SemanticTypes::Lesion();
- }
-
- std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue();
- // the lesion ID of a segmentation is the second value in the vector
- if (segmentationVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect segmentation storage. Not two (2) IDs stored.";
- return SemanticTypes::Lesion();
- }
-
- std::string lesionID = segmentationVectorPropertyValue[1];
- if (lesionID.empty())
- {
- // segmentation does not refer to any lesion; return empty lesion
- return SemanticTypes::Lesion();
- }
-
- return GenerateLesion(caseID, lesionID);
-}
-
-mitk::SemanticTypes::ControlPointVector mitk::RelationStorage::GetAllControlPointsOfCase(const SemanticTypes::CaseID& caseID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::ControlPointVector();
- }
-
- // retrieve a vector property that contains the valid control point-IDs for the current case
- VectorProperty<std::string>* controlPointsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("controlpoints"));
- if (nullptr == controlPointsVectorProperty)
- {
- MITK_DEBUG << "Could not find any control points in the storage.";
- return SemanticTypes::ControlPointVector();
- }
-
- std::vector<std::string> controlPointsVectorPropertyValue = controlPointsVectorProperty->GetValue();
- SemanticTypes::ControlPointVector allControlPointsOfCase;
- for (const auto& controlPointUID : controlPointsVectorPropertyValue)
- {
- SemanticTypes::ControlPoint generatedControlPoint = GenerateControlpoint(caseID, controlPointUID);
- if (!generatedControlPoint.UID.empty())
- {
- allControlPointsOfCase.push_back(generatedControlPoint);
- }
- }
-
- return allControlPointsOfCase;
-}
-
-mitk::SemanticTypes::ControlPoint mitk::RelationStorage::GetControlPointOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::ControlPoint();
- }
- // retrieve a vector property that contains the information type and the referenced ID of a control point (0. information type 1. control point ID)
- VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID));
- if (nullptr == imageVectorProperty)
- {
- MITK_DEBUG << "Could not find the image " << imageID << " in the storage.";
- return SemanticTypes::ControlPoint();
- }
-
- std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue();
- SemanticTypes::ControlPoint controlPoint;
- // an image has to have exactly two values (the information type and the ID of the control point)
- if (imageVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect data storage. Not two (2) values stored.";
- return SemanticTypes::ControlPoint();
- }
-
- // the second value of the image vector is the ID of the referenced control point
- std::string controlPointID = imageVectorPropertyValue[1];
- // retrieve a vector property that contains the integer values of the date of a control point (0. year 1. month 2. day)
- VectorProperty<int>* controlPointVectorProperty = dynamic_cast<VectorProperty<int>*>(propertyList->GetProperty(controlPointID));
- if (nullptr == controlPointVectorProperty)
- {
- MITK_DEBUG << "Could not find the control point " << controlPointID << " in the storage.";
- return SemanticTypes::ControlPoint();
- }
-
- std::vector<int> controlPointVectorPropertyValue = controlPointVectorProperty->GetValue();
- // a control point has to have exactly three integer values (year, month and day)
- if (controlPointVectorPropertyValue.size() != 3)
- {
- MITK_DEBUG << "Incorrect control point storage. Not three (3) values of the date are stored.";
- return SemanticTypes::ControlPoint();
- }
-
- // set the values of the control point
- controlPoint.UID = controlPointID;
- controlPoint.date = boost::gregorian::date(controlPointVectorPropertyValue[0],
- controlPointVectorPropertyValue[1],
- controlPointVectorPropertyValue[2]);
-
- return controlPoint;
-}
-
-mitk::SemanticTypes::ExaminationPeriodVector mitk::RelationStorage::GetAllExaminationPeriodsOfCase(const SemanticTypes::CaseID& caseID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::ExaminationPeriodVector();
- }
-
- // retrieve a vector property that contains the valid examination period UIDs for the current case
- VectorProperty<std::string>::Pointer examinationPeriodsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("examinationperiods"));
- if (nullptr == examinationPeriodsVectorProperty)
- {
- MITK_DEBUG << "Could not find any examination periods in the storage.";
- return SemanticTypes::ExaminationPeriodVector();
- }
-
- std::vector<std::string> examinationPeriodsVectorPropertyValue = examinationPeriodsVectorProperty->GetValue();
- SemanticTypes::ExaminationPeriodVector allExaminationPeriods;
- for (const auto& examinationPeriodID : examinationPeriodsVectorPropertyValue)
- {
- // retrieve a vector property that contains the represented control point-IDs
- VectorProperty<std::string>::Pointer examinationPeriodVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(examinationPeriodID));
- if (nullptr == examinationPeriodVectorProperty)
- {
- MITK_DEBUG << "Could not find the examination period " << examinationPeriodID << " in the storage.";
- continue;
- }
-
- std::vector<std::string> examinationPeriodVectorPropertyValue = examinationPeriodVectorProperty->GetValue();
- // an examination period has an arbitrary number of vector values (name and control point UIDs) (at least one for the name)
- if (examinationPeriodVectorPropertyValue.empty())
- {
- MITK_DEBUG << "Incorrect examination period storage. At least one (1) value for the examination period name has to be stored.";
- continue;
- }
- else
- {
- // set the values of the name and the control points
- SemanticTypes::ExaminationPeriod generatedExaminationPeriod;
- generatedExaminationPeriod.UID = examinationPeriodID;
- generatedExaminationPeriod.name = examinationPeriodVectorPropertyValue[0];
- for (size_t i = 1; i < examinationPeriodVectorPropertyValue.size(); ++i)
- {
- generatedExaminationPeriod.controlPointUIDs.push_back(examinationPeriodVectorPropertyValue[i]);
- }
-
- allExaminationPeriods.push_back(generatedExaminationPeriod);
- }
- }
- return allExaminationPeriods;
-}
-
-mitk::SemanticTypes::InformationTypeVector mitk::RelationStorage::GetAllInformationTypesOfCase(const SemanticTypes::CaseID& caseID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::InformationTypeVector();
- }
- // retrieve a vector property that contains the valid information types of the current case
- VectorProperty<std::string>* informationTypesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("informationtypes"));
- if (nullptr == informationTypesVectorProperty)
- {
- MITK_DEBUG << "Could not find any information types in the storage.";
- return SemanticTypes::InformationTypeVector();
- }
-
- return informationTypesVectorProperty->GetValue();
-}
-
-mitk::SemanticTypes::InformationType mitk::RelationStorage::GetInformationTypeOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::InformationType();
- }
- // retrieve a vector property that contains the information type and the referenced ID of an image (0. information type 1. control point ID)
- VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID));
- if (nullptr == imageVectorProperty)
- {
- MITK_DEBUG << "Could not find the image " << imageID << " in the storage.";
- return SemanticTypes::InformationType();
- }
-
- std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue();
- // an image has to have exactly two values (the information type and the ID of the control point)
- if (imageVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect data storage. Not two (2) values stored.";
- return SemanticTypes::InformationType();
- }
-
- // the first value of the image vector is the information type
- return imageVectorPropertyValue[0];
-}
-
-mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllImageIDsOfCase(const SemanticTypes::CaseID& caseID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::IDVector();
- }
- // retrieve a vector property that contains the valid image-IDs of the current case
- VectorProperty<std::string>* imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images"));
- if (nullptr == imagesVectorProperty)
- {
- MITK_DEBUG << "Could not find any image in the storage.";
- return SemanticTypes::IDVector();
- }
-
- return imagesVectorProperty->GetValue();
-}
-
-mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllImageIDsOfControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::IDVector();
- }
- // retrieve a vector property that contains the valid image-IDs of the current case
- VectorProperty<std::string>* imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images"));
- if (nullptr == imagesVectorProperty)
- {
- MITK_DEBUG << "Could not find any image in the storage.";
- return SemanticTypes::IDVector();
- }
-
- mitk::SemanticTypes::IDVector allImageIDsOfControlPoint;
- std::vector<std::string> imagesVectorPropertyValue = imagesVectorProperty->GetValue();
- for (const auto& imageID : imagesVectorPropertyValue)
- {
- // retrieve a vector property that contains the referenced ID of an image (0. information type 1. control point ID)
- VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID));
- if (nullptr == imageVectorProperty)
- {
- continue;
- }
-
- std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue();
- // an image has to have exactly two values (the information type and the ID of the control point)
- if (imageVectorPropertyValue.size() != 2)
- {
- continue;
- }
-
- // the second value of the image vector is the ID of the referenced control point
- if (imageVectorPropertyValue[1] == controlPoint.UID)
- {
- allImageIDsOfControlPoint.push_back(imageID);
- }
- }
-
- return allImageIDsOfControlPoint;
-}
-
-mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllImageIDsOfInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::IDVector();
- }
- // retrieve a vector property that contains the valid image-IDs of the current case
- VectorProperty<std::string>* imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images"));
- if (nullptr == imagesVectorProperty)
- {
- MITK_DEBUG << "Could not find any image in the storage.";
- return SemanticTypes::IDVector();
- }
-
- mitk::SemanticTypes::IDVector allImageIDsOfInformationType;
- std::vector<std::string> imagesVectorPropertyValue = imagesVectorProperty->GetValue();
- for (const auto& imageID : imagesVectorPropertyValue)
- {
- // retrieve a vector property that contains the referenced ID of an image (0. information type 1. control point ID)
- VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID));
- if (nullptr == imageVectorProperty)
- {
- continue;
- }
-
- std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue();
- // an image has to have exactly two values (the information type and the ID of the control point)
- if (imageVectorPropertyValue.size() != 2)
- {
- continue;
- }
-
- // the first value of the image vector is the ID of the referenced information type
- if (imageVectorPropertyValue[0] == informationType)
- {
- allImageIDsOfInformationType.push_back(imageID);
- }
- }
-
- return allImageIDsOfInformationType;
-}
-
-mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllSegmentationIDsOfCase(const SemanticTypes::CaseID& caseID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::IDVector();
- }
- // retrieve a vector property that contains the valid segmentation-IDs for the current case
- VectorProperty<std::string>* segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations"));
- if (nullptr == segmentationsVectorProperty)
- {
- MITK_DEBUG << "Could not find any segmentation in the storage.";
- return SemanticTypes::IDVector();
- }
-
- return segmentationsVectorProperty->GetValue();
-}
-
-mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllSegmentationIDsOfImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::IDVector();
- }
- // retrieve a vector property that contains the valid segmentation-IDs for the current case
- VectorProperty<std::string>* segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations"));
- if (nullptr == segmentationsVectorProperty)
- {
- MITK_DEBUG << "Could not find any segmentation in the storage.";
- return SemanticTypes::IDVector();
- }
-
- mitk::SemanticTypes::IDVector allSegmentationIDsOfImage;
- std::vector<std::string> segmentationsVectorPropertyValue = segmentationsVectorProperty->GetValue();
- for (const auto& segmentationID : segmentationsVectorPropertyValue)
- {
- // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID)
- VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID));
- if (nullptr == segmentationVectorProperty)
- {
- continue;
- }
-
- std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue();
- // a segmentation has to have exactly two values (the ID of the referenced image and the ID of the referenced lesion)
- if (segmentationVectorPropertyValue.size() != 2)
- {
- continue;
- }
-
- // the first value of the segmentation vector is the ID of the referenced image
- if (segmentationVectorPropertyValue[0] == imageID)
- {
- allSegmentationIDsOfImage.push_back(segmentationID);
- }
- }
-
- return allSegmentationIDsOfImage;
-}
-
-mitk::SemanticTypes::IDVector mitk::RelationStorage::GetAllSegmentationIDsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::IDVector();
- }
- // retrieve a vector property that contains the valid segmentation-IDs for the current case
- VectorProperty<std::string>* segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations"));
- if (nullptr == segmentationsVectorProperty)
- {
- MITK_DEBUG << "Could not find any segmentation in the storage.";
- return SemanticTypes::IDVector();
- }
-
- mitk::SemanticTypes::IDVector allSegmentationIDsOfLesion;
- std::vector<std::string> segmentationsVectorPropertyValue = segmentationsVectorProperty->GetValue();
- for (const auto& segmentationID : segmentationsVectorPropertyValue)
- {
- // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID)
- VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID));
- if (nullptr == segmentationVectorProperty)
- {
- continue;
- }
-
- std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue();
- // a segmentation has to have exactly two values (the ID of the referenced image and the ID of the referenced lesion)
- if (segmentationVectorPropertyValue.size() != 2)
- {
- continue;
- }
-
- // the second value of the segmentation vector is the ID of the referenced lesion
- if (segmentationVectorPropertyValue[1] == lesion.UID)
- {
- allSegmentationIDsOfLesion.push_back(segmentationID);
- }
- }
-
- return allSegmentationIDsOfLesion;
-}
-
-mitk::SemanticTypes::ID mitk::RelationStorage::GetImageIDOfSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return SemanticTypes::ID();
- }
-
- // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID)
- VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID));
- if (nullptr == segmentationVectorProperty)
- {
- MITK_DEBUG << "Could not find the segmentation " << segmentationID << " in the storage.";
- return SemanticTypes::ID();
- }
-
- std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue();
- // the lesion ID of a segmentation is the second value in the vector
- if (segmentationVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect segmentation storage. Not two (2) IDs stored.";
- return SemanticTypes::ID();
- }
-
- return segmentationVectorPropertyValue[0];
-}
-
-std::vector<mitk::SemanticTypes::CaseID> mitk::RelationStorage::GetAllCaseIDs()
-{
- return GetCaseIDs();
-}
-
-bool mitk::RelationStorage::InstanceExists(const SemanticTypes::CaseID& caseID)
-{
- return CaseIDExists(caseID);
-}
-
-void mitk::RelationStorage::AddCase(const SemanticTypes::CaseID& caseID)
-{
- PERSISTENCE_GET_SERVICE_MACRO
- if (nullptr == persistenceService)
- {
- MITK_DEBUG << "Persistence service could not be loaded";
- return;
- }
- // the property list is valid for a certain scenario and contains all the case IDs of the radiological user's MITK session
- std::string listIdentifier = "caseIDs";
- PropertyList::Pointer propertyList = persistenceService->GetPropertyList(listIdentifier);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << listIdentifier << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains all case IDs
- VectorProperty<std::string>::Pointer caseIDsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(listIdentifier));
- std::vector<std::string> caseIDsVectorPropertyValue;
- if (nullptr == caseIDsVectorProperty)
- {
- caseIDsVectorProperty = VectorProperty<std::string>::New();
- }
- else
- {
- caseIDsVectorPropertyValue = caseIDsVectorProperty->GetValue();
- }
-
- auto existingCase = std::find(caseIDsVectorPropertyValue.begin(), caseIDsVectorPropertyValue.end(), caseID);
- if (existingCase != caseIDsVectorPropertyValue.end())
- {
- return;
- }
-
- // add case to the "caseIDs" property list
- caseIDsVectorPropertyValue.push_back(caseID);
- caseIDsVectorProperty->SetValue(caseIDsVectorPropertyValue);
- propertyList->SetProperty(listIdentifier, caseIDsVectorProperty);
-}
-
-void mitk::RelationStorage::AddImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
-
- // retrieve a vector property that contains the valid image-IDs for the current case
- VectorProperty<std::string>::Pointer imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images"));
- std::vector<std::string> imagesVectorPropertyValue;
- if (nullptr == imagesVectorProperty)
- {
- imagesVectorProperty = VectorProperty<std::string>::New();
- }
- else
- {
- imagesVectorPropertyValue = imagesVectorProperty->GetValue();
- }
-
- auto existingImage = std::find(imagesVectorPropertyValue.begin(), imagesVectorPropertyValue.end(), imageID);
- if (existingImage != imagesVectorPropertyValue.end())
- {
- return;
- }
-
- // add image to the "images" property list
- imagesVectorPropertyValue.push_back(imageID);
- imagesVectorProperty->SetValue(imagesVectorPropertyValue);
- propertyList->SetProperty("images", imagesVectorProperty);
-
- // add the image itself
- VectorProperty<std::string>::Pointer imageVectorProperty = VectorProperty<std::string>::New();
- // an image has to have exactly two values (the information type and the ID of the control point)
- std::vector<std::string> imageVectorPropertyValue(2);
- imageVectorProperty->SetValue(imageVectorPropertyValue);
- propertyList->SetProperty(imageID, imageVectorProperty);
-}
-
-void mitk::RelationStorage::RemoveImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
-
- // retrieve a vector property that contains the valid image-IDs for the current case
- VectorProperty<std::string>::Pointer imagesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("images"));
- if (nullptr == imagesVectorProperty)
- {
- MITK_DEBUG << "Could not find any images in the storage.";
- return;
- }
-
- // remove the image reference from the list of all images of the current case
- std::vector<std::string> imagesVectorPropertyValue = imagesVectorProperty->GetValue();
- imagesVectorPropertyValue.erase(std::remove(imagesVectorPropertyValue.begin(), imagesVectorPropertyValue.end(), imageID), imagesVectorPropertyValue.end());
- if (imagesVectorPropertyValue.empty())
- {
- // no more images stored -> remove the images property list
- propertyList->DeleteProperty("images");
- }
- else
- {
- // or store the modified vector value
- imagesVectorProperty->SetValue(imagesVectorPropertyValue);
- }
-
- // remove the image instance itself
- propertyList->DeleteProperty(imageID);
-}
-
-void mitk::RelationStorage::AddSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID, const SemanticTypes::ID& parentID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
-
- // retrieve a vector property that contains the valid segmentation-IDs for the current case
- VectorProperty<std::string>::Pointer segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations"));
- std::vector<std::string> segmentationsVectorPropertyValue;
- if (nullptr == segmentationsVectorProperty)
- {
- segmentationsVectorProperty = VectorProperty<std::string>::New();
- }
- else
- {
- segmentationsVectorPropertyValue = segmentationsVectorProperty->GetValue();
- }
-
- auto existingSegmentation = std::find(segmentationsVectorPropertyValue.begin(), segmentationsVectorPropertyValue.end(), segmentationID);
- if (existingSegmentation != segmentationsVectorPropertyValue.end())
- {
- return;
- }
-
- // add segmentation to the "segmentations" property list
- segmentationsVectorPropertyValue.push_back(segmentationID);
- segmentationsVectorProperty->SetValue(segmentationsVectorPropertyValue);
- propertyList->SetProperty("segmentations", segmentationsVectorProperty);
-
- // add the segmentation itself
- VectorProperty<std::string>::Pointer segmentationVectorProperty = VectorProperty<std::string>::New();
- // a segmentation has to have exactly two values (the ID of the referenced image and the ID of the referenced lesion)
- std::vector<std::string> segmentationVectorPropertyValue(2);
- segmentationVectorPropertyValue[0] = parentID;
- segmentationVectorProperty->SetValue(segmentationVectorPropertyValue);
- propertyList->SetProperty(segmentationID, segmentationVectorProperty);
-}
-
-void mitk::RelationStorage::RemoveSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
-
- // retrieve a vector property that contains the valid segmentation-IDs for the current case
- VectorProperty<std::string>::Pointer segmentationsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("segmentations"));
- if (nullptr == segmentationsVectorProperty)
- {
- MITK_DEBUG << "Could not find any segmentation in the storage.";
- return;
- }
-
- // remove the lesion reference from the list of all lesions of the current case
- std::vector<std::string> segmentationsVectorPropertyValue = segmentationsVectorProperty->GetValue();
- segmentationsVectorPropertyValue.erase(std::remove(segmentationsVectorPropertyValue.begin(), segmentationsVectorPropertyValue.end(), segmentationID), segmentationsVectorPropertyValue.end());
- if (segmentationsVectorPropertyValue.empty())
- {
- // no more segmentations stored -> remove the segmentations property list
- propertyList->DeleteProperty("segmentations");
- }
- else
- {
- // or store the modified vector value
- segmentationsVectorProperty->SetValue(segmentationsVectorPropertyValue);
- }
-
- // remove the lesion instance itself
- propertyList->DeleteProperty(segmentationID);
-}
-
-void mitk::RelationStorage::AddLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid lesion-IDs for the current case
- VectorProperty<std::string>::Pointer lesionsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions"));
- std::vector<std::string> lesionsVectorPropertyValue;
- if (nullptr == lesionsVectorProperty)
- {
- lesionsVectorProperty = VectorProperty<std::string>::New();
- }
- else
- {
- lesionsVectorPropertyValue = lesionsVectorProperty->GetValue();
- }
-
- const auto& existingIndex = std::find(lesionsVectorPropertyValue.begin(), lesionsVectorPropertyValue.end(), lesion.UID);
- if (existingIndex != lesionsVectorPropertyValue.end())
- {
- return;
- }
-
- // add the new lesion id from the given lesion to the vector of all current lesion IDs
- lesionsVectorPropertyValue.push_back(lesion.UID);
- // overwrite the current vector property with the new, extended string vector
- lesionsVectorProperty->SetValue(lesionsVectorPropertyValue);
- propertyList->SetProperty("lesions", lesionsVectorProperty);
-
- // add the lesion with the lesion UID as the key and the lesion information as value
- std::vector<std::string> lesionData;
- lesionData.push_back(lesion.name);
- lesionData.push_back(lesion.lesionClass.UID);
- VectorProperty<std::string>::Pointer newLesionVectorProperty = VectorProperty<std::string>::New();
- newLesionVectorProperty->SetValue(lesionData);
- propertyList->SetProperty(lesion.UID, newLesionVectorProperty);
-
- // add the lesion class with the lesion class UID as key and the class type as value
- std::string lesionClassType = lesion.lesionClass.classType;
- propertyList->SetStringProperty(lesion.lesionClass.UID.c_str(), lesionClassType.c_str());
-}
-
-void mitk::RelationStorage::OverwriteLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid lesion-IDs for the current case
- VectorProperty<std::string>* lesionVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions"));
- if (nullptr == lesionVectorProperty)
- {
- MITK_DEBUG << "Could not find any lesion in the storage.";
- return;
- }
-
- std::vector<std::string> lesionVectorPropertyValue = lesionVectorProperty->GetValue();
- const auto existingLesion = std::find(lesionVectorPropertyValue.begin(), lesionVectorPropertyValue.end(), lesion.UID);
- if (existingLesion != lesionVectorPropertyValue.end())
- {
- // overwrite the referenced lesion class UID with the new, given lesion class data
- std::vector<std::string> lesionData;
- lesionData.push_back(lesion.name);
- lesionData.push_back(lesion.lesionClass.UID);
- VectorProperty<std::string>::Pointer newLesionVectorProperty = VectorProperty<std::string>::New();
- newLesionVectorProperty->SetValue(lesionData);
- propertyList->SetProperty(lesion.UID, newLesionVectorProperty);
-
- // overwrite the lesion class with the lesion class UID as key and the new, given class type as value
- std::string lesionClassType = lesion.lesionClass.classType;
- propertyList->SetStringProperty(lesion.lesionClass.UID.c_str(), lesionClassType.c_str());
- }
- else
- {
- MITK_DEBUG << "Could not find lesion " << lesion.UID << " in the storage. Cannot overwrite the lesion.";
- }
-}
-
-void mitk::RelationStorage::LinkSegmentationToLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID, const SemanticTypes::Lesion& lesion)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid lesion-IDs for the current case
- VectorProperty<std::string>* lesionVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions"));
- if (nullptr == lesionVectorProperty)
- {
- MITK_DEBUG << "Could not find any lesion in the storage.";
- return;
- }
-
- std::vector<std::string> lesionVectorPropertyValue = lesionVectorProperty->GetValue();
- const auto existingLesion = std::find(lesionVectorPropertyValue.begin(), lesionVectorPropertyValue.end(), lesion.UID);
- if (existingLesion != lesionVectorPropertyValue.end())
- {
- // set / overwrite the lesion reference of the given segmentation
- // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID)
- VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID));
- if (nullptr == segmentationVectorProperty)
- {
- MITK_DEBUG << "Could not find the segmentation " << segmentationID << " in the storage. Cannot link segmentation to lesion.";
- return;
- }
-
- std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue();
- if (segmentationVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect segmentation storage. Not two (2) IDs stored.";
- return;
- }
-
- // the lesion ID of a segmentation is the second value in the vector
- segmentationVectorPropertyValue[1] = lesion.UID;
- segmentationVectorProperty->SetValue(segmentationVectorPropertyValue);
- return;
- }
-
- MITK_DEBUG << "Could not find lesion " << lesion.UID << " in the storage. Cannot link segmentation to lesion.";
-}
-
-void mitk::RelationStorage::UnlinkSegmentationFromLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the referenced ID of a segmentation (0. image ID 1. lesion ID)
- VectorProperty<std::string>* segmentationVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(segmentationID));
- if (nullptr == segmentationVectorProperty)
- {
- MITK_DEBUG << "Could not find the segmentation " << segmentationID << " in the storage. Cannot unlink lesion from segmentation.";
- return;
- }
-
- std::vector<std::string> segmentationVectorPropertyValue = segmentationVectorProperty->GetValue();
- // a segmentation has to have exactly two values (the ID of the linked image and the ID of the lesion)
- if (segmentationVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect data storage. Not two (2) values stored.";
- return;
- }
-
- // the second value of the segmentation vector is the ID of the referenced lesion
- // set the lesion reference to an empty string for removal
- segmentationVectorPropertyValue[1] = "";
- segmentationVectorProperty->SetValue(segmentationVectorPropertyValue);
-}
-
-void mitk::RelationStorage::RemoveLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid lesions of the current case
- VectorProperty<std::string>* lesionVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions"));
- if (nullptr == lesionVectorProperty)
- {
- MITK_DEBUG << "Could not find any lesion in the storage.";
- return;
- }
-
- // remove the lesion reference from the list of all lesions of the current case
- std::vector<std::string> lesionsVectorPropertyValue = lesionVectorProperty->GetValue();
- lesionsVectorPropertyValue.erase(std::remove(lesionsVectorPropertyValue.begin(), lesionsVectorPropertyValue.end(), lesion.UID), lesionsVectorPropertyValue.end());
- if (lesionsVectorPropertyValue.empty())
- {
- // no more lesions stored -> remove the lesions property list
- propertyList->DeleteProperty("lesions");
- }
- else
- {
- // or store the modified vector value
- lesionVectorProperty->SetValue(lesionsVectorPropertyValue);
- }
-
- // remove the lesion instance itself
- // the lesion data is stored under the lesion ID
- VectorProperty<std::string>* lesionDataProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(lesion.UID));
- if (nullptr == lesionDataProperty)
- {
- MITK_DEBUG << "Lesion " << lesion.UID << " not found (already removed?). Cannot remove the lesion.";
- return;
- }
-
- std::vector<std::string> lesionData = lesionDataProperty->GetValue();
- // a lesion date has to have exactly two values (the name of the lesion and the UID of the lesion class)
- if (lesionData.size() != 2)
- {
- MITK_DEBUG << "Incorrect lesion data storage. Not two (2) strings of the lesion UID and the lesion name are stored.";
- }
- else
- {
- std::string lesionClassID = lesionData[1];
- RemoveLesionClass(caseID, lesionClassID);
- }
- propertyList->DeleteProperty(lesion.UID);
-}
-
-void mitk::RelationStorage::RemoveLesionClass(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& lesionClassID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
-
- // retrieve a vector property that contains the lesion class
- StringProperty* lesionClassProperty = dynamic_cast<StringProperty*>(propertyList->GetProperty(lesionClassID));
- if (nullptr == lesionClassProperty)
- {
- MITK_DEBUG << "Lesion class " << lesionClassID << " not found (already removed?). Cannot remove the lesion class.";
- return;
- }
-
- // retrieve a vector property that contains the valid lesions of the current case
- VectorProperty<std::string>* lesionVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("lesions"));
- if (nullptr == lesionVectorProperty)
- {
- return;
- }
-
- // check if the lesion class ID is referenced by any other lesion
- std::vector<std::string> lesionsVectorPropertyValue = lesionVectorProperty->GetValue();
- const auto existingLesionClass = std::find_if(lesionsVectorPropertyValue.begin(), lesionsVectorPropertyValue.end(),
- [&propertyList, &lesionClassID](const std::string& lesionID)
- {
- VectorProperty<std::string>* lesionDataProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(lesionID));
- if (nullptr == lesionDataProperty)
- {
- return false;
- }
-
- std::vector<std::string> lesionData = lesionDataProperty->GetValue();
- // a lesion date has to have exactly two values (the name of the lesion and the UID of the lesion class)
- if (lesionData.size() != 2)
- {
- return false;
- }
-
- return lesionData[1] == lesionClassID;
- });
-
- if (existingLesionClass == lesionsVectorPropertyValue.end())
- {
- // lesion class ID not referenced; remove lesion class
- propertyList->DeleteProperty(lesionClassID);
- }
-}
-
-void mitk::RelationStorage::AddControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid controlPoint UIDs for the current case
- VectorProperty<std::string>::Pointer controlPointsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("controlpoints"));
- std::vector<std::string> controlPointsVectorPropertyValue;
- if (nullptr == controlPointsVectorProperty)
- {
- controlPointsVectorProperty = VectorProperty<std::string>::New();
- }
- else
- {
- controlPointsVectorPropertyValue = controlPointsVectorProperty->GetValue();
- }
-
- const auto existingControlPoint = std::find(controlPointsVectorPropertyValue.begin(), controlPointsVectorPropertyValue.end(), controlPoint.UID);
- if (existingControlPoint != controlPointsVectorPropertyValue.end())
- {
- return;
- }
-
- // add the new control point UID from the given control point to the vector of all current control point UIDs
- controlPointsVectorPropertyValue.push_back(controlPoint.UID);
- // overwrite the current vector property with the new, extended string vector
- controlPointsVectorProperty->SetValue(controlPointsVectorPropertyValue);
- propertyList->SetProperty("controlpoints", controlPointsVectorProperty);
-
- // store the control point values (the three integer values of a date)
- std::vector<int> controlPointDate;
- controlPointDate.push_back(controlPoint.date.year());
- controlPointDate.push_back(controlPoint.date.month());
- controlPointDate.push_back(controlPoint.date.day());
-
- VectorProperty<int>::Pointer newControlPointVectorProperty = VectorProperty<int>::New();
- newControlPointVectorProperty->SetValue(controlPointDate);
- propertyList->SetProperty(controlPoint.UID, newControlPointVectorProperty);
-}
-
-void mitk::RelationStorage::LinkImageToControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID, const SemanticTypes::ControlPoint& controlPoint)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid controlPoint UIDs for the current case
- VectorProperty<std::string>* controlPointsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("controlpoints"));
- if (nullptr == controlPointsVectorProperty)
- {
- MITK_DEBUG << "Could not find any control point in the storage.";
- return;
- }
-
- std::vector<std::string> controlPointsVectorPropertyValue = controlPointsVectorProperty->GetValue();
- const auto existingControlPoint = std::find(controlPointsVectorPropertyValue.begin(), controlPointsVectorPropertyValue.end(), controlPoint.UID);
- if (existingControlPoint != controlPointsVectorPropertyValue.end())
- {
- // set / overwrite the control point reference of the given data
- // retrieve a vector property that contains the referenced ID of a image (0. information type 1. control point ID)
- VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID));
- if (nullptr == imageVectorProperty)
- {
- MITK_DEBUG << "Could not find the image " << imageID << " in the storage. Cannot link data to control point.";
- return;
- }
-
- std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue();
- // an image has to have exactly two values (the information type and the ID of the control point)
- if (imageVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect data storage. Not two (2) values stored.";
- return;
- }
-
- // the second value of the image vector is the ID of the referenced control point
- imageVectorPropertyValue[1] = controlPoint.UID;
- imageVectorProperty->SetValue(imageVectorPropertyValue);
- return;
- }
-
- MITK_DEBUG << "Could not find control point " << controlPoint.UID << " in the storage. Cannot link data to control point.";
-}
-
-void mitk::RelationStorage::UnlinkImageFromControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the referenced ID of a date (0. information type 1. control point ID)
- VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID));
- if (nullptr == imageVectorProperty)
- {
- MITK_DEBUG << "Could not find the date " << imageID << " in the storage. Cannot unlink control point from date.";
- return;
- }
-
- std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue();
- // an image has to have exactly two values (the information type and the ID of the control point)
- if (imageVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect data storage. Not two (2) values stored.";
- return;
- }
-
- // the second value of the image vector is the ID of the referenced control point
- // set the control point reference to an empty string for removal
- imageVectorPropertyValue[1] = "";
- imageVectorProperty->SetValue(imageVectorPropertyValue);
-}
-
-void mitk::RelationStorage::RemoveControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid controlPoint UIDs for the current case
- VectorProperty<std::string>* controlPointsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("controlpoints"));
- if (nullptr == controlPointsVectorProperty)
- {
- MITK_DEBUG << "Could not find any control point in the storage.";
- return;
- }
-
- // remove the control point reference from the list of all control points of the current case
- std::vector<std::string> controlPointsVectorPropertyValue = controlPointsVectorProperty->GetValue();
- controlPointsVectorPropertyValue.erase(std::remove(controlPointsVectorPropertyValue.begin(), controlPointsVectorPropertyValue.end(), controlPoint.UID), controlPointsVectorPropertyValue.end());
- if (controlPointsVectorPropertyValue.empty())
- {
- // no more control points stored -> remove the control point property list
- propertyList->DeleteProperty("controlpoints");
- }
- else
- {
- // or store the modified vector value
- controlPointsVectorProperty->SetValue(controlPointsVectorPropertyValue);
- }
-
- // remove the control point instance itself
- propertyList->DeleteProperty(controlPoint.UID);
-}
-
-void mitk::RelationStorage::AddExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid examination period UIDs for the current case
- VectorProperty<std::string>::Pointer examinationPeriodsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("examinationperiods"));
- std::vector<std::string> examinationPeriodsVectorPropertyValue;
- if (nullptr == examinationPeriodsVectorProperty)
- {
- examinationPeriodsVectorProperty = VectorProperty<std::string>::New();
- }
- else
- {
- examinationPeriodsVectorPropertyValue = examinationPeriodsVectorProperty->GetValue();
- }
-
- const auto& existingIndex = std::find(examinationPeriodsVectorPropertyValue.begin(), examinationPeriodsVectorPropertyValue.end(), examinationPeriod.UID);
- if (existingIndex != examinationPeriodsVectorPropertyValue.end())
- {
- return;
- }
-
- // add the new examination period id from the given examination period to the vector of all current examination period UIDs
- examinationPeriodsVectorPropertyValue.push_back(examinationPeriod.UID);
- // overwrite the current vector property with the new, extended string vector
- examinationPeriodsVectorProperty->SetValue(examinationPeriodsVectorPropertyValue);
- propertyList->SetProperty("examinationperiods", examinationPeriodsVectorProperty);
-
- // add the examination period with the UID as the key and the name as as the vector value
- std::vector<std::string> examinationPeriodData;
- examinationPeriodData.push_back(examinationPeriod.name);
- VectorProperty<std::string>::Pointer newExaminationPeriodVectorProperty = VectorProperty<std::string>::New();
- newExaminationPeriodVectorProperty->SetValue(examinationPeriodData);
- propertyList->SetProperty(examinationPeriod.UID, newExaminationPeriodVectorProperty);
-}
-
-void mitk::RelationStorage::RenameExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the data of the given examination period
- VectorProperty<std::string>* examinationPeriodDataVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(examinationPeriod.UID));
- if (nullptr == examinationPeriodDataVectorProperty)
- {
- MITK_DEBUG << "Could not find examination period " << examinationPeriod.UID << " in the storage. Cannot rename the examination period.";
- return;
- }
-
- std::vector<std::string> examinationPeriodDataVectorPropertyValue = examinationPeriodDataVectorProperty->GetValue();
- // an examination period has an arbitrary number of vector values (name and control point UIDs) (at least one for the name)
- if (examinationPeriodDataVectorPropertyValue.size() < 1)
- {
- MITK_DEBUG << "Incorrect examination period storage. At least one (1) name has to be stored.";
- return;
- }
- else
- {
- // set the first vector value - the name
- examinationPeriodDataVectorPropertyValue[0] = examinationPeriod.name;
- // store the modified vector value
- examinationPeriodDataVectorProperty->SetValue(examinationPeriodDataVectorPropertyValue);
- }
-}
-
-void mitk::RelationStorage::AddControlPointToExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
-
- // retrieve a vector property that contains the represented control point UIDs of the given examination period
- VectorProperty<std::string>* controlPointUIDsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(examinationPeriod.UID));
- if (nullptr == controlPointUIDsVectorProperty)
- {
- MITK_DEBUG << "Could not find the examination period " << examinationPeriod.UID << " in the storage. Cannot add the control point to the examination period.";
- return;
- }
-
- std::vector<std::string> controlPointUIDsVectorPropertyValue = controlPointUIDsVectorProperty->GetValue();
- // store the control point UID
- controlPointUIDsVectorPropertyValue.push_back(controlPoint.UID);
- // sort the vector according to the date of the control points referenced by the UIDs
- auto lambda = [&caseID](const SemanticTypes::ID& leftControlPointUID, const SemanticTypes::ID& rightControlPointUID)
- {
- const auto& leftControlPoint = GenerateControlpoint(caseID, leftControlPointUID);
- const auto& rightControlPoint = GenerateControlpoint(caseID, rightControlPointUID);
-
- return leftControlPoint.date <= rightControlPoint.date;
- };
-
- std::sort(controlPointUIDsVectorPropertyValue.begin(), controlPointUIDsVectorPropertyValue.end(), lambda);
- // store the modified and sorted control point UID vector of this examination period
- controlPointUIDsVectorProperty->SetValue(controlPointUIDsVectorPropertyValue);
-}
-
-void mitk::RelationStorage::RemoveControlPointFromExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
-
- // retrieve a vector property that contains the represented control point UIDs of the given examination period
- VectorProperty<std::string>* controlPointUIDsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(examinationPeriod.UID));
- if (nullptr == controlPointUIDsVectorProperty)
- {
- MITK_DEBUG << "Could not find examination period " << examinationPeriod.UID << " in the storage. Cannot add the control point to the examination period.";
- return;
- }
-
- std::vector<std::string> controlPointUIDsVectorPropertyValue = controlPointUIDsVectorProperty->GetValue();
- // an examination period has an arbitrary number of vector values (name and control point UIDs) (at least one for the name)
- if (controlPointUIDsVectorPropertyValue.size() < 2)
- {
- MITK_DEBUG << "Incorrect examination period storage. At least one (1) control point ID has to be stored.";
- return;
- }
- else
- {
- controlPointUIDsVectorPropertyValue.erase(std::remove(controlPointUIDsVectorPropertyValue.begin(), controlPointUIDsVectorPropertyValue.end(), controlPoint.UID), controlPointUIDsVectorPropertyValue.end());
- if (controlPointUIDsVectorPropertyValue.size() < 2)
- {
- RemoveExaminationPeriod(caseID, examinationPeriod);
- }
- else
- {
- // store the modified vector value
- controlPointUIDsVectorProperty->SetValue(controlPointUIDsVectorPropertyValue);
- }
- }
-}
-
-void mitk::RelationStorage::RemoveExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid examination period UIDs for the current case
- VectorProperty<std::string>::Pointer examinationPeriodsVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("examinationperiods"));
- if (nullptr == examinationPeriodsVectorProperty)
- {
- MITK_DEBUG << "Could not find any examination periods in the storage.";
- return;
- }
-
- std::vector<std::string> examinationPeriodsVectorPropertyValue = examinationPeriodsVectorProperty->GetValue();
- examinationPeriodsVectorPropertyValue.erase(std::remove(examinationPeriodsVectorPropertyValue.begin(), examinationPeriodsVectorPropertyValue.end(), examinationPeriod.UID), examinationPeriodsVectorPropertyValue.end());
- if (examinationPeriodsVectorPropertyValue.empty())
- {
- // no more examination periods stored -> remove the examination period property list
- propertyList->DeleteProperty("examinationperiods");
- }
- else
- {
- // or store the modified vector value
- examinationPeriodsVectorProperty->SetValue(examinationPeriodsVectorPropertyValue);
- }
-
- // remove the examination period instance itself
- propertyList->DeleteProperty(examinationPeriod.UID);
-}
-
-void mitk::RelationStorage::AddInformationTypeToImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID, const SemanticTypes::InformationType& informationType)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid information types of the current case
- VectorProperty<std::string>::Pointer informationTypesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("informationtypes"));
- std::vector<std::string> informationTypesVectorPropertyValue;
- if (nullptr == informationTypesVectorProperty)
- {
- informationTypesVectorProperty = VectorProperty<std::string>::New();
- }
- else
- {
- informationTypesVectorPropertyValue = informationTypesVectorProperty->GetValue();
- }
-
- const auto existingInformationType = std::find(informationTypesVectorPropertyValue.begin(), informationTypesVectorPropertyValue.end(), informationType);
- if (existingInformationType == informationTypesVectorPropertyValue.end())
- {
- // at first: add the information type to the storage
- informationTypesVectorPropertyValue.push_back(informationType);
- informationTypesVectorProperty->SetValue(informationTypesVectorPropertyValue);
- propertyList->SetProperty("informationtypes", informationTypesVectorProperty);
- }
-
- // set / overwrite the information type of the given data
- // retrieve a vector property that contains the referenced ID of an image (0. information type 1. control point ID)
- VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID));
- if (nullptr == imageVectorProperty)
- {
- MITK_DEBUG << "Could not find the image " << imageID << " in the storage. Cannot add information type to image.";
- return;
- }
-
- std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue();
- // an image has to have exactly two values (the information type and the ID of the control point)
- if (imageVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect data storage. Not two (2) values stored.";
- return;
- }
-
- // the first value of the image vector is the information type
- imageVectorPropertyValue[0] = informationType;
- imageVectorProperty->SetValue(imageVectorPropertyValue);
-}
-
-void mitk::RelationStorage::RemoveInformationTypeFromImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& imageID)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the referenced ID of an image (0. information type 1. control point ID)
- VectorProperty<std::string>* imageVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty(imageID));
- if (nullptr == imageVectorProperty)
- {
- MITK_DEBUG << "Could not find the image " << imageID << " in the storage. Cannot remove information type from image.";
- return;
- }
-
- std::vector<std::string> imageVectorPropertyValue = imageVectorProperty->GetValue();
- // an image has to have exactly two values (the information type and the ID of the control point)
- if (imageVectorPropertyValue.size() != 2)
- {
- MITK_DEBUG << "Incorrect data storage. Not two (2) values stored.";
- return;
- }
-
- // the first value of the image vector is the information type
- // set the information type to an empty string for removal
- imageVectorPropertyValue[0] = "";
- imageVectorProperty->SetValue(imageVectorPropertyValue);
-}
-
-void mitk::RelationStorage::RemoveInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType)
-{
- PropertyList::Pointer propertyList = GetStorageData(caseID);
- if (nullptr == propertyList)
- {
- MITK_DEBUG << "Could not find the property list " << caseID << " for the current MITK workbench / session.";
- return;
- }
- // retrieve a vector property that contains the valid information types of the current case
- VectorProperty<std::string>* informationTypesVectorProperty = dynamic_cast<VectorProperty<std::string>*>(propertyList->GetProperty("informationtypes"));
- if (nullptr == informationTypesVectorProperty)
- {
- MITK_DEBUG << "Could not find any information type in the storage.";
- return;
- }
-
- std::vector<std::string> informationTypesVectorPropertyValue = informationTypesVectorProperty->GetValue();
- informationTypesVectorPropertyValue.erase(std::remove(informationTypesVectorPropertyValue.begin(), informationTypesVectorPropertyValue.end(), informationType), informationTypesVectorPropertyValue.end());
- if (informationTypesVectorPropertyValue.empty())
- {
- // no more information types stored -> remove the information types property list
- propertyList->DeleteProperty("informationtypes");
- }
- else
- {
- // or store the modified vector value
- informationTypesVectorProperty->SetValue(informationTypesVectorPropertyValue);
- }
-}
diff --git a/Modules/SemanticRelations/src/mitkSemanticRelationsDataStorageAccess.cpp b/Modules/SemanticRelations/src/mitkSemanticRelationsDataStorageAccess.cpp
deleted file mode 100644
index 5994a9a4d7..0000000000
--- a/Modules/SemanticRelations/src/mitkSemanticRelationsDataStorageAccess.cpp
+++ /dev/null
@@ -1,348 +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 "mitkSemanticRelationsDataStorageAccess.h"
-
-// semantic relations module
-#include "mitkControlPointManager.h"
-#include "mitkDICOMHelper.h"
-#include "mitkNodePredicates.h"
-#include "mitkRelationStorage.h"
-#include "mitkSemanticRelationException.h"
-#include "mitkSemanticRelationsInference.h"
-
-// c++
-#include <iterator>
-#include <algorithm>
-
-mitk::SemanticRelationsDataStorageAccess::SemanticRelationsDataStorageAccess(DataStorage* dataStorage)
- : m_DataStorage(dataStorage)
-{
- // nothing here
-}
-
-/************************************************************************/
-/* functions to get instances / attributes */
-/************************************************************************/
-
-mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllSegmentationsOfCase(const SemanticTypes::CaseID& caseID) const
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data storage.";
- }
-
- SemanticTypes::IDVector allSegmentationIDsOfCase = RelationStorage::GetAllSegmentationIDsOfCase(caseID);
- DataNodeVector allSegmentationsOfCase;
- // get all segmentation nodes of the current data storage
- // only those nodes are respected, that are currently held in the data storage
- DataStorage::SetOfObjects::ConstPointer segmentationNodes = dataStorage->GetSubset(NodePredicates::GetSegmentationPredicate());
- for (auto it = segmentationNodes->Begin(); it != segmentationNodes->End(); ++it)
- {
- DataNode* segmentationNode = it->Value();
-
- SemanticTypes::CaseID currentCaseID;
- SemanticTypes::ID segmentationID;
- try
- {
- // find the corresponding segmentation node for the given segmentation ID
- currentCaseID = GetCaseIDFromDataNode(segmentationNode);
- segmentationID = GetIDFromDataNode(segmentationNode);
- }
- catch (SemanticRelationException&)
- {
- // found a segmentation node that is not stored in the semantic relations
- // this segmentation node does not have any DICOM information --> exception thrown
- // continue with the next segmentation to compare IDs
- continue;
- }
-
- if (caseID == currentCaseID && (std::find(allSegmentationIDsOfCase.begin(), allSegmentationIDsOfCase.end(), segmentationID) != allSegmentationIDsOfCase.end()))
- {
- // found current image node in the storage, add it to the return vector
- allSegmentationsOfCase.push_back(segmentationNode);
- }
- }
-
- return allSegmentationsOfCase;
-}
-
-mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllSegmentationsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) const
-{
- if (SemanticRelationsInference::InstanceExists(caseID, lesion))
- {
- // lesion exists, retrieve all case segmentations from the storage
- DataNodeVector allSegmentationsOfLesion = GetAllSegmentationsOfCase(caseID);
-
- // filter all segmentations: check for semantic relation with the given lesion using a lambda function
- auto lambda = [&lesion](DataNode::Pointer segmentation)
- {
- try
- {
- SemanticTypes::Lesion representedLesion = SemanticRelationsInference::GetLesionOfSegmentation(segmentation);
- return lesion.UID != representedLesion.UID;
- }
- catch (const SemanticRelationException&)
- {
- return true;
- }
- };
- allSegmentationsOfLesion.erase(std::remove_if(allSegmentationsOfLesion.begin(), allSegmentationsOfLesion.end(), lambda), allSegmentationsOfLesion.end());
-
- return allSegmentationsOfLesion;
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "Could not find an existing lesion instance for the given caseID " << caseID << " and lesion " << lesion.UID << ".";
- }
-}
-
-mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllImagesOfCase(const SemanticTypes::CaseID& caseID) const
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data storage.";
- }
-
- SemanticTypes::IDVector allImageIDsOfCase = RelationStorage::GetAllImageIDsOfCase(caseID);
- DataNodeVector allImagesOfCase;
- // get all image nodes of the current data storage
- // only those nodes are respected, that are currently held in the data storage
- DataStorage::SetOfObjects::ConstPointer imageNodes = dataStorage->GetSubset(NodePredicates::GetImagePredicate());
- for (auto it = imageNodes->Begin(); it != imageNodes->End(); ++it)
- {
- DataNode* imageNode = it->Value();
-
- SemanticTypes::CaseID currentCaseID;
- SemanticTypes::ID imageID;
- try
- {
- // find the corresponding image node for the given segmentation ID
- currentCaseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException&)
- {
- // found an image node that is not stored in the semantic relations
- // this image node does not have any DICOM information --> exception thrown
- // continue with the next image to compare IDs
- continue;
- }
-
- if (caseID == currentCaseID && (std::find(allImageIDsOfCase.begin(), allImageIDsOfCase.end(), imageID) != allImageIDsOfCase.end()))
- {
- // found current image node in the storage, add it to the return vector
- allImagesOfCase.push_back(imageNode);
- }
- }
-
- return allImagesOfCase;
-}
-
-mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllImagesByID(const SemanticTypes::IDVector& imageIDs) const
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data storage.";
- }
-
- DataNodeVector allImagesOfCase;
- // get all image nodes of the current data storage
- // only those nodes are respected, that are currently held in the data storage
- DataStorage::SetOfObjects::ConstPointer imageNodes = dataStorage->GetSubset(NodePredicates::GetImagePredicate());
- for (auto it = imageNodes->Begin(); it != imageNodes->End(); ++it)
- {
- DataNode* imageNode = it->Value();
-
- SemanticTypes::CaseID currentCaseID;
- SemanticTypes::ID imageID;
- try
- {
- // find the corresponding image node for the given segmentation ID
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException&)
- {
- // found an image node that is not stored in the semantic relations
- // this image node does not have any DICOM information --> exception thrown
- // continue with the next image to compare IDs
- continue;
- }
-
- if (std::find(imageIDs.begin(), imageIDs.end(), imageID) != imageIDs.end())
- {
- // found current image node in the storage, add it to the return vector
- allImagesOfCase.push_back(imageNode);
- }
- }
-
- return allImagesOfCase;
-}
-
-mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllImagesOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) const
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data storage.";
- }
-
- DataNodeVector allImagesOfLesion;
- // 1. get all segmentations that define the lesion
- // 2. retrieve the parent node (source) of the found segmentation node
- DataNodeVector allSegmentationsOfLesion = GetAllSegmentationsOfLesion(caseID, lesion);
- for (const auto& segmentationNode : allSegmentationsOfLesion)
- {
- // get parent node of the current segmentation node with the node predicate
- DataStorage::SetOfObjects::ConstPointer parentNodes = dataStorage->GetSources(segmentationNode, NodePredicates::GetImagePredicate(), false);
- for (auto it = parentNodes->Begin(); it != parentNodes->End(); ++it)
- {
- DataNode::Pointer dataNode = it->Value();
- allImagesOfLesion.push_back(it->Value());
- }
- }
-
- std::sort(allImagesOfLesion.begin(), allImagesOfLesion.end());
- allImagesOfLesion.erase(std::unique(allImagesOfLesion.begin(), allImagesOfLesion.end()), allImagesOfLesion.end());
- return allImagesOfLesion;
-}
-
-mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllSpecificImages(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType) const
-{
- if (SemanticRelationsInference::InstanceExists(caseID, controlPoint))
- {
- if (SemanticRelationsInference::InstanceExists(caseID, informationType))
- {
- // control point exists, information type exists, retrieve all images from the storage
- DataNodeVector allImagesOfCase = GetAllImagesOfCase(caseID);
- // filter all images to remove the ones with a different control point and information type using a lambda function
- auto lambda = [&controlPoint, &informationType](DataNode::Pointer imageNode)
- {
- return (informationType != SemanticRelationsInference::GetInformationTypeOfImage(imageNode))
- || (controlPoint.date != SemanticRelationsInference::GetControlPointOfImage(imageNode).date);
- };
-
- allImagesOfCase.erase(std::remove_if(allImagesOfCase.begin(), allImagesOfCase.end(), lambda), allImagesOfCase.end());
-
- return allImagesOfCase;
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "Could not find an existing information type for the given caseID " << caseID << " and information type " << informationType << ".";
- }
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "Could not find an existing control point for the given caseID " << caseID << " and control point " << controlPoint.UID << ".";
- }
-}
-
-mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllSpecificImages(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType, const SemanticTypes::ExaminationPeriod& examinationPeriod) const
-{
- if (SemanticRelationsInference::InstanceExists(caseID, informationType))
- {
- if (SemanticRelationsInference::InstanceExists(caseID, examinationPeriod))
- {
- // examination period exists, information type exists, retrieve all imageIDs from the storage
- auto allImageIDsOfExaminationPeriod = SemanticRelationsInference::GetAllImageIDsOfExaminationPeriod(caseID, examinationPeriod);
- // filter all images to remove the ones with a different information type using a lambda function
- auto lambda = [&caseID, &informationType](SemanticTypes::ID imageID)
- {
- return (informationType != RelationStorage::GetInformationTypeOfImage(caseID, imageID));
- };
-
- allImageIDsOfExaminationPeriod.erase(std::remove_if(allImageIDsOfExaminationPeriod.begin(), allImageIDsOfExaminationPeriod.end(), lambda), allImageIDsOfExaminationPeriod.end());
-
- auto allImagesOfExaminationPeriod = GetAllImagesByID(allImageIDsOfExaminationPeriod);
- return allImagesOfExaminationPeriod;
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "Could not find an existing examination period for the given caseID " << caseID << " and examination period " << examinationPeriod.name << ".";
- }
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "Could not find an existing information type for the given caseID " << caseID << " and information type " << informationType << ".";
- }
-}
-
-mitk::SemanticRelationsDataStorageAccess::DataNodeVector mitk::SemanticRelationsDataStorageAccess::GetAllSpecificSegmentations(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType) const
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- mitkThrow() << "Not a valid data storage.";
- }
-
- DataNodeVector allSpecificImages;
- try
- {
- allSpecificImages = GetAllSpecificImages(caseID, controlPoint, informationType);
-
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot get the specific segmentation.";
- }
-
- DataNodeVector allSpecificSegmentations;
- for (const auto& imageNode : allSpecificImages)
- {
- DataStorage::SetOfObjects::ConstPointer segmentationNodes = dataStorage->GetDerivations(imageNode, NodePredicates::GetSegmentationPredicate(), false);
- for (auto it = segmentationNodes->Begin(); it != segmentationNodes->End(); ++it)
- {
- allSpecificSegmentations.push_back(it->Value());
- }
- }
-
- return allSpecificSegmentations;
-}
-
-mitk::DataNode::Pointer mitk::SemanticRelationsDataStorageAccess::GetSpecificSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint,
- const SemanticTypes::InformationType& informationType, const SemanticTypes::Lesion& lesion) const
-{
- if (m_DataStorage.IsExpired())
- {
- mitkThrow() << "Not a valid data storage.";
- }
-
- DataNodeVector allSpecificSegmentations;
- try
- {
- allSpecificSegmentations = GetAllSpecificSegmentations(caseID, controlPoint, informationType);
-
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot get the specific segmentation.";
- }
-
- for (const auto& segmentationNode : allSpecificSegmentations)
- {
- SemanticTypes::Lesion representedLesion = SemanticRelationsInference::GetLesionOfSegmentation(segmentationNode);
- if (representedLesion.UID == lesion.UID)
- {
- return segmentationNode;
- }
- }
-
- return mitk::DataNode::Pointer();
-}
diff --git a/Modules/SemanticRelations/src/mitkSemanticRelationsInference.cpp b/Modules/SemanticRelations/src/mitkSemanticRelationsInference.cpp
deleted file mode 100644
index af3bdfadb3..0000000000
--- a/Modules/SemanticRelations/src/mitkSemanticRelationsInference.cpp
+++ /dev/null
@@ -1,582 +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 "mitkSemanticRelationsInference.h"
-
-// semantic relations module
-#include "mitkControlPointManager.h"
-#include "mitkDICOMHelper.h"
-#include "mitkNodePredicates.h"
-#include "mitkRelationStorage.h"
-#include "mitkSemanticRelationException.h"
-
-/************************************************************************/
-/* functions to get instances / attributes */
-/************************************************************************/
-
-mitk::SemanticTypes::LesionClassVector mitk::SemanticRelationsInference::GetAllLesionClassesOfCase(const SemanticTypes::CaseID& caseID)
-{
- SemanticTypes::LesionVector allLesionsOfCase = RelationStorage::GetAllLesionsOfCase(caseID);
- SemanticTypes::LesionClassVector allLesionClassesOfCase;
-
- for (const auto& lesion : allLesionsOfCase)
- {
- allLesionClassesOfCase.push_back(lesion.lesionClass);
- }
-
- // remove duplicate entries
- auto lessThan = [](const SemanticTypes::LesionClass& lesionClassLeft, const SemanticTypes::LesionClass& lesionClassRight)
- {
- return lesionClassLeft.UID < lesionClassRight.UID;
- };
-
- auto equal = [](const SemanticTypes::LesionClass& lesionClassLeft, const SemanticTypes::LesionClass& lesionClassRight)
- {
- return lesionClassLeft.UID == lesionClassRight.UID;
- };
-
- std::sort(allLesionClassesOfCase.begin(), allLesionClassesOfCase.end(), lessThan);
- allLesionClassesOfCase.erase(std::unique(allLesionClassesOfCase.begin(), allLesionClassesOfCase.end(), equal), allLesionClassesOfCase.end());
-
- return allLesionClassesOfCase;
-}
-
-mitk::SemanticTypes::Lesion mitk::SemanticRelationsInference::GetLesionOfSegmentation(const DataNode* segmentationNode)
-{
- if (nullptr == segmentationNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid segmentation data node.";
- }
-
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID segmentationID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(segmentationNode);
- segmentationID = GetIDFromDataNode(segmentationNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot get the lesion of the given segmentation data node.";
- }
-
- return RelationStorage::GetLesionOfSegmentation(caseID, segmentationID);
-}
-
-mitk::SemanticTypes::LesionVector mitk::SemanticRelationsInference::GetAllLesionsOfImage(const DataNode* imageNode)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID imageID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot get all lesions of the given image data node.";
- }
-
- SemanticTypes::LesionVector allLesionsOfImage;
- // 1. get all segmentations that are connected to the given image
- // 2. get the lesion of each segmentation
- // 3. guarantee uniqueness of lesions
- SemanticTypes::IDVector allSegmentationIDsOfImage = RelationStorage::GetAllSegmentationIDsOfImage(caseID, imageID);
- for (const auto& segmentationID : allSegmentationIDsOfImage)
- {
- // get represented lesion of the current segmentation
- SemanticTypes::Lesion representedLesion = RelationStorage::GetLesionOfSegmentation(caseID, segmentationID);
- if (!representedLesion.UID.empty())
- {
- allLesionsOfImage.push_back(representedLesion);
- }
- }
-
- // remove duplicate entries
- auto lessThan = [](const SemanticTypes::Lesion& lesionLeft, const SemanticTypes::Lesion& lesionRight)
- {
- return lesionLeft.UID < lesionRight.UID;
- };
-
- auto equal = [](const SemanticTypes::Lesion& lesionLeft, const SemanticTypes::Lesion& lesionRight)
- {
- return lesionLeft.UID == lesionRight.UID;
- };
-
- std::sort(allLesionsOfImage.begin(), allLesionsOfImage.end(), lessThan);
- allLesionsOfImage.erase(std::unique(allLesionsOfImage.begin(), allLesionsOfImage.end(), equal), allLesionsOfImage.end());
-
- return allLesionsOfImage;
-}
-
-mitk::SemanticTypes::LesionVector mitk::SemanticRelationsInference::GetAllLesionsOfControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::LesionVector allLesions = RelationStorage::GetAllLesionsOfCase(caseID);
-
- // filter the lesions: use only those, where the associated data is connected to image data that refers to the given control point using a lambda function
- auto lambda = [&caseID, &controlPoint](const SemanticTypes::Lesion& lesion)
- {
- return !SpecificImageExists(caseID, lesion, controlPoint);
- };
-
- allLesions.erase(std::remove_if(allLesions.begin(), allLesions.end(), lambda), allLesions.end());
-
- return allLesions;
-}
-
-mitk::SemanticTypes::LesionVector mitk::SemanticRelationsInference::GetAllLesionsOfInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType)
-{
- SemanticTypes::LesionVector allLesions = RelationStorage::GetAllLesionsOfCase(caseID);
-
- // filter the lesions: use only those, where the associated data is connected to image data that refers to the given information type using a lambda function
- auto lambda = [&caseID, &informationType](const SemanticTypes::Lesion& lesion)
- {
- return !SpecificImageExists(caseID, lesion, informationType);
- };
-
- allLesions.erase(std::remove_if(allLesions.begin(), allLesions.end(), lambda), allLesions.end());
-
- return allLesions;
-}
-
-mitk::SemanticTypes::LesionVector mitk::SemanticRelationsInference::GetAllSpecificLesions(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType)
-{
- auto allLesionsOfControlPoint = GetAllLesionsOfControlPoint(caseID, controlPoint);
- auto allLesionsOfInformationType = GetAllLesionsOfInformationType(caseID, informationType);
- SemanticTypes::LesionVector allLesionsIntersection;
-
- auto lessThan = [](const SemanticTypes::Lesion& lesionLeft, const SemanticTypes::Lesion& lesionRight)
- {
- return lesionLeft.UID < lesionRight.UID;
- };
-
- std::sort(allLesionsOfControlPoint.begin(), allLesionsOfControlPoint.end(), lessThan);
- std::sort(allLesionsOfInformationType.begin(), allLesionsOfInformationType.end(), lessThan);
- SemanticTypes::IDVector allImageIDsIntersection;
- // set_intersection removes duplicated nodes
- std::set_intersection(allLesionsOfControlPoint.begin(), allLesionsOfControlPoint.end(),
- allLesionsOfInformationType.begin(), allLesionsOfInformationType.end(),
- std::back_inserter(allLesionsIntersection), lessThan);
-
- return allLesionsIntersection;
-}
-
-bool mitk::SemanticRelationsInference::IsRepresentingALesion(const DataNode* segmentationNode)
-{
- SemanticTypes::Lesion representedLesion;
- try
- {
- representedLesion = GetLesionOfSegmentation(segmentationNode);
- }
- catch (const SemanticRelationException&)
- {
- return false;
- }
-
- return !representedLesion.UID.empty();
-}
-
-bool mitk::SemanticRelationsInference::IsRepresentingALesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::ID& segmentationID)
-{
- SemanticTypes::Lesion representedLesion = RelationStorage::GetLesionOfSegmentation(caseID, segmentationID);
- return !representedLesion.UID.empty();
-}
-
-bool mitk::SemanticRelationsInference::IsLesionPresent(const SemanticTypes::Lesion& lesion, const DataNode* dataNode)
-{
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID dataNodeID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(dataNode);
- dataNodeID = GetIDFromDataNode(dataNode);
- }
- catch (const SemanticRelationException&)
- {
- return false;
- }
-
- if (NodePredicates::GetImagePredicate()->CheckNode(dataNode))
- {
- return IsLesionPresentOnImage(caseID, lesion, dataNodeID);
- }
-
- if (NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
- {
- return IsLesionPresentOnSegmentation(caseID, lesion, dataNodeID);
- }
-
- return false;
-}
-
-bool mitk::SemanticRelationsInference::IsLesionPresentOnImage(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::ID& imageID)
-{
- SemanticTypes::IDVector allImageIDsOfLesion;
- try
- {
- allImageIDsOfLesion = GetAllImageIDsOfLesion(caseID, lesion);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot get all image IDs of the given lesion to determine the lesion presence.";
- }
-
- for (const auto& imageIDOfLesion : allImageIDsOfLesion)
- {
- if (imageIDOfLesion == imageID)
- {
- return true;
- }
- }
-
- return false;
-}
-
-bool mitk::SemanticRelationsInference::IsLesionPresentOnSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::ID& segmentationID)
-{
- const auto representedLesion = RelationStorage::GetLesionOfSegmentation(caseID, segmentationID);
- return lesion.UID == representedLesion.UID;
-}
-
-bool mitk::SemanticRelationsInference::IsLesionPresentAtControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::IDVector allImageIDsOfLesion;
- try
- {
- allImageIDsOfLesion = GetAllImageIDsOfLesion(caseID, lesion);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot get all image IDs of the given lesion to determine the lesion presence.";
- }
-
- for (const auto& imageIDOfLesion : allImageIDsOfLesion)
- {
- auto imageControlPoint = RelationStorage::GetControlPointOfImage(caseID, imageIDOfLesion);
- if (imageControlPoint.date == controlPoint.date)
- {
- return true;
- }
- }
-
- return false;
-}
-
-bool mitk::SemanticRelationsInference::InstanceExists(const DataNode* dataNode)
-{
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID dataNodeID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(dataNode);
- dataNodeID = GetIDFromDataNode(dataNode);
- }
- catch (const SemanticRelationException&)
- {
- return false;
- }
-
- if (NodePredicates::GetImagePredicate()->CheckNode(dataNode))
- {
- SemanticTypes::IDVector allImageIDsOfCase = RelationStorage::GetAllImageIDsOfCase(caseID);
- return std::find(allImageIDsOfCase.begin(), allImageIDsOfCase.end(), dataNodeID) != allImageIDsOfCase.end();
- }
-
- if (NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
- {
- SemanticTypes::IDVector allSegmentationIDsOfCase = RelationStorage::GetAllSegmentationIDsOfCase(caseID);
- return std::find(allSegmentationIDsOfCase.begin(), allSegmentationIDsOfCase.end(), dataNodeID) != allSegmentationIDsOfCase.end();
- }
-
- return false;
-}
-
-bool mitk::SemanticRelationsInference::InstanceExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- SemanticTypes::LesionVector allLesions = RelationStorage::GetAllLesionsOfCase(caseID);
-
- // filter all lesions: check for equality with the given lesion using a lambda function
- auto lambda = [&lesion](const SemanticTypes::Lesion& currentLesion)
- {
- return currentLesion.UID == lesion.UID;
- };
-
- const auto existingLesion = std::find_if(allLesions.begin(), allLesions.end(), lambda);
-
- return existingLesion != allLesions.end();
-}
-
-mitk::SemanticTypes::IDVector mitk::SemanticRelationsInference::GetAllImageIDsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- if (!InstanceExists(caseID, lesion))
- {
- mitkThrowException(SemanticRelationException) << "Could not find an existing lesion instance for the given caseID " << caseID << " and lesion " << lesion.UID << ".";
- }
-
- SemanticTypes::IDVector allImageIDsOfLesion;
- // 1. get all segmentations that define the lesion
- // 2. get the parentID (imageID) of each segmentation
- // 3. guarantee uniqueness of image IDs
- SemanticTypes::IDVector allSegmentationIDsOfLesion = RelationStorage::GetAllSegmentationIDsOfLesion(caseID, lesion);
- for (const auto& segmentationID : allSegmentationIDsOfLesion)
- {
- // get parent ID of the current segmentation ID
- SemanticTypes::ID imageID = RelationStorage::GetImageIDOfSegmentation(caseID, segmentationID);
- if(!imageID.empty())
- {
- allImageIDsOfLesion.push_back(imageID);
- }
- }
-
- std::sort(allImageIDsOfLesion.begin(), allImageIDsOfLesion.end());
- allImageIDsOfLesion.erase(std::unique(allImageIDsOfLesion.begin(), allImageIDsOfLesion.end()), allImageIDsOfLesion.end());
-
- return allImageIDsOfLesion;
-}
-
-mitk::SemanticTypes::IDVector mitk::SemanticRelationsInference::GetAllImageIDsOfExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- if (!InstanceExists(caseID, examinationPeriod))
- {
- mitkThrowException(SemanticRelationException) << "Could not find an existing examination period for the given caseID " << caseID << " and examination period " << examinationPeriod.name << ".";
- }
-
- SemanticTypes::IDVector allImageIDsOfExaminationPeriod;
- // 1. get all control point UIDs of the examination period
- // 2. get all images of each control points to find all images of the examination period
- SemanticTypes::ControlPoint controlPoint;
- for (const auto& controlPointUID : examinationPeriod.controlPointUIDs)
- {
- controlPoint = GetControlPointByUID(caseID, controlPointUID);
- auto allImageIDsOfControlPoint = RelationStorage::GetAllImageIDsOfControlPoint(caseID, controlPoint);
- allImageIDsOfExaminationPeriod.insert(allImageIDsOfExaminationPeriod.end(), allImageIDsOfControlPoint.begin(), allImageIDsOfControlPoint.end());
- }
-
- return allImageIDsOfExaminationPeriod;
-}
-
-mitk::SemanticTypes::ControlPoint mitk::SemanticRelationsInference::GetControlPointOfImage(const DataNode* imageNode)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid data node.";
- }
-
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID imageID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot get the control point of the given image data node.";
- }
-
- return RelationStorage::GetControlPointOfImage(caseID, imageID);
-}
-
-mitk::SemanticTypes::ControlPointVector mitk::SemanticRelationsInference::GetAllControlPointsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- SemanticTypes::ControlPointVector allControlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
-
- // filter the control points: use only those, where the associated image data has a segmentation that refers to the given lesion using a lambda function
- auto lambda = [&caseID, &lesion](const SemanticTypes::ControlPoint& controlPoint)
- {
- return !SpecificImageExists(caseID, lesion, controlPoint);
- };
-
- allControlPoints.erase(std::remove_if(allControlPoints.begin(), allControlPoints.end(), lambda), allControlPoints.end());
-
- return allControlPoints;
-}
-
-mitk::SemanticTypes::ControlPointVector mitk::SemanticRelationsInference::GetAllControlPointsOfInformationType(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType)
-{
- SemanticTypes::ControlPointVector allControlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
-
- // filter the control points: use only those, where the associated image data refers to the given information type using a lambda function
- auto lambda = [&caseID, &informationType](const SemanticTypes::ControlPoint& controlPoint)
- {
- return !SpecificImageExists(caseID, informationType, controlPoint);
- };
-
- allControlPoints.erase(std::remove_if(allControlPoints.begin(), allControlPoints.end(), lambda), allControlPoints.end());
-
- return allControlPoints;
-}
-
-bool mitk::SemanticRelationsInference::InstanceExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::ControlPointVector allControlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
-
- // filter all control points: check for equality with the given control point using a lambda function
- auto lambda = [&controlPoint](const SemanticTypes::ControlPoint& currentControlPoint) { return currentControlPoint.UID == controlPoint.UID; };
- const auto existingControlPoint = std::find_if(allControlPoints.begin(), allControlPoints.end(), lambda);
-
- if (existingControlPoint != allControlPoints.end())
- {
- return true;
- }
- else
- {
- return false;
- }
-}
-
-bool mitk::SemanticRelationsInference::InstanceExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- SemanticTypes::ExaminationPeriodVector allExaminationPeriods = RelationStorage::GetAllExaminationPeriodsOfCase(caseID);
-
- // filter all examination periods: check for equality with the given examination period using a lambda function
- auto lambda = [&examinationPeriod](const SemanticTypes::ExaminationPeriod& currentExaminationPeriod) { return currentExaminationPeriod.UID == examinationPeriod.UID; };
- const auto existingExaminationPeriod = std::find_if(allExaminationPeriods.begin(), allExaminationPeriods.end(), lambda);
-
- if (existingExaminationPeriod != allExaminationPeriods.end())
- {
- return true;
- }
- else
- {
- return false;
- }
-}
-
-mitk::SemanticTypes::InformationType mitk::SemanticRelationsInference::GetInformationTypeOfImage(const DataNode* imageNode)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID imageID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot get the information type of the given image data node.";
- }
-
- return RelationStorage::GetInformationTypeOfImage(caseID, imageID);
-}
-
-mitk::SemanticTypes::InformationTypeVector mitk::SemanticRelationsInference::GetAllInformationTypesOfControlPoint(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::InformationTypeVector allInformationTypes = RelationStorage::GetAllInformationTypesOfCase(caseID);
-
- // filter the information types: use only those, where the associated data refers to the given control point using a lambda function
- auto lambda = [&caseID, &controlPoint](const SemanticTypes::InformationType& informationType)
- {
- return !SpecificImageExists(caseID, informationType, controlPoint);
- };
-
- allInformationTypes.erase(std::remove_if(allInformationTypes.begin(), allInformationTypes.end(), lambda), allInformationTypes.end());
-
- return allInformationTypes;
-}
-
-bool mitk::SemanticRelationsInference::InstanceExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType)
-{
- SemanticTypes::InformationTypeVector allInformationTypes = RelationStorage::GetAllInformationTypesOfCase(caseID);
-
- // filter all information types: check for equality with the given information type using a lambda function
- auto lambda = [&informationType](const SemanticTypes::InformationType& currentInformationType) { return currentInformationType == informationType; };
- const auto existingInformationType = std::find_if(allInformationTypes.begin(), allInformationTypes.end(), lambda);
-
- if (existingInformationType != allInformationTypes.end())
- {
- return true;
- }
- else
- {
- return false;
- }
-}
-
-bool mitk::SemanticRelationsInference::SpecificImageExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::InformationType& informationType)
-{
- SemanticTypes::IDVector allImageIDsOfLesion;
- try
- {
- allImageIDsOfLesion = GetAllImageIDsOfLesion(caseID, lesion);
- }
- catch (const SemanticRelationException&)
- {
- return false;
- }
-
- SemanticTypes::IDVector allImageIDsOfInformationType = RelationStorage::GetAllImageIDsOfInformationType(caseID, informationType);
-
- std::sort(allImageIDsOfLesion.begin(), allImageIDsOfLesion.end());
- std::sort(allImageIDsOfInformationType.begin(), allImageIDsOfInformationType.end());
- SemanticTypes::IDVector allImageIDsIntersection;
- // set_intersection removes duplicated nodes, since 'GetAllImageIDsOfInformationType' only contains at most one of each node
- std::set_intersection(allImageIDsOfLesion.begin(), allImageIDsOfLesion.end(),
- allImageIDsOfInformationType.begin(), allImageIDsOfInformationType.end(),
- std::back_inserter(allImageIDsIntersection));
-
- // if the vector of intersecting image IDs is empty, the information type does not contain the lesion
- return !allImageIDsIntersection.empty();
-}
-
-bool mitk::SemanticRelationsInference::SpecificImageExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::IDVector allImageIDsOfLesion;
- try
- {
- allImageIDsOfLesion = GetAllImageIDsOfLesion(caseID, lesion);
- }
- catch (const SemanticRelationException&)
- {
- return false;
- }
-
- SemanticTypes::IDVector allImageIDsOfControlPoint = RelationStorage::GetAllImageIDsOfControlPoint(caseID, controlPoint);
-
- std::sort(allImageIDsOfLesion.begin(), allImageIDsOfLesion.end());
- std::sort(allImageIDsOfControlPoint.begin(), allImageIDsOfControlPoint.end());
- SemanticTypes::IDVector allImageIDsIntersection;
- // set_intersection removes duplicated nodes, since 'GetAllImageIDsOfControlPoint' only contains at most one of each node
- std::set_intersection(allImageIDsOfLesion.begin(), allImageIDsOfLesion.end(),
- allImageIDsOfControlPoint.begin(), allImageIDsOfControlPoint.end(),
- std::back_inserter(allImageIDsIntersection));
-
- // if the vector of intersecting image IDs is empty, the control point does not contain the lesion
- return !allImageIDsIntersection.empty();
-}
-
-bool mitk::SemanticRelationsInference::SpecificImageExists(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType, const SemanticTypes::ControlPoint& controlPoint)
-{
- SemanticTypes::IDVector allImageIDsOfInformationType = RelationStorage::GetAllImageIDsOfInformationType(caseID, informationType);
- SemanticTypes::IDVector allImageIDsOfControlPoint = RelationStorage::GetAllImageIDsOfControlPoint(caseID, controlPoint);
-
- std::sort(allImageIDsOfInformationType.begin(), allImageIDsOfInformationType.end());
- std::sort(allImageIDsOfControlPoint.begin(), allImageIDsOfControlPoint.end());
- SemanticTypes::IDVector allImageIDsIntersection;
- // set_intersection removes duplicated nodes
- std::set_intersection(allImageIDsOfInformationType.begin(), allImageIDsOfInformationType.end(),
- allImageIDsOfControlPoint.begin(), allImageIDsOfControlPoint.end(),
- std::back_inserter(allImageIDsIntersection));
-
- // if the vector of intersecting image IDs is empty no image exists for the given information type and control point
- return !allImageIDsIntersection.empty();
-}
diff --git a/Modules/SemanticRelations/src/mitkSemanticRelationsIntegration.cpp b/Modules/SemanticRelations/src/mitkSemanticRelationsIntegration.cpp
deleted file mode 100644
index 935bc10202..0000000000
--- a/Modules/SemanticRelations/src/mitkSemanticRelationsIntegration.cpp
+++ /dev/null
@@ -1,606 +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 "mitkSemanticRelationsIntegration.h"
-
-// semantic relations module
-#include "mitkControlPointManager.h"
-#include "mitkDICOMHelper.h"
-#include "mitkNodePredicates.h"
-#include "mitkRelationStorage.h"
-#include "mitkSemanticRelationException.h"
-#include "mitkSemanticRelationsInference.h"
-#include "mitkUIDGeneratorBoost.h"
-
-// multi label module
-#include <mitkLabelSetImage.h>
-
-// c++
-#include <iterator>
-#include <algorithm>
-
-std::vector<mitk::ISemanticRelationsObserver*> mitk::SemanticRelationsIntegration::m_ObserverVector;
-
-void mitk::SemanticRelationsIntegration::AddObserver(ISemanticRelationsObserver* observer)
-{
- std::vector<ISemanticRelationsObserver*>::iterator existingObserver = std::find(m_ObserverVector.begin(), m_ObserverVector.end(), observer);
- if (existingObserver != m_ObserverVector.end())
- {
- // no need to add the already existing observer
- return;
- }
-
- m_ObserverVector.push_back(observer);
-}
-
-void mitk::SemanticRelationsIntegration::RemoveObserver(ISemanticRelationsObserver* observer)
-{
- m_ObserverVector.erase(std::remove(m_ObserverVector.begin(), m_ObserverVector.end(), observer), m_ObserverVector.end());
-}
-
-/************************************************************************/
-/* functions to add / remove instances / attributes */
-/************************************************************************/
-
-void mitk::SemanticRelationsIntegration::AddImage(const DataNode* imageNode)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID;
- SemanticTypes::ID imageID;
- SemanticTypes::InformationType informationType;
- SemanticTypes::ControlPoint controlPoint;
- try // retrieve information
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
-
- informationType = GetDICOMModalityFromDataNode(imageNode);
- controlPoint = GenerateControlPoint(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot add the given image data node.";
- }
-
- try // add and set information
- {
- RelationStorage::AddCase(caseID);
- RelationStorage::AddImage(caseID, imageID);
-
- AddInformationTypeToImage(imageNode, informationType);
- SetControlPointOfImage(imageNode, controlPoint);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot add the given image data node.";
- }
-}
-
-void mitk::SemanticRelationsIntegration::RemoveImage(const DataNode* imageNode)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID;
- SemanticTypes::ID imageID;
- try // retrieve information
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot remove the given image data node.";
- }
-
- try
- {
- RemoveInformationTypeFromImage(imageNode);
- UnlinkImageFromControlPoint(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot remove the given image data node.";
- }
-
- RelationStorage::RemoveImage(caseID, imageID);
- NotifyObserver(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::AddLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- if (SemanticRelationsInference::InstanceExists(caseID, lesion))
- {
- mitkThrowException(SemanticRelationException) << "The lesion " << lesion.UID << " to add already exists for the given case.";
- }
-
- RelationStorage::AddLesion(caseID, lesion);
- NotifyObserver(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::OverwriteLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- if (SemanticRelationsInference::InstanceExists(caseID, lesion))
- {
- RelationStorage::OverwriteLesion(caseID, lesion);
- NotifyObserver(caseID);
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "The lesion " << lesion.UID << " to overwrite does not exist for the given case.";
- }
-}
-
-void mitk::SemanticRelationsIntegration::AddLesionAndLinkSegmentation(const DataNode* segmentationNode, const SemanticTypes::Lesion& lesion)
-{
- if (nullptr == segmentationNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid segmentation data node.";
- }
-
- SemanticTypes::CaseID caseID;
- try
- {
- caseID = GetCaseIDFromDataNode(segmentationNode);
- AddLesion(caseID, lesion);
- LinkSegmentationToLesion(segmentationNode, lesion);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot add given lesion and link the given segmentation data node.";
- }
-
- NotifyObserver(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::RemoveLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion)
-{
- if (SemanticRelationsInference::InstanceExists(caseID, lesion))
- {
- SemanticTypes::IDVector allSegmentationIDsOfLesion = RelationStorage::GetAllSegmentationIDsOfLesion(caseID, lesion);
- if (allSegmentationIDsOfLesion.empty())
- {
- // no more segmentations are linked to the specific lesion
- // the lesion can be removed from the storage
- RelationStorage::RemoveLesion(caseID, lesion);
- NotifyObserver(caseID);
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "The lesion " << lesion.UID << " to remove is still referred to by a segmentation node. Lesion will not be removed.";
- }
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "The lesion " << lesion.UID << " to remove does not exist for the given case.";
- }
-}
-
-void mitk::SemanticRelationsIntegration::AddSegmentation(const DataNode* segmentationNode, const DataNode* parentNode)
-{
- if (nullptr == segmentationNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid segmentation data node.";
- }
-
- if (nullptr == parentNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid parent data node.";
- }
-
- SemanticTypes::CaseID caseID;
- SemanticTypes::ID segmentationNodeID;
- SemanticTypes::ID parentNodeID;
- try
- {
- caseID = GetCaseIDFromDataNode(segmentationNode);
- segmentationNodeID = GetIDFromDataNode(segmentationNode);
- parentNodeID = GetIDFromDataNode(parentNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot add the given segmentation data node.";
- }
-
- RelationStorage::AddSegmentation(caseID, segmentationNodeID, parentNodeID);
- NotifyObserver(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::LinkSegmentationToLesion(const DataNode* segmentationNode, const SemanticTypes::Lesion& lesion)
-{
- if (nullptr == segmentationNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid segmentation data node.";
- }
-
- SemanticTypes::CaseID caseID;
- SemanticTypes::ID segmentationID;
- try
- {
- caseID = GetCaseIDFromDataNode(segmentationNode);
- segmentationID = GetIDFromDataNode(segmentationNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot link the given segmentation data node to the given lesion.";
- }
-
- if (SemanticRelationsInference::InstanceExists(caseID, lesion))
- {
- RelationStorage::LinkSegmentationToLesion(caseID, segmentationID, lesion);
- NotifyObserver(caseID);
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "The lesion " << lesion.UID << " to link does not exist for the given case.";
- }
-}
-
-void mitk::SemanticRelationsIntegration::UnlinkSegmentationFromLesion(const DataNode* segmentationNode)
-{
- if (nullptr == segmentationNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid segmentation data node.";
- }
-
- SemanticTypes::CaseID caseID;
- SemanticTypes::ID segmentationID;
- try
- {
- caseID = GetCaseIDFromDataNode(segmentationNode);
- segmentationID = GetIDFromDataNode(segmentationNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot unlink the given segmentation data node from its lesion.";
- }
-
- RelationStorage::UnlinkSegmentationFromLesion(caseID, segmentationID);
- NotifyObserver(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::RemoveSegmentation(const DataNode* segmentationNode)
-{
- if (nullptr == segmentationNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid segmentation data node.";
- }
-
- SemanticTypes::CaseID caseID;
- SemanticTypes::ID segmentationNodeID;
- try
- {
- caseID = GetCaseIDFromDataNode(segmentationNode);
- segmentationNodeID = GetIDFromDataNode(segmentationNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot remove the given segmentation data node.";
- }
-
- try
- {
- UnlinkSegmentationFromLesion(segmentationNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot remove the given segmentation data node.";
- }
-
- RelationStorage::RemoveSegmentation(caseID, segmentationNodeID);
- NotifyObserver(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::SetControlPointOfImage(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID;
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot set the given control point for the given image data node.";
- }
-
- SemanticTypes::ControlPointVector allControlPoints = RelationStorage::GetAllControlPointsOfCase(caseID);
- // need to check if an already existing control point fits/contains the user control point
- SemanticTypes::ControlPoint existingControlPoint = FindExistingControlPoint(caseID, controlPoint);
- try
- {
- if (!existingControlPoint.UID.empty())
- {
- // found an already existing control point
- LinkImageToControlPoint(imageNode, existingControlPoint, false);
- }
- else
- {
- // find closest control point to add the new control point to the correct examination period
- SemanticTypes::ControlPoint closestControlPoint = FindClosestControlPoint(caseID, controlPoint);
- SemanticTypes::ExaminationPeriod examinationPeriod = FindContainingExaminationPeriod(caseID, closestControlPoint);
- if (examinationPeriod.UID.empty())
- {
- // no closest control point (exceed threshold) or no examination period found
- // create a new examination period for this control point and add it to the storage
- examinationPeriod.UID = UIDGeneratorBoost::GenerateUID();
- examinationPeriod.name = "New examination period";
- AddExaminationPeriod(caseID, examinationPeriod);
- }
-
- // added a new control point
- AddControlPointAndLinkImage(imageNode, controlPoint, false);
- // add the control point to the (newly created or found / close) examination period
- AddControlPointToExaminationPeriod(caseID, controlPoint, examinationPeriod);
- }
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot set the given control point for the given image data node.";
- }
-
- ClearControlPoints(caseID);
- NotifyObserver(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::AddControlPointAndLinkImage(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint, bool checkConsistence)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID;
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot add the given control point and link the given image data node.";
- }
-
- if (SemanticRelationsInference::InstanceExists(caseID, controlPoint))
- {
- mitkThrowException(SemanticRelationException) << "The control point " << controlPoint.UID << " to add already exists for the given case. \n Use 'LinkImageToControlPoint' instead.";
- }
-
- RelationStorage::AddControlPoint(caseID, controlPoint);
-
- try
- {
- LinkImageToControlPoint(imageNode, controlPoint, checkConsistence);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot add the given control point and link the given image data node.";
- }
-}
-
-void mitk::SemanticRelationsIntegration::LinkImageToControlPoint(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint, bool /*checkConsistence*/)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID;
- SemanticTypes::ID imageID;
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot link the image data node to the given control point.";
- }
-
- if (SemanticRelationsInference::InstanceExists(caseID, controlPoint))
- {
- RelationStorage::LinkImageToControlPoint(caseID, imageID, controlPoint);
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "The control point " << controlPoint.UID << " to link does not exist for the given case.";
- }
-}
-
-void mitk::SemanticRelationsIntegration::UnlinkImageFromControlPoint(const DataNode* imageNode)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID imageID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot unlink the given image data node from its control point.";
- }
-
- RelationStorage::UnlinkImageFromControlPoint(caseID, imageID);
- ClearControlPoints(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::AddExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- if (SemanticRelationsInference::InstanceExists(caseID, examinationPeriod))
- {
- mitkThrowException(SemanticRelationException) << "The examination period " << examinationPeriod.UID << " to add already exists for the given case.";
- }
- else
- {
- RelationStorage::AddExaminationPeriod(caseID, examinationPeriod);
- }
-}
-
-void mitk::SemanticRelationsIntegration::RenameExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- if (SemanticRelationsInference::InstanceExists(caseID, examinationPeriod))
- {
- RelationStorage::RenameExaminationPeriod(caseID, examinationPeriod);
- NotifyObserver(caseID);
- }
- else
- {
- mitkThrowException(SemanticRelationException) << "The examination period " << examinationPeriod.UID << " to overwrite does not exist for the given case.";
- }
-}
-
-void mitk::SemanticRelationsIntegration::AddControlPointToExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod)
-{
- if (!SemanticRelationsInference::InstanceExists(caseID, controlPoint))
- {
- mitkThrowException(SemanticRelationException) << "The control point " << controlPoint.UID << " to add does not exist for the given case.";
- }
-
- if (!SemanticRelationsInference::InstanceExists(caseID, examinationPeriod))
- {
- mitkThrowException(SemanticRelationException) << "The examination period " << examinationPeriod.UID << " does not exist for the given case. \n Use 'AddExaminationPeriod' before.";
- }
-
- RelationStorage::AddControlPointToExaminationPeriod(caseID, controlPoint, examinationPeriod);
-}
-
-void mitk::SemanticRelationsIntegration::SetInformationType(const DataNode* imageNode, const SemanticTypes::InformationType& informationType)
-{
- SemanticTypes::CaseID caseID;
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
-
- RemoveInformationTypeFromImage(imageNode);
- AddInformationTypeToImage(imageNode, informationType);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot set the given information type for the given image data node.";
- }
-
- NotifyObserver(caseID);
-}
-
-void mitk::SemanticRelationsIntegration::AddInformationTypeToImage(const DataNode* imageNode, const SemanticTypes::InformationType& informationType)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID imageID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot add the given information type to the given image data node.";
- }
-
- RelationStorage::AddInformationTypeToImage(caseID, imageID, informationType);
-}
-
-void mitk::SemanticRelationsIntegration::RemoveInformationTypeFromImage(const DataNode* imageNode)
-{
- if (nullptr == imageNode)
- {
- mitkThrowException(SemanticRelationException) << "Not a valid image data node.";
- }
-
- SemanticTypes::CaseID caseID = "";
- SemanticTypes::ID imageID = "";
- try
- {
- caseID = GetCaseIDFromDataNode(imageNode);
- imageID = GetIDFromDataNode(imageNode);
- }
- catch (SemanticRelationException& e)
- {
- mitkReThrow(e) << "Cannot remove the information type from the given image data node.";
- }
-
- SemanticTypes::InformationType originalInformationType = RelationStorage::GetInformationTypeOfImage(caseID, imageID);
- RelationStorage::RemoveInformationTypeFromImage(caseID, imageID);
-
- // check for further references to the removed information type
- SemanticTypes::IDVector allImageIDsVectorValue = RelationStorage::GetAllImageIDsOfCase(caseID);
- for (const auto& otherImageID : allImageIDsVectorValue)
- {
- SemanticTypes::InformationType otherInformationType = RelationStorage::GetInformationTypeOfImage(caseID, otherImageID);
- if (otherInformationType == originalInformationType)
- {
- // found the information type in another image -> cannot remove the information type from the case
- return;
- }
- }
-
- // given information type was not referred by any other image of the case -> the information type can be removed from the case
- RelationStorage::RemoveInformationType(caseID, originalInformationType);
-}
-
-/************************************************************************/
-/* private functions */
-/************************************************************************/
-void mitk::SemanticRelationsIntegration::NotifyObserver(const SemanticTypes::CaseID& caseID) const
-{
- for (auto& observer : m_ObserverVector)
- {
- observer->Update(caseID);
- }
-}
-
-void mitk::SemanticRelationsIntegration::ClearControlPoints(const SemanticTypes::CaseID& caseID)
-{
- SemanticTypes::ControlPointVector allControlPointsOfCase = RelationStorage::GetAllControlPointsOfCase(caseID);
-
- SemanticTypes::IDVector allImageIDsVectorValue = RelationStorage::GetAllImageIDsOfCase(caseID);
- SemanticTypes::ControlPointVector referencedControlPoints;
- for (const auto& imageID : allImageIDsVectorValue)
- {
- SemanticTypes::ControlPoint controlPointOfImage = RelationStorage::GetControlPointOfImage(caseID, imageID);
- referencedControlPoints.push_back(controlPointOfImage);
- }
-
- std::sort(allControlPointsOfCase.begin(), allControlPointsOfCase.end());
- std::sort(referencedControlPoints.begin(), referencedControlPoints.end());
-
- SemanticTypes::ControlPointVector nonReferencedControlPoints;
- std::set_difference(allControlPointsOfCase.begin(), allControlPointsOfCase.end(),
- referencedControlPoints.begin(), referencedControlPoints.end(),
- std::inserter(nonReferencedControlPoints, nonReferencedControlPoints.begin()));
-
- for (const auto& controlPoint : nonReferencedControlPoints)
- {
- const SemanticTypes::ExaminationPeriod& examinationPeriod = FindContainingExaminationPeriod(caseID, controlPoint);
- RelationStorage::RemoveControlPointFromExaminationPeriod(caseID, controlPoint, examinationPeriod);
- RelationStorage::RemoveControlPoint(caseID, controlPoint);
- }
-}
diff --git a/Modules/SemanticRelations/src/mitkUIDGeneratorBoost.cpp b/Modules/SemanticRelations/src/mitkUIDGeneratorBoost.cpp
deleted file mode 100644
index 394113e499..0000000000
--- a/Modules/SemanticRelations/src/mitkUIDGeneratorBoost.cpp
+++ /dev/null
@@ -1,24 +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.
-
-============================================================================*/
-
-// semantic relation module
-#include "mitkUIDGeneratorBoost.h"
-
-#include <boost/uuid/uuid.hpp>
-#include <boost/uuid/uuid_generators.hpp>
-#include <boost/uuid/uuid_io.hpp>
-
-std::string mitk::UIDGeneratorBoost::GenerateUID()
-{
- boost::uuids::uuid uuid = boost::uuids::random_generator()();
- return boost::uuids::to_string(uuid);
-}
diff --git a/Modules/SemanticRelationsUI/CMakeLists.txt b/Modules/SemanticRelationsUI/CMakeLists.txt
deleted file mode 100644
index 1a94ea6b53..0000000000
--- a/Modules/SemanticRelationsUI/CMakeLists.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-MITK_CREATE_MODULE(
- DEPENDS MitkQtWidgets MitkSemanticRelations
- PACKAGE_DEPENDS Qt5|Core
-)
diff --git a/Modules/SemanticRelationsUI/files.cmake b/Modules/SemanticRelationsUI/files.cmake
deleted file mode 100644
index a10162f616..0000000000
--- a/Modules/SemanticRelationsUI/files.cmake
+++ /dev/null
@@ -1,36 +0,0 @@
-file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*")
-
-set(CPP_FILES
- mitkModuleActivator.cpp
- QmitkAbstractSemanticRelationsStorageInspector.cpp
- QmitkAbstractSemanticRelationsStorageModel.cpp
- QmitkControlPointDialog.cpp
- QmitkLesionTextDialog.cpp
- QmitkLesionTreeItem.cpp
- QmitkLesionTreeModel.cpp
- QmitkPatientTableHeaderView.cpp
- QmitkPatientTableInspector.cpp
- QmitkPatientTableModel.cpp
- QmitkSemanticRelationsUIHelper.cpp
- QmitkStatisticsCalculator.cpp
- QmitkStatisticsTreeModel.cpp
- QmitkTableItemThumbnailDelegate.cpp
-)
-
-set(MOC_H_FILES
- include/QmitkAbstractSemanticRelationsStorageInspector.h
- include/QmitkAbstractSemanticRelationsStorageModel.h
- include/QmitkControlPointDialog.h
- include/QmitkLesionTextDialog.h
- include/QmitkLesionTreeModel.h
- include/QmitkPatientTableHeaderView.h
- include/QmitkPatientTableInspector.h
- include/QmitkPatientTableModel.h
- include/QmitkStatisticsCalculator.h
- include/QmitkStatisticsTreeModel.h
- include/QmitkTableItemThumbnailDelegate.h
-)
-
-set(UI_FILES
- src/QmitkPatientTableInspector.ui
-)
diff --git a/Modules/SemanticRelationsUI/include/QmitkAbstractSemanticRelationsStorageInspector.h b/Modules/SemanticRelationsUI/include/QmitkAbstractSemanticRelationsStorageInspector.h
deleted file mode 100644
index 91603012dc..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkAbstractSemanticRelationsStorageInspector.h
+++ /dev/null
@@ -1,57 +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 QmitkAbstractSemanticRelationsStorageInspector_h
-#define QmitkAbstractSemanticRelationsStorageInspector_h
-
-// semantic relations UI module
-#include "MitkSemanticRelationsUIExports.h"
-
-// semantic relations module
-#include "mitkSemanticTypes.h"
-
-// qt widgets module
-#include "QmitkAbstractDataStorageInspector.h"
-
-/*
-* @brief The QmitkAbstractSemanticRelationsStorageInspector is a QmitkAbstractDataStorageInspector that can be used to
-* show the currently available data of an (abstract) semantic relations storage model.
-*/
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkAbstractSemanticRelationsStorageInspector : public QmitkAbstractDataStorageInspector
-{
- Q_OBJECT
-
-public:
-
- ~QmitkAbstractSemanticRelationsStorageInspector() override;
-
- /**
- * @brief Extends the abstract base class to allow setting the current case ID which is needed to access the
- * semantic relations storage. The function sets the case ID in the storage model.
- *
- * @param caseID A case ID as string
- */
- virtual void SetCaseID(const mitk::SemanticTypes::CaseID& caseID) = 0;
- /**
- * @brief Extends the abstract base class to allow setting the current lesion.
- * The function sets the lesion in the storage model.
- *
- *@param lesion The selected lesion
- */
- virtual void SetLesion(const mitk::SemanticTypes::Lesion& lesion) = 0;
-
-protected:
-
- QmitkAbstractSemanticRelationsStorageInspector(QWidget* parent = nullptr);
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkAbstractSemanticRelationsStorageModel.h b/Modules/SemanticRelationsUI/include/QmitkAbstractSemanticRelationsStorageModel.h
deleted file mode 100644
index e427abe2a9..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkAbstractSemanticRelationsStorageModel.h
+++ /dev/null
@@ -1,111 +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 QmitkAbstractSemanticRelationsStorageModel_h
-#define QmitkAbstractSemanticRelationsStorageModel_h
-
-// mitk semantic relations UI
-#include "MitkSemanticRelationsUIExports.h"
-
-// semantic relations module
-#include <mitkISemanticRelationsObserver.h>
-#include <mitkSemanticRelationsDataStorageAccess.h>
-#include <mitkSemanticRelationsIntegration.h>
-#include <mitkSemanticTypes.h>
-
-// qt widgets module
-#include "QmitkAbstractDataStorageModel.h"
-
-/*
-* @brief The QmitkAbstractSemanticRelationsStorageModel is a subclass of 'QmitkAbstractDataStorageModel' and provides additional
-* functionality to set and store a semantic relations instance, the current case ID and the current lesion.
-*/
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkAbstractSemanticRelationsStorageModel : public QmitkAbstractDataStorageModel, public mitk::ISemanticRelationsObserver
-{
- Q_OBJECT
-
-public:
-
- QmitkAbstractSemanticRelationsStorageModel(QObject* parent = nullptr);
- ~QmitkAbstractSemanticRelationsStorageModel() override;
-
- /*
- * @brief Update this model with the data from the semantic relations,
- * if the case ID is equal to the currently selected case ID of the table model.
- *
- * Overridden from 'ISemanticRelationsObserver'.
- * In order for the Update-function to be called, this model has to be added as an observer of SemanticRelation
- * (e.g. m_SemanticRelations->AddObserver(m_SemanticRelationsStorageModel);)
- *
- * @par caseID The current case ID to identify the currently active patient / case.
- */
- void Update(const mitk::SemanticTypes::CaseID& caseID) override;
-
- /**
- * @brief Set the current case ID which is needed to access the semantic relations storage.
- *
- * @param caseID A case ID as string
- */
- void SetCaseID(const mitk::SemanticTypes::CaseID& caseID);
-
- const mitk::SemanticTypes::CaseID& GetCaseID() const { return m_CaseID; }
- /**
- * @brief Set the current lesion which can be used to show on which images the lesion is visible.
- *
- * @param lesion The selected lesion
- */
- void SetLesion(const mitk::SemanticTypes::Lesion& lesion);
-
- const mitk::SemanticTypes::Lesion& GetLesion() const { return m_Lesion; }
- /**
- * @brief Set the current data node selection which can be used to show which lesions
- * are visible on the node selection.
- *
- * @param dataNodeSelection The selected data nodes
- */
- void SetDataNodeSelection(const QList<mitk::DataNode::Pointer>& dataNodeSelection);
-
- const QList<mitk::DataNode::Pointer>& GetSelectedDataNodes() const { return m_SelectedDataNodes; };
- /*
- * @brief Update the semantic relations storage model with the current data from the semantic relations model
- * and the current case ID.
- */
- void UpdateModelData();
-
-Q_SIGNALS:
- void ModelUpdated();
-
-protected:
-
- /**
- * @brief Create a new 'SemanticRelationsDataStorageAccess' instance with the new data storage and
- * update the model data.
- * This functions is called inside the 'SetDataStorage'-function from the parent class.
- */
- void DataStorageChanged() override;
-
- /**
- * @brief This function is called if the model data is updated. It can be used by subclasses to define
- * the way the data of a specific model is generated. It typically consists of access to the
- * semantic relations storage to retrieve certain information.
- */
- virtual void SetData() = 0;
-
- std::unique_ptr<mitk::SemanticRelationsDataStorageAccess> m_SemanticRelationsDataStorageAccess;
- std::unique_ptr<mitk::SemanticRelationsIntegration> m_SemanticRelationsIntegration;
-
- mitk::SemanticTypes::CaseID m_CaseID;
- QList<mitk::DataNode::Pointer> m_SelectedDataNodes;
- mitk::SemanticTypes::Lesion m_Lesion;
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkControlPointDialog.h b/Modules/SemanticRelationsUI/include/QmitkControlPointDialog.h
deleted file mode 100644
index 9bb1b46640..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkControlPointDialog.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 QmitkControlPointDialog_h
-#define QmitkControlPointDialog_h
-
-#include <MitkSemanticRelationsUIExports.h>
-
-// semantic relations module
-#include "mitkSemanticTypes.h"
-
-#include <QDateEdit>
-#include <QDialog>
-
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkControlPointDialog : public QDialog
-{
- Q_OBJECT
-
-public:
-
- QmitkControlPointDialog(QWidget *parent = nullptr);
-
- void SetCurrentDate(mitk::SemanticTypes::ControlPoint currentControlPoint);
- QDate GetCurrentDate() const;
-
-private:
-
- QDateEdit* m_DateEdit;
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkLesionTextDialog.h b/Modules/SemanticRelationsUI/include/QmitkLesionTextDialog.h
deleted file mode 100644
index 01b4b18ee3..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkLesionTextDialog.h
+++ /dev/null
@@ -1,43 +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 QmitkLesionTextDialog_h
-#define QmitkLesionTextDialog_h
-
-#include <MitkSemanticRelationsUIExports.h>
-
-// semantic relations module
-#include "mitkSemanticTypes.h"
-
-#include <QLineEdit>
-#include <QDialog>
-
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkLesionTextDialog : public QDialog
-{
- Q_OBJECT
-
-public:
-
- QmitkLesionTextDialog(QWidget *parent = nullptr);
-
- void SetLineEditText(const std::string& lineEditText);
- QString GetLineEditText() const;
-
- QLineEdit* GetLineEdit() const;
-
-private:
-
- QLineEdit* m_LineEdit;
-
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkLesionTreeItem.h b/Modules/SemanticRelationsUI/include/QmitkLesionTreeItem.h
deleted file mode 100644
index 0787b7501a..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkLesionTreeItem.h
+++ /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.
-
-============================================================================*/
-
-#ifndef QmitkLesionTreeItem_h
-#define QmitkLesionTreeItem_h
-
-// mitk semantic relations UI
-#include "mitkLesionData.h"
-
-// mitk semantic relations
-#include <mitkSemanticTypes.h>
-
-// qt
-#include <QVariant>
-
-// c++
-#include <memory>
-#include <vector>
-
-/*
-* @brief This class is used by custom tree models to create their tree items.
-* It provides functions to traverse and modify the tree.
-* Additionally it holds some 'LesionData' that is used to display lesion properties inside a tree view.
-*/
-class QmitkLesionTreeItem : public std::enable_shared_from_this<QmitkLesionTreeItem>
-{
-public:
-
- using ChildPointer = std::shared_ptr<QmitkLesionTreeItem>;
- using ChildConstPointer = std::shared_ptr<const QmitkLesionTreeItem>;
- using ParentPointer = std::weak_ptr<QmitkLesionTreeItem>;
-
- QmitkLesionTreeItem(mitk::LesionData lesionData = mitk::LesionData());
-
- /**
- * @brief Return the child of this item at a specific position.
- *
- * @param row Determines the position of a child item to return.
- *
- * @return The child of this item at a specific position.
- */
- ChildPointer GetChildInRow(int row) const { return m_Children.at(row); };
- /**
- * @brief Return the parent item.
- *
- * @return The parent item as std::weak_ptr.
- */
- ParentPointer GetParent() const { return m_ParentItem; };
- /**
- * @brief Set the parent item of this item.
- *
- * @param parent The new parent item of this item.
- */
- void SetParent(ParentPointer parent);
- /**
- * @brief Return the item data, which contains ...
- *
- * see <code>mitk::LesionItemData</code>
- */
- mitk::LesionData& GetData() { return m_ItemData; };
- /**
- * @brief Get the row of this item relative to its parent item using 'GetRowOfChild'.
- *
- * @return The row of this item relative to its parent item.
- */
- int GetRow() const;
- /**
- * @brief Get the row of the given child item relative to this item.
- *
- * @param child The child item whose row is to be determined.
- *
- * @return The row of the child item.
- */
- int GetRowOfChild(ChildConstPointer child) const;
- /**
- * @brief Return the number of child items.
- *
- * @return Number of child items.
- */
- size_t ChildCount() const { return m_Children.size(); };
- /**
- * @brief Add a new child to the list of children of this item if it is not already a child item.
- *
- * @param child The child item to add to this item.
- */
- void AddChild(ChildPointer child);
- /**
- * @brief Remove a child from the list of children of this item.
- *
- * @param child The child item to remove from this item.
- */
- void RemoveChild(ChildPointer child);
- /**
- * @brief Set the item data of this item.
- *
- * @param lesionData LesionData that provides information about this item.
- */
- void SetData(const mitk::LesionData& lesionData);
-
-private:
-
- ParentPointer m_ParentItem;
- std::vector<ChildPointer> m_Children;
- mitk::LesionData m_ItemData;
-
-};
-
-Q_DECLARE_METATYPE(QmitkLesionTreeItem)
-Q_DECLARE_METATYPE(QmitkLesionTreeItem*)
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkLesionTreeModel.h b/Modules/SemanticRelationsUI/include/QmitkLesionTreeModel.h
deleted file mode 100644
index 23fc04ca86..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkLesionTreeModel.h
+++ /dev/null
@@ -1,106 +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 QmitkLesionTreeModel_h
-#define QmitkLesionTreeModel_h
-
-// mitk semantic relations UI
-#include "MitkSemanticRelationsUIExports.h"
-#include "QmitkAbstractSemanticRelationsStorageModel.h"
-#include "QmitkLesionTreeItem.h"
-
-/*
-* @brief The 'QmitkLesionTreeModel' is a subclass of 'QmitkAbstractSemanticRelationsStorageModel' and provides
-* functionality to serve as a tree model.
-* The tree model creates a new top-level tree item for each lesion that is stored inside the semantic relations storage.
-* Each lesion tree item contains lesion data that can be display inside a tree view. The lesion data
-* consists of a lesion with with its UID, name and lesion class. The name or UID is used for the top-level tree items.
-* Additionally the lesion data contains two vectors which define the lesion presence (bool) and the lesion volume (double)
-* for each control-point - information type pair. The lesion presence will be used inside this model for the tree items.
-* The volume is used inside another tree model.
-*
-* The model holds the last segmentation that is added to the data storage to support the process of defining a new lesion
-* (and linking it with the latest segmentation) (see 'NodeAdded').
-* Furthermore the model is able to accept a 'QList' of currently selected data nodes and to use it to change the background
-* color of each lesion tree item that is connected to this data node(s). This helps to see which lesion is already found and
-* defined for a given (set of) data node(s).
-*/
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkLesionTreeModel : public QmitkAbstractSemanticRelationsStorageModel
-{
- Q_OBJECT
-
-public:
-
- /**
- * @brief Initialize the root item of the model. The root item does not have a parent item.
- */
- QmitkLesionTreeModel(QObject* parent = nullptr);
-
- //////////////////////////////////////////////////////////////////////////
- // overridden virtual functions from QAbstractItemModel
- //////////////////////////////////////////////////////////////////////////
- QModelIndex index(int row, int column, const QModelIndex& itemIndex = QModelIndex()) const override;
- QModelIndex parent(const QModelIndex& itemIndex) const override;
-
- int rowCount(const QModelIndex& itemIndex = QModelIndex()) const override;
- int columnCount(const QModelIndex& itemIndex = QModelIndex()) const override;
-
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
-
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
- //////////////////////////////////////////////////////////////////////////
- // end override
- //////////////////////////////////////////////////////////////////////////
-
- const mitk::DataNode* GetLastSegmentation() const;
-
-protected:
-
- // the following functions have to be overridden but are not implemented in this model
- void NodePredicateChanged() override { }
- void NodeAdded(const mitk::DataNode*) override;
- void NodeChanged(const mitk::DataNode*) override { }
- void NodeRemoved(const mitk::DataNode*) override { }
- /**
- * @brief Overridden from 'QmitkAbstractSemanticRelationsStorageModel': This function retrieves all control points
- * of the current case and stores them to define the header of the tree.
- * Furthermore all lesions are retrieved and the lesion data is stored and show in the tree view.
- */
- void SetData() override;
-
-private:
-
- void SetLesionData();
- void AddLesion(const mitk::SemanticTypes::Lesion& lesion);
- void SetSelectedDataNodesPresence();
- /**
- * @brief The function uses the ID of the lesion to see if a data node presence was already set.
- * If not, the given bool value is used and stored inside a member variable. If the lesion presence
- * was already set, it will be overwritten.
- * The function is used by the 'SetSelectedDataNodesPresence' function.
- *
- * @param lesion The lesion whose data node presence should be set
- * @param dataNodePresence The bool value that defines the data node presence of the given lesion
- */
- void SetDataNodePresenceOfLesion(const mitk::SemanticTypes::Lesion* lesion, bool dataNodePresence);
-
- QmitkLesionTreeItem* GetItemByIndex(const QModelIndex& index) const;
-
- std::map<mitk::SemanticTypes::ID, bool> m_DataNodePresence;
- const mitk::DataNode* m_LastSegmentation;
-
- std::shared_ptr<QmitkLesionTreeItem> m_RootItem;
- mitk::SemanticTypes::ControlPointVector m_ControlPoints;
- mitk::SemanticTypes::LesionVector m_CurrentLesions;
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkPatientInfoWidget.h b/Modules/SemanticRelationsUI/include/QmitkPatientInfoWidget.h
deleted file mode 100644
index 482c3d6d38..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkPatientInfoWidget.h
+++ /dev/null
@@ -1,50 +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 QmitkPatientInfoWidget_h
-#define QmitkPatientInfoWidget_h
-
-// semantic relations UI module
-#include "MitkSemanticRelationsUIExports.h"
-#include <ui_QmitkPatientInfoWidgetControls.h>
-
-// qt
-#include <QWidget>
-
-// mitk core
-#include <mitkDataNode.h>
-
-/*
-* @brief The QmitkPatientInfoWidget is a widget that shows some DICOM information about a specific patient (data node).
-*
-* CURRENTLY NOT USED
-*/
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkPatientInfoWidget : public QWidget
-{
- Q_OBJECT
-
-public:
-
- QmitkPatientInfoWidget(QWidget* parent = nullptr);
- ~QmitkPatientInfoWidget();
-
- void SetPatientInfo(const mitk::DataNode* dataNode);
-
-private:
-
- void QmitkPatientInfoWidget::Init();
-
- Ui::QmitkPatientInfoWidgetControls m_Controls;
-
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkPatientTableHeaderView.h b/Modules/SemanticRelationsUI/include/QmitkPatientTableHeaderView.h
deleted file mode 100644
index 393caac921..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkPatientTableHeaderView.h
+++ /dev/null
@@ -1,79 +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 QmitkPatientTableHeaderView_h
-#define QmitkPatientTableHeaderView_h
-
-// semantic relations ui module
-#include "MitkSemanticRelationsUIExports.h"
-
-// qt
-#include <QStandardItemModel>
-#include <QHeaderView>
-#include <QPointer>
-
-/*
-* @brief
-*/
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkPatientTableHeaderView : public QHeaderView
-{
- Q_OBJECT
-
-public:
-
- QmitkPatientTableHeaderView(QWidget* parent = nullptr);
- ~QmitkPatientTableHeaderView() override;
-
- enum HeaderDataModelRoles
- {
- HorizontalHeaderDataRole = Qt::UserRole
- };
-
- /**
- * @brief Set the model of the table view of this header view.
- * This model returns a standard item model for the 'HorizontalHeaderDataRole'-role.
- * The header model has been previously filled with header data.
- * This function is overwritten from QHeaderView.
- */
- void setModel(QAbstractItemModel* model) override;
-
-protected:
-
- /**
- * @brief Paint each header using 'PaintHeader'.
- * This function is overwritten from QHeaderView.
- */
- void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const override;
- /**
- * @brief Get the section size by retrieving the text content.
- * The section size is dependent on the child and parent headers.
- * This function is overwritten from QHeaderView.
- */
- QSize sectionSizeFromContents(int logicalIndex) const override;
-
-private:
-
- int PaintHeader(QPainter* painter, const QModelIndex& currentIndex, int logicalIndex, const QRect& sectionRect, int top) const;
- QSize HeaderSize(const QModelIndex& index) const;
- int CurrentHeaderLeft(const QModelIndex& currentIndex, const QModelIndex& headerIndex, int sectionIndex, int left) const;
- int CurrentHeaderWidth(const QModelIndex& currentIndex, const QModelIndex& headerIndex, int sectionIndex) const;
-
- QModelIndexList ParentIndexList(QModelIndex index) const;
- QModelIndex HeaderIndex(int sectionIndex) const;
- QModelIndex FindHeader(const QModelIndex& currentIndex, int sectionIndex, int& currentHeaderIndex) const;
- QModelIndexList ListHeader(const QModelIndex& currentIndex) const;
-
- QStandardItemModel* m_HeaderModel;
-
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkPatientTableInspector.h b/Modules/SemanticRelationsUI/include/QmitkPatientTableInspector.h
deleted file mode 100644
index 9ffc9ad505..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkPatientTableInspector.h
+++ /dev/null
@@ -1,85 +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 QmitkPatientTableInspector_h
-#define QmitkPatientTableInspector_h
-
-// semantic relations UI module
-#include "MitkSemanticRelationsUIExports.h"
-#include "QmitkAbstractSemanticRelationsStorageInspector.h"
-#include "QmitkPatientTableModel.h"
-#include "QmitkTableItemThumbnailDelegate.h"
-
-#include "ui_QmitkPatientTableInspector.h"
-
-// qt widgets module
-#include <QmitkEnums.h>
-
-// qt
-#include <QMenu>
-
-/*
-* @brief The QmitkPatientTableInspector is a QmitkAbstractSemanticRelationsStorageInspector that shows the currently
-* available data of the semantic relations storage model in a control-point - information type matrix.
-*
-* The QmitkPatientTableInspector uses the QmitkSemanticRelationsStorageModel, a QmitkAbstractDataStorageModel that
-* presents the semantic relations data as a table, showing a QPixmap as thumbnail for the data nodes.
-*/
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkPatientTableInspector : public QmitkAbstractSemanticRelationsStorageInspector
-{
- Q_OBJECT
-
-public:
-
- QmitkPatientTableInspector(QWidget* parent = nullptr);
-
- QAbstractItemView* GetView() override;
- const QAbstractItemView* GetView() const override;
-
- void SetSelectionMode(SelectionMode mode) override;
- SelectionMode GetSelectionMode() const override;
-
- void SetCaseID(const mitk::SemanticTypes::CaseID& caseID) override;
- void SetLesion(const mitk::SemanticTypes::Lesion& lesion) override;
-
- QItemSelectionModel* GetSelectionModel();
-
-Q_SIGNALS:
-
- void DataNodeDoubleClicked(const mitk::DataNode*);
- void OnContextMenuRequested(const QPoint&);
- void OnNodeRemoved(const mitk::DataNode*);
-
-private Q_SLOTS:
-
- void OnModelUpdated();
- void OnNodeButtonClicked(const QString&);
- void OnDataNodeSelectionChanged(const QList<mitk::DataNode::Pointer>&);
- void OnItemDoubleClicked(const QModelIndex&);
-
-protected:
-
- void Initialize() override;
-
-private:
-
- void SetUpConnections();
-
- void keyPressEvent(QKeyEvent* e) override;
-
- Ui::QmitkPatientTableInspector m_Controls;
- QmitkPatientTableModel* m_StorageModel;
- QmitkTableItemThumbnailDelegate* m_ItemDelegate;
-
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkPatientTableModel.h b/Modules/SemanticRelationsUI/include/QmitkPatientTableModel.h
deleted file mode 100644
index c19f2f41ef..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkPatientTableModel.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 QmitkPatientTableModel_h
-#define QmitkPatientTableModel_h
-
-// semantic relations UI module
-#include "QmitkAbstractSemanticRelationsStorageModel.h"
-
-// semantic relations module
-#include <mitkSemanticTypes.h>
-#include <mitkSemanticRelationsDataStorageAccess.h>
-
-// mitk core
-#include <mitkDataNode.h>
-
-// qt
-#include <QPixmap>
-#include <QStandardItemModel>
-
-/**
-* @brief The QmitkPatientTableModel is a subclass of the QmitkAbstractSemanticRelationsStorageModel and holds the semantic relations data of the currently selected case.
-*
-* The QmitkPatientTableModel uses the 'data' function to return either the data node of a table cell or the thumbnail of the underlying image.
-* The horizontal header of the table shows the control points of the current case and the vertical header of the table shows the information types of the current case.
-* Using the 'GetFilteredData'-function of the SemanticRelations-class the model is able to retrieve the correct data node for each table entry.
-*
-* Additionally the model creates and holds the QPixmaps of the known data nodes in order to return a thumbnail, if needed.
-*/
-class QmitkPatientTableModel : public QmitkAbstractSemanticRelationsStorageModel
-{
- Q_OBJECT
-
-public:
-
- QmitkPatientTableModel(QObject* parent = nullptr);
- ~QmitkPatientTableModel() override;
-
- //////////////////////////////////////////////////////////////////////////
- // overridden functions from QAbstractItemModel
- //////////////////////////////////////////////////////////////////////////
- QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
- QModelIndex parent(const QModelIndex& child) const override;
-
- int rowCount(const QModelIndex& parent = QModelIndex()) const override;
- int columnCount(const QModelIndex& parent = QModelIndex()) const override;
-
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
-
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
- Qt::ItemFlags flags(const QModelIndex& index) const override;
- //////////////////////////////////////////////////////////////////////////
- /// end override
- /////////////////////////////////////////////////////////////////////////
-
- void SetNodeType(const std::string& nodeType);
-
-protected:
-
- // the following functions have to be overridden...
- void NodePredicateChanged() override;
- // but are not implemented in this model
- void NodeAdded(const mitk::DataNode*) override { }
- void NodeChanged(const mitk::DataNode*) override { }
- void NodeRemoved(const mitk::DataNode*) override { }
- /**
- * @brief Overridden from 'QmitkAbstractSemanticRelationsStorageModel': This function retrieves all control points
- * and information types of the current case and stores them to define the header of the table.
- * Furthermore all images are retrieved and the pixmap of the images are generated and stored.
- */
- void SetData() override;
-
-private:
-
- void SetHeaderModel();
- void SetPixmaps();
- void SetLesionPresences();
-
- /**
- * @brief The function uses the ID of the node to see if a pixmap was already set. If not, the given pixmap
- * is used and stored inside a member variable. If the pixmap was already set, it will be overwritten.
- * Using 'nullptr' as a pixmap will erase the entry for the given data node.
- *
- * @param dataNode The data node whose pixmap should be set
- * @param pixmapFromImage The pixmap that shows an image of the content of the data node
- */
- void SetPixmapOfNode(const mitk::DataNode* dataNode, QPixmap* pixmapFromImage);
- /**
- * @brief The function uses the ID of the node to see if a lesion presence was already set. If not, the given
- * bool value is used and stored inside a member variable. If the lesion presence was already set, it
- * will be overwritten.
- * The function is used by the 'SetLesionPresences' function.
- *
- * @param dataNode The data node whose lesion presence should be set
- * @param lesionPresence The bool value that defines the lesion presence of the given data node
- */
- void SetLesionPresenceOfNode(const mitk::DataNode* dataNode, bool lesionPresence);
- /**
- * @brief Returns the data node that is associated with the given table entry (index).
- *
- * The function uses the SemanticRelations-class and the current control point data and information type data to
- * filter the nodes of the current case.
- * The index is used to access the correct row in the table (information type) and the correct column in the table (control point).
- *
- * @par index The QModelIndex of the table entry
- */
- mitk::DataNode* GetCurrentDataNode(const QModelIndex &index) const;
-
- std::map<mitk::DataNode::ConstPointer, QPixmap> m_PixmapMap;
- std::map<mitk::DataNode::ConstPointer, bool> m_LesionPresence;
-
- mitk::SemanticTypes::ExaminationPeriodVector m_ExaminationPeriods;
- mitk::SemanticTypes::InformationTypeVector m_InformationTypes;
- mitk::SemanticRelationsDataStorageAccess::DataNodeVector m_CurrentDataNodes;
- std::string m_SelectedNodeType;
-
- QStandardItemModel* m_HeaderModel;
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkSemanticRelationsUIHelper.h b/Modules/SemanticRelationsUI/include/QmitkSemanticRelationsUIHelper.h
deleted file mode 100644
index 0aed38c9fe..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkSemanticRelationsUIHelper.h
+++ /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.
-
-============================================================================*/
-
-#ifndef QmitkSemanticRelationsUIHelper_h
-#define QmitkSemanticRelationsUIHelper_h
-
-// semantic relations ui module
-#include "MitkSemanticRelationsUIExports.h"
-
-// mitk core
-#include <mitkDataNode.h>
-
-// qt
-#include <QPixmap>
-
-/**
-* @brief Provides a helper function to generate a pixmap from a given image node.
-*/
-namespace QmitkSemanticRelationsUIHelper
-{
- /*
- * @brief Generates a QPixmap of a DICOM image.
- *
- * The center sagittal image slice is extracted and used as the thumbnail image.
- *
- * @par dataNode The data node that holds the image data.
- */
- MITKSEMANTICRELATIONSUI_EXPORT QPixmap GetPixmapFromImageNode(const mitk::DataNode* dataNode);
-
-} // namespace QmitkSemanticRelationsUIHelper
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkStatisticsCalculator.h b/Modules/SemanticRelationsUI/include/QmitkStatisticsCalculator.h
deleted file mode 100644
index 9f9fef5b98..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkStatisticsCalculator.h
+++ /dev/null
@@ -1,76 +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 QmitkStatisticsCalculator_h
-#define QmitkStatisticsCalculator_h
-
-// mitk semantic relations UI
-#include "MitkSemanticRelationsUIExports.h"
-
-// mitk semantic relations module
-#include <mitkLesionData.h>
-#include <mitkSemanticTypes.h>
-
-// mitk core
-#include <mitkDataStorage.h>
-#include <mitkWeakPointer.h>
-
-// mitk image statistics ui module
-#include <QmitkImageStatisticsCalculationJob.h>
-
-/*
-* @brief This class provides functions to compute the lesion volume of a given lesion.
-* A lesion can be defined by a specific segmentation at each control-point - information type pair.
-* This segmentation and its parent image will be used inside the private 'GetSegmentationMaskVolume' function.
-* This function in turn uses the image statistics module (the 'ImageStatisticsContainerManager') to retrieve
-* the specific statistics values from a statistics node. However, if the statistics are not found,
-* a new 'QmitkImageStatisticsCalculationJob' is started. If the job is finished and the statistics are calculated,
-* a new statistics node is added to the data storage (or an existing statistics data node is updated).
-*/
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkStatisticsCalculator : public QObject
-{
- Q_OBJECT
-
-public:
-
- QmitkStatisticsCalculator();
- ~QmitkStatisticsCalculator() override;
-
- void SetDataStorage(mitk::DataStorage* dataStorage) { m_DataStorage = dataStorage; }
- /**
- * @brief Compute and store lesion volume for all available control points and information types.
- *
- * @param lesionData The lesion data that holds the lesion and will hold the additional lesion data.
- * @param caseID The current case ID.
- */
- void ComputeLesionVolume(mitk::LesionData& lesionData, const mitk::SemanticTypes::CaseID& caseID);
-
-private:
-
- /**
- * @brief
- *
- *
- */
- double GetSegmentationMaskVolume(mitk::DataNode::Pointer imageNode, mitk::DataNode::Pointer segmentationNode);
-
- void OnStatisticsCalculationEnds();
-
- QmitkImageStatisticsCalculationJob* m_CalculationJob;
- mitk::WeakPointer<mitk::DataStorage> m_DataStorage;
- mitk::DataNode::Pointer m_ImageNode;
- mitk::DataNode::Pointer m_SegmentationNode;
- double m_MaskVolume;
-
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkStatisticsTreeModel.h b/Modules/SemanticRelationsUI/include/QmitkStatisticsTreeModel.h
deleted file mode 100644
index 1b50084082..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkStatisticsTreeModel.h
+++ /dev/null
@@ -1,94 +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 QmitkStatisticsTreeModel_h
-#define QmitkStatisticsTreeModel_h
-
-// mitk semantic relations UI
-#include "MitkSemanticRelationsUIExports.h"
-#include "QmitkAbstractSemanticRelationsStorageModel.h"
-#include "QmitkLesionTreeItem.h"
-#include "QmitkStatisticsCalculator.h"
-
-/*
-* @brief The 'QmitkStatisticsTreeModel' is a subclass of 'QmitkAbstractSemanticRelationsStorageModel' and provides
-* functionality to serve as a tree model.
-* The tree model creates a new top-level tree item for each lesion that is stored inside the semantic relations storage.
-* The top-level lesion tree items hold child items for each information type.
-* Each lesion tree item contains lesion data that can be display inside a tree view. The lesion data
-* consists of a lesion with with its UID, name and lesion class. The name or UID is used for the top-level tree items.
-* Additionally the lesion data contains two vectors which define the lesion presence (bool) and the lesion volume (double)
-* for each control-point - information type pair. The lesion volume will be used inside this model for the child items.
-* The presence is used inside another tree model.
-*
-* The model uses the 'QmitkStatisticsCalculator' to start the lesion volume calculation for each lesion.
-* This calculator is able to find an existing lesion volume or to trigger the computation of the required statistics.
-* If the required statistics are newly computed and added as a statistics container to the data storage,
-* this model will be notified about this event (see 'NodeAdded', 'NodeChanged' and 'NodeRemoved') and will update
-* its lesion tree items.
-*/
-class MITKSEMANTICRELATIONSUI_EXPORT QmitkStatisticsTreeModel : public QmitkAbstractSemanticRelationsStorageModel
-{
- Q_OBJECT
-
-public:
-
- /**
- * @brief Initialize the root item of the model. The root item does not have a parent item.
- */
- QmitkStatisticsTreeModel(QObject* parent = nullptr);
-
- //////////////////////////////////////////////////////////////////////////
- // overridden virtual functions from QAbstractItemModel
- //////////////////////////////////////////////////////////////////////////
- QModelIndex index(int row, int column, const QModelIndex& itemIndex = QModelIndex()) const override;
- QModelIndex parent(const QModelIndex& itemIndex) const override;
-
- int rowCount(const QModelIndex& itemIndex = QModelIndex()) const override;
- int columnCount(const QModelIndex& itemIndex = QModelIndex()) const override;
-
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
- //////////////////////////////////////////////////////////////////////////
- // end override
- //////////////////////////////////////////////////////////////////////////
-
-protected:
-
- void DataStorageChanged() override;
- void NodePredicateChanged() override { }
- void NodeAdded(const mitk::DataNode*) override;
- void NodeChanged(const mitk::DataNode*) override;
- void NodeRemoved(const mitk::DataNode*) override;
- /**
- * @brief Overridden from 'QmitkAbstractSemanticRelationsStorageModel': This function retrieves all control points
- * of the current case and stores them to define the header of the tree.
- * Furthermore all lesions are retrieved and the lesion data is stored and show in the tree view.
- */
- void SetData() override;
-
-private:
-
- void SetLesionData();
- void AddLesion(const mitk::SemanticTypes::Lesion& lesion);
-
- QmitkLesionTreeItem* GetItemByIndex(const QModelIndex& index) const;
-
- std::unique_ptr<QmitkStatisticsCalculator> m_StatisticsCalculator;
-
- std::shared_ptr<QmitkLesionTreeItem> m_RootItem;
- mitk::SemanticTypes::ControlPointVector m_ControlPoints;
- mitk::SemanticTypes::InformationTypeVector m_InformationTypes;
- mitk::SemanticTypes::LesionVector m_CurrentLesions;
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/QmitkTableItemThumbnailDelegate.h b/Modules/SemanticRelationsUI/include/QmitkTableItemThumbnailDelegate.h
deleted file mode 100644
index d46d68d5da..0000000000
--- a/Modules/SemanticRelationsUI/include/QmitkTableItemThumbnailDelegate.h
+++ /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.
-
-============================================================================*/
-
-#ifndef QmitkTableItemThumbnailDelegate_h
-#define QmitkTableItemThumbnailDelegate_h
-
-#include <QStyledItemDelegate>
-
-/*
-* @brief The QmitkTableItemThumbnailDelegate is a subclass of the QmitkAbstractSemanticRelationsStorageModel
-*/
-class QmitkTableItemThumbnailDelegate : public QStyledItemDelegate
-{
- Q_OBJECT
-
-public:
-
- QmitkTableItemThumbnailDelegate(QObject* parent = nullptr);
-
- void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override;
-};
-
-#endif
diff --git a/Modules/SemanticRelationsUI/include/mitkModuleActivator.h b/Modules/SemanticRelationsUI/include/mitkModuleActivator.h
deleted file mode 100644
index e9ab999834..0000000000
--- a/Modules/SemanticRelationsUI/include/mitkModuleActivator.h
+++ /dev/null
@@ -1,42 +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 mitkModuleActivator_h
-#define mitkModuleActivator_h
-
-// Micro Services
-#include <usModuleActivator.h>
-#include <usModuleEvent.h>
-#include <usServiceRegistration.h>
-#include <usServiceTracker.h>
-
-#include <memory>
-
-// qt widgets module
-#include "mitkIDataStorageInspectorProvider.h"
-
-namespace mitk
-{
- /*
- * This is the module activator for the "SemanticRelationsUI" module.
- */
- class SemanticRelationsUIActivator : public us::ModuleActivator
- {
- public:
- void Load(us::ModuleContext* context) override;
- void Unload(us::ModuleContext* context) override;
-
- private:
- std::unique_ptr<mitk::IDataStorageInspectorProvider> m_PatientTableInspector;
- };
-}
-#endif
diff --git a/Modules/SemanticRelationsUI/src/QmitkAbstractSemanticRelationsStorageInspector.cpp b/Modules/SemanticRelationsUI/src/QmitkAbstractSemanticRelationsStorageInspector.cpp
deleted file mode 100644
index 0bd50689da..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkAbstractSemanticRelationsStorageInspector.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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkAbstractSemanticRelationsStorageInspector.h"
-
-QmitkAbstractSemanticRelationsStorageInspector::QmitkAbstractSemanticRelationsStorageInspector(QWidget* parent /*= nullptr*/)
- : QmitkAbstractDataStorageInspector(parent)
-{
- // nothing here
-}
-
-QmitkAbstractSemanticRelationsStorageInspector::~QmitkAbstractSemanticRelationsStorageInspector()
-{
- // nothing here
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkAbstractSemanticRelationsStorageModel.cpp b/Modules/SemanticRelationsUI/src/QmitkAbstractSemanticRelationsStorageModel.cpp
deleted file mode 100644
index b0f0254cd6..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkAbstractSemanticRelationsStorageModel.cpp
+++ /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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkAbstractSemanticRelationsStorageModel.h"
-
-#include "QmitkCustomVariants.h"
-
-QmitkAbstractSemanticRelationsStorageModel::QmitkAbstractSemanticRelationsStorageModel(QObject* parent /*= nullptr*/)
- : QmitkAbstractDataStorageModel(parent)
- , m_SemanticRelationsDataStorageAccess(nullptr)
-{
- m_SemanticRelationsIntegration = std::make_unique<mitk::SemanticRelationsIntegration>();
- m_SemanticRelationsIntegration->AddObserver(this);
-}
-
-QmitkAbstractSemanticRelationsStorageModel::~QmitkAbstractSemanticRelationsStorageModel()
-{
- if (nullptr != m_SemanticRelationsIntegration)
- {
- m_SemanticRelationsIntegration->RemoveObserver(this);
- }
-}
-
-void QmitkAbstractSemanticRelationsStorageModel::Update(const mitk::SemanticTypes::CaseID& caseID)
-{
- // if the case ID of updated instance is equal to the currently active caseID
- if (caseID == m_CaseID)
- {
- UpdateModelData();
- }
-}
-
-void QmitkAbstractSemanticRelationsStorageModel::SetCaseID(const mitk::SemanticTypes::CaseID& caseID)
-{
- m_CaseID = caseID;
- UpdateModelData();
-}
-
-void QmitkAbstractSemanticRelationsStorageModel::SetLesion(const mitk::SemanticTypes::Lesion& lesion)
-{
- m_Lesion = lesion;
- UpdateModelData();
-}
-
-void QmitkAbstractSemanticRelationsStorageModel::SetDataNodeSelection(const QList<mitk::DataNode::Pointer>& dataNodeSelection)
-{
- m_SelectedDataNodes = dataNodeSelection;
- UpdateModelData();
-}
-
-void QmitkAbstractSemanticRelationsStorageModel::UpdateModelData()
-{
- if (nullptr == m_SemanticRelationsDataStorageAccess)
- {
- return;
- }
-
- // update the model, so that the table will be filled with the new patient information
- beginResetModel();
-
- SetData();
-
- endResetModel();
- emit ModelUpdated();
-}
-
-void QmitkAbstractSemanticRelationsStorageModel::DataStorageChanged()
-{
- m_SemanticRelationsDataStorageAccess = std::make_unique<mitk::SemanticRelationsDataStorageAccess>(m_DataStorage.Lock());
- UpdateModelData();
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkControlPointDialog.cpp b/Modules/SemanticRelationsUI/src/QmitkControlPointDialog.cpp
deleted file mode 100644
index 4dfd6870d8..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkControlPointDialog.cpp
+++ /dev/null
@@ -1,61 +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 "QmitkControlPointDialog.h"
-
-#include <QAbstractItemModel>
-#include <QStringListModel>
-#include <QLabel>
-#include <QLayout>
-#include <qpushbutton.h>
-
-QmitkControlPointDialog::QmitkControlPointDialog(QWidget* parent)
- : QDialog(parent)
-{
- QBoxLayout* verticalLayout = new QVBoxLayout(this);
- verticalLayout->setMargin(5);
- verticalLayout->setSpacing(5);
-
- QLabel* dateLabel = new QLabel(tr("Set date"), this);
- verticalLayout->addWidget(dateLabel);
-
- m_DateEdit = new QDateEdit(this);
- m_DateEdit->setDisplayFormat("yyyy-MM-dd");
- m_DateEdit->setFocus();
- verticalLayout->addWidget(m_DateEdit);
-
- QPushButton* acceptButton = new QPushButton(tr("Ok"), this);
- QPushButton* cancelButton = new QPushButton(tr("Cancel"), this);
- acceptButton->setDefault(true);
-
- connect(acceptButton, &QPushButton::clicked, this, &QmitkControlPointDialog::accept);
- connect(cancelButton, &QPushButton::clicked, this, &QmitkControlPointDialog::reject);
-
- QBoxLayout* horizontalLayout = new QHBoxLayout();
- horizontalLayout->setSpacing(5);
- horizontalLayout->addStretch();
- horizontalLayout->addWidget(acceptButton);
- horizontalLayout->addWidget(cancelButton);
- verticalLayout->addLayout(horizontalLayout);
-
- setMinimumSize(250, 100);
-}
-
-void QmitkControlPointDialog::SetCurrentDate(mitk::SemanticTypes::ControlPoint currentControlPoint)
-{
- m_DateEdit->setDate(QDate(currentControlPoint.date.year(), currentControlPoint.date.month(), currentControlPoint.date.day()));
-}
-
-QDate QmitkControlPointDialog::GetCurrentDate() const
-{
- return m_DateEdit->date();
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkLesionTextDialog.cpp b/Modules/SemanticRelationsUI/src/QmitkLesionTextDialog.cpp
deleted file mode 100644
index 0eb9a7aefd..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkLesionTextDialog.cpp
+++ /dev/null
@@ -1,63 +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 "QmitkLesionTextDialog.h"
-
-#include <QLabel>
-#include <QLayout>
-#include <qpushbutton.h>
-
-QmitkLesionTextDialog::QmitkLesionTextDialog(QWidget* parent)
- : QDialog(parent)
-{
- QBoxLayout* verticalLayout = new QVBoxLayout(this);
- verticalLayout->setMargin(5);
- verticalLayout->setSpacing(5);
-
- QLabel* dialogLabel = new QLabel(tr("Set lesion information"), this);
- verticalLayout->addWidget(dialogLabel);
-
- m_LineEdit = new QLineEdit(this);
- m_LineEdit->setFocus();
- verticalLayout->addWidget(m_LineEdit);
-
- QPushButton* acceptButton = new QPushButton(tr("Ok"), this);
- QPushButton* cancelButton = new QPushButton(tr("Cancel"), this);
- acceptButton->setDefault(true);
-
- connect(acceptButton, &QPushButton::clicked, this, &QmitkLesionTextDialog::accept);
- connect(cancelButton, &QPushButton::clicked, this, &QmitkLesionTextDialog::reject);
-
- QBoxLayout* horizontalLayout = new QHBoxLayout();
- horizontalLayout->setSpacing(5);
- horizontalLayout->addStretch();
- horizontalLayout->addWidget(acceptButton);
- horizontalLayout->addWidget(cancelButton);
- verticalLayout->addLayout(horizontalLayout);
-
- setMinimumSize(250, 100);
-}
-
-void QmitkLesionTextDialog::SetLineEditText(const std::string& lineEditText)
-{
- m_LineEdit->setText(QString::fromStdString(lineEditText));
-}
-
-QString QmitkLesionTextDialog::GetLineEditText() const
-{
- return m_LineEdit->text();
-}
-
-QLineEdit* QmitkLesionTextDialog::GetLineEdit() const
-{
- return m_LineEdit;
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkLesionTreeItem.cpp b/Modules/SemanticRelationsUI/src/QmitkLesionTreeItem.cpp
deleted file mode 100644
index 1546baeb32..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkLesionTreeItem.cpp
+++ /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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkLesionTreeItem.h"
-
-// qt
-#include <QStringList>
-
-QmitkLesionTreeItem::QmitkLesionTreeItem(mitk::LesionData lesionData/* = mitk::LesionTreeItemData()*/)
-{
- m_ItemData = lesionData;
-}
-
-void QmitkLesionTreeItem::SetParent(ParentPointer parent)
-{
- m_ParentItem = parent;
-}
-
-int QmitkLesionTreeItem::GetRow() const
-{
- if (m_ParentItem.expired())
- {
- return 0;
- }
-
- auto parentItem = m_ParentItem.lock();
- return parentItem->GetRowOfChild(this->shared_from_this());
-}
-
-int QmitkLesionTreeItem::GetRowOfChild(ChildConstPointer child) const
-{
- auto it = std::find(m_Children.begin(), m_Children.end(), child);
- if (it == m_Children.end())
- {
- return -1;
- }
- else
- {
- return std::distance(m_Children.begin(), it);
- }
-}
-
-void QmitkLesionTreeItem::AddChild(ChildPointer child)
-{
- auto it = std::find(m_Children.begin(), m_Children.end(), child);
- if (it == m_Children.end())
- {
- // child does not already exist; add to vector of children
- m_Children.push_back(child);
- // add parent item
- child->SetParent(this->shared_from_this());
- }
-}
-
-void QmitkLesionTreeItem::RemoveChild(ChildPointer child)
-{
- auto it = std::find(m_Children.begin(), m_Children.end(), child);
- if (it != m_Children.end())
- {
- m_Children.erase(it);
- }
-}
-
-void QmitkLesionTreeItem::SetData(const mitk::LesionData& lesionData)
-{
- m_ItemData = lesionData;
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkLesionTreeModel.cpp b/Modules/SemanticRelationsUI/src/QmitkLesionTreeModel.cpp
deleted file mode 100644
index fddbc1637d..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkLesionTreeModel.cpp
+++ /dev/null
@@ -1,298 +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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkLesionTreeModel.h"
-
-// semantic relations module
-#include <mitkControlPointManager.h>
-#include <mitkLesionManager.h>
-#include <mitkNodePredicates.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsInference.h>
-#include <mitkRelationStorage.h>
-
-// qt
-#include <QColor>
-
-QmitkLesionTreeModel::QmitkLesionTreeModel(QObject* parent/* = nullptr*/)
- : QmitkAbstractSemanticRelationsStorageModel(parent)
- , m_LastSegmentation(nullptr)
- , m_RootItem(std::make_shared<QmitkLesionTreeItem>(mitk::LesionData()))
-{
- // nothing here
-}
-
-//////////////////////////////////////////////////////////////////////////
-// overridden virtual functions from QAbstractItemModel
-//////////////////////////////////////////////////////////////////////////
-QModelIndex QmitkLesionTreeModel::index(int row, int column, const QModelIndex& itemIndex) const
-{
- if (!hasIndex(row, column, itemIndex))
- {
- return QModelIndex();
- }
-
- auto childItem = GetItemByIndex(itemIndex)->GetChildInRow(row);
- if (nullptr == childItem)
- {
- return QModelIndex();
- }
-
- return createIndex(row, column, childItem.get());
-}
-
-QModelIndex QmitkLesionTreeModel::parent(const QModelIndex& itemIndex) const
-{
- if (!itemIndex.isValid())
- {
- return QModelIndex();
- }
-
- auto parentItem = GetItemByIndex(itemIndex)->GetParent();
- if (parentItem.expired())
- {
- return QModelIndex();
- }
-
- auto sharedParent = parentItem.lock();
- if (sharedParent == m_RootItem)
- {
- return QModelIndex();
- }
-
- return createIndex(sharedParent->GetRow(), 0, sharedParent.get());
-}
-
-int QmitkLesionTreeModel::rowCount(const QModelIndex& itemIndex/* = QModelIndex()*/) const
-{
- return GetItemByIndex(itemIndex)->ChildCount();
-}
-
-int QmitkLesionTreeModel::columnCount(const QModelIndex&/* itemIndex = QModelIndex() */) const
-{
- if (0 == m_RootItem->ChildCount())
- {
- // no lesion items stored, no need to display columns
- return 0;
- }
-
- return m_ControlPoints.size() + 1;
-}
-
-QVariant QmitkLesionTreeModel::data(const QModelIndex& index, int role) const
-{
- if (!index.isValid())
- {
- return QVariant();
- }
-
- if (index.column() < 0 || index.column() > static_cast<int>(m_ControlPoints.size()))
- {
- return QVariant();
- }
-
- QmitkLesionTreeItem* currentItem = GetItemByIndex(index);
- if (Qt::DisplayRole == role)
- {
- if (currentItem->GetParent().expired())
- {
- return QVariant();
- }
-
- auto parentItem = currentItem->GetParent().lock();
- // parent exists and is the root item -> 1. item of a lesion entry
- if (m_RootItem == parentItem)
- {
- // display role fills the first columns with the lesion UID / name
- if (0 == index.column())
- {
- std::string itemString = currentItem->GetData().GetLesionName();
- if (itemString.empty())
- {
- itemString = currentItem->GetData().GetLesionUID();
- }
- return QString::fromStdString(itemString);
- }
- else
- {
- // display role fills other columns with the lesion presence info
- const auto lesionPresence = currentItem->GetData().GetLesionPresence();
- if (index.column() - 1 > static_cast<int>(lesionPresence.size()))
- {
- return "N/A";
- }
-
- if (lesionPresence.at(index.column() - 1))
- {
- return QString::fromStdString("present");
- }
-
- return QString::fromStdString("not present");
- }
- }
- }
-
- if (Qt::BackgroundColorRole == role)
- {
- auto it = m_DataNodePresence.find(currentItem->GetData().GetLesion().UID);
- if (it != m_DataNodePresence.end())
- {
- return it->second ? QVariant(QColor(Qt::darkGreen)) : QVariant(QColor(Qt::transparent));
- }
-
- return QVariant(QColor(Qt::transparent));
- }
-
- if (Qt::UserRole == role)
- {
- return QVariant::fromValue(currentItem);
- }
-
- return QVariant();
-}
-
-QVariant QmitkLesionTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (0 == m_RootItem->ChildCount())
- {
- // no lesion items stored, no need to display the header
- return QVariant();
- }
-
- if (Qt::Horizontal == orientation && Qt::DisplayRole == role)
- {
- if (0 == section)
- {
- return QVariant("Lesion");
- }
-
- if (static_cast<int>(m_ControlPoints.size()) >= section)
- {
- mitk::SemanticTypes::ControlPoint currentControlPoint = m_ControlPoints.at(section-1);
- return QVariant(QString::fromStdString(currentControlPoint.ToString()));
- }
- }
-
- return QVariant();
-}
-
-const mitk::DataNode* QmitkLesionTreeModel::GetLastSegmentation() const
-{
- return m_LastSegmentation;
-}
-
-void QmitkLesionTreeModel::NodeAdded(const mitk::DataNode* dataNode)
-{
- if (mitk::NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
- {
- m_LastSegmentation = dataNode;
- }
-}
-
-void QmitkLesionTreeModel::SetData()
-{
- m_RootItem = std::make_shared<QmitkLesionTreeItem>(mitk::LesionData());
-
- // get all control points of current case
- m_ControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(m_CaseID);
- // sort the vector of control points for the timeline
- std::sort(m_ControlPoints.begin(), m_ControlPoints.end());
-
- SetLesionData();
- SetSelectedDataNodesPresence();
-}
-
-void QmitkLesionTreeModel::SetLesionData()
-{
- m_CurrentLesions = mitk::RelationStorage::GetAllLesionsOfCase(m_CaseID);
- for (auto& lesion : m_CurrentLesions)
- {
- AddLesion(lesion);
- }
-}
-
-void QmitkLesionTreeModel::AddLesion(const mitk::SemanticTypes::Lesion& lesion)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- // create new lesion tree item data and modify it according to the control point data
- mitk::LesionData lesionData(lesion);
- mitk::ComputeLesionPresence(lesionData, m_CaseID);
-
- // add the top-level lesion item to the root item
- std::shared_ptr<QmitkLesionTreeItem> newLesionTreeItem = std::make_shared<QmitkLesionTreeItem>(lesionData);
- m_RootItem->AddChild(newLesionTreeItem);
-}
-
-void QmitkLesionTreeModel::SetSelectedDataNodesPresence()
-{
- m_DataNodePresence.clear();
- for (const auto& dataNode : qAsConst(m_SelectedDataNodes))
- {
- if (!mitk::SemanticRelationsInference::InstanceExists(dataNode))
- {
- continue;
- }
-
- for (const auto& lesion : m_CurrentLesions)
- {
- if (!mitk::SemanticRelationsInference::InstanceExists(m_CaseID, lesion))
- {
- continue;
- }
- try
- {
- // set the lesion presence for the current node
- bool dataNodePresence = mitk::SemanticRelationsInference::IsLesionPresent(lesion, dataNode);
- SetDataNodePresenceOfLesion(&lesion, dataNodePresence);
- }
- catch (const mitk::SemanticRelationException&)
- {
- continue;
- }
- }
- }
-}
-
-void QmitkLesionTreeModel::SetDataNodePresenceOfLesion(const mitk::SemanticTypes::Lesion* lesion, bool dataNodePresence)
-{
- std::map<mitk::SemanticTypes::ID, bool>::iterator iter = m_DataNodePresence.find(lesion->UID);
- if (iter != m_DataNodePresence.end())
- {
- // key already existing, overwrite already stored bool value
- iter->second = dataNodePresence;
- }
- else
- {
- m_DataNodePresence.insert(std::make_pair(lesion->UID, dataNodePresence));
- }
-}
-
-QmitkLesionTreeItem* QmitkLesionTreeModel::GetItemByIndex(const QModelIndex& index) const
-{
- if (index.isValid())
- {
- auto item = static_cast<QmitkLesionTreeItem*>(index.internalPointer());
- if (nullptr != item)
- {
- return item;
- }
- }
-
- return m_RootItem.get();
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkPatientInfoWidget.cpp b/Modules/SemanticRelationsUI/src/QmitkPatientInfoWidget.cpp
deleted file mode 100644
index a0e769cd51..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkPatientInfoWidget.cpp
+++ /dev/null
@@ -1,101 +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 "QmitkPatientInfoWidget.h"
-
-// semantic relations module
-#include <mitkDICOMHelper.h>
-
-// mitk core
-#include <mitkPropertyNameHelper.h>
-
-QmitkPatientInfoWidget::QmitkPatientInfoWidget(QWidget* parent)
- : QWidget(parent)
-{
- Init();
-}
-
-QmitkPatientInfoWidget::~QmitkPatientInfoWidget()
-{
- // nothing here
-}
-
-void QmitkPatientInfoWidget::Init()
-{
- // Create GUI widgets from the Qt Designer's .ui file
- m_Controls.setupUi(this);
-}
-
-void QmitkPatientInfoWidget::SetPatientInfo(const mitk::DataNode* dataNode)
-{
- if (nullptr == dataNode)
- {
- MITK_INFO << "Not a valid data node.";
- return;
- }
-
- mitk::BaseData* baseData = dataNode->GetData();
- if (nullptr == baseData)
- {
- MITK_INFO << "No valid base data.";
- return;
- }
-
- mitk::BaseProperty* acquisitionDate = baseData->GetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0022).c_str());
- std::string acquisitionDateAsString = "";
- if (nullptr != acquisitionDate)
- {
- acquisitionDateAsString = acquisitionDate->GetValueAsString();
- mitk::DICOMHelper::ReformatDICOMTag(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0022).c_str(), acquisitionDateAsString);
- }
-
- mitk::BaseProperty* acquisitionTime = baseData->GetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0032).c_str());
- std::string acquisitionTimeAsString = "";
- if (nullptr != acquisitionTime)
- {
- acquisitionTimeAsString = acquisitionTime->GetValueAsString();
- mitk::DICOMHelper::ReformatDICOMTag(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0032).c_str(), acquisitionTimeAsString);
- }
-
- std::string patiensBirthDateAsString = "";
- mitk::BaseProperty* patientBirthDate = baseData->GetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0010, 0x0030).c_str());
- if (nullptr != patientBirthDate)
- {
- patiensBirthDateAsString = patientBirthDate->GetValueAsString();
- mitk::DICOMHelper::ReformatDICOMTag(mitk::GeneratePropertyNameForDICOMTag(0x0010, 0x0030).c_str(), patiensBirthDateAsString);
- }
-
- mitk::BaseProperty* modality = baseData->GetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0060).c_str());
- std::string modalityAsString = "";
- if (nullptr != modality)
- {
- modalityAsString = modality->GetValueAsString();
- mitk::DICOMHelper::ReformatDICOMTag(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0060).c_str(), modalityAsString);
- }
-
- mitk::BaseProperty* gender = baseData->GetProperty(mitk::GeneratePropertyNameForDICOMTag(0x0010, 0x0040).c_str());
- std::string genderAsString = "";
- if (nullptr != gender)
- {
- genderAsString = gender->GetValueAsString();
- mitk::DICOMHelper::ReformatDICOMTag(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0060).c_str(), genderAsString);
- }
-
- m_Controls.dataIDLineEdit->setText(QString::fromStdString(mitk::DICOMHelper::GetIDFromDataNode(dataNode)));
- m_Controls.nameLineEdit->setText(QString::fromStdString(mitk::DICOMHelper::GetCaseIDFromDataNode(dataNode)));
- m_Controls.dateLineEdit->setText(QString::fromStdString(acquisitionDateAsString));
- m_Controls.timeLineEdit->setText(QString::fromStdString(acquisitionTimeAsString));
- m_Controls.scannerLineEdit->setText("");
- m_Controls.modalityLineEdit->setText(QString::fromStdString(modalityAsString));
- m_Controls.birthdateLineEdit->setText(QString::fromStdString(patiensBirthDateAsString));
- m_Controls.genderLineEdit->setText(QString::fromStdString(genderAsString));
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkPatientInfoWidgetControls.ui b/Modules/SemanticRelationsUI/src/QmitkPatientInfoWidgetControls.ui
deleted file mode 100644
index 3ffbe69f32..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkPatientInfoWidgetControls.ui
+++ /dev/null
@@ -1,166 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkPatientInfoWidgetControls</class>
- <widget class="QWidget" name="QmitkPatientInfoWidgetControls">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>350</width>
- <height>300</height>
- </rect>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="1" column="0" colspan="2">
- <widget class="QLabel" name="patientInfoLabel">
- <property name="font">
- <font>
- <weight>75</weight>
- <italic>false</italic>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Patient data information</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="dataIDLabel">
- <property name="text">
- <string>ID*:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QLineEdit" name="dataIDLineEdit">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QLabel" name="nameLabel">
- <property name="text">
- <string>Name:</string>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <widget class="QLineEdit" name="nameLineEdit">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="4" column="0">
- <widget class="QLabel" name="dateLabel">
- <property name="text">
- <string>Acq. Date:</string>
- </property>
- </widget>
- </item>
- <item row="4" column="1">
- <widget class="QLineEdit" name="dateLineEdit">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- <property name="placeholderText">
- <string>YYYY-MM-DD</string>
- </property>
- </widget>
- </item>
- <item row="5" column="0">
- <widget class="QLabel" name="timeLabel">
- <property name="text">
- <string>Time:</string>
- </property>
- </widget>
- </item>
- <item row="5" column="1">
- <widget class="QLineEdit" name="timeLineEdit">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- <property name="placeholderText">
- <string>hh:mm:ss</string>
- </property>
- </widget>
- </item>
- <item row="6" column="0">
- <widget class="QLabel" name="scannerLabel">
- <property name="text">
- <string>Scanner:</string>
- </property>
- </widget>
- </item>
- <item row="6" column="1">
- <widget class="QLineEdit" name="scannerLineEdit">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="7" column="0">
- <widget class="QLabel" name="modalityLabel">
- <property name="text">
- <string>Modality:</string>
- </property>
- </widget>
- </item>
- <item row="7" column="1">
- <widget class="QLineEdit" name="modalityLineEdit">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="8" column="0">
- <widget class="QLabel" name="birthdateLabel">
- <property name="text">
- <string>Birthdate:</string>
- </property>
- </widget>
- </item>
- <item row="8" column="1">
- <widget class="QLineEdit" name="birthdateLineEdit">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- <property name="placeholderText">
- <string>YYYY-MM-DD</string>
- </property>
- </widget>
- </item>
- <item row="9" column="0">
- <widget class="QLabel" name="genderLabel">
- <property name="text">
- <string>Gender:</string>
- </property>
- </widget>
- </item>
- <item row="9" column="1">
- <widget class="QLineEdit" name="genderLineEdit">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="10" column="0" colspan="2">
- <widget class="QLabel" name="mandatoryLabel">
- <property name="text">
- <string>* mandatory field</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
diff --git a/Modules/SemanticRelationsUI/src/QmitkPatientTableHeaderView.cpp b/Modules/SemanticRelationsUI/src/QmitkPatientTableHeaderView.cpp
deleted file mode 100644
index 7348ebcfda..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkPatientTableHeaderView.cpp
+++ /dev/null
@@ -1,240 +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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkPatientTableHeaderView.h"
-
-// qt
-#include <QPainter>
-#include <QSize>
-
-QmitkPatientTableHeaderView::QmitkPatientTableHeaderView(QWidget* parent/* = nullptr*/)
- : QHeaderView(Qt::Horizontal, parent)
- , m_HeaderModel(nullptr)
-{
- // nothing here
-}
-
-QmitkPatientTableHeaderView::~QmitkPatientTableHeaderView()
-{
- // nothing here
-}
-
-void QmitkPatientTableHeaderView::setModel(QAbstractItemModel* model)
-{
- // retrieve the header model from the given table model
- QVariant variant = model->data(QModelIndex(), HorizontalHeaderDataRole);
- if (variant.isValid() && variant.canConvert<QStandardItemModel*>())
- {
- m_HeaderModel = variant.value<QStandardItemModel*>();
- }
-
- QHeaderView::setModel(model);
-}
-
-void QmitkPatientTableHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const
-{
- if (rect.isValid())
- {
- int top = rect.y();
-
- QModelIndex leafIndex = HeaderIndex(logicalIndex);
- QModelIndexList indexes = ParentIndexList(leafIndex);
- for (const auto& index : qAsConst(indexes))
- {
- top = PaintHeader(painter, index, logicalIndex, rect, top);
- }
-
- return;
- }
-
- QHeaderView::paintSection(painter, rect, logicalIndex);
-}
-
-QSize QmitkPatientTableHeaderView::sectionSizeFromContents(int logicalIndex) const
-{
- if (nullptr != m_HeaderModel)
- {
- QModelIndex headerIndex = HeaderIndex(logicalIndex);
- if (headerIndex.isValid())
- {
- QSize headerSize = HeaderSize(headerIndex);
- headerIndex = headerIndex.parent();
- while (headerIndex.isValid())
- {
- QSize currentHeaderSize = HeaderSize(headerIndex);
- headerSize.rheight() += currentHeaderSize.height();
- if (currentHeaderSize.width() > headerSize.width())
- {
- headerSize.rwidth() = currentHeaderSize.width();
- }
-
- headerIndex = headerIndex.parent();
- }
- return headerSize;
- }
- }
-
- return QHeaderView::sectionSizeFromContents(logicalIndex);
-}
-
-int QmitkPatientTableHeaderView::PaintHeader(QPainter* painter, const QModelIndex& currentIndex, int logicalIndex, const QRect& sectionRect, int top) const
-{
- QModelIndex headerIndex = HeaderIndex(logicalIndex);
- int height = HeaderSize(currentIndex).height();
- if (currentIndex == headerIndex)
- {
- height = sectionRect.height() - top;
- }
- int left = CurrentHeaderLeft(currentIndex, headerIndex, logicalIndex, sectionRect.left());
- int width = CurrentHeaderWidth(currentIndex, headerIndex, logicalIndex);
-
- QStyleOptionHeader headerStyleOptions;
- initStyleOption(&headerStyleOptions);
- headerStyleOptions.text = currentIndex.data(Qt::DisplayRole).toString();
- headerStyleOptions.textAlignment = Qt::AlignCenter;
- painter->save();
-
- QRect rect(left, top, width, height);
- headerStyleOptions.rect = rect;
- style()->drawControl(QStyle::CE_Header, &headerStyleOptions, painter, this);
- painter->restore();
-
- return top + height;
-}
-
-QSize QmitkPatientTableHeaderView::HeaderSize(const QModelIndex& index) const
-{
- QFont font = this->font();
- font.setBold(true);
- QFontMetrics fontMetrics(font);
- QSize fontSize = fontMetrics.size(0, index.data(Qt::DisplayRole).toString());
- QSize emptyFontSize = fontMetrics.size(0, "");
-
- return fontSize + emptyFontSize;
-}
-
-int QmitkPatientTableHeaderView::CurrentHeaderLeft(const QModelIndex& currentIndex, const QModelIndex& headerIndex, int sectionIndex, int left) const
-{
- QModelIndexList headerList = ListHeader(currentIndex);
- if (!headerList.empty())
- {
- int index = headerList.indexOf(headerIndex);
- int firstHeaderSectionIndex = sectionIndex - index;
- --index;
- for (; index >= 0; --index)
- {
- left -= sectionSize(firstHeaderSectionIndex + index);
- }
- }
-
- return left;
-}
-
-int QmitkPatientTableHeaderView::CurrentHeaderWidth(const QModelIndex& currentIndex, const QModelIndex& headerIndex, int sectionIndex) const
-{
- QModelIndexList headerList = ListHeader(currentIndex);
- if (headerList.empty())
- {
- return sectionSize(sectionIndex);
- }
-
- int width = 0;
- int index = headerList.indexOf(headerIndex);
- int firstHeaderSectionIndex = sectionIndex - index;
- for (int i = 0; i < headerList.size(); ++i)
- {
- width += sectionSize(firstHeaderSectionIndex + i);
- }
-
- return width;
-}
-
-QModelIndexList QmitkPatientTableHeaderView::ParentIndexList(QModelIndex index) const
-{
- QModelIndexList indexList;
- while (index.isValid())
- {
- indexList.push_front(index);
- index = index.parent();
- }
-
- return indexList;
-}
-
-QModelIndex QmitkPatientTableHeaderView::HeaderIndex(int sectionIndex) const
-{
- if (nullptr != m_HeaderModel)
- {
- int currentHeaderIndex = -1;
- for (int i = 0; i < m_HeaderModel->columnCount(); ++i)
- {
- QModelIndex modelIndex = FindHeader(m_HeaderModel->index(0, i), sectionIndex, currentHeaderIndex);
- if (modelIndex.isValid())
- {
- return modelIndex;
- }
- }
- }
-
- return QModelIndex();
-}
-
-QModelIndex QmitkPatientTableHeaderView::FindHeader(const QModelIndex& currentIndex, int sectionIndex, int& currentHeaderIndex) const
-{
- if (currentIndex.isValid())
- {
- int childCount = currentIndex.model()->columnCount(currentIndex);
- if (childCount > 0)
- {
- for (int i = 0; i < childCount; ++i)
- {
- QModelIndex modelIndex = FindHeader(currentIndex.child(0, i), sectionIndex, currentHeaderIndex);
- if (modelIndex.isValid())
- {
- return modelIndex;
- }
- }
- }
- else
- {
- ++currentHeaderIndex;
- if (currentHeaderIndex == sectionIndex)
- {
- return currentIndex;
- }
- }
- }
-
- return QModelIndex();
-}
-
-QModelIndexList QmitkPatientTableHeaderView::ListHeader(const QModelIndex& currentIndex) const
-{
- QModelIndexList headerList;
- if (currentIndex.isValid())
- {
- int childCount = currentIndex.model()->columnCount(currentIndex);
- if (childCount > 0)
- {
- for (int i = 0; i < childCount; ++i)
- {
- headerList += ListHeader(currentIndex.child(0, i));
- }
- }
- else
- {
- headerList.push_back(currentIndex);
- }
- }
- return headerList;
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkPatientTableInspector.cpp b/Modules/SemanticRelationsUI/src/QmitkPatientTableInspector.cpp
deleted file mode 100644
index 96d48e69cb..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkPatientTableInspector.cpp
+++ /dev/null
@@ -1,179 +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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkPatientTableInspector.h"
-#include "QmitkPatientTableHeaderView.h"
-
-// mitk qt widgets module
-#include "QmitkCustomVariants.h"
-#include "QmitkEnums.h"
-
-// qt
-#include <QKeyEvent>
-#include <QSignalMapper>
-
-QmitkPatientTableInspector::QmitkPatientTableInspector(QWidget* parent/* =nullptr*/)
- : QmitkAbstractSemanticRelationsStorageInspector(parent)
-{
- m_Controls.setupUi(this);
-
- QmitkPatientTableHeaderView* patientTableHeaderView = new QmitkPatientTableHeaderView(m_Controls.tableView);
- m_Controls.tableView->setHorizontalHeader(patientTableHeaderView);
- m_Controls.tableView->horizontalHeader()->setHighlightSections(false);
- m_Controls.tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
- m_Controls.tableView->verticalHeader()->setHighlightSections(false);
- m_Controls.tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
- m_Controls.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
- m_Controls.tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
- m_Controls.tableView->setContextMenuPolicy(Qt::CustomContextMenu);
-
- m_StorageModel = new QmitkPatientTableModel(m_Controls.tableView);
- m_Controls.tableView->setModel(m_StorageModel);
- m_ItemDelegate = new QmitkTableItemThumbnailDelegate(m_Controls.tableView);
- //m_Controls.tableView->setItemDelegate(m_ItemDelegate);
-
- SetUpConnections();
-}
-
-QAbstractItemView* QmitkPatientTableInspector::GetView()
-{
- return m_Controls.tableView;
-}
-
-const QAbstractItemView* QmitkPatientTableInspector::GetView() const
-{
- return m_Controls.tableView;
-}
-
-void QmitkPatientTableInspector::SetSelectionMode(SelectionMode mode)
-{
- m_Controls.tableView->setSelectionMode(mode);
-}
-
-QmitkPatientTableInspector::SelectionMode QmitkPatientTableInspector::GetSelectionMode() const
-{
- return m_Controls.tableView->selectionMode();
-}
-
-void QmitkPatientTableInspector::SetCaseID(const mitk::SemanticTypes::CaseID& caseID)
-{
- m_StorageModel->SetCaseID(caseID);
-}
-
-void QmitkPatientTableInspector::SetLesion(const mitk::SemanticTypes::Lesion& lesion)
-{
- m_StorageModel->SetLesion(lesion);
-}
-
-QItemSelectionModel* QmitkPatientTableInspector::GetSelectionModel()
-{
- return m_Controls.tableView->selectionModel();
-}
-
-void QmitkPatientTableInspector::Initialize()
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- m_StorageModel->SetDataStorage(dataStorage);
- m_StorageModel->SetNodePredicate(m_NodePredicate);
-
- m_Connector->SetView(m_Controls.tableView);
-}
-
-void QmitkPatientTableInspector::OnModelUpdated()
-{
- m_Controls.tableView->resizeRowsToContents();
- m_Controls.tableView->resizeColumnsToContents();
-}
-
-void QmitkPatientTableInspector::OnNodeButtonClicked(const QString& nodeType)
-{
- m_StorageModel->SetNodeType(nodeType.toStdString());
-}
-
-void QmitkPatientTableInspector::OnDataNodeSelectionChanged(const QList<mitk::DataNode::Pointer>& dataNodeSelection)
-{
- if (m_StorageModel->GetLesion().UID.empty())
- {
- return;
- }
-
- // if lesion is set, reset to empty lesion to hide the "lesion presence background highlighting" in the model
- m_StorageModel->SetLesion(mitk::SemanticTypes::Lesion());
- // need to explicitly set the data node selection
- SetCurrentSelection(dataNodeSelection);
-}
-
-void QmitkPatientTableInspector::OnItemDoubleClicked(const QModelIndex& itemIndex)
-{
- if (itemIndex.isValid())
- {
- QVariant qvariantDataNode = m_StorageModel->data(itemIndex, QmitkDataNodeRawPointerRole);
- if (qvariantDataNode.canConvert<mitk::DataNode*>())
- {
- mitk::DataNode* dataNode = qvariantDataNode.value<mitk::DataNode*>();
- emit DataNodeDoubleClicked(dataNode);
- }
- }
-}
-
-void QmitkPatientTableInspector::SetUpConnections()
-{
- connect(m_StorageModel, &QmitkPatientTableModel::ModelUpdated, this, &QmitkPatientTableInspector::OnModelUpdated);
- connect(m_Controls.tableView, &QTableView::customContextMenuRequested, this, &QmitkPatientTableInspector::OnContextMenuRequested);
-
- QSignalMapper* nodeButtonSignalMapper = new QSignalMapper(this);
- nodeButtonSignalMapper->setMapping(m_Controls.imageNodeButton, QString("Image"));
- nodeButtonSignalMapper->setMapping(m_Controls.segmentationNodeButton, QString("Segmentation"));
- connect(nodeButtonSignalMapper, static_cast<void (QSignalMapper::*)(const QString&)>(&QSignalMapper::mapped), this, &QmitkPatientTableInspector::OnNodeButtonClicked);
- connect(m_Controls.imageNodeButton, &QRadioButton::clicked, nodeButtonSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map));
- connect(m_Controls.segmentationNodeButton, &QRadioButton::clicked, nodeButtonSignalMapper, static_cast<void(QSignalMapper::*)()>(&QSignalMapper::map));
- m_Controls.imageNodeButton->setChecked(true);
-
- connect(this, &QmitkPatientTableInspector::CurrentSelectionChanged, this, &QmitkPatientTableInspector::OnDataNodeSelectionChanged);
- connect(m_Controls.tableView, &QTableView::doubleClicked, this, &QmitkPatientTableInspector::OnItemDoubleClicked);
-}
-
-void QmitkPatientTableInspector::keyPressEvent(QKeyEvent* e)
-{
- mitk::DataNode* dataNode = nullptr;
- QModelIndex selectedIndex = m_Controls.tableView->currentIndex();
- if (selectedIndex.isValid())
- {
- QVariant qvariantDataNode = m_StorageModel->data(selectedIndex, QmitkDataNodeRawPointerRole);
- if (qvariantDataNode.canConvert<mitk::DataNode*>())
- {
- dataNode = qvariantDataNode.value<mitk::DataNode*>();
- }
- }
-
- if (nullptr == dataNode)
- {
- return;
- }
-
- int key = e->key();
- switch (key)
- {
- case Qt::Key_Delete:
- emit OnNodeRemoved(dataNode);
- break;
- default:
- break;
- }
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkPatientTableInspector.ui b/Modules/SemanticRelationsUI/src/QmitkPatientTableInspector.ui
deleted file mode 100644
index c953d1b58a..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkPatientTableInspector.ui
+++ /dev/null
@@ -1,63 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkPatientTableInspector</class>
- <widget class="QWidget" name="QmitkPatientTableInspector">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>350</width>
- <height>300</height>
- </rect>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <property name="leftMargin">
- <number>0</number>
- </property>
- <property name="topMargin">
- <number>0</number>
- </property>
- <property name="rightMargin">
- <number>0</number>
- </property>
- <property name="bottomMargin">
- <number>0</number>
- </property>
- <item row="0" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Semantic Relations content:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="2">
- <widget class="QRadioButton" name="segmentationNodeButton">
- <property name="text">
- <string>Show segmentation nodes</string>
- </property>
- <attribute name="buttonGroup">
- <string notr="true">nodeButtonGroup</string>
- </attribute>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QRadioButton" name="imageNodeButton">
- <property name="text">
- <string>Show image nodes</string>
- </property>
- <attribute name="buttonGroup">
- <string notr="true">nodeButtonGroup</string>
- </attribute>
- </widget>
- </item>
- <item row="1" column="0" colspan="3">
- <widget class="QTableView" name="tableView"/>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
- <buttongroups>
- <buttongroup name="nodeButtonGroup"/>
- </buttongroups>
-</ui>
diff --git a/Modules/SemanticRelationsUI/src/QmitkPatientTableModel.cpp b/Modules/SemanticRelationsUI/src/QmitkPatientTableModel.cpp
deleted file mode 100644
index c60140b1c6..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkPatientTableModel.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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkPatientTableModel.h"
-#include "QmitkPatientTableHeaderView.h"
-#include "QmitkSemanticRelationsUIHelper.h"
-
-// semantic relations module
-#include <mitkControlPointManager.h>
-#include <mitkNodePredicates.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsInference.h>
-#include <mitkRelationStorage.h>
-
-#include <QmitkCustomVariants.h>
-#include <QmitkEnums.h>
-
-// qt
-#include <QColor>
-
-// c++
-#include <iostream>
-#include <string>
-
-QmitkPatientTableModel::QmitkPatientTableModel(QObject* parent /*= nullptr*/)
- : QmitkAbstractSemanticRelationsStorageModel(parent)
- , m_SelectedNodeType("Image")
-{
- m_HeaderModel = new QStandardItemModel(this);
-}
-
-QmitkPatientTableModel::~QmitkPatientTableModel()
-{
- // nothing here
-}
-
-QModelIndex QmitkPatientTableModel::index(int row, int column, const QModelIndex& parent/* = QModelIndex()*/) const
-{
- if (hasIndex(row, column, parent))
- {
- return createIndex(row, column);
- }
-
- return QModelIndex();
-}
-
-QModelIndex QmitkPatientTableModel::parent(const QModelIndex& /*child*/) const
-{
- return QModelIndex();
-}
-
-int QmitkPatientTableModel::rowCount(const QModelIndex& parent/* = QModelIndex()*/) const
-{
- if (parent.isValid())
- {
- return 0;
- }
-
- return m_InformationTypes.size();
-}
-
-int QmitkPatientTableModel::columnCount(const QModelIndex& parent/* = QModelIndex()*/) const
-{
- if (parent.isValid())
- {
- return 0;
- }
-
- return m_ExaminationPeriods.size();
-}
-
-QVariant QmitkPatientTableModel::data(const QModelIndex& index, int role/* = Qt::DisplayRole*/) const
-{
- // special role for returning the horizontal header
- if (QmitkPatientTableHeaderView::HorizontalHeaderDataRole == role)
- {
- return QVariant::fromValue<QStandardItemModel*>(m_HeaderModel);
- }
-
- if (!index.isValid())
- {
- return QVariant();
- }
-
- if (index.row() < 0 || index.row() >= static_cast<int>(m_InformationTypes.size())
- || index.column() < 0 || index.column() >= static_cast<int>(m_ExaminationPeriods.size()))
- {
- return QVariant();
- }
-
- mitk::DataNode* dataNode = GetCurrentDataNode(index);
-
- if (Qt::DecorationRole == role)
- {
- auto it = m_PixmapMap.find(dataNode);
- if (it != m_PixmapMap.end())
- {
- return QVariant(it->second);
- }
-
- auto emptyPixmap = QPixmap(120, 120);
- emptyPixmap.fill(Qt::transparent);
- return emptyPixmap;
- }
-
- if (Qt::BackgroundColorRole == role)
- {
- auto it = m_LesionPresence.find(dataNode);
- if (it != m_LesionPresence.end())
- {
- return it->second ? QVariant(QColor(Qt::darkGreen)) : QVariant(QColor(Qt::transparent));
- }
-
- return QVariant(QColor(Qt::transparent));
- }
-
- if (QmitkDataNodeRole == role)
- {
- return QVariant::fromValue<mitk::DataNode::Pointer>(mitk::DataNode::Pointer(dataNode));
- }
-
- if (QmitkDataNodeRawPointerRole == role)
- {
- return QVariant::fromValue<mitk::DataNode*>(dataNode);
- }
-
- return QVariant();
-}
-
-QVariant QmitkPatientTableModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (Qt::Vertical == orientation && Qt::DisplayRole == role)
- {
- if (static_cast<int>(m_InformationTypes.size()) > section)
- {
- mitk::SemanticTypes::InformationType currentInformationType = m_InformationTypes.at(section);
- return QVariant(QString::fromStdString(currentInformationType));
- }
- }
-
- return QVariant();
-}
-
-Qt::ItemFlags QmitkPatientTableModel::flags(const QModelIndex& index) const
-{
- Qt::ItemFlags flags;
- mitk::DataNode* dataNode = GetCurrentDataNode(index);
- if (nullptr != dataNode)
- {
- flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
- }
-
- return flags;
-}
-
-void QmitkPatientTableModel::SetNodeType(const std::string& nodeType)
-{
- m_SelectedNodeType = nodeType;
- UpdateModelData();
-}
-
-void QmitkPatientTableModel::NodePredicateChanged()
-{
- UpdateModelData();
-}
-
-void QmitkPatientTableModel::SetData()
-{
- // get all examination periods of current case
- m_ExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(m_CaseID);
-
- // sort all examination periods for the timeline
- mitk::SortAllExaminationPeriods(m_CaseID, m_ExaminationPeriods);
-
- // rename examination periods according to their new order
- std::string examinationPeriodName = "Baseline";
- for (size_t i = 0; i < m_ExaminationPeriods.size(); ++i)
- {
- auto& examinationPeriod = m_ExaminationPeriods.at(i);
- examinationPeriod.name = examinationPeriodName;
- mitk::RelationStorage::RenameExaminationPeriod(m_CaseID, examinationPeriod);
- examinationPeriodName = "Follow-up " + std::to_string(i);
- }
-
- // get all information types points of current case
- m_InformationTypes = mitk::RelationStorage::GetAllInformationTypesOfCase(m_CaseID);
-
- if ("Image" == m_SelectedNodeType)
- {
- m_CurrentDataNodes = m_SemanticRelationsDataStorageAccess->GetAllImagesOfCase(m_CaseID);
- }
- else if ("Segmentation" == m_SelectedNodeType)
- {
- m_CurrentDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSegmentationsOfCase(m_CaseID);
- }
-
- SetHeaderModel();
- SetPixmaps();
- SetLesionPresences();
-}
-
-void QmitkPatientTableModel::SetHeaderModel()
-{
- m_HeaderModel->clear();
- QStandardItem* rootItem = new QStandardItem("Timeline");
- QList<QStandardItem*> standardItems;
-
- for (const auto& examinationPeriod : m_ExaminationPeriods)
- {
- QStandardItem* examinationPeriodItem = new QStandardItem(QString::fromStdString(examinationPeriod.name));
- standardItems.push_back(examinationPeriodItem);
- rootItem->appendColumn(standardItems);
- standardItems.clear();
- }
-
- m_HeaderModel->setItem(0, 0, rootItem);
-}
-
-void QmitkPatientTableModel::SetPixmaps()
-{
- m_PixmapMap.clear();
- for (const auto& dataNode : m_CurrentDataNodes)
- {
- // set the pixmap for the current node
- QPixmap pixmapFromImage = QmitkSemanticRelationsUIHelper::GetPixmapFromImageNode(dataNode);
- SetPixmapOfNode(dataNode, &pixmapFromImage);
- }
-}
-
-void QmitkPatientTableModel::SetPixmapOfNode(const mitk::DataNode* dataNode, QPixmap* pixmapFromImage)
-{
- if (nullptr == dataNode)
- {
- return;
- }
-
- std::map<mitk::DataNode::ConstPointer, QPixmap>::iterator iter = m_PixmapMap.find(dataNode);
- if (iter != m_PixmapMap.end())
- {
- // key already existing
- if (nullptr != pixmapFromImage)
- {
- // overwrite already stored pixmap
- iter->second = pixmapFromImage->scaled(120, 120, Qt::IgnoreAspectRatio);
- }
- else
- {
- // remove key if no pixmap is given
- m_PixmapMap.erase(iter);
- }
- }
- else
- {
- m_PixmapMap.insert(std::make_pair(dataNode, pixmapFromImage->scaled(120, 120, Qt::IgnoreAspectRatio)));
- }
-}
-
-void QmitkPatientTableModel::SetLesionPresences()
-{
- m_LesionPresence.clear();
- if (!mitk::SemanticRelationsInference::InstanceExists(m_CaseID, m_Lesion))
- {
- return;
- }
-
- for (const auto& dataNode : m_CurrentDataNodes)
- {
- if (!mitk::SemanticRelationsInference::InstanceExists(dataNode))
- {
- continue;
- }
-
- // set the lesion presence for the current node
- bool lesionPresence = mitk::SemanticRelationsInference::IsLesionPresent(m_Lesion, dataNode);
- SetLesionPresenceOfNode(dataNode, lesionPresence);
- }
-}
-
-void QmitkPatientTableModel::SetLesionPresenceOfNode(const mitk::DataNode* dataNode, bool lesionPresence)
-{
- std::map<mitk::DataNode::ConstPointer, bool>::iterator iter = m_LesionPresence.find(dataNode);
- if (iter != m_LesionPresence.end())
- {
- // key already existing, overwrite already stored bool value
- iter->second = lesionPresence;
- }
- else
- {
- m_LesionPresence.insert(std::make_pair(dataNode, lesionPresence));
- }
-}
-
-mitk::DataNode* QmitkPatientTableModel::GetCurrentDataNode(const QModelIndex& index) const
-{
- if (!index.isValid())
- {
- return nullptr;
- }
-
- auto examinationPeriod = m_ExaminationPeriods.at(index.column());
- auto currentInformationType = m_InformationTypes.at(index.row());
- auto controlPointsOfExaminationPeriod = examinationPeriod.controlPointUIDs;
- for (const auto& controlPointUID : controlPointsOfExaminationPeriod)
- {
- auto currentControlPoint = mitk::GetControlPointByUID(m_CaseID, controlPointUID);
- try
- {
- std::vector<mitk::DataNode::Pointer> filteredDataNodes;
- if ("Image" == m_SelectedNodeType)
- {
- filteredDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSpecificImages(m_CaseID, currentControlPoint, currentInformationType);
- }
- else if ("Segmentation" == m_SelectedNodeType)
- {
- filteredDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSpecificSegmentations(m_CaseID, currentControlPoint, currentInformationType);
- }
-
- if (filteredDataNodes.empty())
- {
- // try next control point
- continue;
- }
- else
- {
- // found a specific image
- return filteredDataNodes.front();
- }
- }
- catch (const mitk::SemanticRelationException&)
- {
- return nullptr;
- }
- }
- // could not find a specif image
- return nullptr;
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkSemanticRelationsUIHelper.cpp b/Modules/SemanticRelationsUI/src/QmitkSemanticRelationsUIHelper.cpp
deleted file mode 100644
index cce4954a44..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkSemanticRelationsUIHelper.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.
-
-============================================================================*/
-
-// semantic relations ui module
-#include <QmitkSemanticRelationsUIHelper.h>
-
-// mitk core
-#include <mitkExtractSliceFilter.h>
-#include <vtkMitkLevelWindowFilter.h>
-#include <mitkPlanarFigure.h>
-#include <mitkPropertyNameHelper.h>
-
-// vtk
-#include <vtkLookupTable.h>
-
-QPixmap QmitkSemanticRelationsUIHelper::GetPixmapFromImageNode(const mitk::DataNode* dataNode)
-{
- if (nullptr == dataNode)
- {
- return QPixmap();
- }
-
- const mitk::Image* image = static_cast<const mitk::Image*>(dataNode->GetData());
- if (nullptr == image || !image->IsInitialized())
- {
- return QPixmap();
- }
-
- if (image->GetPixelType().GetNumberOfComponents() != 1) // for now only single component are allowed
- {
- return QPixmap();
- }
-
- mitk::PlaneGeometry::Pointer sagittalPlaneGeometry = mitk::PlaneGeometry::New();
- int sliceNumber = image->GetDimension(1) / 2;
- sagittalPlaneGeometry->InitializeStandardPlane(image->GetGeometry(), mitk::AnatomicalPlane::Sagittal, sliceNumber);
-
- mitk::ExtractSliceFilter::Pointer extractSliceFilter = mitk::ExtractSliceFilter::New();
- extractSliceFilter->SetInput(image);
- extractSliceFilter->SetInterpolationMode(mitk::ExtractSliceFilter::RESLICE_CUBIC);
- extractSliceFilter->SetResliceTransformByGeometry(image->GetGeometry());
- extractSliceFilter->SetWorldGeometry(sagittalPlaneGeometry);
- extractSliceFilter->SetOutputDimensionality(2);
- extractSliceFilter->SetVtkOutputRequest(true);
- extractSliceFilter->Update();
-
- /*
- mitk::Vector3D spacing;
- mitk::FillVector3D(spacing,1.0,1.0,1.0);
- slice->GetGeometry()->SetSpacing(spacing);
- // save image slice
- mitk::IOUtil::SaveImage( slice, d->m_Path + fileName + ".png" );
- */
-
- vtkImageData* imageData = extractSliceFilter->GetVtkOutput();
-
- mitk::LevelWindow levelWindow;
- dataNode->GetLevelWindow(levelWindow);
- vtkSmartPointer<vtkLookupTable> lookupTable = vtkSmartPointer<vtkLookupTable>::New();
- lookupTable->SetRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound());
- lookupTable->SetSaturationRange(0.0, 0.0);
- lookupTable->SetValueRange(0.0, 1.0);
- lookupTable->SetHueRange(0.0, 0.0);
- lookupTable->SetRampToLinear();
-
- vtkSmartPointer<vtkMitkLevelWindowFilter> levelWindowFilter = vtkSmartPointer<vtkMitkLevelWindowFilter>::New();
- levelWindowFilter->SetLookupTable(lookupTable);
- levelWindowFilter->SetInputData(imageData);
- levelWindowFilter->SetMinOpacity(0.0);
- levelWindowFilter->SetMaxOpacity(1.0);
- int dims[3];
- imageData->GetDimensions(dims);
- double clippingBounds[] = { 0.0, static_cast<double>(dims[0]), 0.0, static_cast<double>(dims[1]) };
- levelWindowFilter->SetClippingBounds(clippingBounds);
- levelWindowFilter->Update();
- imageData = levelWindowFilter->GetOutput();
-
- QImage thumbnailImage(reinterpret_cast<const unsigned char*>(imageData->GetScalarPointer()), dims[0], dims[1], QImage::Format_ARGB32);
-
- thumbnailImage = thumbnailImage.rgbSwapped().mirrored(false, true);
- return QPixmap::fromImage(thumbnailImage);
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkStatisticsCalculator.cpp b/Modules/SemanticRelationsUI/src/QmitkStatisticsCalculator.cpp
deleted file mode 100644
index 01e9882c3b..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkStatisticsCalculator.cpp
+++ /dev/null
@@ -1,232 +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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkStatisticsCalculator.h"
-
-// semantic relations module
-#include <mitkNodePredicates.h>
-#include <mitkRelationStorage.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsDataStorageAccess.h>
-#include <mitkSemanticRelationsInference.h>
-
-// mitk image statistics module
-#include <mitkImageStatisticsContainerManager.h>
-#include <mitkImageStatisticsContainerNodeHelper.h>
-#include <mitkStatisticsToImageRelationRule.h>
-#include <mitkStatisticsToMaskRelationRule.h>
-
-QmitkStatisticsCalculator::QmitkStatisticsCalculator()
- : m_CalculationJob(nullptr)
- , m_DataStorage(nullptr)
- , m_MaskVolume(0.0)
-{
- m_CalculationJob = new QmitkImageStatisticsCalculationJob();
-
- connect(m_CalculationJob, &QmitkImageStatisticsCalculationJob::finished, this,
- &QmitkStatisticsCalculator::OnStatisticsCalculationEnds, Qt::QueuedConnection);
-}
-
-QmitkStatisticsCalculator::~QmitkStatisticsCalculator()
-{
- if (!m_CalculationJob->isFinished())
- {
- m_CalculationJob->terminate();
- m_CalculationJob->wait();
- }
- m_CalculationJob->deleteLater();
-}
-
-void QmitkStatisticsCalculator::ComputeLesionVolume(mitk::LesionData& lesionData, const mitk::SemanticTypes::CaseID& caseID)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- std::vector<double> lesionVolume;
- mitk::SemanticTypes::Lesion lesion = lesionData.GetLesion();
- double volume = 0.0;
-
- mitk::SemanticTypes::ControlPointVector controlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- // sort the vector of control points for the timeline
- std::sort(controlPoints.begin(), controlPoints.end());
- mitk::SemanticTypes::InformationTypeVector informationTypes = mitk::RelationStorage::GetAllInformationTypesOfCase(caseID);
- for (const auto& informationType : informationTypes)
- {
- for (const auto& controlPoint : controlPoints)
- {
- mitk::SemanticRelationsDataStorageAccess semanticRelationsDataStorageAccess(dataStorage);
- mitk::DataNode::Pointer specificImage;
- mitk::DataNode::Pointer specificSegmentation;
- try
- {
- specificSegmentation = semanticRelationsDataStorageAccess.GetSpecificSegmentation(caseID, controlPoint, informationType, lesion);
- if (nullptr == specificSegmentation)
- {
- volume = 0.0;
- }
- else
- {
- // get parent node of the specific segmentation node with the node predicate
- auto parentNodes = dataStorage->GetSources(specificSegmentation, mitk::NodePredicates::GetImagePredicate(), false);
- for (auto it = parentNodes->Begin(); it != parentNodes->End(); ++it)
- {
- specificImage = it->Value();
- }
-
- volume = GetSegmentationMaskVolume(specificImage, specificSegmentation);
- }
- }
- catch (mitk::SemanticRelationException&)
- {
- volume = 0.0;
- }
-
- lesionVolume.push_back(volume);
- }
- }
-
- lesionData.SetLesionVolume(lesionVolume);
-}
-
-double QmitkStatisticsCalculator::GetSegmentationMaskVolume(mitk::DataNode::Pointer imageNode, mitk::DataNode::Pointer segmentationNode)
-{
- m_MaskVolume = 0.0;
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return m_MaskVolume;
- }
-
- if (imageNode.IsNull() || segmentationNode.IsNull())
- {
- return m_MaskVolume;
- }
-
- m_ImageNode = imageNode;
- m_SegmentationNode = segmentationNode;
-
- auto image = dynamic_cast<mitk::Image*>(m_ImageNode->GetData());
- auto segmentation = dynamic_cast<mitk::Image*>(m_SegmentationNode->GetData());
- if (nullptr == image || nullptr == segmentation)
- {
- return m_MaskVolume;
- }
-
- // all nodes and images are valid, retrieve statistics
- mitk::ImageStatisticsContainer::ConstPointer imageStatistics = mitk::ImageStatisticsContainerManager::GetImageStatistics(dataStorage, image, segmentation).GetPointer();
-
- bool imageStatisticsOlderThanInputs = false;
- if (imageStatistics && (imageStatistics->GetMTime() < image->GetMTime() || (imageStatistics->GetMTime() < segmentation->GetMTime())))
- {
- imageStatisticsOlderThanInputs = true;
- }
- // statistics need to be (re)computed
- if (!imageStatistics || imageStatisticsOlderThanInputs)
- {
- m_CalculationJob->Initialize(image, segmentation, nullptr);
- try
- {
- m_CalculationJob->start();
- return m_MaskVolume;
- }
- catch (const std::exception&)
- {
- return m_MaskVolume;
- }
- }
-
- // use a valid statistics object to get the volume of the image-segmentation pair
- mitk::ImageStatisticsContainer::ImageStatisticsObject statisticsObject;
- try
- {
- statisticsObject = imageStatistics->GetStatisticsForTimeStep(0);
- }
- catch (mitk::Exception&)
- {
- return m_MaskVolume;
- }
- try
- {
- if (statisticsObject.HasStatistic(mitk::ImageStatisticsConstants::VOLUME()))
- {
- auto valueVariant = statisticsObject.GetValueNonConverted(mitk::ImageStatisticsConstants::VOLUME());
- m_MaskVolume = boost::get<double>(valueVariant);
- }
- }
- catch (mitk::Exception&)
- {
- return m_MaskVolume;
- }
-
- return m_MaskVolume;
-}
-
-void QmitkStatisticsCalculator::OnStatisticsCalculationEnds()
-{
- // taken from 'QmitkImageStatisticsView' (see measurementtoolbox plugin)
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- if (m_CalculationJob->GetStatisticsUpdateSuccessFlag())
- {
- auto statistic = m_CalculationJob->GetStatisticsData();
- auto image = m_CalculationJob->GetStatisticsImage();
- mitk::BaseData::ConstPointer mask = nullptr;
- auto imageRule = mitk::StatisticsToImageRelationRule::New();
- imageRule->Connect(statistic, image);
-
- if (m_CalculationJob->GetMaskImage())
- {
- auto maskRule = mitk::StatisticsToMaskRelationRule::New();
- mask = m_CalculationJob->GetMaskImage();
- maskRule->Connect(statistic, mask);
- }
-
- auto imageStatistics = mitk::ImageStatisticsContainerManager::GetImageStatistics(dataStorage, image, mask);
-
- // if statistics base data already exist: add to existing node
- if (nullptr != imageStatistics)
- {
- auto allDataNodes = dataStorage->GetAll()->CastToSTLConstContainer();
- for (auto node : allDataNodes)
- {
- auto nodeData = node->GetData();
- if (nullptr != nodeData && nodeData->GetUID() == imageStatistics->GetUID())
- {
- node->SetData(statistic);
- }
- }
- }
- // statistics base data does not exist: add new node
- else
- {
- auto statisticsNodeName = m_ImageNode->GetName();
- if (m_SegmentationNode)
- {
- statisticsNodeName += "_" + m_SegmentationNode->GetName();
- }
- statisticsNodeName += "_statistics";
- auto statisticsNode = mitk::CreateImageStatisticsNode(statistic, statisticsNodeName);
- dataStorage->Add(statisticsNode);
- }
- }
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkStatisticsTreeModel.cpp b/Modules/SemanticRelationsUI/src/QmitkStatisticsTreeModel.cpp
deleted file mode 100644
index 110bff79dc..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkStatisticsTreeModel.cpp
+++ /dev/null
@@ -1,268 +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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkStatisticsTreeModel.h"
-
-// semantic relations module
-#include <mitkControlPointManager.h>
-#include <mitkLesionManager.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsInference.h>
-#include <mitkRelationStorage.h>
-
-QmitkStatisticsTreeModel::QmitkStatisticsTreeModel(QObject* parent/* = nullptr*/)
- : QmitkAbstractSemanticRelationsStorageModel(parent)
- , m_RootItem(std::make_shared<QmitkLesionTreeItem>(mitk::LesionData()))
-{
- m_StatisticsCalculator = std::make_unique<QmitkStatisticsCalculator>();
-}
-
-//////////////////////////////////////////////////////////////////////////
-// overridden virtual functions from QAbstractItemModel
-//////////////////////////////////////////////////////////////////////////
-QModelIndex QmitkStatisticsTreeModel::index(int row, int column, const QModelIndex& itemIndex) const
-{
- if (!hasIndex(row, column, itemIndex))
- {
- return QModelIndex();
- }
-
- auto childItem = GetItemByIndex(itemIndex)->GetChildInRow(row);
- if (nullptr == childItem)
- {
- return QModelIndex();
- }
-
- return createIndex(row, column, childItem.get());
-}
-
-QModelIndex QmitkStatisticsTreeModel::parent(const QModelIndex& itemIndex) const
-{
- if (!itemIndex.isValid())
- {
- return QModelIndex();
- }
-
- auto parentItemWeakPtr = GetItemByIndex(itemIndex)->GetParent();
- if (parentItemWeakPtr.expired())
- {
- return QModelIndex();
- }
-
- auto parentItem = parentItemWeakPtr.lock();
- if (parentItem == m_RootItem)
- {
- return QModelIndex();
- }
-
- return createIndex(parentItem->GetRow(), 0, parentItem.get());
-}
-
-int QmitkStatisticsTreeModel::rowCount(const QModelIndex& itemIndex/* = QModelIndex()*/) const
-{
- return GetItemByIndex(itemIndex)->ChildCount();
-}
-
-int QmitkStatisticsTreeModel::columnCount(const QModelIndex&/* itemIndex = QModelIndex() */) const
-{
- if (0 == m_RootItem->ChildCount())
- {
- // no lesion items stored, no need to display columns
- return 0;
- }
-
- return m_ControlPoints.size() + 1;
-}
-
-QVariant QmitkStatisticsTreeModel::data(const QModelIndex& index, int role) const
-{
- if (!index.isValid())
- {
- return QVariant();
- }
-
- if (index.column() < 0 || index.column() > static_cast<int>(m_ControlPoints.size()))
- {
- return QVariant();
- }
-
- QmitkLesionTreeItem* currentItem = GetItemByIndex(index);
- if (Qt::DisplayRole == role)
- {
- if (currentItem->GetParent().expired())
- {
- return QVariant();
- }
-
- auto parentItem = currentItem->GetParent().lock();
- // parent exists and is the root item -> top level item
- if (m_RootItem == parentItem)
- {
- // display role fills the first columns with the lesion UID / name
- if (0 == index.column())
- {
- std::string itemString = currentItem->GetData().GetLesionName();
- if (itemString.empty())
- {
- itemString = currentItem->GetData().GetLesionUID();
- }
- return QString::fromStdString(itemString);
- }
- }
- // parent is not the root item -> volume item
- else
- {
- // display role fills the first columns with the information type
- if (0 == index.column())
- {
- if (index.row() < static_cast<int>(m_InformationTypes.size()))
- {
- return QString::fromStdString(m_InformationTypes.at(index.row()));
- }
- return "N/A";
- }
- else
- {
- // display role fills other columns with the lesion volume info
- const auto lesionVolume = currentItem->GetData().GetLesionVolume();
- if ((index.column() - 1) * index.row() < static_cast<int>(lesionVolume.size()))
- {
- return QVariant(lesionVolume.at(index.row()*m_ControlPoints.size() + (index.column() - 1)));
- }
- return "N/A";
- }
- }
- }
-
- return QVariant();
-}
-
-QVariant QmitkStatisticsTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (0 == m_RootItem->ChildCount())
- {
- // no lesion items stored, no need to display the header
- return QVariant();
- }
-
- if (Qt::Horizontal == orientation && Qt::DisplayRole == role)
- {
- if (0 == section)
- {
- return QVariant("Lesion");
- }
-
- if (static_cast<int>(m_ControlPoints.size()) >= section)
- {
- mitk::SemanticTypes::ControlPoint currentControlPoint = m_ControlPoints.at(section-1);
- return QVariant(QString::fromStdString(currentControlPoint.ToString()));
- }
- }
-
- return QVariant();
-}
-
-void QmitkStatisticsTreeModel::DataStorageChanged()
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNotNull())
- {
- m_SemanticRelationsDataStorageAccess = std::make_unique<mitk::SemanticRelationsDataStorageAccess>(dataStorage);
- m_StatisticsCalculator->SetDataStorage(dataStorage);
- UpdateModelData();
- }
-}
-
-void QmitkStatisticsTreeModel::NodeAdded(const mitk::DataNode*)
-{
- emit beginResetModel();
- UpdateModelData();
- emit endResetModel();
-}
-
-void QmitkStatisticsTreeModel::NodeChanged(const mitk::DataNode*)
-{
- emit beginResetModel();
- UpdateModelData();
- emit endResetModel();
-}
-
-void QmitkStatisticsTreeModel::NodeRemoved(const mitk::DataNode*)
-{
- emit beginResetModel();
- UpdateModelData();
- emit endResetModel();
-}
-
-void QmitkStatisticsTreeModel::SetData()
-{
- m_RootItem = std::make_shared<QmitkLesionTreeItem>(mitk::LesionData());
-
- // get all control points of current case
- m_ControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(m_CaseID);
- // sort the vector of control points for the timeline
- std::sort(m_ControlPoints.begin(), m_ControlPoints.end());
-
- // get all information types points of current case
- m_InformationTypes = mitk::RelationStorage::GetAllInformationTypesOfCase(m_CaseID);
-
- SetLesionData();
-}
-
-void QmitkStatisticsTreeModel::SetLesionData()
-{
- m_CurrentLesions = mitk::RelationStorage::GetAllLesionsOfCase(m_CaseID);
- for (auto& lesion : m_CurrentLesions)
- {
- AddLesion(lesion);
- }
-}
-
-void QmitkStatisticsTreeModel::AddLesion(const mitk::SemanticTypes::Lesion& lesion)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- // create new lesion tree item data and modify it according to the control point data
- mitk::LesionData lesionData(lesion);
- m_StatisticsCalculator->ComputeLesionVolume(lesionData, m_CaseID);
-
- // add the 1. level lesion item to the root item
- std::shared_ptr<QmitkLesionTreeItem> newLesionTreeItem = std::make_shared<QmitkLesionTreeItem>(lesionData);
- m_RootItem->AddChild(newLesionTreeItem);
-
- for (size_t i = 0; i < m_InformationTypes.size(); ++i)
- {
- std::shared_ptr<QmitkLesionTreeItem> volumeItem = std::make_shared<QmitkLesionTreeItem>(lesionData);
- newLesionTreeItem->AddChild(volumeItem);
- }
-}
-
-QmitkLesionTreeItem* QmitkStatisticsTreeModel::GetItemByIndex(const QModelIndex& index) const
-{
- if (index.isValid())
- {
- auto item = static_cast<QmitkLesionTreeItem*>(index.internalPointer());
- if (nullptr != item)
- {
- return item;
- }
- }
-
- return m_RootItem.get();
-}
diff --git a/Modules/SemanticRelationsUI/src/QmitkTableItemThumbnailDelegate.cpp b/Modules/SemanticRelationsUI/src/QmitkTableItemThumbnailDelegate.cpp
deleted file mode 100644
index 14dcc8f776..0000000000
--- a/Modules/SemanticRelationsUI/src/QmitkTableItemThumbnailDelegate.cpp
+++ /dev/null
@@ -1,42 +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.
-
-============================================================================*/
-
-// semantic relations UI module
-#include "QmitkTableItemThumbnailDelegate.h"
-
-// qt
-#include <QApplication>
-#include <QPainter>
-#include <QStyle>
-
-QmitkTableItemThumbnailDelegate::QmitkTableItemThumbnailDelegate(QObject* parent /*= nullptr*/)
- : QStyledItemDelegate(parent)
-{
- // nothing here
-}
-
-void QmitkTableItemThumbnailDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
-{
- QPixmap pixmap = index.data(Qt::DecorationRole).value<QPixmap>();
- QPoint point = option.rect.center() - pixmap.rect().center();
- painter->save();
-
- if (option.state & QStyle::State_Selected)
- {
- painter->setBrush(option.palette.highlightedText());
- const QWidget* widget = option.widget;
- QStyle* style = widget ? widget->style() : QApplication::style();
- style->drawControl(QStyle::CE_ItemViewItem, &option, painter, widget);
- }
- painter->drawPixmap(point, pixmap);
- painter->restore();
-}
diff --git a/Modules/SemanticRelationsUI/src/mitkModuleActivator.cpp b/Modules/SemanticRelationsUI/src/mitkModuleActivator.cpp
deleted file mode 100644
index dfd9482aab..0000000000
--- a/Modules/SemanticRelationsUI/src/mitkModuleActivator.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 "mitkModuleActivator.h"
-
-// semantic relations ui module
-#include "QmitkPatientTableInspector.h"
-
-// qt widgets module
-#include "QmitkDataStorageInspectorProviderBase.h"
-
-void mitk::SemanticRelationsUIActivator::Load(us::ModuleContext* /*context*/)
-{
- m_PatientTableInspector.reset(new QmitkDataStorageInspectorProviderBase<QmitkPatientTableInspector>("org.mitk.QmitkPatientTableInspector",
- "Patient table inspector", "Displays the content of the semantic relations storage in a control-point - modality table."));
- }
-
-void mitk::SemanticRelationsUIActivator::Unload(us::ModuleContext* /*context*/)
-{
-}
-
-US_EXPORT_MODULE_ACTIVATOR(mitk::SemanticRelationsUIActivator)
diff --git a/Modules/ToFUI/Qmitk/QmitkKinectParameterWidget.h b/Modules/ToFUI/Qmitk/QmitkKinectParameterWidget.h
index 7550460263..fe9317cbd5 100644
--- a/Modules/ToFUI/Qmitk/QmitkKinectParameterWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkKinectParameterWidget.h
@@ -1,80 +1,80 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkKinectParameterWidget_h
#define QmitkKinectParameterWidget_h
#include <MitkToFUIExports.h>
#include "ui_QmitkKinectParameterWidgetControls.h"
//mitk headers
#include <mitkToFImageGrabber.h>
#include <QWidget>
/**
* @brief Widget for configuring the Kinect device
*
* @ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkKinectParameterWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkKinectParameterWidget(QWidget* p = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkKinectParameterWidget(QWidget* p = nullptr, Qt::WindowFlags f = {});
~QmitkKinectParameterWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief returns the ToFImageGrabber
\return ToFImageGrabber currently used by the widget
*/
mitk::ToFImageGrabber* GetToFImageGrabber();
/*!
\brief sets the ToFImageGrabber
*/
void SetToFImageGrabber(mitk::ToFImageGrabber* aToFImageGrabber);
/*!
\brief activate camera settings according to the parameters from GUI
*/
void ActivateAllParameters();
bool IsAcquisitionModeRGB();
bool IsAcquisitionModeIR();
signals:
void AcquisitionModeChanged();
protected slots:
void OnAcquisitionModeChanged();
protected:
Ui::QmitkKinectParameterWidgetControls* m_Controls; ///< member holding the UI elements of this widget
mitk::ToFImageGrabber::Pointer m_ToFImageGrabber; ///< image grabber object to be configured by the widget
private:
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkStructureSensorParameterWidget.h b/Modules/ToFUI/Qmitk/QmitkStructureSensorParameterWidget.h
index 66275497d0..feaf5a42d4 100644
--- a/Modules/ToFUI/Qmitk/QmitkStructureSensorParameterWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkStructureSensorParameterWidget.h
@@ -1,84 +1,84 @@
/*============================================================================
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 QmitkStructureSensorParameterWidget_h
#define QmitkStructureSensorParameterWidget_h
#include "MitkToFUIExports.h"
#include "ui_QmitkStructureSensorParameterWidgetControls.h"
#include <mitkToFImageGrabber.h>
#include <QWidget>
/**
* @brief Widget for configuring the Structure Sensor device (Occipital, Inc.)
*
* @note This device is currently not available open-source, because the required WiFi
* protocol is part of the commercial mbits source code (https://mbits.info/). If you
* want to use the device please contact mitk-users@dkfz-heidelberg.de.
*
* @ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkStructureSensorParameterWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkStructureSensorParameterWidget(QWidget* p = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkStructureSensorParameterWidget(QWidget* p = nullptr, Qt::WindowFlags f = {});
~QmitkStructureSensorParameterWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief returns the ToFImageGrabber
\return ToFImageGrabber currently used by the widget
*/
mitk::ToFImageGrabber* GetToFImageGrabber();
/*!
\brief sets the ToFImageGrabber
*/
void SetToFImageGrabber(mitk::ToFImageGrabber* aToFImageGrabber);
/*!
\brief activate camera settings according to the parameters from GUI
*/
void ActivateAllParameters();
/**
* @brief GetSelectedResolution getter for 640/320 resolution.
* @return 320: 320x240, 640: 640x480 else -1 and a warning.
*/
int GetSelectedResolution();
protected slots:
/**
* @brief OnResolutionChanged called when the resolution combobox is changed.
*/
void OnResolutionChanged();
protected:
Ui::QmitkStructureSensorParameterWidgetControls* m_Controls; ///< member holding the UI elements of this widget
mitk::ToFImageGrabber::Pointer m_ToFImageGrabber; ///< image grabber object to be configured by the widget
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkToFCompositeFilterWidget.h b/Modules/ToFUI/Qmitk/QmitkToFCompositeFilterWidget.h
index 558a1b8365..f7ff3b26c4 100644
--- a/Modules/ToFUI/Qmitk/QmitkToFCompositeFilterWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkToFCompositeFilterWidget.h
@@ -1,171 +1,171 @@
/*============================================================================
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 QmitkToFCompositeFilterWidget_h
#define QmitkToFCompositeFilterWidget_h
#include <MitkToFUIExports.h>
#include "ui_QmitkToFCompositeFilterWidgetControls.h"
//mitk headers
#include <mitkToFCompositeFilter.h>
/**
* @brief Widget for controlling the ToFCompositeFilter (located in module ToFProcessing)
*
* The widget allows to enable/disable the filters internally used in the ToFCompositeFilter
* and to set the individual filter parameters using GUI elements
*
* @ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkToFCompositeFilterWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkToFCompositeFilterWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkToFCompositeFilterWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkToFCompositeFilterWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief Sets the ToFCompositeFilter used by this widget
\param toFCompositeFilter pointer to the internally used ToFCompositeFilter
*/
void SetToFCompositeFilter(mitk::ToFCompositeFilter* toFCompositeFilter);
/*!
\brief Returns the ToFCompositeFilter used by this widget
\return tofCompositeFilter pointer to the internally used ToFCompositeFilter
*/
mitk::ToFCompositeFilter* GetToFCompositeFilter();
/*!
\brief update parameters of ToFCompositeFilter according to current GUI setting
*/
void UpdateFilterParameter();
/*!
\brief set the configuration of the widget specifying which filter is enabled on start
*/
void SetWidgetConfiguration(bool threshold, bool mask, bool tempMedian, bool tempAverage, bool median, bool bilateral );
/*!
\brief sets the standard parameters used for the bilateral filter to the ComboBoxes used in the GUI
\param domainSigma Parameter controlling the smoothing effect of the bilateral filter. Default value: 2
\param rangeSigma Parameter controlling the edge preserving effect of the bilateral filter. Default value: 60
\param kernelRadius radius of the filter mask of the bilateral filter
*/
void SetStandardParametersBilateralFilter(double domainSigma, double rangeSigma, int kernelRadius=0);
/*!
\brief set the standard parameters for the threshold filter to the combo boxes in the GUI
\param min lower threshold of the threshold filter
\param max upper threshold of the threshold filter
*/
void SetStandardParametersThresholdFilter(int min, int max);
/*!
\brief set the standard value for the number of images to be averaged to the combo box in the GUI
*/
void SetStandardParameterTemporalAveraging(int nImages);
void SetDataStorage(mitk::DataStorage::Pointer dataStorage);
signals:
protected slots:
/**
* @brief OnShowAdvancedOptionsCheckboxChecked Show/hide advanced options.
* @param checked show/hide
*/
void OnShowAdvancedOptionsCheckboxChecked(bool checked);
/*!
\brief slot en-/disabling temporal median filter in internal ToFCompositeFilter
*/
void OnTemporalMedianFilterCheckBoxChecked(bool checked);
/*!
\brief slot en-/disabling average filter in internal ToFCompositeFilter
*/
void OnAverageFilterCheckBoxChecked(bool checked);
/*!
\brief slot en-/disabling threshold filter in internal ToFCompositeFilter
*/
void OnThresholdFilterCheckBoxChecked(bool checked);
/*!
\brief slot en-/disabling the mask segmentation in internal ToFCompositeFilter
*/
void OnMaskSegmentationCheckBoxChecked(bool checked);
/*!
\brief slot en-/disabling median filter in internal ToFCompositeFilter
*/
void OnMedianFilterCheckBoxChecked(bool checked);
/*!
\brief slot en-/disabling bilateral filter in internal ToFCompositeFilter
*/
void OnBilateralFilterCheckBoxChecked(bool checked);
/*!
\brief slot updating threshold spin boxes according to slider position
*/
void OnSpanChanged(int lower, int upper);
/*!
\brief slot resetting threshold range slider to default values (min: 1, max: 7000)
*/
void OnResetThresholdFilterRangeSlider();
/*!
\brief slot updating the parameter "number of frames" of the temporal median filter in the ToFCompositeFilter
*/
void OnTemporalMedianFilterNumOfFramesSpinBoxValueChanged(int value);
/*!
\brief slot updating the parameter "domain sigma" of the bilateral filter in the ToFCompositeFilter
*/
void OnBilateralFilterDomainSigmaSpinBoxValueChanged(double value);
/*!
\brief slot updating the paramter "range sigma" of the bilateral filter in the ToFCompositeFilter
*/
void OnBilateralFilterRangeSigmaSpinBoxValueChanged(double value);
/*!
\brief slot updating the paramter "kernel radius" of the bilateral filter in the ToFCompositeFilter
*/
void OnBilateralFilterKernelRadiusSpinBoxValueChanged(int value);
/*!
\brief slot updating the paramter "minimal threshold" of the threshold filter in the ToFCompositeFilter
*/
void OnThresholdFilterMinValueChanged(int value);
/*!
\brief slot updating the paramter "maximal threshold" of the threshold filter in the ToFCompositeFilter
*/
void OnThresholdFilterMaxValueChanged(int value);
protected:
Ui::QmitkToFCompositeFilterWidgetControls* m_Controls; ///< member holding the UI elements of this widget
mitk::ToFCompositeFilter::Pointer m_ToFCompositeFilter; ///< member holding the internally used ToFCompositeFilter
private:
/*!
\brief method updating the parameters of the bilateral filter in the ToFCompositeFilter
*/
void SetBilateralFilterParameter();
/*!
\brief method updating the parameters of the threshold filter in the ToFCompositeFilter
*/
void SetThresholdFilterParameter();
mitk::DataStorage::Pointer m_DataStorage;
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkToFConnectionWidget.h b/Modules/ToFUI/Qmitk/QmitkToFConnectionWidget.h
index 9e5f2381a2..d822ae938b 100644
--- a/Modules/ToFUI/Qmitk/QmitkToFConnectionWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkToFConnectionWidget.h
@@ -1,117 +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 QmitkToFConnectionWidget_h
#define QmitkToFConnectionWidget_h
#include <MitkToFUIExports.h>
#include "ui_QmitkToFConnectionWidgetControls.h"
//QT headers
#include <QWidget>
//mitk headers
#include "mitkToFImageGrabber.h"
/**
* @brief Widget allowing to connect to different ToF / range cameras (located in module ToFProcessing)
*
* The widget basically allows to connect/disconnect to different ToF cameras
*
* @ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkToFConnectionWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkToFConnectionWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkToFConnectionWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkToFConnectionWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief returns the ToFImageGrabber which was configured after selecting a camera / player
\return ToFImageGrabber currently used by the widget
*/
mitk::ToFImageGrabber::Pointer GetToFImageGrabber();
/*!
\brief return the name of the currently selected camera
*/
QString GetSelectedCameraName()
{
return m_SelectedCameraName;
}
/*!
\brief invokes the call of OnConnectCamera()
*/
void ConnectCamera();
signals:
/*!
\brief This signal is sent if the user has connected the TOF camera.
* The ToFImageGrabber is now availiable if the method GetToFImageGrabber() is called.
*/
void ToFCameraConnected();
/*!
\brief This signal is sent if the user has disconnect the TOF camera.
*/
void ToFCameraDisconnected();
/*!
\brief signal that is emitted when a ToF camera is selected
*/
void ToFCameraSelected(const QString selectedText);
void KinectAcquisitionModeChanged();
void ChangeCoronalWindowSelection(int);
protected slots:
/*!
\brief slot called when the "Connect Camera" button was pressed
* According to the selection in the camera combo box, the widget provides
* the desired instance of the ToFImageGrabber
*/
void OnConnectCamera();
/*!
\brief slot updating the GUI elements after the selection of the camera combo box has changed
*/
void OnSelectCamera();
protected:
Ui::QmitkToFConnectionWidgetControls2* m_Controls; ///< member holding the UI elements of this widget
mitk::ToFImageGrabber::Pointer m_ToFImageGrabber; ///< member holding the current ToFImageGrabber
int m_IntegrationTime; ///< member for the current integration time of the ToF device
int m_ModulationFrequency; ///< member for the current modulation frequency of the ToF device
QString m_SelectedCameraName; ///< member holding the name of the currently selected camera
private:
void HideAllParameterWidgets();
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkToFMESAParameterWidget.h b/Modules/ToFUI/Qmitk/QmitkToFMESAParameterWidget.h
index 8c2a5aeb63..9bcaaa55ae 100644
--- a/Modules/ToFUI/Qmitk/QmitkToFMESAParameterWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkToFMESAParameterWidget.h
@@ -1,122 +1,122 @@
/*============================================================================
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 QmitkToFMESAParameterWidget_h
#define QmitkToFMESAParameterWidget_h
#include <MitkToFUIExports.h>
#include "ui_QmitkToFMESAParameterWidgetControls.h"
//QT headers
#include <QWidget>
//mitk headers
#include "mitkToFImageGrabber.h"
/**
* @brief Widget allowing to connect to different ToF / range cameras (located in module ToFProcessing)
*
* The widget basically allows to connect/disconnect to different ToF cameras
*
* @ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkToFMESAParameterWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkToFMESAParameterWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkToFMESAParameterWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkToFMESAParameterWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief returns the ToFImageGrabber which was configured after selecting a camera / player
\return ToFImageGrabber currently used by the widget
*/
mitk::ToFImageGrabber* GetToFImageGrabber();
/*!
\brief sets the ToFImageGrabber which was configured after selecting a camera / player
*/
void SetToFImageGrabber(mitk::ToFImageGrabber* aToFImageGrabber);
/*!
\brief activate camera settings according to the parameters from GUI
*/
void ActivateAllParameters();
signals:
/*!
\brief This signal is sent if the user has connected the TOF camera.
* The ToFImageGrabber is now availiable if the method GetToFImageGrabber() is called.
*/
void ToFCameraConnected();
/*!
\brief This signal is sent if the user has disconnect the TOF camera.
*/
void ToFCameraDisconnected();
/*!
\brief signal that is emitted when the ToF camera is started
*/
void ToFCameraStart();
/*!
\brief signal that is emitted when the ToF camera is stopped
*/
void ToFCameraStop();
/*!
\brief signal that is emitted when a ToF camera is selected in the combo box
*/
void ToFCameraSelected(int);
protected slots:
/*!
\brief slot updating the member m_IntegrationTime and the parameter "integration time" of the current ToFImageGrabber
*/
void OnChangeIntegrationTimeSpinBox(int value);
/*!
\brief slot updating the member m_ModulationFrequency and the parameter "modulation frequency" of the current ToFImageGrabber
*/
void OnChangeModulationFrequencyComboBox(int index);
void OnChangeFPNCheckBox(bool checked);
void OnChangeConvGrayCheckBox(bool checked);
void OnChangeMedianCheckBox(bool checked);
void OnChangeANFCheckBox(bool checked);
protected:
Ui::QmitkToFMESAParameterWidgetControls* m_Controls; ///< member holding the UI elements of this widget
mitk::ToFImageGrabber* m_ToFImageGrabber; ///< member holding the current ToFImageGrabber
int m_IntegrationTime; ///< member for the current integration time of the ToF device
int m_ModulationFrequency; ///< member for the current modulation frequency of the ToF device
private:
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkToFPMDParameterWidget.h b/Modules/ToFUI/Qmitk/QmitkToFPMDParameterWidget.h
index dc2eefe3b3..d2bf5c0953 100644
--- a/Modules/ToFUI/Qmitk/QmitkToFPMDParameterWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkToFPMDParameterWidget.h
@@ -1,114 +1,114 @@
/*============================================================================
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 QmitkToFPMDParameterWidget_h
#define QmitkToFPMDParameterWidget_h
#include <MitkToFUIExports.h>
#include "ui_QmitkToFPMDParameterWidgetControls.h"
//QT headers
#include <QWidget>
//mitk headers
#include "mitkToFImageGrabber.h"
/**
* @brief Widget allowing to connect to different ToF / range cameras (located in module ToFProcessing)
*
* The widget basically allows to connect/disconnect to different ToF cameras
*
* @ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkToFPMDParameterWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkToFPMDParameterWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkToFPMDParameterWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkToFPMDParameterWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief returns the ToFImageGrabber which was configured after selecting a camera / player
\return ToFImageGrabber currently used by the widget
*/
mitk::ToFImageGrabber* GetToFImageGrabber();
/*!
\brief sets the ToFImageGrabber which was configured after selecting a camera / player
*/
void SetToFImageGrabber(mitk::ToFImageGrabber* aToFImageGrabber);
/*!
\brief activate camera settings according to the parameters from GUI
*/
void ActivateAllParameters();
signals:
/*!
\brief This signal is sent if the user has connected the TOF camera.
* The ToFImageGrabber is now availiable if the method GetToFImageGrabber() is called.
*/
void ToFCameraConnected();
/*!
\brief This signal is sent if the user has disconnect the TOF camera.
*/
void ToFCameraDisconnected();
/*!
\brief signal that is emitted when the ToF camera is started
*/
void ToFCameraStart();
/*!
\brief signal that is emitted when the ToF camera is stopped
*/
void ToFCameraStop();
/*!
\brief signal that is emitted when a ToF camera is selected in the combo box
*/
void ToFCameraSelected(int);
protected slots:
/*!
\brief slot updating the member m_IntegrationTime and the parameter "integration time" of the current ToFImageGrabber
*/
void OnChangeIntegrationTimeSpinBox(int value);
/*!
\brief slot updating the member m_ModulationFrequency and the parameter "modulation frequency" of the current ToFImageGrabber
*/
void OnChangeModulationFrequencySpinBox(int value);
protected:
Ui::QmitkToFPMDParameterWidgetControls* m_Controls; ///< member holding the UI elements of this widget
mitk::ToFImageGrabber* m_ToFImageGrabber; ///< member holding the current ToFImageGrabber
int m_IntegrationTime; ///< member for the current integration time of the ToF device
int m_ModulationFrequency; ///< member for the current modulation frequency of the ToF device
private:
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkToFPointSetWidget.h b/Modules/ToFUI/Qmitk/QmitkToFPointSetWidget.h
index 7232971281..701deb0d67 100644
--- a/Modules/ToFUI/Qmitk/QmitkToFPointSetWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkToFPointSetWidget.h
@@ -1,144 +1,144 @@
/*============================================================================
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 QmitkToFPointSetWidget_h
#define QmitkToFPointSetWidget_h
#include <MitkToFUIExports.h>
#include "ui_QmitkToFPointSetWidgetControls.h"
//mitk headers
#include <mitkCameraIntrinsics.h>
#include <mitkDataStorage.h>
#include <mitkPointSet.h>
#include <mitkPointSetDataInteractor.h>
#include <mitkPropertyList.h>
#include <mitkTextAnnotation2D.h>
#include <mitkToFDistanceImageToPointSetFilter.h>
//Qmitk headers
#include <QmitkRenderWindow.h>
// vtk includes
#include <vtkSmartPointer.h>
#include <vtkTextActor.h>
#include <vtkRenderer.h>
/**
* @brief Widget allowing interaction with point sets for measurement and PointSet definition
*
* The widget allows to
* 1. Measure the distance between two points in 3D ToF space by clicking the points in the 2D slices
* 2. Defining a ToF PointSet both in 2D and 3D. CameraIntrinsics are used for calculation between 2D and 3D
*
* NOTE:
* You have to make sure that the widget is initialized at a position in the plugin using it, where the distance
* image is available. CleanUp has to be called to make sure that all observers and renderers are removed correctly.
*
* @ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkToFPointSetWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkToFPointSetWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkToFPointSetWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkToFPointSetWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief initializes the widget. Observers to the change events of the point sets are created, text actors are activated
to be rendered into the foreground of the render window.
\param renderWindowHashMap
\param dataStorage DataStorage to add PointSets
\param cameraIntrinsics
*/
void InitializeWidget(QHash<QString, QmitkRenderWindow*> renderWindowHashMap, mitk::DataStorage::Pointer dataStorage, mitk::CameraIntrinsics::Pointer cameraIntrinsics=nullptr);
/*!
\brief cleans up the widget when it's functionality is not used anymore.
Removes observers and deletes foreground renderer
*/
void CleanUpWidget();
/*!
\brief set the image holding the distance information used for measuring
*/
void SetDistanceImage(mitk::Image::Pointer distanceImage);
/*!
\brief Set intrinsic parameters of the used device
*/
void SetCameraIntrinsics(mitk::CameraIntrinsics::Pointer cameraIntrinsics);
signals:
protected slots:
/*!
\brief Activates the interactor for the measurement point set
*/
void OnMeasurement();
/*!
\brief Activates the interactor for the point set
*/
void OnPointSet();
protected:
/*!
\brief function called when the 2D measurement PointSet has changed
*/
void MeasurementPointSetChanged();
/*!
\brief function called when the 2D PointSet has changed
*/
void PointSetChanged();
Ui::QmitkToFPointSetWidgetControls* m_Controls; ///< member holding the UI elements of this widget
mitk::DataStorage::Pointer m_DataStorage; ///< member holding the set DataStorage
mitk::Image::Pointer m_DistanceImage; ///< image holding the range data of the ToF camera
mitk::CameraIntrinsics::Pointer m_CameraIntrinsics; ///< intrinsic parameters of the camera
mitk::TextAnnotation2D::Pointer m_TextAnnotationAxial; ///< text annotation used to display measurements in axial window
mitk::TextAnnotation2D::Pointer m_TextAnnotationSagittal; ///< text annotation used to display measurement in axial window
mitk::TextAnnotation2D::Pointer m_TextAnnotationCoronal; ///< text annotation used to display measurement in axial window
mitk::TextAnnotation2D::Pointer m_TextAnnotation3D; ///< text annotation used to display measurement in 3d window
mitk::VtkPropRenderer::Pointer m_RendererAxial; ///< renderer of axial render window
mitk::VtkPropRenderer::Pointer m_RendererSagittal; ///< renderer of sagittal render window
mitk::VtkPropRenderer::Pointer m_RendererCoronal; ///< renderer of coronal render window
mitk::VtkPropRenderer::Pointer m_Renderer3D; ///< renderer of 3D render window
mitk::PointSet::Pointer m_MeasurementPointSet2D; ///< PointSet holding the 2D ToF image point selection used for measuring
mitk::DataNode::Pointer m_MeasurementPointSet3DNode; ///< DataNode holding the 3D ToF coordinates used for measuring
mitk::PointSet::Pointer m_PointSet2D; ///< PointSet holding the 2D ToF image points
mitk::DataNode::Pointer m_PointSet3DNode; ///< DataNode holding the 3D ToF coordinates
mitk::PointSetDataInteractor::Pointer m_PointSetInteractor; ///< PointSetInteractor used for PointSet definition
mitk::PointSetDataInteractor::Pointer m_MeasurementPointSetInteractor; ///< PointSetInteractor used for measurement
long m_MeasurementPointSetChangedObserverTag; ///< observer tag for measurement PointSet observer
long m_PointSetChangedObserverTag; ///< observer tag for PointSet observer
// long m_DistanceImageChangedObserverTag; ///< observer tag for distance image observer
int m_WindowHeight; ///< Height of the renderWindow
private:
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkToFRecorderWidget.h b/Modules/ToFUI/Qmitk/QmitkToFRecorderWidget.h
index efa3a2ff4b..d4c6a8adac 100644
--- a/Modules/ToFUI/Qmitk/QmitkToFRecorderWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkToFRecorderWidget.h
@@ -1,183 +1,183 @@
/*============================================================================
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 QmitkToFRecorderWidget_h
#define QmitkToFRecorderWidget_h
#include <MitkToFUIExports.h>
#include <ui_QmitkToFRecorderWidgetControls.h>
//QT headers
#include <QWidget>
#include <QString>
#include <QDialog>
#include <QFileDialog>
//itk headers
#include "itkCommand.h"
//mitk headers
#include <mitkToFImageGrabber.h>
#include <mitkToFImageRecorder.h>
struct QFileDialogArgs;
class QFileIconProvider;
class QFileDialogPrivate;
/**
* @brief Widget allowing to play / record ToF data
*
* @ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkToFRecorderWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkToFRecorderWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkToFRecorderWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkToFRecorderWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief Set the parameters used for this widget
\param ToFImageGrabber image grabber providing images from a ToF device
\param toFImageRecorder image recorder allowing to record ToF images
*/
void SetParameter(mitk::ToFImageGrabber* ToFImageGrabber, mitk::ToFImageRecorder* toFImageRecorder);
/*!
\brief resets the GUI elements to the initial state. Play button: enabled, Stop button: disabled, Recording box: disabled
*/
void ResetGUIToInitial();
signals:
/*!
\brief signal emitted when "Play" button is pressed
*/
void ToFCameraStarted();
/*!
\brief signal emitted when "Stop" button is pressed
*/
void ToFCameraStopped();
/*!
\brief signal emitted when recording is started
*/
void RecordingStarted();
/*!
\brief signal emitted AbortEvent() in ToFImageRecorder is observed
*/
void RecordingStopped();
public slots:
/*!
\brief slot invoking to start the camera.
Calls StartCamera() and emits ToFCameraStarted signal
*/
void OnPlay();
/*!
\brief slot invoking to stop the camera and the recorder.
Calls StopCamera() and StopRecorder and emits ToFCameraStarted signal. Resets GUI to initial state.
*/
void OnStop();
/*!
\brief slot invoking to start the recording
After letting the user chose a file location for the record, m_ImageRecorder->StartRecording() is inoved.
*/
void OnStartRecorder();
/*!
\brief slot resetting the GUI elements of the recording box
*/
void OnRecordingStopped();
/*!
\brief slot activating/deactivating "number of frames" spin box dependent on recording mode (PerFrame / Infinite)
*/
void OnChangeRecordModeComboBox(int index);
protected:
/*!
\brief starts the camera by calling ToFImageGrabber::StartCamera()
*/
void StartCamera();
/*!
\brief stops the camera by calling ToFImageGrabber::StopCamera()
*/
void StopCamera();
/*!
\brief stops the recording by calling ToFImageRecorder::StopRecording()
*/
void StopRecorder();
/*!
\brief emits RecordingStopped signal.
*/
void StopRecordingCallback();
/*!
\brief adapted version of QFileDialog::getSaveFileName()
The user is now asked to choose which images he wants to save
(Distance and/or Intensity and/or Amplitude image) and which type the saved
image should have (3D, 2D+t).
*/
static QString getSaveFileName(mitk::ToFImageWriter::ToFImageType& tofImageType,
bool& distanceImageSelected,
bool& amplitudeImageSelected,
bool& intensityImageSelected,
bool& rgbImageSelected,
bool& rawDataSelected,
QWidget *parent = nullptr,
const QString &caption = QString(),
const QString &dir = QString(),
const QString &filter = QString(),
QString *selectedFilter = nullptr,
- QFileDialog::Options options = nullptr
+ QFileDialog::Options options = {}
);
/*!
\brief method creating a filename from the given information
\param dir directory to save the file
\param baseFilename base file name entered by the user
\param modulationFreq modulation frequency of the camera
\param integrationTime integration time of the camera
\param numOfFrames number of frames recorded
\param extension file extension
\param imageType type of image (DistanceImage, IntensityImage, AmplitudeImage)
\return dir+"/"+baseFilename+"_MF"+modulationFreq+"_IT"+integrationTime+"_"+numOfFrames+"Images"+imageType+extension
*/
std::string prepareFilename(std::string dir,
std::string baseFilename,
std::string modulationFreq,
std::string integrationTime,
std::string numOfFrames,
std::string extension,
std::string imageType);
Ui::QmitkToFRecorderWidgetControls* m_Controls; ///< member holding the UI elements of this widget
mitk::ToFImageGrabber::Pointer m_ToFImageGrabber; ///< member holding the ToFImageGrabber for acquiring ToF images
mitk::ToFImageRecorder::Pointer m_ToFImageRecorder; ///< member holding the recorder for ToF images
mitk::ToFImageRecorder::RecordMode m_RecordMode; ///< member holding the RecordMode of the recorder (PerFrame / Infinite)
typedef itk::SimpleMemberCommand<QmitkToFRecorderWidget> CommandType;
CommandType::Pointer m_StopRecordingCommand; ///< itkCommand for abort of recording
private:
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkToFSurfaceGenerationWidget.h b/Modules/ToFUI/Qmitk/QmitkToFSurfaceGenerationWidget.h
index 549c269e9e..d880207fe8 100644
--- a/Modules/ToFUI/Qmitk/QmitkToFSurfaceGenerationWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkToFSurfaceGenerationWidget.h
@@ -1,155 +1,155 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef QmitkToFSurfaceGenerationWidget_h
#define QmitkToFSurfaceGenerationWidget_h
#include <MitkToFUIExports.h>
#include "ui_QmitkToFSurfaceGenerationWidgetControls.h"
// QT headers
#include <QWidget>
// vtk includes
#include <vtkColorTransferFunction.h>
#include <vtkCamera.h>
#include <vtkSmartPointer.h>
//MITK
#include <mitkDataNode.h>
#include <mitkToFDistanceImageToSurfaceFilter.h>
#include <mitkToFImageGrabber.h>
#include <mitkCameraIntrinsics.h>
#include <mitkSurface.h>
/** Documentation:
*
* This widget provides GUI access for all basic surface generation properties and can
* be reused in any other GUI.
* \ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkToFSurfaceGenerationWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkToFSurfaceGenerationWidget (QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkToFSurfaceGenerationWidget (QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkToFSurfaceGenerationWidget () override;
/* @brief Automatically called method. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief Automatically called method. Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/**
* @brief GetToFDistanceImageToSurfaceFilter Get the internally used surface generation filter.
* @return ToFDistanceImageToSurfaceFilter as filter.
*/
mitk::ToFDistanceImageToSurfaceFilter::Pointer GetToFDistanceImageToSurfaceFilter();
/**
* @brief IsActive Check if the widget was initialized correctly.
* @return True for success.
*/
bool IsActive();
/**
* @brief Initialize Initialize the surface generation widget.
* @param filter ToFDistanceImageToSurfaceFilter for surface computation.
* @param grabber ToFImageGrabber to get/set device properties.
* @param intrinsics Intrincs of the device.
* @param surface Generated Surface.
* @param camera
* @param generateSurface Check the generate surface combo box.
* @param showAdvancedOptions Show/Hide advanced options.
*/
void Initialize(mitk::ToFDistanceImageToSurfaceFilter::Pointer filter, mitk::ToFImageGrabber::Pointer grabber, mitk::CameraIntrinsics::Pointer intrinsics,
mitk::DataNode::Pointer surface, vtkSmartPointer<vtkCamera> camera, bool generateSurface = false, bool showAdvancedOptions = true);
/**
* @brief UpdateSurface Generate new surface data according to the device properties
* @return True for success.
*/
bool UpdateSurface();
/**
* @brief GetSurface Get the generated surface.
* @return Surface.
*/
mitk::Surface::Pointer GetSurface();
protected slots:
/**
* @brief OnRepresentationChanged Change the representation of the surface. In other words: disable/enable
* triangulation (Point cloud/surface). If triangulation is enabled, this will also allow for editing a
* threshold for triangulating vertices.
*/
void OnRepresentationChanged(int index);
/**
* @brief OnReconstructionChanged Change the reconstruction mode of the ToFDistanceImageToSurfaceFilter.
*/
void OnReconstructionChanged(int index);
/**
* @brief OnCompute3DDataCheckboxChecked Slot beeing called, if the "surface"-checkbox is clicked. This method initializes the surface once, if it is necessary.
* @param checked Is it checked or not?
*/
void OnCompute3DDataCheckboxChecked(bool checked);
/**
* @brief OnShowAdvancedOptionsCheckboxChecked Show/hide advanced options.
* @param checked show/hide
*/
void OnShowAdvancedOptionsCheckboxChecked(bool checked);
/*!
\brief Slot trigged from the triangulation threshold spin box. Changed the threshold for connecting a vertex during triangulation.
*/
void OnTriangulationThresholdSpinBoxChanged();
/**
* @brief OnDistanceColorMapCheckBoxChecked Show the distance color mapping (vtkColorTransferFunction) on the surface.
* @param checked Show/hide.
*/
void OnDistanceColorMapCheckBoxChecked(bool checked);
/**
* @brief OnRGBTextureCheckBoxChecked Put the RGB image as texture on the generated surface/point cloud.
* @param checked Show/hide texture.
*/
void OnRGBTextureCheckBoxChecked(bool checked);
protected:
Ui::QmitkToFSurfaceGenerationWidgetControls* m_Controls;
private:
void FindReconstructionModeProperty();
mitk::ToFDistanceImageToSurfaceFilter::Pointer m_ToFDistanceImageToSurfaceFilter;
mitk::ToFImageGrabber::Pointer m_ToFImageGrabber;
mitk::CameraIntrinsics::Pointer m_CameraIntrinsics;
mitk::DataNode::Pointer m_SurfaceNode;
mitk::Surface::Pointer m_Surface;
bool m_Active;
vtkSmartPointer<vtkCamera> m_Camera3d;
};
#endif
diff --git a/Modules/ToFUI/Qmitk/QmitkToFVisualisationSettingsWidget.h b/Modules/ToFUI/Qmitk/QmitkToFVisualisationSettingsWidget.h
index 629dd6173b..7c0e3d4b53 100644
--- a/Modules/ToFUI/Qmitk/QmitkToFVisualisationSettingsWidget.h
+++ b/Modules/ToFUI/Qmitk/QmitkToFVisualisationSettingsWidget.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 QmitkToFVisualisationSettingsWidget_h
#define QmitkToFVisualisationSettingsWidget_h
#include <MitkToFUIExports.h>
#include "ui_QmitkToFVisualisationSettingsWidgetControls.h"
#include "mitkDataNode.h"
// QT headers
#include <QWidget>
// vtk includes
#include <vtkColorTransferFunction.h>
/** Documentation:
* Widget controlling the visualization of Time-of-Flight image data. A color transfer function can be configured for
* a given distance, amplitude and intensity image. The pre-configured vtkColorTransferFunctions can be accessed as
* an output of the widget.
*
* \ingroup ToFUI
*/
class MITKTOFUI_EXPORT QmitkToFVisualisationSettingsWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkToFVisualisationSettingsWidget (QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkToFVisualisationSettingsWidget (QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkToFVisualisationSettingsWidget () override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/*!
\brief initialize the widget with the images to be shown
\param distanceImageNode image holding the range image of a ToF camera
\param amplitudeImageNode image holding the amplitude image of a ToF camera
\param intensityImageNode image holding the intensity image of a ToF camera
\param surfaceNode
*/
void Initialize(mitk::DataNode* distanceImageNode=nullptr, mitk::DataNode* amplitudeImageNode=nullptr,
mitk::DataNode* intensityImageNode=nullptr, mitk::DataNode* surfaceNode=nullptr);
/*!
\brief Access the color transfer function of widget 1 (distance image)
\return vtkColorTransferFunction that can be used to define a TransferFunctionProperty
*/
vtkColorTransferFunction* GetWidget1ColorTransferFunction();
/*!
\brief Access the color transfer function of widget 2 (distance image)
\return vtkColorTransferFunction that can be used to define a TransferFunctionProperty
*/
vtkColorTransferFunction* GetWidget2ColorTransferFunction();
/*!
\brief Access the color transfer function of widget 3 (distance image)
\return vtkColorTransferFunction that can be used to define a TransferFunctionProperty
*/
vtkColorTransferFunction* GetWidget3ColorTransferFunction();
/*!
\brief Access the color transfer of the currently selected widget
\return vtkColorTransferFunction that can be used to define a TransferFunctionProperty
*/
vtkColorTransferFunction* GetSelectedColorTransferFunction();
/*!
\brief Return the index of the selected image: 0 = Distance, 1 = Amplitude, 2 = Intensity
*/
int GetSelectedImageIndex();
protected slots:
void OnShowAdvancedOptionsCheckboxChecked(bool checked);
void OnSetXValueColor();
/*!
\brief Slot invoking a reset of the RangeSlider to the minimal and maximal values of the according image
*/
void OnResetSlider();
/*!
\brief Slot called when the range span has changed.
*/
void OnSpanChanged (int lower, int upper);
/*!
\brief Resets the transfer function according to the currently selected widget / image
*/
void OnTransferFunctionReset();
/*!
\brief Updates the GUI according to the widget / image selection
*/
void OnWidgetSelected(int index);
/*!
\brief Slot called when the line edit of the maximal value of the range slider has changed. Leads to an update of the range slider.
*/
void OnRangeSliderMaxChanged();
/*!
\brief Slot called when the line edit of the minimal value of the range slider has changed. Leads to an update of the range slider.
*/
void OnRangeSliderMinChanged();
/*!
\brief Sets the TransferFunctionType members according to the selection of the widget and the transfer type.
*/
void OnTransferFunctionTypeSelected(int index);
protected:
/*!
\brief Invokes an update of the ColorTransferFunctionCanvas. Called when the ColorTransferFunction has changed
*/
void UpdateCanvas();
/*!
\brief Resets the ColorTransferFunctionCanvas according to the lower and upper value of the RangeSlider
*/
void UpdateRanges();
Ui::QmitkToFVisualisationSettingsWidgetControls* m_Controls;
int m_RangeSliderMin; ///< Minimal value of the transfer function range. Initialized to the minimal value of the corresponding image.
int m_RangeSliderMax; ///< Maximal value of the transfer function range. Initialized to the maximal value of the corresponding image.
mitk::DataNode::Pointer m_MitkDistanceImageNode; ///< DataNode holding the range image of the ToF camera as set by Initialize()
mitk::DataNode::Pointer m_MitkAmplitudeImageNode; ///< DataNode holding the amplitude image of the ToF camera as set by Initialize()
mitk::DataNode::Pointer m_MitkIntensityImageNode; ///< DataNode holding the intensity image of the ToF camera as set by Initialize()
mitk::DataNode::Pointer m_MitkSurfaceNode; ///< DataNode holding the surface
vtkColorTransferFunction* m_Widget1ColorTransferFunction; ///< vtkColorTransferFunction of widget 1 (distance) that can be used to define a TransferFunctionProperty
vtkColorTransferFunction* m_Widget2ColorTransferFunction; ///< vtkColorTransferFunction of widget 2 (amplitude) that can be used to define a TransferFunctionProperty
vtkColorTransferFunction* m_Widget3ColorTransferFunction; ///< vtkColorTransferFunction of widget 3 (intensity) that can be used to define a TransferFunctionProperty
int m_Widget1TransferFunctionType; ///< member holding the type of the transfer function applied to the image shown in widget 1 (distance image): 0 = gray scale, 1 = color
int m_Widget2TransferFunctionType; ///< member holding the type of the transfer function applied to the image shown in widget 2 (amplitude image): 0 = gray scale, 1 = color
int m_Widget3TransferFunctionType; ///< member holding the type of the transfer function applied to the image shown in widget 3 (intensity image): 0 = gray scale, 1 = color
private:
/**
* @brief UpdateSurfaceProperty Private helper method to update the surface property color transfer function.
*/
void UpdateSurfaceProperty();
/*!
\brief Reset the color transfer function to the given type and range
\param colorTransferFunction vtkColorTransferfunction to be resetted
\param type type of the transfer function: 0 = gray scale, 1 = color
\param min minimal value to be set to the transfer function
\param max maximal value to be set to the transfer function
*/
void ResetTransferFunction(vtkColorTransferFunction* colorTransferFunction, int type, double min, double max);
/*!
\brief Reset the color transfer function for the given widget
\param widget 0: axial, 1: coronal, 2: sagittal
\param type: type of the transfer function: 0 = gray scale, 1 = color
*/
void ReinitTransferFunction(int widget, int type);
};
#endif
diff --git a/Modules/TubeGraph/CMakeLists.txt b/Modules/TubeGraph/CMakeLists.txt
deleted file mode 100644
index 13e719c1a9..0000000000
--- a/Modules/TubeGraph/CMakeLists.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-MITK_CREATE_MODULE(
- INCLUDE_DIRS PRIVATE src/Algorithms src/DataStructure src/Interactions src/Rendering src/IO
- DEPENDS MitkSceneSerializationBase
-)
-
-#add_subdirectory(test)
diff --git a/Modules/TubeGraph/files.cmake b/Modules/TubeGraph/files.cmake
deleted file mode 100644
index 8cd0a31a02..0000000000
--- a/Modules/TubeGraph/files.cmake
+++ /dev/null
@@ -1,21 +0,0 @@
-file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*")
-
-set(CPP_FILES
- DataStructure/mitkCircularProfileTubeElement.cpp
- DataStructure/mitkTubeGraph.cpp
- DataStructure/mitkTubeGraphEdge.cpp
- DataStructure/mitkTubeGraphVertex.cpp
- Interactions/mitkTubeGraphDataInteractor.cpp
- Interactions/mitkTubeGraphPicker.cpp
- IO/mitkTubeGraphDefinitions.cpp
- IO/mitkTubeGraphIO.cpp
- IO/mitkTubeGraphModuleActivator.cpp
- IO/mitkTubeGraphObjectFactory.cpp
- Rendering/mitkTubeGraphProperty.cpp
- Rendering/mitkTubeGraphVtkMapper3D.cpp
-)
-
-set(RESOURCE_FILES
- Interactions/TubeGraphConfig.xml
- Interactions/TubeGraphInteraction.xml
-)
diff --git a/Modules/TubeGraph/include/mitkCircularProfileTubeElement.h b/Modules/TubeGraph/include/mitkCircularProfileTubeElement.h
deleted file mode 100644
index 33a8d8f961..0000000000
--- a/Modules/TubeGraph/include/mitkCircularProfileTubeElement.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 mitkCircularProfileTubeElement_h
-#define mitkCircularProfileTubeElement_h
-
-#include <MitkTubeGraphExports.h>
-
-#include "mitkTubeElement.h"
-
-namespace mitk
-{
- /**
- * \brief Class for elements which describes tubular structur with a circular cross section.
- */
- class MITKTUBEGRAPH_EXPORT CircularProfileTubeElement : virtual public TubeElement
- {
- public:
- CircularProfileTubeElement();
- CircularProfileTubeElement(float x, float y, float z, float d = 0.0f);
- CircularProfileTubeElement(const Point3D, float d = 0.0f);
- ~CircularProfileTubeElement() override;
-
- /**
- * Set the 3D position of the element.
- */
- void SetCoordinates(Point3D coordinates) override;
-
- /**
- * Returns the 3D position of the element.
- */
- const Point3D &GetCoordinates() const override;
-
- /**
- * Set the diameter of the circle.
- */
- void SetDiameter(float d);
-
- /**
- * Returns the diameter of the circle.
- */
- float GetDiameter() const;
-
- /**
- * Comparison operation between this object and the given object.
- * @param right The object to compare with.
- * @return true, if the object is the same;false, if not.
- */
- bool operator==(const TubeElement &right) const override;
-
- private:
- Point3D m_coordinates;
- float m_diameter;
-
- }; // class
-
-} // namespace
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeElement.h b/Modules/TubeGraph/include/mitkTubeElement.h
deleted file mode 100644
index 6290cb40f5..0000000000
--- a/Modules/TubeGraph/include/mitkTubeElement.h
+++ /dev/null
@@ -1,50 +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 mitkTubeElement_h
-#define mitkTubeElement_h
-
-#include <MitkTubeGraphExports.h>
-
-#include <mitkPoint.h>
-
-namespace mitk
-{
- /**
- * \brief Abstract class for elements which describes tubular structur.
- */
- class MITKTUBEGRAPH_EXPORT TubeElement
- {
- public:
- virtual ~TubeElement(){};
-
- /**
- * Set the 3D position of the element.
- */
- virtual void SetCoordinates(Point3D coordinates) = 0;
-
- /**
- * Returns the 3D position of the element.
- */
- virtual const Point3D &GetCoordinates() const = 0;
-
- /**
- * Comparison operation between this object and the given object.
- * @param right The object to compare with.
- * @return true, if the object is the same;false, if not.
- */
- virtual bool operator==(const TubeElement &right) const = 0;
-
- }; // class
-
-} // namespace
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraph.h b/Modules/TubeGraph/include/mitkTubeGraph.h
deleted file mode 100644
index 10aa38ce70..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraph.h
+++ /dev/null
@@ -1,152 +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 mitkTubeGraph_h
-#define mitkTubeGraph_h
-
-#include <MitkTubeGraphExports.h>
-
-#include "mitkTubeGraphEdge.h"
-#include "mitkTubeGraphVertex.h"
-#include "mitkUndirectedGraph.h"
-
-#ifdef _MSC_VER
-# pragma warning(push)
-# pragma warning(disable: 4172) // boost/graph/named_function_params.hpp(240): returning address of local variable or temporary
-#endif
-
-#include <boost/graph/undirected_dfs.hpp>
-#include <boost/graph/visitors.hpp>
-#include <boost/property_map/property_map.hpp>
-
-#include <boost/graph/breadth_first_search.hpp>
-#include <boost/pending/property.hpp>
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
-
-namespace mitk
-{
- /**
- * \brief Base Class for Tube Graphs
- */
- class MITKTUBEGRAPH_EXPORT TubeGraph : public UndirectedGraph<TubeGraphVertex, TubeGraphEdge>
- {
- public:
- /**
- * Defines the type of the id of a single tube. It is allways the source and target descriptor: [uint, uint]
- */
- typedef std::pair<VertexDescriptorType, VertexDescriptorType> TubeDescriptorType;
-
- typedef boost::adjacency_list<boost::vecS,
- boost::vecS,
- boost::directedS // directed graph
- >
- DirectedGraphType;
-
- /**
- * Represents a tube id which may not occur. This may be used
- * for error states or for indicating that something went wrong.
- */
- static const TubeDescriptorType ErrorId;
-
- //--- Macros ---//
- mitkClassMacro(TubeGraph, Superclass);
- itkNewMacro(Self);
-
- /**
- * Search only the shortest path between two tubes.
- */
- std::vector<TubeDescriptorType> SearchShortestPath(
- const TubeDescriptorType &startTube, const TubeDescriptorType &endTube /*, std::vector<unsigned long> barrier*/);
-
- /**
- * Search every path between two tubes.
- */
- std::vector<TubeDescriptorType> SearchAllPathBetweenVertices(
- const TubeDescriptorType &startTube, const TubeDescriptorType &endTube /*, std::vector<unsigned long> barrier*/);
- std::vector<TubeDescriptorType> SearchPathToPeriphery(
- const TubeDescriptorType &startTube /*, std::vector<unsigned long> barrier*/);
-
- /**
- * Find thickest tube in the graph. This means the tube which has the element with the largest diameter.
- */
- TubeDescriptorType GetThickestTube();
-
- /**
- * Get this undirected graph as a directed graph. For this convertation you need a start point.
- */
- DirectedGraphType GetDirectedGraph(VertexDescriptorType startVertex);
-
- /**
- * Create a subgraph with all given tubes. The origin graph would not be changed.
- */
- TubeGraph::Pointer CreateSubGraph(std::vector<TubeDescriptorType> subGraphTubes);
-
- /**
- * Remove a part of the graph. All tubes, that means all edges and if necessary also the vertex (no other out-edge)
- * of the tube will be deleted.
- */
- void RemoveSubGraph(std::vector<TubeDescriptorType> deletedTubes);
-
- void SetRootTube(const TubeDescriptorType &root);
- void SetRoot(const VertexDescriptorType &root);
- TubeDescriptorType GetRootTube();
- VertexDescriptorType GetRootVertex();
-
- protected:
- TubeGraph();
- TubeGraph(const TubeGraph &graph);
- ~TubeGraph() override;
-
- TubeGraph &operator=(const TubeGraph &rhs);
-
- private:
- TubeDescriptorType m_RootTube;
- VertexDescriptorType m_Root;
-
- void GetOutEdgesOfAVertex(VertexDescriptorType vertex,
- DirectedGraphType &directedGraph,
- std::vector<TubeDescriptorType> &pathToPeriphery);
- };
-
- /**
- * Defines a own graph visitor for breadth-first-search.
- * This visitor should be create a new directed graph by passing the edges of a undirected graph.
- */
- class DirectedGraphBfsVisitor : public boost::default_bfs_visitor
- {
- public:
- DirectedGraphBfsVisitor(TubeGraph *oldGraph, TubeGraph::DirectedGraphType &newGraph)
- : m_OrignialGraph(oldGraph), m_DirectedGraph(newGraph)
- {
- }
-
- void tree_edge(TubeGraph::EdgeDescriptorType e, const TubeGraph::GraphType &g)
- {
- unsigned int numberSource = boost::source(e, g);
- unsigned int numberTarget = boost::target(e, g);
- boost::graph_traits<TubeGraph::DirectedGraphType>::vertex_descriptor source = numberSource;
- boost::graph_traits<TubeGraph::DirectedGraphType>::vertex_descriptor target = numberTarget;
-
- boost::add_edge(source, target, m_DirectedGraph);
- }
-
- private:
- TubeGraph::Pointer m_OrignialGraph;
- TubeGraph::DirectedGraphType &m_DirectedGraph;
- };
-
-} // namespace mitk
-
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphDataInteractor.h b/Modules/TubeGraph/include/mitkTubeGraphDataInteractor.h
deleted file mode 100644
index 37c09298d5..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphDataInteractor.h
+++ /dev/null
@@ -1,122 +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 mitkTubeGraphDataInteractor_h
-#define mitkTubeGraphDataInteractor_h
-
-#include <MitkTubeGraphExports.h>
-
-#include <mitkBaseRenderer.h>
-#include <mitkDataInteractor.h>
-
-#include "mitkTubeGraph.h"
-#include "mitkTubeGraphProperty.h"
-
-namespace mitk
-{
- // Define events for TubeGraph interaction notifications
- itkEventMacroDeclaration(SelectionChangedTubeGraphEvent, itk::AnyEvent);
-
- /**
- * \brief
- *
- * \ingroup Interaction
- */
- // Inherit from DataInteratcor, this provides functionality of a state machine and configurable inputs.
- class MITKTUBEGRAPH_EXPORT TubeGraphDataInteractor : public DataInteractor
- {
- public:
- mitkClassMacro(TubeGraphDataInteractor, DataInteractor);
- itkNewMacro(Self);
-
- /**
- * Describes, which activation modes are available based on the
- * currently picked tube:
- *
- * \li <b>None</b> means "no tube is active"
- * \li <b>Single</b> means "only the picked tube is active"
- * \li <b>ToRoot</b> means "all tubes from the picked on down to the root of the tube graph are active"
- * \li <b>ToPeriphery</b> means "all tubes included in the subgraph of the currently picked vessel are active"
- * \li <b>Points</b> means "shortes path between two picked tubes are active"
- * \li <b>Multiple</b> means "all picked tubes are active"
- */
- enum ActivationMode
- {
- None = 0,
- Single,
- ToRoot,
- ToPeriphery,
- Points,
- Multiple
- };
-
- enum ActionMode
- {
- AttributationMode = 0,
- AnnotationMode,
- EditMode,
- RootMode,
- InformationMode
- };
-
- void SetActivationMode(const ActivationMode &activationMode);
- ActivationMode GetActivationMode();
-
- void SetActionMode(const ActionMode &actionMode);
- ActionMode GetActionMode();
-
- void ResetPickedTubes();
-
- mitk::Point3D GetLastPickedPosition();
-
- protected:
- TubeGraphDataInteractor();
- ~TubeGraphDataInteractor() override;
-
- /**
- * Here actions strings from the loaded state machine pattern are mapped to functions of
- * the DataInteractor. These functions are called when an action from the state machine pattern is executed.
- */
- void ConnectActionsAndFunctions() override;
-
- /**
- * This function is called when a DataNode has been set/changed.
- */
- void DataNodeChanged() override;
-
- /**
- * Initializes the movement, stores starting position.
- */
- virtual bool CheckOverTube(const InteractionEvent *);
- virtual void SelectTube(StateMachineAction *, InteractionEvent *);
- virtual void DeselectTube(StateMachineAction *, InteractionEvent *);
-
- void SelectTubesByActivationModus();
- void UpdateActivation();
-
- private:
- std::vector<TubeGraph::TubeDescriptorType> GetTubesToRoot();
- std::vector<TubeGraph::TubeDescriptorType> GetTubesBetweenPoints();
- std::vector<TubeGraph::TubeDescriptorType> GetPathToPeriphery();
- std::vector<TubeGraph::TubeDescriptorType> GetPathBetweenTubes(const TubeGraph::TubeDescriptorType &start,
- const TubeGraph::TubeDescriptorType &end);
-
- TubeGraph::Pointer m_TubeGraph;
- TubeGraphProperty::Pointer m_TubeGraphProperty;
- TubeGraph::TubeDescriptorType m_LastPickedTube;
- TubeGraph::TubeDescriptorType m_SecondLastPickedTube;
- ActivationMode m_ActivationMode;
- ActionMode m_ActionMode;
- mitk::TubeElement *m_LastPickedElement = nullptr;
- };
-}
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphDefinitions.h b/Modules/TubeGraph/include/mitkTubeGraphDefinitions.h
deleted file mode 100644
index d5b4a35fef..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphDefinitions.h
+++ /dev/null
@@ -1,110 +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 mitkTubeGraphDefinitions_h
-#define mitkTubeGraphDefinitions_h
-
-#include <string>
-
-namespace mitk
-{
- /** \brief The XML consts for reading and writing
- */
-
- class TubeGraphDefinitions
- {
- public:
- //============== XML const chars ===================
-
- //==== Header information ====
- static const std::string XML_TUBEGRAPH_FILE;
- static const std::string XML_FILE_VERSION;
- static const std::string VERSION_STRING;
- static const std::string ASCII_FILE;
- static const std::string FILE_NAME;
-
- //==== Geometry details ====
- static const std::string XML_GEOMETRY;
-
- static const std::string XML_MATRIX_XX;
- static const std::string XML_MATRIX_XY;
- static const std::string XML_MATRIX_XZ;
- static const std::string XML_MATRIX_YX;
- static const std::string XML_MATRIX_YY;
- static const std::string XML_MATRIX_YZ;
- static const std::string XML_MATRIX_ZX;
- static const std::string XML_MATRIX_ZY;
- static const std::string XML_MATRIX_ZZ;
-
- static const std::string XML_ORIGIN_X;
- static const std::string XML_ORIGIN_Y;
- static const std::string XML_ORIGIN_Z;
-
- static const std::string XML_SPACING_X;
- static const std::string XML_SPACING_Y;
- static const std::string XML_SPACING_Z;
-
- //==== tube graph structures ====
- static const std::string XML_VERTICES;
- static const std::string XML_EDGES;
- static const std::string XML_LABELGROUPS;
- static const std::string XML_ATTRIBUTIONS;
- static const std::string XML_ANNOTATIONS;
- static const std::string XML_VERTEX;
- static const std::string XML_EDGE;
- static const std::string XML_ELEMENT;
- static const std::string XML_LABELGROUP;
- static const std::string XML_LABEL;
- static const std::string XML_ATTRIBUTION;
- static const std::string XML_ANNOTATION;
-
- //==== vertex properties ====
- static const std::string XML_VERTEX_ID;
-
- //==== edge properties ====
- static const std::string XML_EDGE_ID;
- static const std::string XML_EDGE_SOURCE_ID;
- static const std::string XML_EDGE_TARGET_ID;
-
- //==== element properties ====
-
- static const std::string XML_ELEMENT_X;
- static const std::string XML_ELEMENT_Y;
- static const std::string XML_ELEMENT_Z;
- static const std::string XML_ELEMENT_DIAMETER;
-
- //==== label group properties ====
- static const std::string XML_LABELGROUP_NAME;
-
- //==== label properties ====
- static const std::string XML_LABEL_NAME;
- static const std::string XML_LABEL_VISIBILITY;
- static const std::string XML_LABEL_COLOR_R;
- static const std::string XML_LABEL_COLOR_G;
- static const std::string XML_LABEL_COLOR_B;
-
- //==== tube properties ====
- static const std::string XML_TUBE_ID_1;
- static const std::string XML_TUBE_ID_2;
-
- //==== annotation properties ====
- static const std::string XML_ANNOTATION_NAME;
- static const std::string XML_ANNOTATION_DESCRIPTION;
-
- private:
- TubeGraphDefinitions();
- ~TubeGraphDefinitions();
- };
-
-} // namespace MITK
-
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphEdge.h b/Modules/TubeGraph/include/mitkTubeGraphEdge.h
deleted file mode 100644
index 4debead6b3..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphEdge.h
+++ /dev/null
@@ -1,102 +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 mitkTubeGraphEdge_h
-#define mitkTubeGraphEdge_h
-
-#include <MitkTubeGraphExports.h>
-
-#include "mitkCircularProfileTubeElement.h"
-#include "mitkTubeElement.h"
-#include "mitkTubeGraphVertex.h"
-
-namespace mitk
-{
- /**
- * \brief Base Class for Tube Graph Edges
- */
- class MITKTUBEGRAPH_EXPORT TubeGraphEdge
- {
- public:
- TubeGraphEdge();
- virtual ~TubeGraphEdge();
-
- /**
- * Set the vector which contains all TubeElements.
- * @param elementVector Vector with all TubeElements
- */
- void SetElementVector(std::vector<TubeElement *> elementVector);
-
- /**
- * Returns the vector which contains all TubeElements.
- * @returns vector with all TubeElements.
- */
- std::vector<TubeElement *> GetElementVector();
-
- /**
- * Returns the number of TubeElements which are contained in this tube.
- * @returns Number of TubeElements.
- */
- unsigned int GetNumberOfElements() const;
-
- /**
- * Adds a new TubeElement at the end of this edge.
- * @param element The new TubeElement.
- */
- void AddTubeElement(TubeElement *element);
-
- /**
- * Adds a new TubeElement at the given position.
- * @param position The position for the TubeElement.
- * @param element The new TubeElement.
- */
- void AddTubeElementAt(unsigned int position, TubeElement *element);
-
- /**
- * Returns the TubeElement at the given position.
- * @param position The position of the Element.
- * @returns The TubeElement at the given position.
- */
- TubeElement *GetTubeElement(unsigned int position);
-
- /**
- * Calculates the length of tube graph edge inc. the source and target vertex..
- *
- * @param source the source vertex of the edge
- * @param target the target vertex of the edge
- * @returns the length of the edge in mm
- */
- float GetEdgeLength(TubeGraphVertex &source, TubeGraphVertex &target);
-
- /**
- * Calculates the average diameter of tube graph edge inc. the source and target vertex.
- *
- * @param source the source vertex of the edge
- * @param target the target vertex of the edge
- * @returns the average diameter of the edge
- */
- float GetEdgeAverageDiameter(TubeGraphVertex &source, TubeGraphVertex &target);
-
- /**
- * Comparison operation between this object and the given object.
- * @param right The object to compare with.
- * @return true, if the object is the same;false, if not.
- */
- bool operator==(const TubeGraphEdge &right) const;
-
- private:
- std::vector<TubeElement *> m_ElementVector;
-
- }; // class
-
-} // namespace
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphIO.h b/Modules/TubeGraph/include/mitkTubeGraphIO.h
deleted file mode 100644
index 9be4e611ab..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphIO.h
+++ /dev/null
@@ -1,69 +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 mitkTubeGraphIO_h
-#define mitkTubeGraphIO_h
-
-#include <mitkAbstractFileIO.h>
-#include <mitkCustomMimeType.h>
-#include <mitkIOMimeTypes.h>
-
-#include "mitkTubeGraph.h"
-
-namespace mitk
-{
- /**
- * @brief reader and writer for xml representations of mitk::TubeGraph
- *
- * @ingroup IO
- */
- class TubeGraphIO : public mitk::AbstractFileIO
- {
- public:
- TubeGraphIO();
-
- // -------------- AbstractFileReader -------------
-
- using AbstractFileReader::Read;
-
- ConfidenceLevel GetReaderConfidenceLevel() const override;
-
- // -------------- AbstractFileWriter -------------
-
- void Write() override;
- ConfidenceLevel GetWriterConfidenceLevel() const override;
-
- static CustomMimeType TUBEGRAPH_MIMETYPE() // tsf
- {
- CustomMimeType mimeType(TUBEGRAPH_MIMETYPE_NAME());
- mimeType.AddExtension("tsf");
- mimeType.SetCategory("Graphs");
- mimeType.SetComment("MITK Tube Graph Structure File");
- return mimeType;
- }
- static std::string TUBEGRAPH_MIMETYPE_NAME()
- {
- static std::string name = mitk::IOMimeTypes::DEFAULT_BASE_NAME() + ".graphs.tubular-sructure";
- return name;
- }
-
- protected:
- std::vector<itk::SmartPointer<BaseData>> DoRead() override;
-
- private:
- TubeGraphIO *IOClone() const override;
- TubeGraphIO(const TubeGraphIO &other);
- const BoundingBox::Pointer ComputeBoundingBox(TubeGraph::Pointer graph) const;
- };
-}
-
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphObjectFactory.h b/Modules/TubeGraph/include/mitkTubeGraphObjectFactory.h
deleted file mode 100644
index 3d8548db67..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphObjectFactory.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkTubeGraphObjectFactory_h
-#define mitkTubeGraphObjectFactory_h
-
-#include <MitkTubeGraphExports.h>
-
-#include <mitkCoreObjectFactory.h>
-
-namespace mitk
-{
- class MITKTUBEGRAPH_EXPORT TubeGraphObjectFactory : public CoreObjectFactoryBase
- {
- public:
- mitkClassMacro(TubeGraphObjectFactory, CoreObjectFactoryBase);
- itkFactorylessNewMacro(Self);
- itkCloneMacro(Self);
-
- Mapper::Pointer CreateMapper(mitk::DataNode *node, MapperSlotId slotId) override;
- void SetDefaultProperties(mitk::DataNode *node) override;
- std::string GetFileExtensions() override;
- mitk::CoreObjectFactoryBase::MultimapType GetFileExtensionsMap() override;
- std::string GetSaveFileExtensions() override;
- mitk::CoreObjectFactoryBase::MultimapType GetSaveFileExtensionsMap() override;
- void RegisterIOFactories();
-
- protected:
- TubeGraphObjectFactory();
-
- private:
- void CreateFileExtensionsMap();
-
- std::string m_ExternalFileExtensions;
- std::string m_InternalFileExtensions;
- std::string m_SaveFileExtensions;
- MultimapType m_FileExtensionsMap;
- MultimapType m_SaveFileExtensionsMap;
- };
-}
-
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphPicker.h b/Modules/TubeGraph/include/mitkTubeGraphPicker.h
deleted file mode 100644
index 930b16e6a7..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphPicker.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 mitkTubeGraphPicker_h
-#define mitkTubeGraphPicker_h
-
-#include <MitkTubeGraphExports.h>
-
-#include "mitkCircularProfileTubeElement.h"
-#include "mitkTubeGraph.h"
-#include "mitkTubeGraphProperty.h"
-
-namespace mitk
-{
- class MITKTUBEGRAPH_EXPORT TubeGraphPicker
- {
- public:
- /* mitkClassMacro( TubeGraphPicker, BaseDataSource );
- itkNewMacro( Self );*/
-
- void SetTubeGraph(const TubeGraph *tubeGraph);
-
- std::pair<mitk::TubeGraph::TubeDescriptorType, mitk::TubeElement *> GetPickedTube(const Point3D pickedPosition);
-
- TubeGraphPicker();
- virtual ~TubeGraphPicker();
-
- protected:
- Point3D m_WorldPosition;
- TubeGraph::ConstPointer m_TubeGraph;
- TubeGraphProperty::Pointer m_TubeGraphProperty;
- };
-
-} // namespace
-
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphProperty.h b/Modules/TubeGraph/include/mitkTubeGraphProperty.h
deleted file mode 100644
index 95fc651efe..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphProperty.h
+++ /dev/null
@@ -1,149 +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 mitkTubeGraphProperty_h
-#define mitkTubeGraphProperty_h
-
-#include <MitkTubeGraphExports.h>
-
-#include "mitkTubeGraph.h"
-#include <mitkBaseProperty.h>
-#include <mitkColorProperty.h>
-
-#include <itkObject.h>
-#include <map>
-#include <vector>
-
-namespace mitk
-{
- /**
- * \brief Property for tube graphs
- */
- class MITKTUBEGRAPH_EXPORT TubeGraphProperty : public BaseProperty
- {
- public:
- mitkClassMacro(TubeGraphProperty, BaseProperty);
- itkNewMacro(TubeGraphProperty);
-
- struct LabelGroup
- {
- struct Label
- {
- std::string labelName;
- bool isVisible;
- Color labelColor;
- };
- std::string labelGroupName;
- std::vector<Label *> labels;
- };
-
- ///////////////TYPEDEF///////////////
- typedef TubeGraph::TubeDescriptorType TubeDescriptorType;
- typedef std::vector<TubeGraphProperty::LabelGroup *> LabelGroupSetType;
- typedef std::pair<TubeDescriptorType, std::string> TubeToLabelGroupType;
- /////////////////////////////////////
-
- struct Annotation
- {
- std::string name;
- std::string description;
- TubeDescriptorType tube;
- };
-
- /**
- * Checks, if a given tube is visible
- * @param tube the tube id of the tube to check
- * @returns true, if the tube with id is visible or false otherwise
- */
- bool IsTubeVisible(const TubeDescriptorType &tube);
-
- /**
- * Sets a tube active.
- * @param tube the tube id of the tube, which has to be set active
- * @param active true, if the tube should be active or false if not.
- */
- void SetTubeActive(const TubeDescriptorType &tube, const bool &active);
-
- /**
- * Sets tubes active.
- *
- */
- void SetTubesActive(std::vector<TubeDescriptorType> &tubes);
-
- /**
- * Checks, if a given tube is activated
- * @param tube the to check
- * @returns true, if the tube with id is active or false otherwise
- */
- bool IsTubeActive(const TubeDescriptorType &tube);
-
- std::vector<TubeDescriptorType> GetActiveTubes();
-
- Color GetColorOfTube(const TubeDescriptorType &tube);
-
- void SetTubesToLabels(std::map<TubeToLabelGroupType, std::string> tubeToLabelMap);
-
- std::map<TubeToLabelGroupType, std::string> GetTubesToLabels();
-
- /**
- * Deactivates all tubes
- */
- void DeactivateAllTubes();
-
- void AddAnnotation(Annotation *annotation);
- Annotation *GetAnnotationByName(std::string annotation);
- std::vector<Annotation *> GetAnnotations();
- void RemoveAnnotation(Annotation *annotation);
-
- void AddLabelGroup(LabelGroup *labelGroup, unsigned int position); // Add LG by name and vec<labelName>??
- void RemoveLabelGroup(LabelGroup *labelGroup);
- LabelGroupSetType GetLabelGroups();
- unsigned int GetNumberOfLabelGroups();
- unsigned int GetIndexOfLabelGroup(LabelGroup *labelGroup);
- LabelGroup *GetLabelGroupByName(std::string labelGroup);
-
- void SetLabelVisibility(LabelGroup::Label *label, bool isVisible);
- void SetLabelColor(LabelGroup::Label *label, Color color);
- void RenameLabel(LabelGroup *labelGroup, LabelGroup::Label *label, std::string newName);
- void SetLabelForActivatedTubes(LabelGroup *labelGroup, LabelGroup::Label *label);
-
- LabelGroup::Label *GetLabelByName(LabelGroup *labelGroup, std::string labelName);
-
- std::string GetValueAsString() const override;
-
- bool ToJSON(nlohmann::json& j) const override;
- bool FromJSON(const nlohmann::json& j) override;
-
- protected:
- TubeGraphProperty();
- TubeGraphProperty(const TubeGraphProperty &other);
- ~TubeGraphProperty() override;
-
- private:
- std::vector<TubeDescriptorType> m_ActiveTubes;
- LabelGroupSetType m_LabelGroups;
- std::map<TubeToLabelGroupType, std::string> m_TubeToLabelsMap;
- std::vector<Annotation *> m_Annotations;
-
- bool TubeDescriptorsCompare(const TubeDescriptorType &tube1, const TubeDescriptorType &tube2);
-
- // purposely not implemented
- TubeGraphProperty &operator=(const TubeGraphProperty &);
-
- bool IsEqual(const BaseProperty &property) const override;
- bool Assign(const BaseProperty &property) override;
- itk::LightObject::Pointer InternalClone() const override;
- };
-
-} // namespace mitk
-
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphVertex.h b/Modules/TubeGraph/include/mitkTubeGraphVertex.h
deleted file mode 100644
index 5688b4e8af..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphVertex.h
+++ /dev/null
@@ -1,57 +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 mitkTubeGraphVertex_h
-#define mitkTubeGraphVertex_h
-
-#include <MitkTubeGraphExports.h>
-
-#include "mitkTubeElement.h"
-
-namespace mitk
-{
- /**
- * \brief Base Class for Tube Graph Vertices
- */
- class MITKTUBEGRAPH_EXPORT TubeGraphVertex
- {
- public:
- TubeGraphVertex();
- TubeGraphVertex(TubeElement *element);
- virtual ~TubeGraphVertex();
-
- /**
- * Set the TubeElement which contains the information about diameter and position.
- * @param element The TubeElement for the vertex.
- */
- void SetTubeElement(TubeElement *element);
-
- /**
- * Returns the TubeElement.
- * @returns The TubeElement
- */
- const TubeElement *GetTubeElement() const;
-
- /**
- * Comparison operation between this object and the given object.
- * @param right The object to compare with.
- * @return true, if the object is the same;false, if not.
- */
- bool operator==(const TubeGraphVertex &right) const;
-
- private:
- TubeElement *m_element;
-
- }; // class
-
-} // namespace
-#endif
diff --git a/Modules/TubeGraph/include/mitkTubeGraphVtkMapper3D.h b/Modules/TubeGraph/include/mitkTubeGraphVtkMapper3D.h
deleted file mode 100644
index a2f2bebf7e..0000000000
--- a/Modules/TubeGraph/include/mitkTubeGraphVtkMapper3D.h
+++ /dev/null
@@ -1,116 +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 mitkTubeGraphVtkMapper3D_h
-#define mitkTubeGraphVtkMapper3D_h
-
-#include <MitkTubeGraphExports.h>
-#include <mitkLocalStorageHandler.h>
-
-#include "mitkCircularProfileTubeElement.h"
-#include "mitkTubeGraph.h"
-#include "mitkTubeGraphProperty.h"
-#include "mitkVtkMapper.h"
-
-#include <vtkActor.h>
-#include <vtkAppendPolyData.h>
-#include <vtkAssembly.h>
-#include <vtkPolyData.h>
-#include <vtkSmartPointer.h>
-
-namespace mitk
-{
- /**
- * 3D Mapper for mitk::Graph< TubeGraphVertex, TubeGraphEdge >. This mapper creates tubes
- * around each tubular structure by using vtkTubeFilter.
- *
- */
-
- class MITKTUBEGRAPH_EXPORT TubeGraphVtkMapper3D : public VtkMapper
- {
- public:
- /* Typedefs */
- typedef TubeGraph::EdgeDescriptorType EdgeDescriptorType;
- typedef TubeGraph::VertexDescriptorType VertexDescriptorType;
-
- mitkClassMacro(TubeGraphVtkMapper3D, VtkMapper);
- itkNewMacro(Self);
- /**
- * Returns the input data object of the given filter. In this
- * case, a mitk::Graph< TubeGraphVertex, TubeGraphEdge > is returned.
- */
- virtual const TubeGraph *GetInput();
- vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override;
-
- protected:
- TubeGraphVtkMapper3D();
- ~TubeGraphVtkMapper3D() override;
-
- /**
- * This method is called, each time a specific renderer is updated.
- */
- void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override;
-
- /**
- * Generate vtkPolyData containing the tube centerlines and
- * sets these as input for a vtkTubeFilter, which generates tubes
- * around the edges. Also generates vtkActors for each vertex. Here
- * the vtkPolyData are vtkSphereSources. All poly data will be clipped
- * with each other on an furcation. So you get end-caps and connecting
- * pieces from the spheres. Clipping the tubes with each other avoids
- * structures within the general view.
- */
- virtual void GenerateTubeGraphData(mitk::BaseRenderer *renderer);
-
- /**
- * Render only the visual information like color or visibility new.
- */
- virtual void RenderTubeGraphPropertyInformation(mitk::BaseRenderer *renderer);
-
- /**
- * Converts a single tube into a vtkPolyData. Each point of the
- * tube surface is labeled with the tube id.
- */
- void GeneratePolyDataForTube(TubeGraphEdge &edge,
- const TubeGraph::Pointer &graph,
- const TubeGraphProperty::Pointer &graphProperty,
- mitk::BaseRenderer *renderer);
- void GeneratePolyDataForFurcation(TubeGraphVertex &vertex,
- const TubeGraph::Pointer &graph,
- mitk::BaseRenderer *renderer);
- void ClipPolyData(TubeGraphVertex &vertex,
- const TubeGraph::Pointer &graph,
- const TubeGraphProperty::Pointer &graphProperty,
- mitk::BaseRenderer *renderer);
-
- private:
- bool ClipStructures();
-
- class LocalStorage : public mitk::Mapper::BaseLocalStorage
- {
- public:
- vtkSmartPointer<vtkAssembly> m_vtkTubeGraphAssembly;
- std::map<TubeGraph::TubeDescriptorType, vtkSmartPointer<vtkActor>> m_vtkTubesActorMap;
- std::map<TubeGraph::VertexDescriptorType, vtkSmartPointer<vtkActor>> m_vtkSpheresActorMap;
-
- itk::TimeStamp m_lastGenerateDataTime;
- itk::TimeStamp m_lastRenderDataTime;
-
- LocalStorage() { m_vtkTubeGraphAssembly = vtkSmartPointer<vtkAssembly>::New(); }
- ~LocalStorage() override {}
- };
-
- LocalStorageHandler<LocalStorage> m_LSH;
- };
-} // namespace
-
-#endif
diff --git a/Modules/TubeGraph/include/mitkUndirectedGraph.h b/Modules/TubeGraph/include/mitkUndirectedGraph.h
deleted file mode 100644
index d59150607d..0000000000
--- a/Modules/TubeGraph/include/mitkUndirectedGraph.h
+++ /dev/null
@@ -1,174 +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 mitkUndirectedGraph_h
-#define mitkUndirectedGraph_h
-
-#include <mitkBaseData.h>
-
-#ifndef Q_MOC_RUN
-#include <boost/graph/adjacency_list.hpp>
-#endif
-
-/* definition of basic boost::graph properties */
-enum vertex_properties_t
-{
- vertex_properties
-};
-enum edge_properties_t
-{
- edge_properties
-};
-
-namespace boost
-{
- BOOST_INSTALL_PROPERTY(vertex, properties);
- BOOST_INSTALL_PROPERTY(edge, properties);
-}
-
-namespace mitk
-{
- /**
- * \brief Template class for undirected graphs.Paramters should be the vertex and edge classes, which contains the
- * information.
- */
- template <class TVertex, class TEdge>
- class UndirectedGraph : public BaseData
- {
- public:
- //--- Typedefs ---//
-
- typedef TVertex VertexType;
- typedef TEdge EdgeType;
- /**
- * Creating the graph type
- * listS: Represents the OutEdgeList as a std::list
- * vecS: Represents the VertexList as a std::vector
- * undirectedS: Representation for an undirected graph
- * VertexProperty: Defines that all vertex are represented by VertexType
- * EdgeProperty: Defines that all edges are represented by EdgeType
- */
- typedef boost::adjacency_list<boost::listS,
- boost::vecS,
- boost::undirectedS, // undirected graph
- boost::property<vertex_properties_t, VertexType>,
- boost::property<edge_properties_t, EdgeType>>
- GraphType;
-
- /* a bunch of graph-specific typedefs */
- typedef typename boost::graph_traits<GraphType>::vertex_descriptor VertexDescriptorType;
- typedef typename boost::graph_traits<GraphType>::edge_descriptor EdgeDescriptorType;
-
- typedef typename boost::graph_traits<GraphType>::vertex_iterator VertexIteratorType;
- typedef typename boost::graph_traits<GraphType>::edge_iterator EdgeIteratorType;
- typedef typename boost::graph_traits<GraphType>::adjacency_iterator AdjacenyIteratorType;
- typedef typename boost::graph_traits<GraphType>::out_edge_iterator OutEdgeIteratorType;
- typedef typename boost::graph_traits<GraphType>::in_edge_iterator InEdgeIteratorType;
-
- //--- Macros ---//
- mitkClassMacro(UndirectedGraph, BaseData);
- itkNewMacro(Self);
-
- // virtual methods that need to be implemented
- void UpdateOutputInformation() override
- {
- if (this->GetSource())
- this->GetSource()->UpdateOutputInformation();
- }
- void SetRequestedRegionToLargestPossibleRegion() override {}
- bool RequestedRegionIsOutsideOfTheBufferedRegion() override { return false; }
- bool VerifyRequestedRegion() override { return true; }
- void SetRequestedRegion(const itk::DataObject *) override {}
- /** Add a new vertex to the graph */
- VertexDescriptorType AddVertex(const VertexType &vertexData);
-
- /** Remove the vertex from the graph */
- void RemoveVertex(const VertexDescriptorType &vertex);
-
- /** Get the vertex data of the given vertex descriptor */
- VertexType GetVertex(const VertexDescriptorType &vertex);
-
- /** Set the vertex data of the given vertex descriptor */
- void SetVertex(const VertexDescriptorType &vertex, const VertexType &vertexData);
-
- /**Returns the descriptor if the vertex exist in the graph, otherwise undefined*/
- VertexDescriptorType GetVertexDescriptor(const VertexType &vertexData) const;
-
- /** Add a new edge between the given vertices to the graph */
- EdgeDescriptorType AddEdge(const VertexDescriptorType &vertexA,
- const VertexDescriptorType &vertexB,
- const EdgeType &edgeData);
-
- /** Remove the edge from the graph */
- void RemoveEdge(const EdgeDescriptorType &edge);
-
- /** Get the edge data of the given edge descriptor */
- EdgeType GetEdge(const EdgeDescriptorType &edge);
-
- /** Set the edge data of the given edge descriptor */
- void SetEdge(const EdgeDescriptorType &edge, const EdgeType &edgeData);
-
- /**Returns the descriptor if the edge exist in the graph, otherwise undefined*/
- EdgeDescriptorType GetEdgeDescriptor(const EdgeType &edgeData) const;
-
- /** Get parent and target vertex of the given edge*/
- std::pair<VertexType, VertexType> GetVerticesOfAnEdge(const EdgeDescriptorType &edge) const;
-
- /** Returns the edge descriptor from the edge which has the given vertices as source and target */
- EdgeDescriptorType GetEdgeDescriptorByVerices(const VertexDescriptorType &vertexA,
- const VertexDescriptorType &vertexB) const;
-
- /** Get all edges of the given vertex */
- std::vector<EdgeType> GetAllEdgesOfAVertex(const VertexDescriptorType &vertex) const;
-
- /** Get overall number of vertices in the graph */
- int GetNumberOfVertices() const;
-
- /** get overall number of edges in the graph */
- int GetNumberOfEdges() const;
-
- /** get vector containing all the vertices of the graph*/
- std::vector<VertexType> GetVectorOfAllVertices() const;
-
- /** get vector containing all the edges of the network */
- std::vector<EdgeType> GetVectorOfAllEdges() const;
-
- /** clear the graph */
- void Clear() override;
-
- /** get the graph */
- const GraphType &GetGraph() const;
-
- UndirectedGraph<VertexType, EdgeType> &operator=(const UndirectedGraph<VertexType, EdgeType> &rhs);
-
- protected:
- UndirectedGraph();
- ~UndirectedGraph() override;
-
- GraphType m_Graph;
-
- private:
- /** property access for vertices */
- VertexType &properties(const VertexDescriptorType &vertex);
- /** property access for vertices */
- const VertexType &properties(const VertexDescriptorType &vertex) const;
- /** property access for edges */
- EdgeType &properties(const EdgeDescriptorType &edge);
- /** property access for edges */
- const EdgeType &properties(const EdgeDescriptorType &edge) const;
- };
-
-} // namespace mitk
-
-#include "mitkUndirectedGraph.txx"
-
-#endif
diff --git a/Modules/TubeGraph/include/mitkUndirectedGraph.txx b/Modules/TubeGraph/include/mitkUndirectedGraph.txx
deleted file mode 100644
index a33c826a72..0000000000
--- a/Modules/TubeGraph/include/mitkUndirectedGraph.txx
+++ /dev/null
@@ -1,336 +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 _mitkUndirectedGraph_txx
-#define _mitkUndirectedGraph_txx
-
-namespace mitk
-{
- template <class TVertex, class TEdge>
- UndirectedGraph<TVertex, TEdge>::UndirectedGraph()
- {
- }
-
- template <class TVertex, class TEdge>
- UndirectedGraph<TVertex, TEdge>::~UndirectedGraph()
- {
- }
-
- template <class TVertex, class TEdge>
- typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType UndirectedGraph<TVertex, TEdge>::AddVertex(
- const typename UndirectedGraph<TVertex, TEdge>::VertexType &vertexData)
- {
- VertexDescriptorType vertex = boost::add_vertex(m_Graph);
- this->properties(vertex) = vertexData;
-
- this->Modified();
-
- return vertex;
- }
-
- template <class TVertex, class TEdge>
- void UndirectedGraph<TVertex, TEdge>::RemoveVertex(
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertex)
- {
- boost::clear_vertex(vertex, m_Graph);
- boost::remove_vertex(vertex, m_Graph);
- this->Modified();
- }
-
- template <class TVertex, class TEdge>
- typename UndirectedGraph<TVertex, TEdge>::VertexType UndirectedGraph<TVertex, TEdge>::GetVertex(
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertex)
- {
- return this->properties(vertex);
- }
-
- template <class TVertex, class TEdge>
- void UndirectedGraph<TVertex, TEdge>::SetVertex(
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertex,
- const typename UndirectedGraph<TVertex, TEdge>::VertexType &vertexData)
- {
- this->properties(vertex) = vertexData;
-
- this->Modified();
- }
-
- template <class TVertex, class TEdge>
- typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType UndirectedGraph<TVertex, TEdge>::GetVertexDescriptor(
- const typename UndirectedGraph<TVertex, TEdge>::VertexType &vertexData) const
- {
- typename UndirectedGraph<TVertex, TEdge>::VertexIteratorType iterator, end;
-
- boost::tie(iterator, end) = boost::vertices(m_Graph);
-
- for (; iterator != end; ++iterator)
- {
- typename UndirectedGraph<TVertex, TEdge>::VertexType tempVertex;
-
- // the value of an iterator is a descriptor
- tempVertex = this->properties(*iterator);
-
- if (vertexData == tempVertex)
- return *iterator;
- }
- MITK_ERROR << "Error in mitkUndirectedGraph::GetVertexDescriptor(...): vertex could not be found." << std::endl;
- throw std::runtime_error(
- "Exception thrown in mitkUndirectedGraph::GetVertexDescriptor(...): vertex could not be found.");
- }
-
- template <class TVertex, class TEdge>
- typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType UndirectedGraph<TVertex, TEdge>::AddEdge(
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertexA,
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertexB,
- const typename UndirectedGraph<TVertex, TEdge>::EdgeType &edgeData)
- {
- EdgeDescriptorType edge;
- bool inserted = false;
-
- boost::tie(edge, inserted) = boost::add_edge(vertexA, vertexB, m_Graph);
-
- if (!inserted)
- {
- MITK_ERROR << "Error in mitkUndirectedGraph::addEdge(...): edge could not be inserted." << std::endl;
- throw std::runtime_error("Exception thrown in mitkUndirectedGraph::addEdge(...): edge could not be inserted.");
- }
- this->properties(edge) = edgeData;
-
- this->Modified();
-
- return edge;
- }
-
- template <class TVertex, class TEdge>
- void UndirectedGraph<TVertex, TEdge>::RemoveEdge(
- const typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType &edge)
- {
- boost::remove_edge(edge, m_Graph);
- this->Modified();
- }
-
- template <class TVertex, class TEdge>
- typename UndirectedGraph<TVertex, TEdge>::EdgeType UndirectedGraph<TVertex, TEdge>::GetEdge(
- const typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType &edge)
- {
- return this->properties(edge);
- }
-
- template <class TVertex, class TEdge>
- void UndirectedGraph<TVertex, TEdge>::SetEdge(
- const typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType &edge,
- const typename UndirectedGraph<TVertex, TEdge>::EdgeType &edgeData)
- {
- this->properties(edge) = edgeData;
-
- this->Modified();
- }
-
- template <class TVertex, class TEdge>
- typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType UndirectedGraph<TVertex, TEdge>::GetEdgeDescriptor(
- const typename UndirectedGraph<TVertex, TEdge>::EdgeType &edgeData) const
- {
- typename UndirectedGraph<TVertex, TEdge>::EdgeIteratorType iterator, end;
- boost::tie(iterator, end) = boost::edges(m_Graph);
-
- for (; iterator != end; ++iterator)
- {
- typename UndirectedGraph<TVertex, TEdge>::EdgeType tempEdge;
-
- // the value of an iterator is a descriptor
- tempEdge = this->properties(*iterator);
-
- if (edgeData == tempEdge)
- return iterator.dereference();
- }
- // if no edge match, throw error
- MITK_ERROR << "Error in mitkUndirectedGraph::GetEdgeDescriptor(...): edge could not be found." << std::endl;
- throw std::runtime_error(
- "Exception thrown in mitkUndirectedGraph::GetEdgeDescriptor(...): edge could not be found.");
- }
-
- template <class TVertex, class TEdge>
- std::pair<typename UndirectedGraph<TVertex, TEdge>::VertexType, typename UndirectedGraph<TVertex, TEdge>::VertexType>
- UndirectedGraph<TVertex, TEdge>::GetVerticesOfAnEdge(
- const typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType &edge) const
- {
- typename UndirectedGraph<TVertex, TEdge>::VertexType sourceNode, targetNode;
-
- sourceNode = this->properties(boost::source(edge, m_Graph));
- targetNode = this->properties(boost::target(edge, m_Graph));
- std::pair<typename UndirectedGraph<TVertex, TEdge>::VertexType,
- typename UndirectedGraph<TVertex, TEdge>::VertexType>
- nodePair(sourceNode, targetNode);
-
- return nodePair;
- }
-
- template <class TVertex, class TEdge>
- typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType
- UndirectedGraph<TVertex, TEdge>::GetEdgeDescriptorByVerices(
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertexA,
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertexB) const
- {
- typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType edge;
- bool edgeExists(false);
- boost::tie(edge, edgeExists) = boost::edge(vertexA, vertexB, m_Graph);
- if (edgeExists)
- return edge;
- else
- {
- MITK_ERROR << "Error in mitkUndirectedGraph::GetEdgeDescriptorByVerices(...): edge could not be found."
- << std::endl;
- throw std::runtime_error(
- "Exception thrown in mitkUndirectedGraph::GetEdgeDescriptorByVerices(...): edge could not be found.");
- }
- }
-
- template <class TVertex, class TEdge>
- std::vector<typename UndirectedGraph<TVertex, TEdge>::EdgeType> UndirectedGraph<TVertex, TEdge>::GetAllEdgesOfAVertex(
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertex) const
- {
- typename UndirectedGraph<TVertex, TEdge>::OutEdgeIteratorType iterator, end;
- boost::tie(iterator, end) = boost::out_edges(vertex, m_Graph);
-
- std::vector<typename UndirectedGraph<TVertex, TEdge>::EdgeType> vectorOfEdges;
- for (; iterator != end; ++iterator)
- {
- typename UndirectedGraph<TVertex, TEdge>::EdgeType tempEdge;
-
- // the value of an iterator is a descriptor
- tempEdge = this->properties(*iterator);
-
- vectorOfEdges.push_back(tempEdge);
- }
-
- return vectorOfEdges;
- }
-
- template <class TVertex, class TEdge>
- int UndirectedGraph<TVertex, TEdge>::GetNumberOfVertices() const
- {
- // Returns the number of vertices in the graph
- return boost::num_vertices(m_Graph);
- }
-
- template <class TVertex, class TEdge>
- int UndirectedGraph<TVertex, TEdge>::GetNumberOfEdges() const
- {
- // Returns the number of edges in the graph
- return boost::num_edges(m_Graph);
- }
-
- template <class TVertex, class TEdge>
- std::vector<typename UndirectedGraph<TVertex, TEdge>::VertexType>
- UndirectedGraph<TVertex, TEdge>::GetVectorOfAllVertices() const
- {
- typename UndirectedGraph<TVertex, TEdge>::VertexIteratorType iterator, end;
-
- // sets iterator to start end end to end
- boost::tie(iterator, end) = boost::vertices(m_Graph);
-
- std::vector<typename UndirectedGraph<TVertex, TEdge>::VertexType> vectorOfNodes;
-
- for (; iterator != end; ++iterator)
- {
- typename UndirectedGraph<TVertex, TEdge>::VertexType tempVertex;
-
- // the value of an iterator is a descriptor
- tempVertex = this->properties(*iterator);
-
- vectorOfNodes.push_back(tempVertex);
- }
-
- return vectorOfNodes;
- }
-
- template <class TVertex, class TEdge>
- std::vector<typename UndirectedGraph<TVertex, TEdge>::EdgeType> UndirectedGraph<TVertex, TEdge>::GetVectorOfAllEdges()
- const
- {
- typename UndirectedGraph<TVertex, TEdge>::EdgeIteratorType iterator, end;
-
- // sets iterator to start end end to end
- boost::tie(iterator, end) = boost::edges(m_Graph);
-
- std::vector<typename UndirectedGraph<TVertex, TEdge>::EdgeType> vectorOfEdges;
-
- for (; iterator != end; ++iterator)
- {
- typename UndirectedGraph<TVertex, TEdge>::EdgeType tempEdge;
-
- // the value of an iterator is a descriptor
- tempEdge = this->properties(*iterator);
-
- vectorOfEdges.push_back(tempEdge);
- }
-
- return vectorOfEdges;
- }
-
- template <class TVertex, class TEdge>
- void UndirectedGraph<TVertex, TEdge>::Clear()
- {
- m_Graph.clear();
- this->Modified();
- }
-
- template <class TVertex, class TEdge>
- const typename UndirectedGraph<TVertex, TEdge>::GraphType &UndirectedGraph<TVertex, TEdge>::GetGraph() const
- {
- return m_Graph;
- }
-
- /* operators */
- template <class TVertex, class TEdge>
- UndirectedGraph<TVertex, TEdge> &UndirectedGraph<TVertex, TEdge>::operator=(
- const UndirectedGraph<TVertex, TEdge> &rhs)
- {
- m_Graph = rhs.m_Graph;
- return *this;
- }
-
- template <class TVertex, class TEdge>
- TVertex &UndirectedGraph<TVertex, TEdge>::properties(
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertex)
- {
- typename boost::property_map<GraphType, vertex_properties_t>::type param = boost::get(vertex_properties, m_Graph);
- return param[vertex];
- }
-
- template <class TVertex, class TEdge>
- const TVertex &UndirectedGraph<TVertex, TEdge>::properties(
- const typename UndirectedGraph<TVertex, TEdge>::VertexDescriptorType &vertex) const
- {
- typename boost::property_map<GraphType, vertex_properties_t>::const_type param =
- boost::get(vertex_properties, m_Graph);
- return param[vertex];
- }
-
- template <class TVertex, class TEdge>
- TEdge &UndirectedGraph<TVertex, TEdge>::properties(
- const typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType &edge)
- {
- typename boost::property_map<GraphType, edge_properties_t>::type param = boost::get(edge_properties, m_Graph);
- return param[edge];
- }
-
- template <class TVertex, class TEdge>
- const TEdge &UndirectedGraph<TVertex, TEdge>::properties(
- const typename UndirectedGraph<TVertex, TEdge>::EdgeDescriptorType &edge) const
- {
- typename boost::property_map<GraphType, edge_properties_t>::const_type param = boost::get(edge_properties, m_Graph);
- return param[edge];
- }
-
-} // namespace mitk
-
-#endif //_mitkUndirectedGraph_txx
diff --git a/Modules/TubeGraph/resource/Interactions/TubeGraphConfig.xml b/Modules/TubeGraph/resource/Interactions/TubeGraphConfig.xml
deleted file mode 100644
index 837a989c6f..0000000000
--- a/Modules/TubeGraph/resource/Interactions/TubeGraphConfig.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<config>
- <event_variant name="PickByDouble" class="MouseDoubleClickEvent">
- <attribute name="EventButton" value="LeftMouseButton"/>
- </event_variant>
- <event_variant name="PickByShift" class="MousePressEvent">
- <attribute name="EventButton" value="LeftMouseButton"/>
- <attribute name="Modifiers" value="shift"/>
- </event_variant>
-</config>
diff --git a/Modules/TubeGraph/resource/Interactions/TubeGraphInteraction.xml b/Modules/TubeGraph/resource/Interactions/TubeGraphInteraction.xml
deleted file mode 100644
index 41032b97af..0000000000
--- a/Modules/TubeGraph/resource/Interactions/TubeGraphInteraction.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<statemachine NAME="TubeGraph">
- <state name="start" startstate="true" >
- <transition event_class="InteractionPositionEvent" event_variant="PickByDouble" target="select">
- <condition name="isOverTube"/>
- <action name="selectTube"/>
- </transition>
- <transition event_class="InteractionPositionEvent" event_variant="PickByDouble" target="start">
- <condition name="isOverTube" inverted="true"/>
- <action name="deselectTube"/>
- </transition>
- <transition event_class="InteractionPositionEvent" event_variant="PickByShift" target="select">
- <condition name="isOverTube"/>
- <action name="selectTube"/>
- </transition>
- <transition event_class="InteractionPositionEvent" event_variant="PickByShift" target="start">
- <condition name="isOverTube" inverted="true"/>
- <action name="deselectTube"/>
- </transition>
- </state>
- <state name="select" >
- <transition event_class="InteractionPositionEvent" event_variant="PickByDouble" target="select">
- <condition name="isOverTube"/>
- <action name="selectTube"/>
- </transition>
- <transition event_class="InteractionPositionEvent" event_variant="PickByDouble" target="start">
- <condition name="isOverTube" inverted="true" />
- <action name="deselectTube"/>
- </transition>
- <transition event_class="InteractionPositionEvent" event_variant="PickByShift" target="select">
- <condition name="isOverTube"/>
- <action name="selectTube"/>
- </transition>
- <transition event_class="InteractionPositionEvent" event_variant="PickByShift" target="start">
- <condition name="isOverTube" inverted="true" />
- <action name="deselectTube"/>
- </transition>
- </state>
- </statemachine>
\ No newline at end of file
diff --git a/Modules/TubeGraph/src/DataStructure/mitkCircularProfileTubeElement.cpp b/Modules/TubeGraph/src/DataStructure/mitkCircularProfileTubeElement.cpp
deleted file mode 100644
index a7fbba8da2..0000000000
--- a/Modules/TubeGraph/src/DataStructure/mitkCircularProfileTubeElement.cpp
+++ /dev/null
@@ -1,63 +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 "mitkCircularProfileTubeElement.h"
-
-mitk::CircularProfileTubeElement::CircularProfileTubeElement() : m_coordinates(), m_diameter(0.0f)
-{
-}
-
-mitk::CircularProfileTubeElement::CircularProfileTubeElement(float x, float y, float z, float d) : m_diameter(d)
-{
- mitk::FillVector3D(m_coordinates, x, y, z);
-}
-
-mitk::CircularProfileTubeElement::CircularProfileTubeElement(const mitk::Point3D c, float d)
- : m_coordinates(c), m_diameter(d)
-{
-}
-
-mitk::CircularProfileTubeElement::~CircularProfileTubeElement()
-{
-}
-
-const mitk::Point3D &mitk::CircularProfileTubeElement::GetCoordinates() const
-{
- return m_coordinates;
-}
-
-void mitk::CircularProfileTubeElement::SetCoordinates(mitk::Point3D coordinates)
-{
- m_coordinates = coordinates;
-}
-
-float mitk::CircularProfileTubeElement::GetDiameter() const
-{
- return m_diameter;
-}
-
-void mitk::CircularProfileTubeElement::SetDiameter(float d)
-{
- m_diameter = d;
-}
-
-bool mitk::CircularProfileTubeElement::operator==(const mitk::TubeElement &right) const
-{
- // Check if given TubeElement is CircularProfileTubeElement
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(&right))
- {
- const auto *element = dynamic_cast<const mitk::CircularProfileTubeElement *>(&right);
- return ((m_diameter == element->m_diameter) && (m_coordinates == element->m_coordinates));
- }
- else
- return false;
-}
diff --git a/Modules/TubeGraph/src/DataStructure/mitkTubeGraph.cpp b/Modules/TubeGraph/src/DataStructure/mitkTubeGraph.cpp
deleted file mode 100644
index cdb8a26cf6..0000000000
--- a/Modules/TubeGraph/src/DataStructure/mitkTubeGraph.cpp
+++ /dev/null
@@ -1,273 +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 "mitkTubeGraph.h"
-#include "mitkGeometry3D.h"
-
-const mitk::TubeGraph::TubeDescriptorType mitk::TubeGraph::ErrorId =
- std::pair<VertexDescriptorType, VertexDescriptorType>(boost::graph_traits<GraphType>::null_vertex(),
- boost::graph_traits<GraphType>::null_vertex());
-
-mitk::TubeGraph::TubeGraph()
-{
-}
-
-mitk::TubeGraph::TubeGraph(const mitk::TubeGraph &graph) : UndirectedGraph<TubeGraphVertex, TubeGraphEdge>(graph)
-{
-}
-
-mitk::TubeGraph::~TubeGraph()
-{
-}
-
-std::vector<mitk::TubeGraph::TubeDescriptorType> mitk::TubeGraph::SearchShortestPath(
- const TubeDescriptorType &, const TubeDescriptorType &)
-{
- std::vector<TubeDescriptorType> shortestPath;
- return shortestPath;
-}
-
-std::vector<mitk::TubeGraph::TubeDescriptorType> mitk::TubeGraph::SearchAllPathBetweenVertices(
- const mitk::TubeGraph::TubeDescriptorType &startTube,
- const mitk::TubeGraph::TubeDescriptorType &endTube /*, std::vector<unsigned long> barrier*/)
-{ // https://lists.boost.org/boost-users/att-9001/maze.cpp
- // https://www.boost.org/doc/libs/1_49_0/libs/graph/example/bfs.cpp
-
- typedef std::map<VertexDescriptorType, EdgeDescriptorType> EdgeMap;
- typedef boost::associative_property_map<EdgeMap> PredecessorMap;
- typedef boost::edge_predecessor_recorder<PredecessorMap, boost::on_tree_edge> PredecessorVisitor;
- typedef boost::dfs_visitor<std::pair<PredecessorVisitor, boost::null_visitor>> DFSVisitor;
-
- EdgeMap edgesMap;
- PredecessorMap predecessorMap(edgesMap);
-
- PredecessorVisitor predecessorVisitor(predecessorMap);
- boost::null_visitor nullVisitor;
- DFSVisitor visitor = boost::make_dfs_visitor(std::make_pair(predecessorVisitor, nullVisitor));
-
- std::map<VertexDescriptorType, boost::default_color_type> vertexColorMap;
- std::map<EdgeDescriptorType, boost::default_color_type> edgeColorMap;
-
- boost::undirected_dfs(
- m_Graph, visitor, make_assoc_property_map(vertexColorMap), make_assoc_property_map(edgeColorMap), startTube.second);
-
- std::vector<TubeDescriptorType> solutionPath;
- solutionPath.push_back(endTube);
- VertexDescriptorType pathEdgeSource = endTube.first;
- VertexDescriptorType pathEdgeTarget;
-
- MITK_INFO << "Source: [" << startTube.first << "," << startTube.second << "] Target: [" << endTube.first << ","
- << endTube.second << "]";
- MITK_INFO << "tube [" << endTube.first << "," << endTube.second << "]";
- do
- {
- if (pathEdgeSource == 10393696)
- break;
- EdgeDescriptorType edge = get(predecessorMap, pathEdgeSource);
- pathEdgeSource = boost::source(edge, m_Graph);
- pathEdgeTarget = boost::target(edge, m_Graph);
- TubeDescriptorType tube(pathEdgeSource, pathEdgeTarget);
- MITK_INFO << "tube [" << tube.first << "," << tube.second << "]";
- solutionPath.push_back(tube);
- } while (pathEdgeSource != startTube.second);
-
- return solutionPath;
-}
-
-std::vector<mitk::TubeGraph::TubeDescriptorType> mitk::TubeGraph::SearchPathToPeriphery(
- const mitk::TubeGraph::TubeDescriptorType &startTube /*, std::vector<unsigned long> barrier*/)
-{
- std::vector<mitk::TubeGraph::TubeDescriptorType> pathToPeriphery;
-
- if (m_RootTube == ErrorId)
- {
- m_RootTube = this->GetThickestTube();
- if (m_Root == m_RootTube.first)
- m_Root = m_RootTube.second;
- else
- m_Root = m_RootTube.first;
- }
-
- // Attention!! No check which one is the right one
- DirectedGraphType directedGraph = this->GetDirectedGraph(m_Root);
-
- // Only the target vertex: it's a directed Graph, and we want only the "after tube" tubes and the clicked ones
- // this->GetOutEdgesOfAVertex(startTube.first, directedGraph, pathToPeriphery);
- pathToPeriphery.push_back(startTube);
- this->GetOutEdgesOfAVertex(startTube.second, directedGraph, pathToPeriphery);
-
- return pathToPeriphery;
-}
-
-void mitk::TubeGraph::GetOutEdgesOfAVertex(mitk::TubeGraph::VertexDescriptorType vertex,
- mitk::TubeGraph::DirectedGraphType &directedGraph,
- std::vector<mitk::TubeGraph::TubeDescriptorType> &pathToPeriphery)
-{
- typedef boost::graph_traits<DirectedGraphType>::out_edge_iterator OutEdgeIteratorType;
- std::pair<OutEdgeIteratorType, OutEdgeIteratorType> outEdges = boost::out_edges(vertex, directedGraph);
- for (; outEdges.first != outEdges.second; ++outEdges.first)
- {
- TubeDescriptorType tube;
- tube.first = boost::source(*outEdges.first, directedGraph);
- tube.second = boost::target(*outEdges.first, directedGraph);
-
- if (std::find(pathToPeriphery.begin(), pathToPeriphery.end(), tube) == pathToPeriphery.end())
- {
- pathToPeriphery.push_back(tube);
- this->GetOutEdgesOfAVertex(tube.second, directedGraph, pathToPeriphery);
- }
- }
-}
-
-mitk::TubeGraph::TubeDescriptorType mitk::TubeGraph::GetThickestTube()
-{
- TubeDescriptorType thickestTube;
- float tubeDiameter = 0.0;
-
- EdgeIteratorType iterator, end;
-
- boost::tie(iterator, end) = boost::edges(m_Graph);
-
- for (; iterator != end; ++iterator)
- {
- TubeGraphEdge edge = this->GetEdge(*iterator);
-
- std::pair<TubeGraphVertex, TubeGraphVertex> soureTargetPair = this->GetVerticesOfAnEdge(*iterator);
-
- float tempDiameter = edge.GetEdgeAverageDiameter(soureTargetPair.first, soureTargetPair.second);
- if (tempDiameter > tubeDiameter)
- {
- tubeDiameter = tempDiameter;
- thickestTube.first = this->GetVertexDescriptor(soureTargetPair.first);
- thickestTube.second = this->GetVertexDescriptor(soureTargetPair.second);
- }
- }
- return thickestTube;
-}
-
-mitk::TubeGraph::DirectedGraphType mitk::TubeGraph::GetDirectedGraph(VertexDescriptorType startVertex)
-{
- DirectedGraphType directedGraph(boost::num_vertices(m_Graph));
- DirectedGraphBfsVisitor vis(this, directedGraph);
- boost::breadth_first_search(m_Graph, startVertex, visitor(vis));
- return directedGraph;
-}
-
-mitk::TubeGraph::Pointer mitk::TubeGraph::CreateSubGraph(std::vector<TubeDescriptorType> subGraphTubes)
-{
- TubeGraph::Pointer subGraph = new TubeGraph();
- // store the descriptor from origin graph to the correspondent new descriptors
- std::map<VertexDescriptorType, VertexDescriptorType> vertexDescriptorOldToNewMap;
-
- // add a new edge and if necessary also the vertices of each tube to the new sub graph
- for (auto it = subGraphTubes.begin(); it != subGraphTubes.end(); it++)
- {
- // search for the source vertex in the subgraph; if it is already added continue, otherwise add it
- if (vertexDescriptorOldToNewMap.find(it->first) == vertexDescriptorOldToNewMap.end())
- {
- // add the vertex to the subgraph
- VertexDescriptorType newVertexDescriptor = subGraph->AddVertex(this->GetVertex(it->first));
- // add the pair of descriptor from the origin graph to the descriptor from the subgraph
- vertexDescriptorOldToNewMap.insert(
- std::pair<VertexDescriptorType, VertexDescriptorType>(it->first, newVertexDescriptor));
- }
- // and now...search for the target vertex...
- if (vertexDescriptorOldToNewMap.find(it->second) == vertexDescriptorOldToNewMap.end())
- {
- VertexDescriptorType newVertexDescriptor = subGraph->AddVertex(this->GetVertex(it->second));
- vertexDescriptorOldToNewMap.insert(
- std::pair<VertexDescriptorType, VertexDescriptorType>(it->second, newVertexDescriptor));
- }
- // Get the EdgeDescriptor from origin graph
- EdgeDescriptorType edgeDescriptor = this->GetEdgeDescriptorByVerices(it->first, it->second);
-
- TubeGraphEdge oldEdge = this->GetEdge(edgeDescriptor);
-
- // AddEdge needs the source vertex, the target vertex and the edge data
- // source Vertex: get the subgraph VertexDescriptor by the origin descriptor (tubeDescriptor->first)from the
- // assigning map
- // target Vertex: get the subgraph VertexDescriptor by the origin descriptor (tubeDescriptor->second)from the
- // assigning map
- // edge data: copy the TubeGraphEdge object using the origin edge desciptor and the origin graph
- VertexDescriptorType sourceVertex = vertexDescriptorOldToNewMap[it->first];
- VertexDescriptorType targetVertex = vertexDescriptorOldToNewMap[it->second];
- subGraph->AddEdge(sourceVertex, targetVertex, this->GetEdge(edgeDescriptor));
- }
- subGraph->CopyInformation(this);
-
- mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New();
- geometry->Initialize();
- subGraph->SetGeometry(geometry);
-
- this->Modified();
-
- return subGraph;
-}
-
-void mitk::TubeGraph::RemoveSubGraph(std::vector<TubeDescriptorType> deletedTubes)
-{
- for (auto it = deletedTubes.begin(); it != deletedTubes.end(); it++)
- {
- VertexDescriptorType source = it->first;
- VertexDescriptorType target = it->second;
-
- EdgeDescriptorType edge = this->GetEdgeDescriptorByVerices(source, target);
- this->RemoveEdge(edge);
-
- if (this->GetAllEdgesOfAVertex(source).size() == 0)
- {
- this->RemoveVertex(source);
- }
- if (this->GetAllEdgesOfAVertex(target).size() == 0)
- {
- this->RemoveVertex(target);
- }
- }
- this->Modified();
-}
-
-void mitk::TubeGraph::SetRootTube(const TubeDescriptorType &root)
-{
- if (root != TubeGraph::ErrorId)
- {
- m_RootTube = root;
- if (m_Root == root.first)
- m_Root = root.second;
- else
- m_Root = root.first;
- this->Modified();
- }
-}
-
-void mitk::TubeGraph::SetRoot(const VertexDescriptorType &root)
-{
- if (root != TubeGraph::ErrorId.first)
- {
- m_Root = root;
- }
-}
-
-mitk::TubeGraph::TubeDescriptorType mitk::TubeGraph::GetRootTube()
-{
- return m_RootTube;
-}
-
-mitk::TubeGraph::VertexDescriptorType mitk::TubeGraph::GetRootVertex()
-{
- return m_Root;
-}
-
-mitk::TubeGraph &mitk::TubeGraph::operator=(const mitk::TubeGraph &rhs)
-{
- UndirectedGraph<TubeGraphVertex, TubeGraphEdge>::operator=(rhs);
- return *this;
-}
diff --git a/Modules/TubeGraph/src/DataStructure/mitkTubeGraphEdge.cpp b/Modules/TubeGraph/src/DataStructure/mitkTubeGraphEdge.cpp
deleted file mode 100644
index 2fc109f26e..0000000000
--- a/Modules/TubeGraph/src/DataStructure/mitkTubeGraphEdge.cpp
+++ /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.
-
-============================================================================*/
-
-#include "mitkTubeGraphEdge.h"
-
-mitk::TubeGraphEdge::TubeGraphEdge() : m_ElementVector(0)
-{
-}
-
-mitk::TubeGraphEdge::~TubeGraphEdge()
-{
- /*while(!m_ElementVector.empty())
- {
- delete m_ElementVector.back();
- m_ElementVector.pop_back();
- }*/
- m_ElementVector.clear();
-}
-
-std::vector<mitk::TubeElement *> mitk::TubeGraphEdge::GetElementVector()
-{
- return m_ElementVector;
-}
-
-void mitk::TubeGraphEdge::SetElementVector(std::vector<mitk::TubeElement *> elementVector)
-{
- m_ElementVector = elementVector;
-}
-
-unsigned int mitk::TubeGraphEdge::GetNumberOfElements() const
-{
- return m_ElementVector.size();
-}
-
-void mitk::TubeGraphEdge::AddTubeElement(mitk::TubeElement *element)
-{
- m_ElementVector.push_back(element);
-}
-
-void mitk::TubeGraphEdge::AddTubeElementAt(unsigned int position, TubeElement *element)
-{
- m_ElementVector.insert(m_ElementVector.begin() + position, element);
-}
-
-mitk::TubeElement *mitk::TubeGraphEdge::GetTubeElement(unsigned int position)
-{
- if (position >= GetNumberOfElements())
- throw std::runtime_error("Exception thrown in TubeGraphEdge::getTubeElement(uint): getTubeElement(uint)");
- else
- return m_ElementVector[position];
-}
-
-float mitk::TubeGraphEdge::GetEdgeLength(mitk::TubeGraphVertex &source, mitk::TubeGraphVertex &target)
-{
- float length = 0.0f;
- mitk::Point3D pos1, pos2;
- std::vector<float> diff;
- diff.resize(3);
- unsigned int numberOfElements = this->GetNumberOfElements();
-
- // if there are no elements return 0
- if (numberOfElements == 0)
- {
- // If the edge has no elements, then take the difference between the vertices directly
- pos1 = (source.GetTubeElement())->GetCoordinates();
- pos2 = (target.GetTubeElement())->GetCoordinates();
-
- diff[0] = pos1[0] - pos2[0];
- diff[1] = pos1[1] - pos2[1];
- diff[2] = pos1[2] - pos2[2];
-
- float sum = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];
- length = length + std::sqrt(sum);
- }
- else
- {
- // difference between source and first element of the edge
- pos1 = (source.GetTubeElement())->GetCoordinates();
- pos2 = (this->GetTubeElement(0))->GetCoordinates();
-
- diff[0] = pos1[0] - pos2[0];
- diff[1] = pos1[1] - pos2[1];
- diff[2] = pos1[2] - pos2[2];
-
- float sum = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];
- length = length + std::sqrt(sum);
-
- // Differences within the edge
- for (unsigned int i = 0; i < numberOfElements - 1; ++i)
- {
- pos1 = (this->GetTubeElement(i))->GetCoordinates();
- pos2 = (this->GetTubeElement(i + 1))->GetCoordinates();
-
- diff[0] = pos1[0] - pos2[0];
- diff[1] = pos1[1] - pos2[1];
- diff[2] = pos1[2] - pos2[2];
-
- sum = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];
- length = length + std::sqrt(sum);
- }
-
- // difference between last element and target of the edge
- pos1 = (this->GetTubeElement(numberOfElements - 1))->GetCoordinates();
- pos2 = (target.GetTubeElement())->GetCoordinates();
-
- diff[0] = pos1[0] - pos2[0];
- diff[1] = pos1[1] - pos2[1];
- diff[2] = pos1[2] - pos2[2];
-
- sum = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2];
- length = length + std::sqrt(sum);
- }
-
- return length;
-}
-
-float mitk::TubeGraphEdge::GetEdgeAverageDiameter(mitk::TubeGraphVertex &source, mitk::TubeGraphVertex &target)
-{
- float diameterSum = 0.0;
- unsigned int numberOfElements = this->GetNumberOfElements();
-
- // add source diameter
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(source.GetTubeElement()))
- diameterSum += (dynamic_cast<const mitk::CircularProfileTubeElement *>(source.GetTubeElement()))->GetDiameter();
- ;
-
- // add all edge element diameter
- for (unsigned int i = 0; i < numberOfElements; i++)
- {
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(this->GetTubeElement(i)))
- diameterSum += (dynamic_cast<const mitk::CircularProfileTubeElement *>(this->GetTubeElement(i)))->GetDiameter();
- }
-
- // add target diameter
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(target.GetTubeElement()))
- diameterSum += (dynamic_cast<const mitk::CircularProfileTubeElement *>(target.GetTubeElement()))->GetDiameter();
-
- return diameterSum / (numberOfElements + 2);
-}
-
-bool mitk::TubeGraphEdge::operator==(const mitk::TubeGraphEdge &right) const
-{
- return (m_ElementVector == right.m_ElementVector);
-}
diff --git a/Modules/TubeGraph/src/DataStructure/mitkTubeGraphVertex.cpp b/Modules/TubeGraph/src/DataStructure/mitkTubeGraphVertex.cpp
deleted file mode 100644
index 4a3c0aa348..0000000000
--- a/Modules/TubeGraph/src/DataStructure/mitkTubeGraphVertex.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 "mitkTubeGraphVertex.h"
-
-mitk::TubeGraphVertex::TubeGraphVertex() : m_element(nullptr)
-{
-}
-
-mitk::TubeGraphVertex::TubeGraphVertex(mitk::TubeElement *element)
-{
- m_element = element;
-}
-
-mitk::TubeGraphVertex::~TubeGraphVertex()
-{
-}
-
-void mitk::TubeGraphVertex::SetTubeElement(mitk::TubeElement *element)
-{
- m_element = element;
-}
-
-const mitk::TubeElement *mitk::TubeGraphVertex::GetTubeElement() const
-{
- return m_element;
-}
-
-bool mitk::TubeGraphVertex::operator==(const mitk::TubeGraphVertex &right) const
-{
- return (m_element == right.m_element);
-}
diff --git a/Modules/TubeGraph/src/IO/mitkTubeGraphDefinitions.cpp b/Modules/TubeGraph/src/IO/mitkTubeGraphDefinitions.cpp
deleted file mode 100644
index 648a5bddba..0000000000
--- a/Modules/TubeGraph/src/IO/mitkTubeGraphDefinitions.cpp
+++ /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.
-
-============================================================================*/
-
-#include "mitkTubeGraphDefinitions.h"
-
-//============== XML const chars ===================
-
-//==== Header information ====
-const std::string mitk::TubeGraphDefinitions::XML_TUBEGRAPH_FILE = "tube_graph_file";
-const std::string mitk::TubeGraphDefinitions::XML_FILE_VERSION = "file_version";
-const std::string mitk::TubeGraphDefinitions::VERSION_STRING = "0.1";
-const std::string mitk::TubeGraphDefinitions::ASCII_FILE = "ascii_file";
-const std::string mitk::TubeGraphDefinitions::FILE_NAME = "file_name";
-
-//==== Geometry details ====
-const std::string mitk::TubeGraphDefinitions::XML_GEOMETRY = "geometry";
-
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_XX = "xx";
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_XY = "xy";
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_XZ = "xz";
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_YX = "yx";
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_YY = "yy";
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_YZ = "yz";
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_ZX = "zx";
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_ZY = "zy";
-const std::string mitk::TubeGraphDefinitions::XML_MATRIX_ZZ = "zz";
-
-const std::string mitk::TubeGraphDefinitions::XML_ORIGIN_X = "origin_x";
-const std::string mitk::TubeGraphDefinitions::XML_ORIGIN_Y = "origin_y";
-const std::string mitk::TubeGraphDefinitions::XML_ORIGIN_Z = "origin_z";
-
-const std::string mitk::TubeGraphDefinitions::XML_SPACING_X = "spacing_x";
-const std::string mitk::TubeGraphDefinitions::XML_SPACING_Y = "spacing_y";
-const std::string mitk::TubeGraphDefinitions::XML_SPACING_Z = "spacing_z";
-
-//==== TubeGraph structures ====
-const std::string mitk::TubeGraphDefinitions::XML_VERTICES = "vertices";
-const std::string mitk::TubeGraphDefinitions::XML_EDGES = "edges";
-const std::string mitk::TubeGraphDefinitions::XML_LABELGROUPS = "labelgroups";
-const std::string mitk::TubeGraphDefinitions::XML_ATTRIBUTIONS = "attributions";
-const std::string mitk::TubeGraphDefinitions::XML_ANNOTATIONS = "annotations";
-const std::string mitk::TubeGraphDefinitions::XML_VERTEX = "vertex";
-const std::string mitk::TubeGraphDefinitions::XML_EDGE = "edge";
-const std::string mitk::TubeGraphDefinitions::XML_ELEMENT = "element";
-const std::string mitk::TubeGraphDefinitions::XML_LABELGROUP = "labelgroup";
-const std::string mitk::TubeGraphDefinitions::XML_LABEL = "label";
-const std::string mitk::TubeGraphDefinitions::XML_ATTRIBUTION = "attribut";
-const std::string mitk::TubeGraphDefinitions::XML_ANNOTATION = "annotation";
-
-//==== vertex properties ====
-const std::string mitk::TubeGraphDefinitions::XML_VERTEX_ID = "vertex_id";
-
-//==== edge properties ====
-const std::string mitk::TubeGraphDefinitions::XML_EDGE_ID = "edge_id";
-const std::string mitk::TubeGraphDefinitions::XML_EDGE_SOURCE_ID = "edge_source_id";
-const std::string mitk::TubeGraphDefinitions::XML_EDGE_TARGET_ID = "edge_target_id";
-
-//==== element properties ====
-const std::string mitk::TubeGraphDefinitions::XML_ELEMENT_X = "element_x";
-const std::string mitk::TubeGraphDefinitions::XML_ELEMENT_Y = "element_y";
-const std::string mitk::TubeGraphDefinitions::XML_ELEMENT_Z = "element_z";
-const std::string mitk::TubeGraphDefinitions::XML_ELEMENT_DIAMETER = "element_diameter";
-
-//==== label group properties ====
-const std::string mitk::TubeGraphDefinitions::XML_LABELGROUP_NAME = "labelgroup_name";
-
-//==== label properties ====
-const std::string mitk::TubeGraphDefinitions::XML_LABEL_NAME = "label_name";
-const std::string mitk::TubeGraphDefinitions::XML_LABEL_VISIBILITY = "label_visible";
-const std::string mitk::TubeGraphDefinitions::XML_LABEL_COLOR_R = "label_color_r";
-const std::string mitk::TubeGraphDefinitions::XML_LABEL_COLOR_G = "label_color_g";
-const std::string mitk::TubeGraphDefinitions::XML_LABEL_COLOR_B = "label_color_b";
-
-//==== tube properties ====
-const std::string mitk::TubeGraphDefinitions::XML_TUBE_ID_1 = "tube_id_1";
-const std::string mitk::TubeGraphDefinitions::XML_TUBE_ID_2 = "tube_id_2";
-
-//==== annotation properties ====
-const std::string mitk::TubeGraphDefinitions::XML_ANNOTATION_NAME = "annotation_name";
-const std::string mitk::TubeGraphDefinitions::XML_ANNOTATION_DESCRIPTION = "annotation_description";
diff --git a/Modules/TubeGraph/src/IO/mitkTubeGraphIO.cpp b/Modules/TubeGraph/src/IO/mitkTubeGraphIO.cpp
deleted file mode 100644
index 9edfb8e2d9..0000000000
--- a/Modules/TubeGraph/src/IO/mitkTubeGraphIO.cpp
+++ /dev/null
@@ -1,580 +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 "mitkTubeGraphIO.h"
-
-#include "mitkCircularProfileTubeElement.h"
-#include "mitkTubeGraphDefinitions.h"
-#include "mitkTubeGraphProperty.h"
-
-#include <mitkIOMimeTypes.h>
-
-#include <tinyxml2.h>
-
-#include <vtkMatrix4x4.h>
-
-#include <itksys/SystemTools.hxx>
-
-namespace mitk
-{
- TubeGraphIO::TubeGraphIO(const TubeGraphIO &other) : AbstractFileIO(other) {}
- TubeGraphIO::TubeGraphIO()
- : AbstractFileIO(
- mitk::TubeGraph::GetStaticNameOfClass(), mitk::TubeGraphIO::TUBEGRAPH_MIMETYPE(), "Tube Graph Structure File")
- {
- this->RegisterService();
- }
-
- std::vector<BaseData::Pointer> TubeGraphIO::DoRead()
- {
- std::locale::global(std::locale("C"));
-
- std::vector<itk::SmartPointer<mitk::BaseData>> result;
-
- InputStream stream(this);
- std::string string(std::istreambuf_iterator<char>(stream), {});
- tinyxml2::XMLDocument doc;
-
- if (tinyxml2::XML_SUCCESS == doc.Parse(string.c_str()))
- {
- TubeGraph::Pointer newTubeGraph = TubeGraph::New();
-
- tinyxml2::XMLHandle hDoc(&doc);
- tinyxml2::XMLHandle hRoot = hDoc.FirstChildElement();
- tinyxml2::XMLElement *pElem = hRoot.FirstChildElement(mitk::TubeGraphDefinitions::XML_GEOMETRY.c_str()).ToElement();
-
- // read geometry
- mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New();
- geometry->Initialize();
-
- // read origin
- mitk::Point3D origin;
- double temp = 0;
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_ORIGIN_X.c_str(), &temp);
- origin[0] = temp;
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_ORIGIN_Y.c_str(), &temp);
- origin[1] = temp;
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_ORIGIN_Z.c_str(), &temp);
- origin[2] = temp;
- geometry->SetOrigin(origin);
-
- // read spacing
- Vector3D spacing;
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_SPACING_X.c_str(), &temp);
- spacing.SetElement(0, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_SPACING_Y.c_str(), &temp);
- spacing.SetElement(1, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_SPACING_Z.c_str(), &temp);
- spacing.SetElement(2, temp);
- geometry->SetSpacing(spacing);
-
- // read transform
- vtkMatrix4x4 *m = vtkMatrix4x4::New();
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_XX.c_str(), &temp);
- m->SetElement(0, 0, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_XY.c_str(), &temp);
- m->SetElement(1, 0, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_XZ.c_str(), &temp);
- m->SetElement(2, 0, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_YX.c_str(), &temp);
- m->SetElement(0, 1, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_YY.c_str(), &temp);
- m->SetElement(1, 1, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_YZ.c_str(), &temp);
- m->SetElement(2, 1, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_ZX.c_str(), &temp);
- m->SetElement(0, 2, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_ZY.c_str(), &temp);
- m->SetElement(1, 2, temp);
- pElem->QueryAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_ZZ.c_str(), &temp);
- m->SetElement(2, 2, temp);
-
- m->SetElement(0, 3, origin[0]);
- m->SetElement(1, 3, origin[1]);
- m->SetElement(2, 3, origin[2]);
- m->SetElement(3, 3, 1);
- geometry->SetIndexToWorldTransformByVtkMatrix(m);
-
- geometry->SetImageGeometry(false);
-
- // read tube graph
-
- // read vertices
- pElem = hRoot.FirstChildElement(mitk::TubeGraphDefinitions::XML_VERTICES.c_str()).ToElement();
- if (pElem != nullptr)
- {
- // walk through the vertices
- for (auto *vertexElement = pElem->FirstChildElement(); vertexElement != nullptr; vertexElement = vertexElement->NextSiblingElement())
- {
- int vertexID(0);
- mitk::Point3D coordinate;
- coordinate.Fill(0.0);
- double diameter(0);
-
- vertexElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_VERTEX_ID.c_str(), &vertexID);
-
- auto *tubeElement = vertexElement->FirstChildElement();
-
- tubeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_X.c_str(), &temp);
- coordinate[0] = temp;
- tubeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_Y.c_str(), &temp);
- coordinate[1] = temp;
- tubeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_Z.c_str(), &temp);
- coordinate[2] = temp;
- tubeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_DIAMETER.c_str(), &diameter);
-
- mitk::TubeGraphVertex vertexData;
- auto *newElement = new mitk::CircularProfileTubeElement(coordinate, diameter);
- vertexData.SetTubeElement(newElement);
-
- mitk::TubeGraph::VertexDescriptorType newVertex = newTubeGraph->AddVertex(vertexData);
- if (static_cast<int>(newVertex) != vertexID)
- {
- MITK_ERROR << "Aborting tube graph creation, different vertex ids.";
- return result;
- ;
- }
- }
- }
-
- // read edges
- pElem = hRoot.FirstChildElement(mitk::TubeGraphDefinitions::XML_EDGES.c_str()).ToElement();
- if (pElem != nullptr)
- {
- // walk through the edges
- auto edgeElement = pElem->FirstChildElement();
- for ( ; edgeElement != nullptr; edgeElement = edgeElement->NextSiblingElement())
- {
- int edgeID(0), edgeSourceID(0), edgeTargetID(0);
- mitk::Point3D coordinate;
- double diameter(0);
-
- edgeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_EDGE_ID.c_str(), &edgeID);
- edgeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_EDGE_SOURCE_ID.c_str(), &edgeSourceID);
- edgeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_EDGE_TARGET_ID.c_str(), &edgeTargetID);
-
- mitk::TubeGraphEdge edgeData;
-
- for (auto *tubeElement = edgeElement->FirstChildElement(mitk::TubeGraphDefinitions::XML_ELEMENT.c_str()); tubeElement != nullptr; tubeElement = tubeElement->NextSiblingElement())
- {
- tubeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_X.c_str(), &temp);
- coordinate[0] = temp;
- tubeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_Y.c_str(), &temp);
- coordinate[1] = temp;
- tubeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_Z.c_str(), &temp);
- coordinate[2] = temp;
- tubeElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_DIAMETER.c_str(), &diameter);
-
- auto *newElement = new mitk::CircularProfileTubeElement(coordinate, diameter);
-
- edgeData.AddTubeElement(newElement);
- }
- try
- {
- newTubeGraph->AddEdge(edgeSourceID, edgeTargetID, edgeData);
- }
- catch (const std::runtime_error &error)
- {
- MITK_ERROR << error.what();
- return result;
- }
- }
- }
-
- // Compute bounding box
- BoundingBox::Pointer bb = this->ComputeBoundingBox(newTubeGraph);
- geometry->SetBounds(bb->GetBounds());
-
- MITK_INFO << "Tube Graph read";
- MITK_INFO << "Edge numb:" << newTubeGraph->GetNumberOfEdges()
- << " Vertices: " << newTubeGraph->GetNumberOfVertices();
-
- MITK_INFO << "Reading tube graph property";
- mitk::TubeGraphProperty::Pointer newProperty = mitk::TubeGraphProperty::New();
-
- // read label groups
- pElem = hRoot.FirstChildElement(mitk::TubeGraphDefinitions::XML_LABELGROUPS.c_str()).ToElement();
- if (pElem != nullptr)
- {
- // walk through the label groups
- for (auto *labelGroupElement = pElem->FirstChildElement(); labelGroupElement != nullptr; labelGroupElement = labelGroupElement->NextSiblingElement())
- {
- auto *newLabelGroup = new mitk::TubeGraphProperty::LabelGroup();
- const char *labelGroupName;
-
- labelGroupName =
- labelGroupElement->Attribute((char *)mitk::TubeGraphDefinitions::XML_LABELGROUP_NAME.c_str());
- if (labelGroupName)
- newLabelGroup->labelGroupName = labelGroupName;
-
- for (auto *labelElement = labelGroupElement->FirstChildElement(mitk::TubeGraphDefinitions::XML_LABEL.c_str()); labelElement != nullptr; labelElement = labelElement->NextSiblingElement())
- {
- auto *newLabel = new mitk::TubeGraphProperty::LabelGroup::Label();
- const char *labelName;
- bool isVisible = true;
- Color color;
-
- labelName = labelElement->Attribute((char *)mitk::TubeGraphDefinitions::XML_LABEL_NAME.c_str());
- if (labelName)
- newLabel->labelName = labelName;
-
- labelElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_LABEL_VISIBILITY.c_str(), &temp);
- if (temp == 0)
- isVisible = false;
- else
- isVisible = true;
- labelElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_LABEL_COLOR_R.c_str(), &temp);
- color[0] = temp;
- labelElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_LABEL_COLOR_G.c_str(), &temp);
- color[1] = temp;
- labelElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_LABEL_COLOR_B.c_str(), &temp);
- color[2] = temp;
-
- newLabel->isVisible = isVisible;
- newLabel->labelColor = color;
- newLabelGroup->labels.push_back(newLabel);
- }
- newProperty->AddLabelGroup(newLabelGroup, newProperty->GetLabelGroups().size());
- }
- }
- // read attributations
- pElem = hRoot.FirstChildElement(mitk::TubeGraphDefinitions::XML_ATTRIBUTIONS.c_str()).ToElement();
- if (pElem != nullptr)
- {
- std::map<TubeGraphProperty::TubeToLabelGroupType, std::string> tubeToLabelsMap;
- for (auto *tubeToLabelElement = pElem->FirstChildElement(); tubeToLabelElement != nullptr; tubeToLabelElement = tubeToLabelElement->NextSiblingElement())
- {
- TubeGraph::TubeDescriptorType tube;
- auto *labelGroup = new mitk::TubeGraphProperty::LabelGroup();
- auto *label = new mitk::TubeGraphProperty::LabelGroup::Label();
-
- tubeToLabelElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_TUBE_ID_1.c_str(), &temp);
- tube.first = temp;
- tubeToLabelElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_TUBE_ID_2.c_str(), &temp);
- tube.second = temp;
- const char *labelGroupName =
- tubeToLabelElement->Attribute(mitk::TubeGraphDefinitions::XML_LABELGROUP_NAME.c_str());
- if (labelGroupName)
- labelGroup = newProperty->GetLabelGroupByName(labelGroupName);
-
- const char *labelName =
- tubeToLabelElement->Attribute(mitk::TubeGraphDefinitions::XML_LABEL_NAME.c_str());
- if (labelName)
- label = newProperty->GetLabelByName(labelGroup, labelName);
-
- if (tube != TubeGraph::ErrorId && labelGroup != nullptr && label != nullptr)
- {
- TubeGraphProperty::TubeToLabelGroupType tubeToLabelGroup(tube, labelGroupName);
- tubeToLabelsMap.insert(
- std::pair<TubeGraphProperty::TubeToLabelGroupType, std::string>(tubeToLabelGroup, labelName));
- }
- }
- if (tubeToLabelsMap.size() > 0)
- newProperty->SetTubesToLabels(tubeToLabelsMap);
- }
- // read annotations
- pElem = hRoot.FirstChildElement(mitk::TubeGraphDefinitions::XML_ANNOTATIONS.c_str()).ToElement();
- if (pElem != nullptr)
- {
- for (auto *annotationElement = pElem->FirstChildElement(); annotationElement != nullptr; annotationElement = annotationElement->NextSiblingElement())
- {
- auto *annotation = new mitk::TubeGraphProperty::Annotation();
- TubeGraph::TubeDescriptorType tube;
-
- const char *annotationName =
- annotationElement->Attribute(mitk::TubeGraphDefinitions::XML_ANNOTATION_NAME.c_str());
- annotation->name = nullptr != annotationName ? annotationName : "";
-
- const char *annotationDescription =
- annotationElement->Attribute(mitk::TubeGraphDefinitions::XML_ANNOTATION_DESCRIPTION.c_str());
- annotation->description = nullptr != annotationDescription ? annotationDescription : "";
-
- annotationElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_TUBE_ID_1.c_str(), &temp);
- tube.first = temp;
- annotationElement->QueryAttribute(mitk::TubeGraphDefinitions::XML_TUBE_ID_2.c_str(), &temp);
- tube.second = temp;
-
- if (tube != TubeGraph::ErrorId)
- {
- annotation->tube = tube;
- newProperty->AddAnnotation(annotation);
- }
- }
- }
-
- MITK_INFO << "Tube Graph Property read";
-
- newTubeGraph->SetGeometry(geometry);
- newTubeGraph->SetProperty("Tube Graph.Visualization Information", newProperty);
- result.push_back(newTubeGraph.GetPointer());
- }
- else
- {
- mitkThrow() << "Parsing error at line " << doc.ErrorLineNum() << ": " << doc.ErrorStr();
- }
- return result;
- }
-
- AbstractFileIO::ConfidenceLevel TubeGraphIO::GetReaderConfidenceLevel() const
- {
- if (AbstractFileIO::GetReaderConfidenceLevel() == Unsupported)
- return Unsupported;
- return Supported;
- }
-
- void TubeGraphIO::Write()
- {
- OutputStream out(this);
-
- if (!out.good())
- {
- mitkThrow() << "Stream not good.";
- }
-
- std::locale previousLocale(out.getloc());
- std::locale I("C");
- out.imbue(I);
-
- const auto *tubeGraph = dynamic_cast<const mitk::TubeGraph *>(this->GetInput());
- // Get geometry of the tube graph
- mitk::Geometry3D::Pointer geometry = dynamic_cast<mitk::Geometry3D *>(tubeGraph->GetGeometry());
- // Get property of the tube graph
- mitk::TubeGraphProperty::Pointer tubeGraphProperty = dynamic_cast<mitk::TubeGraphProperty *>(
- tubeGraph->GetProperty("Tube Graph.Visualization Information").GetPointer());
- // Create XML document
- tinyxml2::XMLDocument documentXML;
- { // Begin document
- documentXML.InsertEndChild(documentXML.NewDeclaration());
-
- auto *mainXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_TUBEGRAPH_FILE.c_str());
- mainXML->SetAttribute(mitk::TubeGraphDefinitions::XML_FILE_VERSION.c_str(), mitk::TubeGraphDefinitions::VERSION_STRING.c_str());
- documentXML.InsertEndChild(mainXML);
-
- auto *geometryXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_GEOMETRY.c_str());
- { // begin geometry
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_XX.c_str(), geometry->GetMatrixColumn(0)[0]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_XY.c_str(), geometry->GetMatrixColumn(0)[1]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_XZ.c_str(), geometry->GetMatrixColumn(0)[2]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_YX.c_str(), geometry->GetMatrixColumn(1)[0]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_YY.c_str(), geometry->GetMatrixColumn(1)[1]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_YZ.c_str(), geometry->GetMatrixColumn(1)[2]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_ZX.c_str(), geometry->GetMatrixColumn(2)[0]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_ZY.c_str(), geometry->GetMatrixColumn(2)[1]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_MATRIX_ZZ.c_str(), geometry->GetMatrixColumn(2)[2]);
-
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ORIGIN_X.c_str(), geometry->GetOrigin()[0]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ORIGIN_Y.c_str(), geometry->GetOrigin()[1]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ORIGIN_Z.c_str(), geometry->GetOrigin()[2]);
-
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_SPACING_X.c_str(), geometry->GetSpacing()[0]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_SPACING_Y.c_str(), geometry->GetSpacing()[1]);
- geometryXML->SetAttribute(mitk::TubeGraphDefinitions::XML_SPACING_Z.c_str(), geometry->GetSpacing()[2]);
-
- } // end geometry
- mainXML->InsertEndChild(geometryXML);
-
- auto *verticesXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_VERTICES.c_str());
- { // begin vertices section
- std::vector<mitk::TubeGraphVertex> vertexVector = tubeGraph->GetVectorOfAllVertices();
- for (unsigned int index = 0; index < vertexVector.size(); index++)
- {
- auto *vertexXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_VERTEX.c_str());
- vertexXML->SetAttribute(mitk::TubeGraphDefinitions::XML_VERTEX_ID.c_str(),
- static_cast<int>(tubeGraph->GetVertexDescriptor(vertexVector[index])));
- // element of each vertex
- const mitk::TubeElement *element = vertexVector[index].GetTubeElement();
- auto *elementXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_ELEMENT.c_str());
- elementXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_X.c_str(),
- element->GetCoordinates().GetElement(0));
- elementXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_Y.c_str(),
- element->GetCoordinates().GetElement(1));
- elementXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_Z.c_str(),
- element->GetCoordinates().GetElement(2));
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(element))
- elementXML->SetAttribute(
- mitk::TubeGraphDefinitions::XML_ELEMENT_DIAMETER.c_str(),
- (dynamic_cast<const mitk::CircularProfileTubeElement *>(element))->GetDiameter());
- else
- elementXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_DIAMETER.c_str(), 2);
-
- vertexXML->InsertEndChild(elementXML);
-
- verticesXML->InsertEndChild(vertexXML);
- }
- } // end vertices section
- mainXML->InsertEndChild(verticesXML);
-
- auto *edgesXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_EDGES.c_str());
- { // begin edges section
- std::vector<mitk::TubeGraphEdge> edgeVector = tubeGraph->GetVectorOfAllEdges();
- for (unsigned int index = 0; index < edgeVector.size(); index++)
- {
- auto *edgeXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_EDGE.c_str());
- edgeXML->SetAttribute(mitk::TubeGraphDefinitions::XML_EDGE_ID.c_str(), index);
- std::pair<mitk::TubeGraphVertex, mitk::TubeGraphVertex> soureTargetPair =
- tubeGraph->GetVerticesOfAnEdge(tubeGraph->GetEdgeDescriptor(edgeVector[index]));
- edgeXML->SetAttribute(mitk::TubeGraphDefinitions::XML_EDGE_SOURCE_ID.c_str(),
- static_cast<int>(tubeGraph->GetVertexDescriptor(soureTargetPair.first)));
- edgeXML->SetAttribute(mitk::TubeGraphDefinitions::XML_EDGE_TARGET_ID.c_str(),
- static_cast<int>(tubeGraph->GetVertexDescriptor(soureTargetPair.second)));
-
- // begin elements of the edge
- std::vector<mitk::TubeElement *> elementVector = edgeVector[index].GetElementVector();
- for (unsigned int elementIndex = 0; elementIndex < elementVector.size(); elementIndex++)
- {
- auto *elementXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_ELEMENT.c_str());
- elementXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_X.c_str(),
- elementVector[elementIndex]->GetCoordinates().GetElement(0));
- elementXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_Y.c_str(),
- elementVector[elementIndex]->GetCoordinates().GetElement(1));
- elementXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_Z.c_str(),
- elementVector[elementIndex]->GetCoordinates().GetElement(2));
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(elementVector[elementIndex]))
- elementXML->SetAttribute(
- mitk::TubeGraphDefinitions::XML_ELEMENT_DIAMETER.c_str(),
- (dynamic_cast<const mitk::CircularProfileTubeElement *>(elementVector[elementIndex]))->GetDiameter());
- else
- elementXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ELEMENT_DIAMETER.c_str(), 2);
- edgeXML->InsertEndChild(elementXML);
- // elementsXML->InsertEndChild(elementXML);
- }
- edgesXML->InsertEndChild(edgeXML);
- }
- } // end edges section
- mainXML->InsertEndChild(edgesXML);
-
- auto *labelGroupsXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_LABELGROUPS.c_str());
- { // begin label group section
- std::vector<TubeGraphProperty::LabelGroup *> labelGroupVector = tubeGraphProperty->GetLabelGroups();
- for (unsigned int index = 0; index < labelGroupVector.size(); index++)
- {
- auto *labelGroupXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_LABELGROUP.c_str());
- labelGroupXML->SetAttribute(mitk::TubeGraphDefinitions::XML_LABELGROUP_NAME.c_str(),
- labelGroupVector[index]->labelGroupName.c_str());
- // begin labels of the label group
- std::vector<TubeGraphProperty::LabelGroup::Label *> labelVector = labelGroupVector[index]->labels;
- for (unsigned int labelIndex = 0; labelIndex < labelVector.size(); labelIndex++)
- {
- auto *labelXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_LABEL.c_str());
- labelXML->SetAttribute(mitk::TubeGraphDefinitions::XML_LABEL_NAME.c_str(), labelVector[labelIndex]->labelName.c_str());
- labelXML->SetAttribute(mitk::TubeGraphDefinitions::XML_LABEL_VISIBILITY.c_str(),
- labelVector[labelIndex]->isVisible ? 1 : 0);
- labelXML->SetAttribute(mitk::TubeGraphDefinitions::XML_LABEL_COLOR_R.c_str(),
- labelVector[labelIndex]->labelColor[0]);
- labelXML->SetAttribute(mitk::TubeGraphDefinitions::XML_LABEL_COLOR_G.c_str(),
- labelVector[labelIndex]->labelColor[1]);
- labelXML->SetAttribute(mitk::TubeGraphDefinitions::XML_LABEL_COLOR_B.c_str(),
- labelVector[labelIndex]->labelColor[2]);
- labelGroupXML->InsertEndChild(labelXML);
- }
- labelGroupsXML->InsertEndChild(labelGroupXML);
- }
- } // end labe group section
- mainXML->InsertEndChild(labelGroupsXML);
-
- auto *attributionsXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_ATTRIBUTIONS.c_str());
- { // begin attributions section
- std::map<mitk::TubeGraphProperty::TubeToLabelGroupType, std::string> tubeToLabelGroup =
- tubeGraphProperty->GetTubesToLabels();
- for (auto it =
- tubeToLabelGroup.begin();
- it != tubeToLabelGroup.end();
- it++)
- {
- auto *attributXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_ATTRIBUTION.c_str());
- attributXML->SetAttribute(mitk::TubeGraphDefinitions::XML_TUBE_ID_1.c_str(), static_cast<int>(it->first.first.first));
- attributXML->SetAttribute(mitk::TubeGraphDefinitions::XML_TUBE_ID_2.c_str(), static_cast<int>(it->first.first.second));
- attributXML->SetAttribute(mitk::TubeGraphDefinitions::XML_LABELGROUP_NAME.c_str(), it->first.second.c_str());
- attributXML->SetAttribute(mitk::TubeGraphDefinitions::XML_LABEL_NAME.c_str(), it->second.c_str());
- attributionsXML->InsertEndChild(attributXML);
- }
-
- } // end attributions section
- mainXML->InsertEndChild(attributionsXML);
-
- auto *annotationsXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_ANNOTATIONS.c_str());
- { // begin annotations section
- std::vector<mitk::TubeGraphProperty::Annotation *> annotations = tubeGraphProperty->GetAnnotations();
- for (unsigned int index = 0; index < annotations.size(); index++)
- {
- auto *annotationXML = documentXML.NewElement(mitk::TubeGraphDefinitions::XML_ANNOTATION.c_str());
- annotationXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ANNOTATION_NAME.c_str(), annotations[index]->name.c_str());
- annotationXML->SetAttribute(mitk::TubeGraphDefinitions::XML_ANNOTATION_DESCRIPTION.c_str(), annotations[index]->description.c_str());
- annotationXML->SetAttribute(mitk::TubeGraphDefinitions::XML_TUBE_ID_1.c_str(), static_cast<int>(annotations[index]->tube.first));
- annotationXML->SetAttribute(mitk::TubeGraphDefinitions::XML_TUBE_ID_2.c_str(), static_cast<int>(annotations[index]->tube.second));
-
- annotationsXML->InsertEndChild(annotationXML);
- }
- } // end annotations section
- mainXML->InsertEndChild(annotationsXML);
- } // end document
-
- tinyxml2::XMLPrinter printer;
- documentXML.Print(&printer);
-
- out << printer.CStr();
- }
-
- AbstractFileIO::ConfidenceLevel TubeGraphIO::GetWriterConfidenceLevel() const
- {
- if (AbstractFileIO::GetWriterConfidenceLevel() == Unsupported)
- return Unsupported;
- return Supported;
- }
-
- TubeGraphIO *TubeGraphIO::IOClone() const { return new TubeGraphIO(*this); }
-}
-
-const mitk::BoundingBox::Pointer mitk::TubeGraphIO::ComputeBoundingBox(mitk::TubeGraph::Pointer graph) const
-{
- BoundingBox::Pointer boundingBox = BoundingBox::New();
- BoundingBox::PointIdentifier pointid = 0;
- BoundingBox::PointsContainer::Pointer pointscontainer = BoundingBox::PointsContainer::New();
-
- ScalarType nullpoint[] = {0, 0, 0};
- BoundingBox::PointType p(nullpoint);
-
- // traverse the tree and add each point to the pointscontainer
-
- mitk::Point3D pos;
-
- std::vector<mitk::TubeGraphVertex> vertexVector = graph->GetVectorOfAllVertices();
- for (auto vertex = vertexVector.begin(); vertex != vertexVector.end();
- ++vertex)
- {
- pos = vertex->GetTubeElement()->GetCoordinates();
- p[0] = pos[0];
- p[1] = pos[1];
- p[2] = pos[2];
- pointscontainer->InsertElement(pointid++, p);
- }
-
- std::vector<mitk::TubeGraphEdge> edgeVector = graph->GetVectorOfAllEdges();
-
- for (auto edge = edgeVector.begin(); edge != edgeVector.end(); ++edge)
- {
- std::vector<mitk::TubeElement *> allElements = edge->GetElementVector();
- for (unsigned int index = 0; index < edge->GetNumberOfElements(); index++)
- {
- pos = allElements[index]->GetCoordinates();
- p[0] = pos[0];
- p[1] = pos[1];
- p[2] = pos[2];
- pointscontainer->InsertElement(pointid++, p);
- }
- }
-
- boundingBox->SetPoints(pointscontainer);
- boundingBox->ComputeBoundingBox();
-
- return boundingBox;
-}
diff --git a/Modules/TubeGraph/src/IO/mitkTubeGraphModuleActivator.cpp b/Modules/TubeGraph/src/IO/mitkTubeGraphModuleActivator.cpp
deleted file mode 100644
index 2cb0333333..0000000000
--- a/Modules/TubeGraph/src/IO/mitkTubeGraphModuleActivator.cpp
+++ /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.
-
-============================================================================*/
-#include <usModuleActivator.h>
-#include <usModuleContext.h>
-
-#include "mitkTubeGraphIO.h"
-
-namespace mitk
-{
- /**
- \brief Registers services for tube graph module.
- */
- class TubeGraphActivator : public us::ModuleActivator
- {
- std::vector<AbstractFileIO *> m_FileIOs;
-
- public:
- void Load(us::ModuleContext * /*context*/) override { m_FileIOs.push_back(new TubeGraphIO()); }
- void Unload(us::ModuleContext *) override
- {
- for (auto &elem : m_FileIOs)
- {
- delete elem;
- }
- }
- };
-}
-
-US_EXPORT_MODULE_ACTIVATOR(mitk::TubeGraphActivator)
diff --git a/Modules/TubeGraph/src/IO/mitkTubeGraphObjectFactory.cpp b/Modules/TubeGraph/src/IO/mitkTubeGraphObjectFactory.cpp
deleted file mode 100644
index 71c131963a..0000000000
--- a/Modules/TubeGraph/src/IO/mitkTubeGraphObjectFactory.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 "mitkTubeGraphObjectFactory.h"
-
-#include <mitkBaseRenderer.h>
-#include <mitkDataNode.h>
-#include <mitkProperties.h>
-
-#include "mitkTubeGraph.h"
-#include "mitkTubeGraphVtkMapper3D.h"
-
-mitk::TubeGraphObjectFactory::TubeGraphObjectFactory() : CoreObjectFactoryBase()
-{
- static bool alreadyDone = false;
- if (!alreadyDone)
- {
- CreateFileExtensionsMap();
- alreadyDone = true;
- }
-}
-
-mitk::Mapper::Pointer mitk::TubeGraphObjectFactory::CreateMapper(mitk::DataNode *node, MapperSlotId id)
-{
- mitk::Mapper::Pointer newMapper = nullptr;
-
- if (id == mitk::BaseRenderer::Standard3D)
- {
- if ((dynamic_cast<mitk::TubeGraph *>(node->GetData()) != nullptr))
- {
- newMapper = mitk::TubeGraphVtkMapper3D::New();
- newMapper->SetDataNode(node);
- }
- }
-
- return newMapper;
-}
-
-void mitk::TubeGraphObjectFactory::SetDefaultProperties(mitk::DataNode *node)
-{
- if ((dynamic_cast<mitk::TubeGraph *>(node->GetData()) != nullptr))
- {
- node->SetProperty("Tube Graph.Clip Structures", mitk::BoolProperty::New(false));
- mitk::TubeGraphVtkMapper3D::SetDefaultProperties(node);
- }
-}
-
-std::string mitk::TubeGraphObjectFactory::GetFileExtensions()
-{
- std::string fileExtension;
- this->CreateFileExtensions(m_FileExtensionsMap, fileExtension);
- return fileExtension.c_str();
-};
-
-mitk::CoreObjectFactoryBase::MultimapType mitk::TubeGraphObjectFactory::GetFileExtensionsMap()
-{
- return m_FileExtensionsMap;
-}
-
-std::string mitk::TubeGraphObjectFactory::GetSaveFileExtensions()
-{
- std::string fileExtension;
- this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension);
- return fileExtension.c_str();
-};
-
-mitk::CoreObjectFactoryBase::MultimapType mitk::TubeGraphObjectFactory::GetSaveFileExtensionsMap()
-{
- return m_SaveFileExtensionsMap;
-}
-
-void mitk::TubeGraphObjectFactory::CreateFileExtensionsMap()
-{
-}
-
-struct RegisterTubeGraphObjectFactory
-{
- RegisterTubeGraphObjectFactory() : m_Factory(mitk::TubeGraphObjectFactory::New())
- {
- mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(m_Factory);
- }
- ~RegisterTubeGraphObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory(m_Factory); }
- mitk::TubeGraphObjectFactory::Pointer m_Factory;
-};
-
-static RegisterTubeGraphObjectFactory registerTubeGraphObjectFactory;
diff --git a/Modules/TubeGraph/src/Interactions/mitkTubeGraphDataInteractor.cpp b/Modules/TubeGraph/src/Interactions/mitkTubeGraphDataInteractor.cpp
deleted file mode 100644
index bd0af564dd..0000000000
--- a/Modules/TubeGraph/src/Interactions/mitkTubeGraphDataInteractor.cpp
+++ /dev/null
@@ -1,290 +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 "mitkTubeGraphDataInteractor.h"
-
-#include <mitkInteractionConst.h>
-#include <mitkInteractionPositionEvent.h>
-#include <mitkStatusBar.h>
-
-#include "mitkTubeGraphPicker.h"
-
-#include <vtkCamera.h>
-#include <vtkInteractorStyle.h>
-#include <vtkPointData.h>
-#include <vtkPolyData.h>
-#include <vtkRenderWindowInteractor.h>
-
-namespace mitk
-{
- itkEventMacroDefinition(SelectionChangedTubeGraphEvent, itk::AnyEvent);
-}
-
-mitk::TubeGraphDataInteractor::TubeGraphDataInteractor()
- : m_LastPickedTube(TubeGraph::ErrorId),
- m_SecondLastPickedTube(TubeGraph::ErrorId),
- m_ActivationMode(None),
- m_ActionMode(AttributationMode)
-{
-}
-
-mitk::TubeGraphDataInteractor::~TubeGraphDataInteractor() {}
-
-void mitk::TubeGraphDataInteractor::ConnectActionsAndFunctions()
-{
- // **Conditions** that can be used in the state machine, to ensure that certain conditions are met, before actually
- // executing an action
- CONNECT_CONDITION("isOverTube", CheckOverTube);
-
- // **Function** in the statmachine patterns also referred to as **Actions**
- CONNECT_FUNCTION("selectTube", SelectTube);
- CONNECT_FUNCTION("deselectTube", DeselectTube);
-}
-
-void mitk::TubeGraphDataInteractor::DataNodeChanged()
-{
- if (GetDataNode() != nullptr)
- {
- if (GetDataNode()->GetData() != nullptr)
- {
- m_TubeGraph = dynamic_cast<TubeGraph *>(GetDataNode()->GetData());
- m_TubeGraphProperty = dynamic_cast<TubeGraphProperty *>(
- m_TubeGraph->GetProperty("Tube Graph.Visualization Information").GetPointer());
- if (m_TubeGraphProperty.IsNull())
- MITK_ERROR << "Something went wrong! No tube graph property!";
- }
- else
- m_TubeGraph = nullptr;
- }
- else
- m_TubeGraph = nullptr;
-}
-
-bool mitk::TubeGraphDataInteractor::CheckOverTube(const InteractionEvent *interactionEvent)
-{
- const auto *positionEvent = dynamic_cast<const InteractionPositionEvent *>(interactionEvent);
- if (positionEvent == nullptr)
- return false;
-
- auto *picker = new mitk::TubeGraphPicker();
- picker->SetTubeGraph(m_TubeGraph);
-
- auto pickedTube = picker->GetPickedTube(positionEvent->GetPositionInWorld());
-
- TubeGraph::TubeDescriptorType tubeDescriptor = pickedTube.first;
-
- if (tubeDescriptor != TubeGraph::ErrorId)
- {
- m_LastPickedElement = pickedTube.second;
- m_SecondLastPickedTube = m_LastPickedTube;
- m_LastPickedTube = tubeDescriptor;
- return true;
- }
- else // nothing picked
- return false;
-}
-
-void mitk::TubeGraphDataInteractor::SelectTube(StateMachineAction *, InteractionEvent *)
-{
- if (m_TubeGraph.IsNull())
- return;
-
- this->SelectTubesByActivationModus();
-
- RenderingManager::GetInstance()->RequestUpdateAll();
-
- if (m_ActivationMode != None)
- {
- // show tube id on status bar
- std::stringstream displayText;
- displayText << "Picked tube: ID [" << m_LastPickedTube.first << "," << m_LastPickedTube.second << "]";
- StatusBar::GetInstance()->DisplayText(displayText.str().c_str());
- // TODO!!! this->InvokeEvent(SelectionChangedTubeGraphEvent());
- }
-}
-
-void mitk::TubeGraphDataInteractor::DeselectTube(StateMachineAction *, InteractionEvent *)
-{
- if (m_TubeGraph.IsNull())
- return;
-
- if ((m_ActivationMode != Multiple) && (m_ActivationMode != Points))
- {
- m_TubeGraphProperty->DeactivateAllTubes();
- RenderingManager::GetInstance()->RequestUpdateAll();
- // TODO!!!this->InvokeEvent(SelectionChangedTubeGraphEvent());
- }
- // show info on status bar
- StatusBar::GetInstance()->DisplayText("No tube hit!");
-}
-
-void mitk::TubeGraphDataInteractor::SetActivationMode(const ActivationMode &activationMode)
-{
- m_ActivationMode = activationMode;
- if (m_TubeGraph.IsNotNull())
- if (m_LastPickedTube != mitk::TubeGraph::ErrorId)
- this->UpdateActivation();
-}
-
-mitk::TubeGraphDataInteractor::ActivationMode mitk::TubeGraphDataInteractor::GetActivationMode()
-{
- return m_ActivationMode;
-}
-
-void mitk::TubeGraphDataInteractor::SetActionMode(const ActionMode &actionMode)
-{
- m_ActionMode = actionMode;
-}
-
-mitk::TubeGraphDataInteractor::ActionMode mitk::TubeGraphDataInteractor::GetActionMode()
-{
- return m_ActionMode;
-}
-
-void mitk::TubeGraphDataInteractor::SelectTubesByActivationModus()
-{
- if (m_LastPickedTube != mitk::TubeGraph::ErrorId)
- {
- this->UpdateActivation();
- }
-}
-
-void mitk::TubeGraphDataInteractor::UpdateActivation()
-{
- if (m_ActionMode == RootMode)
- {
- m_TubeGraphProperty->DeactivateAllTubes();
- m_TubeGraphProperty->SetTubeActive(m_LastPickedTube, true);
-
- // QmitkTubeGraphSelectRootDialog* dialog = new QmitkTubeGraphSelectRootDialog(m_Parent);
- // int dialogReturnValue = dialog->exec();
- // delete dialog;
-
- // if ( dialogReturnValue != QDialog::Rejected ) // user doesn't clicked cancel or pressed Esc or something similar
- //{
- m_TubeGraph->SetRootTube(m_LastPickedTube);
- //}
- m_TubeGraphProperty->DeactivateAllTubes();
- RenderingManager::GetInstance()->RequestUpdateAll();
- }
- else
- {
- switch (m_ActivationMode)
- {
- case None:
- {
- m_TubeGraphProperty->DeactivateAllTubes();
- }
- break;
-
- case Single:
- {
- m_TubeGraphProperty->DeactivateAllTubes();
- m_TubeGraphProperty->SetTubeActive(m_LastPickedTube, true);
- }
- break;
-
- case Multiple:
- { // special deactivation for multiple modus
- // if activated--> deactivate; if not activated--> activate
- if (m_TubeGraphProperty->IsTubeActive(m_LastPickedTube))
- m_TubeGraphProperty->SetTubeActive(m_LastPickedTube, false);
- else
- m_TubeGraphProperty->SetTubeActive(m_LastPickedTube, true);
- }
- break;
-
- case ToRoot:
- {
- m_TubeGraphProperty->DeactivateAllTubes();
- std::vector<TubeGraph::TubeDescriptorType> activeTubes = this->GetTubesToRoot();
- m_TubeGraphProperty->SetTubesActive(activeTubes);
- }
- break;
- case ToPeriphery:
- {
- m_TubeGraphProperty->DeactivateAllTubes();
- std::vector<TubeGraph::TubeDescriptorType> activeTubes = this->GetPathToPeriphery();
- m_TubeGraphProperty->SetTubesActive(activeTubes);
- }
- break;
-
- case Points:
- {
- m_TubeGraphProperty->DeactivateAllTubes();
- std::vector<TubeGraph::TubeDescriptorType> activeTubes = this->GetTubesBetweenPoints();
- m_TubeGraphProperty->SetTubesActive(activeTubes);
- }
- break;
-
- default:
- MITK_WARN << "Unknown tube graph interaction mode!";
- break;
- }
- }
-}
-
-std::vector<mitk::TubeGraph::TubeDescriptorType> mitk::TubeGraphDataInteractor::GetTubesToRoot()
-{
- TubeGraph::TubeDescriptorType root = m_TubeGraph->GetRootTube();
- if (root == TubeGraph::ErrorId)
- {
- root = m_TubeGraph->GetThickestTube();
- m_TubeGraph->SetRootTube(root);
- }
-
- return this->GetPathBetweenTubes(m_LastPickedTube, root);
-}
-
-std::vector<mitk::TubeGraph::TubeDescriptorType> mitk::TubeGraphDataInteractor::GetTubesBetweenPoints()
-{
- return this->GetPathBetweenTubes(m_LastPickedTube, m_SecondLastPickedTube);
-}
-
-std::vector<mitk::TubeGraph::TubeDescriptorType> mitk::TubeGraphDataInteractor::GetPathBetweenTubes(
- const mitk::TubeGraph::TubeDescriptorType &start, const mitk::TubeGraph::TubeDescriptorType &end)
-{
- std::vector<mitk::TubeGraph::TubeDescriptorType> solutionPath;
- if ((start != TubeGraph::ErrorId) && (end != TubeGraph::ErrorId))
- {
- if (start != end)
- solutionPath = m_TubeGraph->SearchAllPathBetweenVertices(start, end);
- else
- solutionPath.push_back(start);
- }
-
- return solutionPath;
-}
-
-std::vector<mitk::TubeGraph::TubeDescriptorType> mitk::TubeGraphDataInteractor::GetPathToPeriphery()
-{
- std::vector<mitk::TubeGraph::TubeDescriptorType> solutionPath;
-
- if (m_LastPickedTube != TubeGraph::ErrorId)
- solutionPath = m_TubeGraph->SearchPathToPeriphery(m_LastPickedTube);
-
- return solutionPath;
-}
-
-void mitk::TubeGraphDataInteractor::ResetPickedTubes()
-{
- m_LastPickedTube = TubeGraph::ErrorId;
- m_SecondLastPickedTube = TubeGraph::ErrorId;
-}
-
-mitk::Point3D mitk::TubeGraphDataInteractor::GetLastPickedPosition()
-{
- if (m_LastPickedElement)
- return m_LastPickedElement->GetCoordinates();
- else
- return mitk::Point3D();
-}
diff --git a/Modules/TubeGraph/src/Interactions/mitkTubeGraphPicker.cpp b/Modules/TubeGraph/src/Interactions/mitkTubeGraphPicker.cpp
deleted file mode 100644
index 3fa1a9ca3a..0000000000
--- a/Modules/TubeGraph/src/Interactions/mitkTubeGraphPicker.cpp
+++ /dev/null
@@ -1,93 +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 "mitkTubeGraphPicker.h"
-
-mitk::TubeGraphPicker::TubeGraphPicker()
-{
- m_WorldPosition.Fill(0.0);
-}
-
-mitk::TubeGraphPicker::~TubeGraphPicker() {}
-
-void mitk::TubeGraphPicker::SetTubeGraph(const mitk::TubeGraph *tubeGraph)
-{
- m_TubeGraph = tubeGraph;
- m_TubeGraphProperty =
- dynamic_cast<TubeGraphProperty *>(m_TubeGraph->GetProperty("Tube Graph.Visualization Information").GetPointer());
-}
-
-/**
- * Implements the picking process
- */
-std::pair<mitk::TubeGraph::TubeDescriptorType, mitk::TubeElement *> mitk::TubeGraphPicker::GetPickedTube(
- const Point3D pickedPosition)
-{
- if (!m_TubeGraph)
- {
- MITK_ERROR << "mitk::TubeGraphPicker: No tube graph available. Please set an input!" << std::endl;
- mitk::TubeElement *nullPointer = nullptr;
- return std::pair<mitk::TubeGraph::TubeDescriptorType, mitk::TubeElement *>(TubeGraph::ErrorId, nullPointer);
- }
- m_WorldPosition = pickedPosition;
-
- Point3D currentPosition;
- ScalarType closestDistance = itk::NumericTraits<ScalarType>::max();
- ScalarType currentDistance = itk::NumericTraits<ScalarType>::max();
- float currentRadius = 0;
-
- TubeGraph::TubeDescriptorType currentTubeId(TubeGraph::ErrorId);
- TubeGraph::TubeDescriptorType tubeId(TubeGraph::ErrorId);
- TubeElement *tubeElement;
-
- // iterate over all edges and find the edge, which element is near by the clicked point
- std::vector<mitk::TubeGraphEdge> allEdges = m_TubeGraph->GetVectorOfAllEdges();
- for (auto edge = allEdges.begin(); edge != allEdges.end(); ++edge)
- {
- std::pair<mitk::TubeGraphVertex, mitk::TubeGraphVertex> soureTargetPair =
- m_TubeGraph->GetVerticesOfAnEdge(m_TubeGraph->GetEdgeDescriptor(*edge));
-
- currentTubeId = TubeGraph::TubeDescriptorType(m_TubeGraph->GetVertexDescriptor(soureTargetPair.first),
- m_TubeGraph->GetVertexDescriptor(soureTargetPair.second));
- // check if the tube is visible, if not pass this tube. User can not choose a tube, which he can't see
- if (m_TubeGraphProperty->IsTubeVisible(currentTubeId))
- {
- std::vector<mitk::TubeElement *> allElements = edge->GetElementVector();
- for (unsigned int index = 0; index < edge->GetNumberOfElements(); index++)
- {
- currentPosition = allElements[index]->GetCoordinates();
- if (dynamic_cast<mitk::CircularProfileTubeElement *>(allElements[index]))
- currentRadius = ((dynamic_cast<mitk::CircularProfileTubeElement *>(allElements[index]))->GetDiameter()) / 2;
- else
- currentRadius = 0;
-
- // calculate point->point distance
- itk::Index<3> worldIndex;
- m_TubeGraph->GetGeometry()->WorldToIndex(pickedPosition, worldIndex);
-
- m_WorldPosition[0] = worldIndex[0];
- m_WorldPosition[1] = worldIndex[1];
- m_WorldPosition[2] = worldIndex[2];
-
- currentDistance = m_WorldPosition.EuclideanDistanceTo(currentPosition);
- if (currentDistance < closestDistance && (currentDistance - currentRadius) < 1.0)
- {
- closestDistance = currentDistance;
- tubeId = currentTubeId;
- tubeElement = allElements[index];
- }
- }
- }
- }
-
- return std::make_pair(tubeId, tubeElement);
-}
diff --git a/Modules/TubeGraph/src/Rendering/mitkTubeGraphProperty.cpp b/Modules/TubeGraph/src/Rendering/mitkTubeGraphProperty.cpp
deleted file mode 100644
index 745be8cc85..0000000000
--- a/Modules/TubeGraph/src/Rendering/mitkTubeGraphProperty.cpp
+++ /dev/null
@@ -1,438 +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 "mitkTubeGraphProperty.h"
-
-#include <mitkRenderingManager.h>
-
-mitk::TubeGraphProperty::TubeGraphProperty()
-/*: m_LabelGroups(), m_ActiveTubes(), m_TubeToLabelsMap()*/
-{
-}
-
-mitk::TubeGraphProperty::TubeGraphProperty(const mitk::TubeGraphProperty &other)
- : BaseProperty(other),
- m_ActiveTubes(other.m_ActiveTubes),
- m_LabelGroups(other.m_LabelGroups),
- m_TubeToLabelsMap(other.m_TubeToLabelsMap),
- m_Annotations(other.m_Annotations)
-{
-}
-
-mitk::TubeGraphProperty::~TubeGraphProperty()
-{
- m_ActiveTubes.clear();
- m_TubeToLabelsMap.clear();
-
- for (auto it = m_LabelGroups.begin(); it != m_LabelGroups.end(); it++)
- delete *it;
- m_LabelGroups.clear();
-}
-
-bool mitk::TubeGraphProperty::IsTubeVisible(const TubeDescriptorType &tube)
-{
- // search for any label settings for the tube
- if (m_LabelGroups.size() > 0)
- {
- for (auto it = m_TubeToLabelsMap.begin(); it != m_TubeToLabelsMap.end(); it++)
- {
- if (this->TubeDescriptorsCompare(tube, (*it).first.first))
- {
- // At the moment only the first entry is considered
- LabelGroup *lg = this->GetLabelGroupByName((*it).first.second);
- LabelGroup::Label *label = this->GetLabelByName(lg, (*it).second);
- return label->isVisible;
- }
- }
- // If nothing is found, look if the first labelgroup is visible for "undefined" label
- LabelGroup::Label *label = this->GetLabelByName((*m_LabelGroups.begin()), "Undefined");
- return label->isVisible;
- }
- else
- return true;
-}
-
-void mitk::TubeGraphProperty::SetTubeActive(const TubeDescriptorType &tube, const bool &active)
-{
- // set active
- if (active)
- {
- for (std::vector<TubeDescriptorType>::const_iterator it = m_ActiveTubes.begin(); it != m_ActiveTubes.end(); it++)
- {
- if (this->TubeDescriptorsCompare(tube, (*it)))
- {
- return;
- }
- }
- // if not found, add it
- m_ActiveTubes.push_back(tube);
- this->Modified();
- }
- // set deactive
- else
- {
- for (auto it = m_ActiveTubes.begin(); it != m_ActiveTubes.end(); it++)
- {
- if (this->TubeDescriptorsCompare(tube, (*it)))
- { // if found, delete it
- m_ActiveTubes.erase(it);
- this->Modified();
- return;
- }
- }
- }
- //// render new activation
- // RenderingManager::GetInstance()->RequestUpdateAll();
-}
-
-void mitk::TubeGraphProperty::SetTubesActive(std::vector<TubeDescriptorType> &tubes)
-{
- for (auto it = tubes.begin(); it != tubes.end(); it++)
- this->SetTubeActive(*it, true);
-}
-
-bool mitk::TubeGraphProperty::IsTubeActive(const TubeDescriptorType &tube)
-{
- for (std::vector<TubeDescriptorType>::const_iterator it = m_ActiveTubes.begin(); it != m_ActiveTubes.end(); it++)
- {
- if (this->TubeDescriptorsCompare((*it), tube))
- return true;
- }
- return false;
-}
-
-std::vector<mitk::TubeGraphProperty::TubeDescriptorType> mitk::TubeGraphProperty::GetActiveTubes()
-{
- return m_ActiveTubes;
-}
-
-void mitk::TubeGraphProperty::DeactivateAllTubes()
-{
- // if (!m_ActiveTubes.empty())
- m_ActiveTubes.clear();
- this->Modified();
-}
-
-void mitk::TubeGraphProperty::AddAnnotation(mitk::TubeGraphProperty::Annotation *annotation)
-{
- for (auto it = m_Annotations.begin(); it != m_Annotations.end(); it++)
- {
- if ((*it)->name == annotation->name)
- {
- MITK_INFO << "An Annotation with this name already exists.";
- return;
- }
- }
- m_Annotations.push_back(annotation);
-}
-mitk::TubeGraphProperty::Annotation *mitk::TubeGraphProperty::GetAnnotationByName(std::string annotation)
-{
- for (auto it = m_Annotations.begin(); it != m_Annotations.end(); it++)
- {
- if ((*it)->name == annotation)
- return *it;
- }
- return nullptr;
-}
-std::vector<mitk::TubeGraphProperty::Annotation *> mitk::TubeGraphProperty::GetAnnotations()
-{
- return m_Annotations;
-}
-void mitk::TubeGraphProperty::RemoveAnnotation(mitk::TubeGraphProperty::Annotation *annotation)
-{
- for (auto it = m_Annotations.begin(); it != m_Annotations.end(); it++)
- {
- if ((*it)->name == annotation->name)
- {
- m_Annotations.erase(it);
- return;
- }
- }
-}
-
-mitk::Color mitk::TubeGraphProperty::GetColorOfTube(const TubeDescriptorType &tube)
-{
- Color color;
- // grey as default color
- color[0] = 150;
- color[1] = 150;
- color[2] = 150;
-
- bool isActive(false);
- bool hasLabel(false);
- // search the vector with active tubes first. If the tube is active it can not have another color.
- for (std::vector<TubeDescriptorType>::const_iterator it = m_ActiveTubes.begin(); it != m_ActiveTubes.end(); it++)
- {
- if (this->TubeDescriptorsCompare(tube, (*it)))
- {
- color[0] = 255;
- color[1] = 255;
- color[2] = 0;
- isActive = true;
- break;
- }
- }
-
- if (!isActive)
- {
- // So let see which label is activ on this tube and which color is set.
- if (m_LabelGroups.size() > 0)
- {
- for (auto it = m_TubeToLabelsMap.begin(); it != m_TubeToLabelsMap.end(); it++)
- {
- if (this->TubeDescriptorsCompare(tube, (*it).first.first))
- { // At the moment only the first entry is considered
- LabelGroup *lg = this->GetLabelGroupByName((*it).first.second);
- LabelGroup::Label *label = this->GetLabelByName(lg, (*it).second);
- color = label->labelColor;
- hasLabel = true;
- }
- }
- // If nothing is found, look if the first labelgroup is visible for "undefined" label
- if (!hasLabel)
- {
- LabelGroup::Label *label = this->GetLabelByName(*(m_LabelGroups.begin()), "Undefined");
- color = label->labelColor;
- }
- }
- }
-
- return color;
-}
-
-void mitk::TubeGraphProperty::SetLabelForActivatedTubes(LabelGroup *labelGroup, LabelGroup::Label *label)
-{
- bool isUndefined(label->labelName.compare("Undefined") == 0);
- for (unsigned int i = 0; i < m_ActiveTubes.size(); i++)
- {
- bool isInList(false);
- for (auto it = m_TubeToLabelsMap.begin(); it != m_TubeToLabelsMap.end(); it++)
- {
- if ((this->TubeDescriptorsCompare(it->first.first, m_ActiveTubes[i])) &&
- (labelGroup->labelGroupName.compare(it->first.second) == 0))
- {
- // If tube has a label fromlabel group, deleted if "undefined" is clicked.
- if (isUndefined)
- {
- m_TubeToLabelsMap.erase(it);
- break;
- }
- else
- {
- it->second = label->labelName;
- isInList = true;
- }
- }
- }
- if (!isInList && !isUndefined)
- {
- TubeToLabelGroupType tubeToLabelGroup(m_ActiveTubes[i], labelGroup->labelGroupName);
- m_TubeToLabelsMap.insert(std::pair<TubeToLabelGroupType, std::string>(tubeToLabelGroup, label->labelName));
- }
- }
- this->Modified();
- m_ActiveTubes.clear();
-}
-
-void mitk::TubeGraphProperty::SetTubesToLabels(std::map<TubeToLabelGroupType, std::string> tubeToLabelMap)
-{
- m_TubeToLabelsMap = tubeToLabelMap;
-}
-
-std::map<mitk::TubeGraphProperty::TubeToLabelGroupType, std::string> mitk::TubeGraphProperty::GetTubesToLabels()
-{
- return m_TubeToLabelsMap;
-}
-
-void mitk::TubeGraphProperty::AddLabelGroup(LabelGroup *labelGroup, unsigned int position)
-{
- // Check if the name is unique
- for (auto it = m_LabelGroups.begin(); it != m_LabelGroups.end(); it++)
- {
- if (labelGroup->labelGroupName.compare((*it)->labelGroupName) == 0)
- {
- MITK_ERROR << "The label group must be unique! This name already exists!";
- return;
- }
- }
-
- // Add the label group at position, if you can, otherwise put it at the end of the vector
- if (position < m_LabelGroups.size() - 1)
- {
- auto it = m_LabelGroups.begin() + position;
- m_LabelGroups.insert(it, labelGroup);
- }
- else
- {
- m_LabelGroups.push_back(labelGroup);
-
- // when given position is larger then vector size, the label group will be added at the last position
- if (position >= m_LabelGroups.size())
- MITK_INFO << "Position is out of space. So the label group was added on last position: "
- << m_LabelGroups.size() - 1;
- }
-}
-
-void mitk::TubeGraphProperty::RemoveLabelGroup(LabelGroup *labelGroup)
-{
- // find labelGroup in vector
- auto foundElement = std::find(m_LabelGroups.begin(), m_LabelGroups.end(), labelGroup);
- unsigned int pos = foundElement - m_LabelGroups.begin();
-
- // found it? delete it!
- if (pos < m_LabelGroups.size())
- {
- // delete every assignment to a tube
- for (auto it = m_TubeToLabelsMap.begin(); it != m_TubeToLabelsMap.end(); it++)
- {
- if (labelGroup->labelGroupName.compare((*it).first.second) == 0)
- m_TubeToLabelsMap.erase(it);
- }
-
- m_LabelGroups.erase(foundElement);
- }
- else
- {
- MITK_ERROR << "Could not find the label group!";
- return;
- }
-}
-
-void mitk::TubeGraphProperty::SetLabelColor(LabelGroup::Label *label, mitk::Color color)
-{
- // LabelGroup? Check if it is a label in property class
- if (label)
- {
- label->labelColor = color;
- this->Modified();
- }
-}
-
-void mitk::TubeGraphProperty::SetLabelVisibility(LabelGroup::Label *label, bool isVisible)
-{
- // LabelGroup? Check if it is a label in property class
- if (label)
- {
- label->isVisible = isVisible;
- this->Modified();
- }
-}
-
-void mitk::TubeGraphProperty::RenameLabel(LabelGroup *labelGroup, LabelGroup::Label *label, std::string newName)
-{
- // LabelGroup? Check if it is a label in property class
- if (label)
- {
- // rename the label in the assignement vector for tubes
- for (auto it = m_TubeToLabelsMap.begin(); it != m_TubeToLabelsMap.end(); it++)
- {
- // Label group fit?
- if (labelGroup->labelGroupName.compare((*it).first.second) == 0)
- // label fit?
- if (label->labelName.compare((*it).second) == 0)
- // rename it
- (*it).second = newName;
- }
-
- // rename the label in label group
- label->labelName = newName;
- }
-}
-
-mitk::TubeGraphProperty::LabelGroupSetType mitk::TubeGraphProperty::GetLabelGroups()
-{
- return m_LabelGroups;
-}
-
-unsigned int mitk::TubeGraphProperty::GetNumberOfLabelGroups()
-{
- return m_LabelGroups.size();
-}
-
-unsigned int mitk::TubeGraphProperty::GetIndexOfLabelGroup(mitk::TubeGraphProperty::LabelGroup *labelGroup)
-{
- unsigned int pos = std::find(m_LabelGroups.begin(), m_LabelGroups.end(), labelGroup) - m_LabelGroups.begin();
-
- if (pos < m_LabelGroups.size())
- return pos;
- // label group is not in property class
- else
- {
- MITK_ERROR << "Could not find such a label group!";
- return m_LabelGroups.size();
- }
-}
-
-mitk::TubeGraphProperty::LabelGroup *mitk::TubeGraphProperty::GetLabelGroupByName(std::string labelGroup)
-{
- for (auto it = m_LabelGroups.begin(); it != m_LabelGroups.end(); it++)
- {
- if (labelGroup.compare((*it)->labelGroupName) == 0)
- return (*it);
- }
-
- MITK_ERROR << "Could not find such a label group!";
- return nullptr;
-}
-
-mitk::TubeGraphProperty::LabelGroup::Label *mitk::TubeGraphProperty::GetLabelByName(LabelGroup *labelGroup,
- std::string labelName)
-{
- for (auto it = labelGroup->labels.begin(); it != labelGroup->labels.end(); it++)
- {
- if (labelName.compare((*it)->labelName) == 0)
- return (*it);
- }
-
- MITK_ERROR << "Could not find such a label!";
- return nullptr;
-}
-
-bool mitk::TubeGraphProperty::TubeDescriptorsCompare(const TubeDescriptorType &tube1, const TubeDescriptorType &tube2)
-{
- if (((tube1.first == tube2.first) && (tube1.second == tube2.second)) ||
- ((tube1.first == tube2.second) && (tube1.second == tube2.first)))
- return true;
- else
- return false;
-}
-
-bool mitk::TubeGraphProperty::IsEqual(const BaseProperty &) const
-{ // TODO see ResectionProposalDescriptorProperty
- return true;
-}
-
-bool mitk::TubeGraphProperty::Assign(const BaseProperty &)
-{ // TODO see ResectionProposalDescriptorProperty
- return true;
-}
-
-std::string mitk::TubeGraphProperty::GetValueAsString() const
-{ // TODO
- return "";
-}
-
-itk::LightObject::Pointer mitk::TubeGraphProperty::InternalClone() const
-{
- itk::LightObject::Pointer result(new Self(*this));
- return result;
-}
-
-bool mitk::TubeGraphProperty::ToJSON(nlohmann::json&) const
-{
- return false; // Not implemented
-}
-
-bool mitk::TubeGraphProperty::FromJSON(const nlohmann::json&)
-{
- return false; // Not implemented
-}
diff --git a/Modules/TubeGraph/src/Rendering/mitkTubeGraphVtkMapper3D.cpp b/Modules/TubeGraph/src/Rendering/mitkTubeGraphVtkMapper3D.cpp
deleted file mode 100644
index 864d163416..0000000000
--- a/Modules/TubeGraph/src/Rendering/mitkTubeGraphVtkMapper3D.cpp
+++ /dev/null
@@ -1,753 +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 "mitkTubeGraphVtkMapper3D.h"
-
-#include <mitkColorProperty.h>
-
-#include <vtkCellArray.h>
-#include <vtkClipPolyData.h>
-#include <vtkContourFilter.h>
-#include <vtkCylinder.h>
-#include <vtkFloatArray.h>
-#include <vtkGeneralTransform.h>
-#include <vtkImplicitBoolean.h>
-#include <vtkImplicitModeller.h>
-#include <vtkPlane.h>
-#include <vtkPointData.h>
-#include <vtkPoints.h>
-#include <vtkPolyDataMapper.h>
-#include <vtkProperty.h>
-#include <vtkRenderer.h>
-#include <vtkSampleFunction.h>
-#include <vtkSphereSource.h>
-#include <vtkTubeFilter.h>
-#include <vtkUnsignedCharArray.h>
-
-mitk::TubeGraphVtkMapper3D::TubeGraphVtkMapper3D()
-{
-}
-
-mitk::TubeGraphVtkMapper3D::~TubeGraphVtkMapper3D()
-{
-}
-
-const mitk::TubeGraph *mitk::TubeGraphVtkMapper3D::GetInput()
-{
- return dynamic_cast<const TubeGraph *>(GetDataNode()->GetData());
-}
-
-vtkProp *mitk::TubeGraphVtkMapper3D::GetVtkProp(mitk::BaseRenderer *renderer)
-{
- return m_LSH.GetLocalStorage(renderer)->m_vtkTubeGraphAssembly;
-}
-
-void mitk::TubeGraphVtkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
-{
- bool renderTubeGraph(false);
- LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
-
- TubeGraph::Pointer tubeGraph = const_cast<mitk::TubeGraph *>(this->GetInput());
- TubeGraphProperty::Pointer tubeGraphProperty =
- dynamic_cast<TubeGraphProperty *>(tubeGraph->GetProperty("Tube Graph.Visualization Information").GetPointer());
-
- if (tubeGraph.IsNull() || tubeGraphProperty.IsNull())
- {
- itkWarningMacro(<< "Input of tube graph mapper is nullptr!");
- return;
- }
- // Check if the tube graph has changed; if the data has changed, generate the spheres and tubes new;
- if (tubeGraph->GetMTime() > ls->m_lastGenerateDataTime)
- {
- this->GenerateTubeGraphData(renderer);
- renderTubeGraph = true;
- }
- else
- {
- // Check if the tube graph property has changed; if the property has changed, render the visualization information
- // new;
- if (tubeGraphProperty->GetMTime() > ls->m_lastRenderDataTime)
- {
- this->RenderTubeGraphPropertyInformation(renderer);
- renderTubeGraph = true;
- }
- }
-
- if (renderTubeGraph)
- {
- std::vector<TubeGraph::VertexDescriptorType> alreadyRenderedVertexList;
- // don't render the sphere which is the root of the graph; so add it to the list before;
- // TODO check both spheres
- TubeGraph::VertexDescriptorType root = tubeGraph->GetRootVertex();
- alreadyRenderedVertexList.push_back(root);
-
- for (auto itTubes =
- ls->m_vtkTubesActorMap.begin();
- itTubes != ls->m_vtkTubesActorMap.end();
- itTubes++)
- {
- if (tubeGraphProperty->IsTubeVisible(itTubes->first))
- {
- // add tube actor to assembly
- ls->m_vtkTubeGraphAssembly->AddPart(itTubes->second);
-
- // render the clipped spheres as end-cups of a tube and connections between tubes
- if (std::find(alreadyRenderedVertexList.begin(), alreadyRenderedVertexList.end(), itTubes->first.first) ==
- alreadyRenderedVertexList.end())
- {
- auto itSourceSphere =
- ls->m_vtkSpheresActorMap.find(itTubes->first.first);
- if (itSourceSphere != ls->m_vtkSpheresActorMap.end())
- ls->m_vtkTubeGraphAssembly->AddPart(itSourceSphere->second);
- alreadyRenderedVertexList.push_back(itSourceSphere->first);
- }
- if (std::find(alreadyRenderedVertexList.begin(), alreadyRenderedVertexList.end(), itTubes->first.second) ==
- alreadyRenderedVertexList.end())
- {
- auto itTargetSphere =
- ls->m_vtkSpheresActorMap.find(itTubes->first.second);
- if (itTargetSphere != ls->m_vtkSpheresActorMap.end())
- ls->m_vtkTubeGraphAssembly->AddPart(itTargetSphere->second);
- alreadyRenderedVertexList.push_back(itTargetSphere->first);
- }
- }
- }
- }
-
- //// Opacity TODO
- //{
- // float opacity = 1.0f;
- // if( this->GetDataNode()->GetOpacity(opacity,renderer) )
- // ls->m_vtkTubesActor->GetProperty()->SetOpacity( opacity );
- //}
-}
-
-void mitk::TubeGraphVtkMapper3D::RenderTubeGraphPropertyInformation(mitk::BaseRenderer *renderer)
-{
- MITK_INFO << "Render tube graph property information!";
- LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
- TubeGraph::ConstPointer tubeGraph = this->GetInput();
- TubeGraphProperty::Pointer tubeGraphProperty =
- dynamic_cast<TubeGraphProperty *>(tubeGraph->GetProperty("Tube Graph.Visualization Information").GetPointer());
-
- if (tubeGraphProperty.IsNull())
- {
- MITK_INFO << "No tube graph property!! So no special render information...";
- return;
- }
-
- std::vector<TubeGraphVertex> allVertices = tubeGraph->GetVectorOfAllVertices();
- for (auto vertex = allVertices.begin(); vertex != allVertices.end(); ++vertex)
- {
- TubeGraph::VertexDescriptorType vertexDesc = tubeGraph->GetVertexDescriptor(*vertex);
-
- double sphereColorR = 0;
- double sphereColorG = 0;
- double sphereColorB = 0;
-
- int numberOfVisibleEdges = 0;
- std::vector<TubeGraphEdge> allEdgesOfVertex = tubeGraph->GetAllEdgesOfAVertex(vertexDesc);
- for (auto edge = allEdgesOfVertex.begin(); edge != allEdgesOfVertex.end(); ++edge)
- {
- // get edge descriptor
- EdgeDescriptorType edgeDesc = tubeGraph->GetEdgeDescriptor(*edge);
-
- // get source and target vertex descriptor
- std::pair<TubeGraphVertex, TubeGraphVertex> soureTargetPair = tubeGraph->GetVerticesOfAnEdge(edgeDesc);
- TubeGraphVertex source = soureTargetPair.first;
- TubeGraphVertex target = soureTargetPair.second;
-
- // build tube descriptor [sourceId,targetId]
- TubeGraph::TubeDescriptorType tube;
- tube.first = tubeGraph->GetVertexDescriptor(source);
- tube.second = tubeGraph->GetVertexDescriptor(target);
-
- if (tubeGraphProperty->IsTubeVisible(tube))
- {
- mitk::Color tubeColor = tubeGraphProperty->GetColorOfTube(tube);
-
- vtkSmartPointer<vtkDataArray> scalars =
- ls->m_vtkTubesActorMap[tube]->GetMapper()->GetInput()->GetPointData()->GetScalars();
- double color[3];
- scalars->GetTuple(0, color);
-
- if (color[0] != tubeColor[0] || color[1] != tubeColor[1] || color[2] != tubeColor[2])
- {
- int numberOfPoints = scalars->GetSize();
-
- vtkSmartPointer<vtkUnsignedCharArray> colorScalars = vtkSmartPointer<vtkUnsignedCharArray>::New();
- colorScalars->SetName("colorScalars");
- colorScalars->SetNumberOfComponents(3);
- colorScalars->SetNumberOfTuples(numberOfPoints);
- for (int i = 0; i < numberOfPoints; i++)
- {
- scalars->InsertTuple3(i, tubeColor[0], tubeColor[1], tubeColor[2]);
- }
- ls->m_vtkTubesActorMap[tube]->GetMapper()->GetInput()->GetPointData()->SetActiveScalars("colorScalars");
- }
-
- sphereColorR += tubeColor[0];
- sphereColorG += tubeColor[1];
- sphereColorB += tubeColor[2];
- numberOfVisibleEdges++;
- }
- }
- if (numberOfVisibleEdges > 0)
- {
- sphereColorR /= 255 * numberOfVisibleEdges;
- sphereColorG /= 255 * numberOfVisibleEdges;
- sphereColorB /= 255 * numberOfVisibleEdges;
- }
-
- ls->m_vtkSpheresActorMap[vertexDesc]->GetProperty()->SetColor(sphereColorR, sphereColorG, sphereColorB);
- }
- ls->m_lastRenderDataTime.Modified();
-}
-
-void mitk::TubeGraphVtkMapper3D::GenerateTubeGraphData(mitk::BaseRenderer *renderer)
-{
- MITK_INFO << "Render tube graph!";
- LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
-
- ls->m_vtkTubesActorMap.clear();
- ls->m_vtkSpheresActorMap.clear();
-
- TubeGraph::Pointer tubeGraph = const_cast<mitk::TubeGraph *>(this->GetInput());
- TubeGraphProperty::Pointer tubeGraphProperty =
- dynamic_cast<TubeGraphProperty *>(tubeGraph->GetProperty("Tube Graph.Visualization Information").GetPointer());
- if (tubeGraphProperty.IsNull())
- MITK_INFO << "No tube graph property!! So no special render information...";
-
- // render all edges as tubular structures using the vtkTubeFilter
- std::vector<TubeGraphEdge> allEdges = tubeGraph->GetVectorOfAllEdges();
- for (auto edge = allEdges.begin(); edge != allEdges.end(); ++edge)
- {
- this->GeneratePolyDataForTube(*edge, tubeGraph, tubeGraphProperty, renderer);
- }
-
- // Generate all vertices as spheres
- std::vector<TubeGraphVertex> allVertices = tubeGraph->GetVectorOfAllVertices();
- for (auto vertex = allVertices.begin(); vertex != allVertices.end(); ++vertex)
- {
- this->GeneratePolyDataForFurcation(*vertex, tubeGraph, renderer);
- if (this->ClipStructures())
- {
- this->ClipPolyData(*vertex, tubeGraph, tubeGraphProperty, renderer);
- }
-
- ls->m_lastGenerateDataTime.Modified();
- }
-}
-
-void mitk::TubeGraphVtkMapper3D::GeneratePolyDataForFurcation(mitk::TubeGraphVertex &vertex,
- const mitk::TubeGraph::Pointer &graph,
- mitk::BaseRenderer *renderer)
-{
- LocalStorage *ls = this->m_LSH.GetLocalStorage(renderer);
-
- mitk::Point3D coordinates;
- float diameter = 2;
-
- coordinates = (vertex.GetTubeElement())->GetCoordinates();
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(vertex.GetTubeElement()))
- {
- diameter = (dynamic_cast<const mitk::CircularProfileTubeElement *>(vertex.GetTubeElement()))->GetDiameter();
- }
- vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();
- sphereSource->SetCenter(coordinates[0], coordinates[1], coordinates[2]);
- sphereSource->SetRadius(diameter / 2.0f);
- sphereSource->SetThetaResolution(12);
- sphereSource->SetPhiResolution(12);
- sphereSource->Update();
-
- // generate a actor with a mapper for the sphere
- vtkSmartPointer<vtkPolyDataMapper> sphereMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
- vtkSmartPointer<vtkActor> sphereActor = vtkSmartPointer<vtkActor>::New();
-
- sphereMapper->SetInputConnection(sphereSource->GetOutputPort());
- sphereActor->SetMapper(sphereMapper);
-
- ls->m_vtkSpheresActorMap.insert(std::make_pair(graph->GetVertexDescriptor(vertex), sphereActor));
-}
-
-void mitk::TubeGraphVtkMapper3D::GeneratePolyDataForTube(mitk::TubeGraphEdge &edge,
- const mitk::TubeGraph::Pointer &graph,
- const mitk::TubeGraphProperty::Pointer &graphProperty,
- mitk::BaseRenderer *renderer)
-{
- LocalStorage *ls = this->m_LSH.GetLocalStorage(renderer);
-
- // get edge descriptor
- EdgeDescriptorType edgeDesc = graph->GetEdgeDescriptor(edge);
-
- // get source and target vertex descriptor
- std::pair<TubeGraphVertex, TubeGraphVertex> soureTargetPair = graph->GetVerticesOfAnEdge(edgeDesc);
- TubeGraphVertex source = soureTargetPair.first;
- TubeGraphVertex target = soureTargetPair.second;
-
- // build tube descriptor [sourceId,targetId]
- TubeGraph::TubeDescriptorType tube;
- tube.first = graph->GetVertexDescriptor(source);
- tube.second = graph->GetVertexDescriptor(target);
-
- Color color;
- if (graphProperty.IsNotNull())
- {
- color = graphProperty->GetColorOfTube(tube);
- }
- else
- {
- color[0] = 150;
- color[1] = 150;
- color[2] = 150;
- }
-
- // add 2 points for the source and target vertices.
- unsigned int numberOfPoints = edge.GetNumberOfElements() + 2;
-
- // Initialize the required data-structures for building
- // an appropriate input to the tube filter
- vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
- points->SetNumberOfPoints(numberOfPoints);
-
- vtkSmartPointer<vtkFloatArray> radii = vtkSmartPointer<vtkFloatArray>::New();
- radii->SetName("radii");
- radii->SetNumberOfComponents(1);
-
- vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
-
- vtkSmartPointer<vtkUnsignedCharArray> colorScalars = vtkSmartPointer<vtkUnsignedCharArray>::New();
- colorScalars->SetName("colorScalars");
- colorScalars->SetNumberOfComponents(3);
-
- // resize the data-arrays
- radii->SetNumberOfTuples(numberOfPoints);
- colorScalars->SetNumberOfTuples(numberOfPoints);
- lines->InsertNextCell(numberOfPoints);
-
- // Add the positions of the source node, the elements along the edge and
- // the target node as lines to a cell. This cell is used as input
- // for a Tube Filter
- mitk::Point3D coordinates;
- float diameter = 2;
- unsigned int id = 0;
-
- // Source Node
- coordinates = (source.GetTubeElement())->GetCoordinates();
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(source.GetTubeElement()))
- {
- diameter = (dynamic_cast<const mitk::CircularProfileTubeElement *>(source.GetTubeElement()))->GetDiameter();
- }
- points->InsertPoint(id, coordinates[0], coordinates[1], coordinates[2]);
- radii->InsertTuple1(id, diameter / 2.0f);
-
- colorScalars->InsertTuple3(id, color[0], color[1], color[2]);
- lines->InsertCellPoint(id);
- ++id;
-
- // Iterate along the edge
- std::vector<mitk::TubeElement *> allElements = edge.GetElementVector();
- for (unsigned int index = 0; index < edge.GetNumberOfElements(); index++)
- {
- coordinates = allElements[index]->GetCoordinates();
- if (dynamic_cast<mitk::CircularProfileTubeElement *>(allElements[index]))
- {
- diameter = (dynamic_cast<mitk::CircularProfileTubeElement *>(allElements[index]))->GetDiameter();
- }
- points->InsertPoint(id, coordinates[0], coordinates[1], coordinates[2]);
- radii->InsertTuple1(id, diameter / 2.0f);
- colorScalars->InsertTuple3(id, color[0], color[1], color[2]);
- lines->InsertCellPoint(id);
- ++id;
- }
-
- // Target Node
- coordinates = (target.GetTubeElement())->GetCoordinates();
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(target.GetTubeElement()))
- {
- diameter = (dynamic_cast<const mitk::CircularProfileTubeElement *>(target.GetTubeElement()))->GetDiameter();
- }
- points->InsertPoint(id, coordinates[0], coordinates[1], coordinates[2]);
- radii->InsertTuple1(id, diameter / 2.0f);
- colorScalars->InsertTuple3(id, color[0], color[1], color[2]);
- lines->InsertCellPoint(id);
- ++id;
-
- // Initialize poly data from the point set and the cell array
- // (representing topology)
- vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
- polyData->SetPoints(points);
- polyData->SetLines(lines);
- polyData->GetPointData()->AddArray(radii);
- polyData->GetPointData()->AddArray(colorScalars);
- polyData->GetPointData()->SetActiveScalars(radii->GetName());
-
- // Generate a tube for all lines in the polydata object
- double *range = radii->GetRange();
-
- assert(range[0] != 0.0f && range[1] != 0.0f);
-
- vtkSmartPointer<vtkTubeFilter> tubeFilter = vtkSmartPointer<vtkTubeFilter>::New();
- tubeFilter->SetInputData(polyData);
- tubeFilter->SetRadius(range[0]);
- tubeFilter->SetRadiusFactor(range[1] / range[0]);
-
- if (range[0] != range[1])
- tubeFilter->SetVaryRadiusToVaryRadiusByScalar();
-
- tubeFilter->SetNumberOfSides(9);
- tubeFilter->SidesShareVerticesOn();
- tubeFilter->CappingOff();
- tubeFilter->Update();
-
- tubeFilter->GetOutput()->GetPointData()->SetActiveScalars("colorScalars");
-
- // generate a actor with a mapper for the
- vtkSmartPointer<vtkPolyDataMapper> tubeMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
- vtkSmartPointer<vtkActor> tubeActor = vtkSmartPointer<vtkActor>::New();
-
- tubeMapper->SetInputConnection(tubeFilter->GetOutputPort());
- tubeActor->SetMapper(tubeMapper);
- tubeActor->GetProperty()->SetColor(color[0], color[1], color[2]);
-
- ls->m_vtkTubesActorMap.insert(std::pair<TubeGraph::TubeDescriptorType, vtkSmartPointer<vtkActor>>(tube, tubeActor));
-}
-
-void mitk::TubeGraphVtkMapper3D::ClipPolyData(mitk::TubeGraphVertex &vertex,
- const mitk::TubeGraph::Pointer &graph,
- const mitk::TubeGraphProperty::Pointer &graphProperty,
- mitk::BaseRenderer *renderer)
-{
- LocalStorage *ls = this->m_LSH.GetLocalStorage(renderer);
-
- mitk::Point3D centerVertex = vertex.GetTubeElement()->GetCoordinates();
- float diameter = 2;
- if (dynamic_cast<const mitk::CircularProfileTubeElement *>(vertex.GetTubeElement()))
- {
- diameter = (dynamic_cast<const mitk::CircularProfileTubeElement *>(vertex.GetTubeElement()))->GetDiameter();
- }
-
- TubeGraph::VertexDescriptorType vertexDesc = graph->GetVertexDescriptor(vertex);
-
- std::map<TubeGraph::TubeDescriptorType, vtkSmartPointer<vtkImplicitBoolean>> cylinderForClipping;
-
- // generate for all edges/tubes cylinders. With this structure you can clip the sphere and the other tubes, so that no
- // fragments are shown in the tube.
- std::vector<TubeGraphEdge> allEdgesOfVertex = graph->GetAllEdgesOfAVertex(vertexDesc);
- for (auto edge = allEdgesOfVertex.begin(); edge != allEdgesOfVertex.end(); ++edge)
- {
- // get edge descriptor
- EdgeDescriptorType edgeDesc = graph->GetEdgeDescriptor(*edge);
-
- // get source and target vertex descriptor
- auto soureTargetPair = graph->GetVerticesOfAnEdge(edgeDesc);
- TubeGraphVertex source = soureTargetPair.first;
- TubeGraphVertex target = soureTargetPair.second;
-
- // build tube descriptor [sourceId,targetId]
- TubeGraph::TubeDescriptorType tube;
- tube.first = graph->GetVertexDescriptor(source);
- tube.second = graph->GetVertexDescriptor(target);
-
- // get reference point in the tube for the direction
- mitk::Point3D edgeDirectionPoint;
- // get reference diameter
- double cylinderDiameter = diameter;
- float radius = diameter / 2;
- // if the vertex is the source vertex of the edge get the first element of elementVector; otherwise get the last
- // element.
- if (source == vertex)
- {
- // if the edge has no element get the other vertex
- if ((*edge).GetNumberOfElements() != 0)
- {
- double lastDistance = 0, distance = 0;
-
- unsigned int index = 0;
- // Get the first element behind the radius of the sphere
- for (; index < (*edge).GetNumberOfElements(); index++)
- {
- mitk::Vector3D diffVec = (*edge).GetTubeElement(index)->GetCoordinates() - centerVertex;
- distance = std::sqrt(pow(diffVec[0], 2) + pow(diffVec[1], 2) + pow(diffVec[2], 2));
- if (distance > radius)
- break;
- lastDistance = distance;
- }
- // if the last element is not inside the sphere
- if (index < (*edge).GetNumberOfElements())
- {
- double withinSphereDiameter = diameter, outsideSphereDiameter = diameter, interpolationValue = 0.5;
-
- interpolationValue = (radius - lastDistance) / (distance - lastDistance);
- // if first element is outside of the sphere use sphere diameter and the element diameter for interpolation
- if (index == 0)
- {
- if (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(0)))
- outsideSphereDiameter =
- (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(0)))->GetDiameter();
- }
- else
- {
- if (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(index - 1)))
- withinSphereDiameter =
- (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(index - 1)))->GetDiameter();
-
- if (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(index)))
- outsideSphereDiameter =
- (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(index)))->GetDiameter();
- }
- // interpolate the diameter for clipping
- cylinderDiameter =
- (1 - interpolationValue) * withinSphereDiameter + interpolationValue * outsideSphereDiameter;
- }
- // Get the reference point, so the direction of the tube can be calculated
- edgeDirectionPoint = (*edge).GetTubeElement(0)->GetCoordinates();
- }
- else
- {
- // Get the reference point, so the direction of the tube can be calculated
- edgeDirectionPoint = target.GetTubeElement()->GetCoordinates();
- }
- }
-
- // if vertex is target of the tube
- else
- {
- // if the edge has no element, get the other vertex
- if ((*edge).GetNumberOfElements() != 0)
- {
- double lastDistance = 0, distance = 0;
- // Get the first element behind the radius of the sphere; now backwards through the element list
- int index = (*edge).GetNumberOfElements();
- for ( ; index >= 0; --index)
- {
- mitk::Vector3D diffVec = (*edge).GetTubeElement(index)->GetCoordinates() - centerVertex;
- distance = std::sqrt(pow(diffVec[0], 2) + pow(diffVec[1], 2) + pow(diffVec[2], 2));
- if (distance > radius)
- break;
- lastDistance = distance;
- }
-
- if (index >= 0)
- {
- double withinSphereDiameter = diameter, outsideSphereDiameter = diameter, interpolationValue = 0.5;
-
- interpolationValue = (radius - lastDistance) / (distance - lastDistance);
-
- if (index == static_cast<int>((*edge).GetNumberOfElements() - 1))
- {
- if (dynamic_cast<mitk::CircularProfileTubeElement *>(
- (*edge).GetTubeElement((*edge).GetNumberOfElements() - 1)))
- outsideSphereDiameter = (dynamic_cast<mitk::CircularProfileTubeElement *>(
- (*edge).GetTubeElement((*edge).GetNumberOfElements() - 1)))
- ->GetDiameter();
- }
- else
- {
- if (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(index + 1)))
- withinSphereDiameter =
- (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(index + 1)))->GetDiameter();
-
- if (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(index)))
- outsideSphereDiameter =
- (dynamic_cast<mitk::CircularProfileTubeElement *>((*edge).GetTubeElement(index)))->GetDiameter();
- }
- // interpolate the diameter for clipping
- cylinderDiameter =
- (1 - interpolationValue) * withinSphereDiameter + interpolationValue * outsideSphereDiameter;
- }
- // Get the reference point, so the direction of the tube can be calculated
- edgeDirectionPoint = (*edge).GetTubeElement((*edge).GetNumberOfElements() - 1)->GetCoordinates();
- }
- else
- {
- // Get the reference point, so the direction of the tube can be calculated
- edgeDirectionPoint = source.GetTubeElement()->GetCoordinates();
- }
- }
-
- //////Calculate the matrix for rotation and translation////
- // get the normalized vector for the orientation (tube element direction)
- mitk::Vector3D vecOrientation;
- mitk::FillVector3D(vecOrientation,
- (edgeDirectionPoint[0] - centerVertex[0]),
- (edgeDirectionPoint[1] - centerVertex[1]),
- (edgeDirectionPoint[2] - centerVertex[2]));
- vecOrientation.Normalize();
-
- // generate a random vector
- mitk::Vector3D vecRandom;
- mitk::FillVector3D(vecRandom, (rand() % 100 - 50), (rand() % 100 - 50), (rand() % 100 - 50));
- // project the random vector on the plane-->orthogonal vector to plane normal; normalize it!
- mitk::Vector3D vecOrthoToOrientation;
- vecOrthoToOrientation = vecRandom - (vecRandom * vecOrientation) * vecOrientation;
- vecOrthoToOrientation.Normalize();
-
- // get the cross product of both orthogonale vectors to get a third one
- mitk::Vector3D vecCrossProduct;
- vecCrossProduct = itk::CrossProduct(vecOrientation, vecOrthoToOrientation);
- vecCrossProduct.Normalize();
-
- // Fill matrix
- vtkSmartPointer<vtkMatrix4x4> vtkTransformMatrix = vtkSmartPointer<vtkMatrix4x4>::New();
- vtkTransformMatrix->Identity();
- // 1. column
- vtkTransformMatrix->SetElement(0, 0, vecOrthoToOrientation[0]);
- vtkTransformMatrix->SetElement(1, 0, vecOrthoToOrientation[1]);
- vtkTransformMatrix->SetElement(2, 0, vecOrthoToOrientation[2]);
- // 2. column
- vtkTransformMatrix->SetElement(0, 1, vecOrientation[0]);
- vtkTransformMatrix->SetElement(1, 1, vecOrientation[1]);
- vtkTransformMatrix->SetElement(2, 1, vecOrientation[2]);
- // 3. column
- vtkTransformMatrix->SetElement(0, 2, vecCrossProduct[0]);
- vtkTransformMatrix->SetElement(1, 2, vecCrossProduct[1]);
- vtkTransformMatrix->SetElement(2, 2, vecCrossProduct[2]);
- // 4. column
- vtkTransformMatrix->SetElement(0, 3, centerVertex[0]);
- vtkTransformMatrix->SetElement(1, 3, centerVertex[1]);
- vtkTransformMatrix->SetElement(2, 3, centerVertex[2]);
-
- vtkSmartPointer<vtkGeneralTransform> transform = vtkSmartPointer<vtkGeneralTransform>::New();
- transform->Concatenate(vtkTransformMatrix);
- // transform->Translate(centerVertex[0],centerVertex[1],centerVertex[2]);
-
- transform->Inverse();
- transform->Update();
-
- // Generate plane in center [0,0,0] with n= (0,1,0) as normal vector
- vtkSmartPointer<vtkPlane> plane = vtkSmartPointer<vtkPlane>::New();
- plane->SetOrigin(0, 0, 0);
- plane->SetNormal(0, 1, 0);
-
- // Generate a cylinder in center [0,0,0] and the axes of rotation is along the y-axis; radius is vertex diameter/2;
- vtkSmartPointer<vtkCylinder> cylinder = vtkSmartPointer<vtkCylinder>::New();
- cylinder->SetCenter(0, 0, 0);
- cylinder->SetRadius(cylinderDiameter / 2);
- // cylinder->SetTransform(transform);
-
- // Truncate the infinite cylinder with the plane
- vtkSmartPointer<vtkImplicitBoolean> cutCylinder = vtkSmartPointer<vtkImplicitBoolean>::New();
- cutCylinder->SetOperationTypeToDifference();
- cutCylinder->SetTransform(transform);
- cutCylinder->AddFunction(cylinder);
- cutCylinder->AddFunction(plane);
-
- cylinderForClipping.insert(
- std::pair<TubeGraph::TubeDescriptorType, vtkSmartPointer<vtkImplicitBoolean>>(tube, cutCylinder));
-
- //// Sample the function
- // vtkSmartPointer<vtkSampleFunction> sample = vtkSmartPointer<vtkSampleFunction>::New();
- // sample->SetSampleDimensions(100,100,100);
- // sample->SetImplicitFunction(cutCylinder);
- ////double value = 200.0;
- // double xmin = centerVertex[0]-(2*diameter), xmax = centerVertex[0]+(2*diameter),
- // ymin = centerVertex[1]-(2*diameter), ymax = centerVertex[1]+(2*diameter),
- // zmin = centerVertex[2]-(2*diameter), zmax = centerVertex[2]+(2*diameter);
- // sample->SetModelBounds(xmin, xmax, ymin, ymax, zmin, zmax);
-
- // vtkSmartPointer<vtkContourFilter> contour =vtkSmartPointer<vtkContourFilter>::New();
- // contour->SetInputConnection(sample->GetOutputPort());
- // contour->SetValue( 0, 0.25);
-
- // vtkSmartPointer<vtkPolyDataMapper> impMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
- // impMapper->SetInputConnection (contour->GetOutputPort());
- // impMapper->ScalarVisibilityOff();
- // vtkSmartPointer<vtkActor> impActor = vtkSmartPointer<vtkActor>::New();
- // impActor->SetMapper(impMapper);
-
- // ls->m_vtkTubeGraphAssembly->AddPart(impActor);
- }
-
- double sphereColorR = 0;
- double sphereColorG = 0;
- double sphereColorB = 0;
-
- for (auto itClipStructure =
- cylinderForClipping.begin();
- itClipStructure != cylinderForClipping.end();
- itClipStructure++)
- {
- vtkSmartPointer<vtkPolyDataMapper> sphereMapper =
- dynamic_cast<vtkPolyDataMapper *>(ls->m_vtkSpheresActorMap[vertexDesc]->GetMapper());
-
- if (sphereMapper != nullptr)
- {
- // first clip the sphere with the cylinder
- vtkSmartPointer<vtkClipPolyData> clipperSphere = vtkSmartPointer<vtkClipPolyData>::New();
- clipperSphere->SetInputData(sphereMapper->GetInput());
- clipperSphere->SetClipFunction(itClipStructure->second);
- clipperSphere->GenerateClippedOutputOn();
- clipperSphere->Update();
-
- sphereMapper->SetInputConnection(clipperSphere->GetOutputPort());
- sphereMapper->Update();
- }
-
- mitk::Color tubeColor = graphProperty->GetColorOfTube(itClipStructure->first);
- sphereColorR += tubeColor[0];
- sphereColorG += tubeColor[1];
- sphereColorB += tubeColor[2];
-
- // than clip with all other tubes
- for (auto itTobBeClipped =
- cylinderForClipping.begin();
- itTobBeClipped != cylinderForClipping.end();
- itTobBeClipped++)
- {
- TubeGraph::TubeDescriptorType toBeClippedTube = itTobBeClipped->first;
-
- if (itClipStructure->first != toBeClippedTube)
- {
- vtkSmartPointer<vtkPolyDataMapper> tubeMapper =
- dynamic_cast<vtkPolyDataMapper *>(ls->m_vtkTubesActorMap[toBeClippedTube]->GetMapper());
-
- if (tubeMapper != nullptr)
- {
- // first clip the sphere with the cylinder
- vtkSmartPointer<vtkClipPolyData> clipperTube = vtkSmartPointer<vtkClipPolyData>::New();
- tubeMapper->Update();
- clipperTube->SetInputData(tubeMapper->GetInput());
- clipperTube->SetClipFunction(itClipStructure->second);
- clipperTube->GenerateClippedOutputOn();
- clipperTube->Update();
-
- tubeMapper->SetInputConnection(clipperTube->GetOutputPort());
- tubeMapper->Update();
- }
- }
- }
- }
- if (cylinderForClipping.size() != 0)
- {
- sphereColorR /= 255 * cylinderForClipping.size();
- sphereColorG /= 255 * cylinderForClipping.size();
- sphereColorB /= 255 * cylinderForClipping.size();
- }
-
- ls->m_vtkSpheresActorMap[vertexDesc]->GetProperty()->SetColor(sphereColorR, sphereColorG, sphereColorB);
-}
-
-bool mitk::TubeGraphVtkMapper3D::ClipStructures()
-{
- DataNode::Pointer node = this->GetDataNode();
- if (node.IsNull())
- {
- itkWarningMacro(<< "associated node is nullptr!");
- return false;
- }
-
- bool clipStructures = false;
- node->GetBoolProperty("Tube Graph.Clip Structures", clipStructures);
-
- return clipStructures;
-}
diff --git a/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.h b/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.h
index fff4ca6245..462d062cbb 100644
--- a/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.h
+++ b/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.h
@@ -1,89 +1,89 @@
/*============================================================================
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 QmitkUSDeviceManagerWidget_h
#define QmitkUSDeviceManagerWidget_h
#include "MitkUSUIExports.h"
#include "ui_QmitkUSDeviceManagerWidgetControls.h"
#include "mitkUSDevice.h"
#include <vector>
//QT headers
#include <QWidget>
#include <QListWidgetItem>
/**
* @brief This Widget is used to manage available Ultrasound Devices.
*
* It allows activation, deactivation and disconnection of connected devices.
*
* @ingroup USUI
*/
class MITKUSUI_EXPORT QmitkUSDeviceManagerWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkUSDeviceManagerWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkUSDeviceManagerWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkUSDeviceManagerWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
/* @brief Disconnects all devices immediately. */
virtual void DisconnectAllDevices();
signals:
void NewDeviceButtonClicked();
void EditDeviceButtonClicked(mitk::USDevice::Pointer);
/* This signal is emitted if a device is activated. */
void DeviceActivated();
public slots:
protected slots :
/*
\brief Called, when the button "Activate Device" was clicked.
*/
void OnClickedActivateDevice();
/*
\brief Called, when the button "Disconnect Device" was clicked.
*/
void OnClickedDisconnectDevice();
void OnClickedRemoveDevice();
void OnClickedNewDevice();
void OnClickedEditDevice();
/*
\brief Called, when the selection in the devicelist changes.
*/
void OnDeviceSelectionChanged(us::ServiceReferenceU reference);
protected:
Ui::QmitkUSDeviceManagerWidgetControls* m_Controls; ///< member holding the UI elements of this widget
private:
};
#endif
diff --git a/Modules/USUI/Qmitk/QmitkUSNewVideoDeviceWidget.h b/Modules/USUI/Qmitk/QmitkUSNewVideoDeviceWidget.h
index 91df35f175..2adebac4f0 100644
--- a/Modules/USUI/Qmitk/QmitkUSNewVideoDeviceWidget.h
+++ b/Modules/USUI/Qmitk/QmitkUSNewVideoDeviceWidget.h
@@ -1,165 +1,165 @@
/*============================================================================
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 QmitkUSNewVideoDeviceWidget_h
#define QmitkUSNewVideoDeviceWidget_h
#include "MitkUSUIExports.h"
#include "ui_QmitkUSNewVideoDeviceWidgetControls.h"
#include "mitkUSVideoDevice.h"
#include "mitkUSIGTLDevice.h"
#include "mitkUSDeviceReaderXML.h"
//QT headers
#include <QWidget>
#include <QListWidgetItem>
//mitk header
/**
* @brief This Widget enables the USer to create and connect Video Devices.
*
* @ingroup USUI
*/
class MITKUSUI_EXPORT QmitkUSNewVideoDeviceWidget :public QWidget
{
//this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
Q_OBJECT
public:
static const std::string VIEW_ID;
- QmitkUSNewVideoDeviceWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = nullptr);
+ QmitkUSNewVideoDeviceWidget(QWidget* p = nullptr, Qt::WindowFlags f1 = {});
~QmitkUSNewVideoDeviceWidget() override;
/* @brief This method is part of the widget an needs not to be called seperately. */
virtual void CreateQtPartControl(QWidget *parent);
/* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/
virtual void CreateConnections();
signals:
void Finished();
public slots:
/*
\brief Activates the widget and displays the given device's Data to edit.
*/
void EditDevice(mitk::USDevice::Pointer device);
/*
\brief Activates the widget with fields empty.
*/
void CreateNewDevice();
protected slots:
/*
\brief Called, when the the user clicks the "Done" button (Labeled either "Add Device" or "Edit Device", depending on the situation.
*/
void OnClickedDone();
void OnClickedFinishedEditing();
/*
\brief Called, when the button "Cancel" was clicked
*/
void OnClickedCancel();
/*
\brief Called, when the Use selects one of the Radiobuttons
*/
void OnDeviceTypeSelection();
void OnOpenFileButtonClicked();
void OnClickedRemoveProbe();
void OnClickedRemoveDepth();
void OnClickedAddDepths();
void OnProbeChanged(const QString & probename);
void OnDepthChanged(int depth, mitk::USProbe::Pointer probe);
void OnDepthChanged(const QString &depth);
void OnSaveButtonClicked();
void OnLoadConfigurationButtonClicked();
void OnAddNewProbeClicked();
void OnXSpacingSpinBoxChanged(double value);
void OnYSpacingSpinBoxChanged(double value);
void OnCroppingTopSpinBoxChanged(int value);
void OnCroppingRightSpinBoxChanged(int value);
void OnCroppingBottomSpinBoxChanged(int value);
void OnCroppingLeftSpinBoxChanged(int value);
protected:
Ui::QmitkUSNewVideoDeviceWidgetControls* m_Controls; ///< member holding the UI elements of this widget
/*
\brief Constructs a ListItem from the given device for display in the list of active devices
*/
QListWidgetItem* ConstructItemFromDevice(mitk::USDevice::Pointer device);
void ChangeUIEditingUSVideoDevice();
void CleanUpAfterEditingOfDevice();
void CleanUpAfterCreatingNewDevice();
void AddProbesToDevice(mitk::USDevice::Pointer device);
mitk::USProbe::Pointer CheckIfProbeExistsAlready(const std::string &probe);
void CollectUltrasoundDeviceConfigInformation(mitk::USDeviceReaderXML::USDeviceConfigData &config);
/**
* \brief Enables or disables the GUI elements of the spacing and cropping options.
* \param enable If true: the GUI elements are enabled. If false: elements are disabled.
*/
void EnableDisableSpacingAndCropping(bool enable);
/*
\brief Displays whether this widget is active or not. It gets activated by either sending a Signal to
* the "CreateNewDevice" Slot or to the "EditDevice" Slot. If the user finishes editing the device, a
* "EditingComplete" Signal is sent, and the widget is set to inactive again. Clicking Cancel also
* deactivates it.
*/
bool m_Active;
/**
* \brief This is the device to edit. It is either the device transmitted in the "EditDevice" signal, or a new one
* if the "CreateNewDevice slot was called. As device type: either mitkUSVideoDevice or mitkUSIGTLDevice
*/
mitk::USDevice::Pointer m_TargetDevice;
/**
* \brief The config probes are used to have a possibility to configure ultrasound probes without having an existing
* created USVideoDevice yet.
*/
std::vector<mitk::USProbe::Pointer> m_ConfigProbes;
};
#endif
diff --git a/Modules/XNAT/CMakeLists.txt b/Modules/XNAT/CMakeLists.txt
index 467e78c28e..df26e50214 100644
--- a/Modules/XNAT/CMakeLists.txt
+++ b/Modules/XNAT/CMakeLists.txt
@@ -1,6 +1,6 @@
MITK_CREATE_MODULE(
DEPENDS MitkCore MitkQtWidgets
PACKAGE_DEPENDS
PUBLIC CTK|CTKXNATCore
- PRIVATE Qt5|UiTools+XmlPatterns+Widgets
+ PRIVATE Qt6|UiTools+Xml+Widgets
)
diff --git a/Modules/XNAT/src/QmitkXnatTreeModel.cpp b/Modules/XNAT/src/QmitkXnatTreeModel.cpp
index deb1309bc4..65fe4a215d 100644
--- a/Modules/XNAT/src/QmitkXnatTreeModel.cpp
+++ b/Modules/XNAT/src/QmitkXnatTreeModel.cpp
@@ -1,310 +1,321 @@
/*============================================================================
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 "QmitkXnatTreeModel.h"
#include <QmitkHttpStatusCodeHandler.h>
#include <QmitkMimeTypes.h>
#include <QIcon>
+#include <QRegularExpression>
#include <ctkXnatDataModel.h>
#include <ctkXnatExperiment.h>
#include <ctkXnatFile.h>
#include <ctkXnatProject.h>
#include <ctkXnatResource.h>
#include <ctkXnatResourceCatalogXmlParser.h>
#include <ctkXnatResourceFolder.h>
#include <ctkXnatScan.h>
#include <ctkXnatScanFolder.h>
#include <ctkXnatSubject.h>
#include <iostream>
QmitkXnatTreeModel::QmitkXnatTreeModel() : ctkXnatTreeModel()
{
}
QModelIndexList QmitkXnatTreeModel::match(
const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const
{
QModelIndexList result;
- uint matchType = flags & 0x0F;
- Qt::CaseSensitivity cs = flags & Qt::MatchCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive;
+ uint matchType = flags & Qt::MatchTypeMask;
+ Qt::CaseSensitivity cs = flags.testFlag(Qt::MatchCaseSensitive)
+ ? Qt::CaseSensitive
+ : Qt::CaseInsensitive;
bool recurse = flags & Qt::MatchRecursive;
bool wrap = flags & Qt::MatchWrap;
bool allHits = (hits == -1);
QString text; // only convert to a string if it is needed
QModelIndex p = parent(start);
int from = start.row();
int to = rowCount(p);
// iterates twice if wrapping
for (int i = 0; (wrap && i < 2) || (!wrap && i < 1); ++i)
{
for (int r = from; (r < to) && (allHits || result.count() < hits); ++r)
{
QModelIndex idx = index(r, start.column(), p);
if (!idx.isValid())
continue;
QVariant v = data(idx, role);
// QVariant based matching
if (matchType == Qt::MatchExactly)
{
if (value != v)
result.append(idx);
}
else
{ // QString based matching
if (text.isEmpty()) // lazy conversion
text = value.toString();
QString t = v.toString();
switch (matchType)
{
- case Qt::MatchRegExp:
- if (!QRegExp(text, cs).exactMatch(t))
+ case Qt::MatchRegularExpression:
+ {
+ QRegularExpression::PatternOptions options;
+ options.setFlag(QRegularExpression::CaseInsensitiveOption, !flags.testFlag(Qt::MatchCaseSensitive));
+ QRegularExpression regExp(QString("^%1$").arg(text), options);
+ if (!regExp.match(t).hasMatch())
result.append(idx);
break;
+ }
case Qt::MatchWildcard:
- if (!QRegExp(text, cs, QRegExp::Wildcard).exactMatch(t))
+ {
+ auto regExp = QRegularExpression::fromWildcard(text, cs);
+ if (!regExp.match(t).hasMatch())
result.append(idx);
break;
+ }
case Qt::MatchStartsWith:
if (!t.startsWith(text, cs))
result.append(idx);
break;
case Qt::MatchEndsWith:
if (!t.endsWith(text, cs))
result.append(idx);
break;
case Qt::MatchFixedString:
if (t.compare(text, cs) != 0)
result.append(idx);
break;
case Qt::MatchContains:
default:
if (!t.contains(text, cs))
result.append(idx);
}
}
if (recurse && hasChildren(idx))
{ // search the hierarchy
result += match(index(0, idx.column(), idx),
role,
(text.isEmpty() ? value : text),
(allHits ? -1 : hits - result.count()),
flags);
}
}
// prepare for the next iteration
from = 0;
to = start.row();
}
return result;
}
void QmitkXnatTreeModel::fetchMore(const QModelIndex &index)
{
try
{
ctkXnatTreeModel::fetchMore(index);
}
catch (const ctkRuntimeException& e)
{
QmitkHttpStatusCodeHandler::HandleErrorMessage(e.what());
emit Error(index);
}
}
QVariant QmitkXnatTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
{
return QVariant();
}
if (role == Qt::DecorationRole)
{
ctkXnatObject *xnatObject = this->xnatObject(index);
QString path;
if (dynamic_cast<ctkXnatDataModel *>(xnatObject))
{
path = ":/xnat-module/xnat-server.png";
}
else if (dynamic_cast<ctkXnatProject *>(xnatObject))
{
path = ":/xnat-module/xnat-project.png";
}
else if (dynamic_cast<ctkXnatSubject *>(xnatObject))
{
path = ":/xnat-module/xnat-subject.png";
}
else if (dynamic_cast<ctkXnatExperiment *>(xnatObject))
{
path = ":/xnat-module/xnat-experiment.png";
}
else if (dynamic_cast<ctkXnatResourceFolder *>(xnatObject))
{
path = ":/xnat-module/xnat-folder.png";
}
else if (dynamic_cast<ctkXnatResource *>(xnatObject))
{
path = ":/xnat-module/xnat-resource.png";
}
else if (dynamic_cast<ctkXnatScanFolder *>(xnatObject))
{
path = ":/xnat-module/xnat-folder.png";
}
else if (dynamic_cast<ctkXnatScan *>(xnatObject))
{
path = ":/xnat-module/xnat-scan.png";
}
else if (dynamic_cast<ctkXnatFile *>(xnatObject))
{
path = ":/xnat-module/xnat-file.png";
}
return QIcon(path);
}
return ctkXnatTreeModel::data(index, role);
}
bool QmitkXnatTreeModel::dropMimeData(
const QMimeData *data, Qt::DropAction action, int /*row*/, int /*column*/, const QModelIndex &parent)
{
if (action == Qt::IgnoreAction)
return true;
// Return true if data can be handled
bool returnVal(false);
if (data->hasFormat(QmitkMimeTypes::DataNodePtrs))
{
returnVal = true;
QList<mitk::DataNode *> droppedNodes = QmitkMimeTypes::ToDataNodePtrList(data);
ctkXnatObject *parentXnatObj = this->xnatObject(parent);
emit ResourceDropped(droppedNodes, parentXnatObj, parent);
}
return returnVal;
}
Qt::DropActions QmitkXnatTreeModel::supportedDropActions()
{
return Qt::CopyAction;
}
Qt::ItemFlags QmitkXnatTreeModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags defaultFlags = ctkXnatTreeModel::flags(index);
if (index.isValid())
{
bool droppingAllowed = dynamic_cast<ctkXnatSubject *>(this->xnatObject(index)) != nullptr;
droppingAllowed |= dynamic_cast<ctkXnatExperiment *>(this->xnatObject(index)) != nullptr;
droppingAllowed |= dynamic_cast<ctkXnatResource *>(this->xnatObject(index)) != nullptr;
droppingAllowed |= dynamic_cast<ctkXnatResourceFolder *>(this->xnatObject(index)) != nullptr;
// No dropping at project, session or data model level allowed
if (droppingAllowed)
{
return Qt::ItemIsDropEnabled | defaultFlags;
}
else
{
return defaultFlags;
}
}
else
return defaultFlags;
}
ctkXnatObject *QmitkXnatTreeModel::InternalGetXnatObjectFromUrl(const QString &xnatObjectType,
const QString &url,
ctkXnatObject *parent)
{
// 1. Find project
int start = url.lastIndexOf(xnatObjectType);
if (start == -1)
return nullptr;
start += xnatObjectType.length();
parent->fetch();
QList<ctkXnatObject *> children = parent->children();
foreach (ctkXnatObject *child, children)
{
if (url.indexOf(child->resourceUri()) != -1)
{
return child;
}
}
return nullptr;
}
ctkXnatObject *QmitkXnatTreeModel::GetXnatObjectFromUrl(const QString &url)
{
QModelIndex index = this->index(0, 0, QModelIndex());
ctkXnatObject *currentXnatObject = nullptr;
currentXnatObject = this->xnatObject(index);
if (currentXnatObject != nullptr)
{
// 1. Find project
ctkXnatObject *project = nullptr;
project = this->InternalGetXnatObjectFromUrl("projects/", url, currentXnatObject);
// 2. Find subject
ctkXnatObject *subject = nullptr;
if (project != nullptr)
{
currentXnatObject = project;
subject = this->InternalGetXnatObjectFromUrl("subjects/", url, project);
}
// 3. Find experiment
ctkXnatObject *experiment = nullptr;
if (subject != nullptr)
{
currentXnatObject = subject;
experiment = this->InternalGetXnatObjectFromUrl("experiments/", url, subject);
}
// 4. Find scan
ctkXnatObject *scan = nullptr;
if (experiment != nullptr)
{
currentXnatObject = experiment;
scan = this->InternalGetXnatObjectFromUrl("scans/", url, experiment);
}
if (scan != nullptr)
{
scan->fetch();
QList<ctkXnatObject *> scans = scan->children();
foreach (ctkXnatObject *child, scans)
{
if (url.indexOf(child->resourceUri()) != -1)
{
return child;
}
}
}
currentXnatObject->fetch();
QList<ctkXnatObject *> bla = currentXnatObject->children();
foreach (ctkXnatObject *child, bla)
{
if (child->name() == "Resources")
return child;
}
}
return nullptr;
}
diff --git a/Plugins/PluginList.cmake b/Plugins/PluginList.cmake
index 231542bd9e..4e73a65a56 100644
--- a/Plugins/PluginList.cmake
+++ b/Plugins/PluginList.cmake
@@ -1,84 +1,76 @@
# 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.mitk.core.services:ON
org.mitk.gui.common:ON
org.mitk.core.jobs:OFF
org.mitk.gui.qt.application:ON
org.mitk.gui.qt.ext:OFF
org.mitk.gui.qt.extapplication:OFF
org.mitk.gui.qt.mitkworkbench.intro:OFF
org.mitk.gui.qt.common:ON
org.mitk.gui.qt.stdmultiwidgeteditor:ON
org.mitk.gui.qt.mxnmultiwidgeteditor: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.dicombrowser: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.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.deformableclippingplane: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.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.overlaymanager:OFF
org.mitk.gui.qt.igt.app.hummelprotocolmeasurements: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.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.concentration.mri:OFF
org.mitk.gui.qt.pharmacokinetics.curvedescriptor: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.flowapplication:OFF
org.mitk.gui.qt.flow.segmentation:OFF
org.mitk.gui.qt.pixelvalue:ON
)
diff --git a/Plugins/org.blueberry.core.commands/src/berryCommand.cpp b/Plugins/org.blueberry.core.commands/src/berryCommand.cpp
index a1da140043..722a2e26b1 100644
--- a/Plugins/org.blueberry.core.commands/src/berryCommand.cpp
+++ b/Plugins/org.blueberry.core.commands/src/berryCommand.cpp
@@ -1,555 +1,555 @@
/*============================================================================
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 "berryCommand.h"
#include "berryIParameter.h"
#include "berryITypedParameter.h"
#include "berryIHandler.h"
#include "berryIHandlerListener.h"
#include "berryIParameterValueConverter.h"
#include "berryHandlerEvent.h"
#include "berryCommandEvent.h"
#include "berryExecutionEvent.h"
#include "berryCommandCategory.h"
#include "berryState.h"
#include "util/berryCommandTracing.h"
#include "internal/berryCommandUtils.h"
#include <QTextStream>
namespace berry {
bool Command::DEBUG_COMMAND_EXECUTION = false;
bool Command::DEBUG_HANDLERS = false;
-QString Command::DEBUG_HANDLERS_COMMAND_ID = QString::null;
+QString Command::DEBUG_HANDLERS_COMMAND_ID = QString();
Command::Command(const QString& id)
: NamedHandleObjectWithState(id)
{
}
void Command::AddCommandListener(ICommandListener* commandListener)
{
if (!commandListener)
{
throw ctkInvalidArgumentException("Cannot add a null command listener");
}
commandEvents.AddListener(commandListener);
}
void Command::AddExecutionListener(IExecutionListener* executionListener)
{
if (!executionListener)
{
throw ctkInvalidArgumentException("Cannot add a null execution listener");
}
executionEvents.AddListener(executionListener);
}
void Command::AddState(const QString& id, const State::Pointer& state)
{
NamedHandleObjectWithState::AddState(id, state);
state->SetId(id);
if (IObjectWithState::Pointer stateHandler = handler.Cast<IObjectWithState>())
{
stateHandler->AddState(id, state);
}
}
bool Command::operator<(const Object* object) const
{
const Command* castedObject = dynamic_cast<const Command*>(object);
int compareTo = CommandUtils::CompareObj(category, castedObject->category);
if (compareTo == 0)
{
compareTo = CommandUtils::Compare(defined, castedObject->defined);
if (compareTo == 0)
{
compareTo = CommandUtils::Compare(description, castedObject->description);
if (compareTo == 0)
{
compareTo = CommandUtils::CompareObj(handler, castedObject->handler);
if (compareTo == 0)
{
compareTo = CommandUtils::Compare(id, castedObject->id);
if (compareTo == 0)
{
compareTo = CommandUtils::Compare(name, castedObject->name);
if (compareTo == 0)
{
compareTo = CommandUtils::Compare(parameters,
castedObject->parameters);
}
}
}
}
}
}
return compareTo < 0;
}
void Command::Define(const QString& name, const QString& description,
const CommandCategory::Pointer category,
const QList<IParameter::Pointer>& parameters,
const ParameterType::Pointer& returnType,
const QString& helpContextId)
{
if (name == "")
{
throw ctkInvalidArgumentException("The name of a command cannot be empty");
}
if (!category)
{
throw ctkInvalidArgumentException("The category of a command cannot be null");
}
const bool definedChanged = !this->defined;
this->defined = true;
const bool nameChanged = this->name != name;
this->name = name;
const bool descriptionChanged = this->description != description;
this->description = description;
const bool categoryChanged = this->category != category;
this->category = category;
const bool parametersChanged = !CommandUtils::Equals(this->parameters,
parameters);
this->parameters = parameters;
const bool returnTypeChanged = this->returnType != returnType;
this->returnType = returnType;
const bool helpContextIdChanged = this->helpContextId != helpContextId;
this->helpContextId = helpContextId;
CommandEvent::Pointer event(new CommandEvent(Command::Pointer(this), categoryChanged,
definedChanged, descriptionChanged, false, nameChanged,
parametersChanged, returnTypeChanged, helpContextIdChanged));
this->FireCommandChanged(event);
}
Object::Pointer Command::ExecuteWithChecks(const ExecutionEvent::ConstPointer event)
{
this->FirePreExecute(event);
const IHandler::Pointer handler(this->handler);
if (!this->IsDefined())
{
const NotDefinedException exception(
"Trying to execute a command that is not defined. " + this->GetId());
this->FireNotDefined(&exception);
throw exception;
}
// Perform the execution, if there is a handler.
if (handler && handler->IsHandled())
{
this->SetEnabled(event->GetApplicationContext());
if (!this->IsEnabled()) {
const NotEnabledException exception(
"Trying to execute the disabled command " + this->GetId());
this->FireNotEnabled(&exception);
throw exception;
}
try
{
const Object::Pointer returnValue(handler->Execute(event));
this->FirePostExecuteSuccess(returnValue);
return returnValue;
}
catch (const ExecutionException* e)
{
this->FirePostExecuteFailure(e);
throw e;
}
}
const NotHandledException e(
"There is no handler to execute for command " + this->GetId());
this->FireNotHandled(&e);
throw e;
}
void Command::FireCommandChanged(const CommandEvent::ConstPointer commandEvent)
{
if (!commandEvent)
{
throw ctkInvalidArgumentException("Cannot fire a null event");
}
try
{
commandEvents.commandChanged(commandEvent);
}
catch (...)
{
//TODO log exceptions?
}
}
void Command::FireNotDefined(const NotDefinedException* e)
{
// Debugging output
if (DEBUG_COMMAND_EXECUTION)
{
CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR
+ "not defined: id=" + this->GetId() + "; exception=" + e->what());
}
executionEvents.notDefined(this->GetId(), e);
}
void Command::FireNotEnabled(const NotEnabledException* e)
{
// Debugging output
if (DEBUG_COMMAND_EXECUTION)
{
CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR
+ "not enabled: id=" + this->GetId() + "; exception=" + e->what());
}
executionEvents.notEnabled(this->GetId(), e);
}
void Command::FireNotHandled(const NotHandledException* e)
{
// Debugging output
if (DEBUG_COMMAND_EXECUTION) {
CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR
+ "not handled: id=" + this->GetId() + "; exception=" + e->what());
}
executionEvents.notHandled(this->GetId(), e);
}
void Command::FirePostExecuteFailure(const ExecutionException* e)
{
// Debugging output
if (DEBUG_COMMAND_EXECUTION)
{
CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR
+ "failure: id=" + this->GetId() + "; exception=" + e->what());
}
executionEvents.postExecuteFailure(this->GetId(), e);
}
void Command::FirePostExecuteSuccess(const Object::Pointer returnValue)
{
// Debugging output
if (DEBUG_COMMAND_EXECUTION)
{
CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR
+ "success: id=" + this->GetId() + "; returnValue=" +
(returnValue.IsNull() ? QString("nullptr") : returnValue->ToString()));
}
executionEvents.postExecuteSuccess(this->GetId(), returnValue);
}
void Command::FirePreExecute(const ExecutionEvent::ConstPointer event)
{
// Debugging output
if (DEBUG_COMMAND_EXECUTION)
{
CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR
+ "starting: id=" + this->GetId() + "; event=" + event->ToString());
}
executionEvents.preExecute(this->GetId(), event);
}
IHandler::Pointer Command::GetHandler() const
{
return handler;
}
QString Command::GetHelpContextId() const
{
return helpContextId;
}
IParameter::Pointer Command::GetParameter(const QString& parameterId) const
{
if (!this->IsDefined())
{
throw NotDefinedException(
"Cannot get a parameter from an undefined command. " + id);
}
for (int i = 0; i < parameters.size(); i++)
{
IParameter::Pointer parameter(parameters[i]);
if (parameter->GetId() == parameterId) {
return parameter;
}
}
return IParameter::Pointer(nullptr);
}
QList<SmartPointer<IParameter> > Command::GetParameters() const
{
if (!this->IsDefined())
{
throw NotDefinedException(
"Cannot get the parameters from an undefined command. " + id);
}
return parameters;
}
ParameterType::Pointer Command::GetParameterType(const QString& parameterId) const
{
const IParameter::Pointer parameter(this->GetParameter(parameterId));
if (ITypedParameter::Pointer parameterWithType = parameter.Cast<ITypedParameter>())
{
return parameterWithType->GetParameterType();
}
return ParameterType::Pointer(nullptr);
}
ParameterType::Pointer Command::GetReturnType() const
{
if (!this->IsDefined())
{
throw NotDefinedException(
"Cannot get the return type of an undefined command. " + id);
}
return returnType;
}
bool Command::IsEnabled() const
{
if (!handler)
{
return false;
}
return handler->IsEnabled();
}
void Command::SetEnabled(const Object::Pointer& evaluationContext)
{
if (handler)
{
handler->SetEnabled(evaluationContext);
}
}
bool Command::IsHandled() const
{
if (!handler)
{
return false;
}
return handler->IsHandled();
}
void Command::RemoveCommandListener(ICommandListener *commandListener)
{
if (!commandListener)
{
throw ctkInvalidArgumentException(
"Cannot remove a null command listener");
}
commandEvents.RemoveListener(commandListener);
}
/**
* Removes a listener from this command.
*
* @param executionListener
* The listener to be removed; must not be <code>null</code>.
*
*/
void Command::RemoveExecutionListener(IExecutionListener* executionListener)
{
if (!executionListener)
{
throw Poco::NullPointerException(
"Cannot remove a null execution listener");
}
executionEvents.RemoveListener(executionListener);
}
void Command::RemoveState(const QString& stateId)
{
if (IObjectWithState::Pointer stateHandler = handler.Cast<IObjectWithState>())
{
stateHandler->RemoveState(stateId);
}
NamedHandleObjectWithState::RemoveState(stateId);
}
bool Command::SetHandler(const IHandler::Pointer handler)
{
if (handler == this->handler)
{
return false;
}
// Swap the state around.
const QList<QString> stateIds(this->GetStateIds());
for (int i = 0; i < stateIds.size(); ++i)
{
const QString stateId = stateIds[i];
if (IObjectWithState::Pointer stateHandler = this->handler.Cast<IObjectWithState>())
{
stateHandler->RemoveState(stateId);
}
if (IObjectWithState::Pointer stateHandler = handler.Cast<IObjectWithState>())
{
const State::Pointer stateToAdd(this->GetState(stateId));
stateHandler->AddState(stateId, stateToAdd);
}
}
bool enabled = this->IsEnabled();
if (this->handler)
{
this->handler->RemoveHandlerListener(this->GetHandlerListener());
}
// Update the handler, and flush the string representation.
this->handler = handler;
if (this->handler)
{
this->handler->AddHandlerListener(this->GetHandlerListener());
}
this->str = "";
// Debugging output
if ((DEBUG_HANDLERS)
&& ((DEBUG_HANDLERS_COMMAND_ID.isEmpty()) || (DEBUG_HANDLERS_COMMAND_ID == id)))
{
QString buffer("Command('");
buffer += id + "') has changed to ";
if (!handler) {
buffer += "no handler";
} else {
buffer += "\'" + handler->ToString() + "' as its handler";
}
CommandTracing::PrintTrace("HANDLERS", buffer);
}
// Send notification
CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), false, false, false, true,
false, false, false, false, enabled != this->IsEnabled()));
this->FireCommandChanged(cmdEvent);
return true;
}
IHandlerListener* Command::GetHandlerListener()
{
return this;
}
void Command::HandlerChanged(const SmartPointer<HandlerEvent>& handlerEvent)
{
bool enabledChanged = handlerEvent->IsEnabledChanged();
bool handledChanged = handlerEvent->IsHandledChanged();
CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), false,
false, false, handledChanged, false, false, false,
false, enabledChanged));
this->FireCommandChanged(cmdEvent);
}
QString Command::ToString() const
{
if (str.isEmpty())
{
QTextStream buffer(&str);
buffer << "Command(" << id << ',' << name << ",\n\t\t";
buffer << description << ",\n\t\t" << (category ? category->ToString() : QString(""));
buffer << ",\n\t\t" << (handler ? handler->ToString() : "");
buffer << ",\n\t\t" << "[";
for (int i = 0; i < parameters.size(); ++i)
{
buffer << parameters[i]->GetId();
}
buffer << "]," << (returnType ? returnType->ToString() : "");
buffer << "," << defined << ")";
}
return str;
}
void Command::Undefine()
{
bool enabledChanged = this->IsEnabled();
str = "";
const bool definedChanged = defined;
defined = false;
const bool nameChanged = !name.isEmpty();
name = "";
const bool descriptionChanged = !description.isEmpty();
description = "";
const bool categoryChanged = category;
category = nullptr;
const bool parametersChanged = !parameters.empty();
parameters.clear();
const bool returnTypeChanged = returnType;
returnType = nullptr;
const QList<QString> stateIds(this->GetStateIds());
if (IObjectWithState::Pointer handlerWithState = handler.Cast<IObjectWithState>())
{
for (int i = 0; i < stateIds.size(); i++)
{
const QString stateId(stateIds[i]);
handlerWithState->RemoveState(stateId);
const State::Pointer state(this->GetState(stateId));
this->RemoveState(stateId);
//state.dispose();
}
}
else
{
for (int i = 0; i < stateIds.size(); ++i)
{
const QString stateId(stateIds[i]);
const State::Pointer state(this->GetState(stateId));
this->RemoveState(stateId);
//state.dispose();
}
}
CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), categoryChanged,
definedChanged, descriptionChanged, false, nameChanged,
parametersChanged, returnTypeChanged, false, enabledChanged));
this->FireCommandChanged(cmdEvent);
}
}
diff --git a/Plugins/org.blueberry.core.runtime/CMakeLists.txt b/Plugins/org.blueberry.core.runtime/CMakeLists.txt
index 8c5c528849..8048d6f423 100644
--- a/Plugins/org.blueberry.core.runtime/CMakeLists.txt
+++ b/Plugins/org.blueberry.core.runtime/CMakeLists.txt
@@ -1,18 +1,18 @@
project(org_blueberry_core_runtime)
mitk_create_plugin(
EXPORT_DIRECTIVE org_blueberry_core_runtime_EXPORT
EXPORTED_INCLUDE_SUFFIXES
src
src/application
src/dynamichelpers
src/registry
MODULE_DEPENDS PUBLIC MitkCore
PACKAGE_DEPENDS
PUBLIC Poco|Foundation+Util+XML
- PRIVATE Qt5|Gui+Xml
+ PRIVATE Qt6|Gui+Xml
)
target_compile_definitions(${PLUGIN_TARGET} PUBLIC "$<$<PLATFORM_ID:Windows>:WIN32_LEAN_AND_MEAN>")
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/src/berryConfig.h.in" "${CMAKE_CURRENT_BINARY_DIR}/berryConfig.h" @ONLY)
diff --git a/Plugins/org.blueberry.core.runtime/src/berryDebugUtil.cpp b/Plugins/org.blueberry.core.runtime/src/berryDebugUtil.cpp
index 7aadca18ea..0fc0e56205 100755
--- a/Plugins/org.blueberry.core.runtime/src/berryDebugUtil.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/berryDebugUtil.cpp
@@ -1,537 +1,537 @@
/*============================================================================
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 "berryIDebugObjectListener.h"
#include "berryDebugUtil.h"
#include "berryObject.h"
#include "berryLog.h"
#include "berryPlatform.h"
#include "berryDebugBreakpointManager.h"
#include "internal/berryCTKPluginActivator.h"
#include <QDir>
#include <QDebug>
#include <Poco/Bugcheck.h>
#include <Poco/NumberParser.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Document.h>
#include <Poco/DOM/Element.h>
#include <Poco/DOM/DOMWriter.h>
#include <Poco/SAX/InputSource.h>
#include <Poco/SAX/SAXException.h>
#include <Poco/FileStream.h>
#include <sstream>
#include <numeric>
namespace berry
{
static IDebugObjectListener::Events _G_ObjectEvents;
const QString DebugUtil::DEBUG_UTIL_XML = "debugutil.xml";
const QString DebugUtil::DEBUGUTIL_TAG = "debugutil";
const QString DebugUtil::TRACEOBJECT_TAG = "traceObject";
const QString DebugUtil::TRACECLASS_TAG = "traceClass";
const QString DebugUtil::ID_ATTR = "id";
const QString DebugUtil::NAME_ATTR = "name";
QHash<quint32, QList<unsigned int> > DebugUtil::m_TraceIdToSmartPointerMap;
QHash<quint32, const Object*> DebugUtil::m_TraceIdToObjectMap;
QSet<unsigned int> DebugUtil::m_TracedObjects;
QSet<QString> DebugUtil::m_TracedClasses;
class NotClassName
{
QString name;
public:
NotClassName(const QString& s) :
name(s)
{
}
bool operator()(const Object* entry) const
{
return name != entry->GetClassName();
}
};
DebugBreakpointManager* DebugUtil::GetBreakpointManager()
{
static DebugBreakpointManager breakpointManager;
return &breakpointManager;
}
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::TraceObject(const Object* object)
{
BERRY_INFO << "Tracing enabled for: " << object->GetTraceId() << std::endl;
m_TracedObjects.insert(object->GetTraceId());
_G_ObjectEvents.objTracingEvent(object->GetTraceId(), true, object);
}
#else
void DebugUtil::TraceObject(const Object* /*object*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::TraceObject(unsigned int traceId)
{
BERRY_INFO << "Tracing enabled for: " << traceId << std::endl;
m_TracedObjects.insert(traceId);
TraceIdToObjectType::ConstIterator i = m_TraceIdToObjectMap.find(traceId);
if (i != m_TraceIdToObjectMap.end())
_G_ObjectEvents.objTracingEvent(traceId, true, i.value());
else
_G_ObjectEvents.objTracingEvent(traceId, true, 0);
}
#else
void DebugUtil::TraceObject(unsigned int /*traceId*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::TraceClass(const QString& className)
{
BERRY_INFO << "Tracing enabled for: " << className << std::endl;
m_TracedClasses.insert(className);
//_G_ObjectEvents.objTracingEvent(object->GetTraceId(), true, object);
}
#else
void DebugUtil::TraceClass(const QString& /*className*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::StopTracing(unsigned int traceId)
{
BERRY_INFO << "Tracing stopped for: " << traceId << std::endl;
m_TracedObjects.remove(traceId);
TraceIdToObjectType::ConstIterator i = m_TraceIdToObjectMap.find(traceId);
if (i != m_TraceIdToObjectMap.end())
_G_ObjectEvents.objTracingEvent(traceId, false, i.value());
else
_G_ObjectEvents.objTracingEvent(traceId, false, 0);
}
#else
void DebugUtil::StopTracing(unsigned int /*traceId*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::StopTracing(const Object* obj)
{
BERRY_INFO << "Tracing stopped for: " << obj->GetTraceId() << std::endl;
m_TracedObjects.remove(obj->GetTraceId());
_G_ObjectEvents.objTracingEvent(obj->GetTraceId(), false, obj);
}
#else
void DebugUtil::StopTracing(const Object* /*obj*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::StopTracing(const QString& className)
{
BERRY_INFO << "Tracing stopped for: " << className << std::endl;
m_TracedClasses.remove(className);
//_G_ObjectEvents.objTracingEvent(obj->GetTraceId(), false, obj);
}
#else
void DebugUtil::StopTracing(const QString& /*className*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
bool DebugUtil::IsTraced(const Object* object)
{
if (m_TracedObjects.find(object->GetTraceId()) != m_TracedObjects.end())
return true;
if (m_TracedClasses.find(object->GetClassName()) != m_TracedClasses.end())
return true;
return false;
}
#else
bool DebugUtil::IsTraced(const Object* /*object*/)
{
return false;
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
bool DebugUtil::IsTraced(unsigned int traceId)
{
if (m_TracedObjects.find(traceId) != m_TracedObjects.end())
return true;
TraceIdToObjectType::Iterator it = m_TraceIdToObjectMap.find(traceId);
if (it != m_TraceIdToObjectMap.end())
{
if (m_TracedClasses.find(it.value()->GetClassName()) != m_TracedClasses.end())
return true;
}
return false;
}
#else
bool DebugUtil::IsTraced(unsigned int /*traceId*/)
{
return false;
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
bool DebugUtil::IsTraced(const QString& className)
{
return m_TracedClasses.find(className) != m_TracedClasses.end();
}
#else
bool DebugUtil::IsTraced(const QString& /*className*/)
{
return false;
}
#endif
QSet<unsigned int> DebugUtil::GetTracedObjects()
{
return m_TracedObjects;
}
const Object* DebugUtil::GetObject(unsigned int traceId)
{
return m_TraceIdToObjectMap[traceId];
}
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
QList<unsigned int> DebugUtil::GetSmartPointerIDs(
const Object* objectPointer, const QList<unsigned int>& excludeList)
{
Q_ASSERT(objectPointer != 0);
QList<unsigned int> ids = m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()];
for (QList<unsigned int>::const_iterator iter = excludeList.begin();
iter != excludeList.end(); ++iter)
ids.removeAll(*iter);
return ids;
}
#else
QList<unsigned int> DebugUtil::GetSmartPointerIDs(
const Object* /*objectPointer*/, const QList<unsigned int>& /*excludeList*/)
{
return QList<unsigned int>();
}
#endif
QList<const Object*> DebugUtil::GetRegisteredObjects()
{
return m_TraceIdToObjectMap.values();
}
void DebugUtil::PrintSmartPointerIDs(const Object* objectPointer, const QList<unsigned int>& excludeList)
{
qDebug() << "SmartPointer IDs [ ";
if (IsTraced(objectPointer))
{
QList<unsigned int> ids = GetSmartPointerIDs(objectPointer, excludeList);
for (QList<unsigned int>::const_iterator iter = ids.begin();
iter != ids.end(); ++iter)
{
qDebug() << *iter << " ";
}
}
else
{
qDebug() << "n/a ";
}
qDebug() << "]\n";
}
void DebugUtil::AddObjectListener(IDebugObjectListener* listener)
{
_G_ObjectEvents.AddListener(listener);
}
void DebugUtil::RemoveObjectListener(IDebugObjectListener* listener)
{
_G_ObjectEvents.RemoveListener(listener);
}
void DebugUtil::ResetObjectSummary()
{
m_TraceIdToObjectMap.clear();
m_TraceIdToSmartPointerMap.clear();
m_TracedObjects.clear();
}
bool DebugUtil::PrintObjectSummary(bool details)
{
QSet<QString> names;
- for (auto object : qAsConst(m_TraceIdToObjectMap))
+ for (auto object : std::as_const(m_TraceIdToObjectMap))
names.insert(object->GetClassName());
if (!names.isEmpty())
{
std::cout << std::endl << std::endl << "#########################################################" << std::endl;
std::cout << "######## berry::Object leakage summary: ########" << std::endl << std::endl;
for (QSet<QString>::const_iterator i = names.begin();
i != names.end(); ++i)
{
PrintObjectSummary(*i, details);
if (details) std::cout << std::endl;
}
std::cout << std::endl << "#########################################################" << std::endl << std::endl;
}
return !names.isEmpty();
}
bool DebugUtil::PrintObjectSummary(const QString& className, bool details)
{
TraceIdToObjectType::ConstIterator endIter =
std::remove_if(m_TraceIdToObjectMap.begin(), m_TraceIdToObjectMap.end(), NotClassName(className));
qDebug() << "Class:" << className;
if (details) std::cout << std::endl;
std::size_t count = 0;
for (TraceIdToObjectType::ConstIterator iter = m_TraceIdToObjectMap.begin();
iter != endIter; ++iter, ++count)
{
if (details)
{
qDebug() << (*(iter.value()));
PrintSmartPointerIDs(iter.value());
}
}
qDebug() << "(" << count << " instances)\n";
return (count!=0);
}
unsigned int& DebugUtil::GetSmartPointerCounter()
{
static unsigned int counter = 0;
return counter;
}
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::UnregisterSmartPointer(unsigned int smartPointerId, const Object* objectPointer)
{
poco_assert(objectPointer != 0);
m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()].removeAll(smartPointerId);
_G_ObjectEvents.spDestroyedEvent(smartPointerId, objectPointer);
}
#else
void DebugUtil::UnregisterSmartPointer(unsigned int /*smartPointerId*/, const Object* /*objectPointer*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::RegisterSmartPointer(unsigned int smartPointerId, const Object* objectPointer, bool /*recordStack*/)
{
poco_assert(objectPointer != 0);
if (m_TracedClasses.find(objectPointer->GetClassName()) != m_TracedClasses.end() ||
m_TracedObjects.find(objectPointer->GetTraceId()) != m_TracedObjects.end())
{
m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()].push_back(smartPointerId);
_G_ObjectEvents.spCreatedEvent(smartPointerId, objectPointer);
}
if (GetBreakpointManager()->BreakAtSmartpointer(smartPointerId))
poco_debugger_msg("SmartPointer Breakpoint reached");
}
#else
void DebugUtil::RegisterSmartPointer(unsigned int /*smartPointerId*/, const Object* /*objectPointer*/, bool /*recordStack*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::RegisterObject(const Object* objectPointer)
{
m_TraceIdToObjectMap.insert(objectPointer->GetTraceId(), objectPointer);
_G_ObjectEvents.objCreatedEvent(objectPointer);
if (GetBreakpointManager()->BreakAtObject(objectPointer->GetTraceId()))
{
std::string msg = "SmartPointer Breakpoint reached for ";
msg += objectPointer->GetClassName().toStdString();
poco_debugger_msg(msg.c_str());
}
}
#else
void DebugUtil::RegisterObject(const Object* /*objectPointer*/)
{
}
#endif
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
void DebugUtil::UnregisterObject(const Object* objectPointer)
{
m_TraceIdToObjectMap.remove(objectPointer->GetTraceId());
_G_ObjectEvents.objDestroyedEvent(objectPointer);
}
#else
void DebugUtil::UnregisterObject(const Object* /*objectPointer*/)
{
}
#endif
bool DebugUtil::GetPersistencePath(QDir& path)
{
QFileInfo statePath = CTKPluginActivator::getPluginContext()->getDataFile(QString());
path = statePath.absoluteFilePath();
return true;
}
void DebugUtil::SaveState(const QDir& path)
{
QString saveFile = path.absoluteFilePath(DEBUG_UTIL_XML);
auto doc = new Poco::XML::Document();
Poco::XML::Element* debugutil = doc->createElement(DEBUGUTIL_TAG.toStdString());
doc->appendChild(debugutil)->release();
for (QSet<unsigned int>::const_iterator i = m_TracedObjects.begin();
i != m_TracedObjects.end(); ++i)
{
Poco::XML::Element* traceObject = doc->createElement(TRACEOBJECT_TAG.toStdString());
debugutil->appendChild(traceObject)->release();
traceObject->setAttribute(ID_ATTR.toStdString(), QString::number(*i).toStdString());
}
for (QSet<QString>::const_iterator i = m_TracedClasses.begin();
i != m_TracedClasses.end(); ++i)
{
Poco::XML::Element* traceClass = doc->createElement(TRACECLASS_TAG.toStdString());
debugutil->appendChild(traceClass)->release();
traceClass->setAttribute(NAME_ATTR.toStdString(), i->toStdString());
}
try
{
Poco::FileOutputStream writer(saveFile.toStdString());
Poco::XML::DOMWriter out;
out.setOptions(3); //write declaration and pretty print
out.writeNode(writer, doc);
doc->release();
// save BreakpointManager
QString saveBM = path.absoluteFilePath(QString::fromStdString(DebugBreakpointManager::BREAKPOINTS_XML));
GetBreakpointManager()->SaveState(saveBM);
}
catch (Poco::FileException& e)
{
BERRY_WARN << e.displayText();
}
}
void DebugUtil::RestoreState(const QDir& path)
{
QString restoreFile = path.absoluteFilePath(DEBUG_UTIL_XML);
try
{
Poco::XML::DOMParser parser;
Poco::FileInputStream reader(restoreFile.toStdString());
Poco::XML::InputSource source(reader);
//source.setSystemId(baseDir);
Poco::XML::Document* doc = parser.parse(&source);
Poco::XML::Element* debugutil = doc->documentElement();
if (debugutil)
{
// restore traced objects
Poco::XML::NodeList* elementList = debugutil->getElementsByTagName(TRACEOBJECT_TAG.toStdString());
for (std::size_t i = 0; i < elementList->length(); i++)
{
Poco::XML::Element* elem =
dynamic_cast<Poco::XML::Element*> (elementList->item(static_cast<unsigned long>(i)));
if (!elem->hasAttribute(ID_ATTR.toStdString())) continue;
const std::string& attr = elem->getAttribute(ID_ATTR.toStdString());
int traceId = 0;
try
{
traceId = Poco::NumberParser::parse(attr);
}
catch (const Poco::SyntaxException& e)
{
BERRY_WARN << e.displayText();
}
DebugUtil::TraceObject(traceId);
}
elementList->release();
// restore traced classes
elementList = debugutil->getElementsByTagName(TRACECLASS_TAG.toStdString());
for (std::size_t i = 0; i < elementList->length(); i++)
{
Poco::XML::Element* elem =
dynamic_cast<Poco::XML::Element*> (elementList->item(static_cast<unsigned long>(i)));
if (!elem->hasAttribute(NAME_ATTR.toStdString())) continue;
const std::string& traceClass = elem->getAttribute(NAME_ATTR.toStdString());
if (!traceClass.empty())
DebugUtil::TraceClass(QString::fromStdString(traceClass));
}
elementList->release();
}
doc->release();
}
catch (Poco::XML::SAXParseException& e)
{
BERRY_WARN << e.displayText();
}
catch (Poco::FileNotFoundException&)
{
}
catch (Poco::FileException& e)
{
BERRY_WARN << e.displayText();
}
// restore BreakpointManager
GetBreakpointManager()->RestoreState(path.absoluteFilePath(QString::fromStdString(DebugBreakpointManager::BREAKPOINTS_XML)));
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/berryMacros.h b/Plugins/org.blueberry.core.runtime/src/berryMacros.h
index 31387c7544..d7defa8091 100644
--- a/Plugins/org.blueberry.core.runtime/src/berryMacros.h
+++ b/Plugins/org.blueberry.core.runtime/src/berryMacros.h
@@ -1,87 +1,85 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#ifndef __BERRY_MACROS_H__
#define __BERRY_MACROS_H__
#include "berryWeakPointer.h"
#include "berryReflection.h"
#include "berryExtensionType.h"
-class QStringList;
-
#define berryArgGlue(x, y) x y
#define berryArgCount(_1,_2,_3,_4,_5,_6,_7,_8,count,...) count
#define berryExpandArgs(args) berryArgCount args
#define berryCountArgsMax8(...) berryExpandArgs((__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0))
#define berryOverloadMacro2(name, count) name##count
#define berryOverloadMacro1(name, count) berryOverloadMacro2(name, count)
#define berryOverloadMacro(name, count) berryOverloadMacro1(name, count)
#define berryCallOverload(name, ...) berryArgGlue(berryOverloadMacro(name, berryCountArgsMax8(__VA_ARGS__)), (__VA_ARGS__))
#define berryObjectMacro(...) berryCallOverload(berryObjectMacro, __VA_ARGS__)
#define berryObjectTypeInfo(...) \
static ::berry::Reflection::TypeInfo GetStaticTypeInfo() \
{ return ::berry::Reflection::TypeInfo::New<Self>(); } \
::berry::Reflection::TypeInfo GetTypeInfo() const override \
{ return Self::GetStaticTypeInfo(); } \
/*typedef ::berry::Reflection::TypeList<__VA_ARGS__> SuperclassTypes;*/\
static QList< ::berry::Reflection::TypeInfo> GetStaticSuperclasses() \
{ return ::berry::Reflection::GetSuperclasses<Self>(); } \
QList< ::berry::Reflection::TypeInfo> GetSuperclasses() const override \
{ return Self::GetStaticSuperclasses(); }
#define berryObjectMacro1(className) \
typedef className Self; \
typedef berry::SmartPointer<Self> Pointer; \
typedef berry::SmartPointer<const Self> ConstPointer; \
typedef berry::WeakPointer<Self> WeakPtr; \
typedef berry::WeakPointer<const Self> ConstWeakPtr; \
static const char* GetStaticClassName() \
{ return #className; }
#define berryObjectMacro2(className, super1) \
berryObjectMacro1(className) \
berryObjectTypeInfo(super1)
#define berryObjectMacro3(className, super1, super2) \
berryObjectMacro1(className) \
berryObjectTypeInfo(super1, super2)
#define berryObjectMacro4(className, super1, super2, super3) \
berryObjectMacro1(className) \
berryObjectTypeInfo(super1, super2, super3)
#define berryObjectMacro5(className, super1, super2, super3, super4) \
berryObjectMacro1(className) \
berryObjectTypeInfo(super1, super2, super3, super4)
#define berryObjectMacro6(className, super1, super2, super3, super4, super5) \
berryObjectMacro1(className) \
berryObjectTypeInfo(super1, super2, super3, super4, super5)
#define berryObjectMacro7(className, super1, super2, super3, super4, super5, super6) \
berryObjectMacro1(className) \
berryObjectTypeInfo(super1, super2, super3, super4, super5, super6)
#define berryObjectMacro8(className, super1, super2, super3, super4, super5, super6, super7) \
berryObjectMacro1(className) \
berryObjectTypeInfo(super1, super2, super3, super4, super5, super6, super7)
#define berryObjectMacro9(className, super1, super2, super3, super4, super5, super6, super7, super8) \
berryObjectMacro1(className) \
berryObjectTypeInfo(super1, super2, super3, super4, super5, super6, super7, super8)
#define BERRY_REGISTER_EXTENSION_CLASS(_ClassType, _PluginContext) \
{ \
Q_UNUSED(_PluginContext) \
QString typeName = _ClassType::staticMetaObject.className(); \
::berry::registerExtensionType<_ClassType>(typeName.toLatin1().data()); \
}
#endif /*__BERRY_MACROS_H__*/
diff --git a/Plugins/org.blueberry.core.runtime/src/berryObject.cpp b/Plugins/org.blueberry.core.runtime/src/berryObject.cpp
index 1d1b428357..62e095dcab 100644
--- a/Plugins/org.blueberry.core.runtime/src/berryObject.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/berryObject.cpp
@@ -1,285 +1,255 @@
/*============================================================================
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 "berryObject.h"
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
#include "berryDebugUtil.h"
#endif
#include "berryLog.h"
#include "berryReflection.h"
#include <QDebug>
#include <list>
#include <memory>
#include <exception>
namespace berry
{
void Object::Delete()
{
this->UnRegister();
}
-#ifdef _WIN32
-void*
-Object
-::operator new(size_t n)
-{
- return new char[n];
-}
-
-void*
-Object
-::operator new[](size_t n)
-{
- return new char[n];
-}
-
-void
-Object
-::operator delete(void* m)
-{
- delete [] (char*)m;
-}
-
-void
-Object
-::operator delete[](void* m, size_t)
-{
- delete [] (char*)m;
-}
-#endif
-
const char* Object::GetStaticClassName()
{
return "berry::Object";
}
QString Object::GetClassName() const
{
return Reflection::DemangleName(typeid(*this).name());
}
Reflection::TypeInfo Object::GetStaticTypeInfo()
{
return Reflection::TypeInfo::New<Self>();
}
Reflection::TypeInfo Object::GetTypeInfo() const
{
return Self::GetStaticTypeInfo();
}
QList<Reflection::TypeInfo> Object::GetStaticSuperclasses()
{
return QList<Reflection::TypeInfo>();
}
QList<Reflection::TypeInfo> Object::GetSuperclasses() const
{
return GetStaticSuperclasses();
}
QDebug Object::Print(QDebug os, Indent indent) const
{
os = this->PrintHeader(os, indent);
os = this->PrintSelf(os, indent.GetNextIndent());
return this->PrintTrailer(os, indent);
}
QString Object::ToString() const
{
QString str;
QDebug ss(&str);
this->Print(ss);
return str;
}
uint Object::HashCode() const
{
return qHash(this);
}
bool Object::operator<(const Object* o) const
{
return this < o;
}
void Object::Register() const
{
m_ReferenceCount.ref();
}
void Object::UnRegister(bool del) const
{
if (!m_ReferenceCount.deref() && del)
{
delete this;
}
}
void Object::SetReferenceCount(int ref)
{
QMutexLocker lock(&m_ReferenceCountLock);
- m_ReferenceCount.store(ref);
+ m_ReferenceCount.storeRelaxed(ref);
if (ref == 0)
{
delete this;
}
}
bool Object::operator==(const Object* o) const
{
return this == o;
}
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
unsigned int Object::GetTraceId() const
{
return m_TraceId;
}
unsigned int& Object::GetTraceIdCounter() const
{
static unsigned int traceId = 0;
return traceId;
}
#endif
Object::Object() :
m_ReferenceCount(0)
{
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
unsigned int& id = GetTraceIdCounter();
m_TraceId = ++id;
DebugUtil::RegisterObject(this);
#endif
}
Object::~Object()
{
/**
* warn user if reference counting is on and the object is being referenced
* by another object.
*/
- if (m_ReferenceCount.load() > 0)
+ if (m_ReferenceCount.loadRelaxed() > 0)
{
// A general exception safety rule is that destructors should
// never throw. Something is wrong with a program that reaches
// this point anyway. Also this is the least-derived class so the
// whole object has been destroyed by this point anyway. Just
// issue a warning.
BERRY_WARN << "WARNING: In " __FILE__ ", line " << __LINE__ << "\n"
<< this->GetClassName() << " (" << this
<< "): Trying to delete object with non-zero reference count.";
}
/**
* notifies the registered functions that the object is being destroyed
*/
m_DestroyMessage.Send();
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
DebugUtil::UnregisterObject(this);
#endif
}
QDebug Object::PrintSelf(QDebug os, Indent Indent) const
{
QString demangledName = Reflection::DemangleName(typeid(*this).name());
os << Indent << "RTTI typeinfo: " << demangledName << '\n';
- os << Indent << "Reference Count: " << m_ReferenceCount.load() << '\n';
+ os << Indent << "Reference Count: " << m_ReferenceCount.loadRelaxed() << '\n';
return os;
}
/**
* Define a default print header for all objects.
*/
QDebug Object::PrintHeader(QDebug os, Indent Indent) const
{
os << Indent << this->GetClassName() << " (" << this << ")\n";
return os;
}
/**
* Define a default print trailer for all objects.
*/
QDebug Object::PrintTrailer(QDebug os, Indent /*Indent*/) const
{
return os;
}
// ============== Indent related implementations ==============
static const char blanks[41] = " ";
Indent Indent::GetNextIndent()
{
int Indent = m_Indent + 2;
if (Indent > 40)
{
Indent = 40;
}
return Indent;
}
QDebug operator<<(QDebug os, const berry::Indent& ind)
{
os.nospace() << blanks + (40 - ind.m_Indent);
return os;
}
} // namespace berry
QDebug operator<<(QDebug os, const berry::Object& o)
{
return o.Print(os);
}
QDebug operator<<(QDebug os, const berry::SmartPointer<const berry::Object>& o)
{
return o->Print(os);
}
QDebug operator<<(QDebug os, const berry::SmartPointer<berry::Object>& o)
{
return o->Print(os);
}
QTextStream& operator<<(QTextStream& os, const berry::Object& o)
{
os << o.ToString();
return os;
}
QTextStream& operator<<(QTextStream& os, const berry::SmartPointer<const berry::Object>& o)
{
os << o->ToString();
return os;
}
//QTextStream& operator<<(QTextStream& os, const berry::SmartPointer<berry::Object>& o)
//{
// os << o->ToString();
// return os;
//}
uint qHash(const berry::Object& o)
{
return o.HashCode();
}
diff --git a/Plugins/org.blueberry.core.runtime/src/berryObject.h b/Plugins/org.blueberry.core.runtime/src/berryObject.h
index 513786dcd5..2879c2a49d 100644
--- a/Plugins/org.blueberry.core.runtime/src/berryObject.h
+++ b/Plugins/org.blueberry.core.runtime/src/berryObject.h
@@ -1,241 +1,232 @@
/*============================================================================
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 BERRYOBJECT_H_
#define BERRYOBJECT_H_
#include <org_blueberry_core_runtime_Export.h>
#include "berryMacros.h"
#include "berryMessage.h"
#include <berryConfig.h>
#include <QString>
#include <QMetaType>
#include <QMutex>
#include <QAtomicInt>
#ifdef _MSC_VER
// disable inheritance by dominance warnings
#pragma warning( disable : 4250 4275 )
#endif
class QDebug;
class QTextStream;
namespace berry {
class org_blueberry_core_runtime_EXPORT Indent
{
public:
/** Standard class typedefs. */
typedef Indent Self;
/** Construct the object with an initial Indentation level. */
Indent(int ind = 0) { m_Indent=ind; }
/**
* Determine the next Indentation level. Keep Indenting by two until the
* a maximum of forty spaces is reached.
*/
Indent GetNextIndent();
/** Print out the Indentation. Basically output a bunch of spaces. */
friend org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const Indent& o);
private:
int m_Indent;
};
/** \class Object
* \brief Light weight base class for most BlueBerry classes.
*
* Object is copied from itk::LightObject and is the highest
* level base class for most BlueBerry objects. It
* implements reference counting and the API for object printing.
*
*/
class org_blueberry_core_runtime_EXPORT Object
{
private:
mutable Message<> m_DestroyMessage;
public:
typedef Object Self;
typedef berry::SmartPointer<Self> Pointer;
typedef berry::SmartPointer<const Self> ConstPointer;
typedef berry::WeakPointer<Self> WeakPtr;
typedef berry::WeakPointer<const Self> ConstWeakPtr;
static const char* GetStaticClassName();
virtual QString GetClassName() const;
static Reflection::TypeInfo GetStaticTypeInfo();
virtual Reflection::TypeInfo GetTypeInfo() const;
static QList<Reflection::TypeInfo> GetStaticSuperclasses();
virtual QList<Reflection::TypeInfo> GetSuperclasses() const;
/** Delete an BlueBerry object. This method should always be used to delete an
* object when the new operator was used to create it. Using the C
* delete method will not work with reference counting. */
virtual void Delete();
-
-#ifdef _WIN32
- /** Used to avoid dll boundary problems. */
- void* operator new(size_t);
- void* operator new[](size_t);
- void operator delete(void*);
- void operator delete[](void*, size_t);
-#endif
-
/**
* Cause the object to print itself out. This is usually used to provide
* detailed information about the object's state. It just calls the
* header/self/trailer virtual print methods, which can be overridden by
* subclasses.
*/
QDebug Print(QDebug os, Indent Indent=0) const;
/**
* Returns a string representation of this object. The default
* implementation returns an empty string.
*/
virtual QString ToString() const;
/**
* Returns a hash code value for the object.
*/
virtual uint HashCode() const;
/**
* Override this method to implement a specific "less than" operator
* for associative STL containers.
*/
virtual bool operator<(const Object*) const;
/** Increase the reference count (mark as used by another object). */
void Register() const;
/** Decrease the reference count (release by another object).
* Set del to false if you do not want the object to be deleted if
* the reference count is zero (use with care!) */
void UnRegister(bool del = true) const;
/** Gets the reference count on this object. */
int GetReferenceCount() const
{
- return m_ReferenceCount.load();
+ return m_ReferenceCount.loadRelaxed();
}
/** Sets the reference count on this object. This is a dangerous
* method, use it with care. */
void SetReferenceCount(int);
inline void AddDestroyListener(const MessageAbstractDelegate<>& delegate) const
{ m_DestroyMessage += delegate; }
inline void RemoveDestroyListener(const MessageAbstractDelegate<>& delegate) const
{ m_DestroyMessage -= delegate; }
/**
* A generic comparison method. Override this method in subclasses and
* cast to your derived class to provide a more detailed comparison.
*/
virtual bool operator==(const Object*) const;
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
unsigned int GetTraceId() const;
private:
unsigned int m_TraceId;
unsigned int& GetTraceIdCounter() const;
public:
#endif
protected:
friend struct QScopedPointerObjectDeleter;
Object();
virtual ~Object();
/**
* Methods invoked by Print() to print information about the object
* including superclasses. Typically not called by the user (use Print()
* instead) but used in the hierarchical print process to combine the
* output of several classes.
*/
virtual QDebug PrintSelf(QDebug os, Indent indent) const;
virtual QDebug PrintHeader(QDebug os, Indent indent) const;
virtual QDebug PrintTrailer(QDebug os, Indent indent) const;
/** Number of uses of this object by other objects. */
mutable QAtomicInt m_ReferenceCount;
/** Mutex lock to protect modification to the reference count */
mutable QMutex m_ReferenceCountLock;
private:
Object(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
};
// A custom deleter for QScopedPointer
// berry::Object instances in a QScopedPointer should have reference count one,
// such that they are not accidentally deleted when a temporary smart pointer
// pointing to it goes out of scope. This deleter fixes the reference count and
// always deletes the instance. Use a berry::SmartPointer if the lifetime should
// exceed the one of the pointer.
struct QScopedPointerObjectDeleter
{
static inline void cleanup(Object* obj)
{
if (obj == nullptr) return;
obj->UnRegister(false);
delete obj;
}
};
org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const berry::Indent& o);
}
/**
* This operator allows all subclasses of Object to be printed via QDebug <<.
* It in turn invokes the Print method, which in turn will invoke the
* PrintSelf method that all objects should define, if they have anything
* interesting to print out.
*/
org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const berry::Object& o);
org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const berry::SmartPointer<const berry::Object>& o);
org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const berry::SmartPointer<berry::Object>& o);
org_blueberry_core_runtime_EXPORT QTextStream& operator<<(QTextStream& os, const berry::Object& o);
org_blueberry_core_runtime_EXPORT QTextStream& operator<<(QTextStream& os, const berry::SmartPointer<const berry::Object>& o);
//org_blueberry_core_runtime_EXPORT QTextStream& operator<<(QTextStream& os, const berry::SmartPointer<berry::Object>& o);
Q_DECLARE_METATYPE(berry::Object::Pointer)
org_blueberry_core_runtime_EXPORT uint qHash(const berry::Object& o);
#endif /*BERRYOBJECT_H_*/
diff --git a/Plugins/org.blueberry.core.runtime/src/berryReflection.cpp b/Plugins/org.blueberry.core.runtime/src/berryReflection.cpp
index 069c31cea2..44a847b61e 100644
--- a/Plugins/org.blueberry.core.runtime/src/berryReflection.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/berryReflection.cpp
@@ -1,107 +1,107 @@
/*============================================================================
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 "berryReflection.h"
#include "berryObject.h"
#include <QStringList>
// Better name demangling for gcc
#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 )
#define GCC_USEDEMANGLE
#endif
#ifdef GCC_USEDEMANGLE
#include <cstdlib>
#include <cxxabi.h>
#endif
#if defined(_WIN32) && defined(NDEBUG)
// exported from VC CRT
extern "C"
char * __unDName(char * outputString, const char * name, int maxStringLength,
void * (* pAlloc )(size_t), void (* pFree )(void *),
unsigned short disableFlags);
#endif
namespace berry {
namespace Reflection {
QString DemangleName(const char* mangledName)
{
QString name(mangledName);
#ifdef GCC_USEDEMANGLE
int status;
char* unmangled = abi::__cxa_demangle(mangledName, nullptr, nullptr, &status);
if(status == 0)
{
name = QString(unmangled);
free(unmangled);
}
#elif defined(_WIN32) && defined(NDEBUG)
char * const unmangled = __unDName(0, mangledName, 0, malloc, free, 0x2800);
if (unmangled)
{
QString unmangledName(unmangled);
- name = unmangledName.split(' ', QString::SkipEmptyParts).back();
+ name = unmangledName.split(' ', Qt::SkipEmptyParts).back();
free(unmangled);
}
#else
- name = name.split(' ', QString::SkipEmptyParts).back();
+ name = name.split(' ', Qt::SkipEmptyParts).back();
#endif
return name;
}
#ifdef GetClassName
// clash with WinUser.h definition
#undef GetClassName
#endif
QString GetClassName(const Object* obj)
{
return DemangleName(typeid(*const_cast<Object*>(obj)).name());
}
TypeInfo::Concept::~Concept(){}
template<>
struct TypeInfo::Model<EmptyType> : Concept {
QString GetName() const override { return QString(); }
QList<TypeInfo> GetSuperclasses() const override { return QList<TypeInfo>(); }
};
TypeInfo::TypeInfo()
: m_Self(std::make_shared<Model<EmptyType> >())
{
}
bool TypeInfo::operator==(const TypeInfo& other) const
{
return this->GetName() == other.GetName();
}
QString TypeInfo::GetName() const
{
return m_Self->GetName();
}
QList<TypeInfo> TypeInfo::GetSuperclasses() const
{
return m_Self->GetSuperclasses();
}
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp b/Plugins/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp
index 516f9f51e7..ffae990899 100644
--- a/Plugins/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp
@@ -1,330 +1,330 @@
/*============================================================================
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 "berryExtensionTracker.h"
#include <berryIExtension.h>
#include <berryIExtensionPoint.h>
#include <berryIExtensionPointFilter.h>
#include <berryIExtensionRegistry.h>
#include <berryIExtensionChangeHandler.h>
#include <berryIRegistryEventListener.h>
#include <berryListenerList.h>
#include <berryLog.h>
#include "internal/berrySimpleExtensionPointFilter.h"
#include <berryPlatform.h>
#include <QSet>
#include <QHash>
#include <QMutex>
namespace berry {
struct ExtensionTracker::Impl
{
struct HandlerWrapper;
ExtensionTracker* const q;
QHash<IExtension::Pointer, QSet<Object::Pointer> > extensionToStrongObjects;
QHash<IExtension::Pointer, QSet<Object::WeakPtr> > extensionToWeakObjects;
//ListenerList<HandlerWrapper> handlers;
QHash<IExtensionChangeHandler*, HandlerWrapper*> handlerToWrapper;
QMutex mutex;
bool closed;
IExtensionRegistry* registry; // the registry that this tacker works with
Impl(ExtensionTracker* q, IExtensionRegistry* theRegistry)
: q(q)
, closed(false)
, registry(theRegistry)
{}
};
struct ExtensionTracker::Impl::HandlerWrapper : public IRegistryEventListener
{
ExtensionTracker* const q;
IExtensionChangeHandler* const handler;
HandlerWrapper(ExtensionTracker* q, IExtensionChangeHandler* handler)
: q(q)
, handler(handler)
{}
bool operator==(const HandlerWrapper& target) const
{
return handler == target.handler;
}
void Added(const QList<IExtension::Pointer>& extensions) override
{
for (int i = 0; i < extensions.size(); ++i)
{
q->ApplyAdd(handler, extensions[i]);
}
}
void Removed(const QList<IExtension::Pointer>& extensions) override
{
QList<QList<Object::Pointer> > removedObjects;
{
QMutexLocker lock(&q->d->mutex);
for (int i = 0; i < extensions.size(); ++i)
{
QSet<Object::Pointer> associatedObjects = q->d->extensionToStrongObjects.take(extensions[i]);
foreach(const Object::WeakPtr& ptr, q->d->extensionToWeakObjects.take(extensions[i]))
{
if (!ptr.Expired())
{
associatedObjects.insert(ptr.Lock());
}
}
- removedObjects.push_back(associatedObjects.toList());
+ removedObjects.push_back(associatedObjects.values());
}
}
for (int i = 0; i < extensions.size(); ++i)
{
q->ApplyRemove(handler, extensions[i], removedObjects[i]);
}
}
void Added(const QList<IExtensionPoint::Pointer>& /*extensionPoints*/) override
{
// do nothing
}
void Removed(const QList<IExtensionPoint::Pointer>& /*extensionPoints*/) override
{
// do nothing
}
};
ExtensionTracker::ExtensionTracker()
{
this->Init(Platform::GetExtensionRegistry());
}
ExtensionTracker::~ExtensionTracker()
{
}
ExtensionTracker::ExtensionTracker(IExtensionRegistry* theRegistry)
: d()
{
this->Init(theRegistry);
}
void ExtensionTracker::Init(IExtensionRegistry* registry)
{
d.reset(new Impl(this, registry));
if (registry == nullptr)
{
//RuntimeLog.log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.registry_no_default, null));
BERRY_ERROR << "Extension tracker was unable to obtain BlueBerry extension registry.";
d->closed = true;
}
}
void ExtensionTracker::RegisterHandler(IExtensionChangeHandler* handler, const IExtensionPointFilter& filter)
{
QMutexLocker lock(&d->mutex);
if (d->closed) return;
auto iter = d->handlerToWrapper.insert(handler, new Impl::HandlerWrapper(this, handler));
d->registry->AddListener(iter.value(), filter);
}
void ExtensionTracker::RegisterHandler(IExtensionChangeHandler* handler, const QString& extensionPointId)
{
this->RegisterHandler(handler, extensionPointId.isEmpty() ? IExtensionPointFilter(nullptr)
: IExtensionPointFilter(new SimpleExtensionPointFilter(extensionPointId)));
}
void ExtensionTracker::UnregisterHandler(IExtensionChangeHandler* handler)
{
QMutexLocker lock(&d->mutex);
if (d->closed) return;
IRegistryEventListener* listener = d->handlerToWrapper.take(handler);
d->registry->RemoveListener(listener);
delete listener;
}
void ExtensionTracker::RegisterObject(const SmartPointer<IExtension>& element, const SmartPointer<Object>& object, IExtensionTracker::ReferenceType referenceType)
{
if (element.IsNull() || object.IsNull()) return;
QMutexLocker lock(&d->mutex);
if (d->closed) return;
if (referenceType == REF_STRONG)
{
d->extensionToStrongObjects[element].insert(object);
}
else if (referenceType == REF_WEAK)
{
d->extensionToWeakObjects[element].insert(Object::WeakPtr(object));
}
}
QList<SmartPointer<Object> > ExtensionTracker::GetObjects(const IExtension::Pointer& element) const
{
QSet<Object::Pointer> objectSet;
QMutexLocker lock(&d->mutex);
- if (d->closed) return objectSet.toList();
+ if (d->closed) return objectSet.values();
auto iter = d->extensionToStrongObjects.find(element);
if (iter != d->extensionToStrongObjects.end())
{
objectSet.unite(iter.value());
}
auto iter2 = d->extensionToWeakObjects.find(element);
if (iter2 != d->extensionToWeakObjects.end())
{
foreach(const Object::WeakPtr& ptr, iter2.value())
{
if (!ptr.Expired()) objectSet.insert(ptr.Lock());
}
}
- return objectSet.toList();
+ return objectSet.values();
}
void ExtensionTracker::Close()
{
QMutexLocker lock(&d->mutex);
if (d->closed) return;
foreach(Impl::HandlerWrapper* wrapper, d->handlerToWrapper.values())
{
d->registry->RemoveListener(wrapper);
delete wrapper;
}
d->extensionToStrongObjects.clear();
d->extensionToWeakObjects.clear();
d->handlerToWrapper.clear();
d->closed = true;
}
void ExtensionTracker::UnregisterObject(const SmartPointer<IExtension>& extension, const SmartPointer<Object>& object)
{
QMutexLocker lock(&d->mutex);
if (d->closed) return;
auto iter = d->extensionToStrongObjects.find(extension);
if (iter != d->extensionToStrongObjects.end())
{
iter.value().remove(object);
}
auto iter2 = d->extensionToWeakObjects.find(extension);
if (iter2 != d->extensionToWeakObjects.end())
{
iter2.value().remove(Object::WeakPtr(object));
}
}
QList<SmartPointer<Object> > ExtensionTracker::UnregisterObject(const SmartPointer<IExtension>& extension)
{
QSet<Object::Pointer> objectSet;
QMutexLocker lock(&d->mutex);
- if (d->closed) return objectSet.toList();
+ if (d->closed) return objectSet.values();
auto iter = d->extensionToStrongObjects.find(extension);
if (iter != d->extensionToStrongObjects.end())
{
objectSet.unite(iter.value());
d->extensionToStrongObjects.erase(iter);
}
auto iter2 = d->extensionToWeakObjects.find(extension);
if (iter2 != d->extensionToWeakObjects.end())
{
foreach(const Object::WeakPtr& ptr, iter2.value())
{
if (!ptr.Expired()) objectSet.insert(ptr.Lock());
}
d->extensionToWeakObjects.erase(iter2);
}
- return objectSet.toList();
+ return objectSet.values();
}
IExtensionPointFilter ExtensionTracker::CreateExtensionPointFilter(const SmartPointer<IExtensionPoint>& xpt)
{
struct F : IExtensionPointFilter::Concept {
const IExtensionPoint::Pointer m_Xpt;
F(const IExtensionPoint::Pointer& xp)
: m_Xpt(xp)
{}
bool Matches(const IExtensionPoint* target) const override
{
return m_Xpt == target;
}
};
return IExtensionPointFilter(new F(xpt));
}
IExtensionPointFilter ExtensionTracker::CreateExtensionPointFilter(const QList<SmartPointer<IExtensionPoint> >& xpts)
{
struct F : IExtensionPointFilter::Concept {
const QList<IExtensionPoint::Pointer> m_Xpts;
F(const QList<IExtensionPoint::Pointer>& xps)
: m_Xpts(xps)
{}
bool Matches(const IExtensionPoint* target) const override
{
for (int i = 0; i < m_Xpts.size(); i++)
{
if (m_Xpts[i] == target)
{
return true;
}
}
return false;
}
};
return IExtensionPointFilter(new F(xpts));
}
IExtensionPointFilter ExtensionTracker::CreateNamespaceFilter(const QString& id)
{
struct F : IExtensionPointFilter::Concept {
const QString m_Id;
F(const QString& id)
: m_Id(id)
{}
bool Matches(const IExtensionPoint* target) const override
{
return m_Id == target->GetNamespaceIdentifier();
}
};
return IExtensionPointFilter(new F(id));
}
void ExtensionTracker::ApplyAdd(IExtensionChangeHandler* handler, const SmartPointer<IExtension>& extension)
{
handler->AddExtension(this, extension);
}
void ExtensionTracker::ApplyRemove(IExtensionChangeHandler* handler, const SmartPointer<IExtension>& removedExtension, const QList<Object::Pointer>& removedObjects)
{
handler->RemoveExtension(removedExtension, removedObjects);
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationContainer.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationContainer.cpp
index 3d58e4de79..1b4a74dde7 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationContainer.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationContainer.cpp
@@ -1,718 +1,718 @@
/*============================================================================
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 "berryApplicationContainer.h"
#include <berryIConfigurationElement.h>
#include <berryIContributor.h>
#include <berryIExtensionRegistry.h>
#include <berryIExtension.h>
#include <berryIExtensionPoint.h>
#include <berryIProductProvider.h>
#include <berryIProduct.h>
#include "berryApplicationHandle.h"
#include "berryApplicationDescriptor.h"
#include "berryCoreException.h"
#include "berryErrorApplication.h"
#include "berryMainApplicationLauncher.h"
#include "berryProductExtensionBranding.h"
#include "berryProviderExtensionBranding.h"
#include <berryLog.h>
#include "berryCTKPluginActivator.h"
#include <service/application/ctkApplicationException.h>
#include <service/application/ctkApplicationLauncher.h>
namespace berry {
static const QString PI_OSGI = "org.blueberry.osgi";
const QString ApplicationContainer::PI_RUNTIME = "org.blueberry.core.runtime";
const QString ApplicationContainer::PT_APPLICATIONS = "applications";
const QString ApplicationContainer::PT_APP_VISIBLE = "visible";
const QString ApplicationContainer::PT_APP_THREAD = "thread";
const QString ApplicationContainer::PT_APP_THREAD_ANY = "any";
const QString ApplicationContainer::PT_APP_CARDINALITY = "cardinality";
const QString ApplicationContainer::PT_APP_CARDINALITY_SINGLETON_GLOBAL = "singleton-global";
const QString ApplicationContainer::PT_APP_CARDINALITY_SINGLETON_SCOPED = "singleton-scoped";
const QString ApplicationContainer::PT_APP_CARDINALITY_UNLIMITED = "*";
const QString ApplicationContainer::PT_APP_ICON = "icon";
const QString ApplicationContainer::PT_PRODUCTS = "products";
const QString ApplicationContainer::EXT_ERROR_APP = "org.blueberry.core.runtime.app.error";
const QString ApplicationContainer::PROP_PRODUCT = "blueberry.product";
const QString ApplicationContainer::PROP_BLUEBERRY_APPLICATION = "blueberry.application";
const QString ApplicationContainer::PROP_BLUEBERRY_APPLICATION_LAUNCH_DEFAULT = "blueberry.application.launchDefault";
const int ApplicationContainer::NOT_LOCKED = 0;
const int ApplicationContainer::LOCKED_SINGLETON_GLOBAL_RUNNING = 1;
const int ApplicationContainer::LOCKED_SINGLETON_GLOBAL_APPS_RUNNING = 2;
const int ApplicationContainer::LOCKED_SINGLETON_SCOPED_RUNNING = 3;
const int ApplicationContainer::LOCKED_SINGLETON_LIMITED_RUNNING = 4;
const int ApplicationContainer::LOCKED_MAIN_THREAD_RUNNING = 5;
ApplicationContainer::ApplicationContainer(ctkPluginContext* context, IExtensionRegistry* extensionRegistry)
: context(context)
, extensionRegistry(extensionRegistry)
, launcherTracker(new ctkServiceTracker<ctkApplicationLauncher*>(context, this))
, branding(nullptr)
, missingProductReported(false)
, defaultMainThreadAppHandle(nullptr)
, missingApp(false)
{
}
ApplicationContainer::~ApplicationContainer()
{
}
void ApplicationContainer::Start()
{
launcherTracker->open();
extensionRegistry->AddListener(this, PI_OSGI + '.' + PT_APPLICATIONS);
// need to listen for system bundle stopping
context->connectPluginListener(this, SLOT(PluginChanged(ctkPluginEvent)), Qt::DirectConnection);
// register all the descriptors
RegisterAppDescriptors();
QVariant startDefaultProp = context->getProperty(ApplicationContainer::PROP_BLUEBERRY_APPLICATION_LAUNCH_DEFAULT);
if (startDefaultProp.isNull() || startDefaultProp.toBool())
{
// Start the default application
try
{
StartDefaultApp(true);
}
catch (const ctkApplicationException& e)
{
BERRY_ERROR << "An error occurred while starting the application:" << e.message();
}
}
}
void ApplicationContainer::Stop()
{
// stop all applications
StopAllApps();
context->disconnectPluginListener(this);
extensionRegistry->RemoveListener(this);
// flush the apps
apps.clear();
branding.reset();
missingProductReported = false;
launcherTracker->close();
}
IBranding* ApplicationContainer::GetBranding() const
{
if (branding)
{
return branding.data();
}
// try pluginContext properties
if (context == nullptr) return nullptr;
QString productId = context->getProperty(PROP_PRODUCT).toString();
if (productId.isEmpty()) return nullptr;
QList<IConfigurationElement::Pointer> entries = extensionRegistry->GetConfigurationElementsFor(PI_RUNTIME, PT_PRODUCTS, productId);
if (!entries.isEmpty())
{
// There should only be one product with the given id so just take the first element
branding.reset(new ProductExtensionBranding(productId, entries[0]));
return branding.data();
}
QList<IConfigurationElement::Pointer> elements = extensionRegistry->GetConfigurationElementsFor(PI_RUNTIME, PT_PRODUCTS);
- for (const auto &element : qAsConst(elements))
+ for (const auto &element : std::as_const(elements))
{
if (element->GetName().compare("provider", Qt::CaseInsensitive) == 0)
{
try
{
IProductProvider* provider = element->CreateExecutableExtension<IProductProvider>("run");
QList<IProduct::Pointer> products = provider->GetProducts();
- for (const auto &product : qAsConst(products))
+ for (const auto &product : std::as_const(products))
{
if (productId.compare(product->GetId(), Qt::CaseInsensitive) == 0)
{
branding.reset(new ProviderExtensionBranding(product));
return branding.data();
}
}
}
catch (const CoreException&)
{
BERRY_WARN << "Problem creating the provider registered by " << element->GetParent()->ToString() << ".";
}
}
}
if (!missingProductReported)
{
BERRY_WARN << "Product " << productId << " could not be found.";
missingProductReported = true;
}
return nullptr;
}
ctkPluginContext* ApplicationContainer::GetContext() const
{
return context;
}
ApplicationDescriptor* ApplicationContainer::GetAppDescriptor(const QString& applicationId)
{
ApplicationDescriptor* result = nullptr;
{
- QMutexLocker l(&lock);
+ QMutexLocker l(&appDescLock);
auto iter = apps.find(applicationId);
result = iter == apps.end() ? nullptr : iter.value();
}
if (result == nullptr)
{
RegisterAppDescriptor(applicationId); // try again just in case we are waiting for an event
{
- QMutexLocker l(&lock);
+ QMutexLocker l(&appDescLock);
auto iter = apps.find(applicationId);
result = iter == apps.end() ? nullptr : iter.value();
}
}
return result;
}
ApplicationDescriptor* ApplicationContainer::CreateAppDescriptor(const SmartPointer<IExtension>& appExtension)
{
if (org_blueberry_core_runtime_Activator::DEBUG)
{
BERRY_INFO << "Creating application descriptor: " << appExtension->GetUniqueIdentifier();
}
QString iconPath;
{
- QMutexLocker l(&lock);
+ QMutexLocker l(&appDescLock);
auto iter = apps.find(appExtension->GetUniqueIdentifier());
ApplicationDescriptor* appDescriptor = iter == apps.end() ? nullptr : iter.value();
if (appDescriptor != nullptr)
{
return appDescriptor;
}
// the appDescriptor does not exist for the app ID; create it
QList<IConfigurationElement::Pointer> configs = appExtension->GetConfigurationElements();
ApplicationDescriptor::Flags flags = ApplicationDescriptor::FLAG_CARD_SINGLETON_GLOGAL | ApplicationDescriptor::FLAG_VISIBLE |
ApplicationDescriptor::FLAG_TYPE_MAIN_THREAD;
int cardinality = 0;
if (!configs.isEmpty())
{
QString sVisible = configs[0]->GetAttribute(PT_APP_VISIBLE);
if (!sVisible.isEmpty() && sVisible.compare("true", Qt::CaseInsensitive) != 0)
{
flags &= ~(ApplicationDescriptor::FLAG_VISIBLE);
}
QString sThread = configs[0]->GetAttribute(PT_APP_THREAD);
if (PT_APP_THREAD_ANY == sThread)
{
flags |= ApplicationDescriptor::FLAG_TYPE_ANY_THREAD;
flags &= ~(ApplicationDescriptor::FLAG_TYPE_MAIN_THREAD);
}
QString sCardinality = configs[0]->GetAttribute(PT_APP_CARDINALITY);
if (!sCardinality.isEmpty())
{
flags &= ~(ApplicationDescriptor::FLAG_CARD_SINGLETON_GLOGAL); // clear the global bit
if (PT_APP_CARDINALITY_SINGLETON_SCOPED == sCardinality)
{
flags |= ApplicationDescriptor::FLAG_CARD_SINGLETON_SCOPED;
}
else if (PT_APP_CARDINALITY_UNLIMITED == sCardinality)
{
flags |= ApplicationDescriptor::FLAG_CARD_UNLIMITED;
}
else if (PT_APP_CARDINALITY_SINGLETON_GLOBAL == sCardinality)
{
flags |= ApplicationDescriptor::FLAG_CARD_SINGLETON_GLOGAL;
}
else
{
bool okay = false;
cardinality = sCardinality.toInt(&okay);
if (okay)
{
flags |= ApplicationDescriptor::FLAG_CARD_LIMITED;
}
else
{
// TODO should we log this?
// just fall back to the default
flags |= ApplicationDescriptor::FLAG_CARD_SINGLETON_GLOGAL;
}
}
}
QString defaultApp = GetDefaultAppId();
QString appId = appExtension->GetUniqueIdentifier();
if (defaultApp == appId)
{
flags |= ApplicationDescriptor::FLAG_DEFAULT_APP;
}
iconPath = configs[0]->GetAttribute(PT_APP_ICON);
}
appDescriptor = new ApplicationDescriptor(org_blueberry_core_runtime_Activator::GetPlugin(appExtension->GetContributor()),
appExtension->GetUniqueIdentifier(), appExtension->GetLabel(), iconPath, flags, cardinality, this);
// register the appDescriptor as a service
ctkServiceRegistration sr = context->registerService<ctkApplicationDescriptor>(appDescriptor, appDescriptor->GetServiceProperties());
appDescriptor->SetServiceRegistration(sr);
// save the app descriptor in the cache
apps.insert(appExtension->GetUniqueIdentifier(), appDescriptor);
return appDescriptor;
}
}
ApplicationDescriptor*ApplicationContainer::RemoveAppDescriptor(const QString& applicationId)
{
if (org_blueberry_core_runtime_Activator::DEBUG)
{
BERRY_INFO << "Removing application descriptor: " << applicationId;
}
{
- QMutexLocker l(&lock);
+ QMutexLocker l(&appDescLock);
ApplicationDescriptor* appDescriptor = apps.take(applicationId);
if (appDescriptor == nullptr)
{
return nullptr;
}
appDescriptor->Unregister();
return appDescriptor;
}
}
void ApplicationContainer::StartDefaultApp(bool delayError)
{
// find the default application
QString applicationId = GetDefaultAppId();
ApplicationDescriptor* defaultDesc = nullptr;
QHash<QString, QVariant> args;
args.insert(ApplicationDescriptor::APP_DEFAULT, true);
if (applicationId.isEmpty() && !delayError)
{
// the application id is not set; use a descriptor that will throw an exception
args.insert(ErrorApplication::ERROR_EXCEPTION, QString("No application id has been found."));
defaultDesc = GetAppDescriptor(EXT_ERROR_APP);
}
else
{
defaultDesc = GetAppDescriptor(applicationId);
if (defaultDesc == nullptr && !delayError)
{
// the application id is not available in the registry; use a descriptor that will throw an exception
args.insert(ErrorApplication::ERROR_EXCEPTION, QString("Application \"%1\" could not be found in the registry. The applications available are: %2.")
.arg(applicationId)
.arg(GetAvailableAppsMsg()));
defaultDesc = GetAppDescriptor(EXT_ERROR_APP);
}
}
if (delayError && defaultDesc == nullptr)
{
// could not find the application; but we want to delay the error.
// another bundle may get installed that provides the application
// before we actually try to launch it.
missingApp = true;
return;
}
if (defaultDesc != nullptr)
{
defaultDesc->launch(args);
}
else
{
throw ctkApplicationException(ctkApplicationException::APPLICATION_INTERNAL_ERROR, "No application id has been found.");
}
}
void ApplicationContainer::RegisterAppDescriptors()
{
QList<IExtension::Pointer> availableApps = GetAvailableAppExtensions();
for (int i = 0; i < availableApps.size(); i++)
{
CreateAppDescriptor(availableApps[i]);
}
}
void ApplicationContainer::RegisterAppDescriptor(const QString& applicationId)
{
IExtension::Pointer appExtension = GetAppExtension(applicationId);
if (appExtension.IsNotNull())
{
CreateAppDescriptor(appExtension);
}
}
QList<SmartPointer<IExtension> > ApplicationContainer::GetAvailableAppExtensions() const
{
IExtensionPoint::Pointer point = extensionRegistry->GetExtensionPoint(PI_OSGI + '.' + PT_APPLICATIONS);
if (point.IsNull())
{
return QList<IExtension::Pointer>();
}
return point->GetExtensions();
}
QString ApplicationContainer::GetAvailableAppsMsg() const
{
QList<IExtension::Pointer> availableApps = GetAvailableAppExtensions();
QString availableAppsMsg = "<NONE>";
if (!availableApps.isEmpty())
{
availableAppsMsg = availableApps.front()->GetUniqueIdentifier();
- for (const auto &availableApp : qAsConst(availableApps))
+ for (const auto &availableApp : std::as_const(availableApps))
{
availableAppsMsg = availableAppsMsg + ", " + availableApp->GetUniqueIdentifier();
}
}
return availableAppsMsg;
}
SmartPointer<IExtension> ApplicationContainer::GetAppExtension(const QString& applicationId) const
{
return extensionRegistry->GetExtension(PI_OSGI, PT_APPLICATIONS, applicationId);
}
void ApplicationContainer::Launch(ApplicationHandle* appHandle)
{
bool isDefault = appHandle->IsDefault();
if (appHandle->getApplicationDescriptor()->GetThreadType() == ApplicationDescriptor::FLAG_TYPE_MAIN_THREAD)
{
// use the ApplicationLauncher provided by the framework to ensure it is launched on the main thread
//DefaultApplicationListener curDefaultApplicationListener = null;
MainApplicationLauncher* curMissingAppLauncher = nullptr;
ctkApplicationLauncher* appLauncher = nullptr;
{
QMutexLocker l(this);
appLauncher = launcherTracker->getService();
if (appLauncher == nullptr)
{
if (isDefault)
{
// we need to wait to allow the ApplicationLauncher to get registered;
// save the handle to be launched as soon as the ApplicationLauncher is available
defaultMainThreadAppHandle = appHandle;
return;
}
throw ctkApplicationException(ctkApplicationException::APPLICATION_INTERNAL_ERROR,
QString("The main thread is not available to launch the application: %1").arg(appHandle->getInstanceId()));
}
//curDefaultApplicationListener = defaultAppListener;
curMissingAppLauncher = missingAppLauncher.data();
}
//if (curDefaultApplicationListener != nullptr)
//{
// curDefaultApplicationListener->launch(appHandle);
//}
//else
if (curMissingAppLauncher != nullptr)
{
curMissingAppLauncher->Launch(appHandle);
}
else
{
appLauncher->launch(appHandle, appHandle->GetArguments()[IApplicationContext::APPLICATION_ARGS]);
}
}
else
{
if (isDefault)
{
//DefaultApplicationListener curDefaultApplicationListener = null;
MainApplicationLauncher* curMissingAppLauncher = nullptr;
ctkApplicationLauncher* appLauncher = nullptr;
{
QMutexLocker l(this);
appLauncher = launcherTracker->getService();
//if (defaultAppListener == nullptr)
//{
// defaultAppListener = new DefaultApplicationListener(appHandle);
//}
//curDefaultApplicationListener = defaultAppListener;
if (appLauncher == nullptr)
{
// we need to wait to allow the ApplicationLauncher to get registered;
// save the default app listener to be launched as soon as the ApplicationLauncher is available
//defaultMainThreadAppHandle = curDefaultApplicationListener;
return;
}
curMissingAppLauncher = missingAppLauncher.data();
}
if (curMissingAppLauncher != nullptr)
{
//curMissingAppLauncher->Launch(curDefaultApplicationListener);
}
else
{
//appLauncher->Launch(curDefaultApplicationListener, QVariant());
}
}
else
{
//AnyThreadAppLauncher.launchEclipseApplication(appHandle);
}
}
}
void ApplicationContainer::PluginChanged(const ctkPluginEvent& event)
{
// if this is not the system bundle stopping then ignore the event
if ((ctkPluginEvent::STOPPING & event.getType()) == 0 || event.getPlugin()->getPluginId() != 0)
{
return;
}
// The system bundle is stopping; better stop all applications and containers now
StopAllApps();
}
void ApplicationContainer::StopAllApps()
{
// get a stapshot of running applications
QList<ctkServiceReference> runningRefs = context->getServiceReferences<ctkApplicationHandle>("(!(application.state=STOPPING))");
- for (const auto &runningRef : qAsConst(runningRefs))
+ for (const auto &runningRef : std::as_const(runningRefs))
{
ctkApplicationHandle* handle = context->getService<ctkApplicationHandle>(runningRef);
try
{
if (handle != nullptr)
{
handle->destroy();
}
}
catch (const std::exception&)
{
BERRY_WARN << QString("An error occurred while stopping the application: %1").arg(handle->getInstanceId());
}
if (handle != nullptr)
{
context->ungetService(runningRef);
}
}
}
QString ApplicationContainer::GetDefaultAppId() const
{
if (!defaultAppId.isNull())
{
return defaultAppId;
}
// try plugin context properties
defaultAppId = context->getProperty(ApplicationContainer::PROP_BLUEBERRY_APPLICATION).toString();
if (!defaultAppId.isEmpty())
{
return defaultAppId;
}
//Derive the application from the product information
defaultAppId = GetBranding() == nullptr ? QString("") : GetBranding()->GetApplication();
return defaultAppId;
}
void ApplicationContainer::Lock(ApplicationHandle* /*appHandle*/)
{
/*
ApplicationDescriptor eclipseApp = (ApplicationDescriptor) appHandle.getApplicationDescriptor();
{
- QMutexLocker l(&lock);
+ QMutexLocker l(&appDescLock);
switch (isLocked(eclipseApp))
{
case NOT_LOCKED :
break;
case LOCKED_SINGLETON_GLOBAL_RUNNING :
throw new ApplicationException(ApplicationException.APPLICATION_NOT_LAUNCHABLE, NLS.bind(Messages.singleton_running, activeGlobalSingleton.getInstanceId()));
case LOCKED_SINGLETON_GLOBAL_APPS_RUNNING :
throw new ApplicationException(ApplicationException.APPLICATION_NOT_LAUNCHABLE, Messages.apps_running);
case LOCKED_SINGLETON_SCOPED_RUNNING :
throw new ApplicationException(ApplicationException.APPLICATION_NOT_LAUNCHABLE, NLS.bind(Messages.singleton_running, activeScopedSingleton.getInstanceId()));
case LOCKED_SINGLETON_LIMITED_RUNNING :
throw new ApplicationException(ApplicationException.APPLICATION_NOT_LAUNCHABLE, NLS.bind(Messages.max_running, eclipseApp.getApplicationId()));
case LOCKED_MAIN_THREAD_RUNNING :
throw new ApplicationException(ApplicationException.APPLICATION_NOT_LAUNCHABLE, NLS.bind(Messages.main_running, activeMain.getInstanceId()));
default :
break;
}
// ok we can now successfully lock the container
switch (eclipseApp.getCardinalityType())
{
case ApplicationDescriptor::FLAG_CARD_SINGLETON_GLOGAL :
activeGlobalSingleton = appHandle;
break;
case ApplicationDescriptor::FLAG_CARD_SINGLETON_SCOPED :
activeScopedSingleton = appHandle;
break;
case ApplicationDescriptor::FLAG_CARD_LIMITED :
if (activeLimited == null)
activeLimited = new HashMap(3);
ArrayList limited = (ArrayList) activeLimited.get(eclipseApp.getApplicationId());
if (limited == null)
{
limited = new ArrayList(eclipseApp.getCardinality());
activeLimited.put(eclipseApp.getApplicationId(), limited);
}
limited.add(appHandle);
break;
case ApplicationDescriptor::FLAG_CARD_UNLIMITED :
break;
default :
break;
}
if (eclipseApp.getThreadType() == ApplicationDescriptor::FLAG_TYPE_MAIN_THREAD)
{
activeMain = appHandle;
}
activeHandles.add(appHandle);
refreshAppDescriptors();
}
*/
}
void ApplicationContainer::Unlock(ApplicationHandle* /*appHandle*/)
{
/*
- QMutexLocker l(&lock);
+ QMutexLocker l(&appDescLock);
if (activeGlobalSingleton == appHandle)
activeGlobalSingleton = null;
else if (activeScopedSingleton == appHandle)
activeScopedSingleton = null;
else if (((ApplicationDescriptor) appHandle.getApplicationDescriptor()).getCardinalityType() == ApplicationDescriptor::FLAG_CARD_LIMITED) {
if (activeLimited != null) {
ArrayList limited = (ArrayList) activeLimited.get(((ApplicationDescriptor) appHandle.getApplicationDescriptor()).getApplicationId());
if (limited != null)
limited.remove(appHandle);
}
}
if (activeMain == appHandle)
activeMain = null;
if (activeHandles.remove(appHandle))
refreshAppDescriptors(); // only refresh descriptors if we really unlocked something
*/
}
int ApplicationContainer::IsLocked(const ApplicationDescriptor* /*eclipseApp*/) const
{
/*
{
- QMutexLocker l(&lock);
+ QMutexLocker l(&appDescLock);
if (activeGlobalSingleton != null)
return LOCKED_SINGLETON_GLOBAL_RUNNING;
switch (eclipseApp.getCardinalityType()) {
case ApplicationDescriptor::FLAG_CARD_SINGLETON_GLOGAL :
if (activeHandles.size() > 0)
return LOCKED_SINGLETON_GLOBAL_APPS_RUNNING;
break;
case ApplicationDescriptor::FLAG_CARD_SINGLETON_SCOPED :
if (activeScopedSingleton != null)
return LOCKED_SINGLETON_SCOPED_RUNNING;
break;
case ApplicationDescriptor::FLAG_CARD_LIMITED :
if (activeLimited != null) {
ArrayList limited = (ArrayList) activeLimited.get(eclipseApp.getApplicationId());
if (limited != null && limited.size() >= eclipseApp.getCardinality())
return LOCKED_SINGLETON_LIMITED_RUNNING;
}
break;
case ApplicationDescriptor::FLAG_CARD_UNLIMITED :
break;
default :
break;
}
if (eclipseApp.getThreadType() == ApplicationDescriptor::FLAG_TYPE_MAIN_THREAD && activeMain != null)
return LOCKED_MAIN_THREAD_RUNNING;
return NOT_LOCKED;
}
*/
return NOT_LOCKED;
}
ctkApplicationLauncher* ApplicationContainer::addingService(const ctkServiceReference& reference)
{
ctkApplicationLauncher* appLauncher = nullptr;
ctkApplicationRunnable* appRunnable = nullptr;
{
QMutexLocker l(this);
appLauncher = context->getService<ctkApplicationLauncher>(reference);
// see if there is a default main threaded application waiting to run
appRunnable = defaultMainThreadAppHandle;
// null out so we do not attempt to start this handle again
defaultMainThreadAppHandle = nullptr;
if (appRunnable == nullptr && missingApp)
{
missingAppLauncher.reset(new MainApplicationLauncher(this));
appRunnable = missingAppLauncher.data();
missingApp = false;
}
}
if (appRunnable != nullptr)
{
// found a main threaded app; start it now that the app launcher is available
ApplicationHandle* handle = dynamic_cast<ApplicationHandle*>(appRunnable);
appLauncher->launch(appRunnable, handle ? handle->GetArguments()[IApplicationContext::APPLICATION_ARGS] : QVariant());
}
return appLauncher;
}
void ApplicationContainer::modifiedService(const ctkServiceReference& /*reference*/, ctkApplicationLauncher* /*service*/)
{
// Do nothing
}
void ApplicationContainer::removedService(const ctkServiceReference& /*reference*/, ctkApplicationLauncher* /*service*/)
{
// Do nothing
}
void ApplicationContainer::Added(const QList<SmartPointer<IExtension> >& extensions)
{
for (const IExtension::Pointer &extension : extensions)
{
CreateAppDescriptor(extension);
}
}
void ApplicationContainer::Added(const QList<SmartPointer<IExtensionPoint> >& /*extensionPoints*/)
{
// nothing
}
void ApplicationContainer::Removed(const QList<SmartPointer<IExtension> >& extensions)
{
for (const IExtension::Pointer &extension : extensions)
{
RemoveAppDescriptor(extension->GetUniqueIdentifier());
}
}
void ApplicationContainer::Removed(const QList<SmartPointer<IExtensionPoint> >& /*extensionPoints*/)
{
// nothing
}
void ApplicationContainer::RefreshAppDescriptors()
{
- QMutexLocker l(&lock);
+ QMutexLocker l(&appDescLock);
for (ApplicationDescriptor* app : apps.values())
{
app->RefreshProperties();
}
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationContainer.h b/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationContainer.h
index 778bce9295..6cda616af8 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationContainer.h
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationContainer.h
@@ -1,180 +1,180 @@
/*============================================================================
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 BERRYAPPLICATIONCONTAINER_H
#define BERRYAPPLICATIONCONTAINER_H
#include <berryIRegistryEventListener.h>
#include <ctkServiceTracker.h>
#include <ctkServiceTrackerCustomizer.h>
#include <QObject>
#include <QMutex>
struct ctkApplicationLauncher;
struct ctkApplicationRunnable;
namespace berry {
struct IBranding;
struct IExtensionRegistry;
class ApplicationDescriptor;
class ApplicationHandle;
class MainApplicationLauncher;
/*
* This container will discover installed BlueBerry applications and register the
* appropriate ctkApplicationDescriptor service with the service registry.
*/
class ApplicationContainer : public QObject, public QMutex, private IRegistryEventListener,
private ctkServiceTrackerCustomizer<ctkApplicationLauncher*>
{
Q_OBJECT
private:
static const QString PI_RUNTIME; // = "org.blueberry.core.runtime";
static const QString PT_APPLICATIONS; // = "applications";
static const QString PT_APP_VISIBLE; // = "visible";
static const QString PT_APP_THREAD; // = "thread";
static const QString PT_APP_THREAD_ANY; // = "any";
static const QString PT_APP_CARDINALITY; // = "cardinality";
static const QString PT_APP_CARDINALITY_SINGLETON_GLOBAL; // = "singleton-global";
static const QString PT_APP_CARDINALITY_SINGLETON_SCOPED; // = "singleton-scoped";
static const QString PT_APP_CARDINALITY_UNLIMITED; // = "*";
static const QString PT_APP_ICON; // = "icon";
static const QString PT_PRODUCTS; // = "products";
static const QString EXT_ERROR_APP; // = "org.blueberry.core.runtime.app.error";
static const QString PROP_PRODUCT; // = "blueberry.product";
static const QString PROP_BLUEBERRY_APPLICATION; // = "blueberry.application";
static const QString PROP_BLUEBERRY_APPLICATION_LAUNCH_DEFAULT; // = "blueberry.application.launchDefault";
static const int NOT_LOCKED; // = 0;
static const int LOCKED_SINGLETON_GLOBAL_RUNNING; // = 1;
static const int LOCKED_SINGLETON_GLOBAL_APPS_RUNNING; // = 2;
static const int LOCKED_SINGLETON_SCOPED_RUNNING; // = 3;
static const int LOCKED_SINGLETON_LIMITED_RUNNING; // = 4;
static const int LOCKED_MAIN_THREAD_RUNNING; // = 5;
ctkPluginContext* context;
- QMutex lock;
+ QMutex appDescLock;
// A map of ApplicationDescriptors keyed by application ID
/* @GuardedBy(lock) */
QHash<QString, ApplicationDescriptor*> apps;
IExtensionRegistry* extensionRegistry;
QScopedPointer<ctkServiceTracker<ctkApplicationLauncher*>> launcherTracker;
mutable QScopedPointer<IBranding> branding;
mutable bool missingProductReported;
/* @GuardedBy(lock) */
QList<ApplicationHandle*> activeHandles; // the currently active application handles
/* @GuardedBy(lock) */
ApplicationHandle* activeMain; // the handle currently running on the main thread
/* @GuardedBy(lock) */
ApplicationHandle* activeGlobalSingleton; // the current global singleton handle
/* @GuardedBy(lock) */
ApplicationHandle* activeScopedSingleton; // the current scoped singleton handle
/* @GuardedBy(lock) */
QHash<QString, QList<ApplicationHandle*> > activeLimited; // Map of handles that have cardinality limits
mutable QString defaultAppId;
//DefaultApplicationListener defaultAppListener;
ctkApplicationRunnable* defaultMainThreadAppHandle; // holds the default app handle to be run on the main thread
volatile bool missingApp;
QScopedPointer<MainApplicationLauncher> missingAppLauncher;
public:
ApplicationContainer(ctkPluginContext* context, IExtensionRegistry* extensionRegistry);
~ApplicationContainer() override;
void Start();
void Stop();
IBranding* GetBranding() const;
ctkPluginContext* GetContext() const;
void Launch(ApplicationHandle* appHandle);
void Lock(ApplicationHandle* appHandle);
void Unlock(ApplicationHandle* appHandle);
int IsLocked(const ApplicationDescriptor* eclipseApp) const;
void StartDefaultApp(bool delayError);
private:
Q_DISABLE_COPY(ApplicationContainer)
friend class ApplicationHandle;
/*
* Only used to find the default application
*/
ApplicationDescriptor* GetAppDescriptor(const QString& applicationId);
ApplicationDescriptor* CreateAppDescriptor(const SmartPointer<IExtension>& appExtension);
ApplicationDescriptor* RemoveAppDescriptor(const QString& applicationId);
/*
* Registers an ApplicationDescriptor service for each eclipse application
* available in the extension registry.
*/
void RegisterAppDescriptors();
void RegisterAppDescriptor(const QString& applicationId);
/*
* Returns a list of all the available application IDs which are available
* in the extension registry.
*/
QList<SmartPointer<IExtension> > GetAvailableAppExtensions() const;
QString GetAvailableAppsMsg() const;
/*
* Returns the application extension for the specified application ID.
* A RuntimeException is thrown if the extension does not exist for the
* given application ID.
*/
SmartPointer<IExtension> GetAppExtension(const QString& applicationId) const;
Q_SLOT void PluginChanged(const ctkPluginEvent& event);
void StopAllApps();
QString GetDefaultAppId() const;
ctkApplicationLauncher* addingService(const ctkServiceReference& reference) override;
void modifiedService(const ctkServiceReference& reference, ctkApplicationLauncher* service) override;
void removedService(const ctkServiceReference& reference, ctkApplicationLauncher* service) override;
void Added(const QList<SmartPointer<IExtension> >& extensions) override;
void Added(const QList<SmartPointer<IExtensionPoint> >& extensionPoints) override;
void Removed(const QList<SmartPointer<IExtension> >& extensions) override;
void Removed(const QList<SmartPointer<IExtensionPoint> >& extensionPoints) override;
void RefreshAppDescriptors();
};
}
#endif // BERRYAPPLICATIONCONTAINER_H
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationDescriptor.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationDescriptor.cpp
index f15f2dffbd..4bde4b4807 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationDescriptor.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationDescriptor.cpp
@@ -1,267 +1,267 @@
/*============================================================================
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 "berryApplicationDescriptor.h"
#include "berryApplicationHandle.h"
#include "berryApplicationContainer.h"
#include "berryIRuntimeConstants.h"
#include <service/application/ctkApplicationException.h>
namespace berry {
const QString ApplicationDescriptor::APP_TYPE = "blueberry.application.type";
const QString ApplicationDescriptor::APP_DEFAULT = "blueberry.application.default";
const QString ApplicationDescriptor::APP_TYPE_MAIN_THREAD = "main.thread";
const QString ApplicationDescriptor::APP_TYPE_ANY_THREAD = "any.thread";
ApplicationDescriptor::ApplicationDescriptor(const QSharedPointer<ctkPlugin>& contributor, const QString& pid, const QString& name, const QString& iconPath, const Flags& flags, int cardinality, ApplicationContainer* appContainer)
: pid(pid)
, name(name)
, contributor(contributor)
, appContainer(appContainer)
, flags(flags)
, cardinality(cardinality)
, iconPath(iconPath)
, instanceId(0)
, locked(false)
{
if (pid.isEmpty())
{
throw std::invalid_argument("Application ID must not be empty!");
}
}
ApplicationDescriptor::~ApplicationDescriptor()
{
}
QString ApplicationDescriptor::getApplicationId() const
{
return pid;
}
QHash<QString, QVariant> ApplicationDescriptor::getProperties(const QLocale& /*locale*/) const
{
return this->getProperties();
}
QHash<QString, QVariant> berry::ApplicationDescriptor::getProperties() const
{
// just use the service properties; for now we do not localize any properties
return GetServiceProperties();
}
ctkApplicationHandle* ApplicationDescriptor::launch(const QHash<QString, QVariant>& arguments)
{
CheckArgs(arguments);
try
{
// if this application is locked throw an exception.
/*
if (GetLocked())
{
throw ctkIllegalStateException("Cannot launch a locked application.");
}
*/
// initialize the appHandle
ApplicationHandle* appHandle = CreateAppHandle(arguments);
try
{
// use the appContainer to launch the application on the main thread.
appContainer->Launch(appHandle);
}
catch (const std::exception& t)
{
// be sure to destroy the appHandle if an error occurs
try
{
appHandle->destroy();
}
catch (...)
{
// ignore and clean up
}
throw t;
}
return appHandle;
}
catch (const ctkIllegalStateException& ise)
{
throw ise;
}
catch (const ctkApplicationException& ae)
{
throw ae;
}
catch (const ctkException& e)
{
throw ctkApplicationException(ctkApplicationException::APPLICATION_INTERNAL_ERROR, e);
}
catch (const std::exception& e)
{
throw ctkApplicationException(ctkApplicationException::APPLICATION_INTERNAL_ERROR, QString(e.what()));
}
catch (...)
{
throw ctkApplicationException(ctkApplicationException::APPLICATION_INTERNAL_ERROR);
}
}
void ApplicationDescriptor::CheckArgs(const QHash<QString, QVariant> arguments)
{
foreach(QString key, arguments.keys())
{
if (key.isEmpty())
{
throw std::invalid_argument("Empty string is an invalid key");
}
}
}
ctkProperties ApplicationDescriptor::GetServiceProperties() const
{
ctkProperties props;
props[ctkApplicationDescriptor::APPLICATION_PID] = getApplicationId();
if (!name.isEmpty())
{
props[ctkApplicationDescriptor::APPLICATION_NAME] = name;
}
props[ctkApplicationDescriptor::APPLICATION_CONTAINER] = IRuntimeConstants::PI_RUNTIME();
props[ctkApplicationDescriptor::APPLICATION_LOCATION] = GetLocation();
bool launchable = appContainer->IsLocked(this) == 0 ? true : false;
props[ctkApplicationDescriptor::APPLICATION_LAUNCHABLE] = launchable;
props[ctkApplicationDescriptor::APPLICATION_LOCKED] = GetLocked();
bool visible = flags.testFlag(FLAG_VISIBLE);
props[ctkApplicationDescriptor::APPLICATION_VISIBLE] = visible;
props[APP_TYPE] = GetThreadTypeString();
if (flags.testFlag(FLAG_DEFAULT_APP))
{
props[APP_DEFAULT] = true;
}
if (!iconPath.isEmpty())
{
props[ctkApplicationDescriptor::APPLICATION_ICON] = iconPath;
}
return props;
}
ApplicationHandle* ApplicationDescriptor::CreateAppHandle(const QHash<QString, QVariant>& arguments)
{
ApplicationHandle* newAppHandle = new ApplicationHandle(GetInstanceID(), arguments, this);
//appContainer.lock(newAppHandle);
QStringList clazzes;
clazzes.push_back(qobject_interface_iid<ctkApplicationHandle*>());
clazzes.push_back(qobject_interface_iid<IApplicationContext*>());
ctkServiceRegistration appHandleReg = appContainer->GetContext()->registerService(clazzes, newAppHandle,
newAppHandle->GetServiceProperties());
newAppHandle->SetServiceRegistration(appHandleReg);
return newAppHandle;
}
QString ApplicationDescriptor::GetInstanceID() const
{
QMutexLocker l(&mutex);
// make sure the instanceID has not reached the max
if (instanceId == std::numeric_limits<long>::max())
{
instanceId = 0;
}
// create a unique instance id
- return getApplicationId() + "." + instanceId++;
+ return QString("%1.%2").arg(getApplicationId()).arg(instanceId++);
}
QString ApplicationDescriptor::GetLocation() const
{
if (!contributor)
{
return QString();
}
return contributor->getLocation();
}
bool ApplicationDescriptor::GetLocked() const
{
QMutexLocker l(&mutex);
return locked;
}
QString ApplicationDescriptor::GetThreadTypeString() const
{
if (flags.testFlag(FLAG_TYPE_ANY_THREAD))
{
return APP_TYPE_ANY_THREAD;
}
return APP_TYPE_MAIN_THREAD;
}
ApplicationContainer* ApplicationDescriptor::GetContainerManager() const
{
return appContainer;
}
void ApplicationDescriptor::RefreshProperties()
{
ctkServiceRegistration reg = GetServiceRegistration();
if (reg)
{
try
{
reg.setProperties(GetServiceProperties());
}
catch (const ctkIllegalStateException&)
{
// this must mean the service was unregistered
// just ignore
}
}
}
void ApplicationDescriptor::SetServiceRegistration(const ctkServiceRegistration& sr)
{
QMutexLocker l(&registrationMutex);
this->sr = sr;
registrationValidOrWaiting = sr;
registrationMutexCondition.wakeAll();
}
ctkServiceRegistration ApplicationDescriptor::GetServiceRegistration() const
{
QMutexLocker l(&registrationMutex);
if (!sr && registrationValidOrWaiting)
{
registrationMutexCondition.wait(&registrationMutex, 1000); // timeout after 1 second
}
return sr;
}
void ApplicationDescriptor::Unregister()
{
ctkServiceRegistration temp = GetServiceRegistration();
if (temp)
{
SetServiceRegistration(ctkServiceRegistration());
temp.unregister();
}
}
int ApplicationDescriptor::GetThreadType() const
{
return flags & (FLAG_TYPE_ANY_THREAD | FLAG_TYPE_MAIN_THREAD);
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationHandle.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationHandle.cpp
index 9b92df55a2..7fd1e10acc 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationHandle.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryApplicationHandle.cpp
@@ -1,381 +1,381 @@
/*============================================================================
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 "berryApplicationHandle.h"
#include <berryIConfigurationElement.h>
#include <berryIExtension.h>
#include <berryIApplication.h>
#include "berryApplicationDescriptor.h"
#include "berryApplicationContainer.h"
#include "berryCTKPluginActivator.h"
#include <service/application/ctkApplicationException.h>
#include <ctkServiceRegistration.h>
#include <QTime>
#include <QMutexLocker>
#include <QCoreApplication>
namespace berry {
static const QString STARTING = "org.blueberry.app.starting";
static const QString STOPPED = "org.blueberry.app.stopped";
ApplicationHandle::ApplicationHandle(const QString& instanceId, const QHash<QString, QVariant>& arguments,
ApplicationDescriptor* descriptor)
: instanceId(instanceId)
, descriptor(descriptor)
, defaultAppInstance(false)
, arguments(arguments)
, status(FLAG_STARTING)
, result(0)
, setResult(false)
, application(nullptr)
{
if (instanceId.isEmpty() || descriptor == nullptr)
{
throw std::invalid_argument("Parameters must not be null!");
}
defaultAppInstance = arguments.isEmpty() ||
this->arguments.remove(ApplicationDescriptor::APP_DEFAULT);
}
ApplicationDescriptor* ApplicationHandle::getApplicationDescriptor() const
{
return descriptor;
}
QString ApplicationHandle::getState_unlocked() const
{
switch (status)
{
case FLAG_STARTING :
return STARTING;
case FLAG_ACTIVE :
return ApplicationHandle::RUNNING;
case FLAG_STOPPING :
return ApplicationHandle::STOPPING;
case FLAG_STOPPED :
default :
// must only check this if the status is STOPPED; otherwise we throw exceptions before we have set the registration.
if (!GetServiceRegistration())
{
throw ctkIllegalStateException("This instance of the application has been stopped: " + getInstanceId());
}
return STOPPED;
}
}
QString ApplicationHandle::getState() const
{
QMutexLocker l(&mutex);
return getState_unlocked();
}
QVariant ApplicationHandle::getExitValue(long timeout) const
{
QMutexLocker l(&mutex);
if (!handleRegistration && application == nullptr) return result;
QTime stopTime = QTime::currentTime().addMSecs(timeout);
while(!setResult && (QTime::currentTime() < stopTime || timeout == 0))
{
QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );
}
if (!result.isValid())
{
throw ctkApplicationException(ctkApplicationException::APPLICATION_EXITVALUE_NOT_AVAILABLE);
}
return result;
}
QString ApplicationHandle::getInstanceId() const
{
return instanceId;
}
void ApplicationHandle::destroy()
{
if (STOPPING == getState()) return;
// when this method is called we must force the application to exit.
// first set the status to stopping
SetAppStatus(FLAG_STOPPING);
// now force the application to stop
IApplication* app = GetApplication();
if (app != nullptr)
{
app->Stop();
}
// make sure the app status is stopped
SetAppStatus(FLAG_STOPPED);
}
QHash<QString, QVariant> ApplicationHandle::GetArguments() const
{
return arguments;
}
void ApplicationHandle::ApplicationRunning()
{
// first set the application handle status to running
SetAppStatus(FLAG_ACTIVE);
// now run the splash handler
/*
final ServiceReference[] monitors = getStartupMonitors();
if (monitors == null)
return;
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
// just continue ... the exception has already been logged by
// handleException(ISafeRunnable)
}
public void run() throws Exception {
for (int i = 0; i < monitors.length; i++) {
StartupMonitor monitor = (StartupMonitor) Activator.getContext().getService(monitors[i]);
if (monitor != null) {
monitor.applicationRunning();
Activator.getContext().ungetService(monitors[i]);
}
}
}
});
*/
}
QVariant ApplicationHandle::run(const QVariant& context_)
{
QVariant context = context_;
if (context.isValid())
{
// always force the use of the context if it is not null
arguments[IApplicationContext::APPLICATION_ARGS] = context;
}
else
{
// get the context from the arguments
context = arguments[IApplicationContext::APPLICATION_ARGS];
}
QVariant tempResult;
try
{
{
QMutexLocker l(&mutex);
if (!(status.testFlag(FLAG_STARTING) || status.testFlag(FLAG_STOPPING)))
{
throw ctkApplicationException(ctkApplicationException::APPLICATION_INTERNAL_ERROR,
QString("The application instance has been stopped before it could be started: ") + getInstanceId());
}
application = GetConfiguration()->CreateExecutableExtension<IApplication>("run");
waitCondition.wakeAll();
}
tempResult = application->Start(this);
- if (!tempResult.isValid()) tempResult = QVariant(QVariant::Int);
+ if (!tempResult.isValid()) tempResult = QVariant();
tempResult = SetInternalResult(tempResult, nullptr);
}
catch (...)
{
tempResult = SetInternalResult(tempResult, nullptr);
throw;
}
if (org_blueberry_core_runtime_Activator::DEBUG)
{
qDebug() << QString("The application \"%1\" returned with code: %2.").arg(
getApplicationDescriptor()->getApplicationId()).arg(tempResult.toString());
}
return tempResult;
}
void ApplicationHandle::stop()
{
try
{
destroy();
}
catch (const ctkIllegalStateException&)
{
// Do nothing; we don't care that the application was already stopped
// return with no error
}
}
void ApplicationHandle::SetAppStatus_unlocked(Status status)
{
if (this->status == status)
{
return;
}
if (status & FLAG_STARTING)
{
throw std::invalid_argument("Cannot set app status to starting");
}
// if status is stopping and the context is already stopping then return
if (status & FLAG_STOPPING)
{
if (this->status & (FLAG_STOPPING | FLAG_STOPPED))
{
return;
}
}
// change the service properties to reflect the state change.
this->status = status;
ctkServiceRegistration handleReg = GetServiceRegistration();
if (!handleReg) return;
handleReg.setProperties(GetServiceProperties_unlocked());
// if the status is stopped then unregister the service
if (this->status & FLAG_STOPPED)
{
// GetApplicationDescriptor().getContainerManager().unlock(this);
handleReg.unregister();
SetServiceRegistration(ctkServiceRegistration());
}
}
void ApplicationHandle::SetAppStatus(Status status)
{
QMutexLocker l(&mutex);
SetAppStatus_unlocked(status);
}
void ApplicationHandle::SetServiceRegistration(const ctkServiceRegistration& sr)
{
this->handleRegistration = sr;
}
ctkServiceRegistration ApplicationHandle::GetServiceRegistration() const
{
return handleRegistration;
}
ctkDictionary ApplicationHandle::GetServiceProperties_unlocked() const
{
ctkDictionary props;
props[APPLICATION_PID] = getInstanceId();
props[APPLICATION_STATE] = getState_unlocked();
props[APPLICATION_DESCRIPTOR] = getApplicationDescriptor()->getApplicationId();
props[ApplicationDescriptor::APP_TYPE] = getApplicationDescriptor()->GetThreadTypeString();
props[APPLICATION_SUPPORTS_EXITVALUE] = true;
if (defaultAppInstance)
{
props[ApplicationDescriptor::APP_DEFAULT] = defaultAppInstance;
}
return props;
}
ctkDictionary ApplicationHandle::GetServiceProperties() const
{
ctkDictionary props;
props[APPLICATION_PID] = getInstanceId();
props[APPLICATION_STATE] = getState();
props[APPLICATION_DESCRIPTOR] = getApplicationDescriptor()->getApplicationId();
props[ApplicationDescriptor::APP_TYPE] = getApplicationDescriptor()->GetThreadTypeString();
props[APPLICATION_SUPPORTS_EXITVALUE] = true;
if (defaultAppInstance)
{
props[ApplicationDescriptor::APP_DEFAULT] = defaultAppInstance;
}
return props;
}
QVariant ApplicationHandle::SetInternalResult(const QVariant& result, IApplication* /*tokenApp*/)
{
QMutexLocker l(&mutex);
if (setResult)
{
throw ctkIllegalStateException("The result of the application is already set.");
}
/*
if (isAsync) {
if (!setAsyncResult)
throw new IllegalStateException("The application must return IApplicationContext.EXIT_ASYNC_RESULT to set asynchronous results."); //$NON-NLS-1$
if (application != tokenApp)
throw new IllegalArgumentException("The application is not the correct instance for this application context."); //$NON-NLS-1$
} else {
if (result == IApplicationContext.EXIT_ASYNC_RESULT) {
setAsyncResult = true;
return nullptr_RESULT; // the result well be set with setResult
}
}
*/
this->result = result;
setResult = true;
application = nullptr;
waitCondition.wakeAll();
// The application exited itself; notify the app context
SetAppStatus_unlocked(FLAG_STOPPING); // must ensure the STOPPING event is fired
SetAppStatus_unlocked(FLAG_STOPPED);
// only set the exit code property if this is the default application
// (bug 321386) only set the exit code if the result != null; when result == null we assume an exception was thrown
if (IsDefault() && !result.isNull())
{
//FrameworkProperties::SetProperty(FrameworkProperties::PROP_EXITCODE, result.toInt());
}
return result;
}
IApplication* ApplicationHandle::GetApplication() const
{
QMutexLocker l(&mutex);
if (handleRegistration && application == nullptr)
{
// the handle has been initialized by the container but the launcher has not
// gotten around to creating the application object and starting it yet.
waitCondition.wait(&mutex, 5000); // timeout after a while in case there was an internal error and there will be no application created
}
return application;
}
bool ApplicationHandle::IsDefault() const
{
return defaultAppInstance;
}
IConfigurationElement::Pointer ApplicationHandle::GetConfiguration() const
{
IExtension::Pointer applicationExtension = getApplicationDescriptor()->GetContainerManager()->
GetAppExtension(getApplicationDescriptor()->getApplicationId());
if (applicationExtension.IsNull())
{
throw ctkRuntimeException(QString("Application \"%1\" could not be found in the registry. The applications available are: %2.")
.arg(getApplicationDescriptor()->getApplicationId())
.arg(getApplicationDescriptor()->GetContainerManager()->GetAvailableAppsMsg()));
}
QList<IConfigurationElement::Pointer> configs = applicationExtension->GetConfigurationElements();
if (configs.isEmpty())
{
throw ctkRuntimeException(QString("Invalid (empty) application extension \"%1\".")
.arg(getApplicationDescriptor()->getApplicationId()));
}
return configs.front();
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp
index e95b2dbebc..fd2cb919fa 100755
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp
@@ -1,284 +1,284 @@
/*============================================================================
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 NOMINMAX
#define NOMINMAX
#endif
#include "berryCTKPluginActivator.h"
#include <berryIApplication.h>
#include <berryIConfigurationElement.h>
#include <berryIContributor.h>
#include "berryApplicationContainer.h"
#include "berryPlatform.h"
#include "berryInternalPlatform.h"
#include "berryErrorApplication.h"
#include "berryExtensionRegistry.h"
#include "berryRegistryConstants.h"
#include "berryRegistryProperties.h"
#include "berryRegistryStrategy.h"
#include "berryRegistryContributor.h"
#include <QCoreApplication>
#include <QDebug>
namespace berry {
static const QString XP_APPLICATIONS = "org.blueberry.osgi.applications";
ctkPluginContext* org_blueberry_core_runtime_Activator::context = nullptr;
QScopedPointer<ApplicationContainer> org_blueberry_core_runtime_Activator::appContainer;
const bool org_blueberry_core_runtime_Activator::DEBUG = false;
void org_blueberry_core_runtime_Activator::start(ctkPluginContext* context)
{
this->context = context;
BERRY_REGISTER_EXTENSION_CLASS(ErrorApplication, context)
RegistryProperties::SetContext(context);
//ProcessCommandLine();
this->startRegistry();
// // register a listener to catch new plugin installations/resolutions.
// pluginListener.reset(new CTKPluginListener(m_ExtensionPointService));
// context->connectPluginListener(pluginListener.data(), SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection);
// // populate the registry with all the currently installed plugins.
// // There is a small window here while processPlugins is being
// // called where the pluginListener may receive a ctkPluginEvent
// // to add/remove a plugin from the registry. This is ok since
// // the registry is a synchronized object and will not add the
// // same bundle twice.
// pluginListener->processPlugins(context->getPlugins());
this->startAppContainer();
InternalPlatform::GetInstance()->Start(context);
}
void org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context)
{
InternalPlatform::GetInstance()->Stop(context);
//pluginListener.reset();
//Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID);
this->stopRegistry();
RegistryProperties::SetContext(nullptr);
stopAppContainer();
this->context = nullptr;
}
ctkPluginContext* org_blueberry_core_runtime_Activator::getPluginContext()
{
return context;
}
ApplicationContainer* org_blueberry_core_runtime_Activator::GetContainer()
{
return appContainer.data();
}
#if defined(Q_OS_LINUX) || defined(Q_OS_DARWIN)
#include <dlfcn.h>
QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol)
{
if (symbol == nullptr) return QString();
Dl_info info = {nullptr,nullptr,nullptr,nullptr};
if(dladdr(symbol, &info) == 0)
{
return QString();
}
else if(info.dli_fname)
{
QFile soPath(info.dli_fname);
int index = soPath.fileName().lastIndexOf('.');
QString pluginId = soPath.fileName().left(index);
if (pluginId.startsWith("lib"))
pluginId = pluginId.mid(3);
return pluginId.replace('_', '.');
}
return QString();
}
#elif defined(Q_CC_MSVC)
#include <ctkBackTrace.h>
#include <windows.h>
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4091)
#endif
#include <dbghelp.h>
#ifdef _MSC_VER
# pragma warning(pop)
#endif
QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol)
{
if (symbol == nullptr) return QString();
if (ctk::DebugSymInitialize())
{
std::vector<char> moduleBuffer(sizeof(IMAGEHLP_MODULE64));
PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front();
pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo))
{
QString pluginId = pModuleInfo->ModuleName;
return pluginId.replace('_', '.');
}
}
return QString();
}
#endif
QSharedPointer<ctkPlugin> org_blueberry_core_runtime_Activator::GetPlugin(const SmartPointer<IContributor>& contributor)
{
if (RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>())
{
bool okay = false;
long id = regContributor->GetActualId().toLong(&okay);
if (okay)
{
if (context != nullptr)
{
return context->getPlugin(id);
}
}
else
{
// try using the name of the contributor below
}
}
auto plugins = context->getPlugins();
//Return the first plugin that is not installed or uninstalled
- for (auto plugin : qAsConst(plugins))
+ for (auto plugin : std::as_const(plugins))
{
if (!(plugin->getState() == ctkPlugin::INSTALLED ||
plugin->getState() == ctkPlugin::UNINSTALLED))
{
return plugin;
}
}
return QSharedPointer<ctkPlugin>();
}
org_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator()
: userRegistryKey(new QObject())
, masterRegistryKey(new QObject())
{
}
org_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator()
{
}
void org_blueberry_core_runtime_Activator::startRegistry()
{
// see if the customer suppressed the creation of default registry
QString property = context->getProperty(RegistryConstants::PROP_DEFAULT_REGISTRY).toString();
if (property.compare("false", Qt::CaseInsensitive) == 0) return;
// check to see if we need to use null as a userToken
if (context->getProperty(RegistryConstants::PROP_REGISTRY_nullptr_USER_TOKEN).toString().compare("true", Qt::CaseInsensitive) == 0)
{
userRegistryKey.reset(nullptr);
}
// Determine primary and alternative registry locations. BlueBerry extension registry cache
// can be found in one of the two locations:
// a) in the local configuration area (standard location passed in by the platform) -> priority
// b) in the shared configuration area (typically, shared install is used)
QList<QString> registryLocations;
QList<bool> readOnlyLocations;
RegistryStrategy* strategy = nullptr;
//Location configuration = OSGIUtils.getDefault().getConfigurationLocation();
QString configuration = context->getDataFile("").absoluteFilePath();
if (configuration.isEmpty())
{
RegistryProperties::SetProperty(RegistryConstants::PROP_NO_REGISTRY_CACHE, "true");
RegistryProperties::SetProperty(RegistryConstants::PROP_NO_LAZY_REGISTRY_CACHE_LOADING, "true");
strategy = new RegistryStrategy(QList<QString>(), QList<bool>(), masterRegistryKey.data());
}
else
{
//File primaryDir = new File(configuration.getURL().getPath() + '/' + STORAGE_DIR);
//bool primaryReadOnly = configuration.isReadOnly();
QString primaryDir = configuration;
bool primaryReadOnly = false;
//Location parentLocation = configuration.getParentLocation();
QString parentLocation;
if (!parentLocation.isEmpty())
{
// File secondaryDir = new File(parentLocation.getURL().getFile() + '/' + IRegistryConstants.RUNTIME_NAME);
// registryLocations << primaryDir << secondaryDir;
// readOnlyLocations << primaryReadOnly << true; // secondary BlueBerry location is always read only
}
else
{
registryLocations << primaryDir;
readOnlyLocations << primaryReadOnly;
}
strategy = new RegistryStrategy(registryLocations, readOnlyLocations, masterRegistryKey.data());
}
auto registry = new ExtensionRegistry(strategy, masterRegistryKey.data(), userRegistryKey.data());
defaultRegistry.reset(registry);
registryServiceReg = context->registerService<IExtensionRegistry>(registry);
//commandRegistration = EquinoxUtils.registerCommandProvider(Activator.getContext());
}
void org_blueberry_core_runtime_Activator::stopRegistry()
{
if (!defaultRegistry.isNull())
{
registryServiceReg.unregister();
defaultRegistry->Stop(masterRegistryKey.data());
}
// if (!commandRegistration.isNull())
// {
// commandRegistration.unregister();
// }
}
void org_blueberry_core_runtime_Activator::startAppContainer()
{
appContainer.reset(new ApplicationContainer(context, defaultRegistry.data()));
appContainer->Start();
}
void org_blueberry_core_runtime_Activator::stopAppContainer()
{
appContainer->Stop();
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryConfigurationElement.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryConfigurationElement.cpp
index 5b98a2a021..ce073e600e 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryConfigurationElement.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryConfigurationElement.cpp
@@ -1,311 +1,311 @@
/*============================================================================
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 "berryConfigurationElement.h"
#include "berryIExecutableExtension.h"
#include "berryIExecutableExtensionFactory.h"
#include "berryConfigurationElementHandle.h"
#include "berryStatus.h"
#include "berryRegistryMessages.h"
#include "berryRegistryConstants.h"
#include "berryCoreException.h"
#include "berryExtensionRegistry.h"
#include "berryRegistryObjectManager.h"
#include "berryRegistryContributor.h"
#include "berryObjectString.h"
#include "berryObjectStringMap.h"
-#include <QRegExp>
+#include <QRegularExpression>
namespace berry {
ConfigurationElement::ConfigurationElement(ExtensionRegistry* registry, bool persist)
: RegistryObject(registry, persist)
{
}
ConfigurationElement::ConfigurationElement(int self, const QString& contributorId,
const QString& name, const QList<QString>& propertiesAndValue,
const QList<int>& children, int extraDataOffset, int parent,
short parentType, ExtensionRegistry* registry, bool persist)
: RegistryObject(registry, persist), parentId(parent), parentType(parentType),
propertiesAndValue(propertiesAndValue), name(name), contributorId(contributorId)
{
SetObjectId(self);
SetRawChildren(children);
SetExtraDataOffset(extraDataOffset);
}
void ConfigurationElement::ThrowException(const QString& message, const ctkException& exc)
{
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME,
RegistryConstants::PLUGIN_ERROR, message, exc,
BERRY_STATUS_LOC));
throw CoreException(status);
}
void ConfigurationElement::ThrowException(const QString &message)
{
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME,
RegistryConstants::PLUGIN_ERROR, message,
BERRY_STATUS_LOC));
throw CoreException(status);
}
QString ConfigurationElement::GetValue() const
{
return GetValueAsIs();
}
QString ConfigurationElement::GetValueAsIs() const
{
if (!propertiesAndValue.empty() && propertiesAndValue.size() % 2 == 1)
return propertiesAndValue.back();
return QString();
}
QString ConfigurationElement::GetAttributeAsIs(const QString& attrName) const
{
if (propertiesAndValue.size() <= 1)
return QString();
int size = propertiesAndValue.size() - (propertiesAndValue.size() % 2);
for (int i = 0; i < size; i += 2)
{
if (propertiesAndValue[i] == attrName)
return propertiesAndValue[i + 1];
}
return QString();
}
QList<QString> ConfigurationElement::GetAttributeNames() const
{
if (propertiesAndValue.size() <= 1)
return QList<QString>();
QList<QString> result;
int size = propertiesAndValue.size() / 2;
for (int i = 0; i < size; i++)
{
result.push_back(propertiesAndValue[i * 2]);
}
return result;
}
void ConfigurationElement::SetProperties(const QList<QString>& value)
{
propertiesAndValue = value;
}
QList<QString> ConfigurationElement::GetPropertiesAndValue() const
{
return propertiesAndValue;
}
void ConfigurationElement::SetValue(const QString& value)
{
if (propertiesAndValue.empty())
{
propertiesAndValue.push_back(value);
return;
}
if (propertiesAndValue.size() % 2 == 1)
{
propertiesAndValue[propertiesAndValue.size() - 1] = value;
return;
}
propertiesAndValue.push_back(value);
}
void ConfigurationElement::SetContributorId(const QString& id)
{
contributorId = id;
}
QString ConfigurationElement::GetContributorId() const
{
return contributorId;
}
void ConfigurationElement::SetParentId(int objectId)
{
parentId = objectId;
}
QString ConfigurationElement::GetName() const
{
return name;
}
void ConfigurationElement::SetName(const QString& name)
{
this->name = name;
}
void ConfigurationElement::SetParentType(short type)
{
parentType = type;
}
QObject* ConfigurationElement::CreateExecutableExtension(const QString& attributeName)
{
QString prop;
QString executable;
QString contributorName;
QString className;
Object::Pointer initData;
int i = 0;
if (!attributeName.isEmpty())
{
prop = GetAttribute(attributeName);
}
else
{
// property not specified, try as element value
prop = GetValue().trimmed();
}
if (prop.isEmpty())
{
// property not defined, try as a child element
QList<ConfigurationElement::Pointer> exec = GetChildren(attributeName);
if (!exec.empty())
{
ConfigurationElement::Pointer element = exec[0]; // assumes single definition
contributorName = element->GetAttribute("plugin");
className = element->GetAttribute("class");
QList<ConfigurationElement::Pointer> parms = element->GetChildren("parameter");
if (!parms.empty())
{
QHash<QString,QString> initParms;
for (i = 0; i < parms.size(); i++)
{
QString pname = parms[i]->GetAttribute("name");
if (!pname.isEmpty())
initParms.insert(pname, parms[i]->GetAttribute("value"));
}
if (!initParms.isEmpty())
initData = new ObjectStringMap(initParms);
}
}
else
{
// specified name is not a simple attribute nor child element
ThrowException(QString("Executable extension definition for \"%1\" not found.").arg(attributeName));
}
}
else
{
// simple property or element value, parse it into its components
- i = prop.indexOf(QRegExp("[^:]:[^:]"));
+ i = prop.indexOf(QRegularExpression("[^:]:[^:]"));
if (i != -1)
{
executable = prop.left(i+1).trimmed();
initData = new ObjectString(prop.mid(i + 2).trimmed());
}
else
{
executable = prop;
}
i = executable.indexOf('/');
if (i != -1)
{
contributorName = executable.left(i).trimmed();
className = executable.mid(i + 1).trimmed();
}
else
{
className = executable;
}
}
// create a new instance
RegistryContributor::Pointer defaultContributor = registry->GetObjectManager()->GetContributor(contributorId);
QObject* result = registry->CreateExecutableExtension(defaultContributor, className, contributorName);
// Check if we have extension adapter and initialize;
// Make the call even if the initialization string is null
try
{
// We need to take into account both "old" and "new" style executable extensions
if (IExecutableExtension* execExt = qobject_cast<IExecutableExtension*>(result))
{
ConfigurationElementHandle::Pointer confElementHandle(new ConfigurationElementHandle(
registry->GetObjectManager(), GetObjectId()));
execExt->SetInitializationData(confElementHandle, attributeName, initData);
}
}
catch (const CoreException& ce)
{
// user code threw exception
throw ce;
}
catch (const ctkException& te)
{
// user code caused exception
ThrowException(QString("Plug-in \"%1\" was unable to execute setInitializationData on an instance of \"%2\".")
.arg(GetContributor()->GetName()).arg(className), te);
}
// Deal with executable extension factories.
if (IExecutableExtensionFactory* execExtFactory = qobject_cast<IExecutableExtensionFactory*>(result))
{
result = execExtFactory->Create();
}
return result;
}
QString ConfigurationElement::GetAttribute(const QString& attrName, const QLocale& /*locale*/) const
{
registry->LogMultiLangError();
return GetAttribute(attrName);
}
QString ConfigurationElement::GetValue(const QLocale& /*locale*/) const
{
registry->LogMultiLangError();
return GetValue();
}
QString ConfigurationElement::GetAttribute(const QString& attrName) const
{
return GetAttributeAsIs(attrName);
}
QList<ConfigurationElement::Pointer> ConfigurationElement::GetChildren(const QString& childrenName) const
{
QList<ConfigurationElement::Pointer> result;
if (GetRawChildren().empty())
return result;
RegistryObjectManager::Pointer objectManager = registry->GetObjectManager();
for (int i = 0; i < children.size(); i++)
{
ConfigurationElement::Pointer toTest = objectManager->GetObject(
children[i], NoExtraData() ? RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT).Cast<ConfigurationElement>();
if (toTest->name == childrenName)
{
result.push_back(toTest);
}
}
return result;
}
SmartPointer<IContributor> ConfigurationElement::GetContributor() const
{
return registry->GetObjectManager()->GetContributor(contributorId);
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp
index bd600d2bcc..360ee8568c 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp
@@ -1,1340 +1,1340 @@
/*============================================================================
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 "berryExtensionRegistry.h"
#include "berryCombinedEventDelta.h"
#include "berryConfigurationElement.h"
#include "berryConfigurationElementAttribute.h"
#include "berryConfigurationElementDescription.h"
#include "berryExtension.h"
#include "berryExtensionHandle.h"
#include "berryExtensionPoint.h"
#include "berryExtensionPointHandle.h"
#include "berryExtensionsParser.h"
#include "berryIConfigurationElement.h"
#include "berryIExtension.h"
#include "berryIExtensionPoint.h"
#include "berrySimpleExtensionPointFilter.h"
#include "berryMultiStatus.h"
#include "berryRegistryConstants.h"
#include "berryRegistryContribution.h"
#include "berryRegistryContributor.h"
#include "berryRegistryMessages.h"
#include "berryRegistryObjectFactory.h"
#include "berryRegistryObjectManager.h"
#include "berryRegistryProperties.h"
#include "berryRegistryStrategy.h"
#include "berryStatus.h"
#include <QThread>
-#include <QTime>
+#include <QElapsedTimer>
namespace berry {
struct ExtensionRegistry::ListenerInfo {
IExtensionPointFilter filter;
IRegistryEventListener* listener;
ListenerInfo(IRegistryEventListener* listener, const IExtensionPointFilter& filter)
: filter(filter), listener(listener)
{
}
/**
* Used by ListenerList to ensure uniqueness.
*/
bool operator==(const ListenerInfo& another) const
{
return another.listener == this->listener;
}
};
void ExtensionRegistry::Add(const SmartPointer<RegistryContribution> &element)
{
QWriteLocker l(&access);
eventDelta = CombinedEventDelta::RecordAddition();
BasicAdd(element, true);
FireRegistryChangeEvent();
eventDelta.Reset();
}
QString ExtensionRegistry::AddExtension(int extension)
{
Extension::Pointer addedExtension = registryObjects->GetObject(extension, RegistryObjectManager::EXTENSION).Cast<Extension>();
QString extensionPointToAddTo = addedExtension->GetExtensionPointIdentifier();
ExtensionPoint::Pointer extPoint = registryObjects->GetExtensionPointObject(extensionPointToAddTo);
//orphan extension
if (extPoint.IsNull())
{
registryObjects->AddOrphan(extensionPointToAddTo, extension);
return QString();
}
// otherwise, link them
QList<int> newExtensions = extPoint->GetRawChildren();
newExtensions.push_back(extension);
Link(extPoint, newExtensions);
if (!eventDelta.IsNull())
eventDelta.RememberExtension(extPoint, extension);
return extPoint->GetNamespace();
//return RecordChange(extPoint, extension, ExtensionDelta::ADDED);
}
QString ExtensionRegistry::AddExtensionPoint(int extPoint)
{
ExtensionPoint::Pointer extensionPoint = registryObjects->GetObject(extPoint, RegistryObjectManager::EXTENSION_POINT).Cast<ExtensionPoint>();
if (!eventDelta.IsNull())
eventDelta.RememberExtensionPoint(extensionPoint);
QList<int> orphans = registryObjects->RemoveOrphans(extensionPoint->GetUniqueIdentifier());
if (orphans.empty())
return QString();
Link(extensionPoint, orphans);
if (!eventDelta.IsNull())
eventDelta.RememberExtensions(extensionPoint, orphans);
return extensionPoint->GetNamespace();
//return RecordChange(extensionPoint, orphans, ExtensionDelta::ADDED);
}
QSet<QString> ExtensionRegistry::AddExtensionsAndExtensionPoints(const SmartPointer<RegistryContribution>& element)
{
// now add and resolve extensions and extension points
QSet<QString> affectedNamespaces;
QList<int> extPoints = element->GetExtensionPoints();
for (int i = 0; i < extPoints.size(); i++)
{
QString namespaze = this->AddExtensionPoint(extPoints[i]);
if (!namespaze.isEmpty())
affectedNamespaces.insert(namespaze);
}
QList<int> extensions = element->GetExtensions();
for (int i = 0; i < extensions.size(); i++)
{
QString namespaze = this->AddExtension(extensions[i]);
if (!namespaze.isEmpty())
affectedNamespaces.insert(namespaze);
}
return affectedNamespaces;
}
void ExtensionRegistry::AddListenerInternal(IRegistryEventListener* listener, const IExtensionPointFilter& filter)
{
listeners.Add(ListenerInfo(listener, filter));
}
void ExtensionRegistry::BasicAdd(const SmartPointer<RegistryContribution>& element, bool link)
{
registryObjects->AddContribution(element);
if (!link)
return;
AddExtensionsAndExtensionPoints(element);
SetObjectManagers(registryObjects->CreateDelegatingObjectManager(
registryObjects->GetAssociatedObjects(element->GetContributorId())));
}
void ExtensionRegistry::SetObjectManagers(const SmartPointer<IObjectManager>& manager)
{
if (!eventDelta.IsNull())
eventDelta.SetObjectManager(manager);
}
void ExtensionRegistry::BasicRemove(const QString& contributorId)
{
// ignore anonymous namespaces
RemoveExtensionsAndExtensionPoints(contributorId);
QHash<int, RegistryObject::Pointer> associatedObjects = registryObjects->GetAssociatedObjects(contributorId);
registryObjects->RemoveObjects(associatedObjects);
registryObjects->AddNavigableObjects(associatedObjects); // put the complete set of navigable objects
SetObjectManagers(registryObjects->CreateDelegatingObjectManager(associatedObjects));
registryObjects->RemoveContribution(contributorId);
registryObjects->RemoveContributor(contributorId);
}
void ExtensionRegistry::FireRegistryChangeEvent()
{
// if there is nothing to say, just bail out
if (listeners.IsEmpty())
{
return;
}
// for thread safety, create tmp collections
QList<ListenerInfo> tmpListeners = listeners.GetListeners();
// do the notification asynchronously
//strategy->ScheduleChangeEvent(tmpListeners, tmpDeltas, this);
this->ScheduleChangeEvent(tmpListeners, eventDelta);
}
//RegistryDelta ExtensionRegistry::GetDelta(const QString& namespaze) const
//{
// // is there a delta for the plug-in?
// RegistryDelta existingDelta = deltas.value(namespaze);
// if (existingDelta != null)
// return existingDelta;
// //if not, create one
// RegistryDelta delta = new RegistryDelta();
// deltas.put(namespace, delta);
// return delta;
//}
void ExtensionRegistry::Link(const SmartPointer<ExtensionPoint>& extPoint, const QList<int>& extensions)
{
extPoint->SetRawChildren(extensions);
registryObjects->Add(extPoint, true);
}
//QString ExtensionRegistry::RecordChange(const SmartPointer<ExtensionPoint>& extPoint, int extension, int kind)
//{
// // avoid computing deltas when there are no listeners
// if (listeners.isEmpty())
// return QString();
// ExtensionDelta extensionDelta = new ExtensionDelta();
// extensionDelta.setExtension(extension);
// extensionDelta.setExtensionPoint(extPoint.getObjectId());
// extensionDelta.setKind(kind);
// getDelta(extPoint.getNamespace()).addExtensionDelta(extensionDelta);
// return extPoint.getNamespace();
//}
//QString ExtensionRegistry::RecordChange(const SmartPointer<ExtensionPoint>& extPoint, const QList<int>& extensions, int kind)
//{
// if (listeners.isEmpty())
// return null;
// QString namespace = extPoint.getNamespace();
// if (extensions == null || extensions.length == 0)
// return namespace;
// RegistryDelta pluginDelta = getDelta(extPoint.getNamespace());
// for (int i = 0; i < extensions.length; i++) {
// ExtensionDelta extensionDelta = new ExtensionDelta();
// extensionDelta.setExtension(extensions[i]);
// extensionDelta.setExtensionPoint(extPoint.getObjectId());
// extensionDelta.setKind(kind);
// pluginDelta.addExtensionDelta(extensionDelta);
// }
// return namespace;
//}
QString ExtensionRegistry::RemoveExtension(int extensionId)
{
Extension::Pointer extension = registryObjects->GetObject(extensionId, RegistryObjectManager::EXTENSION).Cast<Extension>();
registryObjects->RemoveExtensionFromNamespaceIndex(extensionId, extension->GetNamespaceIdentifier());
QString xptName = extension->GetExtensionPointIdentifier();
ExtensionPoint::Pointer extPoint = registryObjects->GetExtensionPointObject(xptName);
if (extPoint.IsNull())
{
registryObjects->RemoveOrphan(xptName, extensionId);
return QString();
}
// otherwise, unlink the extension from the extension point
QList<int> existingExtensions = extPoint->GetRawChildren();
QList<int> newExtensions;
if (existingExtensions.size() > 1)
{
for (int i = 0; i < existingExtensions.size(); ++i)
if (existingExtensions[i] != extension->GetObjectId())
newExtensions.push_back(existingExtensions[i]);
}
Link(extPoint, newExtensions);
if (!eventDelta.IsNull())
eventDelta.RememberExtension(extPoint, extensionId);
return extPoint->GetNamespace();
//return recordChange(extPoint, extension.getObjectId(), IExtensionDelta.REMOVED);
}
QString ExtensionRegistry::RemoveExtensionPoint(int extPoint)
{
ExtensionPoint::Pointer extensionPoint = registryObjects->GetObject(
extPoint, RegistryObjectManager::EXTENSION_POINT).Cast<ExtensionPoint>();
registryObjects->RemoveExtensionPointFromNamespaceIndex(extPoint, extensionPoint->GetNamespace());
QList<int> existingExtensions = extensionPoint->GetRawChildren();
if (!existingExtensions.empty())
{
registryObjects->AddOrphans(extensionPoint->GetUniqueIdentifier(), existingExtensions);
Link(extensionPoint, QList<int>());
}
if (!eventDelta.IsNull())
{
eventDelta.RememberExtensionPoint(extensionPoint);
eventDelta.RememberExtensions(extensionPoint, existingExtensions);
}
return extensionPoint->GetNamespace();
//return recordChange(extensionPoint, existingExtensions, IExtensionDelta.REMOVED);
}
QSet<QString> ExtensionRegistry::RemoveExtensionsAndExtensionPoints(const QString& contributorId)
{
QSet<QString> affectedNamespaces;
QList<int> extensions = registryObjects->GetExtensionsFrom(contributorId);
for (int i = 0; i < extensions.size(); i++)
{
QString namespaze = this->RemoveExtension(extensions[i]);
if (!namespaze.isEmpty())
affectedNamespaces.insert(namespaze);
}
// remove extension points
QList<int> extPoints = registryObjects->GetExtensionPointsFrom(contributorId);
for (int i = 0; i < extPoints.size(); i++)
{
QString namespaze = this->RemoveExtensionPoint(extPoints[i]);
if (!namespaze.isEmpty())
affectedNamespaces.insert(namespaze);
}
return affectedNamespaces;
}
struct ExtensionRegistry::QueueElement
{
QList<ListenerInfo> listenerInfos;
CombinedEventDelta scheduledDelta;
QueueElement()
{
}
QueueElement(const QList<ListenerInfo>& infos, const CombinedEventDelta& delta)
: listenerInfos(infos), scheduledDelta(delta)
{
}
};
class ExtensionRegistry::RegistryEventThread : public QThread
{
private:
QAtomicInt stop;
ExtensionRegistry* registry;
Queue& queue;
public:
RegistryEventThread(ExtensionRegistry* registry, Queue& queue)
: stop(0), registry(registry), queue(queue)
{
this->setObjectName("Extension Registry Event Dispatcher");
}
void interrupt()
{
stop.fetchAndStoreOrdered(1);
}
void run() override
{
while (!stop.fetchAndAddOrdered(0))
{
QueueElement element;
{
Queue::Locker l(&queue);
while (queue.empty())
queue.wait();
element = queue.takeFirst();
}
registry->ProcessChangeEvent(element.listenerInfos, element.scheduledDelta);
}
}
};
bool ExtensionRegistry::CheckReadWriteAccess(QObject* key, bool persist) const
{
if (masterToken == key)
return true;
if (userToken == key && !persist)
return true;
return false;
}
void ExtensionRegistry::LogError(const QString& owner, const QString& contributionName, const ctkException& e)
{
QString message = QString("Could not parse XML contribution for \"%1\". Any contributed extensions "
"and extension points will be ignored.").arg(QString(owner) + "/" + contributionName);
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, message, e, BERRY_STATUS_LOC));
Log(status);
}
void ExtensionRegistry::CreateExtensionData(const QString& contributorId,
const ConfigurationElementDescription& description,
const SmartPointer<RegistryObject>& parent, bool persist)
{
ConfigurationElement::Pointer currentConfigurationElement = GetElementFactory()->CreateConfigurationElement(persist);
currentConfigurationElement->SetContributorId(contributorId);
currentConfigurationElement->SetName(description.GetName());
QList<ConfigurationElementAttribute> descriptionProperties = description.GetAttributes();
QList<QString> properties;
if (!descriptionProperties.empty())
{
for (int i = 0; i < descriptionProperties.size(); i++)
{
properties.push_back(descriptionProperties[i].GetName());
properties.push_back(Translate(descriptionProperties[i].GetValue(), nullptr));
}
}
currentConfigurationElement->SetProperties(properties);
QString value = description.GetValue();
if (!value.isEmpty())
currentConfigurationElement->SetValue(value);
GetObjectManager()->Add(currentConfigurationElement, true);
// process children
QList<ConfigurationElementDescription> children = description.GetChildren();
if (!children.empty())
{
for (int i = 0; i < children.size(); i++)
{
CreateExtensionData(contributorId, children[i], currentConfigurationElement, persist);
}
}
QList<int> newValues = parent->GetRawChildren();
newValues.push_back(currentConfigurationElement->GetObjectId());
parent->SetRawChildren(newValues);
currentConfigurationElement->SetParentId(parent->GetObjectId());
currentConfigurationElement->SetParentType(parent.Cast<ConfigurationElement>() ?
RegistryObjectManager::CONFIGURATION_ELEMENT :
RegistryObjectManager::EXTENSION);
}
bool ExtensionRegistry::RemoveObject(const SmartPointer<RegistryObject>& registryObject,
bool isExtensionPoint, QObject* token)
{
if (!CheckReadWriteAccess(token, registryObject->ShouldPersist()))
throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.removeExtension() method. Check if proper access token is supplied.");
int id = registryObject->GetObjectId();
QWriteLocker l(&access);
eventDelta = CombinedEventDelta::RecordRemoval();
if (isExtensionPoint)
{
RemoveExtensionPoint(id);
}
else
{
RemoveExtension(id);
}
QHash<int, RegistryObject::Pointer> removed;
removed.insert(id, registryObject);
// There is some asymmetry between extension and extension point removal. Removing extension point makes
// extensions "orphans" but does not remove them. As a result, only extensions needs to be processed.
if (!isExtensionPoint)
{
registryObjects->AddAssociatedObjects(removed, registryObject);
}
registryObjects->RemoveObjects(removed);
registryObjects->AddNavigableObjects(removed);
IObjectManager::Pointer manager = registryObjects->CreateDelegatingObjectManager(removed);
//GetDelta(namespaze)->SetObjectManager(manager);
//eventDelta->SetObjectManager(manager);
registryObjects->UnlinkChildFromContributions(id);
FireRegistryChangeEvent();
eventDelta.Reset();
return true;
}
void ExtensionRegistry::SetFileManager(const QString& /*cacheBase*/, bool /*isCacheReadOnly*/)
{
// if (cacheStorageManager != nullptr)
// cacheStorageManager->Close(); // close existing file manager first
// if (cacheBase != null) {
// cacheStorageManager = new StorageManager(cacheBase, isCacheReadOnly ? "none" : null, isCacheReadOnly); //$NON-NLS-1$
// try {
// cacheStorageManager.open(!isCacheReadOnly);
// } catch (IOException e) {
// // Ignore the exception. The registry will be rebuilt from source.
// }
// }
}
void ExtensionRegistry::EnterRead()
{
access.lockForRead();
}
void ExtensionRegistry::ExitRead()
{
access.unlock();
}
void ExtensionRegistry::SetElementFactory()
{
if (isMultiLanguage)
{
throw ctkRuntimeException("Multi-language registry not supported yet.");
//theRegistryObjectFactory = new RegistryObjectFactoryMulti(this);
}
else
{
theRegistryObjectFactory.reset(new RegistryObjectFactory(this));
}
}
//TableReader ExtensionRegistry::getTableReader() const
//{
// return theTableReader;
//}
bool ExtensionRegistry::CheckCache()
{
// for (int index = 0; index < strategy.getLocationsLength(); index++) {
// File possibleCacheLocation = strategy.getStorage(index);
// if (possibleCacheLocation == null)
// break; // bail out on the first null
// setFileManager(possibleCacheLocation, strategy.isCacheReadOnly(index));
// if (cacheStorageManager != null) {
// // check this new location:
// File cacheFile = null;
// try {
// cacheFile = cacheStorageManager.lookup(TableReader.getTestFileName(), false);
// } catch (IOException e) {
// //Ignore the exception. The registry will be rebuilt from the xml files.
// }
// if (cacheFile != null && cacheFile.isFile())
// return true; // found the appropriate location
// }
// }
return false;
}
void ExtensionRegistry::StopChangeEventScheduler()
{
if (!eventThread.isNull())
{
Queue::Locker l(&queue);
eventThread->interrupt();
eventThread->wait();
eventThread.reset();
}
}
SmartPointer<RegistryObjectManager> ExtensionRegistry::GetObjectManager() const
{
return registryObjects;
}
void ExtensionRegistry::AddListener(IRegistryEventListener* listener, const QString& extensionPointId)
{
AddListenerInternal(listener, extensionPointId.isEmpty() ? IExtensionPointFilter(nullptr)
: IExtensionPointFilter(new SimpleExtensionPointFilter(extensionPointId)));
}
void ExtensionRegistry::AddListener(IRegistryEventListener* listener, const IExtensionPointFilter& filter)
{
this->AddListenerInternal(listener, filter);
}
QList<SmartPointer<IConfigurationElement> > ExtensionRegistry::GetConfigurationElementsFor(const QString& extensionPointId) const
{
// this is just a convenience API - no need to do any sync'ing here
int lastdot = extensionPointId.lastIndexOf('.');
if (lastdot == -1)
{
QList<IConfigurationElement::Pointer>();
}
return GetConfigurationElementsFor(extensionPointId.left(lastdot), extensionPointId.mid(lastdot + 1));
}
QList<SmartPointer<IConfigurationElement> > ExtensionRegistry::GetConfigurationElementsFor(const QString& pluginId,
const QString& extensionPointSimpleId) const
{
// this is just a convenience API - no need to do any sync'ing here
IExtensionPoint::Pointer extPoint = this->GetExtensionPoint(pluginId, extensionPointSimpleId);
if (extPoint.IsNull())
return QList<IConfigurationElement::Pointer>();
return extPoint->GetConfigurationElements();
}
QList<SmartPointer<IConfigurationElement> > ExtensionRegistry::GetConfigurationElementsFor(const QString& pluginId,
const QString& extensionPointName,
const QString& extensionId) const
{
// this is just a convenience API - no need to do any sync'ing here
IExtension::Pointer extension = this->GetExtension(pluginId, extensionPointName, extensionId);
if (extension.IsNull())
return QList<IConfigurationElement::Pointer>();
return extension->GetConfigurationElements();
}
SmartPointer<IExtension> ExtensionRegistry::GetExtension(const QString& extensionId) const
{
if (extensionId.isEmpty())
return IExtension::Pointer();
int lastdot = extensionId.lastIndexOf('.');
if (lastdot == -1)
return IExtension::Pointer();
QString namespaze = extensionId.left(lastdot);
QList<ExtensionHandle::Pointer> extensions;
{
QReadLocker l(&access);
extensions = registryObjects->GetExtensionsFromNamespace(namespaze);
}
for (int i = 0; i < extensions.size(); i++)
{
ExtensionHandle::Pointer suspect = extensions[i];
if (extensionId == suspect->GetUniqueIdentifier())
return suspect;
}
return IExtension::Pointer();
}
SmartPointer<IExtension> ExtensionRegistry::GetExtension(const QString& extensionPointId, const QString& extensionId) const
{
// this is just a convenience API - no need to do any sync'ing here
int lastdot = extensionPointId.lastIndexOf('.');
if (lastdot == -1)
return IExtension::Pointer();
return GetExtension(extensionPointId.left(lastdot), extensionPointId.mid(lastdot + 1), extensionId);
}
SmartPointer<IExtension> ExtensionRegistry::GetExtension(const QString& pluginId,
const QString& extensionPointName,
const QString& extensionId) const
{
// this is just a convenience API - no need to do any sync'ing here
IExtensionPoint::Pointer extPoint = GetExtensionPoint(pluginId, extensionPointName);
if (extPoint.IsNotNull())
return extPoint->GetExtension(extensionId);
return IExtension::Pointer();
}
SmartPointer<IExtensionPoint> ExtensionRegistry::GetExtensionPoint(const QString& xptUniqueId) const
{
QReadLocker l(&access);
return registryObjects->GetExtensionPointHandle(xptUniqueId);
}
SmartPointer<IExtensionPoint> ExtensionRegistry::GetExtensionPoint(const QString& elementName, const QString& xpt) const
{
QReadLocker l(&access);
return registryObjects->GetExtensionPointHandle(elementName + '.' + xpt);
}
QList<SmartPointer<IExtensionPoint> > ExtensionRegistry::GetExtensionPoints() const
{
QList<ExtensionPointHandle::Pointer> handles;
{
QReadLocker l(&access);
handles = registryObjects->GetExtensionPointsHandles();
}
QList<IExtensionPoint::Pointer> result;
foreach(ExtensionPointHandle::Pointer handle, handles)
{
result.push_back(handle);
}
return result;
}
QList<SmartPointer<IExtensionPoint> > ExtensionRegistry::GetExtensionPoints(const QString& namespaceName) const
{
QList<ExtensionPointHandle::Pointer> handles;
{
QReadLocker l(&access);
handles = registryObjects->GetExtensionPointsFromNamespace(namespaceName);
}
QList<IExtensionPoint::Pointer> result;
foreach(ExtensionPointHandle::Pointer handle, handles)
{
result.push_back(handle);
}
return result;
}
QList<SmartPointer<IExtension> > ExtensionRegistry::GetExtensions(const QString& namespaceName) const
{
QList<ExtensionHandle::Pointer> handles;
{
QReadLocker l(&access);
handles = registryObjects->GetExtensionsFromNamespace(namespaceName);
}
QList<IExtension::Pointer> result;
foreach (ExtensionHandle::Pointer handle, handles)
{
result.push_back(handle);
}
return result;
}
QList<SmartPointer<IExtension> > ExtensionRegistry::GetExtensions(const SmartPointer<IContributor>& contributor) const
{
RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>();
if (regContributor.IsNull())
throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen
QString contributorId = regContributor->GetActualId();
QList<ExtensionHandle::Pointer> handles;
{
QReadLocker l(&access);
handles = registryObjects->GetExtensionsFromContributor(contributorId);
}
QList<IExtension::Pointer> result;
foreach (ExtensionHandle::Pointer handle, handles)
{
result.push_back(handle);
}
return result;
}
QList<SmartPointer<IExtensionPoint> > ExtensionRegistry::GetExtensionPoints(const SmartPointer<IContributor>& contributor) const
{
RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>();
if (regContributor.IsNull())
throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen
QString contributorId = regContributor->GetActualId();
QList<ExtensionPointHandle::Pointer> handles;
{
QReadLocker l(&access);
handles = registryObjects->GetExtensionPointsFromContributor(contributorId);
}
QList<IExtensionPoint::Pointer> result;
foreach (ExtensionPointHandle::Pointer handle, handles)
{
result.push_back(handle);
}
return result;
}
QList<QString> ExtensionRegistry::GetNamespaces() const
{
QReadLocker l(&access);
QList<KeyedElement::Pointer> namespaceElements = registryObjects->GetNamespacesIndex().Elements();
QList<QString> namespaceNames;
for (int i = 0; i < namespaceElements.size(); i++)
{
namespaceNames.push_back(namespaceElements[i]->GetKey());
}
return namespaceNames;
}
bool ExtensionRegistry::HasContributor(const SmartPointer<IContributor>& contributor) const
{
RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>();
if (regContributor.IsNull())
throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen
QString contributorId = regContributor->GetActualId();
return HasContributor(contributorId);
}
bool ExtensionRegistry::HasContributor(const QString& contributorId) const
{
QReadLocker l(&access);
return registryObjects->HasContribution(contributorId);
}
void ExtensionRegistry::Remove(const QString& removedContributorId, long timestamp)
{
Remove(removedContributorId);
if (timestamp != 0)
aggregatedTimestamp.Remove(timestamp);
}
void ExtensionRegistry::RemoveContributor(const SmartPointer<IContributor>& contributor, QObject* key)
{
RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>();
if (regContributor.IsNull())
throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen
if (!CheckReadWriteAccess(key, true))
throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.removeContributor() method. Check if proper access token is supplied.");
QString contributorId = regContributor->GetActualId();
Remove(contributorId);
}
void ExtensionRegistry::Remove(const QString& removedContributorId)
{
QWriteLocker l(&access);
eventDelta = CombinedEventDelta::RecordRemoval();
BasicRemove(removedContributorId);
FireRegistryChangeEvent();
eventDelta.Reset();
}
void ExtensionRegistry::RemoveListener(IRegistryEventListener* listener)
{
listeners.Remove(ListenerInfo(listener, IExtensionPointFilter(nullptr)));
}
ExtensionRegistry::ExtensionRegistry(RegistryStrategy* registryStrategy, QObject* masterToken, QObject* userToken)
: registryObjects(nullptr), isMultiLanguage(false), mlErrorLogged(false), eventThread(nullptr)
{
isMultiLanguage = RegistryProperties::GetProperty(RegistryConstants::PROP_REGISTRY_MULTI_LANGUAGE) == "true";
if (registryStrategy != nullptr)
strategy.reset(registryStrategy);
else
strategy.reset(new RegistryStrategy(QList<QString>(), QList<bool>(), nullptr));
this->masterToken = masterToken;
this->userToken = userToken;
registryObjects = new RegistryObjectManager(this);
bool isRegistryFilledFromCache = false; // indicates if registry was able to use cache to populate it's content
if (strategy->CacheUse())
{
// Try to read the registry from the cache first. If that fails, create a new registry
- QTime timer;
+ QElapsedTimer timer;
if (Debug())
timer.start();
//The cache is made of several files, find the real names of these other files. If all files are found, try to initialize the objectManager
if (CheckCache())
{
// TODO Registry Cache
// try {
// theTableReader.setTableFile(cacheStorageManager.lookup(TableReader.TABLE, false));
// theTableReader.setExtraDataFile(cacheStorageManager.lookup(TableReader.EXTRA, false));
// theTableReader.setMainDataFile(cacheStorageManager.lookup(TableReader.MAIN, false));
// theTableReader.setContributionsFile(cacheStorageManager.lookup(TableReader.CONTRIBUTIONS, false));
// theTableReader.setContributorsFile(cacheStorageManager.lookup(TableReader.CONTRIBUTORS, false));
// theTableReader.setNamespacesFile(cacheStorageManager.lookup(TableReader.NAMESPACES, false));
// theTableReader.setOrphansFile(cacheStorageManager.lookup(TableReader.ORPHANS, false));
// long timestamp = strategy.getContributionsTimestamp();
// isRegistryFilledFromCache = registryObjects.init(timestamp);
// if (isRegistryFilledFromCache)
// aggregatedTimestamp.set(timestamp);
// } catch (IOException e) {
// // The registry will be rebuilt from the xml files. Make sure to clear anything filled
// // from cache so that we won't have partially filled items.
// isRegistryFilledFromCache = false;
// clearRegistryCache();
// log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.registry_bad_cache, e));
// }
}
// if (!isRegistryFilledFromCache)
// {
// // set cache storage manager to a first writable location
// for (int index = 0; index < strategy.getLocationsLength(); index++) {
// if (!strategy.isCacheReadOnly(index)) {
// setFileManager(strategy.getStorage(index), false);
// break;
// }
// }
// }
if (Debug() && isRegistryFilledFromCache)
BERRY_INFO << "Reading registry cache: " << timer.elapsed() << "ms";
if (Debug())
{
if (!isRegistryFilledFromCache)
BERRY_INFO << "Reloading registry from manifest files...";
else
BERRY_INFO << "Using registry cache...";
}
}
if (DebugEvents())
{
struct DebugRegistryListener : public IRegistryEventListener
{
void Added(const QList<IExtension::Pointer>& extensions) override
{
BERRY_INFO << "Registry extensions ADDED:";
foreach(IExtension::Pointer extension, extensions)
{
BERRY_INFO << "\t" << extension->GetExtensionPointUniqueIdentifier() << " - "
<< extension->GetNamespaceIdentifier() << "." << extension->GetSimpleIdentifier();
}
}
void Removed(const QList<IExtension::Pointer>& extensions) override
{
BERRY_INFO << "Registry extensions REMOVED:";
foreach(IExtension::Pointer extension, extensions)
{
BERRY_INFO << "\t" << extension->GetExtensionPointUniqueIdentifier() << " - "
<< extension->GetNamespaceIdentifier() << "." << extension->GetSimpleIdentifier();
}
}
void Added(const QList<IExtensionPoint::Pointer>& extensionPoints) override
{
BERRY_INFO << "Registry extension-points ADDED:";
foreach(IExtensionPoint::Pointer extensionPoint, extensionPoints)
{
BERRY_INFO << "\t" << extensionPoint->GetUniqueIdentifier();
}
}
void Removed(const QList<IExtensionPoint::Pointer>& extensionPoints) override
{
BERRY_INFO << "Registry extension-points REMOVED:";
foreach(IExtensionPoint::Pointer extensionPoint, extensionPoints)
{
BERRY_INFO << "\t" << extensionPoint->GetUniqueIdentifier();
}
}
};
debugRegistryListener.reset(new DebugRegistryListener());
AddListener(debugRegistryListener.data());
}
// Do extra start processing if specified in the registry strategy
strategy->OnStart(this, isRegistryFilledFromCache);
}
ExtensionRegistry::~ExtensionRegistry()
{
}
void ExtensionRegistry::Stop(QObject* /*key*/)
{
// If the registry creator specified a key token, check that the key mathches it
// (it is assumed that registry owner keeps the key to prevent unautorized access).
if (masterToken != nullptr && masterToken != nullptr)
{
throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.stop() method. Check if proper access token is supplied."); //$NON-NLS-1$
}
// Do extra stop processing if specified in the registry strategy
strategy->OnStop(this);
StopChangeEventScheduler();
// if (cacheStorageManager == nullptr)
// return;
// if (!registryObjects.isDirty() || cacheStorageManager.isReadOnly()) {
// cacheStorageManager.close();
// theTableReader.close();
// return;
// }
// File tableFile = null;
// File mainFile = null;
// File extraFile = null;
// File contributionsFile = null;
// File contributorsFile = null;
// File namespacesFile = null;
// File orphansFile = null;
// TableWriter theTableWriter = new TableWriter(this);
// try {
// cacheStorageManager.lookup(TableReader.TABLE, true);
// cacheStorageManager.lookup(TableReader.MAIN, true);
// cacheStorageManager.lookup(TableReader.EXTRA, true);
// cacheStorageManager.lookup(TableReader.CONTRIBUTIONS, true);
// cacheStorageManager.lookup(TableReader.CONTRIBUTORS, true);
// cacheStorageManager.lookup(TableReader.NAMESPACES, true);
// cacheStorageManager.lookup(TableReader.ORPHANS, true);
// tableFile = File.createTempFile(TableReader.TABLE, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$
// mainFile = File.createTempFile(TableReader.MAIN, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$
// extraFile = File.createTempFile(TableReader.EXTRA, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$
// contributionsFile = File.createTempFile(TableReader.CONTRIBUTIONS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$
// contributorsFile = File.createTempFile(TableReader.CONTRIBUTORS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$
// namespacesFile = File.createTempFile(TableReader.NAMESPACES, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$
// orphansFile = File.createTempFile(TableReader.ORPHANS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$
// theTableWriter.setTableFile(tableFile);
// theTableWriter.setExtraDataFile(extraFile);
// theTableWriter.setMainDataFile(mainFile);
// theTableWriter.setContributionsFile(contributionsFile);
// theTableWriter.setContributorsFile(contributorsFile);
// theTableWriter.setNamespacesFile(namespacesFile);
// theTableWriter.setOrphansFile(orphansFile);
// } catch (IOException e) {
// cacheStorageManager.close();
// return; //Ignore the exception since we can recompute the cache
// }
// try {
// long timestamp;
// // A bit of backward compatibility: if registry was modified, but timestamp was not,
// // it means that the new timestamp tracking mechanism was not used. In this case
// // explicitly obtain timestamps for all contributions. Note that this logic
// // maintains a problem described in the bug 104267 for contributions that
// // don't use the timestamp tracking mechanism.
// if (aggregatedTimestamp.isModifed())
// timestamp = aggregatedTimestamp.getContentsTimestamp(); // use timestamp tracking
// else
// timestamp = strategy.getContributionsTimestamp(); // use legacy approach
// if (theTableWriter.saveCache(registryObjects, timestamp))
// cacheStorageManager.update(new QString[] {TableReader.TABLE, TableReader.MAIN, TableReader.EXTRA, TableReader.CONTRIBUTIONS, TableReader.CONTRIBUTORS, TableReader.NAMESPACES, TableReader.ORPHANS}, new QString[] {tableFile.getName(), mainFile.getName(), extraFile.getName(), contributionsFile.getName(), contributorsFile.getName(), namespacesFile.getName(), orphansFile.getName()});
// } catch (IOException e) {
// //Ignore the exception since we can recompute the cache
// }
// theTableReader.close();
// cacheStorageManager.close();
}
void ExtensionRegistry::ClearRegistryCache()
{
// QString[] keys = new QString[] {TableReader.TABLE, TableReader.MAIN, TableReader.EXTRA, TableReader.CONTRIBUTIONS, TableReader.ORPHANS};
// for (int i = 0; i < keys.length; i++)
// try {
// cacheStorageManager.remove(keys[i]);
// } catch (IOException e) {
// log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, IStatus.ERROR, RegistryMessages.meta_registryCacheReadProblems, e));
// }
aggregatedTimestamp.Reset();
}
RegistryObjectFactory* ExtensionRegistry::GetElementFactory()
{
if (theRegistryObjectFactory.isNull())
SetElementFactory();
return theRegistryObjectFactory.data();
}
void ExtensionRegistry::Log(const SmartPointer<IStatus>& status) const
{
strategy->Log(status);
}
QString ExtensionRegistry::Translate(const QString& key, QTranslator* resources) const
{
if (isMultiLanguage)
return key;
return strategy->Translate(key, resources);
}
bool ExtensionRegistry::Debug() const
{
return strategy->Debug();
}
bool ExtensionRegistry::DebugEvents() const
{
return strategy->DebugRegistryEvents();
}
bool ExtensionRegistry::UseLazyCacheLoading() const
{
return strategy->CacheLazyLoading();
}
long ExtensionRegistry::ComputeState() const
{
return strategy->GetContainerTimestamp();
}
QObject* ExtensionRegistry::CreateExecutableExtension(const SmartPointer<RegistryContributor>& defaultContributor,
const QString& className, const QString& requestedContributorName)
{
return strategy->CreateExecutableExtension(defaultContributor, className, requestedContributorName);
}
void ExtensionRegistry::ProcessChangeEvent(
const QList<ListenerInfo>& listenerInfos, const CombinedEventDelta& scheduledDelta)
{
for (int i = 0; i < listenerInfos.size(); i++)
{
const ListenerInfo& listenerInfo = listenerInfos[i];
IRegistryEventListener* extensionListener = listenerInfo.listener;
QList<IExtension::Pointer> extensions = scheduledDelta.GetExtensions(listenerInfo.filter);
QList<IExtensionPoint::Pointer> extensionPoints = scheduledDelta.GetExtensionPoints(listenerInfo.filter);
// notification order - on addition: extension points; then extensions
if (scheduledDelta.IsAddition())
{
if (!extensionPoints.empty())
extensionListener->Added(extensionPoints);
if (!extensions.empty())
extensionListener->Added(extensions);
}
else
{ // on removal: extensions; then extension points
if (!extensions.empty())
extensionListener->Removed(extensions);
if (!extensionPoints.empty())
extensionListener->Removed(extensionPoints);
}
}
IObjectManager::Pointer manager = scheduledDelta.GetObjectManager();
if (manager.IsNotNull())
manager->Close();
}
void ExtensionRegistry::ScheduleChangeEvent(const QList<ListenerInfo>& listenerInfos,
const CombinedEventDelta& scheduledDelta)
{
QueueElement newElement(listenerInfos, scheduledDelta);
if (eventThread.isNull())
{
eventThread.reset(new RegistryEventThread(this, queue));
eventThread->start();
}
{
Queue::Locker l(&queue);
queue.push_back(newElement);
queue.notify();
}
}
bool ExtensionRegistry::AddContribution(QIODevice* is, const SmartPointer<IContributor>& contributor,
bool persist, const QString& contributionName,
QTranslator* translationBundle, QObject* key, long timestamp)
{
bool result = AddContribution(is, contributor, persist, contributionName, translationBundle, key);
if (timestamp != 0)
aggregatedTimestamp.Add(timestamp);
return result;
}
bool ExtensionRegistry::AddContribution(QIODevice* is, const SmartPointer<IContributor>& contributor, bool persist,
const QString& contributionName, QTranslator* translationBundle, QObject* key)
{
if (!CheckReadWriteAccess(key, persist))
throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddContribution() method. Check if proper access token is supplied.");
RegistryContributor::Pointer internalContributor = contributor.Cast<RegistryContributor>();
registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present
QString ownerName = internalContributor->GetActualName();
QString message = QString("Problems parsing plug-in manifest for: \"%1\".").arg(ownerName);
MultiStatus::Pointer problems(new MultiStatus(RegistryMessages::OWNER_NAME,
ExtensionsParser::PARSE_PROBLEM, message, BERRY_STATUS_LOC));
ExtensionsParser parser(problems, this);
RegistryContribution::Pointer contribution =
GetElementFactory()->CreateContribution(internalContributor->GetActualId(), persist);
try
{
QXmlInputSource xmlInput(is);
bool success = parser.parseManifest(strategy->GetXMLParser(), &xmlInput, contributionName,
GetObjectManager().GetPointer(), contribution, translationBundle);
int status = problems->GetSeverity();
if (status != IStatus::OK_TYPE || !success)
{
Log(problems);
if (status == IStatus::ERROR_TYPE || status == IStatus::CANCEL_TYPE || !success)
return false;
}
}
catch (const ctkException& e)
{
LogError(ownerName, contributionName, e);
return false;
}
Add(contribution); // the add() method does synchronization
return true;
}
bool ExtensionRegistry::AddExtensionPoint(const QString& identifier, const SmartPointer<IContributor>& contributor,
bool persist, const QString& label, const QString& schemaReference, QObject* token)
{
if (!CheckReadWriteAccess(token, persist))
throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddExtensionPoint() method. Check if proper access token is supplied.");
RegistryContributor::Pointer internalContributor = contributor.Cast<RegistryContributor>();
registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present
QString contributorId = internalContributor->GetActualId();
// Extension point Id might not be null
if (identifier.isEmpty())
{
QString message = QString("Missing ID for the extension point \"%1\". Element ignored.").arg(label);
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, message, BERRY_STATUS_LOC));
Log(status);
}
// addition wraps in a contribution
RegistryContribution::Pointer contribution = GetElementFactory()->CreateContribution(contributorId, persist);
ExtensionPoint::Pointer currentExtPoint = GetElementFactory()->CreateExtensionPoint(persist);
QString uniqueId;
QString namespaceName;
int simpleIdStart = identifier.lastIndexOf('.');
if (simpleIdStart == -1)
{
namespaceName = contribution->GetDefaultNamespace();
uniqueId = namespaceName + '.' + identifier;
}
else
{
namespaceName = identifier.left(simpleIdStart);
uniqueId = identifier;
}
currentExtPoint->SetUniqueIdentifier(uniqueId);
currentExtPoint->SetNamespace(namespaceName);
QString labelNLS = Translate(label, nullptr);
currentExtPoint->SetLabel(labelNLS);
currentExtPoint->SetSchema(schemaReference);
if (!GetObjectManager()->AddExtensionPoint(currentExtPoint, true))
{
if (Debug())
{
QString msg = QString("Ignored duplicate extension point \"%1\" supplied by \"%2\".").arg(uniqueId).arg(contribution->GetDefaultNamespace());
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC));
Log(status);
}
return false;
}
currentExtPoint->SetContributorId(contributorId);
// array format: {Number of extension points, Number of extensions, Extension Id}
QList<int> contributionChildren;
// Put the extension points into this namespace
contributionChildren.push_back(1);
contributionChildren.push_back(0);
contributionChildren.push_back(currentExtPoint->GetObjectId());
contribution->SetRawChildren(contributionChildren);
Add(contribution);
return true;
}
bool ExtensionRegistry::AddExtension(const QString& identifier, const SmartPointer<IContributor>& contributor,
bool persist, const QString& label, const QString& extensionPointId,
const ConfigurationElementDescription& configurationElements, QObject* token)
{
if (!CheckReadWriteAccess(token, persist))
throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddExtensionPoint() method. Check if proper access token is supplied.");
// prepare namespace information
RegistryContributor::Pointer internalContributor = contributor.Cast<RegistryContributor>();
registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present
QString contributorId = internalContributor->GetActualId();
// addition wraps in a contribution
RegistryContribution::Pointer contribution = GetElementFactory()->CreateContribution(contributorId, persist);
Extension::Pointer currentExtension = GetElementFactory()->CreateExtension(persist);
QString simpleId;
QString namespaceName;
int simpleIdStart = identifier.lastIndexOf('.');
if (simpleIdStart != -1)
{
simpleId = identifier.mid(simpleIdStart + 1);
namespaceName = identifier.left(simpleIdStart);
}
else
{
simpleId = identifier;
namespaceName = contribution->GetDefaultNamespace();
}
currentExtension->SetSimpleIdentifier(simpleId);
currentExtension->SetNamespaceIdentifier(namespaceName);
QString extensionLabelNLS = Translate(label, nullptr);
currentExtension->SetLabel(extensionLabelNLS);
QString targetExtensionPointId;
if (extensionPointId.indexOf('.') == -1) // No dots -> namespace name added at the start
targetExtensionPointId = contribution->GetDefaultNamespace() + '.' + extensionPointId;
else
targetExtensionPointId = extensionPointId;
currentExtension->SetExtensionPointIdentifier(targetExtensionPointId);
// if we have an Id specified, check for duplicates. Only issue warning if duplicate found
// as it might still work fine - depending on the access pattern.
if (!simpleId.isNull() && Debug())
{
QString uniqueId = namespaceName + '.' + simpleId;
IExtension::Pointer existingExtension = GetExtension(uniqueId);
if (existingExtension.IsNotNull())
{
QString currentSupplier = contribution->GetDefaultNamespace();
QString existingSupplier = existingExtension->GetContributor()->GetName();
QString msg = QString("Extensions supplied by \"%1\" and \"%2\" have the same Id: \"%3\".")
.arg(currentSupplier).arg(existingSupplier).arg(uniqueId);
IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC));
Log(status);
return false;
}
}
GetObjectManager()->Add(currentExtension, true);
CreateExtensionData(contributorId, configurationElements, currentExtension, persist);
currentExtension->SetContributorId(contributorId);
QList<int> contributionChildren;
contributionChildren.push_back(0);
contributionChildren.push_back(1);
contributionChildren.push_back(currentExtension->GetObjectId());
contribution->SetRawChildren(contributionChildren);
Add(contribution);
return true;
}
bool ExtensionRegistry::RemoveExtension(const SmartPointer<IExtension>& extension, QObject* token)
{
ExtensionHandle::Pointer handle = extension.Cast<ExtensionHandle>();
if (handle.IsNull())
return false;
return RemoveObject(handle->GetObject(), false, token);
}
bool ExtensionRegistry::RemoveExtensionPoint(const SmartPointer<IExtensionPoint>& extensionPoint, QObject* token)
{
ExtensionPointHandle::Pointer handle = extensionPoint.Cast<ExtensionPointHandle>();
if (handle.IsNull())
return false;
return RemoveObject(handle->GetObject(), true, token);
}
QList<SmartPointer<IContributor> > ExtensionRegistry::GetAllContributors() const
{
QList<IContributor::Pointer> result;
QReadLocker l(&access);
foreach(RegistryContributor::Pointer contributor, registryObjects->GetContributors().values())
{
result.push_back(contributor);
}
return result;
}
bool ExtensionRegistry::IsMultiLanguage() const
{
return isMultiLanguage;
}
QList<QString> ExtensionRegistry::Translate(const QList<QString>& nonTranslated, const SmartPointer<IContributor>& contributor,
const QLocale& locale) const
{
return strategy->Translate(nonTranslated, contributor, locale);
}
QLocale ExtensionRegistry::GetLocale() const
{
return strategy->GetLocale();
}
void ExtensionRegistry::LogMultiLangError() const
{
if (mlErrorLogged) // only log this error ones
return;
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0,
QString("The requested multi-language operation is not enabled. See runtime option \"")
+ RegistryConstants::PROP_REGISTRY_MULTI_LANGUAGE + "\".", ctkInvalidArgumentException(""), BERRY_STATUS_LOC));
Log(status);
mlErrorLogged = true;
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.h b/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.h
index 80b96759fc..5a833556dd 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.h
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.h
@@ -1,448 +1,449 @@
/*============================================================================
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 BERRYEXTENSIONREGISTRY_H
#define BERRYEXTENSIONREGISTRY_H
#include <berryIExtensionRegistry.h>
#include <berryIRegistryEventListener.h>
#include "berryRegistryTimestamp.h"
#include "berryCombinedEventDelta.h"
#include "berryListenerList.h"
+#include <QObject>
#include <QReadWriteLock>
#include <QWaitCondition>
class QTranslator;
namespace berry {
struct IContributor;
struct IStatus;
class ConfigurationElementDescription;
class RegistryContribution;
class RegistryContributor;
class RegistryObject;
class RegistryObjectFactory;
class RegistryObjectManager;
class RegistryStrategy;
/**
* An implementation for the extension registry API.
*/
class ExtensionRegistry : public QObject, public IExtensionRegistry
{
Q_OBJECT
Q_INTERFACES(berry::IExtensionRegistry)
private:
struct ListenerInfo;
class RegistryEventThread;
// used to enforce concurrent access policy for readers/writers
mutable QReadWriteLock access;
// all registry event listeners
ListenerList<ListenerInfo> listeners;
QScopedPointer<IRegistryEventListener> debugRegistryListener;
SmartPointer<RegistryObjectManager> registryObjects;
QObject* masterToken; // use to get full control of the registry; objects created as "static"
QObject* userToken; // use to modify non-persisted registry elements
RegistryTimestamp aggregatedTimestamp; // tracks current contents of the registry
// encapsulates processing of new registry deltas
CombinedEventDelta eventDelta;
// marks a new extended delta. The namespace that normally would not exists is used for this purpose
const static QString notNamespace;
// does this instance of the extension registry has multiple language support enabled?
bool isMultiLanguage;
// have we already logged a error on usage of an unsupported multi-language method?
mutable bool mlErrorLogged;
QScopedPointer<RegistryEventThread> eventThread; // registry event loop
// The pair of values we store in the event queue
struct QueueElement;
class Queue : public QList<QueueElement>
{
QMutex mutex;
QWaitCondition waitCond;
public:
class Locker {
private: Queue* q;
public:
Locker(Queue* q) : q(q) { q->mutex.lock(); }
~Locker() { q->mutex.unlock(); }
};
void wait() { waitCond.wait(&mutex); }
void notify() { waitCond.wakeOne(); }
};
Queue queue; // stores registry events info
/**
* Adds and resolves all extensions and extension points provided by the
* plug-in.
* <p>
* A corresponding IRegistryChangeEvent will be broadcast to all listeners
* interested on changes in the given plug-in.
* </p>
*/
void Add(const SmartPointer<RegistryContribution>& element);
QString AddExtension(int extension);
/**
* Looks for existing orphan extensions to connect to the given extension
* point. If none is found, there is nothing to do. Otherwise, link them.
*/
QString AddExtensionPoint(int extPoint);
QSet<QString> AddExtensionsAndExtensionPoints(const SmartPointer<RegistryContribution>& element);
void AddListenerInternal(IRegistryEventListener* listener, const IExtensionPointFilter& filter);
void BasicAdd(const SmartPointer<RegistryContribution>& element, bool link);
void SetObjectManagers(const SmartPointer<IObjectManager> &manager);
void BasicRemove(const QString& contributorId);
/**
* Broadcasts (asynchronously) the event to all interested parties.
*/
void FireRegistryChangeEvent();
//RegistryDelta GetDelta(const QString& namespaze) const;
void Link(const SmartPointer<ExtensionPoint>& extPoint, const QList<int>& extensions);
/*
* Records an extension addition/removal.
*/
//QString RecordChange(const SmartPointer<ExtensionPoint>& extPoint, int extension, int kind);
/*
* Records a set of extension additions/removals.
*/
//QString RecordChange(const SmartPointer<ExtensionPoint>& extPoint, const QList<int>& extensions, int kind);
//Return the affected namespace
QString RemoveExtension(int extensionId);
QString RemoveExtensionPoint(int extPoint);
QSet<QString> RemoveExtensionsAndExtensionPoints(const QString& contributorId);
/**
* Access check for add/remove operations:
* - Master key allows all operations
* - User key allows modifications of non-persisted elements
*
* @param key key to the registry supplied by the user
* @param persist true if operation affects persisted elements
* @return true is the key grants read/write access to the registry
*/
bool CheckReadWriteAccess(QObject* key, bool persist) const;
void LogError(const QString& owner, const QString& contributionName, const ctkException& e);
void LogError(const QString& owner, const QString& contributionName);
// Fill in the actual content of this extension
void CreateExtensionData(const QString& contributorId,
const ConfigurationElementDescription& description,
const SmartPointer<RegistryObject>& parent, bool persist);
bool RemoveObject(const SmartPointer<RegistryObject>& registryObject,
bool isExtensionPoint, QObject* token);
protected:
//storage manager associated with the registry cache
//StorageManager cacheStorageManager;
// Table reader associated with this extension registry
//TableReader theTableReader = new TableReader(this);
QScopedPointer<RegistryStrategy> strategy; // overridable portions of the registry functionality
/**
* Sets new cache file manager. If existing file manager was owned by the registry,
* closes it.
*
* @param cacheBase the base location for the registry cache
* @param isCacheReadOnly whether the file cache is read only
*/
void SetFileManager(const QString& cacheBase, bool isCacheReadOnly);
// allow other objects in the registry to use the same lock
void EnterRead();
// allow other objects in the registry to use the same lock
void ExitRead();
/////////////////////////////////////////////////////////////////////////////////////////////////
// Registry Object Factory
// The factory produces contributions, extension points, extensions, and configuration elements
// to be stored in the extension registry.
QScopedPointer<RegistryObjectFactory> theRegistryObjectFactory;
// Override to provide domain-specific elements to be stored in the extension registry
void SetElementFactory();
//TableReader getTableReader() const;
// Find the first location that contains a cache table file and set file manager to it.
bool CheckCache();
void StopChangeEventScheduler();
public:
SmartPointer<RegistryObjectManager> GetObjectManager() const;
void AddListener(IRegistryEventListener* listener, const QString& extensionPointId = QString()) override;
void AddListener(IRegistryEventListener *listener, const IExtensionPointFilter& filter) override;
/*
* @see IExtensionRegistry#getConfigurationElementsFor(java.lang. QString)
*/
QList<SmartPointer<IConfigurationElement> > GetConfigurationElementsFor(const QString& extensionPointId) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getConfigurationElementsFor(java.lang. QString, java.lang. QString)
*/
QList<SmartPointer<IConfigurationElement> > GetConfigurationElementsFor(const QString& pluginId,
const QString& extensionPointSimpleId) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getConfigurationElementsFor(java.lang. QString, java.lang. QString, java.lang. QString)
*/
QList<SmartPointer<IConfigurationElement> > GetConfigurationElementsFor(const QString& pluginId,
const QString& extensionPointName,
const QString& extensionId) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getExtension(java.lang. QString)
*/
SmartPointer<IExtension> GetExtension(const QString& extensionId) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getExtension(java.lang. QString, java.lang. QString)
*/
SmartPointer<IExtension> GetExtension(const QString& extensionPointId, const QString& extensionId) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getExtension(java.lang. QString, java.lang. QString, java.lang. QString)
*/
SmartPointer<IExtension> GetExtension(const QString& pluginId,
const QString& extensionPointName,
const QString& extensionId) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getExtensionPoint(java.lang. QString)
*/
SmartPointer<IExtensionPoint> GetExtensionPoint(const QString& xptUniqueId) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getExtensionPoint(java.lang. QString, java.lang. QString)
*/
SmartPointer<IExtensionPoint> GetExtensionPoint(const QString& elementName, const QString& xpt) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getExtensionPoints()
*/
QList<SmartPointer<IExtensionPoint> > GetExtensionPoints() const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getExtensionPoints(java.lang. QString)
*/
QList<SmartPointer<IExtensionPoint> > GetExtensionPoints(const QString& namespaceName) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getExtensions(java.lang. QString)
*/
QList<SmartPointer<IExtension> > GetExtensions(const QString& namespaceName) const override;
QList<SmartPointer<IExtension> > GetExtensions(const SmartPointer<IContributor>& contributor) const override;
QList<SmartPointer<IExtensionPoint> > GetExtensionPoints(const SmartPointer<IContributor>& contributor) const override;
/*
* @see org.eclipse.core.runtime.IExtensionRegistry#getNamespaces()
*/
QList<QString> GetNamespaces() const override;
bool HasContributor(const SmartPointer<IContributor>& contributor) const;
bool HasContributor(const QString& contributorId) const;
void Remove(const QString& removedContributorId, long timestamp);
void RemoveContributor(const SmartPointer<IContributor>& contributor, QObject* key);
/**
* Unresolves and removes all extensions and extension points provided by
* the plug-in.
* <p>
* A corresponding IRegistryChangeEvent will be broadcast to all listeners
* interested on changes in the given plug-in.
* </p>
*/
void Remove(const QString& removedContributorId);
void RemoveListener(IRegistryEventListener* listener) override;
ExtensionRegistry(RegistryStrategy* registryStrategy, QObject* masterToken, QObject* userToken);
~ExtensionRegistry() override;
/**
* Stops the registry. Registry has to be stopped to properly
* close cache and dispose of listeners.
* @param key - key token for this registry
*/
void Stop(QObject* key) override;
/*
* Clear the registry cache files from the file manager so on next start-up we recompute it.
*/
void ClearRegistryCache();
// Lazy initialization.
RegistryObjectFactory* GetElementFactory();
void Log(const SmartPointer<IStatus>& status) const;
/**
* With multi-locale support enabled this method returns the non-translated
* key so that they can be cached and translated later into desired languages.
* In the absence of the multi-locale support the key gets translated immediately
* and only translated values is cached.
*/
QString Translate(const QString& key, QTranslator* resources) const;
bool Debug() const;
bool DebugEvents() const;
bool UseLazyCacheLoading() const;
long ComputeState() const;
QObject* CreateExecutableExtension(const SmartPointer<RegistryContributor>& defaultContributor,
const QString& className, const QString& requestedContributorName);
//////////////////////////////////////////////////////////////////////////////////////////
// Registry change events processing
void ProcessChangeEvent(const QList<ListenerInfo>& listenerInfos,
const CombinedEventDelta &scheduledDelta);
// Registry events notifications are done on a separate thread in a sequential manner
// (first in - first processed)
void ScheduleChangeEvent(const QList<ListenerInfo>& listenerInfos,
const CombinedEventDelta& scheduledDeltas);
bool AddContribution(QIODevice* is, const SmartPointer<IContributor>& contributor,
bool persist, const QString& contributionName,
QTranslator* translationBundle, QObject* key, long timestamp);
bool AddContribution(QIODevice* is, const SmartPointer<IContributor>& contributor, bool persist,
const QString& contributionName, QTranslator* translationBundle, QObject* key) override;
/**
* Adds an extension point to the extension registry.
* <p>
* If the registry is not modifiable, this method is an access controlled method.
* Proper token should be passed as an argument for non-modifiable registries.
* </p>
* @param identifier Id of the extension point. If non-qualified names is supplied,
* it will be converted internally into a fully qualified name
* @param contributor the contributor of this extension point
* @param persist indicates if contribution should be stored in the registry cache. If false,
* contribution is not persisted in the registry cache and is lost on Eclipse restart
* @param label display string for the extension point
* @param schemaReference reference to the extension point schema. The schema reference
* is a URL path relative to the plug-in installation URL. May be null
* @param token the key used to check permissions. Two registry keys are set in the registry
* constructor {@link RegistryFactory#createRegistry(org.eclipse.core.runtime.spi.RegistryStrategy, Object, Object)}:
* master token and a user token. Master token allows all operations; user token
* allows non-persisted registry elements to be modified.
* @return <code>true</code> if successful, <code>false</code> if a problem was encountered
* @throws IllegalArgumentException if incorrect token is passed in
*/
bool AddExtensionPoint(const QString& identifier, const SmartPointer<IContributor>& contributor,
bool persist, const QString& label, const QString& schemaReference, QObject* token);
/**
* Adds an extension to the extension registry.
* <p>
* If the registry is not modifiable, this method is an access controlled method.
* Proper token should be passed as an argument for non-modifiable registries.
* </p>
* @see org.eclipse.core.internal.registry.spi.ConfigurationElementDescription
*
* @param identifier Id of the extension. If non-qualified name is supplied,
* it will be converted internally into a fully qualified name
* @param contributor the contributor of this extension
* @param persist indicates if contribution should be stored in the registry cache. If false,
* contribution is not persisted in the registry cache and is lost on Eclipse restart
* @param label display string for this extension
* @param extensionPointId Id of the point being extended. If non-qualified
* name is supplied, it is assumed to have the same contributorId as this extension
* @param configurationElements contents of the extension
* @param token the key used to check permissions. Two registry keys are set in the registry
* constructor {@link RegistryFactory#createRegistry(org.eclipse.core.runtime.spi.RegistryStrategy, Object, Object)}:
* master token and a user token. Master token allows all operations; user token
* allows non-persisted registry elements to be modified.
* @return <code>true</code> if successful, <code>false</code> if a problem was encountered
* @throws IllegalArgumentException if incorrect token is passed in
*/
bool AddExtension(const QString& identifier, const SmartPointer<IContributor>& contributor,
bool persist, const QString& label, const QString& extensionPointId,
const ConfigurationElementDescription& configurationElements, QObject* token);
bool RemoveExtension(const SmartPointer<IExtension>& extension, QObject* token) override;
bool RemoveExtensionPoint(const SmartPointer<IExtensionPoint>& extensionPoint, QObject* token) override;
QList<SmartPointer<IContributor> > GetAllContributors() const;
bool IsMultiLanguage() const override;
QList<QString> Translate(const QList<QString>& nonTranslated, const SmartPointer<IContributor>& contributor,
const QLocale& locale) const;
QLocale GetLocale() const;
void LogMultiLangError() const;
};
}
#endif // BERRYEXTENSIONREGISTRY_H
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionsParser.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionsParser.cpp
index 145430f5eb..39274c7718 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionsParser.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryExtensionsParser.cpp
@@ -1,639 +1,639 @@
/*============================================================================
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 "berryExtensionsParser.h"
#include "berryConfigurationElement.h"
#include "berryExtension.h"
#include "berryExtensionPoint.h"
#include "berryExtensionRegistry.h"
#include "berryIContributor.h"
#include "berryIExtension.h"
#include "berryLog.h"
#include "berryMultiStatus.h"
#include "berryRegistryContribution.h"
#include "berryRegistryMessages.h"
#include "berryRegistryObject.h"
#include "berryRegistryObjectFactory.h"
#include "berryRegistryObjectManager.h"
-#include <QTime>
+#include <QElapsedTimer>
namespace berry {
long ExtensionsParser::cumulativeTime = 0;
// Valid States
const int ExtensionsParser::IGNORED_ELEMENT_STATE = 0;
const int ExtensionsParser::INITIAL_STATE = 1;
const int ExtensionsParser::PLUGIN_STATE = 2;
const int ExtensionsParser::PLUGIN_EXTENSION_POINT_STATE = 5;
const int ExtensionsParser::PLUGIN_EXTENSION_STATE = 6;
const int ExtensionsParser::CONFIGURATION_ELEMENT_STATE = 10;
const int ExtensionsParser::EXTENSION_POINT_INDEX = 0;
const int ExtensionsParser::EXTENSION_INDEX = 1;
const int ExtensionsParser::LAST_INDEX = 1;
const int ExtensionsParser::PARSE_PROBLEM = 1;
const QString ExtensionsParser::PLUGIN = "plugin";
const QString ExtensionsParser::PLUGIN_ID = "id";
const QString ExtensionsParser::PLUGIN_NAME = "name";
const QString ExtensionsParser::BUNDLE_UID = "id";
const QString ExtensionsParser::EXTENSION_POINT = "extension-point";
const QString ExtensionsParser::EXTENSION_POINT_NAME = "name";
const QString ExtensionsParser::EXTENSION_POINT_ID = "id";
const QString ExtensionsParser::EXTENSION_POINT_SCHEMA = "schema";
const QString ExtensionsParser::EXTENSION = "extension";
const QString ExtensionsParser::EXTENSION_NAME = "name";
const QString ExtensionsParser::EXTENSION_ID = "id";
const QString ExtensionsParser::EXTENSION_TARGET = "point";
const QString ExtensionsParser::ELEMENT = "element";
const QString ExtensionsParser::ELEMENT_NAME = "name";
const QString ExtensionsParser::ELEMENT_VALUE = "value";
const QString ExtensionsParser::PROPERTY = "property";
const QString ExtensionsParser::PROPERTY_NAME = "name";
const QString ExtensionsParser::PROPERTY_VALUE = "value";
ExtensionsParser::ExtensionsParser(const SmartPointer<MultiStatus>& status, ExtensionRegistry* registry)
: locator(nullptr), extractNamespaces(true), status(status),
registry(registry), resources(nullptr), objectManager(nullptr)
{
}
void ExtensionsParser::setDocumentLocator(QXmlLocator* locator)
{
this->locator = locator;
}
bool ExtensionsParser::characters(const QString& ch)
{
int state = stateStack.back();
if (state != CONFIGURATION_ELEMENT_STATE)
return true;
if (state == CONFIGURATION_ELEMENT_STATE)
{
// Accept character data within an element, is when it is
// part of a configuration element (i.e. an element within an EXTENSION element
ConfigurationElement::Pointer currentConfigElement = objectStack.back().Cast<ConfigurationElement>();
if (configurationElementValue.isNull())
{
if (!ch.trimmed().isEmpty())
{
configurationElementValue = ch;
}
}
else
{
configurationElementValue.append(ch);
}
if (!configurationElementValue.isEmpty())
currentConfigElement->SetValue(configurationElementValue);
}
return true;
}
bool ExtensionsParser::endElement(const QString& /*uri*/, const QString& elementName, const QString& /*qName*/)
{
switch (stateStack.back())
{
case IGNORED_ELEMENT_STATE :
{
stateStack.pop();
return true;
}
case INITIAL_STATE :
{
// shouldn't get here
internalError(QString("Element/end element mismatch for element \"%1\".").arg(elementName));
return false;
}
case PLUGIN_STATE :
{
stateStack.pop();
QList<RegistryObject::Pointer>& extensionPoints = scratchVectors[EXTENSION_POINT_INDEX];
QList<RegistryObject::Pointer>& extensions = scratchVectors[EXTENSION_INDEX];
QList<int> namespaceChildren;
namespaceChildren.push_back(0);
namespaceChildren.push_back(0);
// Put the extension points into this namespace
if (extensionPoints.size() > 0)
{
namespaceChildren[RegistryContribution::EXTENSION_POINT] = extensionPoints.size();
for (int i = 0; i < extensionPoints.size(); ++i)
{
namespaceChildren.push_back(extensionPoints[i]->GetObjectId());
}
extensionPoints.clear();
}
// Put the extensions into this namespace too
if (extensions.size() > 0)
{
namespaceChildren[RegistryContribution::EXTENSION] = extensions.size();
for (int i = 0; i < extensions.size(); ++i)
{
namespaceChildren.push_back(extensions[i]->GetObjectId());
}
extensions.clear();
}
contribution->SetRawChildren(namespaceChildren);
return true;
}
case PLUGIN_EXTENSION_POINT_STATE :
{
if (elementName == EXTENSION_POINT)
{
stateStack.pop();
}
return true;
}
case PLUGIN_EXTENSION_STATE :
{
if (elementName == EXTENSION)
{
stateStack.pop();
// Finish up extension object
Extension::Pointer currentExtension = objectStack.pop().Cast<Extension>();
if (currentExtension->GetNamespaceIdentifier().isEmpty())
currentExtension->SetNamespaceIdentifier(contribution->GetDefaultNamespace());
currentExtension->SetContributorId(contribution->GetContributorId());
scratchVectors[EXTENSION_INDEX].push_back(currentExtension);
}
return true;
}
case CONFIGURATION_ELEMENT_STATE :
{
// We don't care what the element name was
stateStack.pop();
// Now finish up the configuration element object
configurationElementValue.clear();
ConfigurationElement::Pointer currentConfigElement = objectStack.pop().Cast<ConfigurationElement>();
QString value = currentConfigElement->GetValueAsIs();
if (!value.isEmpty())
{
currentConfigElement->SetValue(translate(value).trimmed());
}
RegistryObject::Pointer parent = objectStack.back().Cast<RegistryObject>();
// Want to add this configuration element to the subelements of an extension
QList<int> newValues = parent->GetRawChildren();
newValues.push_back(currentConfigElement->GetObjectId());
parent->SetRawChildren(newValues);
currentConfigElement->SetParentId(parent->GetObjectId());
currentConfigElement->SetParentType(parent.Cast<ConfigurationElement>() ?
RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::EXTENSION);
return true;
}
default:
// should never get here
return false;
}
}
bool ExtensionsParser::error(const QXmlParseException& ex)
{
logStatus(ex);
return true;
}
bool ExtensionsParser::fatalError(const QXmlParseException& ex)
{
cleanup();
logStatus(ex);
return false;
}
bool
ExtensionsParser::parseManifest(QXmlReader* reader, QXmlInputSource* in,
const QString& manifestName, RegistryObjectManager* registryObjects,
const SmartPointer<RegistryContribution>& currentNamespace,
QTranslator* translator)
{
- QTime start;
+ QElapsedTimer timer;
this->resources = translator;
this->objectManager = registryObjects;
//initialize the parser with this object
this->contribution = currentNamespace;
if (registry->Debug())
- start.start();
+ timer.start();
if (reader == nullptr)
{
- cumulativeTime += start.elapsed();
+ cumulativeTime += timer.elapsed();
throw ctkInvalidArgumentException("XML Reader not available");
}
locationName = manifestName;
reader->setContentHandler(this);
reader->setDeclHandler(this);
reader->setDTDHandler(this);
reader->setEntityResolver(this);
reader->setErrorHandler(this);
reader->setLexicalHandler(this);
bool success = reader->parse(in);
if (registry->Debug())
{
- cumulativeTime += start.elapsed();
+ cumulativeTime += timer.elapsed();
BERRY_INFO << "Cumulative parse time so far : " << cumulativeTime;
}
return success;
}
bool ExtensionsParser::startDocument()
{
stateStack.push(INITIAL_STATE);
for (int i = 0; i <= LAST_INDEX; i++)
{
scratchVectors[i].clear();
}
return true;
}
bool ExtensionsParser::startElement(const QString& /*uri*/, const QString& elementName,
const QString& /*qName*/, const QXmlAttributes& attributes)
{
switch (stateStack.back())
{
case INITIAL_STATE :
handleInitialState(elementName, attributes);
break;
case PLUGIN_STATE :
handlePluginState(elementName, attributes);
break;
case PLUGIN_EXTENSION_POINT_STATE :
handleExtensionPointState(elementName);
break;
case PLUGIN_EXTENSION_STATE :
case CONFIGURATION_ELEMENT_STATE :
handleExtensionState(elementName, attributes);
break;
default :
stateStack.push(IGNORED_ELEMENT_STATE);
internalError(QString("Unknown element \"%1\", found at the top level, ignored.").arg(elementName));
}
return true;
}
bool ExtensionsParser::warning(const QXmlParseException& ex)
{
logStatus(ex);
return true;
}
void ExtensionsParser::error(const SmartPointer<IStatus>& error)
{
status->Add(error);
}
void ExtensionsParser::cleanup()
{
foreach (RegistryObject::Pointer object, addedRegistryObjects)
{
if (ExtensionPoint::Pointer extPoint = object.Cast<ExtensionPoint>())
{
QString id = extPoint->GetUniqueIdentifier();
objectManager->RemoveExtensionPoint(id);
}
else
{
objectManager->Remove(object->GetObjectId(), true);
}
}
}
void ExtensionsParser::handleExtensionPointState(const QString& elementName)
{
// We ignore all elements under extension points (if there are any)
stateStack.push(IGNORED_ELEMENT_STATE);
unknownElement(EXTENSION_POINT, elementName);
}
void ExtensionsParser::handleExtensionState(const QString& elementName, const QXmlAttributes& attributes)
{
// You need to change the state here even though we will be executing the same
// code for ExtensionState and ConfigurationElementState. We ignore the name
// of the element for ConfigurationElements. When we are wrapping up, we will
// want to add each configuration element object to the subElements vector of
// its parent configuration element object. However, the first configuration
// element object we created (the last one we pop off the stack) will need to
// be added to a vector in the extension object called _configuration.
stateStack.push(CONFIGURATION_ELEMENT_STATE);
configurationElementValue.clear();
// create a new Configuration Element and push it onto the object stack
ConfigurationElement::Pointer currentConfigurationElement =
registry->GetElementFactory()->CreateConfigurationElement(contribution->ShouldPersist());
currentConfigurationElement->SetContributorId(contribution->GetContributorId());
objectStack.push(currentConfigurationElement);
currentConfigurationElement->SetName(elementName);
// Processing the attributes of a configuration element involves creating
// a new configuration property for each attribute and populating the configuration
// property with the name/value pair of the attribute. Note there will be one
// configuration property for each attribute
parseConfigurationElementAttributes(attributes);
objectManager->Add(currentConfigurationElement, true);
addedRegistryObjects.push_back(currentConfigurationElement);
}
void ExtensionsParser::handleInitialState(const QString& /*elementName*/, const QXmlAttributes& /*attributes*/)
{
// new manifests should have the plugin (or fragment) element empty
stateStack.push(PLUGIN_STATE);
objectStack.push(contribution);
}
void ExtensionsParser::handlePluginState(const QString& elementName, const QXmlAttributes& attributes)
{
if (elementName == EXTENSION_POINT)
{
stateStack.push(PLUGIN_EXTENSION_POINT_STATE);
parseExtensionPointAttributes(attributes);
return;
}
if (elementName == EXTENSION)
{
stateStack.push(PLUGIN_EXTENSION_STATE);
parseExtensionAttributes(attributes);
return;
}
// If we get to this point, the element name is one we don't currently accept.
// Set the state to indicate that this element will be ignored
stateStack.push(IGNORED_ELEMENT_STATE);
unknownElement(PLUGIN, elementName);
}
void ExtensionsParser::logStatus(const QXmlParseException& ex)
{
QString name = ex.systemId();
if (name.isEmpty())
name = locationName;
if (!name.isEmpty())
name = name.mid(1 + name.lastIndexOf("/"));
QString msg;
if (name.isEmpty())
msg = QString("Parsing error: \"%1\"").arg(ex.message());
else
msg = QString("Parsing error in \"%1\" [line %2, column %3]: \"%4\".").arg(name)
.arg(ex.lineNumber()).arg(ex.columnNumber()).arg(ex.message());
IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME,
PARSE_PROBLEM, msg, BERRY_STATUS_LOC));
error(status);
}
void ExtensionsParser::parseConfigurationElementAttributes(const QXmlAttributes& attributes)
{
ConfigurationElement::Pointer parentConfigurationElement =
objectStack.back().Cast<ConfigurationElement>();
// process attributes
int len = attributes.length();
if (len == 0)
{
parentConfigurationElement->SetProperties(QList<QString>());
return;
}
QList<QString> properties;
for (int i = 0; i < len; i++)
{
properties.push_back(attributes.localName(i));
properties.push_back(translate(attributes.value(i)));
}
parentConfigurationElement->SetProperties(properties);
}
void ExtensionsParser::parseExtensionAttributes(const QXmlAttributes& attributes)
{
Extension::Pointer currentExtension = registry->GetElementFactory()->CreateExtension(contribution->ShouldPersist());
objectStack.push(currentExtension);
QString simpleId;
QString namespaceName;
// Process Attributes
int len = attributes.length();
for (int i = 0; i < len; i++)
{
QString attrName = attributes.localName(i);
QString attrValue = attributes.value(i).trimmed();
if (attrName == EXTENSION_NAME)
currentExtension->SetLabel(translate(attrValue));
else if (attrName == EXTENSION_ID)
{
int simpleIdStart = attrValue.lastIndexOf('.');
if ((simpleIdStart != -1) && extractNamespaces)
{
simpleId = attrValue.mid(simpleIdStart + 1);
namespaceName = attrValue.left(simpleIdStart);
}
else
{
simpleId = attrValue;
namespaceName = contribution->GetDefaultNamespace();
}
currentExtension->SetSimpleIdentifier(simpleId);
currentExtension->SetNamespaceIdentifier(namespaceName);
}
else if (attrName == EXTENSION_TARGET)
{
// check if point is specified as a simple or qualified name
QString targetName;
if (attrValue.lastIndexOf('.') == -1)
{
QString baseId = contribution->GetDefaultNamespace();
targetName = baseId + '.' + attrValue;
}
else
{
targetName = attrValue;
}
currentExtension->SetExtensionPointIdentifier(targetName);
}
else
{
unknownAttribute(attrName, EXTENSION);
}
}
if (currentExtension->GetExtensionPointIdentifier().isEmpty())
{
missingAttribute(EXTENSION_TARGET, EXTENSION);
stateStack.pop();
stateStack.push(IGNORED_ELEMENT_STATE);
objectStack.pop();
return;
}
// if we have an Id specified, check for duplicates. Only issue warning (not error) if duplicate found
// as it might still work fine - depending on the access pattern.
if (!simpleId.isEmpty() && registry->Debug())
{
QString uniqueId = namespaceName + '.' + simpleId;
IExtension::Pointer existingExtension = registry->GetExtension(uniqueId);
if (existingExtension.IsNotNull())
{
QString currentSupplier = contribution->GetDefaultNamespace();
QString existingSupplier = existingExtension->GetContributor()->GetName();
QString msg = QString("Extensions supplied by \"%1\" and \"%2\" have the same Id: \"%3\".")
.arg(currentSupplier).arg(existingSupplier).arg(uniqueId);
IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, 0,
msg, BERRY_STATUS_LOC));
registry->Log(status);
}
else if (!processedExtensionIds.isEmpty())
{ // check elements in this contribution
foreach (QString processedId, processedExtensionIds)
{
if (uniqueId == processedId)
{
QString currentSupplier = contribution->GetDefaultNamespace();
QString existingSupplier = currentSupplier;
QString msg = QString("Extensions supplied by \"%1\" and \"%2\" have the same Id: \"%3\".")
.arg(currentSupplier).arg(existingSupplier).arg(uniqueId);
IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, 0,
msg, BERRY_STATUS_LOC));
registry->Log(status);
break;
}
}
}
processedExtensionIds.push_back(uniqueId);
}
objectManager->Add(currentExtension, true);
addedRegistryObjects.push_back(currentExtension);
}
void ExtensionsParser::missingAttribute(const QString& attribute, const QString& element)
{
if (locator == nullptr)
internalError(QString("Missing \"%1\" attribute in \"%2\" element. Element ignored.").arg(attribute).arg(element));
else
internalError(QString("Missing \"%1\" attribute in \"%2\" element (line: %3). Element ignored.")
.arg(attribute).arg(element).arg(locator->lineNumber()));
}
void ExtensionsParser::unknownAttribute(const QString& attribute, const QString& element)
{
if (locator == nullptr)
internalError(QString("Unknown attribute \"%1\" for element \"%2\" ignored.").arg(attribute).arg(element));
else
internalError(QString("Unknown attribute \"%1\" for element \"%2\" ignored (line: %3).")
.arg(attribute).arg(element).arg(locator->lineNumber()));
}
void ExtensionsParser::unknownElement(const QString& parent, const QString& element)
{
if (locator == nullptr)
internalError(QString("Unknown element \"%1\", found within a \"%2\", ignored.").arg(element).arg(parent));
else
internalError(QString("Unknown element \"%1\", found within a \"%2\", ignored (line: %3).")
.arg(element).arg(parent).arg(locator->lineNumber()));
}
void ExtensionsParser::parseExtensionPointAttributes(const QXmlAttributes& attributes)
{
ExtensionPoint::Pointer currentExtPoint =
registry->GetElementFactory()->CreateExtensionPoint(contribution->ShouldPersist());
// Process Attributes
int len = attributes.length();
for (int i = 0; i < len; i++)
{
QString attrName = attributes.localName(i);
QString attrValue = attributes.value(i).trimmed();
if (attrName == EXTENSION_POINT_NAME)
currentExtPoint->SetLabel(translate(attrValue));
else if (attrName == EXTENSION_POINT_ID)
{
QString uniqueId;
QString namespaceName;
int simpleIdStart = attrValue.lastIndexOf('.');
if (simpleIdStart != -1 && extractNamespaces)
{
namespaceName = attrValue.left(simpleIdStart);
uniqueId = attrValue;
}
else
{
namespaceName = contribution->GetDefaultNamespace();
uniqueId = namespaceName + '.' + attrValue;
}
currentExtPoint->SetUniqueIdentifier(uniqueId);
currentExtPoint->SetNamespace(namespaceName);
}
else if (attrName == EXTENSION_POINT_SCHEMA)
currentExtPoint->SetSchema(attrValue);
else
unknownAttribute(attrName, EXTENSION_POINT);
}
if (currentExtPoint->GetSimpleIdentifier().isEmpty() || currentExtPoint->GetLabel().isEmpty())
{
QString attribute = currentExtPoint->GetSimpleIdentifier().isEmpty() ? EXTENSION_POINT_ID : EXTENSION_POINT_NAME;
missingAttribute(attribute, EXTENSION_POINT);
stateStack.pop();
stateStack.push(IGNORED_ELEMENT_STATE);
return;
}
if (!objectManager->AddExtensionPoint(currentExtPoint, true))
{
// avoid adding extension point second time as it might cause
// extensions associated with the existing extension point to
// become inaccessible.
if (registry->Debug())
{
QString msg = QString("Ignored duplicate extension point \"%1\" supplied by \"%2\".")
.arg(currentExtPoint->GetUniqueIdentifier()).arg(contribution->GetDefaultNamespace());
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC));
registry->Log(status);
}
stateStack.pop();
stateStack.push(IGNORED_ELEMENT_STATE);
return;
}
if (currentExtPoint->GetNamespace().isEmpty())
currentExtPoint->SetNamespace(contribution->GetDefaultNamespace());
currentExtPoint->SetContributorId(contribution->GetContributorId());
addedRegistryObjects.push_back(currentExtPoint);
// Now populate the the vector just below us on the objectStack with this extension point
scratchVectors[EXTENSION_POINT_INDEX].push_back(currentExtPoint);
}
void ExtensionsParser::internalError(const QString& message)
{
IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME,
PARSE_PROBLEM, message, BERRY_STATUS_LOC));
error(status);
}
QString ExtensionsParser::translate(const QString& key) const
{
return registry->Translate(key, resources);
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp
index f59a422aa6..e05e69c7bb 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp
@@ -1,497 +1,498 @@
/*============================================================================
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 NOMINMAX
#define NOMINMAX
#endif
#include "berryInternalPlatform.h"
#include "berryLog.h"
#include "berryLogImpl.h"
#include "berryPlatform.h"
#include "berryPlatformException.h"
#include "berryDebugUtil.h"
#include "berryPlatformException.h"
#include "berryCTKPluginActivator.h"
#include "berryPlatformException.h"
#include "berryApplicationContainer.h"
#include "berryProduct.h"
#include "berryIBranding.h"
//#include "event/berryPlatformEvents.h"
//#include "berryPlatformLogChannel.h"
#include <berryIApplicationContext.h>
#include <berryIExtensionRegistry.h>
#include <berryIProduct.h>
#include <service/datalocation/ctkLocation.h>
#include <service/debug/ctkDebugOptions.h>
#include <ctkPluginContext.h>
#include <ctkPlugin.h>
#include <ctkPluginException.h>
#include <ctkPluginFrameworkLauncher.h>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QDebug>
#include <QMutexLocker>
+#include <QStringList>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <usModuleInitialization.h>
US_INITIALIZE_MODULE
namespace berry {
QMutex InternalPlatform::m_Mutex;
bool InternalPlatform::DEBUG = false;
bool InternalPlatform::DEBUG_PLUGIN_PREFERENCES = false;
InternalPlatform::InternalPlatform()
: m_Initialized(false)
, m_ConsoleLog(false)
, m_Context(nullptr)
{
}
InternalPlatform::~InternalPlatform()
{
}
InternalPlatform* InternalPlatform::GetInstance()
{
QMutexLocker lock(&m_Mutex);
static InternalPlatform instance;
return &instance;
}
bool InternalPlatform::ConsoleLog() const
{
return m_ConsoleLog;
}
QVariant InternalPlatform::GetOption(const QString& option, const QVariant& defaultValue) const
{
ctkDebugOptions* options = GetDebugOptions();
if (options != nullptr)
{
return options->getOption(option, defaultValue);
}
return QVariant();
}
IAdapterManager* InternalPlatform::GetAdapterManager() const
{
AssertInitialized();
return nullptr;
}
SmartPointer<IProduct> InternalPlatform::GetProduct() const
{
if (product.IsNotNull()) return product;
ApplicationContainer* container = org_blueberry_core_runtime_Activator::GetContainer();
IBranding* branding = container == nullptr ? nullptr : container->GetBranding();
if (branding == nullptr) return IProduct::Pointer();
IProduct::Pointer brandingProduct = branding->GetProduct();
if (!brandingProduct)
{
brandingProduct = new Product(branding);
}
product = brandingProduct;
return product;
}
void InternalPlatform::InitializePluginPaths()
{
QMutexLocker lock(&m_Mutex);
// Add search paths for Qt plugins
for(const auto& qtPluginPath : m_Context->getProperty(Platform::PROP_QTPLUGIN_PATH).toStringList())
{
if (qtPluginPath.isEmpty())
continue;
if (QFile::exists(qtPluginPath))
{
QCoreApplication::addLibraryPath(qtPluginPath);
}
else if (m_ConsoleLog)
{
BERRY_WARN << "Qt plugin path does not exist: " << qtPluginPath.toStdString();
}
}
// Add a default search path. It is assumed that installed applications
// provide their Qt plugins in that path.
static const QString defaultQtPluginPath = QCoreApplication::applicationDirPath() + "/plugins";
if (QFile::exists(defaultQtPluginPath))
{
QCoreApplication::addLibraryPath(defaultQtPluginPath);
}
if (m_ConsoleLog)
{
std::string pathList;
foreach(QString libPath, QCoreApplication::libraryPaths())
{
pathList += (pathList.empty() ? "" : ", ") + libPath.toStdString();
}
BERRY_INFO << "Qt library search paths: " << pathList;
}
/*
m_ConfigPath.setPath(m_Context->getProperty("application.configDir").toString());
m_InstancePath.setPath(m_Context->getProperty("application.dir").toString());
QString installPath = m_Context->getProperty(Platform::PROP_HOME).toString();
if (installPath.isEmpty())
{
m_InstallPath = m_InstancePath;
}
else {
m_InstallPath.setPath(installPath);
}
QString dataLocation = m_Context->getProperty(Platform::PROP_STORAGE_DIR).toString();
if (!storageDir.isEmpty())
{
if (dataLocation.at(dataLocation.size()-1) != '/')
{
dataLocation += '/';
}
m_UserPath.setPath(dataLocation);
}
else
{
// 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.
dataLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + this->getOrganizationName() + "/" + this->getApplicationName() + '_';
dataLocation += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/";
m_UserPath.setPath(dataLocation);
}
BERRY_INFO(m_ConsoleLog) << "Framework storage dir: " << m_UserPath.absolutePath();
QFileInfo userFile(m_UserPath.absolutePath());
if (!QDir().mkpath(userFile.absoluteFilePath()) || !userFile.isWritable())
{
QString tmpPath = QDir::temp().absoluteFilePath(QString::fromStdString(this->commandName()));
BERRY_WARN << "Storage dir " << userFile.absoluteFilePath() << " is not writable. Falling back to temporary path " << tmpPath;
QDir().mkpath(tmpPath);
userFile.setFile(tmpPath);
}
m_BaseStatePath.setPath(m_UserPath.absolutePath() + "/bb-metadata/bb-plugins");
QString logPath(m_UserPath.absoluteFilePath(QString::fromStdString(this->commandName()) + ".log"));
m_PlatformLogChannel = new Poco::SimpleFileChannel(logPath.toStdString());
*/
}
ctkDebugOptions* InternalPlatform::GetDebugOptions() const
{
return m_DebugTracker.isNull() ? nullptr : m_DebugTracker->getService();
}
IApplicationContext* InternalPlatform::GetApplicationContext() const
{
QList<ctkServiceReference> refs;
try
{
refs = m_Context->getServiceReferences<IApplicationContext>("(blueberry.application.type=main.thread)");
}
catch (const std::invalid_argument&)
{
return nullptr;
}
if (refs.isEmpty()) return nullptr;
// assumes the application context is available as a service
IApplicationContext* result = m_Context->getService<IApplicationContext>(refs.front());
if (result != nullptr)
{
m_Context->ungetService(refs.front());
return result;
}
return nullptr;
}
void InternalPlatform::Start(ctkPluginContext* context)
{
this->m_Context = context;
m_ConsoleLog = m_Context->getProperty(ctkPluginFrameworkLauncher::PROP_CONSOLE_LOG).toBool();
OpenServiceTrackers();
this->InitializePluginPaths();
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
DebugUtil::RestoreState(m_UserPath);
#endif
InitializeDebugFlags();
this->m_Initialized = true;
}
void InternalPlatform::Stop(ctkPluginContext* /*context*/)
{
AssertInitialized();
this->m_Initialized = false;
CloseServiceTrackers();
#ifdef BLUEBERRY_DEBUG_SMARTPOINTER
DebugUtil::SaveState(m_UserPath);
#endif
this->m_Context = nullptr;
}
void InternalPlatform::AssertInitialized() const
{
if (!m_Initialized)
{
throw PlatformException("The Platform has not been initialized yet!");
}
}
void InternalPlatform::OpenServiceTrackers()
{
ctkPluginContext* context = this->m_Context;
instanceLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::INSTANCE_FILTER)));
instanceLocation->open();
userLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::USER_FILTER)));
userLocation->open();
configurationLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::CONFIGURATION_FILTER)));
configurationLocation->open();
installLocation.reset(new ctkServiceTracker<ctkLocation*>(context, ctkLDAPSearchFilter(ctkLocation::INSTALL_FILTER)));
installLocation->open();
m_RegistryTracker.reset(new ctkServiceTracker<berry::IExtensionRegistry*>(context));
m_RegistryTracker->open();
m_DebugTracker.reset(new ctkServiceTracker<ctkDebugOptions*>(context));
m_DebugTracker->open();
}
void InternalPlatform::CloseServiceTrackers()
{
if (!m_RegistryTracker.isNull())
{
m_RegistryTracker->close();
m_RegistryTracker.reset();
}
if (!m_DebugTracker.isNull())
{
m_DebugTracker->close();
m_DebugTracker.reset();
}
if (!configurationLocation.isNull()) {
configurationLocation->close();
configurationLocation.reset();
}
if (!installLocation.isNull()) {
installLocation->close();
installLocation.reset();
}
if (!instanceLocation.isNull()) {
instanceLocation->close();
instanceLocation.reset();
}
if (!userLocation.isNull()) {
userLocation->close();
userLocation.reset();
}
}
void InternalPlatform::InitializeDebugFlags()
{
DEBUG = this->GetOption(Platform::PI_RUNTIME + "/debug", false).toBool();
if (DEBUG)
{
DEBUG_PLUGIN_PREFERENCES = GetOption(Platform::PI_RUNTIME + "/preferences/plugin", false).toBool();
}
}
IExtensionRegistry* InternalPlatform::GetExtensionRegistry()
{
return m_RegistryTracker.isNull() ? nullptr : m_RegistryTracker->getService();
}
mitk::IPreferencesService *InternalPlatform::GetPreferencesService()
{
return mitk::CoreServices::GetPreferencesService();
}
ctkLocation* InternalPlatform::GetConfigurationLocation()
{
this->AssertInitialized();
return configurationLocation->getService();
}
ctkLocation* InternalPlatform::GetInstallLocation()
{
this->AssertInitialized();
return installLocation->getService();
}
ctkLocation* InternalPlatform::GetInstanceLocation()
{
this->AssertInitialized();
return instanceLocation->getService();
}
QDir InternalPlatform::GetStateLocation(const QSharedPointer<ctkPlugin>& plugin)
{
ctkLocation* service = GetInstanceLocation();
if (service == nullptr)
{
throw ctkIllegalStateException("No instance data can be specified.");
}
QUrl url = GetInstanceLocation()->getDataArea(plugin->getSymbolicName());
if (!url.isValid())
{
throw ctkIllegalStateException("The instance data location has not been specified yet.");
}
QDir location(url.toLocalFile());
if (!location.exists())
{
if (!location.mkpath(location.absolutePath()))
{
throw PlatformException(QString("Could not create plugin state location \"%1\"").arg(location.absolutePath()));
}
}
return location;
}
//PlatformEvents& InternalPlatform::GetEvents()
//{
// return m_Events;
//}
ctkLocation* InternalPlatform::GetUserLocation()
{
this->AssertInitialized();
return userLocation->getService();
}
ILog *InternalPlatform::GetLog(const QSharedPointer<ctkPlugin> &plugin) const
{
LogImpl* result = m_Logs.value(plugin->getPluginId());
if (result != nullptr)
return result;
// ExtendedLogService logService = (ExtendedLogService) extendedLogTracker.getService();
// Logger logger = logService == null ? null : logService.getLogger(bundle, PlatformLogWriter.EQUINOX_LOGGER_NAME);
// result = new Log(bundle, logger);
// ExtendedLogReaderService logReader = (ExtendedLogReaderService) logReaderTracker.getService();
// logReader.addLogListener(result, result);
// logs.put(bundle, result);
// return result;
result = new LogImpl(plugin);
m_Logs.insert(plugin->getPluginId(), result);
return result;
}
bool InternalPlatform::IsRunning() const
{
QMutexLocker lock(&m_Mutex);
try
{
return m_Initialized && m_Context && m_Context->getPlugin()->getState() == ctkPlugin::ACTIVE;
}
catch (const ctkIllegalStateException&)
{
return false;
}
}
QSharedPointer<ctkPlugin> InternalPlatform::GetPlugin(const QString &symbolicName)
{
QList<QSharedPointer<ctkPlugin> > plugins = m_Context->getPlugins();
QSharedPointer<ctkPlugin> res(nullptr);
foreach(QSharedPointer<ctkPlugin> plugin, plugins)
{
if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 &&
plugin->getSymbolicName() == symbolicName)
{
if (res.isNull())
{
res = plugin;
}
else if (res->getVersion().compare(plugin->getVersion()) < 0)
{
res = plugin;
}
}
}
return res;
}
QList<QSharedPointer<ctkPlugin> > InternalPlatform::GetPlugins(const QString &symbolicName, const QString &version)
{
QList<QSharedPointer<ctkPlugin> > plugins = m_Context->getPlugins();
QMap<ctkVersion, QSharedPointer<ctkPlugin> > selected;
ctkVersion versionObj(version);
foreach(QSharedPointer<ctkPlugin> plugin, plugins)
{
if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 &&
plugin->getSymbolicName() == symbolicName)
{
if (plugin->getVersion().compare(versionObj) > -1)
{
selected.insert(plugin->getVersion(), plugin);
}
}
}
QList<QSharedPointer<ctkPlugin> > sortedPlugins = selected.values();
QList<QSharedPointer<ctkPlugin> > reversePlugins;
- qCopyBackward(sortedPlugins.begin(), sortedPlugins.end(), reversePlugins.end());
+ std::copy_backward(sortedPlugins.begin(), sortedPlugins.end(), reversePlugins.end());
return reversePlugins;
}
QStringList InternalPlatform::GetApplicationArgs() const
{
QStringList result;
IApplicationContext* appContext = this->GetApplicationContext();
if (appContext)
{
QHash<QString, QVariant> args = appContext->GetArguments();
result = args[IApplicationContext::APPLICATION_ARGS].toStringList();
}
return result;
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryProductExtensionBranding.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryProductExtensionBranding.cpp
index 629c2b1da7..409824922f 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryProductExtensionBranding.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryProductExtensionBranding.cpp
@@ -1,92 +1,92 @@
/*============================================================================
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 "berryProductExtensionBranding.h"
#include <berryIConfigurationElement.h>
#include <berryIContributor.h>
#include <berryIProduct.h>
#include "berryCTKPluginActivator.h"
namespace berry {
const QString ProductExtensionBranding::ATTR_DESCRIPTION = "description";
const QString ProductExtensionBranding::ATTR_NAME = "name";
const QString ProductExtensionBranding::ATTR_APPLICATION = "application";
const QString ProductExtensionBranding::ATTR_VALUE = "value";
ProductExtensionBranding::ProductExtensionBranding(const QString& id, const SmartPointer<IConfigurationElement>& element)
: id(id)
{
if (element.IsNull()) return;
application = element->GetAttribute(ATTR_APPLICATION);
name = element->GetAttribute(ATTR_NAME);
description = element->GetAttribute(ATTR_DESCRIPTION);
LoadProperties(element);
}
QSharedPointer<ctkPlugin> ProductExtensionBranding::GetDefiningPlugin() const
{
return definingPlugin;
}
QString ProductExtensionBranding::GetApplication() const
{
return application;
}
QString ProductExtensionBranding::GetName() const
{
return name;
}
QString ProductExtensionBranding::GetDescription() const
{
return description;
}
QString ProductExtensionBranding::GetId() const
{
return id;
}
QString ProductExtensionBranding::GetProperty(const QString& key) const
{
auto iter = properties.find(key);
- return iter != properties.end() ? iter.value() : QString::null;
+ return iter != properties.end() ? iter.value() : QString();
}
SmartPointer<IProduct> ProductExtensionBranding::GetProduct() const
{
return IProduct::Pointer();
}
void ProductExtensionBranding::LoadProperties(const SmartPointer<IConfigurationElement>& element)
{
QList<IConfigurationElement::Pointer> children = element->GetChildren();
properties.clear();
- for (const auto &child : qAsConst(children))
+ for (const auto &child : std::as_const(children))
{
QString key = child->GetAttribute(ATTR_NAME);
QString value = child->GetAttribute(ATTR_VALUE);
if (!key.isEmpty() && !value.isEmpty())
{
properties.insert(key, value);
}
}
definingPlugin = org_blueberry_core_runtime_Activator::GetPlugin(element->GetContributor());
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryObject.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryObject.cpp
index 402bf7a6ed..e90e666400 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryObject.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryObject.cpp
@@ -1,119 +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.
============================================================================*/
#include "berryRegistryObject.h"
#include "berryExtensionRegistry.h"
#include "berryRegistryObjectManager.h"
+#include <QLocale>
+
namespace berry {
// it is assumed that int has 32 bits (bits #0 to #31);
// bits #0 - #29 are the offset (limited to about 1Gb)
// bit #30 - persistence flag
// bit #31 - registry object has no extra data offset
// the bit#31 is a sign bit; bit#30 is the highest mantissa bit
const int RegistryObject::EMPTY_MASK = 0x80000000; // only taking bit #31
const int RegistryObject::PERSIST_MASK = 0x40000000; // only taking bit #30
const int RegistryObject::OFFSET_MASK = 0x3FFFFFFF; // all bits but #30, #31
RegistryObject::RegistryObject()
: registry(nullptr), objectId(RegistryObjectManager::UNKNOWN), extraDataOffset(EMPTY_MASK)
{
objectKey = QString::number(objectId);
}
QString RegistryObject::GetKey() const
{
return objectKey;
}
bool RegistryObject::IsEqual(const KeyedElement& other) const
{
return objectId == static_cast<const RegistryObject&>(other).objectId;
}
RegistryObject::RegistryObject(ExtensionRegistry* registry, bool persist)
: registry(registry), objectId(RegistryObjectManager::UNKNOWN), extraDataOffset(EMPTY_MASK)
{
objectKey = QString::number(objectId);
SetPersist(persist);
}
void RegistryObject::SetRawChildren(const QList<int>& values)
{
children = values;
}
QList<int> RegistryObject::GetRawChildren() const
{
return children;
}
void RegistryObject::SetObjectId(int value)
{
objectId = value;
objectKey = QString::number(value);
}
int RegistryObject::GetObjectId() const
{
return objectId;
}
bool RegistryObject::ShouldPersist() const
{
return (extraDataOffset & PERSIST_MASK) == PERSIST_MASK;
}
bool RegistryObject::NoExtraData() const
{
return (extraDataOffset & EMPTY_MASK) == EMPTY_MASK;
}
int RegistryObject::GetExtraDataOffset() const
{
if (NoExtraData())
return -1;
return extraDataOffset & OFFSET_MASK;
}
void RegistryObject::SetExtraDataOffset(int offset)
{
if (offset == -1)
{
extraDataOffset &= ~OFFSET_MASK; // clear all offset bits
extraDataOffset |= EMPTY_MASK;
return;
}
if ((offset & OFFSET_MASK) != offset)
throw ctkInvalidArgumentException("Registry object: extra data offset is out of range");
extraDataOffset &= ~(OFFSET_MASK | EMPTY_MASK); // clear all offset bits; mark as non-empty
extraDataOffset |= (offset & OFFSET_MASK); // set all offset bits
}
QLocale RegistryObject::GetLocale() const
{
return registry->GetLocale();
}
void RegistryObject::SetPersist(bool persist)
{
if (persist)
extraDataOffset |= PERSIST_MASK;
else
extraDataOffset &= ~PERSIST_MASK;
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp b/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp
index 663db3296c..ec4eb443af 100644
--- a/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp
@@ -1,269 +1,269 @@
/*============================================================================
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 "berryRegistryStrategy.h"
#include "berryCoreException.h"
#include "berryCTKPluginListener.h"
#include "berryExtensionRegistry.h"
#include "berryExtensionType.h"
#include "berryRegistryConstants.h"
#include "berryRegistryContributor.h"
#include "berryRegistryMessages.h"
#include "berryRegistrySupport.h"
#include "berryStatus.h"
#include "berryLog.h"
#include "berryCTKPluginActivator.h"
#include "berryCTKPluginUtils.h"
#include <ctkPlugin.h>
#include <ctkPluginContext.h>
#include <ctkUtils.h>
#include <QFileInfo>
#include <QDateTime>
#include <QXmlSimpleReader>
namespace berry {
RegistryStrategy::RegistryStrategy(const QList<QString>& storageDirs, const QList<bool>& cacheReadOnly,
QObject* key)
: storageDirs(storageDirs), cacheReadOnly(cacheReadOnly), token(key), trackTimestamp(false)
{
// Only do timestamp calculations if osgi.checkConfiguration is set to "true" (typically,
// this implies -dev mode)
ctkPluginContext* context = org_blueberry_core_runtime_Activator::getPluginContext();
if (context)
{
trackTimestamp = context->getProperty(RegistryConstants::PROP_CHECK_CONFIG).toString().compare("true", Qt::CaseInsensitive) == 0;
}
}
RegistryStrategy::~RegistryStrategy()
{
}
int RegistryStrategy::GetLocationsLength() const
{
return storageDirs.size();
}
QString RegistryStrategy::GetStorage(int index) const
{
return storageDirs[index];
}
bool RegistryStrategy::IsCacheReadOnly(int index) const
{
if (!cacheReadOnly.empty())
return cacheReadOnly[index];
return true;
}
void RegistryStrategy::Log(const SmartPointer<IStatus>& status)
{
RegistrySupport::Log(status, QString());
}
QString RegistryStrategy::Translate(const QString& key, QTranslator* resources)
{
return RegistrySupport::Translate(key, resources);
}
void RegistryStrategy::OnStart(IExtensionRegistry* reg, bool loadedFromCache)
{
ExtensionRegistry* registry = dynamic_cast<ExtensionRegistry*>(reg);
if (registry == nullptr)
return;
// register a listener to catch new plugin installations/resolutions.
pluginListener.reset(new CTKPluginListener(registry, token, this));
org_blueberry_core_runtime_Activator::getPluginContext()->connectPluginListener(
pluginListener.data(), SLOT(PluginChanged(ctkPluginEvent)), Qt::DirectConnection);
// populate the registry with all the currently installed plugins.
// There is a small window here while ProcessPlugins is being
// called where the pluginListener may receive a ctkPluginEvent
// to add/remove a plugin from the registry. This is ok since
// the registry is a synchronized object and will not add the
// same bundle twice.
if (!loadedFromCache)
pluginListener->ProcessPlugins(org_blueberry_core_runtime_Activator::getPluginContext()->getPlugins());
}
void RegistryStrategy::OnStop(IExtensionRegistry* /*registry*/)
{
if (!pluginListener.isNull())
{
org_blueberry_core_runtime_Activator::getPluginContext()->disconnectPluginListener(pluginListener.data());
}
}
QObject* RegistryStrategy::CreateExecutableExtension(const SmartPointer<RegistryContributor>& contributor,
const QString& className, const QString& /*overridenContributorName*/)
{
QObject* result = nullptr;
QSharedPointer<ctkPlugin> plugin = CTKPluginUtils::GetDefault()->GetPlugin(contributor->GetName());
if (!plugin.isNull())
{
// immediately start the plugin but do not change the plugins autostart setting
plugin->start(ctkPlugin::START_TRANSIENT);
}
else
{
QString message = QString("Unable to find plugin \"%1\" for contributor \"%2\".")
.arg(contributor->GetName()).arg(contributor->GetActualName());
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME,
RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC));
throw CoreException(status);
}
//QString typeName = contributor->GetActualName() + "_" + className;
QString typeName = className;
int extensionTypeId = ExtensionType::type(typeName.toLatin1().data());
if (extensionTypeId == 0)
{
QString message = QString("Unable to find class \"%1\" from contributor \"%2\"."
" The class was either not registered via "
"BERRY_REGISTER_EXTENSION_CLASS(type, pluginContext) "
"or you forgot to run Qt's moc on the header file.")
.arg(className).arg(contributor->GetActualName());
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME,
RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC));
throw CoreException(status);
}
else
{
try
{
result = ExtensionType::construct(extensionTypeId);
}
catch (const ctkException& e)
{
QString message = QString("Contributor \"%1\" was unable to instantiate class \"%2\".")
.arg(contributor->GetActualName()).arg(className);
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME,
RegistryConstants::PLUGIN_ERROR, message, e, BERRY_STATUS_LOC));
throw CoreException(status);
}
catch (const std::exception& e)
{
QString message = QString("Contributor \"%1\" was unable to instantiate class \"%2\". Error: \"%3\"")
.arg(contributor->GetActualName()).arg(className).arg(QString(e.what()));
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME,
RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC));
throw CoreException(status);
}
}
return result;
}
//void RegistryStrategy::ScheduleChangeEvent(const QList<IRegistryEventListener>& listeners,
// const QHash<QString, CombinedEventDelta>& deltas,
// IExtensionRegistry* registry)
//{
// if (ExtensionRegistry* extRegistry = dynamic_cast<ExtensionRegistry*>(registry))
// extRegistry->ScheduleChangeEvent(listeners, deltas);
//}
//SmartPointer<IStatus> RegistryStrategy::ProcessChangeEvent(const QList<IRegistryEventListener>& listeners,
// const QHash<QString, CombinedEventDelta>& deltas,
// IExtensionRegistry* registry)
//{
// if (ExtensionRegistry* extRegistry = dynamic_cast<ExtensionRegistry*>(registry))
// return extRegistry->ProcessChangeEvent(listeners, deltas);
// return IStatus::Pointer();
//}
bool RegistryStrategy::Debug() const
{
return false;
}
bool RegistryStrategy::DebugRegistryEvents() const
{
return false;
}
bool RegistryStrategy::CacheUse() const
{
return true;
}
bool RegistryStrategy::CacheLazyLoading() const
{
return true;
}
long RegistryStrategy::GetContainerTimestamp() const
{
return 0;
}
long RegistryStrategy::GetContributionsTimestamp() const
{
return 0;
}
bool RegistryStrategy::CheckContributionsTimestamp() const
{
return trackTimestamp;
}
long RegistryStrategy::GetExtendedTimestamp(const QSharedPointer<ctkPlugin>& plugin, const QString& pluginManifest) const
{
if (pluginManifest.isEmpty())
return 0;
// The plugin manifest does not have a timestamp as it is embedded into
// the plugin itself. Try to get the timestamp of the plugin instead.
QFileInfo pluginInfo(QUrl(plugin->getLocation()).toLocalFile());
if (pluginInfo.exists())
{
- return ctk::msecsTo(QDateTime::fromTime_t(0), pluginInfo.lastModified()) + plugin->getPluginId();
+ return ctk::msecsTo(QDateTime::fromSecsSinceEpoch(0), pluginInfo.lastModified()) + plugin->getPluginId();
//return pluginManifest.openConnection().getLastModified() + bundle.getBundleId();
}
else
{
if (Debug())
{
BERRY_DEBUG << "Unable to obtain timestamp for the plugin " <<
plugin->getSymbolicName();
}
return 0;
}
}
QXmlReader* RegistryStrategy::GetXMLParser() const
{
if (theXMLParser.isNull())
{
theXMLParser.reset(new QXmlSimpleReader());
}
return theXMLParser.data();
}
QList<QString> RegistryStrategy::Translate(const QList<QString>& nonTranslated,
const SmartPointer<IContributor>& /*contributor*/,
const QLocale& /*locale*/)
{
return nonTranslated;
}
QLocale RegistryStrategy::GetLocale() const
{
return QLocale();
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.cpp b/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.cpp
index c18e061073..f434599415 100644
--- a/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.cpp
+++ b/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.cpp
@@ -1,42 +1,42 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryIExtensionPointFilter.h"
namespace berry {
-IExtensionPointFilter::IExtensionPointFilter(const IExtensionPointFilter::Concept* concept)
- : m_Self(concept)
+IExtensionPointFilter::IExtensionPointFilter(const IExtensionPointFilter::Concept* c)
+ : m_Self(c)
{
}
IExtensionPointFilter::Concept::~Concept()
{
}
bool IExtensionPointFilter::IsNull() const
{
return m_Self.get() == nullptr;
}
const IExtensionPointFilter::Concept* IExtensionPointFilter::GetConcept() const
{
return m_Self.get();
}
bool IExtensionPointFilter::Matches(const IExtensionPoint* target) const
{
return m_Self->Matches(target);
}
}
diff --git a/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.h b/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.h
index 6ace090e4f..16e15eb5bf 100644
--- a/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.h
+++ b/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.h
@@ -1,63 +1,63 @@
/*============================================================================
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 BERRYIEXTENSIONPOINTFILTER_H
#define BERRYIEXTENSIONPOINTFILTER_H
#include <org_blueberry_core_runtime_Export.h>
#include <memory>
namespace berry {
struct IExtensionPoint;
/**
* A filter compares the given object to some pattern and returns
* <code>true</code> if the two match and <code>false</code> otherwise.
* <p>
* This interface may be implemented by clients, however factory methods are
* available on IExtensionTracker.
* </p>
*/
struct org_blueberry_core_runtime_EXPORT IExtensionPointFilter
{
struct org_blueberry_core_runtime_EXPORT Concept {
virtual bool Matches(const IExtensionPoint* target) const = 0;
virtual ~Concept();
};
- IExtensionPointFilter(const Concept* concept);
+ IExtensionPointFilter(const Concept* c);
bool IsNull() const;
const Concept* GetConcept() const;
/**
* Return <code>true</code> if the given object matches the criteria
* for this filter.
*
* @param target the object to match
* @return <code>true</code> if the target matches this filter
* and <code>false</code> otherwise
*/
bool Matches(const IExtensionPoint* target) const;
private:
std::shared_ptr<const Concept> m_Self;
};
}
#endif // BERRYIEXTENSIONPOINTFILTER_H
diff --git a/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionRegistry.h b/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionRegistry.h
index a42b906847..d216827edd 100644
--- a/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionRegistry.h
+++ b/Plugins/org.blueberry.core.runtime/src/registry/berryIExtensionRegistry.h
@@ -1,396 +1,397 @@
/*============================================================================
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 BERRYIEXTENSIONREGISTRY_H
#define BERRYIEXTENSIONREGISTRY_H
#include "org_blueberry_core_runtime_Export.h"
#include <berrySmartPointer.h>
#include <QList>
+#include <QtPlugin>
class QTranslator;
namespace berry {
struct IConfigurationElement;
struct IContributor;
struct IExtension;
struct IExtensionPoint;
struct IExtensionPointFilter;
struct IRegistryEventListener;
/**
* The extension registry holds the master list of all
* discovered namespaces, extension points and extensions.
* <p>
* The extension registry can be queried, by name, for
* extension points and extensions.
* </p>
* <p>
* The various objects that describe the contents of the extension registry
* ({@link IExtensionPoint}, {@link IExtension}, and {@link IConfigurationElement})
* are intended for relatively short-term use. Clients that deal with these objects
* must be aware that they may become invalid if the declaring plug-in is updated
* or uninstalled. If this happens, all methods on these object except
* <code>isValid()</code> will throw {@link InvalidRegistryObjectException}.
* Code in a plug-in that has declared that it is not dynamic aware (or not declared
* anything) can safely ignore this issue, since the registry would not be
* modified while it is active. However, code in a plug-in that declares that it
* is dynamic aware must be careful if it accesses extension registry objects,
* because it's at risk if plug-in are removed. Similarly, tools that analyze
* or display the extension registry are vulnerable. Client code can pre-test for
* invalid objects by calling <code>isValid()</code>, which never throws this exception.
* However, pre-tests are usually not sufficient because of the possibility of the
* extension registry object becoming invalid as a result of a concurrent activity.
* At-risk clients must treat <code>InvalidRegistryObjectException</code> as if it
* were a checked exception. Also, such clients should probably register a listener
* with the extension registry so that they receive notification of any changes to
* the registry.
* </p>
* <p>
* Extensions and extension points are declared by generic entities called
* \c namespaces . The only fact known about namespaces is that they
* have unique string-based identifiers. One example of a namespace
* is a plug-in, for which the namespace id is the plug-in id.
* </p><p>
* This interface is not intended to be implemented by clients.
* </p>
*/
struct org_blueberry_core_runtime_EXPORT IExtensionRegistry
{
virtual ~IExtensionRegistry();
/**
* Returns all configuration elements from all extensions configured
* into the identified extension point. Returns an empty list if the extension
* point does not exist, has no extensions configured, or none of the extensions
* contain configuration elements.
*
* @param extensionPointId the unique identifier of the extension point
* (e.g. <code>"org.blueberry.core.applications"</code>)
* @return the configuration elements
*/
virtual QList<SmartPointer<IConfigurationElement> > GetConfigurationElementsFor(
const QString& extensionPointId) const = 0;
/**
* Returns all configuration elements from all extensions configured
* into the identified extension point. Returns an empty list if the extension
* point does not exist, has no extensions configured, or none of the extensions
* contain configuration elements.
*
* @param namespaze the namespace for the extension point
* (e.g. <code>"org.eclipse.core.resources"</code>)
* @param extensionPointName the simple identifier of the
* extension point (e.g. <code>"builders"</code>)
* @return the configuration elements
*/
virtual QList<SmartPointer<IConfigurationElement> > GetConfigurationElementsFor(
const QString& namespaze, const QString& extensionPointName) const = 0;
/**
* Returns all configuration elements from the identified extension.
* Returns an empty array if the extension does not exist or
* contains no configuration elements.
*
* @param namespaze the namespace for the extension point
* (e.g. <code>"org.eclipse.core.resources"</code>)
* @param extensionPointName the simple identifier of the
* extension point (e.g. <code>"builders"</code>)
* @param extensionId the unique identifier of the extension
* (e.g. <code>"com.example.acme.coolbuilder"</code>)
* @return the configuration elements
*/
virtual QList<SmartPointer<IConfigurationElement> > GetConfigurationElementsFor(
const QString& namespaze, const QString& extensionPointName, const QString& extensionId) const = 0;
/**
* Returns the specified extension in this extension registry,
* or <code>null</code> if there is no such extension.
*
* @param extensionId the unique identifier of the extension
* (e.g. <code>"com.example.acme.coolbuilder"</code>)
* @return the extension, or <code>null</code>
*/
virtual SmartPointer<IExtension> GetExtension(const QString& extensionId) const = 0;
/**
* Returns the specified extension in this extension registry,
* or <code>null</code> if there is no such extension.
* The first parameter identifies the extension point, and the second
* parameter identifies an extension plugged in to that extension point.
*
* @param extensionPointId the unique identifier of the extension point
* (e.g. <code>"org.eclipse.core.resources.builders"</code>)
* @param extensionId the unique identifier of the extension
* (e.g. <code>"com.example.acme.coolbuilder"</code>)
* @return the extension, or <code>null</code>
*/
virtual SmartPointer<IExtension> GetExtension(const QString& extensionPointId,
const QString& extensionId) const = 0;
/**
* Returns the specified extension in this extension registry,
* or <code>null</code> if there is no such extension.
* The first two parameters identify the extension point, and the third
* parameter identifies an extension plugged in to that extension point.
*
* @param namespaze the namespace for the extension point
* (e.g. <code>"org.eclipse.core.resources"</code>)
* @param extensionPointName the simple identifier of the
* extension point (e.g. <code>"builders"</code>)
* @param extensionId the unique identifier of the extension
* (e.g. <code>"com.example.acme.coolbuilder"</code>)
* @return the extension, or <code>null</code>
*/
virtual SmartPointer<IExtension> GetExtension(const QString& namespaze,
const QString& extensionPointName,
const QString& extensionId) const = 0;
/**
* Returns the extension point with the given extension point identifier
* in this extension registry, or <code>null</code> if there is no such
* extension point.
*
* @param extensionPointId the unique identifier of the extension point
* (e.g., <code>"org.blueberry.core.applications"</code>)
* @return the extension point, or <code>null</code>
*/
virtual SmartPointer<IExtensionPoint> GetExtensionPoint(const QString& extensionPointId) const = 0;
/**
* Returns the extension point in this extension registry
* with the given namespace and extension point simple identifier,
* or <code>null</code> if there is no such extension point.
*
* @param namespaze the namespace for the given extension point
* (e.g. <code>"org.eclipse.core.resources"</code>)
* @param extensionPointName the simple identifier of the
* extension point (e.g. <code>"builders"</code>)
* @return the extension point, or <code>null</code>
*/
virtual SmartPointer<IExtensionPoint> GetExtensionPoint(const QString& namespaze,
const QString& extensionPointName) const = 0;
/**
* Returns all extension points known to this extension registry.
* Returns an empty array if there are no extension points.
*
* @return the extension points known to this extension registry
*/
virtual QList<SmartPointer<IExtensionPoint> > GetExtensionPoints() const = 0;
/**
* Returns all extension points declared in the given namespace. Returns an empty array if
* there are no extension points declared in the namespace.
*
* @param namespaze the namespace for the extension points
* (e.g. <code>"org.eclipse.core.resources"</code>)
* @return the extension points in this registry declared in the given namespace
*/
virtual QList<SmartPointer<IExtensionPoint> > GetExtensionPoints(const QString& namespaze) const = 0;
/**
* Returns all extension points supplied by the contributor, or <code>null</code>
* if there are no such extension points.
*
* @param contributor the contributor for the extensions (for OSGi registry, bundles and
* fragments are different contributors)
* @return the extension points, or <code>null</code>
* @since 3.4
*/
virtual QList<SmartPointer<IExtensionPoint> > GetExtensionPoints(
const SmartPointer<IContributor>& contributor) const = 0;
/**
* Returns all extensions declared in the given namespace. Returns an empty array if
* no extensions are declared in the namespace.
*
* @param namespaze the namespace for the extensions
* (e.g. <code>"org.eclipse.core.resources"</code>)
* @return the extensions in this registry declared in the given namespace
*/
virtual QList<SmartPointer<IExtension> > GetExtensions(const QString& namespaze) const = 0;
/**
* Returns all extensions supplied by the contributor, or <code>null</code> if there
* are no such extensions.
* @param contributor the contributor for the extensions (for OSGi registry, bundles and
* fragments are different contributors)
* @return the extensions, or <code>null</code>
*/
virtual QList<SmartPointer<IExtension> > GetExtensions(const SmartPointer<IContributor>& contributor) const = 0;
/**
* Returns all namespaces currently used by extensions and extension points in this
* registry. Returns an empty array if there are no known extensions/extension points
* in this registry.
* <p>
* The fully-qualified name of an extension point or an extension consist of
* a namespace and a simple name (much like a qualified Java class name consist
* of a package name and a class name). The simple names are presumed to be unique
* in the namespace.
* </p>
* @return all namespaces known to this registry
*/
virtual QList<QString> GetNamespaces() const = 0;
/**
* Adds to this extension registry an extension point(s), extension(s), or
* a combination of those described by the XML file. The information in
* the XML file should be supplied in the same format as the plugin.xml; in fact,
* Plug-in Manifest editor can be used to prepare the XML file. The top token
* of the contribution (normally, "plugin" or "fragment" in the Plug-in Manifest
* editor) is ignored by this method.
* <p>
* This method is an access controlled method. Proper token (master token or user token) should
* be passed as an argument. Two registry keys are set in the registry constructor:
* master token and a user token. Master token allows all operations; user token allows
* non-persisted registry elements to be modified.
* </p>
*
* @param is stream open on the XML file. The XML file can contain an extension
* point(s) or/and extension(s) described in the format similar to plugin.xml. The method
* closes the device before returning.
* @param contributor the contributor making this contribution.
* @param persist indicates if the contribution(s) should be stored in the registry cache. If <code>false</code>,
* contribution is not persisted in the registry cache and is lost on BlueBerry restart
* @param name optional name of the contribution. Used for error reporting; might be <code>QString()</code>
* @param translationBundle optional translator used for translations; might be <code>nullptr</code>
* @param token the key used to check permissions
* @return <code>true</code> if the contribution was successfully processed and <code>false</code> otherwise
* @throws ctkInvalidArgumentException if an incorrect token is passed
*
* @see IContributor
*/
virtual bool AddContribution(QIODevice* is, const SmartPointer<IContributor>& contributor,
bool persist, const QString& name, QTranslator* translationBundle, QObject* token) = 0;
/**
* Removes the given extension from this registry.
* <p>
* This method is an access controlled method. Proper token (master token or user token) should
* be passed as an argument. Two registry keys are set in the registry constructor:
* master token and a user token. Master token allows all operations; user token only
* allows non-persisted registry elements to be modified.
* </p>
*
* @param extension extension to be removed
* @param token the key used to check permissions
* @return <code>true</code> if the extension was successfully removed, and <code>false</code> otherwise
* @throws ctkInvalidArgumentException if an incorrect token is passed
*/
virtual bool RemoveExtension(const SmartPointer<IExtension>& extension, QObject* token) = 0;
/**
* Removes the specified extension point from this registry.
* <p>
* This method is an access controlled method. Proper token (master token or user token) should
* be passed as an argument. Two registry keys are set in the registry constructor:
* master token and a user token. Master token allows all operations; user token only
* allows non-persisted registry elements to be modified.
* </p>
*
* @param extensionPoint extension point to be removed
* @param token the key used to check permissions
* @return <code>true</code> if the extension point was successfully removed, and
* <code>false</code> otherwise
* @throws ctkInvalidArgumentException if incorrect token is passed
*/
virtual bool RemoveExtensionPoint(const SmartPointer<IExtensionPoint>& extensionPoint, QObject* token) = 0;
/**
* Call this method to properly stop the registry. The method stops registry event processing
* and writes out cache information to be used in the next run. This is an access controlled
* method; master token is required.
* <p>
* This method is an access controlled method. Master token should be passed as an argument.
* </p>
* @param token master token for the registry
* @throws IllegalArgumentException if incorrect token is passed
*/
virtual void Stop(QObject* token) = 0;
/**
* Adds the given listener for registry change events related to the specified
* extension point or for changes to all extension points and underlying
* extensions if the \c extensionPointId argument is empty.
* <p>
* Depending on activity, listeners of this type might receive a large number
* of modifications and negatively impact overall system performance. Whenever
* possible, consider registering listener specific to an extension point rather
* than a "global" listener.
* </p><p>
* Once registered, a listener starts receiving notification of changes to
* the registry. Registry change notifications are sent asynchronously.
* The listener continues to receive notifications until it is removed.
* </p><p>
* This method has no effect if the listener is already registered.
* </p>
* @param listener the listener
* @param extensionPointId the unique identifier of extension point
* @see IExtensionPoint#GetUniqueIdentifier()
*/
virtual void AddListener(IRegistryEventListener* listener, const QString& extensionPointId = QString()) = 0;
/**
* Adds the given listener for registry change events for extension points
* matching the provided filter.
* <p>
* Depending on activity, listeners of this type might receive a large number
* of modifications and negatively impact overall system performance. Whenever
* possible, consider registering listener specific to an extension point rather
* than a "global" listener.
* </p><p>
* Once registered, a listener starts receiving notification of changes to
* the registry. Registry change notifications are sent asynchronously.
* The listener continues to receive notifications until it is removed.
* </p><p>
* This method has no effect if the listener is already registered.
* </p>
* @param listener the listener
* @param filter An extension point filter
* @see ExtensionTracker
*/
virtual void AddListener(IRegistryEventListener *listener, const IExtensionPointFilter& filter) = 0;
/**
* Removes the given registry change listener from this registry.
* <p>
* This method has no effect if the listener is not registered.
* </p>
* @param listener the listener
* @see #AddListener(IRegistryEventListener*, const QString&)
*/
virtual void RemoveListener(IRegistryEventListener* listener) = 0;
/**
* Call this method to determine if this extension registry supports multiple languages.
* <p>
* See the runtime option "-registryMultiLanguage" for enabling multi-language
* support.
* </p>
* @return <code>true</code> if multiple languages are supported by this
* instance of the extension registry; <code>false</code> otherwise.
*/
virtual bool IsMultiLanguage() const = 0;
};
}
Q_DECLARE_INTERFACE(berry::IExtensionRegistry, "org.blueberry.service.IExtensionRegistry")
#endif // BERRYIEXTENSIONREGISTRY_H
diff --git a/Plugins/org.blueberry.ui.qt.help/CMakeLists.txt b/Plugins/org.blueberry.ui.qt.help/CMakeLists.txt
index dee5567fde..61fe8f70b4 100644
--- a/Plugins/org.blueberry.ui.qt.help/CMakeLists.txt
+++ b/Plugins/org.blueberry.ui.qt.help/CMakeLists.txt
@@ -1,11 +1,11 @@
project(org_blueberry_ui_qt_help)
set(QT_USE_QTHELP 1)
set(QT_USE_QTWEBENGINE 1)
set(QT_USE_QTNETWORK 1)
mitk_create_plugin(
EXPORT_DIRECTIVE org_blueberry_ui_qt_help_EXPORT
EXPORTED_INCLUDE_SUFFIXES src
- PACKAGE_DEPENDS PRIVATE Qt5|Help+OpenGL+PrintSupport+WebEngineWidgets+Xml
+ PACKAGE_DEPENDS PRIVATE Qt6|Help+OpenGL+WebEngineWidgets+Xml
)
diff --git a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.cpp b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.cpp
index 8161333a64..ec38c48b6b 100644
--- a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.cpp
+++ b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.cpp
@@ -1,320 +1,321 @@
/*============================================================================
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 "berryHelpEditor.h"
#include "berryHelpEditorInput.h"
#include "berryHelpPluginActivator.h"
#include "berryHelpPerspective.h"
#include "berryHelpWebView.h"
#include "berryQHelpEngineWrapper.h"
#include "berryHelpEditorFindWidget.h"
#include "berryHelpPluginActivator.h"
#include "berryQHelpEngineWrapper.h"
#include <berryUIException.h>
#include <berryPlatformUI.h>
#include <berryIWorkbenchPage.h>
#include <berryIWorkbenchPartConstants.h>
#include <QToolBar>
#include <QHelpEngine>
#include <QVBoxLayout>
+#include <QWebEngineFindTextResult>
namespace berry {
const QString HelpEditor::EDITOR_ID = "org.blueberry.editors.help";
HelpEditor::HelpEditor()
: m_ToolBar(nullptr)
, m_WebEngineView(nullptr)
{
}
HelpEditor::~HelpEditor()
{
this->GetSite()->GetPage()->RemovePartListener(this);
this->GetSite()->GetPage()->GetWorkbenchWindow()->RemovePerspectiveListener(this);
}
void HelpEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input)
{
if (input.Cast<HelpEditorInput>().IsNull())
throw PartInitException("Invalid Input: Must be berry::HelpEditorInput");
this->SetSite(site);
site->GetPage()->AddPartListener(this);
site->GetPage()->GetWorkbenchWindow()->AddPerspectiveListener(this);
m_WebEngineView = new HelpWebView(site, nullptr);
connect(m_WebEngineView, SIGNAL(loadFinished(bool)), this, SLOT(InitializeTitle()));
this->DoSetInput(input);
}
void HelpEditor::CreateQtPartControl(QWidget* parent)
{
auto verticalLayout = new QVBoxLayout(parent);
verticalLayout->setSpacing(0);
verticalLayout->setContentsMargins(0, 0, 0, 0);
m_ToolBar = new QToolBar(parent);
m_ToolBar->setMaximumHeight(32);
verticalLayout->addWidget(m_ToolBar);
m_WebEngineView->setParent(parent);
m_WebEngineView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
verticalLayout->addWidget(m_WebEngineView);
m_FindWidget = new HelpEditorFindWidget(parent);
m_FindWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);
verticalLayout->addWidget(m_FindWidget);
m_FindWidget->hide();
connect(m_FindWidget, SIGNAL(findNext()), this, SLOT(findNext()));
connect(m_FindWidget, SIGNAL(findPrevious()), this, SLOT(findPrevious()));
connect(m_FindWidget, SIGNAL(find(QString, bool)), this,
SLOT(find(QString, bool)));
connect(m_FindWidget, SIGNAL(escapePressed()), m_WebEngineView, SLOT(setFocus()));
// Fill the editor toolbar
m_BackAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/go-previous.png"), "Go back",
m_WebEngineView, SLOT(backward()));
m_ForwardAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/go-next.png"), "Go forward",
m_WebEngineView, SLOT(forward()));
m_HomeAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/go-home.png"), "Go home",
m_WebEngineView, SLOT(home()));
m_ToolBar->addSeparator();
m_FindAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/find.png"), "Find in text",
this, SLOT(ShowTextSearch()));
m_ToolBar->addSeparator();
m_ZoomIn = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/zoom-in.png"), "Zoom in", m_WebEngineView, SLOT(scaleUp()));
m_ZoomOut = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/zoom-out.png"), "Zoom out", m_WebEngineView, SLOT(scaleDown()));
m_ToolBar->addSeparator();
m_OpenHelpMode = m_ToolBar->addAction("Open Help Perspective", this, SLOT(OpenHelpPerspective()));
m_CloseHelpMode = m_ToolBar->addAction("Close Help Perspective", this, SLOT(CloseHelpPerspective()));
IPerspectiveDescriptor::Pointer currPersp = this->GetSite()->GetPage()->GetPerspective();
m_OpenHelpMode->setVisible(!(currPersp.IsNotNull() && currPersp->GetId() == HelpPerspective::ID));
m_CloseHelpMode->setVisible((currPersp.IsNotNull() && currPersp->GetId() == HelpPerspective::ID));
connect(m_WebEngineView, SIGNAL(backwardAvailable(bool)), m_BackAction, SLOT(setEnabled(bool)));
connect(m_WebEngineView, SIGNAL(forwardAvailable(bool)), m_ForwardAction, SLOT(setEnabled(bool)));
m_BackAction->setEnabled(false);
m_ForwardAction->setEnabled(false);
m_HomeAction->setEnabled(!HelpPluginActivator::getInstance()->getQHelpEngine().homePage().isEmpty());
connect(&HelpPluginActivator::getInstance()->getQHelpEngine(), SIGNAL(homePageChanged(QString)),
this, SLOT(HomePageChanged(QString)));
}
void HelpEditor::DoSetInput(IEditorInput::Pointer input)
{
if (input.IsNull())
{
// close editor
class CloseEditorRunnable : public Poco::Runnable
{
private:
IEditorPart::Pointer editor;
public:
CloseEditorRunnable(IEditorPart::Pointer editor)
: editor(editor)
{}
void run() override
{
editor->GetSite()->GetPage()->CloseEditor(editor, false);
delete this;
}
};
Display::GetDefault()->AsyncExec(new CloseEditorRunnable(IEditorPart::Pointer(this)));
}
else
{
// an empty url represents the home page
HelpEditorInput::Pointer helpInput = input.Cast<HelpEditorInput>();
QString currHomePage = HelpPluginActivator::getInstance()->getQHelpEngine().homePage();
if (helpInput->GetUrl().isEmpty() && !currHomePage.isEmpty())
{
helpInput = HelpEditorInput::Pointer(new HelpEditorInput(currHomePage));
}
QtEditorPart::SetInput(helpInput);
m_WebEngineView->setSource(helpInput->GetUrl());
}
}
void HelpEditor::SetInputWithNotify(IEditorInput::Pointer input)
{
DoSetInput(input);
FirePropertyChange(IWorkbenchPartConstants::PROP_INPUT);
}
void HelpEditor::SetInput(IEditorInput::Pointer input)
{
SetInputWithNotify(input);
}
void HelpEditor::HomePageChanged(const QString &page)
{
if (page.isEmpty())
{
m_HomeAction->setEnabled(false);
}
m_HomeAction->setEnabled(true);
if (this->GetEditorInput().Cast<HelpEditorInput>()->GetUrl().isEmpty())
{
IEditorInput::Pointer newInput(new HelpEditorInput(page));
DoSetInput(newInput);
}
}
void HelpEditor::OpenHelpPerspective()
{
PlatformUI::GetWorkbench()->ShowPerspective(HelpPerspective::ID, this->GetSite()->GetPage()->GetWorkbenchWindow());
}
void HelpEditor::CloseHelpPerspective()
{
berry::IWorkbenchPage::Pointer
page =
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage();
page->ClosePerspective(page->GetPerspective(), true, true);
}
void HelpEditor::InitializeTitle()
{
QString title = m_WebEngineView->title();
this->SetPartName(title);
}
void HelpEditor::ShowTextSearch()
{
m_FindWidget->show();
}
void HelpEditor::SetFocus()
{
m_WebEngineView->setFocus();
enableShortcuts();
}
QWebEnginePage *HelpEditor::GetQWebPage() const
{
return m_WebEngineView->page();
}
IPartListener::Events::Types HelpEditor::GetPartEventTypes() const
{
return IPartListener::Events::DEACTIVATED;
}
void HelpEditor::PartDeactivated(const IWorkbenchPartReference::Pointer& partRef)
{
if (partRef == GetSite()->GetPage()->GetReference(IWorkbenchPart::Pointer(this)))
disableShortcuts();
}
IPerspectiveListener::Events::Types HelpEditor::GetPerspectiveEventTypes() const
{
return IPerspectiveListener::Events::ACTIVATED | IPerspectiveListener::Events::DEACTIVATED;
}
void HelpEditor::PerspectiveActivated(const SmartPointer<IWorkbenchPage>& /*page*/,
const IPerspectiveDescriptor::Pointer& perspective)
{
if (perspective->GetId() == HelpPerspective::ID)
{
m_OpenHelpMode->setVisible(false);
m_CloseHelpMode->setVisible(true);
}
}
void HelpEditor::PerspectiveDeactivated(const SmartPointer<IWorkbenchPage>& /*page*/,
const IPerspectiveDescriptor::Pointer& perspective)
{
if (perspective->GetId() == HelpPerspective::ID)
{
m_OpenHelpMode->setVisible(true);
m_CloseHelpMode->setVisible(false);
}
}
void HelpEditor::findNext()
{
find(m_FindWidget->text(), true);
}
void HelpEditor::findPrevious()
{
find(m_FindWidget->text(), false);
}
void HelpEditor::find(const QString &ttf, bool forward)
{
this->findInWebPage(ttf, forward);
if (!m_FindWidget->isVisible())
m_FindWidget->show();
}
void HelpEditor::findInWebPage(const QString &ttf, bool forward)
{
if (ttf.isEmpty())
{
m_WebEngineView->findText(ttf);
m_FindWidget->setPalette(true);
return;
}
QWebEnginePage::FindFlags options;
if (!forward)
options |= QWebEnginePage::FindBackward;
if (m_FindWidget->caseSensitive())
options |= QWebEnginePage::FindCaseSensitively;
- m_WebEngineView->findText(ttf, options, [this](bool found) { m_FindWidget->setPalette(found); });
+ m_WebEngineView->findText(ttf, options, [this](const QWebEngineFindTextResult& result) { m_FindWidget->setPalette(result.numberOfMatches() != 0); });
}
void HelpEditor::enableShortcuts()
{
m_BackAction->setShortcut(QKeySequence::Back);
m_ForwardAction->setShortcut(QKeySequence::Forward);
m_FindAction->setShortcut(QKeySequence::Find);
m_ZoomIn->setShortcut(QKeySequence::ZoomIn);
m_ZoomOut->setShortcut(QKeySequence::ZoomOut);
}
void HelpEditor::disableShortcuts()
{
m_BackAction->setShortcut(QKeySequence());
m_ForwardAction->setShortcut(QKeySequence());
m_FindAction->setShortcut(QKeySequence());
m_ZoomIn->setShortcut(QKeySequence());
m_ZoomOut->setShortcut(QKeySequence());
}
}
diff --git a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditorFindWidget.cpp b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditorFindWidget.cpp
index dea8dcea63..a5a282d4e3 100644
--- a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditorFindWidget.cpp
+++ b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpEditorFindWidget.cpp
@@ -1,164 +1,164 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryHelpEditorFindWidget.h"
#include <QApplication>
#include <QCheckBox>
#include <QHideEvent>
#include <QKeyEvent>
#include <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QToolButton>
namespace berry {
HelpEditorFindWidget::HelpEditorFindWidget(QWidget *parent)
: QWidget(parent)
, appPalette(qApp->palette())
{
installEventFilter(this);
auto hboxLayout = new QHBoxLayout(this);
QString resourcePath = QLatin1String(":/org.blueberry.ui.qt.help");
#ifndef Q_OS_MAC
- hboxLayout->setMargin(0);
+ hboxLayout->setContentsMargins({});
hboxLayout->setSpacing(6);
#endif
toolClose = setupToolButton(QLatin1String(""),
resourcePath + QLatin1String("/close.png"));
hboxLayout->addWidget(toolClose);
connect(toolClose, SIGNAL(clicked()), SLOT(hide()));
editFind = new QLineEdit(this);
hboxLayout->addWidget(editFind);
editFind->setMinimumSize(QSize(150, 0));
connect(editFind, SIGNAL(textChanged(QString)), this,
SLOT(textChanged(QString)));
connect(editFind, SIGNAL(returnPressed()), this, SIGNAL(findNext()));
connect(editFind, SIGNAL(textChanged(QString)), this, SLOT(updateButtons()));
toolPrevious = setupToolButton(tr("Previous"),
resourcePath + QLatin1String("/go-previous.png"));
connect(toolPrevious, SIGNAL(clicked()), this, SIGNAL(findPrevious()));
hboxLayout->addWidget(toolPrevious);
toolNext = setupToolButton(tr("Next"),
resourcePath + QLatin1String("/go-next.png"));
hboxLayout->addWidget(toolNext);
connect(toolNext, SIGNAL(clicked()), this, SIGNAL(findNext()));
checkCase = new QCheckBox(tr("Case Sensitive"), this);
hboxLayout->addWidget(checkCase);
setMinimumWidth(minimumSizeHint().width());
updateButtons();
}
HelpEditorFindWidget::~HelpEditorFindWidget()
{
}
void HelpEditorFindWidget::show()
{
QWidget::show();
editFind->selectAll();
editFind->setFocus(Qt::ShortcutFocusReason);
}
void HelpEditorFindWidget::showAndClear()
{
show();
editFind->clear();
}
QString HelpEditorFindWidget::text() const
{
return editFind->text();
}
bool HelpEditorFindWidget::caseSensitive() const
{
return checkCase->isChecked();
}
void HelpEditorFindWidget::setPalette(bool found)
{
QPalette palette = editFind->palette();
palette.setColor(QPalette::Active, QPalette::Base, found ? Qt::white
: QColor(255, 102, 102));
editFind->setPalette(palette);
}
void HelpEditorFindWidget::hideEvent(QHideEvent* event)
{
// TODO: remove this once webkit supports setting the palette
if (!event->spontaneous())
qApp->setPalette(appPalette);
}
void HelpEditorFindWidget::showEvent(QShowEvent* event)
{
// TODO: remove this once webkit supports setting the palette
if (!event->spontaneous())
{
QPalette p = appPalette;
p.setColor(QPalette::Inactive, QPalette::Highlight,
p.color(QPalette::Active, QPalette::Highlight));
p.setColor(QPalette::Inactive, QPalette::HighlightedText,
p.color(QPalette::Active, QPalette::HighlightedText));
qApp->setPalette(p);
}
}
void HelpEditorFindWidget::updateButtons()
{
const bool enable = !editFind->text().isEmpty();
toolNext->setEnabled(enable);
toolPrevious->setEnabled(enable);
}
void HelpEditorFindWidget::textChanged(const QString &text)
{
emit find(text, true);
}
bool HelpEditorFindWidget::eventFilter(QObject *object, QEvent *e)
{
if (e->type() == QEvent::KeyPress)
{
if ((static_cast<QKeyEvent*>(e))->key() == Qt::Key_Escape)
{
hide();
emit escapePressed();
}
}
return QWidget::eventFilter(object, e);
}
QToolButton* HelpEditorFindWidget::setupToolButton(const QString &text, const QString &icon)
{
auto toolButton = new QToolButton(this);
toolButton->setText(text);
toolButton->setAutoRaise(true);
toolButton->setIcon(QIcon(icon));
toolButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
return toolButton;
}
}
diff --git a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpIndexView.cpp b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpIndexView.cpp
index d4efe34f72..77a22144d0 100644
--- a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpIndexView.cpp
+++ b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpIndexView.cpp
@@ -1,310 +1,325 @@
/*============================================================================
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 "berryHelpIndexView.h"
#include "berryHelpPluginActivator.h"
#include "berryHelpEditor.h"
#include "berryHelpEditorInput.h"
#include "berryQHelpEngineWrapper.h"
#include "berryHelpTopicChooser.h"
#include <berryIWorkbenchPage.h>
#include <ctkSearchBox.h>
#include <QHelpIndexWidget>
+#include <QHelpLink>
#include <QLayout>
#include <QLabel>
#include <QMenu>
#include <QKeyEvent>
namespace berry {
HelpIndexWidget::HelpIndexWidget()
: QListView(nullptr)
{
setEditTriggers(QAbstractItemView::NoEditTriggers);
setUniformItemSizes(true);
connect(this, SIGNAL(activated(QModelIndex)),
this, SLOT(showLink(QModelIndex)));
}
void HelpIndexWidget::showLink(const QModelIndex &index)
{
if (!index.isValid())
return;
QHelpIndexModel *indexModel = qobject_cast<QHelpIndexModel*>(model());
if (!indexModel)
return;
QVariant v = indexModel->data(index, Qt::DisplayRole);
QString name;
if (v.isValid())
name = v.toString();
- QMap<QString, QUrl> links = indexModel->linksForKeyword(name);
+ QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine();
+ auto links = helpEngine.documentsForKeyword(name);
+
if (links.count() == 1)
{
- emit linkActivated(links.constBegin().value(), name);
+ emit linkActivated(links[0].url, name);
}
else if (links.count() > 1)
{
- emit linksActivated(links, name);
+ QMap<QString, QUrl> legacyLinks;
+
+ for (const auto& link : links)
+ legacyLinks.insert(link.title, link.url);
+
+ emit linksActivated(legacyLinks, name);
}
}
void HelpIndexWidget::activateCurrentItem()
{
showLink(currentIndex());
}
void HelpIndexWidget::filterIndices(const QString &filter, const QString &wildcard)
{
QHelpIndexModel *indexModel = qobject_cast<QHelpIndexModel*>(model());
if (!indexModel)
return;
QModelIndex idx = indexModel->filter(filter, wildcard);
if (idx.isValid())
setCurrentIndex(idx);
}
HelpIndexView::HelpIndexView()
: m_IndexWidget(nullptr)
{
}
HelpIndexView::~HelpIndexView()
{
}
void HelpIndexView::CreateQtPartControl(QWidget* parent)
{
if (m_IndexWidget == nullptr)
{
auto layout = new QVBoxLayout(parent);
//QLabel *l = new QLabel(tr("&Look for:"));
//layout->addWidget(l);
m_SearchLineEdit = new ctkSearchBox(parent);
m_SearchLineEdit->setClearIcon(QIcon(":/org.blueberry.ui.qt.help/clear.png"));
m_SearchLineEdit->setPlaceholderText("Filter...");
m_SearchLineEdit->setContentsMargins(2,2,2,0);
//l->setBuddy(m_SearchLineEdit);
connect(m_SearchLineEdit, SIGNAL(textChanged(QString)), this,
SLOT(filterIndices(QString)));
m_SearchLineEdit->installEventFilter(this);
- layout->setMargin(0);
+ layout->setContentsMargins({});
layout->setSpacing(2);
layout->addWidget(m_SearchLineEdit);
QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine();
m_IndexWidget = new HelpIndexWidget();
m_IndexWidget->setModel(helpEngine.indexModel());
connect(helpEngine.indexModel(), SIGNAL(indexCreationStarted()),
this, SLOT(setIndexWidgetBusy()));
connect(helpEngine.indexModel(), SIGNAL(indexCreated()),
this, SLOT(unsetIndexWidgetBusy()));
m_IndexWidget->installEventFilter(this);
connect(helpEngine.indexModel(), SIGNAL(indexCreationStarted()), this,
SLOT(disableSearchLineEdit()));
connect(helpEngine.indexModel(), SIGNAL(indexCreated()), this,
SLOT(enableSearchLineEdit()));
connect(m_IndexWidget, SIGNAL(linkActivated(QUrl,QString)), this,
SLOT(linkActivated(QUrl)));
connect(m_IndexWidget, SIGNAL(linksActivated(QMap<QString,QUrl>,QString)),
this, SLOT(linksActivated(QMap<QString,QUrl>,QString)));
connect(m_SearchLineEdit, SIGNAL(returnPressed()), m_IndexWidget,
SLOT(activateCurrentItem()));
layout->addWidget(m_IndexWidget);
m_IndexWidget->viewport()->installEventFilter(this);
}
}
void HelpIndexView::SetFocus()
{
if (!(m_IndexWidget->hasFocus() || m_SearchLineEdit->hasFocus()))
{
m_SearchLineEdit->setFocus();
}
}
void HelpIndexView::filterIndices(const QString &filter)
{
if (filter.contains(QLatin1Char('*')))
m_IndexWidget->filterIndices(filter, filter);
else
m_IndexWidget->filterIndices(filter, QString());
}
bool HelpIndexView::eventFilter(QObject *obj, QEvent *e)
{
if (obj == m_SearchLineEdit && e->type() == QEvent::KeyPress)
{
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
QModelIndex idx = m_IndexWidget->currentIndex();
switch (ke->key())
{
case Qt::Key_Up:
idx = m_IndexWidget->model()->index(idx.row()-1,
idx.column(), idx.parent());
if (idx.isValid())
{
m_IndexWidget->setCurrentIndex(idx);
return true;
}
break;
case Qt::Key_Down:
idx = m_IndexWidget->model()->index(idx.row()+1,
idx.column(), idx.parent());
if (idx.isValid())
{
m_IndexWidget->setCurrentIndex(idx);
return true;
}
break;
default: ; // stop complaining
}
}
else if (obj == m_IndexWidget && e->type() == QEvent::ContextMenu)
{
QContextMenuEvent *ctxtEvent = static_cast<QContextMenuEvent*>(e);
QModelIndex idx = m_IndexWidget->indexAt(ctxtEvent->pos());
if (idx.isValid())
{
QMenu menu;
QAction *curTab = menu.addAction(tr("Open Link"));
QAction *newTab = menu.addAction(tr("Open Link in New Tab"));
menu.move(m_IndexWidget->mapToGlobal(ctxtEvent->pos()));
QAction *action = menu.exec();
if (curTab == action)
m_IndexWidget->activateCurrentItem();
else if (newTab == action)
{
open(m_IndexWidget, idx);
}
}
}
else if (m_IndexWidget && obj == m_IndexWidget->viewport()
&& e->type() == QEvent::MouseButtonRelease)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(e);
QModelIndex idx = m_IndexWidget->indexAt(mouseEvent->pos());
if (idx.isValid())
{
Qt::MouseButtons button = mouseEvent->button();
if (((button == Qt::LeftButton) && (mouseEvent->modifiers() & Qt::ControlModifier))
- || (button == Qt::MidButton))
+ || (button == Qt::MiddleButton))
{
open(m_IndexWidget, idx);
}
}
}
#ifdef Q_OS_MAC
else if (obj == m_IndexWidget && e->type() == QEvent::KeyPress)
{
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter)
m_IndexWidget->activateCurrentItem();
}
#endif
return QObject::eventFilter(obj, e);
}
void HelpIndexView::enableSearchLineEdit()
{
m_SearchLineEdit->setDisabled(false);
filterIndices(m_SearchLineEdit->text());
}
void HelpIndexView::disableSearchLineEdit()
{
m_SearchLineEdit->setDisabled(true);
}
void HelpIndexView::setIndexWidgetBusy()
{
m_IndexWidget->setCursor(Qt::WaitCursor);
}
void HelpIndexView::unsetIndexWidgetBusy()
{
m_IndexWidget->unsetCursor();
}
void HelpIndexView::setSearchLineEditText(const QString &text)
{
m_SearchLineEdit->setText(text);
}
QString HelpIndexView::searchLineEditText() const
{
return m_SearchLineEdit->text();
}
void HelpIndexView::focusInEvent(QFocusEvent *e)
{
if (e->reason() != Qt::MouseFocusReason)
{
m_SearchLineEdit->selectAll();
m_SearchLineEdit->setFocus();
}
}
void HelpIndexView::open(HelpIndexWidget* indexWidget, const QModelIndex &index)
{
QHelpIndexModel *model = qobject_cast<QHelpIndexModel*>(indexWidget->model());
if (model)
{
QString keyword = model->data(index, Qt::DisplayRole).toString();
- QMap<QString, QUrl> links = model->linksForKeyword(keyword);
+
+ QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine();
+ auto links = helpEngine.documentsForKeyword(keyword);
QUrl url;
if (links.count() > 1)
{
- HelpTopicChooser tc(m_IndexWidget, keyword, links);
+ QMap<QString, QUrl> legacyLinks;
+
+ for (const auto& link : links)
+ legacyLinks.insert(link.title, link.url);
+
+ HelpTopicChooser tc(m_IndexWidget, keyword, legacyLinks);
if (tc.exec() == QDialog::Accepted)
url = tc.link();
}
else if (links.count() == 1)
{
- url = links.constBegin().value();
+ url = links[0].url;
}
else
{
return;
}
IEditorInput::Pointer input(new HelpEditorInput(url));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
}
void HelpIndexView::linkActivated(const QUrl& link)
{
IWorkbenchPage::Pointer page = this->GetSite()->GetPage();
HelpPluginActivator::linkActivated(page, link);
}
void HelpIndexView::linksActivated(const QMap<QString,QUrl>& links, const QString& keyword)
{
HelpTopicChooser tc(m_IndexWidget, keyword, links);
if (tc.exec() == QDialog::Accepted)
{
IWorkbenchPage::Pointer page = this->GetSite()->GetPage();
HelpPluginActivator::linkActivated(page, tc.link());
}
}
}
diff --git a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpIndexView.h b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpIndexView.h
index cb4c05330b..c005928b2b 100644
--- a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpIndexView.h
+++ b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpIndexView.h
@@ -1,118 +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 BERRYHELPINDEXVIEW_H_
#define BERRYHELPINDEXVIEW_H_
#include <berryQtViewPart.h>
#include <QModelIndex>
#include <QListView>
+#include <QUrl>
class ctkSearchBox;
class QHelpIndexWidget;
namespace berry {
class HelpIndexWidget : public QListView
{
Q_OBJECT
Q_SIGNALS:
/**
* This signal is emitted when an item is activated and its
* associated \a link should be shown. To know where the link
* belongs to, the \a keyword is given as a second parameter.
*/
void linkActivated(const QUrl &link, const QString &keyword);
/**
* This signal is emitted when the item representing the \a keyword
* is activated and the item has more than one link associated.
* The \a links consist of the document title and their URL.
*/
void linksActivated(const QMap<QString, QUrl> &links,
const QString &keyword);
public:
HelpIndexWidget();
public Q_SLOTS:
/**
* Filters the indices according to \a filter or \a wildcard.
* The item with the best match is set as current item.
*/
void filterIndices(const QString &filter,
const QString &wildcard = QString());
/**
* Activates the current item which will result eventually in
* the emitting of a linkActivated() or linksActivated()
* signal.
*/
void activateCurrentItem();
private Q_SLOTS:
void showLink(const QModelIndex &index);
};
class HelpIndexView : public QtViewPart
{
Q_OBJECT
public:
HelpIndexView();
~HelpIndexView() override;
void SetFocus() override;
protected:
void CreateQtPartControl(QWidget* parent) override;
void setSearchLineEditText(const QString &text);
QString searchLineEditText() const;
protected Q_SLOTS:
void linkActivated(const QUrl& link);
void linksActivated(const QMap<QString, QUrl> &links, const QString &keyword);
private Q_SLOTS:
void filterIndices(const QString &filter);
void enableSearchLineEdit();
void disableSearchLineEdit();
void setIndexWidgetBusy();
void unsetIndexWidgetBusy();
private:
bool eventFilter(QObject *obj, QEvent *e) override;
void focusInEvent(QFocusEvent *e);
void open(HelpIndexWidget *indexWidget, const QModelIndex &index);
Q_DISABLE_COPY(HelpIndexView)
ctkSearchBox* m_SearchLineEdit;
HelpIndexWidget* m_IndexWidget;
};
} // namespace berry
#endif /*BERRYHELPINDEXVIEW_H_*/
diff --git a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.cpp b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.cpp
index 1ef2c93bca..38acff3ef9 100644
--- a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.cpp
+++ b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.cpp
@@ -1,474 +1,475 @@
/*============================================================================
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 "berryHelpPluginActivator.h"
#include "berryHelpContentView.h"
#include "berryHelpIndexView.h"
#include "berryHelpSearchView.h"
#include "berryHelpEditor.h"
#include "berryHelpEditorInput.h"
#include "berryHelpEditorInputFactory.h"
#include "berryHelpPerspective.h"
#include "berryQHelpEngineConfiguration.h"
#include "berryQHelpEngineWrapper.h"
#include <berryPlatformUI.h>
#include <service/event/ctkEventConstants.h>
#include <QDir>
#include <QDateTime>
namespace berry {
class HelpPerspectiveListener : public IPerspectiveListener
{
public:
Events::Types GetPerspectiveEventTypes() const override;
using IPerspectiveListener::PerspectiveChanged;
void PerspectiveOpened(const SmartPointer<IWorkbenchPage>& page, const IPerspectiveDescriptor::Pointer& perspective) override;
void PerspectiveChanged(const SmartPointer<IWorkbenchPage>& page, const IPerspectiveDescriptor::Pointer& perspective, const QString &changeId) override;
};
class HelpWindowListener : public IWindowListener
{
public:
HelpWindowListener();
~HelpWindowListener() override;
void WindowClosed(const IWorkbenchWindow::Pointer& window) override;
void WindowOpened(const IWorkbenchWindow::Pointer& window) override;
private:
// We use the same perspective listener for every window
QScopedPointer<IPerspectiveListener> perspListener;
};
HelpPluginActivator* HelpPluginActivator::instance = nullptr;
HelpPluginActivator::HelpPluginActivator()
: pluginListener(nullptr)
{
this->instance = this;
}
HelpPluginActivator::~HelpPluginActivator()
{
instance = nullptr;
}
void
HelpPluginActivator::start(ctkPluginContext* context)
{
BERRY_REGISTER_EXTENSION_CLASS(berry::HelpContentView, context)
BERRY_REGISTER_EXTENSION_CLASS(berry::HelpIndexView, context)
BERRY_REGISTER_EXTENSION_CLASS(berry::HelpSearchView, context)
BERRY_REGISTER_EXTENSION_CLASS(berry::HelpEditor, context)
BERRY_REGISTER_EXTENSION_CLASS(berry::HelpEditorInputFactory, context)
BERRY_REGISTER_EXTENSION_CLASS(berry::HelpPerspective, context)
QFileInfo qhcInfo = context->getDataFile("qthelpcollection.qhc");
helpEngine.reset(new QHelpEngineWrapper(qhcInfo.absoluteFilePath()));
+ helpEngine->setReadOnly(false);
if (!helpEngine->setupData())
{
BERRY_ERROR << "QHelpEngine set-up failed: " << helpEngine->error().toStdString();
return;
}
helpEngineConfiguration.reset(new QHelpEngineConfiguration(context, *helpEngine.data()));
delete pluginListener;
pluginListener = new QCHPluginListener(context, helpEngine.data());
context->connectPluginListener(pluginListener, SLOT(pluginChanged(ctkPluginEvent)));
// register all QCH files from all the currently installed plugins
pluginListener->processPlugins();
helpEngine->initialDocSetupDone();
// Register a wnd listener which registers a perspective listener for each
// new window. The perspective listener opens the help home page in the window
// if no other help page is opened yet.
wndListener.reset(new HelpWindowListener());
PlatformUI::GetWorkbench()->AddWindowListener(wndListener.data());
// Register an event handler for CONTEXTHELP_REQUESTED events
helpContextHandler.reset(new HelpContextHandler);
ctkDictionary helpHandlerProps;
helpHandlerProps.insert(ctkEventConstants::EVENT_TOPIC, "org/blueberry/ui/help/CONTEXTHELP_REQUESTED");
context->registerService<ctkEventHandler>(helpContextHandler.data(), helpHandlerProps);
}
void
HelpPluginActivator::stop(ctkPluginContext* /*context*/)
{
delete pluginListener;
pluginListener = nullptr;
if (PlatformUI::IsWorkbenchRunning())
{
PlatformUI::GetWorkbench()->RemoveWindowListener(wndListener.data());
}
wndListener.reset();
helpEngineConfiguration.reset();
helpEngine.reset();
}
HelpPluginActivator *HelpPluginActivator::getInstance()
{
return instance;
}
QHelpEngineWrapper& HelpPluginActivator::getQHelpEngine()
{
return *helpEngine;
}
void HelpPluginActivator::linkActivated(IWorkbenchPage::Pointer page, const QUrl &link)
{
IEditorInput::Pointer input(new HelpEditorInput(link));
// see if an editor with the same input is already open
IEditorPart::Pointer reuseEditor = page->FindEditor(input);
if (reuseEditor)
{
// just activate it
page->Activate(reuseEditor);
}
else
{
// reuse the currently active editor, if it is a HelpEditor
reuseEditor = page->GetActiveEditor();
if (reuseEditor.IsNotNull() && page->GetReference(reuseEditor)->GetId() == HelpEditor::EDITOR_ID)
{
page->ReuseEditor(reuseEditor.Cast<IReusableEditor>(), input);
page->Activate(reuseEditor);
}
else
{
// get the last used HelpEditor instance
QList<IEditorReference::Pointer> editors =
page->FindEditors(IEditorInput::Pointer(nullptr), HelpEditor::EDITOR_ID, IWorkbenchPage::MATCH_ID);
if (editors.empty())
{
// no HelpEditor is currently open, create a new one
page->OpenEditor(input, HelpEditor::EDITOR_ID);
}
else
{
// reuse an existing editor
reuseEditor = editors.front()->GetEditor(false);
page->ReuseEditor(reuseEditor.Cast<IReusableEditor>(), input);
page->Activate(reuseEditor);
}
}
}
}
QCHPluginListener::QCHPluginListener(ctkPluginContext* context, QHelpEngine* helpEngine)
: delayRegistration(true), context(context), helpEngine(helpEngine)
{}
void QCHPluginListener::processPlugins()
{
QMutexLocker lock(&mutex);
processPlugins_unlocked();
}
void QCHPluginListener::pluginChanged(const ctkPluginEvent& event)
{
QMutexLocker lock(&mutex);
if (delayRegistration)
{
this->processPlugins_unlocked();
return;
}
/* Only should listen for RESOLVED and UNRESOLVED events.
*
* When a plugin is updated the Framework will publish an UNRESOLVED and
* then a RESOLVED event which should cause the plugin to be removed
* and then added back into the registry.
*
* When a plugin is uninstalled the Framework should publish an UNRESOLVED
* event and then an UNINSTALLED event so the plugin will have been removed
* by the UNRESOLVED event before the UNINSTALLED event is published.
*/
QSharedPointer<ctkPlugin> plugin = event.getPlugin();
switch (event.getType())
{
case ctkPluginEvent::RESOLVED :
addPlugin(plugin);
break;
case ctkPluginEvent::UNRESOLVED :
removePlugin(plugin);
break;
default:
break;
}
}
void QCHPluginListener::processPlugins_unlocked()
{
if (!delayRegistration) return;
foreach (QSharedPointer<ctkPlugin> plugin, context->getPlugins())
{
if (isPluginResolved(plugin))
addPlugin(plugin);
else
removePlugin(plugin);
}
delayRegistration = false;
}
bool QCHPluginListener::isPluginResolved(QSharedPointer<ctkPlugin> plugin)
{
return (plugin->getState() & (ctkPlugin::RESOLVED | ctkPlugin::ACTIVE | ctkPlugin::STARTING | ctkPlugin::STOPPING)) != 0;
}
void QCHPluginListener::removePlugin(QSharedPointer<ctkPlugin> plugin)
{
// bail out if system plugin
if (plugin->getPluginId() == 0) return;
QFileInfo qchDirInfo = context->getDataFile("qch_files/" + QString::number(plugin->getPluginId()));
if (qchDirInfo.exists())
{
QDir qchDir(qchDirInfo.absoluteFilePath());
QStringList qchEntries = qchDir.entryList(QStringList("*.qch"));
QStringList qchFiles;
foreach(QString qchEntry, qchEntries)
{
qchFiles << qchDir.absoluteFilePath(qchEntry);
}
// unregister the cached qch files
foreach(QString qchFile, qchFiles)
{
QString namespaceName = QHelpEngineCore::namespaceName(qchFile);
if (namespaceName.isEmpty())
{
BERRY_ERROR << "Could not get the namespace for qch file " << qchFile.toStdString();
continue;
}
else
{
if (!helpEngine->unregisterDocumentation(namespaceName))
{
BERRY_ERROR << "Unregistering qch namespace " << namespaceName.toStdString() << " failed: " << helpEngine->error().toStdString();
}
}
}
// clean the directory
foreach(QString qchEntry, qchEntries)
{
qchDir.remove(qchEntry);
}
}
}
void QCHPluginListener::addPlugin(QSharedPointer<ctkPlugin> plugin)
{
// bail out if system plugin
if (plugin->getPluginId() == 0) return;
QFileInfo qchDirInfo = context->getDataFile("qch_files/" + QString::number(plugin->getPluginId()));
QUrl location(plugin->getLocation());
QFileInfo pluginFileInfo(location.toLocalFile());
if (!qchDirInfo.exists() || qchDirInfo.lastModified() < pluginFileInfo.lastModified())
{
removePlugin(plugin);
if (!qchDirInfo.exists())
{
QDir().mkpath(qchDirInfo.absoluteFilePath());
}
QStringList localQCHFiles;
QStringList resourceList = plugin->findResources("/", "*.qch", true);
foreach(QString resource, resourceList)
{
QByteArray content = plugin->getResource(resource);
QFile localFile(qchDirInfo.absoluteFilePath() + "/" + resource.section('/', -1));
localFile.open(QIODevice::WriteOnly);
localFile.write(content);
localFile.close();
if (localFile.error() != QFile::NoError)
{
BERRY_WARN << "Error writing " << localFile.fileName().toStdString()
<< ": " << localFile.errorString().toStdString();
}
else
{
localQCHFiles << localFile.fileName();
}
}
foreach(QString qchFile, localQCHFiles)
{
if (!helpEngine->registerDocumentation(qchFile))
{
BERRY_ERROR << "Registering qch file " << qchFile.toStdString() << " failed: " << helpEngine->error().toStdString();
}
}
}
}
IPerspectiveListener::Events::Types HelpPerspectiveListener::GetPerspectiveEventTypes() const
{
return Events::OPENED | Events::CHANGED;
}
void HelpPerspectiveListener::PerspectiveOpened(const SmartPointer<IWorkbenchPage>& page, const IPerspectiveDescriptor::Pointer& perspective)
{
// if no help editor is opened, open one showing the home page
if (perspective->GetId() == HelpPerspective::ID &&
page->FindEditors(IEditorInput::Pointer(nullptr), HelpEditor::EDITOR_ID, IWorkbenchPage::MATCH_ID).empty())
{
IEditorInput::Pointer input(new HelpEditorInput());
page->OpenEditor(input, HelpEditor::EDITOR_ID);
}
}
void HelpPerspectiveListener::PerspectiveChanged(const SmartPointer<IWorkbenchPage>& page, const IPerspectiveDescriptor::Pointer& perspective, const QString &changeId)
{
if (perspective->GetId() == HelpPerspective::ID && changeId == IWorkbenchPage::CHANGE_RESET)
{
PerspectiveOpened(page, perspective);
}
}
HelpWindowListener::HelpWindowListener()
: perspListener(new HelpPerspectiveListener())
{
// Register perspective listener for already opened windows
typedef QList<IWorkbenchWindow::Pointer> WndVec;
WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows();
for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i)
{
(*i)->AddPerspectiveListener(perspListener.data());
}
}
HelpWindowListener::~HelpWindowListener()
{
if (!PlatformUI::IsWorkbenchRunning()) return;
typedef QList<IWorkbenchWindow::Pointer> WndVec;
WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows();
for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i)
{
(*i)->RemovePerspectiveListener(perspListener.data());
}
}
void HelpWindowListener::WindowClosed(const IWorkbenchWindow::Pointer& window)
{
window->RemovePerspectiveListener(perspListener.data());
}
void HelpWindowListener::WindowOpened(const IWorkbenchWindow::Pointer& window)
{
window->AddPerspectiveListener(perspListener.data());
}
void HelpContextHandler::handleEvent(const ctkEvent &event)
{
struct _runner : public Poco::Runnable
{
_runner(const ctkEvent& ev) : ev(ev) {}
void run() override
{
QUrl helpUrl;
if (ev.containsProperty("url"))
{
helpUrl = QUrl(ev.getProperty("url").toString());
}
else
{
helpUrl = contextUrl();
}
HelpPluginActivator::linkActivated(PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(),
helpUrl);
delete this;
}
QUrl contextUrl() const
{
berry::IWorkbench* currentWorkbench = berry::PlatformUI::GetWorkbench();
if (currentWorkbench)
{
berry::IWorkbenchWindow::Pointer currentWorkbenchWindow = currentWorkbench->GetActiveWorkbenchWindow();
if (currentWorkbenchWindow)
{
berry::IWorkbenchPage::Pointer currentPage = currentWorkbenchWindow->GetActivePage();
if (currentPage)
{
berry::IWorkbenchPart::Pointer currentPart = currentPage->GetActivePart();
if (currentPart)
{
QString pluginID = currentPart->GetSite()->GetPluginId();
QString viewID = currentPart->GetSite()->GetId();
QString loc = "qthelp://" + pluginID + "/bundle/%1.html";
QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine();
// Get view help page if available
QUrl contextUrl(loc.arg(viewID.replace(".", "_")));
QUrl url = helpEngine.findFile(contextUrl);
if (url.isValid()) return url;
else
{
BERRY_INFO << "Context help url invalid: " << contextUrl.toString().toStdString();
}
// If no view help exists get plugin help if available
QUrl pluginContextUrl(loc.arg(pluginID.replace(".", "_")));
url = helpEngine.findFile(pluginContextUrl);
if (url.isValid()) return url;
// Try to get the index.html file of the plug-in contributing the
// currently active part.
QUrl pluginIndexUrl(loc.arg("index"));
url = helpEngine.findFile(pluginIndexUrl);
if (url != pluginIndexUrl)
{
// Use the default page instead of another index.html
// (merged via the virtual folder property).
url = QUrl();
}
return url;
}
}
}
}
return QUrl();
}
ctkEvent ev;
};
// sync with GUI thread
Display::GetDefault()->AsyncExec(new _runner(event));
}
}
diff --git a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpSearchView.cpp b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpSearchView.cpp
index 5703479177..dc79c3c551 100644
--- a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpSearchView.cpp
+++ b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpSearchView.cpp
@@ -1,233 +1,233 @@
/*============================================================================
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 "berryHelpSearchView.h"
#include "berryHelpPluginActivator.h"
#include "berryQHelpEngineWrapper.h"
#include "berryHelpEditorInput.h"
#include "berryHelpEditor.h"
#include <QLayout>
#include <QMenu>
#include <QEvent>
#include <QMouseEvent>
#include <QMimeData>
#include <QTextBrowser>
#include <QClipboard>
#include <QHelpSearchQueryWidget>
#include <QHelpSearchResultWidget>
#include <QApplication>
namespace berry {
HelpSearchView::HelpSearchView()
: m_ZoomCount(0)
, m_Parent(nullptr)
, m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine())
, m_ResultWidget(nullptr)
, m_QueryWidget(nullptr)
{
}
HelpSearchView::~HelpSearchView()
{
// prevent deletion of the widget
m_ResultWidget->setParent(nullptr);
}
void HelpSearchView::CreateQtPartControl(QWidget* parent)
{
if (m_ResultWidget == nullptr)
{
m_Parent = parent;
auto vLayout = new QVBoxLayout(parent);
// This will be lead to strange behavior when using multiple instances of this view
// because the QHelpSearchResultWidget instance is shared. The new view will
// reparent the widget.
m_ResultWidget = m_SearchEngine->resultWidget();
m_QueryWidget = new QHelpSearchQueryWidget();
vLayout->addWidget(m_QueryWidget);
vLayout->addWidget(m_ResultWidget);
connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search()));
connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this,
SLOT(requestShowLink(QUrl)));
connect(m_SearchEngine, SIGNAL(searchingStarted()), this,
SLOT(searchingStarted()));
connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this,
SLOT(searchingFinished(int)));
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser) // Will be null if QtHelp was configured not to use CLucene.
{
browser->document()->setDefaultStyleSheet(QStringLiteral("body { background-color: white; }"));
browser->viewport()->installEventFilter(this);
browser->setContextMenuPolicy(Qt::CustomContextMenu);
connect(browser, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(showContextMenu(QPoint)));
}
}
}
void HelpSearchView::SetFocus()
{
if (!(m_ResultWidget->hasFocus()))
{
m_QueryWidget->setFocus();
}
}
void HelpSearchView::zoomIn()
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && m_ZoomCount != 10)
{
m_ZoomCount++;
browser->zoomIn();
}
}
void HelpSearchView::zoomOut()
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && m_ZoomCount != -5)
{
m_ZoomCount--;
browser->zoomOut();
}
}
void HelpSearchView::resetZoom()
{
if (m_ZoomCount == 0)
return;
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser)
{
browser->zoomOut(m_ZoomCount);
m_ZoomCount = 0;
}
}
void HelpSearchView::search() const
{
QList<QHelpSearchQuery> query = m_QueryWidget->query();
m_SearchEngine->search(query);
}
void HelpSearchView::searchingStarted()
{
m_Parent->setCursor(QCursor(Qt::WaitCursor));
}
void HelpSearchView::searchingFinished(int hits)
{
Q_UNUSED(hits)
m_Parent->unsetCursor();
//qApp->restoreOverrideCursor();
}
void HelpSearchView::requestShowLink(const QUrl &link)
{
HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link);
}
bool HelpSearchView::eventFilter(QObject* o, QEvent *e)
{
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (browser && o == browser->viewport()
&& e->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* me = static_cast<QMouseEvent*>(e);
QUrl link = m_ResultWidget->linkAt(me->pos());
if (!link.isEmpty() || link.isValid())
{
bool controlPressed = me->modifiers() & Qt::ControlModifier;
if((me->button() == Qt::LeftButton && controlPressed)
- || (me->button() == Qt::MidButton))
+ || (me->button() == Qt::MiddleButton))
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
}
}
return QObject::eventFilter(o,e);
}
void HelpSearchView::showContextMenu(const QPoint& point)
{
QMenu menu;
QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();
if (!browser)
return;
// QPoint point = browser->mapFromGlobal(pos);
// if (!browser->rect().contains(point, true))
// return;
QUrl link = browser->anchorAt(point);
QKeySequence keySeq(QKeySequence::Copy);
QAction *copyAction = menu.addAction(tr("&Copy") + QLatin1String("\t") +
keySeq.toString(QKeySequence::NativeText));
copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection());
QAction *copyAnchorAction = menu.addAction(tr("Copy &Link Location"));
copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid());
keySeq = QKeySequence(Qt::CTRL);
QAction *newTabAction = menu.addAction(tr("Open Link in New Tab") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText) +
QLatin1String("LMB"));
newTabAction->setEnabled(!link.isEmpty() && link.isValid());
menu.addSeparator();
keySeq = QKeySequence::SelectAll;
QAction *selectAllAction = menu.addAction(tr("Select All") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText));
QAction *usedAction = menu.exec(browser->mapToGlobal(point));
if (usedAction == copyAction)
{
QTextCursor cursor = browser->textCursor();
if (!cursor.isNull() && cursor.hasSelection())
{
QString selectedText = cursor.selectedText();
auto data = new QMimeData();
data->setText(selectedText);
QApplication::clipboard()->setMimeData(data);
}
}
else if (usedAction == copyAnchorAction)
{
QApplication::clipboard()->setText(link.toString());
}
else if (usedAction == newTabAction)
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
else if (usedAction == selectAllAction)
{
browser->selectAll();
}
}
}
diff --git a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpWebView.cpp b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpWebView.cpp
index 95f80daed9..1e81da25a5 100644
--- a/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpWebView.cpp
+++ b/Plugins/org.blueberry.ui.qt.help/src/internal/berryHelpWebView.cpp
@@ -1,450 +1,450 @@
/*============================================================================
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 "berryHelpWebView.h"
#include "berryHelpPluginActivator.h"
#include "berryHelpEditor.h"
#include "berryHelpEditorInput.h"
#include "berryQHelpEngineWrapper.h"
#include <berryIWorkbenchPage.h>
#include <QCoreApplication>
#include <QTimer>
#include <QStringBuilder>
#include <QTemporaryFile>
#include <QDesktopServices>
#include <QWheelEvent>
#include <QWebEngineSettings>
#include <QWebEngineUrlSchemeHandler>
#include <QWebEngineUrlRequestJob>
#include <QWebEngineProfile>
namespace berry {
struct ExtensionMap {
const char *extension;
const char *mimeType;
} extensionMap[] = {
{ ".bmp", "image/bmp" },
{ ".css", "text/css" },
{ ".gif", "image/gif" },
{ ".html", "text/html" },
{ ".htm", "text/html" },
{ ".ico", "image/x-icon" },
{ ".jpeg", "image/jpeg" },
{ ".jpg", "image/jpeg" },
{ ".js", "application/x-javascript" },
{ ".mng", "video/x-mng" },
{ ".pbm", "image/x-portable-bitmap" },
{ ".pgm", "image/x-portable-graymap" },
{ ".pdf", "application/pdf" },
{ ".png", "image/png" },
{ ".ppm", "image/x-portable-pixmap" },
{ ".rss", "application/rss+xml" },
{ ".svg", "image/svg+xml" },
{ ".svgz", "image/svg+xml" },
{ ".text", "text/plain" },
{ ".tif", "image/tiff" },
{ ".tiff", "image/tiff" },
{ ".txt", "text/plain" },
{ ".xbm", "image/x-xbitmap" },
{ ".xml", "text/xml" },
{ ".xpm", "image/x-xpm" },
{ ".xsl", "text/xsl" },
{ ".xhtml", "application/xhtml+xml" },
{ ".wml", "text/vnd.wap.wml" },
{ ".wmlc", "application/vnd.wap.wmlc" },
{ "about:blank", nullptr },
{ nullptr, nullptr }
};
class HelpDeviceReply final : public QIODevice
{
public:
HelpDeviceReply(const QUrl& request, const QByteArray& fileData);
~HelpDeviceReply() override;
qint64 bytesAvailable() const override;
void close() override;
private:
qint64 readData(char* data, qint64 maxlen) override;
qint64 writeData(const char* data, qint64 maxlen) override;
QByteArray m_Data;
const qint64 m_OrigLen;
};
HelpDeviceReply::HelpDeviceReply(const QUrl&, const QByteArray& fileData)
: m_Data(fileData),
m_OrigLen(fileData.length())
{
this->setOpenMode(QIODevice::ReadOnly);
QTimer::singleShot(0, this, &QIODevice::readyRead);
QTimer::singleShot(0, this, &QIODevice::readChannelFinished);
}
HelpDeviceReply::~HelpDeviceReply()
{
}
qint64 HelpDeviceReply::bytesAvailable() const
{
return m_Data.length() + QIODevice::bytesAvailable();
}
void HelpDeviceReply::close()
{
QIODevice::close();
this->deleteLater();
}
qint64 HelpDeviceReply::readData(char* data, qint64 maxlen)
{
qint64 len = qMin(qint64(m_Data.length()), maxlen);
if (len)
{
memcpy(data, m_Data.constData(), len);
m_Data.remove(0, len);
}
return len;
}
qint64 HelpDeviceReply::writeData(const char*, qint64)
{
return 0;
}
class HelpUrlSchemeHandler final : public QWebEngineUrlSchemeHandler
{
public:
explicit HelpUrlSchemeHandler(QObject* parent = nullptr);
~HelpUrlSchemeHandler() override;
void requestStarted(QWebEngineUrlRequestJob* job) override;
};
HelpUrlSchemeHandler::HelpUrlSchemeHandler(QObject* parent)
: QWebEngineUrlSchemeHandler(parent)
{
}
HelpUrlSchemeHandler::~HelpUrlSchemeHandler()
{
}
enum class ResolveUrlResult
{
Error,
Redirect,
Data
};
ResolveUrlResult ResolveUrl(const QUrl& url, QUrl& redirectedUrl, QByteArray& data)
{
auto& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine();
const auto targetUrl = helpEngine.findFile(url);
if (!targetUrl.isValid())
return ResolveUrlResult::Error;
if (targetUrl != url)
{
redirectedUrl = targetUrl;
return ResolveUrlResult::Redirect;
}
data = helpEngine.fileData(targetUrl);
return ResolveUrlResult::Data;
}
void HelpUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob* job)
{
QUrl url = job->requestUrl();
QUrl redirectedUrl;
QByteArray data;
switch (ResolveUrl(url, redirectedUrl, data))
{
case ResolveUrlResult::Data:
job->reply(
HelpWebView::mimeFromUrl(url).toLatin1(),
new HelpDeviceReply(url, data));
break;
case ResolveUrlResult::Redirect:
job->redirect(redirectedUrl);
break;
case ResolveUrlResult::Error:
job->reply(
QByteArrayLiteral("text/html"),
new HelpDeviceReply(url, HelpWebView::m_PageNotFoundMessage.arg(url.toString()).toUtf8()));
break;
}
}
const QString HelpWebView::m_PageNotFoundMessage =
QCoreApplication::translate("org.blueberry.ui.qt.help", "<title>Context Help</title><div "
"align=\"center\"><br><br><h1>No help page found for identifier</h1><br><h3>'%1'"
"</h3></div>");
const QString HelpWebView::m_MissingContextMessage =
QCoreApplication::translate("org.blueberry.ui.qt.help", "<title>Context Help</title><div "
"align=\"center\"><br><br><h1>Unknown context..</h1><h1>&nbsp;</h1><h1>Please click inside a view and hit F1 again!</h1></div>");
class HelpPage final : public QWebEnginePage
{
public:
explicit HelpPage(QObject* parent = nullptr);
~HelpPage() override;
private:
bool acceptNavigationRequest(const QUrl& url, NavigationType type, bool isMainFrame) override;
};
HelpPage::HelpPage(QObject* parent)
: QWebEnginePage(parent)
{
}
HelpPage::~HelpPage()
{
}
bool HelpPage::acceptNavigationRequest(const QUrl& url, NavigationType, bool)
{
if (url.scheme().contains("http"))
{
QDesktopServices::openUrl(url);
return false;
}
return true;
}
HelpWebView::HelpWebView(IEditorSite::Pointer, QWidget *parent, qreal zoom)
: QWebEngineView(parent),
m_LoadFinished(false),
m_HelpEngine(HelpPluginActivator::getInstance()->getQHelpEngine()),
m_HelpSchemeHandler(new HelpUrlSchemeHandler(this))
{
QWebEngineProfile::defaultProfile()->installUrlSchemeHandler("qthelp", m_HelpSchemeHandler);
auto helpPage = new HelpPage(this);
this->setPage(helpPage);
this->setAcceptDrops(false);
auto action = pageAction(QWebEnginePage::OpenLinkInNewWindow);
action->setText("Open Link in New Tab");
if (parent == nullptr)
action->setVisible(false);
this->pageAction(QWebEnginePage::DownloadLinkToDisk)->setVisible(false);
this->pageAction(QWebEnginePage::DownloadImageToDisk)->setVisible(false);
connect(pageAction(QWebEnginePage::Copy), SIGNAL(changed()), this, SLOT(actionChanged()));
connect(pageAction(QWebEnginePage::Back), SIGNAL(changed()), this, SLOT(actionChanged()));
connect(pageAction(QWebEnginePage::Forward), SIGNAL(changed()), this, SLOT(actionChanged()));
connect(page(), SIGNAL(linkHovered(QString)), this, SIGNAL(highlighted(QString)));
connect(this, SIGNAL(urlChanged(QUrl)), this, SIGNAL(sourceChanged(QUrl)));
connect(this, SIGNAL(loadStarted()), this, SLOT(setLoadStarted()));
connect(this, SIGNAL(loadFinished(bool)), this, SLOT(setLoadFinished(bool)));
this->setFont(this->viewerFont());
this->setZoomFactor(zoom == 0.0 ? 1.0 : zoom);
}
HelpWebView::~HelpWebView()
{
}
QFont HelpWebView::viewerFont() const
{
- QWebEngineSettings *webSettings = QWebEngineSettings::globalSettings();
+ QWebEngineSettings* webSettings = settings();
return QFont(webSettings->fontFamily(QWebEngineSettings::StandardFont),
webSettings->fontSize(QWebEngineSettings::DefaultFontSize));
}
void HelpWebView::setViewerFont(const QFont &font)
{
QWebEngineSettings *webSettings = settings();
webSettings->setFontFamily(QWebEngineSettings::StandardFont, font.family());
webSettings->setFontSize(QWebEngineSettings::DefaultFontSize, font.pointSize());
}
void HelpWebView::scaleUp()
{
setZoomFactor(zoomFactor() + 0.1);
}
void HelpWebView::scaleDown()
{
setZoomFactor(qMax(0.0, zoomFactor() - 0.1));
}
void HelpWebView::resetScale()
{
setZoomFactor(1.0);
}
bool HelpWebView::handleForwardBackwardMouseButtons(QMouseEvent *e)
{
if (e->button() == Qt::XButton1)
{
triggerPageAction(QWebEnginePage::Back);
return true;
}
if (e->button() == Qt::XButton2)
{
triggerPageAction(QWebEnginePage::Forward);
return true;
}
return false;
}
void HelpWebView::setSource(const QUrl &url)
{
if (url.toString().trimmed().isEmpty()) {
setHtml(m_MissingContextMessage);
}
else if (m_HelpEngine.findFile(url).isValid())
{
load(url);
}
else
{
setHtml(m_PageNotFoundMessage.arg(url.toString()));
}
}
void HelpWebView::wheelEvent(QWheelEvent *e)
{
if (e->modifiers()& Qt::ControlModifier)
{
e->accept();
- e->delta() > 0 ? scaleUp() : scaleDown();
+ e->angleDelta().y() > 0 ? scaleUp() : scaleDown();
}
else
{
QWebEngineView::wheelEvent(e);
}
}
void HelpWebView::actionChanged()
{
QAction *a = qobject_cast<QAction *>(sender());
if (a == pageAction(QWebEnginePage::Copy))
emit copyAvailable(a->isEnabled());
else if (a == pageAction(QWebEnginePage::Back))
emit backwardAvailable(a->isEnabled());
else if (a == pageAction(QWebEnginePage::Forward))
emit forwardAvailable(a->isEnabled());
}
void HelpWebView::setLoadStarted()
{
m_LoadFinished = false;
}
void HelpWebView::setLoadFinished(bool ok)
{
m_LoadFinished = ok;
emit sourceChanged(url());
}
QString HelpWebView::mimeFromUrl(const QUrl &url)
{
const QString &path = url.path();
const int index = path.lastIndexOf(QLatin1Char('.'));
const QByteArray &ext = path.mid(index).toUtf8().toLower();
const ExtensionMap *e = extensionMap;
while (e->extension)
{
if (ext == e->extension)
return QLatin1String(e->mimeType);
++e;
}
return QLatin1String("");
}
bool HelpWebView::canOpenPage(const QString &url)
{
return !mimeFromUrl(url).isEmpty();
}
bool HelpWebView::isLocalUrl(const QUrl &url)
{
const QString &scheme = url.scheme();
return scheme.isEmpty()
|| scheme == QLatin1String("file")
|| scheme == QLatin1String("qrc")
|| scheme == QLatin1String("data")
|| scheme == QLatin1String("qthelp")
|| scheme == QLatin1String("about");
}
bool HelpWebView::launchWithExternalApp(const QUrl &url)
{
if (isLocalUrl(url))
{
const QHelpEngine& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine();
const QUrl &resolvedUrl = helpEngine.findFile(url);
if (!resolvedUrl.isValid())
return false;
const QString& path = resolvedUrl.path();
if (!canOpenPage(path))
{
QTemporaryFile tmpTmpFile;
if (!tmpTmpFile.open())
return false;
const QString &extension = QFileInfo(path).completeSuffix();
QFile actualTmpFile(tmpTmpFile.fileName() % QLatin1String(".")
% extension);
if (!actualTmpFile.open(QIODevice::ReadWrite | QIODevice::Truncate))
return false;
actualTmpFile.write(helpEngine.fileData(resolvedUrl));
actualTmpFile.close();
return QDesktopServices::openUrl(QUrl(actualTmpFile.fileName()));
}
}
else if (url.scheme() == QLatin1String("http"))
{
return QDesktopServices::openUrl(url);
}
return false;
}
void HelpWebView::home()
{
setSource(m_HelpEngine.homePage());
}
}
diff --git a/Plugins/org.blueberry.ui.qt.log/CMakeLists.txt b/Plugins/org.blueberry.ui.qt.log/CMakeLists.txt
index f4dca98e14..29122e7f2f 100644
--- a/Plugins/org.blueberry.ui.qt.log/CMakeLists.txt
+++ b/Plugins/org.blueberry.ui.qt.log/CMakeLists.txt
@@ -1,7 +1,7 @@
project(org_blueberry_ui_qt_log)
mitk_create_plugin(
EXPORT_DIRECTIVE org_blueberry_ui_qt_log_EXPORT
EXPORTED_INCLUDE_SUFFIXES src
- PACKAGE_DEPENDS PUBLIC Qt5|Widgets
+ PACKAGE_DEPENDS PUBLIC Qt6|Widgets
)
diff --git a/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp b/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp
index d1960b8dd7..c3052f2719 100644
--- a/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp
+++ b/Plugins/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp
@@ -1,152 +1,153 @@
/*============================================================================
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 "berryQtLogView.h"
#include "berryQtLogPlugin.h"
#include <berryPlatform.h>
#include <berryPlatformUI.h>
#include <QHeaderView>
#include <QTimer>
#include <QClipboard>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
namespace berry {
QtLogView::QtLogView(QWidget *parent)
: QWidget(parent)
{
auto* prefService = berry::Platform::GetPreferencesService();
auto* prefs = prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log");
prefs->PutBool("ShowAdvancedFields", false);
prefs->PutBool("ShowCategory", true);
bool showAdvancedFields = false;
ui.setupUi(this);
model = QtLogPlugin::GetInstance()->GetLogModel();
model->SetShowAdvancedFiels( showAdvancedFields );
filterModel = new QSortFilterProxyModel(this);
filterModel->setSourceModel(model);
filterModel->setFilterKeyColumn(-1);
#ifdef __APPLE__
QFont fnt = ui.tableView->font();
fnt.setPointSize(11);
ui.tableView->setFont(fnt);
#endif
ui.tableView->setModel(filterModel);
ui.tableView->verticalHeader()->setVisible(false);
ui.tableView->horizontalHeader()->setStretchLastSection(true);
connect( ui.filterContent, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotFilterChange( const QString& ) ) );
connect( filterModel, SIGNAL( rowsInserted ( const QModelIndex &, int, int ) ), this, SLOT( slotRowAdded( const QModelIndex &, int , int ) ) );
connect( ui.SaveToClipboard, SIGNAL( clicked()),this, SLOT(on_SaveToClipboard_clicked()));
ui.ShowAdvancedFields->setChecked( showAdvancedFields );
ui.filterContent->setClearButtonEnabled(true);
}
QtLogView::~QtLogView()
{
}
void QtLogView::slotScrollDown( )
{
ui.tableView->scrollToBottom();
}
void QtLogView::slotFilterChange( const QString& q )
{
- filterModel->setFilterRegExp(QRegExp(q, Qt::CaseInsensitive, QRegExp::FixedString));
+ QRegularExpression regExp(QRegularExpression::escape(q), QRegularExpression::CaseInsensitiveOption);
+ filterModel->setFilterRegularExpression(regExp);
}
void QtLogView::slotRowAdded ( const QModelIndex & /*parent*/, int /*start*/, int /*end*/ )
{
ui.tableView->setVisible(false);
ui.tableView->resizeRowsToContents();
//only resize columns when first entry is added
static bool first = true;
if(first)
{
ui.tableView->resizeColumnsToContents();
first = false;
}
ui.tableView->setVisible(true);
QTimer::singleShot(0,this,SLOT( slotScrollDown() ) );
}
void QtLogView::showEvent( QShowEvent * /*event*/ )
{
ui.tableView->setVisible(false);
ui.tableView->resizeColumnsToContents();
ui.tableView->resizeRowsToContents();
ui.tableView->setVisible(true);
}
void QtLogView::on_ShowAdvancedFields_clicked( bool checked )
{
ui.tableView->setVisible(false);
QtLogPlugin::GetInstance()->GetLogModel()->SetShowAdvancedFiels( checked );
ui.tableView->resizeColumnsToContents();
ui.tableView->setVisible(true);
auto* prefService = berry::Platform::GetPreferencesService();
auto* prefs = prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log");
prefs->PutBool("ShowAdvancedFields", checked);
prefs->Flush();
}
void QtLogView::on_ShowCategory_clicked( bool checked )
{
ui.tableView->setVisible(false);
QtLogPlugin::GetInstance()->GetLogModel()->SetShowCategory( checked );
ui.tableView->resizeColumnsToContents();
ui.tableView->setVisible(true);
auto* prefService = berry::Platform::GetPreferencesService();
auto* prefs = prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log");
prefs->PutBool("ShowCategory", checked);
prefs->Flush();
}
void QtLogView::on_SaveToClipboard_clicked()
{
QClipboard *clipboard = QApplication::clipboard();
QString loggingMessagesAsText = QString("");
for (int i=0; i<ui.tableView->model()->rowCount(); i++)
{
for (int j=0; j<ui.tableView->model()->columnCount(); j++)
{
QModelIndex index = ui.tableView->model()->index(i, j);
loggingMessagesAsText += ui.tableView->model()->data(index, Qt::DisplayRole).toString() + " ";
}
loggingMessagesAsText += "\n";
}
clipboard->setText(loggingMessagesAsText);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/CMakeLists.txt b/Plugins/org.blueberry.ui.qt/CMakeLists.txt
index b675068ba7..fd7b5e3956 100644
--- a/Plugins/org.blueberry.ui.qt/CMakeLists.txt
+++ b/Plugins/org.blueberry.ui.qt/CMakeLists.txt
@@ -1,42 +1,42 @@
project(org_blueberry_ui_qt)
set(PLUGIN_exported_include_suffixes
src
src/actions
src/application
src/commands
src/guitk
src/handlers
src/intro
src/model
src/presentations
src/services
src/testing
src/tweaklets
src/util
)
-if(MITK_USE_Qt5)
+if(MITK_USE_Qt6)
set(PLUGIN_package_depends
- PUBLIC Qt5|Widgets+PrintSupport+Svg
+ PUBLIC Qt6|Widgets+PrintSupport+Svg
)
endif()
mitk_create_plugin(
EXPORT_DIRECTIVE BERRY_UI_QT
EXPORTED_INCLUDE_SUFFIXES ${PLUGIN_exported_include_suffixes}
MODULE_DEPENDS PUBLIC MitkCore
PACKAGE_DEPENDS ${PLUGIN_package_depends}
)
if (TARGET ${PLUGIN_TARGET} AND MSVC)
#[[ Compiler warnings/errors because of QList on Visual Studio 2022 version 17.8:
'stdext::checked_array_iterator<const T *>': warning STL4043: stdext::checked_array_iterator,
stdext::unchecked_array_iterator, and related factory functions are non-Standard extensions
and will be removed in the future. std::span (since C++20) and gsl::span can be used instead.
You can define _SILENCE_STDEXT_ARR_ITERS_DEPRECATION_WARNING or _SILENCE_ALL_MS_EXT_DEPRECATION_WARNINGS
to suppress this warning.
]]
target_compile_definitions(${PLUGIN_TARGET} PRIVATE _SILENCE_STDEXT_ARR_ITERS_DEPRECATION_WARNING)
endif()
diff --git a/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp b/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp
index 2b1d6a2d19..56426bdb85 100644
--- a/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp
@@ -1,726 +1,726 @@
/*============================================================================
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 "berryCommandContributionItem.h"
#include "berryIMenuService.h"
#include "berryICommandService.h"
#include "berryICommandImageService.h"
#include "berryIContributionManager.h"
#include "berryIElementReference.h"
#include "berryIElementUpdater.h"
#include "berryUIElement.h"
#include <berryICommandListener.h>
#include <berryIEvaluationContext.h>
#include <berryIHandler.h>
#include <berryCommand.h>
#include <berryCommandEvent.h>
#include <berryParameterizedCommand.h>
#include <berryCommandExceptions.h>
#include <berryCommandContributionItemParameter.h>
#include "../berryDisplay.h"
#include "../berryAsyncRunnable.h"
#include "../handlers/berryIHandlerService.h"
#include "../services/berryIServiceLocator.h"
#include "../berryWorkbenchPlugin.h"
#include <QMenu>
#include <QMenuBar>
#include <QToolBar>
#include <QApplication>
#include <QMetaMethod>
namespace berry
{
ContributionItem::Modes CommandContributionItem::modes = ContributionItem::MODE_FORCE_TEXT;
//class CommandUIElementListener : public IUIElementListener
//{
//private:
// CommandContributionItem* item;
// public:
// CommandUIElementListener(CommandContributionItem* item);
// void UIElementDisposed(UIElement* item);
//void UIElementSelected(SmartPointer<UIElement> item);
//};
CommandContributionItem::CommandContributionItem(
const SmartPointer<CommandContributionItemParameter>& contributionParameters)
: ContributionItem(contributionParameters->id)
, action(nullptr)
, checkedState(false)
{
this->icon = contributionParameters->icon;
this->label = contributionParameters->label;
this->mnemonic = contributionParameters->mnemonic;
this->shortcut = contributionParameters->shortcut;
this->tooltip = contributionParameters->tooltip;
this->style = contributionParameters->style;
this->helpContextId = contributionParameters->helpContextId;
this->visibleEnabled = contributionParameters->visibleEnabled;
this->mode = contributionParameters->mode;
menuService = contributionParameters->serviceLocator->GetService<IMenuService>();
commandService = contributionParameters->serviceLocator->GetService<ICommandService>();
handlerService = contributionParameters->serviceLocator->GetService<IHandlerService>();
// bindingService = (IBindingService) contributionParameters.serviceLocator
// .getService(IBindingService.class);
this->CreateCommand(contributionParameters->commandId,
contributionParameters->parameters);
if (command)
{
try
{
class CommandUIElement : public UIElement
{
private:
CommandContributionItem* item;
public:
CommandUIElement(CommandContributionItem* item, IServiceLocator* serviceLocator)
: UIElement(serviceLocator), item(item) {}
void SetText(const QString& text) override
{
item->SetText(text);
}
void SetToolTip(const QString& text) override
{
item->SetToolTip(text);
}
void SetIcon(const QIcon& icon) override
{
item->SetIcon(icon);
}
void SetChecked(bool checked) override
{
item->SetChecked(checked);
}
void SetDropDownId(const QString& id) override
{
item->dropDownMenuOverride = id;
}
};
UIElement::Pointer callback(new CommandUIElement(this,
contributionParameters->serviceLocator));
elementRef = commandService->RegisterElementForCommand(command, callback);
command->GetCommand()->AddCommandListener(this->GetCommandListener());
this->SetImages(contributionParameters->serviceLocator,
contributionParameters->iconStyle);
if (contributionParameters->helpContextId.isEmpty())
{
try
{
this->helpContextId = commandService->GetHelpContextId(
contributionParameters->commandId);
}
catch (const NotDefinedException& /*e*/)
{
// it's OK to not have a helpContextId
}
}
// IWorkbenchLocationService::Pointer wls = contributionParameters.serviceLocator
// ->GetService(IWorkbenchLocationService::GetManifestName()).Cast<IWorkbenchLocationService>();
// const IWorkbench* workbench = wls->GetWorkbench();;
// if (workbench != 0 && !helpContextId.empty()) {
// this->workbenchHelpSystem = workbench->GetHelpSystem();
// }
}
catch (const NotDefinedException& /*e*/)
{
WorkbenchPlugin::Log(QString("Unable to register menu item \"") + this->GetId()
+ "\", command \"" + contributionParameters->commandId
+ "\" not defined");
}
}
}
void CommandContributionItem::Fill(QMenu* parent, QAction* before)
{
if (!command || action || parent == nullptr)
{
return;
}
// Menus don't support the pulldown style
Style tmpStyle = style;
if (tmpStyle == STYLE_PULLDOWN)
tmpStyle = STYLE_PUSH;
QAction* item = nullptr;
if (before)
{
item = new QAction(icon, label, parent);
parent->insertAction(before, item);
}
else
{
item = parent->addAction(icon, label);
}
// Remove this when key binding support is fully implemented
if (!shortcut.isEmpty())
{
item->setShortcut(shortcut);
}
item->setData(QVariant::fromValue(Object::Pointer(this)));
item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this)));
// if (workbenchHelpSystem != null)
// {
// workbenchHelpSystem.setHelp(item, helpContextId);
// }
connect(item, SIGNAL(triggered()), SLOT(HandleWidgetSelection()));
connect(item, SIGNAL(destroyed()), SLOT(HandleActionDestroyed()));
action = item;
this->Update();
this->UpdateIcons();
//bindingService.addBindingManagerListener(bindingManagerListener);
}
void CommandContributionItem::Fill(QToolBar *parent, QAction *before)
{
if (!command || action || parent == nullptr)
{
return;
}
QAction* item = nullptr;
if (before)
{
item = parent->addAction(icon, label);
}
else
{
item = new QAction(icon, label, parent);
parent->insertAction(before, item);
}
item->setData(QVariant::fromValue(Object::Pointer(this)));
item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this)));
connect(item, SIGNAL(triggered()), SLOT(HandleWidgetSelection()));
connect(item, SIGNAL(destroyed()), SLOT(HandleActionDestroyed()));
action = item;
this->Update();
this->UpdateIcons();
//bindingService.addBindingManagerListener(bindingManagerListener);
}
void CommandContributionItem::Update()
{
- this->Update(QString::null);
+ this->Update(QString());
}
void CommandContributionItem::Update(const QString& /*id*/)
{
if (action)
{
- QWidget* parent = action->parentWidget();
+ auto parent = qobject_cast<QWidget*>(action->parent());
if(qobject_cast<QMenu*>(parent))
{
this->UpdateMenuItem();
}
else if (qobject_cast<QMenuBar*>(parent))
{
this->UpdateMenuItem();
}
else if (qobject_cast<QToolBar*>(parent))
{
this->UpdateToolItem();
}
}
}
void CommandContributionItem::UpdateMenuItem()
{
QString text = label;
if (text.isEmpty())
{
if (command.IsNotNull())
{
try
{
text = command->GetCommand()->GetName();
}
catch (const NotDefinedException& e)
{
// StatusManager.getManager().handle(
// StatusUtil.newStatus(IStatus.ERROR,
// "Update item failed "
// + getId(), e));
BERRY_ERROR << "Update item failed " << GetId() << e.what();
}
}
}
text = UpdateMnemonic(text);
// String keyBindingText = null;
// if (command != null)
// {
// TriggerSequence binding = bindingService
// .getBestActiveBindingFor(command);
// if (binding != null)
// {
// keyBindingText = binding.format();
// }
// }
// if (text != null)
// {
// if (keyBindingText == null)
// {
// item.setText(text);
// }
// else
// {
// item.setText(text + '\t' + keyBindingText);
// }
// }
if (action->isChecked() != checkedState)
{
action->setChecked(checkedState);
}
// allow the handler update its enablement
bool shouldBeEnabled = IsEnabled();
if (action->isEnabled() != shouldBeEnabled)
{
action->setEnabled(shouldBeEnabled);
}
}
void CommandContributionItem::UpdateToolItem()
{
QString text = label;
QString tooltip = label;
if (text.isNull())
{
if (command.IsNotNull())
{
try
{
text = command->GetCommand()->GetName();
tooltip = command->GetCommand()->GetDescription();
if (tooltip.trimmed().isEmpty())
{
tooltip = text;
}
}
catch (const NotDefinedException& e)
{
// StatusManager.getManager().handle(
// StatusUtil.newStatus(IStatus.ERROR,
// "Update item failed "
// + getId(), e));
BERRY_ERROR << "Update item failed " << GetId() << e.what();
}
}
}
if ((icon.isNull() || (mode & MODE_FORCE_TEXT) == MODE_FORCE_TEXT)
&& !text.isNull())
{
action->setText(text);
}
QString toolTipText = GetToolTipText(tooltip);
action->setToolTip(toolTipText);
if (action->isChecked() != checkedState)
{
action->setChecked(checkedState);
}
// allow the handler update its enablement
bool shouldBeEnabled = IsEnabled();
if (action->isEnabled() != shouldBeEnabled)
{
action->setEnabled(shouldBeEnabled);
}
}
CommandContributionItem::~CommandContributionItem()
{
if (elementRef)
{
commandService->UnregisterElement(elementRef);
}
if (commandListener)
{
command->GetCommand()->RemoveCommandListener(commandListener.data());
}
}
bool CommandContributionItem::IsEnabled() const
{
if (command)
{
command->GetCommand()->SetEnabled(menuService->GetCurrentState());
return command->GetCommand()->IsEnabled();
}
return false;
}
bool CommandContributionItem::IsVisible() const
{
if (visibleEnabled)
{
return ContributionItem::IsVisible() && this->IsEnabled();
}
return ContributionItem::IsVisible();
}
void CommandContributionItem::SetImages(IServiceLocator* locator,
const QString& iconStyle)
{
if (icon.isNull())
{
ICommandImageService* service = locator->GetService<ICommandImageService>();
if (service)
{
icon = service->GetImage(command->GetId(), iconStyle);
}
}
}
ICommandListener* CommandContributionItem::GetCommandListener()
{
if (!commandListener)
{
class MyCommandListener : public ICommandListener
{
private:
CommandContributionItem* item;
public:
MyCommandListener(CommandContributionItem* item)
: item(item)
{}
void CommandChanged(const SmartPointer<const CommandEvent>& commandEvent) override
{
if (commandEvent->IsHandledChanged() || commandEvent->IsEnabledChanged()
|| commandEvent->IsDefinedChanged())
{
item->UpdateCommandProperties(commandEvent);
}
}
};
commandListener.reset(new MyCommandListener(this));
}
return commandListener.data();
}
void CommandContributionItem::UpdateCommandProperties(const SmartPointer<
const CommandEvent> commandEvent)
{
if (commandEvent->IsHandledChanged())
{
dropDownMenuOverride = "";
}
if (!action)
{
return;
}
Display* display = Display::GetDefault();
typedef AsyncRunnable<SmartPointer<const CommandEvent>, CommandContributionItem > UpdateRunnable;
Poco::Runnable* update = new UpdateRunnable(this, &CommandContributionItem::UpdateCommandPropertiesInUI, commandEvent);
if (display->InDisplayThread())
{
update->run();
}
else
{
display->AsyncExec(update);
}
}
void CommandContributionItem::UpdateCommandPropertiesInUI(const SmartPointer<
const CommandEvent>& commandEvent)
{
if (commandEvent->GetCommand()->IsDefined())
{
this->Update();
}
if (commandEvent->IsEnabledChanged()
|| commandEvent->IsHandledChanged())
{
if (visibleEnabled)
{
IContributionManager* parent = this->GetParent();
if (parent)
{
parent->Update(true);
}
}
}
}
void CommandContributionItem::HandleActionDestroyed()
{
this->action = nullptr;
}
bool CommandContributionItem::ShouldRestoreAppearance(const SmartPointer<IHandler>& handler)
{
// if no handler or handler doesn't implement IElementUpdater,
// restore the contributed elements
if (handler.IsNull())
return true;
if (!(handler.Cast<IElementUpdater>()))
return true;
// special case, if its HandlerProxy, then check the actual handler
// if (handler instanceof HandlerProxy) {
// HandlerProxy handlerProxy = (HandlerProxy) handler;
// IHandler actualHandler = handlerProxy.getHandler();
// return shouldRestoreAppearance(actualHandler);
// }
return false;
}
SmartPointer<ParameterizedCommand> CommandContributionItem::GetCommand() const
{
return command;
}
void CommandContributionItem::CreateCommand(const QString &commandId,
const QHash<QString,Object::Pointer> &parameters)
{
if (commandId.isEmpty())
{
// StatusManager.getManager().handle(StatusUtil.newStatus(IStatus.ERROR,
// "Unable to create menu item \"" + getId()
// + "\", no command id", null));
BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString()
<< "\", no command id";
return;
}
Command::Pointer cmd = commandService->GetCommand(commandId);
if (!cmd->IsDefined())
{
// StatusManager.getManager().handle(StatusUtil.newStatus(
// IStatus.ERROR, "Unable to create menu item \"" + getId()
// + "\", command \"" + commandId + "\" not defined", null));
BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString()
<< "\", command \"" << commandId.toStdString() << "\" not defined";
return;
}
command = ParameterizedCommand::GenerateCommand(cmd, parameters);
}
QString CommandContributionItem::GetToolTipText(const QString& text) const
{
QString tooltipText = tooltip;
if (tooltip.isNull())
{
if (!text.isNull())
{
tooltipText = text;
}
else
{
tooltipText = "";
}
}
// TriggerSequence activeBinding = bindingService
// .getBestActiveBindingFor(command);
// if (activeBinding != null && !activeBinding.isEmpty())
// {
// String acceleratorText = activeBinding.format();
// if (acceleratorText != null
// && acceleratorText.length() != 0)
// {
// tooltipText = NLS.bind(CommandMessages.Tooltip_Accelerator,
// tooltipText, acceleratorText);
// }
// }
return tooltipText;
}
QString CommandContributionItem::UpdateMnemonic(const QString &s)
{
if (mnemonic.isNull() || s.isEmpty())
{
return s;
}
int idx = s.indexOf(mnemonic);
if (idx == -1)
{
return s;
}
return s.left(idx) + '&' + s.mid(idx);
}
//SmartPointer<IUIElementListener> CommandContributionItem::GetItemListener()
//{
// if (!itemListener)
// {
// itemListener = new CommandUIElementListener(this);
// }
// return itemListener;
//}
void CommandContributionItem::HandleWidgetSelection()
{
// // Special check for ToolBar dropdowns...
// if (this->OpenDropDownMenu(event))
// //return;
if ((style & STYLE_CHECK) != 0)
{
checkedState = action->isChecked();
}
try
{
handlerService->ExecuteCommand(command, UIElement::Pointer(nullptr));
}
catch (const ExecutionException& e)
{
WorkbenchPlugin::Log("Failed to execute item " + GetId(), e);
}
catch (const NotDefinedException& e)
{
WorkbenchPlugin::Log("Failed to execute item " + GetId(), e);
}
catch (const NotEnabledException& e)
{
WorkbenchPlugin::Log("Failed to execute item " + GetId(), e);
}
catch (const NotHandledException& e)
{
WorkbenchPlugin::Log("Failed to execute item " + GetId(), e);
}
}
//TODO Tool item drop down menu contributions
//bool CommandContributionItem::OpenDropDownMenu(SmartPointer<GuiTk::Event> event)
//{
//Widget item = event.widget;
//if (item != null)
//{
// int style = item.getStyle();
// if ((style & SWT.DROP_DOWN) != 0)
// {
// if (event.detail == 4)
// { // on drop-down button
// ToolItem ti = (ToolItem) item;
//
// final MenuManager menuManager = new MenuManager();
// Menu menu = menuManager.createContextMenu(ti.getParent());
// if (workbenchHelpSystem != null)
// {
// workbenchHelpSystem.setHelp(menu, helpContextId);
// }
// menuManager.addMenuListener(new IMenuListener()
// {
// public void menuAboutToShow(IMenuManager manager)
// {
// String id = getId();
// if (dropDownMenuOverride != null)
// {
// id = dropDownMenuOverride;
// }
// menuService.populateContributionManager(
// menuManager, "menu:" + id); //$NON-NLS-1$
// }
// });
//
// // position the menu below the drop down item
// Point point = ti.getParent().toDisplay(
// new Point(event.x, event.y));
// menu.setLocation(point.x, point.y); // waiting for SWT
// // 0.42
// menu.setVisible(true);
// return true; // we don't fire the action
// }
// }
//}
//
//return false;
//}
void CommandContributionItem::SetIcon(const QIcon &icon)
{
this->icon = icon;
this->UpdateIcons();
}
void CommandContributionItem::UpdateIcons()
{
action->setIcon(icon);
}
void CommandContributionItem::SetText(const QString &text)
{
label = text;
this->Update();
}
void CommandContributionItem::SetChecked(bool checked)
{
if (checkedState == checked)
{
return;
}
checkedState = checked;
action->setChecked(checkedState);
}
void CommandContributionItem::SetToolTip(const QString &text)
{
tooltip = text;
action->setToolTip(text);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/actions/berryMenuManager.h b/Plugins/org.blueberry.ui.qt/src/actions/berryMenuManager.h
index 4e84952186..d67618ba5a 100644
--- a/Plugins/org.blueberry.ui.qt/src/actions/berryMenuManager.h
+++ b/Plugins/org.blueberry.ui.qt/src/actions/berryMenuManager.h
@@ -1,403 +1,403 @@
/*============================================================================
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 BERRYMENUMANAGER_H_
#define BERRYMENUMANAGER_H_
#include "berryIMenuManager.h"
#include "berryContributionManager.h"
#include <org_blueberry_ui_qt_Export.h>
#include <QIcon>
class QMenu;
class QMenuProxy;
class QAction;
namespace berry
{
/**
* A menu manager is a contribution manager which realizes itself and its items
* in a menu control; either as a menu bar, a sub-menu, or a context menu.
* <p>
* This class may be instantiated; it may also be subclassed.
* </p>
*/
class BERRY_UI_QT MenuManager: public QObject, public ContributionManager, public IMenuManager
{
Q_OBJECT
public:
berryObjectMacro(MenuManager);
private:
/**
* The menu id.
*/
QString id;
/**
* The menu control; <code>null</code> before
* creation and after disposal.
*/
QMenuProxy* menu;
QAction* menuItem;
/**
* The menu item widget; <code>null</code> before
* creation and after disposal. This field is used
* when this menu manager is a sub-menu.
*/
//SmartPointer<IMenuItem> menuItem;
/**
* The text for a sub-menu.
*/
QString menuText;
/**
* The image for a sub-menu.
*/
QIcon image;
/**
* The overrides for items of this manager
*/
SmartPointer<IContributionManagerOverrides> overrides;
/**
* The parent contribution manager.
*/
IContributionManager* parent;
/**
* Indicates whether <code>removeAll</code> should be
* called just before the menu is displayed.
*/
bool removeAllWhenShown;
/**
* allows a submenu to display a shortcut key. This is often used with the
* QuickMenu command or action which can pop up a menu using the shortcut.
*/
QString definitionId;
private:
Q_SLOT void HandleAboutToShow();
Q_SLOT void HandleAboutToHide();
protected:
/**
* Indicates this item is visible in its manager; <code>true</code>
* by default.
*/
bool visible;
public:
Q_SIGNAL void AboutToShow(IMenuManager* mm);
Q_SIGNAL void AboutToHide(IMenuManager* mm);
/**
* Creates a menu manager with the given text and id.
* Typically no text is given when creating a context menu.
* Supply a text and id for creating a sub-menu, where it needs to be referred to by the id.
*
* @param text the text for the menu, or <code>""</code> if none
* @param id the menu id, or <code>""</code> if it is to have no id
*/
- MenuManager(const QString& text = QString(), const QString& id = QString());
+ MenuManager(const QString& text, const QString& id = QString());
~MenuManager() override;
/**
* Creates a menu manager with the given text, image, and id.
* Typically used for creating a sub-menu, where it needs to be referred to by id.
*
* @param text the text for the menu, or <code>""</code> if none
* @param image the image for the menu, or <code>ImageDescriptor::Pointer(0)</code> if none
* @param id the menu id, or <code>""</code> if it is to have no id
*/
MenuManager(const QString& text, const QIcon& image,
const QString& id);
bool IsDirty() const override;
/**
* Creates and returns a Qt menu control for this menu,
* and installs all registered contributions.
* Does not create a new control if one already exists.
* <p>
* Note that the menu is not expected to be dynamic.
* </p>
*
* @param parent the parent control
* @return the menu control
*/
QMenu* CreateContextMenu(QWidget* parent);
/**
* Creates and returns a Qt menu bar control for this menu,
* for use in the given <code>QWidget</code>, and installs all registered
* contributions. Does not create a new control if one already exists.
*
* @param parent the parent decorations
* @return the menu control
* @since 2.1
*/
QMenuBar* CreateMenuBar(QWidget* parent);
void AddMenuListener(QObject* listener) override;
void RemoveMenuListener(QObject *listener) override;
/*
* @see IContributionItem#Fill(QStatusBar*)
*/
void Fill(QStatusBar* parent) override;
/*
* @see IContributionItem#Fill(QToolBar*, int)
*/
void Fill(QToolBar* parent, QAction *index) override;
/*
* @see IContributionItem#Fill(QMenu*, int)
*/
void Fill(QMenu* parent, QAction *before) override;
/*
* @see IContributionItem#Fill(QMenuBar*, int)
*/
void Fill(QMenuBar* parent, QAction *before) override;
/*
* @see IMenuManager#FindMenuUsingPath(const QString&)
*/
IMenuManager::Pointer FindMenuUsingPath(const QString& path) const override;
/*
* @see IMenuManager#FindUsingPath(const QString&)
*/
IContributionItem::Pointer FindUsingPath(const QString& path) const override;
/**
* Returns the menu id. The menu id is used when creating a contribution
* item for adding this menu as a sub menu of another.
*
* @return the menu id
*/
QString GetId() const override;
/**
* Returns the SWT menu control for this menu manager.
*
* @return the menu control
*/
QMenu* GetMenu() const;
/**
* Returns the text shown in the menu, potentially with a shortcut
* appended.
*
* @return the menu text
*/
QString GetMenuText() const;
/**
* Returns the image for this menu as an image descriptor.
*
* @return the image, or <code>null</code> if this menu has no image
*/
QIcon GetImage() const;
/*
* @see IContributionManager#GetOverrides()
*/
SmartPointer<IContributionManagerOverrides> GetOverrides() override;
/**
* Returns the parent contribution manager of this manager.
*
* @return the parent contribution manager
*/
IContributionManager* GetParent() const;
/*
* @see IMenuManager#GetRemoveAllWhenShown()
*/
bool GetRemoveAllWhenShown() const override;
/*
* @see IContributionItem#IsDynamic()
*/
bool IsDynamic() const override;
/**
* Returns whether this menu should be enabled or not.
* Used to enable the menu item containing this menu when it is realized as a sub-menu.
* <p>
* The default implementation of this framework method
* returns <code>true</code>. Subclasses may reimplement.
* </p>
*
* @return <code>true</code> if enabled, and
* <code>false</code> if disabled
*/
bool IsEnabled() const override;
/*
* @see IContributionItem#IsGroupMarker()
*/
bool IsGroupMarker() const override;
/*
* @see IContributionItem#IsSeparator()
*/
bool IsSeparator() const override;
/*
* @see IContributionItem#IsVisible()
*/
bool IsVisible() const override;
/**
* The <code>MenuManager</code> implementation of this <code>ContributionManager</code> method
* also propagates the dirty flag up the parent chain.
*/
void MarkDirty() override;
/*
* @see IMenuManager#removeMenuListener(IMenuListener)
*/
//void RemoveMenuListener(SmartPointer<IMenuListener> listener);
/*
* @IContributionItem#SaveWidgetState()
*/
void SaveWidgetState() override;
/**
* Sets the overrides for this contribution manager
*
* @param newOverrides the overrides for the items of this manager
*/
void SetOverrides(SmartPointer<IContributionManagerOverrides> newOverrides);
/*
* @see IContributionItem#SetParent(IContributionManager)
*/
void SetParent(IContributionManager* manager) override;
/*
* @see IMenuManager#SetRemoveAllWhenShown(boolean)
*/
void SetRemoveAllWhenShown(bool removeAll) override;
/*
* @see IContributionItem#SetVisible(bool)
*/
void SetVisible(bool visible) override;
/**
* Sets the command id of this action. This simply allows the menu
* item text to include a short cut if available. It can be used to
* notify a user of a key combination that will open a quick menu.
*
* @param definitionId
* the command definition id
*/
void SetCommandId(const QString& definitionId);
/*
* @see IContributionItem#Update()
*/
void Update() override;
void Update(const QString& property) override;
/**
* The <code>MenuManager</code> implementation of this <code>IContributionManager</code>
* updates this menu, but not any of its submenus.
*
* @see #UpdateAll
*/
void Update(bool force) override;
/*
* @see IMenuManager#UpdateAll(bool)
*/
void UpdateAll(bool force) override;
private:
/**
* Initializes the menu control.
*/
void InitializeMenu();
/**
* Dispose any images allocated for this menu
*/
// void DisposeOldImages();
/**
* Updates the menu item for this sub menu.
* The menu item is disabled if this sub menu is empty.
* Does nothing if this menu is not a submenu.
*/
void UpdateMenuItem();
void FillMenu(QWidget* parent, QAction* before);
void DumpActionInfo(QMenuProxy* menu);
void DumpActionInfo(QWidget* widget, int level);
protected:
/**
* Call an <code>IContributionItem</code>'s fill method with the
* implementation's widget. The default is to use the <code>Menu</code>
* widget.<br>
* <code>fill(Menu menu, int index)</code>
*
* @param ci
* An <code>IContributionItem</code> whose <code>fill()</code>
* method should be called.
* @param before
* The position the <code>fill()</code> method should start
* inserting at.
*/
void DoItemFill(IContributionItem::Pointer ci, QAction *before);
/**
* Incrementally builds the menu from the contribution items.
* This method leaves out double separators and separators in the first
* or last position.
*
* @param force <code>true</code> means update even if not dirty,
* and <code>false</code> for normal incremental updating
* @param recursive <code>true</code> means recursively update
* all submenus, and <code>false</code> means just this menu
*/
void Update(bool force, bool recursive);
};
}
#endif /* BERRYMENUMANAGER_H_ */
diff --git a/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.h b/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.h
index 7135b29cf2..5e65da9603 100644
--- a/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.h
+++ b/Plugins/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.h
@@ -1,262 +1,264 @@
/*============================================================================
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 BERRYWORKBENCHWINDOWADVISOR_H_
#define BERRYWORKBENCHWINDOWADVISOR_H_
#include <berrySmartPointer.h>
#include <org_blueberry_ui_qt_Export.h>
+class QWidget;
+
namespace berry
{
struct IActionBarConfigurer;
struct IMemento;
struct IWorkbenchWindowConfigurer;
class ActionBarAdvisor;
class Shell;
/**
* Public base class for configuring a workbench window.
* <p>
* The workbench window advisor object is created in response to a workbench
* window being created (one per window), and is used to configure the window.
* </p>
* <p>
* An application should declare a subclass of <code>WorkbenchWindowAdvisor</code>
* and override methods to configure workbench windows to suit the needs of the
* particular application.
* </p>
* <p>
* The following advisor methods are called at strategic points in the
* workbench window's lifecycle (as with the workbench advisor, all occur
* within the dynamic scope of the call to
* <code>PlatformUI#CreateAndRunWorkbench()</code>):
* <ul>
* <li>PreWindowOpen() - called as the window is being opened;
* use to configure aspects of the window other than actions bars</li>
* <li>PostWindowRestore() - called after the window has been
* recreated from a previously saved state; use to adjust the restored
* window</li>
* <li>PostWindowCreate() - called after the window has been created,
* either from an initial state or from a restored state; used to adjust the
* window</li>
* <li>OpenIntro() - called immediately before the window is opened in
* order to create the introduction component, if any.</li>
* <li>PostWindowOpen() - called after the window has been
* opened; use to hook window listeners, etc.</li>
* <li>PreWindowShellClose() - called when the window's shell
* is closed by the user; use to pre-screen window closings</li>
* </ul>
* </p>
*
*/
class BERRY_UI_QT WorkbenchWindowAdvisor
{
private:
SmartPointer<IWorkbenchWindowConfigurer> windowConfigurer;
protected:
/**
* Returns the workbench window configurer.
*
* @return the workbench window configurer
*/
SmartPointer<IWorkbenchWindowConfigurer> GetWindowConfigurer();
public:
/**
* Creates a new workbench window advisor for configuring a workbench
* window via the given workbench window configurer.
*
* @param configurer an object for configuring the workbench window
*/
WorkbenchWindowAdvisor(const SmartPointer<IWorkbenchWindowConfigurer>& configurer);
virtual ~WorkbenchWindowAdvisor();
/**
* Performs arbitrary actions before the window is opened.
* <p>
* This method is called before the window's controls have been created.
* Clients must not call this method directly (although super calls are okay).
* The default implementation does nothing. Subclasses may override.
* Typical clients will use the window configurer to tweak the
* workbench window in an application-specific way; however, filling the
* window's menu bar, tool bar, and status line must be done in
* <code>ActionBarAdvisor#FillActionBars()</code>, which is called immediately
* after this method is called.
* </p>
*/
virtual void PreWindowOpen();
/**
* Creates a new action bar advisor to configure the action bars of the window
* via the given action bar configurer.
* The default implementation returns a new instance of <code>ActionBarAdvisor</code>.
*
* @param configurer the action bar configurer for the window
* @return the action bar advisor for the window
*/
virtual SmartPointer<ActionBarAdvisor> CreateActionBarAdvisor(
SmartPointer<IActionBarConfigurer> configurer);
/**
* Performs arbitrary actions after the window has been restored,
* but before it is opened.
* <p>
* This method is called after a previously-saved window has been
* recreated. This method is not called when a new window is created from
* scratch. This method is never called when a workbench is started for the
* very first time, or when workbench state is not saved or restored.
* Clients must not call this method directly (although super calls are okay).
* The default implementation does nothing. Subclasses may override.
* It is okay to call <code>IWorkbench#Close()</code> from this method.
* </p>
*
* @exception WorkbenchException thrown if there are any errors to report
* from post-restoration of the window
*/
virtual void PostWindowRestore();
/**
* Opens the introduction component.
* <p>
* Clients must not call this method directly (although super calls are okay).
* The default implementation opens the intro in the first window provided
* if the preference <code>WorkbenchPreferenceConstants#SHOW_INTRO</code> is <code>true</code>. If
* an intro is shown then this preference will be set to <code>false</code>.
* Subsequently, and intro will be shown only if
* <code>WorkbenchConfigurer#GetSaveAndRestore()</code> returns
* <code>true</code> and the introduction was visible on last shutdown.
* Subclasses may override.
* </p>
*/
virtual void OpenIntro();
/**
* Performs arbitrary actions after the window has been created (possibly
* after being restored), but has not yet been opened.
* <p>
* This method is called after the window has been created from scratch,
* or when it has been restored from a previously-saved window. In the latter case,
* this method is called after <code>PostWindowRestore()</code>.
* Clients must not call this method directly (although super calls are okay).
* The default implementation does nothing. Subclasses may override.
* </p>
*/
virtual void PostWindowCreate();
/**
* Performs arbitrary actions after the window has been opened (possibly
* after being restored).
* <p>
* This method is called after the window has been opened. This method is
* called after the window has been created from scratch, or when
* it has been restored from a previously-saved window.
* Clients must not call this method directly (although super calls are okay).
* The default implementation does nothing. Subclasses may override.
* </p>
*/
virtual void PostWindowOpen();
/**
* Performs arbitrary actions as the window's shell is being closed
* directly, and possibly veto the close.
* <p>
* This method is called from a <code>IShellListener</code> associated with the window,
* for example when the user clicks the window's close button. It is not
* called when the window is being closed for other reasons, such as if the
* user exits the workbench via the <code>ActionFactory#QUIT</code> action.
* Clients must not call this method directly (although super calls are
* okay). If this method returns <code>false</code>, then the user's
* request to close the shell is ignored. This gives the workbench advisor
* an opportunity to query the user and/or veto the closing of a window
* under some circumstances.
* </p>
*
* @return <code>true</code> to allow the window to close, and
* <code>false</code> to prevent the window from closing
* @see IWorkbenchWindow#Close()
* @see WorkbenchAdvisor#PreShutdown()
*/
virtual bool PreWindowShellClose();
/**
* Performs arbitrary actions after the window is closed.
* <p>
* This method is called after the window's controls have been disposed.
* Clients must not call this method directly (although super calls are
* okay). The default implementation does nothing. Subclasses may override.
* </p>
*/
virtual void PostWindowClose();
/**
* Creates the contents of the window.
* <p>
* The default implementation adds a menu bar, a cool bar, a status line,
* a perspective bar, and a fast view bar. The visibility of these controls
* can be configured using the <code>SetShow*</code> methods on
* IWorkbenchWindowConfigurer.
* </p>
* <p>
* Subclasses may override to define custom window contents and layout,
* but must call <code>IWorkbenchWindowConfigurer#CreatePageComposite()</code>.
* </p>
*
* @param shell the window's shell
* @see IWorkbenchWindowConfigurer#CreateMenuBar()
* @see IWorkbenchWindowConfigurer#CreateCoolBarControl()
* @see IWorkbenchWindowConfigurer#CreateStatusLineControl()
* @see IWorkbenchWindowConfigurer#CreatePageComposite()
*/
virtual void CreateWindowContents(SmartPointer<Shell> shell);
/**
* Creates and returns the control to be shown when the window has no open pages.
* If <code>null</code> is returned, the default window background is shown.
* <p>
* The default implementation returns <code>null</code>.
* Subclasses may override.
* </p>
*
* @param parent the parent composite
* @return the control or <code>null</code>
*/
virtual QWidget* CreateEmptyWindowContents(QWidget* parent);
/**
* Saves arbitrary application specific state information.
*
* @param memento the storage area for object's state
* @return a status object indicating whether the save was successful
*/
virtual bool SaveState(SmartPointer<IMemento> memento);
/**
* Restores arbitrary application specific state information.
*
* @param memento the storage area for object's state
* @return a status object indicating whether the restore was successful
*/
virtual bool RestoreState(SmartPointer<IMemento> memento);
};
}
#endif /*BERRYWORKBENCHWINDOWADVISOR_H_*/
diff --git a/Plugins/org.blueberry.ui.qt/src/berryIElementFactory.h b/Plugins/org.blueberry.ui.qt/src/berryIElementFactory.h
index 4105bba7fd..4435cee61e 100644
--- a/Plugins/org.blueberry.ui.qt/src/berryIElementFactory.h
+++ b/Plugins/org.blueberry.ui.qt/src/berryIElementFactory.h
@@ -1,71 +1,72 @@
/*============================================================================
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 BERRYIELEMENTFACTORY_H
#define BERRYIELEMENTFACTORY_H
#include <org_blueberry_ui_qt_Export.h>
#include <berrySmartPointer.h>
+#include <QtPlugin>
namespace berry {
struct IAdaptable;
struct IMemento;
/**
* A factory for re-creating objects from a previously saved memento.
* <p>
* Clients should implement this interface and include the name of their class
* in an extension to the platform extension point named
* <code>"org.blueberry.ui.elementFactories"</code>.
* For example, the plug-in's XML markup might contain:
* \code{.unparsed}
* <extension point="org.blueberry.ui.elementFactories">
* <factory id="com.example.myplugin.MyFactory" class="MyFactory" />
* </extension>
* \endcode
* </p>
*
* @see IPersistableElement
* @see IMemento
* @see IWorkbench#GetElementFactory
*/
struct BERRY_UI_QT IElementFactory
{
virtual ~IElementFactory();
/**
* Re-creates and returns an object from the state captured within the given
* memento.
* <p>
* If the result is not null, it should be persistable; that is,
* <pre>
* result.getAdapter(org.eclipse.ui.IPersistableElement.class)
* </pre>
* should not return <code>null</code>. The caller takes ownership of the
* result and must delete it when it is not needed any more.
* </p>
*
* @param memento
* a memento containing the state for the object
* @return an object, or <code>nullptr</code> if the element could not be
* created
*/
virtual IAdaptable* CreateElement(const SmartPointer<IMemento>& memento) = 0;
};
}
Q_DECLARE_INTERFACE(berry::IElementFactory, "org.blueberry.ui.IElementFactory")
#endif // BERRYIELEMENTFACTORY_H
diff --git a/Plugins/org.blueberry.ui.qt/src/berryQtStyleManager.cpp b/Plugins/org.blueberry.ui.qt/src/berryQtStyleManager.cpp
index 2bf59d3112..04692dc19c 100644
--- a/Plugins/org.blueberry.ui.qt/src/berryQtStyleManager.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/berryQtStyleManager.cpp
@@ -1,399 +1,399 @@
/*============================================================================
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 "berryQtStyleManager.h"
#include <QApplication>
#include <QFile>
#include <QTextStream>
#include <QFileInfo>
#include <QRegularExpression>
#include <QStringList>
#include <QDirIterator>
#include <QFont>
#include <QFontDatabase>
#include <QIcon>
#include <berryLog.h>
#include <berryPlatformUI.h>
#include <berryQtPreferences.h>
#include "berryWorkbenchPlugin.h"
#include <mitkIPreferences.h>
namespace berry
{
static QString ParseColor(const QString &subject, const QString &pattern, const QString &fallback)
{
QRegularExpression re(pattern, QRegularExpression::CaseInsensitiveOption);
auto match = re.match(subject);
return match.hasMatch()
? match.captured(1)
: fallback;
}
QIcon QtStyleManager::ThemeIcon(const QByteArray &originalSVG)
{
auto styleSheet = qApp->styleSheet();
if (styleSheet.isEmpty())
return QPixmap::fromImage(QImage::fromData(originalSVG));
auto iconColor = ParseColor(styleSheet,
QStringLiteral("iconColor\\s*[=:]\\s*(#[0-9a-f]{6})"),
QStringLiteral("#000000"));
auto iconAccentColor = ParseColor(styleSheet,
QStringLiteral("iconAccentColor\\s*[=:]\\s*(#[0-9a-f]{6})"),
QStringLiteral("#ffffff"));
auto themedSVG = QString(originalSVG).replace(QStringLiteral("#00ff00"), iconColor, Qt::CaseInsensitive);
themedSVG = themedSVG.replace(QStringLiteral("#ff00ff"), iconAccentColor, Qt::CaseInsensitive);
return QPixmap::fromImage(QImage::fromData(themedSVG.toLatin1()));
}
QIcon QtStyleManager::ThemeIcon(const QString &resourcePath)
{
QFile resourceFile(resourcePath);
if (resourceFile.open(QIODevice::ReadOnly))
{
auto originalSVG = resourceFile.readAll();
return ThemeIcon(originalSVG);
}
BERRY_WARN << "Could not read " << resourcePath;
return QIcon();
}
QtStyleManager::QtStyleManager()
{
AddDefaultStyle();
AddDefaultFonts();
ReadPreferences();
}
void QtStyleManager::ReadPreferences()
{
auto* stylePref = WorkbenchPlugin::GetDefault()->GetPreferences()->Node(QtPreferences::QT_STYLES_NODE);
QString paths = QString::fromStdString(stylePref->Get(QtPreferences::QT_STYLE_SEARCHPATHS, ""));
- QStringList pathList = paths.split(";", QString::SkipEmptyParts);
+ QStringList pathList = paths.split(";", Qt::SkipEmptyParts);
QStringListIterator it(pathList);
while (it.hasNext())
{
AddStyles(it.next());
}
QString styleName = QString::fromStdString(stylePref->Get(QtPreferences::QT_STYLE_NAME, ""));
// if a style is contributed via the Qt resource mechanism, it may not be
// registered yet.
if (Contains(styleName))
SetStyle(styleName);
else
SetDefaultStyle();
}
QtStyleManager::~QtStyleManager()
{
for (FileNameToStyleMap::const_iterator i = styles.begin(); i != styles.end(); ++i)
{
delete i.value();
}
}
void QtStyleManager::AddDefaultStyle()
{
#ifndef _APPLE_
AddStyle(":/org.blueberry.ui.qt/darkstyle.qss", "Dark");
AddStyle(":/org.blueberry.ui.qt/lightstyle.qss", "Light");
defaultStyle = styles[":/org.blueberry.ui.qt/darkstyle.qss"];
#endif
}
void QtStyleManager::AddDefaultFonts()
{
m_customFontNames.append(QString("<<system>>"));
m_customFontNames.append(QString("Fira Sans"));
QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/FiraSans/FiraSans.ttf");
m_customFontNames.append(QString("Light Fira Sans"));
QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/LightFiraSans/LightFiraSans.ttf");
m_customFontNames.append(QString("Roboto"));
QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/Roboto/Roboto.ttf");
m_customFontNames.push_back(QString("Open Sans"));
QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/OpenSans/OpenSans-Regular.ttf");
m_customFontNames.push_back(QString("xkcd"));
QFontDatabase::addApplicationFont(":/org.blueberry.ui.qt/fonts/xkcd/xkcd.ttf");
}
void QtStyleManager::ClearStyles()
{
for (FileNameToStyleMap::iterator i = styles.begin(); i != styles.end(); )
{
if (!i.value()->fileName.startsWith(':'))
{
delete i.value();
i = styles.erase(i);
}
else ++i;
}
SetDefaultStyle();
}
QtStyleManager::Style QtStyleManager::GetStyle() const
{
return Style(currentStyle->name, currentStyle->fileName);
}
QString QtStyleManager::GetStylesheet() const
{
return currentStyle->stylesheet;
}
QString QtStyleManager::GetActiveTabStylesheet() const
{
return currentStyle->activeTabStylesheet;
}
QString QtStyleManager::GetTabStylesheet() const
{
return currentStyle->tabStylesheet;
}
void QtStyleManager::AddStyle(const QString& styleFileName,
const QString& styleName)
{
auto newStyle = new ExtStyle();
if (styleName.isEmpty())
{
QFileInfo info(styleFileName);
newStyle->name = info.completeBaseName();
}
else
{
newStyle->name = styleName;
}
newStyle->fileName = styleFileName;
styles.insert(newStyle->fileName, newStyle);
}
void QtStyleManager::GetFonts(QStringList& fontNames) const
{
fontNames = m_customFontNames;
}
QString QtStyleManager::GetFont() const
{
return m_currentFont;
}
void QtStyleManager::AddStyles(const QString& path)
{
QDirIterator dirIt(path);
while (dirIt.hasNext())
{
QString current = dirIt.next();
QFileInfo info = dirIt.fileInfo();
if (info.isFile() && info.isReadable())
{
QString fileName = info.fileName();
if (fileName.endsWith("-tab.qss") || fileName.endsWith("-activetab.qss"))
continue;
if (fileName.endsWith(".qss"))
AddStyle(current);
}
}
}
void QtStyleManager::ReadStyleData(ExtStyle* style)
{
QString tabStyleFileName(style->fileName);
QString activeTabStyleFileName(style->fileName);
int index = style->fileName.lastIndexOf(".qss");
tabStyleFileName.replace(index, 4, "-tab.qss");
activeTabStyleFileName.replace(index, 4, "-activetab.qss");
QFile styleFile(style->fileName);
if (styleFile.open(QIODevice::ReadOnly))
{
QTextStream in(&styleFile);
style->stylesheet = in.readAll();
}
else
{
BERRY_WARN << "Could not read " << style->fileName.toStdString();
}
QFile tabStyleFile(tabStyleFileName);
if (tabStyleFile.open(QIODevice::ReadOnly))
{
QTextStream in(&tabStyleFile);
style->tabStylesheet = in.readAll();
}
else
{
BERRY_WARN << "Could not read " << tabStyleFileName.toStdString();
}
QFile activeTabStyleFile(activeTabStyleFileName);
if (activeTabStyleFile.open(QIODevice::ReadOnly))
{
QTextStream in(&activeTabStyleFile);
style->activeTabStylesheet = in.readAll();
}
else
{
BERRY_WARN << "Could not read " << activeTabStyleFileName.toStdString();
}
}
void QtStyleManager::RemoveStyle(const QString& styleFileName)
{
if (currentStyle->fileName == styleFileName)
{
SetDefaultStyle();
}
delete styles.take(styleFileName);
}
void QtStyleManager::RemoveStyles(const QString& repo)
{
if (repo.isEmpty())
{
ClearStyles();
return;
}
for (FileNameToStyleMap::iterator i = styles.begin(); i != styles.end();)
{
ExtStyle* style = i.value();
QFileInfo info(style->fileName);
if (info.absolutePath() == repo)
{
if (style->name == currentStyle->name)
{
SetDefaultStyle();
}
i = styles.erase(i);
delete style;
}
else
{
++i;
}
}
}
void QtStyleManager::GetStyles(StyleList& styleNames) const
{
for (FileNameToStyleMap::const_iterator i = styles.begin(); i != styles.end(); ++i)
styleNames.push_back(Style(i.value()->name, i.value()->fileName));
}
void QtStyleManager::SetStyle(const QString& fileName)
{
if (fileName.isEmpty())
{
SetDefaultStyle();
return;
}
FileNameToStyleMap::const_iterator i = styles.find(fileName);
ExtStyle* style = nullptr;
if (i == styles.end())
{
BERRY_WARN << "Style " + fileName.toStdString() << " does not exist";
style = defaultStyle;
}
else
{
style = i.value();
}
currentStyle = style;
ReadStyleData(style);
qApp->setStyleSheet(currentStyle->stylesheet);
try
{
PlatformUI::GetWorkbench()->UpdateTheme();
}
catch (...)
{
// Swallow any exception if the Workbench instance has not been created yet.
// Will be called later again but for now we just want to make sure that the
// application style sheet can be at least already retrieved from qApp to
// theme icons in plugins with eager activation policy.
}
}
void QtStyleManager::SetFont(const QString& fontName)
{
m_currentFont = fontName;
}
void QtStyleManager::SetFontSize(const int fontSize)
{
m_currentFontSize = fontSize;
}
void QtStyleManager::UpdateWorkbenchFont()
{
if( m_currentFont == QString( "<<system>>" ) || m_currentFont == QString( "" ))
{
qApp->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));
}
else
{
QFont font;
font.setFamily(m_currentFont);
font.setPointSize(m_currentFontSize);
qApp->setFont(font);
}
qApp->setStyleSheet(currentStyle->stylesheet);
PlatformUI::GetWorkbench()->UpdateTheme();
}
QtStyleManager::Style QtStyleManager::GetDefaultStyle() const
{
return Style(defaultStyle->name, defaultStyle->fileName);
}
void QtStyleManager::SetDefaultStyle()
{
SetStyle(defaultStyle->fileName);
}
bool QtStyleManager::Contains(const QString& fileName) const
{
return styles.contains(fileName);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/berryWindow.cpp b/Plugins/org.blueberry.ui.qt/src/berryWindow.cpp
index 0e1381b7ee..d840b77cf3 100644
--- a/Plugins/org.blueberry.ui.qt/src/berryWindow.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/berryWindow.cpp
@@ -1,572 +1,572 @@
/*============================================================================
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 "tweaklets/berryGuiWidgetsTweaklet.h"
#include "berryWindow.h"
#include "berryConstants.h"
#include "berrySameShellProvider.h"
#include "berryMenuManager.h"
#include <QMainWindow>
namespace berry
{
const int Window::OK = 0;
const int Window::CANCEL = 1;
QList<QIcon> Window::defaultImages = QList<QIcon>();
Window::IExceptionHandler::Pointer Window::exceptionHandler(new DefaultExceptionHandler());
IShellProvider::Pointer Window::defaultModalParent(new DefaultModalParent());
Window::WindowShellListener::WindowShellListener(Window* wnd)
: window(wnd)
{
}
void Window::WindowShellListener::ShellClosed(const ShellEvent::Pointer& event)
{
event->doit = false; // don't close now
if (window->CanHandleShellCloseEvent())
{
window->HandleShellCloseEvent();
}
}
void Window::DefaultExceptionHandler::HandleException(const std::exception& t)
{
// Try to keep running.
std::cerr << t.what();
}
Shell::Pointer Window::DefaultModalParent::GetShell() const
{
Shell::Pointer parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetActiveShell();
// Make sure we don't pick a parent that has a modal child (this can lock the app)
if (parent == 0)
{
// If this is a top-level window, then there must not be any open modal windows.
parent = Window::GetModalChild(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShells());
}
else
{
// If we picked a parent with a modal child, use the modal child instead
Shell::Pointer modalChild = Window::GetModalChild(parent->GetShells());
if (modalChild != 0)
{
parent = modalChild;
}
}
return parent;
}
Shell::Pointer Window::GetModalChild(const QList<Shell::Pointer>& toSearch)
{
int modal = Constants::APPLICATION_MODAL | Constants::SYSTEM_MODAL | Constants::PRIMARY_MODAL;
int size = toSearch.size();
for (int i = size - 1; i < size; i--)
{
Shell::Pointer shell = toSearch[i];
// Check if this shell has a modal child
QList<Shell::Pointer> children = shell->GetShells();
Shell::Pointer modalChild = GetModalChild(children);
if (modalChild != 0)
{
return modalChild;
}
// If not, check if this shell is modal itself
if (shell->IsVisible() && (shell->GetStyle() & modal) != 0)
{
return shell;
}
}
return Shell::Pointer(nullptr);
}
//void Window::RunEventLoop()
//{
//
// //Use the display provided by the shell if possible
// Display display;
// if (shell == null)
// {
// display = Display.getCurrent();
// }
// else
// {
// display = loopShell.getDisplay();
// }
//
// while (loopShell != null && !loopShell.isDisposed())
// {
// try
// {
// if (!display.readAndDispatch())
// {
// display.sleep();
// }
// } catch (Throwable e)
// {
// exceptionHandler.handleException(e);
// }
// }
// display.update();
//}
Window::Window(Shell::Pointer parentShell)
{
this->parentShell = new SameShellProvider(parentShell);
this->Init();
}
Window::Window(IShellProvider::Pointer shellProvider)
{
poco_assert(shellProvider != 0);
this->parentShell = shellProvider;
this->Init();
}
Window::~Window()
{
}
void Window::Init()
{
this->shellStyle = Constants::SHELL_TRIM;
this->returnCode = OK;
this->block = false;
}
bool Window::CanHandleShellCloseEvent()
{
return true;
}
void Window::ConfigureShell(Shell::Pointer newShell)
{
// The single image version of this code had a comment related to bug
// 46624,
// and some code that did nothing if the stored image was already
// disposed.
// The equivalent in the multi-image version seems to be to remove the
// disposed images from the array passed to the shell.
if (defaultImages.size() > 0)
{
// ArrayList nonDisposedImages = new ArrayList(defaultImages.length);
// for (int i = 0; i < defaultImages.length; ++i)
// {
// if (defaultImages[i] != null && !defaultImages[i].isDisposed())
// {
// nonDisposedImages.add(defaultImages[i]);
// }
// }
//
// if (nonDisposedImages.size() <= 0)
// {
// System.err.println("Window.configureShell: images disposed"); //$NON-NLS-1$
// }
// else
// {
// //Image[] array = new Image[nonDisposedImages.size()];
// nonDisposedImages.toArray(array);
newShell->SetImages(defaultImages);
// }
}
// Layout layout = getLayout();
// if (layout != null)
// {
// newShell.setLayout(layout);
// }
CreateTrimWidgets(newShell);
}
//voidWindow::ConstrainShellSize()
//{
// // limit the shell size to the display size
// QRect bounds = shell.getBounds();
// QRect constrained = getConstrainedShellBounds(bounds);
// if (!bounds.equals(constrained))
// {
// shell.setBounds(constrained);
// }
//}
QWidget* Window::CreateContents(Shell::Pointer parent)
{
// by default, just create a composite
//return new Composite(parent, SWT.NONE);
return parent->GetControl();
}
Shell::Pointer Window::CreateShell()
{
Shell::Pointer newParent = this->GetParentShell();
// if (newParent != 0 && newParent.isDisposed())
// {
// parentShell = new SameShellProvider(null);
// newParent = getParentShell();//Find a better parent
// }
//Create the shell
Shell::Pointer newShell = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateShell(newParent, this->GetShellStyle());
// resizeListener = new Listener() {
// public void handleEvent(Event e) {
// resizeHasOccurred = true;
// }
// };
//newShell.addListener(SWT.Resize, resizeListener);
newShell->SetData(Object::Pointer(this));
//Add a listener
newShell->AddShellListener(this->GetShellListener());
//Set the layout
this->ConfigureShell(newShell);
// //Register for font changes
// if (fontChangeListener == null)
// {
// fontChangeListener = new FontChangeListener();
// }
// JFaceResources.getFontRegistry().addListener(fontChangeListener);
return newShell;
}
QWidget* Window::GetContents()
{
return contents;
}
QPoint Window::GetInitialLocation(const QPoint& initialSize)
{
QWidget* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(shell->GetControl());
QPoint centerPoint(0,0);
QRect parentBounds(0,0,0,0);
if (parent != nullptr)
{
parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(parent);
centerPoint.setX(parentBounds.x() + parentBounds.width()/2);
centerPoint.setY(parentBounds.y() - parentBounds.height()/2);
}
else
{
parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)
->GetScreenSize(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetPrimaryScreenNumber());
centerPoint.setX(parentBounds.width()/2);
centerPoint.setY(parentBounds.height()/2);
}
return QPoint(centerPoint.x() - initialSize.x() / 2, centerPoint.y() - initialSize.y() / 2);
}
QPoint Window::GetInitialSize()
{
return shell->ComputeSize(Constants::DEFAULT, Constants::DEFAULT, true);
}
Shell::Pointer Window::GetParentShell()
{
Shell::Pointer parent = parentShell->GetShell();
int modal = Constants::APPLICATION_MODAL | Constants::SYSTEM_MODAL | Constants::PRIMARY_MODAL;
if ((this->GetShellStyle() & modal) != 0)
{
// If this is a modal shell with no parent, pick a shell using defaultModalParent.
if (parent == 0)
{
parent = defaultModalParent->GetShell();
}
}
return parent;
}
IShellListener* Window::GetShellListener()
{
if (windowShellListener.isNull())
windowShellListener.reset(new WindowShellListener(this));
return windowShellListener.data();
}
int Window::GetShellStyle()
{
return shellStyle;
}
void Window::HandleShellCloseEvent()
{
this->SetReturnCode(CANCEL);
this->Close();
}
void Window::InitializeBounds()
{
// if (resizeListener != null)
// {
// shell.removeListener(SWT.Resize, resizeListener);
// }
// if (resizeHasOccurred)
// { // Check if shell size has been set already.
// return;
// }
QPoint size = this->GetInitialSize();
QPoint location = this->GetInitialLocation(size);
shell->SetBounds(this->GetConstrainedShellBounds(QRect(location.x(), location.y(), size.x(), size.y())));
}
QRect Window::GetConstrainedShellBounds(const QRect& preferredSize)
{
QRect result(preferredSize);
GuiWidgetsTweaklet* guiTweaklet(Tweaklets::Get(GuiWidgetsTweaklet::KEY));
int screenNum = guiTweaklet->GetClosestScreenNumber(result);
QRect bounds(guiTweaklet->GetAvailableScreenSize(screenNum));
if (result.height() > bounds.height()) {
result.setHeight(bounds.height());
}
if (result.width() > bounds.width()) {
result.setWidth(bounds.width());
}
result.moveLeft( std::max<int>(bounds.x(), std::min<int>(result.x(), bounds.x()
+ bounds.width() - result.width())));
result.moveTop(std::max<int>(bounds.y(), std::min<int>(result.y(), bounds.y()
+ bounds.height() - result.height())));
return result;
}
void Window::SetParentShell(Shell::Pointer newParentShell)
{
poco_assert(shell == 0); // "There must not be an existing shell."; //$NON-NLS-1$
parentShell = new SameShellProvider(newParentShell);
}
void Window::SetReturnCode(int code)
{
returnCode = code;
}
void Window::SetShellStyle(int newShellStyle)
{
shellStyle = newShellStyle;
}
void Window::AddMenuBar()
{
if (GetShell().IsNull() && menuBarManager.IsNull())
{
menuBarManager = CreateMenuManager();
}
}
SmartPointer<MenuManager> Window::CreateMenuManager()
{
- MenuManager::Pointer manager(new MenuManager());
+ MenuManager::Pointer manager(new MenuManager(""));
return manager;
}
void Window::CreateTrimWidgets(SmartPointer<Shell> shell)
{
if (menuBarManager.IsNotNull())
{
QMainWindow* mw = qobject_cast<QMainWindow*>(shell->GetControl());
if (mw)
{
mw->setMenuBar(menuBarManager->CreateMenuBar(shell->GetControl()));
menuBarManager->UpdateAll(true);
}
}
// if (showTopSeperator())
// {
// seperator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
// }
//CreateToolBarControl(shell);
//CreateStatusLine(shell);
}
bool Window::Close()
{
// BERRY_INFO << "Window::Close()";
// // stop listening for font changes
// if (fontChangeListener != null)
// {
// JFaceResources.getFontRegistry().removeListener(fontChangeListener);
// fontChangeListener = null;
// }
// remove this window from a window manager if it has one
if (windowManager != nullptr)
{
windowManager->Remove(Window::Pointer(this));
windowManager = nullptr;
}
if (shell == 0)
{
return true;
}
shell->RemoveShellListener(this->GetShellListener());
shell->SetData(Object::Pointer(nullptr));
// If we "close" the shell recursion will occur.
// Instead, we need to "dispose" the shell to remove it from the
// display.
Tweaklets::Get(GuiWidgetsTweaklet::KEY)->DisposeShell(shell);
shell = nullptr;
contents = nullptr;
return true;
}
void Window::Create()
{
shell = this->CreateShell();
contents = this->CreateContents(shell);
//initialize the bounds of the shell to that appropriate for the
// contents
this->InitializeBounds();
}
QIcon Window::GetDefaultImage()
{
return (defaultImages.size() < 1) ? QIcon() : defaultImages[0];
}
QList<QIcon> Window::GetDefaultImages()
{
return defaultImages;
}
int Window::GetReturnCode()
{
return returnCode;
}
Shell::Pointer Window::GetShell() const
{
return shell;
}
WindowManager* Window::GetWindowManager()
{
return windowManager;
}
MenuManager *Window::GetMenuBarManager() const
{
return menuBarManager.GetPointer();
}
int Window::Open()
{
if (shell == 0)
{
// create the window
this->Create();
}
// limit the shell size to the display size
//constrainShellSize();
// open the window
shell->Open(block);
// // run the event loop if specified
// if (block)
// {
// this->RunEventLoop();
// }
return returnCode;
}
void Window::SetBlockOnOpen(bool shouldBlock)
{
block = shouldBlock;
}
void Window::SetDefaultImage(const QIcon& image)
{
if (!image.isNull())
defaultImages.push_back(image);
}
void Window::SetDefaultImages(const QList<QIcon>& images)
{
defaultImages = images;
}
void Window::SetWindowManager(WindowManager* manager)
{
windowManager = manager;
// Code to detect invalid usage
if (manager != nullptr)
{
QList<Window::Pointer> windows = manager->GetWindows();
for (int i = 0; i < windows.size(); i++)
{
if (windows[i] == this)
{
return;
}
}
manager->Add(Window::Pointer(this));
}
}
void Window::SetExceptionHandler(IExceptionHandler::Pointer handler)
{
if (exceptionHandler == 0)
{
exceptionHandler = handler;
}
}
void Window::SetDefaultModalParent(IShellProvider::Pointer provider)
{
defaultModalParent = provider;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.cpp b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.cpp
index 9dd5a5913f..b6a02d2bc9 100644
--- a/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/berryWorkbenchPlugin.cpp
@@ -1,473 +1,473 @@
/*============================================================================
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 "berryLog.h"
#include "berryWorkbenchPlugin.h"
#include "internal/berryWorkbenchRegistryConstants.h"
#include "internal/berryWorkbench.h"
#include "berryPlatform.h"
#include "internal/intro/berryEditorIntroAdapterPart.h"
#include "internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h"
#include "berryQtStyleManager.h"
#include "berryExtensionFactory.h"
#include "internal/berryQtWorkbenchTweaklet.h"
#include "internal/berryQtWorkbenchPageTweaklet.h"
#include "internal/berryQtWidgetsTweaklet.h"
#include "internal/dialogs/berryPerspectivesPreferencePage.h"
#include "internal/berryQtStylePreferencePage.h"
#include "internal/berryStatusUtil.h"
#include "internal/berryHandlerServiceFactory.h"
#include "internal/berryMenuServiceFactory.h"
#include "internal/berryCommandServiceFactory.h"
#include "internal/berryWorkbenchSourceProvider.h"
#include "berryObjectString.h"
#include "berryObjects.h"
#include "internal/berryPolicy.h"
#include "internal/berryHandlerAuthority.h"
#include "internal/berryOpenPerspectivePropertyTester.h"
#include "internal/berryPerspectiveParameterValues.h"
#include "internal/handlers/berryCloseAllPerspectivesHandler.h"
#include "internal/handlers/berryClosePerspectiveHandler.h"
#include "internal/handlers/berryDynamicHelpHandler.h"
#include "internal/handlers/berryHelpContentsHandler.h"
#include "internal/handlers/berryIntroHandler.h"
#include "internal/handlers/berryOpenInNewWindowHandler.h"
#include "internal/handlers/berryNewEditorHandler.h"
#include "internal/handlers/berryQuitHandler.h"
#include "internal/handlers/berryResetPerspectiveHandler.h"
#include "internal/handlers/berrySavePerspectiveHandler.h"
#include "internal/handlers/berryShowPerspectiveHandler.h"
#include "internal/handlers/berryShowViewHandler.h"
#include "berryIQtStyleManager.h"
#include "berryIContributor.h"
#include "berryILog.h"
#include "berryIElementFactory.h"
#include "berryIExtension.h"
#include <QDebug>
#include <QPrinterInfo>
#include <QSvgGenerator>
namespace berry
{
bool WorkbenchPlugin::DEBUG = false;
char WorkbenchPlugin::PREFERENCE_PAGE_CATEGORY_SEPARATOR = '/';
WorkbenchPlugin* WorkbenchPlugin::inst = nullptr;
WorkbenchPlugin::WorkbenchPlugin()
: AbstractUICTKPlugin()
{
inst = this;
presentationFactory = nullptr;
editorRegistry = nullptr;
viewRegistry = nullptr;
perspRegistry = nullptr;
introRegistry = nullptr;
}
WorkbenchPlugin::~WorkbenchPlugin()
{
delete presentationFactory;
delete editorRegistry;
delete viewRegistry;
delete perspRegistry;
delete introRegistry;
inst = nullptr;
}
bool WorkbenchPlugin::HasExecutableExtension(
const IConfigurationElement::Pointer& element, const QString& extensionName)
{
if (!element->GetAttribute(extensionName).isNull()) return true;
QString elementText = element->GetValue();
if (!elementText.isEmpty()) return true;
QList<IConfigurationElement::Pointer> children(element->GetChildren(extensionName));
if (children.size() == 1)
{
if (!(children[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS).isNull()))
return true;
}
return false;
}
bool WorkbenchPlugin::IsBundleLoadedForExecutableExtension(
const IConfigurationElement::Pointer& element, const QString& extensionName)
{
QSharedPointer<ctkPlugin> plugin = WorkbenchPlugin::GetBundleForExecutableExtension(element, extensionName);
if (plugin.isNull())
return true;
return plugin->getState() == ctkPlugin::ACTIVE;
}
QSharedPointer<ctkPlugin> WorkbenchPlugin::GetBundleForExecutableExtension(
const IConfigurationElement::Pointer& element, const QString& extensionName)
{
// this code is derived heavily from
// ConfigurationElement.createExecutableExtension.
QString prop;
QString executable;
QString contributorName;
int i = 0;
if (!extensionName.isNull())
prop = element->GetAttribute(extensionName);
else
{
// property not specified, try as element value
prop = element->GetValue();
if (!prop.isNull())
{
prop = prop.trimmed();
if (prop.isEmpty())
prop = QString();
}
}
if (prop.isNull())
{
// property not defined, try as a child element
QList<IConfigurationElement::Pointer> exec(element->GetChildren(extensionName));
if (!exec.isEmpty())
contributorName = exec[0]->GetAttribute("plugin");
}
else
{
// simple property or element value, parse it into its components
i = prop.indexOf(':');
if (i != -1)
executable = prop.left(i).trimmed();
else
executable = prop;
i = executable.indexOf('/');
if (i != -1)
contributorName = executable.left(i).trimmed();
}
if (contributorName.isNull())
contributorName = element->GetContributor()->GetName();
return Platform::GetPlugin(contributorName);
}
WorkbenchPlugin* WorkbenchPlugin::GetDefault()
{
return inst;
}
std::size_t WorkbenchPlugin::GetBundleCount()
{
// TODO BundleContext GetBundles
//return bundleContext->GetBundles().size();
return 0;
}
IPerspectiveRegistry* WorkbenchPlugin::GetPerspectiveRegistry()
{
if (perspRegistry == nullptr)
{
perspRegistry = new PerspectiveRegistry();
// the load methods can touch on WorkbenchImages if an image is
// missing so we need to wrap the call in
// a startup block for the case where a custom descriptor exists on
// startup that does not have an image
// associated with it. See bug 196352.
//StartupThreading.runWithoutExceptions(new StartupRunnable() {
// public void runWithException() throws Throwable {
perspRegistry->Load();
// }
//});
}
return perspRegistry;
}
// PreferenceManager getPreferenceManager() {
// if (preferenceManager == null) {
// preferenceManager = new WorkbenchPreferenceManager(
// PREFERENCE_PAGE_CATEGORY_SEPARATOR);
//
// //Get the pages from the registry
// PreferencePageRegistryReader registryReader = new PreferencePageRegistryReader(
// getWorkbench());
// registryReader
// .loadFromRegistry(Platform.getExtensionRegistry());
// preferenceManager.addPages(registryReader.getTopLevelNodes());
//
// }
// return preferenceManager;
// }
IIntroRegistry* WorkbenchPlugin::GetIntroRegistry()
{
if (introRegistry == nullptr)
{
introRegistry = new IntroRegistry();
}
return introRegistry;
}
IViewRegistry* WorkbenchPlugin::GetViewRegistry()
{
if (!viewRegistry)
viewRegistry = new ViewRegistry();
return viewRegistry;
}
IEditorRegistry* WorkbenchPlugin::GetEditorRegistry()
{
if (!editorRegistry)
editorRegistry = new EditorRegistry();
return editorRegistry;
}
IElementFactory* WorkbenchPlugin::GetElementFactory(const QString& targetID) const
{
// Get the extension point registry.
IExtensionPoint::Pointer extensionPoint = Platform::GetExtensionRegistry()->GetExtensionPoint(
PlatformUI::PLUGIN_ID(),
WorkbenchRegistryConstants::PL_ELEMENT_FACTORY);
IElementFactory* factory = nullptr;
if (!extensionPoint)
{
WorkbenchPlugin::Log("Unable to find element factory. Extension point: " +
WorkbenchRegistryConstants::PL_ELEMENT_FACTORY + " not found");
return factory;
}
// Loop through the config elements.
IConfigurationElement::Pointer targetElement;
QList<IConfigurationElement::Pointer> configElements =
extensionPoint->GetConfigurationElements();
for (int j = 0; j < configElements.size(); j++)
{
QString strID = configElements[j]->GetAttribute("id");
if (targetID == strID)
{
targetElement = configElements[j];
break;
}
}
if (!targetElement)
{
// log it since we cannot safely display a dialog.
WorkbenchPlugin::Log("Unable to find element factory: " + targetID);
return factory;
}
// Create the extension.
try
{
factory = targetElement->CreateExecutableExtension<IElementFactory>("class");
}
catch (const CoreException& e)
{
// log it since we cannot safely display a dialog.
WorkbenchPlugin::Log("Unable to create element factory.", e.GetStatus());
factory = nullptr;
}
return factory;
}
IPresentationFactory* WorkbenchPlugin::GetPresentationFactory() {
if (presentationFactory != nullptr) return presentationFactory;
QString targetID = Workbench::GetInstance()->GetPresentationId();
presentationFactory = this->CreateExtension<IPresentationFactory>(
WorkbenchRegistryConstants::PL_PRESENTATION_FACTORIES,
"factory", targetID);
if (presentationFactory == nullptr)
WorkbenchPlugin::Log("Error creating presentation factory: " +
targetID + " -- class is not an IPresentationFactory");
return presentationFactory;
}
void WorkbenchPlugin::Log(const QString& message)
{
BERRY_INFO << "LOG: " << message << std::endl;
//inst->GetLog().log(message);
}
void WorkbenchPlugin::Log(const ctkException &exc)
{
QString str;
QDebug dbg(&str);
dbg << exc.printStackTrace();
BERRY_INFO << "LOG: " << str << std::endl;
//inst->GetLog().log(exc);
}
void WorkbenchPlugin::Log(const QString& message, const ctkException &t)
{
PlatformException exc(message, t);
WorkbenchPlugin::Log(exc);
}
void WorkbenchPlugin::Log(const QString& clazz,
const QString& methodName, const ctkException &t)
{
QString msg = QString("Exception in ") + clazz + "." + methodName + ": "
+ t.what();
WorkbenchPlugin::Log(msg, t);
}
void WorkbenchPlugin::Log(const QString& message, const SmartPointer<IStatus>& status)
{
//1FTUHE0: ITPCORE:ALL - API - Status & logging - loss of semantic info
if (!message.isEmpty())
{
GetDefault()->GetLog()->Log(StatusUtil::NewStatus(IStatus::ERROR_TYPE, message, BERRY_STATUS_LOC));
}
GetDefault()->GetLog()->Log(status);
}
void WorkbenchPlugin::Log(const SmartPointer<IStatus>& status)
{
GetDefault()->GetLog()->Log(status);
}
void WorkbenchPlugin::start(ctkPluginContext* context)
{
- // Dummy code to force linkage to Qt5PrintSupport (issue with GCC 7.3)
- QPrinterInfo forceQt5PrintSupportLinkage;
- forceQt5PrintSupportLinkage.isNull();
+ // Dummy code to force linkage to Qt6PrintSupport (issue with GCC 7.3)
+ QPrinterInfo forceQt6PrintSupportLinkage;
+ forceQt6PrintSupportLinkage.isNull();
- // Same for Qt5Svg
- QSvgGenerator forceQt5SvgLinkage;
- forceQt5SvgLinkage.title();
+ // Same for Qt6Svg
+ QSvgGenerator forceQt6SvgLinkage;
+ forceQt6SvgLinkage.title();
//context.addBundleListener(getBundleListener());
AbstractUICTKPlugin::start(context);
bundleContext = context;
AbstractSourceProvider::DEBUG = Policy::DEBUG_SOURCES();
HandlerAuthority::DEBUG = Policy::DEBUG_HANDLERS();
HandlerAuthority::DEBUG_PERFORMANCE = Policy::DEBUG_HANDLERS_PERFORMANCE();
HandlerAuthority::DEBUG_VERBOSE = Policy::DEBUG_HANDLERS_VERBOSE();
HandlerAuthority::DEBUG_VERBOSE_COMMAND_ID = Policy::DEBUG_HANDLERS_VERBOSE_COMMAND_ID();
BERRY_REGISTER_EXTENSION_CLASS(EditorIntroAdapterPart, context)
BERRY_REGISTER_EXTENSION_CLASS(ExtensionFactory, context)
BERRY_REGISTER_EXTENSION_CLASS(QtWidgetsTweaklet, context)
BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchTweaklet, context)
BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPageTweaklet, context)
BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPresentationFactory, context)
BERRY_REGISTER_EXTENSION_CLASS(PerspectivesPreferencePage, context)
BERRY_REGISTER_EXTENSION_CLASS(QtStylePreferencePage, context)
BERRY_REGISTER_EXTENSION_CLASS(HandlerServiceFactory, context)
BERRY_REGISTER_EXTENSION_CLASS(MenuServiceFactory, context)
BERRY_REGISTER_EXTENSION_CLASS(CommandServiceFactory, context)
BERRY_REGISTER_EXTENSION_CLASS(WorkbenchSourceProvider, context)
BERRY_REGISTER_EXTENSION_CLASS(OpenPerspectivePropertyTester, context)
BERRY_REGISTER_EXTENSION_CLASS(PerspectiveParameterValues, context)
BERRY_REGISTER_EXTENSION_CLASS(HelpContentsHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(DynamicHelpHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(IntroHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(OpenInNewWindowHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(NewEditorHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(QuitHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(ShowPerspectiveHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(ShowViewHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(SavePerspectiveHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(ClosePerspectiveHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(CloseAllPerspectivesHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(ResetPerspectiveHandler, context)
styleManager.reset(new QtStyleManager());
context->registerService<berry::IQtStyleManager>(styleManager.data());
// The UI plugin needs to be initialized so that it can install the callback in PrefUtil,
// which needs to be done as early as possible, before the workbench
// accesses any API preferences.
// Bundle uiBundle = Platform.getBundle(PlatformUI.PLUGIN_ID);
// try
// {
// // Attempt to load the activator of the ui bundle. This will force lazy start
// // of the ui bundle. Using the bundle activator class here because it is a
// // class that needs to be loaded anyway so it should not cause extra classes
// // to be loaded.
// if(uiBundle != null)
// uiBundle.loadClass(UI_BUNDLE_ACTIVATOR);
// }
// catch (ClassNotFoundException e)
// {
// WorkbenchPlugin.log("Unable to load UI activator", e); //$NON-NLS-1$
// }
/*
* DO NOT RUN ANY OTHER CODE AFTER THIS LINE. If you do, then you are
* likely to cause a deadlock in class loader code. Please see Bug 86450
* for more information.
*/
}
//const QList<IBundle::Pointer> WorkbenchPlugin::GetBundles()
//{
// return bundleContext.IsNull() ? QList<IBundle::Pointer>() : bundleContext->GetBundles();
//}
ctkPluginContext* WorkbenchPlugin::GetPluginContext()
{
return bundleContext;
}
void WorkbenchPlugin::stop(ctkPluginContext* context)
{
AbstractUICTKPlugin::stop(context);
styleManager.reset();
delete perspRegistry;
// avoid possible crash, see bug #18399
perspRegistry = nullptr;
}
QString WorkbenchPlugin::GetDataLocation() const
{
QFileInfo fileInfo = bundleContext->getDataFile("");
if (!fileInfo.isWritable()) return QString();
return fileInfo.absoluteFilePath();
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryCategory.txx b/Plugins/org.blueberry.ui.qt/src/internal/berryCategory.txx
index a0c0342af0..258799f40a 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryCategory.txx
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCategory.txx
@@ -1,190 +1,190 @@
/*============================================================================
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_CATEGORY_TXX__
#define __BERRY_CATEGORY_TXX__
#include "berryWorkbenchRegistryConstants.h"
#include <berryIContributor.h>
#include <berryUIException.h>
#include <QStringList>
namespace berry
{
template<class T>
const QString Category<T>::MISC_NAME = "Other";
template<class T>
const QString Category<T>::MISC_ID =
"org.blueberry.ui.internal.otherCategory";
template<class T> Category<T>::Category()
{
this->id = MISC_ID;
this->name = MISC_NAME;
this->pluginId = MISC_ID;
}
template<class T> Category<T>::Category(const QString& ID,
const QString& label)
: id(ID), name(label)
{
}
template<class T>
Category<T>::Category(IConfigurationElement::Pointer configElement)
: configurationElement(configElement) {
id = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID);
if (id.isEmpty() || GetLabel().isEmpty())
{
throw WorkbenchException(QString("Invalid category: ") + id);
}
}
template<class T>
void Category<T>::AddElement(ElementType element)
{
elements.push_back(element);
}
template<class T>
Object* Category<T>::GetAdapter(const QString& adapter) const
{
if (adapter == qobject_interface_iid<IConfigurationElement*>())
{
return configurationElement.GetPointer();
}
else
{
return nullptr;
}
}
//template<class T>
//ImageDescriptor Category<T>::GetImageDescriptor()
//{
// return WorkbenchImages.getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER);
//}
template<class T>
const QString& Category<T>::GetId() const
{
return id;
}
template<class T>
QString Category<T>::GetLabel() const
{
if (configurationElement.IsNull())
return name;
return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME);
}
template<class T>
QList<QString> Category<T>::GetParentPath()
{
if (parentPath.size() > 0)
{
return parentPath;
}
QString unparsedPath(this->GetRawParentPath());
- foreach(QString token, unparsedPath.split('/', QString::SkipEmptyParts))
+ foreach(QString token, unparsedPath.split('/', Qt::SkipEmptyParts))
{
parentPath.push_back(token.trimmed());
}
return parentPath;
}
template<class T>
QString Category<T>::GetRawParentPath() const
{
if (configurationElement.IsNull())
return QString();
return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_PARENT_CATEGORY);
}
template<class T>
QString Category<T>::GetRootPath()
{
if (this->GetParentPath().size() > 0)
{
return GetParentPath()[0];
}
return id;
}
template<class T>
const QList<T>& Category<T>::GetElements() const
{
return elements;
}
template<class T>
bool Category<T>::HasElement(const ElementType& o) const
{
if (elements.empty())
{
return false;
}
for (typename QList<ElementType>::const_iterator iter = elements.begin(); iter != elements.end(); ++iter)
{
if (*iter == o) return true;
}
return false;
}
template<class T>
bool Category<T>::HasElements() const
{
return !elements.empty();
}
template<class T>
T* Category<T>::GetParent(const ElementType& /*o*/)
{
return 0;
}
template<class T>
QString Category<T>::GetLocalId() const
{
return id;
}
template<class T>
QString Category<T>::GetPluginId() const
{
return configurationElement.IsNull() ?
pluginId : configurationElement->GetContributor()->GetName();
}
template<class T>
void Category<T>::Clear()
{
elements.clear();
}
} // namespace berry
#endif // __BERRY_CATEGORY_TXX__
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp
index b2e87cfab6..f820a434c1 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp
@@ -1,251 +1,251 @@
/*============================================================================
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 "berryChangeToPerspectiveMenu.h"
#include <berryMenuManager.h>
#include <berryIWorkbenchWindow.h>
#include <berryIWorkbenchPage.h>
#include <berryCommandContributionItem.h>
#include <berrySeparator.h>
#include <berryIPluginContribution.h>
#include <berryIPerspectiveRegistry.h>
#include <berryIWorkbenchCommandConstants.h>
#include <berryObjectString.h>
#include <berryObjects.h>
#include "berryCommandContributionItemParameter.h"
#include "berryWorkbenchPlugin.h"
#include "berryWorkbenchPreferenceConstants.h"
#include "berryPreferenceConstants.h"
#include <QMenu>
#include <mitkIPreferences.h>
namespace berry {
const QString ChangeToPerspectiveMenu::NO_TARGETS_MSG = "<No Applicable Perspectives>";
bool PerspectiveComparator(const IPerspectiveDescriptor::Pointer& d1,
const IPerspectiveDescriptor::Pointer& d2)
{
return d1->GetLabel() < d2->GetLabel();
}
ChangeToPerspectiveMenu::ChangeToPerspectiveMenu(IWorkbenchWindow* window, const QString& id)
: ContributionItem(id)
, window(window)
, reg(window->GetWorkbench()->GetPerspectiveRegistry())
, showActive(true)
, dirty(true)
{
CommandContributionItemParameter::Pointer showDlgItemParms(
new CommandContributionItemParameter(
- window, QString::null, IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE,
+ window, QString(), IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE,
CommandContributionItem::STYLE_PUSH));
showDlgItemParms->label = "&Other...";
showDlgItem = new CommandContributionItem(showDlgItemParms);
// indicate that a open perspectives submenu has been created
/*
if (WorkbenchWindow* window = dynamic_cast<WorkbenchWindow*>(window))
{
window->AddSubmenu(WorkbenchWindow::OPEN_PERSPECTIVE_SUBMENU);
}
*/
}
void ChangeToPerspectiveMenu::Fill(QMenu* menu, QAction* before)
{
if (MenuManager* mm = dynamic_cast<MenuManager*>(GetParent()))
{
this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*)));
}
if (!dirty)
{
return;
}
- MenuManager::Pointer manager(new MenuManager());
+ MenuManager::Pointer manager(new MenuManager(""));
FillMenu(manager.GetPointer());
QList<IContributionItem::Pointer> items = manager->GetItems();
if (items.isEmpty())
{
auto action = new QAction(NO_TARGETS_MSG, menu);
action->setEnabled(false);
menu->insertAction(before, action);
}
else
{
foreach (IContributionItem::Pointer item, items)
{
item->Fill(menu, before);
}
}
dirty = false;
}
bool ChangeToPerspectiveMenu::IsDirty() const
{
return dirty;
}
bool ChangeToPerspectiveMenu::IsDynamic() const
{
return true;
}
void ChangeToPerspectiveMenu::AboutToShow(IMenuManager* manager)
{
manager->MarkDirty();
dirty = true;
}
void ChangeToPerspectiveMenu::FillMenu(IMenuManager* manager)
{
// Clear out the manager so that we have a blank slate.
manager->RemoveAll();
// Collect and sort perspective descriptors.
QList<IPerspectiveDescriptor::Pointer> persps = GetPerspectiveShortcuts();
- qSort(persps.begin(), persps.end(), PerspectiveComparator);
+ std::sort(persps.begin(), persps.end(), PerspectiveComparator);
/*
* Convert the perspective descriptors to command parameters, and filter
* using the activity/capability mechanism.
*/
- for (const IPerspectiveDescriptor::Pointer &descriptor : qAsConst(persps))
+ for (const IPerspectiveDescriptor::Pointer &descriptor : std::as_const(persps))
{
CommandContributionItemParameter::Pointer ccip = GetItem(descriptor);
// if (WorkbenchActivityHelper.filterItem(ccip)) {
// continue;
// }
CommandContributionItem::Pointer item(new CommandContributionItem(ccip));
manager->Add(item);
}
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
bool showOther = prefs->GetBool(WorkbenchPreferenceConstants::SHOW_OTHER_IN_PERSPECTIVE_MENU, true);
if (showOther)
{
// Add a separator and then "Other..."
if (!manager->IsEmpty())
{
IContributionItem::Pointer separator(new Separator());
manager->Add(separator);
}
manager->Add(showDlgItem);
}
}
SmartPointer<CommandContributionItemParameter> ChangeToPerspectiveMenu::GetItem(const IPerspectiveDescriptor::Pointer& desc) const
{
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
int mode = prefs->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE);
IWorkbenchPage::Pointer page = window->GetActivePage();
IPerspectiveDescriptor::Pointer persp;
if (page.IsNotNull())
{
persp = page->GetPerspective();
}
QString perspId = desc->GetId();
class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution
{
QString localId;
QString pluginId;
public:
typedef PluginCCIP Self;
static const char* GetStaticClassName() { return "PluginCCIP"; }
berryObjectTypeInfo(CommandContributionItemParameter, IPluginContribution)
PluginCCIP(const IPerspectiveDescriptor::Pointer& v, IServiceLocator* serviceLocator,
const QString& id, const QString& commandId, CommandContributionItem::Style style)
: CommandContributionItemParameter(serviceLocator, id, commandId, style)
{
PerspectiveDescriptor::Pointer vd = v.Cast<PerspectiveDescriptor>();
localId = vd->GetLocalId();
pluginId = vd->GetPluginId();
}
QString GetLocalId() const override
{
return localId;
}
QString GetPluginId() const override
{
return pluginId;
}
};
CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc,
window, perspId, IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE,
CommandContributionItem::STYLE_PUSH));
parms->label = desc->GetLabel();
parms->icon = desc->GetImageDescriptor();
Object::Pointer strId(new ObjectString(perspId));
parms->parameters.insert(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID, strId);
// Only open a new window if user preference is set and the window
// has an active perspective.
if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp.IsNotNull())
{
Object::Pointer bNewWnd(new ObjectBool(true));
parms->parameters.insert(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW,
bNewWnd);
}
return parms;
}
QList<SmartPointer<IPerspectiveDescriptor> > ChangeToPerspectiveMenu::GetPerspectiveShortcuts() const
{
QList<IPerspectiveDescriptor::Pointer> list;
IWorkbenchPage::Pointer page = window->GetActivePage();
if (page.IsNull())
{
return list;
}
QList<QString> ids = page->GetPerspectiveShortcuts();
for (int i = 0; i < ids.size(); i++)
{
IPerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId(ids[i]);
if (desc.IsNotNull() && !list.contains(desc))
{
/*
if (WorkbenchActivityHelper::FilterItem(desc))
{
continue;
}
*/
list.push_back(desc);
}
}
return list;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandParameter.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandParameter.cpp
index a5d0823254..860397be92 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandParameter.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandParameter.cpp
@@ -1,143 +1,143 @@
/*============================================================================
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 "berryCommandParameter.h"
#include "berryIConfigurationElement.h"
#include "berryIParameterValues.h"
#include "berryCoreException.h"
#include "berryCommandExceptions.h"
#include "berryParameterType.h"
namespace berry {
const QString CommandParameter::ATTRIBUTE_VALUES = "values";
const int CommandParameter::HASH_CODE_NOT_COMPUTED = 0;
const int CommandParameter::HASH_FACTOR = 89;
const int CommandParameter::HASH_INITIAL = qHash(CommandParameter::GetStaticClassName());
CommandParameter::CommandParameter(const QString& id, const QString& name,
const SmartPointer<IConfigurationElement>& values,
const SmartPointer<ParameterType>& parameterType,
const bool optional)
: name(name)
, optional(optional)
, parameterType(parameterType)
, valuesConfigurationElement(values)
, id(id)
{
if (id.isNull())
{
throw ctkInvalidArgumentException("Cannot create a parameter with a null id");
}
if (name.isNull())
{
throw ctkInvalidArgumentException("The name of a parameter cannot be null.");
}
if (values.IsNull())
{
throw ctkInvalidArgumentException("The values for a parameter cannot be null.");
}
}
bool CommandParameter::operator==(const Object* object) const
{
if (this == object)
{
return true;
}
if (const CommandParameter* parameter = dynamic_cast<const CommandParameter*>(object))
{
if (id != parameter->id)
{
return false;
}
if (name != parameter->name)
{
return false;
}
if (values != parameter->values)
{
return false;
}
return optional == parameter->optional;
}
else
{
return false;
}
}
QString CommandParameter::GetId() const
{
return id;
}
QString CommandParameter::GetName() const
{
return name;
}
SmartPointer<ParameterType> CommandParameter::GetParameterType() const
{
return parameterType;
}
IParameterValues* CommandParameter::GetValues() const
{
if (values.isNull())
{
try
{
values.reset(valuesConfigurationElement->CreateExecutableExtension<IParameterValues>(ATTRIBUTE_VALUES));
}
catch (const CoreException& e)
{
throw ParameterValuesException("Problem creating parameter values", e);
}
if (values.isNull())
{
throw ParameterValuesException(
"Parameter values were not an instance of IParameterValues");
}
}
return values.data();
}
bool CommandParameter::IsOptional() const
{
return optional;
}
QString CommandParameter::ToString() const
{
if (str.isNull())
{
QString paramValuesStr;
if (!values.isNull())
{
QDebug dbg(&paramValuesStr);
dbg << values->GetParameterValues();
}
- str = "Parameter(" + id + ',' + name + ',' + paramValuesStr + ',' + optional +')';
+ str = QString("Parameter(%1,%2,%3,%4)").arg(id).arg(name).arg(paramValuesStr).arg(optional);
}
return str;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp
index 889118ab0a..b23926e210 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryCommandService.cpp
@@ -1,313 +1,313 @@
/*============================================================================
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 "berryCommandService.h"
#include <berryCommand.h>
#include <berryCommandManager.h>
#include <berryCommandCategory.h>
#include <berryParameterizedCommand.h>
#include <berryUIElement.h>
#include "berryPersistentState.h"
#include "berryWorkbenchPlugin.h"
#include "berryElementReference.h"
#include <berryIHandler.h>
#include <berryIElementUpdater.h>
#include <berryIElementReference.h>
#include <berryISafeRunnable.h>
#include <berrySafeRunner.h>
#include <berryObjectString.h>
#include <QStringList>
namespace berry {
const std::string CommandService::PREFERENCE_KEY_PREFIX = "org.blueberry.ui.commands/state";
std::string CommandService::CreatePreferenceKey(const SmartPointer<Command>& command,
const QString& stateId)
{
return PREFERENCE_KEY_PREFIX + '/' + command->GetId().toStdString() + '/' + stateId.toStdString();
}
CommandService::CommandService( CommandManager* commandManager)
: commandManager(commandManager)
, commandPersistence(this)
{
if (commandManager == nullptr)
{
throw std::invalid_argument("Cannot create a command service with a null manager");
}
}
CommandService::~CommandService()
{
this->Dispose();
}
void CommandService::AddExecutionListener(IExecutionListener* listener)
{
commandManager->AddExecutionListener(listener);
}
void CommandService::DefineUncategorizedCategory(const QString& name,
const QString& description)
{
commandManager->DefineUncategorizedCategory(name, description);
}
SmartPointer<ParameterizedCommand> CommandService::Deserialize(const QString& serializedParameterizedCommand) const
{
return commandManager->Deserialize(serializedParameterizedCommand);
}
void CommandService::Dispose()
{
/*
* All state on all commands needs to be disposed. This is so that the
* state has a chance to persist any changes.
*/
const QList<Command::Pointer> commands = commandManager->GetAllCommands();
foreach (const Command::Pointer& command, commands)
{
const QList<QString> stateIds = command->GetStateIds();
foreach(const QString& stateId, stateIds)
{
const State::Pointer state = command->GetState(stateId);
if (PersistentState::Pointer persistentState = state.Cast<PersistentState>())
{
if (persistentState->ShouldPersist())
{
persistentState->Save(WorkbenchPlugin::GetDefault()->GetPreferences(),
CreatePreferenceKey(command, stateId));
}
}
}
}
commandCallbacks.clear();
}
SmartPointer<CommandCategory> CommandService::GetCategory(const QString& categoryId) const
{
return commandManager->GetCategory(categoryId);
}
SmartPointer<Command> CommandService::GetCommand(const QString& commandId) const
{
return commandManager->GetCommand(commandId);
}
QList<SmartPointer<CommandCategory> > CommandService::GetDefinedCategories() const
{
return commandManager->GetDefinedCategories();
}
QStringList CommandService::GetDefinedCategoryIds() const
{
- return commandManager->GetDefinedCategoryIds().toList();
+ return commandManager->GetDefinedCategoryIds().values();
}
QStringList CommandService::GetDefinedCommandIds() const
{
- return commandManager->GetDefinedCommandIds().toList();
+ return commandManager->GetDefinedCommandIds().values();
}
QList<SmartPointer<Command> > CommandService::GetDefinedCommands() const
{
return commandManager->GetDefinedCommands();
}
QStringList CommandService::GetDefinedParameterTypeIds() const
{
- return commandManager->GetDefinedParameterTypeIds().toList();
+ return commandManager->GetDefinedParameterTypeIds().values();
}
QList<SmartPointer<ParameterType> > CommandService::GetDefinedParameterTypes() const
{
return commandManager->GetDefinedParameterTypes();
}
QString CommandService::GetHelpContextId(const SmartPointer<const Command>& command) const
{
return commandManager->GetHelpContextId(command);
}
QString CommandService::GetHelpContextId(const QString& commandId) const
{
Command::Pointer command = GetCommand(commandId);
return commandManager->GetHelpContextId(command);
}
SmartPointer<ParameterType> CommandService::GetParameterType(const QString& parameterTypeId) const
{
return commandManager->GetParameterType(parameterTypeId);
}
void CommandService::ReadRegistry()
{
commandPersistence.Read();
}
void CommandService::RemoveExecutionListener(IExecutionListener* listener)
{
commandManager->RemoveExecutionListener(listener);
}
void CommandService::SetHelpContextId(const SmartPointer<IHandler>& handler,
const QString& helpContextId)
{
commandManager->SetHelpContextId(handler, helpContextId);
}
void CommandService::RefreshElements(const QString& commandId,
const QHash<QString, Object::Pointer>& filter)
{
Command::Pointer cmd = GetCommand(commandId);
if (!cmd->IsDefined() || !(cmd->GetHandler().Cast<IElementUpdater>()))
{
return;
}
IElementUpdater::Pointer updater = cmd->GetHandler().Cast<IElementUpdater>();
if (commandCallbacks.isEmpty())
{
return;
}
if(!commandCallbacks.contains(commandId))
{
return;
}
foreach (IElementReference::Pointer callbackRef, commandCallbacks[commandId])
{
struct _SafeRunnable : public ISafeRunnable
{
IElementUpdater* updater;
IElementReference* callbackRef;
_SafeRunnable(IElementUpdater* updater, IElementReference* callbackRef)
: updater(updater), callbackRef(callbackRef)
{}
void HandleException(const ctkException& exc) override
{
WorkbenchPlugin::Log(QString("Failed to update callback: ") +
callbackRef->GetCommandId() + exc.what());
}
void Run() override
{
updater->UpdateElement(callbackRef->GetElement().GetPointer(), callbackRef->GetParameters());
}
};
QHash<QString,Object::Pointer> parms = callbackRef->GetParameters();
ISafeRunnable::Pointer run(new _SafeRunnable(updater.GetPointer(), callbackRef.GetPointer()));
if (filter.isEmpty())
{
SafeRunner::Run(run);
}
else
{
bool match = true;
QHashIterator<QString, Object::Pointer> i(filter);
while (i.hasNext())
{
i.next();
Object::Pointer value = parms[i.key()];
if (i.value() != value)
{
match = false;
break;
}
}
if (match)
{
SafeRunner::Run(run);
}
}
}
}
SmartPointer<IElementReference> CommandService::RegisterElementForCommand(
const SmartPointer<ParameterizedCommand>& command,
const SmartPointer<UIElement>& element)
{
if (!command->GetCommand()->IsDefined())
{
throw NotDefinedException(
"Cannot define a callback for undefined command "
+ command->GetCommand()->GetId());
}
if (element.IsNull())
{
throw NotDefinedException("No callback defined for command "
+ command->GetCommand()->GetId());
}
QHash<QString, QString> paramMap = command->GetParameterMap();
QHash<QString, Object::Pointer> parms;
for (QHash<QString, QString>::const_iterator i = paramMap.begin();
i != paramMap.end(); ++i)
{
Object::Pointer value(new ObjectString(i.value()));
parms.insert(i.key(), value);
}
IElementReference::Pointer ref(new ElementReference(command->GetId(),
element, parms));
RegisterElement(ref);
return ref;
}
void CommandService::RegisterElement(const SmartPointer<IElementReference>& elementReference)
{
QList<IElementReference::Pointer>& parameterizedCommands = commandCallbacks[elementReference->GetCommandId()];
parameterizedCommands.push_back(elementReference);
// If the active handler wants to update the callback, it can do
// so now
Command::Pointer command = GetCommand(elementReference->GetCommandId());
if (command->IsDefined())
{
if (IElementUpdater::Pointer updater = command->GetHandler().Cast<IElementUpdater>())
{
updater->UpdateElement(elementReference->GetElement().GetPointer(),
elementReference->GetParameters());
}
}
}
void CommandService::UnregisterElement(const SmartPointer<IElementReference>& elementReference)
{
if (commandCallbacks.contains(elementReference->GetCommandId()))
{
QList<IElementReference::Pointer>& parameterizedCommands = commandCallbacks[elementReference->GetCommandId()];
parameterizedCommands.removeAll(elementReference);
if (parameterizedCommands.isEmpty())
{
commandCallbacks.remove(elementReference->GetCommandId());
}
}
}
const CommandPersistence* CommandService::GetCommandPersistence() const
{
return &commandPersistence;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryContainerPlaceholder.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryContainerPlaceholder.cpp
index dcad3f95a6..0d3bcc3c7b 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryContainerPlaceholder.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryContainerPlaceholder.cpp
@@ -1,128 +1,128 @@
/*============================================================================
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 "berryContainerPlaceholder.h"
#include "berryPartPlaceholder.h"
#include "berryILayoutContainer.h"
namespace berry
{
int ContainerPlaceholder::nextId = 0;
ContainerPlaceholder::ContainerPlaceholder(const QString& id) :
- PartPlaceholder(id == "" ? QString("Container Placeholder ") + nextId++ : id)
+ PartPlaceholder(id == "" ? QString("Container Placeholder %1").arg(nextId++) : id)
{
}
void ContainerPlaceholder::Add(LayoutPart::Pointer child)
{
if (child.Cast<PartPlaceholder>() == 0)
{
return;
}
realContainer->Add(child);
}
bool ContainerPlaceholder::AllowsAdd(LayoutPart::Pointer /*toAdd*/)
{
return false;
}
QList<LayoutPart::Pointer> ContainerPlaceholder::GetChildren() const
{
return realContainer->GetChildren();
}
QString ContainerPlaceholder::GetID() const
{
return LayoutPart::GetID();
}
LayoutPart::Pointer ContainerPlaceholder::GetRealContainer()
{
return realContainer.Cast<LayoutPart>();
}
void ContainerPlaceholder::Remove(LayoutPart::Pointer child)
{
if (child.Cast<PartPlaceholder> () == 0)
{
return;
}
realContainer->Remove(child);
}
void ContainerPlaceholder::Replace(LayoutPart::Pointer oldChild,
LayoutPart::Pointer newChild)
{
if (oldChild.Cast<PartPlaceholder>() == 0 && newChild.Cast<PartPlaceholder>()
== 0)
{
return;
}
realContainer->Replace(oldChild, newChild);
}
void ContainerPlaceholder::SetRealContainer(
ILayoutContainer::Pointer container)
{
if (container == 0)
{
// set the parent container of the children back to the real container
if (realContainer != 0)
{
QList<LayoutPart::Pointer> children = realContainer->GetChildren();
for (QList<LayoutPart::Pointer>::iterator iter = children.begin(); iter
!= children.end(); ++iter)
{
(*iter)->SetContainer(realContainer);
}
}
}
else
{
// replace the real container with this place holder
QList<LayoutPart::Pointer> children = container->GetChildren();
for (QList<LayoutPart::Pointer>::iterator iter = children.begin(); iter
!= children.end(); ++iter)
{
(*iter)->SetContainer(ILayoutContainer::Pointer(this));
}
}
this->realContainer = container;
}
void ContainerPlaceholder::FindSashes(LayoutPart::Pointer /*part*/, PartPane::Sashes& sashes)
{
ILayoutContainer::Pointer container = this->GetContainer();
if (container != 0) {
container->FindSashes(LayoutPart::Pointer(this), sashes);
}
}
void ContainerPlaceholder::ResizeChild(LayoutPart::Pointer /*childThatChanged*/)
{
}
bool ContainerPlaceholder::AllowsAutoFocus()
{
return false;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp
index e259834687..50ea7619d6 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp
@@ -1,211 +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.
============================================================================*/
#include "berryEditorHistoryItem.h"
#include "berryIEditorInput.h"
#include "berryIEditorDescriptor.h"
#include "berryIElementFactory.h"
#include "berryIMemento.h"
#include "berryIPersistableElement.h"
#include "berryStatus.h"
#include "berryWorkbenchConstants.h"
#include "berryWorkbenchPlugin.h"
namespace berry {
EditorHistoryItem::EditorHistoryItem(const SmartPointer<IEditorInput>& input,
const SmartPointer<IEditorDescriptor>& descriptor)
: input(input)
, descriptor(descriptor)
{
}
EditorHistoryItem::EditorHistoryItem(const SmartPointer<IMemento>& memento)
: memento(memento)
{
}
SmartPointer<IEditorDescriptor> EditorHistoryItem::GetDescriptor() const
{
return descriptor;
}
SmartPointer<IEditorInput> EditorHistoryItem::GetInput() const
{
return input;
}
bool EditorHistoryItem::IsRestored() const
{
return memento.IsNull();
}
QString EditorHistoryItem::GetName() const
{
QString result;
if (IsRestored() && GetInput().IsNotNull())
{
result = GetInput()->GetName();
}
else if (memento.IsNotNull())
{
memento->GetString(WorkbenchConstants::TAG_NAME, result);
}
return result;
}
QString EditorHistoryItem::GetToolTipText() const
{
QString result;
if (IsRestored() && GetInput().IsNotNull())
{
result = GetInput()->GetToolTipText();
}
else if (memento.IsNotNull())
{
memento->GetString(WorkbenchConstants::TAG_TOOLTIP, result);
}
return result;
}
bool EditorHistoryItem::Matches(const SmartPointer<IEditorInput>& input) const
{
if (IsRestored())
{
return input == GetInput();
}
// if not restored, compare name, tool tip text and factory id,
// avoiding as much work as possible
if (GetName() != input->GetName())
{
return false;
}
if (GetToolTipText() != input->GetToolTipText())
{
return false;
}
const IPersistableElement* persistable = input->GetPersistable();
- QString inputId = persistable ? persistable->GetFactoryId() : QString::null;
+ QString inputId = persistable ? persistable->GetFactoryId() : QString();
QString myId = GetFactoryId();
return myId.isEmpty() ? inputId.isEmpty() : myId == inputId;
}
QString EditorHistoryItem::GetFactoryId() const
{
QString result;
if (IsRestored())
{
if (input.IsNotNull())
{
const IPersistableElement* persistable = input->GetPersistable();
if (persistable != nullptr)
{
result = persistable->GetFactoryId();
}
}
}
else if (memento.IsNotNull())
{
memento->GetString(WorkbenchConstants::TAG_FACTORY_ID, result);
}
return result;
}
SmartPointer<const IStatus> EditorHistoryItem::RestoreState()
{
Q_ASSERT_X(!IsRestored(), "RestoreState", "already restored");
IStatus::ConstPointer result = Status::OK_STATUS(BERRY_STATUS_LOC);
IMemento::Pointer memento = this->memento;
this->memento = nullptr;
QString factoryId;
memento->GetString(WorkbenchConstants::TAG_FACTORY_ID, factoryId);
if (factoryId.isEmpty())
{
WorkbenchPlugin::Log("Unable to restore mru list - no input factory ID.");
return result;
}
QScopedPointer<IElementFactory> factory(
PlatformUI::GetWorkbench()->GetElementFactory(factoryId));
if (!factory)
{
return result;
}
IMemento::Pointer persistableMemento = memento->GetChild(WorkbenchConstants::TAG_PERSISTABLE);
if (persistableMemento.IsNull())
{
WorkbenchPlugin::Log("Unable to restore mru list - no input element state: " + factoryId);
return result;
}
QScopedPointer<IAdaptable> adaptable(factory->CreateElement(persistableMemento));
if (adaptable == nullptr || dynamic_cast<IEditorInput*>(adaptable.data()) == nullptr)
{
return result;
}
input = dynamic_cast<IEditorInput*>(adaptable.data());
// Get the editor descriptor.
QString editorId;
memento->GetString(WorkbenchConstants::TAG_ID, editorId);
if (!editorId.isEmpty())
{
IEditorRegistry* registry = WorkbenchPlugin::GetDefault()->GetEditorRegistry();
descriptor = registry->FindEditor(editorId);
}
return result;
}
bool EditorHistoryItem::CanSave() const
{
return !IsRestored()
|| (GetInput().IsNotNull() && GetInput()->GetPersistable() != nullptr);
}
SmartPointer<const IStatus> EditorHistoryItem::SaveState(const SmartPointer<IMemento>& memento)
{
if (!IsRestored())
{
memento->PutMemento(this->memento);
}
else if (input.IsNotNull())
{
const IPersistableElement* persistable = input->GetPersistable();
if (persistable != nullptr)
{
/*
* Store IPersistable of the IEditorInput in a separate section
* since it could potentially use a tag already used in the parent
* memento and thus overwrite data.
*/
IMemento::Pointer persistableMemento = memento->CreateChild(WorkbenchConstants::TAG_PERSISTABLE);
persistable->SaveState(persistableMemento);
memento->PutString(WorkbenchConstants::TAG_FACTORY_ID,
persistable->GetFactoryId());
if (descriptor.IsNotNull() && !descriptor->GetId().isEmpty())
{
memento->PutString(WorkbenchConstants::TAG_ID, descriptor->GetId());
}
// save the name and tooltip separately so they can be restored
// without having to instantiate the input, which can activate plugins
memento->PutString(WorkbenchConstants::TAG_NAME, input->GetName());
memento->PutString(WorkbenchConstants::TAG_TOOLTIP, input->GetToolTipText());
}
}
return Status::OK_STATUS(BERRY_STATUS_LOC);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp
index c4c35cbdda..139d7056f3 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp
@@ -1,1295 +1,1295 @@
/*============================================================================
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 "berryEditorRegistry.h"
#include "berryWorkbenchPlugin.h"
#include "berryEditorRegistryReader.h"
#include "berryWorkbenchRegistryConstants.h"
namespace berry
{
const QString EditorRegistry::EMPTY_EDITOR_ID =
"org.blueberry.ui.internal.emptyEditorTab";
QHash<QString, FileEditorMapping::Pointer>
EditorRegistry::EditorMap::defaultMap;
QHash<QString, FileEditorMapping::Pointer> EditorRegistry::EditorMap::map;
EditorRegistry::RelatedRegistry::RelatedRegistry(EditorRegistry* reg) :
editorRegistry(reg)
{
}
QList<IEditorDescriptor::Pointer> EditorRegistry::RelatedRegistry::GetRelatedObjects(
const QString& fileName)
{
IFileEditorMapping::Pointer mapping = editorRegistry->GetMappingFor(fileName);
if (mapping.IsNull())
{
return QList<IEditorDescriptor::Pointer>();
}
return mapping->GetEditors();
}
EditorRegistry::EditorRegistry() :
relatedRegistry(this)
{
this->InitialIdToEditorMap(mapIDtoEditor);
this->InitializeFromStorage();
//IExtensionTracker tracker = PlatformUI.getWorkbench().getExtensionTracker();
//tracker.registerHandler(this,
// ExtensionTracker.createExtensionPointFilter(getExtensionPointFilter()));
}
void EditorRegistry::AddEditorFromPlugin(EditorDescriptor::Pointer editor,
const QList<QString>& extensions,
const QList<QString>& filenames,
const QList<QString>& /*contentTypeVector*/, bool bDefault)
{
//PlatformUI.getWorkbench().getExtensionTracker().registerObject(editor.getConfigurationElement().getDeclaringExtension(), editor, IExtensionTracker.REF_WEAK);
// record it in our quick reference list
sortedEditorsFromPlugins.push_back(editor);
// add it to the table of mappings
for (QList<QString>::const_iterator itr = extensions.begin(); itr
!= extensions.end(); ++itr)
{
QString fileExtension = *itr;
if (!fileExtension.isEmpty())
{
FileEditorMapping::Pointer mapping = this->GetMappingFor("*." + fileExtension);
if (mapping.IsNull())
{ // no mapping for that extension
mapping = new FileEditorMapping(fileExtension);
typeEditorMappings.PutDefault(this->MappingKeyFor(mapping), mapping);
}
mapping->AddEditor(editor);
if (bDefault)
{
mapping->SetDefaultEditor(editor);
}
}
}
// add it to the table of mappings
for (QList<QString>::const_iterator itr = filenames.begin(); itr
!= filenames.end(); ++itr)
{
QString filename = *itr;
if (!filename.isEmpty())
{
FileEditorMapping::Pointer mapping = this->GetMappingFor(filename);
if (mapping.IsNull())
{ // no mapping for that extension
QString name;
QString extension;
int index = filename.indexOf('.');
if (index == -1)
{
name = filename;
extension = "";
}
else
{
name = filename.left(index);
extension = filename.mid(index + 1);
}
mapping = new FileEditorMapping(name, extension);
typeEditorMappings.PutDefault(this->MappingKeyFor(mapping), mapping);
}
mapping->AddEditor(editor);
if (bDefault)
{
mapping->SetDefaultEditor(editor);
}
}
}
// for (QList<QString>::const_iterator itr = contentTypeVector.begin();
// itr != contentTypeVector.end(); ++itr)
// {
// QString contentTypeId = *itr;
// if (!contentTypeId.empty())
// {
// IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeId);
// if (contentType != null)
// {
// IEditorDescriptor [] editorArray = (IEditorDescriptor[]) contentTypeToEditorMappings.get(contentType);
// if (editorArray == null)
// {
// editorArray = new IEditorDescriptor[]
// { editor};
// contentTypeToEditorMappings.put(contentType, editorArray);
// }
// else
// {
// IEditorDescriptor [] newArray = new IEditorDescriptor[editorArray.length + 1];
// if (bDefault)
// { // default editors go to the front of the line
// newArray[0] = editor;
// System.arraycopy(editorArray, 0, newArray, 1, editorArray.length);
// }
// else
// {
// newArray[editorArray.length] = editor;
// System.arraycopy(editorArray, 0, newArray, 0, editorArray.length);
// }
// contentTypeToEditorMappings.put(contentType, newArray);
// }
// }
// }
// }
// Update editor map.
mapIDtoEditor[editor->GetId()] = editor;
}
void EditorRegistry::AddExternalEditorsToEditorMap()
{
// Add registered editors (may include external editors).
QList<FileEditorMapping::Pointer> maps =
typeEditorMappings.AllMappings();
for (int i = 0; i < maps.size(); ++i)
{
FileEditorMapping::Pointer map = maps[i];
QList<IEditorDescriptor::Pointer> descArray = map->GetEditors();
for (QList<IEditorDescriptor::Pointer>::iterator itr =
descArray.begin(); itr != descArray.end(); ++itr)
{
mapIDtoEditor[(*itr)->GetId()] = itr->Cast<EditorDescriptor> ();
}
}
}
IEditorDescriptor::Pointer EditorRegistry::FindEditor(const QString& id)
{
return mapIDtoEditor[id];
}
IEditorDescriptor::Pointer EditorRegistry::GetDefaultEditor()
{
// the default editor will always be the system external editor
// this should never return null
return this->FindEditor(IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID);
}
IEditorDescriptor::Pointer EditorRegistry::GetDefaultEditor(
const QString& fileName)
{
//return this->GetDefaultEditor(filename, guessAtContentType(filename));
return this->GetEditorForContentType(fileName /*, contentType*/);
}
IEditorDescriptor::Pointer EditorRegistry::GetEditorForContentType(
const QString& filename
/*IContentType contentType*/)
{
IEditorDescriptor::Pointer desc;
;
QList<IEditorDescriptor::Pointer> contentTypeResults =
this->FindRelatedObjects(/*contentType,*/filename, relatedRegistry);
if (contentTypeResults.size() > 0)
{
desc = contentTypeResults.front();
}
return desc;
}
QList<IEditorDescriptor::Pointer> EditorRegistry::FindRelatedObjects(
/*IContentType type,*/const QString& fileName,
RelatedRegistry& /*registry*/)
{
QList<IEditorDescriptor::Pointer> allRelated;
QList<IEditorDescriptor::Pointer> nonDefaultFileEditors;
QList<IEditorDescriptor::Pointer> related;
if (!fileName.isEmpty())
{
FileEditorMapping::Pointer mapping = this->GetMappingFor(fileName);
if (!mapping.IsNull())
{
// backwards compatibility - add editors flagged as "default"
related = mapping->GetDeclaredDefaultEditors();
for (QList<IEditorDescriptor::Pointer>::iterator itr =
related.begin(); itr != related.end(); ++itr)
{
// we don't want to return duplicates
if (std::find(allRelated.begin(), allRelated.end(), *itr)
== allRelated.end())
{
allRelated.push_back(*itr);
}
}
// add all filename editors to the nonDefaultList
// we'll later try to add them all after content types are resolved
// duplicates (ie: default editors) will be ignored
QList<IEditorDescriptor::Pointer> tmpList = mapping->GetEditors();
nonDefaultFileEditors.append(tmpList);
}
int index = fileName.indexOf('.');
if (index != -1)
{
QString extension = "*" + fileName.mid(index);
mapping = this->GetMappingFor(extension);
if (!mapping.IsNull())
{
related = mapping->GetDeclaredDefaultEditors();
for (QList<IEditorDescriptor::Pointer>::iterator itr =
related.begin(); itr != related.end(); ++itr)
{
// we don't want to return duplicates
if (std::find(allRelated.begin(), allRelated.end(), *itr)
== allRelated.end())
{
allRelated.push_back(*itr);
}
}
QList<IEditorDescriptor::Pointer> tmpList = mapping->GetEditors();
nonDefaultFileEditors.append(tmpList);
}
}
}
// if (type != null) {
// // now add any objects directly related to the content type
// related = registry.getRelatedObjects(type);
// for (int i = 0; i < related.length; i++) {
// // we don't want to return duplicates
// if (!allRelated.contains(related[i])) {
// // if it's not filtered, add it to the list
// if (!WorkbenchActivityHelper.filterItem(related[i])) {
// allRelated.add(related[i]);
// }
// }
// }
//
// }
// if (type != null) {
// // now add any indirectly related objects, walking up the content type hierarchy
// while ((type = type.getBaseType()) != null) {
// related = registry.getRelatedObjects(type);
// for (int i = 0; i < related.length; i++) {
// // we don't want to return duplicates
// if (!allRelated.contains(related[i])) {
// // if it's not filtered, add it to the list
// if (!WorkbenchActivityHelper.filterItem(related[i])) {
// allRelated.add(related[i]);
// }
// }
// }
// }
// }
// add all non-default editors to the list
for (QList<IEditorDescriptor::Pointer>::iterator i =
nonDefaultFileEditors.begin(); i != nonDefaultFileEditors.end(); ++i)
{
IEditorDescriptor::Pointer editor = *i;
if (std::find(allRelated.begin(), allRelated.end(), editor)
== allRelated.end())
{
allRelated.push_back(editor);
}
}
return allRelated;
}
QList<IEditorDescriptor::Pointer> EditorRegistry::GetEditors(
const QString& filename)
{
//return getEditors(filename, guessAtContentType(filename));
return this->FindRelatedObjects(/*contentType,*/filename, relatedRegistry);
}
QList<IFileEditorMapping::Pointer> EditorRegistry::GetFileEditorMappings()
{
QList<FileEditorMapping::Pointer>
array(typeEditorMappings.AllMappings());
std::sort(array.begin(), array.end(), CmpFileEditorMapping());
QList<IFileEditorMapping::Pointer> result;
for (QList<FileEditorMapping::Pointer>::iterator itr = array.begin(); itr
!= array.end(); ++itr)
{
result.push_back(itr->Cast<IFileEditorMapping> ());
}
return result;
}
FileEditorMapping::Pointer EditorRegistry::GetMappingFor(const QString& ext)
{
QString key = this->MappingKeyFor(ext);
return typeEditorMappings.Get(key);
}
QList<FileEditorMapping::Pointer> EditorRegistry::GetMappingForFilename(
const QString& filename)
{
QList<FileEditorMapping::Pointer> mapping;
// Lookup on entire filename
mapping[0] = this->GetMappingFor(filename);
// Lookup on filename's extension
int index = filename.indexOf('.');
if (index != -1)
{
QString extension = filename.mid(index);
mapping[1] = this->GetMappingFor("*" + extension);
}
return mapping;
}
// QList<IEditorDescriptor::Pointer> EditorRegistry::GetSortedEditorsFromOS()
// {
// List externalEditors = new ArrayList();
// Program[] programs = Program.getPrograms();
//
// for (int i = 0; i < programs.length; i++)
// {
// //1FPLRL2: ITPUI:WINNT - NOTEPAD editor cannot be launched
// //Some entries start with %SystemRoot%
// //For such cases just use the file name as they are generally
// //in directories which are on the path
// /*
// * if (fileName.charAt(0) == '%') { fileName = name + ".exe"; }
// */
//
// EditorDescriptor editor = new EditorDescriptor();
// editor.setOpenMode(EditorDescriptor.OPEN_EXTERNAL);
// editor.setProgram(programs[i]);
//
// // determine the program icon this editor would need (do not let it
// // be cached in the workbench registry)
// ImageDescriptor desc = new ExternalProgramImageDescriptor(
// programs[i]);
// editor.setImageDescriptor(desc);
// externalEditors.add(editor);
// }
//
// Object[] tempArray = sortEditors(externalEditors);
// IEditorDescriptor[] array = new IEditorDescriptor[externalEditors
// .size()];
// for (int i = 0; i < tempArray.length; i++)
// {
// array[i] = (IEditorDescriptor) tempArray[i];
// }
// return array;
// }
QList<IEditorDescriptor::Pointer> EditorRegistry::GetSortedEditorsFromPlugins()
{
QList<IEditorDescriptor::Pointer> result;
for (QList<EditorDescriptor::Pointer>::iterator itr =
sortedEditorsFromPlugins.begin(); itr != sortedEditorsFromPlugins.end(); ++itr)
{
result.push_back((*itr).Cast<IEditorDescriptor> ());
}
return result;
}
void EditorRegistry::InitialIdToEditorMap(
QHash<QString, EditorDescriptor::Pointer>& map)
{
this->AddSystemEditors(map);
}
void EditorRegistry::AddSystemEditors(
QHash<QString, EditorDescriptor::Pointer>& map)
{
// there will always be a system external editor descriptor
EditorDescriptor::Pointer editor(new EditorDescriptor());
editor->SetID(IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID);
editor->SetName("System Editor");
editor->SetOpenMode(EditorDescriptor::OPEN_EXTERNAL);
// @issue we need a real icon for this editor?
map[IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID] = editor;
// there may be a system in-place editor if supported by platform
// if (ComponentSupport.inPlaceEditorSupported())
// {
// editor = new EditorDescriptor();
// editor.setID(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID);
// editor.setName(WorkbenchMessages.SystemInPlaceDescription_name);
// editor.setOpenMode(EditorDescriptor.OPEN_INPLACE);
// // @issue we need a real icon for this editor?
// map.put(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID, editor);
// }
EditorDescriptor::Pointer emptyEditorDescriptor(new EditorDescriptor());
emptyEditorDescriptor->SetID(EMPTY_EDITOR_ID);
emptyEditorDescriptor->SetName("(Empty)"); //$NON-NLS-1$
//emptyEditorDescriptor.setImageDescriptor(WorkbenchImages
//.getImageDescriptor(IWorkbenchGraphicConstants.IMG_OBJ_ELEMENT));
map[EMPTY_EDITOR_ID] = emptyEditorDescriptor;
}
void EditorRegistry::InitializeFromStorage()
{
//Get editors from the registry
EditorRegistryReader registryReader;
registryReader.AddEditors(this);
this->SortInternalEditors();
this->RebuildInternalEditorMap();
// IPreferenceStore store = PlatformUI.getPreferenceStore();
// String defaultEditors = store
// .getString(IPreferenceConstants.DEFAULT_EDITORS);
// String chachedDefaultEditors = store
// .getString(IPreferenceConstants.DEFAULT_EDITORS_CACHE);
//If defaults has changed load it afterwards so it overrides the users
// associations.
//if (defaultEditors == null
// || defaultEditors.equals(chachedDefaultEditors))
//{
this->SetProductDefaults("");//defaultEditors);
this->LoadAssociations(); //get saved earlier state
// }
// else
// {
// loadAssociations(); //get saved earlier state
// setProductDefaults(defaultEditors);
// store.putValue(IPreferenceConstants.DEFAULT_EDITORS_CACHE,
// defaultEditors);
// }
this->AddExternalEditorsToEditorMap();
}
void EditorRegistry::SetProductDefaults(const QString& defaultEditors)
{
if (defaultEditors.isEmpty())
{
return;
}
// Poco::StringTokenizer extEditors(defaultEditors,
// IPreferenceConstants::SEPARATOR, Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);
// while (extEditors.hasMoreTokens())
// {
// String extEditor = extEditors.nextToken().trim();
// int index = extEditor.indexOf(':');
// if (extEditor.length() < 3 || index <= 0 || index
// >= (extEditor.length() - 1))
// {
// //Extension and id must have at least one char.
// WorkbenchPlugin
// .log("Error setting default editor. Could not parse '" + extEditor
// + "'. Default editors should be specified as '*.ext1:editorId1;*.ext2:editorId2'"); //$NON-NLS-1$ //$NON-NLS-2$
// return;
// }
// String ext = extEditor.substring(0, index).trim();
// String editorId = extEditor.substring(index + 1).trim();
// FileEditorMapping mapping = getMappingFor(ext);
// if (mapping == null)
// {
// WorkbenchPlugin
// .log("Error setting default editor. Could not find mapping for '"
// + ext + "'."); //$NON-NLS-1$ //$NON-NLS-2$
// continue;
// }
// EditorDescriptor editor = (EditorDescriptor) findEditor(editorId);
// if (editor == null)
// {
// WorkbenchPlugin
// .log("Error setting default editor. Could not find editor: '"
// + editorId + "'."); //$NON-NLS-1$ //$NON-NLS-2$
// continue;
// }
// mapping.setDefaultEditor(editor);
// }
}
bool EditorRegistry::ReadEditors(
QHash<QString, EditorDescriptor::Pointer>& /*editorTable*/)
{
//Get the workbench plugin's working directory
QString workbenchStatePath = WorkbenchPlugin::GetDefault()->GetDataLocation();
if (workbenchStatePath.isNull())
{
return false;
}
// IPreferenceStore store = WorkbenchPlugin.getDefault()
// .getPreferenceStore();
// Reader reader = null;
// try
// {
// // Get the editors defined in the preferences store
// String xmlString = store.getString(IPreferenceConstants.EDITORS);
// if (xmlString == null || xmlString.length() == 0)
// {
// FileInputStream stream = new FileInputStream(workbenchStatePath
// .append(IWorkbenchConstants.EDITOR_FILE_NAME)
// .toOSString());
// reader = new BufferedReader(new InputStreamReader(stream,
// "utf-8")); //$NON-NLS-1$
// }
// else
// {
// reader = new StringReader(xmlString);
// }
// XMLMemento memento = XMLMemento.createReadRoot(reader);
// EditorDescriptor editor;
// IMemento[] edMementos = memento
// .getChildren(IWorkbenchConstants.TAG_DESCRIPTOR);
// // Get the editors and validate each one
// for (int i = 0; i < edMementos.length; i++)
// {
// editor = new EditorDescriptor();
// boolean valid = editor.loadValues(edMementos[i]);
// if (!valid)
// {
// continue;
// }
// if (editor.getPluginID() != null)
// {
// //If the editor is from a plugin we use its ID to look it
// // up in the mapping of editors we
// //have obtained from plugins. This allows us to verify that
// // the editor is still valid
// //and allows us to get the editor description from the
// // mapping table which has
// //a valid config element field.
// EditorDescriptor validEditorDescritor = (EditorDescriptor) mapIDtoEditor
// .get(editor.getId());
// if (validEditorDescritor != null)
// {
// editorTable.put(validEditorDescritor.getId(),
// validEditorDescritor);
// }
// }
// else
// { //This is either from a program or a user defined
// // editor
// ImageDescriptor descriptor;
// if (editor.getProgram() == null)
// {
// descriptor = new ProgramImageDescriptor(editor
// .getFileName(), 0);
// }
// else
// {
// descriptor = new ExternalProgramImageDescriptor(editor
// .getProgram());
// }
// editor.setImageDescriptor(descriptor);
// editorTable.put(editor.getId(), editor);
// }
// }
// }
// catch (IOException e)
// {
// try
// {
// if (reader != null)
// {
// reader.close();
// }
// }
// catch (IOException ex)
// {
// e.printStackTrace();
// }
// //Ignore this as the workbench may not yet have saved any state
// return false;
// }
// catch (WorkbenchException e)
// {
// ErrorDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle,
// WorkbenchMessages.EditorRegistry_errorMessage,
// e.getStatus());
// return false;
// }
return true;
}
void EditorRegistry::ReadResources(
QHash<QString, EditorDescriptor::Pointer>& /*editorTable*/,
std::ostream& /*reader*/)
{
// XMLMemento memento = XMLMemento.createReadRoot(reader);
// String versionString = memento.getString(IWorkbenchConstants.TAG_VERSION);
// boolean versionIs31 = "3.1".equals(versionString); //$NON-NLS-1$
//
// IMemento[] extMementos = memento
// .getChildren(IWorkbenchConstants.TAG_INFO);
// for (int i = 0; i < extMementos.length; i++)
// {
// String name = extMementos[i]
// .getString(IWorkbenchConstants.TAG_NAME);
// if (name == null)
// {
// name = "*"; //$NON-NLS-1$
// }
// String extension = extMementos[i]
// .getString(IWorkbenchConstants.TAG_EXTENSION);
// IMemento[] idMementos = extMementos[i]
// .getChildren(IWorkbenchConstants.TAG_EDITOR);
// String[] editorIDs = new String[idMementos.length];
// for (int j = 0; j < idMementos.length; j++)
// {
// editorIDs[j] = idMementos[j]
// .getString(IWorkbenchConstants.TAG_ID);
// }
// idMementos = extMementos[i]
// .getChildren(IWorkbenchConstants.TAG_DELETED_EDITOR);
// String[] deletedEditorIDs = new String[idMementos.length];
// for (int j = 0; j < idMementos.length; j++)
// {
// deletedEditorIDs[j] = idMementos[j]
// .getString(IWorkbenchConstants.TAG_ID);
// }
// FileEditorMapping mapping = getMappingFor(name + "." + extension); //$NON-NLS-1$
// if (mapping == null)
// {
// mapping = new FileEditorMapping(name, extension);
// }
// List editors = new ArrayList();
// for (int j = 0; j < editorIDs.length; j++)
// {
// if (editorIDs[j] != null)
// {
// EditorDescriptor editor = (EditorDescriptor) editorTable
// .get(editorIDs[j]);
// if (editor != null)
// {
// editors.add(editor);
// }
// }
// }
// List deletedEditors = new ArrayList();
// for (int j = 0; j < deletedEditorIDs.length; j++)
// {
// if (deletedEditorIDs[j] != null)
// {
// EditorDescriptor editor = (EditorDescriptor) editorTable
// .get(deletedEditorIDs[j]);
// if (editor != null)
// {
// deletedEditors.add(editor);
// }
// }
// }
//
// List defaultEditors = new ArrayList();
//
// if (versionIs31)
// { // parse the new format
// idMementos = extMementos[i]
// .getChildren(IWorkbenchConstants.TAG_DEFAULT_EDITOR);
// String[] defaultEditorIds = new String[idMementos.length];
// for (int j = 0; j < idMementos.length; j++)
// {
// defaultEditorIds[j] = idMementos[j]
// .getString(IWorkbenchConstants.TAG_ID);
// }
// for (int j = 0; j < defaultEditorIds.length; j++)
// {
// if (defaultEditorIds[j] != null)
// {
// EditorDescriptor editor = (EditorDescriptor) editorTable
// .get(defaultEditorIds[j]);
// if (editor != null)
// {
// defaultEditors.add(editor);
// }
// }
// }
// }
// else
// { // guess at pre 3.1 format defaults
// if (!editors.isEmpty())
// {
// EditorDescriptor editor = (EditorDescriptor) editors.get(0);
// if (editor != null)
// {
// defaultEditors.add(editor);
// }
// }
// defaultEditors.addAll(Arrays.asList(mapping.getDeclaredDefaultEditors()));
// }
//
// // Add any new editors that have already been read from the registry
// // which were not deleted.
// IEditorDescriptor[] editorsArray = mapping.getEditors();
// for (int j = 0; j < editorsArray.length; j++)
// {
// if (!contains(editors, editorsArray[j])
// && !deletedEditors.contains(editorsArray[j]))
// {
// editors.add(editorsArray[j]);
// }
// }
// // Map the editor(s) to the file type
// mapping.setEditorsList(editors);
// mapping.setDeletedEditorsList(deletedEditors);
// mapping.setDefaultEditors(defaultEditors);
// typeEditorMappings.put(mappingKeyFor(mapping), mapping);
// }
}
bool EditorRegistry::Contains(
const QList<IEditorDescriptor::Pointer>& editorsArray,
IEditorDescriptor::Pointer editorDescriptor)
{
IEditorDescriptor::Pointer currentEditorDescriptor;
for (QList<IEditorDescriptor::Pointer>::const_iterator i =
editorsArray.begin(); i != editorsArray.end(); ++i)
{
currentEditorDescriptor = *i;
if (currentEditorDescriptor->GetId() == editorDescriptor->GetId())
{
return true;
}
}
return false;
}
bool EditorRegistry::ReadResources(
QHash<QString, EditorDescriptor::Pointer>& /*editorTable*/)
{
//Get the workbench plugin's working directory
QString workbenchStatePath = WorkbenchPlugin::GetDefault()->GetDataLocation();
// XXX: nobody cares about this return value
if (workbenchStatePath.isNull())
{
return false;
}
// IPreferenceStore store = WorkbenchPlugin.getDefault()
// .getPreferenceStore();
// Reader reader = null;
// try
// {
// // Get the resource types
// String xmlString = store.getString(IPreferenceConstants.RESOURCES);
// if (xmlString == null || xmlString.length() == 0)
// {
// FileInputStream stream = new FileInputStream(workbenchStatePath
// .append(IWorkbenchConstants.RESOURCE_TYPE_FILE_NAME)
// .toOSString());
// reader = new BufferedReader(new InputStreamReader(stream,
// "utf-8")); //$NON-NLS-1$
// }
// else
// {
// reader = new StringReader(xmlString);
// }
// // Read the defined resources into the table
// readResources(editorTable, reader);
// }
// catch (IOException e)
// {
// try
// {
// if (reader != null)
// {
// reader.close();
// }
// }
// catch (IOException ex)
// {
// ex.printStackTrace();
// }
// MessageDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle,
// WorkbenchMessages.EditorRegistry_errorMessage);
// return false;
// }
// catch (WorkbenchException e)
// {
// ErrorDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle,
// WorkbenchMessages.EditorRegistry_errorMessage,
// e.getStatus());
// return false;
// }
return true;
}
bool EditorRegistry::LoadAssociations()
{
QHash<QString, EditorDescriptor::Pointer> editorTable;
if (!this->ReadEditors(editorTable))
{
return false;
}
return this->ReadResources(editorTable);
}
QString EditorRegistry::MappingKeyFor(const QString& type)
{
// keep everything lower case for case-sensitive platforms
return type.toLower();
}
QString EditorRegistry::MappingKeyFor(FileEditorMapping::Pointer mapping)
{
return this->MappingKeyFor(mapping->GetName()
+ (mapping->GetExtension().size() == 0 ? "" : "."
+ mapping->GetExtension())); //$NON-NLS-1$ //$NON-NLS-2$
}
void EditorRegistry::RebuildEditorMap()
{
this->RebuildInternalEditorMap();
this->AddExternalEditorsToEditorMap();
}
void EditorRegistry::RebuildInternalEditorMap()
{
EditorDescriptor::Pointer desc;
// Allocate a new map.
mapIDtoEditor.clear();
this->InitialIdToEditorMap(mapIDtoEditor);
// Add plugin editors.
for (QList<EditorDescriptor::Pointer>::iterator itr =
sortedEditorsFromPlugins.begin(); itr != sortedEditorsFromPlugins.end(); ++itr)
{
desc = *itr;
mapIDtoEditor[desc->GetId()] = desc;
}
}
void EditorRegistry::SaveAssociations()
{
//Save the resource type descriptions
// List editors = new ArrayList();
// IPreferenceStore store = WorkbenchPlugin.getDefault()
// .getPreferenceStore();
//
// XMLMemento memento = XMLMemento
// .createWriteRoot(IWorkbenchConstants.TAG_EDITORS);
// memento.putString(IWorkbenchConstants.TAG_VERSION, "3.1"); //$NON-NLS-1$
// FileEditorMapping maps[] = typeEditorMappings.userMappings();
// for (int mapsIndex = 0; mapsIndex < maps.length; mapsIndex++)
// {
// FileEditorMapping type = maps[mapsIndex];
// IMemento editorMemento = memento
// .createChild(IWorkbenchConstants.TAG_INFO);
// editorMemento.putString(IWorkbenchConstants.TAG_NAME, type
// .getName());
// editorMemento.putString(IWorkbenchConstants.TAG_EXTENSION, type
// .getExtension());
// IEditorDescriptor[] editorArray = type.getEditors();
// for (int i = 0; i < editorArray.length; i++)
// {
// EditorDescriptor editor = (EditorDescriptor) editorArray[i];
// if (!editors.contains(editor))
// {
// editors.add(editor);
// }
// IMemento idMemento = editorMemento
// .createChild(IWorkbenchConstants.TAG_EDITOR);
// idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i]
// .getId());
// }
// editorArray = type.getDeletedEditors();
// for (int i = 0; i < editorArray.length; i++)
// {
// EditorDescriptor editor = (EditorDescriptor) editorArray[i];
// if (!editors.contains(editor))
// {
// editors.add(editor);
// }
// IMemento idMemento = editorMemento
// .createChild(IWorkbenchConstants.TAG_DELETED_EDITOR);
// idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i]
// .getId());
// }
// editorArray = type.getDeclaredDefaultEditors();
// for (int i = 0; i < editorArray.length; i++)
// {
// EditorDescriptor editor = (EditorDescriptor) editorArray[i];
// if (!editors.contains(editor))
// {
// editors.add(editor);
// }
// IMemento idMemento = editorMemento
// .createChild(IWorkbenchConstants.TAG_DEFAULT_EDITOR);
// idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i]
// .getId());
// }
// }
// Writer writer = null;
// try
// {
// writer = new StringWriter();
// memento.save(writer);
// writer.close();
// store.setValue(IPreferenceConstants.RESOURCES, writer.toString());
// }
// catch (IOException e)
// {
// try
// {
// if (writer != null)
// {
// writer.close();
// }
// }
// catch (IOException ex)
// {
// ex.printStackTrace();
// }
// MessageDialog.openError((Shell) null, "Saving Problems", //$NON-NLS-1$
// "Unable to save resource associations."); //$NON-NLS-1$
// return;
// }
//
// memento = XMLMemento.createWriteRoot(IWorkbenchConstants.TAG_EDITORS);
// Iterator itr = editors.iterator();
// while (itr.hasNext())
// {
// EditorDescriptor editor = (EditorDescriptor) itr.next();
// IMemento editorMemento = memento
// .createChild(IWorkbenchConstants.TAG_DESCRIPTOR);
// editor.saveValues(editorMemento);
// }
// writer = null;
// try
// {
// writer = new StringWriter();
// memento.save(writer);
// writer.close();
// store.setValue(IPreferenceConstants.EDITORS, writer.toString());
// }
// catch (IOException e)
// {
// try
// {
// if (writer != null)
// {
// writer.close();
// }
// }
// catch (IOException ex)
// {
// ex.printStackTrace();
// }
// MessageDialog.openError((Shell) null,
// "Error", "Unable to save resource associations."); //$NON-NLS-1$ //$NON-NLS-2$
// return;
// }
}
void EditorRegistry::SetFileEditorMappings(
const QList<FileEditorMapping::Pointer>& newResourceTypes)
{
typeEditorMappings.Clear();
for (int i = 0; i < newResourceTypes.size(); i++)
{
FileEditorMapping::Pointer mapping = newResourceTypes[i];
typeEditorMappings.Put(this->MappingKeyFor(mapping), mapping);
}
//extensionImages = new HashMap();
this->RebuildEditorMap();
//firePropertyChange(PROP_CONTENTS);
}
void EditorRegistry::SetDefaultEditor(const QString& fileName,
const QString& editorId)
{
EditorDescriptor::Pointer desc = this->FindEditor(editorId).Cast<
EditorDescriptor> ();
QList<FileEditorMapping::Pointer> mapping = this->GetMappingForFilename(
fileName);
if (!mapping[0].IsNull())
{
mapping[0]->SetDefaultEditor(desc);
}
if (!mapping[1].IsNull())
{
mapping[1]->SetDefaultEditor(desc);
}
}
QList<IEditorDescriptor::Pointer> EditorRegistry::SortEditors(
const QList<IEditorDescriptor::Pointer>& unsortedList)
{
QList<IEditorDescriptor::Pointer> result(unsortedList);
std::sort(result.begin(), result.end(), CmpIEditorDescriptor());
return result;
}
void EditorRegistry::SortInternalEditors()
{
- qSort(sortedEditorsFromPlugins.begin(), sortedEditorsFromPlugins.end(), CmpEditorDescriptor());
+ std::sort(sortedEditorsFromPlugins.begin(), sortedEditorsFromPlugins.end(), CmpEditorDescriptor());
}
void EditorRegistry::EditorMap::PutDefault(const QString& key,
FileEditorMapping::Pointer value)
{
defaultMap[key] = value;
}
void EditorRegistry::EditorMap::Put(const QString& key,
FileEditorMapping::Pointer value)
{
QHash<QString, FileEditorMapping::Pointer>::iterator result =
defaultMap.find(key);
if (result != defaultMap.end())
{
map[key] = value;
}
}
FileEditorMapping::Pointer EditorRegistry::EditorMap::Get(
const QString& key)
{
QHash<QString, FileEditorMapping::Pointer>::const_iterator result =
map.find(key);
if (result == map.end())
{
return defaultMap[key];
}
return result.value();
}
void EditorRegistry::EditorMap::Clear()
{
defaultMap.clear();
map.clear();
}
QList<FileEditorMapping::Pointer> EditorRegistry::EditorMap::AllMappings()
{
QSet<FileEditorMapping::Pointer> resultSet;
QHash<QString, FileEditorMapping::Pointer>::const_iterator iter;
for (iter = defaultMap.begin(); iter != defaultMap.end(); ++iter)
{
resultSet.insert(iter.value());
}
for (iter = map.begin(); iter != map.end(); ++iter)
{
resultSet.insert(iter.value());
}
- return resultSet.toList();
+ return resultSet.values();
}
QList<FileEditorMapping::Pointer> EditorRegistry::EditorMap::UserMappings()
{
return map.values();
}
bool EditorRegistry::IsSystemInPlaceEditorAvailable(const QString& /*filename*/)
{
//return ComponentSupport.inPlaceEditorAvailable(filename);
return false;
}
bool EditorRegistry::IsSystemExternalEditorAvailable(
const QString& /*filename*/)
{
// QString::size_type nDot = filename.find_last_of('.');
// if (nDot != QString::npos)
// {
// QString strName = filename.substr(nDot);
// return Program.findProgram(strName) != null;
// }
return false;
}
void EditorRegistry::RemoveEditorFromMapping(
QHash<QString, FileEditorMapping::Pointer>& map,
IEditorDescriptor::Pointer desc)
{
FileEditorMapping::Pointer mapping;
for (QHash<QString, FileEditorMapping::Pointer>::iterator iter =
map.begin(); iter != map.end(); ++iter)
{
mapping = iter.value();
QList<IEditorDescriptor::Pointer> editors(mapping->GetEditors());
QList<IEditorDescriptor::Pointer>::iterator result = std::find(
editors.begin(), editors.end(), desc);
if (result != editors.end())
{
mapping->RemoveEditor(result->Cast<EditorDescriptor> ());
editors.erase(result);
}
if (editors.empty())
{
map.erase(iter);
break;
}
}
}
IExtensionPoint::Pointer EditorRegistry::GetExtensionPointFilter()
{
return Platform::GetExtensionRegistry()->GetExtensionPoint(
PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_EDITOR);
}
QList<IFileEditorMapping::Pointer> EditorRegistry::GetUnifiedMappings()
{
QList<IFileEditorMapping::Pointer>
standardMappings(
dynamic_cast<EditorRegistry*> (PlatformUI::GetWorkbench() ->GetEditorRegistry())->GetFileEditorMappings());
QList<IFileEditorMapping::Pointer> allMappings(standardMappings);
// mock-up content type extensions into IFileEditorMappings
// IContentType [] contentTypes = Platform.getContentTypeManager().getAllContentTypes();
// for (int i = 0; i < contentTypes.length; i++)
// {
// IContentType type = contentTypes[i];
// String [] extensions = type.getFileSpecs(IContentType.FILE_EXTENSION_SPEC);
// for (int j = 0; j < extensions.length; j++)
// {
// String extension = extensions[j];
// boolean found = false;
// for (Iterator k = allMappings.iterator(); k.hasNext();)
// {
// IFileEditorMapping mapping = (IFileEditorMapping) k.next();
// if ("*".equals(mapping.getName())
// && extension.equals(mapping.getExtension()))
// { //$NON-NLS-1$
// found = true;
// break;
// }
// }
// if (!found)
// {
// MockMapping mockMapping = new MockMapping(type, "*", extension); //$NON-NLS-1$
// allMappings.add(mockMapping);
// }
// }
//
// String [] filenames = type.getFileSpecs(IContentType.FILE_NAME_SPEC);
// for (int j = 0; j < filenames.length; j++)
// {
// String wholename = filenames[j];
// int idx = wholename.indexOf('.');
// String name = idx == -1 ? wholename : wholename.substring(0, idx);
// String extension = idx == -1 ? "" : wholename.substring(idx + 1); //$NON-NLS-1$
//
// boolean found = false;
// for (Iterator k = allMappings.iterator(); k.hasNext();)
// {
// IFileEditorMapping mapping = (IFileEditorMapping) k.next();
// if (name.equals(mapping.getName())
// && extension.equals(mapping.getExtension()))
// {
// found = true;
// break;
// }
// }
// if (!found)
// {
// MockMapping mockMapping = new MockMapping(type, name, extension);
// allMappings.add(mockMapping);
// }
// }
// }
return allMappings;
}
MockMapping::MockMapping(/*IContentType type,*/const QString& name,
const QString& ext) :
extension(ext), filename(name)
{
//this.contentType = type;
}
IEditorDescriptor::Pointer MockMapping::GetDefaultEditor()
{
// QList<IEditorDescriptor::Pointer> candidates = PlatformUI::GetWorkbench()->GetEditorRegistry()
// ->GetEditorsForContentType(contentType);
// if (candidates.empty())
// {
// return IEditorDescriptor::Pointer();
// }
// return candidates[0];
return IEditorDescriptor::Pointer();
}
QList<IEditorDescriptor::Pointer> MockMapping::GetEditors() const
{
// QList<IEditorDescriptor::Pointer> editorsForContentType = (dynamic_cast<EditorRegistry*>(PlatformUI
// ::GetWorkbench()->GetEditorRegistry())
// ->GetEditorsForContentType(contentType);
// return editorsForContentType;
return QList<IEditorDescriptor::Pointer>();
}
QList<IEditorDescriptor::Pointer> MockMapping::GetDeletedEditors() const
{
return QList<IEditorDescriptor::Pointer>();
}
QString MockMapping::GetExtension() const
{
return extension;
}
QString MockMapping::GetLabel() const
{
return filename + '.' + extension;
}
QString MockMapping::GetName() const
{
return filename;
}
bool MockMapping::operator==(const Object* obj) const
{
if (const MockMapping* other = dynamic_cast<const MockMapping*>(obj))
{
if (this == other)
{
return true;
}
//MockMapping mapping = (MockMapping) obj;
if (!(this->filename == other->filename))
{
return false;
}
if (!(this->extension == other->extension))
{
return false;
}
if (!(this->GetEditors() == other->GetEditors()))
{
return false;
}
return this->GetDeletedEditors() == other->GetDeletedEditors();
}
return false;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistryReader.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistryReader.cpp
index 4e09f525dc..47ecab1c48 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistryReader.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistryReader.cpp
@@ -1,113 +1,113 @@
/*============================================================================
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 "berryEditorRegistryReader.h"
#include "berryEditorRegistry.h"
#include "berryEditorDescriptor.h"
#include "berryWorkbenchRegistryConstants.h"
#include "berryPlatformUI.h"
#include "berryPlatform.h"
#include <QStringList>
namespace berry
{
void EditorRegistryReader::AddEditors(EditorRegistry* registry)
{
this->editorRegistry = registry;
this->ReadRegistry(Platform::GetExtensionRegistry(),
PlatformUI::PLUGIN_ID(),
WorkbenchRegistryConstants::PL_EDITOR);
}
bool EditorRegistryReader::ReadElement(const IConfigurationElement::Pointer& element)
{
if (element->GetName() != WorkbenchRegistryConstants::TAG_EDITOR)
{
return false;
}
QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_ID);
if (id.isEmpty())
{
this->LogMissingAttribute(element, WorkbenchRegistryConstants::ATT_ID);
return true;
}
EditorDescriptor::Pointer editor(new EditorDescriptor(id, element));
QList<QString> extensionsVector;
QList<QString> filenamesVector;
QList<QString> contentTypeVector;
bool defaultEditor = false;
QString value = element->GetAttribute(WorkbenchRegistryConstants::ATT_NAME);
// Get editor name (required field).
if (value.isEmpty())
{
this->LogMissingAttribute(element, WorkbenchRegistryConstants::ATT_NAME);
return true;
}
// Get target extensions (optional field)
QString extensionsString = element->GetAttribute(WorkbenchRegistryConstants::ATT_EXTENSIONS);
if (!extensionsString.isEmpty())
{
- QStringList tokens = extensionsString.split(',', QString::SkipEmptyParts);
+ QStringList tokens = extensionsString.split(',', Qt::SkipEmptyParts);
foreach(QString token, tokens)
{
extensionsVector.push_back(token.trimmed());
}
}
QString filenamesString = element->GetAttribute(WorkbenchRegistryConstants::ATT_FILENAMES);
if (!filenamesString.isEmpty())
{
- QStringList tokens = filenamesString.split(',', QString::SkipEmptyParts);
+ QStringList tokens = filenamesString.split(',', Qt::SkipEmptyParts);
foreach(QString token, tokens)
{
filenamesVector.push_back(token.trimmed());
}
}
QList<IConfigurationElement::Pointer> bindings = element->GetChildren(
WorkbenchRegistryConstants::TAG_CONTENT_TYPE_BINDING);
for (int i = 0; i < bindings.size(); ++i)
{
QString contentTypeId = bindings[i]->GetAttribute(
WorkbenchRegistryConstants::ATT_CONTENT_TYPE_ID);
if (contentTypeId.isEmpty())
{
continue;
}
contentTypeVector.push_back(contentTypeId);
}
// Is this the default editor?
defaultEditor = element->GetAttribute(WorkbenchRegistryConstants::ATT_DEFAULT).compare("true", Qt::CaseInsensitive) == 0;
// Add the editor to the manager.
editorRegistry->AddEditorFromPlugin(editor, extensionsVector,
filenamesVector, contentTypeVector, defaultEditor);
return true;
}
void EditorRegistryReader::ReadElement(EditorRegistry* editorRegistry,
const IConfigurationElement::Pointer& element)
{
this->editorRegistry = editorRegistry;
this->ReadElement(element);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp
index ee9098c4cd..5a700c2801 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp
@@ -1,244 +1,244 @@
/*============================================================================
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 "berryEvaluationAuthority.h"
#include "berryCommandTracing.h"
#include "berryExpressionInfo.h"
#include "berryExpression.h"
#include "berryEvaluationReference.h"
#include "berryPolicy.h"
#include "berryWorkbenchPlugin.h"
#include <berryObjects.h>
#include <berryISources.h>
#include <berryIEvaluationService.h>
#include <QStringList>
#include <QString>
namespace berry {
const QString EvaluationAuthority::COMPONENT = "EVALUATION";
QStringList EvaluationAuthority::GetNames(const SmartPointer<IEvaluationReference>& ref) const
{
ExpressionInfo info;
ref->GetExpression()->CollectExpressionInfo(&info);
QSet<QString> allNames = info.GetAccessedVariableNames();
if (info.HasDefaultVariableAccess())
{
allNames << ISources::ACTIVE_CURRENT_SELECTION_NAME();
}
allNames.unite(info.GetAccessedPropertyNames());
- return allNames.toList();
+ return allNames.values();
}
void EvaluationAuthority::RefsWithSameExpression(const QList<SmartPointer<EvaluationReference> >& refs)
{
int k = 0;
while (k < refs.size() && !refs[k]->IsPostingChanges())
{
k++;
}
if (k >= refs.size())
{
return;
}
EvaluationReference::Pointer ref = refs[k];
bool oldValue = Evaluate(ref);
ref->ClearResult();
const bool newValue = Evaluate(ref);
if (oldValue != newValue)
{
FirePropertyChange(ref, ValueOf(oldValue), ValueOf(newValue));
}
for (k++; k < refs.size(); k++)
{
ref = refs[k];
// this is not as expensive as it looks
if (ref->IsPostingChanges())
{
oldValue = Evaluate(ref);
if (oldValue != newValue)
{
ref->SetResult(newValue);
FirePropertyChange(ref, ValueOf(oldValue),
ValueOf(newValue));
}
}
}
}
void EvaluationAuthority::StartSourceChange(const QStringList& sourceNames)
{
if (Policy::DEBUG_SOURCES())
{
CommandTracing::PrintTrace(COMPONENT, "start source changed: " + sourceNames.join(", "));
}
notifying++;
if (notifying == 1)
{
FireServiceChange(IEvaluationService::PROP_NOTIFYING, ValueOf(false),
ValueOf(true));
}
}
void EvaluationAuthority::EndSourceChange(const QStringList& sourceNames)
{
if (Policy::DEBUG_SOURCES())
{
CommandTracing::PrintTrace(COMPONENT, "end source changed: " + sourceNames.join(", "));
}
if (notifying == 1)
{
FireServiceChange(IEvaluationService::PROP_NOTIFYING, ValueOf(true),
ValueOf(false));
}
notifying--;
}
void EvaluationAuthority::FirePropertyChange(const SmartPointer<IEvaluationReference>& ref,
Object::Pointer oldValue, Object::Pointer newValue)
{
PropertyChangeEvent::Pointer event(new PropertyChangeEvent(ref, ref->GetProperty(), oldValue,
newValue));
ref->GetListener()->PropertyChange(event);
}
void EvaluationAuthority::FireServiceChange(const QString& property, Object::Pointer oldValue,
Object::Pointer newValue)
{
PropertyChangeEvent::Pointer event(
new PropertyChangeEvent(Object::Pointer(this), property, oldValue, newValue));
serviceListeners.propertyChange(event);
}
void EvaluationAuthority::ServiceChangeException(const std::exception &exc)
{
WorkbenchPlugin::Log(exc.what());
}
Object::Pointer EvaluationAuthority::ValueOf(bool result)
{
return ObjectBool::Pointer(new ObjectBool(result));
}
void EvaluationAuthority::SourceChanged(int /*sourcePriority*/)
{
// no-op, we want the other one
}
void EvaluationAuthority::SourceChanged(const QStringList& sourceNames)
{
struct SourceChangeScope {
EvaluationAuthority* const ea;
const QStringList& sourceNames;
SourceChangeScope(EvaluationAuthority* ea, const QStringList& sourceNames)
: ea(ea), sourceNames(sourceNames)
{
ea->StartSourceChange(sourceNames);
}
~SourceChangeScope()
{
ea->EndSourceChange(sourceNames);
}
};
SourceChangeScope(this, sourceNames);
// evaluations to recompute
for (int i = 0; i < sourceNames.size(); i++)
{
if (cachesBySourceName.contains(sourceNames[i]))
{
const ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]];
QList<QSet<EvaluationReference::Pointer> > expressionCaches = cachesByExpression.values();
for (int j = 0; j < expressionCaches.size(); j++)
{
if (!(expressionCaches[j].isEmpty()))
{
- QList<EvaluationReference::Pointer> refs = expressionCaches[j].toList();
+ QList<EvaluationReference::Pointer> refs = expressionCaches[j].values();
RefsWithSameExpression(refs);
}
}
}
}
}
EvaluationAuthority::EvaluationAuthority()
: serviceExceptionHandler(this, &EvaluationAuthority::ServiceChangeException), notifying(0)
{
serviceListeners.propertyChange.SetExceptionHandler(serviceExceptionHandler);
}
SmartPointer<const Shell> EvaluationAuthority::GetActiveShell() const
{
return GetVariable(ISources::ACTIVE_SHELL_NAME()).Cast<const Shell>();
}
void EvaluationAuthority::AddEvaluationListener(const SmartPointer<IEvaluationReference>& ref)
{
// we update the source priority bucket sort of activations.
QStringList sourceNames = GetNames(ref);
for (int i = 0; i < sourceNames.size(); i++)
{
ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]];
const Expression::Pointer expression = ref->GetExpression();
cachesByExpression[expression].insert(ref.Cast<EvaluationReference>());
}
bool result = Evaluate(ref);
FirePropertyChange(ref, Object::Pointer(nullptr), ValueOf(result));
}
void EvaluationAuthority::RemoveEvaluationListener(const SmartPointer<IEvaluationReference>& ref)
{
// Next we update the source priority bucket sort of activations.
QStringList sourceNames = GetNames(ref);
for (int i = 0; i < sourceNames.size(); i++)
{
if (cachesBySourceName.contains(sourceNames[i]))
{
ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]];
if (cachesByExpression.contains(ref->GetExpression()))
{
QSet<EvaluationReference::Pointer>& caches = cachesByExpression[ref->GetExpression()];
caches.remove(ref.Cast<EvaluationReference>());
if (caches.isEmpty())
{
cachesByExpression.remove(ref->GetExpression());
}
}
if (cachesByExpression.isEmpty())
{
cachesBySourceName.remove(sourceNames[i]);
}
}
}
bool result = Evaluate(ref);
FirePropertyChange(ref, ValueOf(result), Object::Pointer(nullptr));
}
void EvaluationAuthority::AddServiceListener(IPropertyChangeListener* listener)
{
serviceListeners.AddListener(listener);
}
void EvaluationAuthority::RemoveServiceListener(IPropertyChangeListener* listener)
{
serviceListeners.RemoveListener(listener);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp
index c5d902ecfb..92f357e9aa 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp
@@ -1,505 +1,505 @@
/*============================================================================
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 "berryHandlerAuthority.h"
#include "berryISources.h"
#include "berryIServiceLocator.h"
#include "berryIEvaluationService.h"
#include "berryIEvaluationContext.h"
#include "berryIEvaluationReference.h"
#include "berryICommandService.h"
#include "berryIHandler.h"
#include "berryISourceProvider.h"
#include "services/berryISourceProviderService.h"
#include "berryObjects.h"
#include "berryHandlerActivation.h"
#include "berryMultiStatus.h"
#include "berryPlatformUI.h"
#include "berryWorkbenchPlugin.h"
#include "berryCommandTracing.h"
#include "berryCommand.h"
#include "berryEvaluationContext.h"
#include "berryExpression.h"
#include <QTime>
namespace berry {
bool HandlerAuthority::DEBUG = false; // = Policy.DEBUG_HANDLERS;
bool HandlerAuthority::DEBUG_PERFORMANCE = false; // = Policy.DEBUG_HANDLERS_PERFORMANCE;
bool HandlerAuthority::DEBUG_VERBOSE = false; // = Policy.DEBUG_HANDLERS && Policy.DEBUG_HANDLERS_VERBOSE;
QString HandlerAuthority::DEBUG_VERBOSE_COMMAND_ID; // = Policy.DEBUG_HANDLERS_VERBOSE_COMMAND_ID;
const QString HandlerAuthority::TRACING_COMPONENT = "HANDLERS";
const QList<QString> HandlerAuthority::SELECTION_VARIABLES = QList<QString>()
<< ISources::ACTIVE_CURRENT_SELECTION_NAME()
<< ISources::ACTIVE_FOCUS_CONTROL_ID_NAME()
<< ISources::ACTIVE_FOCUS_CONTROL_NAME()
<< ISources::ACTIVE_MENU_EDITOR_INPUT_NAME()
<< ISources::ACTIVE_MENU_NAME()
<< ISources::ACTIVE_MENU_SELECTION_NAME();
class HandlerAuthority::HandlerPropertyListener : public IPropertyChangeListener
{
private:
HandlerAuthority* authority;
HandlerActivation::Pointer handler;
public:
HandlerPropertyListener(HandlerAuthority* authority, const HandlerActivation::Pointer& activation)
: authority(authority)
, handler(activation)
{
handler->SetListener(this);
}
using IPropertyChangeListener::PropertyChange;
void PropertyChange(const PropertyChangeEvent::Pointer& event) override
{
if (handler->GetCommandId() == event->GetProperty())
{
bool val = false;
if (ObjectBool::Pointer boolObj = event->GetNewValue().Cast<ObjectBool>())
{
val = boolObj->GetValue();
}
handler->SetResult(val);
authority->changedCommandIds.insert(handler->GetCommandId());
}
}
};
IEvaluationService* HandlerAuthority::GetEvaluationService() const
{
if (evalService == nullptr)
{
evalService = locator->GetService<IEvaluationService>();
evalService->AddServiceListener(GetServiceListener());
}
return evalService;
}
IPropertyChangeListener* HandlerAuthority::GetServiceListener() const
{
return const_cast<HandlerAuthority*>(this);
}
void HandlerAuthority::PropertyChange(const PropertyChangeEvent::Pointer& event)
{
if (IEvaluationService::PROP_NOTIFYING == event->GetProperty())
{
if (ObjectBool::Pointer boolObj = event->GetNewValue().Cast<ObjectBool>())
{
bool startNotifying = boolObj->GetValue();
if (startNotifying)
{
changedCommandIds.clear();
}
else
{
ProcessChangedCommands();
}
}
}
}
HandlerAuthority::HandlerAuthority(ICommandService* commandService,
IServiceLocator* locator)
: commandService(commandService)
, locator(locator)
, evalService(nullptr)
{
if (commandService == nullptr)
{
throw ctkInvalidArgumentException("The handler authority needs a command service");
}
}
HandlerAuthority::~HandlerAuthority()
{
GetEvaluationService()->RemoveServiceListener(GetServiceListener());
}
void HandlerAuthority::ActivateHandler(const SmartPointer<IHandlerActivation>& activation)
{
const HandlerActivation::Pointer handler = activation.Cast<HandlerActivation>();
// First we update the handlerActivationsByCommandId map.
const QString commandId = handler->GetCommandId();
MultiStatus::Pointer conflicts(
new MultiStatus(PlatformUI::PLUGIN_ID(), 0,
"A handler conflict occurred. This may disable some commands.",
BERRY_STATUS_LOC)
);
IdToHandlerActivationMap::mapped_type& handlerActivations = handlerActivationsByCommandId[commandId];
handlerActivations.insert(handler, Empty());
if (handler->GetExpression().IsNotNull())
{
auto l = new HandlerPropertyListener(this, handler);
handler->SetReference(GetEvaluationService()->AddEvaluationListener(
handler->GetExpression(), l,
handler->GetCommandId()));
}
if (handlerActivations.size() > 1)
{
UpdateCommand(commandId, ResolveConflicts(commandId, handlerActivations, conflicts));
}
else
{
UpdateCommand(commandId, (Evaluate(handler) ? handler : HandlerActivation::Pointer(nullptr)));
}
if (conflicts->GetSeverity() != IStatus::OK_TYPE)
{
WorkbenchPlugin::Log(conflicts);
}
}
void HandlerAuthority::DeactivateHandler(const SmartPointer<IHandlerActivation>& activation)
{
const HandlerActivation::Pointer handler = activation.Cast<HandlerActivation>();
// First we update the handlerActivationsByCommandId map.
const QString commandId = handler->GetCommandId();
MultiStatus::Pointer conflicts(
new MultiStatus("org.blueberry.ui", 0, "A handler conflict occurred. This may disable some commands.", BERRY_STATUS_LOC));
IdToHandlerActivationMap::iterator value = handlerActivationsByCommandId.find(commandId);
if (value != handlerActivationsByCommandId.end())
{
IdToHandlerActivationMap::mapped_type& handlerActivations = value.value();
if (handlerActivations.remove(handler) > 0)
{
if (handler->GetReference().IsNotNull())
{
GetEvaluationService()->RemoveEvaluationListener(handler->GetReference());
handler->SetReference(IEvaluationReference::Pointer(nullptr));
handler->SetListener(nullptr);
}
if (handlerActivations.isEmpty())
{
handlerActivationsByCommandId.remove(commandId);
UpdateCommand(commandId, IHandlerActivation::Pointer(nullptr));
}
else if (handlerActivations.size() == 1)
{
IHandlerActivation::Pointer remainingActivation = handlerActivations.begin().key();
UpdateCommand(commandId, (Evaluate(remainingActivation) ? remainingActivation : IHandlerActivation::Pointer(nullptr)));
}
else
{
UpdateCommand(commandId, ResolveConflicts(commandId, handlerActivations, conflicts));
}
}
}
if (conflicts->GetSeverity() != IStatus::OK_TYPE)
{
WorkbenchPlugin::Log(conflicts);
}
}
SmartPointer<IHandlerActivation> HandlerAuthority::ResolveConflicts(
const QString& commandId,
const QMap<SmartPointer<HandlerActivation>,Empty>& activations,
SmartPointer<MultiStatus> conflicts)
{
// If we don't have any, then there is no match.
if (activations.isEmpty())
{
return IHandlerActivation::Pointer(nullptr);
}
// Cycle over the activations, remembered the current best.
QMapIterator<HandlerActivation::Pointer,Empty> activationItr(activations);
HandlerActivation::Pointer bestActivation;
HandlerActivation::Pointer currentActivation;
bool conflict = false;
while (activationItr.hasNext())
{
currentActivation = activationItr.next().key();
if (!Evaluate(currentActivation))
{
continue; // only consider potentially active handlers
}
// Check to see if we haven't found a potentially active handler yet
if ((DEBUG_VERBOSE) && ((DEBUG_VERBOSE_COMMAND_ID.isNull()) ||
(DEBUG_VERBOSE_COMMAND_ID == commandId)))
{
CommandTracing::PrintTrace(TRACING_COMPONENT,
" resolveConflicts: eval: " + currentActivation->ToString());
}
if (bestActivation.IsNull())
{
bestActivation = currentActivation;
conflict = false;
continue;
}
// Compare the two handlers.
int comparison = bestActivation->CompareTo(currentActivation.GetPointer());
if (comparison < 0)
{
bestActivation = currentActivation;
conflict = false;
}
else if (comparison == 0)
{
if (currentActivation->GetHandler() != bestActivation->GetHandler())
{
conflict = true;
break;
}
}
else
{
break;
}
}
// If we are logging information, now is the time to do it.
if (DEBUG)
{
if (conflict)
{
CommandTracing::PrintTrace(TRACING_COMPONENT,
"Unresolved conflict detected for '" + commandId + '\'');
}
else if ((bestActivation.IsNotNull()) && (DEBUG_VERBOSE) &&
((DEBUG_VERBOSE_COMMAND_ID.isNull()) || (DEBUG_VERBOSE_COMMAND_ID == commandId)))
{
CommandTracing::PrintTrace(TRACING_COMPONENT,
"Resolved conflict detected. The following activation won: ");
CommandTracing::PrintTrace(TRACING_COMPONENT, " " + bestActivation->ToString());
}
}
// Return the current best.
if (conflict)
{
if (!previousLogs.contains(commandId))
{
previousLogs.insert(commandId);
QString str;
QDebug dbg(&str);
dbg << "Conflict for" << commandId << ":";
dbg << bestActivation->ToString();
dbg << currentActivation->ToString();
IStatus::Pointer s(new Status(IStatus::WARNING_TYPE, "org.blueberry.ui", str, BERRY_STATUS_LOC));
conflicts->Add(s);
}
return IHandlerActivation::Pointer(nullptr);
}
return bestActivation;
}
void HandlerAuthority::UpdateCommand(const QString& commandId,
const SmartPointer<IHandlerActivation>& activation)
{
const Command::Pointer command = commandService->GetCommand(commandId);
if (activation.IsNull())
{
command->SetHandler(IHandler::Pointer(nullptr));
}
else
{
command->SetHandler(activation->GetHandler());
commandService->RefreshElements(commandId, QHash<QString, Object::Pointer>());
}
}
SmartPointer<IHandler> HandlerAuthority::FindHandler(const QString& commandId,
IEvaluationContext* context)
{
IdToHandlerActivationMap::mapped_type activations = handlerActivationsByCommandId.value(commandId);
IHandlerActivation::Pointer lastActivation;
IHandlerActivation::Pointer currentActivation;
QMapIterator<HandlerActivation::Pointer,Empty> i(activations);
while (i.hasNext() && lastActivation.IsNull())
{
HandlerActivation::Pointer activation = i.next().key();
try
{
if (Eval(context, activation))
{
lastActivation = currentActivation;
currentActivation = activation;
}
}
catch (const CoreException&)
{
// OK, this one is out of the running
}
}
if (currentActivation.IsNotNull())
{
if (lastActivation.IsNull())
{
return currentActivation->GetHandler();
}
if (lastActivation->GetSourcePriority() != currentActivation->GetSourcePriority())
{
return lastActivation->GetHandler();
}
}
return IHandler::Pointer(nullptr);
}
IEvaluationContext::Pointer HandlerAuthority::CreateContextSnapshot(bool includeSelection)
{
IEvaluationContext::Pointer tmpContext = GetCurrentState();
EvaluationContext::Pointer context;
if (includeSelection)
{
context = new EvaluationContext(nullptr, tmpContext->GetDefaultVariable());
for (int i = 0; i < SELECTION_VARIABLES.size(); i++)
{
CopyVariable(context.GetPointer(), tmpContext.GetPointer(), SELECTION_VARIABLES[i]);
}
}
else
{
context = new EvaluationContext(nullptr, Object::Pointer(nullptr));
}
ISourceProviderService* sp = locator->GetService<ISourceProviderService>();
QList<ISourceProvider::Pointer> providers = sp->GetSourceProviders();
for (int i = 0; i < providers.size(); i++)
{
QList<QString> names = providers[i]->GetProvidedSourceNames();
for (int j = 0; j < names.size(); j++)
{
if (!IsSelectionVariable(names[j]))
{
CopyVariable(context.GetPointer(), tmpContext.GetPointer(), names[j]);
}
}
}
return context;
}
bool HandlerAuthority::Eval(IEvaluationContext* context,
const SmartPointer<IHandlerActivation>& activation)
{
Expression::Pointer expression = activation->GetExpression();
if (expression.IsNull())
{
return true;
}
return expression->Evaluate(context) == EvaluationResult::TRUE_EVAL;
}
bool HandlerAuthority::IsSelectionVariable(const QString& name)
{
for (int i = 0; i < SELECTION_VARIABLES.size(); i++)
{
if (SELECTION_VARIABLES[i] == name)
{
return true;
}
}
return false;
}
void HandlerAuthority::CopyVariable(IEvaluationContext* context,
IEvaluationContext* tmpContext, const QString& var)
{
Object::ConstPointer o = tmpContext->GetVariable(var);
if (o.IsNotNull())
{
context->AddVariable(var, o);
}
}
void HandlerAuthority::ProcessChangedCommands()
{
// If tracing, then track how long it takes to process the activations.
- QTime startTime;
+ QElapsedTimer timer;
if (DEBUG_PERFORMANCE)
{
- startTime.start();
+ timer.start();
}
MultiStatus::Pointer conflicts(
new MultiStatus("org.blueberry.ui", 0,
"A handler conflict occurred. This may disable some commands.", BERRY_STATUS_LOC));
/*
* For every command identifier with a changed activation, we resolve
* conflicts and trigger an update.
*/
const QSet<QString> changedIds = changedCommandIds;
changedCommandIds.clear();
foreach(const QString& commandId, changedIds)
{
IdToHandlerActivationMap::mapped_type activations = handlerActivationsByCommandId.value(commandId);
if (activations.size() == 1)
{
const IHandlerActivation::Pointer activation = activations.begin().key();
UpdateCommand(commandId, (Evaluate(activation) ? activation : IHandlerActivation::Pointer(nullptr)));
}
else
{
const IHandlerActivation::Pointer activation = ResolveConflicts(
commandId, activations, conflicts);
UpdateCommand(commandId, activation);
}
}
if (conflicts->GetSeverity() != IStatus::OK_TYPE)
{
WorkbenchPlugin::Log(conflicts);
}
// If tracing performance, then print the results.
if (DEBUG_PERFORMANCE)
{
- const int elapsedTime = startTime.elapsed();
+ const int elapsedTime = timer.elapsed();
const int size = changedCommandIds.size();
if (size > 0)
{
- CommandTracing::PrintTrace(TRACING_COMPONENT, QString::number(size) + " command ids changed in " + elapsedTime + "ms");
+ CommandTracing::PrintTrace(TRACING_COMPONENT, QString("%1 command ids changed in %2 ms").arg(size).arg(elapsedTime));
}
}
}
bool HandlerAuthority::Evaluate(const SmartPointer<IEvaluationResultCache>& expression)
{
IEvaluationContext::Pointer contextWithDefaultVariable = GetCurrentState();
return expression->Evaluate(contextWithDefaultVariable.GetPointer());
}
SmartPointer<IEvaluationContext> HandlerAuthority::GetCurrentState() const
{
return GetEvaluationService()->GetCurrentState();
}
//void HandlerAuthority::UpdateShellKludge()
//{
// ((EvaluationService) getEvaluationService()).updateShellKludge();
//}
//void HandlerAuthority::UpdateShellKludge(const SmartPointer<Shell>& shell)
//{
// ((EvaluationService) getEvaluationService()).updateShellKludge(shell);
//}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp
index bea2f397df..c18a6cccea 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp
@@ -1,88 +1,88 @@
/*============================================================================
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 "berryKeywordRegistry.h"
#include "berryIConfigurationElement.h"
#include "berryIExtension.h"
#include "berryIExtensionPoint.h"
#include "berryIExtensionPointFilter.h"
#include "berryIExtensionRegistry.h"
#include "berryExtensionTracker.h"
#include "berryObjectString.h"
#include "berryPlatform.h"
#include "berryPlatformUI.h"
#include "berryWorkbenchRegistryConstants.h"
namespace berry {
const QString KeywordRegistry::ATT_ID = "id";
const QString KeywordRegistry::ATT_LABEL = "label";
const QString KeywordRegistry::TAG_KEYWORD = "keyword";
KeywordRegistry::KeywordRegistry()
{
IExtensionTracker* tracker = PlatformUI::GetWorkbench()->GetExtensionTracker();
tracker->RegisterHandler(this, ExtensionTracker::CreateExtensionPointFilter(GetExtensionPointFilter()));
QList<IExtension::Pointer> extensions = GetExtensionPointFilter()->GetExtensions();
for (auto& extension : extensions)
{
AddExtension(tracker, extension);
}
}
SmartPointer<IExtensionPoint> KeywordRegistry::GetExtensionPointFilter() const
{
return Platform::GetExtensionRegistry()->GetExtensionPoint(
PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_KEYWORDS);
}
KeywordRegistry*KeywordRegistry::GetInstance()
{
static KeywordRegistry instance;
return &instance;
}
void KeywordRegistry::AddExtension(IExtensionTracker* tracker, const SmartPointer<IExtension>& extension)
{
for (const auto &element : extension->GetConfigurationElements())
{
if (element->GetName() == TAG_KEYWORD)
{
QString name = element->GetAttribute(ATT_LABEL);
QString id = element->GetAttribute(ATT_ID);
internalKeywordMap.insert(id, name);
Object::Pointer trackedObject(new ObjectString(id));
tracker->RegisterObject(extension, trackedObject, IExtensionTracker::REF_STRONG);
}
}
}
QString KeywordRegistry::GetKeywordLabel(const QString& id)
{
auto it = internalKeywordMap.find(id);
- return it == internalKeywordMap.end() ? QString::null : *it;
+ return it == internalKeywordMap.end() ? QString() : *it;
}
void KeywordRegistry::RemoveExtension(const SmartPointer<IExtension>& /*extension*/, const QList<SmartPointer<Object> >& objects)
{
for (const auto &object : objects)
{
if (ObjectString::Pointer objString = object.Cast<ObjectString>())
{
internalKeywordMap.remove(*objString);
}
}
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp
index 00d07f3fc2..fcfad52895 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp
@@ -1,81 +1,81 @@
/*============================================================================
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 "berryNestableHandlerService.h"
#include "berryExpression.h"
#include "berryIHandlerActivation.h"
#include "berryISourceProvider.h"
namespace berry {
NestableHandlerService::NestableHandlerService(IHandlerService* parentHandlerService,
const SmartPointer<Expression>& defaultExpression)
: SlaveHandlerService(parentHandlerService, defaultExpression)
, active(false)
{
}
void NestableHandlerService::Activate()
{
if (active)
{
return;
}
QList<IHandlerActivation::Pointer> localActivations = localActivationsToParentActivations.keys();
for (int i = 0; i < localActivations.size(); i++)
{
// Ignore activations that have been cleared since the copy
// was made.
if (localActivationsToParentActivations.contains(localActivations[i]))
{
SlaveHandlerService::DoActivation(localActivations[i]);
}
}
active = true;
}
void NestableHandlerService::Deactivate()
{
if (!active)
{
return;
}
- DeactivateHandlers(parentActivations.toList());
+ DeactivateHandlers(parentActivations.values());
parentActivations.clear();
QList<IHandlerActivation::Pointer> localActivations = localActivationsToParentActivations.keys();
for (int i = 0; i < localActivations.size(); i++)
{
if (localActivationsToParentActivations.contains(localActivations[i]))
{
localActivationsToParentActivations.insert(localActivations[i], nullptr);
}
}
active = false;
}
SmartPointer<IHandlerActivation> NestableHandlerService::DoActivation(
const SmartPointer<IHandlerActivation>& localActivation)
{
if (active)
{
return SlaveHandlerService::DoActivation(localActivation);
}
localActivationsToParentActivations.insert(localActivation, nullptr);
return localActivation;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspective.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspective.cpp
index ae868a8d1f..e058aaad62 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspective.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspective.cpp
@@ -1,1807 +1,1807 @@
/*============================================================================
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 "tweaklets/berryGuiWidgetsTweaklet.h"
#include "berryPerspective.h"
#include "berryPerspectiveHelper.h"
#include "berryWorkbenchPlugin.h"
#include "berryWorkbenchConstants.h"
#include "berryPerspectiveExtensionReader.h"
#include "berryEditorSashContainer.h"
#include "berryPartSite.h"
#include "berryViewSite.h"
#include "berryEditorAreaHelper.h"
#include "intro/berryIntroConstants.h"
#include "berryWorkbenchWindow.h"
#include "berryStatusUtil.h"
#include "berryMultiStatus.h"
#include "berryXMLMemento.h"
#include "presentations/berryIStackPresentationSite.h"
#include "berryIContextService.h"
#include <QMessageBox>
namespace berry
{
const QString Perspective::VERSION_STRING = "0.016";
Perspective::Perspective(PerspectiveDescriptor::Pointer desc,
WorkbenchPage::Pointer page)
: descriptor(desc)
{
this->Register();
this->Init(page);
if (desc.IsNotNull())
{
this->CreatePresentation(desc);
}
this->UnRegister(false);
}
Perspective::Perspective(WorkbenchPage::Pointer page)
{
this->Init(page);
}
void Perspective::Init(WorkbenchPage::Pointer page)
{
editorHidden = false;
editorAreaState = IStackPresentationSite::STATE_RESTORED;
fixed = false;
presentation = nullptr;
shouldHideEditorsOnActivate = false;
this->page = page.GetPointer();
this->editorArea = page->GetEditorPresentation()->GetLayoutPart();
this->viewFactory = page->GetViewFactory();
}
bool Perspective::BringToTop(IViewReference::Pointer ref)
{
return presentation->BringPartToTop(this->GetPane(ref));
}
bool Perspective::ContainsView(IViewPart::Pointer view)
{
IViewSite::Pointer site = view->GetViewSite();
IViewReference::Pointer ref = this->FindView(site->GetId(), site->GetSecondaryId());
if (ref.IsNull())
{
return false;
}
return (view.Cast<IWorkbenchPart>() == ref->GetPart(false));
}
bool Perspective::ContainsView(const QString& viewId) const
{
return mapIDtoViewLayoutRec.contains(viewId);
}
void Perspective::CreatePresentation(PerspectiveDescriptor::Pointer persp)
{
if (persp->HasCustomDefinition())
{
this->LoadCustomPersp(persp);
}
else
{
this->LoadPredefinedPersp(persp);
}
}
Perspective::~Perspective()
{
// Get rid of presentation.
if (presentation == nullptr)
{
DisposeViewRefs();
return;
}
presentation->Deactivate();
// Release each view.
QList<IViewReference::Pointer> refs(this->GetViewReferences());
for (auto & ref : refs)
{
this->GetViewFactory()->ReleaseView(ref);
}
mapIDtoViewLayoutRec.clear();
delete presentation;
}
void Perspective::DisposeViewRefs()
{
if (!memento)
{
return;
}
QList<IMemento::Pointer> views(memento->GetChildren(WorkbenchConstants::TAG_VIEW));
for (int x = 0; x < views.size(); x++)
{
// Get the view details.
IMemento::Pointer childMem = views[x];
QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id);
// skip creation of the intro reference - it's handled elsewhere.
if (id == IntroConstants::INTRO_VIEW_ID)
{
continue;
}
QString secondaryId = ViewFactory::ExtractSecondaryId(id);
if (!secondaryId.isEmpty())
{
id = ViewFactory::ExtractPrimaryId(id);
}
QString removed;
childMem->GetString(WorkbenchConstants::TAG_REMOVED, removed);
if (removed != "true")
{
IViewReference::Pointer ref = viewFactory->GetView(id, secondaryId);
if (ref)
{
viewFactory->ReleaseView(ref);
}
}
}
}
IViewReference::Pointer Perspective::FindView(const QString& viewId)
{
return this->FindView(viewId, "");
}
IViewReference::Pointer Perspective::FindView(const QString& id, const QString& secondaryId)
{
QList<IViewReference::Pointer> refs(this->GetViewReferences());
for (int i = 0; i < refs.size(); i++)
{
IViewReference::Pointer ref = refs[i];
if (id == ref->GetId()
&& (secondaryId == ref->GetSecondaryId()))
{
return ref;
}
}
return IViewReference::Pointer(nullptr);
}
QWidget* Perspective::GetClientComposite()
{
return page->GetClientComposite();
}
IPerspectiveDescriptor::Pointer Perspective::GetDesc()
{
return descriptor;
}
PartPane::Pointer Perspective::GetPane(IViewReference::Pointer ref)
{
return ref.Cast<WorkbenchPartReference>()->GetPane();
}
QList<QString> Perspective::GetPerspectiveShortcuts()
{
return perspectiveShortcuts;
}
PerspectiveHelper* Perspective::GetPresentation() const
{
return presentation;
}
QList<QString> Perspective::GetShowViewShortcuts()
{
return showViewShortcuts;
}
ViewFactory* Perspective::GetViewFactory()
{
return viewFactory;
}
QList<IViewReference::Pointer> Perspective::GetViewReferences()
{
// Get normal views.
if (presentation == nullptr)
{
return QList<IViewReference::Pointer>();
}
QList<PartPane::Pointer> panes;
presentation->CollectViewPanes(panes);
QList<IViewReference::Pointer> result;
// List fastViews = (fastViewManager != 0) ?
// fastViewManager.getFastViews(0)
// : new ArrayList();
// IViewReference[] resultArray = new IViewReference[panes.size()
// + fastViews.size()];
//
// // Copy fast views.
// int nView = 0;
// for (int i = 0; i < fastViews.size(); i++)
// {
// resultArray[nView] = (IViewReference) fastViews.get(i);
// ++nView;
// }
// Copy normal views.
for (QList<PartPane::Pointer>::iterator iter = panes.begin();
iter != panes.end(); ++iter)
{
PartPane::Pointer pane = *iter;
result.push_back(pane->GetPartReference().Cast<IViewReference>());
}
return result;
}
void Perspective::HideEditorArea()
{
if (!this->IsEditorAreaVisible())
{
return;
}
// Show the editor in the appropriate location
if (this->UseNewMinMax(Perspective::Pointer(this)))
{
// If it's the currently maximized part we have to restore first
// if (this->GetPresentation().getMaximizedStack().Cast<EditorStack>() != 0)
// {
// getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED);
// }
bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED;
if (!isMinimized)
this->HideEditorAreaLocal();
//else
// this->SetEditorAreaTrimVisibility(false);
}
else
{
this->HideEditorAreaLocal();
}
editorHidden = true;
}
void Perspective::HideEditorAreaLocal()
{
if (editorHolder != 0)
{
return;
}
// Replace the editor area with a placeholder so we
// know where to put it back on show editor area request.
editorHolder = new PartPlaceholder(editorArea->GetID());
presentation->GetLayout()->Replace(editorArea, editorHolder);
}
bool Perspective::HideView(IViewReference::Pointer ref)
{
// If the view is locked just return.
PartPane::Pointer pane = this->GetPane(ref);
presentation->RemovePart(pane);
// Dispose view if ref count == 0.
this->GetViewFactory()->ReleaseView(ref);
return true;
}
bool Perspective::IsEditorAreaVisible()
{
return !editorHidden;
}
ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(IViewReference::Pointer ref, bool create)
{
ViewLayoutRec::Pointer result = this->GetViewLayoutRec(ViewFactory::GetKey(ref), create);
if (result.IsNull() && create==false)
{
result = this->GetViewLayoutRec(ref->GetId(), false);
}
return result;
}
ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(const QString& viewId, bool create)
{
ViewLayoutRec::Pointer rec = mapIDtoViewLayoutRec[viewId];
if (rec.IsNull() && create)
{
rec = new ViewLayoutRec();
mapIDtoViewLayoutRec[viewId] = rec;
}
return rec;
}
bool Perspective::IsFixedLayout()
{
//@issue is there a difference between a fixed
//layout and a fixed perspective?? If not the API
//may need some polish, WorkbenchPage, PageLayout
//and Perspective all have isFixed methods.
//PageLayout and Perspective have their own fixed
//attribute, we are assuming they are always in sync.
//WorkbenchPage delegates to the perspective.
return fixed;
}
bool Perspective::IsStandaloneView(IViewReference::Pointer ref)
{
ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false);
return rec.IsNotNull() && rec->isStandalone;
}
bool Perspective::GetShowTitleView(IViewReference::Pointer ref)
{
ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false);
return rec.IsNotNull() && rec->showTitle;
}
void Perspective::LoadCustomPersp(PerspectiveDescriptor::Pointer persp)
{
//get the layout from the registry
PerspectiveRegistry* perspRegistry = dynamic_cast<PerspectiveRegistry*>(WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry());
try
{
IMemento::Pointer memento = perspRegistry->GetCustomPersp(persp->GetId());
// Restore the layout state.
// MultiStatus status = new MultiStatus(
// PlatformUI.PLUGIN_ID,
// IStatus.OK,
// NLS.bind(WorkbenchMessages.Perspective_unableToRestorePerspective, persp.getLabel()),
// 0);
// status.merge(restoreState(memento));
// status.merge(restoreState());
bool okay = true;
okay &= this->RestoreState(memento);
okay &= this->RestoreState();
if (!okay)
{
this->UnableToOpenPerspective(persp, "Unable to open perspective: " + persp->GetLabel());
}
}
//catch (IOException e)
//{
// unableToOpenPerspective(persp, 0);
//}
catch (const WorkbenchException& e)
{
this->UnableToOpenPerspective(persp, e.what());
}
}
void Perspective::UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp,
const QString& status)
{
PerspectiveRegistry* perspRegistry = dynamic_cast<PerspectiveRegistry*>(WorkbenchPlugin
::GetDefault()->GetPerspectiveRegistry());
perspRegistry->DeletePerspective(persp);
// If this is a predefined perspective, we will not be able to delete
// the perspective (we wouldn't want to). But make sure to delete the
// customized portion.
persp->DeleteCustomDefinition();
QString title = "Restoring problems";
QString msg = "Unable to read workbench state.";
if (status == "")
{
QMessageBox::critical(nullptr, title, msg);
}
else
{
//TODO error dialog
//ErrorDialog.openError((Shell) 0, title, msg, status);
QMessageBox::critical(nullptr, title, msg + "\n" + status);
}
}
void Perspective::LoadPredefinedPersp(PerspectiveDescriptor::Pointer persp)
{
// Create layout engine.
IPerspectiveFactory::Pointer factory;
try
{
factory = persp->CreateFactory();
}
catch (CoreException& /*e*/)
{
throw WorkbenchException("Unable to load perspective: " + persp->GetId());
}
/*
* IPerspectiveFactory#createFactory() can return 0
*/
if (factory == 0)
{
throw WorkbenchException("Unable to load perspective: " + persp->GetId());
}
// Create layout factory.
ViewSashContainer::Pointer container(new ViewSashContainer(page, this->GetClientComposite()));
layout = new PageLayout(container, this->GetViewFactory(),
editorArea, descriptor);
layout->SetFixed(descriptor->GetFixed());
// // add the placeholders for the sticky folders and their contents
IPlaceholderFolderLayout::Pointer stickyFolderRight, stickyFolderLeft, stickyFolderTop, stickyFolderBottom;
QList<IStickyViewDescriptor::Pointer> descs(WorkbenchPlugin::GetDefault()
->GetViewRegistry()->GetStickyViews());
for (int i = 0; i < descs.size(); i++)
{
IStickyViewDescriptor::Pointer stickyViewDescriptor = descs[i];
QString id = stickyViewDescriptor->GetId();
int location = stickyViewDescriptor->GetLocation();
if (location == IPageLayout::RIGHT)
{
if (stickyFolderRight == 0)
{
stickyFolderRight = layout
->CreatePlaceholderFolder(
StickyViewDescriptor::STICKY_FOLDER_RIGHT,
IPageLayout::RIGHT, .75f,
IPageLayout::ID_EDITOR_AREA);
}
stickyFolderRight->AddPlaceholder(id);
}
else if (location == IPageLayout::LEFT)
{
if (stickyFolderLeft == 0)
{
stickyFolderLeft = layout->CreatePlaceholderFolder(
StickyViewDescriptor::STICKY_FOLDER_LEFT,
IPageLayout::LEFT, .25f, IPageLayout::ID_EDITOR_AREA);
}
stickyFolderLeft->AddPlaceholder(id);
}
else if (location == IPageLayout::TOP)
{
if (stickyFolderTop == 0)
{
stickyFolderTop = layout->CreatePlaceholderFolder(
StickyViewDescriptor::STICKY_FOLDER_TOP,
IPageLayout::TOP, .25f, IPageLayout::ID_EDITOR_AREA);
}
stickyFolderTop->AddPlaceholder(id);
}
else if (location == IPageLayout::BOTTOM)
{
if (stickyFolderBottom == 0)
{
stickyFolderBottom = layout->CreatePlaceholderFolder(
StickyViewDescriptor::STICKY_FOLDER_BOTTOM,
IPageLayout::BOTTOM, .75f,
IPageLayout::ID_EDITOR_AREA);
}
stickyFolderBottom->AddPlaceholder(id);
}
//should never be 0 as we've just added the view above
IViewLayout::Pointer viewLayout = layout->GetViewLayout(id);
viewLayout->SetCloseable(stickyViewDescriptor->IsCloseable());
viewLayout->SetMoveable(stickyViewDescriptor->IsMoveable());
}
// Run layout engine.
factory->CreateInitialLayout(layout);
PerspectiveExtensionReader extender;
extender.ExtendLayout(page->GetExtensionTracker(), descriptor->GetId(), layout);
// Retrieve view layout info stored in the page layout.
QHash<QString, ViewLayoutRec::Pointer> layoutInfo = layout->GetIDtoViewLayoutRecMap();
- mapIDtoViewLayoutRec.unite(layoutInfo);
+ mapIDtoViewLayoutRec.insert(layoutInfo);
//TODO Perspective action sets
// Create action sets.
//List temp = new ArrayList();
//this->CreateInitialActionSets(temp, layout.getActionSets());
// IContextService* service = 0;
// if (page != 0)
// {
// service = page->GetWorkbenchWindow()->GetService<IContextService>();
// }
// try
// {
// if (service != 0)
// {
// service->DeferUpdates(true);
// }
// for (Iterator iter = temp.iterator(); iter.hasNext();)
// {
// IActionSetDescriptor descriptor = (IActionSetDescriptor) iter
// .next();
// addAlwaysOn(descriptor);
// }
// }finally
// {
// if (service!=0)
// {
// service.activateContext(ContextAuthority.SEND_EVENTS);
// }
// }
// newWizardShortcuts = layout.getNewWizardShortcuts();
showViewShortcuts = layout->GetShowViewShortcuts();
perspectiveShortcuts = layout->GetPerspectiveShortcuts();
showInPartIds = layout->GetShowInPartIds();
// // Retrieve fast views
// if (fastViewManager != 0)
// {
// ArrayList fastViews = layout.getFastViews();
// for (Iterator fvIter = fastViews.iterator(); fvIter.hasNext();)
// {
// IViewReference ref = (IViewReference) fvIter.next();
// fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref,
// !fvIter.hasNext());
// }
// }
// Is the layout fixed
fixed = layout->IsFixed();
showViewShortcuts = layout->GetShowViewShortcuts();
// Create presentation.
presentation = new PerspectiveHelper(page, container, this);
// Hide editor area if requested by factory
if (!layout->IsEditorAreaVisible())
{
this->HideEditorArea();
}
}
void Perspective::OnActivate()
{
// Update editor area state.
if (editorArea->GetControl() != nullptr)
{
bool visible = this->IsEditorAreaVisible();
bool inTrim = editorAreaState == IStackPresentationSite::STATE_MINIMIZED;
editorArea->SetVisible(visible && !inTrim);
}
// // Update fast views.
// // Make sure the control for the fastviews are created so they can
// // be activated.
// if (fastViewManager != 0)
// {
// List fastViews = fastViewManager.getFastViews(0);
// for (int i = 0; i < fastViews.size(); i++)
// {
// ViewPane pane = getPane((IViewReference) fastViews.get(i));
// if (pane != 0)
// {
// Control ctrl = pane.getControl();
// if (ctrl == 0)
// {
// pane.createControl(getClientComposite());
// ctrl = pane.getControl();
// }
// ctrl.setEnabled(false); // Remove focus support.
// }
// }
// }
// // Set the visibility of all fast view pins
// setAllPinsVisible(true);
// Trim Stack Support
bool useNewMinMax = Perspective::UseNewMinMax(Perspective::Pointer(this));
bool hideEditorArea = shouldHideEditorsOnActivate || (editorHidden && editorHolder == 0);
// We have to set the editor area's stack state -before-
// activating the presentation since it's used there to determine
// size of the resulting stack
if (useNewMinMax && !hideEditorArea)
{
this->RefreshEditorAreaVisibility();
}
// Show the layout
presentation->Activate(this->GetClientComposite());
// if (useNewMinMax)
// {
// fastViewManager.activate();
//
// // Move any minimized extension stacks to the trim
// if (layout != 0)
// {
// // Turn aimations off
// IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
// bool useAnimations = preferenceStore
// .getbool(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS);
// preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, false);
//
// List minStacks = layout.getMinimizedStacks();
// for (Iterator msIter = minStacks.iterator(); msIter.hasNext();)
// {
// ViewStack vs = (ViewStack) msIter.next();
// vs.setMinimized(true);
// }
//
// // Restore the animation pref
// preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, useAnimations);
//
// // this is a one-off deal...set during the extension reading
// minStacks.clear();
// layout = 0;
// }
// }
// else
// {
// // Update the FVB only if not using the new min/max
//
// // WorkbenchWindow wbw = (WorkbenchWindow) page.getWorkbenchWindow();
//// if (wbw != 0)
//// {
//// ITrimManager tbm = wbw.getTrimManager();
//// if (tbm != 0)
//// {
//// IWindowTrim fvb = tbm.getTrim(FastViewBar.FASTVIEWBAR_ID);
//// if (fvb instanceof FastViewBar)
//// {
//// ((FastViewBar)fvb).update(true);
//// }
//// }
//// }
// }
// // If we are -not- using the new min/max then ensure that there
// // are no stacks in the trim. This can happen when a user switches
// // back to the 3.0 presentation...
// if (!Perspective.useNewMinMax(this) && fastViewManager != 0)
// {
// bool stacksWereRestored = fastViewManager.restoreAllTrimStacks();
// setEditorAreaTrimVisibility(false);
//
// // Restore any 'maximized' view stack since we've restored
// // the minimized stacks
// if (stacksWereRestored && presentation.getMaximizedStack().Cast<ViewStack>() != 0)
// {
// ViewStack vs = (ViewStack) presentation.getMaximizedStack();
// vs.setPresentationState(IStackPresentationSite.STATE_RESTORED);
// presentation.setMaximizedStack(0);
// }
// }
// We hide the editor area -after- the presentation activates
if (hideEditorArea)
{
// We do this here to ensure that createPartControl is called on the
// top editor
// before it is hidden. See bug 20166.
this->HideEditorArea();
shouldHideEditorsOnActivate = false;
// // this is an override so it should handle both states
// if (useNewMinMax)
// setEditorAreaTrimVisibility(editorAreaState == IStackPresentationSite.STATE_MINIMIZED);
}
// Fix perspectives whose contributing bundle has gone away
FixOrphan();
}
void Perspective::FixOrphan()
{
PerspectiveRegistry* reg = static_cast<PerspectiveRegistry*>(PlatformUI::GetWorkbench()->GetPerspectiveRegistry());
IPerspectiveDescriptor::Pointer regDesc = reg->FindPerspectiveWithId(descriptor->GetId());
if (regDesc.IsNull())
{
QString msg = "Perspective " + descriptor->GetLabel() + " has been made into a local copy";
IStatus::Pointer status = StatusUtil::NewStatus(IStatus::WARNING_TYPE, msg, BERRY_STATUS_LOC);
//StatusManager.getManager().handle(status, StatusManager.LOG);
WorkbenchPlugin::Log(status);
QString localCopyLabel("<%1>");
QString newDescId = localCopyLabel.arg(descriptor->GetLabel());
while (reg->FindPerspectiveWithId(newDescId).IsNotNull())
{
newDescId = localCopyLabel.arg(newDescId);
}
IPerspectiveDescriptor::Pointer newDesc = reg->CreatePerspective(newDescId, descriptor);
page->SavePerspectiveAs(newDesc);
}
}
void Perspective::OnDeactivate()
{
presentation->Deactivate();
//setActiveFastView(0);
//setAllPinsVisible(false);
// // Update fast views.
// if (fastViewManager != 0)
// {
// List fastViews = fastViewManager.getFastViews(0);
// for (int i = 0; i < fastViews.size(); i++)
// {
// ViewPane pane = getPane((IViewReference) fastViews.get(i));
// if (pane != 0)
// {
// Control ctrl = pane.getControl();
// if (ctrl != 0)
// {
// ctrl.setEnabled(true); // Add focus support.
// }
// }
// }
//
// fastViewManager.deActivate();
// }
//
// // Ensure that the editor area trim is hidden as well
// setEditorAreaTrimVisibility(false);
}
void Perspective::PartActivated(IWorkbenchPart::Pointer /*activePart*/)
{
// // If a fastview is open close it.
// if (activeFastView != 0
// && activeFastView.getPart(false) != activePart)
// {
// setActiveFastView(0);
// }
}
void Perspective::PerformedShowIn(const QString& /*partId*/)
{
//showInTimes.insert(std::make_pair(partId, new Long(System.currentTimeMillis())));
}
bool Perspective::RestoreState(IMemento::Pointer memento)
{
// MultiStatus result = new MultiStatus(
// PlatformUI.PLUGIN_ID,
// IStatus.OK,
// WorkbenchMessages.Perspective_problemsRestoringPerspective, 0);
bool result = true;
// Create persp descriptor.
descriptor = new PerspectiveDescriptor("", "", PerspectiveDescriptor::Pointer(nullptr));
//result.add(descriptor.restoreState(memento));
result &= descriptor->RestoreState(memento);
PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->
GetPerspectiveRegistry()->FindPerspectiveWithId(descriptor->GetId()).Cast<PerspectiveDescriptor>();
if (desc)
{
descriptor = desc;
}
this->memento = memento;
// Add the visible views.
QList<IMemento::Pointer> views(memento->GetChildren(WorkbenchConstants::TAG_VIEW));
//result.merge(createReferences(views));
result &= this->CreateReferences(views);
memento = memento->GetChild(WorkbenchConstants::TAG_FAST_VIEWS);
if (memento)
{
views = memento->GetChildren(WorkbenchConstants::TAG_VIEW);
//result.merge(createReferences(views));
result &= this->CreateReferences(views);
}
return result;
}
bool Perspective::CreateReferences(const QList<IMemento::Pointer>& views)
{
// MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK,
// WorkbenchMessages.Perspective_problemsRestoringViews, 0);
bool result = true;
for (int x = 0; x < views.size(); x++)
{
// Get the view details.
IMemento::Pointer childMem = views[x];
QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id);
// skip creation of the intro reference - it's handled elsewhere.
if (id == IntroConstants::INTRO_VIEW_ID)
{
continue;
}
QString secondaryId(ViewFactory::ExtractSecondaryId(id));
if (!secondaryId.isEmpty())
{
id = ViewFactory::ExtractPrimaryId(id);
}
// Create and open the view.
try
{
QString rm; childMem->GetString(WorkbenchConstants::TAG_REMOVED, rm);
if (rm != "true")
{
viewFactory->CreateView(id, secondaryId);
}
}
catch (const PartInitException& e)
{
childMem->PutString(WorkbenchConstants::TAG_REMOVED, "true");
// result.add(StatusUtil.newStatus(IStatus.ERR,
// e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$
// e));
WorkbenchPlugin::Log(e.what(), e);
result &= true;
}
}
return result;
}
bool Perspective::RestoreState()
{
if (this->memento == 0)
{
//return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$
return true;
}
// MultiStatus result = new MultiStatus(
// PlatformUI.PLUGIN_ID,
// IStatus.OK,
// WorkbenchMessages.Perspective_problemsRestoringPerspective, 0);
IMemento::Pointer memento = this->memento;
this->memento = nullptr;
const IMemento::Pointer boundsMem(memento->GetChild(WorkbenchConstants::TAG_WINDOW));
if (boundsMem)
{
int x, y, w, h;
boundsMem->GetInteger(WorkbenchConstants::TAG_X, x);
boundsMem->GetInteger(WorkbenchConstants::TAG_Y, y);
boundsMem->GetInteger(WorkbenchConstants::TAG_HEIGHT, h);
boundsMem->GetInteger(WorkbenchConstants::TAG_WIDTH, w);
QRect r(x, y, w, h);
//StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
// void runWithException() throws Throwable
// {
if (page->GetWorkbenchWindow()->GetActivePage() == 0)
{
page->GetWorkbenchWindow()->GetShell()->SetBounds(r);
}
// }
// });
}
// Create an empty presentation..
PerspectiveHelper* pres;
//StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
// void runWithException() throws Throwable
// {
ViewSashContainer::Pointer mainLayout(new ViewSashContainer(page, this->GetClientComposite()));
pres = new PerspectiveHelper(page, mainLayout, this);
// }});
// Read the layout.
// result.merge(pres.restoreState(memento
// .getChild(IWorkbenchConstants.TAG_LAYOUT)));
pres->RestoreState(memento->GetChild(WorkbenchConstants::TAG_LAYOUT));
//StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
// void runWithException() throws Throwable
// {
// Add the editor workbook. Do not hide it now.
pres->ReplacePlaceholderWithPart(editorArea);
// }});
// Add the visible views.
QList<IMemento::Pointer> views(memento->GetChildren(WorkbenchConstants::TAG_VIEW));
for (int x = 0; x < views.size(); x++)
{
// Get the view details.
IMemento::Pointer childMem = views[x];
QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id);
QString secondaryId(ViewFactory::ExtractSecondaryId(id));
if (!secondaryId.isEmpty())
{
id = ViewFactory::ExtractPrimaryId(id);
}
// skip the intro as it is restored higher up in workbench.
if (id == IntroConstants::INTRO_VIEW_ID)
{
continue;
}
// Create and open the view.
IViewReference::Pointer viewRef = viewFactory->GetView(id, secondaryId);
WorkbenchPartReference::Pointer ref = viewRef.Cast<WorkbenchPartReference>();
// report error
if (ref == 0)
{
QString key = ViewFactory::GetKey(id, secondaryId);
// result.add(new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0,
// NLS.bind(WorkbenchMessages.Perspective_couldNotFind, key ), 0));
WorkbenchPlugin::Log("Could not find view: " + key);
continue;
}
bool willPartBeVisible = pres->WillPartBeVisible(ref->GetId(), secondaryId);
if (willPartBeVisible)
{
IViewPart::Pointer view = ref->GetPart(true).Cast<IViewPart>();
if (view)
{
ViewSite::Pointer site = view->GetSite().Cast<ViewSite>();
pres->ReplacePlaceholderWithPart(site->GetPane().Cast<LayoutPart>());
}
}
else
{
pres->ReplacePlaceholderWithPart(ref->GetPane());
}
}
// // Load the fast views
// if (fastViewManager != 0)
// fastViewManager.restoreState(memento, result);
// Load the view layout recs
QList<IMemento::Pointer> recMementos(memento
->GetChildren(WorkbenchConstants::TAG_VIEW_LAYOUT_REC));
for (int i = 0; i < recMementos.size(); i++)
{
IMemento::Pointer recMemento = recMementos[i];
QString compoundId;
if (recMemento->GetString(WorkbenchConstants::TAG_ID, compoundId))
{
ViewLayoutRec::Pointer rec = GetViewLayoutRec(compoundId, true);
QString closeablestr; recMemento->GetString(WorkbenchConstants::TAG_CLOSEABLE, closeablestr);
if (WorkbenchConstants::FALSE_VAL == closeablestr)
{
rec->isCloseable = false;
}
QString moveablestr; recMemento->GetString(WorkbenchConstants::TAG_MOVEABLE, moveablestr);
if (WorkbenchConstants::FALSE_VAL == moveablestr)
{
rec->isMoveable = false;
}
QString standalonestr; recMemento->GetString(WorkbenchConstants::TAG_STANDALONE, standalonestr);
if (WorkbenchConstants::TRUE_VAL == standalonestr)
{
rec->isStandalone = true;
QString showstr; recMemento->GetString(WorkbenchConstants::TAG_SHOW_TITLE, showstr);
rec->showTitle = WorkbenchConstants::FALSE_VAL != showstr;
}
}
}
//final IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class);
try
{ // one big try block, don't kill me here
// // defer context events
// if (service != 0)
// {
// service.activateContext(ContextAuthority.DEFER_EVENTS);
// }
//
// HashSet knownActionSetIds = new HashSet();
//
// // Load the always on action sets.
QList<IMemento::Pointer> actions; // = memento
// .getChildren(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET);
// for (int x = 0; x < actions.length; x++)
// {
// String actionSetID = actions[x]
// .getString(IWorkbenchConstants.TAG_ID);
// final IActionSetDescriptor d = WorkbenchPlugin.getDefault()
// .getActionSetRegistry().findActionSet(actionSetID);
// if (d != 0)
// {
// StartupThreading
// .runWithoutExceptions(new StartupRunnable()
// {
// void runWithException() throws Throwable
// {
// addAlwaysOn(d);
// }
// });
//
// knownActionSetIds.add(actionSetID);
// }
// }
//
// // Load the always off action sets.
// actions = memento
// .getChildren(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET);
// for (int x = 0; x < actions.length; x++)
// {
// String actionSetID = actions[x]
// .getString(IWorkbenchConstants.TAG_ID);
// final IActionSetDescriptor d = WorkbenchPlugin.getDefault()
// .getActionSetRegistry().findActionSet(actionSetID);
// if (d != 0)
// {
// StartupThreading
// .runWithoutExceptions(new StartupRunnable()
// {
// void runWithException() throws Throwable
// {
// addAlwaysOff(d);
// }
// });
// knownActionSetIds.add(actionSetID);
// }
// }
// Load "show view actions".
actions = memento->GetChildren(WorkbenchConstants::TAG_SHOW_VIEW_ACTION);
for (int x = 0; x < actions.size(); x++)
{
QString id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id);
showViewShortcuts.push_back(id);
}
// // Load "show in times".
// actions = memento.getChildren(IWorkbenchConstants.TAG_SHOW_IN_TIME);
// for (int x = 0; x < actions.length; x++)
// {
// String id = actions[x].getString(IWorkbenchConstants.TAG_ID);
// String timeStr = actions[x]
// .getString(IWorkbenchConstants.TAG_TIME);
// if (id != 0 && timeStr != 0)
// {
// try
// {
// long time = Long.parseLong(timeStr);
// showInTimes.put(id, new Long(time));
// }
// catch (NumberFormatException e)
// {
// // skip this one
// }
// }
// }
// Load "show in parts" from registry, not memento
showInPartIds = this->GetShowInIdsFromRegistry();
// // Load "new wizard actions".
// actions = memento
// .getChildren(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION);
// newWizardShortcuts = new ArrayList(actions.length);
// for (int x = 0; x < actions.length; x++)
// {
// String id = actions[x].getString(IWorkbenchConstants.TAG_ID);
// newWizardShortcuts.add(id);
// }
// Load "perspective actions".
actions = memento->GetChildren(WorkbenchConstants::TAG_PERSPECTIVE_ACTION);
for (int x = 0; x < actions.size(); x++)
{
QString id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id);
perspectiveShortcuts.push_back(id);
}
// ArrayList extActionSets = getPerspectiveExtensionActionSets();
// for (int i = 0; i < extActionSets.size(); i++)
// {
// String actionSetID = (String) extActionSets.get(i);
// if (knownActionSetIds.contains(actionSetID))
// {
// continue;
// }
// final IActionSetDescriptor d = WorkbenchPlugin.getDefault()
// .getActionSetRegistry().findActionSet(actionSetID);
// if (d != 0)
// {
// StartupThreading
// .runWithoutExceptions(new StartupRunnable()
// {
// void runWithException() throws Throwable
// {
// addAlwaysOn(d);
// }
// });
// knownActionSetIds.add(d.getId());
// }
// }
// // Add the visible set of action sets to our knownActionSetIds
// // Now go through the registry to ensure we pick up any new action
// // sets
// // that have been added but not yet considered by this perspective.
// ActionSetRegistry reg = WorkbenchPlugin.getDefault()
// .getActionSetRegistry();
// IActionSetDescriptor[] array = reg.getActionSets();
// int count = array.length;
// for (int i = 0; i < count; i++)
// {
// IActionSetDescriptor desc = array[i];
// if ((!knownActionSetIds.contains(desc.getId()))
// && (desc.isInitiallyVisible()))
// {
// addActionSet(desc);
// }
// }
}
catch (...)
{
// // restart context changes
// if (service != 0)
// {
// StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
// void runWithException() throws Throwable
// {
// service.activateContext(ContextAuthority.SEND_EVENTS);
// }
// });
// }
}
// Save presentation.
presentation = pres;
// Hide the editor area if needed. Need to wait for the
// presentation to be fully setup first.
int areaVisible = 0;
bool areaVisibleExists = memento->GetInteger(WorkbenchConstants::TAG_AREA_VISIBLE, areaVisible);
// Rather than hiding the editors now we must wait until after their
// controls
// are created. This ensures that if an editor is instantiated,
// createPartControl
// is also called. See bug 20166.
shouldHideEditorsOnActivate = (areaVisibleExists && areaVisible == 0);
// // Restore the trim state of the editor area
// IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
// bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX);
// if (useNewMinMax)
// {
// Integer trimStateInt = memento.getInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE);
// if (trimStateInt != 0)
// {
// editorAreaState = trimStateInt.intValue() & 0x3; // low order two bits contain the state
// editorAreaRestoreOnUnzoom = (trimStateInt.intValue() & 4) != 0;
// }
// }
// restore the fixed state
int isFixed = 0;
fixed = (memento->GetInteger(WorkbenchConstants::TAG_FIXED, isFixed) && isFixed == 1);
return true;
}
QList<QString> Perspective::GetShowInIdsFromRegistry()
{
PerspectiveExtensionReader reader;
QList<QString> tags;
tags.push_back(WorkbenchRegistryConstants::TAG_SHOW_IN_PART);
reader.SetIncludeOnlyTags(tags);
PageLayout::Pointer layout(new PageLayout());
reader.ExtendLayout(nullptr, descriptor->GetOriginalId(), layout);
return layout->GetShowInPartIds();
}
void Perspective::SaveDesc()
{
this->SaveDescAs(descriptor);
}
void Perspective::SaveDescAs(IPerspectiveDescriptor::Pointer desc)
{
PerspectiveDescriptor::Pointer realDesc = desc.Cast<PerspectiveDescriptor>();
//get the layout from the registry
PerspectiveRegistry* perspRegistry = dynamic_cast<PerspectiveRegistry*>(
WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry());
// Capture the layout state.
XMLMemento::Pointer memento = XMLMemento::CreateWriteRoot("perspective");
//IStatus::Pointer status = SaveState(memento, realDesc, false);
// if (status->GetSeverity() == IStatus::ERROR_TYPE)
// {
// ErrorDialog.openError((Shell) 0, "Saving Problems",
// "Unable to store layout state.",
// status);
// return;
// }
bool status = SaveState(memento, realDesc, false);
if (!status)
{
QMessageBox::critical(nullptr, "Saving Problems", "Unable to store layout state.");
return;
}
//save it to the preference store
try
{
perspRegistry->SaveCustomPersp(realDesc, memento.GetPointer());
descriptor = realDesc;
}
catch (const std::exception& /*e*/)
{
perspRegistry->DeletePerspective(realDesc);
QMessageBox::critical(nullptr, "Saving Problems", "Unable to store layout state.");
}
}
bool Perspective::SaveState(IMemento::Pointer memento)
{
// MultiStatus::Pointer result(new MultiStatus(
// PlatformUI::PLUGIN_ID(),
// IStatus::OK_TYPE,
// "Problems occurred saving perspective.",
// BERRY_STATUS_LOC));
// result->Merge(SaveState(memento, descriptor, true));
bool result = true;
result &= this->SaveState(memento, descriptor, true);
return result;
}
bool Perspective::SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p,
bool saveInnerViewState)
{
// MultiStatus::Pointer result(new MultiStatus(
// PlatformUI::PLUGIN_ID(),
// IStatus::OK_TYPE,
// "Problems occurred saving perspective.",
// BERRY_STATUS_LOC));
bool result = true;
if (this->memento)
{
memento->PutMemento(this->memento);
return result;
}
// Save the version number.
memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING);
//result.add(p.saveState(memento));
result &= p->SaveState(memento);
if (!saveInnerViewState)
{
QRect bounds(page->GetWorkbenchWindow()->GetShell()->GetBounds());
IMemento::Pointer boundsMem = memento
->CreateChild(WorkbenchConstants::TAG_WINDOW);
boundsMem->PutInteger(WorkbenchConstants::TAG_X, bounds.x());
boundsMem->PutInteger(WorkbenchConstants::TAG_Y, bounds.y());
boundsMem->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height());
boundsMem->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width());
}
// // Save the "always on" action sets.
// Iterator itr = alwaysOnActionSets.iterator();
// while (itr.hasNext())
// {
// IActionSetDescriptor desc = (IActionSetDescriptor) itr.next();
// IMemento child = memento
// .createChild(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET);
// child.putString(IWorkbenchConstants.TAG_ID, desc.getId());
// }
// // Save the "always off" action sets.
// itr = alwaysOffActionSets.iterator();
// while (itr.hasNext())
// {
// IActionSetDescriptor desc = (IActionSetDescriptor) itr.next();
// IMemento child = memento
// .createChild(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET);
// child.putString(IWorkbenchConstants.TAG_ID, desc.getId());
// }
// Save "show view actions"
for (QList<QString>::iterator itr = showViewShortcuts.begin();
itr != showViewShortcuts.end(); ++itr)
{
IMemento::Pointer child = memento
->CreateChild(WorkbenchConstants::TAG_SHOW_VIEW_ACTION);
child->PutString(WorkbenchConstants::TAG_ID, *itr);
}
// // Save "show in times"
// itr = showInTimes.keySet().iterator();
// while (itr.hasNext())
// {
// String id = (String) itr.next();
// Long time = (Long) showInTimes.get(id);
// IMemento child = memento
// .createChild(IWorkbenchConstants.TAG_SHOW_IN_TIME);
// child.putString(IWorkbenchConstants.TAG_ID, id);
// child.putString(IWorkbenchConstants.TAG_TIME, time.toString());
// }
// // Save "new wizard actions".
// itr = newWizardShortcuts.iterator();
// while (itr.hasNext())
// {
// String str = (String) itr.next();
// IMemento child = memento
// .createChild(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION);
// child.putString(IWorkbenchConstants.TAG_ID, str);
// }
// Save "perspective actions".
for (QList<QString>::iterator itr = perspectiveShortcuts.begin();
itr != perspectiveShortcuts.end(); ++itr)
{
IMemento::Pointer child = memento
->CreateChild(WorkbenchConstants::TAG_PERSPECTIVE_ACTION);
child->PutString(WorkbenchConstants::TAG_ID, *itr);
}
// Get visible views.
QList<PartPane::Pointer> viewPanes;
presentation->CollectViewPanes(viewPanes);
// Save the views.
for (QList<PartPane::Pointer>::iterator itr = viewPanes.begin();
itr != viewPanes.end(); ++itr)
{
IWorkbenchPartReference::Pointer ref((*itr)->GetPartReference());
IViewDescriptor::Pointer desc = page->GetViewFactory()->GetViewRegistry()
->Find(ref->GetId());
if(desc && desc->IsRestorable())
{
IMemento::Pointer viewMemento = memento
->CreateChild(WorkbenchConstants::TAG_VIEW);
viewMemento->PutString(WorkbenchConstants::TAG_ID, ViewFactory::GetKey(ref.Cast<IViewReference>()));
}
}
// // save all fastview state
// if (fastViewManager != 0)
// fastViewManager.saveState(memento);
// Save the view layout recs.
for (QHash<QString, ViewLayoutRec::Pointer>::iterator i = mapIDtoViewLayoutRec.begin();
i != mapIDtoViewLayoutRec.end(); ++i)
{
QString compoundId(i.key());
ViewLayoutRec::Pointer rec(i.value());
if (rec && (!rec->isCloseable || !rec->isMoveable || rec->isStandalone))
{
IMemento::Pointer layoutMemento(memento
->CreateChild(WorkbenchConstants::TAG_VIEW_LAYOUT_REC));
layoutMemento->PutString(WorkbenchConstants::TAG_ID, compoundId);
if (!rec->isCloseable)
{
layoutMemento->PutString(WorkbenchConstants::TAG_CLOSEABLE,
WorkbenchConstants::FALSE_VAL);
}
if (!rec->isMoveable)
{
layoutMemento->PutString(WorkbenchConstants::TAG_MOVEABLE,
WorkbenchConstants::FALSE_VAL);
}
if (rec->isStandalone)
{
layoutMemento->PutString(WorkbenchConstants::TAG_STANDALONE,
WorkbenchConstants::TRUE_VAL);
layoutMemento->PutString(WorkbenchConstants::TAG_SHOW_TITLE,
rec->showTitle ? WorkbenchConstants::TRUE_VAL : WorkbenchConstants::FALSE_VAL);
}
}
}
// Save the layout.
IMemento::Pointer childMem(memento->CreateChild(WorkbenchConstants::TAG_LAYOUT));
//result->Add(presentation->SaveState(childMem));
result &= presentation->SaveState(childMem);
// Save the editor visibility state
if (this->IsEditorAreaVisible())
{
memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 1);
}
else
{
memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 0);
}
// // Save the trim state of the editor area if using the new min/max
// IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
// bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX);
// if (useNewMinMax)
// {
// int trimState = editorAreaState;
// trimState |= editorAreaRestoreOnUnzoom ? 4 : 0;
// memento.putInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE, trimState);
// }
// Save the fixed state
if (fixed)
{
memento->PutInteger(WorkbenchConstants::TAG_FIXED, 1);
}
else
{
memento->PutInteger(WorkbenchConstants::TAG_FIXED, 0);
}
return result;
}
void Perspective::SetPerspectiveActionIds(const QList<QString>& list)
{
perspectiveShortcuts = list;
}
void Perspective::SetShowInPartIds(const QList<QString>& list)
{
showInPartIds = list;
}
void Perspective::SetShowViewActionIds(const QList<QString>& list)
{
showViewShortcuts = list;
}
void Perspective::ShowEditorArea()
{
if (this->IsEditorAreaVisible())
{
return;
}
editorHidden = false;
// Show the editor in the appropriate location
if (this->UseNewMinMax(Perspective::Pointer(this)))
{
bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED;
if (!isMinimized)
{
// If the editor area is going to show then we have to restore
// if (getPresentation().getMaximizedStack() != 0)
// getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED);
this->ShowEditorAreaLocal();
}
// else
// setEditorAreaTrimVisibility(true);
}
else
{
this->ShowEditorAreaLocal();
}
}
void Perspective::ShowEditorAreaLocal()
{
if (editorHolder == 0 || editorHidden)
{
return;
}
// Replace the part holder with the editor area.
presentation->GetLayout()->Replace(editorHolder, editorArea);
editorHolder = nullptr;
}
void Perspective::SetEditorAreaState(int newState)
{
if (newState == editorAreaState)
return;
editorAreaState = newState;
// // reset the restore flag if we're not minimized
// if (newState != IStackPresentationSite::STATE_MINIMIZED)
// editorAreaRestoreOnUnzoom = false;
this->RefreshEditorAreaVisibility();
}
int Perspective::GetEditorAreaState()
{
return editorAreaState;
}
void Perspective::RefreshEditorAreaVisibility()
{
// Nothing shows up if the editor area isn't visible at all
if (editorHidden)
{
this->HideEditorAreaLocal();
//setEditorAreaTrimVisibility(false);
return;
}
PartStack::Pointer editorStack = editorArea.Cast<EditorSashContainer>()->GetUpperRightEditorStack();
if (editorStack == 0)
return;
// Whatever we're doing, make the current editor stack match it
//editorStack->SetStateLocal(editorAreaState);
// If it's minimized then it's in the trim
if (editorAreaState == IStackPresentationSite::STATE_MINIMIZED)
{
// Hide the editor area and show its trim
this->HideEditorAreaLocal();
//setEditorAreaTrimVisibility(true);
}
else
{
// Show the editor area and hide its trim
//setEditorAreaTrimVisibility(false);
this->ShowEditorAreaLocal();
// if (editorAreaState == IStackPresentationSite::STATE_MAXIMIZED)
// getPresentation().setMaximizedStack(editorStack);
}
}
IViewReference::Pointer Perspective::GetViewReference(const QString& viewId, const QString& secondaryId)
{
IViewReference::Pointer ref = page->FindViewReference(viewId, secondaryId);
if (ref == 0)
{
ViewFactory* factory = this->GetViewFactory();
try
{
ref = factory->CreateView(viewId, secondaryId);
}
catch (PartInitException& /*e*/)
{
// IStatus status = StatusUtil.newStatus(IStatus.ERR,
// e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$
// e);
// StatusUtil.handleStatus(status, "Failed to create view: id=" + viewId, //$NON-NLS-1$
// StatusManager.LOG);
//TODO Perspective status message
WorkbenchPlugin::Log("Failed to create view: id=" + viewId);
}
}
return ref;
}
IViewPart::Pointer Perspective::ShowView(const QString& viewId, const QString& secondaryId)
{
ViewFactory* factory = this->GetViewFactory();
IViewReference::Pointer ref = factory->CreateView(viewId, secondaryId);
IViewPart::Pointer part = ref->GetPart(true).Cast<IViewPart>();
if (part == 0)
{
throw PartInitException("Could not create view: " + ref->GetId());
}
PartSite::Pointer site = part->GetSite().Cast<PartSite>();
PartPane::Pointer pane = site->GetPane();
//TODO Perspective preference store
// IPreferenceStore store = WorkbenchPlugin.getDefault()
// .getPreferenceStore();
// int openViewMode = store.getInt(IPreferenceConstants.OPEN_VIEW_MODE);
//
// if (openViewMode == IPreferenceConstants.OVM_FAST &&
// fastViewManager != 0)
// {
// fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, true);
// setActiveFastView(ref);
// }
// else if (openViewMode == IPreferenceConstants.OVM_FLOAT
// && presentation.canDetach())
// {
// presentation.addDetachedPart(pane);
// }
// else
// {
if (this->UseNewMinMax(Perspective::Pointer(this)))
{
// Is this view going to show in the trim?
// LayoutPart vPart = presentation.findPart(viewId, secondaryId);
// Determine if there is a trim stack that should get the view
QString trimId;
// // If we can locate the correct trim stack then do so
// if (vPart != 0)
// {
// String id = 0;
// ILayoutContainer container = vPart.getContainer();
// if (container.Cast<ContainerPlaceholder>() != 0)
// id = ((ContainerPlaceholder)container).getID();
// else if (container.Cast<ViewStack>() != 0)
// id = ((ViewStack)container).getID();
//
// // Is this place-holder in the trim?
// if (id != 0 && fastViewManager.getFastViews(id).size()> 0)
// {
// trimId = id;
// }
// }
//
// // No explicit trim found; If we're maximized then we either have to find an
// // arbitrary stack...
// if (trimId == 0 && presentation.getMaximizedStack() != 0)
// {
// if (vPart == 0)
// {
// ViewStackTrimToolBar blTrimStack = fastViewManager.getBottomRightTrimStack();
// if (blTrimStack != 0)
// {
// // OK, we've found a trim stack to add it to...
// trimId = blTrimStack.getId();
//
// // Since there was no placeholder we have to add one
// LayoutPart blPart = presentation.findPart(trimId, 0);
// if (blPart.Cast<ContainerPlaceholder>() != 0)
// {
// ContainerPlaceholder cph = (ContainerPlaceholder) blPart;
// if (cph.getRealContainer().Cast<ViewStack>() != 0)
// {
// ViewStack vs = (ViewStack) cph.getRealContainer();
//
// // Create a 'compound' id if this is a multi-instance part
// String compoundId = ref.getId();
// if (ref.getSecondaryId() != 0)
// compoundId = compoundId + ':' + ref.getSecondaryId();
//
// // Add the new placeholder
// vs.add(new PartPlaceholder(compoundId));
// }
// }
// }
// }
// }
//
// // If we have a trim stack located then add the view to it
// if (trimId != "")
// {
// fastViewManager.addViewReference(trimId, -1, ref, true);
// }
// else
// {
// bool inMaximizedStack = vPart != 0 && vPart.getContainer() == presentation.getMaximizedStack();
// Do the default behavior
presentation->AddPart(pane);
// // Now, if we're maximized then we have to minimize the new stack
// if (presentation.getMaximizedStack() != 0 && !inMaximizedStack)
// {
// vPart = presentation.findPart(viewId, secondaryId);
// if (vPart != 0 && vPart.getContainer().Cast<ViewStack>() != 0)
// {
// ViewStack vs = (ViewStack)vPart.getContainer();
// vs.setState(IStackPresentationSite.STATE_MINIMIZED);
//
// // setting the state to minimized will create the trim toolbar
// // so we don't need a 0 pointer check here...
// fastViewManager.getViewStackTrimToolbar(vs.getID()).setRestoreOnUnzoom(true);
// }
// }
// }
}
else
{
presentation->AddPart(pane);
}
//}
// Ensure that the newly showing part is enabled
if (pane != 0 && pane->GetControl() != nullptr)
Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(pane->GetControl(), true);
return part;
}
IWorkbenchPartReference::Pointer Perspective::GetOldPartRef()
{
return oldPartRef;
}
void Perspective::SetOldPartRef(IWorkbenchPartReference::Pointer oldPartRef)
{
this->oldPartRef = oldPartRef;
}
bool Perspective::IsCloseable(IViewReference::Pointer reference)
{
ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false);
if (rec != 0)
{
return rec->isCloseable;
}
return true;
}
bool Perspective::IsMoveable(IViewReference::Pointer reference)
{
ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false);
if (rec != 0)
{
return rec->isMoveable;
}
return true;
}
void Perspective::DescribeLayout(QString& buf) const
{
// QList<IViewReference::Pointer> fastViews = getFastViews();
//
// if (fastViews.length != 0)
// {
// buf.append("fastviews ("); //$NON-NLS-1$
// for (int idx = 0; idx < fastViews.length; idx++)
// {
// IViewReference ref = fastViews[idx];
//
// if (idx> 0)
// {
// buf.append(", "); //$NON-NLS-1$
// }
//
// buf.append(ref.getPartName());
// }
// buf.append("), "); //$NON-NLS-1$
// }
this->GetPresentation()->DescribeLayout(buf);
}
void Perspective::TestInvariants()
{
this->GetPresentation()->GetLayout()->TestInvariants();
}
bool Perspective::UseNewMinMax(Perspective::Pointer activePerspective)
{
// We need to have an active perspective
if (activePerspective == 0)
return false;
// We need to have a trim manager (if we don't then we
// don't create a FastViewManager because it'd be useless)
// if (activePerspective->GetFastViewManager() == 0)
// return false;
// Make sure we don't NPE anyplace
WorkbenchWindow::Pointer wbw = activePerspective->page->GetWorkbenchWindow().Cast<WorkbenchWindow>();
if (wbw == 0)
return false;
// WorkbenchWindowConfigurer* configurer = wbw->GetWindowConfigurer();
// if (configurer == 0)
// return false;
IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory();
if (factory == nullptr)
return false;
// Ok, we should be good to go, return the pref
//IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore();
//bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX);
return true;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp
index 285624ee04..9f4518b24a 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp
@@ -1,334 +1,334 @@
/*============================================================================
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 "berryPerspectiveDescriptor.h"
#include "berryWorkbenchRegistryConstants.h"
#include "berryWorkbenchPlugin.h"
#include "berryWorkbenchConstants.h"
#include "berryPerspectiveRegistry.h"
#include "berryStatus.h"
#include "berryIContributor.h"
#include <QIcon>
namespace berry
{
PerspectiveDescriptor::PerspectiveDescriptor(const QString& id,
const QString& label, PerspectiveDescriptor::Pointer originalDescriptor)
: singleton(false), fixed(false)
{
this->id = id;
this->label = label;
if (originalDescriptor != 0)
{
this->originalId = originalDescriptor->GetOriginalId();
this->imageDescriptor = originalDescriptor->imageDescriptor;
// This perspective is based on a perspective in some bundle -- if
// that
// bundle goes away then I think it makes sense to treat this
// perspective
// the same as any other -- so store it with the original
// descriptor's
// bundle's list.
//
// It might also make sense the other way...removing the following
// line
// will allow the perspective to stay around when the originating
// bundle
// is unloaded.
//
// This might also have an impact on upgrade cases -- should we
// really be
// destroying all user customized perspectives when the older
// version is
// removed?
//
// I'm leaving this here for now since its a good example, but
// wouldn't be
// surprised if we ultimately decide on the opposite.
//
// The reason this line is important is that this is the value used
// to
// put the object into the UI level registry. When that bundle goes
// away,
// the registry will remove the entire list of objects. So if this
// desc
// has been put into that list -- it will go away.
this->pluginId = originalDescriptor->GetPluginId();
}
}
PerspectiveDescriptor::PerspectiveDescriptor(const QString& id,
IConfigurationElement::Pointer configElement)
: singleton(false), fixed(false)
{
this->configElement = configElement;
this->id = id;
// Sanity check.
if ((this->GetId() == "") || (this->GetLabel() == "")
|| (this->GetFactoryClassName() == ""))
{
IStatus::Pointer status(new Status(
IStatus::ERROR_TYPE,
PlatformUI::PLUGIN_ID(),
nullptr,
QString("Invalid extension (missing label, id or class name): ") + GetId()));
throw CoreException(status);
}
}
IPerspectiveFactory::Pointer PerspectiveDescriptor::CreateFactory()
{
// if there is an originalId, then use that descriptor instead
if (originalId != "")
{
// Get the original descriptor to create the factory. If the
// original is gone then nothing can be done.
IPerspectiveDescriptor::Pointer
target =
dynamic_cast<PerspectiveRegistry*> (WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()) ->FindPerspectiveWithId(
originalId);
return target == 0 ? IPerspectiveFactory::Pointer(nullptr) : target.Cast<
PerspectiveDescriptor> ()->CreateFactory();
}
// otherwise try to create the executable extension
if (configElement != 0)
{
try
{
IPerspectiveFactory::Pointer factory(
configElement ->CreateExecutableExtension<IPerspectiveFactory> (
WorkbenchRegistryConstants::ATT_CLASS));
return factory;
}
catch (const CoreException& /*e*/)
{
// do nothing
}
}
return IPerspectiveFactory::Pointer(nullptr);
}
void PerspectiveDescriptor::DeleteCustomDefinition()
{
dynamic_cast<PerspectiveRegistry*> (WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry())->DeleteCustomDefinition(
PerspectiveDescriptor::Pointer(this));
}
QString PerspectiveDescriptor::GetDescription() const
{
return configElement == 0 ? description : RegistryReader::GetDescription(
configElement);
}
void PerspectiveDescriptor::SetDescription(const QString& desc)
{
description = desc;
}
bool PerspectiveDescriptor::GetFixed() const
{
if (configElement == 0)
return fixed;
return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_FIXED).compare("true", Qt::CaseInsensitive) == 0;
}
QStringList PerspectiveDescriptor::GetKeywordReferences() const
{
QStringList result;
if (configElement.IsNull())
{
return result;
}
auto keywordRefs = configElement->GetChildren("keywordReference");
for (auto keywordRefsIt = keywordRefs.begin();
keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs
{
result.push_back((*keywordRefsIt)->GetAttribute("id"));
}
return result;
}
QString PerspectiveDescriptor::GetId() const
{
return id;
}
QString PerspectiveDescriptor::GetLocalId() const
{
return GetId();
}
QString PerspectiveDescriptor::GetPluginId() const
{
return configElement == 0 ? pluginId : configElement->GetContributor()->GetName();
}
QIcon PerspectiveDescriptor::GetImageDescriptor() const
{
if (!imageDescriptor.isNull())
return imageDescriptor;
if (configElement)
{
QString icon = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON);
if (!icon.isEmpty())
{
imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin(
configElement->GetContributor()->GetName(), icon);
}
}
if (imageDescriptor.isNull())
{
imageDescriptor = AbstractUICTKPlugin::GetMissingIcon();
}
return imageDescriptor;
}
QStringList PerspectiveDescriptor::GetCategoryPath() const
{
if(!categoryPath.empty()) return categoryPath;
if (configElement.IsNotNull())
{
QString category = configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY);
- categoryPath = category.split('/', QString::SkipEmptyParts);
+ categoryPath = category.split('/', Qt::SkipEmptyParts);
}
return categoryPath;
}
QString PerspectiveDescriptor::GetLabel() const
{
if (configElement == 0)
return label;
return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME);
}
QString PerspectiveDescriptor::GetOriginalId() const
{
if (originalId == "")
{
return this->GetId();
}
return originalId;
}
bool PerspectiveDescriptor::HasCustomDefinition() const
{
return dynamic_cast<PerspectiveRegistry*> (WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry())->HasCustomDefinition(
PerspectiveDescriptor::ConstPointer(this));
}
bool PerspectiveDescriptor::HasDefaultFlag() const
{
if (configElement == 0)
{
return false;
}
return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_DEFAULT).compare("true", Qt::CaseInsensitive) == 0;
}
bool PerspectiveDescriptor::IsPredefined() const
{
return this->GetFactoryClassName() != "" && configElement != 0;
}
bool PerspectiveDescriptor::IsSingleton() const
{
if (configElement == 0)
return singleton;
return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_SINGLETON).compare("true", Qt::CaseInsensitive) == 0;
}
bool PerspectiveDescriptor::RestoreState(IMemento::Pointer memento)
{
IMemento::Pointer childMem(memento->GetChild(
WorkbenchConstants::TAG_DESCRIPTOR));
if (childMem)
{
childMem->GetString(WorkbenchConstants::TAG_ID, id);
childMem->GetString(WorkbenchConstants::TAG_DESCRIPTOR, originalId);
childMem->GetString(WorkbenchConstants::TAG_LABEL, label);
childMem->GetString(WorkbenchConstants::TAG_CLASS, className);
int singletonVal;
singleton = childMem->GetInteger(WorkbenchConstants::TAG_SINGLETON,
singletonVal);
// Find a descriptor in the registry.
IPerspectiveDescriptor::Pointer
descriptor =
WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry()->FindPerspectiveWithId(
this->GetOriginalId());
if (descriptor)
{
// Copy the state from the registered descriptor.
imageDescriptor = descriptor->GetImageDescriptor();
}
}
//return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); //$NON-NLS-1$
return true;
}
void PerspectiveDescriptor::RevertToPredefined()
{
if (this->IsPredefined())
{
this->DeleteCustomDefinition();
}
}
bool PerspectiveDescriptor::SaveState(IMemento::Pointer memento)
{
IMemento::Pointer childMem(memento->CreateChild(
WorkbenchConstants::TAG_DESCRIPTOR));
childMem->PutString(WorkbenchConstants::TAG_ID, GetId());
if (!originalId.isEmpty())
{
childMem->PutString(WorkbenchConstants::TAG_DESCRIPTOR, originalId);
}
childMem->PutString(WorkbenchConstants::TAG_LABEL, GetLabel());
childMem->PutString(WorkbenchConstants::TAG_CLASS, GetFactoryClassName());
if (singleton)
{
childMem->PutInteger(WorkbenchConstants::TAG_SINGLETON, 1);
}
//return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null);
return true;
}
IConfigurationElement::Pointer PerspectiveDescriptor::GetConfigElement() const
{
return configElement;
}
QString PerspectiveDescriptor::GetFactoryClassName() const
{
return configElement == 0 ? className : RegistryReader::GetClassValue(
configElement, WorkbenchRegistryConstants::ATT_CLASS);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp
index e35824ad1c..6ce8a99aab 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp
@@ -1,1515 +1,1515 @@
/*============================================================================
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 "tweaklets/berryGuiWidgetsTweaklet.h"
#include "berryPerspectiveHelper.h"
#include "berryLayoutTree.h"
#include "berryEditorSashContainer.h"
#include "berryDragUtil.h"
#include "berryPresentationFactoryUtil.h"
#include "berryWorkbenchConstants.h"
#include "berryWorkbenchPlugin.h"
#include "berryPolicy.h"
#include <berryDebugUtil.h>
namespace berry
{
const int PerspectiveHelper::MIN_DETACH_WIDTH = 150;
const int PerspectiveHelper::MIN_DETACH_HEIGHT = 250;
PerspectiveHelper::DragOverListener::DragOverListener(PerspectiveHelper* perspHelper) :
perspHelper(perspHelper)
{
}
IDropTarget::Pointer PerspectiveHelper::DragOverListener::Drag(
QWidget* /*currentControl*/, const Object::Pointer& draggedObject, const QPoint& /*position*/,
const QRect& dragRectangle)
{
if (draggedObject.Cast<PartPane>() != 0)
{
PartPane::Pointer part = draggedObject.Cast<PartPane>();
if (part->GetContainer().Cast<PartStack>()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR)
return IDropTarget::Pointer(nullptr);
// Views that haven't been shown yet have no 'control' which causes
// 'GetWorkbenchWindow' to return 'null' so check explicitly
if (part->GetPage() != perspHelper->page)
return IDropTarget::Pointer(nullptr);
else if (part->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow())
return IDropTarget::Pointer(nullptr);
if (perspHelper->dropTarget == 0)
perspHelper->dropTarget = new ActualDropTarget(perspHelper, part, dragRectangle);
else
perspHelper->dropTarget->SetTarget(part, dragRectangle);
}
else if (draggedObject.Cast<PartStack>() != 0)
{
PartStack::Pointer stack = draggedObject.Cast<PartStack>();
if (stack->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR)
return IDropTarget::Pointer(nullptr);
if (stack->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow())
return IDropTarget::Pointer(nullptr);
if (perspHelper->dropTarget == 0)
perspHelper->dropTarget = new ActualDropTarget(perspHelper, stack, dragRectangle);
else
perspHelper->dropTarget->SetTarget(stack, dragRectangle);
}
return perspHelper->dropTarget;
}
void PerspectiveHelper::ActualDropTarget::SetTarget(PartPane::Pointer part,
const QRect& dragRectangle)
{
this->stack = nullptr;
this->part = part;
this->dragRectangle = dragRectangle;
}
void PerspectiveHelper::ActualDropTarget::SetTarget(PartStack::Pointer stack,
const QRect& dragRectangle)
{
this->stack = stack;
this->part = nullptr;
this->dragRectangle = dragRectangle;
}
PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part,
const QRect& dragRectangle)
: AbstractDropTarget(), perspHelper(perspHelper)
{
this->SetTarget(part, dragRectangle);
}
PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer stack,
const QRect& dragRectangle)
: AbstractDropTarget(), perspHelper(perspHelper)
{
this->SetTarget(stack, dragRectangle);
}
void PerspectiveHelper::ActualDropTarget::Drop()
{
if (part != 0)
{
Shell::Pointer shell = part->GetShell();
if (shell->GetData().Cast<DetachedWindow> () != 0)
{
// if only one view in tab folder then do a window move
ILayoutContainer::Pointer container = part->GetContainer();
if (container.Cast<PartStack> () != 0)
{
if (container.Cast<PartStack>()->GetItemCount() == 1)
{
shell->SetLocation(dragRectangle.x(), dragRectangle.y());
return;
}
}
}
// // If layout is modified always zoom out.
// if (isZoomed())
// {
// zoomOut();
// }
// do a normal part detach
perspHelper->DetachPart(part, dragRectangle.x(), dragRectangle.y());
}
else if (stack != 0)
{
Shell::Pointer shell = stack->GetShell();
if (shell->GetData().Cast<DetachedWindow> () != 0)
{
// only one tab folder in a detach window, so do window
// move
shell->SetLocation(dragRectangle.x(), dragRectangle.y());
return;
}
// // If layout is modified always zoom out.
// if (isZoomed())
// {
// zoomOut();
// }
// do a normal part detach
perspHelper->Detach(stack, dragRectangle.x(), dragRectangle.y());
}
}
CursorType PerspectiveHelper::ActualDropTarget::GetCursor()
{
return CURSOR_OFFSCREEN;
}
PerspectiveHelper::MatchingPart::MatchingPart(const QString& pid,
const QString& sid, LayoutPart::Pointer part)
{
this->pid = pid;
this->sid = sid;
this->part = part;
this->len = pid.size() + sid.size();
this->hasWildcard = (pid.indexOf(PartPlaceholder::WILD_CARD) != -1) ||
(sid.indexOf(PartPlaceholder::WILD_CARD) != -1);
}
bool PerspectiveHelper::CompareMatchingParts::operator()(const MatchingPart& m1, const MatchingPart& m2) const
{
// specific ids always outweigh ids with wildcards
if (m1.hasWildcard && !m2.hasWildcard)
{
return true;
}
if (!m1.hasWildcard && m2.hasWildcard)
{
return false;
}
// if both are specific or both have wildcards, simply compare based on length
return m1.len > m2.len;
}
PerspectiveHelper::PerspectiveHelper(WorkbenchPage* workbenchPage,
ViewSashContainer::Pointer mainLayout, Perspective* persp)
: page(workbenchPage), perspective(persp),
mainLayout(mainLayout),
detachable(false), active(false)
{
// Views can be detached if the feature is enabled (true by default,
// use the plug-in customization file to disable), and if the platform
// supports detaching.
this->dragTarget.reset(new DragOverListener(this));
//TODO preference store
// IPreferenceStore store = PlatformUI.getPreferenceStore();
// this.detachable = store.getBoolean(
// IWorkbenchPreferenceConstants.ENABLE_DETACHED_VIEWS);
this->detachable = true;
if (this->detachable)
{
// Check if some arbitrary Composite supports reparenting. If it
// doesn't, views cannot be detached.
QWidget* client = workbenchPage->GetClientComposite();
if (client == nullptr)
{
// The workbench page is not initialized. I don't think this can happen,
// but if it does, silently set detachable to false.
this->detachable = false;
}
else
{
this->detachable = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsReparentable(client);
}
}
}
void PerspectiveHelper::Activate(QWidget* parent)
{
if (active)
{
return;
}
parentWidget = parent;
// Activate main layout
// make sure all the views have been properly parented
QList<PartPane::Pointer> children;
this->CollectViewPanes(children, mainLayout->GetChildren());
for (QList<PartPane::Pointer>::iterator iter = children.begin();
iter != children.end(); ++iter)
{
PartPane::Pointer part = *iter;
part->Reparent(parent);
}
mainLayout->CreateControl(parent);
mainLayout->SetActive(true);
// Open the detached windows.
for (DetachedWindowsType::iterator iter = detachedWindowList.begin();
iter != detachedWindowList.end(); ++iter)
{
(*iter)->Open();
}
this->EnableAllDrag();
// // Ensure that the maximized stack's presentation state is correct
// if (maximizedStackId != 0)
// {
// LayoutPart part = this->FindPart(maximizedStackId);
// if (part.Cast<PartStack>() != 0)
// {
// maximizedStack = (PartStack) part;
// maximizedStackId = 0;
// }
// }
//
// // NOTE: we only handle ViewStacks here; Editor Stacks are handled by the
// // perspective
// if (maximizedStack instanceof ViewStack)
// {
// maximizedStack.setPresentationState(IStackPresentationSite.STATE_MAXIMIZED);
// }
active = true;
}
void PerspectiveHelper::AddPart(LayoutPart::Pointer part)
{
// Look for a placeholder.
PartPlaceholder::Pointer placeholder;
LayoutPart::Pointer testPart;
QString primaryId = part->GetID();
QString secondaryId;
IViewReference::Pointer ref;
if (part.Cast<PartPane> () != 0)
{
PartPane::Pointer pane = part.Cast<PartPane> ();
ref = pane->GetPartReference().Cast<IViewReference> ();
if (ref != 0)
secondaryId = ref->GetSecondaryId();
}
if (secondaryId != "")
{
testPart = this->FindPart(primaryId, secondaryId);
}
else
{
testPart = this->FindPart(primaryId);
}
// validate the testPart
if (testPart != 0 && testPart.Cast<PartPlaceholder>() != 0)
{
placeholder = testPart.Cast<PartPlaceholder> ();
}
// If there is no placeholder do a simple add. Otherwise, replace the
// placeholder if its not a pattern matching placeholder
if (placeholder == 0)
{
part->Reparent(mainLayout->GetParent());
LayoutPart::Pointer relative = mainLayout->FindBottomRight();
if (relative != 0 && relative.Cast<ILayoutContainer>() != 0)
{
ILayoutContainer::Pointer stack =
relative.Cast<ILayoutContainer> ();
if (stack->AllowsAdd(part))
{
mainLayout->Stack(part, stack);
}
else
{
mainLayout->AddPart(part);
}
}
else
{
mainLayout->AddPart(part);
}
}
else
{
ILayoutContainer::Pointer container = placeholder->GetContainer();
if (container != 0)
{
if (container.Cast<DetachedPlaceHolder> () != 0)
{
//Create a detached window add the part on it.
DetachedPlaceHolder::Pointer holder = container.Cast<DetachedPlaceHolder>();
detachedPlaceHolderList.removeAll(holder);
container->Remove(testPart);
DetachedWindow::Pointer window(new DetachedWindow(page));
detachedWindowList.push_back(window);
window->Create();
part->CreateControl(window->GetShell()->GetControl());
// Open window.
window->GetShell()->SetBounds(holder->GetBounds());
window->Open();
// add part to detached window.
PartPane::Pointer pane = part.Cast<PartPane>();
window->Add(pane);
QList<LayoutPart::Pointer> otherChildren = holder->GetChildren();
for (QList<LayoutPart::Pointer>::iterator iter = otherChildren.begin();
iter != otherChildren.end(); ++iter)
{
part->GetContainer()->Add(*iter);
}
}
else
{
// show parent if necessary
if (container.Cast<ContainerPlaceholder> () != 0)
{
ContainerPlaceholder::Pointer containerPlaceholder =
container.Cast<ContainerPlaceholder>();
ILayoutContainer::Pointer parentContainer =
containerPlaceholder->GetContainer();
if (parentContainer == 0)
{
if (Policy::DEBUG_PERSPECTIVES())
{
QString msg = "Previous ContainerPlaceholder for " + tmpViewId;
if (tmpStackTrace.isNull())
{
WorkbenchPlugin::Log(msg);
}
else
{
WorkbenchPlugin::Log(msg, *tmpStackTrace.data());
}
tmpViewId.clear();
tmpStackTrace.reset(new ctkException(""));
WorkbenchPlugin::Log("Current ContainerPlaceholder with null parent for " +
primaryId + ":" + secondaryId, *tmpStackTrace.data());
tmpStackTrace.reset();
}
return;
}
if (Policy::DEBUG_PERSPECTIVES())
{
tmpViewId = primaryId + ":" + secondaryId;
tmpStackTrace.reset(new ctkException(""));
}
container = containerPlaceholder->GetRealContainer().Cast<ILayoutContainer>();
if (container.Cast<LayoutPart> () != 0)
{
parentContainer->Replace(containerPlaceholder,
container.Cast<LayoutPart>());
}
containerPlaceholder->SetRealContainer(ILayoutContainer::Pointer(nullptr));
}
// // reparent part.
// if (container.Cast<PartStack>() == 0)
// {
// // We don't need to reparent children of PartTabFolders since they will automatically
// // reparent their children when they become visible. This if statement used to be
// // part of an else branch. Investigate if it is still necessary.
// part->Reparent(mainLayout->GetParent());
// }
// see if we should replace the placeholder
if (placeholder->HasWildCard())
{
if (PartSashContainer::Pointer sashContainer = container.Cast<PartSashContainer>())
{
sashContainer->AddChildForPlaceholder(part, placeholder);
}
else
{
container->Add(part);
}
}
else
{
container->Replace(placeholder, part);
}
}
}
}
}
void PerspectiveHelper::AttachPart(IViewReference::Pointer ref)
{
PartPane::Pointer pane = ref.Cast<WorkbenchPartReference>()->GetPane();
// Restore any maximized part before re-attaching.
// Note that 'getMaximizedStack != 0' implies 'useNewMinMax'
// if (getMaximizedStack() != 0)
// {
// getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED);
// }
this->DerefPart(pane);
this->AddPart(pane);
this->BringPartToTop(pane);
pane->SetFocus();
}
bool PerspectiveHelper::CanDetach()
{
return detachable;
}
bool PerspectiveHelper::BringPartToTop(LayoutPart::Pointer part)
{
ILayoutContainer::Pointer container = part->GetContainer();
if (container != 0 && container.Cast<PartStack> () != 0)
{
PartStack::Pointer folder = container.Cast<PartStack> ();
if (folder->GetSelection() != part)
{
folder->SetSelection(part);
return true;
}
}
return false;
}
bool PerspectiveHelper::IsPartVisible(IWorkbenchPartReference::Pointer partRef)
{
LayoutPart::Pointer foundPart;
if (partRef.Cast<IViewReference> () != 0)
{
foundPart = this->FindPart(partRef->GetId(),
partRef.Cast<IViewReference>()->GetSecondaryId());
}
else
{
foundPart = this->FindPart(partRef->GetId());
}
if (foundPart == 0)
{
return false;
}
if (foundPart.Cast<PartPlaceholder> () != 0)
{
return false;
}
ILayoutContainer::Pointer container = foundPart->GetContainer();
if (container.Cast<ContainerPlaceholder> () != 0)
{
return false;
}
if (container.Cast<PartStack> () != 0)
{
PartStack::Pointer folder = container.Cast<PartStack>();
LayoutPart::Pointer visiblePart = folder->GetSelection();
if (visiblePart == 0)
{
return false;
}
return partRef == visiblePart.Cast<PartPane>()->GetPartReference();
}
return true;
}
bool PerspectiveHelper::WillPartBeVisible(const QString& partId)
{
return this->WillPartBeVisible(partId, nullptr);
}
bool PerspectiveHelper::WillPartBeVisible(const QString& partId,
const QString& secondaryId)
{
LayoutPart::Pointer part = this->FindPart(partId, secondaryId);
if (part == 0)
{
return false;
}
ILayoutContainer::Pointer container = part->GetContainer();
if (container != 0 && container.Cast<ContainerPlaceholder> () != 0)
{
container = container.Cast<ContainerPlaceholder>()->GetRealContainer().Cast<ILayoutContainer>();
}
if (container != 0 && container.Cast<PartStack> () != 0)
{
PartStack::Pointer folder = container.Cast<PartStack>();
if (folder->GetSelection() == 0)
{
return false;
}
return part->GetID() == folder->GetSelection()->GetID();
}
return true;
}
QList<PartPlaceholder::Pointer> PerspectiveHelper::CollectPlaceholders()
{
// Scan the main window.
QList<PartPlaceholder::Pointer> results = this->CollectPlaceholders(
mainLayout->GetChildren());
// Scan each detached window.
if (detachable)
{
for (DetachedWindowsType::iterator winIter = detachedWindowList.begin();
winIter != detachedWindowList.end(); ++winIter)
{
DetachedWindow::Pointer win = *winIter;
QList<LayoutPart::Pointer> moreResults = win->GetChildren();
if (moreResults.size()> 0)
{
for (QList<LayoutPart::Pointer>::iterator iter = moreResults.begin();
iter != moreResults.end(); ++iter)
{
if (iter->Cast<PartPlaceholder>() != 0)
results.push_back(iter->Cast<PartPlaceholder>());
}
}
}
}
return results;
}
QList<PartPlaceholder::Pointer> PerspectiveHelper::CollectPlaceholders(
const QList<LayoutPart::Pointer>& parts)
{
QList<PartPlaceholder::Pointer> result;
for (QList<LayoutPart::Pointer>::const_iterator iter = parts.begin();
iter != parts.end(); ++iter)
{
LayoutPart::Pointer part = *iter;
if (ILayoutContainer::Pointer container = part.Cast<ILayoutContainer>())
{
// iterate through sub containers to find sub-parts
QList<PartPlaceholder::Pointer> newParts = this->CollectPlaceholders(
container->GetChildren());
result.append(newParts);
}
else if (PartPlaceholder::Pointer placeholder = part.Cast<PartPlaceholder>())
{
result.push_back(placeholder);
}
}
return result;
}
void PerspectiveHelper::CollectViewPanes(QList<PartPane::Pointer>& result)
{
// Scan the main window.
this->CollectViewPanes(result, mainLayout->GetChildren());
// Scan each detached window.
if (detachable)
{
for (DetachedWindowsType::iterator winIter = detachedWindowList.begin();
winIter != detachedWindowList.end(); ++winIter)
{
DetachedWindow::Pointer win = *winIter;
CollectViewPanes(result, win->GetChildren());
}
}
}
void PerspectiveHelper::CollectViewPanes(QList<PartPane::Pointer>& result,
const QList<LayoutPart::Pointer>& parts)
{
for (QList<LayoutPart::Pointer>::const_iterator iter = parts.begin();
iter != parts.end(); ++iter)
{
LayoutPart::Pointer part = *iter;
if (PartPane::Pointer partPane = part.Cast<PartPane>())
{
if(partPane->GetPartReference().Cast<IViewReference>())
{
result.push_back(partPane);
}
}
else if (ILayoutContainer::Pointer container = part.Cast<ILayoutContainer> ())
{
this->CollectViewPanes(result, container->GetChildren());
}
}
}
void PerspectiveHelper::Deactivate()
{
if (!active)
{
return;
}
this->DisableAllDrag();
// Reparent all views to the main window
QWidget* parent = mainLayout->GetParent();
QList<PartPane::Pointer> children;
this->CollectViewPanes(children, mainLayout->GetChildren());
for (DetachedWindowsType::iterator winIter = detachedWindowList.begin();
winIter != detachedWindowList.end(); ++winIter)
{
DetachedWindow::Pointer window = *winIter;
CollectViewPanes(children, window->GetChildren());
}
// *** Do we even need to do this if detached windows not supported?
for (QList<PartPane::Pointer>::iterator itr = children.begin();
itr != children.end(); ++itr)
{
PartPane::Pointer part = *itr;
part->Reparent(parent);
}
// Dispose main layout.
mainLayout->SetActive(false);
// Dispose the detached windows
for (DetachedWindowsType::iterator iter = detachedWindowList.begin();
iter != detachedWindowList.end(); ++iter)
{
(*iter)->Close();
}
active = false;
}
PerspectiveHelper::~PerspectiveHelper()
{
mainLayout->Dispose();
mainLayout->DisposeSashes();
}
void PerspectiveHelper::DescribeLayout(QString& buf) const
{
if (detachable)
{
if (detachedWindowList.size() != 0)
{
buf.append("detachedWindows ("); //$NON-NLS-1$
for (DetachedWindowsType::const_iterator winIter = detachedWindowList.begin();
winIter != detachedWindowList.end(); ++winIter)
{
DetachedWindow::ConstPointer window = *winIter;
QList<LayoutPart::Pointer> children = window->GetChildren();
int j = 0;
if (children.size() != 0)
{
buf.append("dWindow ("); //$NON-NLS-1$
for (QList<LayoutPart::Pointer>::iterator partIter = children.begin();
partIter != children.end(); ++partIter, ++j)
{
if (partIter->Cast<PartPlaceholder>() != 0)
buf.append(partIter->Cast<PartPlaceholder>()->GetPlaceHolderId());
else if (partIter->Cast<PartPane>() != 0)
buf.append(
partIter->Cast<PartPane>()->GetPartReference()->GetPartName());
if (j < (children.size() - 1))
{
buf.append(", "); //$NON-NLS-1$
}
}
buf.append(")"); //$NON-NLS-1$
}
}
buf.append("), "); //$NON-NLS-1$
}
}
this->GetLayout()->DescribeLayout(buf);
}
void PerspectiveHelper::DerefPart(LayoutPart::Pointer part)
{
// if (part.Cast<PartPane> () != 0)
// {
// IViewReference::Pointer ref = ((ViewPane) part).getViewReference();
// if (perspective.isFastView(ref))
// {
// // Special check: if it's a fast view then it's actual ViewStack
// // may only contain placeholders and the stack is represented in
// // the presentation by a container placeholder...make sure the
// // PartPlaceHolder for 'ref' is removed from the ViewStack
// String id = perspective.getFastViewManager().getIdForRef(ref);
// LayoutPart parentPart = findPart(id, 0);
// if (parentPart.Cast<ContainerPlaceholder> () != 0)
// {
// ViewStack vs =
// (ViewStack) ((ContainerPlaceholder) parentPart).getRealContainer();
// QList<LayoutPart::Pointer> kids = vs.getChildren();
// for (int i = 0; i < kids.length; i++)
// {
// if (kids[i].Cast<PartPlaceholder> () != 0)
// {
// if (ref.getId().equals(kids[i].id))
// vs.remove(kids[i]);
// }
// }
// }
// perspective.getFastViewManager().removeViewReference(ref, true, true);
// }
// }
// Get vital part stats before reparenting.
ILayoutContainer::Pointer oldContainer = part->GetContainer();
bool wasDocked = part->IsDocked();
Shell::Pointer oldShell = part->GetShell();
// Reparent the part back to the main window
part->Reparent(mainLayout->GetParent());
// Update container.
if (oldContainer == 0)
{
return;
}
oldContainer->Remove(part);
ILayoutContainer::ChildrenType children = oldContainer->GetChildren();
if (wasDocked)
{
bool hasChildren = (children.size()> 0);
if (hasChildren)
{
// make sure one is at least visible
int childVisible = 0;
for (ILayoutContainer::ChildrenType::iterator iter = children.begin();
iter != children.end(); ++iter)
{
if ((*iter)->GetControl() != nullptr)
{
childVisible++;
}
}
// none visible, then reprarent and remove container
if (oldContainer.Cast<PartStack> () != 0)
{
PartStack::Pointer folder = oldContainer.Cast<PartStack>();
// Is the part in the trim?
bool inTrim = false;
// // Safety check...there may be no FastViewManager
// if (perspective.getFastViewManager() != 0)
// inTrim
// = perspective.getFastViewManager().getFastViews(folder.getID()).size()
// > 0;
if (childVisible == 0 && !inTrim)
{
ILayoutContainer::Pointer parentContainer = folder->GetContainer();
hasChildren = folder->GetChildren().size()> 0;
// We maintain the stack as a place-holder if it has children
// (which at this point would represent view place-holders)
if (hasChildren)
{
folder->Dispose();
// replace the real container with a ContainerPlaceholder
ContainerPlaceholder::Pointer placeholder(
new ContainerPlaceholder(folder->GetID()));
placeholder->SetRealContainer(folder);
parentContainer->Replace(folder, placeholder);
}
}
else if (childVisible == 1)
{
LayoutTree::Pointer layout = mainLayout->GetLayoutTree();
layout = layout->Find(folder);
layout->SetBounds(layout->GetBounds());
}
}
}
if (!hasChildren)
{
// There are no more children in this container, so get rid of
// it
if (oldContainer.Cast<LayoutPart> () != 0)
{
//BERRY_INFO << "No children left, removing container\n";
LayoutPart::Pointer parent = oldContainer.Cast<LayoutPart>();
ILayoutContainer::Pointer parentContainer = parent->GetContainer();
if (parentContainer != 0)
{
parentContainer->Remove(parent);
parent->Print(qDebug());
parent->Dispose();
}
}
}
}
else if (!wasDocked)
{
if (children.empty())
{
// There are no more children in this container, so get rid of
// it
// Turn on redraw again just in case it was off.
//oldShell.setRedraw(true);
DetachedWindow::Pointer w = oldShell->GetData().Cast<DetachedWindow>();
oldShell->Close();
detachedWindowList.removeAll(w);
}
else
{
// There are children. If none are visible hide detached
// window.
bool allInvisible = true;
for (ILayoutContainer::ChildrenType::iterator iter = children.begin();
iter != children.end(); ++iter)
{
if (iter->Cast<PartPlaceholder> () == 0)
{
allInvisible = false;
break;
}
}
if (allInvisible)
{
DetachedPlaceHolder::Pointer placeholder(new DetachedPlaceHolder("",
oldShell->GetBounds()));
for (ILayoutContainer::ChildrenType::iterator iter = children.begin();
iter != children.end(); ++iter)
{
oldContainer->Remove(*iter);
(*iter)->SetContainer(placeholder);
placeholder->Add(*iter);
}
detachedPlaceHolderList.push_back(placeholder);
DetachedWindow::Pointer w = oldShell->GetData().Cast<DetachedWindow>();
oldShell->Close();
detachedWindowList.removeAll(w);
}
}
}
}
void PerspectiveHelper::Detach(LayoutPart::Pointer part, int x, int y)
{
// Detaching is disabled on some platforms ..
if (!detachable)
{
return;
}
// Calculate detached window size.
QSize size = part->GetSize();
if (size.width() == 0 || size.height() == 0)
{
ILayoutContainer::Pointer container = part->GetContainer();
if (container.Cast<LayoutPart> () != 0)
{
size = container.Cast<LayoutPart>()->GetSize();
}
}
int width = std::max<int>(size.width(), MIN_DETACH_WIDTH);
int height = std::max<int>(size.height(), MIN_DETACH_HEIGHT);
// Create detached window.
DetachedWindow::Pointer window(new DetachedWindow(page));
detachedWindowList.push_back(window);
// Open window.
window->Create();
window->GetShell()->SetBounds(x, y, width, height);
window->Open();
if (part.Cast<PartStack> () != 0)
{
//window.getShell().setRedraw(false);
//parentWidget.setRedraw(false);
PartStack::Pointer stack = part.Cast<PartStack>();
LayoutPart::Pointer visiblePart = stack->GetSelection();
ILayoutContainer::ChildrenType children = stack->GetChildren();
for (ILayoutContainer::ChildrenType::iterator iter = children.begin();
iter != children.end(); ++iter)
{
if (PartPane::Pointer partPane = iter->Cast<PartPane>()
// && check it is a view?
)
{
// remove the part from its current container
this->DerefPart(*iter);
// add part to detached window.
window->Add(*iter);
}
}
if (visiblePart != 0)
{
this->BringPartToTop(visiblePart);
visiblePart->SetFocus();
}
//window.getShell().setRedraw(true);
//parentWidget.setRedraw(true);
}
}
void PerspectiveHelper::DetachPart(LayoutPart::Pointer part, int x, int y)
{
// Detaching is disabled on some platforms ..
if (!detachable)
{
return;
}
// Calculate detached window size.
QSize size = part->GetSize();
if (size.width() == 0 || size.height() == 0)
{
ILayoutContainer::Pointer container = part->GetContainer();
if (container.Cast<LayoutPart> () != 0)
{
size = container.Cast<LayoutPart>()->GetSize();
}
}
int width = std::max<int>(size.width(), MIN_DETACH_WIDTH);
int height = std::max<int>(size.height(), MIN_DETACH_HEIGHT);
// Create detached window.
DetachedWindow::Pointer window(new DetachedWindow(page));
detachedWindowList.push_back(window);
// Open window.
window->Create();
window->GetShell()->SetBounds(x, y, width, height);
window->Open();
// remove the part from its current container
this->DerefPart(part);
// add part to detached window.
window->Add(part);
part->SetFocus();
}
void PerspectiveHelper::DetachPart(IViewReference::Pointer ref)
{
PartPane::Pointer pane = ref.Cast<WorkbenchPartReference>()->GetPane();
if (this->CanDetach() && pane != 0)
{
// if (getMaximizedStack() != 0)
// getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED);
QRect bounds = pane->GetParentBounds();
this->DetachPart(pane, bounds.x(), bounds.y());
}
}
void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part)
{
// Calculate detached window size.
QRect bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parentWidget)->GetBounds();
bounds.setX(bounds.x() + (bounds.width() - 300) / 2);
bounds.setY(bounds.y() + (bounds.height() - 300) / 2);
this->AddDetachedPart(part, bounds);
}
void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part,
const QRect& bounds)
{
// Detaching is disabled on some platforms ..
if (!detachable)
{
this->AddPart(part);
return;
}
// Create detached window.
DetachedWindow::Pointer window(new DetachedWindow(page));
detachedWindowList.push_back(window);
window->Create();
// add part to detached window.
part->CreateControl(window->GetShell()->GetControl());
window->Add(part);
// Open window.
window->GetShell()->SetBounds(bounds.x(), bounds.y(), bounds.width(), bounds.height());
window->Open();
part->SetFocus();
}
void PerspectiveHelper::DisableAllDrag()
{
DragUtil::RemoveDragTarget(nullptr, dragTarget.data());
}
void PerspectiveHelper::EnableAllDrag()
{
DragUtil::AddDragTarget(nullptr, dragTarget.data());
}
LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& id)
{
return this->FindPart(id, "");
}
LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& primaryId,
const QString& secondaryId)
{
//BERRY_INFO << "Looking for part: " << primaryId << ":" << secondaryId << std::endl;
// check main window.
QList<MatchingPart> matchingParts;
LayoutPart::Pointer part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId,
mainLayout->GetChildren(), matchingParts) : this->FindPart(primaryId,
mainLayout->GetChildren(), matchingParts);
if (part != 0)
{
return part;
}
// check each detached windows.
for (DetachedWindowsType::iterator iter = detachedWindowList.begin();
iter != detachedWindowList.end(); ++iter)
{
DetachedWindow::Pointer window = *iter;
part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId,
window->GetChildren(), matchingParts) : this->FindPart(primaryId,
window->GetChildren(), matchingParts);
if (part != 0)
{
return part;
}
}
for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin();
iter != detachedPlaceHolderList.end(); ++iter)
{
DetachedPlaceHolder::Pointer holder = *iter;
part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId,
holder->GetChildren(), matchingParts) : this->FindPart(primaryId,
holder->GetChildren(), matchingParts);
if (part != 0)
{
return part;
}
}
//BERRY_INFO << "Looking through the matched parts (count: " << matchingParts.size() << ")\n";
// sort the matching parts
if (matchingParts.size()> 0)
{
std::partial_sort(matchingParts.begin(), (matchingParts.begin()), matchingParts.end(), CompareMatchingParts());
const MatchingPart& mostSignificantPart = matchingParts.front();
return mostSignificantPart.part;
}
// Not found.
return LayoutPart::Pointer(nullptr);
}
LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& id,
const QList<LayoutPart::Pointer>& parts,
QList<MatchingPart>& matchingParts)
{
for (QList<LayoutPart::Pointer>::const_iterator iter = parts.begin();
iter != parts.end(); ++iter)
{
LayoutPart::Pointer part = *iter;
// check for part equality, parts with secondary ids fail
if (part->GetID() == id)
{
if (part.Cast<PartPane> () != 0)
{
PartPane::Pointer pane = part.Cast<PartPane>();
IViewReference::Pointer ref = pane->GetPartReference().Cast<IViewReference>();
if (ref->GetSecondaryId() != "")
{
continue;
}
}
return part;
}
// check pattern matching placeholders
else if (part->IsPlaceHolder()
&& part.Cast<PartPlaceholder>()->HasWildCard())
{
- QRegExp re(id, Qt::CaseInsensitive);
- if (re.exactMatch(part->GetID()))
+ QRegularExpression re(QString("^%1$").arg(id), QRegularExpression::CaseInsensitiveOption);
+ if (re.match(part->GetID()).hasMatch())
{
matchingParts.push_back(MatchingPart(part->GetID(), "", part));
}
// StringMatcher sm = new StringMatcher(part.getID(), true, false);
// if (sm.match(id))
// {
// matchingParts .add(new MatchingPart(part.getID(), 0, part));
// }
}
else if (ILayoutContainer::Pointer layoutContainer = part.Cast<ILayoutContainer>())
{
part = FindPart(id, layoutContainer->GetChildren(),
matchingParts);
if (part)
{
return part;
}
}
}
//BERRY_INFO << "Returning 0\n";
return LayoutPart::Pointer(nullptr);
}
LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& primaryId,
const QString& secondaryId,
const QList<LayoutPart::Pointer>& parts,
QList<MatchingPart>& matchingParts)
{
for (QList<LayoutPart::Pointer>::const_iterator iter = parts.begin();
iter != parts.end(); ++iter)
{
LayoutPart::Pointer part = *iter;
// check containers first
if (ILayoutContainer::Pointer layoutContainer = part.Cast<ILayoutContainer>())
{
LayoutPart::Pointer testPart = FindPart(primaryId, secondaryId,
layoutContainer->GetChildren(), matchingParts);
if (testPart)
{
return testPart;
}
}
// check for view part equality
if (part.Cast<PartPane> () != 0)
{
PartPane::Pointer pane = part.Cast<PartPane>();
IViewReference::Pointer ref = pane->GetPartReference().Cast<IViewReference>();
if (ref->GetId() == primaryId && ref->GetSecondaryId() == secondaryId)
{
return part;
}
}
// check placeholders
else if (part.Cast<PartPlaceholder> () != 0)
{
QString id = part->GetID();
// optimization: don't bother parsing id if it has no separator -- it can't match
QString phSecondaryId = ViewFactory::ExtractSecondaryId(id);
if (phSecondaryId == "")
{
// but still need to check for wildcard case
if (id == PartPlaceholder::WILD_CARD)
{
matchingParts.push_back(MatchingPart(id, "", part));
}
continue;
}
QString phPrimaryId = ViewFactory::ExtractPrimaryId(id);
// perfect matching pair
if (phPrimaryId == primaryId && phSecondaryId == secondaryId)
{
return part;
}
// check for partial matching pair
- QRegExp pre(phPrimaryId, Qt::CaseInsensitive);
- if (pre.exactMatch(primaryId))
+ QRegularExpression pre(QString("^%1$").arg(phPrimaryId), QRegularExpression::CaseInsensitiveOption);
+ if (pre.match(primaryId).hasMatch())
{
- QRegExp sre(phSecondaryId, Qt::CaseInsensitive);
- if (sre.exactMatch(secondaryId))
+ QRegularExpression sre(QString("^%1$").arg(phSecondaryId), QRegularExpression::CaseInsensitiveOption);
+ if (sre.match(secondaryId).hasMatch())
{
matchingParts.push_back(MatchingPart(phPrimaryId, phSecondaryId, part));
}
}
}
}
return LayoutPart::Pointer(nullptr);
}
bool PerspectiveHelper::HasPlaceholder(const QString& id)
{
return this->HasPlaceholder(id, nullptr);
}
bool PerspectiveHelper::HasPlaceholder(const QString& primaryId,
const QString& secondaryId)
{
LayoutPart::Pointer testPart;
if (secondaryId == "")
{
testPart = this->FindPart(primaryId);
}
else
{
testPart = this->FindPart(primaryId, secondaryId);
}
return (testPart != 0 && testPart.Cast<PartPlaceholder> () != 0);
}
PartSashContainer::Pointer PerspectiveHelper::GetLayout() const
{
return mainLayout;
}
bool PerspectiveHelper::IsActive()
{
return active;
}
float PerspectiveHelper::GetDockingRatio(LayoutPart::Pointer source,
LayoutPart::Pointer target)
{
if ((source.Cast<PartPane> () != 0 || source.Cast<PartStack> () != 0)
&& target.Cast<EditorSashContainer> () != 0)
{
return 0.25f;
}
return 0.5f;
}
void PerspectiveHelper::RemovePart(LayoutPart::Pointer part)
{
// Reparent the part back to the main window
QWidget* parent = mainLayout->GetParent();
part->Reparent(parent);
// Replace part with a placeholder
ILayoutContainer::Pointer container = part->GetContainer();
if (container != 0)
{
QString placeHolderId = part->GetPlaceHolderId();
container->Replace(part, LayoutPart::Pointer(new PartPlaceholder(placeHolderId)));
// // If the parent is root we're done. Do not try to replace
// // it with placeholder.
// if (container == mainLayout)
// {
// return;
// }
// If the parent is empty replace it with a placeholder.
QList<LayoutPart::Pointer> children = container->GetChildren();
bool allInvisible = true;
for (QList<LayoutPart::Pointer>::iterator childIter = children.begin();
childIter != children.end(); ++childIter)
{
if (childIter->Cast<PartPlaceholder> () == 0)
{
allInvisible = false;
break;
}
}
if (allInvisible && (container.Cast<LayoutPart> () != 0))
{
// what type of window are we in?
LayoutPart::Pointer cPart = container.Cast<LayoutPart>();
//Window oldWindow = cPart.getWindow();
bool wasDocked = cPart->IsDocked();
Shell::Pointer oldShell = cPart->GetShell();
if (wasDocked)
{
// PR 1GDFVBY: ViewStack not disposed when page
// closed.
if (container.Cast<PartStack> () != 0)
{
container.Cast<PartStack>()->Dispose();
}
// replace the real container with a
// ContainerPlaceholder
ILayoutContainer::Pointer parentContainer = cPart->GetContainer();
ContainerPlaceholder::Pointer placeholder(
new ContainerPlaceholder(cPart->GetID()));
placeholder->SetRealContainer(container);
parentContainer->Replace(cPart, placeholder);
}
else
{
DetachedPlaceHolder::Pointer placeholder(
new DetachedPlaceHolder("", oldShell->GetBounds())); //$NON-NLS-1$
for (QList<LayoutPart::Pointer>::iterator childIter2 = children.begin();
childIter2 != children.end(); ++childIter2)
{
(*childIter2)->GetContainer()->Remove(*childIter2);
(*childIter2)->SetContainer(placeholder);
placeholder->Add(*childIter2);
}
detachedPlaceHolderList.push_back(placeholder);
DetachedWindow::Pointer w = oldShell->GetData().Cast<DetachedWindow>();
oldShell->Close();
detachedWindowList.removeAll(w);
}
}
}
}
void PerspectiveHelper::ReplacePlaceholderWithPart(LayoutPart::Pointer part)
{
// Look for a PartPlaceholder that will tell us how to position this
// object
QList<PartPlaceholder::Pointer> placeholders = this->CollectPlaceholders();
for (int i = 0; i < placeholders.size(); i++)
{
if (placeholders[i]->GetID() == part->GetID())
{
// found a matching placeholder which we can replace with the
// new View
ILayoutContainer::Pointer container = placeholders[i]->GetContainer();
if (container != 0)
{
if (ContainerPlaceholder::Pointer containerPlaceholder = container.Cast<ContainerPlaceholder> ())
{
// One of the children is now visible so replace the
// ContainerPlaceholder with the real container
ILayoutContainer::Pointer parentContainer =
containerPlaceholder->GetContainer();
container = containerPlaceholder->GetRealContainer().Cast<ILayoutContainer>();
if (LayoutPart::Pointer layoutPart = container.Cast<LayoutPart> ())
{
parentContainer->Replace(containerPlaceholder, layoutPart);
}
containerPlaceholder->SetRealContainer(ILayoutContainer::Pointer(nullptr));
}
container->Replace(placeholders[i], part);
return;
}
}
}
}
bool PerspectiveHelper::RestoreState(IMemento::Pointer memento)
{
// Restore main window.
IMemento::Pointer childMem = memento->GetChild(WorkbenchConstants::TAG_MAIN_WINDOW);
//IStatus r = mainLayout->RestoreState(childMem);
bool r = mainLayout->RestoreState(childMem);
// Restore each floating window.
if (detachable)
{
QList<IMemento::Pointer> detachedWindows(memento->GetChildren(
WorkbenchConstants::TAG_DETACHED_WINDOW));
for (QList<IMemento::Pointer>::iterator iter = detachedWindows.begin();
iter != detachedWindows.end(); ++iter)
{
DetachedWindow::Pointer win(new DetachedWindow(page));
detachedWindowList.push_back(win);
win->RestoreState(*iter);
}
QList<IMemento::Pointer> childrenMem(memento->GetChildren(
WorkbenchConstants::TAG_HIDDEN_WINDOW));
for (QList<IMemento::Pointer>::iterator iter = childrenMem.begin();
iter != childrenMem.end(); ++iter)
{
DetachedPlaceHolder::Pointer holder(
new DetachedPlaceHolder("", QRect(0, 0, 0, 0)));
holder->RestoreState(*iter);
detachedPlaceHolderList.push_back(holder);
}
}
// Get the cached id of the currently maximized stack
//maximizedStackId = childMem.getString(IWorkbenchConstants.TAG_MAXIMIZED);
return r;
}
bool PerspectiveHelper::SaveState(IMemento::Pointer memento)
{
// Persist main window.
IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_MAIN_WINDOW);
//IStatus r = mainLayout->SaveState(childMem);
bool r = mainLayout->SaveState(childMem);
if (detachable)
{
// Persist each detached window.
for (DetachedWindowsType::iterator iter = detachedWindowList.begin();
iter != detachedWindowList.end(); ++iter)
{
childMem = memento->CreateChild(WorkbenchConstants::TAG_DETACHED_WINDOW);
(*iter)->SaveState(childMem);
}
for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin();
iter != detachedPlaceHolderList.end(); ++iter)
{
childMem = memento->CreateChild(WorkbenchConstants::TAG_HIDDEN_WINDOW);
(*iter)->SaveState(childMem);
}
}
// Write out the id of the maximized (View) stack (if any)
// NOTE: we only write this out if it's a ViewStack since the
// Editor Area is handled by the perspective
// if (maximizedStack.Cast<PartStack> () != 0)
// {
// childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED,
// maximizedStack.getID());
// }
// else if (maximizedStackId != 0)
// {
// // Maintain the cache if the perspective has never been activated
// childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, maximizedStackId);
// }
return r;
}
void PerspectiveHelper::UpdateBoundsMap()
{
boundsMap.clear();
// Walk the layout gathering the current bounds of each stack
// and the editor area
QList<LayoutPart::Pointer> kids = mainLayout->GetChildren();
for (QList<LayoutPart::Pointer>::iterator iter = kids.begin();
iter != kids.end(); ++iter)
{
if (iter->Cast<PartStack> () != 0)
{
PartStack::Pointer vs = iter->Cast<PartStack>();
boundsMap.insert(vs->GetID(), vs->GetBounds());
}
else if (iter->Cast<EditorSashContainer> () != 0)
{
EditorSashContainer::Pointer esc = iter->Cast<EditorSashContainer>();
boundsMap.insert(esc->GetID(), esc->GetBounds());
}
}
}
void PerspectiveHelper::ResetBoundsMap()
{
boundsMap.clear();
}
QRect PerspectiveHelper::GetCachedBoundsFor(const QString& id)
{
return boundsMap[id];
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp
index 4d7f9003d4..1920232ef7 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp
@@ -1,624 +1,624 @@
/*============================================================================
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 "berryPerspectiveRegistry.h"
#include "berryWorkbench.h"
#include "berryWorkbenchPage.h"
#include "berryWorkbenchPlugin.h"
#include "berryPreferenceConstants.h"
#include "berryPerspective.h"
#include "berryPerspectiveRegistryReader.h"
#include "berryPlatformUI.h"
#include "handlers/berryClosePerspectiveHandler.h"
#include "berryIExtension.h"
#include "berryIExtensionTracker.h"
#include <mitkIPreferences.h>
namespace berry
{
const QString PerspectiveRegistry::EXT = "_persp.xml";
const QString PerspectiveRegistry::ID_DEF_PERSP = "PerspectiveRegistry.DEFAULT_PERSP";
const QString PerspectiveRegistry::PERSP = "_persp";
const char PerspectiveRegistry::SPACE_DELIMITER = ' ';
class PerspectiveRegistry::PreferenceChangeListener
{
PerspectiveRegistry* m_Registry;
public:
PreferenceChangeListener(PerspectiveRegistry* registry)
: m_Registry(registry)
{}
void PropertyChange(const mitk::IPreferences::ChangeEvent& event)
{
/*
* To ensure that no custom perspective definitions are
* deleted when preferences are imported, merge old and new
* values
*/
if (QString::fromStdString(event.GetProperty()).endsWith(PERSP))
{
/* A Perspective is being changed, merge */
this->MergePerspectives(event);
}
else if (event.GetProperty() == PreferenceConstants::PERSPECTIVES)
{
/* The list of perspectives is being changed, merge */
UpdatePreferenceList(event.GetSource());
}
}
void MergePerspectives(const mitk::IPreferences::ChangeEvent& event)
{
auto* store = event.GetSource();
if (event.GetNewValue().empty())
{
/*
* Perspective is being removed; if the user has deleted or
* reverted a custom perspective, let the change pass
* through. Otherwise, restore the custom perspective entry
*/
// Find the matching descriptor in the registry
QList<IPerspectiveDescriptor::Pointer> perspectiveList = m_Registry->GetPerspectives();
for (int i = 0; i < perspectiveList.size(); i++)
{
QString id = perspectiveList[i]->GetId();
const auto property = QString::fromStdString(event.GetProperty());
if (property == id + PERSP)
{ // found
// descriptor
// see if the perspective has been flagged for
// reverting or deleting
if (!m_Registry->perspToRemove.contains(id))
{ // restore
store->Put((id + PERSP).toStdString(), event.GetOldValue());
}
else
{ // remove element from the list
m_Registry->perspToRemove.removeAll(id);
}
}
}
}
else if (event.GetOldValue().empty())
{
/*
* New perspective is being added, update the
* perspectiveRegistry to contain the new custom perspective
*/
auto property = QString::fromStdString(event.GetProperty());
QString id = property.left(property.lastIndexOf(PERSP));
if (m_Registry->FindPerspectiveWithId(id).IsNull())
{
// perspective does not already exist in registry, add
// it
PerspectiveDescriptor::Pointer desc(new PerspectiveDescriptor(
- QString::null, QString::null, PerspectiveDescriptor::Pointer()));
+ QString(), QString(), PerspectiveDescriptor::Pointer()));
std::stringstream reader;
std::string xmlStr = event.GetNewValue();
reader.str(xmlStr);
try
{
XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(reader);
desc->RestoreState(memento);
m_Registry->AddPerspective(desc);
}
catch (const WorkbenchException& e)
{
//m_Registry->UnableToLoadPerspective(e.getStatus());
m_Registry->UnableToLoadPerspective(e.what());
}
}
}
/* If necessary, add to the list of perspectives */
this->UpdatePreferenceList(store);
}
void UpdatePreferenceList(mitk::IPreferences* store)
{
QList<IPerspectiveDescriptor::Pointer> perspectiveList = m_Registry->GetPerspectives();
QStringList perspBuffer;
for (int i = 0; i < perspectiveList.size(); i++)
{
PerspectiveDescriptor::Pointer desc = perspectiveList[i].Cast<PerspectiveDescriptor>();
if (m_Registry->HasCustomDefinition(desc))
{
perspBuffer.push_back(desc->GetId());
}
}
store->Put(PreferenceConstants::PERSPECTIVES, perspBuffer.join(QString(SPACE_DELIMITER)).toStdString());
}
};
PerspectiveRegistry::PerspectiveRegistry()
: preferenceListener(new PreferenceChangeListener(this))
{
IExtensionTracker* tracker = PlatformUI::GetWorkbench()->GetExtensionTracker();
tracker->RegisterHandler(this, QString("org.blueberry.ui.perspectives"));
mitk::IPreferences* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
prefs->OnPropertyChanged +=
mitk::MessageDelegate1<PreferenceChangeListener, const mitk::IPreferences::ChangeEvent&>(
preferenceListener.data(), &PreferenceChangeListener::PropertyChange);
}
void PerspectiveRegistry::AddPerspective(PerspectiveDescriptor::Pointer desc)
{
if (desc == 0)
{
return;
}
this->Add(desc);
}
void PerspectiveRegistry::RevertPerspectives(
const QList<PerspectiveDescriptor::Pointer>& perspToRevert)
{
// indicate that the user is removing these perspectives
for (QList<PerspectiveDescriptor::Pointer>::const_iterator iter = perspToRevert.begin();
iter != perspToRevert.end(); ++iter)
{
PerspectiveDescriptor::Pointer desc = *iter;
perspToRemove.push_back(desc->GetId());
desc->RevertToPredefined();
}
}
void PerspectiveRegistry::DeletePerspectives(
const QList<PerspectiveDescriptor::Pointer>& perspToDelete)
{
for (QList<PerspectiveDescriptor::Pointer>::const_iterator iter = perspToDelete.begin();
iter != perspToDelete.end(); ++iter)
{
this->DeletePerspective(*iter);
}
}
void PerspectiveRegistry::DeletePerspective(IPerspectiveDescriptor::Pointer in)
{
PerspectiveDescriptor::Pointer desc = in.Cast<PerspectiveDescriptor>();
// Don't delete predefined perspectives
if (!desc->IsPredefined())
{
perspToRemove.push_back(desc->GetId());
perspectives.removeAll(desc);
desc->DeleteCustomDefinition();
this->VerifyDefaultPerspective();
}
}
void PerspectiveRegistry::Load()
{
// Load the registries.
this->LoadPredefined();
this->LoadCustom();
// Get default perspective.
// Get it from the R1.0 dialog settings first. Fixes bug 17039
// IDialogSettings dialogSettings =
// WorkbenchPlugin.getDefault() .getDialogSettings();
// QString str = dialogSettings.get(ID_DEF_PERSP);
// if (str != null && str.length() > 0)
// {
// this->SetDefaultPerspective(str);
// dialogSettings.put(ID_DEF_PERSP, ""); //$NON-NLS-1$
// }
this->VerifyDefaultPerspective();
}
void PerspectiveRegistry::SaveCustomPersp(PerspectiveDescriptor::Pointer desc,
XMLMemento* memento)
{
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
// Save it to the preference store.
std::stringstream ss;
memento->Save(ss);
prefs->Put((desc->GetId() + PERSP).toStdString(), ss.str());
}
IMemento::Pointer PerspectiveRegistry::GetCustomPersp(const QString& id)
{
std::stringstream ss;
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
const auto xmlString = prefs->Get((id + PERSP).toStdString(), "");
if (!xmlString.empty())
{ // defined in store
ss.str(xmlString);
}
XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss);
return memento;
}
bool PerspectiveRegistry::ValidateLabel(const QString& label)
{
return !label.trimmed().isEmpty();
}
IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithId(const QString& id)
{
for (QList<PerspectiveDescriptor::Pointer>::iterator iter = perspectives.begin();
iter != perspectives.end(); ++iter)
{
PerspectiveDescriptor::Pointer desc = *iter;
if (desc->GetId() == id)
{
// if (WorkbenchActivityHelper.restrictUseOf(desc))
// {
// return null;
// }
return desc;
}
}
return IPerspectiveDescriptor::Pointer(nullptr);
}
IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithLabel(
const QString& label)
{
for (QList<PerspectiveDescriptor::Pointer>::iterator iter = perspectives.begin();
iter != perspectives.end(); ++iter)
{
PerspectiveDescriptor::Pointer desc = *iter;
if (desc->GetLabel() == label)
{
// if (WorkbenchActivityHelper.restrictUseOf(desc))
// {
// return 0;
// }
return desc;
}
}
return IPerspectiveDescriptor::Pointer(nullptr);
}
QString PerspectiveRegistry::GetDefaultPerspective()
{
return defaultPerspID;
}
QList<IPerspectiveDescriptor::Pointer> PerspectiveRegistry::GetPerspectives()
{
// Collection descs = WorkbenchActivityHelper.restrictCollection(perspectives,
// new ArrayList());
// return (IPerspectiveDescriptor[]) descs.toArray(
// new IPerspectiveDescriptor[descs.size()]);
QList<IPerspectiveDescriptor::Pointer> result;
for (QList<PerspectiveDescriptor::Pointer>::iterator iter = perspectives.begin();
iter != perspectives.end(); ++iter)
{
result.push_back(iter->Cast<IPerspectiveDescriptor>());
}
return result;
}
void PerspectiveRegistry::SetDefaultPerspective(const QString& id)
{
IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id);
if (desc != 0)
{
defaultPerspID = id;
//TODO Preferences
// PrefUtil.getAPIPreferenceStore().setValue(
// IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID, id);
}
}
IPerspectiveDescriptor::Pointer PerspectiveRegistry::CreatePerspective(const QString& label,
IPerspectiveDescriptor::Pointer originalDescriptor)
{
// Sanity check to avoid invalid or duplicate labels.
if (!this->ValidateLabel(label))
{
return IPerspectiveDescriptor::Pointer(nullptr);
}
if (this->FindPerspectiveWithLabel(label) != 0)
{
return IPerspectiveDescriptor::Pointer(nullptr);
}
// Calculate ID.
QString id(label);
id = id.replace(' ', '_').trimmed();
// Create descriptor.
PerspectiveDescriptor::Pointer desc(
new PerspectiveDescriptor(id, label, originalDescriptor.Cast<PerspectiveDescriptor>()));
this->Add(desc);
return IPerspectiveDescriptor::Pointer(static_cast<IPerspectiveDescriptor*>(desc.GetPointer()));
}
IPerspectiveDescriptor::Pointer PerspectiveRegistry::ClonePerspective(const QString& id,
const QString& label,
IPerspectiveDescriptor::Pointer originalDescriptor)
{
// Check for invalid labels
if (label == "" || label.trimmed().isEmpty())
{
throw Poco::InvalidArgumentException();
}
// Check for duplicates
IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id);
if (desc != 0)
{
throw Poco::InvalidArgumentException();
}
// Create descriptor.
desc
= new PerspectiveDescriptor(id, label, originalDescriptor.Cast<PerspectiveDescriptor>());
this->Add(desc.Cast<PerspectiveDescriptor>());
return desc;
}
void PerspectiveRegistry::RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert)
{
PerspectiveDescriptor::Pointer desc = perspToRevert.Cast<PerspectiveDescriptor>();
perspToRemove.push_back(desc->GetId());
desc->RevertToPredefined();
}
PerspectiveRegistry::~PerspectiveRegistry()
{
// PlatformUI::GetWorkbench()->GetExtensionTracker()->UnregisterHandler(this);
// WorkbenchPlugin::GetDefault()->GetPreferences()->RemovePropertyChangeListener(preferenceListener);
}
void PerspectiveRegistry::DeleteCustomDefinition(PerspectiveDescriptor::Pointer desc)
{
// remove the entry from the preference store.
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
prefs->Remove((desc->GetId() + PERSP).toStdString());
}
bool PerspectiveRegistry::HasCustomDefinition(PerspectiveDescriptor::ConstPointer desc) const
{
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
const auto keys = prefs->Keys();
return std::find(keys.begin(), keys.end(), (desc->GetId() + PERSP).toStdString()) != keys.end();
}
void PerspectiveRegistry::Add(PerspectiveDescriptor::Pointer desc)
{
perspectives.push_back(desc);
IConfigurationElement::Pointer element = desc->GetConfigElement();
if (element.IsNotNull())
{
PlatformUI::GetWorkbench()->GetExtensionTracker()->RegisterObject(
element->GetDeclaringExtension(), desc, IExtensionTracker::REF_WEAK);
}
}
void PerspectiveRegistry::InternalDeletePerspective(PerspectiveDescriptor::Pointer desc)
{
perspToRemove.push_back(desc->GetId());
perspectives.removeAll(desc);
desc->DeleteCustomDefinition();
this->VerifyDefaultPerspective();
}
void PerspectiveRegistry::LoadCustom()
{
QScopedPointer<std::istream> reader;
/* Get the entries from the Preference store */
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
/* Get the space-delimited list of custom perspective ids */
QString customPerspectives = QString::fromStdString(prefs->Get(PreferenceConstants::PERSPECTIVES, ""));
- QStringList perspectivesList = customPerspectives.split(' ', QString::SkipEmptyParts);
+ QStringList perspectivesList = customPerspectives.split(' ', Qt::SkipEmptyParts);
for (int i = 0; i < perspectivesList.size(); i++)
{
try
{
const auto xmlString = prefs->Get((perspectivesList[i] + PERSP).toStdString(), "");
if (!xmlString.empty())
{
reader.reset(new std::stringstream(xmlString));
//reader->exceptions(std::ios_base::failbit);
}
else
{
throw WorkbenchException(QString("Description of '%1' perspective could not be found.").arg(perspectivesList[i]));
}
// Restore the layout state.
XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(*reader);
PerspectiveDescriptor::Pointer newPersp(new PerspectiveDescriptor(
- QString::null, QString::null,
+ QString(), QString(),
PerspectiveDescriptor::Pointer(nullptr)));
newPersp->RestoreState(memento);
QString id = newPersp->GetId();
IPerspectiveDescriptor::Pointer oldPersp = FindPerspectiveWithId(id);
if (oldPersp.IsNull())
{
Add(newPersp);
}
}
catch (const std::ios_base::failure&)
{
- UnableToLoadPerspective(QString::null);
+ UnableToLoadPerspective(QString());
}
catch (const WorkbenchException& e)
{
UnableToLoadPerspective(e.message());
}
}
// // Get the entries from files, if any
// // if -data @noDefault specified the state location may not be
// // initialized
// IPath path = WorkbenchPlugin.getDefault().getDataLocation();
// if (path == null)
// {
// return;
// }
// File folder = path.toFile();
// if (folder.isDirectory())
// {
// File[] fileList = folder.listFiles();
// int nSize = fileList.length;
// for (int nX = 0; nX < nSize; nX++)
// {
// File file = fileList[nX];
// if (file.getName().endsWith(EXT))
// {
// // get the memento
// InputStream stream = null;
// try
// {
// stream = new FileInputStream(file);
// reader = new BufferedReader(new InputStreamReader(stream, "utf-8")); //$NON-NLS-1$
// // Restore the layout state.
// XMLMemento memento = XMLMemento.createReadRoot(reader);
// PerspectiveDescriptor newPersp =
// new PerspectiveDescriptor(null, null, null);
// newPersp.restoreState(memento);
// IPerspectiveDescriptor oldPersp = findPerspectiveWithId(
// newPersp .getId());
// if (oldPersp == null)
// {
// add(newPersp);
// }
// // save to the preference store
// saveCustomPersp(newPersp, memento);
// // delete the file
// file.delete();
// reader.close();
// stream.close();
// } catch (IOException e)
// {
// unableToLoadPerspective(null);
// } catch (WorkbenchException e)
// {
// unableToLoadPerspective(e.getStatus());
// }
// }
// }
// }
}
void PerspectiveRegistry::UnableToLoadPerspective(const QString& status)
{
QString msg = "Unable to load perspective";
if (status == "")
{
WorkbenchPlugin::Log(msg);
//IStatus errStatus =
// new Status(IStatus.ERR, WorkbenchPlugin.PI_WORKBENCH, msg);
//StatusManager.getManager().handle(errStatus, StatusManager.SHOW);
}
else
{
WorkbenchPlugin::Log(status + ": " + msg);
//IStatus errStatus = StatusUtil.newStatus(status, msg);
//StatusManager.getManager().handle(errStatus, StatusManager.SHOW);
}
}
void PerspectiveRegistry::LoadPredefined()
{
PerspectiveRegistryReader reader(this);
reader.ReadPerspectives(Platform::GetExtensionRegistry());
}
void PerspectiveRegistry::VerifyDefaultPerspective()
{
// Step 1: Try current defPerspId value.
IPerspectiveDescriptor::Pointer desc;
if (defaultPerspID != "")
{
desc = this->FindPerspectiveWithId(defaultPerspID);
}
if (desc != 0)
{
return;
}
// Step 2. Read default value.
//TODO Preferences
// QString str = PrefUtil.getAPIPreferenceStore().getString(
// IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID);
// if (str != null && str.length() > 0)
// {
// desc = this->FindPerspectiveWithId(str);
// }
// if (desc != 0)
// {
// defaultPerspID = str;
// return;
// }
// Step 3. Use application-specific default
defaultPerspID = Workbench::GetInstance()->GetDefaultPerspectiveId();
}
void PerspectiveRegistry::RemoveExtension(const IExtension::Pointer& /*source*/,
const QList<Object::Pointer>& objects)
{
for (int i = 0; i < objects.size(); i++)
{
if (PerspectiveDescriptor::Pointer desc = objects[i].Cast<PerspectiveDescriptor>())
{
// close the perspective in all windows
QList<IWorkbenchWindow::Pointer> windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows();
for (int w = 0; w < windows.size(); ++w)
{
IWorkbenchWindow::Pointer window = windows[w];
QList<IWorkbenchPage::Pointer> pages = window->GetPages();
for (int p = 0; p < pages.size(); ++p)
{
WorkbenchPage::Pointer page = pages[p].Cast<WorkbenchPage>();
ClosePerspectiveHandler::ClosePerspective(page, page->FindPerspective(desc));
}
}
// ((Workbench)PlatformUI.getWorkbench()).getPerspectiveHistory().removeItem(desc);
this->InternalDeletePerspective(desc);
}
}
}
void PerspectiveRegistry::AddExtension(IExtensionTracker* /*tracker*/,
const IExtension::Pointer& addedExtension)
{
QList<IConfigurationElement::Pointer> addedElements = addedExtension->GetConfigurationElements();
for (int i = 0; i < addedElements.size(); i++)
{
PerspectiveRegistryReader reader(this);
reader.ReadElement(addedElements[i]);
}
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.cpp
index 2c1c25354e..e942c99d24 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.cpp
@@ -1,74 +1,74 @@
/*============================================================================
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 "berryPreferencePageParameterValues.h"
#include "berryPlatform.h"
#include "berryPlatformUI.h"
#include "berryWorkbenchRegistryConstants.h"
#include "berryIConfigurationElement.h"
#include "berryIExtensionRegistry.h"
#include "berryIWorkbench.h"
namespace berry {
PreferencePageParameterValues::PreferencePageParameterValues()
{
QString xpId = PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_PREFERENCES;
Platform::GetExtensionRegistry()->AddListener(this, xpId);
}
QHash<QString, QString> PreferencePageParameterValues::GetParameterValues() const
{
if (preferenceMap.empty())
{
IExtensionRegistry* registry = Platform::GetExtensionRegistry();
if (registry)
{
QList<IConfigurationElement::Pointer> configElements =
registry->GetConfigurationElementsFor(PlatformUI::PLUGIN_ID(),
WorkbenchRegistryConstants::PL_PREFERENCES);
- for (const auto &configElement : qAsConst(configElements))
+ for (const auto &configElement : std::as_const(configElements))
{
if(configElement->GetName() == "page")
{
preferenceMap.insert(configElement->GetAttribute("name"), configElement->GetAttribute("id"));
}
}
}
}
return preferenceMap;
}
void PreferencePageParameterValues::Added(const QList<SmartPointer<IExtension> >& /*extensions*/)
{
preferenceMap.clear();
}
void berry::PreferencePageParameterValues::Removed(const QList<SmartPointer<berry::IExtension> >& /*extensions*/)
{
preferenceMap.clear();
}
void PreferencePageParameterValues::Added(const QList<SmartPointer<IExtensionPoint> >& /*extensionPoints*/)
{
preferenceMap.clear();
}
void PreferencePageParameterValues::Removed(const QList<SmartPointer<IExtensionPoint> >& /*extensionPoints*/)
{
preferenceMap.clear();
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtControlWidget.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtControlWidget.cpp
index aaa76a78b4..15456536a5 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtControlWidget.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtControlWidget.cpp
@@ -1,157 +1,156 @@
/*============================================================================
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 "berryLog.h"
#include "berryQtControlWidget.h"
#include <berryShell.h>
#include <QMoveEvent>
#include <QResizeEvent>
#include <algorithm>
namespace berry {
QtControlWidget::QtControlWidget(QWidget* parent, Shell* shell, Qt::WindowFlags f)
: QFrame(parent, f)
{
controller = new QtWidgetController(shell);
this->setFrameStyle(QFrame::NoFrame);
// TODO WeakPointer: QVariant should hold a weak pointer
- QVariant variant(QVariant::UserType);
- variant.setValue(controller);
+ auto variant = QVariant::fromValue(controller);
this->setProperty(QtWidgetController::PROPERTY_ID, variant);
}
QtControlWidget::~QtControlWidget()
{
GuiTk::ControlEvent::Pointer controlEvent(new GuiTk::ControlEvent(static_cast<QWidget*>(this)));
controller->controlEvents.destroyedEvent(controlEvent);
}
void QtControlWidget::changeEvent(QEvent* event)
{
typedef IShellListener::Events::ShellEventType::ListenerList ListenerList;
switch (event->type())
{
case QEvent::WindowActivate:
{
ShellEvent::Pointer shellEvent(new ShellEvent(Shell::Pointer(controller->shell)));
ListenerList activatedListeners(controller->shellEvents.shellActivated.GetListeners());
for (auto listener = activatedListeners.begin();
listener != activatedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) {
event->accept();
return;
}
}
}
break;
case QEvent::WindowDeactivate:
{
ShellEvent::Pointer shellEvent(new ShellEvent(Shell::Pointer(controller->shell)));
ListenerList deactivatedListeners(controller->shellEvents.shellDeactivated.GetListeners());
for (auto listener = deactivatedListeners.begin();
listener != deactivatedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) {
event->accept();
return;
}
}
}
break;
case QEvent::WindowStateChange:
{
ShellEvent::Pointer shellEvent(new ShellEvent(Shell::Pointer(controller->shell)));
QWindowStateChangeEvent* stateEvent = dynamic_cast<QWindowStateChangeEvent*>(event);
Qt::WindowStates oldState = stateEvent->oldState();
if (this->isMinimized() && !(oldState & Qt::WindowMinimized))
{
ListenerList iconifiedListeners(controller->shellEvents.shellIconified.GetListeners());
for (auto listener = iconifiedListeners.begin();
listener != iconifiedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) {
event->accept();
return;
}
}
}
else if (oldState & Qt::WindowMinimized && !this->isMinimized())
{
ListenerList deiconifiedListeners(controller->shellEvents.shellDeiconified.GetListeners());
for (auto listener = deiconifiedListeners.begin();
listener != deiconifiedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) return;
}
}
}
break;
default:
break;
}
QFrame::changeEvent(event);
}
void QtControlWidget::closeEvent(QCloseEvent* event)
{
typedef IShellListener::Events::ShellEventType::ListenerList ListenerList;
ShellEvent::Pointer shellEvent(new ShellEvent(Shell::Pointer(controller->shell)));
ListenerList closedListeners(controller->shellEvents.shellClosed.GetListeners());
for (auto listener = closedListeners.begin();
listener != closedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) {
//event->accept();
return;
}
}
event->accept();
}
void QtControlWidget::moveEvent(QMoveEvent* event)
{
GuiTk::ControlEvent::Pointer controlEvent(new GuiTk::ControlEvent(static_cast<QWidget*>(this), event->pos().x(), event->pos().y()));
controller->controlEvents.movedEvent(controlEvent);
}
void QtControlWidget::resizeEvent(QResizeEvent* event)
{
GuiTk::ControlEvent::Pointer controlEvent(new GuiTk::ControlEvent(static_cast<QWidget*>(this), 0, 0, event->size().width(), event->size().height()));
controller->controlEvents.resizedEvent(controlEvent);
}
void QtControlWidget::FireActivateEvent()
{
GuiTk::ControlEvent::Pointer controlEvent(new GuiTk::ControlEvent(static_cast<QWidget*>(this)));
controller->controlEvents.activatedEvent(controlEvent);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtControlWidget.h b/Plugins/org.blueberry.ui.qt/src/internal/berryQtControlWidget.h
index fba0244d08..9360ae7235 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtControlWidget.h
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtControlWidget.h
@@ -1,54 +1,54 @@
/*============================================================================
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 BERRYQTCONTROLWIDGET_H_
#define BERRYQTCONTROLWIDGET_H_
#include <QFrame>
#include "berryQtWidgetController.h"
#include <org_blueberry_ui_qt_Export.h>
namespace berry {
class BERRY_UI_QT QtControlWidget : public QFrame
{
public:
- QtControlWidget(QWidget* parent, Shell* shell, Qt::WindowFlags f = nullptr);
+ QtControlWidget(QWidget* parent, Shell* shell, Qt::WindowFlags f = {});
~QtControlWidget() override;
void FireActivateEvent();
protected:
// used for shell listeners
void changeEvent(QEvent* event) override;
void closeEvent(QCloseEvent* closeEvent) override;
// used for control listeners
void moveEvent(QMoveEvent* event) override;
void resizeEvent(QResizeEvent* event) override;
private:
QtWidgetController::Pointer controller;
};
}
#endif /* BERRYQTCONTROLWIDGET_H_ */
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtGlobalEventFilter.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtGlobalEventFilter.cpp
index d8effa6819..890238f344 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtGlobalEventFilter.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtGlobalEventFilter.cpp
@@ -1,57 +1,57 @@
/*============================================================================
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 "berryQtGlobalEventFilter.h"
#include "berryShell.h"
#include "internal/berryQtControlWidget.h"
#include <QEvent>
#include <QMouseEvent>
#include <QApplication>
#include <QWidget>
#include <iostream>
namespace berry {
QtGlobalEventFilter::QtGlobalEventFilter(QObject* parent)
: QObject(parent)
{
}
bool QtGlobalEventFilter::eventFilter(QObject* /*obj*/, QEvent* event)
{
if (event->type() == QEvent::MouseButtonPress)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
- QWidget* widget = QApplication::widgetAt(mouseEvent->globalPos());
+ QWidget* widget = QApplication::widgetAt(mouseEvent->globalPosition().toPoint());
if (widget)
{
QObject* parent = widget;
while (parent)
{
if (parent->objectName() == "PartPaneControl")
{
(dynamic_cast<QtControlWidget*>(parent))->FireActivateEvent();
break;
}
parent = parent->parent();
}
}
}
return false;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtMainWindowControl.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtMainWindowControl.cpp
index 9b752e30bb..6f3545ecac 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtMainWindowControl.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtMainWindowControl.cpp
@@ -1,151 +1,150 @@
/*============================================================================
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 "berryQtMainWindowControl.h"
#include <berryShell.h>
#include <QEvent>
#include <QMoveEvent>
#include <QResizeEvent>
#include <QWindowStateChangeEvent>
namespace berry {
QtMainWindowControl::QtMainWindowControl(Shell* shell, QWidget* parent, Qt::WindowFlags flags)
: QMainWindow(parent, flags)
{
controller = new QtWidgetController(shell);
// TODO WeakPointer: QVariant should hold a weak pointer
- QVariant variant(QVariant::UserType);
- variant.setValue(controller);
+ auto variant = QVariant::fromValue(controller);
this->setProperty(QtWidgetController::PROPERTY_ID, variant);
}
void QtMainWindowControl::changeEvent(QEvent* event)
{
if (!controller->shell)
return QMainWindow::changeEvent(event);
typedef IShellListener::Events::ShellEventType::ListenerList ListenerList;
ShellEvent::Pointer shellEvent(new ShellEvent(Shell::Pointer(controller->shell)));
switch (event->type())
{
case QEvent::ActivationChange:
{
if (isActiveWindow())
{
ListenerList activatedListeners(controller->shellEvents.shellActivated.GetListeners());
for (auto listener = activatedListeners.begin();
listener != activatedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) {
event->accept();
return;
}
}
}
else
{
ListenerList deactivatedListeners(controller->shellEvents.shellDeactivated.GetListeners());
for (auto listener = deactivatedListeners.begin();
listener != deactivatedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) {
event->accept();
return;
}
}
}
}
break;
case QEvent::WindowStateChange:
{
QWindowStateChangeEvent* stateEvent = dynamic_cast<QWindowStateChangeEvent*>(event);
Qt::WindowStates oldState = stateEvent->oldState();
if (this->isMinimized() && !(oldState & Qt::WindowMinimized))
{
ListenerList iconifiedListeners(controller->shellEvents.shellIconified.GetListeners());
for (auto listener = iconifiedListeners.begin();
listener != iconifiedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) {
event->accept();
return;
}
}
}
else if (oldState & Qt::WindowMinimized && !this->isMinimized())
{
ListenerList deiconifiedListeners(controller->shellEvents.shellDeiconified.GetListeners());
for (auto listener = deiconifiedListeners.begin();
listener != deiconifiedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) return;
}
}
}
break;
default:
break;
}
QMainWindow::changeEvent(event);
}
void QtMainWindowControl::closeEvent(QCloseEvent* event)
{
if (!controller->shell)
return QMainWindow::changeEvent(event);
typedef IShellListener::Events::ShellEventType::ListenerList ListenerList;
ShellEvent::Pointer shellEvent(new ShellEvent(Shell::Pointer(controller->shell)));
ListenerList closedListeners(controller->shellEvents.shellClosed.GetListeners());
for (auto listener = closedListeners.begin();
listener != closedListeners.end(); ++listener)
{
(*listener)->Execute(shellEvent);
if (!shellEvent->doit) {
event->ignore();
return;
}
}
QMainWindow::closeEvent(event);
}
void QtMainWindowControl::moveEvent(QMoveEvent* event)
{
GuiTk::ControlEvent::Pointer controlEvent(new GuiTk::ControlEvent(this, event->pos().x(), event->pos().y()));
controller->controlEvents.movedEvent(controlEvent);
}
void QtMainWindowControl::resizeEvent(QResizeEvent* event)
{
GuiTk::ControlEvent::Pointer controlEvent(new GuiTk::ControlEvent(this, 0, 0, event->size().width(), event->size().height()));
controller->controlEvents.resizedEvent(controlEvent);
}
void QtMainWindowControl::inFocusEvent(QFocusEvent* /*event*/)
{
GuiTk::ControlEvent::Pointer controlEvent(new GuiTk::ControlEvent(this));
controller->controlEvents.activatedEvent(controlEvent);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtMainWindowControl.h b/Plugins/org.blueberry.ui.qt/src/internal/berryQtMainWindowControl.h
index ba97f931ed..86bfc2ba78 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtMainWindowControl.h
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtMainWindowControl.h
@@ -1,52 +1,52 @@
/*============================================================================
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 BERRYQTMAINWINDOWCONTROL_H_
#define BERRYQTMAINWINDOWCONTROL_H_
#include <QMainWindow>
#include <berryShell.h>
#include <internal/berryQtWidgetController.h>
namespace berry {
class QtMainWindowControl : public QMainWindow
{
Q_OBJECT
public:
- QtMainWindowControl(Shell* shell, QWidget* parent = nullptr, Qt::WindowFlags flags = nullptr);
+ QtMainWindowControl(Shell* shell, QWidget* parent = nullptr, Qt::WindowFlags flags = {});
protected:
// used for shell listeners
void changeEvent(QEvent* event) override;
void closeEvent(QCloseEvent* closeEvent) override;
// used for control listeners
void moveEvent(QMoveEvent* event) override;
void resizeEvent(QResizeEvent* event) override;
void inFocusEvent(QFocusEvent* event);
private:
QtWidgetController::Pointer controller;
};
}
#endif /* BERRYQTMAINWINDOWCONTROL_H_ */
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtSash.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtSash.cpp
index d1761d3122..ce880798b5 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtSash.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtSash.cpp
@@ -1,296 +1,288 @@
/*============================================================================
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 "berryLog.h"
#include "berryQtSash.h"
#include <berryConstants.h>
#include <QMouseEvent>
#include <QStyleOption>
#include <QPainter>
namespace berry
{
/*!
Creates a QtSash with the given orientation, parent, and smoothness.
*/
QtSash::QtSash(Qt::Orientation orientation, QWidget *parent, bool smooth) :
QWidget(parent), smooth(smooth), orientation(orientation), rubberBand(nullptr),
lastX(0), lastY(0)
{
if (orientation == Qt::Horizontal)
this->setCursor(Qt::SplitVCursor);
else
this->setCursor(Qt::SplitHCursor);
}
QtSash::~QtSash()
{
}
void QtSash::AddSelectionListener(GuiTk::ISelectionListener::Pointer listener)
{
selectionEvents.AddListener(listener);
}
void QtSash::RemoveSelectionListener(
GuiTk::ISelectionListener::Pointer listener)
{
selectionEvents.AddListener(listener);
}
/*!
Returns the sash's orientation.
*/
Qt::Orientation QtSash::GetOrientation() const
{
return orientation;
}
/*!
Returns true if widgets are resized dynamically (smoothly), otherwise
returns false.
*/
bool QtSash::SmoothResize() const
{
return smooth;
}
/*!
Tells the splitter to move this handle to position \a pos, which is
the distance from the left or top edge of the widget.
Note that \a pos is also measured from the left (or top) for
right-to-left languages. This function will map \a pos to the
appropriate position before calling QSplitter::moveSplitter().
\sa QSplitter::moveSplitter() closestLegalPosition()
*/
//void QtSash::moveSplitter(int pos)
//{
// Q_D(QSplitterHandle);
// if (d->s->isRightToLeft() && d->orient == Qt::Horizontal)
// pos = d->s->contentsRect().width() - pos;
// d->s->moveSplitter(pos, d->s->indexOf(this));
//}
/*!
\reimp
*/
//QSize QtSash::sizeHint() const
//{
// Q_D(const QSplitterHandle);
// int hw = d->s->handleWidth();
// QStyleOption opt(0);
// opt.init(d->s);
// opt.state = QStyle::State_None;
// return parentWidget()->style()->sizeFromContents(QStyle::CT_Splitter, &opt, QSize(hw, hw), d->s)
// .expandedTo(QApplication::globalStrut());
//}
/*!
\reimp
*/
bool QtSash::event(QEvent *event)
{
// switch(event->type()) {
// case QEvent::HoverEnter:
// d->hover = true;
// update();
// break;
// case QEvent::HoverLeave:
// d->hover = false;
// update();
// break;
// default:
// break;
// }
return QWidget::event(event);
}
/*!
\reimp
*/
void QtSash::mouseMoveEvent(QMouseEvent *e)
{
if (!dragging && !(e->buttons() & Qt::LeftButton))
return;
- QPoint eventPoint(e->globalX(), e->globalY());
+ auto eventPoint = e->globalPosition().toPoint();
eventPoint = this->parentWidget()->mapFromGlobal(eventPoint);
+
int eventX = eventPoint.x();
int eventY = eventPoint.y();
-// int eventX = e->globalX();
-// int eventY = e->globalY();
-
- //int x = OS.GTK_WIDGET_X (handle);
- //int y = OS.GTK_WIDGET_Y (handle);
int width = this->geometry().width();
int height = this->geometry().height();
- //int parentBorder = 0;
- //int parentWidth = OS.GTK_WIDGET_WIDTH (parent.handle);
- //int parentHeight = OS.GTK_WIDGET_HEIGHT (parent.handle);
-
int newX = lastX;
int newY = lastY;
if ((orientation & Qt::Vertical) != 0)
{
//newX = std::min(std::max (0, eventX + x - startX - parentBorder), parentWidth - width);
newX = eventX;
}
else
{
// newY = Math.min (Math.max (0, eventY + y - startY - parentBorder), parentHeight - height);
newY = eventY;
}
if (newX == lastX && newY == lastY)
return;
drawRubberBand(lastX, lastY, width, height);
GuiTk::SelectionEvent::Pointer event(new GuiTk::SelectionEvent(this));
event->x = newX;
event->y = newY;
event->width = width;
event->height = height;
if (!smooth)
{
event->detail = Constants::DRAG;
}
selectionEvents.selected(event);
if (event->doit)
{
lastX = event->x;
lastY = event->y;
}
//parent.update (true, (style & SWT.SMOOTH) == 0);
drawRubberBand(lastX, lastY, width, height);
if (smooth)
{
setGeometry(lastX, lastY, width, height);
// widget could be disposed at this point
}
}
/*!
\reimp
*/
void QtSash::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton)
{
// const QRect& rect = this->geometry();
// QPoint p1(this->mapToGlobal(rect.topLeft()));
// QPoint p2(this->mapToGlobal(rect.bottomRight()));
// startRect = QRect(p1, p2);
startRect = this->geometry();
lastX = startRect.x();
lastY = startRect.y();
GuiTk::SelectionEvent::Pointer event(new GuiTk::SelectionEvent(this));
event->x = lastX;
event->y = lastY;
event->width = startRect.width();
event->height = startRect.height();
if (!smooth)
{
event->detail = Constants::DRAG;
}
selectionEvents.selected(event);
if (event->doit)
{
dragging = true;
lastX = event->x;
lastY = event->y;
//parent.update (true, (style & SWT.SMOOTH) == 0);
drawRubberBand(lastX, lastY, startRect.width(), startRect.height());
if (smooth)
{
this->setGeometry(lastX, lastY, startRect.width(), startRect.height());
// widget could be disposed at this point
}
}
}
}
/*!
\reimp
*/
void QtSash::mouseReleaseEvent(QMouseEvent *e)
{
if (dragging && e->button() == Qt::LeftButton)
{
this->drawRubberBand(-1, -1, -1, -1);
dragging = false;
const QRect& rect = this->geometry();
int width = rect.width();
int height = rect.height();
GuiTk::SelectionEvent::Pointer event(new GuiTk::SelectionEvent(this));
event->x = lastX;
event->y = lastY;
event->width = width;
event->height = height;
//drawBand (lastX, lastY, width, height);
selectionEvents.selected(event);
if (event->doit)
{
if (smooth)
{
this->setGeometry(event->x, event->y, width, height);
// widget could be disposed at this point
}
}
}
}
void QtSash::drawRubberBand(int x, int y, int width, int height)
{
if (smooth)
return;
if (x < 0 || y < 0)
{
if (this->rubberBand)
this->rubberBand->hide();
return;
}
if (!this->rubberBand)
{
this->rubberBand = new QRubberBand(QRubberBand::Line, this->parentWidget());
// For accessibility to identify this special widget.
this->rubberBand->setObjectName(QLatin1String("qt_rubberband"));
}
this->rubberBand->setGeometry(x, y, width, height);
if (!this->rubberBand->isVisible())
this->rubberBand->show();
}
void QtSash::paintEvent(QPaintEvent*)
{
QStyleOption opt;
- opt.init(this);
+ opt.initFrom(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShell.h b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShell.h
index ba1277183a..f055700391 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShell.h
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShell.h
@@ -1,81 +1,81 @@
/*============================================================================
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 BERRYQTMAINWINDOWSHELL_H_
#define BERRYQTMAINWINDOWSHELL_H_
#include <berryShell.h>
#include <QWidget>
namespace berry {
class QtAbstractControlWidget;
class QtShell : public Shell
{
public:
- QtShell(QWidget* parent = nullptr, Qt::WindowFlags flags = nullptr);
+ QtShell(QWidget* parent = nullptr, Qt::WindowFlags flags = {});
~QtShell() override;
// berry::Shell
void SetBounds(const QRect& bounds) override;
QRect GetBounds() const override;
void SetLocation(int x, int y) override;
QPoint ComputeSize(int wHint, int hHint, bool changed) override;
QString GetText() const override;
void SetText(const QString& text) override;
bool IsVisible() const override;
void SetVisible(bool visible) override;
void SetActive() override;
QWidget* GetControl() const override;
void SetImages(const QList<QIcon>& images) override;
bool GetMaximized() const override;
bool GetMinimized() const override;
void SetMaximized(bool maximized) override;
void SetMinimized(bool minimized) override;
void AddShellListener(IShellListener* listener) override;
void RemoveShellListener(IShellListener* listener) override;
void Open(bool block = false) override;
void Close() override;
QList<Shell::Pointer> GetShells() override;
Qt::WindowFlags GetStyle () const override;
QWidget* GetWidget();
private:
QWidget* widget;
bool updatesDisabled;
};
}
#endif /* BERRYQTMAINWINDOWSHELL_H_ */
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp
index c783409106..f7714bbcb5 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp
@@ -1,63 +1,63 @@
/*============================================================================
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 "berryQtShowPerspectiveDialog.h"
#include "ui_berryQtShowPerspectiveDialog.h"
#include <berryPerspectiveListModel.h>
#include <QSortFilterProxyModel>
namespace berry {
QtShowPerspectiveDialog::QtShowPerspectiveDialog(IPerspectiveRegistry* perspReg, QWidget *parent)
: QDialog(parent)
, ui(new Ui::QtShowPerspectiveDialog)
{
ui->setupUi(this);
QAbstractItemModel* model = new PerspectiveListModel(*perspReg, true, this);
auto proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->sort(0);
ui->m_ListView->setModel(proxyModel);
ui->m_ListView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->m_ListView->selectionModel()->select(model->index(0, 0), QItemSelectionModel::ClearAndSelect);
ui->m_ListView->setIconSize(QSize(16, 16));
connect(ui->m_ListView, SIGNAL(clicked(QModelIndex)), this, SLOT(setDescription(QModelIndex)));
connect(ui->m_ListView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
connect(ui->m_ListView, SIGNAL(activated(QModelIndex)), this, SLOT(accept()));
}
QtShowPerspectiveDialog::~QtShowPerspectiveDialog()
{
delete ui;
}
QString QtShowPerspectiveDialog::GetSelection() const
{
const QItemSelection selection = ui->m_ListView->selectionModel()->selection();
- if (selection.isEmpty()) return QString::null;
+ if (selection.isEmpty()) return QString();
return selection.indexes().front().data(PerspectiveListModel::Id).toString();
}
void QtShowPerspectiveDialog::setDescription(const QModelIndex& index)
{
ui->m_Description->setText(ui->m_ListView->model()->data(index, PerspectiveListModel::Description).toString());
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewAction.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewAction.cpp
index 8678fa9104..538cbf4bfa 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewAction.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewAction.cpp
@@ -1,55 +1,57 @@
/*============================================================================
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 "berryQtShowViewAction.h"
#include <berryIWorkbenchPage.h>
#include <berryUIException.h>
+#include <QWidget>
+
namespace berry
{
QtShowViewAction::QtShowViewAction(IWorkbenchWindow::Pointer window,
IViewDescriptor::Pointer desc) :
QAction(nullptr)
{
- this->setParent(static_cast<QWidget*>(window->GetShell()->GetControl()));
+ this->setParent(window->GetShell()->GetControl());
this->setText(desc->GetLabel());
this->setToolTip(desc->GetLabel());
this->setIconVisibleInMenu(true);
QIcon icon = desc->GetImageDescriptor();
this->setIcon(icon);
m_Window = window.GetPointer();
m_Desc = desc;
this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run()));
}
void QtShowViewAction::Run()
{
IWorkbenchPage::Pointer page = m_Window->GetActivePage();
if (page.IsNotNull())
{
try
{
page->ShowView(m_Desc->GetId());
}
catch (const PartInitException& e)
{
BERRY_ERROR << "Error: " << e.what();
}
}
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp
index bf38e33d11..51bda7e93a 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp
@@ -1,328 +1,328 @@
/*============================================================================
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 "berryQtShowViewDialog.h"
#include <berryIViewDescriptor.h>
#include <berryViewTreeModel.h>
#include "berryWorkbenchPlugin.h"
#include "berryXMLMemento.h"
#include <QSortFilterProxyModel>
#include <QPushButton>
#include <mitkIPreferences.h>
namespace berry {
static const QString TAG_SHOWVIEWDIALOG = "ShowViewDialog";
static const QString TAG_CATEGORY = "category";
static const QString TAG_SELECTION = "selection";
static const QString TAG_GEOMETRY = "geometry";
class ViewFilterProxyModel : public QSortFilterProxyModel
{
public:
ViewFilterProxyModel(QObject* parent = nullptr)
: QSortFilterProxyModel(parent)
, m_FilterOnKeywords(true)
{
this->setFilterCaseSensitivity(Qt::CaseInsensitive);
}
bool filterOnKeywords() const
{
return m_FilterOnKeywords;
}
void setFilterOnKeywords(bool filterOnKeywords)
{
if (m_FilterOnKeywords != filterOnKeywords)
{
m_FilterOnKeywords = filterOnKeywords;
- this->filterChanged();
+ this->invalidateFilter();
}
}
protected:
bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override
{
- QRegExp regExp = filterRegExp();
- if (!regExp.isValid() || regExp.isEmpty()) return true;
+ QRegularExpression regExp = filterRegularExpression();
+ if (!regExp.isValid() || regExp.pattern().isEmpty()) return true;
QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent);
QStringList keywords;
if (m_FilterOnKeywords)
{
keywords = sourceModel()->data(sourceIndex, ViewTreeModel::Keywords).toStringList();
}
else
{
if (sourceModel()->hasChildren(sourceIndex))
{
// this is a category item
int numChildren = sourceModel()->rowCount(sourceIndex);
for (int i = 0; i < numChildren; ++i)
{
- keywords.push_back(sourceModel()->data(sourceIndex.child(i, 0)).toString());
+ keywords.push_back(sourceModel()->data(sourceModel()->index(i, 0, sourceIndex)).toString());
}
}
else
{
// this is a view item
keywords.push_back(sourceModel()->data(sourceIndex).toString());
}
}
for(auto& keyword : keywords)
{
if (keyword.contains(regExp)) return true;
}
return false;
}
private:
bool m_FilterOnKeywords;
};
QtShowViewDialog::QtShowViewDialog(const IWorkbenchWindow* window, IViewRegistry* registry,
QWidget* parent, Qt::WindowFlags f)
: QDialog(parent, f)
, m_Window(window)
, m_ViewReg(registry)
, m_FilterModel(nullptr)
{
m_UserInterface.setupUi(this);
m_UserInterface.m_TreeView->header()->setVisible(false);
m_UserInterface.m_TreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_FilterModel = new ViewFilterProxyModel(this);
auto sourceModel = new ViewTreeModel(window, m_FilterModel);
m_FilterModel->setSourceModel(sourceModel);
m_UserInterface.m_TreeView->setModel(m_FilterModel);
connect(m_UserInterface.m_Filter, SIGNAL(textChanged(QString)), this, SLOT(setFilter(QString)));
connect(m_UserInterface.m_TreeView, SIGNAL(clicked(QModelIndex)), this, SLOT(setDescription(QModelIndex)));
connect(m_UserInterface.m_TreeView, SIGNAL(collapsed(QModelIndex)), this, SLOT(categoryCollapsed(QModelIndex)));
connect(m_UserInterface.m_TreeView, SIGNAL(expanded(QModelIndex)), this, SLOT(categoryExpanded(QModelIndex)));
connect(m_UserInterface.m_TreeView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
connect(m_UserInterface.m_TreeView, SIGNAL(activated(QModelIndex)), this, SLOT(accept()));
connect(m_UserInterface.m_TreeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
connect(m_UserInterface.m_KeywordFilter, SIGNAL(clicked(bool)), this, SLOT(enableKeywordFilter(bool)));
this->RestoreState();
m_UserInterface.m_Filter->selectAll();
this->UpdateButtons();
}
void QtShowViewDialog::setDescription(const QModelIndex& index)
{
QString description = m_UserInterface.m_TreeView->model()->data(index, Qt::WhatsThisRole).toString();
m_UserInterface.m_Description->setText(description);
}
void QtShowViewDialog::enableKeywordFilter(bool enable)
{
m_FilterModel->setFilterOnKeywords(enable);
this->RestoreExpandedState();
}
void QtShowViewDialog::setFilter(const QString& filter)
{
m_FilterModel->setFilterWildcard(filter);
this->RestoreExpandedState();
}
void QtShowViewDialog::categoryCollapsed(const QModelIndex& index)
{
m_ExpandedCategories.removeAll(m_FilterModel->mapToSource(index));
}
void QtShowViewDialog::categoryExpanded(const QModelIndex& index)
{
m_ExpandedCategories.push_back(m_FilterModel->mapToSource(index));
}
void QtShowViewDialog::selectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/)
{
UpdateButtons();
}
void QtShowViewDialog::RestoreExpandedState()
{
int rowCount = m_FilterModel->rowCount();
for (int i = 0; i < rowCount; ++i)
{
QModelIndex index = m_FilterModel->index(i, 0);
if (m_ExpandedCategories.contains(m_FilterModel->mapToSource(index)))
{
m_UserInterface.m_TreeView->expand(index);
}
}
}
void QtShowViewDialog::UpdateButtons()
{
QPushButton* okBtn = m_UserInterface.m_ButtonBox->button(QDialogButtonBox::Ok);
if (okBtn)
{
okBtn->setEnabled(!m_UserInterface.m_TreeView->selectionModel()->selection().isEmpty());
}
}
void QtShowViewDialog::RestoreState()
{
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
auto str = QString::fromStdString(prefs->Get(TAG_SHOWVIEWDIALOG.toStdString(), ""));
if (str.isEmpty()) return;
std::stringstream ss(str.toStdString());
XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss);
bool keywordFilter = false;
if (memento->GetBoolean("keywordFilter", keywordFilter))
{
m_UserInterface.m_KeywordFilter->setChecked(keywordFilter);
m_FilterModel->setFilterOnKeywords(keywordFilter);
}
QString filter;
if (memento->GetString("filter", filter))
{
m_UserInterface.m_Filter->setText(filter);
}
IMemento::Pointer geomChild = memento->GetChild(TAG_GEOMETRY);
if (geomChild.IsNotNull())
{
QString geom = geomChild->GetTextData();
if (!geom.isEmpty())
{
QByteArray ba = QByteArray::fromBase64(geom.toLatin1());
this->restoreGeometry(ba);
}
}
QHash<QString, QModelIndex> rootIndices;
int rowCount = m_FilterModel->sourceModel()->rowCount();
for (int i = 0; i < rowCount; ++i)
{
QModelIndex sourceIndex = m_FilterModel->sourceModel()->index(i, 0);
QString id = sourceIndex.data(ViewTreeModel::Id).toString();
if (!id.isEmpty())
{
rootIndices[id] = sourceIndex;
}
}
for (const IMemento::Pointer &categoryChild : memento->GetChildren(TAG_CATEGORY))
{
QString id = categoryChild->GetID();
if (!id.isEmpty())
{
if (rootIndices.contains(id))
{
m_ExpandedCategories.push_back(rootIndices[id]);
}
}
}
this->RestoreExpandedState();
QItemSelection itemSelection;
for (const IMemento::Pointer &selectionChild : memento->GetChildren(TAG_SELECTION))
{
QString id = selectionChild->GetID();
if (!id.isEmpty())
{
QModelIndexList indexList = m_FilterModel->match(m_FilterModel->index(0, 0), ViewTreeModel::Id, QVariant::fromValue(id),
1, Qt::MatchExactly | Qt::MatchRecursive);
if (!indexList.isEmpty())
{
QItemSelection subSelection(indexList.front(), indexList.front());
itemSelection.merge(subSelection, QItemSelectionModel::SelectCurrent);
}
}
}
m_UserInterface.m_TreeView->selectionModel()->select(itemSelection, QItemSelectionModel::ClearAndSelect);
}
void QtShowViewDialog::SaveState()
{
XMLMemento::Pointer memento = XMLMemento::CreateWriteRoot(TAG_SHOWVIEWDIALOG);
memento->PutString("filter", m_UserInterface.m_Filter->text());
memento->PutBoolean("keywordFilter", m_UserInterface.m_KeywordFilter->isChecked());
// dialog geometry
QByteArray geom = this->saveGeometry();
IMemento::Pointer geomChild = memento->CreateChild(TAG_GEOMETRY);
geomChild->PutTextData(geom.toBase64().constData());
// expanded categories
- for (const QPersistentModelIndex &index : qAsConst(m_ExpandedCategories))
+ for (const QPersistentModelIndex &index : std::as_const(m_ExpandedCategories))
{
if (index.isValid())
{
QString id = index.data(ViewTreeModel::Id).toString();
if (!id.isEmpty())
{
memento->CreateChild(TAG_CATEGORY, id);
}
}
}
// we only record a single selected item. restoring a multi-selection might be
// confusing for the user
QModelIndexList selectedIndices = m_UserInterface.m_TreeView->selectionModel()->selectedIndexes();
if (!selectedIndices.isEmpty())
{
QString id = selectedIndices.back().data(ViewTreeModel::Id).toString();
if (!id.isEmpty())
{
memento->CreateChild(TAG_SELECTION, id);
}
}
std::stringstream ss;
memento->Save(ss);
auto* prefs = WorkbenchPlugin::GetDefault()->GetPreferences();
prefs->Put(TAG_SHOWVIEWDIALOG.toStdString(), ss.str());
prefs->Flush();
}
void QtShowViewDialog::done(int r)
{
this->SaveState();
QDialog::done(r);
}
QList<QString>
QtShowViewDialog::GetSelection() const
{
QList<QString> selected;
QModelIndexList indices = m_UserInterface.m_TreeView->selectionModel()->selectedIndexes();
- for(QModelIndex index : qAsConst(indices))
+ for(QModelIndex index : std::as_const(indices))
{
QString id = m_FilterModel->data(index, ViewTreeModel::Id).toString();
selected.push_back(id);
}
return selected;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.h b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.h
index 92cc214fb9..9042c3d52c 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.h
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.h
@@ -1,69 +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 BERRYQTSHOWVIEWDIALOG_H_
#define BERRYQTSHOWVIEWDIALOG_H_
#include <berrySmartPointer.h>
#include <QDialog>
#include "ui_berryQtShowViewDialog.h"
namespace berry {
struct IViewRegistry;
struct IWorkbenchWindow;
class ViewFilterProxyModel;
class QtShowViewDialog : public QDialog
{
Q_OBJECT
public:
QtShowViewDialog(const IWorkbenchWindow* window, IViewRegistry* registry,
- QWidget* parent = nullptr, Qt::WindowFlags f = nullptr);
+ QWidget* parent = nullptr, Qt::WindowFlags f = {});
QList<QString> GetSelection() const;
private:
Q_SLOT void setDescription(const QModelIndex& index);
Q_SLOT void enableKeywordFilter(bool enable);
Q_SLOT void setFilter(const QString& filter);
Q_SLOT void categoryCollapsed(const QModelIndex& index);
Q_SLOT void categoryExpanded(const QModelIndex& index);
Q_SLOT void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected);
void RestoreExpandedState();
void UpdateButtons();
void RestoreState();
void SaveState();
void done(int r) override;
const IWorkbenchWindow* m_Window;
IViewRegistry* m_ViewReg;
Ui::QtShowViewDialog_ m_UserInterface;
ViewFilterProxyModel* m_FilterModel;
QList<QPersistentModelIndex> m_ExpandedCategories;
};
}
#endif /*BERRYQTSHOWVIEWDIALOG_H_*/
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp
index 489840defb..5b8cb25bb4 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtStylePreferencePage.cpp
@@ -1,272 +1,272 @@
/*============================================================================
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 "berryQtStylePreferencePage.h"
#include "berryWorkbenchPlugin.h"
#include <berryQtPreferences.h>
#include <QFileDialog>
#include <QDirIterator>
#include <QFontDatabase>
#include <mitkIPreferences.h>
namespace
{
mitk::IPreferences* GetPreferences()
{
return berry::WorkbenchPlugin::GetDefault()->GetPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE);
}
}
namespace berry
{
QtStylePreferencePage::QtStylePreferencePage()
{
}
void QtStylePreferencePage::Init(IWorkbench::Pointer )
{
}
void QtStylePreferencePage::CreateQtControl(QWidget* parent)
{
mainWidget = new QWidget(parent);
controls.setupUi(mainWidget);
ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();
ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();
if (styleManagerRef)
{
styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);
}
Update();
connect(controls.m_StylesCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(StyleChanged(int)));
connect(controls.m_FontComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(FontChanged(int)));
connect(controls.m_FontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(FontChanged(int)));
connect(controls.m_PathList, SIGNAL(itemSelectionChanged()), this, SLOT(UpdatePathListButtons()));
connect(controls.m_AddButton, SIGNAL(clicked(bool)), this, SLOT(AddPathClicked(bool)));
connect(controls.m_EditButton, SIGNAL(clicked(bool)), this, SLOT(EditPathClicked(bool)));
connect(controls.m_RemoveButton, SIGNAL(clicked(bool)), this, SLOT(RemovePathClicked(bool)));
}
void QtStylePreferencePage::FillStyleCombo(const berry::IQtStyleManager::Style& currentStyle)
{
controls.m_StylesCombo->clear();
styles.clear();
styleManager->GetStyles(styles);
- qSort(styles);
+ std::sort(styles.begin(), styles.end());
for (int i = 0; i < styles.size(); ++i)
{
controls.m_StylesCombo->addItem(styles.at(i).name, QVariant(styles.at(i).fileName));
}
controls.m_StylesCombo->setCurrentIndex(styles.indexOf(currentStyle));
}
void QtStylePreferencePage::FillFontCombo(const QString& currentFont)
{
controls.m_FontComboBox->clear();
QStringList fonts;
styleManager->GetFonts(fonts);
for (int i = 0; i < fonts.size(); ++i)
{
controls.m_FontComboBox->addItem(fonts.at(i));
}
controls.m_FontComboBox->setCurrentIndex(fonts.indexOf(currentFont));
if (currentFont == QString("<<system>>"))
{
controls.m_FontSizeSpinBox->setEnabled(false);
}
else
{
controls.m_FontSizeSpinBox->setEnabled(true);
}
}
void QtStylePreferencePage::AddPath(const QString& path, bool updateCombo)
{
if (!controls.m_PathList->findItems(path, Qt::MatchCaseSensitive).isEmpty()) return;
new QListWidgetItem(path, controls.m_PathList);
styleManager->AddStyles(path);
if (updateCombo)
FillStyleCombo(oldStyle);
}
void QtStylePreferencePage::StyleChanged(int /*index*/)
{
QString fileName = controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString();
styleManager->SetStyle(fileName);
}
void QtStylePreferencePage::FontChanged(int /*index*/)
{
QString fontName = controls.m_FontComboBox->currentText();
int fontSize = controls.m_FontSizeSpinBox->value();
if (fontName == QString("<<system>>"))
{
controls.m_FontSizeSpinBox->setEnabled(false);
}
else
{
controls.m_FontSizeSpinBox->setEnabled(true);
}
styleManager->SetFont(fontName);
styleManager->SetFontSize(fontSize);
styleManager->UpdateWorkbenchFont();
}
void QtStylePreferencePage::AddPathClicked(bool /*checked*/)
{
QListWidgetItem* item = controls.m_PathList->currentItem();
QString initialDir;
if (item) initialDir = item->text();
QString dir = QFileDialog::getExistingDirectory(mainWidget, "", initialDir);
if (!dir.isEmpty()) this->AddPath(dir, true);
}
void QtStylePreferencePage::RemovePathClicked(bool /*checked*/)
{
QList<QListWidgetItem*> selection = controls.m_PathList->selectedItems();
QListIterator<QListWidgetItem*> it(selection);
while (it.hasNext())
{
QListWidgetItem* item = it.next();
QString dir = item->text();
controls.m_PathList->takeItem(controls.m_PathList->row(item));
delete item;
styleManager->RemoveStyles(dir);
}
if (!styleManager->Contains(oldStyle.fileName))
{
oldStyle = styleManager->GetDefaultStyle();
}
FillStyleCombo(oldStyle);
}
void QtStylePreferencePage::EditPathClicked(bool checked)
{
QListWidgetItem* item = controls.m_PathList->currentItem();
QString initialDir = item->text();
QString dir = QFileDialog::getExistingDirectory(mainWidget, "", initialDir);
if (!dir.isEmpty())
{
this->RemovePathClicked(checked);
this->AddPath(dir, true);
}
}
void QtStylePreferencePage::UpdatePathListButtons()
{
int s = controls.m_PathList->selectedItems().size();
if (s == 0)
{
controls.m_EditButton->setEnabled(false);
controls.m_RemoveButton->setEnabled(false);
}
else if (s == 1)
{
controls.m_EditButton->setEnabled(true);
controls.m_RemoveButton->setEnabled(true);
}
else
{
controls.m_EditButton->setEnabled(false);
controls.m_RemoveButton->setEnabled(true);
}
}
QWidget* QtStylePreferencePage::GetQtControl() const
{
return mainWidget;
}
bool QtStylePreferencePage::PerformOk()
{
auto* prefs = GetPreferences();
prefs->Put(berry::QtPreferences::QT_STYLE_NAME, controls.m_StylesCombo->itemData(controls.m_StylesCombo->currentIndex()).toString().toStdString());
QString paths;
for (int i = 0; i < controls.m_PathList->count(); ++i)
{
QString path = controls.m_PathList->item(i)->text() + ";";
paths += path;
}
prefs->Put(berry::QtPreferences::QT_STYLE_SEARCHPATHS, paths.toStdString());
prefs->Put(berry::QtPreferences::QT_FONT_NAME, controls.m_FontComboBox->currentText().toStdString());
prefs->Put(berry::QtPreferences::QT_FONT_SIZE, std::to_string(controls.m_FontSizeSpinBox->value()));
prefs->PutBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES,
controls.m_ToolbarCategoryCheckBox->isChecked());
return true;
}
void QtStylePreferencePage::PerformCancel()
{
Update();
}
void QtStylePreferencePage::Update()
{
styleManager->RemoveStyles();
auto* prefs = GetPreferences();
auto paths = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_STYLE_SEARCHPATHS, ""));
- QStringList pathList = paths.split(";", QString::SkipEmptyParts);
+ QStringList pathList = paths.split(";", Qt::SkipEmptyParts);
QStringListIterator it(pathList);
while (it.hasNext())
{
AddPath(it.next(), false);
}
auto styleName = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_STYLE_NAME, ""));
styleManager->SetStyle(styleName);
oldStyle = styleManager->GetStyle();
FillStyleCombo(oldStyle);
auto fontName = QString::fromStdString(prefs->Get(berry::QtPreferences::QT_FONT_NAME, "Open Sans"));
styleManager->SetFont(fontName);
auto fontSize = std::stoi(prefs->Get(berry::QtPreferences::QT_FONT_SIZE, "9"));
styleManager->SetFontSize(fontSize);
controls.m_FontSizeSpinBox->setValue(fontSize);
styleManager->UpdateWorkbenchFont();
FillFontCombo(styleManager->GetFont());
controls.m_ToolbarCategoryCheckBox->setChecked(
prefs->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true));
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp
index 456b947984..457ee2222a 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtTracker.cpp
@@ -1,328 +1,327 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryTweaklets.h"
#include "berryQtTracker.h"
#include "berryConstants.h"
#include "berryIDropTarget.h"
#include "berryDragUtil.h"
#include "berryGuiWidgetsTweaklet.h"
#include <QEvent>
#include <QKeyEvent>
#include <QApplication>
#include <QRubberBand>
#include <QPixmap>
namespace berry
{
CursorType QtDragManager::PositionToCursorType(int positionConstant)
{
if (positionConstant == Constants::LEFT)
return CURSOR_LEFT;
if (positionConstant == Constants::RIGHT)
return CURSOR_RIGHT;
if (positionConstant == Constants::TOP)
return CURSOR_TOP;
if (positionConstant == Constants::BOTTOM)
return CURSOR_BOTTOM;
if (positionConstant == Constants::CENTER)
return CURSOR_CENTER;
return CURSOR_INVALID;
}
int QtDragManager::CursorTypeToPosition(CursorType dragCursorId)
{
switch (dragCursorId)
{
case CURSOR_LEFT:
return Constants::LEFT;
case CURSOR_RIGHT:
return Constants::RIGHT;
case CURSOR_TOP:
return Constants::TOP;
case CURSOR_BOTTOM:
return Constants::BOTTOM;
case CURSOR_CENTER:
return Constants::CENTER;
default:
return Constants::DEFAULT;
}
}
bool QtDragManager::eventFilter(QObject* o, QEvent* e)
{
if (beingCancelled)
{
if (e->type() == QEvent::KeyRelease && ((QKeyEvent*) e)->key()
== Qt::Key_Escape)
{
QApplication::instance()->removeEventFilter(this);
beingCancelled = false;
eventLoop->exit();
return true; // block the key release
}
return false;
}
if (!o->isWidgetType())
return false;
if (e->type() == QEvent::MouseMove)
{
QMouseEvent* me = (QMouseEvent *) e;
- this->Move(me->globalPos());
+ this->Move(me->globalPosition().toPoint());
return true;
}
else if (e->type() == QEvent::MouseButtonRelease)
{
//DEBUG("pre drop");
QApplication::instance()->removeEventFilter(this);
beingCancelled = false;
eventLoop->exit();
return true;
}
if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease)
{
QKeyEvent *ke = ((QKeyEvent*) e);
if (ke->key() == Qt::Key_Escape && e->type() == QEvent::KeyPress)
{
this->Cancel();
QApplication::instance()->removeEventFilter(this);
//beingCancelled = false;
eventLoop->exit();
}
else
{
// move(QCursor::pos());
}
return true; // Eat all key events
}
// ### We bind modality to widgets, so we have to do this
// ### "manually".
// DnD is modal - eat all other interactive events
switch (e->type())
{
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseMove:
case QEvent::KeyPress:
case QEvent::KeyRelease:
case QEvent::Wheel:
case QEvent::ShortcutOverride:
#ifdef QT3_SUPPORT
case QEvent::Accel:
case QEvent::AccelAvailable:
#endif
return true;
default:
return false;
}
}
void QtDragManager::Cancel()
{
beingCancelled = true;
}
void QtDragManager::Move(const QPoint& globalPos)
{
emit tracker->Moved(tracker, globalPos);
}
bool QtDragManager::Drag(QtTracker* tracker)
{
if (tracker == nullptr)
return false;
this->tracker = tracker;
beingCancelled = false;
QApplication::instance()->installEventFilter(this);
// if (!QWidget::mouseGrabber())
// rubberBand->grabMouse();
eventLoop = new QEventLoop;
eventLoop->exec();
delete eventLoop;
eventLoop = nullptr;
return !beingCancelled;
}
QtTracker::QtTracker() :
rubberBand(nullptr), dragManager(nullptr), cursorOverride(0)
{
rubberBand = new QRubberBand(QRubberBand::Rectangle);
QPalette rubberPalette(rubberBand->palette());
//rubberPalette.setColor(QPalette::Button, QColor(Qt::darkRed));
- rubberPalette.setBrush(QPalette::Foreground, QBrush(Qt::darkRed));
+ rubberPalette.setBrush(QPalette::WindowText, QBrush(Qt::darkRed));
rubberPalette.setBrush(QPalette::Window, QBrush(Qt::darkRed));
- rubberPalette.setBrush(QPalette::Background, QBrush(Qt::darkRed));
rubberPalette.setBrush(QPalette::Base, QBrush(Qt::darkRed));
rubberPalette.setBrush(QPalette::Text, QBrush(Qt::darkRed));
rubberBand->setPalette(rubberPalette);
rubberBand->ensurePolished();
QPixmap pixCursorTop(":/org.blueberry.ui.qt/cursor_top.xpm");
auto cursorTop = new QCursor(pixCursorTop, 15, 8);
cursorMap.insert(CURSOR_TOP, cursorTop);
QPixmap pixCursorRight(":/org.blueberry.ui.qt/cursor_right.xpm");
auto cursorRight = new QCursor(pixCursorRight, 23, 15);
cursorMap.insert(CURSOR_RIGHT, cursorRight);
QPixmap pixCursorBottom(":/org.blueberry.ui.qt/cursor_bottom.xpm");
auto cursorBottom = new QCursor(pixCursorBottom, 16, 23);
cursorMap.insert(CURSOR_BOTTOM, cursorBottom);
QPixmap pixCursorLeft(":/org.blueberry.ui.qt/cursor_left.xpm");
auto cursorLeft = new QCursor(pixCursorLeft, 8, 15);
cursorMap.insert(CURSOR_LEFT, cursorLeft);
QPixmap pixCursorCenter(":/org.blueberry.ui.qt/cursor_center.xpm");
auto cursorCenter = new QCursor(pixCursorCenter, 15, 15);
cursorMap.insert(CURSOR_CENTER, cursorCenter);
QPixmap pixCursorOffscreen(":/org.blueberry.ui.qt/cursor_offscreen.xpm");
auto cursorOffscreen = new QCursor(pixCursorOffscreen, 15, 15);
cursorMap.insert(CURSOR_OFFSCREEN, cursorOffscreen);
auto cursorInvalid = new QCursor(Qt::ForbiddenCursor);
cursorMap.insert(CURSOR_INVALID, cursorInvalid);
}
QtTracker::~QtTracker()
{
delete rubberBand;
for (QHash<CursorType, QCursor*>::iterator iter = cursorMap.begin();
iter != cursorMap.end(); ++iter)
{
delete iter.value();
}
}
QRect QtTracker::GetRectangle() const
{
return rubberBand->geometry();
}
void QtTracker::SetRectangle(const QRect& rectangle)
{
rubberBand->setGeometry(rectangle);
}
void QtTracker::SetCursor(CursorType cursorType)
{
QCursor* cursor = cursorMap[cursorType];
if (!cursor) return;
if (cursorOverride > 0)
{
QApplication::changeOverrideCursor(*cursor);
}
else
{
++cursorOverride;
QApplication::setOverrideCursor(*cursor);
}
}
bool QtTracker::Open()
{
rubberBand->show();
dragManager = new QtDragManager();
bool result = dragManager->Drag(this);
delete dragManager;
rubberBand->hide();
while (cursorOverride > 0)
{
QApplication::restoreOverrideCursor();
--cursorOverride;
}
return result;
}
QtTrackerMoveListener::QtTrackerMoveListener(Object::Pointer draggedItem,
const QRect& sourceBounds,
const QPoint& initialLocation,
bool allowSnapping)
: allowSnapping(allowSnapping)
, draggedItem(draggedItem)
, sourceBounds(sourceBounds)
, initialLocation(initialLocation)
{
}
void QtTrackerMoveListener::Moved(QtTracker* tracker, const QPoint& location)
{
// Select a drop target; use the global one by default
IDropTarget::Pointer target;
QWidget* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl();
// Get the drop target for this location
target = DragUtil::GetDropTarget(targetControl, draggedItem, location,
tracker->GetRectangle());
// Set up the tracker feedback based on the target
QRect snapTarget;
if (target != 0)
{
snapTarget = target->GetSnapRectangle();
tracker->SetCursor(target->GetCursor());
}
else
{
tracker->SetCursor(CURSOR_INVALID);
}
// If snapping then reset the tracker's rectangle based on the current drop target
if (allowSnapping)
{
if (snapTarget.width() <= 0 || snapTarget.height() <= 0)
{
snapTarget = QRect(sourceBounds.x() + location.x() - initialLocation.x(),
sourceBounds.y() + location.y() - initialLocation.y(), sourceBounds.width(),
sourceBounds.height());
}
// Try to prevent flicker: don't change the rectangles if they're already in
// the right location
QRect currentRectangle = tracker->GetRectangle();
if (!(currentRectangle == snapTarget))
{
tracker->SetRectangle(snapTarget);
}
}
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.h b/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.h
index b6ea262bba..3197b38fad 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.h
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweaklet.h
@@ -1,127 +1,127 @@
/*============================================================================
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 BERRYQTWIDGETSTWEAKLET_H_
#define BERRYQTWIDGETSTWEAKLET_H_
#include <berryGuiWidgetsTweaklet.h>
#include "berryQtWidgetsTweakletImpl.h"
namespace berry {
class QtWidgetsTweaklet : public QObject, public GuiWidgetsTweaklet
{
Q_OBJECT
Q_INTERFACES(berry::GuiWidgetsTweaklet)
public:
QtWidgetsTweaklet();
void AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) override;
void RemoveSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) override;
void AddControlListener(QWidget* widget, GuiTk::IControlListener::Pointer listener) override;
void RemoveControlListener(QWidget* widget, GuiTk::IControlListener::Pointer listener) override;
bool GetEnabled(QWidget* widget) override;
void SetEnabled(QWidget* widget, bool enabled) override;
void SetBounds(QWidget* widget, const QRect& bounds) override;
QRect GetBounds(QWidget* widget) override;
void SetVisible(QWidget* widget, bool visible) override;
bool GetVisible(QWidget* widget) override;
bool IsVisible(QWidget* widget) override;
QRect GetClientArea(QWidget* widget) override;
QWidget* GetParent(QWidget* widget) override;
bool SetParent(QWidget* widget, QWidget* parent) override;
void SetData(QWidget* widget, const QString& id, Object::Pointer data) override;
Object::Pointer GetData(QWidget* widget, const QString& id) override;
//IMenu::Pointer CreateMenu(QWidget*, IMenu::Style = IMenu::POP_UP);
//IMenu::Pointer CreateMenu(IMenu::Pointer parent);
//IMenuItem::Pointer CreateMenuItem(IMenu::Pointer, IMenuItem::Style, int index = -1);
- QRect GetScreenSize(int i = -1) override;
+ QRect GetScreenSize(int i = 0) override;
unsigned int GetScreenNumber() override;
int GetPrimaryScreenNumber() override;
QRect GetAvailableScreenSize(int i = -1) override;
int GetClosestScreenNumber(const QRect&) override;
QPoint GetCursorLocation() override;
QWidget* GetCursorControl() override;
QWidget* FindControl(const QList<Shell::Pointer>& shells, const QPoint& location) override;
/**
* Determines if one control is a child of another. Returns true iff the second
* argument is a child of the first (or the same object).
*
* @param potentialParent
* @param childToTest
* @return
*/
bool IsChild(QWidget* potentialParent, QWidget* childToTest) override;
/**
* Returns the control which currently has keyboard focus,
* or null if keyboard events are not currently going to
* any of the controls built by the currently running
* application.
*
* @return the control under the cursor
*/
QWidget* GetFocusControl() override;
bool IsReparentable(QWidget* widget) override;
void MoveAbove(QWidget* widgetToMove, QWidget* widget) override;
void MoveBelow(QWidget* widgetToMove, QWidget* widget) override;
void Dispose(QWidget* widget) override;
Shell::Pointer CreateShell(Shell::Pointer parent, int style) override;
void DisposeShell(Shell::Pointer shell) override;
QWidget* CreateComposite(QWidget* parent) override;
QList<Shell::Pointer> GetShells() override;
Shell::Pointer GetShell(QWidget* widget) override;
Shell::Pointer GetActiveShell() override;
QRect ToControl(QWidget* coordinateSystem,
const QRect& toConvert) override;
QPoint ToControl(QWidget* coordinateSystem,
const QPoint& toConvert) override;
QRect ToDisplay(QWidget* coordinateSystem,
const QRect& toConvert) override;
QPoint ToDisplay(QWidget* coordinateSystem,
const QPoint& toConvert) override;
private:
QtWidgetsTweakletImpl impl;
};
}
#endif /* BERRYQTWIDGETSTWEAKLET_H_ */
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp
index b251d0d7ee..fc03fae215 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp
@@ -1,424 +1,437 @@
/*============================================================================
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 "berryLog.h"
#include "berryQtWidgetsTweakletImpl.h"
#include "berryQtSash.h"
#include "berryQtShell.h"
#include <internal/berryQtControlWidget.h>
#include <berryConstants.h>
#include <QAbstractButton>
-#include <QDesktopWidget>
#include <QApplication>
+#include <QScreen>
#include <QVariant>
namespace berry {
QtSelectionListenerWrapper::QtSelectionListenerWrapper(QWidget* w)
: widget(w)
{
}
void QtSelectionListenerWrapper::AddListener(GuiTk::ISelectionListener::Pointer listener)
{
QAbstractButton* button = qobject_cast<QAbstractButton*>(widget);
if (button != nullptr)
{
this->connect(button, "clicked(bool)", this, "QAbstractButtonClicked(bool)");
selectionEvents.AddListener(listener);
}
BERRY_WARN << "WARNING: QtWidgetsTweaklet: no suitable type for listening for selections found!\n";
}
int QtSelectionListenerWrapper::RemoveListener(GuiTk::ISelectionListener::Pointer listener)
{
selectionEvents.RemoveListener(listener);
return static_cast<int>(std::max<std::size_t>(selectionEvents.selected.GetListeners().size(),
selectionEvents.defaultSelected.GetListeners().size()));
}
void QtSelectionListenerWrapper::QAbstractButtonClicked(bool /*checked*/)
{
GuiTk::SelectionEvent::Pointer event(new GuiTk::SelectionEvent(widget));
selectionEvents.selected(event);
}
void QtWidgetsTweakletImpl::AddSelectionListener(QWidget* widget,
GuiTk::ISelectionListener::Pointer listener)
{
if (widget == nullptr) return;
// special handling for berry::QtSash
QtSash* sash = qobject_cast<QtSash*>(widget);
if (sash != nullptr)
{
sash->AddSelectionListener(listener);
return;
}
// "normal" Qt widgets get wrapped
QtSelectionListenerWrapper* wrapper = selectionListenerMap[widget];
if (wrapper == nullptr)
{
wrapper = new QtSelectionListenerWrapper(widget);
selectionListenerMap[widget] = wrapper;
}
wrapper->AddListener(listener);
}
void QtWidgetsTweakletImpl::RemoveSelectionListener(QWidget* widget,
GuiTk::ISelectionListener::Pointer listener)
{
if (widget == nullptr) return;
// special handling for berry::QtSash
QtSash* sash = qobject_cast<QtSash*>(widget);
if (sash != nullptr)
{
sash->RemoveSelectionListener(listener);
return;
}
QtSelectionListenerWrapper* wrapper = selectionListenerMap[widget];
if (wrapper == nullptr) return;
if (wrapper->RemoveListener(listener) == 0)
{
selectionListenerMap.remove(widget);
delete wrapper;
}
}
QRect QtWidgetsTweakletImpl::GetScreenSize(int i)
{
- QDesktopWidget *desktop = QApplication::desktop();
- if (i < 0) return desktop->screen()->geometry();
- return desktop->screenGeometry(i);
+ return QGuiApplication::screens().at(i)->geometry();
}
unsigned int QtWidgetsTweakletImpl::GetScreenNumber()
{
- QDesktopWidget *desktop = QApplication::desktop();
- // get the primary screen
- unsigned int numScreens = desktop->numScreens();
- return numScreens;
+ return QGuiApplication::screens().size();
}
int QtWidgetsTweakletImpl::GetPrimaryScreenNumber()
{
- QDesktopWidget *desktop = QApplication::desktop();
- // get the primary screen
- int primaryScreenNr = desktop->primaryScreen();
- return primaryScreenNr;
+ auto primaryScreenHandle = QGuiApplication::primaryScreen()->handle();
+ auto screens = QGuiApplication::screens();
+ const auto numberOfScreens = static_cast<int>(screens.size());
+
+ for (int i = 0; i < numberOfScreens; ++i)
+ {
+ if (screens[i]->handle() == primaryScreenHandle)
+ return i;
+ }
+
+ return 0;
}
QRect QtWidgetsTweakletImpl::GetAvailableScreenSize(int i)
{
- QDesktopWidget *desktop = QApplication::desktop();
- if (i < 0) return desktop->screen()->geometry();
- return desktop->availableGeometry(i);
+ return QGuiApplication::screens().at(i)->availableGeometry();
}
int QtWidgetsTweakletImpl::GetClosestScreenNumber(const QRect& r)
{
- QDesktopWidget *desktop = QApplication::desktop();
- return desktop->screenNumber(QPoint(r.x() + r.width()/2, r.y() + r.height()/2));
+ auto screen = QGuiApplication::screenAt(QPoint(r.x() + r.width() / 2, r.y() + r.height() / 2));
+
+ if (screen != nullptr)
+ {
+ auto screens = QGuiApplication::screens();
+ const auto numberOfScreens = static_cast<int>(screens.size());
+
+ for (int i = 0; i < numberOfScreens; ++i)
+ {
+ if (screens[i]->handle() == screen->handle())
+ return i;
+ }
+ }
+
+ return 0;
}
void QtWidgetsTweakletImpl::AddControlListener(QtWidgetController* controller,
GuiTk::IControlListener::Pointer listener)
{
controller->AddControlListener(listener);
}
void QtWidgetsTweakletImpl::RemoveControlListener(QtWidgetController* controller,
GuiTk::IControlListener::Pointer listener)
{
controller->RemoveControlListener(listener);
}
bool QtWidgetsTweakletImpl::GetEnabled(QWidget* widget)
{
return widget->isEnabled();
}
void QtWidgetsTweakletImpl::SetEnabled(QWidget* widget, bool enabled)
{
widget->setEnabled(enabled);
}
void QtWidgetsTweakletImpl::SetBounds(QWidget* widget, const QRect& bounds)
{
widget->setGeometry(bounds);
}
QRect QtWidgetsTweakletImpl::GetBounds(QWidget* widget)
{
const QRect& geometry = widget->geometry();
QRect rect(geometry.x(), geometry.y(), geometry.width(), geometry.height());
return rect;
}
void QtWidgetsTweakletImpl::SetVisible(QWidget* widget, bool visible)
{
widget->setVisible(visible);
}
bool QtWidgetsTweakletImpl::GetVisible(QWidget* widget)
{
return !widget->isHidden();
}
bool QtWidgetsTweakletImpl::IsVisible(QWidget* widget)
{
return widget->isVisible();
}
QRect QtWidgetsTweakletImpl::GetClientArea(QWidget* widget)
{
return widget->contentsRect();
}
QWidget* QtWidgetsTweakletImpl::GetParent(QWidget* widget)
{
return widget->parentWidget();
}
bool QtWidgetsTweakletImpl::SetParent(QWidget* widget, QWidget* parent)
{
if (parent != widget->parentWidget())
{
widget->setParent(parent);
return true;
}
return false;
}
void QtWidgetsTweakletImpl::SetData(QWidget* object, const QString& id, Object::Pointer data)
{
if (object == nullptr) return;
QVariant variant;
if (data != 0)
variant.setValue(data);
object->setProperty(qPrintable(id), variant);
}
Object::Pointer QtWidgetsTweakletImpl::GetData(QWidget* object, const QString& id)
{
if (object == nullptr) return Object::Pointer(nullptr);
QVariant variant = object->property(qPrintable(id));
if (variant.isValid())
{
return variant.value<Object::Pointer>();
}
return Object::Pointer(nullptr);
}
QPoint QtWidgetsTweakletImpl::GetCursorLocation()
{
QPoint qpoint = QCursor::pos();
return QPoint(qpoint.x(), qpoint.y());
}
QWidget* QtWidgetsTweakletImpl::GetCursorControl()
{
return QApplication::widgetAt(QCursor::pos());
}
QWidget* QtWidgetsTweakletImpl::FindControl(const QList<Shell::Pointer>& shells, const QPoint& location)
{
for (QList<Shell::Pointer>::const_iterator iter = shells.begin();
iter != shells.end(); ++iter)
{
QWidget* shellWidget = static_cast<QWidget*>((*iter)->GetControl());
QWidget* control = shellWidget->childAt(location.x(), location.y());
if (control) return control;
}
return nullptr;
}
bool QtWidgetsTweakletImpl::IsChild(QObject* parentToTest, QObject* childToTest)
{
bool found = false;
QObject* parent = childToTest->parent();
while (!found && parent != nullptr)
{
if (parent == parentToTest) found = true;
parent = parent->parent();
}
return found;
}
QWidget* QtWidgetsTweakletImpl::GetFocusControl()
{
return QApplication::focusWidget();
}
bool QtWidgetsTweakletImpl::IsReparentable(QWidget* /*widget*/)
{
return true;
}
void QtWidgetsTweakletImpl::MoveAbove(QWidget* widgetToMove, QWidget* /*widget*/)
{
widgetToMove->raise();
}
void QtWidgetsTweakletImpl::MoveBelow(QWidget* widgetToMove, QWidget* /*widget*/)
{
widgetToMove->lower();
}
void QtWidgetsTweakletImpl::Dispose(QWidget* widget)
{
delete widget;
widget = nullptr;
}
Shell::Pointer QtWidgetsTweakletImpl::CreateShell(Shell::Pointer parent, int style)
{
Qt::WindowFlags qtFlags(Qt::CustomizeWindowHint);
if (style & Constants::MAX)
qtFlags |= Qt::WindowMaximizeButtonHint;
if (style & Constants::MIN)
qtFlags |= Qt::WindowMinimizeButtonHint;
if (style & Constants::CLOSE)
{
qtFlags |= Qt::WindowSystemMenuHint;
qtFlags |= Qt::WindowCloseButtonHint;
}
if (!(style & Constants::BORDER))
qtFlags |= Qt::FramelessWindowHint;
if (style & Constants::TITLE)
qtFlags |= Qt::WindowTitleHint;
if (style & Constants::TOOL)
qtFlags |= Qt::Tool;
QWidget* parentWidget = nullptr;
if (parent != 0)
parentWidget = static_cast<QWidget*>(parent->GetControl());
auto qtshell = new QtShell(parentWidget, qtFlags);
Shell::Pointer shell(qtshell);
shellList.push_back(shell);
if ((style & Constants::APPLICATION_MODAL)
|| (style & Constants::SYSTEM_MODAL)) qtshell->GetWidget()->setWindowModality(Qt::ApplicationModal);
if (style & Constants::PRIMARY_MODAL) qtshell->GetWidget()->setWindowModality(Qt::WindowModal);
return shell;
}
QWidget* QtWidgetsTweakletImpl::CreateComposite(QWidget* parent)
{
QWidget* composite = new QtControlWidget(parent, nullptr);
composite->setObjectName("created composite");
return composite;
}
void QtWidgetsTweakletImpl::DisposeShell(Shell::Pointer shell)
{
shellList.removeAll(shell);
shell->SetVisible(false);
}
QList<Shell::Pointer> QtWidgetsTweakletImpl::GetShells()
{
return shellList;
}
Shell::Pointer QtWidgetsTweakletImpl::GetShell(QWidget* widget)
{
QWidget* qwindow = widget->window();
QVariant variant = qwindow->property(QtWidgetController::PROPERTY_ID);
if (variant.isValid())
{
QtWidgetController::Pointer controller = variant.value<QtWidgetController::Pointer>();
poco_assert(controller != 0);
return controller->GetShell();
}
return Shell::Pointer(nullptr);
}
Shell::Pointer QtWidgetsTweakletImpl::GetActiveShell()
{
QWidget* qwidget = QApplication::activeWindow();
if (qwidget == nullptr) return Shell::Pointer(nullptr);
QVariant variant = qwidget->property(QtWidgetController::PROPERTY_ID);
if (variant.isValid())
{
return variant.value<QtWidgetController::Pointer>()->GetShell();
}
return Shell::Pointer(nullptr);
}
QRect QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem,
const QRect& toConvert)
{
QPoint globalUpperLeft = toConvert.topLeft();
QPoint globalLowerRight = toConvert.bottomRight();
QPoint upperLeft = coordinateSystem->mapFromGlobal(globalUpperLeft);
QPoint lowerRight = coordinateSystem->mapFromGlobal(globalLowerRight);
return QRect(upperLeft.x(), upperLeft.y(), lowerRight.x() - upperLeft.x(),
lowerRight.y() - upperLeft.y());
}
QPoint QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem,
const QPoint& toConvert)
{
return coordinateSystem->mapFromGlobal(toConvert);
}
QRect QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem,
const QRect& toConvert)
{
QPoint upperLeft = toConvert.topLeft();
QPoint lowerRight = toConvert.bottomRight();
QPoint globalUpperLeft = coordinateSystem->mapToGlobal(upperLeft);
QPoint globalLowerRight = coordinateSystem->mapToGlobal(lowerRight);
return QRect(globalUpperLeft.x(), globalUpperLeft.y(), globalLowerRight.x() - globalUpperLeft.x(),
globalLowerRight.y() - globalUpperLeft.y());
}
QPoint QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem,
const QPoint& toConvert)
{
return coordinateSystem->mapToGlobal(toConvert);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h b/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h
index 9c09a2a200..6a97147d21 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.h
@@ -1,152 +1,152 @@
/*============================================================================
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 BERRYQTWIDGETSTWEAKLETIMPL_H_
#define BERRYQTWIDGETSTWEAKLETIMPL_H_
#include <internal/berryQtWidgetController.h>
#include <berryShell.h>
#include <berryGuiTkISelectionListener.h>
#include <QMetaType>
#include <list>
#include <vector>
namespace berry {
class QtSelectionListenerWrapper : public QObject
{
Q_OBJECT
public:
QtSelectionListenerWrapper(QWidget* widget);
QWidget* widget;
void AddListener(GuiTk::ISelectionListener::Pointer listener);
int RemoveListener(GuiTk::ISelectionListener::Pointer listener);
protected slots:
void QAbstractButtonClicked(bool checked);
private:
GuiTk::ISelectionListener::Events selectionEvents;
};
class QtWidgetsTweakletImpl
{
public:
void AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener);
void RemoveSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener);
void AddControlListener(QtWidgetController* widget, GuiTk::IControlListener::Pointer listener);
void RemoveControlListener(QtWidgetController* widget, GuiTk::IControlListener::Pointer listener);
bool GetEnabled(QWidget* widget);
void SetEnabled(QWidget* widget, bool enabled);
void SetBounds(QWidget* widget, const QRect& bounds);
QRect GetBounds(QWidget* widget);
void SetVisible(QWidget* widget, bool visible);
bool GetVisible(QWidget* widget);
bool IsVisible(QWidget* widget);
QRect GetClientArea(QWidget* widget);
QWidget* GetParent(QWidget* widget);
bool SetParent(QWidget* widget, QWidget* parent);
void SetData(QWidget* widget, const QString& id, Object::Pointer data);
Object::Pointer GetData(QWidget* widget, const QString& id);
- QRect GetScreenSize(int i = -1);
+ QRect GetScreenSize(int i = 0);
unsigned int GetScreenNumber();
int GetPrimaryScreenNumber();
- QRect GetAvailableScreenSize(int i = -1);
+ QRect GetAvailableScreenSize(int i = 0);
int GetClosestScreenNumber(const QRect&);
QPoint GetCursorLocation();
QWidget* GetCursorControl();
QWidget* FindControl(const QList<Shell::Pointer>& shells, const QPoint& location);
/**
* Determines if one control is a child of another. Returns true iff the second
* argument is a child of the first (or the same object).
*
* @param potentialParent
* @param childToTest
* @return
*/
bool IsChild(QObject* potentialParent, QObject* childToTest);
/**
* Returns the control which currently has keyboard focus,
* or null if keyboard events are not currently going to
* any of the controls built by the currently running
* application.
*
* @return the control under the cursor
*/
QWidget* GetFocusControl();
bool IsReparentable(QWidget* widget);
void MoveAbove(QWidget* widgetToMove, QWidget* widget);
void MoveBelow(QWidget* widgetToMove, QWidget* widget);
void Dispose(QWidget* widget);
Shell::Pointer CreateShell(Shell::Pointer parent, int style);
void DisposeShell(Shell::Pointer shell);
QWidget* CreateComposite(QWidget* parent);
QList<Shell::Pointer> GetShells();
Shell::Pointer GetShell(QWidget* widget);
Shell::Pointer GetActiveShell();
QRect ToControl(QWidget* coordinateSystem,
const QRect& toConvert);
QPoint ToControl(QWidget* coordinateSystem,
const QPoint& toConvert);
QRect ToDisplay(QWidget* coordinateSystem,
const QRect& toConvert);
QPoint ToDisplay(QWidget* coordinateSystem,
const QPoint& toConvert);
private:
typedef QHash<QWidget*, QtSelectionListenerWrapper* > SelectionListenerMap;
SelectionListenerMap selectionListenerMap;
QList<Shell::Pointer> shellList;
friend class QtShell;
};
}
#endif /* BERRYQTWIDGETSTWEAKLETIMPL_H_ */
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp
index bc82394674..a2bb630a98 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp
@@ -1,159 +1,159 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <berryIExtensionRegistry.h>
#include <berryIExtension.h>
#include <berryIConfigurationElement.h>
#include <berryIContributor.h>
#include "berryRegistryReader.h"
#include "berryWorkbenchPlugin.h"
#include "berryWorkbenchRegistryConstants.h"
namespace {
bool CompareExtensionsByContributor(const berry::IExtension::Pointer& e1,
const berry::IExtension::Pointer& e2)
{
return e1->GetContributor()->GetName().compare(e2->GetContributor()->GetName(), Qt::CaseInsensitive) < 0;
}
}
namespace berry
{
RegistryReader::RegistryReader()
{
}
RegistryReader::~RegistryReader()
{
}
void RegistryReader::LogError(const IConfigurationElement::Pointer& element,
const QString& text)
{
IExtension::Pointer extension = element->GetDeclaringExtension();
QString buf = QString("Plugin ") + extension->GetContributor()->GetName() + ", extension "
+ extension->GetExtensionPointUniqueIdentifier();
// look for an ID if available - this should help debugging
QString id = element->GetAttribute("id");
if (!id.isEmpty())
{
buf.append(", id ");
buf.append(id);
}
buf.append(": " + text);
WorkbenchPlugin::Log(buf);
}
void RegistryReader::LogMissingAttribute(
const IConfigurationElement::Pointer& element, const QString& attributeName)
{
RegistryReader::LogError(element, "Required attribute '" + attributeName + "' not defined");
}
void RegistryReader::LogMissingElement(
const IConfigurationElement::Pointer& element, const QString& elementName)
{
RegistryReader::LogError(element, "Required sub element '" + elementName + "' not defined");
}
void RegistryReader::LogUnknownElement(
const IConfigurationElement::Pointer& element)
{
RegistryReader::LogError(element, "Unknown extension tag found: " + element->GetName());
}
QList<IExtension::Pointer> RegistryReader::OrderExtensions(
const QList<IExtension::Pointer>& extensions)
{
// By default, the order is based on plugin id sorted
// in ascending order. The order for a plugin providing
// more than one extension for an extension point is
// dependent in the order listed in the XML file.
QList<IExtension::Pointer> sortedExtension(extensions);
- qStableSort(sortedExtension.begin(), sortedExtension.end(),
+ std::stable_sort(sortedExtension.begin(), sortedExtension.end(),
CompareExtensionsByContributor);
return sortedExtension;
}
void RegistryReader::ReadElementChildren(
const IConfigurationElement::Pointer& element)
{
this->ReadElements(element->GetChildren());
}
void RegistryReader::ReadElements(
const QList<IConfigurationElement::Pointer>& elements)
{
for (int i = 0; i < elements.size(); i++)
{
if (!this->ReadElement(elements[i]))
{
RegistryReader::LogUnknownElement(elements[i]);
}
}
}
void RegistryReader::ReadExtension(const IExtension::Pointer& extension)
{
this->ReadElements(extension->GetConfigurationElements());
}
void RegistryReader::ReadRegistry(IExtensionRegistry* registry,
const QString& pluginId, const QString& extensionPoint)
{
IExtensionPoint::Pointer point = registry->GetExtensionPoint(pluginId, extensionPoint);
if (point == 0)
{
return;
}
QList<IExtension::Pointer> extensions(point->GetExtensions());
extensions = this->OrderExtensions(extensions);
for (int i = 0; i < extensions.size(); i++)
{
this->ReadExtension(extensions[i]);
}
}
QString RegistryReader::GetDescription(const IConfigurationElement::Pointer& configElement)
{
QList<IConfigurationElement::Pointer> children(configElement->GetChildren(WorkbenchRegistryConstants::TAG_DESCRIPTION));
if (children.size() >= 1)
{
return children[0]->GetValue();
}
return "";
}
QString RegistryReader::GetClassValue(
const IConfigurationElement::Pointer& configElement,
const QString& classAttributeName)
{
QString className = configElement->GetAttribute(classAttributeName);
if (!className.isEmpty())
{
return className;
}
QList<IConfigurationElement::Pointer> candidateChildren(configElement->GetChildren(classAttributeName));
if (candidateChildren.isEmpty())
{
return "";
}
return candidateChildren[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp
index 38bd69cefb..0f9778493c 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp
@@ -1,300 +1,300 @@
/*============================================================================
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 "berryReopenEditorMenu.h"
#include <berryIWorkbench.h>
#include <berryIWorkbenchPage.h>
#include <berryMenuManager.h>
#include <berrySafeRunner.h>
#include "berryEditorHistory.h"
#include "berryEditorHistoryItem.h"
#include "berryWorkbench.h"
#include "berryWorkbenchPlugin.h"
#include "berryPreferenceConstants.h"
#include <QAction>
#include <QMenu>
#include <QMessageBox>
#include <mitkIPreferences.h>
namespace berry {
ReopenEditorMenu::ReopenEditorMenu(IWorkbenchWindow* window, const QString& id, bool showSeparator)
: ContributionItem(id)
, window(window)
, history(nullptr)
, showSeparator(showSeparator)
, dirty(true)
{
IWorkbench* workbench = window->GetWorkbench();
if (Workbench* w = dynamic_cast<Workbench*>(workbench))
{
history = w->GetEditorHistory();
}
}
QString ReopenEditorMenu::CalcText(int index, const QString& name, const QString& toolTip, bool rtl)
{
QString sb;
int mnemonic = index + 1;
QString nm = QString::number(mnemonic);
if (mnemonic <= MAX_MNEMONIC_SIZE)
{
nm.prepend('&');
}
QString fileName = name;
QString pathName = toolTip;
if (pathName == fileName)
{
// tool tip text isn't necessarily a path;
// sometimes it's the same as name, so it shouldn't be treated as a path then
pathName.clear();
}
QFileInfo path(pathName);
// if last segment in path is the fileName, remove it
if (path.fileName() == fileName)
{
path.setFile(path.path());
pathName = path.absoluteFilePath();
}
if ((fileName.size() + pathName.size()) <= (MAX_TEXT_LENGTH - 4))
{
// entire item name fits within maximum length
sb += fileName;
if (!pathName.isEmpty())
{
sb += " [" + pathName + "]";
}
}
else
{
// need to shorten the item name
int length = fileName.size();
if (length > MAX_TEXT_LENGTH)
{
// file name does not fit within length, truncate it
- sb += fileName.leftRef(MAX_TEXT_LENGTH - 3);
+ sb += QStringView(fileName).left(MAX_TEXT_LENGTH - 3);
sb += "...";
}
else if (length > MAX_TEXT_LENGTH - 7)
{
sb += fileName;
}
else
{
sb += fileName;
- QStringList pathSegments = path.absoluteFilePath().split('/', QString::SkipEmptyParts);
+ QStringList pathSegments = path.absoluteFilePath().split('/', Qt::SkipEmptyParts);
int segmentCount = pathSegments.size();
if (segmentCount > 0)
{
length += 7; // 7 chars are taken for " [...]"
sb += " [";
// Add first n segments that fit
int i = 0;
while (i < segmentCount && length < MAX_TEXT_LENGTH)
{
const QString& segment = pathSegments[i];
if (length + segment.size() < MAX_TEXT_LENGTH)
{
sb += segment + QDir::separator();
length += segment.size() + 1;
i++;
}
else if (i == 0)
{
// append at least part of the first segment
- sb += segment.leftRef(MAX_TEXT_LENGTH - length);
+ sb += QStringView(segment).left(MAX_TEXT_LENGTH - length);
length = MAX_TEXT_LENGTH;
break;
}
else
{
break;
}
}
sb += "...";
i = segmentCount - 1;
// Add last n segments that fit
while (i > 0 && length < MAX_TEXT_LENGTH)
{
const QString& segment = pathSegments[i];
if (length + segment.size() < MAX_TEXT_LENGTH)
{
sb += QDir::separator();
sb += segment;
length += segment.size() + 1;
i--;
}
else
{
break;
}
}
sb.append("]");
}
}
}
QString process;
if (rtl)
{
process = sb + " " + nm;
}
else
{
process = nm + " " + sb;
}
//return TextProcessor.process(process, TextProcessor.getDefaultDelimiters() + "[]");
return process;
}
void ReopenEditorMenu::Fill(QMenu* menu, QAction* before)
{
if (window->GetActivePage() == nullptr
|| window->GetActivePage()->GetPerspective().IsNull())
{
return;
}
if (MenuManager* mm = dynamic_cast<MenuManager*>(this->GetParent()))
{
mm->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), this, SLOT(MenuAboutToShow(IMenuManager*)));
}
int itemsToShow = WorkbenchPlugin::GetDefault()->GetPreferences()->GetInt(PreferenceConstants::RECENT_FILES, 6);
if (itemsToShow == 0 || history == nullptr)
{
return;
}
// Get items.
QList<EditorHistoryItem::Pointer> historyItems = history->GetItems();
- int n = std::min(itemsToShow, historyItems.size());
+ int n = std::min(itemsToShow, static_cast<int>(historyItems.size()));
if (n <= 0)
{
return;
}
if (showSeparator)
{
menu->addSeparator();
}
struct _SafeRunnable : public ISafeRunnable
{
QMenu* menu;
QAction* before;
EditorHistoryItem::Pointer item;
const int historyIndex;
_SafeRunnable(QMenu* menu, QAction* before, EditorHistoryItem::Pointer item, int index)
: menu(menu), before(before), item(item), historyIndex(index) {}
void Run() override
{
QString text = ReopenEditorMenu::CalcText(historyIndex, item);
auto mi = new QAction(text, nullptr);
menu->insertAction(before, mi);
mi->setData(QVariant::fromValue(item));
}
void HandleException(const ctkException& e) override
{
// just skip the item if there's an error,
// e.g. in the calculation of the shortened name
WorkbenchPlugin::Log(this->GetClassName(), "Fill", e);
}
};
for (int i = 0; i < n; i++)
{
EditorHistoryItem::Pointer item = historyItems[i];
ISafeRunnable::Pointer runnable(new _SafeRunnable(menu, before, item, i));
SafeRunner::Run(runnable);
}
dirty = false;
}
bool ReopenEditorMenu::IsDirty() const
{
return dirty;
}
bool ReopenEditorMenu::IsDynamic() const
{
return true;
}
void ReopenEditorMenu::Open(const EditorHistoryItem::Pointer& item)
{
IWorkbenchPage::Pointer page = window->GetActivePage();
if (page.IsNotNull())
{
try
{
QString itemName = item->GetName();
if (!item->IsRestored())
{
item->RestoreState();
}
IEditorInput::Pointer input = item->GetInput();
IEditorDescriptor::Pointer desc = item->GetDescriptor();
if (!input || !desc)
{
QString title = "Problems opening editor";
QString msg = QString("Unable to open %1.").arg(itemName);
QMessageBox::warning(window->GetShell()->GetControl(), title, msg);
history->Remove(item);
}
else
{
page->OpenEditor(input, desc->GetId());
}
}
catch (const PartInitException& e2)
{
QString title = "Problems opening editor";
QMessageBox::warning(window->GetShell()->GetControl(), title, e2.what());
history->Remove(item);
}
}
}
QString ReopenEditorMenu::CalcText(int index, const EditorHistoryItem::Pointer& item)
{
// IMPORTANT: avoid accessing the item's input since
// this can require activating plugins.
// Instead, ask the item for the info, which can
// consult its memento if it is not restored yet.
return CalcText(index, item->GetName(), item->GetToolTipText(), false);
// Window::GetDefaultOrientation() == SWT.RIGHT_TO_LEFT);
}
void ReopenEditorMenu::MenuAboutToShow(IMenuManager* manager)
{
manager->MarkDirty();
dirty = true;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp
index 9a7fda5765..9c5b90e430 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berrySaveablesList.cpp
@@ -1,628 +1,628 @@
/*============================================================================
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 "berrySaveablesList.h"
#include "berryWorkbenchPlugin.h"
#include "berryDefaultSaveable.h"
#include "berryWorkbenchPart.h"
namespace berry
{
bool SaveablesList::AddModel(Object::Pointer source, Saveable::Pointer model)
{
if (model == 0)
{
this->LogWarning("Ignored attempt to add invalid saveable", source, model); //$NON-NLS-1$
return false;
}
bool result = false;
Saveable::Set& modelsForSource = modelMap[source.GetPointer()];
if (modelsForSource.find(model) == modelsForSource.end())
{
modelsForSource.insert(model);
result = this->IncrementRefCount(modelRefCounts, model);
}
else
{
this->LogWarning("Ignored attempt to add saveable that was already registered",
source, model); //$NON-NLS-1$
}
return result;
}
bool SaveablesList::IncrementRefCount(
QHash<Saveable::Pointer, int>& referenceMap, Saveable::Pointer key)
{
bool result = false;
int& refCount = referenceMap[key];
if (refCount == 0)
{
result = true;
}
refCount++;
return result;
}
bool SaveablesList::DecrementRefCount(
QHash<Saveable::Pointer, int>& referenceMap, Saveable::Pointer key)
{
bool result = false;
int& refCount = referenceMap[key];
poco_assert(refCount != 0);
if (refCount == 1)
{
referenceMap.remove(key);
result = true;
}
else
{
--refCount;
}
return result;
}
bool SaveablesList::RemoveModel(Object::Pointer source, Saveable::Pointer model)
{
bool result = false;
QHash<Object*, Saveable::Set>::iterator it = modelMap.find(source.GetPointer());
if (it == modelMap.end())
{
this->LogWarning(
"Ignored attempt to remove a saveable when no saveables were known",
source, model); //$NON-NLS-1$
}
else
{
Saveable::Set& modelsForSource = it.value();
if (modelsForSource.remove(model))
{
result = this->DecrementRefCount(modelRefCounts, model);
if (modelsForSource.empty())
{
modelMap.remove(source.GetPointer());
}
}
else
{
this->LogWarning(
"Ignored attempt to remove a saveable that was not registered",
source, model); //$NON-NLS-1$
}
}
return result;
}
void SaveablesList::LogWarning(const QString& message,
Object::Pointer source, Saveable::Pointer model)
{
// create a new exception
QString text = message + "; " + "unknown saveable: " + model->GetName()
+ " from part: " + source->GetClassName();
// record the current stack trace to help with debugging
//assertionFailedException.fillInStackTrace();
WorkbenchPlugin::Log(text);
}
void SaveablesList::UpdateNonPartSource(ISaveablesSource::Pointer source)
{
QList<Saveable::Pointer> saveables = source->GetSaveables();
if (saveables.empty())
{
nonPartSources.remove(source);
}
else
{
nonPartSources.insert(source);
}
}
void SaveablesList::RemoveModels(Object::Pointer source,
const QList<Saveable::Pointer>& modelArray)
{
QList<Saveable::Pointer> removed;
for (int i = 0; i < modelArray.size(); i++)
{
Saveable::Pointer model = modelArray[i];
if (this->RemoveModel(source, model))
{
removed.push_back(model);
}
}
if (removed.size() > 0)
{
Object::Pointer source(this);
SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source,
SaveablesLifecycleEvent::POST_OPEN, removed, false));
this->FireModelLifecycleEvent(event);
}
}
void SaveablesList::AddModels(Object::Pointer source,
const QList<Saveable::Pointer>& modelArray)
{
QList<Saveable::Pointer> added;
for (int i = 0; i < modelArray.size(); i++)
{
Saveable::Pointer model = modelArray[i];
if (this->AddModel(source, model))
{
added.push_back(model);
}
}
if (added.size() > 0)
{
Object::Pointer source(this);
SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source,
SaveablesLifecycleEvent::POST_OPEN, added, false));
this->FireModelLifecycleEvent(event);
}
}
void SaveablesList::FireModelLifecycleEvent(
SaveablesLifecycleEvent::Pointer event)
{
events.lifecycleChange(event);
}
bool SaveablesList::PromptForSavingIfNecessary(
IWorkbenchWindow::Pointer /*window*/, const Saveable::Set& /*modelsClosing*/,
const QHash<Saveable::Pointer, int>& /*modelsDecrementing*/, bool /*canCancel*/)
{
// List modelsToOptionallySave = new ArrayList();
// for (Iterator it = modelsDecrementing.keySet().iterator(); it.hasNext();)
// {
// Saveable modelDecrementing = (Saveable) it.next();
// if (modelDecrementing.isDirty() && !modelsClosing.contains(
// modelDecrementing))
// {
// modelsToOptionallySave.add(modelDecrementing);
// }
// }
//
// boolean shouldCancel =
// modelsToOptionallySave.isEmpty() ? false : promptForSaving(
// modelsToOptionallySave, window, window, canCancel, true);
//
// if (shouldCancel)
// {
// return true;
// }
//
// List modelsToSave = new ArrayList();
// for (Iterator it = modelsClosing.iterator(); it.hasNext();)
// {
// Saveable modelClosing = (Saveable) it.next();
// if (modelClosing.isDirty())
// {
// modelsToSave.add(modelClosing);
// }
// }
// return modelsToSave.isEmpty() ? false : promptForSaving(modelsToSave, window,
// window, canCancel, false);
return false;
}
void SaveablesList::FillModelsClosing(Saveable::Set& modelsClosing,
const QHash<Saveable::Pointer, int>& modelsDecrementing)
{
for (QHash<Saveable::Pointer, int>::const_iterator it = modelsDecrementing.begin();
it != modelsDecrementing.end(); ++it)
{
Saveable::Pointer model = it.key();
if (it.value() == modelRefCounts[model])
{
modelsClosing.insert(model);
}
}
}
QList<Saveable::Pointer> SaveablesList::GetSaveables(
IWorkbenchPart::Pointer part)
{
if (part.Cast<ISaveablesSource> () != 0)
{
ISaveablesSource::Pointer source = part.Cast<ISaveablesSource>();
return source->GetSaveables();
}
else if (part.Cast<ISaveablePart> () != 0)
{
QList<Saveable::Pointer> result;
Saveable::Pointer defaultSaveable(new DefaultSaveable(part));
result.push_back(defaultSaveable);
return result;
}
else
{
return QList<Saveable::Pointer>();
}
}
Saveable::Set SaveablesList::GetOpenModels()
{
Saveable::Set allDistinctModels;
for (QHash<Object*, Saveable::Set>::iterator it = modelMap.begin();
it != modelMap.end(); ++it)
allDistinctModels.unite(it.value());
return allDistinctModels;
}
void SaveablesList::HandleLifecycleEvent(const SaveablesLifecycleEvent::Pointer& event)
{
if (event->GetSource().Cast<IWorkbenchPart> () == 0)
{
// just update the set of non-part sources. No prompting necessary.
// See bug 139004.
this->UpdateNonPartSource(event->GetSource().Cast<ISaveablesSource>());
return;
}
QList<Saveable::Pointer> modelArray = event->GetSaveables();
int eventType = event->GetEventType();
if (eventType == SaveablesLifecycleEvent::POST_OPEN)
{
this->AddModels(event->GetSource(), modelArray);
}
else if (eventType == SaveablesLifecycleEvent::PRE_CLOSE)
{
QList<Saveable::Pointer> models = event->GetSaveables();
QHash<Saveable::Pointer, int> modelsDecrementing;
Saveable::Set modelsClosing;
for (int i = 0; i < models.size(); i++)
{
this->IncrementRefCount(modelsDecrementing, models[i]);
}
this->FillModelsClosing(modelsClosing, modelsDecrementing);
bool canceled = this->PromptForSavingIfNecessary(
PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), modelsClosing,
modelsDecrementing, !event->IsForce());
if (canceled)
{
event->SetVeto(true);
}
}
else if (eventType == SaveablesLifecycleEvent::POST_CLOSE)
{
this->RemoveModels(event->GetSource(), modelArray);
}
else if (eventType == SaveablesLifecycleEvent::DIRTY_CHANGED)
{
Object::Pointer source(this);
SaveablesLifecycleEvent::Pointer lifeCycleEvent(
new SaveablesLifecycleEvent(source, event->GetEventType(), event->GetSaveables(), false));
this->FireModelLifecycleEvent(lifeCycleEvent);
}
}
void SaveablesList::AddModelLifecycleListener(ISaveablesLifecycleListener* listener)
{
events.AddListener(listener);
}
void SaveablesList::RemoveModelLifecycleListener(ISaveablesLifecycleListener* listener)
{
events.RemoveListener(listener);
}
SaveablesList::PostCloseInfo::Pointer SaveablesList::PreCloseParts(
const QList<IWorkbenchPart::Pointer>& partsToClose, bool save,
IWorkbenchWindow::Pointer window)
{
// reference count (how many occurrences of a model will go away?)
PostCloseInfo::Pointer postCloseInfo(new PostCloseInfo());
for (QList<IWorkbenchPart::Pointer>::const_iterator it = partsToClose.begin();
it != partsToClose.end(); ++it)
{
WorkbenchPart::Pointer part = it->Cast<WorkbenchPart>();
postCloseInfo->partsClosing.push_back(part);
if (part.Cast<ISaveablePart> () != 0)
{
ISaveablePart::Pointer saveablePart = part.Cast<ISaveablePart>();
if (save && !saveablePart->IsSaveOnCloseNeeded())
{
// pretend for now that this part is not closing
continue;
}
}
// if (save && part.Cast<ISaveablePart2> () != 0)
// {
// ISaveablePart2 saveablePart2 = (ISaveablePart2) part;
// // TODO show saveablePart2 before prompting, see
// // EditorManager.saveAll
// int response = SaveableHelper.savePart(saveablePart2, window, true);
// if (response == ISaveablePart2.CANCEL)
// {
// // user canceled
// return 0;
// }
// else if (response != ISaveablePart2.DEFAULT)
// {
// // only include this part in the following logic if it returned
// // DEFAULT
// continue;
// }
// }
QList<Saveable::Pointer> modelsFromSource = this->GetSaveables(part);
for (int i = 0; i < modelsFromSource.size(); i++)
{
this->IncrementRefCount(postCloseInfo->modelsDecrementing, modelsFromSource[i]);
}
}
this->FillModelsClosing(postCloseInfo->modelsClosing,
postCloseInfo->modelsDecrementing);
if (save)
{
bool canceled = this->PromptForSavingIfNecessary(window,
postCloseInfo->modelsClosing, postCloseInfo->modelsDecrementing, true);
if (canceled)
{
return PostCloseInfo::Pointer(nullptr);
}
}
return postCloseInfo;
}
bool SaveablesList::PromptForSaving(
const QList<Saveable::Pointer>& /*modelsToSave*/,
/*final IShellProvider shellProvider, IRunnableContext runnableContext,*/
bool /*canCancel*/, bool /*stillOpenElsewhere*/)
{
// // Save parts, exit the method if cancel is pressed.
// if (modelsToSave.size() > 0) {
// boolean canceled = SaveableHelper.waitForBackgroundSaveJobs(modelsToSave);
// if (canceled) {
// return true;
// }
//
// IPreferenceStore apiPreferenceStore = PrefUtil.getAPIPreferenceStore();
// boolean dontPrompt = stillOpenElsewhere && !apiPreferenceStore.getBoolean(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN);
//
// if (dontPrompt) {
// modelsToSave.clear();
// return false;
// } else if (modelsToSave.size() == 1) {
// Saveable model = (Saveable) modelsToSave.get(0);
// // Show a dialog.
// QList<QString> buttons;
// if(canCancel) {
// buttons.push_back(IDialogConstants.YES_LABEL);
// buttons.push_back(IDialogConstants.NO_LABEL);
// buttons.push_back(IDialogConstants.CANCEL_LABEL);
// } else {
// buttons.push_back(IDialogConstants.YES_LABEL);
// buttons.push_back(IDialogConstants.NO_LABEL);
// }
//
// // don't save if we don't prompt
// int choice = ISaveablePart2.NO;
//
// MessageDialog dialog;
// if (stillOpenElsewhere) {
// String message = NLS
// .bind(
// WorkbenchMessages.EditorManager_saveChangesOptionallyQuestion,
// model.getName());
// MessageDialogWithToggle dialogWithToggle = new MessageDialogWithToggle(shellProvider.getShell(),
// WorkbenchMessages.Save_Resource, 0, message,
// MessageDialog.QUESTION, buttons, 0, WorkbenchMessages.EditorManager_closeWithoutPromptingOption, false) {
// protected int getShellStyle() {
// return (canCancel ? SWT.CLOSE : SWT.NONE)
// | SWT.TITLE | SWT.BORDER
// | SWT.APPLICATION_MODAL
// | getDefaultOrientation();
// }
// };
// dialog = dialogWithToggle;
// } else {
// String message = NLS
// .bind(
// WorkbenchMessages.EditorManager_saveChangesQuestion,
// model.getName());
// dialog = new MessageDialog(shellProvider.getShell(),
// WorkbenchMessages.Save_Resource, 0, message,
// MessageDialog.QUESTION, buttons, 0) {
// protected int getShellStyle() {
// return (canCancel ? SWT.CLOSE : SWT.NONE)
// | SWT.TITLE | SWT.BORDER
// | SWT.APPLICATION_MODAL
// | getDefaultOrientation();
// }
// };
// }
//
// choice = SaveableHelper.testGetAutomatedResponse();
// if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) {
// choice = dialog.open();
//
// if(stillOpenElsewhere) {
// // map value of choice back to ISaveablePart2 values
// switch (choice) {
// case IDialogConstants.YES_ID:
// choice = ISaveablePart2.YES;
// break;
// case IDialogConstants.NO_ID:
// choice = ISaveablePart2.NO;
// break;
// case IDialogConstants.CANCEL_ID:
// choice = ISaveablePart2.CANCEL;
// break;
// default:
// break;
// }
// MessageDialogWithToggle dialogWithToggle = (MessageDialogWithToggle) dialog;
// if (choice != ISaveablePart2.CANCEL && dialogWithToggle.getToggleState()) {
// apiPreferenceStore.setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, false);
// }
// }
// }
//
// // Branch on the user choice.
// // The choice id is based on the order of button labels
// // above.
// switch (choice) {
// case ISaveablePart2.YES: // yes
// break;
// case ISaveablePart2.NO: // no
// modelsToSave.clear();
// break;
// default:
// case ISaveablePart2.CANCEL: // cancel
// return true;
// }
// } else {
// MyListSelectionDialog dlg = new MyListSelectionDialog(
// shellProvider.getShell(),
// modelsToSave,
// new ArrayContentProvider(),
// new WorkbenchPartLabelProvider(),
// stillOpenElsewhere ? WorkbenchMessages.EditorManager_saveResourcesOptionallyMessage
// : WorkbenchMessages.EditorManager_saveResourcesMessage,
// canCancel, stillOpenElsewhere);
// dlg.setInitialSelections(modelsToSave.toArray());
// dlg.setTitle(EditorManager.SAVE_RESOURCES_TITLE);
//
// // this "if" statement aids in testing.
// if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) {
// int result = dlg.open();
// // Just return 0 to prevent the operation continuing
// if (result == IDialogConstants.CANCEL_ID)
// return true;
//
// if (dlg.getDontPromptSelection()) {
// apiPreferenceStore.setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, false);
// }
//
// modelsToSave = Arrays.asList(dlg.getResult());
// }
// }
// }
// // Create save block.
// return saveModels(modelsToSave, shellProvider, runnableContext);
return true;
}
bool SaveablesList::SaveModels(const QList<Saveable::Pointer>& /*finalModels*/
/*final IShellProvider shellProvider, IRunnableContext runnableContext*/)
{
// IRunnableWithProgress progressOp = new IRunnableWithProgress() {
// public void run(IProgressMonitor monitor) {
// IProgressMonitor monitorWrap = new EventLoopProgressMonitor(
// monitor);
// monitorWrap.beginTask("", finalModels.size()); //$NON-NLS-1$
// for (Iterator i = finalModels.iterator(); i.hasNext();) {
// Saveable model = (Saveable) i.next();
// // handle case where this model got saved as a result of
// // saving another
// if (!model.isDirty()) {
// monitor.worked(1);
// continue;
// }
// SaveableHelper.doSaveModel(model, new SubProgressMonitor(monitorWrap, 1), shellProvider, true);
// if (monitorWrap.isCanceled())
// break;
// }
// monitorWrap.done();
// }
// };
//
// // Do the save.
// return !SaveableHelper.runProgressMonitorOperation(
// WorkbenchMessages.Save_All, progressOp, runnableContext,
// shellProvider);
return true;
}
void SaveablesList::PostClose(PostCloseInfo::Pointer postCloseInfo)
{
QList<Saveable::Pointer> removed;
for (QList<WorkbenchPart::Pointer>::const_iterator it = postCloseInfo->partsClosing.begin();
it != postCloseInfo->partsClosing.end(); ++it)
{
IWorkbenchPart::Pointer part = *it;
QHash<Object*, Saveable::Set>::iterator it2 = modelMap.find(part.GetPointer());
if (it2 != modelMap.end()) {
// make a copy to avoid a ConcurrentModificationException - we
// will remove from the original set as we iterate
Saveable::Set saveables(it2.value());
for (Saveable::Set::const_iterator it3 = saveables.begin();
it3 != saveables.end(); ++it3)
{
if (RemoveModel(part, *it3)) {
removed.push_back(*it3);
}
}
}
}
if (!removed.empty()) {
Object::Pointer source(this);
SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source,
SaveablesLifecycleEvent::POST_CLOSE, removed, false));
this->FireModelLifecycleEvent(event);
}
}
void SaveablesList::PostOpen(IWorkbenchPart::Pointer part)
{
this->AddModels(part, this->GetSaveables(part));
}
void SaveablesList::DirtyChanged(IWorkbenchPart::Pointer part)
{
QList<Saveable::Pointer> saveables = this->GetSaveables(part);
if (saveables.size() > 0) {
Object::Pointer source(this);
SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source,
SaveablesLifecycleEvent::DIRTY_CHANGED, saveables, false));
this->FireModelLifecycleEvent(event);
}
}
QList<Object::Pointer> SaveablesList::TestGetSourcesForModel(
Saveable::Pointer /*model*/)
{
QList<Object::Pointer> result;
// for (Iterator it = modelMap.entrySet().iterator(); it.hasNext();) {
// Map.Entry entry = (Map.Entry) it.next();
// Set values = (Set) entry.getValue();
// if (values.contains(model)) {
// result.add(entry.getKey());
// }
// }
return result;
}
QList<ISaveablesSource::Pointer> SaveablesList::GetNonPartSources()
{
- return nonPartSources.toList();
+ return nonPartSources.values();
}
QList<IWorkbenchPart::Pointer> SaveablesList::GetPartsForSaveable(
Saveable::Pointer model)
{
QList<IWorkbenchPart::Pointer> result;
for (QHash<Object*, Saveable::Set>::iterator it = modelMap.begin(); it
!= modelMap.end(); ++it)
{
Saveable::Set& values = it.value();
IWorkbenchPart::Pointer part(dynamic_cast<IWorkbenchPart*>(it.key()));
if (values.find(model) != values.end() && part)
{
result.push_back(part);
}
}
return result;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp
index 155db01074..d618cd9d0d 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp
@@ -1,275 +1,275 @@
/*============================================================================
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 "berryShowViewMenu.h"
#include <berryMenuManager.h>
#include <berryIWorkbenchWindow.h>
#include <berryIWorkbenchPage.h>
#include <berryCommandContributionItem.h>
#include <berrySeparator.h>
#include <berryIPluginContribution.h>
#include <berryIViewRegistry.h>
#include <berryIWorkbenchCommandConstants.h>
#include <berryObjectString.h>
#include "berryCommandContributionItemParameter.h"
#include "berryWorkbenchPlugin.h"
#include "berryViewDescriptor.h"
#include "intro/berryIntroConstants.h"
#include <QMenu>
#include <QSet>
#include <QPair>
namespace berry {
const QString ShowViewMenu::NO_TARGETS_MSG = "<No Applicable Views>";
struct ActionComparator {
bool operator()(const CommandContributionItemParameter::Pointer& p1,
const CommandContributionItemParameter::Pointer& p2) const
{
return p1->label < p2->label;
}
};
ShowViewMenu::ShowViewMenu(IWorkbenchWindow *window, const QString& id)
: ContributionItem(id), dirty(true), window(window)
{
CommandContributionItemParameter::Pointer showDlgItemParms(
new CommandContributionItemParameter(
- window, QString::null, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW,
+ window, QString(), IWorkbenchCommandConstants::VIEWS_SHOW_VIEW,
CommandContributionItem::STYLE_PUSH));
showDlgItemParms->label = "&Other...";
showDlgItem = new CommandContributionItem(showDlgItemParms);
// window.getWorkbench().getHelpSystem().setHelp(showDlgAction,
// IWorkbenchHelpContextIds.SHOW_VIEW_OTHER_ACTION);
// // indicate that a show views submenu has been created
// if (window instanceof WorkbenchWindow) {
// ((WorkbenchWindow) window)
// .addSubmenu(WorkbenchWindow.SHOW_VIEW_SUBMENU);
// }
}
bool ShowViewMenu::IsDirty() const
{
return dirty;
}
/**
* Overridden to always return true and force dynamic menu building.
*/
bool ShowViewMenu::IsDynamic() const
{
return true;
}
void ShowViewMenu::Fill(QMenu* menu, QAction* before)
{
if (MenuManager* mm = dynamic_cast<MenuManager*>(GetParent()))
{
this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*)));
}
if (!dirty)
{
return;
}
- MenuManager::Pointer manager(new MenuManager());
+ MenuManager::Pointer manager(new MenuManager(""));
FillMenu(manager.GetPointer());
QList<IContributionItem::Pointer> items = manager->GetItems();
if (items.isEmpty())
{
auto action = new QAction(NO_TARGETS_MSG, menu);
action->setEnabled(false);
menu->insertAction(before, action);
}
else
{
foreach (IContributionItem::Pointer item, items)
{
item->Fill(menu, before);
}
}
dirty = false;
}
void ShowViewMenu::FillMenu(IMenuManager* innerMgr)
{
// Remove all.
innerMgr->RemoveAll();
// If no page disable all.
IWorkbenchPage::Pointer page = window->GetActivePage();
if (page.IsNull())
{
return;
}
// If no active perspective disable all
if (page->GetPerspective().IsNull())
{
return;
}
typedef QPair<QString,QString> ViewIdPair;
// Get visible actions.
QSet<ViewIdPair> viewIds = GetShortcuts(page.GetPointer());
// add all open views
viewIds = AddOpenedViews(page.GetPointer(), viewIds);
QList<CommandContributionItemParameter::Pointer> actions;
foreach (ViewIdPair id, viewIds)
{
if (id.first == IntroConstants::INTRO_VIEW_ID)
{
continue;
}
CommandContributionItemParameter::Pointer item = GetItem(id.first, id.second);
if (item)
{
actions.append(item);
}
}
- qSort(actions.begin(), actions.end(), ActionComparator());
+ std::sort(actions.begin(), actions.end(), ActionComparator());
foreach (CommandContributionItemParameter::Pointer ccip, actions)
{
// if (WorkbenchActivityHelper.filterItem(ccip)) {
// continue;
// }
CommandContributionItem::Pointer item(new CommandContributionItem(ccip));
innerMgr->Add(item);
}
// We only want to add the separator if there are show view shortcuts,
// otherwise, there will be a separator and then the 'Other...' entry
// and that looks weird as the separator is separating nothing
if (!innerMgr->IsEmpty())
{
IContributionItem::Pointer separator(new Separator());
innerMgr->Add(separator);
}
// Add Other...
innerMgr->Add(showDlgItem);
}
QSet<QPair<QString,QString> > ShowViewMenu::GetShortcuts(IWorkbenchPage* page) const
{
QSet<QPair<QString,QString> > list;
QList<QString> shortcuts(page->GetShowViewShortcuts());
for (int i = 0; i < shortcuts.size(); ++i)
{
list.insert(qMakePair(shortcuts[i], QString()));
}
return list;
}
void ShowViewMenu::AboutToShow(IMenuManager* manager)
{
manager->MarkDirty();
this->dirty = true;
}
CommandContributionItemParameter::Pointer ShowViewMenu::GetItem(const QString& viewId, const QString& secondaryId) const
{
IViewRegistry* reg = WorkbenchPlugin::GetDefault()->GetViewRegistry();
IViewDescriptor::Pointer desc = reg->Find(viewId);
if (desc.IsNull())
{
return CommandContributionItemParameter::Pointer(nullptr);
}
QString label = desc->GetLabel();
class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution
{
QString localId;
QString pluginId;
public:
typedef PluginCCIP Self;
static const char* GetStaticClassName() { return "PluginCCIP"; }
berryObjectTypeInfo(CommandContributionItemParameter, IPluginContribution)
PluginCCIP(const IViewDescriptor::Pointer& v, IServiceLocator* serviceLocator,
const QString& id, const QString& commandId, CommandContributionItem::Style style)
: CommandContributionItemParameter(serviceLocator, id, commandId, style)
{
ViewDescriptor::Pointer vd = v.Cast<ViewDescriptor>();
localId = vd->GetLocalId();
pluginId = vd->GetPluginId();
}
QString GetLocalId() const override
{
return localId;
}
QString GetPluginId() const override
{
return pluginId;
}
};
CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc,
window, viewId, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW,
CommandContributionItem::STYLE_PUSH));
parms->label = label;
parms->icon = desc->GetImageDescriptor();
Object::Pointer strViewId(new ObjectString(viewId));
parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID, strViewId);
// if (makeFast)
// {
// parms.parameters.put(
// IWorkbenchCommandConstants.VIEWS_SHOW_VIEW_PARM_FASTVIEW,
// "true"); //$NON-NLS-1$
// }
if (!secondaryId.isEmpty())
{
Object::Pointer strSecondaryId(new ObjectString(secondaryId));
parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID,
strSecondaryId);
}
return parms;
}
QSet<QPair<QString,QString> > ShowViewMenu::AddOpenedViews(IWorkbenchPage* page,
QSet<QPair<QString,QString> >& actions) const
{
QSet<QPair<QString,QString> > views = GetParts(page);
return views.unite(actions);
}
QSet<QPair<QString,QString> > ShowViewMenu::GetParts(IWorkbenchPage* page) const
{
QSet<QPair<QString,QString> > parts;
QList<IViewReference::Pointer> refs = page->GetViewReferences();
for (int i = 0; i < refs.size(); ++i)
{
parts.insert(qMakePair(refs[i]->GetId(), refs[i]->GetSecondaryId()));
}
return parts;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berrySlaveHandlerService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berrySlaveHandlerService.cpp
index 20177c4688..315bc51943 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berrySlaveHandlerService.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berrySlaveHandlerService.cpp
@@ -1,232 +1,232 @@
/*============================================================================
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 "berrySlaveHandlerService.h"
#include "berryIHandler.h"
#include "berryIHandlerActivation.h"
#include "berryISourceProvider.h"
#include "berryAndExpression.h"
#include "berryHandlerActivation.h"
#include "berryExecutionEvent.h"
namespace berry {
SlaveHandlerService::SlaveHandlerService(IHandlerService* parentHandlerService,
const SmartPointer<Expression>& defaultExpression)
: defaultExpression(defaultExpression)
, parent(parentHandlerService)
{
if (parentHandlerService == nullptr)
{
throw ctkInvalidArgumentException("The parent handler service cannot be null");
}
}
SmartPointer<IHandlerActivation> SlaveHandlerService::ActivateHandler(const SmartPointer<IHandlerActivation>& childActivation)
{
const QString commandId = childActivation->GetCommandId();
const IHandler::Pointer handler = childActivation->GetHandler();
const Expression::Pointer childExpression = childActivation->GetExpression();
Expression::Pointer expression = defaultExpression;
if (childExpression.IsNotNull() && defaultExpression.IsNotNull())
{
const AndExpression::Pointer andExpression(new AndExpression());
andExpression->Add(childExpression);
andExpression->Add(defaultExpression);
expression = andExpression;
}
else if (childExpression.IsNotNull())
{
expression = childExpression;
}
const int depth = childActivation->GetDepth() + 1;
const IHandlerActivation::Pointer localActivation(
new HandlerActivation(commandId, handler, expression, depth, this));
return DoActivation(localActivation);
}
SmartPointer<IHandlerActivation> SlaveHandlerService::ActivateHandler(const QString& commandId,
const SmartPointer<IHandler>& handler)
{
const IHandlerActivation::Pointer localActivation(
new HandlerActivation(commandId, handler, defaultExpression, IHandlerActivation::ROOT_DEPTH, this));
return DoActivation(localActivation);
}
SmartPointer<IHandlerActivation> SlaveHandlerService::ActivateHandler(const QString& commandId,
const SmartPointer<IHandler>& handler,
const SmartPointer<Expression>& expression)
{
return ActivateHandler(commandId, handler, expression, false);
}
SmartPointer<IHandlerActivation> SlaveHandlerService::ActivateHandler(const QString& commandId,
const SmartPointer<IHandler>& handler,
const SmartPointer<Expression>& expression,
bool global)
{
if (global)
{
const IHandlerActivation::Pointer activation = parent->ActivateHandler(
commandId, handler, expression, global);
parentActivations.insert(activation);
return activation;
}
Expression::Pointer aExpression = defaultExpression;
if (expression.IsNotNull() && defaultExpression.IsNotNull())
{
const AndExpression::Pointer andExpression(new AndExpression());
andExpression->Add(expression);
andExpression->Add(defaultExpression);
aExpression = andExpression;
}
else if (expression.IsNotNull())
{
aExpression = expression;
}
const IHandlerActivation::Pointer localActivation(
new HandlerActivation(commandId, handler, aExpression, IHandlerActivation::ROOT_DEPTH, this));
return DoActivation(localActivation);
}
void SlaveHandlerService::AddSourceProvider(const SmartPointer<ISourceProvider>& provider)
{
if (!fSourceProviders.contains(provider))
{
fSourceProviders.push_back(provider);
}
parent->AddSourceProvider(provider);
}
SmartPointer<const ExecutionEvent> SlaveHandlerService::CreateExecutionEvent(const SmartPointer<const Command>& command,
const SmartPointer<const UIElement>& event)
{
return parent->CreateExecutionEvent(command, event);
}
SmartPointer<const ExecutionEvent> SlaveHandlerService::CreateExecutionEvent(
const SmartPointer<const ParameterizedCommand>& command,
const SmartPointer<const UIElement>& event)
{
return parent->CreateExecutionEvent(command, event);
}
void SlaveHandlerService::DeactivateHandler(const SmartPointer<IHandlerActivation>& activation)
{
IHandlerActivation::Pointer parentActivation;
if (localActivationsToParentActivations.contains(activation))
{
parentActivation = localActivationsToParentActivations.take(activation);
}
else
{
parentActivation = activation;
}
if (parentActivation.IsNotNull())
{
parent->DeactivateHandler(parentActivation);
parentActivations.remove(parentActivation);
}
}
void SlaveHandlerService::DeactivateHandlers(const QList<SmartPointer<IHandlerActivation> >& activations)
{
for (int i = 0; i < activations.size(); i++)
{
DeactivateHandler(activations[i]);
}
}
void SlaveHandlerService::Dispose()
{
- parent->DeactivateHandlers(parentActivations.toList());
+ parent->DeactivateHandlers(parentActivations.values());
parentActivations.clear();
localActivationsToParentActivations.clear();
// Remove any "resource", like listeners, that were associated
// with this service.
if (!fSourceProviders.isEmpty())
{
for (int i = 0; i < fSourceProviders.size(); i++)
{
RemoveSourceProvider(fSourceProviders[i]);
}
fSourceProviders.clear();
}
}
Object::Pointer SlaveHandlerService::ExecuteCommand(const SmartPointer<ParameterizedCommand>& command,
const SmartPointer<const UIElement>& event)
{
return parent->ExecuteCommand(command, event);
}
Object::Pointer SlaveHandlerService::ExecuteCommand(const QString& commandId,
const SmartPointer<const UIElement>& event)
{
return parent->ExecuteCommand(commandId, event);
}
SmartPointer<IEvaluationContext> SlaveHandlerService::GetCurrentState() const
{
return parent->GetCurrentState();
}
void SlaveHandlerService::ReadRegistry()
{
parent->ReadRegistry();
}
void SlaveHandlerService::RemoveSourceProvider(const SmartPointer<ISourceProvider>& provider)
{
fSourceProviders.removeAll(provider);
parent->RemoveSourceProvider(provider);
}
void SlaveHandlerService::SetHelpContextId(const SmartPointer<IHandler>& handler,
const QString& helpContextId)
{
parent->SetHelpContextId(handler, helpContextId);
}
SmartPointer<Expression> SlaveHandlerService::GetDefaultExpression() const
{
return defaultExpression;
}
SmartPointer<IEvaluationContext> SlaveHandlerService::CreateContextSnapshot(bool includeSelection)
{
return parent->CreateContextSnapshot(includeSelection);
}
Object::Pointer SlaveHandlerService::ExecuteCommandInContext(const SmartPointer<ParameterizedCommand>& command,
const SmartPointer<const UIElement>& event,
const SmartPointer<IEvaluationContext>& context)
{
return parent->ExecuteCommandInContext(command, event, context);
}
SmartPointer<IHandlerActivation> SlaveHandlerService::DoActivation(
const SmartPointer<IHandlerActivation>& localActivation)
{
const IHandlerActivation::Pointer parentActivation = parent->ActivateHandler(localActivation);
parentActivations.insert(parentActivation);
localActivationsToParentActivations.insert(localActivation, parentActivation.GetPointer());
return localActivation;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berrySourceProviderService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berrySourceProviderService.cpp
index f0ce866065..4a80d065c4 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berrySourceProviderService.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berrySourceProviderService.cpp
@@ -1,81 +1,81 @@
/*============================================================================
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 "berrySourceProviderService.h"
#include "berryAbstractSourceProvider.h"
#include "berryWorkbenchServiceRegistry.h"
namespace berry {
SourceProviderService::SourceProviderService(IServiceLocator *locator)
: locator(locator)
{
}
void SourceProviderService::Dispose()
{
sourceProvidersByName.clear();
}
SmartPointer<ISourceProvider> SourceProviderService::GetSourceProvider(const QString& sourceName) const
{
return sourceProvidersByName.value(sourceName);
}
QList<SmartPointer<ISourceProvider> > SourceProviderService::GetSourceProviders() const
{
- return sourceProviders.toList();
+ return sourceProviders.values();
}
void SourceProviderService::RegisterProvider(const SmartPointer<ISourceProvider>& sourceProvider)
{
if (sourceProvider.IsNull())
{
throw ctkInvalidArgumentException("The source provider cannot be null");
}
const QList<QString> sourceNames = sourceProvider->GetProvidedSourceNames();
for (int i = 0; i < sourceNames.size(); i++)
{
const QString sourceName = sourceNames[i];
sourceProvidersByName.insert(sourceName, sourceProvider);
}
sourceProviders.insert(sourceProvider);
}
void SourceProviderService::UnregisterProvider(const SmartPointer<ISourceProvider>& sourceProvider)
{
if (sourceProvider.IsNull())
{
throw ctkInvalidArgumentException("The source provider cannot be null");
}
const QList<QString> sourceNames = sourceProvider->GetProvidedSourceNames();
for (int i = 0; i < sourceNames.size(); i++)
{
sourceProvidersByName.remove(sourceNames[i]);
}
sourceProviders.remove(sourceProvider);
}
void SourceProviderService::ReadRegistry()
{
QList<AbstractSourceProvider::Pointer> sp = WorkbenchServiceRegistry::GetRegistry()->GetSourceProviders();
for (int i = 0; i < sp.size(); i++)
{
sp[i]->Initialize(locator);
RegisterProvider(sp[i]);
}
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp
index 18425006a8..f882dff528 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp
@@ -1,155 +1,155 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berrySwitchToWindowMenu.h"
#include <berryMenuManager.h>
#include <berryShell.h>
#include <berryIWorkbench.h>
#include <berryIWorkbenchWindow.h>
#include <QAction>
#include <QActionGroup>
#include <QMenu>
#include <QSignalMapper>
namespace berry {
void SwitchToWindowMenu::AboutToShow(IMenuManager* manager)
{
manager->MarkDirty();
dirty = true;
}
void SwitchToWindowMenu::MenuItemTriggered(int index)
{
if (index < 0 || index >= windows.size()) return;
IWorkbenchWindow* window = windows[index];
Shell::Pointer windowShell = window->GetShell();
if (windowShell->GetMinimized())
{
windowShell->SetMinimized(false);
}
windowShell->SetActive();
windowShell->GetControl()->raise();
}
QString SwitchToWindowMenu::CalcText(int number, IWorkbenchWindow* window)
{
QString suffix = window->GetShell()->GetText();
if (suffix.isEmpty())
{
- return QString::null;
+ return QString();
}
QString sb;
if (number < 10)
{
sb.append('&');
}
sb.append(QString::number(number));
sb.append(' ');
if (suffix.size() <= MAX_TEXT_LENGTH)
{
sb.append(suffix);
}
else
{
- sb.append(suffix.leftRef(MAX_TEXT_LENGTH));
+ sb.append(QStringView(suffix).left(MAX_TEXT_LENGTH));
sb.append("...");
}
return sb;
}
SwitchToWindowMenu::SwitchToWindowMenu(IWorkbenchWindow* window, const QString& id, bool showSeparator)
: ContributionItem(id)
, workbenchWindow(window)
, showSeparator(showSeparator)
, dirty(true)
{
}
void SwitchToWindowMenu::Fill(QMenu* menu, QAction* before)
{
// Get workbench windows.
IWorkbench* workbench = workbenchWindow->GetWorkbench();
windows.clear();
for (const auto &window : workbench->GetWorkbenchWindows())
{
windows.push_back(window.GetPointer());
}
// avoid showing the separator and list for 0 or 1 items
if (windows.size() < 2)
{
return;
}
if (MenuManager* mm = dynamic_cast<MenuManager*>(GetParent()))
{
this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*)));
}
if (!dirty)
{
return;
}
// Add separator.
if (showSeparator)
{
menu->insertSeparator(before);
}
// Add one item for each window.
auto actionGroup = new QActionGroup(menu);
actionGroup->setExclusive(true);
auto signalMapper = new QSignalMapper(menu);
connect(signalMapper, SIGNAL(mapped(int)), SLOT(MenuItemTriggered(int)));
int count = 0;
- for (auto window : qAsConst(windows))
+ for (auto window : std::as_const(windows))
{
// can encounter disposed shells if this update is in response to a shell closing
//if (!window->GetShell()->IsDisposed())
//{
QString name = CalcText(count, window);
if (!name.isEmpty())
{
auto mi = new QAction(name, menu);
mi->setCheckable(true);
mi->setChecked(window == workbenchWindow);
actionGroup->addAction(mi);
menu->insertAction(before, mi);
signalMapper->setMapping(mi, count);
connect(mi, SIGNAL(triggered()), signalMapper, SLOT(map()));
}
++count;
}
//}
dirty = false;
}
bool SwitchToWindowMenu::IsDirty() const
{
return dirty;
}
bool SwitchToWindowMenu::IsDynamic() const
{
return true;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp
index f0a5255a50..c50c98b456 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp
@@ -1,206 +1,206 @@
/*============================================================================
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 "berryViewDescriptor.h"
#include "berryIConfigurationElement.h"
#include "berryCoreException.h"
#include "berryIExtension.h"
#include "berryIContributor.h"
#include "berryStatus.h"
#include "berryRegistryReader.h"
#include "berryWorkbenchRegistryConstants.h"
#include "berryAbstractUICTKPlugin.h"
#include "handlers/berryIHandlerActivation.h"
namespace berry
{
ViewDescriptor::ViewDescriptor(const IConfigurationElement::Pointer& e) :
configElement(e)
{
this->LoadFromExtension();
}
IViewPart::Pointer ViewDescriptor::CreateView()
{
IViewPart::Pointer part(configElement->CreateExecutableExtension<IViewPart> (
WorkbenchRegistryConstants::ATT_CLASS));
return part;
}
QStringList ViewDescriptor::GetCategoryPath() const
{
return categoryPath;
}
IConfigurationElement::Pointer ViewDescriptor::GetConfigurationElement() const
{
return configElement;
}
QString ViewDescriptor::GetDescription() const
{
return RegistryReader::GetDescription(configElement);
}
QString ViewDescriptor::GetId() const
{
return id;
}
bool ViewDescriptor::operator==(const Object* o) const
{
if (const IViewDescriptor* other = dynamic_cast<const IViewDescriptor*>(o))
return this->GetId() == other->GetId();
return false;
}
QIcon ViewDescriptor::GetImageDescriptor() const
{
if (!imageDescriptor.isNull())
{
return imageDescriptor;
}
QString iconName = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON);
// If the icon attribute was omitted, use the default one
if (iconName.isEmpty())
{
//TODO default image descriptor
//return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_DEF_VIEW);
return AbstractUICTKPlugin::GetMissingIcon();
}
IExtension::Pointer extension(configElement->GetDeclaringExtension());
const QString extendingPluginId(extension->GetContributor()->GetName());
imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin(
extendingPluginId, iconName);
// If the icon attribute was invalid, use the error icon
if (imageDescriptor.isNull())
{
imageDescriptor = AbstractUICTKPlugin::GetMissingIcon();
}
return imageDescriptor;
}
QString ViewDescriptor::GetLabel() const
{
return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME);
}
QString ViewDescriptor::GetAccelerator() const
{
return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ACCELERATOR);
}
bool ViewDescriptor::GetAllowMultiple() const
{
return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ALLOW_MULTIPLE).compare("true", Qt::CaseInsensitive) == 0;
}
bool ViewDescriptor::IsRestorable() const
{
QString str = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_RESTORABLE);
return str.isNull() ? true : str.compare("true", Qt::CaseInsensitive) == 0;
}
Object* ViewDescriptor::GetAdapter(const QString& adapter) const
{
if (adapter == qobject_interface_iid<IConfigurationElement*>())
{
return GetConfigurationElement().GetPointer();
}
return nullptr;
}
void
ViewDescriptor::ActivateHandler()
{
//TODO ViewDescriptor handler activation
// if (!handlerActivation)
// {
// IHandler::Pointer handler(new ShowViewHandler(this->GetId()));
// IHandlerService::Pointer handlerService(
// PlatformUI::GetWorkbench()->GetService(IHandlerService::GetManifestName()).Cast<IHandlerService>());
// handlerActivation = handlerService
// ->ActivateHandler(this->GetId(), handler);
// }
}
void
ViewDescriptor::DeactivateHandler()
{
//TODO ViewDescriptor handler deactivation
// if (handlerActivation)
// {
// IHandlerService::Pointer handlerService(
// PlatformUI::GetWorkbench()->GetService(IHandlerService::GetManifestName()).Cast<IHandlerService>());
// handlerService->DeactivateHandler(handlerActivation);
// handlerActivation = 0;
// }
}
QStringList ViewDescriptor::GetKeywordReferences() const
{
QStringList result;
auto keywordRefs = configElement->GetChildren("keywordReference");
for (auto keywordRefsIt = keywordRefs.begin();
keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs
{
result.push_back((*keywordRefsIt)->GetAttribute("id"));
}
return result;
}
QString ViewDescriptor::GetPluginId() const
{
return configElement->GetContributor()->GetName();
}
QString ViewDescriptor::GetLocalId() const
{
return this->GetId();
}
void ViewDescriptor::LoadFromExtension()
{
id = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID);
// Sanity check.
QString name = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME);
if (name.isEmpty() ||
RegistryReader::GetClassValue(configElement, WorkbenchRegistryConstants::ATT_CLASS).isEmpty())
{
IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, configElement->GetContributor()->GetName(), nullptr,
QString("Invalid extension (missing label or class name): ") + id));
throw CoreException(status);
}
QString category = configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY);
if (!category.isEmpty())
{
// Parse the path tokens and store them
- foreach (QString pathElement, category.split('/', QString::SkipEmptyParts))
+ foreach (QString pathElement, category.split('/', Qt::SkipEmptyParts))
{
if (!pathElement.trimmed().isEmpty())
{
categoryPath.push_back(pathElement.trimmed());
}
}
}
}
} // namespace berry
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp
index eab4111d2f..64a04d471b 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp
@@ -1,1059 +1,1059 @@
/*============================================================================
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 "berryWorkbenchMenuService.h"
#include <berryIPropertyChangeListener.h>
#include <berryIServiceLocator.h>
#include <berryIEvaluationService.h>
#include <berryIEvaluationReference.h>
#include <berryIEvaluationContext.h>
#include <berrySafeRunner.h>
#include <berryAbstractContributionFactory.h>
#include <berryObjects.h>
#include <berryMenuUtil.h>
#include <berryWorkbenchActionConstants.h>
#include "berryAbstractGroupMarker.h"
#include "berryAbstractMenuAdditionCacheEntry.h"
#include "berryAlwaysEnabledExpression.h"
#include "berryContributionItem.h"
#include "berryContributionRoot.h"
#include "berryMenuManager.h"
#include "berryWorkbenchPlugin.h"
#include "berryWorkbenchWindow.h"
#include <QUrlQuery>
namespace berry {
const QString WorkbenchMenuService::INDEX_AFTER_ADDITIONS_QK = "after";
const QString WorkbenchMenuService::INDEX_AFTER_ADDITIONS_QV = "additions";
const QString WorkbenchMenuService::PROP_VISIBLE = "visible";
/**
* A combined property and activity listener that updates the visibility of
* contribution items in the new menu system.
*/
class ContributionItemUpdater : public IPropertyChangeListener //, public IIdentifierListener
{
private:
const IContributionItem::Pointer item;
//IIdentifier identifier;
bool lastExpressionResult;
WorkbenchMenuService* wms;
void UpdateVisibility()
{
//bool visible = identifier.IsNotNull() ? (identifier->IsEnabled() && lastExpressionResult)
// : lastExpressionResult;
bool visible = lastExpressionResult;
item->SetVisible(visible);
IContributionManager* parent = nullptr;
if (ContributionItem::Pointer ci = item.Cast<ContributionItem>())
{
parent = ci->GetParent();
}
else if (MenuManager::Pointer mm = item.Cast<MenuManager>())
{
parent = mm->GetParent();
}
if (parent != nullptr)
{
parent->MarkDirty();
wms->managersAwaitingUpdates.insert(parent);
}
}
public:
ContributionItemUpdater(WorkbenchMenuService* wms, const IContributionItem::Pointer& item) //, IIdentifier identifier)
: item(item), lastExpressionResult(true), wms(wms)
{
// if (identifier.IsNotNull())
// {
// this->identifier = identifier;
// this->identifier->AddIdentifierListener(this);
// UpdateVisibility(); // force initial visibility to fall in line
// // with activity enablement
// }
}
/**
* Dispose of this updater
*/
~ContributionItemUpdater() override
{
// if (identifier.IsNotNull())
// identifier->RemoveIdentifierListener(this);
}
using IPropertyChangeListener::PropertyChange;
/*
* @see IPropertyChangeListener#PropertyChange(PropertyChangeEvent)
*/
void PropertyChange(const PropertyChangeEvent::Pointer& event) override
{
if (event->GetProperty() == WorkbenchMenuService::PROP_VISIBLE)
{
if (event->GetNewValue().IsNotNull())
{
lastExpressionResult = event->GetNewValue();
}
else
{
lastExpressionResult = false;
}
UpdateVisibility();
}
}
/*
* @see IIdentifierListener#IdentifierChanged(IdentifierEvent)
*/
// void identifierChanged(IdentifierEvent identifierEvent)
// {
// UpdateVisibility();
// }
};
WorkbenchMenuService::ManagerPopulationRecord::ManagerPopulationRecord()
: wms(nullptr), serviceLocatorToUse(nullptr), recurse(false)
{
}
WorkbenchMenuService::ManagerPopulationRecord::
ManagerPopulationRecord(WorkbenchMenuService* wms, IServiceLocator* serviceLocatorToUse, const QSet<SmartPointer<IEvaluationReference> >& restriction,
const QString& uri, bool recurse)
: wms(wms), serviceLocatorToUse(serviceLocatorToUse), restriction(restriction),
uri(uri), recurse(recurse)
{
}
void WorkbenchMenuService::ManagerPopulationRecord::
AddFactoryContribution(const SmartPointer<AbstractContributionFactory>& factory,
const SmartPointer<ContributionRoot>& ciList)
{
// Remove any existing cache info for this factory
RemoveFactoryContribution(factory);
// save the new info
factoryToItems.insert(factory, ciList);
}
void WorkbenchMenuService::ManagerPopulationRecord::
RemoveFactoryContribution(const SmartPointer<AbstractContributionFactory>& factory)
{
ContributionRoot::Pointer items = factoryToItems.take(factory);
if (items.IsNotNull())
{
wms->ReleaseContributions(items.GetPointer());
}
}
SmartPointer<ContributionRoot> WorkbenchMenuService::ManagerPopulationRecord::
GetContributions(const SmartPointer<AbstractContributionFactory>& factory) const
{
if (factoryToItems.contains(factory))
return factoryToItems[factory];
return ContributionRoot::Pointer(nullptr);
}
void WorkbenchMenuService::ManagerPopulationRecord::
ReleaseContributions()
{
foreach (ContributionRoot::Pointer items, factoryToItems.values())
{
wms->ReleaseContributions(items.GetPointer());
}
factoryToItems.clear();
}
WorkbenchMenuService::WorkbenchMenuService(IServiceLocator* serviceLocator)
: evaluationService(nullptr), serviceLocator(serviceLocator)
{
//this.menuPersistence = new MenuPersistence(this);
evaluationService = serviceLocator->GetService<IEvaluationService>();
evaluationService->AddServiceListener(GetServiceListener());
// IWorkbenchLocationService wls = (IWorkbenchLocationService) serviceLocator
// .getService(IWorkbenchLocationService.class);
// wls.getWorkbench()
// .getActivitySupport().getActivityManager()
// .addActivityManagerListener(getActivityManagerListener());
// final IExtensionRegistry registry = Platform.getExtensionRegistry();
// registryChangeListener = new IRegistryChangeListener() {
// public void registryChanged(final IRegistryChangeEvent event) {
// final Display display = PlatformUI.getWorkbench().getDisplay();
// if (display.isDisposed()) {
// return;
// }
// display.syncExec(new Runnable() {
// public void run() {
// handleRegistryChanges(event);
// }
// });
// }
// };
// registry.addRegistryChangeListener(registryChangeListener);
}
WorkbenchMenuService::~WorkbenchMenuService()
{
this->Dispose();
}
void WorkbenchMenuService::Dispose()
{
//menuPersistence.dispose();
// if (registryChangeListener != null)
// {
// final IExtensionRegistry registry = Platform.getExtensionRegistry();
// registry.removeRegistryChangeListener(registryChangeListener);
// registryChangeListener = null;
// }
foreach (IEvaluationReference::Pointer ref, evaluationsByItem.values())
{
evaluationService->RemoveEvaluationListener(ref);
}
evaluationsByItem.clear();
managersAwaitingUpdates.clear();
evaluationService->RemoveServiceListener(GetServiceListener());
// if (activityManagerListener != null)
// {
// IWorkbenchLocationService wls = (IWorkbenchLocationService) serviceLocator
// .getService(IWorkbenchLocationService.class);
// IWorkbench workbench = wls.getWorkbench();
// if (workbench != null)
// {
// workbench.getActivitySupport().getActivityManager()
// .removeActivityManagerListener(activityManagerListener);
// }
// }
}
void WorkbenchMenuService::AddSourceProvider(const SmartPointer<ISourceProvider>& /*provider*/)
{
// no-op
}
void WorkbenchMenuService::ReadRegistry()
{
//menuPersistence.read();
}
void WorkbenchMenuService::RemoveSourceProvider(const SmartPointer<ISourceProvider>& /*provider*/)
{
// no-op
}
void WorkbenchMenuService::UpdateManagers()
{
- QList<IContributionManager*> managers = managersAwaitingUpdates.toList();
+ QList<IContributionManager*> managers = managersAwaitingUpdates.values();
managersAwaitingUpdates.clear();
foreach (IContributionManager* mgr, managers)
{
mgr->Update(true);
// if (ToolBarManager* tbMgr = dynamic_cast<ToolBarManager*>(mgr))
// {
// if (!UpdateToolBar(tbMgr))
// {
// //UpdateTrim((ToolBarManager) mgr);
// }
// }
// else
if (MenuManager* mMgr = dynamic_cast<MenuManager*>(mgr))
{
IContributionManager* parent = mMgr->GetParent();
if (parent != nullptr)
{
parent->Update(true);
}
}
}
}
WorkbenchMenuService::FactoryListType WorkbenchMenuService::GetAdditionsForURI(const QUrl& uri)
{
if (uri.isEmpty())
return FactoryListType();
return uriToFactories[GetIdFromURI(uri)];
}
void WorkbenchMenuService::AddContributionFactory(const SmartPointer<AbstractContributionFactory>& factory)
{
if (factory.IsNull() || factory->GetLocation().isNull())
return;
QUrl uri(factory->GetLocation());
QString factoryId = GetIdFromURI(uri);
FactoryListType& factories = uriToFactories[factoryId];
{
// MenuAdditionCacheEntry::Pointer mace = factory.Cast<MenuAdditionCacheEntry>();
// if (mace && mace->HasAdditions())
// {
// factories.push_front(factory);
// }
// else
{
factories.push_back(factory);
}
}
// OK, now update any managers that use this uri
FactoryListType factoryList;
factoryList.push_back(factory);
foreach (IContributionManager* mgr, GetManagersFor(factoryId))
{
const ManagerPopulationRecord& mpr = populatedManagers[mgr];
AddContributionsToManager(mpr.serviceLocatorToUse, mpr.restriction,
dynamic_cast<ContributionManager*>(mgr), mpr.uri, mpr.recurse, factoryList);
mgr->Update(true);
}
}
void WorkbenchMenuService::RemoveContributionFactory(const SmartPointer<AbstractContributionFactory>& factory)
{
if (factory.IsNull() || factory->GetLocation().isNull())
return;
QUrl uri(factory->GetLocation());
QString factoryId = GetIdFromURI(uri);
if (uriToFactories.contains(factoryId))
{
FactoryListType& factories = uriToFactories[factoryId];
// // Before we remove the top-level cache we recursively
// // remove any sub-caches created by this one
// if (MenuAdditionCacheEntry::Pointer mace = factory.Cast<MenuAdditionCacheEntry>())
// {
// QList<AbstractMenuAdditionCacheEntry::Pointer> subCaches = mace->GetSubCaches();
// foreach (AbstractMenuAdditionCacheEntry::Pointer amace, subCaches)
// {
// RemoveContributionFactory(amace);
// }
// }
factories.removeAll(factory);
}
// OK, now update any managers that use this uri
FactoryListType factoryList;
factoryList.push_back(factory);
foreach (IContributionManager* mgr, GetManagersFor(factoryId))
{
RemoveContributionsForFactory(mgr, factory);
mgr->Update(true);
}
}
void WorkbenchMenuService::PopulateContributionManager(ContributionManager* mgr, const QString& uri)
{
PopulateContributionManager(serviceLocator, QSet<SmartPointer<IEvaluationReference> >(), mgr, uri, true);
}
void WorkbenchMenuService::PopulateContributionManager(IServiceLocator* serviceLocatorToUse,
const QSet<SmartPointer<IEvaluationReference> >& restriction,
ContributionManager* mgr,
const QString& uri, bool recurse)
{
// Track this attempt to populate the menu, remembering all the parameters
if (!populatedManagers.contains(mgr))
{
populatedManagers.insert(mgr, ManagerPopulationRecord(this, serviceLocatorToUse,
restriction, uri, recurse));
}
QUrl contributionLocation(uri);
FactoryListType factories = GetAdditionsForURI(contributionLocation);
AddContributionsToManager(serviceLocatorToUse, restriction, mgr, uri, recurse, factories);
}
void WorkbenchMenuService::AddContributionsToManager(IServiceLocator* serviceLocatorToUse,
const QSet<SmartPointer<IEvaluationReference> >& restriction,
ContributionManager* mgr,
const QString& uri, bool recurse,
const QList<SmartPointer<AbstractContributionFactory> >& factories)
{
QUrl contributionLocation(uri);
QList<AbstractContributionFactory::Pointer> retryList;
QSet<QString> itemsAdded;
foreach (AbstractContributionFactory::Pointer cache, factories)
{
if (!ProcessAdditions(serviceLocatorToUse, restriction, mgr,
cache, itemsAdded))
{
retryList.push_back(cache);
}
}
// OK, iteratively loop through entries whose URI's could not
// be resolved until we either run out of entries or the list
// doesn't change size (indicating that the remaining entries
// can never be resolved).
bool done = retryList.isEmpty();
while (!done)
{
// Clone the retry list and clear it
QList<AbstractContributionFactory::Pointer> curRetry = retryList;
int retryCount = retryList.size();
retryList.clear();
// Walk the current list seeing if any entries can now be resolved
foreach (AbstractContributionFactory::Pointer cache, curRetry)
{
if (!ProcessAdditions(serviceLocatorToUse, restriction, mgr,
cache, itemsAdded))
{
retryList.push_back(cache);
}
}
// We're done if the retryList is now empty (everything done) or
// if the list hasn't changed at all (no hope)
done = retryList.isEmpty() || (retryList.size() == retryCount);
}
// Now, recurse through any sub-menus
foreach (IContributionItem::Pointer curItem, mgr->GetItems())
{
if (ContributionManager::Pointer cm = curItem.Cast<ContributionManager>())
{
QString id = curItem->GetId();
if (!id.isEmpty() && (recurse || itemsAdded.contains(id)))
{
PopulateContributionManager(serviceLocatorToUse,
restriction, cm.GetPointer(),
contributionLocation.scheme() + ":" + id, true);
}
}
// else if (IToolBarContributionItem::Pointer tbci = curItem.Cast<IToolBarContributionItem>())
// {
// if (!(tbci->GetId().isEmpty()) && (recurse || itemsAdded.contains(tbci->GetId())))
// {
// PopulateContributionManager(serviceLocatorToUse,
// restriction, dynamic_cast<ContributionManager*>(tbci->GetToolBarManager()),
// contributionLocation.scheme() + ":" + tbci->GetId(), true);
// }
// }
}
}
SmartPointer<IEvaluationContext> WorkbenchMenuService::GetCurrentState() const
{
return evaluationService->GetCurrentState();
}
void WorkbenchMenuService::RegisterVisibleWhen(const SmartPointer<IContributionItem>& item,
const SmartPointer<Expression>& visibleWhen,
QSet<SmartPointer<IEvaluationReference> >& /*restriction*/,
const QString& /*identifierID*/)
{
if (item.IsNull())
{
throw std::invalid_argument("item cannot be null");
}
if (visibleWhen.IsNull())
{
throw std::invalid_argument("visibleWhen expression cannot be null");
}
if (evaluationsByItem.contains(item))
{
QString id = item->GetId();
WorkbenchPlugin::Log(QString("item is already registered: ") + (id.isEmpty() ? QString("no id") : id));
return;
}
// TODO activity support
// IIdentifier identifier = null;
// if (identifierID != null) {
// identifier = PlatformUI.getWorkbench().getActivitySupport()
// .getActivityManager().getIdentifier(identifierID);
// }
// ContributionItemUpdater* listener =
// new ContributionItemUpdater(item, identifier);
// if (visibleWhen != AlwaysEnabledExpression::INSTANCE)
// {
// IEvaluationReference::Pointer ref = evaluationService->AddEvaluationListener(
// visibleWhen, listener, PROP_VISIBLE);
// restriction.insert(ref);
// evaluationsByItem.insert(item, ref);
// }
// activityListenersByItem.put(item, listener);
}
void WorkbenchMenuService::UnregisterVisibleWhen(const SmartPointer<IContributionItem>& item,
QSet<SmartPointer<IEvaluationReference> >& restriction)
{
// TODO activity support
// ContributionItemUpdater identifierListener = (ContributionItemUpdater) activityListenersByItem
// .remove(item);
// if (identifierListener != null) {
// identifierListener.dispose();
// }
IEvaluationReference::Pointer ref = evaluationsByItem.take(item);
if (ref.IsNull())
{
return;
}
evaluationService->RemoveEvaluationListener(ref);
restriction.remove(ref);
}
void WorkbenchMenuService::ReleaseContributions(ContributionManager* mgr)
{
if (mgr == nullptr)
return;
// Recursively remove any contributions from sub-menus
foreach (IContributionItem::Pointer item, mgr->GetItems())
{
if (ContributionManager::Pointer cm = item.Cast<ContributionManager>())
{
ReleaseContributions(cm.GetPointer());
}
// else if (IToolBarContributionItem::Pointer tbci = item.Cast<IToolBarContributionItem>())
// {
// ReleaseContributions(tbci->GetToolBarManager());
// }
}
// Now remove any cached information
if (populatedManagers.contains(mgr))
{
populatedManagers[mgr].ReleaseContributions();
populatedManagers.remove(mgr);
}
managersAwaitingUpdates.remove(mgr);
}
//void WorkbenchMenuService::HandleDynamicAdditions(const QList<SmartPointer<IConfigurationElement> >& menuAdditions)
//{
// for (Iterator additionsIter = menuAdditions.iterator(); additionsIter.hasNext();) {
// AbstractContributionFactory newFactory = null;
// final IConfigurationElement menuAddition = (IConfigurationElement) additionsIter.next();
// if (isProgramaticContribution(menuAddition))
// newFactory = new ProxyMenuAdditionCacheEntry(
// menuAddition
// .getAttribute(IWorkbenchRegistryConstants.TAG_LOCATION_URI),
// menuAddition.getNamespaceIdentifier(), menuAddition);
// else
// newFactory = new MenuAdditionCacheEntry(
// this,
// menuAddition,
// menuAddition
// .getAttribute(IWorkbenchRegistryConstants.TAG_LOCATION_URI),
// menuAddition.getNamespaceIdentifier());
// if (newFactory != null)
// addContributionFactory(newFactory);
// }
//}
//void WorkbenchMenuService::HandleDynamicRemovals(const QList<SmartPointer<IConfigurationElement> >& menuRemovals)
//{
// for (Iterator additionsIter = menuRemovals.iterator(); additionsIter.hasNext();) {
// IConfigurationElement ceToRemove = (IConfigurationElement) additionsIter.next();
// AbstractMenuAdditionCacheEntry factoryToRemove = findFactory(ceToRemove);
// removeContributionFactory(factoryToRemove);
// }
//}
//void WorkbenchMenuService::HandleRegistryChanges(const SmartPointer<IRegistryChangeEvent>& event)
//{
// // HACK!! determine if this is an addition or deletion from the first delta
// IExtensionDelta[] deltas = event.getExtensionDeltas();
// if (deltas.length == 0)
// return;
// boolean isAddition = deltas[0].getKind() == IExtensionDelta.ADDED;
// // access all the necessary service persistence handlers
// HandlerService handlerSvc = (HandlerService) serviceLocator.getService(IHandlerService.class);
// HandlerPersistence handlerPersistence = handlerSvc.getHandlerPersistence();
// CommandService cmdSvc = (CommandService) serviceLocator.getService(ICommandService.class);
// CommandPersistence cmdPersistence = cmdSvc.getCommandPersistence();
// BindingService bindingSvc = (BindingService) serviceLocator.getService(IBindingService.class);
// BindingPersistence bindingPersistence = bindingSvc.getBindingPersistence();
// boolean needsUpdate = false;
// // determine order from the type of delta
// if (isAddition) {
// // additions order: Commands, Handlers, Bindings, Menus
// if (cmdPersistence.commandsNeedUpdating(event)) {
// cmdPersistence.reRead();
// needsUpdate = true;
// }
// if (handlerPersistence.handlersNeedUpdating(event)) {
// handlerPersistence.reRead();
// needsUpdate = true;
// }
// if (bindingPersistence.bindingsNeedUpdating(event)) {
// bindingPersistence.reRead();
// needsUpdate = true;
// }
// if (menuPersistence.menusNeedUpdating(event)) {
// handleMenuChanges(event);
// needsUpdate = true;
// }
// }
// else {
// // Removal order: Menus, Bindings, Handlers, Commands
// if (menuPersistence.menusNeedUpdating(event)) {
// handleMenuChanges(event);
// needsUpdate = true;
// }
// if (bindingPersistence.bindingsNeedUpdating(event)) {
// bindingPersistence.reRead();
// needsUpdate = true;
// }
// if (handlerPersistence.handlersNeedUpdating(event)) {
// final IExtensionDelta[] handlerDeltas = event.getExtensionDeltas(
// PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_HANDLERS);
// for (int i = 0; i < handlerDeltas.length; i++) {
// IConfigurationElement[] ices = handlerDeltas[i].getExtension().getConfigurationElements();
// HandlerProxy.updateStaleCEs(ices);
// }
// handlerPersistence.reRead();
// needsUpdate = true;
// }
// if (cmdPersistence.commandsNeedUpdating(event)) {
// cmdPersistence.reRead();
// needsUpdate = true;
// }
// }
// if (needsUpdate) {
// ContributionManager[] managers = (ContributionManager[]) populatedManagers
// .keySet().toArray(
// new ContributionManager[populatedManagers.keySet()
// .size()]);
// for (int i = 0; i < managers.length; i++) {
// ContributionManager mgr = managers[i];
// mgr.update(false);
// }
// }
//}
//MenuPersistence* WorkbenchMenuService::GetMenuPersistence()
//{
// return menuPersistence;
//}
void WorkbenchMenuService::PopulateContributionManager(ContributionManager* mgr,
const QString& uri, bool recurse)
{
PopulateContributionManager(serviceLocator, QSet<IEvaluationReference::Pointer>(), mgr, uri, recurse);
}
void WorkbenchMenuService::RemoveContributionsForFactory(IContributionManager* manager,
const SmartPointer<AbstractContributionFactory>& factory)
{
populatedManagers[manager].RemoveFactoryContribution(factory); // automatically cleans its caches
}
void WorkbenchMenuService::ReleaseContributions(ContributionRoot* items)
{
ContributionManager* mgr = items->GetManager();
foreach(IContributionItem::Pointer item, items->GetItems())
{
ReleaseItem(item, items->restriction);
mgr->Remove(item);
}
ReleaseCache(items);
}
void WorkbenchMenuService::PropertyChange(const PropertyChangeEvent::Pointer& event)
{
if (event->GetProperty() == IEvaluationService::PROP_NOTIFYING)
{
if (!(event->GetNewValue().Cast<ObjectBool>()->GetValue()))
{
// if it's false, the evaluation service has
// finished with its latest round of updates
this->UpdateManagers();
}
}
}
//SmartPointer<IActivityManagerListener> WorkbenchMenuService::GetActivityManagerListener()
//{
// if (activityManagerListener == null) {
// activityManagerListener = new IActivityManagerListener() {
// public void activityManagerChanged(
// ActivityManagerEvent activityManagerEvent) {
// if (activityManagerEvent.haveEnabledActivityIdsChanged()) {
// updateManagers(); // called after all identifiers have
// // been update - now update the
// // managers
// }
// }
// };
// }
// return activityManagerListener;
//}
IPropertyChangeListener* WorkbenchMenuService::GetServiceListener()
{
return this;
}
//void WorkbenchMenuService::UpdateTrim(ToolBarManager* mgr)
//{
// Control control = mgr.getControl();
// if (control == null || control.isDisposed()) {
// return;
// }
// LayoutUtil.resize(control);
//}
bool WorkbenchMenuService::UpdateToolBar(ToolBarManager* /*mgr*/)
{
// QList<IWorkbenchWindow::Pointer> windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows();
// QList<IWorkbenchWindow::Pointer>::iterator wend = windows.end();
// for (QList<IWorkbenchWindow::Pointer>::iterator i = windows.begin(); i != wend; ++i)
// {
// WorkbenchWindow::Pointer window = i->Cast<WorkbenchWindow>();
// IToolBarManager* tb = window->GetToolBarManager();
// if (tb != 0)
// {
// foreach (IContributionItem::Pointer item, tb->GetItems())
// {
// if (ToolBarContributionItem::Pointer tbci = item.Cast<ToolBarContributionItem>())
// {
// IToolBarManager* tbm = tbci->GetToolBarManager();
// if (mgr == tbm)
// {
// tb->Update(true);
// return true;
// }
// }
// }
// }
// }
return false;
}
QString WorkbenchMenuService::GetIdFromURI(const QUrl& uri)
{
return uri.scheme() + ":" + uri.path();
}
QList<IContributionManager*> WorkbenchMenuService::GetManagersFor(const QString& factoryId)
{
QList<IContributionManager*> mgrs;
QHashIterator<IContributionManager*,ManagerPopulationRecord> mgrIter(populatedManagers);
while(mgrIter.hasNext())
{
if (factoryId == mgrIter.value().uri)
{
mgrs.push_back(mgrIter.key());
}
}
return mgrs;
}
bool WorkbenchMenuService::ProcessAdditions(IServiceLocator* serviceLocatorToUse,
const QSet<SmartPointer<IEvaluationReference> >& restriction,
ContributionManager* mgr,
const AbstractContributionFactory::Pointer& cache,
QSet<QString>& itemsAdded)
{
if (!ProcessFactory(mgr, cache))
return true;
const int idx = GetInsertionIndex(mgr, cache->GetLocation());
if (idx == -1)
return false; // can't process (yet)
struct _SafeRunnable : public ISafeRunnable
{
WorkbenchMenuService* wms;
int insertionIndex;
IServiceLocator* serviceLocatorToUse;
QSet<SmartPointer<IEvaluationReference> > restriction;
ContributionManager* mgr;
AbstractContributionFactory::Pointer cache;
QSet<QString>& itemsAdded;
_SafeRunnable(WorkbenchMenuService* wms, int idx, IServiceLocator* serviceLocatorToUse,
const QSet<SmartPointer<IEvaluationReference> >& restriction,
ContributionManager* mgr, AbstractContributionFactory::Pointer cache,
QSet<QString>& itemsAdded)
: wms(wms), insertionIndex(idx), serviceLocatorToUse(serviceLocatorToUse),
restriction(restriction), mgr(mgr), cache(cache), itemsAdded(itemsAdded)
{}
void HandleException(const ctkException&) override
{}
void Run() override
{
// Get the additions
ContributionRoot::Pointer ciList(new ContributionRoot(wms, restriction,
mgr, cache.GetPointer()));
cache->CreateContributionItems(serviceLocatorToUse, ciList);
// If we have any then add them at the correct location
if (!ciList->GetItems().isEmpty())
{
// Cache the items for future cleanup
ManagerPopulationRecord& mpr = wms->populatedManagers[mgr];
ContributionRoot::Pointer contributions = mpr.GetContributions(cache);
if (contributions.IsNotNull())
{
// Existing contributions in the mgr will be released.
// Adjust the insertionIndex
foreach (IContributionItem::Pointer item, contributions->GetItems())
{
if (item == mgr->Find(item->GetId()))
insertionIndex--;
}
}
mpr.AddFactoryContribution(cache, ciList);
foreach (IContributionItem::Pointer ici, ciList->GetItems())
{
if ((ici.Cast<ContributionManager>() ||
//ici.Cast<IToolBarContributionItem> ||
ici.Cast<AbstractGroupMarker>())
&& !(ici->GetId().isEmpty()))
{
IContributionItem::Pointer foundIci = mgr->Find(ici->GetId());
// really, this is a very specific scenario that
// allows merging but, if it is a contribution manager that also
// contains items, then we would be throwing stuff away.
if (ContributionManager::Pointer cm = foundIci.Cast<ContributionManager>())
{
if (cm->GetSize() > 0)
{
// IStatus status = new Status(
// IStatus.WARNING,
// WorkbenchPlugin.PI_WORKBENCH,
// "Menu contribution id collision: "
// + ici.getId());
// StatusManager.getManager().handle(status);
BERRY_WARN << "Menu contribution id collision: " << ici->GetId().toStdString();
}
continue;
}
// else if (IToolBarContributionItem::Pointer tbci = foundIci.Cast<IToolBarContributionItem>())
// {
// IToolBarManager* toolBarManager = tbci->GetToolBarManager();
// if (ContributionManager::Pointer tbcm = dynamic_cast<ContributionManager*>(toolBarManager)
// && tbcm->GetSize() > 0)
// {
//// IStatus status = new Status(
//// IStatus.WARNING,
//// WorkbenchPlugin.PI_WORKBENCH,
//// "Toolbar contribution id collision: " //$NON-NLS-1$
//// + ici.getId());
//// StatusManager.getManager().handle(status);
// BERRY_WARN << "Toolbar contribution id collision: " << ici->GetId().toStdString();
// }
// continue;
// }
else if (foundIci.Cast<AbstractGroupMarker>())
{
continue;
}
}
const int oldSize = mgr->GetSize();
mgr->Insert(insertionIndex, ici);
if (!ici->GetId().isEmpty())
{
itemsAdded.insert(ici->GetId());
}
if (mgr->GetSize() > oldSize)
insertionIndex++;
}
}
}
};
ISafeRunnable::Pointer run (new _SafeRunnable(this, idx, serviceLocatorToUse, restriction,
mgr, cache, itemsAdded));
SafeRunner::Run(run);
return true;
}
bool WorkbenchMenuService::ProcessFactory(ContributionManager* mgr,
const AbstractContributionFactory::Pointer& factory)
{
QUrl uri(factory->GetLocation());
if (MenuUtil::ANY_POPUP == (uri.scheme() + ':' + uri.path()))
{
// its any popup. check whether manager has additions
if (mgr->IndexOf(WorkbenchActionConstants::MB_ADDITIONS) == -1)
{
// // menu has no additions. Add only if allPopups = true
// if (MenuAdditionCacheEntry::Pointer menuEntry = factory.Cast<MenuAdditionCacheEntry>())
// {
// return menuEntry->ContributeToAllPopups();
// }
}
}
return true;
}
void WorkbenchMenuService::ReleaseCache(ContributionRoot* items)
{
items->Release();
}
int WorkbenchMenuService::GetInsertionIndex(ContributionManager* mgr, const QString& location)
{
QUrl uri(location);
QUrlQuery query(uri);
QList<QPair<QString,QString> > queryParts = query.queryItems();
bool indexAfterAdditions = query.queryItemValue(INDEX_AFTER_ADDITIONS_QK) == INDEX_AFTER_ADDITIONS_QV;
int additionsIndex = -1;
// No Query means 'after=additions' (if there) or
// the end of the menu
if (queryParts.isEmpty() || indexAfterAdditions)
{
additionsIndex = mgr->IndexOf(WorkbenchActionConstants::MB_ADDITIONS);
if (additionsIndex == -1)
additionsIndex = mgr->GetItems().size();
else
++additionsIndex;
}
else
{
// Should be in the form "[before|after|endof]=id"
if (queryParts.size() > 0 && !(queryParts[0].second.isEmpty()))
{
QString modifier = queryParts[0].first;
QString id = queryParts[0].second;
additionsIndex = mgr->IndexOf(id);
if (additionsIndex != -1)
{
if (MenuUtil::QUERY_BEFORE == modifier)
{
// this is OK, the additionsIndex will either be correct
// or -1 (which is a no-op)
}
else if (MenuUtil::QUERY_AFTER == modifier)
{
additionsIndex++;
}
else if (MenuUtil::QUERY_ENDOF == modifier)
{
// OK, this one is exciting
QList<IContributionItem::Pointer> items = mgr->GetItems();
for (additionsIndex++; additionsIndex < items.size(); additionsIndex++)
{
if (items[additionsIndex]->IsGroupMarker())
{
break;
}
}
}
}
}
}
return additionsIndex;
}
void WorkbenchMenuService::ReleaseItem(const SmartPointer<IContributionItem>& item, QSet<SmartPointer<IEvaluationReference> >& restriction)
{
UnregisterVisibleWhen(item, restriction);
if (ContributionManager::Pointer cm = item.Cast<ContributionManager>())
{
ReleaseContributions(cm.GetPointer());
}
// else if (IToolBarContributionItem::Pointer tbci = item.Cast<IToolBarContributionItem>())
// {
// ReleaseContributions(dynamic_cast<ContributionManager*>(tbci->GetToolBarManager()));
// }
}
bool WorkbenchMenuService::IsProgramaticContribution(const SmartPointer<IConfigurationElement>& menuAddition) const
{
return !menuAddition->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS).isEmpty();
}
SmartPointer<AbstractMenuAdditionCacheEntry> WorkbenchMenuService::FindFactory(const SmartPointer<IConfigurationElement>& ceToRemove)
{
QUrl uri = ceToRemove->GetAttribute(WorkbenchRegistryConstants::TAG_LOCATION_URI);
FactoryListType factories = GetAdditionsForURI(uri);
foreach (AbstractContributionFactory::Pointer factory, GetAdditionsForURI(uri))
{
if (AbstractMenuAdditionCacheEntry::Pointer mace = factory.Cast<AbstractMenuAdditionCacheEntry>())
{
if (mace->GetConfigElement() == ceToRemove)
return mace;
}
}
return AbstractMenuAdditionCacheEntry::Pointer(nullptr);
}
//void WorkbenchMenuService::HandleMenuChanges(const SmartPointer<IRegistryChangeEvent>& event)
//{
// final IExtensionDelta[] menuDeltas = event.getExtensionDeltas(
// PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_MENUS);
// final List menuAdditions = new ArrayList();
// final List menuRemovals = new ArrayList();
// for (int i = 0; i < menuDeltas.length; i++) {
// IConfigurationElement[] ices = menuDeltas[i].getExtension().getConfigurationElements();
// for (int j = 0; j < ices.length; j++) {
// if (IWorkbenchRegistryConstants.PL_MENU_CONTRIBUTION.equals(ices[j].getName())) {
// if (menuDeltas[i].getKind() == IExtensionDelta.ADDED)
// menuAdditions.add(ices[j]);
// else
// menuRemovals.add(ices[j]);
// }
// }
// }
// // Handle additions
// if (menuAdditions.size() > 0) {
// handleDynamicAdditions(menuAdditions);
// }
// // Handle Removals
// if (menuRemovals.size() > 0) {
// handleDynamicRemovals(menuRemovals);
// }
//}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp
index 76a1a1f3ef..aa35cdf59a 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp
@@ -1,4100 +1,4100 @@
/*============================================================================
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 "berryLog.h"
#include "tweaklets/berryGuiWidgetsTweaklet.h"
#include "tweaklets/berryWorkbenchPageTweaklet.h"
#include "berryWorkbenchPage.h"
#include "berryPartSite.h"
#include "berryWorkbenchRegistryConstants.h"
#include "berryPerspective.h"
#include "berryLayoutPartSash.h"
#include "berryWorkbenchPlugin.h"
#include "berryEditorAreaHelper.h"
#include "berrySaveablesList.h"
#include "berryPerspectiveHelper.h"
#include "berryLayoutTreeNode.h"
#include "berryWorkbench.h"
#include "berryWorkbenchConstants.h"
#include "berryPartService.h"
#include "berryStickyViewManager.h"
#include "berryUIExtensionTracker.h"
#include "intro/berryIntroConstants.h"
#include "intro/berryViewIntroAdapterPart.h"
#include "berryWorkbenchWindow.h"
#include "berryUIException.h"
#include "berryPlatformUI.h"
#include "berryPartPane.h"
#include <berryPlatform.h>
#include <QMessageBox>
namespace berry
{
WorkbenchPage::ActivationOrderPred::ActivationOrderPred(
WorkbenchPage::ActivationList* al) :
activationList(al)
{
}
bool WorkbenchPage::ActivationOrderPred::operator()(
const IViewReference::Pointer o1, const IViewReference::Pointer o2) const
{
auto pos1 = activationList->IndexOf(
o1.Cast<IWorkbenchPartReference> ());
auto pos2 = activationList->IndexOf(
o2.Cast<IWorkbenchPartReference> ());
return pos1 < pos2;
}
void WorkbenchPage::PerspectiveList::UpdateActionSets(
Perspective::Pointer /*oldPersp*/, Perspective::Pointer /*newPersp*/)
{
//TODO WorkbenchPage action sets
// // Update action sets
//
// IContextService service = (IContextService) window
// .getService(IContextService.class);
// try {
// service.activateContext(ContextAuthority.DEFER_EVENTS);
// if (newPersp != 0) {
// IActionSetDescriptor[] newAlwaysOn = newPersp
// .getAlwaysOnActionSets();
// for (int i = 0; i < newAlwaysOn.length; i++) {
// IActionSetDescriptor descriptor = newAlwaysOn[i];
//
// actionSets.showAction(descriptor);
// }
//
// IActionSetDescriptor[] newAlwaysOff = newPersp
// .getAlwaysOffActionSets();
// for (int i = 0; i < newAlwaysOff.length; i++) {
// IActionSetDescriptor descriptor = newAlwaysOff[i];
//
// actionSets.maskAction(descriptor);
// }
// }
//
// if (oldPersp != 0) {
// IActionSetDescriptor[] newAlwaysOn = oldPersp
// .getAlwaysOnActionSets();
// for (int i = 0; i < newAlwaysOn.length; i++) {
// IActionSetDescriptor descriptor = newAlwaysOn[i];
//
// actionSets.hideAction(descriptor);
// }
//
// IActionSetDescriptor[] newAlwaysOff = oldPersp
// .getAlwaysOffActionSets();
// for (int i = 0; i < newAlwaysOff.length; i++) {
// IActionSetDescriptor descriptor = newAlwaysOff[i];
//
// actionSets.unmaskAction(descriptor);
// }
// }
// } finally {
// service.activateContext(ContextAuthority.SEND_EVENTS);
// }
}
WorkbenchPage::PerspectiveList::PerspectiveList()
{
}
void WorkbenchPage::PerspectiveList::Reorder(
IPerspectiveDescriptor::Pointer perspective, int newLoc)
{
PerspectiveListType::iterator oldLocation = openedList.end();
Perspective::Pointer movedPerspective;
for (PerspectiveListType::iterator iterator = openedList.begin(); iterator
!= openedList.end(); ++iterator)
{
Perspective::Pointer openPerspective = *iterator;
if (openPerspective->GetDesc() == perspective)
{
oldLocation = std::find(openedList.begin(), openedList.end(),
openPerspective);
movedPerspective = openPerspective;
}
}
PerspectiveListType::iterator newLocation = openedList.begin();
for (int i = 0; i < newLoc; ++i, ++newLocation)
;
if (oldLocation == newLocation)
{
return;
}
openedList.erase(oldLocation);
openedList.insert(newLocation, movedPerspective);
}
WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetSortedPerspectives()
{
return usedList;
}
bool WorkbenchPage::PerspectiveList::Add(Perspective::Pointer perspective)
{
openedList.push_back(perspective);
usedList.push_front(perspective);
//It will be moved to top only when activated.
return true;
}
WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::Begin()
{
return openedList.begin();
}
WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::End()
{
return openedList.end();
}
WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetOpenedPerspectives()
{
return openedList;
}
bool WorkbenchPage::PerspectiveList::Remove(Perspective::Pointer perspective)
{
if (active == perspective)
{
this->UpdateActionSets(active, Perspective::Pointer(nullptr));
active = nullptr;
}
usedList.removeAll(perspective);
PerspectiveListType::size_type origSize = openedList.size();
openedList.removeAll(perspective);
return openedList.size() != origSize;
}
void WorkbenchPage::PerspectiveList::Swap(Perspective::Pointer oldPerspective,
Perspective::Pointer newPerspective)
{
PerspectiveListType::iterator oldIter = std::find(openedList.begin(),
openedList.end(), oldPerspective);
PerspectiveListType::iterator newIter = std::find(openedList.begin(),
openedList.end(), newPerspective);
if (oldIter == openedList.end() || newIter == openedList.end())
{
return;
}
std::iter_swap(oldIter, newIter);
}
bool WorkbenchPage::PerspectiveList::IsEmpty()
{
return openedList.empty();
}
Perspective::Pointer WorkbenchPage::PerspectiveList::GetActive()
{
return active;
}
Perspective::Pointer WorkbenchPage::PerspectiveList::GetNextActive()
{
if (active == 0)
{
if (usedList.empty())
{
return Perspective::Pointer(nullptr);
}
else
{
return usedList.back();
}
}
else
{
if (usedList.size() < 2)
{
return Perspective::Pointer(nullptr);
}
else
{
return *(usedList.end() - 2);
}
}
}
WorkbenchPage::PerspectiveList::PerspectiveListType::size_type WorkbenchPage::PerspectiveList::Size()
{
return openedList.size();
}
void WorkbenchPage::PerspectiveList::SetActive(Perspective::Pointer perspective)
{
if (perspective == active)
{
return;
}
this->UpdateActionSets(active, perspective);
active = perspective;
if (perspective != 0)
{
usedList.removeAll(perspective);
usedList.push_back(perspective);
}
}
WorkbenchPage::ActivationList::ActivationList(WorkbenchPage* page) :
page(page)
{
}
void WorkbenchPage::ActivationList::SetActive(SmartPointer<IWorkbenchPart> part)
{
if (parts.empty())
{
return;
}
IWorkbenchPartReference::Pointer ref(page->GetReference(part));
if (ref)
{
if (ref == parts.back())
{
return;
}
parts.erase(std::find(parts.begin(), parts.end(), ref));
parts.push_back(ref);
}
}
void WorkbenchPage::ActivationList::BringToTop(SmartPointer<
IWorkbenchPartReference> ref)
{
ILayoutContainer::Pointer targetContainer(page->GetContainer(ref));
auto newIndex = this->LastIndexOfContainer(targetContainer);
if (newIndex != parts.end() && ref == *newIndex)
{
return;
}
if (newIndex == parts.end())
{
parts.push_back(ref);
}
else
{
PartListType::size_type index = newIndex - parts.begin();
parts.erase(std::find(parts.begin(), parts.end(), ref));
auto insertIndex = parts.begin() + index;
parts.insert(insertIndex, ref);
}
}
WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::LastIndexOfContainer(
SmartPointer<ILayoutContainer> container)
{
auto i = parts.rbegin();
while (i != parts.rend())
{
IWorkbenchPartReference::Pointer ref(*i);
ILayoutContainer::Pointer cnt(page->GetContainer(ref));
if (cnt == container)
{
return --i.base();
}
++i;
}
return parts.end();
}
void WorkbenchPage::ActivationList::SetActive(SmartPointer<
IWorkbenchPartReference> ref)
{
this->SetActive(ref->GetPart(true));
}
void WorkbenchPage::ActivationList::Add(
SmartPointer<IWorkbenchPartReference> ref)
{
if (std::find(parts.begin(), parts.end(), ref) != parts.end())
{
return;
}
ref->GetPart(false);
parts.push_front(ref);
}
SmartPointer<IWorkbenchPart> WorkbenchPage::ActivationList::GetActive()
{
if (parts.empty())
{
return IWorkbenchPart::Pointer(nullptr);
}
return this->GetActive(parts.end());
}
SmartPointer<IWorkbenchPart> WorkbenchPage::ActivationList::GetPreviouslyActive()
{
if (parts.size() < 2)
{
return IWorkbenchPart::Pointer(nullptr);
}
return this->GetActive(--parts.end());
}
SmartPointer<IWorkbenchPartReference> WorkbenchPage::ActivationList::GetActiveReference(
bool editorsOnly)
{
return this->GetActiveReference(parts.end(), editorsOnly);
}
WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf(
SmartPointer<IWorkbenchPart> part)
{
IWorkbenchPartReference::Pointer ref(page->GetReference(part));
if (ref == 0)
{
return parts.end();
}
return std::find(parts.begin(), parts.end(), ref);
}
WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf(
SmartPointer<IWorkbenchPartReference> ref)
{
return std::find(parts.begin(), parts.end(), ref);
}
bool WorkbenchPage::ActivationList::Remove(
SmartPointer<IWorkbenchPartReference> ref)
{
bool contains = std::find(parts.begin(), parts.end(), ref) != parts.end();
parts.erase(std::find(parts.begin(), parts.end(), ref));
return contains;
}
SmartPointer<IEditorPart> WorkbenchPage::ActivationList::GetTopEditor()
{
IEditorReference::Pointer editor =
this->GetActiveReference(parts.end(), true).Cast<IEditorReference> ();
if (editor == 0)
{
return IEditorPart::Pointer(nullptr);
}
return editor->GetEditor(true);
}
SmartPointer<IWorkbenchPart> WorkbenchPage::ActivationList::GetActive(
PartListIter start)
{
IWorkbenchPartReference::Pointer ref(this->GetActiveReference(start, false));
if (!ref)
{
return IWorkbenchPart::Pointer(nullptr);
}
return ref->GetPart(true);
}
SmartPointer<IWorkbenchPartReference> WorkbenchPage::ActivationList::GetActiveReference(
PartListIter start, bool editorsOnly)
{
// First look for parts that aren't obscured by the current zoom state
IWorkbenchPartReference::Pointer nonObscured = this->GetActiveReference(
start, editorsOnly, true);
if (nonObscured)
{
return nonObscured;
}
// Now try all the rest of the parts
return this->GetActiveReference(start, editorsOnly, false);
}
SmartPointer<IWorkbenchPartReference> WorkbenchPage::ActivationList::GetActiveReference(
PartListIter start, bool editorsOnly, bool /*skipPartsObscuredByZoom*/)
{
QList<IViewReference::Pointer> views = page->GetViewReferences();
PartListReverseIter i(start);
while (i != parts.rend())
{
WorkbenchPartReference::Pointer ref(i->Cast<WorkbenchPartReference> ());
if (editorsOnly && (ref.Cast<IEditorReference> () == 0))
{
++i;
continue;
}
// Skip parts whose containers have disabled auto-focus
PartPane::Pointer pane(ref->GetPane());
if (pane)
{
if (!pane->AllowsAutoFocus())
{
++i;
continue;
}
// if (skipPartsObscuredByZoom) {
// if (pane.isObscuredByZoom()) {
// continue;
// }
// }
}
// Skip fastviews (unless overridden)
if (IViewReference::Pointer viewRef = ref.Cast<IViewReference>())
{
//if (ref == getActiveFastView() || !((IViewReference) ref).isFastView()) {
for (int j = 0; j < views.size(); j++)
{
if (views[j] == viewRef)
{
return viewRef.Cast<IWorkbenchPartReference> ();
}
}
//}
}
else
{
return ref.Cast<IWorkbenchPartReference> ();
}
++i;
}
return IWorkbenchPartReference::Pointer(nullptr);
}
QList<SmartPointer<IEditorReference> > WorkbenchPage::ActivationList::GetEditors()
{
QList<IEditorReference::Pointer> editors;
for (auto i = parts.begin(); i != parts.end(); ++i)
{
if (IEditorReference::Pointer part = i->Cast<IEditorReference>())
{
editors.push_back(part);
}
}
return editors;
}
QList<SmartPointer<IWorkbenchPartReference> > WorkbenchPage::ActivationList::GetParts()
{
QList<IViewReference::Pointer> views(page->GetViewReferences());
QList<IWorkbenchPartReference::Pointer> resultList;
for (auto iterator = parts.begin(); iterator != parts.end(); ++iterator)
{
if (IViewReference::Pointer ref = iterator->Cast<IViewReference>())
{
//Filter views from other perspectives
for (int i = 0; i < views.size(); i++)
{
if (ref == views[i])
{
resultList.push_back(ref);
break;
}
}
}
else
{
resultList.push_back(*iterator);
}
}
return resultList;
}
WorkbenchPage::ActionSwitcher::ActionSwitcher(WorkbenchPage* page)
: page(page)
{
}
void WorkbenchPage::ActionSwitcher::UpdateActivePart(
IWorkbenchPart::Pointer newPart)
{
IWorkbenchPart::Pointer _activePart = this->activePart.Lock();
IEditorPart::Pointer _topEditor = this->topEditor.Lock();
if (_activePart == newPart)
{
return;
}
bool isNewPartAnEditor = newPart.Cast<IEditorPart> ().IsNotNull();
if (isNewPartAnEditor)
{
QString oldId;
if (_topEditor)
{
oldId = _topEditor->GetSite()->GetId();
}
QString newId = newPart->GetSite()->GetId();
// if the active part is an editor and the new editor
// is the same kind of editor, then we don't have to do
// anything
if (activePart == topEditor && newId == oldId)
{
activePart = newPart;
topEditor = newPart.Cast<IEditorPart> ();
return;
}
// remove the contributions of the old editor
// if it is a different kind of editor
if (oldId != newId)
{
this->DeactivateContributions(_topEditor, true);
}
// if a view was the active part, disable its contributions
if (_activePart && _activePart != _topEditor)
{
this->DeactivateContributions(_activePart, true);
}
// show (and enable) the contributions of the new editor
// if it is a different kind of editor or if the
// old active part was a view
if (newId != oldId || _activePart != _topEditor)
{
this->ActivateContributions(newPart, true);
}
}
else if (newPart.IsNull())
{
if (_activePart)
{
// remove all contributions
this->DeactivateContributions(_activePart, true);
}
}
else
{
// new part is a view
// if old active part is a view, remove all contributions,
// but if old part is an editor only disable
if (_activePart)
{
this->DeactivateContributions(_activePart,
_activePart.Cast<IViewPart> ().IsNotNull());
}
this->ActivateContributions(newPart, true);
}
//TODO WorkbenchPage action sets
// ArrayList newActionSets = 0;
// if (isNewPartAnEditor || (activePart == topEditor && newPart == 0))
// {
// newActionSets = calculateActionSets(newPart, 0);
// }
// else
// {
// newActionSets = calculateActionSets(newPart, topEditor);
// }
//
// if (!updateActionSets(newActionSets))
// {
page->UpdateActionBars();
// }
if (isNewPartAnEditor)
{
topEditor = newPart.Cast<IEditorPart> ();
}
else if (activePart == topEditor && newPart.IsNull())
{
// since we removed all the contributions, we clear the top
// editor
topEditor.Reset();
}
activePart = newPart;
}
void WorkbenchPage::ActionSwitcher::UpdateTopEditor(
IEditorPart::Pointer newEditor)
{
if (topEditor.Lock() == newEditor)
{
return;
}
if (activePart == topEditor)
{
this->UpdateActivePart(newEditor);
return;
}
QString oldId;
if (!topEditor.Expired())
{
oldId = topEditor.Lock()->GetSite()->GetId();
}
QString newId;
if (newEditor.IsNotNull())
{
newId = newEditor->GetSite()->GetId();
}
if (oldId == newId)
{
// we don't have to change anything
topEditor = newEditor;
return;
}
// Remove the contributions of the old editor
if (!topEditor.Expired())
{
this->DeactivateContributions(topEditor.Lock(), true);
}
// Show (disabled) the contributions of the new editor
if (newEditor.IsNotNull())
{
this->ActivateContributions(newEditor, false);
}
// ArrayList newActionSets = calculateActionSets(activePart, newEditor);
// if (!updateActionSets(newActionSets))
// {
page->UpdateActionBars();
// }
topEditor = newEditor;
}
void WorkbenchPage::ActionSwitcher::ActivateContributions(
IWorkbenchPart::Pointer /*part*/, bool /*enable*/)
{
//PartSite::Pointer site = part->GetSite().Cast<PartSite> ();
//site->ActivateActionBars(enable);
}
void WorkbenchPage::ActionSwitcher::DeactivateContributions(
IWorkbenchPart::Pointer /*part*/, bool /*remove*/)
{
//PartSite::Pointer site = part->GetSite().Cast<PartSite> ();
//site->DeactivateActionBars(remove);
}
IExtensionPoint::Pointer WorkbenchPage::GetPerspectiveExtensionPoint()
{
return Platform::GetExtensionRegistry()->GetExtensionPoint(
PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS);
}
WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, const QString& layoutID,
IAdaptable* input)
: actionSwitcher(this)
{
if (layoutID == "")
{
throw WorkbenchException("Perspective ID is undefined");
}
this->Register();
this->Init(w, layoutID, input, true);
this->UnRegister(false);
}
WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, IAdaptable* input)
: actionSwitcher(this)
{
this->Register();
this->Init(w, "", input, false);
this->UnRegister(false);
}
void WorkbenchPage::Activate(IWorkbenchPart::Pointer part)
{
// Sanity check.
if (!this->CertifyPart(part))
{
return;
}
if (window->IsClosing())
{
return;
}
// if (composite!=0 && composite.isVisible() && !((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part))
// {
// return;
// }
// Activate part.
//if (window.getActivePage() == this) {
IWorkbenchPartReference::Pointer ref = this->GetReference(part);
this->InternalBringToTop(ref);
this->SetActivePart(part);
}
void WorkbenchPage::ActivatePart(const IWorkbenchPart::Pointer part)
{
// Platform.run(new SafeRunnable(WorkbenchMessages.WorkbenchPage_ErrorActivatingView)
// {
// public void WorkbenchPage::run()
// {
if (part.IsNotNull())
{
//part.setFocus();
PartPane::Pointer pane = this->GetPane(part);
pane->SetFocus();
PartSite::Pointer site = part->GetSite().Cast<PartSite> ();
pane->ShowFocus(true);
//this->UpdateTabList(part);
//SubActionBars bars = (SubActionBars) site.getActionBars();
//bars.partChanged(part);
}
// }
// }
// );
}
void WorkbenchPage::AddPartListener(IPartListener* l)
{
partList->GetPartService()->AddPartListener(l);
}
void WorkbenchPage::AddSelectionListener(ISelectionListener* listener)
{
selectionService->AddSelectionListener(listener);
}
void WorkbenchPage::AddSelectionListener(const QString& partId,
ISelectionListener* listener)
{
selectionService->AddSelectionListener(partId, listener);
}
void WorkbenchPage::AddPostSelectionListener(
ISelectionListener* listener)
{
selectionService->AddPostSelectionListener(listener);
}
void WorkbenchPage::AddPostSelectionListener(const QString& partId,
ISelectionListener* listener)
{
selectionService->AddPostSelectionListener(partId, listener);
}
ILayoutContainer::Pointer WorkbenchPage::GetContainer(
IWorkbenchPart::Pointer part)
{
PartPane::Pointer pane = this->GetPane(part);
if (pane == 0)
{
return ILayoutContainer::Pointer(nullptr);
}
return pane->GetContainer();
}
ILayoutContainer::Pointer WorkbenchPage::GetContainer(
IWorkbenchPartReference::Pointer part)
{
PartPane::Pointer pane = this->GetPane(part);
if (pane == 0)
{
return ILayoutContainer::Pointer(nullptr);
}
return pane->GetContainer();
}
PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPart::Pointer part)
{
if (part.IsNull())
{
return PartPane::Pointer(nullptr);
}
return this->GetPane(this->GetReference(part));
}
PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPartReference::Pointer part)
{
if (part.IsNull())
{
return PartPane::Pointer(nullptr);
}
return part.Cast<WorkbenchPartReference> ()->GetPane();
}
bool WorkbenchPage::InternalBringToTop(IWorkbenchPartReference::Pointer part)
{
bool broughtToTop = false;
// Move part.
if (part.Cast<IEditorReference> ().IsNotNull())
{
ILayoutContainer::Pointer container = this->GetContainer(part);
if (container.Cast<PartStack> () != 0)
{
PartStack::Pointer stack = container.Cast<PartStack> ();
PartPane::Pointer newPart = this->GetPane(part);
if (stack->GetSelection() != newPart)
{
stack->SetSelection(newPart);
}
broughtToTop = true;
}
}
else if (part.Cast<IViewReference> ().IsNotNull())
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
broughtToTop = persp->BringToTop(part.Cast<IViewReference> ());
}
}
// Ensure that this part is considered the most recently activated part
// in this stack
activationList->BringToTop(part);
return broughtToTop;
}
void WorkbenchPage::BringToTop(IWorkbenchPart::Pointer part)
{
// Sanity check.
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0 || !this->CertifyPart(part))
{
return;
}
// if (!((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part))
// {
// return;
// }
// QString label; // debugging only
// if (UIStats.isDebugging(UIStats.BRING_PART_TO_TOP))
// {
// label = part != 0 ? part.getTitle() : "none"; //$NON-NLS-1$
// }
IWorkbenchPartReference::Pointer ref = this->GetReference(part);
ILayoutContainer::Pointer activeEditorContainer = this->GetContainer(
this->GetActiveEditor().Cast<IWorkbenchPart> ());
ILayoutContainer::Pointer activePartContainer = this->GetContainer(
this->GetActivePart());
ILayoutContainer::Pointer newPartContainer = this->GetContainer(part);
if (newPartContainer == activePartContainer)
{
this->MakeActive(ref);
}
else if (newPartContainer == activeEditorContainer)
{
if (ref.Cast<IEditorReference> () != 0)
{
if (part != 0)
{
IWorkbenchPartSite::Pointer site = part->GetSite();
if (site.Cast<PartSite> () != 0)
{
ref = site.Cast<PartSite> ()->GetPane()->GetPartReference();
}
}
this->MakeActiveEditor(ref.Cast<IEditorReference> ());
}
else
{
this->MakeActiveEditor(IEditorReference::Pointer(nullptr));
}
}
else
{
this->InternalBringToTop(ref);
if (ref != 0)
{
partList->FirePartBroughtToTop(ref);
}
}
}
void WorkbenchPage::BusyResetPerspective()
{
ViewIntroAdapterPart::Pointer
introViewAdapter =
dynamic_cast<WorkbenchIntroManager*> (GetWorkbenchWindow() ->GetWorkbench()->GetIntroManager())->GetIntroAdapterPart().Cast<
ViewIntroAdapterPart> ();
// PartPane introPane = 0;
// boolean introFullScreen = false;
// if (introViewAdapter != 0)
// {
// introPane = ((PartSite) introViewAdapter.getSite()).getPane();
// introViewAdapter.setHandleZoomEvents(false);
// introFullScreen = introPane.isZoomed();
// }
// //try to prevent intro flicker.
// if (introFullScreen)
// {
// window.getShell().setRedraw(false);
// }
// try
// {
// // Always unzoom
// if (isZoomed())
// {
// zoomOut();
// }
// Get the current perspective.
// This describes the working layout of the page and differs from
// the original template.
Perspective::Pointer oldPersp = this->GetActivePerspective();
// Map the current perspective to the original template.
// If the original template cannot be found then it has been deleted.
// In that case just return. (PR#1GDSABU).
IPerspectiveRegistry* reg =
WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry();
PerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId(
oldPersp->GetDesc()->GetId()).Cast<PerspectiveDescriptor> ();
if (desc == 0)
{
desc
= reg->FindPerspectiveWithId(oldPersp ->GetDesc().Cast<
PerspectiveDescriptor> ()->GetOriginalId()).Cast<
PerspectiveDescriptor> ();
}
if (desc == 0)
{
return;
}
// Notify listeners that we are doing a reset.
window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc,
CHANGE_RESET);
// Create new persp from original template.
// Suppress the perspectiveOpened and perspectiveClosed events otherwise it looks like two
// instances of the same perspective are open temporarily (see bug 127470).
Perspective::Pointer newPersp = this->CreatePerspective(desc, false);
if (newPersp == 0)
{
// We're not going through with the reset, so it is complete.
window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc,
CHANGE_RESET_COMPLETE);
return;
}
// Update the perspective list and shortcut
perspList.Swap(oldPersp, newPersp);
// Install new persp.
this->SetPerspective(newPersp);
// Destroy old persp.
this->DisposePerspective(oldPersp, false);
// Update the Coolbar layout.
this->ResetToolBarLayout();
// restore the maximized intro
if (introViewAdapter)
{
try
{
// ensure that the intro is visible in the new perspective
ShowView(IntroConstants::INTRO_VIEW_ID);
// if (introFullScreen)
// {
// toggleZoom(introPane.getPartReference());
// }
} catch (PartInitException& e)
{
//TODO IStatus
WorkbenchPlugin::Log("Could not restore intro", e);
// WorkbenchPlugin.getStatus(e));
}
// finally
// {
// // we want the intro back to a normal state before we fire the event
// introViewAdapter.setHandleZoomEvents(true);
// }
}
// Notify listeners that we have completed our reset.
window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc,
CHANGE_RESET_COMPLETE);
// }
// finally
// {
// // reset the handling of zoom events (possibly for the second time) in case there was
// // an exception thrown
// if (introViewAdapter != 0)
// {
// introViewAdapter.setHandleZoomEvents(true);
// }
//
// if (introFullScreen)
// {
// window.getShell().setRedraw(true);
// }
// }
}
void WorkbenchPage::RemovePerspective(IPerspectiveDescriptor::Pointer desc)
{
Perspective::Pointer newPersp;
PerspectiveDescriptor::Pointer realDesc = desc.Cast<PerspectiveDescriptor> ();
newPersp = this->FindPerspective(desc);
perspList.Remove(newPersp);
}
void WorkbenchPage::BusySetPerspective(IPerspectiveDescriptor::Pointer desc)
{
// Create new layout.
QString label = desc->GetId(); // debugging only
Perspective::Pointer newPersp;
//try
//{
//UIStats.start(UIStats.SWITCH_PERSPECTIVE, label);
PerspectiveDescriptor::Pointer realDesc = desc.Cast<PerspectiveDescriptor> ();
newPersp = this->FindPerspective(realDesc);
if (newPersp == 0)
{
newPersp = this->CreatePerspective(realDesc, true);
if (newPersp == 0)
{
return;
}
}
// Change layout.
this->SetPerspective(newPersp);
// }
// catch (std::exception& e)
// {
// UIStats.end(UIStats.SWITCH_PERSPECTIVE, desc.getId(), label);
// throw e;
// }
}
IViewPart::Pointer WorkbenchPage::BusyShowView(const QString& viewID,
const QString& secondaryID, int mode)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return IViewPart::Pointer(nullptr);
}
// If this view is already visible just return.
IViewReference::Pointer ref = persp->FindView(viewID, secondaryID);
IViewPart::Pointer view;
if (ref != 0)
{
view = ref->GetView(true);
}
if (view != 0)
{
this->BusyShowView(view, mode);
return view;
}
// Show the view.
view = persp->ShowView(viewID, secondaryID);
if (view != 0)
{
this->BusyShowView(view, mode);
IWorkbenchPartReference::Pointer partReference = this->GetReference(view);
PartPane::Pointer partPane = this->GetPane(partReference);
partPane->SetInLayout(true);
IWorkbenchPage::Pointer thisPage(this);
window->FirePerspectiveChanged(thisPage, GetPerspective(), partReference,
CHANGE_VIEW_SHOW);
window->FirePerspectiveChanged(thisPage, GetPerspective(), CHANGE_VIEW_SHOW);
}
return view;
}
void WorkbenchPage::UpdateActionBars()
{
window->UpdateActionBars();
}
void WorkbenchPage::BusyShowView(IViewPart::Pointer part, int mode)
{
// if (!((GrabFocus) Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part))
// {
// return;
// }
if (mode == VIEW_ACTIVATE)
{
this->Activate(part);
}
else if (mode == VIEW_VISIBLE)
{
IWorkbenchPartReference::Pointer ref = this->GetActivePartReference();
// if there is no active part or it's not a view, bring to top
if (ref == 0 || ref.Cast<IViewReference> () == 0)
{
this->BringToTop(part);
}
else
{
// otherwise check to see if the we're in the same stack as the active view
IViewReference::Pointer activeView = ref.Cast<IViewReference> ();
QList<IViewReference::Pointer> viewStack =
this->GetViewReferenceStack(part);
for (int i = 0; i < viewStack.size(); i++)
{
if (viewStack[i] == activeView)
{
return;
}
}
this->BringToTop(part);
}
}
}
bool WorkbenchPage::CertifyPart(IWorkbenchPart::Pointer part)
{
//Workaround for bug 22325
if (part != 0 && part->GetSite().Cast<PartSite> () == 0)
{
return false;
}
if (part.Cast<IEditorPart> () != 0)
{
IEditorReference::Pointer ref = this->GetReference(part).Cast<
IEditorReference> ();
return ref != 0 && this->GetEditorManager()->ContainsEditor(ref);
}
if (part.Cast<IViewPart> () != 0)
{
Perspective::Pointer persp = this->GetActivePerspective();
return persp != 0 && persp->ContainsView(part.Cast<IViewPart> ());
}
return false;
}
bool WorkbenchPage::Close()
{
bool ret;
//BusyIndicator.showWhile(0, new Runnable()
// {
// public void WorkbenchPage::run()
// {
ret = window->ClosePage(IWorkbenchPage::Pointer(this), true);
// }
// });
return ret;
}
bool WorkbenchPage::CloseAllSavedEditors()
{
// get the Saved editors
QList<IEditorReference::Pointer> editors = this->GetEditorReferences();
QList<IEditorReference::Pointer> savedEditors;
for (QList<IEditorReference::Pointer>::iterator iter = editors.begin(); iter
!= editors.end(); ++iter)
{
IEditorReference::Pointer editor = *iter;
if (!editor->IsDirty())
{
savedEditors.push_back(editor);
}
}
//there are no unsaved editors
if (savedEditors.empty())
{
return true;
}
return this->CloseEditors(savedEditors, false);
}
bool WorkbenchPage::CloseAllEditors(bool save)
{
return this->CloseEditors(this->GetEditorReferences(), save);
}
void WorkbenchPage::UpdateActivePart()
{
if (this->IsDeferred())
{
return;
}
IWorkbenchPartReference::Pointer oldActivePart =
partList->GetActivePartReference();
IWorkbenchPartReference::Pointer oldActiveEditor =
partList->GetActiveEditorReference();
IWorkbenchPartReference::Pointer newActivePart;
IEditorReference::Pointer newActiveEditor;
if (!window->IsClosing())
{
// If an editor is active, try to keep an editor active
if (oldActiveEditor && oldActivePart == oldActiveEditor)
{
newActiveEditor = activationList->GetActiveReference(true).Cast<
IEditorReference> ();
newActivePart = newActiveEditor;
if (newActivePart == 0)
{
// Only activate a non-editor if there's no editors left
newActivePart = activationList->GetActiveReference(false);
}
}
else
{
// If a non-editor is active, activate whatever was activated most recently
newActivePart = activationList->GetActiveReference(false);
if (newActivePart.Cast<IEditorReference> () != 0)
{
// If that happens to be an editor, make it the active editor as well
newActiveEditor = newActivePart.Cast<IEditorReference> ();
}
else
{
// Otherwise, select whatever editor was most recently active
newActiveEditor = activationList->GetActiveReference(true).Cast<
IEditorReference> ();
}
}
}
if (oldActiveEditor != newActiveEditor)
{
this->MakeActiveEditor(newActiveEditor);
}
if (newActivePart != oldActivePart)
{
this->MakeActive(newActivePart);
}
}
void WorkbenchPage::MakeActive(IWorkbenchPartReference::Pointer ref)
{
if (ref == 0)
{
this->SetActivePart(IWorkbenchPart::Pointer(nullptr));
}
else
{
IWorkbenchPart::Pointer newActive = ref->GetPart(true);
if (newActive == 0)
{
this->SetActivePart(IWorkbenchPart::Pointer(nullptr));
}
else
{
this->Activate(newActive);
}
}
}
void WorkbenchPage::MakeActiveEditor(IEditorReference::Pointer ref)
{
if (ref == this->GetActiveEditorReference())
{
return;
}
IEditorPart::Pointer part = (ref == 0) ? IEditorPart::Pointer(nullptr)
: ref->GetEditor(true);
if (part)
{
editorMgr->SetVisibleEditor(ref, false);
//navigationHistory.MarkEditor(part);
}
actionSwitcher.UpdateTopEditor(part);
if (ref)
{
activationList->BringToTop(this->GetReference(part));
}
partList->SetActiveEditor(ref);
}
bool WorkbenchPage::CloseEditors(
const QList<IEditorReference::Pointer>& refArray, bool save)
{
if (refArray.empty())
{
return true;
}
IWorkbenchPage::Pointer thisPage(this);
// Check if we're being asked to close any parts that are already closed or cannot
// be closed at this time
QList<IEditorReference::Pointer> editorRefs;
for (QList<IEditorReference::Pointer>::const_iterator iter =
refArray.begin(); iter != refArray.end(); ++iter)
{
IEditorReference::Pointer reference = *iter;
// If we're in the middle of creating this part, this is a programming error. Abort the entire
// close operation. This usually occurs if someone tries to open a dialog in a method that
// isn't allowed to do so, and a *syncExec tries to close the part. If this shows up in a log
// file with a dialog's event loop on the stack, then the code that opened the dialog is usually
// at fault.
if (partBeingActivated == reference)
{
ctkRuntimeException re(
"WARNING: Blocked recursive attempt to close part "
+ partBeingActivated->GetId()
+ " while still in the middle of activating it");
WorkbenchPlugin::Log(re);
return false;
}
// if (reference.Cast<WorkbenchPartReference> () != 0)
// {
// WorkbenchPartReference::Pointer ref = reference.Cast<WorkbenchPartReference>();
//
// // If we're being asked to close a part that is disposed (ie: already closed),
// // skip it and proceed with closing the remaining parts.
// if (ref.isDisposed())
// {
// continue;
// }
// }
editorRefs.push_back(reference);
}
// notify the model manager before the close
QList<IWorkbenchPart::Pointer> partsToClose;
for (int i = 0; i < editorRefs.size(); i++)
{
IWorkbenchPart::Pointer refPart = editorRefs[i]->GetPart(false);
if (refPart != 0)
{
partsToClose.push_back(refPart);
}
}
SaveablesList::Pointer modelManager;
SaveablesList::PostCloseInfo::Pointer postCloseInfo;
if (partsToClose.size() > 0)
{
modelManager = dynamic_cast<SaveablesList*>(
this->GetWorkbenchWindow()->GetService<ISaveablesLifecycleListener>());
// this may prompt for saving and return 0 if the user canceled:
postCloseInfo = modelManager->PreCloseParts(partsToClose, save,
this->GetWorkbenchWindow());
if (postCloseInfo == 0)
{
return false;
}
}
// Fire pre-removal changes
for (int i = 0; i < editorRefs.size(); i++)
{
IEditorReference::Pointer ref = editorRefs[i];
// Notify interested listeners before the close
window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref,
CHANGE_EDITOR_CLOSE);
}
this->DeferUpdates(true);
try
{
if (modelManager != 0)
{
modelManager->PostClose(postCloseInfo);
}
// Close all editors.
for (int i = 0; i < editorRefs.size(); i++)
{
IEditorReference::Pointer ref = editorRefs[i];
// Remove editor from the presentation
editorPresentation->CloseEditor(ref);
this->PartRemoved(ref.Cast<WorkbenchPartReference> ());
}
} catch (...)
{
}
this->DeferUpdates(false);
// Notify interested listeners after the close
window->FirePerspectiveChanged(thisPage, this->GetPerspective(),
CHANGE_EDITOR_CLOSE);
// Return true on success.
return true;
}
void WorkbenchPage::DeferUpdates(bool shouldDefer)
{
if (shouldDefer)
{
if (deferCount == 0)
{
this->StartDeferring();
}
deferCount++;
}
else
{
deferCount--;
if (deferCount == 0)
{
this->HandleDeferredEvents();
}
}
}
void WorkbenchPage::StartDeferring()
{
//editorPresentation.getLayoutPart().deferUpdates(true);
}
void WorkbenchPage::HandleDeferredEvents()
{
editorPresentation->GetLayoutPart()->DeferUpdates(false);
this->UpdateActivePart();
QList<WorkbenchPartReference::Pointer> disposals = pendingDisposals;
pendingDisposals.clear();
for (int i = 0; i < disposals.size(); i++)
{
this->DisposePart(disposals[i]);
}
}
bool WorkbenchPage::IsDeferred()
{
return deferCount > 0;
}
bool WorkbenchPage::CloseEditor(IEditorReference::Pointer editorRef, bool save)
{
QList<IEditorReference::Pointer> list;
list.push_back(editorRef);
return this->CloseEditors(list, save);
}
bool WorkbenchPage::CloseEditor(IEditorPart::Pointer editor, bool save)
{
IWorkbenchPartReference::Pointer ref = this->GetReference(editor);
if (ref.Cast<IEditorReference> ().IsNotNull())
{
QList<IEditorReference::Pointer> list;
list.push_back(ref.Cast<IEditorReference> ());
return this->CloseEditors(list, save);
}
return false;
}
void WorkbenchPage::CloseCurrentPerspective(bool saveParts, bool closePage)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
this->ClosePerspective(persp, saveParts, closePage);
}
}
void WorkbenchPage::ClosePerspective(IPerspectiveDescriptor::Pointer desc,
bool saveParts, bool closePage)
{
Perspective::Pointer persp = this->FindPerspective(desc);
if (persp != 0)
{
this->ClosePerspective(persp, saveParts, closePage);
}
}
void WorkbenchPage::ClosePerspective(Perspective::Pointer persp,
bool saveParts, bool closePage)
{
// // Always unzoom
// if (isZoomed())
// {
// zoomOut();
// }
QList<IWorkbenchPart::Pointer> partsToSave;
QList<IWorkbenchPart::Pointer> viewsToClose;
// collect views that will go away and views that are dirty
QList<IViewReference::Pointer> viewReferences =
persp->GetViewReferences();
for (int i = 0; i < viewReferences.size(); i++)
{
IViewReference::Pointer reference = viewReferences[i];
if (this->GetViewFactory()->GetReferenceCount(reference) == 1)
{
IViewPart::Pointer viewPart = reference->GetView(false);
if (viewPart != 0)
{
viewsToClose.push_back(viewPart);
if (saveParts && reference->IsDirty())
{
partsToSave.push_back(viewPart);
}
}
}
}
if (saveParts && perspList.Size() == 1)
{
// collect editors that are dirty
QList<IEditorReference::Pointer> editorReferences =
this->GetEditorReferences();
for (QList<IEditorReference::Pointer>::iterator refIter =
editorReferences.begin(); refIter != editorReferences.end(); ++refIter)
{
IEditorReference::Pointer reference = *refIter;
if (reference->IsDirty())
{
IEditorPart::Pointer editorPart = reference->GetEditor(false);
if (editorPart != 0)
{
partsToSave.push_back(editorPart);
}
}
}
}
if (saveParts && !partsToSave.empty())
{
if (!EditorManager::SaveAll(partsToSave, true, true, false,
IWorkbenchWindow::Pointer(window)))
{
// user canceled
return;
}
}
// Close all editors on last perspective close
if (perspList.Size() == 1 && this->GetEditorManager()->GetEditorCount() > 0)
{
// Close all editors
if (!this->CloseAllEditors(false))
{
return;
}
}
// closeAllEditors already notified the saveables list about the editors.
SaveablesList::Pointer saveablesList(
dynamic_cast<SaveablesList*>(
this->GetWorkbenchWindow()->GetWorkbench()->GetService<ISaveablesLifecycleListener>()));
// we took care of the saving already, so pass in false (postCloseInfo will be non-0)
SaveablesList::PostCloseInfo::Pointer postCloseInfo =
saveablesList->PreCloseParts(viewsToClose, false,
this->GetWorkbenchWindow());
saveablesList->PostClose(postCloseInfo);
// Dispose of the perspective
bool isActive = (perspList.GetActive() == persp);
if (isActive)
{
this->SetPerspective(perspList.GetNextActive());
}
this->DisposePerspective(persp, true);
if (closePage && perspList.Size() == 0)
{
this->Close();
}
}
void WorkbenchPage::CloseAllPerspectives(bool saveEditors, bool closePage)
{
if (perspList.IsEmpty())
{
return;
}
// // Always unzoom
// if (isZoomed())
// {
// zoomOut();
// }
if (saveEditors)
{
if (!this->SaveAllEditors(true))
{
return;
}
}
// Close all editors
if (!this->CloseAllEditors(false))
{
return;
}
// Deactivate the active perspective and part
this->SetPerspective(Perspective::Pointer(nullptr));
// Close each perspective in turn
PerspectiveList oldList = perspList;
perspList = PerspectiveList();
for (PerspectiveList::iterator itr = oldList.Begin(); itr != oldList.End(); ++itr)
{
this->ClosePerspective(*itr, false, false);
}
if (closePage)
{
this->Close();
}
}
void WorkbenchPage::CreateClientComposite()
{
QWidget* parent = window->GetPageComposite();
// StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
//
// public void WorkbenchPage::runWithException()
// {
composite
= Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateClientComposite(
parent);
Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); // Make visible on activate.
// force the client composite to be layed out
// parent.layout();
// }
// });
}
Perspective::Pointer WorkbenchPage::CreatePerspective(
PerspectiveDescriptor::Pointer desc, bool notify)
{
QString label = desc->GetId(); // debugging only
try
{
//UIStats.start(UIStats.CREATE_PERSPECTIVE, label);
WorkbenchPage::Pointer thisPage(this);
Perspective::Pointer persp(new Perspective(desc, thisPage));
perspList.Add(persp);
if (notify)
{
window->FirePerspectiveOpened(thisPage, desc);
}
//if the perspective is fresh and uncustomzied then it is not dirty
//no reset will be prompted for
if (!desc->HasCustomDefinition())
{
dirtyPerspectives.erase(desc->GetId());
}
return persp;
} catch (WorkbenchException& /*e*/)
{
if (!window->GetWorkbenchImpl()->IsStarting())
{
QMessageBox::critical(reinterpret_cast<QWidget*>(window->GetShell()->GetControl()),
"Error",
"Problems opening perspective \"" + desc->GetId() + "\"");
}
return Perspective::Pointer(nullptr);
}
// finally
// {
// UIStats.end(UIStats.CREATE_PERSPECTIVE, desc.getId(), label);
// }
}
void WorkbenchPage::PartAdded(WorkbenchPartReference::Pointer ref)
{
activationList->Add(ref);
partList->AddPart(ref);
this->UpdateActivePart();
}
void WorkbenchPage::PartRemoved(WorkbenchPartReference::Pointer ref)
{
activationList->Remove(ref);
this->DisposePart(ref);
}
void WorkbenchPage::DisposePart(WorkbenchPartReference::Pointer ref)
{
if (this->IsDeferred())
{
pendingDisposals.push_back(ref);
}
else
{
partList->RemovePart(ref);
ref->Dispose();
}
}
void WorkbenchPage::DeactivatePart(IWorkbenchPart::Pointer part)
{
if (part.IsNotNull())
{
PartSite::Pointer site = part->GetSite().Cast<PartSite> ();
site->GetPane()->ShowFocus(false);
}
}
void WorkbenchPage::DetachView(IViewReference::Pointer ref)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return;
}
PerspectiveHelper* presentation = persp->GetPresentation();
presentation->DetachPart(ref);
}
void WorkbenchPage::AttachView(IViewReference::Pointer ref)
{
PerspectiveHelper* presentation = this->GetPerspectivePresentation();
presentation->AttachPart(ref);
}
WorkbenchPage::~WorkbenchPage()
{
// increment reference count to prevent recursive deletes
this->Register();
{
{
this->MakeActiveEditor(IEditorReference::Pointer(nullptr));
this->MakeActive(IWorkbenchPartReference::Pointer(nullptr));
// Close and dispose the editors.
this->CloseAllEditors(false);
// Need to make sure model data is cleaned up when the page is
// disposed. Collect all the views on the page and notify the
// saveable list of a pre/post close. This will free model data.
QList<IWorkbenchPartReference::Pointer> partsToClose =
this->GetOpenParts();
QList<IWorkbenchPart::Pointer> dirtyParts;
for (int i = 0; i < partsToClose.size(); i++)
{
IWorkbenchPart::Pointer part = partsToClose[i]->GetPart(false);
if (part != 0 && part.Cast<IViewPart> () != 0)
{
dirtyParts.push_back(part);
}
}
SaveablesList::Pointer saveablesList(dynamic_cast<SaveablesList*>(
this->GetWorkbenchWindow()->GetWorkbench()->GetService<ISaveablesLifecycleListener>()));
SaveablesList::PostCloseInfo::Pointer postCloseInfo =
saveablesList->PreCloseParts(dirtyParts, false,
this->GetWorkbenchWindow());
saveablesList->PostClose(postCloseInfo);
IWorkbenchPage::Pointer thisPage(this);
// Get rid of perspectives. This will close the views
for (PerspectiveList::iterator itr = perspList.Begin(); itr
!= perspList.End(); ++itr)
{
Perspective::Pointer perspective = *itr;
window->FirePerspectiveClosed(thisPage, perspective->GetDesc());
//perspective->Dispose();
}
perspList = PerspectiveList();
// Get rid of editor presentation.
//editorPresentation->Dispose();
// Get rid of composite.
//composite.dispose();
//navigationHistory.dispose();
//stickyViewMan.clear();
// if (tracker != 0)
// {
// tracker.close();
// }
// // if we're destroying a window in a non-shutdown situation then we should
// // clean up the working set we made.
// if (!window->GetWorkbench()->IsClosing())
// {
// if (aggregateWorkingSet != 0)
// {
// PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(
// aggregateWorkingSet);
// }
// }
}
partBeingActivated = nullptr;
pendingDisposals.clear();
stickyViewMan = nullptr;
delete viewFactory;
delete editorPresentation;
delete editorMgr;
delete activationList;
deferredActivePersp = nullptr;
dirtyPerspectives.clear();
delete selectionService;
partList.reset();
}
// decrement reference count again, without explicit deletion
this->UnRegister(false);
}
void WorkbenchPage::DisposePerspective(Perspective::Pointer persp, bool notify)
{
// Get rid of perspective.
perspList.Remove(persp);
if (notify)
{
IWorkbenchPage::Pointer thisPage(this);
window->FirePerspectiveClosed(thisPage, persp->GetDesc());
}
//persp->Dispose();
stickyViewMan->Remove(persp->GetDesc()->GetId());
}
Perspective::Pointer WorkbenchPage::FindPerspective(
IPerspectiveDescriptor::Pointer desc)
{
for (PerspectiveList::iterator itr = perspList.Begin(); itr
!= perspList.End(); ++itr)
{
Perspective::Pointer mgr = *itr;
if (desc->GetId() == mgr->GetDesc()->GetId())
{
return mgr;
}
}
return Perspective::Pointer(nullptr);
}
IViewPart::Pointer WorkbenchPage::FindView(const QString& id)
{
IViewReference::Pointer ref = this->FindViewReference(id);
if (ref == 0)
{
return IViewPart::Pointer(nullptr);
}
return ref->GetView(true);
}
IViewReference::Pointer WorkbenchPage::FindViewReference(
const QString& viewId)
{
return this->FindViewReference(viewId, "");
}
IViewReference::Pointer WorkbenchPage::FindViewReference(
const QString& viewId, const QString& secondaryId)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return IViewReference::Pointer(nullptr);
}
return persp->FindView(viewId, secondaryId);
}
IEditorPart::Pointer WorkbenchPage::GetActiveEditor()
{
return partList->GetActiveEditor();
}
IEditorReference::Pointer WorkbenchPage::GetActiveEditorReference()
{
return partList->GetActiveEditorReference();
}
IWorkbenchPart::Pointer WorkbenchPage::GetActivePart()
{
return partList->GetActivePart();
}
IWorkbenchPartReference::Pointer WorkbenchPage::GetActivePartReference()
{
return partList->GetActivePartReference();
}
Perspective::Pointer WorkbenchPage::GetActivePerspective()
{
return perspList.GetActive();
}
QWidget* WorkbenchPage::GetClientComposite()
{
return composite;
}
EditorManager* WorkbenchPage::GetEditorManager()
{
return editorMgr;
}
PerspectiveHelper* WorkbenchPage::GetPerspectivePresentation()
{
if (this->GetActivePerspective() != 0)
{
return this->GetActivePerspective()->GetPresentation();
}
return nullptr;
}
bool WorkbenchPage::HasView(const QString& perspectiveId, const QString& viewId)
{
PerspectiveList::PerspectiveListType list = perspList.GetSortedPerspectives();
for ( PerspectiveList::PerspectiveListType::iterator it = list.begin(); it!=list.end(); it++)
{
SmartPointer<Perspective> p = *it;
if (p->GetDesc()->GetId() == perspectiveId)
{
if (p->ContainsView(viewId))
{
return true;
}
}
}
return false;
}
/**
* Answer the editor presentation.
*/
EditorAreaHelper* WorkbenchPage::GetEditorPresentation()
{
return editorPresentation;
}
QList<IEditorPart::Pointer> WorkbenchPage::GetEditors()
{
QList<IEditorReference::Pointer> refs = this->GetEditorReferences();
QList<IEditorPart::Pointer> result;
//Display d = getWorkbenchWindow().getShell().getDisplay();
//Must be backward compatible.
// d.syncExec(new Runnable()
// {
// public void WorkbenchPage::run()
// {
for (QList<IEditorReference::Pointer>::iterator iter = refs.begin(); iter
!= refs.end(); ++iter)
{
IEditorPart::Pointer part = (*iter)->GetEditor(true);
if (part != 0)
{
result.push_back(part);
}
}
// }
// });
return result;
}
QList<IEditorPart::Pointer> WorkbenchPage::GetDirtyEditors()
{
return this->GetEditorManager()->GetDirtyEditors();
}
QList<ISaveablePart::Pointer> WorkbenchPage::GetDirtyParts()
{
QList<ISaveablePart::Pointer> result;
QList<IWorkbenchPartReference::Pointer> allParts = this->GetAllParts();
for (int i = 0; i < allParts.size(); i++)
{
IWorkbenchPartReference::Pointer reference = allParts[i];
IWorkbenchPart::Pointer part = reference->GetPart(false);
if (part != 0 && part.Cast<ISaveablePart> () != 0)
{
ISaveablePart::Pointer saveable = part.Cast<ISaveablePart> ();
if (saveable->IsDirty())
{
result.push_back(saveable);
}
}
}
return result;
}
IEditorPart::Pointer WorkbenchPage::FindEditor(IEditorInput::Pointer input)
{
return this->GetEditorManager()->FindEditor(input);
}
QList<IEditorReference::Pointer> WorkbenchPage::FindEditors(
IEditorInput::Pointer input, const QString& editorId, int matchFlags)
{
return this->GetEditorManager()->FindEditors(input, editorId, matchFlags);
}
QList<IEditorReference::Pointer> WorkbenchPage::GetEditorReferences()
{
return editorPresentation->GetEditors();
}
IAdaptable* WorkbenchPage::GetInput()
{
return input;
}
QString WorkbenchPage::GetLabel()
{
QString label = "<Unknown label>";
// IWorkbenchAdapter adapter = (IWorkbenchAdapter) Util.getAdapter(input,
// IWorkbenchAdapter.class);
// if (adapter != 0)
// {
// label = adapter.getLabel(input);
// }
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
label = label + " - " + persp->GetDesc()->GetLabel();
}
else if (deferredActivePersp != 0)
{
label = label + " - " + deferredActivePersp->GetLabel();
}
return label;
}
IPerspectiveDescriptor::Pointer WorkbenchPage::GetPerspective()
{
if (deferredActivePersp != 0)
{
return deferredActivePersp;
}
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
return persp->GetDesc();
}
else
{
return IPerspectiveDescriptor::Pointer(nullptr);
}
}
ISelection::ConstPointer WorkbenchPage::GetSelection() const
{
return selectionService->GetSelection();
}
ISelection::ConstPointer WorkbenchPage::GetSelection(const QString& partId)
{
return selectionService->GetSelection(partId);
}
//ISelectionService::SelectionEvents& WorkbenchPage::GetSelectionEvents(const QString& partId)
//{
// return selectionService->GetSelectionEvents(partId);
//}
ViewFactory* WorkbenchPage::GetViewFactory()
{
if (viewFactory == nullptr)
{
viewFactory = new ViewFactory(this,
WorkbenchPlugin::GetDefault()->GetViewRegistry());
}
return viewFactory;
}
QList<IViewReference::Pointer> WorkbenchPage::GetViewReferences()
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
return persp->GetViewReferences();
}
else
{
return QList<IViewReference::Pointer>();
}
}
QList<IViewPart::Pointer> WorkbenchPage::GetViews()
{
return this->GetViews(Perspective::Pointer(nullptr), true);
}
QList<IViewPart::Pointer> WorkbenchPage::GetViews(
Perspective::Pointer persp, bool restore)
{
if (persp == 0)
{
persp = this->GetActivePerspective();
}
QList<IViewPart::Pointer> parts;
if (persp != 0)
{
QList<IViewReference::Pointer> refs = persp->GetViewReferences();
for (int i = 0; i < refs.size(); i++)
{
IViewPart::Pointer part = refs[i]->GetPart(restore).Cast<IViewPart> ();
if (part != 0)
{
parts.push_back(part);
}
}
}
return parts;
}
IWorkbenchWindow::Pointer WorkbenchPage::GetWorkbenchWindow() const
{
return IWorkbenchWindow::Pointer(window);
}
void WorkbenchPage::HideView(IViewReference::Pointer ref)
{
// Sanity check.
if (ref == 0)
{
return;
}
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return;
}
bool promptedForSave = false;
IViewPart::Pointer view = ref->GetView(false);
if (view != 0)
{
if (!this->CertifyPart(view))
{
return;
}
// Confirm.
if (view.Cast<ISaveablePart> () != 0)
{
ISaveablePart::Pointer saveable = view.Cast<ISaveablePart> ();
if (saveable->IsSaveOnCloseNeeded())
{
IWorkbenchWindow::Pointer window =
view->GetSite()->GetWorkbenchWindow();
QList<IWorkbenchPart::Pointer> partsToSave;
partsToSave.push_back(view);
bool success = EditorManager::SaveAll(partsToSave, true, true, false,
window);
if (!success)
{
// the user cancelled.
return;
}
promptedForSave = true;
}
}
}
int refCount = this->GetViewFactory()->GetReferenceCount(ref);
SaveablesList* saveablesList = nullptr;
SaveablesList::PostCloseInfo::Pointer postCloseInfo;
if (refCount == 1)
{
IWorkbenchPart::Pointer actualPart = ref->GetPart(false);
if (actualPart != 0)
{
saveablesList = dynamic_cast<SaveablesList*>(
actualPart->GetSite()->GetService<ISaveablesLifecycleListener>());
QList<IWorkbenchPart::Pointer> partsToClose;
partsToClose.push_back(actualPart);
postCloseInfo = saveablesList->PreCloseParts(partsToClose,
!promptedForSave, this->GetWorkbenchWindow());
if (postCloseInfo == 0)
{
// cancel
return;
}
}
}
IWorkbenchPage::Pointer thisPage(this);
// Notify interested listeners before the hide
window->FirePerspectiveChanged(thisPage, persp->GetDesc(), ref,
CHANGE_VIEW_HIDE);
PartPane::Pointer pane = this->GetPane(ref.Cast<IWorkbenchPartReference> ());
pane->SetInLayout(false);
this->UpdateActivePart();
if (saveablesList != nullptr)
{
saveablesList->PostClose(postCloseInfo);
}
// Hide the part.
persp->HideView(ref);
// Notify interested listeners after the hide
window->FirePerspectiveChanged(thisPage, this->GetPerspective(),
CHANGE_VIEW_HIDE);
}
void WorkbenchPage::RefreshActiveView()
{
this->UpdateActivePart();
}
void WorkbenchPage::HideView(IViewPart::Pointer view)
{
this->HideView(this->GetReference(view).Cast<IViewReference> ());
}
void WorkbenchPage::Init(WorkbenchWindow* w, const QString& layoutID,
IAdaptable* input, bool openExtras)
{
// Save args.
this->window = w;
this->input = input;
this->composite = nullptr;
this->viewFactory = nullptr;
this->activationList = new ActivationList(this);
this->selectionService = new PageSelectionService(this);
this->partList.reset(new WorkbenchPagePartList(this->selectionService));
this->stickyViewMan = new StickyViewManager(this);
//actionSets = new ActionSetManager(w);
deferCount = 0;
// Create presentation.
this->CreateClientComposite();
editorPresentation = new EditorAreaHelper(this);
editorMgr = new EditorManager(WorkbenchWindow::Pointer(window),
WorkbenchPage::Pointer(this), editorPresentation);
//TODO WorkbenchPage perspective reorder listener?
// // add this page as a client to be notified when the UI has re-ordered perspectives
// // so that the order can be properly maintained in the receiver.
// // E.g. a UI might support drag-and-drop and will need to make this known to ensure
// // #saveState and #restoreState do not lose this re-ordering
// w.addPerspectiveReorderListener(new IReorderListener()
// {
// public void WorkbenchPage::reorder(Object perspective, int newLoc)
// {
// perspList.reorder((IPerspectiveDescriptor)perspective, newLoc);
// }
// });
if (openExtras)
{
this->OpenPerspectiveExtras();
}
// Get perspective descriptor.
if (layoutID != "")
{
PerspectiveDescriptor::Pointer
desc =
WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId(
layoutID).Cast<PerspectiveDescriptor> ();
if (desc == 0)
{
throw WorkbenchException("Unable to create Perspective " + layoutID
+ ". There is no corresponding perspective extension.");
}
Perspective::Pointer persp = this->FindPerspective(desc);
if (persp == 0)
{
persp = this->CreatePerspective(desc, true);
}
perspList.SetActive(persp);
window->FirePerspectiveActivated(IWorkbenchPage::Pointer(this), desc);
}
//this->GetExtensionTracker()->RegisterHandler(perspectiveChangeHandler,
// ExtensionTracker::CreateExtensionPointFilter(
// GetPerspectiveExtensionPoint()));
}
void WorkbenchPage::OpenPerspectiveExtras()
{
//TODO WorkbenchPage perspectice extras
QString extras = ""; //PrefUtil.getAPIPreferenceStore().getString(
// IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS);
QList<IPerspectiveDescriptor::Pointer> descs;
- foreach (QString id, extras.split(", ", QString::SkipEmptyParts))
+ foreach (QString id, extras.split(", ", Qt::SkipEmptyParts))
{
if (id.trimmed().isEmpty()) continue;
IPerspectiveDescriptor::Pointer desc =
WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId(id);
if (desc != 0)
{
descs.push_back(desc);
}
}
// HACK: The perspective switcher currently adds the button for a new perspective to the beginning of the list.
// So, we process the extra perspectives in reverse order here to have their buttons appear in the order declared.
for (int i = (int) descs.size(); --i >= 0;)
{
PerspectiveDescriptor::Pointer desc =
descs[i].Cast<PerspectiveDescriptor> ();
if (this->FindPerspective(desc) == 0)
{
this->CreatePerspective(desc, true);
}
}
}
bool WorkbenchPage::IsPartVisible(IWorkbenchPart::Pointer part)
{
PartPane::Pointer pane = this->GetPane(part);
return pane != 0 && pane->GetVisible();
}
bool WorkbenchPage::IsEditorAreaVisible()
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return false;
}
return persp->IsEditorAreaVisible();
}
bool WorkbenchPage::IsFastView(IViewReference::Pointer /*ref*/)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
//return persp->IsFastView(ref);
return false;
}
else
{
return false;
}
}
bool WorkbenchPage::IsCloseable(IViewReference::Pointer ref)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
return persp->IsCloseable(ref);
}
return false;
}
bool WorkbenchPage::IsMoveable(IViewReference::Pointer ref)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
return persp->IsMoveable(ref);
}
return false;
}
bool WorkbenchPage::IsFixedLayout()
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
return persp->IsFixedLayout();
}
else
{
return false;
}
}
bool WorkbenchPage::IsSaveNeeded()
{
return this->GetEditorManager()->IsSaveAllNeeded();
}
void WorkbenchPage::OnActivate()
{
Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, true);
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
persp->OnActivate();
this->UpdateVisibility(Perspective::Pointer(nullptr), persp);
}
}
void WorkbenchPage::OnDeactivate()
{
this->MakeActiveEditor(IEditorReference::Pointer(nullptr));
this->MakeActive(IWorkbenchPartReference::Pointer(nullptr));
if (this->GetActivePerspective() != 0)
{
this->GetActivePerspective()->OnDeactivate();
}
Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false);
}
void WorkbenchPage::ReuseEditor(IReusableEditor::Pointer editor,
IEditorInput::Pointer input)
{
// Rather than calling editor.setInput on the editor directly, we do it through the part reference.
// This case lets us detect badly behaved editors that are not firing a PROP_INPUT event in response
// to the input change... but if all editors obeyed their API contract, the "else" branch would be
// sufficient.
IWorkbenchPartReference::Pointer ref = this->GetReference(editor);
if (ref.Cast<EditorReference> () != 0)
{
EditorReference::Pointer editorRef = ref.Cast<EditorReference> ();
editorRef->SetInput(input);
}
else
{
editor->SetInput(input);
}
//navigationHistory.markEditor(editor);
}
IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input,
const QString& editorID)
{
return this->OpenEditor(input, editorID, true, MATCH_INPUT);
}
IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input,
const QString& editorID, bool activate)
{
return this->OpenEditor(input, editorID, activate, MATCH_INPUT);
}
IEditorPart::Pointer WorkbenchPage::OpenEditor(
const IEditorInput::Pointer input, const QString& editorID,
bool activate, int matchFlags)
{
return this->OpenEditor(input, editorID, activate, matchFlags,
IMemento::Pointer(nullptr));
}
IEditorPart::Pointer WorkbenchPage::OpenEditor(
const IEditorInput::Pointer input, const QString& editorID,
bool activate, int matchFlags, IMemento::Pointer editorState)
{
if (input == 0 || editorID == "")
{
throw Poco::InvalidArgumentException();
}
// BusyIndicator.showWhile(window.getWorkbench().getDisplay(),
// new Runnable()
// {
// public void WorkbenchPage::run()
// {
return this->BusyOpenEditor(input, editorID, activate, matchFlags,
editorState);
}
IEditorPart::Pointer WorkbenchPage::OpenEditorFromDescriptor(
IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor,
bool activate, IMemento::Pointer editorState)
{
if (input == 0 || !(editorDescriptor.Cast<EditorDescriptor> () != 0))
{
throw Poco::InvalidArgumentException();
}
// BusyIndicator.showWhile(window.getWorkbench().getDisplay(),
// new Runnable()
// {
// public void WorkbenchPage::run()
// {
return this->BusyOpenEditorFromDescriptor(input, editorDescriptor.Cast<
EditorDescriptor> (), activate, editorState);
// }
// });
}
IEditorPart::Pointer WorkbenchPage::BusyOpenEditor(IEditorInput::Pointer input,
const QString& editorID, bool activate, int matchFlags,
IMemento::Pointer editorState)
{
Workbench* workbench =
this->GetWorkbenchWindow().Cast<WorkbenchWindow> ()->GetWorkbenchImpl();
workbench->LargeUpdateStart();
IEditorPart::Pointer result;
try
{
result = this->BusyOpenEditorBatched(input, editorID, activate, matchFlags,
editorState);
} catch (std::exception& e)
{
workbench->LargeUpdateEnd();
throw e;
}
workbench->LargeUpdateEnd();
return result;
}
IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptor(
IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor,
bool activate, IMemento::Pointer editorState)
{
Workbench* workbench =
this->GetWorkbenchWindow().Cast<WorkbenchWindow> ()->GetWorkbenchImpl();
workbench->LargeUpdateStart();
IEditorPart::Pointer result;
try
{
result = this->BusyOpenEditorFromDescriptorBatched(input, editorDescriptor,
activate, editorState);
} catch (std::exception& e)
{
workbench->LargeUpdateEnd();
throw e;
}
workbench->LargeUpdateEnd();
return result;
}
IEditorPart::Pointer WorkbenchPage::BusyOpenEditorBatched(
IEditorInput::Pointer input, const QString& editorID, bool activate,
int matchFlags, IMemento::Pointer editorState)
{
// If an editor already exists for the input, use it.
IEditorPart::Pointer editor;
// Reuse an existing open editor, unless we are in "new editor tab management" mode
editor = this->GetEditorManager()->FindEditor(editorID, input, matchFlags);
if (editor != 0)
{
if (IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID == editorID)
{
if (editor->IsDirty())
{
QMessageBox::StandardButton saveFile = QMessageBox::question(
this->GetWorkbenchWindow()->GetShell()->GetControl(),
"Save", "\"" + input->GetName() + "\" is opened and has unsaved changes. Do you want to save it?",
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Cancel);
if (saveFile == QMessageBox::Yes)
{
// try
// {
IEditorPart::Pointer editorToSave = editor;
// getWorkbenchWindow().run(false, false,
// new IRunnableWithProgress()
// {
// public void WorkbenchPage::run(IProgressMonitor monitor)
// throws InvocationTargetException,
// InterruptedException
// {
//TODO progress monitor
editorToSave->DoSave();//monitor);
// }
// });
// }
// catch (InvocationTargetException& e)
// {
// throw(RuntimeException) e->GetTargetException();
// }
// catch (InterruptedException& e)
// {
// return 0;
// }
}
else if (saveFile == QMessageBox::Cancel)
{
return IEditorPart::Pointer(nullptr);
}
}
}
else
{
// // do the IShowEditorInput notification before showing the editor
// // to reduce flicker
// if (editor.Cast<IShowEditorInput> () != 0)
// {
// ((IShowEditorInput) editor).showEditorInput(input);
// }
this->ShowEditor(activate, editor);
return editor;
}
}
// Otherwise, create a new one. This may cause the new editor to
// become the visible (i.e top) editor.
IEditorReference::Pointer ref = this->GetEditorManager()->OpenEditor(
editorID, input, true, editorState);
if (ref != 0)
{
editor = ref->GetEditor(true);
}
if (editor != 0)
{
this->SetEditorAreaVisible(true);
if (activate)
{
this->Activate(editor);
}
else
{
this->BringToTop(editor);
}
IWorkbenchPage::Pointer thisPage(this);
window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref,
CHANGE_EDITOR_OPEN);
window->FirePerspectiveChanged(thisPage, this->GetPerspective(),
CHANGE_EDITOR_OPEN);
}
return editor;
}
/*
* Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program.
* See openEditorFromDescriptor().
*/
IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptorBatched(
IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor,
bool activate, IMemento::Pointer editorState)
{
IEditorPart::Pointer editor;
// Create a new one. This may cause the new editor to
// become the visible (i.e top) editor.
IEditorReference::Pointer ref;
ref = this->GetEditorManager()->OpenEditorFromDescriptor(editorDescriptor,
input, editorState);
if (ref != 0)
{
editor = ref->GetEditor(true);
}
if (editor != 0)
{
this->SetEditorAreaVisible(true);
if (activate)
{
this->Activate(editor);
}
else
{
this->BringToTop(editor);
}
IWorkbenchPage::Pointer thisPage(this);
window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref,
CHANGE_EDITOR_OPEN);
window->FirePerspectiveChanged(thisPage, this->GetPerspective(),
CHANGE_EDITOR_OPEN);
}
return editor;
}
void WorkbenchPage::OpenEmptyTab()
{
IEditorPart::Pointer editor;
EditorReference::Pointer ref;
ref = this->GetEditorManager()->OpenEmptyTab().Cast<EditorReference> ();
if (ref != 0)
{
editor
= ref->GetEmptyEditor(
dynamic_cast<EditorRegistry*> (WorkbenchPlugin::GetDefault()->GetEditorRegistry())->FindEditor(
EditorRegistry::EMPTY_EDITOR_ID).Cast<EditorDescriptor> ());
}
if (editor != 0)
{
this->SetEditorAreaVisible(true);
this->Activate(editor);
IWorkbenchPage::Pointer thisPage(this);
window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref,
CHANGE_EDITOR_OPEN);
window->FirePerspectiveChanged(thisPage, this->GetPerspective(),
CHANGE_EDITOR_OPEN);
}
}
void WorkbenchPage::ShowEditor(bool activate, IEditorPart::Pointer editor)
{
this->SetEditorAreaVisible(true);
if (activate)
{
//zoomOutIfNecessary(editor);
this->Activate(editor);
}
else
{
this->BringToTop(editor);
}
}
bool WorkbenchPage::IsEditorPinned(IEditorPart::Pointer editor)
{
WorkbenchPartReference::Pointer ref = this->GetReference(editor).Cast<
WorkbenchPartReference> ();
return ref != 0 && ref->IsPinned();
}
/**
* Removes an IPartListener from the part service.
*/
void WorkbenchPage::RemovePartListener(IPartListener* l)
{
partList->GetPartService()->RemovePartListener(l);
}
/**
* Implements IWorkbenchPage
*
* @see org.blueberry.ui.IWorkbenchPage#removePropertyChangeListener(IPropertyChangeListener)
* @since 2.0
* @deprecated individual views should store a working set if needed and
* register a property change listener directly with the
* working set manager to receive notification when the view
* working set is removed.
*/
// void WorkbenchPage::RemovePropertyChangeListener(IPropertyChangeListener listener) {
// propertyChangeListeners.remove(listener);
// }
void WorkbenchPage::RemoveSelectionListener(ISelectionListener* listener)
{
selectionService->RemoveSelectionListener(listener);
}
void WorkbenchPage::RemoveSelectionListener(const QString& partId,
ISelectionListener* listener)
{
selectionService->RemoveSelectionListener(partId, listener);
}
void WorkbenchPage::RemovePostSelectionListener(ISelectionListener* listener)
{
selectionService->RemovePostSelectionListener(listener);
}
void WorkbenchPage::RemovePostSelectionListener(const QString& partId,
ISelectionListener* listener)
{
selectionService->RemovePostSelectionListener(partId, listener);
}
void WorkbenchPage::RequestActivation(IWorkbenchPart::Pointer part)
{
// Sanity check.
if (!this->CertifyPart(part))
{
return;
}
// Real work.
this->SetActivePart(part);
}
/**
* Resets the layout for the perspective. The active part in the old layout
* is activated in the new layout for consistent user context.
*/
void WorkbenchPage::ResetPerspective()
{
// Run op in busy cursor.
// Use set redraw to eliminate the "flash" that can occur in the
// coolbar as the perspective is reset.
// ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2();
// try
// {
// mgr.getControl2().setRedraw(false);
// BusyIndicator.showWhile(0, new Runnable()
// {
// public void WorkbenchPage::run()
// {
this->BusyResetPerspective();
// }
// });
// }finally
// {
// mgr.getControl2().setRedraw(true);
// }
}
bool WorkbenchPage::RestoreState(IMemento::Pointer memento,
const IPerspectiveDescriptor::Pointer activeDescriptor)
{
// StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
//
// public void WorkbenchPage::runWithException() throws Throwable
// {
this->DeferUpdates(true);
// }});
try
{
// Restore working set
QString pageName;
memento->GetString(WorkbenchConstants::TAG_LABEL, pageName);
// String label = 0; // debugging only
// if (UIStats.isDebugging(UIStats.RESTORE_WORKBENCH))
// {
// label = pageName == 0 ? "" : "::" + pageName; //$NON-NLS-1$ //$NON-NLS-2$
// }
try
{
//UIStats.start(UIStats.RESTORE_WORKBENCH, "WorkbenchPage" + label); //$NON-NLS-1$
// MultiStatus result =
// new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind(
// WorkbenchMessages.WorkbenchPage_unableToRestorePerspective,
// pageName), 0);
bool result = true;
// String workingSetName = memento .getString(
// IWorkbenchConstants.TAG_WORKING_SET);
// if (workingSetName != 0)
// {
// AbstractWorkingSetManager
// workingSetManager =
// (AbstractWorkingSetManager) getWorkbenchWindow() .getWorkbench().getWorkingSetManager();
// setWorkingSet(workingSetManager.getWorkingSet(workingSetName));
// }
//
// IMemento workingSetMem = memento .getChild(
// IWorkbenchConstants.TAG_WORKING_SETS);
// if (workingSetMem != 0)
// {
// QList<IMemento::Pointer> workingSetChildren =
// workingSetMem .getChildren(IWorkbenchConstants.TAG_WORKING_SET);
// List workingSetList = new ArrayList(workingSetChildren.length);
// for (int i = 0; i < workingSetChildren.length; i++)
// {
// IWorkingSet
// set =
// getWorkbenchWindow().getWorkbench() .getWorkingSetManager().getWorkingSet(
// workingSetChildren[i].getID());
// if (set != 0)
// {
// workingSetList.add(set);
// }
// }
//
// workingSets = (IWorkingSet[]) workingSetList .toArray(
// new IWorkingSet[workingSetList.size()]);
// }
//
// aggregateWorkingSetId = memento.getString(ATT_AGGREGATE_WORKING_SET_ID);
//
// IWorkingSet setWithId =
// window.getWorkbench().getWorkingSetManager().getWorkingSet(
// aggregateWorkingSetId);
//
// // check to see if the set has already been made and assign it if it has
// if (setWithId.Cast<AggregateWorkingSet> () != 0)
// {
// aggregateWorkingSet = (AggregateWorkingSet) setWithId;
// }
// Restore editor manager.
IMemento::Pointer childMem = memento->GetChild(
WorkbenchConstants::TAG_EDITORS);
//result.merge(getEditorManager().restoreState(childMem));
result &= this->GetEditorManager()->RestoreState(childMem);
childMem = memento->GetChild(WorkbenchConstants::TAG_VIEWS);
if (childMem)
{
//result.merge(getViewFactory().restoreState(childMem));
result &= this->GetViewFactory()->RestoreState(childMem);
}
// Get persp block.
childMem = memento->GetChild(WorkbenchConstants::TAG_PERSPECTIVES);
QString activePartID;
childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PART, activePartID);
QString activePartSecondaryID;
if (!activePartID.isEmpty())
{
activePartSecondaryID = ViewFactory::ExtractSecondaryId(activePartID);
if (!activePartSecondaryID.isEmpty())
{
activePartID = ViewFactory::ExtractPrimaryId(activePartID);
}
}
QString activePerspectiveID;
childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE,
activePerspectiveID);
// Restore perspectives.
QList<IMemento::Pointer> perspMems(childMem->GetChildren(
WorkbenchConstants::TAG_PERSPECTIVE));
Perspective::Pointer activePerspective;
for (int i = 0; i < perspMems.size(); i++)
{
IMemento::Pointer current = perspMems[i];
// StartupThreading
// .runWithoutExceptions(new StartupRunnable()
// {
//
// public void WorkbenchPage::runWithException() throws Throwable
// {
Perspective::Pointer persp(new Perspective(
PerspectiveDescriptor::Pointer(nullptr), WorkbenchPage::Pointer(this)));
//result.merge(persp.restoreState(current));
result &= persp->RestoreState(current);
IPerspectiveDescriptor::Pointer desc = persp->GetDesc();
if (desc == activeDescriptor)
{
activePerspective = persp;
}
else if ((activePerspective == 0) && desc->GetId()
== activePerspectiveID)
{
activePerspective = persp;
}
perspList.Add(persp);
window->FirePerspectiveOpened(WorkbenchPage::Pointer(this), desc);
// }
// });
}
bool restoreActivePerspective = false;
if (!activeDescriptor)
{
restoreActivePerspective = true;
}
else if (activePerspective && activePerspective->GetDesc()
== activeDescriptor)
{
restoreActivePerspective = true;
}
else
{
restoreActivePerspective = false;
activePerspective = this->CreatePerspective(activeDescriptor.Cast<
PerspectiveDescriptor> (), true);
if (activePerspective == 0)
{
// result .merge(
// new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, NLS.bind(
// WorkbenchMessages.Workbench_showPerspectiveError,
// activeDescriptor.getId()), 0));
result &= false;
}
}
perspList.SetActive(activePerspective);
// Make sure we have a valid perspective to work with,
// otherwise return.
activePerspective = perspList.GetActive();
if (activePerspective == 0)
{
activePerspective = perspList.GetNextActive();
perspList.SetActive(activePerspective);
}
if (activePerspective && restoreActivePerspective)
{
//result.merge(activePerspective.restoreState());
result &= activePerspective->RestoreState();
}
if (activePerspective)
{
Perspective::Pointer myPerspective = activePerspective;
QString myActivePartId = activePartID;
QString mySecondaryId = activePartSecondaryID;
// StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
//
// public void WorkbenchPage::runWithException() throws Throwable
// {
window->FirePerspectiveActivated(WorkbenchPage::Pointer(this),
myPerspective->GetDesc());
// Restore active part.
if (!myActivePartId.isEmpty())
{
IWorkbenchPartReference::Pointer ref = myPerspective->FindView(
myActivePartId, mySecondaryId);
if (ref)
{
activationList->SetActive(ref);
}
}
// }});
}
// childMem = memento->GetChild(WorkbenchConstants::TAG_NAVIGATION_HISTORY);
// if (childMem)
// {
// navigationHistory.restoreState(childMem);
// }
// else if (GetActiveEditor())
// {
// navigationHistory.markEditor(getActiveEditor());
// }
//
// restore sticky view state
stickyViewMan->Restore(memento);
// QString blame = activeDescriptor == 0 ? pageName
// : activeDescriptor.getId();
// UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$
// StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
// public void WorkbenchPage::runWithException() throws Throwable
// {
DeferUpdates(false);
// }
// });
return result;
} catch (...)
{
// QString blame = activeDescriptor == 0 ? pageName
// : activeDescriptor.getId();
// UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$
throw ;
}
}
catch (...)
{
// StartupThreading.runWithoutExceptions(new StartupRunnable()
// {
// public void WorkbenchPage::runWithException() throws Throwable
// {
DeferUpdates(false);
// }
// });
throw;
}
}
bool WorkbenchPage::SaveAllEditors(bool confirm)
{
return this->SaveAllEditors(confirm, false);
}
bool WorkbenchPage::SaveAllEditors(bool confirm, bool addNonPartSources)
{
return this->GetEditorManager()->SaveAll(confirm, false, addNonPartSources);
}
bool WorkbenchPage::SavePart(ISaveablePart::Pointer saveable,
IWorkbenchPart::Pointer part, bool confirm)
{
// Do not certify part do allow editors inside a multipageeditor to
// call this.
return this->GetEditorManager()->SavePart(saveable, part, confirm);
}
bool WorkbenchPage::SaveEditor(IEditorPart::Pointer editor, bool confirm)
{
return this->SavePart(editor, editor, confirm);
}
/**
* Saves the current perspective.
*/
void WorkbenchPage::SavePerspective()
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return;
}
// // Always unzoom.
// if (isZoomed())
// {
// zoomOut();
// }
persp->SaveDesc();
}
/**
* Saves the perspective.
*/
void WorkbenchPage::SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return;
}
IPerspectiveDescriptor::Pointer oldDesc = persp->GetDesc();
// // Always unzoom.
// if (isZoomed())
// {
// zoomOut();
// }
persp->SaveDescAs(newDesc);
window->FirePerspectiveSavedAs(IWorkbenchPage::Pointer(this), oldDesc, newDesc);
}
/**
* Save the state of the page.
*/
bool WorkbenchPage::SaveState(IMemento::Pointer memento)
{
// // We must unzoom to get correct layout.
// if (isZoomed())
// {
// zoomOut();
// }
// MultiStatus
// result =
// new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind(
// WorkbenchMessages.WorkbenchPage_unableToSavePerspective,
// getLabel()), 0);
bool result = true;
// Save editor manager.
IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_EDITORS);
//result.merge(editorMgr.saveState(childMem));
result &= editorMgr->SaveState(childMem);
childMem = memento->CreateChild(WorkbenchConstants::TAG_VIEWS);
//result.merge(getViewFactory().saveState(childMem));
result &= this->GetViewFactory()->SaveState(childMem);
// Create persp block.
childMem = memento->CreateChild(WorkbenchConstants::TAG_PERSPECTIVES);
if (this->GetPerspective())
{
childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE,
this->GetPerspective()->GetId());
}
if (this->GetActivePart() != 0)
{
if (this->GetActivePart().Cast<IViewPart> ())
{
IViewReference::Pointer ref = this->GetReference(this->GetActivePart()).Cast<IViewReference>();
if (ref)
{
childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART,
ViewFactory::GetKey(ref));
}
}
else
{
childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART,
this->GetActivePart()->GetSite()->GetId());
}
}
// Save each perspective in opened order
for (PerspectiveList::PerspectiveListType::iterator itr = perspList.Begin();
itr != perspList.End(); ++itr)
{
IMemento::Pointer gChildMem = childMem->CreateChild(
WorkbenchConstants::TAG_PERSPECTIVE);
//result.merge(persp.saveState(gChildMem));
result &= (*itr)->SaveState(gChildMem);
}
// // Save working set if set
// if (workingSet != 0)
// {
// memento.putString(IWorkbenchConstants.TAG_WORKING_SET,
// workingSet .getName());
// }
//
// IMemento workingSetMem = memento .createChild(
// IWorkbenchConstants.TAG_WORKING_SETS);
// for (int i = 0; i < workingSets.length; i++)
// {
// workingSetMem.createChild(IWorkbenchConstants.TAG_WORKING_SET,
// workingSets[i].getName());
// }
//
// if (aggregateWorkingSetId != 0)
// {
// memento.putString(ATT_AGGREGATE_WORKING_SET_ID, aggregateWorkingSetId);
// }
//
// navigationHistory.saveState(memento .createChild(
// IWorkbenchConstants.TAG_NAVIGATION_HISTORY));
//
// save the sticky activation state
stickyViewMan->Save(memento);
return result;
}
QString WorkbenchPage::GetId(IWorkbenchPart::Pointer part)
{
return this->GetId(this->GetReference(part));
}
QString WorkbenchPage::GetId(IWorkbenchPartReference::Pointer ref)
{
if (ref == 0)
{
return "0"; //$NON-NLS-1$
}
return ref->GetId();
}
void WorkbenchPage::SetActivePart(IWorkbenchPart::Pointer newPart)
{
// Optimize it.
if (this->GetActivePart() == newPart)
{
return;
}
if (partBeingActivated != 0)
{
if (partBeingActivated->GetPart(false) != newPart)
{
WorkbenchPlugin::Log(ctkRuntimeException(
QString("WARNING: Prevented recursive attempt to activate part ")
+ this->GetId(newPart)
+ " while still in the middle of activating part " + this->GetId(
partBeingActivated)));
}
return;
}
//No need to change the history if the active editor is becoming the
// active part
// String label = 0; // debugging only
// if (UIStats.isDebugging(UIStats.ACTIVATE_PART))
// {
// label = newPart != 0 ? newPart.getTitle() : "none"; //$NON-NLS-1$
// }
try
{
IWorkbenchPartReference::Pointer partref = this->GetReference(newPart);
IWorkbenchPartReference::Pointer realPartRef;
if (newPart != 0)
{
IWorkbenchPartSite::Pointer site = newPart->GetSite();
if (site.Cast<PartSite> () != 0)
{
realPartRef = site.Cast<PartSite> ()->GetPane()->GetPartReference();
}
}
partBeingActivated = realPartRef;
//UIStats.start(UIStats.ACTIVATE_PART, label);
// Notify perspective. It may deactivate fast view.
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
persp->PartActivated(newPart);
}
// Deactivate old part
IWorkbenchPart::Pointer oldPart = this->GetActivePart();
if (oldPart != 0)
{
this->DeactivatePart(oldPart);
}
// Set active part.
if (newPart != 0)
{
activationList->SetActive(newPart);
if (newPart.Cast<IEditorPart> () != 0)
{
this->MakeActiveEditor(realPartRef.Cast<IEditorReference> ());
}
}
this->ActivatePart(newPart);
actionSwitcher.UpdateActivePart(newPart);
partList->SetActivePart(partref);
}
catch (std::exception& e)
{
partBeingActivated = nullptr;
// Object blame = newPart == 0 ? (Object) this : newPart;
// UIStats.end(UIStats.ACTIVATE_PART, blame, label);
throw e;
}
partBeingActivated = nullptr;
}
void WorkbenchPage::SetEditorAreaVisible(bool showEditorArea)
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return;
}
if (showEditorArea == persp->IsEditorAreaVisible())
{
return;
}
// // If parts change always update zoom.
// if (isZoomed())
// {
// zoomOut();
// }
// Update editor area visibility.
IWorkbenchPage::Pointer thisPage(this);
if (showEditorArea)
{
persp->ShowEditorArea();
window->FirePerspectiveChanged(thisPage, this->GetPerspective(),
CHANGE_EDITOR_AREA_SHOW);
}
else
{
persp->HideEditorArea();
this->UpdateActivePart();
window->FirePerspectiveChanged(thisPage, this->GetPerspective(),
CHANGE_EDITOR_AREA_HIDE);
}
}
/**
* Sets the layout of the page. Assumes the new perspective is not 0.
* Keeps the active part if possible. Updates the window menubar and
* toolbar if necessary.
*/
void WorkbenchPage::SetPerspective(Perspective::Pointer newPersp)
{
// Don't do anything if already active layout
Perspective::Pointer oldPersp = this->GetActivePerspective();
if (oldPersp == newPersp)
{
return;
}
window->LargeUpdateStart();
std::exception exc;
bool exceptionOccured = false;
try
{
IWorkbenchPage::Pointer thisPage(this);
if (oldPersp != 0)
{
// fire the pre-deactivate
window->FirePerspectivePreDeactivate(thisPage, oldPersp->GetDesc());
}
if (newPersp != 0)
{
bool status = newPersp->RestoreState();
if (!status)
{
QString title = "Restoring problems";
QString msg = "Unable to read workbench state.";
QMessageBox::critical(reinterpret_cast<QWidget*>(this->GetWorkbenchWindow()->GetShell()->GetControl()),
title, msg);
}
}
// Deactivate the old layout
if (oldPersp != 0)
{
oldPersp->OnDeactivate();
// Notify listeners of deactivation
window->FirePerspectiveDeactivated(thisPage, oldPersp->GetDesc());
}
// Activate the new layout
perspList.SetActive(newPersp);
if (newPersp != 0)
{
newPersp->OnActivate();
// Notify listeners of activation
window->FirePerspectiveActivated(thisPage, newPersp->GetDesc());
}
this->UpdateVisibility(oldPersp, newPersp);
// Update the window
//TODO action sets
//window->UpdateActionSets();
// Update sticky views
stickyViewMan->Update(oldPersp, newPersp);
}
catch (std::exception& e)
{
exc = e;
exceptionOccured = true;
}
window->LargeUpdateEnd();
if (newPersp == 0)
{
return;
}
IPerspectiveDescriptor::Pointer desc = newPersp->GetDesc();
if (desc == 0)
{
return;
}
if (dirtyPerspectives.erase(desc->GetId()))
{
this->SuggestReset();
}
if (exceptionOccured)
throw exc;
}
void WorkbenchPage::UpdateVisibility(Perspective::Pointer oldPersp,
Perspective::Pointer newPersp)
{
// Flag all parts in the old perspective
QList<IViewReference::Pointer> oldRefs;
if (oldPersp != 0)
{
oldRefs = oldPersp->GetViewReferences();
for (int i = 0; i < oldRefs.size(); i++)
{
PartPane::Pointer pane =
oldRefs[i].Cast<WorkbenchPartReference> ()->GetPane();
pane->SetInLayout(false);
}
}
PerspectiveHelper* pres = nullptr;
// Make parts in the new perspective visible
if (newPersp != 0)
{
pres = newPersp->GetPresentation();
QList<IViewReference::Pointer> newRefs =
newPersp->GetViewReferences();
for (int i = 0; i < newRefs.size(); i++)
{
WorkbenchPartReference::Pointer ref = newRefs[i].Cast<
WorkbenchPartReference> ();
PartPane::Pointer pane = ref->GetPane();
if (pres->IsPartVisible(ref))
{
activationList->BringToTop(ref);
}
pane->SetInLayout(true);
}
}
this->UpdateActivePart();
// Hide any parts in the old perspective that are no longer visible
for (int i = 0; i < oldRefs.size(); i++)
{
WorkbenchPartReference::Pointer ref = oldRefs[i].Cast<
WorkbenchPartReference> ();
PartPane::Pointer pane = ref->GetPane();
if (pres == nullptr || !pres->IsPartVisible(ref))
{
pane->SetVisible(false);
}
}
}
/**
* Sets the perspective.
*
* @param desc
* identifies the new perspective.
*/
void WorkbenchPage::SetPerspective(IPerspectiveDescriptor::Pointer desc)
{
if (this->GetPerspective() == desc)
{
return;
}
// // Going from multiple to single rows can make the coolbar
// // and its adjacent views appear jumpy as perspectives are
// // switched. Turn off redraw to help with this.
// ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2();
std::exception exc;
bool exceptionOccured = false;
try
{
//mgr.getControl2().setRedraw(false);
//getClientComposite().setRedraw(false);
// Run op in busy cursor.
// BusyIndicator.showWhile(0, new Runnable()
// {
// public void WorkbenchPage::run()
// {
this->BusySetPerspective(desc);
// }
// });
}
catch (std::exception& e)
{
exc = e;
exceptionOccured = true;
}
// getClientComposite().setRedraw(true);
// mgr.getControl2().setRedraw(true);
IWorkbenchPart::Pointer part = this->GetActivePart();
if (part != 0)
{
part->SetFocus();
}
if (exceptionOccured)
throw exc;
}
PartService* WorkbenchPage::GetPartService()
{
return dynamic_cast<PartService*> (partList->GetPartService());
}
void WorkbenchPage::ResetToolBarLayout()
{
// ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2();
// mgr.resetItemOrder();
}
IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID)
{
return this->ShowView(viewID, "", VIEW_ACTIVATE);
}
IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID,
const QString& secondaryID, int mode)
{
if (secondaryID != "")
{
if (secondaryID.size() == 0 || secondaryID.indexOf(ViewFactory::ID_SEP) != -1)
{
throw ctkInvalidArgumentException(
"Illegal secondary id (cannot be empty or contain a colon)");
}
}
if (!this->CertifyMode(mode))
{
throw ctkInvalidArgumentException("Illegal view mode");
}
// Run op in busy cursor.
// BusyIndicator.showWhile(0, new Runnable()
// {
// public void WorkbenchPage::run()
// {
// try
// {
return this->BusyShowView(viewID, secondaryID, mode);
// } catch (PartInitException& e)
// {
// result = e;
// }
// }
// });
}
bool WorkbenchPage::CertifyMode(int mode)
{
if (mode == VIEW_ACTIVATE || mode == VIEW_VISIBLE || mode == VIEW_CREATE)
return true;
return false;
}
QList<IEditorReference::Pointer> WorkbenchPage::GetSortedEditors()
{
return activationList->GetEditors();
}
QList<IPerspectiveDescriptor::Pointer> WorkbenchPage::GetOpenPerspectives()
{
QList<Perspective::Pointer> opened = perspList.GetOpenedPerspectives();
QList<IPerspectiveDescriptor::Pointer> result;
for (QList<Perspective::Pointer>::iterator iter = opened.begin(); iter
!= opened.end(); ++iter)
{
result.push_back((*iter)->GetDesc());
}
return result;
}
QList<Perspective::Pointer> WorkbenchPage::GetOpenInternalPerspectives()
{
return perspList.GetOpenedPerspectives();
}
Perspective::Pointer WorkbenchPage::GetFirstPerspectiveWithView(
IViewPart::Pointer part)
{
QListIterator<Perspective::Pointer> iter(perspList.GetSortedPerspectives());
iter.toBack();
while(iter.hasPrevious())
{
Perspective::Pointer p = iter.previous();
if (p->ContainsView(part))
{
return p;
}
};
// we should never get here
return Perspective::Pointer(nullptr);
}
QList<IPerspectiveDescriptor::Pointer> WorkbenchPage::GetSortedPerspectives()
{
QList<Perspective::Pointer> sortedArray =
perspList.GetSortedPerspectives();
QList<IPerspectiveDescriptor::Pointer> result;
for (QList<Perspective::Pointer>::iterator iter = sortedArray.begin();
iter != sortedArray.end(); ++iter)
{
result.push_back((*iter)->GetDesc());
}
return result;
}
QList<IWorkbenchPartReference::Pointer> WorkbenchPage::GetSortedParts()
{
//return partList->GetParts(this->GetViewReferences());
return activationList->GetParts();
}
IWorkbenchPartReference::Pointer WorkbenchPage::GetReference(
IWorkbenchPart::Pointer part)
{
if (part == 0)
{
return IWorkbenchPartReference::Pointer(nullptr);
}
IWorkbenchPartSite::Pointer site = part->GetSite();
if (site.Cast<PartSite> () == 0)
{
return IWorkbenchPartReference::Pointer(nullptr);
}
PartSite::Pointer partSite = site.Cast<PartSite> ();
PartPane::Pointer pane = partSite->GetPane();
return partSite->GetPartReference();
}
// for dynamic UI
void WorkbenchPage::AddPerspective(Perspective::Pointer persp)
{
perspList.Add(persp);
IWorkbenchPage::Pointer thisPage(this);
window->FirePerspectiveOpened(thisPage, persp->GetDesc());
}
QList<IViewReference::Pointer> WorkbenchPage::GetViewReferenceStack(
IViewPart::Pointer part)
{
// Sanity check.
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0 || !this->CertifyPart(part))
{
return QList<IViewReference::Pointer>();
}
ILayoutContainer::Pointer container =
part->GetSite().Cast<PartSite> ()->GetPane()->GetContainer();
if (container.Cast<PartStack> () != 0)
{
PartStack::Pointer folder = container.Cast<PartStack> ();
QList<IViewReference::Pointer> list;
ILayoutContainer::ChildrenType children = folder->GetChildren();
for (ILayoutContainer::ChildrenType::iterator childIter =
children.begin(); childIter != children.end(); ++childIter)
{
LayoutPart::Pointer stackablePart = *childIter;
if (stackablePart.Cast<PartPane> () != 0)
{
IViewReference::Pointer view =
stackablePart.Cast<PartPane> ()->GetPartReference().Cast<
IViewReference> ();
if (view != 0)
{
list.push_back(view);
}
}
}
// sort the list by activation order (most recently activated first)
std::sort(list.begin(), list.end(), ActivationOrderPred(activationList));
return list;
}
QList<IViewReference::Pointer> result;
result.push_back(this->GetReference(part).Cast<IViewReference> ());
return result;
}
QList<IViewPart::Pointer> WorkbenchPage::GetViewStack(
IViewPart::Pointer part)
{
QList<IViewReference::Pointer> refStack = this->GetViewReferenceStack(
part);
QList<IViewPart::Pointer> result;
for (int i = 0; i < refStack.size(); i++)
{
IViewPart::Pointer next = refStack[i]->GetView(false);
if (next != 0)
{
result.push_back(next);
}
}
return result;
}
void WorkbenchPage::ResizeView(IViewPart::Pointer part, int width, int height)
{
SashInfo sashInfo;
PartPane::Pointer pane = part->GetSite().Cast<PartSite> ()->GetPane();
ILayoutContainer::Pointer container = pane->GetContainer();
LayoutTree::Pointer tree =
this->GetPerspectivePresentation()->GetLayout()->GetLayoutTree()->Find(
container.Cast<PartStack> ());
// retrieve our layout sashes from the layout tree
this->FindSashParts(tree, pane->FindSashes(), sashInfo);
// first set the width
int deltaWidth = width - pane->GetBounds().width();
if (sashInfo.right != 0)
{
QRect rightBounds = sashInfo.rightNode->GetBounds();
// set the new ratio
sashInfo.right->SetRatio(static_cast<float>((deltaWidth + sashInfo.right->GetBounds().x())
- rightBounds.x()) / rightBounds.width());
// complete the resize
sashInfo.rightNode->SetBounds(rightBounds);
}
else if (sashInfo.left != 0)
{
QRect leftBounds = sashInfo.leftNode->GetBounds();
// set the ratio
sashInfo.left->SetRatio(static_cast<float>((sashInfo.left->GetBounds().x() - deltaWidth)
- leftBounds.x()) / leftBounds.width());
// complete the resize
sashInfo.leftNode->SetBounds(sashInfo.leftNode->GetBounds());
}
// next set the height
int deltaHeight = height - pane->GetBounds().height();
if (sashInfo.bottom != 0)
{
QRect bottomBounds = sashInfo.bottomNode->GetBounds();
// set the new ratio
sashInfo.bottom->SetRatio(static_cast<float>((deltaHeight + sashInfo.bottom->GetBounds().y())
- bottomBounds.y()) / bottomBounds.height());
// complete the resize
sashInfo.bottomNode->SetBounds(bottomBounds);
}
else if (sashInfo.top != 0)
{
QRect topBounds = sashInfo.topNode->GetBounds();
// set the ratio
sashInfo.top->SetRatio(static_cast<float>((sashInfo.top->GetBounds().y() - deltaHeight)
- topBounds.y()) / topBounds.height());
// complete the resize
sashInfo.topNode->SetBounds(topBounds);
}
}
void WorkbenchPage::FindSashParts(LayoutTree::Pointer tree,
const PartPane::Sashes& sashes, SashInfo& info)
{
LayoutTree::Pointer parent(tree->GetParent());
if (parent == 0)
{
return;
}
if (parent->part.Cast<LayoutPartSash> () != 0)
{
// get the layout part sash from this tree node
LayoutPartSash::Pointer sash = parent->part.Cast<LayoutPartSash> ();
// make sure it has a sash control
QWidget* control = sash->GetControl();
if (control != nullptr)
{
// check for a vertical sash
if (sash->IsVertical())
{
if (sashes.left == control)
{
info.left = sash;
info.leftNode = parent->FindSash(sash);
}
else if (sashes.right == control)
{
info.right = sash;
info.rightNode = parent->FindSash(sash);
}
}
// check for a horizontal sash
else
{
if (sashes.top == control)
{
info.top = sash;
info.topNode = parent->FindSash(sash);
}
else if (sashes.bottom == control)
{
info.bottom = sash;
info.bottomNode = parent->FindSash(sash);
}
}
}
}
// recursive call to continue up the tree
this->FindSashParts(parent, sashes, info);
}
QList<IWorkbenchPartReference::Pointer> WorkbenchPage::GetAllParts()
{
QList<IViewReference::Pointer> views = this->GetViewFactory()->GetViews();
QList<IEditorReference::Pointer> editors = this->GetEditorReferences();
QList<IWorkbenchPartReference::Pointer> result;
for (int i = 0; i < views.size(); i++)
{
result.push_back(views[i]);
}
for (QList<IEditorReference::Pointer>::iterator iter = editors.begin(); iter
!= editors.end(); ++iter)
{
result.push_back(*iter);
}
return result;
}
QList<IWorkbenchPartReference::Pointer> WorkbenchPage::GetOpenParts()
{
QList<IWorkbenchPartReference::Pointer> refs = this->GetAllParts();
QList<IWorkbenchPartReference::Pointer> result;
for (int i = 0; i < refs.size(); i++)
{
IWorkbenchPartReference::Pointer reference = refs[i];
IWorkbenchPart::Pointer part = reference->GetPart(false);
if (part != 0)
{
result.push_back(reference);
}
}
return result;
}
void WorkbenchPage::TestInvariants()
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp != 0)
{
persp->TestInvariants();
// When we have widgets, ensure that there is no situation where the editor area is visible
// and the perspective doesn't want an editor area.
if (this->GetClientComposite()
&& editorPresentation->GetLayoutPart()->IsVisible())
{
poco_assert(persp->IsEditorAreaVisible());
}
}
}
IExtensionTracker* WorkbenchPage::GetExtensionTracker() const
{
if (tracker.isNull())
{
tracker.reset(new UIExtensionTracker(GetWorkbenchWindow()->GetWorkbench()->GetDisplay()));
}
return tracker.data();
}
/*
* (non-Javadoc)
*
* @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts()
*/
QList<QString> WorkbenchPage::GetPerspectiveShortcuts()
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return QList<QString>();
}
return persp->GetPerspectiveShortcuts();
}
QList<QString> WorkbenchPage::GetShowViewShortcuts()
{
Perspective::Pointer persp = this->GetActivePerspective();
if (persp == 0)
{
return QList<QString>();
}
return persp->GetShowViewShortcuts();
}
void WorkbenchPage::SuggestReset()
{
IWorkbench* workbench = this->GetWorkbenchWindow()->GetWorkbench();
// workbench.getDisplay().asyncExec(new Runnable()
// {
// public void WorkbenchPage::run()
// {
Shell::Pointer parentShell;
IWorkbenchWindow::Pointer window = workbench->GetActiveWorkbenchWindow();
if (window == 0)
{
if (workbench->GetWorkbenchWindowCount() == 0)
{
return;
}
window = workbench->GetWorkbenchWindows()[0];
}
parentShell = window->GetShell();
if (QMessageBox::question(parentShell.IsNull() ? nullptr : reinterpret_cast<QWidget*>(parentShell->GetControl()),
"Reset Perspective?",
"Changes to installed plug-ins have affected this perspective. Would you like to reset this perspective to accept these changes?") ==
QMessageBox::Yes)
{
IWorkbenchPage::Pointer page = window->GetActivePage();
if (page == 0)
{
return;
}
page->ResetPerspective();
}
// }
// });
}
bool WorkbenchPage::IsPartVisible(
IWorkbenchPartReference::Pointer reference)
{
IWorkbenchPart::Pointer part = reference->GetPart(false);
// Can't be visible if it isn't created yet
if (part == 0)
{
return false;
}
return this->IsPartVisible(part);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp
index 1e0de9ace4..effc5969d1 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchWindowConfigurer.cpp
@@ -1,291 +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.
============================================================================*/
#include "berryWorkbenchWindowConfigurer.h"
#include "berryWorkbenchWindow.h"
#include "berryWorkbench.h"
#include "berryWorkbenchPage.h"
#include "berryEditorSashContainer.h"
#include "berryWorkbenchPlugin.h"
#include "berryMenuManager.h"
#include "berryQtDnDControlWidget.h"
namespace berry
{
WorkbenchWindowConfigurer::WindowActionBarConfigurer::WindowActionBarConfigurer(WorkbenchWindow::WeakPtr wnd)
: window(wnd)
{
}
void WorkbenchWindowConfigurer::WindowActionBarConfigurer::SetProxy(IActionBarConfigurer::Pointer proxy)
{
this->proxy = proxy;
}
IWorkbenchWindowConfigurer::Pointer WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetWindowConfigurer()
{
return WorkbenchWindow::Pointer(window)->GetWindowConfigurer();
}
IMenuManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetMenuManager()
{
if (proxy.IsNotNull())
{
return proxy->GetMenuManager();
}
return window.Lock()->GetMenuManager();
}
IToolBarManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetToolBarManager()
{
if (proxy.IsNotNull())
{
return proxy->GetToolBarManager();
}
//return window.Lock()->GetToolBarManager();
return nullptr;
}
WorkbenchWindowConfigurer::WorkbenchWindowConfigurer(const WorkbenchWindow::Pointer& window)
- : shellStyle(nullptr)
+ : shellStyle({})
, showPerspectiveBar(false)
, showStatusLine(true)
, showToolBar(true)
, showMenuBar(true)
, showProgressIndicator(false)
, dropTargetListener(nullptr)
, initialSize(1632, 918) // 85% of 1920 x 1080 (FullHD, 1080p)
{
if (window.IsNull())
{
throw Poco::InvalidArgumentException();
}
this->window = window;
windowTitle = "BlueBerry Application";
}
IWorkbenchWindow::Pointer WorkbenchWindowConfigurer::GetWindow()
{
return IWorkbenchWindow::Pointer(window);
}
IWorkbenchConfigurer::Pointer WorkbenchWindowConfigurer::GetWorkbenchConfigurer()
{
return dynamic_cast<Workbench*>(PlatformUI::GetWorkbench())->GetWorkbenchConfigurer();
}
QString WorkbenchWindowConfigurer::BasicGetTitle()
{
return windowTitle;
}
QString WorkbenchWindowConfigurer::GetTitle()
{
Shell::Pointer shell = window.Lock()->GetShell();
if (shell)
{
// update the cached title
windowTitle = shell->GetText();
}
return windowTitle;
}
void WorkbenchWindowConfigurer::SetTitle(const QString &title)
{
windowTitle = title;
Shell::Pointer shell = window.Lock()->GetShell();
if (shell)
{
shell->SetText(title);
}
}
bool WorkbenchWindowConfigurer::GetShowMenuBar() const
{
return showMenuBar;
}
void WorkbenchWindowConfigurer::SetShowMenuBar(bool show)
{
showMenuBar = show;
// WorkbenchWindow win = (WorkbenchWindow) getWindow();
// Shell shell = win.getShell();
// if (shell != null)
// {
// boolean showing = shell.getMenuBar() != null;
// if (show != showing)
// {
// if (show)
// {
// shell.setMenuBar(win.getMenuBarManager().getMenu());
// }
// else
// {
// shell.setMenuBar(null);
// }
// }
// }
}
bool WorkbenchWindowConfigurer::GetShowToolBar() const
{
return showToolBar;
}
void WorkbenchWindowConfigurer::SetShowToolBar(bool show)
{
showToolBar = show;
//window.setCoolBarVisible(show);
// @issue need to be able to reconfigure after window's controls created
}
bool WorkbenchWindowConfigurer::GetShowPerspectiveBar() const
{
return showPerspectiveBar;
}
void WorkbenchWindowConfigurer::SetShowPerspectiveBar(bool show)
{
showPerspectiveBar = show;
//window.setPerspectiveBarVisible(show);
// @issue need to be able to reconfigure after window's controls created
}
bool WorkbenchWindowConfigurer::GetShowStatusLine() const
{
return showStatusLine;
}
void WorkbenchWindowConfigurer::SetShowStatusLine(bool show)
{
showStatusLine = show;
// @issue need to be able to reconfigure after window's controls created
}
bool WorkbenchWindowConfigurer::GetShowProgressIndicator() const
{
return showProgressIndicator;
}
void WorkbenchWindowConfigurer::SetShowProgressIndicator(bool show)
{
showProgressIndicator = show;
// @issue need to be able to reconfigure after window's controls created
}
void WorkbenchWindowConfigurer::AddEditorAreaTransfer(const QStringList& transfers)
{
if (transfers.isEmpty()) return;
int oldSize = transferTypes.size();
- transferTypes.unite(QSet<QString>::fromList(transfers));
+ transferTypes.unite(QSet<QString>(transfers.begin(), transfers.end()));
if (transferTypes.size() == oldSize) return;
WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast<WorkbenchPage>();
if (page)
{
QtDnDControlWidget* dropTarget =
static_cast<QtDnDControlWidget*>(page->GetEditorPresentation()->GetLayoutPart().Cast<EditorSashContainer>()->GetParent());
- dropTarget->SetTransferTypes(transferTypes.toList());
+ dropTarget->SetTransferTypes(transferTypes.values());
}
}
void WorkbenchWindowConfigurer::ConfigureEditorAreaDropListener(IDropTargetListener* listener)
{
if (listener == nullptr) return;
dropTargetListener = listener;
WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast<WorkbenchPage>();
if (page)
{
QtDnDControlWidget* dropTarget =
static_cast<QtDnDControlWidget*>(page->GetEditorPresentation()->GetLayoutPart().Cast<EditorSashContainer>()->GetParent());
dropTarget->AddDropListener(listener);
}
}
QStringList WorkbenchWindowConfigurer::GetTransfers() const
{
- return transferTypes.toList();
+ return transferTypes.values();
}
IDropTargetListener* WorkbenchWindowConfigurer::GetDropTargetListener() const
{
return dropTargetListener;
}
IActionBarConfigurer::Pointer WorkbenchWindowConfigurer::GetActionBarConfigurer()
{
if (actionBarConfigurer.IsNull())
{
// lazily initialize
actionBarConfigurer = new WindowActionBarConfigurer(window);
}
return actionBarConfigurer;
}
Qt::WindowFlags WorkbenchWindowConfigurer::GetWindowFlags() const
{
return shellStyle;
}
void WorkbenchWindowConfigurer::SetWindowFlags(Qt::WindowFlags shellStyle)
{
this->shellStyle = shellStyle;
}
QPoint WorkbenchWindowConfigurer::GetInitialSize() const
{
return initialSize;
}
void WorkbenchWindowConfigurer::SetInitialSize(QPoint size)
{
initialSize = size;
}
void WorkbenchWindowConfigurer::CreateDefaultContents(Shell::Pointer shell)
{
WorkbenchWindow::Pointer(window)->CreateDefaultContents(shell);
}
QMenuBar* WorkbenchWindowConfigurer::CreateMenuBar()
{
return window.Lock()->GetMenuManager()->CreateMenuBar(window.Lock()->GetShell()->GetControl());
}
QWidget* WorkbenchWindowConfigurer::CreateToolBar(QWidget* /*parent*/)
{
// IToolBarManager* toolBarManager = window->GetToolBarManager();
// if (toolBarManager)
// {
// return toolBarManager->CreateControl(parent);
// }
return nullptr;
}
QWidget *WorkbenchWindowConfigurer::CreatePageComposite(QWidget *parent)
{
return WorkbenchWindow::Pointer(window)->CreatePageComposite(parent);
}
bool WorkbenchWindowConfigurer::SaveState(IMemento::Pointer memento)
{
return WorkbenchWindow::Pointer(window)->SaveState(memento);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.cpp b/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.cpp
index a76bf29bb2..99a8317d73 100755
--- a/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.cpp
@@ -1,106 +1,106 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryQCTabBar.h"
#include <QApplication>
#include <QMouseEvent>
namespace berry
{
QCTabBar::QCTabBar(QWidget* parent) :
QTabBar(parent)
{
}
QCTabBar::~QCTabBar()
{
qDeleteAll(tabItemList);
}
void QCTabBar::tabRemoved(int index)
{
if (index >= 0 && index < tabItemList.size())
{
delete tabItemList.takeAt(index);
}
}
void QCTabBar::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton)
- dragStartPosition = event->globalPos();
+ dragStartPosition = event->globalPosition().toPoint();
QTabBar::mousePressEvent(event);
}
void QCTabBar::mouseMoveEvent(QMouseEvent* event)
{
if (!(event->buttons() & Qt::LeftButton))
{
QTabBar::mouseMoveEvent(event);
return;
}
- if ((event->globalPos() - dragStartPosition).manhattanLength()
+ if ((event->globalPosition().toPoint() - dragStartPosition).manhattanLength()
< QApplication::startDragDistance())
{
QTabBar::mouseMoveEvent(event);
return;
}
emit dragStarted(dragStartPosition);
}
AbstractTabItem* QCTabBar::getTab(int index) const
{
if (index < 0 || index >= tabItemList.size()) return nullptr;
return tabItemList[index];
}
QList<AbstractTabItem*> QCTabBar::getTabs() const
{
return tabItemList;
}
void QCTabBar::insertTab(int index, AbstractTabItem* item)
{
tabItemList.insert(index, item);
QTabBar::insertTab(index, QString());
}
void QCTabBar::moveAbstractTab(int from, int to)
{
AbstractTabItem* item = tabItemList[from];
if (to >= tabItemList.size()) --to;
tabItemList.removeAt(from);
tabItemList.insert(to, item);
this->moveTab(from, to);
}
void QCTabBar::setCurrentTab(AbstractTabItem* item)
{
this->setCurrentIndex(tabItemList.indexOf(item));
}
AbstractTabItem* QCTabBar::getCurrentTab()
{
int index = this->currentIndex();
return tabItemList[index];
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp
index 7b314e961f..89ef9a6060 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp
@@ -1,292 +1,292 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "berryPerspectivesPreferencePage.h"
#include "ui_berryPerspectivesPreferencePage.h"
#include <berryIWorkbenchPage.h>
#include "internal/berryPerspective.h"
#include "internal/berryPerspectiveRegistry.h"
#include "internal/berryPreferenceConstants.h"
#include "internal/berryWorkbenchPage.h"
#include "berryWorkbenchPlugin.h"
#include <QListWidgetItem>
#include <QMessageBox>
#include <mitkIPreferences.h>
namespace
{
mitk::IPreferences* GetPreferences()
{
return berry::WorkbenchPlugin::GetDefault()->GetPreferences();
}
}
namespace berry {
bool PerspectiveComparator(const PerspectiveDescriptor::Pointer& p1, const PerspectiveDescriptor::Pointer& p2)
{
return p1->GetLabel() < p2->GetLabel();
}
PerspectivesPreferencePage::PerspectivesPreferencePage()
: ui(nullptr)
, pageWidget(nullptr)
, workbench(nullptr)
, perspRegistry(nullptr)
{
}
PerspectivesPreferencePage::~PerspectivesPreferencePage()
{
delete ui;
}
void PerspectivesPreferencePage::Init(berry::IWorkbench::Pointer workbench)
{
ui = new Ui::PerspectivesPreferencePage;
this->workbench = workbench.GetPointer();
perspRegistry = dynamic_cast<PerspectiveRegistry*>(workbench->GetPerspectiveRegistry());
}
void PerspectivesPreferencePage::CreateQtControl(QWidget* parent)
{
pageWidget = new QWidget(parent);
ui->setupUi(pageWidget);
ui->perspectivesListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->perspectivesListWidget->setIconSize(QSize(16, 16));
connect(ui->sameWindowButton, SIGNAL(clicked()), this, SLOT(OpenPerspInSameWindow()));
connect(ui->newWindowButton, SIGNAL(clicked()), this, SLOT(OpenPerspInNewWindow()));
connect(ui->perspectivesListWidget, SIGNAL(itemSelectionChanged()), this, SLOT(PerspectiveSelectionChanged()));
connect(ui->revertButton, SIGNAL(clicked()), this, SLOT(RevertPerspective()));
connect(ui->makeDefaultButton, SIGNAL(clicked()), this, SLOT(MakeDefaultPerspective()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(DeletePerspective()));
this->Update();
}
QWidget* PerspectivesPreferencePage::GetQtControl() const
{
return pageWidget;
}
bool PerspectivesPreferencePage::PerformOk()
{
// Set the default perspective
if (defaultPerspectiveId != perspRegistry->GetDefaultPerspective())
{
perspRegistry->SetDefaultPerspective(defaultPerspectiveId);
}
//Delete the perspective
if(perspectives.size() < perspRegistry->GetPerspectives().size())
{
QList<IWorkbenchWindow::Pointer> windows = workbench->GetWorkbenchWindows();
// close any perspectives that are about to be deleted
for (int i = 0; i < windows.size(); i++)
{
QList<IWorkbenchPage::Pointer> pages = windows[i]->GetPages();
for (int j = 0; j < pages.size(); j++)
{
WorkbenchPage::Pointer page = pages[j].Cast<WorkbenchPage>();
for (int k = 0; k < perspToDelete.size(); k++)
{
IPerspectiveDescriptor::Pointer desc(perspToDelete[k].GetPointer());
if (page->FindPerspective(desc).IsNotNull())
{
page->ClosePerspective(desc, true, true);
}
}
}
}
perspRegistry->DeletePerspectives(perspToDelete);
}
// Revert the perspectives
perspRegistry->RevertPerspectives(perspToRevert);
// store the open perspective mode setting
auto* prefs = GetPreferences();
prefs->PutInt(PreferenceConstants::OPEN_PERSP_MODE, openPerspMode);
return true;
}
void PerspectivesPreferencePage::PerformCancel()
{
}
void PerspectivesPreferencePage::Update()
{
auto* prefs = GetPreferences();
openPerspMode = prefs->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE);
ui->sameWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_ACTIVE_PAGE);
ui->newWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_NEW_WINDOW);
// Populate the perspectivesTable
perspectives.clear();
perspToRevert.clear();
perspToDelete.clear();
QList<IPerspectiveDescriptor::Pointer> persps = perspRegistry->GetPerspectives();
for (int i = 0; i < persps.size(); i++)
{
perspectives.push_back(persps[i].Cast<PerspectiveDescriptor>());
}
- qSort(perspectives.begin(), perspectives.end(), PerspectiveComparator);
+ std::sort(perspectives.begin(), perspectives.end(), PerspectiveComparator);
defaultPerspectiveId = perspRegistry->GetDefaultPerspective();
UpdatePerspectivesTable();
}
void PerspectivesPreferencePage::OpenPerspInSameWindow()
{
openPerspMode = PreferenceConstants::OPM_ACTIVE_PAGE;
}
void PerspectivesPreferencePage::OpenPerspInNewWindow()
{
openPerspMode = PreferenceConstants::OPM_NEW_WINDOW;
}
void PerspectivesPreferencePage::PerspectiveSelectionChanged()
{
UpdateButtons();
}
void PerspectivesPreferencePage::RevertPerspective()
{
PerspectiveDescriptor::Pointer desc = GetSelectedPerspective();
if (desc.IsNotNull() && !perspToRevert.contains(desc))
{
perspToRevert.push_back(desc);
}
UpdateButtons();
}
void PerspectivesPreferencePage::DeletePerspective()
{
PerspectiveDescriptor::Pointer desc = GetSelectedPerspective();
if (desc.IsNotNull() && !perspToDelete.contains(desc))
{
if (!FindOpenInstance(desc))
{
perspToDelete.push_back(desc);
perspToRevert.removeAll(desc);
perspectives.removeAll(desc);
UpdatePerspectivesTable();
}
}
UpdateButtons();
}
void PerspectivesPreferencePage::MakeDefaultPerspective()
{
PerspectiveDescriptor::Pointer desc = GetSelectedPerspective();
if (desc.IsNotNull() && !perspToDelete.contains(desc))
{
int row = perspectives.indexOf(desc);
defaultPerspectiveId = desc->GetId();
UpdatePerspectivesTable();
ui->perspectivesListWidget->item(row)->setSelected(true);
}
UpdateButtons();
}
void PerspectivesPreferencePage::UpdateButtons()
{
PerspectiveDescriptor::Pointer desc = GetSelectedPerspective();
if (desc)
{
ui->revertButton->setEnabled(desc->IsPredefined() && desc->HasCustomDefinition() && !perspToRevert.contains(desc));
ui->deleteButton->setEnabled(!desc->IsPredefined());
ui->makeDefaultButton->setEnabled(true);
}
else
{
ui->revertButton->setEnabled(false);
ui->deleteButton->setEnabled(false);
ui->makeDefaultButton->setEnabled(false);
}
}
void PerspectivesPreferencePage::UpdatePerspectivesTable()
{
ui->perspectivesListWidget->clear();
- for (const PerspectiveDescriptor::Pointer &desc : qAsConst(perspectives))
+ for (const PerspectiveDescriptor::Pointer &desc : std::as_const(perspectives))
{
NewPerspectivesTableItem(desc);
}
}
void PerspectivesPreferencePage::NewPerspectivesTableItem(const SmartPointer<PerspectiveDescriptor>& desc)
{
QString label = desc->GetLabel();
if (desc->GetId() == defaultPerspectiveId)
{
label += " (default)";
}
new QListWidgetItem(desc->GetImageDescriptor(), label, ui->perspectivesListWidget);
}
bool PerspectivesPreferencePage::FindOpenInstance(const PerspectiveDescriptor::Pointer& desc)
{
QList<IWorkbenchWindow::Pointer> windows = workbench->GetWorkbenchWindows();
//find all active perspectives currently
for (int i = 0; i < windows.size(); i++)
{
QList<IWorkbenchPage::Pointer> pages = windows[i]->GetPages();
for (int j = 0; j < pages.size(); j++)
{
WorkbenchPage::Pointer page = pages[j].Cast<WorkbenchPage>();
if (page->FindPerspective(desc).IsNotNull())
{
QMessageBox::StandardButton returnCode =
QMessageBox::question(workbench->GetActiveWorkbenchWindow()->GetShell()->GetControl(),
"Delete Perspective",
QString("Are you sure you want to delete the \"%1\" perspective? It has open instances.").arg(desc->GetLabel()),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
return (returnCode != QMessageBox::Yes);
}
}
}
return false;
}
SmartPointer<PerspectiveDescriptor> PerspectivesPreferencePage::GetSelectedPerspective() const
{
PerspectiveDescriptor::Pointer desc;
QList<QListWidgetItem*> selection = ui->perspectivesListWidget->selectedItems();
if (!selection.isEmpty())
{
int row = ui->perspectivesListWidget->row(selection.back());
if (row > -1)
{
desc = perspectives.at(row);
}
}
return desc;
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp
index bee11dae60..42d5dd5812 100644
--- a/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp
@@ -1,112 +1,112 @@
/*============================================================================
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 "berryShowViewHandler.h"
#include "berryIWorkbenchCommandConstants.h"
#include "berryHandlerUtil.h"
#include "berryUIException.h"
#include "berryIWorkbenchPage.h"
#include "berryIViewDescriptor.h"
#include "berryPlatformUI.h"
#include "berryWorkbenchPlugin.h"
#include "internal/berryQtShowViewDialog.h"
#include <berryCommandExceptions.h>
#include <vector>
namespace berry
{
ShowViewHandler::ShowViewHandler()
{
}
Object::Pointer ShowViewHandler::Execute(const ExecutionEvent::ConstPointer& event)
{
IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event);
// Get the view identifier, if any.
const ExecutionEvent::ParameterMap& parameters = event->GetParameters();
ExecutionEvent::ParameterMap::const_iterator result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID);
- QString viewId = result != parameters.end() ? result.value() : QString::null;
+ QString viewId = result != parameters.end() ? result.value() : QString();
result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID);
- QString secondary = result != parameters.end() ? result.value() : QString::null;
+ QString secondary = result != parameters.end() ? result.value() : QString();
if (viewId.isEmpty())
{
this->OpenOther(window);
}
else
{
try
{
this->OpenView(viewId, secondary, window);
}
catch (const PartInitException& e)
{
throw ExecutionException("Part could not be initialized", e);
}
}
return Object::Pointer(nullptr);
}
void ShowViewHandler::OpenOther(IWorkbenchWindow::Pointer window)
{
const IWorkbenchPage::Pointer page = window->GetActivePage();
if (page.IsNull())
{
return;
}
QtShowViewDialog dialog(window.GetPointer(), WorkbenchPlugin::GetDefault()->GetViewRegistry());
int returnCode = dialog.exec();
if (returnCode == QDialog::Rejected)
{
return;
}
const QList<QString> descriptors = dialog.GetSelection();
for (const QString &id : descriptors)
{
try
{
this->OpenView(id, QString(), window);
}
catch (const PartInitException& e)
{
BERRY_WARN << e.what();
// StatusUtil.handleStatus(e.getStatus(),
// WorkbenchMessages.ShowView_errorTitle
// + ": " + e.getMessage(), //$NON-NLS-1$
// StatusManager.SHOW);
}
}
}
void ShowViewHandler::OpenView(const QString& viewId, const QString& secondaryId, IWorkbenchWindow::Pointer activeWorkbenchWindow)
{
const IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage();
if (activePage.IsNull())
{
return;
}
activePage->ShowView(viewId, secondaryId, IWorkbenchPage::VIEW_ACTIVATE);
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp b/Plugins/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp
index a86ff3d902..40b52eba43 100644
--- a/Plugins/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp
@@ -1,138 +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.
============================================================================*/
#include "berryPerspectiveListModel.h"
#include <berryIPerspectiveRegistry.h>
#include <berryIPerspectiveDescriptor.h>
#include <QIcon>
namespace berry {
struct PerspectiveListModel::Impl
{
IPerspectiveRegistry& m_PerspReg;
QList<IPerspectiveDescriptor::Pointer> m_Perspectives;
const bool m_MarkDefault;
Impl(IPerspectiveRegistry& perspReg, bool markDefault)
: m_PerspReg(perspReg)
// TODO use activity filter for correct perspective list
, m_Perspectives(perspReg.GetPerspectives())
, m_MarkDefault(markDefault)
{
}
};
PerspectiveListModel::PerspectiveListModel(IPerspectiveRegistry& perspReg, bool markDefault, QObject* parent)
: QAbstractListModel(parent)
, d(new Impl(perspReg, markDefault))
{
}
PerspectiveListModel::~PerspectiveListModel()
{
}
int PerspectiveListModel::rowCount(const QModelIndex& /*parent*/) const
{
return d->m_Perspectives.size();
}
QVariant PerspectiveListModel::data(const QModelIndex& index, int role) const
{
if (index.row() < 0 || index.row() >= d->m_Perspectives.size() ||
index.column() > 0)
{
return QVariant();
}
if (role == Qt::DisplayRole)
{
const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row());
QString label = desc->GetLabel();
if (d->m_MarkDefault)
{
QString def = d->m_PerspReg.GetDefaultPerspective();
if (desc->GetId() == def)
{
label += " (default)";
}
}
return label;
}
else if (role == Qt::DecorationRole)
{
const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row());
return desc->GetImageDescriptor();
}
else if (role == Id)
{
const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row());
return desc->GetId();
}
else if (role == Description)
{
const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row());
return desc->GetDescription();
}
return QVariant();
}
QVariant PerspectiveListModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const
{
if (role == Qt::DisplayRole)
{
if (section == 0)
{
return QString("Perspective");
}
}
return QVariant();
}
QString PerspectiveListModel::perspectiveName(const QModelIndex& index) const
{
- if (!index.isValid()) return QString::null;
+ if (!index.isValid()) return QString();
return d->m_Perspectives.at(index.row())->GetLabel();
}
IPerspectiveDescriptor::Pointer PerspectiveListModel::perspectiveDescriptor(const QModelIndex& index) const
{
return d->m_Perspectives.at(index.row());
}
QModelIndex PerspectiveListModel::index(const QString& perspId) const
{
int index = -1;
for(int i = 0; i < d->m_Perspectives.size(); ++i)
{
if (d->m_Perspectives.at(i)->GetId() == perspId)
{
index = i;
break;
}
}
if (index > -1)
{
return this->createIndex(index, 0);
}
return QModelIndex();
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp b/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp
index 790bb57380..71a4a90ae2 100644
--- a/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp
+++ b/Plugins/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp
@@ -1,460 +1,461 @@
/*============================================================================
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 "berryViewTreeModel.h"
#include "berryIViewRegistry.h"
#include "berryIViewCategory.h"
#include "berryIWorkbench.h"
#include "berryIWorkbenchWindow.h"
#include "berryIWorkbenchPage.h"
#include "internal/intro/berryIntroConstants.h"
#include "internal/berryKeywordRegistry.h"
#include <QIcon>
#include <QBrush>
+#include <QStringList>
namespace berry {
// --------------------------- Tree Item Classes ---------------------------
struct ViewTreeItem;
bool CompareViewTreeItem(ViewTreeItem* item1, ViewTreeItem* item2);
struct ViewTreeItem
{
ViewTreeItem(ViewTreeModel* model)
: m_parent(nullptr)
, m_model(model)
{}
virtual ~ViewTreeItem()
{
QList<ViewTreeItem*> children = m_children;
if (m_parent) m_parent->removeChild(this);
qDeleteAll(children);
}
virtual QVariant data(int role)
{
if (role == ViewTreeModel::Keywords)
{
if (m_keywordCache.isEmpty())
{
- m_keywordCache = QStringList(keywordLabels().toList());
+ m_keywordCache = keywordLabels().values();
}
return m_keywordCache;
}
return QVariant();
}
virtual Qt::ItemFlags flags() const
{
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
virtual QSet<QString> keywordLabels() const
{
return QSet<QString>();
}
void appendChild(ViewTreeItem* child)
{
m_children.push_back(child);
child->m_parent = this;
- qSort(m_children.begin(), m_children.end(), CompareViewTreeItem);
+ std::sort(m_children.begin(), m_children.end(), CompareViewTreeItem);
}
void removeChild(ViewTreeItem* child)
{
m_children.removeAll(child);
}
QList<ViewTreeItem*> takeChildren()
{
QList<ViewTreeItem*> children = m_children;
m_children.clear();
return children;
}
ViewTreeItem* childItem(int row) const
{
if (row < 0 || row >= m_children.size()) return nullptr;
return m_children.at(row);
}
ViewTreeItem* parentItem() const
{
return m_parent;
}
int childCount() const
{
return m_children.size();
}
int row() const
{
if (m_parent) return m_parent->rowIndex(this);
return 0;
}
int rowIndex(const ViewTreeItem* child) const
{
return m_children.indexOf(const_cast<ViewTreeItem*>(child));
}
QList<ViewTreeItem*> m_children;
ViewTreeItem* m_parent;
ViewTreeModel* m_model;
private:
QStringList m_keywordCache;
};
bool CompareViewTreeItem(ViewTreeItem* item1, ViewTreeItem* item2)
{
return item1->data(Qt::DisplayRole).toString() < item2->data(Qt::DisplayRole).toString();
}
struct RootTreeItem : ViewTreeItem
{
RootTreeItem(ViewTreeModel* model) : ViewTreeItem(model) {}
QVariant data(int /*role*/) override { return QVariant(); }
};
struct DescriptorTreeItem : ViewTreeItem
{
DescriptorTreeItem(ViewTreeModel* model, IViewDescriptor::Pointer descriptor, ViewTreeItem* parent = nullptr);
QVariant data(int role) override;
protected:
QSet<QString> keywordLabels() const override;
IViewDescriptor::Pointer m_descriptor;
};
struct CategoryTreeItem : ViewTreeItem
{
CategoryTreeItem(ViewTreeModel* model, IViewCategory::Pointer category, ViewTreeItem* parent = nullptr);
QVariant data(int role) override;
Qt::ItemFlags flags() const override;
protected:
QSet<QString> keywordLabels() const override;
/**
* Removes the temporary intro view from the list so that it cannot be activated except through
* the introduction command.
*/
void RemoveIntroView(QList<IViewDescriptor::Pointer>& list);
private:
void CreateChildren();
IViewCategory::Pointer m_category;
};
// --------------------------- Tree Model Classes ---------------------------
struct ViewTreeModel::Impl
{
Impl(const IWorkbenchWindow* window)
: window(window)
, viewRegistry(*window->GetWorkbench()->GetViewRegistry())
{
}
const IWorkbenchWindow* window;
IViewRegistry& viewRegistry;
QScopedPointer<RootTreeItem> rootItem;
};
ViewTreeModel::ViewTreeModel(const IWorkbenchWindow* window, QObject* parent)
: QAbstractItemModel(parent)
, d(new Impl(window))
{
d->rootItem.reset(new RootTreeItem(this));
QList<CategoryTreeItem*> categoryItems;
QList<IViewCategory::Pointer> categories = d->viewRegistry.GetCategories();
- for (const auto &category : qAsConst(categories))
+ for (const auto &category : std::as_const(categories))
{
if (category->GetViews().isEmpty()) continue;
CategoryTreeItem* categoryItem = new CategoryTreeItem(this, category);
if (categoryItem->childCount() == 0)
{
delete categoryItem;
}
else
{
categoryItems.push_back(categoryItem);
}
}
// if there is only one category, return it's children directly
if (categoryItems.size() == 1)
{
QList<ViewTreeItem*> items = categoryItems.front()->takeChildren();
- for (auto item : qAsConst(items))
+ for (auto item : std::as_const(items))
{
d->rootItem->appendChild(item);
}
qDeleteAll(categoryItems);
}
else
{
- for (auto category : qAsConst(categoryItems))
+ for (auto category : std::as_const(categoryItems))
{
d->rootItem->appendChild(category);
}
}
}
ViewTreeModel::~ViewTreeModel()
{
}
QVariant ViewTreeModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid()) return QVariant();
return static_cast<ViewTreeItem*>(index.internalPointer())->data(role);
}
Qt::ItemFlags ViewTreeModel::flags(const QModelIndex& index) const
{
- if (!index.isValid()) return nullptr;
+ if (!index.isValid()) return {};
return static_cast<ViewTreeItem*>(index.internalPointer())->flags();
}
QVariant ViewTreeModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const
{
if (role == Qt::DisplayRole && section == 0)
{
return "View";
}
return QVariant();
}
QModelIndex ViewTreeModel::index(int row, int column, const QModelIndex& parent) const
{
if (!hasIndex(row, column, parent))
{
return QModelIndex();
}
ViewTreeItem* parentItem = nullptr;
if (!parent.isValid())
{
parentItem = d->rootItem.data();
}
else
{
parentItem = static_cast<ViewTreeItem*>(parent.internalPointer());
}
ViewTreeItem* childItem = parentItem->childItem(row);
if (childItem)
{
return createIndex(row, column, childItem);
}
return QModelIndex();
}
QModelIndex ViewTreeModel::parent(const QModelIndex& child) const
{
if (!child.isValid())
{
return QModelIndex();
}
ViewTreeItem* childItem = static_cast<ViewTreeItem*>(child.internalPointer());
ViewTreeItem* parentItem = childItem->parentItem();
if (parentItem == d->rootItem.data())
{
return QModelIndex();
}
return createIndex(parentItem->row(), 0, parentItem);
}
int ViewTreeModel::rowCount(const QModelIndex& parent) const
{
ViewTreeItem* parentItem = nullptr;
if (parent.column() > 0) return 0;
if (!parent.isValid())
{
parentItem = d->rootItem.data();
}
else
{
parentItem = static_cast<ViewTreeItem*>(parent.internalPointer());
}
return parentItem->childCount();
}
int ViewTreeModel::columnCount(const QModelIndex& /*parent*/) const
{
return 1;
}
const IWorkbenchWindow*ViewTreeModel::GetWorkbenchWindow() const
{
return d->window;
}
// --------------------------- DescriptorTreeItem ---------------------------
DescriptorTreeItem::DescriptorTreeItem(ViewTreeModel* model, IViewDescriptor::Pointer descriptor, ViewTreeItem* parent)
: ViewTreeItem(model)
, m_descriptor(descriptor)
{
if (parent) parent->appendChild(this);
}
QVariant DescriptorTreeItem::data(int role)
{
if (role == Qt::DisplayRole)
{
return m_descriptor->GetLabel();
}
else if (role == Qt::DecorationRole)
{
return m_descriptor->GetImageDescriptor();
}
else if (role == Qt::ForegroundRole)
{
IWorkbenchPage::Pointer page = this->m_model->GetWorkbenchWindow()->GetActivePage();
if (page.IsNotNull())
{
if (page->FindViewReference(m_descriptor->GetId()).IsNotNull())
{
return QBrush(QColor(Qt::gray));
}
}
}
else if (role == ViewTreeModel::Description)
{
return m_descriptor->GetDescription();
}
else if (role == ViewTreeModel::Id)
{
return m_descriptor->GetId();
}
return ViewTreeItem::data(role);
}
QSet<QString> DescriptorTreeItem::keywordLabels() const
{
KeywordRegistry* registry = KeywordRegistry::GetInstance();
QStringList ids = m_descriptor->GetKeywordReferences();
QSet<QString> keywords;
keywords.insert(m_descriptor->GetLabel());
- for(const auto &id : qAsConst(ids))
+ for(const auto &id : std::as_const(ids))
{
QString label = registry->GetKeywordLabel(id);
- for (const auto &keyword : label.split(' ', QString::SkipEmptyParts))
+ for (const auto &keyword : label.split(' ', Qt::SkipEmptyParts))
{
keywords.insert(keyword);
}
}
return keywords;
}
// --------------------------- CategoryTreeItem ---------------------------
CategoryTreeItem::CategoryTreeItem(ViewTreeModel* model, IViewCategory::Pointer category, ViewTreeItem* parent)
: ViewTreeItem(model)
, m_category(category)
{
if (parent) parent->appendChild(this);
this->CreateChildren();
}
QVariant CategoryTreeItem::data(int role)
{
if (role == Qt::DisplayRole)
{
return m_category->GetLabel();
}
else if (role == Qt::DecorationRole)
{
return QIcon::fromTheme("folder");
}
else if (role == ViewTreeModel::Id)
{
return m_category->GetId();
}
return ViewTreeItem::data(role);
}
Qt::ItemFlags CategoryTreeItem::flags() const
{
return Qt::ItemIsEnabled;
}
QSet<QString> CategoryTreeItem::keywordLabels() const
{
QSet<QString> keywords;
for(auto child : this->m_children)
{
for (const auto &keyword : child->data(ViewTreeModel::Keywords).toStringList())
{
keywords.insert(keyword);
}
}
return keywords;
}
void CategoryTreeItem::CreateChildren()
{
auto viewDescriptors = m_category->GetViews();
RemoveIntroView(viewDescriptors);
- for(const auto &viewDescriptor : qAsConst(viewDescriptors))
+ for(const auto &viewDescriptor : std::as_const(viewDescriptors))
{
new DescriptorTreeItem(this->m_model, viewDescriptor, this);
}
}
void CategoryTreeItem::RemoveIntroView(QList<IViewDescriptor::Pointer>& list)
{
for (auto view = list.begin(); view != list.end();)
{
if ((*view)->GetId() == IntroConstants::INTRO_VIEW_ID)
{
view = list.erase(view);
}
else ++view;
}
}
}
diff --git a/Plugins/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h b/Plugins/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h
index ce09eb7a02..0edede110d 100755
--- a/Plugins/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h
+++ b/Plugins/org.blueberry.ui.qt/src/tweaklets/berryGuiWidgetsTweaklet.h
@@ -1,208 +1,208 @@
/*============================================================================
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 BERRYGUIWIDGETSTWEAKLET_H_
#define BERRYGUIWIDGETSTWEAKLET_H_
#include "internal/berryTweaklets.h"
#include "guitk/berryGuiTkISelectionListener.h"
#include "guitk/berryGuiTkIControlListener.h"
#include "berryShell.h"
//#include "commands/berryIMenu.h"
//#include "commands/berryIMenuItem.h"
namespace berry {
struct BERRY_UI_QT GuiWidgetsTweaklet
{
static Tweaklets::TweakKey<GuiWidgetsTweaklet> KEY;
virtual void AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) = 0;
virtual void RemoveSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) = 0;
/**
* Adds the listener to the collection of listeners who will
* be notified when the widget is moved or resized, by sending
* it one of the messages defined in the <code>IControlListener</code>
* interface.
*
* @param widget
* @param listener the listener which should be notified
*
* @see IControlListener
* @see #RemoveControlListener
*/
virtual void AddControlListener(QWidget* widget, GuiTk::IControlListener::Pointer listener) = 0;
/**
* Removes the listener from the collection of listeners who will
* be notified when the widget is moved or resized.
*
* @param widget
* @param listener the listener which should no longer be notified
*
* @see IControlListener
* @see #AddControlListener
*/
virtual void RemoveControlListener(QWidget* widget, GuiTk::IControlListener::Pointer listener) = 0;
virtual bool GetEnabled(QWidget* widget) = 0;
virtual void SetEnabled(QWidget* widget, bool enabled) = 0;
virtual void SetBounds(QWidget* widget, const QRect& bounds) = 0;
virtual QRect GetBounds(QWidget* widget) = 0;
virtual void SetVisible(QWidget* widget, bool visible) = 0;
virtual bool GetVisible(QWidget* widget) = 0;
virtual bool IsVisible(QWidget* widget) = 0;
virtual QRect GetClientArea(QWidget* widget) = 0;
virtual QWidget* GetParent(QWidget* widget) = 0;
virtual bool SetParent(QWidget* widget, QWidget* parent) = 0;
virtual void SetData(QWidget* widget, const QString& id, Object::Pointer data) = 0;
virtual Object::Pointer GetData(QWidget* widget, const QString& id) = 0;
virtual QPoint GetCursorLocation() = 0;
virtual QWidget* GetCursorControl() = 0;
virtual QWidget* FindControl(const QList<Shell::Pointer>& shells, const QPoint& location) = 0;
/**
* Determines if one control is a child of another. Returns true iff the second
* argument is a child of the first (or the same object).
*
* @param potentialParent
* @param childToTest
* @return
*/
virtual bool IsChild(QWidget* potentialParent, QWidget* childToTest) = 0;
/**
* Returns the control which currently has keyboard focus,
* or null if keyboard events are not currently going to
* any of the controls built by the currently running
* application.
*
* @return the control under the cursor
*/
virtual QWidget* GetFocusControl() = 0;
virtual bool IsReparentable(QWidget* widget) = 0;
virtual void MoveAbove(QWidget* widgetToMove, QWidget* widget) = 0;
virtual void MoveBelow(QWidget* widgetToMove, QWidget* widget) = 0;
virtual void Dispose(QWidget* widget) = 0;
virtual Shell::Pointer CreateShell(Shell::Pointer parent, int style) = 0;
virtual void DisposeShell(Shell::Pointer shell) = 0;
virtual QWidget* CreateComposite(QWidget* parent) = 0;
virtual QList<Shell::Pointer> GetShells() = 0;
virtual Shell::Pointer GetShell(QWidget* widget) = 0;
virtual Shell::Pointer GetActiveShell() = 0;
// command framework interface classes
//virtual IMenu::Pointer CreateMenu(QWidget*, IMenu::Style = IMenu::POP_UP) = 0;
//virtual IMenu::Pointer CreateMenu(IMenu::Pointer parent) = 0;
//virtual IMenuItem::Pointer CreateMenuItem(IMenu::Pointer, IMenuItem::Style, int index = -1) = 0;
/**
* @brief returns the coordinates of the center point of the primary screen
* (where the application starts) of the current desktop.
*
* @param i the number of the screen (if there are multiple). If i = -1
* a rectangle representing the size of the virtual desktop is returned.
* @return the screen Geometry.
* @see GetScreenNumber()
* @see GetPrimaryScreenNumber()
*/
- virtual QRect GetScreenSize(int i = -1) = 0;
+ virtual QRect GetScreenSize(int i = 0) = 0;
- virtual QRect GetAvailableScreenSize(int i = -1) = 0;
+ virtual QRect GetAvailableScreenSize(int i = 0) = 0;
virtual int GetClosestScreenNumber(const QRect&) = 0;
/**
* @brief Gets the number of available screens in a multi-screen environment.
*
* @return the number of available screens in a multi-screen environment.
*/
virtual unsigned int GetScreenNumber() = 0;
/**
* @brief Gets the number of the primary screen.
*
* @return the number of the primary screen.
*/
virtual int GetPrimaryScreenNumber() = 0;
/**
* Converts the given rectangle from display coordinates to the local coordinate system
* of the given object
*
* @param coordinateSystem local coordinate system (widget) being converted to
* @param toConvert rectangle to convert
* @return a rectangle in control coordinates
* @since 3.0
*/
virtual QRect ToControl(QWidget* coordinateSystem,
const QRect& toConvert) = 0;
/**
* Converts the given point from display coordinates to the local coordinate system
* of the given object
*
* @param coordinateSystem local coordinate system (widget) being converted to
* @param toConvert point to convert
* @return a point in control coordinates
* @since 3.0
*/
virtual QPoint ToControl(QWidget* coordinateSystem,
const QPoint& toConvert) = 0;
/**
* Converts the given rectangle from the local coordinate system of the given object
* into display coordinates.
*
* @param coordinateSystem local coordinate system (widget) being converted from
* @param toConvert rectangle to convert
* @return a rectangle in display coordinates
* @since 3.0
*/
virtual QRect ToDisplay(QWidget* coordinateSystem,
const QRect& toConvert) = 0;
/**
* Converts the given point from the local coordinate system of the given object
* into display coordinates.
*
* @param coordinateSystem local coordinate system (widget) being converted from
* @param toConvert point to convert
* @return a point in display coordinates
* @since 3.0
*/
virtual QPoint ToDisplay(QWidget* coordinateSystem,
const QPoint& toConvert) = 0;
};
}
Q_DECLARE_INTERFACE(berry::GuiWidgetsTweaklet, "org.blueberry.GuiWidgetsTweaklet")
#endif /* BERRYGUIWIDGETSTWEAKLET_H_ */
diff --git a/Plugins/org.mitk.gui.qt.application/CMakeLists.txt b/Plugins/org.mitk.gui.qt.application/CMakeLists.txt
index 5790187d9c..b855750ecd 100644
--- a/Plugins/org.mitk.gui.qt.application/CMakeLists.txt
+++ b/Plugins/org.mitk.gui.qt.application/CMakeLists.txt
@@ -1,8 +1,8 @@
project(org_mitk_gui_qt_application)
mitk_create_plugin(
EXPORT_DIRECTIVE MITK_QT_APP
EXPORTED_INCLUDE_SUFFIXES src
MODULE_DEPENDS MitkQtWidgets MitkQtWidgetsExt
- PACKAGE_DEPENDS Qt5|OpenGL+Xml
+ PACKAGE_DEPENDS Qt6|OpenGL+Xml
)
diff --git a/Plugins/org.mitk.gui.qt.application/files.cmake b/Plugins/org.mitk.gui.qt.application/files.cmake
index 701f4e7b55..234ec063b1 100644
--- a/Plugins/org.mitk.gui.qt.application/files.cmake
+++ b/Plugins/org.mitk.gui.qt.application/files.cmake
@@ -1,88 +1,93 @@
set(SRC_CPP_FILES
QmitkAbstractDataNodeAction.cpp
+ QmitkApplicationConstants.cpp
QmitkCloseProjectAction.cpp
QmitkDataNodeColorAction.cpp
QmitkDataNodeColorMapAction.cpp
QmitkDataNodeComponentAction.cpp
QmitkDataNodeContextMenu.cpp
QmitkDataNodeGlobalReinitAction.cpp
QmitkDataNodeHideAllAction.cpp
QmitkDataNodeOpacityAction.cpp
QmitkDataNodeOpenInAction.cpp
QmitkDataNodeReinitAction.cpp
QmitkDataNodeRemoveAction.cpp
QmitkDataNodeResetGeometryAction.cpp
QmitkDataNodeShowDetailsAction.cpp
QmitkDataNodeShowSelectedNodesAction.cpp
QmitkDataNodeSurfaceRepresentationAction.cpp
QmitkDataNodeTextureInterpolationAction.cpp
QmitkDataNodeToggleVisibilityAction.cpp
QmitkDefaultDropTargetListener.cpp
QmitkFileExitAction.cpp
QmitkFileOpenAction.cpp
QmitkFileSaveAction.cpp
QmitkUndoAction.cpp
QmitkRedoAction.cpp
QmitkPreferencesDialog.cpp
QmitkStatusBar.cpp
)
set(INTERNAL_CPP_FILES
org_mitk_gui_qt_application_Activator.cpp
QmitkEditorsPreferencePage.cpp
QmitkGeneralPreferencePage.cpp
+ QmitkToolBarsPreferencePage.cpp
QmitkShowPreferencePageHandler.cpp
)
set(MOC_H_FILES
src/QmitkCloseProjectAction.h
src/QmitkDataNodeColorAction.h
src/QmitkDataNodeColorMapAction.h
src/QmitkDataNodeComponentAction.h
src/QmitkDataNodeGlobalReinitAction.h
src/QmitkDataNodeContextMenu.h
src/QmitkDataNodeHideAllAction.h
src/QmitkDataNodeOpacityAction.h
src/QmitkDataNodeOpenInAction.h
src/QmitkDataNodeReinitAction.h
src/QmitkDataNodeRemoveAction.h
src/QmitkDataNodeResetGeometryAction.h
src/QmitkDataNodeShowDetailsAction.h
src/QmitkDataNodeShowSelectedNodesAction.h
src/QmitkDataNodeSurfaceRepresentationAction.h
src/QmitkDataNodeTextureInterpolationAction.h
src/QmitkDataNodeToggleVisibilityAction.h
src/QmitkFileExitAction.h
src/QmitkFileOpenAction.h
src/QmitkFileSaveAction.h
src/QmitkUndoAction.h
src/QmitkRedoAction.h
src/QmitkPreferencesDialog.h
src/internal/org_mitk_gui_qt_application_Activator.h
src/internal/QmitkEditorsPreferencePage.h
src/internal/QmitkGeneralPreferencePage.h
+ src/internal/QmitkToolBarsPreferencePage.h
src/internal/QmitkShowPreferencePageHandler.h
)
set(UI_FILES
src/QmitkPreferencesDialog.ui
+
+ src/internal/QmitkToolBarsPreferencePage.ui
)
set(CACHED_RESOURCE_FILES
plugin.xml
)
set(QRC_FILES
resources/resources.qrc
)
set(CPP_FILES )
foreach(file ${SRC_CPP_FILES})
set(CPP_FILES ${CPP_FILES} src/${file})
endforeach(file ${SRC_CPP_FILES})
foreach(file ${INTERNAL_CPP_FILES})
set(CPP_FILES ${CPP_FILES} src/internal/${file})
endforeach(file ${INTERNAL_CPP_FILES})
diff --git a/Plugins/org.mitk.gui.qt.application/plugin.xml b/Plugins/org.mitk.gui.qt.application/plugin.xml
index 5c19286c7d..13a35d3932 100644
--- a/Plugins/org.mitk.gui.qt.application/plugin.xml
+++ b/Plugins/org.mitk.gui.qt.application/plugin.xml
@@ -1,16 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
<extension point="org.blueberry.ui.preferencePages">
<page id="org.mitk.GeneralPreferencePage" name="General" class="QmitkGeneralPreferencePage"/>
<page id="org.mitk.EditorsPreferencePage" name="Editors" class="QmitkEditorsPreferencePage"/>
+ <page id="org.mitk.ToolBarsPreferencePage" name="Tool Bars" class="QmitkToolBarsPreferencePage">
+ <keywordreference id="org.mitk.ToolBarsPreferencePageKeywords"/>
+ </page>
+ </extension>
+
+ <extension point="org.blueberry.ui.keywords">
+ <keyword id="org.mitk.ToolBarsPreferencePageKeywords" label="tool bars toolbars"/>
</extension>
<extension point="org.blueberry.ui.handlers">
<handler
class="QmitkShowPreferencePageHandler"
commandId="org.blueberry.ui.window.preferences"/>
</extension>
</plugin>
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkAbstractDataNodeAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkAbstractDataNodeAction.cpp
index c706326752..f0e7398335 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkAbstractDataNodeAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkAbstractDataNodeAction.cpp
@@ -1,117 +1,118 @@
/*============================================================================
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 <QmitkAbstractDataNodeAction.h>
#include "mitkIRenderWindowPart.h"
// mitk gui common plugin
#include <mitkDataNodeSelection.h>
// berry
#include <berryIWorkbenchPage.h>
QList<mitk::DataNode::Pointer> AbstractDataNodeAction::GetSelectedNodes(berry::IWorkbenchPartSite::Pointer workbenchPartSite)
{
QList<mitk::DataNode::Pointer> selectedNodes;
if (workbenchPartSite.IsNull())
{
return selectedNodes;
}
berry::ISelection::ConstPointer selection = workbenchPartSite->GetWorkbenchWindow()->GetSelectionService()->GetSelection();
mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast<const mitk::DataNodeSelection>();
if (currentSelection.IsNull() || currentSelection->IsEmpty())
{
return selectedNodes;
}
- selectedNodes = QList<mitk::DataNode::Pointer>::fromStdList(currentSelection->GetSelectedDataNodes());
+ auto nodes = currentSelection->GetSelectedDataNodes();
+ selectedNodes = QList<mitk::DataNode::Pointer>(nodes.begin(), nodes.end());
return selectedNodes;
}
QmitkAbstractDataNodeAction::QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer workbenchPartSite)
{
m_WorkbenchPartSite = workbenchPartSite;
}
QmitkAbstractDataNodeAction::QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite* workbenchPartSite)
{
m_WorkbenchPartSite = berry::IWorkbenchPartSite::Pointer(workbenchPartSite);
}
void QmitkAbstractDataNodeAction::SetDataStorage(mitk::DataStorage* dataStorage)
{
if (m_DataStorage != dataStorage)
{
// set the new data storage
m_DataStorage = dataStorage;
}
}
void QmitkAbstractDataNodeAction::SetSelectedNodes(const QList<mitk::DataNode::Pointer>& selectedNodes)
{
m_SelectedNodes = selectedNodes;
// use the first selected node to initialize the data node actions
InitializeWithDataNode(m_SelectedNodes.front());
}
void QmitkAbstractDataNodeAction::SetBaseRenderer(mitk::BaseRenderer* baseRenderer)
{
if (m_BaseRenderer != baseRenderer)
{
// set the new base renderer
m_BaseRenderer = baseRenderer;
}
}
mitk::BaseRenderer::Pointer QmitkAbstractDataNodeAction::GetBaseRenderer()
{
return m_BaseRenderer.Lock();
}
QList<mitk::DataNode::Pointer> QmitkAbstractDataNodeAction::GetSelectedNodes() const
{
if (!m_SelectedNodes.isEmpty())
{
return m_SelectedNodes;
}
auto workbenchPartSite = m_WorkbenchPartSite.Lock();
if (workbenchPartSite.IsNull())
{
// return empty list of selected nodes
return m_SelectedNodes;
}
// retrieve selection from the workbench selection service
return AbstractDataNodeAction::GetSelectedNodes(workbenchPartSite);
}
mitk::DataNode::Pointer QmitkAbstractDataNodeAction::GetSelectedNode() const
{
QList<mitk::DataNode::Pointer> selectedNodes = GetSelectedNodes();
if (selectedNodes.empty())
{
return nullptr;
}
// no batch action; should only be called with a single node
mitk::DataNode::Pointer dataNode = selectedNodes.front();
if (nullptr == dataNode)
{
return nullptr;
}
return dataNode;
}
diff --git a/Modules/OpenCL/mitkOpenCL.h b/Plugins/org.mitk.gui.qt.application/src/QmitkApplicationConstants.cpp
similarity index 66%
rename from Modules/OpenCL/mitkOpenCL.h
rename to Plugins/org.mitk.gui.qt.application/src/QmitkApplicationConstants.cpp
index 32eea4f91d..2fa48ecae8 100644
--- a/Modules/OpenCL/mitkOpenCL.h
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkApplicationConstants.cpp
@@ -1,23 +1,15 @@
/*============================================================================
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 mitkOpenCL_h
-#define mitkOpenCL_h
+#include "QmitkApplicationConstants.h"
-#if defined (__APPLE__) || defined(MACOSX)
-#include <OpenCL/cl.h>
-#else
-#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
-#include <CL/cl.h>
-#endif
-
-#endif
+const std::string QmitkApplicationConstants::TOOL_BARS_PREFERENCES = "org.mitk.gui.qt.application/toolbars";
diff --git a/Modules/OpenCL/Documentation/doxygen/snippets/mitkOcl-binarythrfilter/gpucode.cl b/Plugins/org.mitk.gui.qt.application/src/QmitkApplicationConstants.h
similarity index 62%
rename from Modules/OpenCL/Documentation/doxygen/snippets/mitkOcl-binarythrfilter/gpucode.cl
rename to Plugins/org.mitk.gui.qt.application/src/QmitkApplicationConstants.h
index 6c0348be42..5f352c0fec 100644
--- a/Modules/OpenCL/Documentation/doxygen/snippets/mitkOcl-binarythrfilter/gpucode.cl
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkApplicationConstants.h
@@ -1,18 +1,19 @@
/*============================================================================
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.
============================================================================*/
-//! [GPUHeader]
-__kernel void ckBinaryThreshold(
- __read_only image3d_t dSource, // input image
- __global uchar* dDest, // output buffer
- int lowerT, int upperT, int outsideVal, int insideVal // parameters
-)
-//! [GPUHeader]
+
+#include <org_mitk_gui_qt_application_Export.h>
+#include <string>
+
+struct MITK_QT_APP QmitkApplicationConstants
+{
+ static const std::string TOOL_BARS_PREFERENCES;
+};
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeContextMenu.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeContextMenu.cpp
index b7e0afe75d..9be4827ce2 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeContextMenu.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeContextMenu.cpp
@@ -1,488 +1,489 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <QmitkDataNodeContextMenu.h>
#include <QmitkCustomVariants.h>
#include <QmitkFileSaveAction.h>
#include <QmitkNodeDescriptorManager.h>
#include <mitkDataNodeSelection.h>
#include <mitkIContextMenuAction.h>
#include <berryAbstractUICTKPlugin.h>
#include <berryIContributor.h>
#include <berryIExtensionRegistry.h>
#include <berryISelectionService.h>
#include <berryPlatform.h>
QmitkDataNodeContextMenu::QmitkDataNodeContextMenu(berry::IWorkbenchPartSite::Pointer workbenchPartSite, QWidget* parent)
: QMenu(parent),
m_Parent(parent),
m_WorkbenchPartSite(workbenchPartSite)
{
this->InitNodeDescriptors();
this->InitDefaultActions();
this->InitExtensionPointActions();
}
QmitkDataNodeContextMenu::~QmitkDataNodeContextMenu()
{
for (auto& descriptorActionPair : m_DescriptorActionList)
descriptorActionPair.first->RemoveAction(descriptorActionPair.second);
}
void QmitkDataNodeContextMenu::SetDataStorage(mitk::DataStorage* dataStorage)
{
m_DataStorage = dataStorage;
for (auto& descriptorActionPair : m_DescriptorActionList)
{
auto dataNodeAction = dynamic_cast<QmitkAbstractDataNodeAction*>(descriptorActionPair.second);
if (nullptr != dataNodeAction)
dataNodeAction->SetDataStorage(dataStorage);
}
}
void QmitkDataNodeContextMenu::SetBaseRenderer(mitk::BaseRenderer* baseRenderer)
{
m_BaseRenderer = baseRenderer;
for (auto& descriptorActionPair : m_DescriptorActionList)
{
auto dataNodeAction = dynamic_cast<QmitkAbstractDataNodeAction*>(descriptorActionPair.second);
if (nullptr != dataNodeAction)
dataNodeAction->SetBaseRenderer(baseRenderer);
}
}
void QmitkDataNodeContextMenu::SetSurfaceDecimation(bool surfaceDecimation)
{
m_SurfaceDecimation = surfaceDecimation;
}
void QmitkDataNodeContextMenu::SetSelectedNodes(const QList<mitk::DataNode::Pointer>& selectedNodes)
{
m_SelectedNodes = selectedNodes;
}
void QmitkDataNodeContextMenu::InitNodeDescriptors()
{
auto nodeDescriptorManager = QmitkNodeDescriptorManager::GetInstance();
m_UnknownDataNodeDescriptor = nodeDescriptorManager->GetUnknownDataNodeDescriptor();
m_ImageDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("Image");
m_MultiComponentImageDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("MultiComponentImage");
m_DiffusionImageDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("DiffusionImage");
m_FiberBundleDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("FiberBundle");
m_PeakImageDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("PeakImage");
m_SegmentDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("Segment");
m_SurfaceDataNodeDescriptor = nodeDescriptorManager->GetDescriptor("Surface");
m_PointSetNodeDescriptor = nodeDescriptorManager->GetDescriptor("PointSet");
m_PlanarLineNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarLine");
m_PlanarCircleNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarCircle");
m_PlanarEllipseNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarEllipse");
m_PlanarAngleNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarAngle");
m_PlanarFourPointAngleNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarFourPointAngle");
m_PlanarRectangleNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarRectangle");
m_PlanarPolygonNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarPolygon");
m_PlanarPathNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarPath");
m_PlanarDoubleEllipseNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarDoubleEllipse");
m_PlanarBezierCurveNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarBezierCurve");
m_PlanarSubdivisionPolygonNodeDescriptor = nodeDescriptorManager->GetDescriptor("PlanarSubdivisionPolygon");
}
void QmitkDataNodeContextMenu::InitDefaultActions()
{
auto workbenchPartSite = m_WorkbenchPartSite.Lock();
m_GlobalReinitAction = new QmitkDataNodeGlobalReinitAction(m_Parent, workbenchPartSite);
m_GlobalReinitAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png"));
m_UnknownDataNodeDescriptor->AddAction(m_GlobalReinitAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_GlobalReinitAction));
m_ReinitAction = new QmitkDataNodeReinitAction(m_Parent, workbenchPartSite);
m_ReinitAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png"));
m_UnknownDataNodeDescriptor->AddAction(m_ReinitAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ReinitAction));
m_ResetGeometryAction = new QmitkDataNodeResetGeometryAction(m_Parent, workbenchPartSite);
m_ResetGeometryAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/Refresh_48.png"));
m_UnknownDataNodeDescriptor->AddAction(m_ResetGeometryAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ResetGeometryAction));
QAction* saveAction = new QmitkFileSaveAction(QIcon(":/org.mitk.gui.qt.datamanager/Save_48.png"), workbenchPartSite->GetWorkbenchWindow());
m_UnknownDataNodeDescriptor->AddAction(saveAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, saveAction));
m_RemoveAction = new QmitkDataNodeRemoveAction(m_Parent, workbenchPartSite);
m_RemoveAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/Remove_48.png"));
m_UnknownDataNodeDescriptor->AddAction(m_RemoveAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_RemoveAction));
m_ShowSelectedNodesAction = new QmitkDataNodeShowSelectedNodesAction(m_Parent, workbenchPartSite);
m_ShowSelectedNodesAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/ShowSelectedNode_48.png"));
m_UnknownDataNodeDescriptor->AddAction(m_ShowSelectedNodesAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ShowSelectedNodesAction));
m_ToggleVisibilityAction = new QmitkDataNodeToggleVisibilityAction(m_Parent, workbenchPartSite);
m_ToggleVisibilityAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/InvertShowSelectedNode_48.png"));
m_UnknownDataNodeDescriptor->AddAction(m_ToggleVisibilityAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ToggleVisibilityAction));
m_ShowDetailsAction = new QmitkDataNodeShowDetailsAction(m_Parent, workbenchPartSite);
m_ShowDetailsAction->setIcon(QIcon(":/org.mitk.gui.qt.datamanager/ShowDataInfo_48.png"));
m_UnknownDataNodeDescriptor->AddAction(m_ShowDetailsAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_ShowDetailsAction));
m_OpacityAction = new QmitkDataNodeOpacityAction(m_Parent, workbenchPartSite);
m_UnknownDataNodeDescriptor->AddAction(m_OpacityAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_UnknownDataNodeDescriptor, m_OpacityAction));
m_ColorAction = new QmitkDataNodeColorAction(m_Parent, workbenchPartSite);
this->AddColorAction(m_ColorAction);
m_ColormapAction = new QmitkDataNodeColorMapAction(m_Parent, workbenchPartSite);
m_ImageDataNodeDescriptor->AddAction(m_ColormapAction);
m_DescriptorActionList.push_back(std::make_pair(m_ImageDataNodeDescriptor, m_ColormapAction));
if (nullptr != m_DiffusionImageDataNodeDescriptor)
{
m_DiffusionImageDataNodeDescriptor->AddAction(m_ColormapAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_DiffusionImageDataNodeDescriptor, m_ColormapAction));
}
m_ComponentAction = new QmitkDataNodeComponentAction(m_Parent, workbenchPartSite);
m_MultiComponentImageDataNodeDescriptor->AddAction(m_ComponentAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_MultiComponentImageDataNodeDescriptor, m_ComponentAction));
if (nullptr != m_DiffusionImageDataNodeDescriptor)
{
m_DiffusionImageDataNodeDescriptor->AddAction(m_ComponentAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_DiffusionImageDataNodeDescriptor, m_ComponentAction));
}
m_TextureInterpolationAction = new QmitkDataNodeTextureInterpolationAction(m_Parent, workbenchPartSite);
m_ImageDataNodeDescriptor->AddAction(m_TextureInterpolationAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_ImageDataNodeDescriptor, m_TextureInterpolationAction));
if (nullptr != m_DiffusionImageDataNodeDescriptor)
{
m_DiffusionImageDataNodeDescriptor->AddAction(m_TextureInterpolationAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_DiffusionImageDataNodeDescriptor, m_TextureInterpolationAction));
}
if (nullptr != m_SegmentDataNodeDescriptor)
{
m_SegmentDataNodeDescriptor->AddAction(m_TextureInterpolationAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_SegmentDataNodeDescriptor, m_TextureInterpolationAction));
}
m_SurfaceRepresentationAction = new QmitkDataNodeSurfaceRepresentationAction(m_Parent, workbenchPartSite);
m_SurfaceDataNodeDescriptor->AddAction(m_SurfaceRepresentationAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_SurfaceDataNodeDescriptor, m_SurfaceRepresentationAction));
}
void QmitkDataNodeContextMenu::InitExtensionPointActions()
{
auto extensionPointService = berry::Platform::GetExtensionRegistry();
auto customMenuConfigs = extensionPointService->GetConfigurationElementsFor("org.mitk.gui.qt.datamanager.contextMenuActions");
DescriptorActionListType descriptorActionList;
m_ConfigElements.clear();
- for (const auto& customMenuConfig : qAsConst(customMenuConfigs))
+ for (const auto& customMenuConfig : std::as_const(customMenuConfigs))
{
auto descriptorName = customMenuConfig->GetAttribute("nodeDescriptorName");
auto actionLabel = customMenuConfig->GetAttribute("label");
auto actionClass = customMenuConfig->GetAttribute("class");
if (descriptorName.isEmpty() || actionLabel.isEmpty() || actionClass.isEmpty())
continue;
auto descriptor = QmitkNodeDescriptorManager::GetInstance()->GetDescriptor(descriptorName);
if (nullptr == descriptor)
{
MITK_WARN << "Cannot add action \"" << actionLabel << "\" to non-existent descriptor \"" << descriptorName << "\".";
continue;
}
QAction* action = nullptr;
auto actionIcon = customMenuConfig->GetAttribute("icon");
if (!actionIcon.isEmpty())
{
QIcon icon = !QFile::exists(actionIcon)
? berry::AbstractUICTKPlugin::ImageDescriptorFromPlugin(customMenuConfig->GetContributor()->GetName(), actionIcon)
: QIcon(actionIcon);
action = new QAction(icon, actionLabel, m_Parent);
}
else
{
action = new QAction(actionLabel, m_Parent);
}
if (nullptr != action)
{
// See T26938. We do not know why but without the lambda function indirection, the
// connection is lost after the content menu was shown for the first time.
connect(action, &QAction::triggered, [action, this]()
{
this->OnExtensionPointActionTriggered(action);
});
m_ConfigElements[action] = customMenuConfig;
descriptorActionList.push_back(std::make_pair(descriptor, action));
}
}
this->AddDescriptorActionList(descriptorActionList);
}
void QmitkDataNodeContextMenu::InitServiceActions()
{
}
void QmitkDataNodeContextMenu::OnContextMenuRequested(const QPoint& /*pos*/)
{
auto workbenchPartSite = m_WorkbenchPartSite.Lock();
if (workbenchPartSite.IsNull())
return;
auto selection = workbenchPartSite->GetWorkbenchWindow()->GetSelectionService()->GetSelection()
.Cast<const mitk::DataNodeSelection>();
if (selection.IsNull() || selection->IsEmpty())
return;
- m_SelectedNodes = QList<mitk::DataNode::Pointer>::fromStdList(selection->GetSelectedDataNodes());
+ auto nodes = selection->GetSelectedDataNodes();
+ m_SelectedNodes = QList<mitk::DataNode::Pointer>(nodes.begin(), nodes.end());
if (!m_SelectedNodes.isEmpty())
{
this->clear();
auto actions = m_SelectedNodes.size() == 1
? this->GetActions(m_SelectedNodes.front())
: this->GetActions(m_SelectedNodes);
for (auto& action : actions)
{
auto dataNodeAction = dynamic_cast<QmitkAbstractDataNodeAction*>(action);
if (nullptr != dataNodeAction)
dataNodeAction->SetSelectedNodes(m_SelectedNodes);
}
this->addActions(actions);
this->popup(QCursor::pos());
}
}
void QmitkDataNodeContextMenu::OnExtensionPointActionTriggered(QAction* action)
{
auto configElementIter = m_ConfigElements.find(action);
if (m_ConfigElements.end() == configElementIter)
{
MITK_WARN << "Associated configuration element for action \"" << action->text() << "\" not found.";
return;
}
auto configElement = configElementIter->second;
auto contextMenuAction = configElement->CreateExecutableExtension<mitk::IContextMenuAction>("class");
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNotNull())
contextMenuAction->SetDataStorage(dataStorage);
if ("QmitkCreatePolygonModelAction" == configElement->GetAttribute("class"))
{
contextMenuAction->SetSmoothed("true" == configElement->GetAttribute("smoothed"));
contextMenuAction->SetDecimated(m_SurfaceDecimation);
}
contextMenuAction->Run(m_SelectedNodes);
}
void QmitkDataNodeContextMenu::AddColorAction(QWidgetAction* colorAction)
{
if (nullptr != m_ImageDataNodeDescriptor)
{
m_ImageDataNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_ImageDataNodeDescriptor, colorAction));
}
if (nullptr != m_MultiComponentImageDataNodeDescriptor)
{
m_MultiComponentImageDataNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_MultiComponentImageDataNodeDescriptor, colorAction));
}
if (nullptr != m_DiffusionImageDataNodeDescriptor)
{
m_DiffusionImageDataNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_DiffusionImageDataNodeDescriptor, colorAction));
}
if (nullptr != m_FiberBundleDataNodeDescriptor)
{
m_FiberBundleDataNodeDescriptor->AddAction(colorAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_FiberBundleDataNodeDescriptor, colorAction));
}
if (nullptr != m_PeakImageDataNodeDescriptor)
{
m_PeakImageDataNodeDescriptor->AddAction(colorAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_PeakImageDataNodeDescriptor, colorAction));
}
if (nullptr != m_SegmentDataNodeDescriptor)
{
m_SegmentDataNodeDescriptor->AddAction(colorAction, false);
m_DescriptorActionList.push_back(std::make_pair(m_SegmentDataNodeDescriptor, colorAction));
}
if (nullptr != m_SurfaceDataNodeDescriptor)
{
m_SurfaceDataNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_SurfaceDataNodeDescriptor, colorAction));
}
if (nullptr != m_PointSetNodeDescriptor)
{
m_PointSetNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PointSetNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarLineNodeDescriptor)
{
m_PlanarLineNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarLineNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarCircleNodeDescriptor)
{
m_PlanarCircleNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarCircleNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarEllipseNodeDescriptor)
{
m_PlanarEllipseNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarEllipseNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarAngleNodeDescriptor)
{
m_PlanarAngleNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarAngleNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarFourPointAngleNodeDescriptor)
{
m_PlanarFourPointAngleNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarFourPointAngleNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarRectangleNodeDescriptor)
{
m_PlanarRectangleNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarRectangleNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarPolygonNodeDescriptor)
{
m_PlanarPolygonNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarPolygonNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarPathNodeDescriptor)
{
m_PlanarPathNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarPathNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarDoubleEllipseNodeDescriptor)
{
m_PlanarDoubleEllipseNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarDoubleEllipseNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarBezierCurveNodeDescriptor)
{
m_PlanarBezierCurveNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarBezierCurveNodeDescriptor, colorAction));
}
if (nullptr != m_PlanarSubdivisionPolygonNodeDescriptor)
{
m_PlanarSubdivisionPolygonNodeDescriptor->AddAction(colorAction, true);
m_DescriptorActionList.push_back(std::make_pair(m_PlanarSubdivisionPolygonNodeDescriptor, colorAction));
}
}
void QmitkDataNodeContextMenu::AddDescriptorActionList(DescriptorActionListType& descriptorActionList)
{
using ListItem = std::pair<QmitkNodeDescriptor*, QAction*>;
std::sort(descriptorActionList.begin(), descriptorActionList.end(), [](const ListItem& left, const ListItem& right) -> bool
{
return left.second->text() < right.second->text();
});
for (auto& descriptorActionPair : descriptorActionList)
{
descriptorActionPair.first->AddAction(descriptorActionPair.second);
m_DescriptorActionList.push_back(descriptorActionPair);
}
}
QList<QAction*> QmitkDataNodeContextMenu::GetActions(const mitk::DataNode* node)
{
QList<QAction*> actions;
for(const auto& descriptorActionPair : m_DescriptorActionList)
{
if (descriptorActionPair.first->CheckNode(node) || "Unknown" == descriptorActionPair.first->GetNameOfClass())
actions.append(descriptorActionPair.second);
}
return actions;
}
QList<QAction*> QmitkDataNodeContextMenu::GetActions(const QList<mitk::DataNode::Pointer>& nodes)
{
QList<QAction*> actions;
for (const auto& descriptorActionPair : m_DescriptorActionList)
{
for (const auto& node : nodes)
{
if (descriptorActionPair.first->CheckNode(node) || "Unknown" == descriptorActionPair.first->GetNameOfClass())
{
auto batchActions = descriptorActionPair.first->GetBatchActions();
if (std::find(batchActions.begin(), batchActions.end(), descriptorActionPair.second) != batchActions.end())
actions.append(descriptorActionPair.second);
break;
}
}
}
return actions;
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeGlobalReinitAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeGlobalReinitAction.cpp
index 7529cc5fbc..5a06815e16 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeGlobalReinitAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeGlobalReinitAction.cpp
@@ -1,81 +1,83 @@
/*============================================================================
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 <QmitkDataNodeGlobalReinitAction.h>
// mitk core
#include <mitkRenderingManager.h>
// mitk gui common plugin
#include <mitkWorkbenchUtil.h>
+#include <QWidget>
+
const QString QmitkDataNodeGlobalReinitAction::ACTION_ID = "org.mitk.gui.qt.application.globalreinitaction";
// namespace that contains the concrete action
namespace GlobalReinitAction
{
void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite, mitk::DataStorage::Pointer dataStorage)
{
auto renderWindow = mitk::WorkbenchUtil::GetRenderWindowPart(workbenchPartSite->GetPage(), mitk::WorkbenchUtil::NONE);
if (nullptr == renderWindow)
{
renderWindow = mitk::WorkbenchUtil::OpenRenderWindowPart(workbenchPartSite->GetPage(), false);
if (nullptr == renderWindow)
{
// no render window available
return;
}
}
mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage);
}
}
QmitkDataNodeGlobalReinitAction::QmitkDataNodeGlobalReinitAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(workbenchPartSite)
{
setText(tr("Global Reinit"));
InitializeAction();
}
QmitkDataNodeGlobalReinitAction::QmitkDataNodeGlobalReinitAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
{
setText(tr("Global Reinit"));
InitializeAction();
}
void QmitkDataNodeGlobalReinitAction::InitializeAction()
{
connect(this, &QmitkDataNodeGlobalReinitAction::triggered, this, &QmitkDataNodeGlobalReinitAction::OnActionTriggered);
}
void QmitkDataNodeGlobalReinitAction::OnActionTriggered(bool /*checked*/)
{
auto workbenchPartSite = m_WorkbenchPartSite.Lock();
if (workbenchPartSite.IsNull())
{
return;
}
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNull())
{
return;
}
GlobalReinitAction::Run(workbenchPartSite, dataStorage);
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeHideAllAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeHideAllAction.cpp
index 128961634a..7ff07a1526 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeHideAllAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeHideAllAction.cpp
@@ -1,73 +1,75 @@
/*============================================================================
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 <QmitkDataNodeHideAllAction.h>
// mitk core
#include <mitkRenderingManager.h>
+#include <QWidget>
+
namespace HideAllAction
{
void Run(const QList<mitk::DataNode::Pointer>& selectedNodes, mitk::BaseRenderer* baseRenderer /*= nullptr*/)
{
if (selectedNodes.empty())
{
return;
}
for (auto& node : selectedNodes)
{
if (node.IsNotNull())
{
node->SetVisibility(false, baseRenderer);
}
}
if (nullptr == baseRenderer)
{
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else
{
mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow());
}
}
}
QmitkDataNodeHideAllAction::QmitkDataNodeHideAllAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(workbenchpartSite)
{
setText(tr("Hide all nodes"));
InitializeAction();
}
QmitkDataNodeHideAllAction::QmitkDataNodeHideAllAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchpartSite))
{
setText(tr("Hide all nodes"));
InitializeAction();
}
void QmitkDataNodeHideAllAction::InitializeAction()
{
connect(this, &QmitkDataNodeHideAllAction::triggered, this, &QmitkDataNodeHideAllAction::OnActionTriggered);
}
void QmitkDataNodeHideAllAction::OnActionTriggered(bool /*checked*/)
{
mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer();
auto selectedNodes = GetSelectedNodes();
HideAllAction::Run(selectedNodes, baseRenderer);
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeReinitAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeReinitAction.cpp
index 622d38362f..b492c2d399 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeReinitAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeReinitAction.cpp
@@ -1,137 +1,139 @@
/*============================================================================
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 <QmitkDataNodeReinitAction.h>
// mitk core
#include <mitkImage.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkRenderingManager.h>
// mitk gui common plugin
#include <mitkWorkbenchUtil.h>
+#include <QWidget>
+
// namespace that contains the concrete action
namespace ReinitAction
{
void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite, mitk::DataStorage::Pointer dataStorage, const QList<mitk::DataNode::Pointer>& selectedNodes /*= QList<mitk::DataNode::Pointer>()*/, mitk::BaseRenderer* baseRenderer /*= nullptr*/)
{
if (selectedNodes.empty())
{
return;
}
if (workbenchPartSite.IsNotNull())
{
auto renderWindow = mitk::WorkbenchUtil::GetRenderWindowPart(workbenchPartSite->GetPage(), mitk::WorkbenchUtil::NONE);
if (nullptr == renderWindow)
{
renderWindow = mitk::WorkbenchUtil::OpenRenderWindowPart(workbenchPartSite->GetPage(), false);
if (nullptr == renderWindow)
{
// no render window available
return;
}
}
}
auto boundingBoxPredicate = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false), baseRenderer));
mitk::DataStorage::SetOfObjects::Pointer nodes = mitk::DataStorage::SetOfObjects::New();
for (const auto& dataNode : selectedNodes)
{
if (boundingBoxPredicate->CheckNode(dataNode))
{
nodes->InsertElement(nodes->Size(), dataNode);
}
}
if (nodes->empty())
{
return;
}
if (1 == nodes->Size()) // Special case: If exactly one ...
{
auto image = dynamic_cast<mitk::Image*>(nodes->ElementAt(0)->GetData());
if (nullptr != image) // ... image is selected, reinit is expected to rectify askew images.
{
if (nullptr == baseRenderer)
{
mitk::RenderingManager::GetInstance()->InitializeViews(image->GetTimeGeometry());
}
else
{
mitk::RenderingManager::GetInstance()->InitializeView(baseRenderer->GetRenderWindow(), image->GetTimeGeometry());
}
return;
}
}
auto boundingGeometry = dataStorage->ComputeBoundingGeometry3D(nodes, "visible", baseRenderer);
if (nullptr == baseRenderer)
{
mitk::RenderingManager::GetInstance()->InitializeViews(boundingGeometry);
}
else
{
mitk::RenderingManager::GetInstance()->InitializeView(baseRenderer->GetRenderWindow(), boundingGeometry);
}
}
}
QmitkDataNodeReinitAction::QmitkDataNodeReinitAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(workbenchpartSite)
{
setText(tr("Reinit"));
InitializeAction();
}
QmitkDataNodeReinitAction::QmitkDataNodeReinitAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchpartSite))
{
setText(tr("Reinit"));
InitializeAction();
}
void QmitkDataNodeReinitAction::InitializeAction()
{
connect(this, &QmitkDataNodeReinitAction::triggered, this, &QmitkDataNodeReinitAction::OnActionTriggered);
}
void QmitkDataNodeReinitAction::OnActionTriggered(bool /*checked*/)
{
auto workbenchPartSite = m_WorkbenchPartSite.Lock();
if (workbenchPartSite.IsNull())
{
return;
}
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNull())
{
return;
}
mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer();
auto selectedNodes = GetSelectedNodes();
ReinitAction::Run(workbenchPartSite, dataStorage, selectedNodes, baseRenderer);
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeResetGeometryAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeResetGeometryAction.cpp
index 49aabdb6f1..34aec1209d 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeResetGeometryAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeResetGeometryAction.cpp
@@ -1,113 +1,115 @@
/*============================================================================
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 <QmitkDataNodeResetGeometryAction.h>
// mitk core
#include <mitkImage.h>
#include <mitkRenderingManager.h>
// mitk gui common plugin
#include <mitkWorkbenchUtil.h>
+#include <QWidget>
+
// namespace that contains the concrete action
namespace ResetGeometryAction
{
void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite, const mitk::TimeGeometry* referenceGeometry, mitk::BaseRenderer* baseRenderer /*= nullptr*/)
{
if (workbenchPartSite.IsNull())
{
return;
}
auto* renderWindowPart = mitk::WorkbenchUtil::GetRenderWindowPart(workbenchPartSite->GetPage(), mitk::WorkbenchUtil::NONE);
if (nullptr == renderWindowPart)
{
renderWindowPart = mitk::WorkbenchUtil::OpenRenderWindowPart(workbenchPartSite->GetPage(), false);
if (nullptr == renderWindowPart)
{
// no render window available
return;
}
}
if (nullptr == referenceGeometry)
{
return;
}
mitk::TimeStepType imageTimeStep = 0;
// store the current position to set it again later, if the camera should not be reset
mitk::Point3D currentPosition = renderWindowPart->GetSelectedPosition();
// store the current time step to set it again later, if the camera should not be reset
auto* renderingManager = mitk::RenderingManager::GetInstance();
const mitk::TimePointType currentTimePoint = renderingManager->GetTimeNavigationController()->GetSelectedTimePoint();
if (referenceGeometry->IsValidTimePoint(currentTimePoint))
{
imageTimeStep = referenceGeometry->TimePointToTimeStep(currentTimePoint);
}
if (nullptr == baseRenderer)
{
renderingManager->InitializeViews(referenceGeometry, mitk::RenderingManager::REQUEST_UPDATE_ALL, false);
}
else
{
renderingManager->InitializeView(baseRenderer->GetRenderWindow(), referenceGeometry, false);
}
renderWindowPart->SetSelectedPosition(currentPosition);
renderingManager->GetTimeNavigationController()->GetStepper()->SetPos(imageTimeStep);
}
} // namespace ResetGeometryAction
QmitkDataNodeResetGeometryAction::QmitkDataNodeResetGeometryAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(workbenchpartSite)
{
this->setText(tr("Reset geometry"));
this->InitializeAction();
}
QmitkDataNodeResetGeometryAction::QmitkDataNodeResetGeometryAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite)
: QmitkDataNodeResetGeometryAction(parent, berry::IWorkbenchPartSite::Pointer(workbenchpartSite))
{
}
void QmitkDataNodeResetGeometryAction::InitializeAction()
{
connect(this, &QmitkDataNodeResetGeometryAction::triggered, this, &QmitkDataNodeResetGeometryAction::OnActionTriggered);
}
void QmitkDataNodeResetGeometryAction::OnActionTriggered(bool /*checked*/)
{
auto workbenchPartSite = m_WorkbenchPartSite.Lock();
if (workbenchPartSite.IsNull())
{
return;
}
auto baseRenderer = this->GetBaseRenderer();
auto selectedNode = this->GetSelectedNode();
mitk::Image::ConstPointer selectedImage = dynamic_cast<mitk::Image*>(selectedNode->GetData());
if (selectedImage.IsNull())
{
return;
}
ResetGeometryAction::Run(workbenchPartSite, selectedImage->GetTimeGeometry(), baseRenderer);
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeShowSelectedNodesAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeShowSelectedNodesAction.cpp
index e42ec1aa42..8c5857c707 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeShowSelectedNodesAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeShowSelectedNodesAction.cpp
@@ -1,70 +1,72 @@
/*============================================================================
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 <QmitkDataNodeShowSelectedNodesAction.h>
// mitk core
#include <mitkRenderingManager.h>
+#include <QWidget>
+
QmitkDataNodeShowSelectedNodesAction::QmitkDataNodeShowSelectedNodesAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(workbenchpartSite)
{
setText(tr("Show only selected nodes"));
InitializeAction();
}
QmitkDataNodeShowSelectedNodesAction::QmitkDataNodeShowSelectedNodesAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchpartSite))
{
setText(tr("Show only selected nodes"));
InitializeAction();
}
void QmitkDataNodeShowSelectedNodesAction::InitializeAction()
{
connect(this, &QmitkDataNodeShowSelectedNodesAction::triggered, this, &QmitkDataNodeShowSelectedNodesAction::OnActionTriggered);
}
void QmitkDataNodeShowSelectedNodesAction::OnActionTriggered(bool /*checked*/)
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNull())
{
return;
}
mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer();
auto selectedNodes = GetSelectedNodes();
auto allNodes = dataStorage->GetAll();
for (auto& node : *allNodes)
{
if (node.IsNotNull() && node->GetData() != nullptr && strcmp(node->GetData()->GetNameOfClass(), "PlaneGeometryData"))
{
node->SetVisibility(selectedNodes.contains(node), baseRenderer);
}
}
if (nullptr == baseRenderer)
{
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else
{
mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow());
}
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeTextureInterpolationAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeTextureInterpolationAction.cpp
index fea8a8598c..b041e59329 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeTextureInterpolationAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeTextureInterpolationAction.cpp
@@ -1,87 +1,89 @@
/*============================================================================
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 <QmitkDataNodeTextureInterpolationAction.h>
// mitk core
#include <mitkRenderingManager.h>
+#include <QWidget>
+
QmitkDataNodeTextureInterpolationAction::QmitkDataNodeTextureInterpolationAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(workbenchpartSite)
{
setText(tr("Texture Interpolation"));
InitializeAction();
}
QmitkDataNodeTextureInterpolationAction::QmitkDataNodeTextureInterpolationAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchpartSite))
{
setText(tr("Texture Interpolation"));
InitializeAction();
}
void QmitkDataNodeTextureInterpolationAction::InitializeAction()
{
setCheckable(true);
connect(this, &QmitkDataNodeTextureInterpolationAction::toggled, this, &QmitkDataNodeTextureInterpolationAction::OnActionToggled);
connect(this, &QmitkDataNodeTextureInterpolationAction::changed, this, &QmitkDataNodeTextureInterpolationAction::OnActionChanged);
}
void QmitkDataNodeTextureInterpolationAction::InitializeWithDataNode(const mitk::DataNode* dataNode)
{
if (nullptr == dataNode)
{
setChecked(false);
return;
}
mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer();
bool textureInterpolation = false;
dataNode->GetBoolProperty("texture interpolation", textureInterpolation, baseRenderer);
setChecked(textureInterpolation);
}
void QmitkDataNodeTextureInterpolationAction::OnActionToggled(bool checked)
{
auto dataNode = GetSelectedNode();
if (dataNode.IsNull())
{
return;
}
mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer();
dataNode->SetBoolProperty("texture interpolation", checked, baseRenderer);
if (nullptr == baseRenderer)
{
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else
{
mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow());
}
}
void QmitkDataNodeTextureInterpolationAction::OnActionChanged()
{
auto dataNode = GetSelectedNode();
if (dataNode.IsNull())
{
return;
}
InitializeWithDataNode(dataNode);
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeToggleVisibilityAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeToggleVisibilityAction.cpp
index d5aa7de5b4..51c9684afe 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeToggleVisibilityAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkDataNodeToggleVisibilityAction.cpp
@@ -1,102 +1,104 @@
/*============================================================================
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 <QmitkDataNodeToggleVisibilityAction.h>
#include <QmitkDataNodeGlobalReinitAction.h>
// mitk core
#include <mitkRenderingManager.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
+#include <QWidget>
+
// namespace that contains the concrete action
namespace ToggleVisibilityAction
{
void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite, mitk::DataStorage::Pointer dataStorage, const QList<mitk::DataNode::Pointer>& selectedNodes /*= QList<mitk::DataNode::Pointer>()*/, mitk::BaseRenderer* baseRenderer /*= nullptr*/)
{
bool isVisible;
for (auto& node : selectedNodes)
{
if (node.IsNotNull())
{
isVisible = false;
node->GetBoolProperty("visible", isVisible, baseRenderer);
node->SetVisibility(!isVisible, baseRenderer);
}
}
auto* prefService = mitk::CoreServices::GetPreferencesService();
auto* preferences = prefService->GetSystemPreferences()->Node(QmitkDataNodeGlobalReinitAction::ACTION_ID.toStdString());
bool globalReinit = preferences->GetBool("Call global reinit if node visibility is changed", false);
if (globalReinit)
{
GlobalReinitAction::Run(workbenchPartSite, dataStorage);
}
else
{
if (nullptr == baseRenderer)
{
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else
{
mitk::RenderingManager::GetInstance()->RequestUpdate(baseRenderer->GetRenderWindow());
}
}
}
}
QmitkDataNodeToggleVisibilityAction::QmitkDataNodeToggleVisibilityAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(workbenchpartSite)
{
setText(tr("Toggle visibility"));
InitializeAction();
}
QmitkDataNodeToggleVisibilityAction::QmitkDataNodeToggleVisibilityAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchpartSite)
: QAction(parent)
, QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchpartSite))
{
setText(tr("Toggle visibility"));
InitializeAction();
}
void QmitkDataNodeToggleVisibilityAction::InitializeAction()
{
connect(this, &QmitkDataNodeToggleVisibilityAction::triggered, this, &QmitkDataNodeToggleVisibilityAction::OnActionTriggered);
}
void QmitkDataNodeToggleVisibilityAction::OnActionTriggered(bool /*checked*/)
{
auto workbenchPartSite = m_WorkbenchPartSite.Lock();
if (workbenchPartSite.IsNull())
{
return;
}
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNull())
{
return;
}
mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer();
auto dataNodes = GetSelectedNodes();
ToggleVisibilityAction::Run(workbenchPartSite, dataStorage, dataNodes, baseRenderer);
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp
index 58460a6b40..45448868cb 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp
@@ -1,275 +1,275 @@
/*============================================================================
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 "QmitkFileSaveAction.h"
#include "internal/org_mitk_gui_qt_application_Activator.h"
#include <mitkWorkbenchUtil.h>
#include <mitkDataNodeSelection.h>
#include <mitkIDataStorageService.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
#include <berryISelectionService.h>
#include <berryINullSelectionListener.h>
#include <QmitkIOUtil.h>
#include <QFileDialog>
#include <QMessageBox>
namespace
{
mitk::DataStorage::Pointer GetDataStorage()
{
auto context = mitk::org_mitk_gui_qt_application_Activator::GetContext();
if (nullptr == context)
return nullptr;
auto dataStorageServiceReference = context->getServiceReference<mitk::IDataStorageService>();
if (!dataStorageServiceReference)
return nullptr;
auto dataStorageService = context->getService<mitk::IDataStorageService>(dataStorageServiceReference);
if (nullptr == dataStorageService)
return nullptr;
auto dataStorageReference = dataStorageService->GetDataStorage();
if (dataStorageReference.IsNull())
return nullptr;
return dataStorageReference->GetDataStorage();
}
QString GetParentPath(mitk::DataNode::Pointer dataNode)
{
if (dataNode.IsNull())
return "";
auto dataStorage = GetDataStorage();
if (dataStorage.IsNull())
return "";
auto sources = dataStorage->GetSources(dataNode);
if (sources.IsNull() || sources->empty())
return "";
const auto &parentNode = sources->front();
if (parentNode.IsNull())
return "";
auto data = parentNode->GetData();
if (nullptr != data)
{
auto pathProperty = data->GetConstProperty("path");
if (pathProperty.IsNotNull())
return QFileInfo(QString::fromStdString(pathProperty->GetValueAsString())).canonicalPath();
}
return GetParentPath(parentNode);
}
}
class QmitkFileSaveActionPrivate
{
private:
void HandleSelectionChanged(const berry::IWorkbenchPart::Pointer& /*part*/,
const berry::ISelection::ConstPointer& selection)
{
this->SetEnabled(selection);
}
QScopedPointer<berry::ISelectionListener> m_SelectionListener;
public:
QmitkFileSaveActionPrivate()
: m_SelectionListener(new berry::NullSelectionChangedAdapter<QmitkFileSaveActionPrivate>(
this, &QmitkFileSaveActionPrivate::HandleSelectionChanged))
{
}
~QmitkFileSaveActionPrivate()
{
auto window = m_Window.Lock();
if (window.IsNotNull())
{
window->GetSelectionService()->RemoveSelectionListener(m_SelectionListener.data());
}
}
void Init(berry::IWorkbenchWindow* window, QAction* action)
{
m_Window = berry::IWorkbenchWindow::Pointer(window);
m_Action = action;
m_Action->setText("&Save...");
m_Action->setToolTip("Save data objects (images, surfaces,...)");
berry::ISelectionService* selectionService = m_Window.Lock()->GetSelectionService();
SetEnabled(selectionService->GetSelection());
selectionService->AddSelectionListener(m_SelectionListener.data());
QObject::connect(m_Action, SIGNAL(triggered(bool)), m_Action, SLOT(Run()));
}
mitk::IPreferences* GetPreferences() const
{
auto* prefService = mitk::CoreServices::GetPreferencesService();
return prefService != nullptr
? prefService->GetSystemPreferences()->Node("/General")
: nullptr;
}
QString GetLastFileSavePath() const
{
auto* prefs = GetPreferences();
return prefs != nullptr
? QString::fromStdString(prefs->Get("LastFileSavePath", ""))
: QString();
}
void SetLastFileSavePath(const QString& path) const
{
auto* prefs = GetPreferences();
if (prefs != nullptr)
{
prefs->Put("LastFileSavePath", path.toStdString());
prefs->Flush();
}
}
void SetEnabled(berry::ISelection::ConstPointer selection)
{
mitk::DataNodeSelection::ConstPointer nodeSelection = selection.Cast<const mitk::DataNodeSelection>();
if (nodeSelection.IsNotNull() && !selection->IsEmpty())
{
bool enable = false;
std::list<mitk::DataNode::Pointer> dataNodes = nodeSelection->GetSelectedDataNodes();
for (std::list<mitk::DataNode::Pointer>::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter)
{
if ((*nodeIter)->GetData() != nullptr)
{
enable = true;
break;
}
}
m_Action->setEnabled(enable);
}
else
{
m_Action->setEnabled(false);
}
}
berry::IWorkbenchWindow::WeakPtr m_Window;
QAction* m_Action;
};
QmitkFileSaveAction::QmitkFileSaveAction(berry::IWorkbenchWindow::Pointer window)
: QAction(tr("Save..."))
, d(new QmitkFileSaveActionPrivate)
{
d->Init(window.GetPointer(), this);
}
QmitkFileSaveAction::QmitkFileSaveAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window)
: QAction(tr("Save..."))
, d(new QmitkFileSaveActionPrivate)
{
d->Init(window.GetPointer(), this);
setIcon(icon);
}
QmitkFileSaveAction::QmitkFileSaveAction(const QIcon& icon, berry::IWorkbenchWindow* window)
: QAction(tr("Save..."))
, d(new QmitkFileSaveActionPrivate)
{
d->Init(window, this);
setIcon(icon);
}
QmitkFileSaveAction::~QmitkFileSaveAction()
{
}
void QmitkFileSaveAction::Run()
{
// get the list of selected base data objects
mitk::DataNodeSelection::ConstPointer selection = d->m_Window.Lock()->GetSelectionService()->GetSelection().Cast<const mitk::DataNodeSelection>();
if (selection.IsNull() || selection->IsEmpty())
{
MITK_ERROR << "Assertion failed: data node selection is nullptr or empty";
return;
}
std::list<mitk::DataNode::Pointer> dataNodes = selection->GetSelectedDataNodes();
std::vector<const mitk::BaseData*> data;
QStringList names;
for (std::list<mitk::DataNode::Pointer>::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter)
{
data.push_back((*nodeIter)->GetData());
std::string name;
(*nodeIter)->GetStringProperty("name", name);
names.push_back(QString::fromStdString(name));
}
QString path;
if (1 == data.size())
{
if (nullptr != data[0])
{
auto pathProperty = data[0]->GetConstProperty("path");
if (pathProperty.IsNotNull())
path = QFileInfo(QString::fromStdString(pathProperty->GetValueAsString())).canonicalPath();
}
if (path.isEmpty())
path = GetParentPath(dataNodes.front());
}
if (path.isEmpty())
path = d->GetLastFileSavePath();
try
{
auto setPathProperty = true;
- auto fileNames = QmitkIOUtil::Save(data, names, path, d->m_Action->parentWidget(), setPathProperty);
+ auto fileNames = QmitkIOUtil::Save(data, names, path, qobject_cast<QWidget*>(d->m_Action->parent()), setPathProperty);
if (!fileNames.empty())
d->SetLastFileSavePath(QFileInfo(fileNames.back()).absolutePath());
}
catch (const mitk::Exception& e)
{
MITK_INFO << e;
return;
}
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h
index 13f3301efb..56f245b04e 100644
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.h
@@ -1,62 +1,62 @@
/*============================================================================
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 QmitkPreferencesDialog_h
#define QmitkPreferencesDialog_h
#include <org_mitk_gui_qt_application_Export.h>
#include <QDialog>
#include <QScopedPointer>
class QmitkPreferencesDialogPrivate;
/**
* \ingroup org_mitk_gui_qt_application
*/
class MITK_QT_APP QmitkPreferencesDialog : public QDialog
{
Q_OBJECT
public:
- QmitkPreferencesDialog(QWidget * parent = nullptr, Qt::WindowFlags f = nullptr);
+ QmitkPreferencesDialog(QWidget * parent = nullptr, Qt::WindowFlags f = {});
~QmitkPreferencesDialog() override;
void SetSelectedPage(const QString& id);
protected slots:
void OnDialogAccepted();
void OnDialogRejected();
void OnKeywordTextChanged(const QString & s);
void OnKeywordEditingFinished();
void OnPreferencesTreeItemSelectionChanged();
protected:
//bool eventFilter(QObject *obj, QEvent *event);
void UpdateTree();
///
/// Saves all preferencepages.
///
void SavePreferences();
QScopedPointer<QmitkPreferencesDialogPrivate> d;
};
#endif
diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.cpp
index 9329824efc..ec20534007 100755
--- a/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/QmitkStatusBar.cpp
@@ -1,89 +1,89 @@
/*============================================================================
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 "QmitkStatusBar.h"
-#include <qmainwindow.h>
-#include <qstatusbar.h>
-#include <qapplication.h>
-#include <qdesktopwidget.h>
+#include <QMainWindow>
+#include <QScreen>
+#include <QStatusBar>
+#include <QGuiApplication>
#include <mitkStatusBar.h>
#include <itkObjectFactory.h>
/**
* Display the text in the statusbar of the application
*/
void QmitkStatusBar::DisplayText(const char* t)
{
m_StatusBar->showMessage(t);
// TODO bug #1357
//qApp->processEvents(); // produces crashes!
}
/**
* Display the text in the statusbar of the application for ms seconds
*/
void QmitkStatusBar::DisplayText(const char* t, int ms)
{
m_StatusBar->showMessage(t, ms);
// TODO bug #1357
//qApp->processEvents(); // produces crashes!
}
/**
* Show the grey value text in the statusbar
*/
void QmitkStatusBar::DisplayGreyValueText(const char* t)
{
QString text(t);
m_GreyValueLabel->setText(text);
}
/**
* Clear the text in the StatusBar
*/
void QmitkStatusBar::Clear()
{
if (m_StatusBar != nullptr)
m_StatusBar->clearMessage();
// TODO bug #1357
//qApp->processEvents(); // produces crashes!
}
/**
* enable or disable the QSizeGrip
*/
void QmitkStatusBar::SetSizeGripEnabled(bool enable)
{
if (m_StatusBar != nullptr)
m_StatusBar->setSizeGripEnabled(enable);
}
QmitkStatusBar::QmitkStatusBar(QStatusBar* instance)
:StatusBarImplementation()
{
m_StatusBar = instance;
- m_GreyValueLabel = new QLabel(m_StatusBar,nullptr);
- int xResolution = QApplication::desktop()->screenGeometry(0).width()-100;
+ m_GreyValueLabel = new QLabel(m_StatusBar);
+ int xResolution = QGuiApplication::primaryScreen()->geometry().width()-100;
m_GreyValueLabel->setMaximumSize(QSize(xResolution,50));
m_GreyValueLabel->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Fixed);
m_StatusBar->addPermanentWidget(m_GreyValueLabel);
mitk::StatusBar::SetImplementation(this);
}
QmitkStatusBar::~QmitkStatusBar()
{
}
diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.cpp
new file mode 100644
index 0000000000..df04dfe6f3
--- /dev/null
+++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.cpp
@@ -0,0 +1,190 @@
+/*============================================================================
+
+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 "QmitkToolBarsPreferencePage.h"
+#include <ui_QmitkToolBarsPreferencePage.h>
+
+#include <mitkCoreServices.h>
+#include <mitkIPreferencesService.h>
+#include <mitkIPreferences.h>
+
+#include <QmitkApplicationConstants.h>
+
+#include <berryPlatformUI.h>
+
+#include <QMainWindow>
+#include <QToolBar>
+
+namespace
+{
+ mitk::IPreferences* GetPreferences()
+ {
+ auto prefService = mitk::CoreServices::GetPreferencesService();
+ return prefService->GetSystemPreferences()->Node(QmitkApplicationConstants::TOOL_BARS_PREFERENCES);
+ }
+
+ // Get views as multimap with categories as keys.
+ //
+ // Exclude views without category and categories that contain a literal '.', e.g.
+ // "org.blueberry.ui" or "org.mitk.views.general", as they typically do not have
+ // a corresponding tool bar.
+ std::multimap<QString, berry::IViewDescriptor::Pointer> GetViews()
+ {
+ std::multimap<QString, berry::IViewDescriptor::Pointer> result;
+
+ const auto workbench = berry::PlatformUI::GetWorkbench();
+ const auto viewRegistry = workbench->GetViewRegistry();
+ const auto views = viewRegistry->GetViews();
+
+ for (auto view : views)
+ {
+ QString category;
+
+ if (auto categoryPath = view->GetCategoryPath(); !categoryPath.isEmpty())
+ category = categoryPath.back();
+
+ if (!category.isEmpty() && !category.contains('.'))
+ result.emplace(category, view);
+ }
+
+ return result;
+ }
+
+ // Get all toolbars of all (typically one) Workbench windows.
+ std::vector<QToolBar*> GetToolBars()
+ {
+ std::vector<QToolBar*> result;
+
+ const auto* workbench = berry::PlatformUI::GetWorkbench();
+ auto workbenchWindows = workbench->GetWorkbenchWindows();
+
+ for (auto workbenchWindow : workbenchWindows)
+ {
+ if (auto shell = workbenchWindow->GetShell(); shell.IsNotNull())
+ {
+ if (const auto* mainWindow = qobject_cast<QMainWindow*>(shell->GetControl()); mainWindow != nullptr)
+ {
+ for (auto child : mainWindow->children())
+ {
+ if (auto toolBar = qobject_cast<QToolBar*>(child); toolBar != nullptr)
+ result.push_back(toolBar);
+ }
+ }
+ }
+ }
+
+ return result;
+ }
+
+ // Find a toolbar by object name and apply visibility.
+ bool ApplyVisibility(const std::vector<QToolBar*>& toolBars, const QString& name, bool isVisible)
+ {
+ auto it = std::find_if(toolBars.cbegin(), toolBars.cend(), [&name](const QToolBar* toolBar) {
+ return toolBar->objectName() == name;
+ });
+
+ if (it != toolBars.cend())
+ {
+ (*it)->setVisible(isVisible);
+ return true;
+ }
+
+ return false;
+ }
+}
+
+QmitkToolBarsPreferencePage::QmitkToolBarsPreferencePage()
+ : m_Ui(new Ui::QmitkToolBarsPreferencePage),
+ m_Control(nullptr)
+{
+}
+
+QmitkToolBarsPreferencePage::~QmitkToolBarsPreferencePage()
+{
+}
+
+void QmitkToolBarsPreferencePage::Init(berry::IWorkbench::Pointer)
+{
+}
+
+void QmitkToolBarsPreferencePage::CreateQtControl(QWidget* parent)
+{
+ m_Control = new QWidget(parent);
+
+ m_Ui->setupUi(m_Control);
+
+ const auto views = GetViews();
+
+ for (auto category = views.cbegin(), end = views.cend(); category != end; category = views.upper_bound(category->first))
+ {
+ auto categoryItem = new QTreeWidgetItem;
+ categoryItem->setText(0, category->first);
+ categoryItem->setCheckState(0, Qt::Checked);
+
+ const auto range = views.equal_range(category->first);
+
+ for (auto view = range.first; view != range.second; ++view)
+ {
+ auto viewItem = new QTreeWidgetItem;
+ viewItem->setText(0, view->second->GetLabel());
+
+ categoryItem->addChild(viewItem);
+ }
+
+ m_Ui->treeWidget->addTopLevelItem(categoryItem);
+ }
+
+ this->Update();
+}
+
+QWidget* QmitkToolBarsPreferencePage::GetQtControl() const
+{
+ return m_Control;
+}
+
+bool QmitkToolBarsPreferencePage::PerformOk()
+{
+ auto prefs = GetPreferences();
+ const auto toolBars = GetToolBars();
+
+ for (int i = 0, count = m_Ui->treeWidget->topLevelItemCount(); i < count; ++i)
+ {
+ const auto* item = m_Ui->treeWidget->topLevelItem(i);
+ const auto category = item->text(0);
+ const bool isVisible = item->checkState(0) == Qt::Checked;
+
+ prefs->PutBool(category.toStdString(), isVisible);
+
+ if (!ApplyVisibility(toolBars, category, isVisible))
+ MITK_WARN << "Could not find tool bar for category \"" << category << "\" to set its visibility!";
+ }
+
+ return true;
+}
+
+void QmitkToolBarsPreferencePage::PerformCancel()
+{
+}
+
+void QmitkToolBarsPreferencePage::Update()
+{
+ const auto prefs = GetPreferences();
+
+ for (int i = 0, count = m_Ui->treeWidget->topLevelItemCount(); i < count; ++i)
+ {
+ auto item = m_Ui->treeWidget->topLevelItem(i);
+ const auto category = item->text(0).toStdString();
+ const bool isVisible = prefs->GetBool(category, true);
+
+ item->setCheckState(0, isVisible ? Qt::Checked : Qt::Unchecked);
+ }
+}
diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.h
similarity index 64%
copy from Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h
copy to Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.h
index 64e2162497..e210d3b634 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h
+++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.h
@@ -1,47 +1,44 @@
/*============================================================================
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 QmitkAppInstancesPreferencePage_h
-#define QmitkAppInstancesPreferencePage_h
+#ifndef QmitkToolBarsPreferencePage_h
+#define QmitkToolBarsPreferencePage_h
#include <berryIQtPreferencePage.h>
-#include <ui_QmitkAppInstancesPreferencePage.h>
-
-class QmitkAppInstancesPreferencePage : public QObject, public berry::IQtPreferencePage
+namespace Ui
{
+ class QmitkToolBarsPreferencePage;
+}
+class QmitkToolBarsPreferencePage : public QObject, public berry::IQtPreferencePage
+{
Q_OBJECT
Q_INTERFACES(berry::IPreferencePage)
public:
-
- QmitkAppInstancesPreferencePage();
- QmitkAppInstancesPreferencePage(const QmitkAppInstancesPreferencePage& other);
+ QmitkToolBarsPreferencePage();
+ ~QmitkToolBarsPreferencePage() override;
void Init(berry::IWorkbench::Pointer workbench) override;
-
void CreateQtControl(QWidget* parent) override;
QWidget* GetQtControl() const override;
-
bool PerformOk() override;
void PerformCancel() override;
void Update() override;
private:
-
- Ui::QmitkAppInstancesPreferencePage controls;
- QWidget* mainWidget;
+ Ui::QmitkToolBarsPreferencePage* m_Ui;
+ QWidget* m_Control;
};
#endif
diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.ui b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.ui
new file mode 100644
index 0000000000..56d6c9c062
--- /dev/null
+++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkToolBarsPreferencePage.ui
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>QmitkToolBarsPreferencePage</class>
+ <widget class="QWidget" name="QmitkToolBarsPreferencePage">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>640</width>
+ <height>480</height>
+ </rect>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QTreeWidget" name="treeWidget">
+ <property name="editTriggers">
+ <set>QAbstractItemView::NoEditTriggers</set>
+ </property>
+ <property name="showDropIndicator" stdset="0">
+ <bool>false</bool>
+ </property>
+ <property name="selectionMode">
+ <enum>QAbstractItemView::NoSelection</enum>
+ </property>
+ <property name="headerHidden">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp
index 38ce44d27b..5af3e84819 100644
--- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp
+++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp
@@ -1,52 +1,54 @@
/*============================================================================
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_application_Activator.h"
#include "QmitkGeneralPreferencePage.h"
#include "QmitkEditorsPreferencePage.h"
+#include "QmitkToolBarsPreferencePage.h"
#include <QmitkRegisterClasses.h>
#include "QmitkShowPreferencePageHandler.h"
#include <usModuleInitialization.h>
US_INITIALIZE_MODULE
namespace mitk
{
ctkPluginContext* org_mitk_gui_qt_application_Activator::m_Context = nullptr;
void org_mitk_gui_qt_application_Activator::start(ctkPluginContext* context)
{
m_Context = context;
BERRY_REGISTER_EXTENSION_CLASS(QmitkGeneralPreferencePage, context)
BERRY_REGISTER_EXTENSION_CLASS(QmitkEditorsPreferencePage, context)
+ BERRY_REGISTER_EXTENSION_CLASS(QmitkToolBarsPreferencePage, context)
BERRY_REGISTER_EXTENSION_CLASS(QmitkShowPreferencePageHandler, context)
QmitkRegisterClasses();
}
void org_mitk_gui_qt_application_Activator::stop(ctkPluginContext* context)
{
Q_UNUSED(context)
m_Context = nullptr;
}
ctkPluginContext* org_mitk_gui_qt_application_Activator::GetContext()
{
return m_Context;
}
}
diff --git a/Plugins/org.mitk.gui.qt.chartExample/src/internal/QmitkChartExampleView.cpp b/Plugins/org.mitk.gui.qt.chartExample/src/internal/QmitkChartExampleView.cpp
index 1adeb0b41b..82dd8e35f3 100644
--- a/Plugins/org.mitk.gui.qt.chartExample/src/internal/QmitkChartExampleView.cpp
+++ b/Plugins/org.mitk.gui.qt.chartExample/src/internal/QmitkChartExampleView.cpp
@@ -1,452 +1,452 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
// Blueberry
#include <berryIQtStyleManager.h>
#include <berryWorkbenchPlugin.h>
// Qmitk
#include "QmitkChartExampleView.h"
#include <QmitkChartxyData.h>
const std::string QmitkChartExampleView::VIEW_ID = "org.mitk.views.qmitkchartexample";
void QmitkChartExampleView::SetFocus()
{
m_Controls.m_buttonCreateChart->setFocus();
}
void QmitkChartExampleView::CreateQtPartControl(QWidget *parent)
{
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi(parent);
CreateConnectionsForGUIElements();
connect(m_Controls.m_comboBoxChartType, &QComboBox::currentTextChanged, this, &QmitkChartExampleView::AdaptDataGUI);
m_Controls.m_lineEditDataXVector->setText("0;1;2;3;4;5;6;7;8;9");
m_Controls.m_lineEditDataYVector->setText("0;1;2;3;4;5;6;7;8;9");
m_Controls.m_lineEditDataLabel->setText("Test");
m_Controls.m_lineEditXAxisLabel->setText("X-Axis");
m_Controls.m_lineEditYAxisLabel->setText("Y-Axis");
m_Controls.m_lineEditTitle->setText("Title");
m_Controls.m_labelPieData->setVisible(false);
m_Controls.m_lineEditPieDataLabel->setVisible(false);
m_Controls.m_groupBoxErrors->setVisible(false);
m_Controls.m_groupBoxXErrors->setVisible(false);
m_Controls.m_groupBoxYErrors->setVisible(false);
m_Controls.m_doubleSpinBox_maxZoomX->setValue(10);
m_Controls.m_doubleSpinBox_maxZoomY->setValue(10);
m_AxisScaleNameToAxisScaleType.emplace("linear", QmitkChartWidget::AxisScale::linear);
m_AxisScaleNameToAxisScaleType.emplace("logarithmic", QmitkChartWidget::AxisScale::log);
m_LegendPositionNameToLegendPositionType.emplace("bottom middle", QmitkChartWidget::LegendPosition::bottomMiddle);
m_LegendPositionNameToLegendPositionType.emplace("bottom right", QmitkChartWidget::LegendPosition::bottomRight);
m_LegendPositionNameToLegendPositionType.emplace("top right", QmitkChartWidget::LegendPosition::topRight);
m_LegendPositionNameToLegendPositionType.emplace("top left", QmitkChartWidget::LegendPosition::topLeft);
m_LegendPositionNameToLegendPositionType.emplace("middle right", QmitkChartWidget::LegendPosition::middleRight);
}
void QmitkChartExampleView::CreateConnectionsForGUIElements()
{
connect(m_Controls.m_buttonCreateChart, &QPushButton::clicked, this, &QmitkChartExampleView::CreateChart);
connect(m_Controls.m_buttonUpdateData, &QPushButton::clicked, this, &QmitkChartExampleView::UpdateData);
connect(m_Controls.m_buttonClearChart, &QPushButton::clicked, this, &QmitkChartExampleView::ClearChart);
connect(m_Controls.m_buttonAddData, &QPushButton::clicked, this, &QmitkChartExampleView::AddData);
connect(m_Controls.m_comboBoxExistingData, &QComboBox::currentTextChanged, this, &QmitkChartExampleView::UpdateSelectedData);
connect(m_Controls.m_checkBoxEnableErrors, &QCheckBox::toggled, this, &QmitkChartExampleView::ShowErrorOptions);
connect(m_Controls.m_checkBoxEnableXErrors, &QCheckBox::toggled, this, &QmitkChartExampleView::ShowXErrorOptions);
connect(m_Controls.m_checkBoxEnableYErrors, &QCheckBox::toggled, this, &QmitkChartExampleView::ShowYErrorOptions);
connect(m_Controls.m_doubleSpinBox_minZoomX, &QSpinBox::editingFinished, this, &QmitkChartExampleView::AdaptZoomX);
connect(m_Controls.m_doubleSpinBox_maxZoomX, &QSpinBox::editingFinished, this, &QmitkChartExampleView::AdaptZoomX);
connect(m_Controls.m_doubleSpinBox_minZoomY, &QSpinBox::editingFinished, this, &QmitkChartExampleView::AdaptZoomY);
connect(m_Controls.m_doubleSpinBox_maxZoomY, &QSpinBox::editingFinished, this, &QmitkChartExampleView::AdaptZoomY);
connect(m_Controls.m_comboBoxLegendPosition, &QComboBox::currentTextChanged, this, &QmitkChartExampleView::OnLegendPositionChanged);
connect(m_Controls.m_lineEditTitle, &QLineEdit::editingFinished, this, &QmitkChartExampleView::OnTitleChanged);
connect(m_Controls.m_lineEditXAxisLabel, &QLineEdit::editingFinished, this, &QmitkChartExampleView::OnXAxisLabelChanged);
connect(m_Controls.m_lineEditYAxisLabel, &QLineEdit::editingFinished, this, &QmitkChartExampleView::OnYAxisLabelChanged);
connect(m_Controls.m_comboBoxYAxisScale, &QComboBox::currentTextChanged, this, &QmitkChartExampleView::OnYAxisScaleChanged);
connect(m_Controls.m_checkBoxShowLegend, &QCheckBox::stateChanged, this, &QmitkChartExampleView::OnShowLegendChanged);
connect(m_Controls.m_checkBoxStackedData, &QCheckBox::stateChanged, this, &QmitkChartExampleView::OnStackedDataChanged);
connect(m_Controls.m_checkBoxShowDataPoints, &QCheckBox::stateChanged, this, &QmitkChartExampleView::OnShowDataPointsChanged);
connect(m_Controls.m_checkBoxShowSubchart, &QCheckBox::stateChanged, this, &QmitkChartExampleView::OnShowSubchartChanged);
}
void QmitkChartExampleView::AddData()
{
QString lineEditDataX = m_Controls.m_lineEditDataXVector->text();
QString lineEditDataY = m_Controls.m_lineEditDataYVector->text();
auto dataX = ConvertToDoubleVector(lineEditDataX);
auto dataY = ConvertToDoubleVector(lineEditDataY);
auto dataXandY = CreatePairList(dataX, dataY);
QString data = QString::fromStdString(ConvertToText(dataXandY));
std::string dataLabel = m_Controls.m_lineEditDataLabel->text().toStdString();
std::string chartTypeAsString = m_Controls.m_comboBoxChartType->currentText().toStdString();
std::string chartColorAsString = m_Controls.m_comboBoxColor->currentText().toStdString();
std::string chartLineStyleAsString = m_Controls.m_comboBoxLineStyle->currentText().toStdString();
std::string pieLabelsAsString = m_Controls.m_lineEditPieDataLabel->text().toStdString();
if (std::find(labelStorage.begin(), labelStorage.end(), dataLabel) != labelStorage.end())
{
m_Controls.m_labelInfo->setText("This data already exists");
m_Controls.m_labelInfo->setStyleSheet("color: red;");
return;
}
if (dataX.size() != dataY.size())
{
m_Controls.m_labelInfo->setText("Data x and y size have to be equal");
m_Controls.m_labelInfo->setStyleSheet("color: red;");
return;
}
labelStorage.push_back(dataLabel);
m_Controls.m_Chart->AddChartExampleData(dataXandY, dataLabel, chartTypeAsString, chartColorAsString, chartLineStyleAsString, pieLabelsAsString);
m_Controls.m_comboBoxExistingData->addItem(m_Controls.m_lineEditDataLabel->text());
if (m_Controls.m_checkBoxEnableErrors->isChecked())
{
if (m_Controls.m_checkBoxEnableXErrors->isChecked())
{
auto errorsPlus = ConvertToDoubleVector(m_Controls.m_lineEditXErrorPlus->text());
auto errorsMinus = ConvertToDoubleVector(m_Controls.m_lineEditXErrorMinus->text());
m_Controls.m_Chart->SetXErrorBars(m_Controls.m_lineEditDataLabel->text().toStdString(), errorsPlus, errorsMinus);
}
if (m_Controls.m_checkBoxEnableYErrors->isChecked())
{
auto errorsPlus = ConvertToDoubleVector(m_Controls.m_lineEditYErrorPlus->text());
auto errorsMinus = ConvertToDoubleVector(m_Controls.m_lineEditYErrorMinus->text());
m_Controls.m_Chart->SetYErrorBars(m_Controls.m_lineEditDataLabel->text().toStdString(), errorsPlus, errorsMinus);
}
}
QString dataOverview;
dataOverview.append(m_Controls.m_lineEditDataLabel->text());
dataOverview.append("(").append(m_Controls.m_comboBoxChartType->currentText());
dataOverview.append(", ").append(m_Controls.m_comboBoxLineStyle->currentText());
dataOverview.append(")");
dataOverview.append(":").append(data);
m_Controls.m_plainTextEditDataView->appendPlainText(dataOverview);
}
void QmitkChartExampleView::CreateChart()
{
auto dataYAxisScaleType =
m_AxisScaleNameToAxisScaleType.at(m_Controls.m_comboBoxYAxisScale->currentText().toStdString());
auto xAxisLabel = m_Controls.m_lineEditXAxisLabel->text().toStdString();
auto yAxisLabel = m_Controls.m_lineEditYAxisLabel->text().toStdString();
auto showLegend = m_Controls.m_checkBoxShowLegend->isChecked();
auto legendPosition =
m_LegendPositionNameToLegendPositionType.at(m_Controls.m_comboBoxLegendPosition->currentText().toStdString());
auto showDataPoints = m_Controls.m_checkBoxShowDataPoints->isChecked();
auto stackedData = m_Controls.m_checkBoxStackedData->isChecked();
auto showSubchart = m_Controls.m_checkBoxShowSubchart->isChecked();
auto title = m_Controls.m_lineEditTitle->text().toStdString();
m_Controls.m_Chart->SetTitle(title);
m_Controls.m_Chart->SetYAxisScale(dataYAxisScaleType);
m_Controls.m_Chart->SetXAxisLabel(xAxisLabel);
m_Controls.m_Chart->SetYAxisLabel(yAxisLabel);
m_Controls.m_Chart->SetShowLegend(showLegend);
m_Controls.m_Chart->SetLegendPosition(legendPosition);
m_Controls.m_Chart->SetShowErrorBars(true);
m_Controls.m_Chart->SetShowDataPoints(showDataPoints);
m_Controls.m_Chart->SetStackedData(stackedData);
m_Controls.m_Chart->Show(showSubchart);
}
void QmitkChartExampleView::UpdateData()
{
if (m_Controls.m_comboBoxExistingData->currentText().isEmpty())
{
m_Controls.m_labelInfo->setText("Please enter a valid Datalabel");
m_Controls.m_labelInfo->setStyleSheet("color: red;");
return;
}
if (m_Controls.m_lineEditDataLabel->text() != m_Controls.m_comboBoxExistingData->currentText())
{
return;
}
QString lineEditDataX = m_Controls.m_lineEditDataXVector->text();
QString lineEditDataY = m_Controls.m_lineEditDataYVector->text();
auto dataX = ConvertToDoubleVector(lineEditDataX);
auto dataY = ConvertToDoubleVector(lineEditDataY);
auto dataXandY = CreatePairList(dataX, dataY);
QString data = QString::fromStdString(ConvertToText(dataXandY));
std::string dataLabel = m_Controls.m_lineEditDataLabel->text().toStdString();
std::string chartTypeAsString = m_Controls.m_comboBoxChartType->currentText().toStdString();
std::string chartColorAsString = m_Controls.m_comboBoxColor->currentText().toStdString();
std::string chartLineStyleAsString = m_Controls.m_comboBoxLineStyle->currentText().toStdString();
std::string pieLabelsAsString = m_Controls.m_lineEditPieDataLabel->text().toStdString();
if (dataX.size() != dataY.size())
{
m_Controls.m_labelInfo->setText("Data x and y size have to be equal");
m_Controls.m_labelInfo->setStyleSheet("color: red;");
return;
}
m_Controls.m_Chart->UpdateChartExampleData(dataXandY, dataLabel, chartTypeAsString, chartColorAsString, chartLineStyleAsString, pieLabelsAsString);
}
void QmitkChartExampleView::UpdateSelectedData()
{
std::string label = m_Controls.m_comboBoxExistingData->currentText().toStdString();
auto data = m_Controls.m_Chart->GetDataElementByLabel(label);
if (data == nullptr)
{
return;
}
auto x = data->GetXData();
auto y = data->GetYData();
- auto xVector = x.toVector().toStdVector();
- auto yVector = y.toVector().toStdVector();
+ std::vector<QVariant> xVector(x.begin(), x.end());
+ std::vector<QVariant> yVector(y.begin(), y.end());
QString xString = QString::fromStdString(ConvertToText(xVector));
QString yString = QString::fromStdString(ConvertToText(yVector));
auto color = data->GetColor();
auto type = data->GetChartType();
auto style = data->GetLineStyle();
if (type.toString() == "pie")
{
m_Controls.m_comboBoxLineStyle->setVisible(false);
m_Controls.m_labelLineStyle->setVisible(false);
m_Controls.m_lineEditPieDataLabel->setVisible(true);
m_Controls.m_labelPieData->setVisible(true);
auto pieLabelsString = ConvertToText(data->GetPieLabels());
m_Controls.m_lineEditPieDataLabel->setText(QString::fromStdString(pieLabelsString));
}
else
{
m_Controls.m_lineEditPieDataLabel->setVisible(false);
m_Controls.m_labelPieData->setVisible(false);
m_Controls.m_comboBoxLineStyle->setVisible(true);
m_Controls.m_labelLineStyle->setVisible(true);
m_Controls.m_comboBoxLineStyle->setCurrentText(style.toString());
}
m_Controls.m_lineEditDataXVector->setText(xString);
m_Controls.m_lineEditDataYVector->setText(yString);
m_Controls.m_lineEditDataLabel->setText(QString::fromStdString(label));
m_Controls.m_comboBoxColor->setCurrentText(color.toString());
m_Controls.m_comboBoxChartType->setCurrentText(type.toString());
}
void QmitkChartExampleView::ClearChart()
{
m_Controls.m_Chart->Clear();
m_Controls.m_plainTextEditDataView->clear();
m_Controls.m_comboBoxExistingData->clear();
labelStorage.clear();
}
void QmitkChartExampleView::ShowErrorOptions(bool show)
{
m_Controls.m_groupBoxErrors->setVisible(show);
}
void QmitkChartExampleView::ShowXErrorOptions(bool show)
{
m_Controls.m_groupBoxXErrors->setVisible(show);
}
void QmitkChartExampleView::ShowYErrorOptions(bool show)
{
m_Controls.m_groupBoxYErrors->setVisible(show);
}
void QmitkChartExampleView::AdaptZoomX()
{
m_Controls.m_Chart->SetMinMaxValueXView(m_Controls.m_doubleSpinBox_minZoomX->value(),
m_Controls.m_doubleSpinBox_maxZoomX->value());
m_Controls.m_Chart->Show();
}
void QmitkChartExampleView::AdaptZoomY()
{
m_Controls.m_Chart->SetMinMaxValueYView(m_Controls.m_doubleSpinBox_minZoomY->value(),
m_Controls.m_doubleSpinBox_maxZoomY->value());
m_Controls.m_Chart->Show();
}
void QmitkChartExampleView::AdaptDataGUI(QString chartType)
{
if (chartType == "pie")
{
m_Controls.m_labelPieData->setVisible(true);
m_Controls.m_lineEditPieDataLabel->setVisible(true);
m_Controls.m_labelLineStyle->setVisible(false);
m_Controls.m_comboBoxLineStyle->setVisible(false);
}
else
{
m_Controls.m_labelLineStyle->setVisible(true);
m_Controls.m_comboBoxLineStyle->setVisible(true);
m_Controls.m_labelPieData->setVisible(false);
m_Controls.m_lineEditPieDataLabel->setVisible(false);
}
}
void QmitkChartExampleView::OnLegendPositionChanged(const QString &newText)
{
auto legendPosition = m_LegendPositionNameToLegendPositionType.at(newText.toStdString());
m_Controls.m_Chart->SetLegendPosition(legendPosition);
}
void QmitkChartExampleView::OnTitleChanged() {
auto newTitle = m_Controls.m_lineEditTitle->text();
m_Controls.m_Chart->SetTitle(newTitle.toStdString());
}
void QmitkChartExampleView::OnXAxisLabelChanged() {
auto newXAxisLabel = m_Controls.m_lineEditXAxisLabel->text();
m_Controls.m_Chart->SetXAxisLabel(newXAxisLabel.toStdString());
}
void QmitkChartExampleView::OnYAxisLabelChanged() {
auto newYAxisLabel = m_Controls.m_lineEditYAxisLabel->text();
m_Controls.m_Chart->SetYAxisLabel(newYAxisLabel.toStdString());
}
void QmitkChartExampleView::OnYAxisScaleChanged(const QString &newYAxisScale) {
auto yAxisScale = m_AxisScaleNameToAxisScaleType.at(newYAxisScale.toStdString());
m_Controls.m_Chart->SetYAxisScale(yAxisScale);
}
void QmitkChartExampleView::OnShowLegendChanged(int newState) {
m_Controls.m_Chart->SetShowLegend(newState == Qt::Checked);
}
void QmitkChartExampleView::OnStackedDataChanged(int newState) {
m_Controls.m_Chart->SetStackedData(newState == Qt::Checked);
}
void QmitkChartExampleView::OnShowDataPointsChanged(int newState) {
m_Controls.m_Chart->SetShowDataPoints(newState == Qt::Checked);
}
void QmitkChartExampleView::OnShowSubchartChanged(int newState) {
m_Controls.m_Chart->SetShowSubchart(newState == Qt::Checked);
}
std::vector< std::pair<double, double> > QmitkChartExampleView::CreatePairList(std::vector<double> keys, std::vector<double> values) const
{
std::vector< std::pair<double, double> > aMap;
std::transform(keys.begin(), keys.end(), values.begin(), std::inserter(aMap, aMap.end()), [](double a, double b) {
return std::make_pair(a, b);
});
return aMap;
}
std::string QmitkChartExampleView::ConvertToText(std::vector<std::pair<double, double> > numbers, std::string delimiter) const
{
std::ostringstream oss;
oss.precision(3);
if (!numbers.empty())
{
for (const auto& keyValue : numbers)
{
oss << keyValue.first << ":" << keyValue.second << delimiter;
}
}
auto aString = oss.str();
aString.pop_back();
return aString;
}
std::string QmitkChartExampleView::ConvertToText(std::vector<QVariant> numbers, std::string delimiter) const
{
std::ostringstream oss;
oss.precision(3);
if (!numbers.empty())
{
for (auto number : numbers)
{
oss << number.toDouble() << delimiter;
}
}
auto aString = oss.str();
aString.pop_back();
return aString;
}
std::string QmitkChartExampleView::ConvertToText(QVariantList list, std::string delimiter) const
{
std::ostringstream oss;
if (!list.isEmpty())
{
for (auto element : list)
{
oss << element.toString().toStdString() << delimiter;
}
auto aString = oss.str();
aString.pop_back();
return aString;
}
return "";
}
std::vector<double> QmitkChartExampleView::ConvertToDoubleVector(const QString& data, QChar delimiter) const
{
std::vector<double> output;
if (data.isEmpty())
{
return output;
}
for (const QString& entry : data.split(delimiter))
{
output.push_back(entry.toDouble());
}
return output;
}
std::vector<std::string> QmitkChartExampleView::ConvertToStringVector(const QString& data, QChar delimiter) const
{
std::vector<std::string> output;
if (data.isEmpty())
{
return output;
}
for (const QString& entry : data.split(delimiter))
{
output.push_back(entry.toStdString());
}
return output;
}
diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp
index 95103106a7..ecd5f692f9 100644
--- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp
+++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractView.cpp
@@ -1,522 +1,526 @@
/*============================================================================
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 "QmitkAbstractView.h"
#include "QmitkDataNodeSelectionProvider.h"
#include "internal/QmitkCommonActivator.h"
#include "internal/QmitkDataNodeItemModel.h"
// mitk Includes
#include <mitkLog.h>
#include <mitkCoreServices.h>
#include <mitkIPreferences.h>
#include <mitkIPreferencesService.h>
#include <mitkIDataStorageService.h>
#include <mitkDataStorageEditorInput.h>
#include <mitkDataNodeObject.h>
#include <mitkIRenderingManager.h>
#include <mitkTimeNavigationController.h>
// berry Includes
#include <berryIWorkbenchPage.h>
#include <berryIEditorPart.h>
#include <berryINullSelectionListener.h>
#include <berryUIException.h>
// CTK Includes
#include <ctkServiceTracker.h>
// Qt Includes
#include <QItemSelectionModel>
#include <QApplication>
#include <QMessageBox>
#include <QScrollArea>
#include <QVBoxLayout>
class QmitkAbstractViewPrivate
{
public:
QmitkAbstractViewPrivate(QmitkAbstractView* qq)
: q(qq)
, m_DataStorageServiceTracker(QmitkCommonActivator::GetContext())
, m_Parent(nullptr)
, m_DataNodeItemModel(new QmitkDataNodeItemModel)
, m_DataNodeSelectionModel(new QItemSelectionModel(m_DataNodeItemModel))
, m_InDataStorageChanged(false)
{
m_DataStorageServiceTracker.open();
}
~QmitkAbstractViewPrivate()
{
delete m_DataNodeSelectionModel;
delete m_DataNodeItemModel;
m_DataStorageServiceTracker.close();
}
/**
* Called when a DataStorage Add Event was thrown. Sets
* m_InDataStorageChanged to true and calls NodeAdded afterwards.
* \see m_InDataStorageChanged
*/
void NodeAddedProxy(const mitk::DataNode* node)
{
// garantuee no recursions when a new node event is thrown in NodeAdded()
if(!m_InDataStorageChanged)
{
m_InDataStorageChanged = true;
q->NodeAdded(node);
q->DataStorageModified();
m_InDataStorageChanged = false;
}
}
/**
* Called when a DataStorage remove event was thrown. Sets
* m_InDataStorageChanged to true and calls NodeRemoved afterwards.
* \see m_InDataStorageChanged
*/
void NodeRemovedProxy(const mitk::DataNode* node)
{
// garantuee no recursions when a new node event is thrown in NodeAdded()
if(!m_InDataStorageChanged)
{
m_InDataStorageChanged = true;
q->NodeRemoved(node);
q->DataStorageModified();
m_InDataStorageChanged = false;
}
}
/**
* Called when a DataStorage changed event was thrown. Sets
* m_InDataStorageChanged to true and calls NodeChanged afterwards.
* \see m_InDataStorageChanged
*/
void NodeChangedProxy(const mitk::DataNode* node)
{
// garantuee no recursions when a new node event is thrown in NodeAdded()
if(!m_InDataStorageChanged)
{
m_InDataStorageChanged = true;
q->NodeChanged(node);
q->DataStorageModified();
m_InDataStorageChanged = false;
}
}
/**
* reactions to selection events from views
*/
void BlueBerrySelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart,
const berry::ISelection::ConstPointer& selection)
{
if(sourcepart.IsNull() || sourcepart.GetPointer() == static_cast<berry::IWorkbenchPart*>(q))
return;
if(selection.IsNull())
{
q->OnNullSelection(sourcepart);
return;
}
mitk::DataNodeSelection::ConstPointer _DataNodeSelection
= selection.Cast<const mitk::DataNodeSelection>();
q->OnSelectionChanged(sourcepart, this->DataNodeSelectionToQList(_DataNodeSelection));
}
/**
* Converts a mitk::DataNodeSelection to a QList<mitk::DataNode::Pointer> (possibly empty)
*/
QList<mitk::DataNode::Pointer> DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const;
QmitkAbstractView* const q;
ctkServiceTracker<mitk::IDataStorageService*> m_DataStorageServiceTracker;
/**
* Saves the parent of this view (this is the scrollarea created in CreatePartControl(QWidget*)
* \see CreatePartControl(QWidget*)
*/
QWidget* m_Parent;
/**
* Holds the current selection (selection made by this View !!!)
*/
QmitkDataNodeSelectionProvider::Pointer m_SelectionProvider;
/**
* Holds a helper model for firing selection events.
*/
QmitkDataNodeItemModel* m_DataNodeItemModel;
/**
* The selection model for the QmitkDataNodeItemModel;
*/
QItemSelectionModel* m_DataNodeSelectionModel;
/**
* object to observe BlueBerry selections
*/
QScopedPointer<berry::ISelectionListener> m_BlueBerrySelectionListener;
/**
* Saves if this class is currently working on DataStorage changes.
* This is a protector variable to avoid recursive calls on event listener functions.
*/
bool m_InDataStorageChanged;
};
QmitkAbstractView::QmitkAbstractView()
: d(new QmitkAbstractViewPrivate(this))
{
}
void QmitkAbstractView::CreatePartControl(QWidget* parent)
{
// scrollArea
auto scrollArea = new QScrollArea;
//QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollArea);
scrollArea->setFrameShadow(QFrame::Plain);
scrollArea->setFrameShape(QFrame::NoFrame);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
// m_Parent
d->m_Parent = new QWidget;
//m_Parent->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));
this->CreateQtPartControl(d->m_Parent);
//scrollAreaLayout->addWidget(m_Parent);
//scrollArea->setLayout(scrollAreaLayout);
// set the widget now
scrollArea->setWidgetResizable(true);
scrollArea->setWidget(d->m_Parent);
// add the scroll area to the real parent (the view tabbar)
QWidget* parentQWidget = static_cast<QWidget*>(parent);
auto parentLayout = new QVBoxLayout(parentQWidget);
- parentLayout->setMargin(0);
+ parentLayout->setContentsMargins({});
parentLayout->setSpacing(0);
parentLayout->addWidget(scrollArea);
// finally set the layout containing the scroll area to the parent widget (= show it)
parentQWidget->setLayout(parentLayout);
this->AfterCreateQtPartControl();
}
void QmitkAbstractView::AfterCreateQtPartControl()
{
this->SetSelectionProvider();
// REGISTER DATASTORAGE LISTENER
this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*>
( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) );
this->GetDataStorage()->ChangedNodeEvent.AddListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*>
( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) );
this->GetDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*>
( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy ) );
// REGISTER PREFERENCES LISTENER
auto* prefs = this->GetPreferences();
if (prefs != nullptr)
prefs->OnChanged.AddListener(mitk::MessageDelegate1<QmitkAbstractView, const mitk::IPreferences*>(this, &QmitkAbstractView::OnPreferencesChanged));
// REGISTER FOR WORKBENCH SELECTION EVENTS
d->m_BlueBerrySelectionListener.reset(new berry::NullSelectionChangedAdapter<QmitkAbstractViewPrivate>(
d.data(), &QmitkAbstractViewPrivate::BlueBerrySelectionChanged));
this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(d->m_BlueBerrySelectionListener.data());
// EMULATE INITIAL SELECTION EVENTS
// send the current selection
berry::IWorkbenchPart::Pointer activePart = this->GetSite()->GetPage()->GetActivePart();
if (activePart.IsNotNull())
{
this->OnSelectionChanged(activePart, this->GetCurrentSelection());
}
// send preferences changed event
this->OnPreferencesChanged(this->GetPreferences());
}
QmitkAbstractView::~QmitkAbstractView()
{
this->Register();
this->GetDataStorage()->AddNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*>
( d.data(), &QmitkAbstractViewPrivate::NodeAddedProxy ) );
this->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*>
( d.data(), &QmitkAbstractViewPrivate::NodeRemovedProxy) );
this->GetDataStorage()->ChangedNodeEvent.RemoveListener( mitk::MessageDelegate1<QmitkAbstractViewPrivate, const mitk::DataNode*>
( d.data(), &QmitkAbstractViewPrivate::NodeChangedProxy ) );
auto* prefs = this->GetPreferences();
if(prefs != nullptr)
prefs->OnChanged.RemoveListener(mitk::MessageDelegate1<QmitkAbstractView, const mitk::IPreferences*>(this, &QmitkAbstractView::OnPreferencesChanged));
// REMOVE SELECTION PROVIDER
this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(nullptr));
berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService();
if(s)
{
s->RemovePostSelectionListener(d->m_BlueBerrySelectionListener.data());
}
this->UnRegister(false);
}
void QmitkAbstractView::SetSelectionProvider()
{
// REGISTER A SELECTION PROVIDER
d->m_SelectionProvider = QmitkDataNodeSelectionProvider::Pointer(new QmitkDataNodeSelectionProvider);
d->m_SelectionProvider->SetItemSelectionModel(GetDataNodeSelectionModel());
this->GetSite()->SetSelectionProvider(berry::ISelectionProvider::Pointer(d->m_SelectionProvider));
}
QItemSelectionModel *QmitkAbstractView::GetDataNodeSelectionModel() const
{
return nullptr;
}
void QmitkAbstractView::OnPreferencesChanged( const mitk::IPreferences* )
{
}
void QmitkAbstractView::DataStorageModified()
{
}
void QmitkAbstractView::DataStorageChanged(mitk::IDataStorageReference::Pointer /*dsRef*/)
{
}
mitk::IRenderWindowPart* QmitkAbstractView::GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategies strategies) const
{
berry::IWorkbenchPage::Pointer page = GetSite()->GetPage();
return mitk::WorkbenchUtil::GetRenderWindowPart(page, strategies);
}
void QmitkAbstractView::RequestRenderWindowUpdate(mitk::RenderingManager::RequestType requestType)
{
mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart();
if (renderPart == nullptr)
return;
if (mitk::IRenderingManager* renderingManager = renderPart->GetRenderingManager())
{
renderingManager->RequestUpdateAll(requestType);
}
else
{
renderPart->RequestUpdate(requestType);
}
}
void QmitkAbstractView::HandleException( const char* str, QWidget* parent, bool showDialog ) const
{
//itkGenericOutputMacro( << "Exception caught: " << str );
MITK_ERROR << str;
if ( showDialog )
{
QMessageBox::critical ( parent, "Exception caught!", str );
}
}
void QmitkAbstractView::HandleException( std::exception& e, QWidget* parent, bool showDialog ) const
{
HandleException( e.what(), parent, showDialog );
}
void QmitkAbstractView::WaitCursorOn()
{
QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
}
void QmitkAbstractView::BusyCursorOn()
{
QApplication::setOverrideCursor( QCursor(Qt::BusyCursor) );
}
void QmitkAbstractView::WaitCursorOff()
{
this->RestoreOverrideCursor();
}
void QmitkAbstractView::BusyCursorOff()
{
this->RestoreOverrideCursor();
}
void QmitkAbstractView::RestoreOverrideCursor()
{
QApplication::restoreOverrideCursor();
}
mitk::IPreferences* QmitkAbstractView::GetPreferences() const
{
mitk::CoreServicePointer prefsService(mitk::CoreServices::GetPreferencesService());
auto* prefs = prefsService->GetSystemPreferences();
if (prefs != nullptr)
{
auto viewSite = const_cast<QmitkAbstractView*>(this)->GetViewSite();
if (viewSite.IsNotNull())
return prefs->Node("/" + viewSite->GetId().toStdString());
}
return nullptr;
}
mitk::DataStorage::Pointer QmitkAbstractView::GetDataStorage() const
{
mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService();
if (dsService != nullptr)
{
return dsService->GetDataStorage()->GetDataStorage();
}
return nullptr;
}
mitk::IDataStorageReference::Pointer QmitkAbstractView::GetDataStorageReference() const
{
mitk::IDataStorageService* dsService = d->m_DataStorageServiceTracker.getService();
if (dsService != nullptr)
{
return dsService->GetDataStorage();
}
return mitk::IDataStorageReference::Pointer(nullptr);
}
QList<mitk::DataNode::Pointer> QmitkAbstractView::GetCurrentSelection() const
{
berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection());
mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast<const mitk::DataNodeSelection>();
return d->DataNodeSelectionToQList(currentSelection);
}
bool QmitkAbstractView::IsCurrentSelectionValid() const
{
return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection();
}
QList<mitk::DataNode::Pointer> QmitkAbstractView::GetDataManagerSelection() const
{
berry::ISelection::ConstPointer selection( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager"));
mitk::DataNodeSelection::ConstPointer currentSelection = selection.Cast<const mitk::DataNodeSelection>();
return d->DataNodeSelectionToQList(currentSelection);
}
bool QmitkAbstractView::IsDataManagerSelectionValid() const
{
return this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager");
}
void QmitkAbstractView::SetDataManagerSelection(const berry::ISelection::ConstPointer &selection,
QItemSelectionModel::SelectionFlags flags) const
{
berry::IViewPart::Pointer datamanagerView = this->GetSite()->GetWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.datamanager");
if (datamanagerView.IsNull()) return;
datamanagerView->GetSite()->GetSelectionProvider().Cast<berry::QtSelectionProvider>()->SetSelection(selection, flags);
}
void QmitkAbstractView::SynchronizeDataManagerSelection() const
{
berry::ISelection::ConstPointer currentSelection = this->GetSite()->GetSelectionProvider()->GetSelection();
if (currentSelection.IsNull()) return;
SetDataManagerSelection(currentSelection);
}
void QmitkAbstractView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/,
const QList<mitk::DataNode::Pointer>& /*nodes*/)
{
}
void QmitkAbstractView::OnNullSelection(berry::IWorkbenchPart::Pointer /*part*/)
{
}
QList<mitk::DataNode::Pointer> QmitkAbstractViewPrivate::DataNodeSelectionToQList(mitk::DataNodeSelection::ConstPointer currentSelection) const
{
- if (currentSelection.IsNull()) return QList<mitk::DataNode::Pointer>();
- return QList<mitk::DataNode::Pointer>::fromStdList(currentSelection->GetSelectedDataNodes());
+ if (currentSelection.IsNull())
+ return QList<mitk::DataNode::Pointer>();
+
+ auto nodes = currentSelection->GetSelectedDataNodes();
+
+ return QList<mitk::DataNode::Pointer>(nodes.begin(), nodes.end());
}
void QmitkAbstractView::NodeAdded( const mitk::DataNode* /*node*/ )
{
}
void QmitkAbstractView::NodeRemoved( const mitk::DataNode* /*node*/ )
{
}
void QmitkAbstractView::NodeChanged( const mitk::DataNode* /*node*/ )
{
}
void QmitkAbstractView::FireNodeSelected( mitk::DataNode::Pointer node )
{
QList<mitk::DataNode::Pointer> nodes;
nodes << node;
this->FireNodesSelected(nodes);
}
void QmitkAbstractView::FireNodesSelected( const QList<mitk::DataNode::Pointer>& nodes )
{
// if this is the first call to FireNodesSelected and the selection provider has no QItemSelectiomMode
// yet, set our helper model
if (d->m_SelectionProvider->GetItemSelectionModel() == nullptr)
{
d->m_SelectionProvider->SetItemSelectionModel(d->m_DataNodeSelectionModel);
}
else if (d->m_SelectionProvider->GetItemSelectionModel() != d->m_DataNodeSelectionModel)
{
MITK_WARN << "A custom data node selection model has been set. Ignoring call to FireNodesSelected().";
return;
}
if (nodes.empty())
{
d->m_DataNodeSelectionModel->clearSelection();
d->m_DataNodeItemModel->clear();
}
else
{
// The helper data node model is just used for sending selection events.
// We add the to be selected nodes and set the selection range to everything.
d->m_DataNodeItemModel->clear();
foreach(mitk::DataNode::Pointer node, nodes)
{
d->m_DataNodeItemModel->AddDataNode(node);
}
d->m_DataNodeSelectionModel->select(QItemSelection(d->m_DataNodeItemModel->index(0,0), d->m_DataNodeItemModel->index(nodes.size()-1, 0)),
QItemSelectionModel::ClearAndSelect);
}
}
diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkSelectionServiceConnector.cpp b/Plugins/org.mitk.gui.qt.common/src/QmitkSelectionServiceConnector.cpp
index 674d0e9758..5f3a5efc1d 100644
--- a/Plugins/org.mitk.gui.qt.common/src/QmitkSelectionServiceConnector.cpp
+++ b/Plugins/org.mitk.gui.qt.common/src/QmitkSelectionServiceConnector.cpp
@@ -1,126 +1,127 @@
/*============================================================================
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 gui qt common plugin
#include "QmitkSelectionServiceConnector.h"
#include "internal/QmitkDataNodeSelection.h"
// qt widgets module
#include "QmitkCustomVariants.h"
#include "QmitkEnums.h"
// blueberry ui qt plugin
#include <berryINullSelectionListener.h>
QmitkSelectionServiceConnector::QmitkSelectionServiceConnector()
: m_SelectionService(nullptr)
, m_SelectionProvider(nullptr)
{
m_DataNodeItemModel = std::make_shared<QmitkDataNodeItemModel>();
m_DataNodeSelectionModel = std::make_shared<QItemSelectionModel>(m_DataNodeItemModel.get());
}
QmitkSelectionServiceConnector::~QmitkSelectionServiceConnector()
{
RemovePostSelectionListener();
RemoveAsSelectionProvider();
}
void QmitkSelectionServiceConnector::AddPostSelectionListener(berry::ISelectionService* selectionService)
{
if (nullptr == selectionService)
{
return;
}
m_SelectionService = selectionService;
m_BerrySelectionListener.reset(new berry::NullSelectionChangedAdapter<QmitkSelectionServiceConnector>(this, &QmitkSelectionServiceConnector::OnServiceSelectionChanged));
m_SelectionService->AddPostSelectionListener(m_BerrySelectionListener.get());
}
void QmitkSelectionServiceConnector::RemovePostSelectionListener()
{
if (nullptr == m_SelectionService)
{
return;
}
m_SelectionService->RemovePostSelectionListener(m_BerrySelectionListener.get());
m_SelectionService = nullptr;
}
void QmitkSelectionServiceConnector::SetAsSelectionProvider(QmitkDataNodeSelectionProvider* selectionProvider)
{
m_SelectionProvider = selectionProvider;
}
void QmitkSelectionServiceConnector::RemoveAsSelectionProvider()
{
m_SelectionProvider = nullptr;
}
void QmitkSelectionServiceConnector::ChangeServiceSelection(QList<mitk::DataNode::Pointer> nodes)
{
if (nullptr == m_SelectionProvider)
{
return;
}
m_SelectionProvider->SetItemSelectionModel(m_DataNodeSelectionModel.get());
if (nodes.empty())
{
m_DataNodeSelectionModel->clearSelection();
m_DataNodeItemModel->clear();
}
else
{
m_DataNodeItemModel->clear();
// fill the temporary helper data node item model with the nodes to select
for (const auto& node : nodes)
{
m_DataNodeItemModel->AddDataNode(node);
}
m_DataNodeSelectionModel->select(QItemSelection(m_DataNodeItemModel->index(0, 0), m_DataNodeItemModel->index(nodes.size() - 1, 0)), QItemSelectionModel::ClearAndSelect);
}
}
void QmitkSelectionServiceConnector::OnServiceSelectionChanged(const berry::IWorkbenchPart::Pointer& sourcePart, const berry::ISelection::ConstPointer& selection)
{
if (sourcePart.IsNull())
{
return;
}
QList<mitk::DataNode::Pointer> nodes;
if (selection.IsNull())
{
emit ServiceNullSelection(sourcePart);
return;
}
// transform valid selection to DataNodeSelection, which allows to retrieve the selected nodes
mitk::DataNodeSelection::ConstPointer dataNodeSelection = selection.Cast<const mitk::DataNodeSelection>();
if (dataNodeSelection.IsNull())
{
// propagate an empty list
nodes = QList<mitk::DataNode::Pointer>();
}
else
{
- nodes = QList<mitk::DataNode::Pointer>::fromStdList(dataNodeSelection->GetSelectedDataNodes());
+ auto selectedNodes = dataNodeSelection->GetSelectedDataNodes();
+ nodes = QList<mitk::DataNode::Pointer>(selectedNodes.begin(), selectedNodes.end());
}
// send new (possibly empty) list of selected nodes
emit ServiceSelectionChanged(nodes);
}
diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.cpp b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.cpp
index 2a6a403d21..007a1a3c03 100644
--- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.cpp
+++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.cpp
@@ -1,234 +1,234 @@
/*============================================================================
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 "QmitkViewCoordinator.h"
#include "QmitkAbstractView.h"
#include <mitkIRenderWindowPart.h>
#include <mitkIRenderWindowPartListener.h>
#include <mitkIZombieViewPart.h>
#include <berryPlatformUI.h>
#include <berryIWorkbenchPage.h>
QmitkViewCoordinator::QmitkViewCoordinator()
: m_ActiveZombieView(nullptr)
, m_ActiveRenderWindowPart(nullptr)
, m_VisibleRenderWindowPart(nullptr)
{
}
QmitkViewCoordinator::~QmitkViewCoordinator()
{
}
void QmitkViewCoordinator::Start()
{
berry::PlatformUI::GetWorkbench()->AddWindowListener(this);
QList<berry::IWorkbenchWindow::Pointer> wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows());
for (QList<berry::IWorkbenchWindow::Pointer>::iterator i = wnds.begin(); i != wnds.end(); ++i)
{
(*i)->GetPartService()->AddPartListener(this);
}
}
void QmitkViewCoordinator::Stop()
{
if (!berry::PlatformUI::IsWorkbenchRunning()) return;
berry::PlatformUI::GetWorkbench()->RemoveWindowListener(this);
QList<berry::IWorkbenchWindow::Pointer> wnds(berry::PlatformUI::GetWorkbench()->GetWorkbenchWindows());
for (QList<berry::IWorkbenchWindow::Pointer>::iterator i = wnds.begin(); i != wnds.end(); ++i)
{
(*i)->GetPartService()->RemovePartListener(this);
}
}
berry::IPartListener::Events::Types QmitkViewCoordinator::GetPartEventTypes() const
{
return berry::IPartListener::Events::ACTIVATED | berry::IPartListener::Events::DEACTIVATED
| berry::IPartListener::Events::CLOSED | berry::IPartListener::Events::HIDDEN
| berry::IPartListener::Events::VISIBLE | berry::IPartListener::Events::OPENED
| berry::IPartListener::Events::INPUT_CHANGED;
}
void QmitkViewCoordinator::PartActivated(const berry::IWorkbenchPartReference::Pointer& partRef)
{
//MITK_INFO << "*** PartActivated (" << partRef->GetPart(false)->GetPartName() << ")";
berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer();
// Check for a render window part and inform IRenderWindowPartListener views
// that it was activated
if (mitk::IRenderWindowPart* renderPart = dynamic_cast<mitk::IRenderWindowPart*>(part))
{
if (m_VisibleRenderWindowPart != renderPart)
{
RenderWindowPartActivated(renderPart);
m_ActiveRenderWindowPart = renderPart;
m_VisibleRenderWindowPart = renderPart;
}
}
// Check if the activated part wants to be notified
if (mitk::ILifecycleAwarePart* lifecycleAwarePart = dynamic_cast<mitk::ILifecycleAwarePart*>(part))
{
lifecycleAwarePart->Activated();
}
// Check if a zombie view has been activated.
if (mitk::IZombieViewPart* zombieView = dynamic_cast<mitk::IZombieViewPart*>(part))
{
if (m_ActiveZombieView && (m_ActiveZombieView != zombieView))
{
// Another zombie view has been activated. Tell the old one about it.
m_ActiveZombieView->ActivatedZombieView(partRef);
m_ActiveZombieView = zombieView;
}
}
}
void QmitkViewCoordinator::PartDeactivated(const berry::IWorkbenchPartReference::Pointer& partRef)
{
//MITK_INFO << "*** PartDeactivated (" << partRef->GetPart(false)->GetPartName() << ")";
berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer();
// Check for a render window part and inform IRenderWindowPartListener views
// that it was deactivated
if (mitk::IRenderWindowPart* renderPart = dynamic_cast<mitk::IRenderWindowPart*>(part))
{
if (m_ActiveRenderWindowPart == renderPart)
{
this->RenderWindowPartDeactivated(renderPart);
m_ActiveRenderWindowPart = nullptr;
m_VisibleRenderWindowPart = nullptr;
}
}
if (mitk::ILifecycleAwarePart* lifecycleAwarePart = dynamic_cast<mitk::ILifecycleAwarePart*>(part))
{
lifecycleAwarePart->Deactivated();
}
}
void QmitkViewCoordinator::PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef)
{
//MITK_INFO << "*** PartOpened (" << partRef->GetPart(false)->GetPartName() << ")";
berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer();
if (mitk::IRenderWindowPartListener* renderWindowListener = dynamic_cast<mitk::IRenderWindowPartListener*>(part))
{
m_RenderWindowListeners.insert(renderWindowListener);
}
}
void QmitkViewCoordinator::PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef)
{
//MITK_INFO << "*** PartClosed (" << partRef->GetPart(false)->GetPartName() << ")";
berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer();
if (mitk::IRenderWindowPartListener* renderWindowListener = dynamic_cast<mitk::IRenderWindowPartListener*>(part))
{
m_RenderWindowListeners.remove(renderWindowListener);
}
}
void QmitkViewCoordinator::PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef)
{
//MITK_INFO << "*** PartHidden (" << partRef->GetPart(false)->GetPartName() << ")";
berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer();
// Check for a render window part and if it is the currently active on.
// Inform IRenderWindowPartListener views that it has been hidden.
if (mitk::IRenderWindowPart* renderPart = dynamic_cast<mitk::IRenderWindowPart*>(part))
{
if (!m_ActiveRenderWindowPart && m_VisibleRenderWindowPart == renderPart)
{
RenderWindowPartDeactivated(renderPart);
m_VisibleRenderWindowPart = nullptr;
}
}
if (mitk::ILifecycleAwarePart* lifecycleAwarePart = dynamic_cast<mitk::ILifecycleAwarePart*>(part))
{
lifecycleAwarePart->Hidden();
}
}
void QmitkViewCoordinator::PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef)
{
//MITK_INFO << "*** PartVisible (" << partRef->GetPart(false)->GetPartName() << ")";
berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer();
// Check for a render window part and inform IRenderWindowPartListener views
// that it was activated
if (mitk::IRenderWindowPart* renderPart = dynamic_cast<mitk::IRenderWindowPart*>(part))
{
if (!m_ActiveRenderWindowPart)
{
RenderWindowPartActivated(renderPart);
m_VisibleRenderWindowPart = renderPart;
}
}
if (mitk::ILifecycleAwarePart* lifecycleAwarePart = dynamic_cast<mitk::ILifecycleAwarePart*>(part))
{
lifecycleAwarePart->Visible();
}
}
void QmitkViewCoordinator::PartInputChanged(const berry::IWorkbenchPartReference::Pointer& partRef)
{
berry::IWorkbenchPart* part = partRef->GetPart(false).GetPointer();
// Check for a render window part and inform IRenderWindowPartListener views
// that it was changed
if (mitk::IRenderWindowPart* renderPart = dynamic_cast<mitk::IRenderWindowPart*>(part))
{
if (!m_ActiveRenderWindowPart)
{
RenderWindowPartInputChanged(renderPart);
}
}
}
void QmitkViewCoordinator::WindowOpened(const berry::IWorkbenchWindow::Pointer& window)
{
window->GetPartService()->AddPartListener(this);
}
void QmitkViewCoordinator::WindowClosed(const berry::IWorkbenchWindow::Pointer& /*window*/)
{
}
void QmitkViewCoordinator::RenderWindowPartActivated(mitk::IRenderWindowPart* renderPart)
{
- for (auto& listener : qAsConst(m_RenderWindowListeners))
+ for (auto& listener : std::as_const(m_RenderWindowListeners))
{
listener->RenderWindowPartActivated(renderPart);
}
}
void QmitkViewCoordinator::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderPart)
{
- for (auto& listener : qAsConst(m_RenderWindowListeners))
+ for (auto& listener : std::as_const(m_RenderWindowListeners))
{
listener->RenderWindowPartDeactivated(renderPart);
}
}
void QmitkViewCoordinator::RenderWindowPartInputChanged(mitk::IRenderWindowPart* renderPart)
{
- for (auto& listener : qAsConst(m_RenderWindowListeners))
+ for (auto& listener : std::as_const(m_RenderWindowListeners))
{
listener->RenderWindowPartInputChanged(renderPart);
}
}
diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp
index 7adc044f6d..6c8668c497 100644
--- a/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp
+++ b/Plugins/org.mitk.gui.qt.datamanager/src/QmitkDataManagerView.cpp
@@ -1,231 +1,231 @@
/*============================================================================
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 "QmitkDataManagerView.h"
// mitk gui qt datamanager
#include "internal/QmitkDataManagerItemDelegate.h"
#include "internal/QmitkNodeTableViewKeyFilter.h"
// mitk core
#include <mitkCommon.h>
#include <mitkCoreObjectFactory.h>
#include <mitkEnumerationProperty.h>
#include <mitkImageCast.h>
#include <mitkITKImageImport.h>
#include <mitkLookupTableProperty.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateData.h>
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateOr.h>
#include <mitkNodePredicateProperty.h>
#include <mitkProperties.h>
#include <mitkRenderingModeProperty.h>
#include <mitkIPreferences.h>
// qt widgets module
#include <QmitkCustomVariants.h>
#include <QmitkDataStorageFilterProxyModel.h>
#include <QmitkDataStorageTreeModel.h>
#include <QmitkIOUtil.h>
#include <QmitkNodeDescriptorManager.h>
// mitk core services plugin
#include <mitkIDataStorageReference.h>
#include <mitkIDataStorageService.h>
// mitk gui common plugin
#include <mitkDataNodeObject.h>
// mitk gui qt application plugin
#include <QmitkDataNodeGlobalReinitAction.h>
#include <QmitkDataNodeToggleVisibilityAction.h>
// mitk gui qt common plugin
#include <QmitkDnDFrameWidget.h>
// qt
#include <QGridLayout>
#include <QVBoxLayout>
#include <QTreeView>
const QString QmitkDataManagerView::VIEW_ID = "org.mitk.views.datamanager";
QmitkDataManagerView::QmitkDataManagerView()
: m_ItemDelegate(nullptr)
{
}
QmitkDataManagerView::~QmitkDataManagerView()
{
// nothing here
}
void QmitkDataManagerView::CreateQtPartControl(QWidget* parent)
{
m_CurrentRowCount = 0;
m_Parent = parent;
auto* prefs = this->GetPreferences();
assert(prefs != nullptr);
m_NodeTreeModel = new QmitkDataStorageTreeModel(GetDataStorage(), prefs->GetBool("Place new nodes on top", true));
m_NodeTreeModel->setParent(parent);
m_NodeTreeModel->SetAllowHierarchyChange(prefs->GetBool("Allow changing of parent node", false));
// Prepare filters
m_HelperObjectFilterPredicate = mitk::NodePredicateOr::New(
mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true)),
mitk::NodePredicateProperty::New("hidden object", mitk::BoolProperty::New(true)));
m_NodeWithNoDataFilterPredicate = mitk::NodePredicateData::New(nullptr);
m_FilterModel = new QmitkDataStorageFilterProxyModel();
m_FilterModel->setSourceModel(m_NodeTreeModel);
m_FilterModel->AddFilterPredicate(m_HelperObjectFilterPredicate);
m_FilterModel->AddFilterPredicate(m_NodeWithNoDataFilterPredicate);
m_NodeTreeView = new QTreeView;
m_NodeTreeView->setHeaderHidden(true);
m_NodeTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_NodeTreeView->setSelectionBehavior(QAbstractItemView::SelectRows);
m_NodeTreeView->setAlternatingRowColors(true);
m_NodeTreeView->setDragEnabled(true);
m_NodeTreeView->setDropIndicatorShown(true);
m_NodeTreeView->setAcceptDrops(true);
m_NodeTreeView->setContextMenuPolicy(Qt::CustomContextMenu);
m_NodeTreeView->setModel(m_FilterModel);
m_NodeTreeView->setTextElideMode(Qt::ElideMiddle);
m_NodeTreeView->installEventFilter(new QmitkNodeTableViewKeyFilter(this, GetDataStorage()));
m_ItemDelegate = new QmitkDataManagerItemDelegate(m_NodeTreeView);
m_NodeTreeView->setItemDelegate(m_ItemDelegate);
connect(m_NodeTreeModel, SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, SLOT(NodeTreeViewRowsInserted(const QModelIndex&, int, int)));
connect(m_NodeTreeModel, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, SLOT(NodeTreeViewRowsRemoved(const QModelIndex&, int, int)));
connect(m_NodeTreeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(NodeSelectionChanged(const QItemSelection &, const QItemSelection &)));
connect(m_NodeTreeModel, &QmitkDataStorageTreeModel::nodeVisibilityChanged, this, &QmitkDataManagerView::OnNodeVisibilityChanged);
// data node context menu and menu actions
m_DataNodeContextMenu = new QmitkDataNodeContextMenu(GetSite(), m_NodeTreeView);
m_DataNodeContextMenu->SetDataStorage(GetDataStorage());
connect(m_NodeTreeView, SIGNAL(customContextMenuRequested(const QPoint&)), m_DataNodeContextMenu, SLOT(OnContextMenuRequested(const QPoint&)));
QGridLayout* dndFrameWidgetLayout = new QGridLayout;
dndFrameWidgetLayout->addWidget(m_NodeTreeView, 0, 0);
dndFrameWidgetLayout->setContentsMargins(0, 0, 0, 0);
m_DnDFrameWidget = new QmitkDnDFrameWidget(m_Parent);
m_DnDFrameWidget->setLayout(dndFrameWidgetLayout);
QVBoxLayout* layout = new QVBoxLayout(parent);
layout->addWidget(m_DnDFrameWidget);
layout->setContentsMargins(0, 0, 0, 0);
m_Parent->setLayout(layout);
}
void QmitkDataManagerView::SetFocus()
{
}
//////////////////////////////////////////////////////////////////////////
// Node tree modification
//////////////////////////////////////////////////////////////////////////
void QmitkDataManagerView::NodeTreeViewRowsInserted(const QModelIndex& parent, int /*start*/, int /*end*/)
{
QModelIndex viewIndex = m_FilterModel->mapFromSource(parent);
m_NodeTreeView->setExpanded(viewIndex, true);
// a new row was inserted
if (m_CurrentRowCount == 0 && m_NodeTreeModel->rowCount() == 1)
{
mitk::WorkbenchUtil::OpenRenderWindowPart(GetSite()->GetPage());
m_CurrentRowCount = m_NodeTreeModel->rowCount();
}
}
void QmitkDataManagerView::NodeTreeViewRowsRemoved(const QModelIndex& /*parent*/, int /*start*/, int /*end*/)
{
m_CurrentRowCount = m_NodeTreeModel->rowCount();
}
void QmitkDataManagerView::NodeSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/)
{
auto selectedNodes = GetCurrentSelection();
auto nodeSet = m_NodeTreeModel->GetNodeSet();
- for (auto node : qAsConst(nodeSet))
+ for (auto node : std::as_const(nodeSet))
{
if (node.IsNotNull())
{
node->SetSelected(selectedNodes.contains(node));
}
}
m_DataNodeContextMenu->SetSelectedNodes(selectedNodes);
}
void QmitkDataManagerView::OnNodeVisibilityChanged()
{
ToggleVisibilityAction::Run(GetSite(), GetDataStorage(), QList<mitk::DataNode::Pointer>());
}
void QmitkDataManagerView::NodeChanged(const mitk::DataNode* /*node*/)
{
// m_FilterModel->invalidate();
// fix as proposed by R. Khlebnikov in the mitk-users mail from 02.09.2014
QMetaObject::invokeMethod(m_FilterModel, "invalidate", Qt::QueuedConnection);
}
void QmitkDataManagerView::OnPreferencesChanged(const mitk::IPreferences* prefs)
{
if (m_NodeTreeModel->GetPlaceNewNodesOnTopFlag() != prefs->GetBool("Place new nodes on top", true))
{
m_NodeTreeModel->SetPlaceNewNodesOnTop(!m_NodeTreeModel->GetPlaceNewNodesOnTopFlag());
}
bool hideHelperObjects = !prefs->GetBool("Show helper objects", false);
if (m_FilterModel->HasFilterPredicate(m_HelperObjectFilterPredicate) != hideHelperObjects)
{
if (hideHelperObjects)
{
m_FilterModel->AddFilterPredicate(m_HelperObjectFilterPredicate);
}
else
{
m_FilterModel->RemoveFilterPredicate(m_HelperObjectFilterPredicate);
}
}
bool hideNodesWithNoData = !prefs->GetBool("Show nodes containing no data", false);
if (m_FilterModel->HasFilterPredicate(m_NodeWithNoDataFilterPredicate) != hideNodesWithNoData)
{
if (hideNodesWithNoData)
{
m_FilterModel->AddFilterPredicate(m_NodeWithNoDataFilterPredicate);
}
else
{
m_FilterModel->RemoveFilterPredicate(m_NodeWithNoDataFilterPredicate);
}
}
m_NodeTreeView->expandAll();
m_NodeTreeModel->SetAllowHierarchyChange(prefs->GetBool("Allow changing of parent node", false));
GlobalReinitAction::Run(GetSite(), GetDataStorage());
}
QItemSelectionModel* QmitkDataManagerView::GetDataNodeSelectionModel() const
{
return m_NodeTreeView->selectionModel();
}
diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDataManagerItemDelegate.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDataManagerItemDelegate.cpp
index fc48fd6312..6c34ebeb8d 100644
--- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDataManagerItemDelegate.cpp
+++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkDataManagerItemDelegate.cpp
@@ -1,41 +1,41 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <QLineEdit>
#include "QmitkDataManagerItemDelegate.h"
QmitkDataManagerItemDelegate::QmitkDataManagerItemDelegate(QObject* parent)
: QStyledItemDelegate(parent)
{
}
QmitkDataManagerItemDelegate::~QmitkDataManagerItemDelegate()
{
}
void QmitkDataManagerItemDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
QVariant data = index.data();
if (!data.isValid())
return;
- if (data.type() == QVariant::String)
+ if (data.typeId() == QMetaType::QString)
{
QLineEdit* lineEdit = qobject_cast<QLineEdit*>(editor);
lineEdit->setText(data.toString());
}
else
{
QStyledItemDelegate::setEditorData(editor, index);
}
}
diff --git a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp
index 23e017ba55..f32ab1c17d 100644
--- a/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp
+++ b/Plugins/org.mitk.gui.qt.datamanager/src/internal/QmitkNodeTableViewKeyFilter.cpp
@@ -1,124 +1,124 @@
/*============================================================================
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 "QmitkNodeTableViewKeyFilter.h"
#include "../QmitkDataManagerView.h"
// mitk gui qt application plugin
#include <QmitkDataNodeGlobalReinitAction.h>
#include <QmitkDataNodeHideAllAction.h>
#include <QmitkDataNodeReinitAction.h>
#include <QmitkDataNodeRemoveAction.h>
#include <QmitkDataNodeShowDetailsAction.h>
#include <QmitkDataNodeToggleVisibilityAction.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
// qt
#include <QKeyEvent>
#include <QKeySequence>
namespace
{
mitk::IPreferences* GetPreferences()
{
auto* preferencesService = mitk::CoreServices::GetPreferencesService();
return preferencesService->GetSystemPreferences()->Node("DataManager/Hotkeys");
}
}
QmitkNodeTableViewKeyFilter::QmitkNodeTableViewKeyFilter(QObject *dataManagerView, mitk::DataStorage *dataStorage)
: QObject(dataManagerView), m_DataStorage(dataStorage)
{
}
bool QmitkNodeTableViewKeyFilter::eventFilter(QObject *obj, QEvent *event)
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNull())
{
// standard event processing
return QObject::eventFilter(obj, event);
}
QmitkDataManagerView *dataManagerView = qobject_cast<QmitkDataManagerView *>(this->parent());
if (event->type() == QEvent::KeyPress && dataManagerView)
{
auto* prefs = GetPreferences();
QKeySequence makeAllInvisible = QKeySequence(QString::fromStdString(prefs->Get("Make all nodes invisible", "Ctrl+V")));
QKeySequence toggleVisibility = QKeySequence(QString::fromStdString(prefs->Get("Toggle visibility of selected nodes", "V")));
QKeySequence deleteSelectedNodes = QKeySequence(QString::fromStdString(prefs->Get("Delete selected nodes", "Del")));
QKeySequence reinit = QKeySequence(QString::fromStdString(prefs->Get("Reinit selected nodes", "R")));
QKeySequence globalReinit = QKeySequence(QString::fromStdString(prefs->Get("Global reinit", "Ctrl+R")));
QKeySequence showInfo = QKeySequence(QString::fromStdString(prefs->Get("Show node information", "Ctrl+I")));
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
- QKeySequence keySequence = QKeySequence(keyEvent->modifiers() + keyEvent->key());
+ QKeySequence keySequence = QKeySequence(keyEvent->modifiers() | keyEvent->key());
// if no modifier was pressed the sequence is now empty
if (keySequence.isEmpty())
{
keySequence = QKeySequence(keyEvent->key());
}
auto selectedNodes = AbstractDataNodeAction::GetSelectedNodes(dataManagerView->GetSite());
if (keySequence == makeAllInvisible)
{
if (selectedNodes.empty())
{
// if no nodes are selected, hide all nodes of the data storage
auto nodeset = dataStorage->GetAll();
for (auto it = nodeset->Begin(); it != nodeset->End(); ++it)
{
mitk::DataNode* node = it->Value();
if (nullptr != node)
{
selectedNodes.push_back(node);
}
}
}
HideAllAction::Run(selectedNodes);
return true;
}
if (keySequence == deleteSelectedNodes)
{
RemoveAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes);
return true;
}
if (keySequence == toggleVisibility)
{
ToggleVisibilityAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes);
return true;
}
if (keySequence == reinit)
{
ReinitAction::Run(dataManagerView->GetSite(), dataStorage, selectedNodes);
return true;
}
if (keySequence == globalReinit)
{
GlobalReinitAction::Run(dataManagerView->GetSite(), dataStorage);
return true;
}
if (keySequence == showInfo)
{
ShowDetailsAction::Run(selectedNodes);
return true;
}
}
// standard event processing
return QObject::eventFilter(obj, event);
}
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/CMakeLists.txt b/Plugins/org.mitk.gui.qt.deformableclippingplane/CMakeLists.txt
deleted file mode 100644
index 8dd1c33292..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/CMakeLists.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-project(org_mitk_gui_qt_deformableclippingplane)
-
-mitk_create_plugin(
- EXPORT_DIRECTIVE DEFORMABLECLIPPINGPLANE_EXPORT
- EXPORTED_INCLUDE_SUFFIXES src
-)
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane.dox b/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane.dox
deleted file mode 100644
index e4eb5ea593..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane.dox
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
-\page org_mitk_views_deformableclippingplane The Clipping Plane View
-
-\imageMacro{QmitkClippingPlane_Icon.png,"Icon of the Clipping Plane Plugin",5.00}
-
-
-\imageMacro{QmitkClippingPlane_Overview2.png,"Clipping Plane view",16.00}
-
-\tableofcontents
-
-\section org_mitk_views_clippingPlaneManualOverview Overview
-
-The <b>Clipping Plane view</b> allows you to create clipping planes and calculate the volumina of the divided parts.
-
-
-\section org_mitk_views_clippingPlaneTechnicalIssue Technical Issue
-
-To use the Update Volumina function your image should be binary.
-
-\section org_mitk_views_clippingPlaneManualImageSelection Image Selection
-
-The Clipping Plane view makes use of the Data Manager view to give you an overview of all images, segmentations and clipping planes.
-
-\imageMacro{QmitkClippingPlane_DataManager.png,"Data Manager is used for selecting the current clipping plane. The reference plane is selected in the drop down box of the control area.",8.00}
-
-To select the reference plane use the drop down box in the control area of the Clipping Plane view or the Data Manager. The clipping plane selected in the Data Manager is displayed below the drop down box. If no clipping plane exists or none is selected create a new clipping plane by using the "Create new clipping plane" button.
-Some items of the graphical user interface might be disabled when no plane is selected.
-In any case, the application will give you hints if a selection is needed.
-
-\section org_mitk_views_clippingPlaneCreating Creating New Clipping Plane
-
-If you want to create a new clipping plane select an image from the Data Manager and press the button "Create new clipping plane". Optionally you can enable the "...with surface model" option.
-
-\section org_mitk_views_clippingPlaneInteraction Interaction with the planes
-\imageMacro{QmitkClippingPlane_Interaction.png,"The interaction buttons",5.00}
-
-You have different options to interact with the clipping planes:
-
-\subsection org_mitk_views_clippingPlaneTranslation Translation
-
-In Translation mode you can change the position of the clipping plane.
- - Click the Translation Button
- - Move mouse over the selected clipping plane (the plane changes its color from blue to green)
- - Hold mouse-left button and move the mouse orthogonally to the plane
-
-\subsection org_mitk_views_clippingPlaneRotation Rotation
-
-In Rotation mode you can change the angle of the clipping plane.
- - Click the Rotation Button
- - Move mouse over the selected clipping plane (the plane changes its color from blue to green)
- - Hold mouse-left button and move the mouse in the direction it should be rotated
-
-\subsection org_mitk_views_clippingPlaneDeformation Deformation
-
-In Deformation mode you can change the surface of the clipping plane.
- - Click the Deformation Button
- - Move mouse over the selected clipping plane (the plane changes its color from blue to green). The deformation area is highlighted in red and yellow.
- - On mouse-scrolling you can change the size of the deformation area (Scroll-Down = smaller / Scroll-Up = bigger).
- - Hold mouse-left button and move the mouse orthogonally to the plane to deformate the plane
-
-\section org_mitk_views_clippingPlaneUpdateVolumina Update Volumina
-
-\imageMacro{QmitkClippingPlane_UpdateVolumina.png,"The 'Update Volumina' button",5.00}
-
-Calculating the volumina of the segmentation parts, which are divided by the clipping plane(s).
- - Create a segmentation (see Segmentation-Manual)
- - Create one or more clipping plane(s)
- - Use the interaction buttons (Translation, Rotation, Deformation) to adjust the clipping plane for intersecting the segmentation
- - (You can decide which planes shouldn't be included for the calculation by changing their visibility to invisible)
- - Click button "Update Volumina" button
- - The intersected parts are displayed in different colors and their volumina are shown beneath the "Update Volumina" button
-
-**/
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_DataManager.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_DataManager.png
deleted file mode 100644
index d786549d26..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_DataManager.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Icon.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Icon.png
deleted file mode 100644
index c8e3ab8953..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Icon.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Interaction.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Interaction.png
deleted file mode 100644
index 0ed78e487f..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Interaction.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Overview.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Overview.png
deleted file mode 100644
index 3e1de5fb08..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Overview.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Overview2.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Overview2.png
deleted file mode 100644
index c261f169b4..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_Overview2.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_UpdateVolumina.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_UpdateVolumina.png
deleted file mode 100644
index 11baa0631c..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/documentation/UserManual/QmitkClippingPlane_UpdateVolumina.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/files.cmake b/Plugins/org.mitk.gui.qt.deformableclippingplane/files.cmake
deleted file mode 100644
index d6fb308c8c..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/files.cmake
+++ /dev/null
@@ -1,21 +0,0 @@
-set(CPP_FILES
- src/internal/QmitkDeformableClippingPlaneView.cpp
- src/internal/mitkPluginActivator.cpp
-)
-
-set(MOC_H_FILES
- src/internal/mitkPluginActivator.h
- src/internal/QmitkDeformableClippingPlaneView.h
-)
-
-set(UI_FILES
- src/internal/QmitkDeformableClippingPlaneViewControls.ui
-)
-
-set(CACHED_RESOURCE_FILES
- resources/deformablePlane.png
- resources/clipping_plane_translate_48x48.png
- resources/clipping_plane_rotate48x48.png
- resources/clipping_plane_deform48x48.png
- plugin.xml
-)
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.deformableclippingplane/manifest_headers.cmake
deleted file mode 100644
index b64619ac32..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/manifest_headers.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(Plugin-Name "Clipping Plane")
-set(Plugin-Version "1.0.0")
-set(Plugin-Vendor "German Cancer Research Center (DKFZ)")
-set(Plugin-ContactAddress "https://www.mitk.org")
-set(Require-Plugin org.mitk.gui.qt.common org.mitk.gui.qt.datamanager)
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/plugin.xml b/Plugins/org.mitk.gui.qt.deformableclippingplane/plugin.xml
deleted file mode 100644
index 09a9fd4c0c..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/plugin.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin>
- <extension point="org.blueberry.ui.views">
- <view id="org.mitk.views.deformableclippingplane"
- name="Clipping Plane"
- category="Segmentation"
- class="QmitkDeformableClippingPlaneView"
- icon="resources/deformablePlane.png">
- <description>Allow the clipping of a volume using a deformable plane.</description>
- <keywordReference id="org.mitk.views.deformableclippingplane.ViewKeyword" />
- </view>
- </extension>
- <extension point="org.blueberry.ui.keywords">
- <keyword id="org.mitk.views.deformableclippingplane.ViewKeyword" label="Plane" />
- <keyword id="org.mitk.views.deformableclippingplane.ViewKeyword" label="Volume calculation" />
- <keyword id="org.mitk.views.deformableclippingplane.ViewKeyword" label="Splitting" />
- <keyword id="org.mitk.views.deformableclippingplane.ViewKeyword" label="Deformation" />
- <keyword id="org.mitk.views.deformableclippingplane.ViewKeyword" label="Volume analysis" />
- </extension>
-</plugin>
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_deform48x48.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_deform48x48.png
deleted file mode 100644
index 74af5fa6eb..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_deform48x48.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_rotate48x48.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_rotate48x48.png
deleted file mode 100644
index 19018f23fc..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_rotate48x48.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_translate_48x48.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_translate_48x48.png
deleted file mode 100644
index 01fe80f023..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_translate_48x48.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/deformablePlane.png b/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/deformablePlane.png
deleted file mode 100644
index c8e3ab8953..0000000000
Binary files a/Plugins/org.mitk.gui.qt.deformableclippingplane/resources/deformablePlane.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneView.cpp b/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneView.cpp
deleted file mode 100644
index 2d2ffa0a09..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneView.cpp
+++ /dev/null
@@ -1,584 +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 "QmitkDeformableClippingPlaneView.h"
-
-#include <usModuleRegistry.h>
-
-// mitk core
-#include <mitkImageToSurfaceFilter.h>
-#include <mitkInteractionConst.h>
-#include <mitkLevelWindowProperty.h>
-#include <mitkLookupTableProperty.h>
-#include <mitkNodePredicateDataType.h>
-#include <mitkNodePredicateNot.h>
-#include <mitkRenderingModeProperty.h>
-#include <mitkRotationOperation.h>
-#include <mitkSurfaceVtkMapper3D.h>
-#include <mitkVtkRepresentationProperty.h>
-#include <mitkVtkResliceInterpolationProperty.h>
-
-#include <mitkHeightFieldSurfaceClipImageFilter.h>
-#include <mitkClippingPlaneInteractor3D.h>
-#include <mitkLabeledImageLookupTable.h>
-#include <mitkLabeledImageVolumeCalculator.h>
-#include <mitkSurfaceDeformationDataInteractor3D.h>
-
-#include <vtkFloatArray.h>
-#include <vtkPointData.h>
-#include <vtkPlaneSource.h>
-#include <vtkProperty.h>
-
-#include <mitkILinkedRenderWindowPart.h>
-
-#include <array>
-
-const std::string QmitkDeformableClippingPlaneView::VIEW_ID = "org.mitk.views.deformableclippingplane";
-
-QmitkDeformableClippingPlaneView::QmitkDeformableClippingPlaneView()
- : QmitkAbstractView()
- , m_Controls(new Ui::QmitkDeformableClippingPlaneViewControls)
- , m_WorkingNode(nullptr)
-{
- auto isImage = mitk::TNodePredicateDataType<mitk::Image>::New();
- auto isNotHelperObject = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true)));
-
- m_IsImagePredicate = mitk::NodePredicateAnd::New(isImage, isNotHelperObject);
-
- m_IsClippingPlanePredicate = mitk::NodePredicateProperty::New("clippingPlane", mitk::BoolProperty::New(true));
-}
-
-QmitkDeformableClippingPlaneView::~QmitkDeformableClippingPlaneView()
-{
- if (m_WorkingNode.IsNotNull())
- m_WorkingNode->SetDataInteractor(nullptr);
-}
-
-void QmitkDeformableClippingPlaneView::SetFocus()
-{
- m_Controls->createNewPlanePushButton->setFocus();
-}
-
-void QmitkDeformableClippingPlaneView::CreateQtPartControl(QWidget *parent)
-{
- m_Controls->setupUi(parent);
-
- m_Controls->imageSelectionWidget->SetDataStorage(GetDataStorage());
- m_Controls->imageSelectionWidget->SetNodePredicate(m_IsImagePredicate);
- m_Controls->imageSelectionWidget->SetSelectionIsOptional(false);
- m_Controls->imageSelectionWidget->SetInvalidInfo("Select an image or segmentation.");
- m_Controls->imageSelectionWidget->SetPopUpTitel("Select an image or segmentation.");
-
- m_Controls->clippingPlaneSelector->SetDataStorage(this->GetDataStorage());
- m_Controls->clippingPlaneSelector->SetPredicate(m_IsClippingPlanePredicate);
-
- m_Controls->volumeGroupBox->setEnabled(false);
- m_Controls->interactionSelectionBox->setEnabled(false);
- m_Controls->planesWarningLabel->hide();
-
- this->CreateConnections();
-
- m_Controls->imageSelectionWidget->SetAutoSelectNewNodes(true);
-}
-
-void QmitkDeformableClippingPlaneView::OnCurrentSelectionChanged(const QList<mitk::DataNode::Pointer>& /*nodes*/)
-{
- this->UpdateView();
-}
-
-void QmitkDeformableClippingPlaneView::OnComboBoxSelectionChanged(const mitk::DataNode* node)
-{
- this->DeactivateInteractionButtons();
-
- auto selectedNode = const_cast<mitk::DataNode*>(node);
- if(nullptr != selectedNode)
- {
- if(m_WorkingNode.IsNotNull())
- selectedNode->SetDataInteractor(m_WorkingNode->GetDataInteractor());
-
- m_WorkingNode = selectedNode;
- }
-
- this->UpdateView();
-}
-
-void QmitkDeformableClippingPlaneView::OnCreateNewClippingPlane()
-{
- this->DeactivateInteractionButtons();
-
- auto plane = mitk::Surface::New();
- auto planeSource = vtkSmartPointer<vtkPlaneSource>::New();
-
- planeSource->SetOrigin(-32.0, -32.0, 0.0);
- planeSource->SetPoint1(32.0, -32.0, 0.0);
- planeSource->SetPoint2(-32.0, 32.0, 0.0);
- planeSource->SetResolution(128, 128);
- planeSource->Update();
-
- plane->SetVtkPolyData(planeSource->GetOutput());
-
- mitk::ScalarType imageDiagonal = 200.0;
-
- auto selectedNode = m_Controls->imageSelectionWidget->GetSelectedNode();
- if (selectedNode.IsNotNull())
- {
- auto selectedImage = dynamic_cast<mitk::Image*>(selectedNode->GetData());
- if (nullptr != selectedImage)
- {
- // check if user wants a surface model
- if (m_Controls->surfaceModelCheckBox->isChecked())
- {
- //Check if there is a surface node from the image. If not, create one
- bool createSurfaceFromImage = true;
- auto isSurface = mitk::NodePredicateDataType::New("Surface");
- auto childNodes = GetDataStorage()->GetDerivations(selectedNode, isSurface, true);
-
- for (mitk::DataStorage::SetOfObjects::ConstIterator it = childNodes->Begin();
- it != childNodes->End(); it++)
- {
- if (it.Value().IsNotNull() && it->Value()->GetName() == selectedNode->GetName())
- {
- createSurfaceFromImage = false;
- it.Value()->SetVisibility(true);
- }
- }
-
- if (createSurfaceFromImage)
- {
- //Lsg 2: Surface for the 3D-perspective
- auto surfaceFilter = mitk::ImageToSurfaceFilter::New();
- surfaceFilter->SetInput(selectedImage);
- surfaceFilter->SetThreshold(1);
- surfaceFilter->SetSmooth(true);
- //Downsampling
- surfaceFilter->SetDecimate(mitk::ImageToSurfaceFilter::DecimatePro);
-
- auto surfaceNode = mitk::DataNode::New();
- surfaceNode->SetData(surfaceFilter->GetOutput());
- surfaceNode->SetProperty("color", selectedNode->GetProperty("color"));
- surfaceNode->SetOpacity(0.5);
- surfaceNode->SetName(selectedNode->GetName());
- this->GetDataStorage()->Add(surfaceNode, selectedNode);
- }
- }
-
- //If an image is selected trim the plane to this.
- imageDiagonal = selectedImage->GetGeometry()->GetDiagonalLength();
- plane->SetOrigin(selectedImage->GetGeometry()->GetCenter());
-
- // Rotate plane
- mitk::Vector3D rotationAxis;
- mitk::FillVector3D(rotationAxis, 0.0, 1.0, 0.0);
- mitk::RotationOperation op(mitk::OpROTATE, selectedImage->GetGeometry()->GetCenter(), rotationAxis, 90.0);
- plane->GetGeometry()->ExecuteOperation(&op);
- }
- }
-
- // equivalent to the extent and resolution function of the clipping plane
- const auto x = imageDiagonal * 0.9;
- planeSource->SetOrigin(-x / 2.0, -x / 2.0, 0.0);
- planeSource->SetPoint1(x / 2.0, -x / 2.0, 0.0);
- planeSource->SetPoint2(-x / 2.0, x / 2.0, 0.0);
- planeSource->SetResolution(64, 64);
- planeSource->Update();
-
- plane->SetVtkPolyData(planeSource->GetOutput());
-
- // Set scalars (for colorization of plane)
- vtkFloatArray *scalars = vtkFloatArray::New();
- scalars->SetName("Distance");
- scalars->SetNumberOfComponents(1);
-
- const auto numerOfPoints = plane->GetVtkPolyData(0)->GetNumberOfPoints();
- for (std::remove_const_t<decltype(numerOfPoints)> i = 0; i < plane->GetVtkPolyData(0)->GetNumberOfPoints(); ++i)
- {
- scalars->InsertNextValue(-1.0);
- }
- plane->GetVtkPolyData(0)->GetPointData()->SetScalars(scalars);
- plane->GetVtkPolyData(0)->GetPointData()->Update();
-
- auto planeNode = mitk::DataNode::New();
- planeNode->SetData(plane);
-
- std::stringstream planeName;
- planeName << "ClippingPlane ";
- planeName << this->GetAllClippingPlanes()->Size() + 1;
-
- planeNode->SetName(planeName.str());
- planeNode->AddProperty("clippingPlane", mitk::BoolProperty::New(true));
- // Make plane pickable
- planeNode->SetBoolProperty("pickable", true);
-
- mitk::SurfaceVtkMapper3D::SetDefaultProperties(planeNode);
-
- // Don't include plane in bounding box!
- planeNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
-
- // Set lookup table for plane surface visualization
- auto lookupTablevtk = vtkSmartPointer<vtkLookupTable>::New();
- lookupTablevtk->SetHueRange(0.6, 0.0);
- lookupTablevtk->SetSaturationRange(1.0, 1.0);
- lookupTablevtk->SetValueRange(1.0, 1.0);
- lookupTablevtk->SetTableRange(-1.0, 1.0);
- lookupTablevtk->Build();
-
- auto lookupTable = mitk::LookupTable::New();
- lookupTable->SetVtkLookupTable(lookupTablevtk);
-
- auto prop = mitk::LookupTableProperty::New(lookupTable);
-
- planeNode->SetProperty("LookupTable", prop);
- planeNode->SetBoolProperty("scalar visibility", true);
- planeNode->SetBoolProperty("color mode", true);
- planeNode->SetFloatProperty("ScalarsRangeMinimum", -1.0);
- planeNode->SetFloatProperty("ScalarsRangeMaximum", 1.0);
-
- // Configure material so that only scalar colors are shown
- planeNode->SetColor(0.0f, 0.0f, 0.0f);
- planeNode->SetOpacity(1.0f);
- planeNode->SetFloatProperty("material.wireframeLineWidth", 2.0f);
-
- //Set view of plane to wireframe
- planeNode->SetProperty("material.representation", mitk::VtkRepresentationProperty::New(VTK_WIREFRAME));
-
- //Add the plane to data storage
- this->GetDataStorage()->Add(planeNode);
-
- //Change the index of the selector to the new generated node
- m_Controls->clippingPlaneSelector->setCurrentIndex(m_Controls->clippingPlaneSelector->Find(planeNode));
-
- m_Controls->interactionSelectionBox->setEnabled(true);
-
- if (auto renderWindowPart = dynamic_cast<mitk::ILinkedRenderWindowPart*>(this->GetRenderWindowPart()))
- {
- renderWindowPart->EnableSlicingPlanes(false);
- }
-
- mitk::RenderingManager::GetInstance()->RequestUpdateAll();
-}
-
-void QmitkDeformableClippingPlaneView::OnCalculateClippingVolume()
-{
- auto selectedNode = m_Controls->imageSelectionWidget->GetSelectedNode();
- if (selectedNode.IsNull())
- {
- MITK_ERROR << "No segmentation selected! Can't calculate volume";
- return;
- }
-
- bool isSegmentation = false;
- selectedNode->GetBoolProperty("binary", isSegmentation);
- if (!isSegmentation)
- {
- MITK_ERROR << "No segmentation selected! Can't calculate volume";
- return;
- }
-
- std::vector<mitk::Surface*> clippingPlanes;
- mitk::DataStorage::SetOfObjects::ConstPointer allClippingPlanes = this->GetAllClippingPlanes();
- for (mitk::DataStorage::SetOfObjects::ConstIterator itPlanes = allClippingPlanes->Begin(); itPlanes != allClippingPlanes->End(); itPlanes++)
- {
- bool isVisible = false;
- itPlanes.Value()->GetBoolProperty("visible", isVisible);
- auto plane = dynamic_cast<mitk::Surface*>(itPlanes.Value()->GetData());
-
- if (isVisible && nullptr != plane)
- clippingPlanes.push_back(plane);
- }
-
- if (clippingPlanes.empty())
- {
- MITK_ERROR << "No clipping plane selected! Can't calculate volume";
- return;
- }
-
- // deactivate Tools
- this->DeactivateInteractionButtons();
- //Clear the list of volumes, before calculating the new values
- m_Controls->volumeList->clear();
-
- selectedNode->SetBoolProperty("visible", false);
-
- //set some properties for clipping the image-->Output: labeled Image
- mitk::HeightFieldSurfaceClipImageFilter::Pointer surfaceClipFilter = mitk::HeightFieldSurfaceClipImageFilter::New();
-
- surfaceClipFilter->SetInput(dynamic_cast<mitk::Image*>(selectedNode->GetData()));
- surfaceClipFilter->SetClippingModeToMultiPlaneValue();
- surfaceClipFilter->SetClippingSurfaces(clippingPlanes);
- surfaceClipFilter->Update();
-
- //delete the old clipped image node
- mitk::DataStorage::SetOfObjects::ConstPointer oldClippedNode = this->GetDataStorage()->GetSubset(mitk::NodePredicateProperty::New("name", mitk::StringProperty::New("Clipped Image")));
- if (oldClippedNode.IsNotNull())
- this->GetDataStorage()->Remove(oldClippedNode);
-
- //add the new clipped image node
- auto clippedNode = mitk::DataNode::New();
- mitk::Image::Pointer clippedImage = surfaceClipFilter->GetOutput();
- clippedImage->DisconnectPipeline();
- clippedNode->SetData(clippedImage);
- clippedNode->SetName("Clipped Image");
- clippedNode->SetColor(1.0, 1.0, 1.0); // color property will not be used, labeled image lookuptable will be used instead
- clippedNode->SetProperty("use color", mitk::BoolProperty::New(false));
- clippedNode->SetProperty("reslice interpolation", mitk::VtkResliceInterpolationProperty::New(VTK_RESLICE_NEAREST));
- clippedNode->SetOpacity(0.4);
- this->GetDataStorage()->Add(clippedNode);
-
- auto volumeCalculator = mitk::LabeledImageVolumeCalculator::New();
- volumeCalculator->SetImage(clippedImage);
- volumeCalculator->Calculate();
-
- auto volumes = volumeCalculator->GetVolumes();
-
- auto lookupTable = mitk::LabeledImageLookupTable::New();
- int lablesWithVolume = 0;
- const auto numberOfVolumes = volumes.size();
- for (std::remove_const_t<decltype(numberOfVolumes)> i = 1; i < numberOfVolumes; ++i)
- {
- if (0 != volumes[0])
- {
- lablesWithVolume++;
-
- mitk::Color color(GetLabelColor(lablesWithVolume));
- lookupTable->SetColorForLabel(i, color.GetRed(), color.GetGreen(), color.GetBlue(), 1.0);
-
- QColor qcolor;
- qcolor.setRgbF(color.GetRed(), color.GetGreen(), color.GetBlue(), 0.7);
-
- //output volume as string "x.xx ml"
- std::stringstream stream;
- stream << std::fixed << std::setprecision(2) << 0.001 * volumes[i] << " ml";
- stream << " ml";
-
- auto item = new QListWidgetItem();
- item->setText(QString::fromStdString(stream.str()));
- item->setBackgroundColor(qcolor);
- m_Controls->volumeList->addItem(item);
- }
- }
-
- //set the rendering mode to use the lookup table and level window
- clippedNode->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New(mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR));
- mitk::LookupTableProperty::Pointer lutProp = mitk::LookupTableProperty::New(lookupTable.GetPointer());
- clippedNode->SetProperty("LookupTable", lutProp);
- // it is absolutely important, to use the LevelWindow settings provided by
- // the LUT generator, otherwise, it is not guaranteed, that colors show
- // up correctly.
- clippedNode->SetProperty("levelwindow", mitk::LevelWindowProperty::New(lookupTable->GetLevelWindow()));
-}
-
-void QmitkDeformableClippingPlaneView::OnTranslationMode(bool check)
-{
- if (check)
- { //uncheck all other buttons
- m_Controls->rotationPushButton->setChecked(false);
- m_Controls->deformationPushButton->setChecked(false);
-
- mitk::ClippingPlaneInteractor3D::Pointer affineDataInteractor = mitk::ClippingPlaneInteractor3D::New();
- affineDataInteractor->LoadStateMachine("ClippingPlaneInteraction3D.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- affineDataInteractor->SetEventConfig("ClippingPlaneTranslationConfig.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- affineDataInteractor->SetDataNode(m_WorkingNode);
- }
- else
- m_WorkingNode->SetDataInteractor(nullptr);
-}
-
-void QmitkDeformableClippingPlaneView::OnRotationMode(bool check)
-{
- if (check)
- { //uncheck all other buttons
- m_Controls->translationPushButton->setChecked(false);
- m_Controls->deformationPushButton->setChecked(false);
-
- mitk::ClippingPlaneInteractor3D::Pointer affineDataInteractor = mitk::ClippingPlaneInteractor3D::New();
- affineDataInteractor->LoadStateMachine("ClippingPlaneInteraction3D.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- affineDataInteractor->SetEventConfig("ClippingPlaneRotationConfig.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- affineDataInteractor->SetDataNode(m_WorkingNode);
- }
- else
- m_WorkingNode->SetDataInteractor(nullptr);
-}
-
-void QmitkDeformableClippingPlaneView::OnDeformationMode(bool check)
-{
- if (check)
- { //uncheck all other buttons
- m_Controls->translationPushButton->setChecked(false);
- m_Controls->rotationPushButton->setChecked(false);
-
- mitk::SurfaceDeformationDataInteractor3D::Pointer surfaceDataInteractor = mitk::SurfaceDeformationDataInteractor3D::New();
- surfaceDataInteractor->LoadStateMachine("ClippingPlaneInteraction3D.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- surfaceDataInteractor->SetEventConfig("ClippingPlaneDeformationConfig.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- surfaceDataInteractor->SetDataNode(m_WorkingNode);
- }
- else
- m_WorkingNode->SetDataInteractor(nullptr);
-}
-
-void QmitkDeformableClippingPlaneView::CreateConnections()
-{
- connect(m_Controls->imageSelectionWidget, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged,
- this, &QmitkDeformableClippingPlaneView::OnCurrentSelectionChanged);
- connect(m_Controls->translationPushButton, &QPushButton::toggled,
- this, &QmitkDeformableClippingPlaneView::OnTranslationMode);
- connect(m_Controls->rotationPushButton, &QPushButton::toggled,
- this, &QmitkDeformableClippingPlaneView::OnRotationMode);
- connect(m_Controls->deformationPushButton, &QPushButton::toggled,
- this, &QmitkDeformableClippingPlaneView::OnDeformationMode);
- connect(m_Controls->createNewPlanePushButton, &QPushButton::clicked,
- this, &QmitkDeformableClippingPlaneView::OnCreateNewClippingPlane);
- connect(m_Controls->updateVolumePushButton, &QPushButton::clicked,
- this, &QmitkDeformableClippingPlaneView::OnCalculateClippingVolume);
- connect(m_Controls->clippingPlaneSelector, &QmitkDataStorageComboBox::OnSelectionChanged,
- this, &QmitkDeformableClippingPlaneView::OnComboBoxSelectionChanged);
-}
-
-void QmitkDeformableClippingPlaneView::NodeRemoved(const mitk::DataNode* node)
-{
- if (m_IsClippingPlanePredicate->CheckNode(node))
- {
- if (this->GetAllClippingPlanes()->Size() <= 1)
- {
- m_WorkingNode = nullptr;
- this->UpdateView();
- }
- }
-}
-
-void::QmitkDeformableClippingPlaneView::NodeChanged(const mitk::DataNode*)
-{
- this->UpdateView();
-}
-
-void QmitkDeformableClippingPlaneView::UpdateView()
-{
- auto selectedNode = m_Controls->imageSelectionWidget->GetSelectedNode();
- if (selectedNode.IsNotNull())
- {
- m_Controls->selectedReferenceImageLabel->setText(QString::fromUtf8(selectedNode->GetName().c_str()));
- if (m_WorkingNode.IsNotNull())
- {
- bool isSegmentation = false;
- selectedNode->GetBoolProperty("binary", isSegmentation);
- m_Controls->interactionSelectionBox->setEnabled(true);
-
- m_Controls->volumeGroupBox->setEnabled(isSegmentation);
-
- //clear list --> than search for all shown clipping plans (max 7 planes)
- m_Controls->selectedClippingPlanesLabel->setText("");
- m_Controls->planesWarningLabel->hide();
- int volumePlanes = 0;
-
- auto allClippingPlanes = this->GetAllClippingPlanes();
- for (mitk::DataStorage::SetOfObjects::ConstIterator itPlanes = allClippingPlanes->Begin(); itPlanes != allClippingPlanes->End(); itPlanes++)
- {
- bool isVisible = false;
- itPlanes.Value()->GetBoolProperty("visible", isVisible);
- if (isVisible)
- {
- if (volumePlanes < 7)
- {
- ++volumePlanes;
- m_Controls->selectedClippingPlanesLabel->setText(m_Controls->selectedClippingPlanesLabel->text().append(QString::fromStdString(itPlanes.Value()->GetName()+"\n")));
- }
- else
- {
- m_Controls->planesWarningLabel->show();
- return;
- }
- }
- }
- }
- else
- {
- m_Controls->volumeGroupBox->setEnabled(false);
- m_Controls->interactionSelectionBox->setEnabled(false);
- m_Controls->selectedClippingPlanesLabel->setText("");
- m_Controls->volumeList->clear();
- }
- }
- else
- {
- m_Controls->volumeGroupBox->setEnabled(false);
- m_Controls->selectedReferenceImageLabel->setText("");
- m_Controls->selectedClippingPlanesLabel->setText("");
- m_Controls->planesWarningLabel->hide();
-
- m_Controls->interactionSelectionBox->setEnabled(m_WorkingNode.IsNotNull());
- }
-}
-
-mitk::DataStorage::SetOfObjects::ConstPointer QmitkDeformableClippingPlaneView::GetAllClippingPlanes()
-{
- auto allPlanes = GetDataStorage()->GetSubset(m_IsClippingPlanePredicate);
- return allPlanes;
-}
-
-mitk::Color QmitkDeformableClippingPlaneView::GetLabelColor(int label)
-{
- std::array<float, 3> color = { 0.0f, 0.0f, 0.0f };
-
- switch (label % 6)
- {
- case 0: // red
- color[0] = 1.0f;
- break;
- case 1: // green
- color[1] = 1.0f;
- break;
- case 2: // blue
- color[2] = 1.0f;
- break;
- case 3: // yellow
- color[0] = 1.0f;
- color[1] = 1.0f;
- break;
- case 4: // magenta
- color[0] = 1.0f;
- color[2] = 1.0f;
- break;
- case 5: // cyan
- color[1] = 1.0f;
- color[2] = 1.0f;
- default: // black
- break;
- }
-
- int outerCycleNr = label / 6;
- int cycleSize = std::min(1, static_cast<int>(std::pow(2.0, std::log(outerCycleNr) / std::log(2.0))));
- int insideCycleCounter = outerCycleNr % cycleSize;
-
- float factor;
- if (0 == outerCycleNr)
- {
- factor = 255.0f;
- }
- else
- {
- factor = 256.0f / (2.0f * cycleSize) + insideCycleCounter * (256.0f / cycleSize);
- }
-
- color = {
- std::min(1.0f, color[0] / 256.0f * factor),
- std::min(1.0f, color[1] / 256.0f * factor),
- std::min(1.0f, color[2] / 256.0f * factor)
- };
-
- return mitk::Color(color.data());
-}
-
-void QmitkDeformableClippingPlaneView::DeactivateInteractionButtons()
-{
- m_Controls->translationPushButton->setChecked(false);
- m_Controls->rotationPushButton->setChecked(false);
- m_Controls->deformationPushButton->setChecked(false);
-}
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneView.h b/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneView.h
deleted file mode 100644
index 9b2a17dccb..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneView.h
+++ /dev/null
@@ -1,75 +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 QmitkDeformableClippingPlaneView_h
-#define QmitkDeformableClippingPlaneView_h
-
-#include <ui_QmitkDeformableClippingPlaneViewControls.h>
-
-#include <mitkImage.h>
-#include <mitkNodePredicateAnd.h>
-#include <mitkNodePredicateProperty.h>
-#include <QmitkAbstractView.h>
-
-typedef itk::RGBPixel< float > Color;
-
-/**
- * @brief
- */
-class QmitkDeformableClippingPlaneView : public QmitkAbstractView
-{
- Q_OBJECT
-
-public:
-
- static const std::string VIEW_ID;
-
- QmitkDeformableClippingPlaneView();
- ~QmitkDeformableClippingPlaneView() override;
-
- void SetFocus() override;
-
-private Q_SLOTS:
-
- void OnCurrentSelectionChanged(const QList<mitk::DataNode::Pointer>& nodes);
- void OnComboBoxSelectionChanged(const mitk::DataNode* node);
- void OnCreateNewClippingPlane();
- void OnCalculateClippingVolume();
-
- void OnTranslationMode(bool check);
- void OnRotationMode(bool check);
- void OnDeformationMode(bool check);
-
-private:
-
- void CreateQtPartControl(QWidget *parent) override;
- virtual void CreateConnections();
-
- void NodeRemoved(const mitk::DataNode* node) override;
- void NodeChanged(const mitk::DataNode* node) override;
-
- void UpdateView();
-
- mitk::DataStorage::SetOfObjects::ConstPointer GetAllClippingPlanes();
- mitk::Color GetLabelColor(int label);
- void DeactivateInteractionButtons();
-
- Ui::QmitkDeformableClippingPlaneViewControls* m_Controls;
-
- mitk::NodePredicateAnd::Pointer m_IsImagePredicate;
- mitk::NodePredicateProperty::Pointer m_IsClippingPlanePredicate;
-
- mitk::DataNode::Pointer m_WorkingNode;
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneViewControls.ui b/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneViewControls.ui
deleted file mode 100644
index f19a2edcc3..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/QmitkDeformableClippingPlaneViewControls.ui
+++ /dev/null
@@ -1,429 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkDeformableClippingPlaneViewControls</class>
- <widget class="QWidget" name="QmitkDeformableClippingPlaneViewControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>300</width>
- <height>600</height>
- </rect>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="windowTitle">
- <string>Deformable surface</string>
- </property>
- <layout class="QVBoxLayout">
- <item>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="imageSelectionLabel">
- <property name="text">
- <string>Selected image</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QmitkSingleNodeSelectionWidget" name="imageSelectionWidget" native="true">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Minimum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>40</height>
- </size>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QGroupBox" name="planeGroupBox">
- <property name="checkable">
- <bool>false</bool>
- </property>
- <property name="checked">
- <bool>false</bool>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_1">
- <item>
- <widget class="QPushButton" name="createNewPlanePushButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Create new clipping plane</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QCheckBox" name="surfaceModelCheckBox">
- <property name="layoutDirection">
- <enum>Qt::RightToLeft</enum>
- </property>
- <property name="text">
- <string>...with surface model</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QLabel" name="clippingPlaneSelectorLabel">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Maximum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="maximumSize">
- <size>
- <width>16777215</width>
- <height>16777215</height>
- </size>
- </property>
- <property name="text">
- <string>Plane</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QmitkDataStorageComboBox" name="clippingPlaneSelector">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="sizeAdjustPolicy">
- <enum>QComboBox::AdjustToMinimumContentsLength</enum>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QGroupBox" name="interactionSelectionBox">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="font">
- <font>
- <weight>50</weight>
- <bold>false</bold>
- </font>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout_3">
- <item>
- <widget class="QPushButton" name="translationPushButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>20</width>
- <height>50</height>
- </size>
- </property>
- <property name="toolTip">
- <string>Translation</string>
- </property>
- <property name="text">
- <string/>
- </property>
- <property name="icon">
- <iconset>
- <normaloff>:/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_translate_48x48.png</normaloff>:/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_translate_48x48.png</iconset>
- </property>
- <property name="iconSize">
- <size>
- <width>32</width>
- <height>32</height>
- </size>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="autoRepeat">
- <bool>false</bool>
- </property>
- <property name="autoExclusive">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="rotationPushButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>20</width>
- <height>50</height>
- </size>
- </property>
- <property name="toolTip">
- <string>Rotation</string>
- </property>
- <property name="text">
- <string/>
- </property>
- <property name="icon">
- <iconset>
- <normaloff>:/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_rotate48x48.png</normaloff>:/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_rotate48x48.png</iconset>
- </property>
- <property name="iconSize">
- <size>
- <width>32</width>
- <height>32</height>
- </size>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="autoExclusive">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="deformationPushButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>20</width>
- <height>50</height>
- </size>
- </property>
- <property name="toolTip">
- <string>Deformation</string>
- </property>
- <property name="text">
- <string/>
- </property>
- <property name="icon">
- <iconset>
- <normaloff>:/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_deform48x48.png</normaloff>:/org.mitk.gui.qt.deformableclippingplane/resources/clipping_plane_deform48x48.png</iconset>
- </property>
- <property name="iconSize">
- <size>
- <width>32</width>
- <height>32</height>
- </size>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="autoExclusive">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Preferred</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="planesWarningLabel">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Please select less or equal 6 clipping planes!</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="volumeGroupBox">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Minimum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="title">
- <string/>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_5">
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <layout class="QVBoxLayout" name="verticalLayout_2">
- <item>
- <widget class="QLabel" name="referenceImageLabel">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Referenced image</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="clippingPlanesLabel">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Clipping planes</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <layout class="QVBoxLayout" name="verticalLayout_4">
- <item>
- <widget class="QLabel" name="selectedReferenceImageLabel">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="selectedClippingPlanesLabel">
- <property name="font">
- <font>
- <pointsize>8</pointsize>
- </font>
- </property>
- <property name="alignment">
- <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QPushButton" name="updateVolumePushButton">
- <property name="text">
- <string>Update Volumina</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_2">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Preferred</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QListWidget" name="volumeList">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Minimum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <layoutdefault spacing="6" margin="11"/>
- <customwidgets>
- <customwidget>
- <class>QmitkSingleNodeSelectionWidget</class>
- <extends>QWidget</extends>
- <header location="global">QmitkSingleNodeSelectionWidget.h</header>
- </customwidget>
- <customwidget>
- <class>QmitkDataStorageComboBox</class>
- <extends>QComboBox</extends>
- <header location="global">QmitkDataStorageComboBox.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/mitkPluginActivator.cpp
deleted file mode 100644
index 6fdaaa8cdd..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/mitkPluginActivator.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 "mitkPluginActivator.h"
-#include "QmitkDeformableClippingPlaneView.h"
-
-void mitk::PluginActivator::start(ctkPluginContext *context)
-{
- BERRY_REGISTER_EXTENSION_CLASS(QmitkDeformableClippingPlaneView, context)
-}
-
-void mitk::PluginActivator::stop(ctkPluginContext *)
-{
-}
diff --git a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/mitkPluginActivator.h
deleted file mode 100644
index 0adc31438c..0000000000
--- a/Plugins/org.mitk.gui.qt.deformableclippingplane/src/internal/mitkPluginActivator.h
+++ /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.
-
-============================================================================*/
-
-#ifndef mitkPluginActivator_h
-#define mitkPluginActivator_h
-
-#include <ctkPluginActivator.h>
-
-namespace mitk
-{
- class PluginActivator : public QObject, public ctkPluginActivator
- {
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_deformableclippingplane")
- Q_INTERFACES(ctkPluginActivator)
-
- public:
- void start(ctkPluginContext *context) override;
- void stop(ctkPluginContext *context) override;
- };
-}
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkStoreSCPLauncher.cpp b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkStoreSCPLauncher.cpp
index 1ef4353f0e..cb8de364af 100644
--- a/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkStoreSCPLauncher.cpp
+++ b/Plugins/org.mitk.gui.qt.dicombrowser/src/internal/QmitkStoreSCPLauncher.cpp
@@ -1,199 +1,199 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkStoreSCPLauncher.h"
#include <QMessageBox>
#include <QProcessEnvironment>
#include <mitkLog.h>
#include <fstream>
#include <iostream>
#include <QFile>
#include <QTextStream>
#include <QIODevice>
#include <QDir>
#include <QDirIterator>
#include <QCoreApplication>
#include "org_mitk_gui_qt_dicombrowser_config.h"
QmitkStoreSCPLauncher::QmitkStoreSCPLauncher(QmitkStoreSCPLauncherBuilder* builder)
: m_StoreSCP(new QProcess())
{
m_StoreSCP->setProcessChannelMode(QProcess::MergedChannels);
connect( m_StoreSCP, SIGNAL(error(QProcess::ProcessError)),this, SLOT(OnProcessError(QProcess::ProcessError)));
connect( m_StoreSCP, SIGNAL(stateChanged(QProcess::ProcessState)),this, SLOT(OnStateChanged(QProcess::ProcessState)));
connect( m_StoreSCP, SIGNAL(readyReadStandardOutput()),this, SLOT(OnReadyProcessOutput()));
SetArgumentList(builder);
}
QmitkStoreSCPLauncher::~QmitkStoreSCPLauncher()
{
disconnect( m_StoreSCP, SIGNAL(error(QProcess::ProcessError)),this, SLOT(OnProcessError(QProcess::ProcessError)));
disconnect( m_StoreSCP, SIGNAL(stateChanged(QProcess::ProcessState)),this, SLOT(OnStateChanged(QProcess::ProcessState)));
disconnect( m_StoreSCP, SIGNAL(readyReadStandardOutput()),this, SLOT(OnReadyProcessOutput()));
m_StoreSCP->close();
m_StoreSCP->waitForFinished(1000);
delete m_StoreSCP;
}
void QmitkStoreSCPLauncher::StartStoreSCP()
{
FindPathToStoreSCP();
m_StoreSCP->start(m_PathToStoreSCP,m_ArgumentList);
}
void QmitkStoreSCPLauncher::FindPathToStoreSCP()
{
QString appPath= QCoreApplication::applicationDirPath();
if(m_PathToStoreSCP.isEmpty())
{
QString fileName;
#ifdef _WIN32
fileName = "/storescp.exe";
#else
fileName = "/storescp";
#endif
m_PathToStoreSCP = appPath + fileName;
//In development the storescp isn't copied into bin directory
if(!QFile::exists(m_PathToStoreSCP))
{
m_PathToStoreSCP = static_cast<QString>(DCMTK_STORESCP);
}
}
}
void QmitkStoreSCPLauncher::OnReadyProcessOutput()
{
QString out(m_StoreSCP->readAllStandardOutput());
QStringList allDataList,importList;
- allDataList = out.split("\n",QString::SkipEmptyParts);
+ allDataList = out.split("\n",Qt::SkipEmptyParts);
QStringListIterator it(allDataList);
while(it.hasNext())
{
QString output = it.next();
if (output.contains("E: "))
{
output.replace("E: ","");
m_ErrorText = output;
OnProcessError(QProcess::UnknownError);
return;
}
if(output.contains("I: storing DICOM file: "))
{
output.replace("I: storing DICOM file: ","");
output.replace("\\", "/"); // cannot handle backslashes
output.replace("\r", ""); // cannot handle carriage return
importList += output;
}
}
if(!importList.isEmpty())
{
emit SignalStartImport(importList);
}
}
void QmitkStoreSCPLauncher::OnProcessError(QProcess::ProcessError err)
{
switch(err)
{
case QProcess::FailedToStart:
m_ErrorText.prepend("Failed to start storage provider: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::Crashed:
m_ErrorText.prepend("Storage provider closed: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::Timedout:
m_ErrorText.prepend("Storage provider timeout: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::WriteError:
m_ErrorText.prepend("Storage provider write error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::ReadError:
m_ErrorText.prepend("Storage provider read error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
case QProcess::UnknownError:
m_ErrorText.prepend("Storage provider unknown error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
default:
m_ErrorText.prepend("Storage provider unknown error: ");
m_ErrorText.append(m_StoreSCP->errorString());
emit SignalStoreSCPError(m_ErrorText);
m_ErrorText.clear();
break;
}
}
void QmitkStoreSCPLauncher::OnStateChanged(QProcess::ProcessState status)
{
switch(status)
{
case QProcess::NotRunning:
m_StatusText.prepend("Storage provider not running!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
case QProcess::Starting:
m_StatusText.prepend("Starting storage provider!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
case QProcess::Running:
m_StatusText.prepend(m_ArgumentList[0]).prepend(" Port: ").prepend(m_ArgumentList[2]).prepend(" AET: ").prepend("Storage provider running! ");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
default:
m_StatusText.prepend("Storage provider unknown error!");
emit SignalStatusOfStoreSCP(m_StatusText);
m_StatusText.clear();
break;
}
}
void QmitkStoreSCPLauncher::SetArgumentList(QmitkStoreSCPLauncherBuilder* builder)
{
m_ArgumentList << *builder->GetPort() << QString("-aet") <<*builder->GetAETitle() << *builder->GetTransferSyntax()
<< *builder->GetOtherNetworkOptions() << *builder->GetMode() << QString("-od") << *builder->GetOutputDirectory();
}
QString QmitkStoreSCPLauncher::ArgumentListToQString()
{
QString argumentString;
QStringListIterator argumentIterator(m_ArgumentList);
while(argumentIterator.hasNext())
{
argumentString.append(" ");
argumentString.append(argumentIterator.next());
}
return argumentString;
}
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/CMakeLists.txt b/Plugins/org.mitk.gui.qt.eventrecorder/CMakeLists.txt
deleted file mode 100644
index 2f08c6d36d..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-project(org_mitk_gui_qt_eventrecorder)
-
-mitk_create_plugin(
- EXPORT_DIRECTIVE EVENTRECORDER_EXPORT
- EXPORTED_INCLUDE_SUFFIXES src
- MODULE_DEPENDS MitkQtWidgetsExt
-)
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/files.cmake b/Plugins/org.mitk.gui.qt.eventrecorder/files.cmake
deleted file mode 100644
index 858711fa87..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/files.cmake
+++ /dev/null
@@ -1,46 +0,0 @@
-set(SRC_CPP_FILES
-
-)
-
-set(INTERNAL_CPP_FILES
- org_mitk_gui_qt_eventrecorder_Activator.cpp
- InteractionEventRecorder.cpp
-)
-
-set(UI_FILES
- src/internal/InteractionEventRecorderControls.ui
-)
-
-set(MOC_H_FILES
- src/internal/org_mitk_gui_qt_eventrecorder_Activator.h
- src/internal/InteractionEventRecorder.h
-)
-
-# list of resource files which can be used by the plug-in
-# system without loading the plug-ins shared library,
-# for example the icon used in the menu and tabs for the
-# plug-in views in the workbench
-set(CACHED_RESOURCE_FILES
- plugin.xml
- resources/play.png
- resources/rec.png
- resources/stop_rec.png
- resources/stop.png
- resources/icon.png
-)
-
-# list of Qt .qrc files which contain additional resources
-# specific to this plugin
-set(QRC_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/org.mitk.gui.qt.eventrecorder/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.eventrecorder/manifest_headers.cmake
deleted file mode 100644
index ea9bb6e6f3..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/manifest_headers.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(Plugin-Name "Eventrecorder")
-set(Plugin-Version "0.1")
-set(Plugin-Vendor "German Cancer Research Center (DKFZ)")
-set(Plugin-ContactAddress "")
-set(Require-Plugin org.mitk.gui.qt.common)
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/plugin.xml b/Plugins/org.mitk.gui.qt.eventrecorder/plugin.xml
deleted file mode 100644
index c412788f66..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/plugin.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin>
-
- <extension point="org.blueberry.ui.views">
- <view id="org.mitk.views.interactioneventrecorder"
- name="Interaction Event Recorder"
- class="InteractionEventRecorder"
- icon="resources/icon.png" >
- <description>Records and plays interaction to test the GUI</description>
- <keywordReference id="org.mitk.views.interactioneventrecorder.Keyword"/>
- </view>
- </extension>
- <extension point="org.blueberry.ui.keywords">
- <keyword label="Testing" id="org.mitk.views.interactioneventrecorder.Keyword"/>
- <keyword label="Recording" id="org.mitk.views.interactioneventrecorder.Keyword"/>
- <keyword label="GUI" id="org.mitk.views.interactioneventrecorder.Keyword"/>
- <keyword label="Interaction" id="org.mitk.views.interactioneventrecorder.Keyword"/>
- </extension>
-
-</plugin>
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/resources/icon.png b/Plugins/org.mitk.gui.qt.eventrecorder/resources/icon.png
deleted file mode 100644
index 7f2545d959..0000000000
Binary files a/Plugins/org.mitk.gui.qt.eventrecorder/resources/icon.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/resources/play.png b/Plugins/org.mitk.gui.qt.eventrecorder/resources/play.png
deleted file mode 100644
index b352da58ad..0000000000
Binary files a/Plugins/org.mitk.gui.qt.eventrecorder/resources/play.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/resources/rec.png b/Plugins/org.mitk.gui.qt.eventrecorder/resources/rec.png
deleted file mode 100644
index 26c424ca75..0000000000
Binary files a/Plugins/org.mitk.gui.qt.eventrecorder/resources/rec.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/resources/stop.png b/Plugins/org.mitk.gui.qt.eventrecorder/resources/stop.png
deleted file mode 100644
index e9e377b46c..0000000000
Binary files a/Plugins/org.mitk.gui.qt.eventrecorder/resources/stop.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/resources/stop_rec.png b/Plugins/org.mitk.gui.qt.eventrecorder/resources/stop_rec.png
deleted file mode 100644
index 25c782ac37..0000000000
Binary files a/Plugins/org.mitk.gui.qt.eventrecorder/resources/stop_rec.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.cpp b/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.cpp
deleted file mode 100644
index cfdecd38f2..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.cpp
+++ /dev/null
@@ -1,152 +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.
-
-============================================================================*/
-
-
-// Blueberry
-#include <berryISelectionService.h>
-#include <berryIWorkbenchWindow.h>
-
-// Qmitk
-#include "InteractionEventRecorder.h"
-
-// Qt
-#include <QMessageBox>
-#include <QFileDialog>
-// us
-#include "usGetModuleContext.h"
-#include "usModuleContext.h"
-#include "usModuleResource.h"
-
-#include <usModuleInitialization.h>
-#include <mitkXML2EventParser.h>
-#include <vtkSmartPointer.h>
-#include "QmitkRenderWindow.h"
-
-
-US_INITIALIZE_MODULE
-
-
-const std::string InteractionEventRecorder::VIEW_ID = "org.mitk.views.interactioneventrecorder";
-
-void InteractionEventRecorder::SetFocus()
-{
- m_Controls.textFileName->setFocus();
-}
-
-void InteractionEventRecorder::StartRecording()
-{
-
- MITK_INFO << "Start Recording";
- MITK_INFO << "Performing Reinit";
- mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());
-
- m_CurrentObserver->SetOutputFile(m_Controls.textFileName->text().toStdString());
- m_CurrentObserver->StartRecording();
-}
-
-void InteractionEventRecorder::StopRecording()
-{
- MITK_INFO << "Stop Recording";
- m_CurrentObserver->StopRecording();
-}
-
-void InteractionEventRecorder::Play()
-{
- std::ifstream xmlStream(m_Controls.textFileName->text().toStdString().c_str());
- mitk::XML2EventParser parser(xmlStream);
- mitk::XML2EventParser::EventContainerType events = parser.GetInteractions();
-
- MITK_INFO << "parsed events";
-
- for (std::size_t i=0; i < events.size(); ++i)
- events.at(i)->GetSender()->GetDispatcher()->ProcessEvent(events.at(i));
-
- MITK_INFO << "DONE";
-}
-
-void InteractionEventRecorder::OpenFile()
-{
- QString fn = QFileDialog::getOpenFileName(nullptr, "Open File...",
- QString(), "All Files (*)");
- if (!fn.isEmpty())
- this->m_Controls.textFileName->setText(fn);
-}
-
-void InteractionEventRecorder::RotatePlanes()
-{
- mitk::Point3D center;
- center.Fill(0);
- mitk::Vector3D firstVec;
- mitk::Vector3D secondVec;
-
- firstVec[0] = 1.0;
- firstVec[1] = .5;
- firstVec[2] = .25;
-
- secondVec[0] = 1;
- secondVec[1] = .25;
- secondVec[2] = 1;
-
- // Rotate Planes to a predefined state which can later be used again in tests
- auto* axialRenderWindow = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindow("axial");
- axialRenderWindow->GetSliceNavigationController()->ReorientSlices( center, firstVec,secondVec );
- axialRenderWindow->GetRenderer()->RequestUpdate();
-
-}
-
-void InteractionEventRecorder::RotateView()
-{
- // Rotate the view in 3D to a predefined state which can later be used again in tests
- // this simulates a prior VTK Interaction
- auto allRenderWindows = mitk::BaseRenderer::GetAll3DRenderWindows();
- for (auto mapit = allRenderWindows.begin(); mapit != allRenderWindows.end(); ++mapit)
- {
- vtkRenderWindow* renderWindow = mapit->first;
- if (renderWindow == nullptr)
- continue;
-
- mitk::Stepper* stepper = mapit->second->GetCameraRotationController()->GetStepper();
- if (stepper == nullptr)
- return;
-
- unsigned int newPos = 17;
- stepper->SetPos(newPos);
- }
-}
-
-void InteractionEventRecorder::CreateQtPartControl( QWidget *parent )
-{
- // create GUI widgets from the Qt Designer's .ui file
- m_Controls.setupUi( parent );
- connect( m_Controls.btnStopRecording, SIGNAL(clicked()), this, SLOT(StopRecording()) );
- connect( m_Controls.btnStartRecording, SIGNAL(clicked()), this, SLOT(StartRecording()) );
- connect( m_Controls.btnPlay, SIGNAL(clicked()), this, SLOT(Play()) );
- connect( m_Controls.btnOpenFile, SIGNAL(clicked()), this, SLOT(OpenFile()) );
- connect( m_Controls.rotatePlanes, SIGNAL(clicked()), this, SLOT(RotatePlanes()) );
- connect( m_Controls.rotate3D, SIGNAL(clicked()), this, SLOT(RotateView()) );
-
- m_CurrentObserver = new mitk::EventRecorder();
- // Register as listener via micro services
- us::ServiceProperties props;
-
- props["name"] = std::string("EventRecorder");
- m_ServiceRegistration = us::GetModuleContext()->RegisterService<mitk::InteractionEventObserver>(m_CurrentObserver,props);
-
-
- /*
-
-delete m_CurrentObserverDEBUG;
- m_ServiceRegistrationDEBUG.Unregister();
- */
-}
-
-
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.h b/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.h
deleted file mode 100644
index c3a8fe5374..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorder.h
+++ /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.
-
-============================================================================*/
-
-
-#ifndef InteractionEventRecorder_h
-#define InteractionEventRecorder_h
-
-#include <berryISelectionListener.h>
-
-#include <QmitkAbstractView.h>
-
-#include "ui_InteractionEventRecorderControls.h"
-
-#include "mitkInteractionEventObserver.h"
-#include "mitkEventRecorder.h"
-
-/**
- \brief InteractionEventRecorder
-
- Demontrates the use of InteractionOversers.
-
- Allows to record all mouse interaction in the renderwindows save it as XML file. And also replay the interaction.
-
- \sa QmitkAbstractView
- \ingroup ${plugin_target}_internal
-*/
-class InteractionEventRecorder : public QmitkAbstractView
-{
- // this is needed for all Qt objects that should have a Qt meta-object
- // (everything that derives from QObject and wants to have signal/slots)
- Q_OBJECT
-
- public:
-
- static const std::string VIEW_ID;
-
- protected slots:
-
- /// \brief Called when the user clicks the GUI button
-
- void StartRecording();
- void StopRecording();
- void OpenFile();
- void RotatePlanes();
- void RotateView();
- void Play();
-
- protected:
-
- void CreateQtPartControl(QWidget *parent) override;
-
- void SetFocus() override;
-
-
-
- Ui::InteractionEventRecorderControls m_Controls;
-
- private:
- mitk::EventRecorder* m_CurrentObserver;
-
- us::ServiceRegistration<mitk::InteractionEventObserver> m_ServiceRegistration;
-
-};
-
-#endif // InteractionEventRecorder_h
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorderControls.ui b/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorderControls.ui
deleted file mode 100644
index cbf775f228..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/InteractionEventRecorderControls.ui
+++ /dev/null
@@ -1,197 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>InteractionEventRecorderControls</class>
- <widget class="QWidget" name="InteractionEventRecorderControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>432</width>
- <height>359</height>
- </rect>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="windowTitle">
- <string>QmitkTemplate</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Filename to store interaction</string>
- </property>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QLineEdit" name="textFileName"/>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Fixed</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>5</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="btnOpenFile">
- <property name="maximumSize">
- <size>
- <width>30</width>
- <height>20</height>
- </size>
- </property>
- <property name="toolTip">
- <string>Open file</string>
- </property>
- <property name="text">
- <string>...</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QPushButton" name="btnStartRecording">
- <property name="toolTip">
- <string>Record</string>
- </property>
- <property name="text">
- <string/>
- </property>
- <property name="icon">
- <iconset resource="../../../../../bin-MITK/MITK-build/Plugins/org.mitk.gui.qt.eventrecorder/org_mitk_gui_qt_eventrecorder_cached.qrc">
- <normaloff>:/org.mitk.gui.qt.eventrecorder/resources/rec.png</normaloff>:/org.mitk.gui.qt.eventrecorder/resources/rec.png</iconset>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer_2">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Fixed</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="btnStopRecording">
- <property name="toolTip">
- <string>Stop recording</string>
- </property>
- <property name="text">
- <string/>
- </property>
- <property name="icon">
- <iconset resource="../../../../../bin-MITK/MITK-build/Plugins/org.mitk.gui.qt.eventrecorder/org_mitk_gui_qt_eventrecorder_cached.qrc">
- <normaloff>:/org.mitk.gui.qt.eventrecorder/resources/stop_rec.png</normaloff>:/org.mitk.gui.qt.eventrecorder/resources/stop_rec.png</iconset>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer_3">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Fixed</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="btnPlay">
- <property name="toolTip">
- <string>Play</string>
- </property>
- <property name="text">
- <string/>
- </property>
- <property name="icon">
- <iconset resource="../../../../../bin-MITK/MITK-build/Plugins/org.mitk.gui.qt.eventrecorder/org_mitk_gui_qt_eventrecorder_cached.qrc">
- <normaloff>:/org.mitk.gui.qt.eventrecorder/resources/play.png</normaloff>:/org.mitk.gui.qt.eventrecorder/resources/play.png</iconset>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer_4">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QPushButton" name="rotate3D">
- <property name="text">
- <string>Rotate 3D View</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="rotatePlanes">
- <property name="text">
- <string>Rotated Planes</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="spacer1">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Expanding</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>200</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- <layoutdefault spacing="6" margin="11"/>
- <resources>
- <include location="../../../../../bin-MITK/MITK-build/Plugins/org.mitk.gui.qt.eventrecorder/org_mitk_gui_qt_eventrecorder_cached.qrc"/>
- </resources>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/org_mitk_gui_qt_eventrecorder_Activator.cpp b/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/org_mitk_gui_qt_eventrecorder_Activator.cpp
deleted file mode 100644
index ff11c49a72..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/org_mitk_gui_qt_eventrecorder_Activator.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*============================================================================
-
-The Medical Imaging Interaction Toolkit (MITK)
-
-Copyright (c) German Cancer Research Center (DKFZ)
-All rights reserved.
-
-Use of this source code is governed by a 3-clause BSD license that can be
-found in the LICENSE file.
-
-============================================================================*/
-
-#include "org_mitk_gui_qt_eventrecorder_Activator.h"
-#include "InteractionEventRecorder.h"
-
-namespace mitk {
-
-void org_mitk_gui_qt_eventrecorder_Activator::start(ctkPluginContext* context)
-{
- BERRY_REGISTER_EXTENSION_CLASS(InteractionEventRecorder, context)
-}
-
-void org_mitk_gui_qt_eventrecorder_Activator::stop(ctkPluginContext* context)
-{
- Q_UNUSED(context)
-}
-
-}
diff --git a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/org_mitk_gui_qt_eventrecorder_Activator.h b/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/org_mitk_gui_qt_eventrecorder_Activator.h
deleted file mode 100644
index 1f340d2b3d..0000000000
--- a/Plugins/org.mitk.gui.qt.eventrecorder/src/internal/org_mitk_gui_qt_eventrecorder_Activator.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 org_mitk_gui_qt_eventrecorder_Activator_h
-#define org_mitk_gui_qt_eventrecorder_Activator_h
-
-#include <ctkPluginActivator.h>
-
-namespace mitk {
-
-class org_mitk_gui_qt_eventrecorder_Activator :
- public QObject, public ctkPluginActivator
-{
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_eventrecorder")
- Q_INTERFACES(ctkPluginActivator)
-
-public:
-
- void start(ctkPluginContext* context) override;
- void stop(ctkPluginContext* context) override;
-
-}; // org_mitk_gui_qt_eventrecorder_Activator
-
-}
-
-#endif // org_mitk_gui_qt_eventrecorder_Activator_h
diff --git a/Plugins/org.mitk.gui.qt.ext/CMakeLists.txt b/Plugins/org.mitk.gui.qt.ext/CMakeLists.txt
index 16e873d40f..3886a63606 100644
--- a/Plugins/org.mitk.gui.qt.ext/CMakeLists.txt
+++ b/Plugins/org.mitk.gui.qt.ext/CMakeLists.txt
@@ -1,16 +1,16 @@
project(org_mitk_gui_qt_ext)
# see bug-19679
set(additional_dependencies "")
if(APPLE)
- set(additional_dependencies Qt5|DBus)
+ set(additional_dependencies Qt6|DBus)
endif()
mitk_create_plugin(
EXPORT_DIRECTIVE MITK_QT_COMMON_EXT_EXPORT
EXPORTED_INCLUDE_SUFFIXES src
MODULE_DEPENDS
PRIVATE MitkQtWidgetsExt MitkSceneSerialization MitkAppUtil
PACKAGE_DEPENDS ${additional_dependencies}
)
diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp
index b6f5c20ae0..79ce40d827 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp
+++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp
@@ -1,1444 +1,1433 @@
/*============================================================================
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 "QmitkExtWorkbenchWindowAdvisor.h"
#include "QmitkExtActionBarAdvisor.h"
#include <QMenu>
#include <QMenuBar>
#include <QMainWindow>
#include <QStatusBar>
#include <QString>
#include <QFile>
-#include <QRegExp>
+#include <QRegularExpression>
#include <QTextStream>
#include <QSettings>
#include <ctkPluginException.h>
#include <service/event/ctkEventAdmin.h>
#include <berryPlatform.h>
#include <berryPlatformUI.h>
#include <berryIActionBarConfigurer.h>
#include <berryIWorkbenchWindow.h>
#include <berryIWorkbenchPage.h>
#include <berryIPerspectiveRegistry.h>
#include <berryIPerspectiveDescriptor.h>
#include <berryIProduct.h>
#include <berryIWorkbenchPartConstants.h>
#include <berryQtPreferences.h>
#include <berryQtStyleManager.h>
#include <berryWorkbenchPlugin.h>
#include <internal/berryQtShowViewAction.h>
#include <internal/berryQtOpenPerspectiveAction.h>
#include <QmitkFileOpenAction.h>
#include <QmitkFileSaveAction.h>
#include <QmitkExtFileSaveProjectAction.h>
#include <QmitkFileExitAction.h>
#include <QmitkCloseProjectAction.h>
#include <QmitkUndoAction.h>
#include <QmitkRedoAction.h>
#include <QmitkDefaultDropTargetListener.h>
#include <QmitkStatusBar.h>
#include <QmitkProgressBar.h>
#include <QmitkMemoryUsageIndicatorView.h>
#include <QmitkPreferencesDialog.h>
#include <QmitkOpenDicomEditorAction.h>
#include <QmitkOpenMxNMultiWidgetEditorAction.h>
#include <QmitkOpenStdMultiWidgetEditorAction.h>
+#include <QmitkApplicationConstants.h>
#include <itkConfigure.h>
#include <mitkVersion.h>
#include <mitkIDataStorageService.h>
#include <mitkIDataStorageReference.h>
#include <mitkDataStorageEditorInput.h>
#include <mitkWorkbenchUtil.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
#include <vtkVersionMacros.h>
// UGLYYY
#include "internal/QmitkExtWorkbenchWindowAdvisorHack.h"
#include "internal/QmitkCommonExtPlugin.h"
#include "mitkUndoController.h"
#include "mitkVerboseLimitedLinearUndo.h"
#include <QToolBar>
#include <QToolButton>
#include <QMessageBox>
#include <QMouseEvent>
#include <QLabel>
#include <QmitkAboutDialog.h>
QmitkExtWorkbenchWindowAdvisorHack* QmitkExtWorkbenchWindowAdvisorHack::undohack =
new QmitkExtWorkbenchWindowAdvisorHack();
QString QmitkExtWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini";
static bool USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS = false;
class PartListenerForTitle: public berry::IPartListener
{
public:
PartListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa)
: windowAdvisor(wa)
{
}
Events::Types GetPartEventTypes() const override
{
return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED
| Events::HIDDEN | Events::VISIBLE;
}
void PartActivated(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref.Cast<berry::IEditorReference> ())
{
windowAdvisor->UpdateTitle(false);
}
}
void PartBroughtToTop(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref.Cast<berry::IEditorReference> ())
{
windowAdvisor->UpdateTitle(false);
}
}
void PartClosed(const berry::IWorkbenchPartReference::Pointer& /*ref*/) override
{
windowAdvisor->UpdateTitle(false);
}
void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override
{
auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock();
if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor)
{
windowAdvisor->UpdateTitle(true);
}
}
void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override
{
auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock();
if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor)
{
windowAdvisor->UpdateTitle(false);
}
}
private:
QmitkExtWorkbenchWindowAdvisor* windowAdvisor;
};
class PartListenerForViewNavigator: public berry::IPartListener
{
public:
PartListenerForViewNavigator(QAction* act)
: viewNavigatorAction(act)
{
}
Events::Types GetPartEventTypes() const override
{
return Events::OPENED | Events::CLOSED | Events::HIDDEN |
Events::VISIBLE;
}
void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.viewnavigator")
{
viewNavigatorAction->setChecked(true);
}
}
void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.viewnavigator")
{
viewNavigatorAction->setChecked(false);
}
}
void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.viewnavigator")
{
viewNavigatorAction->setChecked(true);
}
}
void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.viewnavigator")
{
viewNavigatorAction->setChecked(false);
}
}
private:
QAction* viewNavigatorAction;
};
class PartListenerForImageNavigator: public berry::IPartListener
{
public:
PartListenerForImageNavigator(QAction* act)
: imageNavigatorAction(act)
{
}
Events::Types GetPartEventTypes() const override
{
return Events::OPENED | Events::CLOSED | Events::HIDDEN |
Events::VISIBLE;
}
void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.imagenavigator")
{
imageNavigatorAction->setChecked(true);
}
}
void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.imagenavigator")
{
imageNavigatorAction->setChecked(false);
}
}
void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.imagenavigator")
{
imageNavigatorAction->setChecked(true);
}
}
void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.imagenavigator")
{
imageNavigatorAction->setChecked(false);
}
}
private:
QAction* imageNavigatorAction;
};
class PerspectiveListenerForTitle: public berry::IPerspectiveListener
{
public:
PerspectiveListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa)
: windowAdvisor(wa)
, perspectivesClosed(false)
{
}
Events::Types GetPerspectiveEventTypes() const override
{
if (USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS)
{
return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED;
}
else
{
return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED
| Events::CLOSED | Events::OPENED;
}
}
void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
windowAdvisor->UpdateTitle(false);
}
void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/,
const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) override
{
windowAdvisor->UpdateTitle(false);
}
void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
windowAdvisor->UpdateTitle(false);
}
void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
if (perspectivesClosed)
{
QListIterator<QAction*> i(windowAdvisor->viewActions);
while (i.hasNext())
{
i.next()->setEnabled(true);
}
//GetViewRegistry()->Find("org.mitk.views.imagenavigator");
if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser"))
{
windowAdvisor->openDicomEditorAction->setEnabled(true);
}
if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget"))
{
windowAdvisor->openStdMultiWidgetEditorAction->setEnabled(true);
}
if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget"))
{
windowAdvisor->openMxNMultiWidgetEditorAction->setEnabled(true);
}
windowAdvisor->fileSaveProjectAction->setEnabled(true);
windowAdvisor->closeProjectAction->setEnabled(true);
windowAdvisor->undoAction->setEnabled(true);
windowAdvisor->redoAction->setEnabled(true);
windowAdvisor->imageNavigatorAction->setEnabled(true);
windowAdvisor->viewNavigatorAction->setEnabled(true);
windowAdvisor->resetPerspAction->setEnabled(true);
if( windowAdvisor->GetShowClosePerspectiveMenuItem() )
{
windowAdvisor->closePerspAction->setEnabled(true);
}
}
perspectivesClosed = false;
}
void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow();
bool allClosed = true;
if (wnd->GetActivePage())
{
QList<berry::IPerspectiveDescriptor::Pointer> perspectives(wnd->GetActivePage()->GetOpenPerspectives());
allClosed = perspectives.empty();
}
if (allClosed)
{
perspectivesClosed = true;
QListIterator<QAction*> i(windowAdvisor->viewActions);
while (i.hasNext())
{
i.next()->setEnabled(false);
}
if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser"))
{
windowAdvisor->openDicomEditorAction->setEnabled(false);
}
if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget"))
{
windowAdvisor->openStdMultiWidgetEditorAction->setEnabled(false);
}
if (windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget"))
{
windowAdvisor->openMxNMultiWidgetEditorAction->setEnabled(false);
}
windowAdvisor->fileSaveProjectAction->setEnabled(false);
windowAdvisor->closeProjectAction->setEnabled(false);
windowAdvisor->undoAction->setEnabled(false);
windowAdvisor->redoAction->setEnabled(false);
windowAdvisor->imageNavigatorAction->setEnabled(false);
windowAdvisor->viewNavigatorAction->setEnabled(false);
windowAdvisor->resetPerspAction->setEnabled(false);
if( windowAdvisor->GetShowClosePerspectiveMenuItem() )
{
windowAdvisor->closePerspAction->setEnabled(false);
}
}
}
private:
QmitkExtWorkbenchWindowAdvisor* windowAdvisor;
bool perspectivesClosed;
};
class PerspectiveListenerForMenu: public berry::IPerspectiveListener
{
public:
PerspectiveListenerForMenu(QmitkExtWorkbenchWindowAdvisor* wa)
: windowAdvisor(wa)
{
}
Events::Types GetPerspectiveEventTypes() const override
{
return Events::ACTIVATED | Events::DEACTIVATED;
}
void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& perspective) override
{
QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()];
if (action)
{
action->setChecked(true);
}
}
void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& perspective) override
{
QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()];
if (action)
{
action->setChecked(false);
}
}
private:
QmitkExtWorkbenchWindowAdvisor* windowAdvisor;
};
QmitkExtWorkbenchWindowAdvisor::QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor,
berry::IWorkbenchWindowConfigurer::Pointer configurer)
: berry::WorkbenchWindowAdvisor(configurer)
, lastInput(nullptr)
, wbAdvisor(wbAdvisor)
, showViewToolbar(true)
, showPerspectiveToolbar(false)
, showVersionInfo(true)
, showMitkVersionInfo(true)
, showViewMenuItem(true)
, showNewWindowMenuItem(false)
, showClosePerspectiveMenuItem(true)
, viewNavigatorFound(false)
, showMemoryIndicator(true)
, dropTargetListener(new QmitkDefaultDropTargetListener)
{
productName = QCoreApplication::applicationName();
viewExcludeList.push_back("org.mitk.views.viewnavigator");
}
QmitkExtWorkbenchWindowAdvisor::~QmitkExtWorkbenchWindowAdvisor()
{
}
berry::ActionBarAdvisor::Pointer QmitkExtWorkbenchWindowAdvisor::CreateActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer)
{
if (USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS)
{
berry::ActionBarAdvisor::Pointer actionBarAdvisor(new QmitkExtActionBarAdvisor(configurer));
return actionBarAdvisor;
}
else
{
return berry::WorkbenchWindowAdvisor::CreateActionBarAdvisor(configurer);
}
}
QWidget* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* parent)
{
QWidget* parentWidget = static_cast<QWidget*>(parent);
auto label = new QLabel(parentWidget);
label->setText("<b>No perspectives are open. Open a perspective in the <i>Window->Open Perspective</i> menu.</b>");
label->setContentsMargins(10,10,10,10);
label->setAlignment(Qt::AlignTop);
label->setEnabled(false);
parentWidget->layout()->addWidget(label);
return label;
}
void QmitkExtWorkbenchWindowAdvisor::ShowClosePerspectiveMenuItem(bool show)
{
showClosePerspectiveMenuItem = show;
}
bool QmitkExtWorkbenchWindowAdvisor::GetShowClosePerspectiveMenuItem()
{
return showClosePerspectiveMenuItem;
}
void QmitkExtWorkbenchWindowAdvisor::ShowMemoryIndicator(bool show)
{
showMemoryIndicator = show;
}
bool QmitkExtWorkbenchWindowAdvisor::GetShowMemoryIndicator()
{
return showMemoryIndicator;
}
void QmitkExtWorkbenchWindowAdvisor::ShowNewWindowMenuItem(bool show)
{
showNewWindowMenuItem = show;
}
void QmitkExtWorkbenchWindowAdvisor::ShowViewToolbar(bool show)
{
showViewToolbar = show;
}
void QmitkExtWorkbenchWindowAdvisor::ShowViewMenuItem(bool show)
{
showViewMenuItem = show;
}
void QmitkExtWorkbenchWindowAdvisor::ShowPerspectiveToolbar(bool show)
{
showPerspectiveToolbar = show;
}
void QmitkExtWorkbenchWindowAdvisor::ShowVersionInfo(bool show)
{
showVersionInfo = show;
}
void QmitkExtWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show)
{
showMitkVersionInfo = show;
}
void QmitkExtWorkbenchWindowAdvisor::SetProductName(const QString& product)
{
productName = product;
}
void QmitkExtWorkbenchWindowAdvisor::SetWindowIcon(const QString& wndIcon)
{
windowIcon = wndIcon;
}
void QmitkExtWorkbenchWindowAdvisor::PostWindowCreate()
{
// very bad hack...
berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow();
QMainWindow* mainWindow = qobject_cast<QMainWindow*> (window->GetShell()->GetControl());
if (!windowIcon.isEmpty())
{
mainWindow->setWindowIcon(QIcon(windowIcon));
}
mainWindow->setContextMenuPolicy(Qt::PreventContextMenu);
// Load icon theme
QIcon::setThemeSearchPaths(QStringList() << QStringLiteral(":/org_mitk_icons/icons/"));
QIcon::setThemeName(QStringLiteral("awesome"));
// ==== Application menu ============================
QMenuBar* menuBar = mainWindow->menuBar();
menuBar->setContextMenuPolicy(Qt::PreventContextMenu);
#ifdef __APPLE__
menuBar->setNativeMenuBar(true);
#else
menuBar->setNativeMenuBar(false);
#endif
auto basePath = QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/");
auto fileOpenAction = new QmitkFileOpenAction(berry::QtStyleManager::ThemeIcon(basePath + "document-open.svg"), window);
fileOpenAction->setShortcut(QKeySequence::Open);
auto fileSaveAction = new QmitkFileSaveAction(berry::QtStyleManager::ThemeIcon(basePath + "document-save.svg"), window);
fileSaveAction->setShortcut(QKeySequence::Save);
fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window);
fileSaveProjectAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "document-save.svg"));
closeProjectAction = new QmitkCloseProjectAction(window);
closeProjectAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "edit-delete.svg"));
auto perspGroup = new QActionGroup(menuBar);
std::map<QString, berry::IViewDescriptor::Pointer> VDMap;
// sort elements (converting vector to map...)
QList<berry::IViewDescriptor::Pointer>::const_iterator iter;
berry::IViewRegistry* viewRegistry =
berry::PlatformUI::GetWorkbench()->GetViewRegistry();
const QList<berry::IViewDescriptor::Pointer> viewDescriptors = viewRegistry->GetViews();
bool skip = false;
for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter)
{
// if viewExcludeList is set, it contains the id-strings of view, which
// should not appear as an menu-entry in the menu
if (viewExcludeList.size() > 0)
{
for (int i=0; i<viewExcludeList.size(); i++)
{
if (viewExcludeList.at(i) == (*iter)->GetId())
{
skip = true;
break;
}
}
if (skip)
{
skip = false;
continue;
}
}
if ((*iter)->GetId() == "org.blueberry.ui.internal.introview")
continue;
if ((*iter)->GetId() == "org.mitk.views.imagenavigator")
continue;
if ((*iter)->GetId() == "org.mitk.views.viewnavigator")
continue;
std::pair<QString, berry::IViewDescriptor::Pointer> p((*iter)->GetLabel(), (*iter));
VDMap.insert(p);
}
std::map<QString, berry::IViewDescriptor::Pointer>::const_iterator MapIter;
for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter)
{
berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second);
viewActions.push_back(viewAction);
}
if (!USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS)
{
QMenu* fileMenu = menuBar->addMenu("&File");
fileMenu->setObjectName("FileMenu");
fileMenu->addAction(fileOpenAction);
fileMenu->addAction(fileSaveAction);
fileMenu->addAction(fileSaveProjectAction);
fileMenu->addAction(closeProjectAction);
fileMenu->addSeparator();
QAction* fileExitAction = new QmitkFileExitAction(window);
fileExitAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "system-log-out.svg"));
fileExitAction->setShortcut(QKeySequence::Quit);
fileExitAction->setObjectName("QmitkFileExitAction");
fileMenu->addAction(fileExitAction);
// another bad hack to get an edit/undo menu...
QMenu* editMenu = menuBar->addMenu("&Edit");
- undoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-undo.svg"),
+ undoAction = editMenu->addAction(
+ berry::QtStyleManager::ThemeIcon(basePath + "edit-undo.svg"),
"&Undo",
- QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()),
- QKeySequence("CTRL+Z"));
+ QKeySequence("CTRL+Z"),
+ QmitkExtWorkbenchWindowAdvisorHack::undohack,
+ SLOT(onUndo()));
undoAction->setToolTip("Undo the last action (not supported by all modules)");
- redoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-redo.svg"),
+ redoAction = editMenu->addAction(
+ berry::QtStyleManager::ThemeIcon(basePath + "edit-redo.svg"),
"&Redo",
- QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()),
- QKeySequence("CTRL+Y"));
+ QKeySequence("CTRL+Y"),
+ QmitkExtWorkbenchWindowAdvisorHack::undohack,
+ SLOT(onRedo()));
redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)");
// ==== Window Menu ==========================
QMenu* windowMenu = menuBar->addMenu("Window");
if (showNewWindowMenuItem)
{
windowMenu->addAction("&New Window", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onNewWindow()));
windowMenu->addSeparator();
}
QMenu* perspMenu = windowMenu->addMenu("&Open Perspective");
QMenu* viewMenu = nullptr;
if (showViewMenuItem)
{
viewMenu = windowMenu->addMenu("Show &View");
viewMenu->setObjectName("Show View");
}
windowMenu->addSeparator();
resetPerspAction = windowMenu->addAction("&Reset Perspective",
QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective()));
if(showClosePerspectiveMenuItem)
closePerspAction = windowMenu->addAction("&Close Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onClosePerspective()));
windowMenu->addSeparator();
- windowMenu->addAction("&Preferences...",
- QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()),
- QKeySequence("CTRL+P"));
+ windowMenu->addAction("&Preferences...", QKeySequence("CTRL+P"),
+ QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()));
// fill perspective menu
berry::IPerspectiveRegistry* perspRegistry =
window->GetWorkbench()->GetPerspectiveRegistry();
QList<berry::IPerspectiveDescriptor::Pointer> perspectives(
perspRegistry->GetPerspectives());
skip = false;
for (QList<berry::IPerspectiveDescriptor::Pointer>::iterator perspIt =
perspectives.begin(); perspIt != perspectives.end(); ++perspIt)
{
// if perspectiveExcludeList is set, it contains the id-strings of perspectives, which
// should not appear as an menu-entry in the perspective menu
if (perspectiveExcludeList.size() > 0)
{
for (int i=0; i<perspectiveExcludeList.size(); i++)
{
if (perspectiveExcludeList.at(i) == (*perspIt)->GetId())
{
skip = true;
break;
}
}
if (skip)
{
skip = false;
continue;
}
}
QAction* perspAction = new berry::QtOpenPerspectiveAction(window, *perspIt, perspGroup);
mapPerspIdToAction.insert((*perspIt)->GetId(), perspAction);
}
perspMenu->addActions(perspGroup->actions());
if (showViewMenuItem)
{
- for (auto viewAction : qAsConst(viewActions))
+ for (auto viewAction : std::as_const(viewActions))
{
viewMenu->addAction(viewAction);
}
}
// ===== Help menu ====================================
QMenu* helpMenu = menuBar->addMenu("&Help");
helpMenu->addAction("&Welcome",this, SLOT(onIntro()));
helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective()));
- helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1"));
+ helpMenu->addAction("&Context Help", QKeySequence("F1"), this, SLOT(onHelp()));
helpMenu->addAction("&About",this, SLOT(onAbout()));
// =====================================================
}
else
{
undoAction = new QmitkUndoAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-undo.svg"), nullptr);
undoAction->setShortcut(QKeySequence::Undo);
redoAction = new QmitkRedoAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-redo.svg"), nullptr);
redoAction->setShortcut(QKeySequence::Redo);
}
// toolbar for showing file open, undo, redo and other main actions
auto mainActionsToolBar = new QToolBar;
mainActionsToolBar->setObjectName("mainActionsToolBar");
mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu);
#ifdef __APPLE__
mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
#else
mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
#endif
basePath = QStringLiteral(":/org.mitk.gui.qt.ext/");
imageNavigatorAction = new QAction(berry::QtStyleManager::ThemeIcon(basePath + "image_navigator.svg"), "&Image Navigator", nullptr);
bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator");
if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser"))
{
openDicomEditorAction = new QmitkOpenDicomEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "dicom.svg"), window);
}
if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget"))
{
openStdMultiWidgetEditorAction = new QmitkOpenStdMultiWidgetEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "Editor.svg"), window);
}
if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget"))
{
openMxNMultiWidgetEditorAction = new QmitkOpenMxNMultiWidgetEditorAction(berry::QtStyleManager::ThemeIcon(basePath + "Editor.svg"), window);
}
if (imageNavigatorViewFound)
{
QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator()));
imageNavigatorAction->setCheckable(true);
// add part listener for image navigator
imageNavigatorPartListener.reset(new PartListenerForImageNavigator(imageNavigatorAction));
window->GetPartService()->AddPartListener(imageNavigatorPartListener.data());
berry::IViewPart::Pointer imageNavigatorView = window->GetActivePage()->FindView("org.mitk.views.imagenavigator");
imageNavigatorAction->setChecked(false);
if (imageNavigatorView)
{
bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView);
if (isImageNavigatorVisible)
imageNavigatorAction->setChecked(true);
}
imageNavigatorAction->setToolTip("Toggle image navigator for navigating through image");
}
viewNavigatorAction = new QAction(berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org.mitk.gui.qt.ext/view-manager.svg")),"&View Navigator", nullptr);
viewNavigatorFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.viewnavigator");
if (viewNavigatorFound)
{
QObject::connect(viewNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onViewNavigator()));
viewNavigatorAction->setCheckable(true);
// add part listener for view navigator
viewNavigatorPartListener.reset(new PartListenerForViewNavigator(viewNavigatorAction));
window->GetPartService()->AddPartListener(viewNavigatorPartListener.data());
berry::IViewPart::Pointer viewnavigatorview = window->GetActivePage()->FindView("org.mitk.views.viewnavigator");
viewNavigatorAction->setChecked(false);
if (viewnavigatorview)
{
bool isViewNavigatorVisible = window->GetActivePage()->IsPartVisible(viewnavigatorview);
if (isViewNavigatorVisible)
viewNavigatorAction->setChecked(true);
}
viewNavigatorAction->setToolTip("Toggle View Navigator");
}
mainActionsToolBar->addAction(fileOpenAction);
mainActionsToolBar->addAction(fileSaveProjectAction);
mainActionsToolBar->addAction(closeProjectAction);
mainActionsToolBar->addAction(undoAction);
mainActionsToolBar->addAction(redoAction);
if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicombrowser"))
{
mainActionsToolBar->addAction(openDicomEditorAction);
}
if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.stdmultiwidget"))
{
mainActionsToolBar->addAction(openStdMultiWidgetEditorAction);
}
if (this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.mxnmultiwidget"))
{
mainActionsToolBar->addAction(openMxNMultiWidgetEditorAction);
}
if (imageNavigatorViewFound)
{
mainActionsToolBar->addAction(imageNavigatorAction);
}
if (viewNavigatorFound)
{
mainActionsToolBar->addAction(viewNavigatorAction);
}
mainWindow->addToolBar(mainActionsToolBar);
// ==== Perspective Toolbar ==================================
auto qPerspectiveToolbar = new QToolBar;
qPerspectiveToolbar->setObjectName("perspectiveToolBar");
if (showPerspectiveToolbar)
{
qPerspectiveToolbar->addActions(perspGroup->actions());
mainWindow->addToolBar(qPerspectiveToolbar);
}
else
delete qPerspectiveToolbar;
if (showViewToolbar)
{
auto* prefService = mitk::CoreServices::GetPreferencesService();
+
auto* stylePrefs = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE);
bool showCategoryNames = stylePrefs->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true);
+ auto* toolBarsPrefs = prefService->GetSystemPreferences()->Node(QmitkApplicationConstants::TOOL_BARS_PREFERENCES);
+
// Order view descriptors by category
QMultiMap<QString, berry::IViewDescriptor::Pointer> categoryViewDescriptorMap;
for (const auto &labelViewDescriptorPair : VDMap)
{
auto viewDescriptor = labelViewDescriptorPair.second;
auto category = !viewDescriptor->GetCategoryPath().isEmpty()
? viewDescriptor->GetCategoryPath().back()
: QString();
categoryViewDescriptorMap.insert(category, viewDescriptor);
}
// Create a separate toolbar for each category
for (const auto &category : categoryViewDescriptorMap.uniqueKeys())
{
auto viewDescriptorsInCurrentCategory = categoryViewDescriptorMap.values(category);
if (!viewDescriptorsInCurrentCategory.isEmpty())
{
auto toolbar = new QToolBar;
- toolbar->setObjectName(category + " View Toolbar");
+ toolbar->setObjectName(category);
mainWindow->addToolBar(toolbar);
+ toolbar->setVisible(toolBarsPrefs->GetBool(category.toStdString(), true));
+
if (showCategoryNames && !category.isEmpty())
{
auto categoryButton = new QToolButton;
categoryButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
categoryButton->setText(category);
categoryButton->setStyleSheet("background: transparent; margin: 0; padding: 0;");
toolbar->addWidget(categoryButton);
connect(categoryButton, &QToolButton::clicked, [toolbar]()
{
for (QWidget* widget : toolbar->findChildren<QWidget*>())
{
if (QStringLiteral("qt_toolbar_ext_button") == widget->objectName() && widget->isVisible())
{
- QMouseEvent pressEvent(QEvent::MouseButtonPress, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
- QMouseEvent releaseEvent(QEvent::MouseButtonRelease, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
+ QMouseEvent pressEvent(QEvent::MouseButtonPress, QPointF(0.0f, 0.0f), QCursor::pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
+ QMouseEvent releaseEvent(QEvent::MouseButtonRelease, QPointF(0.0f, 0.0f), QCursor::pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QApplication::sendEvent(widget, &pressEvent);
QApplication::sendEvent(widget, &releaseEvent);
}
}
});
}
- for (const auto &viewDescriptor : qAsConst(viewDescriptorsInCurrentCategory))
+ for (const auto &viewDescriptor : std::as_const(viewDescriptorsInCurrentCategory))
{
auto viewAction = new berry::QtShowViewAction(window, viewDescriptor);
toolbar->addAction(viewAction);
}
+
+
}
}
}
QSettings settings(GetQSettingsFile(), QSettings::IniFormat);
mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray());
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();
// progBar->AddStepsToDo(2);
// progBar->Progress(1);
mainWindow->setStatusBar(qStatusBar);
if (showMemoryIndicator)
{
auto memoryIndicator = new QmitkMemoryUsageIndicatorView();
qStatusBar->addPermanentWidget(memoryIndicator, 0);
}
}
void QmitkExtWorkbenchWindowAdvisor::PreWindowOpen()
{
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
// show the shortcut bar and progress indicator, which are hidden by
// default
//configurer->SetShowPerspectiveBar(true);
//configurer->SetShowFastViewBars(true);
//configurer->SetShowProgressIndicator(true);
// // add the drag and drop support for the editor area
// configurer.addEditorAreaTransfer(EditorInputTransfer.getInstance());
// configurer.addEditorAreaTransfer(ResourceTransfer.getInstance());
// configurer.addEditorAreaTransfer(FileTransfer.getInstance());
// configurer.addEditorAreaTransfer(MarkerTransfer.getInstance());
// configurer.configureEditorAreaDropListener(new EditorAreaDropAdapter(
// configurer.getWindow()));
this->HookTitleUpdateListeners(configurer);
menuPerspectiveListener.reset(new PerspectiveListenerForMenu(this));
configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener.data());
configurer->AddEditorAreaTransfer(QStringList("text/uri-list"));
configurer->ConfigureEditorAreaDropListener(dropTargetListener.data());
}
void QmitkExtWorkbenchWindowAdvisor::PostWindowOpen()
{
berry::WorkbenchWindowAdvisor::PostWindowOpen();
// Force Rendering Window Creation on startup.
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
ctkPluginContext* context = QmitkCommonExtPlugin::getContext();
ctkServiceReference serviceRef = context->getServiceReference<mitk::IDataStorageService>();
if (serviceRef)
{
mitk::IDataStorageService *dsService = context->getService<mitk::IDataStorageService>(serviceRef);
if (dsService)
{
mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage();
mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dsRef));
mitk::WorkbenchUtil::OpenEditor(configurer->GetWindow()->GetActivePage(),dsInput);
}
}
auto introPart = configurer->GetWindow()->GetWorkbench()->GetIntroManager()->GetIntro();
if (introPart.IsNotNull())
{
configurer->GetWindow()->GetWorkbench()->GetIntroManager()->ShowIntro(GetWindowConfigurer()->GetWindow(), false);
}
}
void QmitkExtWorkbenchWindowAdvisor::onIntro()
{
QmitkExtWorkbenchWindowAdvisorHack::undohack->onIntro();
}
void QmitkExtWorkbenchWindowAdvisor::onHelp()
{
QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelp();
}
void QmitkExtWorkbenchWindowAdvisor::onHelpOpenHelpPerspective()
{
QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelpOpenHelpPerspective();
}
void QmitkExtWorkbenchWindowAdvisor::onAbout()
{
QmitkExtWorkbenchWindowAdvisorHack::undohack->onAbout();
}
//--------------------------------------------------------------------------------
// Ugly hack from here on. Feel free to delete when command framework
// and undo buttons are done.
//--------------------------------------------------------------------------------
QmitkExtWorkbenchWindowAdvisorHack::QmitkExtWorkbenchWindowAdvisorHack()
: QObject()
{
}
QmitkExtWorkbenchWindowAdvisorHack::~QmitkExtWorkbenchWindowAdvisorHack()
{
}
void QmitkExtWorkbenchWindowAdvisorHack::onUndo()
{
mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel();
if (model)
{
if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast<mitk::VerboseLimitedLinearUndo*>( model ))
{
mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions();
if (descriptions.size() >= 1)
{
MITK_INFO << "Undo " << descriptions.front().second;
}
}
model->Undo();
}
else
{
MITK_ERROR << "No undo model instantiated";
}
}
void QmitkExtWorkbenchWindowAdvisorHack::onRedo()
{
mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel();
if (model)
{
if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast<mitk::VerboseLimitedLinearUndo*>( model ))
{
mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions();
if (descriptions.size() >= 1)
{
MITK_INFO << "Redo " << descriptions.front().second;
}
}
model->Redo();
}
else
{
MITK_ERROR << "No undo model instantiated";
}
}
// safe calls to the complete chain
// berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator");
// to cover for all possible cases of closed pages etc.
static void SafeHandleNavigatorView(QString view_query_name)
{
berry::IWorkbench* wbench = berry::PlatformUI::GetWorkbench();
if( wbench == nullptr )
return;
berry::IWorkbenchWindow::Pointer wbench_window = wbench->GetActiveWorkbenchWindow();
if( wbench_window.IsNull() )
return;
berry::IWorkbenchPage::Pointer wbench_page = wbench_window->GetActivePage();
if( wbench_page.IsNull() )
return;
auto wbench_view = wbench_page->FindView( view_query_name );
if( wbench_view.IsNotNull() )
{
bool isViewVisible = wbench_page->IsPartVisible( wbench_view );
if( isViewVisible )
{
wbench_page->HideView( wbench_view );
return;
}
}
wbench_page->ShowView( view_query_name );
}
void QmitkExtWorkbenchWindowAdvisorHack::onImageNavigator()
{
// show/hide ImageNavigatorView
SafeHandleNavigatorView("org.mitk.views.imagenavigator");
}
void QmitkExtWorkbenchWindowAdvisorHack::onViewNavigator()
{
// show/hide viewnavigatorView
SafeHandleNavigatorView("org.mitk.views.viewnavigator");
}
void QmitkExtWorkbenchWindowAdvisorHack::onEditPreferences()
{
QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow());
_PreferencesDialog.exec();
}
void QmitkExtWorkbenchWindowAdvisorHack::onQuit()
{
berry::PlatformUI::GetWorkbench()->Close();
}
void QmitkExtWorkbenchWindowAdvisorHack::onResetPerspective()
{
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective();
}
void QmitkExtWorkbenchWindowAdvisorHack::onClosePerspective()
{
berry::IWorkbenchPage::Pointer page =
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage();
page->ClosePerspective(page->GetPerspective(), true, true);
}
void QmitkExtWorkbenchWindowAdvisorHack::onNewWindow()
{
berry::PlatformUI::GetWorkbench()->OpenWorkbenchWindow(nullptr);
}
void QmitkExtWorkbenchWindowAdvisorHack::onIntro()
{
- bool hasIntro =
- berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro();
- if (!hasIntro)
- {
- QRegExp reg("(.*)<title>(\\n)*");
- QRegExp reg2("(\\n)*</title>(.*)");
- QFile file(":/org.mitk.gui.qt.ext/index.html");
- file.open(QIODevice::ReadOnly | QIODevice::Text); //text file only for reading
-
- QString text = QString(file.readAll());
-
- file.close();
-
- QString title = text;
- title.replace(reg, "");
- title.replace(reg2, "");
-
- std::cout << title.toStdString() << std::endl;
-
- QMessageBox::information(nullptr, title,
- text, "Close");
- }
- else
+ if (berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro())
{
berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro(
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false);
}
}
void QmitkExtWorkbenchWindowAdvisorHack::onHelp()
{
ctkPluginContext* context = QmitkCommonExtPlugin::getContext();
if (context == nullptr)
{
MITK_WARN << "Plugin context not set, unable to open context help";
return;
}
// Check if the org.blueberry.ui.qt.help plug-in is installed and started
QList<QSharedPointer<ctkPlugin> > plugins = context->getPlugins();
foreach(QSharedPointer<ctkPlugin> p, plugins)
{
if (p->getSymbolicName() == "org.blueberry.ui.qt.help")
{
if (p->getState() != ctkPlugin::ACTIVE)
{
// try to activate the plug-in explicitly
try
{
p->start(ctkPlugin::START_TRANSIENT);
}
catch (const ctkPluginException& pe)
{
MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what();
return;
}
}
}
}
ctkServiceReference eventAdminRef = context->getServiceReference<ctkEventAdmin>();
ctkEventAdmin* eventAdmin = nullptr;
if (eventAdminRef)
{
eventAdmin = context->getService<ctkEventAdmin>(eventAdminRef);
}
if (eventAdmin == nullptr)
{
MITK_WARN << "ctkEventAdmin service not found. Unable to open context help";
}
else
{
ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED");
eventAdmin->postEvent(ev);
}
}
void QmitkExtWorkbenchWindowAdvisorHack::onHelpOpenHelpPerspective()
{
berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help",
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow());
}
void QmitkExtWorkbenchWindowAdvisorHack::onAbout()
{
- auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(),nullptr);
+ auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(), {});
aboutDialog->open();
}
void QmitkExtWorkbenchWindowAdvisor::HookTitleUpdateListeners(berry::IWorkbenchWindowConfigurer::Pointer configurer)
{
// hook up the listeners to update the window title
titlePartListener.reset(new PartListenerForTitle(this));
titlePerspectiveListener.reset(new PerspectiveListenerForTitle(this));
editorPropertyListener.reset(new berry::PropertyChangeIntAdapter<
QmitkExtWorkbenchWindowAdvisor>(this,
&QmitkExtWorkbenchWindowAdvisor::PropertyChange));
// configurer.getWindow().addPageListener(new IPageListener() {
// public void pageActivated(IWorkbenchPage page) {
// updateTitle(false);
// }
//
// public void pageClosed(IWorkbenchPage page) {
// updateTitle(false);
// }
//
// public void pageOpened(IWorkbenchPage page) {
// // do nothing
// }
// });
configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener.data());
configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener.data());
}
QString QmitkExtWorkbenchWindowAdvisor::ComputeTitle()
{
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage();
berry::IEditorPart::Pointer activeEditor;
if (currentPage)
{
activeEditor = lastActiveEditor.Lock();
}
QString title;
berry::IProduct::Pointer product = berry::Platform::GetProduct();
if (product.IsNotNull())
{
title = product->GetName();
}
if (title.isEmpty())
{
// instead of the product name, we use a custom variable for now
title = productName;
}
if(showMitkVersionInfo)
{
QString mitkVersionInfo = MITK_REVISION_DESC;
if(mitkVersionInfo.isEmpty())
mitkVersionInfo = MITK_VERSION_STRING;
title += " " + mitkVersionInfo;
}
if (showVersionInfo)
{
// add version informatioin
QString versions = QString(" (ITK %1.%2.%3 | VTK %4.%5.%6 | Qt %7)")
.arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH)
.arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION)
.arg(QT_VERSION_STR);
title += versions;
}
if (currentPage)
{
if (activeEditor)
{
lastEditorTitle = activeEditor->GetTitleToolTip();
if (!lastEditorTitle.isEmpty())
title = lastEditorTitle + " - " + title;
}
berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective();
QString label = "";
if (persp)
{
label = persp->GetLabel();
}
berry::IAdaptable* input = currentPage->GetInput();
if (input && input != wbAdvisor->GetDefaultPageInput())
{
label = currentPage->GetLabel();
}
if (!label.isEmpty())
{
title = label + " - " + title;
}
}
title += " (Not for use in diagnosis or treatment of patients)";
return title;
}
void QmitkExtWorkbenchWindowAdvisor::RecomputeTitle()
{
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
QString oldTitle = configurer->GetTitle();
QString newTitle = ComputeTitle();
if (newTitle != oldTitle)
{
configurer->SetTitle(newTitle);
}
}
void QmitkExtWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden)
{
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
berry::IWorkbenchWindow::Pointer window = configurer->GetWindow();
berry::IEditorPart::Pointer activeEditor;
berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage();
berry::IPerspectiveDescriptor::Pointer persp;
berry::IAdaptable* input = nullptr;
if (currentPage)
{
activeEditor = currentPage->GetActiveEditor();
persp = currentPage->GetPerspective();
input = currentPage->GetInput();
}
if (editorHidden)
{
activeEditor = nullptr;
}
// Nothing to do if the editor hasn't changed
if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock()
&& persp == lastPerspective.Lock() && input == lastInput)
{
return;
}
auto lockedLastActiveEditor = lastActiveEditor.Lock();
if (lockedLastActiveEditor.IsNotNull())
{
lockedLastActiveEditor->RemovePropertyListener(editorPropertyListener.data());
}
lastActiveEditor = activeEditor;
lastActivePage = currentPage;
lastPerspective = persp;
lastInput = input;
if (activeEditor)
{
activeEditor->AddPropertyListener(editorPropertyListener.data());
}
RecomputeTitle();
}
void QmitkExtWorkbenchWindowAdvisor::PropertyChange(const berry::Object::Pointer& /*source*/, int propId)
{
if (propId == berry::IWorkbenchPartConstants::PROP_TITLE)
{
auto lockedLastActiveEditor = lastActiveEditor.Lock();
if (lockedLastActiveEditor.IsNotNull())
{
QString newTitle = lockedLastActiveEditor->GetPartName();
if (lastEditorTitle != newTitle)
{
RecomputeTitle();
}
}
}
}
void QmitkExtWorkbenchWindowAdvisor::SetPerspectiveExcludeList(const QList<QString>& v)
{
this->perspectiveExcludeList = v;
}
QList<QString> QmitkExtWorkbenchWindowAdvisor::GetPerspectiveExcludeList()
{
return this->perspectiveExcludeList;
}
void QmitkExtWorkbenchWindowAdvisor::SetViewExcludeList(const QList<QString>& v)
{
this->viewExcludeList = v;
}
QList<QString> QmitkExtWorkbenchWindowAdvisor::GetViewExcludeList()
{
return this->viewExcludeList;
}
void QmitkExtWorkbenchWindowAdvisor::PostWindowClose()
{
berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow();
QMainWindow* mainWindow = static_cast<QMainWindow*> (window->GetShell()->GetControl());
auto fileName = this->GetQSettingsFile();
if (!fileName.isEmpty())
{
QSettings settings(fileName, QSettings::IniFormat);
settings.setValue("ToolbarPosition", mainWindow->saveState());
}
}
QString QmitkExtWorkbenchWindowAdvisor::GetQSettingsFile() const
{
QFileInfo settingsInfo = QmitkCommonExtPlugin::getContext()->getDataFile(QT_SETTINGS_FILENAME);
return settingsInfo.canonicalFilePath();
}
diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp
index e9b6b0b708..a7829fa0d2 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp
+++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenMxNMultiWidgetEditorAction.cpp
@@ -1,72 +1,74 @@
/*============================================================================
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 "QmitkOpenMxNMultiWidgetEditorAction.h"
#include "mitkCoreObjectFactory.h"
#include <berryIEditorPart.h>
#include <berryIWorkbenchPage.h>
#include <berryIWorkbench.h>
#include <mitkDataStorageEditorInput.h>
#include "internal/QmitkCommonExtPlugin.h"
#include <mitkIDataStorageService.h>
+#include <QWidget>
+
class ctkPluginContext;
QmitkOpenMxNMultiWidgetEditorAction::QmitkOpenMxNMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window)
: QAction(nullptr)
{
this->init(window);
}
QmitkOpenMxNMultiWidgetEditorAction::QmitkOpenMxNMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window)
: QAction(nullptr)
{
this->setIcon(icon);
this->init(window);
}
void QmitkOpenMxNMultiWidgetEditorAction::init(berry::IWorkbenchWindow::Pointer window)
{
m_Window = window;
this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl()));
this->setText("MxN Display");
this->setToolTip("Open the mxn multi widget editor");
this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run()));
}
void QmitkOpenMxNMultiWidgetEditorAction::Run()
{
// check if there is an open perspective, if not open the default perspective
if (m_Window->GetActivePage().IsNull())
{
QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective();
m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window);
}
ctkPluginContext* context = QmitkCommonExtPlugin::getContext();
ctkServiceReference serviceRef = context->getServiceReference<mitk::IDataStorageService>();
if (serviceRef)
{
mitk::IDataStorageService* dsService = context->getService<mitk::IDataStorageService>(serviceRef);
if (dsService)
{
mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage();
berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput(dsRef));
m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.mxnmultiwidget", true, berry::IWorkbenchPage::MATCH_ID);
}
}
}
diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp
index a6aad97a05..bc530ca86d 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp
+++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkOpenStdMultiWidgetEditorAction.cpp
@@ -1,72 +1,74 @@
/*============================================================================
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 "QmitkOpenStdMultiWidgetEditorAction.h"
#include "mitkCoreObjectFactory.h"
#include <berryIEditorPart.h>
#include <berryIWorkbenchPage.h>
#include <berryIWorkbench.h>
#include <mitkDataStorageEditorInput.h>
#include "internal/QmitkCommonExtPlugin.h"
#include <mitkIDataStorageService.h>
+#include <QWidget>
+
class ctkPluginContext;
QmitkOpenStdMultiWidgetEditorAction::QmitkOpenStdMultiWidgetEditorAction(berry::IWorkbenchWindow::Pointer window)
: QAction(nullptr)
{
this->init(window);
}
QmitkOpenStdMultiWidgetEditorAction::QmitkOpenStdMultiWidgetEditorAction(const QIcon& icon, berry::IWorkbenchWindow::Pointer window)
: QAction(nullptr)
{
this->setIcon(icon);
this->init(window);
}
void QmitkOpenStdMultiWidgetEditorAction::init(berry::IWorkbenchWindow::Pointer window)
{
m_Window = window;
this->setParent(static_cast<QWidget*>(m_Window->GetShell()->GetControl()));
this->setText("Standard Display");
this->setToolTip("Open the standard multi widget editor");
this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run()));
}
void QmitkOpenStdMultiWidgetEditorAction::Run()
{
// check if there is an open perspective, if not open the default perspective
if (m_Window->GetActivePage().IsNull())
{
QString defaultPerspId = m_Window->GetWorkbench()->GetPerspectiveRegistry()->GetDefaultPerspective();
m_Window->GetWorkbench()->ShowPerspective(defaultPerspId, m_Window);
}
ctkPluginContext* context = QmitkCommonExtPlugin::getContext();
ctkServiceReference serviceRef = context->getServiceReference<mitk::IDataStorageService>();
if (serviceRef)
{
mitk::IDataStorageService* dsService = context->getService<mitk::IDataStorageService>(serviceRef);
if (dsService)
{
mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage();
berry::IEditorInput::Pointer editorInput(new mitk::DataStorageEditorInput(dsRef));
m_Window->GetActivePage()->OpenEditor(editorInput, "org.mitk.editors.stdmultiwidget", true, berry::IWorkbenchPage::MATCH_ID);
}
}
}
diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.cpp
index 3e766a803b..d9c2209e93 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.cpp
+++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.cpp
@@ -1,22 +1,22 @@
/*============================================================================
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 "QmitkAboutHandler.h"
#include <QmitkAboutDialog.h>
berry::Object::Pointer QmitkAboutHandler::Execute(const berry::SmartPointer<const berry::ExecutionEvent>& /*event*/)
{
- auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(), nullptr);
+ auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(), {});
aboutDialog->open();
return berry::Object::Pointer();
}
diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp
index 30b3422b74..1fc1168d01 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp
+++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.cpp
@@ -1,75 +1,75 @@
/*============================================================================
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 "QmitkAppInstancesPreferencePage.h"
+#include <ui_QmitkAppInstancesPreferencePage.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
namespace
{
mitk::IPreferences* GetPreferences()
{
auto* preferencesService = mitk::CoreServices::GetPreferencesService();
return preferencesService->GetSystemPreferences()->Node("General");
}
}
QmitkAppInstancesPreferencePage::QmitkAppInstancesPreferencePage()
+ : controls(new Ui::QmitkAppInstancesPreferencePage)
{
-
}
void QmitkAppInstancesPreferencePage::Init(berry::IWorkbench::Pointer )
{
-
}
void QmitkAppInstancesPreferencePage::CreateQtControl(QWidget* parent)
{
mainWidget = new QWidget(parent);
- controls.setupUi(mainWidget);
+ controls->setupUi(mainWidget);
Update();
}
QWidget* QmitkAppInstancesPreferencePage::GetQtControl() const
{
return mainWidget;
}
bool QmitkAppInstancesPreferencePage::PerformOk()
{
auto* prefs = GetPreferences();
- prefs->PutBool("newInstance.always", controls.newInstanceAlways->isChecked());
- prefs->PutBool("newInstance.scene", controls.newInstanceScene->isChecked());
+ prefs->PutBool("newInstance.always", controls->newInstanceAlways->isChecked());
+ prefs->PutBool("newInstance.scene", controls->newInstanceScene->isChecked());
return true;
}
void QmitkAppInstancesPreferencePage::PerformCancel()
{
}
void QmitkAppInstancesPreferencePage::Update()
{
auto* prefs = GetPreferences();
bool always = prefs->GetBool("newInstance.always", false);
bool scene = prefs->GetBool("newInstance.scene", true);
- controls.newInstanceAlways->setChecked(always);
- controls.newInstanceScene->setChecked(scene);
+ controls->newInstanceAlways->setChecked(always);
+ controls->newInstanceScene->setChecked(scene);
}
diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h
index 64e2162497..5a154f0d97 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h
+++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAppInstancesPreferencePage.h
@@ -1,47 +1,49 @@
/*============================================================================
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 QmitkAppInstancesPreferencePage_h
#define QmitkAppInstancesPreferencePage_h
#include <berryIQtPreferencePage.h>
-#include <ui_QmitkAppInstancesPreferencePage.h>
+namespace Ui
+{
+ class QmitkAppInstancesPreferencePage;
+}
class QmitkAppInstancesPreferencePage : public QObject, public berry::IQtPreferencePage
{
Q_OBJECT
Q_INTERFACES(berry::IPreferencePage)
public:
QmitkAppInstancesPreferencePage();
- QmitkAppInstancesPreferencePage(const QmitkAppInstancesPreferencePage& other);
void Init(berry::IWorkbench::Pointer workbench) override;
void CreateQtControl(QWidget* parent) override;
QWidget* GetQtControl() const override;
bool PerformOk() override;
void PerformCancel() override;
void Update() override;
private:
- Ui::QmitkAppInstancesPreferencePage controls;
+ Ui::QmitkAppInstancesPreferencePage* controls;
QWidget* mainWidget;
};
#endif
diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp
index 7e85faa6f1..99394e3e56 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp
+++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp
@@ -1,237 +1,238 @@
/*============================================================================
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 "QmitkCommonExtPlugin.h"
#include <QtWidgetsExtRegisterClasses.h>
#include "QmitkAboutHandler.h"
#include "QmitkAppInstancesPreferencePage.h"
#include "QmitkExternalProgramsPreferencePage.h"
#include "QmitkModuleView.h"
#include <mitkIDataStorageService.h>
#include <mitkSceneIO.h>
#include <mitkProgressBar.h>
#include <mitkRenderingManager.h>
#include <mitkIOUtil.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
#include <mitkBaseApplication.h>
#include <berryPlatformUI.h>
#include <berryPlatform.h>
#include <Poco/Util/OptionProcessor.h>
+#include <QApplication>
#include <QProcess>
#include <QMainWindow>
#include <usModuleInitialization.h>
US_INITIALIZE_MODULE
ctkPluginContext* QmitkCommonExtPlugin::_context = nullptr;
void QmitkCommonExtPlugin::start(ctkPluginContext* context)
{
this->_context = context;
QtWidgetsExtRegisterClasses();
BERRY_REGISTER_EXTENSION_CLASS(QmitkAboutHandler, context)
BERRY_REGISTER_EXTENSION_CLASS(QmitkAppInstancesPreferencePage, context)
BERRY_REGISTER_EXTENSION_CLASS(QmitkExternalProgramsPreferencePage, context)
BERRY_REGISTER_EXTENSION_CLASS(QmitkModuleView, context)
if (qApp->metaObject()->indexOfSignal("messageReceived(QByteArray)") > -1)
{
connect(qApp, SIGNAL(messageReceived(QByteArray)), this, SLOT(handleIPCMessage(QByteArray)));
}
// This is a potentially long running operation.
loadDataFromDisk(berry::Platform::GetApplicationArgs(), true);
}
void QmitkCommonExtPlugin::stop(ctkPluginContext* context)
{
Q_UNUSED(context)
this->_context = nullptr;
}
ctkPluginContext* QmitkCommonExtPlugin::getContext()
{
return _context;
}
void QmitkCommonExtPlugin::loadDataFromDisk(const QStringList &arguments, bool globalReinit)
{
if (!arguments.empty())
{
ctkServiceReference serviceRef = _context->getServiceReference<mitk::IDataStorageService>();
if (serviceRef)
{
mitk::IDataStorageService* dataStorageService = _context->getService<mitk::IDataStorageService>(serviceRef);
mitk::DataStorage::Pointer dataStorage = dataStorageService->GetDefaultDataStorage()->GetDataStorage();
int argumentsAdded = 0;
for (int i = 0; i < arguments.size(); ++i)
{
if (arguments[i].right(5) == ".mitk")
{
mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New();
bool clearDataStorageFirst(false);
mitk::ProgressBar::GetInstance()->AddStepsToDo(2);
dataStorage = sceneIO->LoadScene( arguments[i].toLocal8Bit().constData(), dataStorage, clearDataStorageFirst );
mitk::ProgressBar::GetInstance()->Progress(2);
argumentsAdded++;
}
else if (arguments[i].right(15) == ".mitksceneindex")
{
mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New();
bool clearDataStorageFirst(false);
mitk::ProgressBar::GetInstance()->AddStepsToDo(2);
dataStorage = sceneIO->LoadSceneUnzipped(arguments[i].toLocal8Bit().constData(), dataStorage, clearDataStorageFirst);
mitk::ProgressBar::GetInstance()->Progress(2);
argumentsAdded++;
}
else
{
try
{
const std::string path(arguments[i].toStdString());
auto addedNodes = mitk::IOUtil::Load(path, *dataStorage);
for (const auto& node : *addedNodes )
{
node->SetIntProperty("layer", argumentsAdded);
}
argumentsAdded++;
}
catch(...)
{
MITK_WARN << "Failed to load command line argument: " << arguments[i].toStdString();
}
}
} // end for each command line argument
if (argumentsAdded > 0 && globalReinit)
{
// calculate bounding geometry
mitk::RenderingManager::GetInstance()->InitializeViews(dataStorage->ComputeBoundingGeometry3D());
}
}
else
{
MITK_ERROR << "A service reference for mitk::IDataStorageService does not exist";
}
}
}
void QmitkCommonExtPlugin::startNewInstance(const QStringList &args, const QStringList& files)
{
QStringList newArgs(args);
#ifdef Q_OS_UNIX
newArgs << QString("--") + mitk::BaseApplication::ARG_NEWINSTANCE;
#else
newArgs << QString("/") + mitk::BaseApplication::ARG_NEWINSTANCE;
#endif
newArgs << files;
QProcess::startDetached(qApp->applicationFilePath(), newArgs);
}
void QmitkCommonExtPlugin::handleIPCMessage(const QByteArray& msg)
{
QDataStream ds(msg);
QString msgType;
ds >> msgType;
// we only handle messages containing command line arguments
if (msgType != "$cmdLineArgs") return;
// activate the current workbench window
berry::IWorkbenchWindow::Pointer window =
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow();
QMainWindow* mainWindow =
static_cast<QMainWindow*> (window->GetShell()->GetControl());
mainWindow->setWindowState(mainWindow->windowState() & ~Qt::WindowMinimized);
mainWindow->raise();
mainWindow->activateWindow();
// Get the preferences for the instantiation behavior
auto* prefService = mitk::CoreServices::GetPreferencesService();
auto* prefs = prefService->GetSystemPreferences()->Node("/General");
bool newInstanceAlways = prefs->GetBool("newInstance.always", false);
bool newInstanceScene = prefs->GetBool("newInstance.scene", true);
QStringList args;
ds >> args;
QStringList fileArgs;
QStringList sceneArgs;
foreach (QString arg, args)
{
if (arg.endsWith(".mitk"))
{
sceneArgs << arg;
}
else
{
fileArgs << arg;
}
}
if (newInstanceAlways)
{
if (newInstanceScene)
{
startNewInstance(args, fileArgs);
foreach(QString sceneFile, sceneArgs)
{
startNewInstance(args, QStringList(sceneFile));
}
}
else
{
fileArgs.append(sceneArgs);
startNewInstance(args, fileArgs);
}
}
else
{
loadDataFromDisk(fileArgs, false);
if (newInstanceScene)
{
foreach(QString sceneFile, sceneArgs)
{
startNewInstance(args, QStringList(sceneFile));
}
}
else
{
loadDataFromDisk(sceneArgs, false);
}
}
}
diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp
index 29f1622c41..e157933464 100644
--- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp
+++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkModuleView.cpp
@@ -1,94 +1,94 @@
/*============================================================================
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 "QmitkModuleView.h"
#include <QmitkModuleTableModel.h>
#include <QTableView>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QSortFilterProxyModel>
#include <QSettings>
QmitkModuleView::QmitkModuleView()
: tableView(nullptr)
{
}
void QmitkModuleView::SetFocus()
{
//tableView->setFocus();
}
void QmitkModuleView::CreateQtPartControl(QWidget *parent)
{
auto layout = new QHBoxLayout();
- layout->setMargin(0);
+ layout->setContentsMargins({});
parent->setLayout(layout);
tableView = new QTableView(parent);
auto tableModel = new QmitkModuleTableModel(tableView);
auto sortProxyModel = new QSortFilterProxyModel(tableView);
sortProxyModel->setSourceModel(tableModel);
sortProxyModel->setDynamicSortFilter(true);
tableView->setModel(sortProxyModel);
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
tableView->setTextElideMode(Qt::ElideMiddle);
tableView->setSortingEnabled(true);
tableView->sortByColumn(0, Qt::AscendingOrder);
tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
tableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
tableView->horizontalHeader()->setStretchLastSection(true);
tableView->horizontalHeader()->setCascadingSectionResizes(true);
layout->addWidget(tableView);
if (viewState)
{
berry::IMemento::Pointer tableHeaderState = viewState->GetChild("tableHeader");
if (tableHeaderState)
{
QString key;
tableHeaderState->GetString("qsettings-key", key);
if (!key.isEmpty())
{
QSettings settings;
QByteArray ba = settings.value(key).toByteArray();
tableView->horizontalHeader()->restoreState(ba);
}
}
}
}
void QmitkModuleView::Init(berry::IViewSite::Pointer site, berry::IMemento::Pointer memento)
{
berry::QtViewPart::Init(site, memento);
viewState = memento;
}
void QmitkModuleView::SaveState(berry::IMemento::Pointer memento)
{
QString key = "QmitkModuleView_tableHeader";
QByteArray ba = tableView->horizontalHeader()->saveState();
QSettings settings;
settings.setValue(key, ba);
berry::IMemento::Pointer tableHeaderState = memento->CreateChild("tableHeader");
tableHeaderState->PutString("qsettings-key", key);
}
diff --git a/Plugins/org.mitk.gui.qt.fit.inspector/src/internal/ModelFitInspectorView.cpp b/Plugins/org.mitk.gui.qt.fit.inspector/src/internal/ModelFitInspectorView.cpp
index bb5465eb1b..b7351fe0f3 100644
--- a/Plugins/org.mitk.gui.qt.fit.inspector/src/internal/ModelFitInspectorView.cpp
+++ b/Plugins/org.mitk.gui.qt.fit.inspector/src/internal/ModelFitInspectorView.cpp
@@ -1,918 +1,918 @@
/*============================================================================
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 "ModelFitInspectorView.h"
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
#include <berryIWorkbenchPage.h>
// mitk
#include <QmitkRenderWindow.h>
// Qt
#include <QMessageBox>
#include <QFileDialog>
#include <QTableWidget>
#include <qwt_plot_marker.h>
#include <QmitkPlotWidget.h>
#include <mitkNodePredicateFunction.h>
#include <mitkScalarListLookupTableProperty.h>
#include <mitkModelFitConstants.h>
#include <mitkExtractTimeGrid.h>
#include <mitkModelGenerator.h>
#include <mitkModelFitException.h>
#include <mitkModelFitParameterValueExtraction.h>
#include <mitkModelFitResultRelationRule.h>
#include <mitkModelFitPlotDataHelper.h>
#include <mitkTimeGridHelper.h>
#include <mitkTimeNavigationController.h>
const std::string ModelFitInspectorView::VIEW_ID = "org.mitk.views.fit.inspector";
const unsigned int ModelFitInspectorView::INTERPOLATION_STEPS = 10;
const std::string DEFAULT_X_AXIS = "Time [s]";
ModelFitInspectorView::ModelFitInspectorView() :
m_renderWindowPart(nullptr),
m_internalUpdateFlag(false),
m_currentFit(nullptr),
m_currentModelParameterizer(nullptr),
m_currentModelProviderService(nullptr),
m_currentSelectedTimeStep(0),
m_currentSelectedNode(nullptr)
{
m_currentSelectedPosition.Fill(0.0);
m_modelfitList.clear();
}
ModelFitInspectorView::~ModelFitInspectorView()
{
}
void ModelFitInspectorView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
{
if (m_renderWindowPart != renderWindowPart)
{
m_renderWindowPart = renderWindowPart;
}
this->m_SliceChangeListener.RenderWindowPartActivated(renderWindowPart);
}
void ModelFitInspectorView::RenderWindowPartDeactivated(
mitk::IRenderWindowPart* renderWindowPart)
{
m_renderWindowPart = nullptr;
this->m_SliceChangeListener.RenderWindowPartDeactivated(renderWindowPart);
}
void ModelFitInspectorView::CreateQtPartControl(QWidget* parent)
{
m_Controls.setupUi(parent);
m_SelectionServiceConnector = std::make_unique<QmitkSelectionServiceConnector>();
m_SelectionServiceConnector->AddPostSelectionListener(this->GetSite()->GetWorkbenchWindow()->GetSelectionService());
m_Controls.inputNodeSelector->SetDataStorage(GetDataStorage());
m_Controls.inputNodeSelector->SetEmptyInfo(QString("Please select input data to be viewed."));
m_Controls.inputNodeSelector->SetInvalidInfo(QString("<b><font color=\"red\">No input data is selected</font></b>"));
m_Controls.inputNodeSelector->SetPopUpTitel(QString("Choose 3D+t input data that should be viewed!"));
m_Controls.inputNodeSelector->SetSelectionIsOptional(false);
m_Controls.inputNodeSelector->SetSelectOnlyVisibleNodes(true);
auto predicate = mitk::NodePredicateFunction::New([](const mitk::DataNode *node) {
bool isModelFitNode = node->GetData() && node->GetData()->GetProperty(mitk::ModelFitConstants::FIT_UID_PROPERTY_NAME().c_str()).IsNotNull();
return isModelFitNode || (node && node->GetData() && node->GetData()->GetTimeSteps() > 1);
});
m_Controls.inputNodeSelector->SetNodePredicate(predicate);
connect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.inputNodeSelector, &QmitkSingleNodeSelectionWidget::SetCurrentSelection);
connect(m_Controls.inputNodeSelector, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &ModelFitInspectorView::OnInputChanged);
this->m_SliceChangeListener.RenderWindowPartActivated(this->GetRenderWindowPart());
connect(&m_SliceChangeListener, SIGNAL(SliceChanged()), this, SLOT(OnSliceChanged()));
connect(m_Controls.cmbFit, SIGNAL(currentIndexChanged(int)), this,
SLOT(OnFitSelectionChanged(int)));
connect(m_Controls.radioScaleFixed, SIGNAL(toggled(bool)), m_Controls.sbFixMin,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed, SIGNAL(toggled(bool)), m_Controls.sbFixMax,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed, SIGNAL(toggled(bool)), m_Controls.labelFixMin,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed, SIGNAL(toggled(bool)), m_Controls.labelFixMax,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed, SIGNAL(toggled(bool)), m_Controls.btnScaleToData,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed, SIGNAL(toggled(bool)), this, SLOT(OnScaleFixedYChecked(bool)));
connect(m_Controls.btnScaleToData, SIGNAL(clicked()), this, SLOT(OnScaleToDataYClicked()));
connect(m_Controls.sbFixMax, SIGNAL(valueChanged(double)), this,
SLOT(OnFixedScalingYChanged(double)));
connect(m_Controls.sbFixMin, SIGNAL(valueChanged(double)), this,
SLOT(OnFixedScalingYChanged(double)));
connect(m_Controls.radioScaleFixed_x, SIGNAL(toggled(bool)), m_Controls.sbFixMin_x,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed_x, SIGNAL(toggled(bool)), m_Controls.sbFixMax_x,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed_x, SIGNAL(toggled(bool)), m_Controls.labelFixMin_x,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed_x, SIGNAL(toggled(bool)), m_Controls.labelFixMax_x,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed_x, SIGNAL(toggled(bool)), m_Controls.btnScaleToData_x,
SLOT(setEnabled(bool)));
connect(m_Controls.radioScaleFixed_x, SIGNAL(toggled(bool)), this, SLOT(OnScaleFixedXChecked(bool)));
connect(m_Controls.btnScaleToData_x, SIGNAL(clicked()), this, SLOT(OnScaleToDataXClicked()));
connect(m_Controls.sbFixMax_x, SIGNAL(valueChanged(double)), this,
SLOT(OnFixedScalingXChanged(double)));
connect(m_Controls.sbFixMin_x, SIGNAL(valueChanged(double)), this,
SLOT(OnFixedScalingXChanged(double)));
connect(m_Controls.btnFullPlot, SIGNAL(clicked(bool)), this, SLOT(OnFullPlotClicked(bool)));
this->EnsureBookmarkPointSet();
m_Controls.inspectionPositionWidget->SetPositionBookmarkNode(m_PositionBookmarksNode.Lock());
connect(m_Controls.inspectionPositionWidget, SIGNAL(PositionBookmarksChanged()), this, SLOT(OnPositionBookmarksChanged()));
// For some reason this needs to be called to set the plot widget's minimum width to an
// acceptable level (since Qwt 6).
// Otherwise it tries to keep both axes equal in length, resulting in a minimum width of
// 400-500px which is way too much.
m_Controls.widgetPlot->GetPlot()->updateAxes();
m_Controls.cmbFit->clear();
mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart();
RenderWindowPartActivated(renderWindowPart);
}
void ModelFitInspectorView::SetFocus()
{
}
void ModelFitInspectorView::NodeRemoved(const mitk::DataNode* node)
{
if (node == this->m_currentSelectedNode)
{
QmitkSingleNodeSelectionWidget::NodeList emptylist;
this->m_Controls.inputNodeSelector->SetCurrentSelection(emptylist);
}
}
void ModelFitInspectorView::OnScaleFixedYChecked(bool checked)
{
m_Controls.widgetPlot->GetPlot()->setAxisAutoScale(QwtPlot::yLeft, !checked);
if (checked)
{
OnScaleToDataYClicked();
}
m_Controls.widgetPlot->GetPlot()->replot();
};
void ModelFitInspectorView::OnScaleFixedXChecked(bool checked)
{
m_Controls.widgetPlot->GetPlot()->setAxisAutoScale(QwtPlot::xBottom, !checked);
if (checked)
{
OnScaleToDataXClicked();
}
m_Controls.widgetPlot->GetPlot()->replot();
};
void ModelFitInspectorView::OnScaleToDataYClicked()
{
auto minmax = this->m_PlotCurves.GetYMinMax();
auto min = minmax.first - std::abs(minmax.first) * 0.01;
auto max = minmax.second + std::abs(minmax.second) * 0.01;
m_Controls.sbFixMin->setValue(min);
m_Controls.sbFixMax->setValue(max);
};
void ModelFitInspectorView::OnScaleToDataXClicked()
{
auto minmax = this->m_PlotCurves.GetXMinMax();
auto min = minmax.first - std::abs(minmax.first) * 0.01;
auto max = minmax.second + std::abs(minmax.second) * 0.01;
m_Controls.sbFixMin_x->setValue(min);
m_Controls.sbFixMax_x->setValue(max);
};
void ModelFitInspectorView::OnFixedScalingYChanged(double /*value*/)
{
m_Controls.widgetPlot->GetPlot()->setAxisScale(QwtPlot::yLeft, m_Controls.sbFixMin->value(),
m_Controls.sbFixMax->value());
m_Controls.widgetPlot->GetPlot()->replot();
};
void ModelFitInspectorView::OnFixedScalingXChanged(double /*value*/)
{
m_Controls.widgetPlot->GetPlot()->setAxisScale(QwtPlot::xBottom, m_Controls.sbFixMin_x->value(),
m_Controls.sbFixMax_x->value());
m_Controls.widgetPlot->GetPlot()->replot();
};
void ModelFitInspectorView::OnFullPlotClicked(bool checked)
{
m_Controls.tabWidget->setVisible(!checked);
};
int ModelFitInspectorView::ActualizeFitSelectionWidget()
{
mitk::modelFit::ModelFitInfo::UIDType selectedFitUD = "";
bool isModelFitNode = false;
if (this->m_Controls.inputNodeSelector->GetSelectedNode().IsNotNull())
{
isModelFitNode = this->m_Controls.inputNodeSelector->GetSelectedNode()->GetData()->GetPropertyList()->GetStringProperty(
mitk::ModelFitConstants::FIT_UID_PROPERTY_NAME().c_str(), selectedFitUD);
}
mitk::DataStorage::Pointer storage = this->GetDataStorage();
mitk::modelFit::NodeUIDSetType fitUIDs = mitk::modelFit::GetFitUIDsOfNode(
this->m_currentSelectedNode, storage);
this->m_modelfitList.clear();
this->m_Controls.cmbFit->clear();
for (const auto & fitUID : fitUIDs)
{
mitk::modelFit::ModelFitInfo::ConstPointer info = mitk::modelFit::CreateFitInfoFromNode(fitUID,
storage).GetPointer();
if (info.IsNotNull())
{
this->m_modelfitList.insert(std::make_pair(info->uid, info));
std::ostringstream nameStrm;
if (info->fitName.empty())
{
nameStrm << info->uid;
}
else
{
nameStrm << info->fitName;
}
nameStrm << " (" << info->modelName << ")";
QVariant data(info->uid.c_str());
m_Controls.cmbFit->addItem(QString::fromStdString(nameStrm.str()), data);
}
else
{
MITK_ERROR <<
"Was not able to extract model fit information from storage. Node properties in storage may be invalid. Failed fit UID:"
<< fitUID;
}
}
int cmbIndex = 0;
if (m_modelfitList.empty())
{
cmbIndex = -1;
};
if (isModelFitNode)
{
//model was selected, thus select this one in combobox
QVariant data(selectedFitUD.c_str());
cmbIndex = m_Controls.cmbFit->findData(data);
if (cmbIndex == -1)
{
MITK_WARN <<
"Model fit Inspector in invalid state. Selected fit seems to be not available in plugin selection. Failed fit UID:"
<< selectedFitUD;
}
};
m_Controls.cmbFit->setCurrentIndex(cmbIndex);
return cmbIndex;
}
void ModelFitInspectorView::OnInputChanged(const QList<mitk::DataNode::Pointer>& nodes)
{
if (nodes.size() > 0)
{
if (nodes.front() != this->m_currentSelectedNode)
{
m_internalUpdateFlag = true;
this->m_currentSelectedNode = nodes.front();
mitk::modelFit::ModelFitInfo::UIDType selectedFitUD = "";
bool isModelFitNode = this->m_currentSelectedNode->GetData()->GetPropertyList()->GetStringProperty(
mitk::ModelFitConstants::FIT_UID_PROPERTY_NAME().c_str(), selectedFitUD);
if (isModelFitNode)
{
this->m_currentSelectedNode = this->GetInputNode(this->m_currentSelectedNode);
if (this->m_currentSelectedNode.IsNull())
{
MITK_WARN <<
"Model fit Inspector in invalid state. Input image for selected fit cannot be found in data storage. Failed fit UID:"
<< selectedFitUD;
}
}
auto cmbIndex = ActualizeFitSelectionWidget();
m_internalUpdateFlag = false;
m_selectedNodeTime.Modified();
if (cmbIndex == -1)
{
//only raw 4D data selected. Just update plots for current position
m_currentFit = nullptr;
m_currentFitTime.Modified();
OnSliceChanged();
m_Controls.plotDataWidget->SetXName(DEFAULT_X_AXIS);
}
else
{
//refresh fit selection (and implicitly update plots)
OnFitSelectionChanged(cmbIndex);
}
}
}
else
{
if (this->m_currentSelectedNode.IsNotNull())
{
m_internalUpdateFlag = true;
this->m_currentSelectedNode = nullptr;
this->m_currentFit = nullptr;
this->m_modelfitList.clear();
this->m_Controls.cmbFit->clear();
m_internalUpdateFlag = false;
m_selectedNodeTime.Modified();
OnFitSelectionChanged(0);
RefreshPlotData();
m_Controls.plotDataWidget->SetPlotData(&(this->m_PlotCurves));
m_Controls.fitParametersWidget->setFits(QmitkFitParameterModel::FitVectorType());
RenderPlot();
}
}
}
mitk::DataNode::ConstPointer
ModelFitInspectorView::GetInputNode(mitk::DataNode::ConstPointer node)
{
if (node.IsNotNull())
{
std::string selectedFitUD = "";
auto rule = mitk::ModelFitResultRelationRule::New();
auto predicate = rule->GetDestinationsDetector(node);
mitk::DataStorage::SetOfObjects::ConstPointer parentNodeList =
GetDataStorage()->GetSubset(predicate);
if (parentNodeList->size() > 0)
{
return parentNodeList->front().GetPointer();
}
}
return mitk::DataNode::ConstPointer();
}
void ModelFitInspectorView::ValidateAndSetCurrentPosition()
{
const mitk::Point3D currentSelectedPosition = GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetSelectedPosition(nullptr);
const unsigned int currentSelectedTimestep = mitk::RenderingManager::GetInstance()->GetTimeNavigationController()->GetSelectedTimeStep();
if (m_currentSelectedPosition != currentSelectedPosition
|| m_currentSelectedTimeStep != currentSelectedTimestep
|| m_selectedNodeTime > m_currentPositionTime)
{
//the current position has been changed or the selected node has been changed since the last position validation -> check position
m_currentSelectedPosition = currentSelectedPosition;
m_currentSelectedTimeStep = currentSelectedTimestep;
m_currentPositionTime.Modified();
m_validSelectedPosition = false;
auto inputImage = this->GetCurrentInputImage();
if (inputImage.IsNull())
{
return;
}
mitk::BaseGeometry::ConstPointer geometry = inputImage->GetTimeGeometry()->GetGeometryForTimeStep(
m_currentSelectedTimeStep).GetPointer();
// check for invalid time step
if (geometry.IsNull())
{
geometry = inputImage->GetTimeGeometry()->GetGeometryForTimeStep(0);
}
if (geometry.IsNull())
{
return;
}
m_validSelectedPosition = geometry->IsInside(m_currentSelectedPosition);
}
}
mitk::Image::ConstPointer ModelFitInspectorView::GetCurrentInputImage() const
{
mitk::Image::ConstPointer result = nullptr;
if (this->m_currentFit.IsNotNull())
{
result = m_currentFit->inputImage;
}
else if (this->m_currentSelectedNode.IsNotNull())
{
result = dynamic_cast<mitk::Image*>(this->m_currentSelectedNode->GetData());
if (result.IsNotNull() && result->GetTimeSteps() <= 1)
{
//if the image is not dynamic, we can't use it.
result = nullptr;
}
}
return result;
};
const mitk::ModelBase::TimeGridType ModelFitInspectorView::GetCurrentTimeGrid() const
{
if (m_currentModelProviderService && m_currentFit.IsNotNull())
{
return m_currentModelProviderService->GetVariableGrid(m_currentFit);
}
else
{ //fall back if there is no model provider we assume to use the normal time grid.
return ExtractTimeGrid(GetCurrentInputImage());
}
};
void ModelFitInspectorView::OnSliceChanged()
{
ValidateAndSetCurrentPosition();
m_Controls.widgetPlot->setEnabled(m_validSelectedPosition);
if (m_currentSelectedNode.IsNotNull())
{
m_Controls.inspectionPositionWidget->SetCurrentPosition(m_currentSelectedPosition);
if (RefreshPlotData())
{
RenderPlot();
m_Controls.plotDataWidget->SetPlotData(&m_PlotCurves);
RenderFitInfo();
}
}
}
void ModelFitInspectorView::OnPositionBookmarksChanged()
{
if (RefreshPlotData())
{
RenderPlot();
m_Controls.plotDataWidget->SetPlotData(&m_PlotCurves);
RenderFitInfo();
}
}
void ModelFitInspectorView::OnFitSelectionChanged(int index)
{
if (!m_internalUpdateFlag)
{
MITK_DEBUG << "selected fit index: " << index;
std::string uid = "";
if (m_Controls.cmbFit->count() > index)
{
uid = m_Controls.cmbFit->itemData(index).toString().toStdString();
}
mitk::modelFit::ModelFitInfo::ConstPointer newFit = nullptr;
ModelFitInfoListType::iterator finding = m_modelfitList.find(uid);
if (finding != m_modelfitList.end())
{
newFit = finding->second;
}
if (m_currentFit != newFit)
{
m_currentModelParameterizer = nullptr;
m_currentModelProviderService = nullptr;
if (newFit.IsNotNull())
{
m_currentModelParameterizer = mitk::ModelGenerator::GenerateModelParameterizer(*newFit);
m_currentModelProviderService = mitk::ModelGenerator::GetProviderService(newFit->functionClassID);
}
m_currentFit = newFit;
m_currentFitTime.Modified();
auto name = m_currentFit->xAxisName;
if (!m_currentFit->xAxisUnit.empty())
{
name += " [" + m_currentFit->xAxisUnit + "]";
}
m_Controls.plotDataWidget->SetXName(name);
OnSliceChanged();
}
}
}
mitk::PlotDataCurveCollection::Pointer ModelFitInspectorView::RefreshPlotDataCurveCollection(const mitk::Point3D& position,
const mitk::Image* input, const mitk::modelFit::ModelFitInfo* fitInfo,
const mitk::ModelBase::TimeGridType& timeGrid, mitk::ModelParameterizerBase* parameterizer)
{
mitk::PlotDataCurveCollection::Pointer result = mitk::PlotDataCurveCollection::New();
//sample curve
if (input)
{
result->InsertElement(mitk::MODEL_FIT_PLOT_SAMPLE_NAME(), GenerateImageSamplePlotData(position, input, timeGrid));
}
//model signal curve
if (fitInfo)
{
// Interpolate time grid (x values) so the curve looks smooth
const mitk::ModelBase::TimeGridType interpolatedTimeGrid = mitk::GenerateSupersampledTimeGrid(timeGrid, INTERPOLATION_STEPS);
auto hires_curve = mitk::GenerateModelSignalPlotData(position, fitInfo, interpolatedTimeGrid, parameterizer);
result->InsertElement(mitk::MODEL_FIT_PLOT_INTERPOLATED_SIGNAL_NAME(), hires_curve);
auto curve = mitk::GenerateModelSignalPlotData(position, fitInfo, timeGrid, parameterizer);
result->InsertElement(mitk::MODEL_FIT_PLOT_SIGNAL_NAME(), curve);
}
return result;
};
bool ModelFitInspectorView::RefreshPlotData()
{
bool changed = false;
if (m_currentSelectedNode.IsNull())
{
this->m_PlotCurves = mitk::ModelFitPlotData();
changed = m_selectedNodeTime > m_lastRefreshTime;
m_lastRefreshTime.Modified();
}
else
{
assert(GetRenderWindowPart() != NULL);
const mitk::Image* input = GetCurrentInputImage();
const mitk::ModelBase::TimeGridType timeGrid = GetCurrentTimeGrid();
if (m_currentFitTime > m_lastRefreshTime || m_currentPositionTime > m_lastRefreshTime)
{
if (m_validSelectedPosition)
{
m_PlotCurves.currentPositionPlots = RefreshPlotDataCurveCollection(m_currentSelectedPosition,input,m_currentFit, timeGrid, m_currentModelParameterizer);
}
else
{
m_PlotCurves.currentPositionPlots = mitk::PlotDataCurveCollection::New();
}
changed = true;
}
auto bookmarks = m_PositionBookmarks.Lock();
if (bookmarks.IsNotNull())
{
if (m_currentFitTime > m_lastRefreshTime || bookmarks->GetMTime() > m_lastRefreshTime)
{
m_PlotCurves.positionalPlots.clear();
auto endIter = bookmarks->End();
for (auto iter = bookmarks->Begin(); iter != endIter; iter++)
{
auto collection = RefreshPlotDataCurveCollection(iter.Value(), input, m_currentFit, timeGrid, m_currentModelParameterizer);
m_PlotCurves.positionalPlots.emplace(iter.Index(), std::make_pair(iter.Value(), collection));
}
changed = true;
}
}
else
{
m_PlotCurves.positionalPlots.clear();
}
// input data curve
if (m_currentFitTime > m_lastRefreshTime)
{
m_PlotCurves.staticPlots->clear();
if (m_currentFit.IsNotNull())
{
m_PlotCurves.staticPlots = GenerateAdditionalModelFitPlotData(m_currentSelectedPosition, m_currentFit, timeGrid);
}
changed = true;
}
m_lastRefreshTime.Modified();
}
return changed;
}
void ModelFitInspectorView::RenderFitInfo()
{
assert(m_renderWindowPart != nullptr);
// configure fit information
if (m_currentFit.IsNull())
{
m_Controls.lFitType->setText("");
m_Controls.lFitUID->setText("");
m_Controls.lModelName->setText("");
m_Controls.lModelType->setText("");
}
else
{
m_Controls.lFitType->setText(QString::fromStdString(m_currentFit->fitType));
m_Controls.lFitUID->setText(QString::fromStdString(m_currentFit->uid));
m_Controls.lModelName->setText(QString::fromStdString(m_currentFit->modelName));
m_Controls.lModelType->setText(QString::fromStdString(m_currentFit->modelType));
}
// print results
std::stringstream infoOutput;
m_Controls.fitParametersWidget->setVisible(false);
m_Controls.groupSettings->setVisible(false);
if (m_currentFit.IsNull())
{
infoOutput << "No fit selected. Only raw image data is plotted.";
}
else if (!m_validSelectedPosition)
{
infoOutput <<
"Current position is outside of the input image of the selected fit.\nInspector is deactivated.";
}
else
{
m_Controls.fitParametersWidget->setVisible(true);
m_Controls.fitParametersWidget->setFits({ m_currentFit });
m_Controls.fitParametersWidget->setPositionBookmarks(m_PositionBookmarks.Lock());
m_Controls.fitParametersWidget->setCurrentPosition(m_currentSelectedPosition);
}
// configure data table
m_Controls.tableInputData->clearContents();
if (m_currentFit.IsNull())
{
infoOutput << "No fit selected. Only raw image data is plotted.";
}
else
{
m_Controls.groupSettings->setVisible(true);
m_Controls.tableInputData->setRowCount(m_PlotCurves.staticPlots->size());
unsigned int rowIndex = 0;
for (mitk::PlotDataCurveCollection::const_iterator pos = m_PlotCurves.staticPlots->begin();
pos != m_PlotCurves.staticPlots->end(); ++pos, ++rowIndex)
{
QColor dataColor;
if (pos->first == "ROI")
{
dataColor = QColor(0, 190, 0);
}
else
{
//Use HSV schema of QColor to calculate a different color depending on the
//number of already existing free iso lines.
dataColor.setHsv(((rowIndex + 1) * 85) % 360, 255, 255);
}
QTableWidgetItem* newItem = new QTableWidgetItem(QString::fromStdString(pos->first));
m_Controls.tableInputData->setItem(rowIndex, 0, newItem);
newItem = new QTableWidgetItem();
- newItem->setBackgroundColor(dataColor);
+ newItem->setBackground(dataColor);
m_Controls.tableInputData->setItem(rowIndex, 1, newItem);
}
}
m_Controls.lInfo->setText(QString::fromStdString(infoOutput.str()));
}
void ModelFitInspectorView::RenderPlotCurve(const mitk::PlotDataCurveCollection* curveCollection, const QColor& sampleColor, const QColor& signalColor, const std::string& posString)
{
auto sampleCurve = mitk::ModelFitPlotData::GetSamplePlot(curveCollection);
if (sampleCurve)
{
std::string name = mitk::MODEL_FIT_PLOT_SAMPLE_NAME() + posString;
unsigned int curveId = m_Controls.widgetPlot->InsertCurve(name.c_str());
m_Controls.widgetPlot->SetCurveData(curveId, sampleCurve->GetValues());
m_Controls.widgetPlot->SetCurvePen(curveId, QPen(Qt::NoPen));
// QwtSymbol needs to passed as a real pointer from MITK v2013.09.0 on
// (QwtPlotCurve deletes it on destruction and assignment).
QwtSymbol* dataSymbol = new QwtSymbol(QwtSymbol::Diamond, sampleColor, sampleColor, QSize(8, 8));
m_Controls.widgetPlot->SetCurveSymbol(curveId, dataSymbol);
// Again, there is no way to set a curve's legend attributes via QmitkPlotWidget so this
// gets unnecessarily complicated.
QwtPlotCurve* measurementCurve = dynamic_cast<QwtPlotCurve*>(m_Controls.widgetPlot->
GetPlot()->itemList(QwtPlotItem::Rtti_PlotCurve).back());
measurementCurve->setLegendAttribute(QwtPlotCurve::LegendShowSymbol);
measurementCurve->setLegendIconSize(QSize(8, 8));
}
//draw model curve
auto signalCurve = mitk::ModelFitPlotData::GetInterpolatedSignalPlot(curveCollection);
if (signalCurve)
{
std::string name = mitk::MODEL_FIT_PLOT_SIGNAL_NAME() + posString;
QPen pen;
pen.setColor(signalColor);
pen.setWidth(2);
unsigned int curveId = m_Controls.widgetPlot->InsertCurve(name.c_str());
m_Controls.widgetPlot->SetCurveData(curveId, signalCurve->GetValues());
m_Controls.widgetPlot->SetCurvePen(curveId, pen);
// Manually set the legend attribute to use the symbol as the legend icon and alter its
// size. Otherwise it would revert to default which is drawing a square which is the color
// of the curve's pen, so in this case none which defaults to black.
// Unfortunately, QmitkPlotWidget offers no way to set the legend attribute and icon size so
// this looks a bit hacky.
QwtPlotCurve* fitCurve = dynamic_cast<QwtPlotCurve*>(m_Controls.widgetPlot->GetPlot()->
itemList(QwtPlotItem::Rtti_PlotCurve).back());
fitCurve->setLegendAttribute(QwtPlotCurve::LegendShowLine);
}
}
void ModelFitInspectorView::RenderPlot()
{
m_Controls.widgetPlot->Clear();
std::string xAxis = DEFAULT_X_AXIS;
std::string yAxis = "Intensity";
std::string plotTitle = "Raw data plot: no data";
if (m_currentSelectedNode.IsNotNull())
{
plotTitle = "Raw data plot: " + m_currentSelectedNode->GetName();
}
if (m_currentFit.IsNotNull())
{
plotTitle = m_currentFit->modelName.c_str();
xAxis = m_currentFit->xAxisName;
if (!m_currentFit->xAxisUnit.empty())
{
xAxis += " [" + m_currentFit->xAxisUnit + "]";
}
yAxis = m_currentFit->yAxisName;
if (!m_currentFit->yAxisUnit.empty())
{
yAxis += " [" + m_currentFit->yAxisUnit + "]";
}
}
m_Controls.widgetPlot->SetAxisTitle(QwtPlot::xBottom, xAxis.c_str());
m_Controls.widgetPlot->SetAxisTitle(QwtPlot::yLeft, yAxis.c_str());
m_Controls.widgetPlot->SetPlotTitle(plotTitle.c_str());
// Draw static curves
unsigned int colorIndex = 0;
for (mitk::PlotDataCurveCollection::const_iterator pos = m_PlotCurves.staticPlots->begin();
pos != m_PlotCurves.staticPlots->end(); ++pos)
{
QColor dataColor;
unsigned int curveId = m_Controls.widgetPlot->InsertCurve(pos->first.c_str());
m_Controls.widgetPlot->SetCurveData(curveId, pos->second->GetValues());
if (pos->first == "ROI")
{
dataColor = QColor(0, 190, 0);
QPen pen;
pen.setColor(dataColor);
pen.setStyle(Qt::SolidLine);
m_Controls.widgetPlot->SetCurvePen(curveId, pen);
}
else
{
//Use HSV schema of QColor to calculate a different color depending on the
//number of already existing curves.
dataColor.setHsv((++colorIndex * 85) % 360, 255, 150);
m_Controls.widgetPlot->SetCurvePen(curveId, QPen(Qt::NoPen));
}
// QwtSymbol needs to passed as a real pointer from MITK v2013.09.0 on
// (QwtPlotCurve deletes it on destruction and assignment).
QwtSymbol* dataSymbol = new QwtSymbol(QwtSymbol::Triangle, dataColor, dataColor,
QSize(8, 8));
m_Controls.widgetPlot->SetCurveSymbol(curveId, dataSymbol);
// Again, there is no way to set a curve's legend attributes via QmitkPlotWidget so this
// gets unnecessarily complicated.
QwtPlotCurve* measurementCurve = dynamic_cast<QwtPlotCurve*>(m_Controls.widgetPlot->
GetPlot()->itemList(QwtPlotItem::Rtti_PlotCurve).back());
measurementCurve->setLegendAttribute(QwtPlotCurve::LegendShowSymbol);
measurementCurve->setLegendIconSize(QSize(8, 8));
}
// Draw positional curves
for (const auto& posIter : this->m_PlotCurves.positionalPlots)
{
QColor dataColor;
dataColor.setHsv((++colorIndex * 85) % 360, 255, 150);
this->RenderPlotCurve(posIter.second.second, dataColor, dataColor, " @ "+mitk::ModelFitPlotData::GetPositionalCollectionName(posIter));
}
// Draw current pos curve
this->RenderPlotCurve(m_PlotCurves.currentPositionPlots, QColor(Qt::red), QColor(Qt::black), "");
QwtLegend* legend = new QwtLegend();
legend->setFrameShape(QFrame::Box);
legend->setFrameShadow(QFrame::Sunken);
legend->setLineWidth(1);
m_Controls.widgetPlot->SetLegend(legend, QwtPlot::BottomLegend);
m_Controls.widgetPlot->Replot();
}
void ModelFitInspectorView::EnsureBookmarkPointSet()
{
if (m_PositionBookmarks.IsExpired() || m_PositionBookmarksNode.IsExpired())
{
const char* nodeName = "org.mitk.gui.qt.fit.inspector.positions";
mitk::DataNode::Pointer node = this->GetDataStorage()->GetNamedNode(nodeName);
if (!node)
{
node = mitk::DataNode::New();
node->SetName(nodeName);
node->SetBoolProperty("helper object", true);
this->GetDataStorage()->Add(node);
}
m_PositionBookmarksNode = node;
mitk::PointSet::Pointer pointSet = dynamic_cast<mitk::PointSet*>(node->GetData());
if (pointSet.IsNull())
{
pointSet = mitk::PointSet::New();
node->SetData(pointSet);
}
m_PositionBookmarks = pointSet;
}
}
diff --git a/Plugins/org.mitk.gui.qt.flowapplication/CMakeLists.txt b/Plugins/org.mitk.gui.qt.flowapplication/CMakeLists.txt
index 68e309ef49..1fc30ca053 100644
--- a/Plugins/org.mitk.gui.qt.flowapplication/CMakeLists.txt
+++ b/Plugins/org.mitk.gui.qt.flowapplication/CMakeLists.txt
@@ -1,17 +1,17 @@
project(org_mitk_gui_qt_flowapplication)
# see bug-19679
set(additional_dependencies "")
if(APPLE)
- set(additional_dependencies Qt5|DBus)
+ set(additional_dependencies Qt6|DBus)
endif()
mitk_create_plugin(
EXPORT_DIRECTIVE MITK_QT_FLOW_BENCH_APP_EXPORT
EXPORTED_INCLUDE_SUFFIXES src
MODULE_DEPENDS
PRIVATE MitkQtWidgetsExt MitkSceneSerialization MitkAppUtil
- PACKAGE_DEPENDS Qt5|WebEngineWidgets ${additional_dependencies}
+ PACKAGE_DEPENDS Qt6|WebEngineWidgets ${additional_dependencies}
)
diff --git a/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationWorkbenchWindowAdvisor.cpp
index 35379f49fa..4932ae0a6d 100644
--- a/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationWorkbenchWindowAdvisor.cpp
+++ b/Plugins/org.mitk.gui.qt.flowapplication/src/internal/QmitkFlowApplicationWorkbenchWindowAdvisor.cpp
@@ -1,1158 +1,1164 @@
/*============================================================================
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 "QmitkFlowApplicationWorkbenchWindowAdvisor.h"
#include <QMenu>
#include <QMenuBar>
#include <QMainWindow>
#include <QStatusBar>
#include <QString>
#include <QFile>
-#include <QRegExp>
+#include <QRegularExpression>
#include <QTextStream>
#include <QSettings>
#include <ctkPluginException.h>
#include <service/event/ctkEventAdmin.h>
#include <berryPlatform.h>
#include <berryPlatformUI.h>
#include <berryIActionBarConfigurer.h>
#include <berryIWorkbenchWindow.h>
#include <berryIWorkbenchPage.h>
#include <berryIPerspectiveRegistry.h>
#include <berryIPerspectiveDescriptor.h>
#include <berryIProduct.h>
#include <berryIWorkbenchPartConstants.h>
#include <berryQtPreferences.h>
#include <berryQtStyleManager.h>
#include <berryWorkbenchPlugin.h>
#include <internal/berryQtShowViewAction.h>
#include <internal/berryQtOpenPerspectiveAction.h>
#include <QmitkFileExitAction.h>
#include <QmitkCloseProjectAction.h>
#include <QmitkUndoAction.h>
#include <QmitkRedoAction.h>
#include <QmitkDefaultDropTargetListener.h>
#include <QmitkStatusBar.h>
#include <QmitkProgressBar.h>
#include <QmitkMemoryUsageIndicatorView.h>
#include <QmitkPreferencesDialog.h>
+#include <QmitkApplicationConstants.h>
#include "QmitkExtFileSaveProjectAction.h"
#include <itkConfigure.h>
#include <mitkVersion.h>
#include <mitkIDataStorageService.h>
#include <mitkIDataStorageReference.h>
#include <mitkDataStorageEditorInput.h>
#include <mitkWorkbenchUtil.h>
#include <vtkVersionMacros.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
// UGLYYY
#include "QmitkFlowApplicationWorkbenchWindowAdvisorHack.h"
#include "QmitkFlowApplicationPlugin.h"
#include "mitkUndoController.h"
#include "mitkVerboseLimitedLinearUndo.h"
#include <QToolBar>
#include <QToolButton>
#include <QMessageBox>
#include <QMouseEvent>
#include <QLabel>
#include <QmitkAboutDialog.h>
QmitkFlowApplicationWorkbenchWindowAdvisorHack* QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack =
new QmitkFlowApplicationWorkbenchWindowAdvisorHack();
QString QmitkFlowApplicationWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini";
class PartListenerForTitle: public berry::IPartListener
{
public:
PartListenerForTitle(QmitkFlowApplicationWorkbenchWindowAdvisor* wa)
: windowAdvisor(wa)
{
}
Events::Types GetPartEventTypes() const override
{
return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED
| Events::HIDDEN | Events::VISIBLE;
}
void PartActivated(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref.Cast<berry::IEditorReference> ())
{
windowAdvisor->UpdateTitle(false);
}
}
void PartBroughtToTop(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref.Cast<berry::IEditorReference> ())
{
windowAdvisor->UpdateTitle(false);
}
}
void PartClosed(const berry::IWorkbenchPartReference::Pointer& /*ref*/) override
{
windowAdvisor->UpdateTitle(false);
}
void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override
{
auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock();
if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor)
{
windowAdvisor->UpdateTitle(true);
}
}
void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override
{
auto lockedLastActiveEditor = windowAdvisor->lastActiveEditor.Lock();
if (lockedLastActiveEditor.IsNotNull() && ref->GetPart(false) == lockedLastActiveEditor)
{
windowAdvisor->UpdateTitle(false);
}
}
private:
QmitkFlowApplicationWorkbenchWindowAdvisor* windowAdvisor;
};
class PartListenerForImageNavigator: public berry::IPartListener
{
public:
PartListenerForImageNavigator(QAction* act)
: imageNavigatorAction(act)
{
}
Events::Types GetPartEventTypes() const override
{
return Events::OPENED | Events::CLOSED | Events::HIDDEN |
Events::VISIBLE;
}
void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.imagenavigator")
{
imageNavigatorAction->setChecked(true);
}
}
void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.imagenavigator")
{
imageNavigatorAction->setChecked(false);
}
}
void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.imagenavigator")
{
imageNavigatorAction->setChecked(true);
}
}
void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) override
{
if (ref->GetId()=="org.mitk.views.imagenavigator")
{
imageNavigatorAction->setChecked(false);
}
}
private:
QAction* imageNavigatorAction;
};
class PerspectiveListenerForTitle: public berry::IPerspectiveListener
{
public:
PerspectiveListenerForTitle(QmitkFlowApplicationWorkbenchWindowAdvisor* wa)
: windowAdvisor(wa)
, perspectivesClosed(false)
{
}
Events::Types GetPerspectiveEventTypes() const override
{
return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED
| Events::CLOSED | Events::OPENED;
}
void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
windowAdvisor->UpdateTitle(false);
}
void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/,
const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) override
{
windowAdvisor->UpdateTitle(false);
}
void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
windowAdvisor->UpdateTitle(false);
}
void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
if (perspectivesClosed)
{
QListIterator<QAction*> i(windowAdvisor->viewActions);
while (i.hasNext())
{
i.next()->setEnabled(true);
}
windowAdvisor->fileSaveProjectAction->setEnabled(true);
windowAdvisor->undoAction->setEnabled(true);
windowAdvisor->redoAction->setEnabled(true);
windowAdvisor->imageNavigatorAction->setEnabled(true);
windowAdvisor->resetPerspAction->setEnabled(true);
}
perspectivesClosed = false;
}
void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow();
bool allClosed = true;
if (wnd->GetActivePage())
{
QList<berry::IPerspectiveDescriptor::Pointer> perspectives(wnd->GetActivePage()->GetOpenPerspectives());
allClosed = perspectives.empty();
}
if (allClosed)
{
perspectivesClosed = true;
QListIterator<QAction*> i(windowAdvisor->viewActions);
while (i.hasNext())
{
i.next()->setEnabled(false);
}
windowAdvisor->fileSaveProjectAction->setEnabled(false);
windowAdvisor->undoAction->setEnabled(false);
windowAdvisor->redoAction->setEnabled(false);
windowAdvisor->imageNavigatorAction->setEnabled(false);
windowAdvisor->resetPerspAction->setEnabled(false);
}
}
private:
QmitkFlowApplicationWorkbenchWindowAdvisor* windowAdvisor;
bool perspectivesClosed;
};
class PerspectiveListenerForMenu: public berry::IPerspectiveListener
{
public:
PerspectiveListenerForMenu(QmitkFlowApplicationWorkbenchWindowAdvisor* wa)
: windowAdvisor(wa)
{
}
Events::Types GetPerspectiveEventTypes() const override
{
return Events::ACTIVATED | Events::DEACTIVATED;
}
void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& perspective) override
{
QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()];
if (action)
{
action->setChecked(true);
}
}
void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& perspective) override
{
QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()];
if (action)
{
action->setChecked(false);
}
}
private:
QmitkFlowApplicationWorkbenchWindowAdvisor* windowAdvisor;
};
QmitkFlowApplicationWorkbenchWindowAdvisor::QmitkFlowApplicationWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor,
berry::IWorkbenchWindowConfigurer::Pointer configurer)
: berry::WorkbenchWindowAdvisor(configurer)
, lastInput(nullptr)
, wbAdvisor(wbAdvisor)
, showViewToolbar(true)
, showVersionInfo(true)
, showMitkVersionInfo(true)
, showMemoryIndicator(true)
, dropTargetListener(new QmitkDefaultDropTargetListener)
{
productName = QCoreApplication::applicationName();
viewExcludeList.push_back("org.mitk.views.viewnavigator");
}
QmitkFlowApplicationWorkbenchWindowAdvisor::~QmitkFlowApplicationWorkbenchWindowAdvisor()
{
}
QWidget* QmitkFlowApplicationWorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* parent)
{
QWidget* parentWidget = static_cast<QWidget*>(parent);
auto label = new QLabel(parentWidget);
label->setText("<b>No perspectives are open. Open a perspective in the <i>Window->Open Perspective</i> menu.</b>");
label->setContentsMargins(10,10,10,10);
label->setAlignment(Qt::AlignTop);
label->setEnabled(false);
parentWidget->layout()->addWidget(label);
return label;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::ShowMemoryIndicator(bool show)
{
showMemoryIndicator = show;
}
bool QmitkFlowApplicationWorkbenchWindowAdvisor::GetShowMemoryIndicator()
{
return showMemoryIndicator;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::ShowViewToolbar(bool show)
{
showViewToolbar = show;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::ShowVersionInfo(bool show)
{
showVersionInfo = show;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show)
{
showMitkVersionInfo = show;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::SetProductName(const QString& product)
{
productName = product;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::SetWindowIcon(const QString& wndIcon)
{
windowIcon = wndIcon;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::PostWindowCreate()
{
// very bad hack...
berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow();
QMainWindow* mainWindow = qobject_cast<QMainWindow*> (window->GetShell()->GetControl());
if (!windowIcon.isEmpty())
{
mainWindow->setWindowIcon(QIcon(windowIcon));
}
mainWindow->setContextMenuPolicy(Qt::PreventContextMenu);
// Load icon theme
QIcon::setThemeSearchPaths(QStringList() << QStringLiteral(":/org_mitk_icons/icons/"));
QIcon::setThemeName(QStringLiteral("awesome"));
// ==== Application menu ============================
QMenuBar* menuBar = mainWindow->menuBar();
menuBar->setContextMenuPolicy(Qt::PreventContextMenu);
#ifdef __APPLE__
menuBar->setNativeMenuBar(true);
#else
menuBar->setNativeMenuBar(false);
#endif
auto basePath = QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/");
fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window);
fileSaveProjectAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "document-save.svg"));
auto perspGroup = new QActionGroup(menuBar);
std::map<QString, berry::IViewDescriptor::Pointer> VDMap;
// sort elements (converting vector to map...)
QList<berry::IViewDescriptor::Pointer>::const_iterator iter;
berry::IViewRegistry* viewRegistry =
berry::PlatformUI::GetWorkbench()->GetViewRegistry();
const QList<berry::IViewDescriptor::Pointer> viewDescriptors = viewRegistry->GetViews();
bool skip = false;
for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter)
{
// if viewExcludeList is set, it contains the id-strings of view, which
// should not appear as an menu-entry in the menu
if (viewExcludeList.size() > 0)
{
for (int i=0; i<viewExcludeList.size(); i++)
{
if (viewExcludeList.at(i) == (*iter)->GetId())
{
skip = true;
break;
}
}
if (skip)
{
skip = false;
continue;
}
}
if ((*iter)->GetId() == "org.blueberry.ui.internal.introview")
continue;
if ((*iter)->GetId() == "org.mitk.views.imagenavigator")
continue;
if ((*iter)->GetId() == "org.mitk.views.viewnavigator")
continue;
std::pair<QString, berry::IViewDescriptor::Pointer> p((*iter)->GetLabel(), (*iter));
VDMap.insert(p);
}
std::map<QString, berry::IViewDescriptor::Pointer>::const_iterator MapIter;
for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter)
{
berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second);
viewActions.push_back(viewAction);
}
QMenu* fileMenu = menuBar->addMenu("&File");
fileMenu->setObjectName("FileMenu");
fileMenu->addAction(fileSaveProjectAction);
fileMenu->addSeparator();
QAction* fileExitAction = new QmitkFileExitAction(window);
fileExitAction->setIcon(berry::QtStyleManager::ThemeIcon(basePath + "system-log-out.svg"));
fileExitAction->setShortcut(QKeySequence::Quit);
fileExitAction->setObjectName("QmitkFileExitAction");
fileMenu->addAction(fileExitAction);
// another bad hack to get an edit/undo menu...
QMenu* editMenu = menuBar->addMenu("&Edit");
undoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-undo.svg"),
"&Undo",
QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()),
QKeySequence("CTRL+Z"));
undoAction->setToolTip("Undo the last action (not supported by all modules)");
redoAction = editMenu->addAction(berry::QtStyleManager::ThemeIcon(basePath + "edit-redo.svg"),
"&Redo",
QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()),
QKeySequence("CTRL+Y"));
redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)");
// ==== Window Menu ==========================
QMenu* windowMenu = menuBar->addMenu("Window");
QMenu* perspMenu = windowMenu->addMenu("&Open Perspective");
windowMenu->addSeparator();
resetPerspAction = windowMenu->addAction("&Reset Perspective",
QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective()));
windowMenu->addSeparator();
windowMenu->addAction("&Preferences...",
QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()),
QKeySequence("CTRL+P"));
// fill perspective menu
berry::IPerspectiveRegistry* perspRegistry =
window->GetWorkbench()->GetPerspectiveRegistry();
QList<berry::IPerspectiveDescriptor::Pointer> perspectives(
perspRegistry->GetPerspectives());
skip = false;
for (QList<berry::IPerspectiveDescriptor::Pointer>::iterator perspIt =
perspectives.begin(); perspIt != perspectives.end(); ++perspIt)
{
// if perspectiveExcludeList is set, it contains the id-strings of perspectives, which
// should not appear as an menu-entry in the perspective menu
if (perspectiveExcludeList.size() > 0)
{
for (int i=0; i<perspectiveExcludeList.size(); i++)
{
if (perspectiveExcludeList.at(i) == (*perspIt)->GetId())
{
skip = true;
break;
}
}
if (skip)
{
skip = false;
continue;
}
}
QAction* perspAction = new berry::QtOpenPerspectiveAction(window, *perspIt, perspGroup);
mapPerspIdToAction.insert((*perspIt)->GetId(), perspAction);
}
perspMenu->addActions(perspGroup->actions());
// ===== Help menu ====================================
QMenu* helpMenu = menuBar->addMenu("&Help");
helpMenu->addAction("&Welcome",this, SLOT(onIntro()));
helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective()));
helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1"));
helpMenu->addAction("&About",this, SLOT(onAbout()));
// =====================================================
// toolbar for showing file open, undo, redo and other main actions
auto mainActionsToolBar = new QToolBar;
mainActionsToolBar->setObjectName("mainActionsToolBar");
mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu);
#ifdef __APPLE__
mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
#else
mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
#endif
basePath = QStringLiteral(":/org.mitk.gui.qt.ext/");
imageNavigatorAction = new QAction(berry::QtStyleManager::ThemeIcon(basePath + "image_navigator.svg"), "&Image Navigator", nullptr);
bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator");
if (imageNavigatorViewFound)
{
QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator()));
imageNavigatorAction->setCheckable(true);
// add part listener for image navigator
imageNavigatorPartListener.reset(new PartListenerForImageNavigator(imageNavigatorAction));
window->GetPartService()->AddPartListener(imageNavigatorPartListener.data());
berry::IViewPart::Pointer imageNavigatorView = window->GetActivePage()->FindView("org.mitk.views.imagenavigator");
imageNavigatorAction->setChecked(false);
if (imageNavigatorView)
{
bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView);
if (isImageNavigatorVisible)
imageNavigatorAction->setChecked(true);
}
imageNavigatorAction->setToolTip("Toggle image navigator for navigating through image");
}
mainActionsToolBar->addAction(undoAction);
mainActionsToolBar->addAction(redoAction);
if (imageNavigatorViewFound)
{
mainActionsToolBar->addAction(imageNavigatorAction);
}
mainWindow->addToolBar(mainActionsToolBar);
// ==== View Toolbar ==================================
if (showViewToolbar)
{
auto* prefService = mitk::CoreServices::GetPreferencesService();
+
auto* stylePrefs = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE);
bool showCategoryNames = stylePrefs->GetBool(berry::QtPreferences::QT_SHOW_TOOLBAR_CATEGORY_NAMES, true);
+ auto* toolBarsPrefs = prefService->GetSystemPreferences()->Node(QmitkApplicationConstants::TOOL_BARS_PREFERENCES);
+
// Order view descriptors by category
QMultiMap<QString, berry::IViewDescriptor::Pointer> categoryViewDescriptorMap;
for (auto labelViewDescriptorPair : VDMap)
{
auto viewDescriptor = labelViewDescriptorPair.second;
auto category = !viewDescriptor->GetCategoryPath().isEmpty()
? viewDescriptor->GetCategoryPath().back()
: QString();
categoryViewDescriptorMap.insert(category, viewDescriptor);
}
// Create a separate toolbar for each category
for (auto category : categoryViewDescriptorMap.uniqueKeys())
{
auto viewDescriptorsInCurrentCategory = categoryViewDescriptorMap.values(category);
QList<berry::SmartPointer<berry::IViewDescriptor> > relevantViewDescriptors;
for (auto viewDescriptor : viewDescriptorsInCurrentCategory)
{
if (viewDescriptor->GetId() != "org.mitk.views.flow.control" &&
viewDescriptor->GetId() != "org.mitk.views.segmentationtasklist")
{
relevantViewDescriptors.push_back(viewDescriptor);
}
}
if (!relevantViewDescriptors.isEmpty())
{
auto toolbar = new QToolBar;
- toolbar->setObjectName(category + " View Toolbar");
+ toolbar->setObjectName(category);
mainWindow->addToolBar(toolbar);
+ toolbar->setVisible(toolBarsPrefs->GetBool(category.toStdString(), true));
+
if (showCategoryNames && !category.isEmpty())
{
auto categoryButton = new QToolButton;
categoryButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
categoryButton->setText(category);
categoryButton->setStyleSheet("background: transparent; margin: 0; padding: 0;");
toolbar->addWidget(categoryButton);
connect(categoryButton, &QToolButton::clicked, [toolbar]()
{
for (QWidget* widget : toolbar->findChildren<QWidget*>())
{
if (QStringLiteral("qt_toolbar_ext_button") == widget->objectName() && widget->isVisible())
{
QMouseEvent pressEvent(QEvent::MouseButtonPress, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QMouseEvent releaseEvent(QEvent::MouseButtonRelease, QPointF(0.0f, 0.0f), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QApplication::sendEvent(widget, &pressEvent);
QApplication::sendEvent(widget, &releaseEvent);
}
}
});
}
for (auto viewDescriptor : relevantViewDescriptors)
{
auto viewAction = new berry::QtShowViewAction(window, viewDescriptor);
toolbar->addAction(viewAction);
}
}
}
}
QSettings settings(GetQSettingsFile(), QSettings::IniFormat);
mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray());
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);
if (showMemoryIndicator)
{
auto memoryIndicator = new QmitkMemoryUsageIndicatorView();
qStatusBar->addPermanentWidget(memoryIndicator, 0);
}
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::PreWindowOpen()
{
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
this->HookTitleUpdateListeners(configurer);
menuPerspectiveListener.reset(new PerspectiveListenerForMenu(this));
configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener.data());
configurer->AddEditorAreaTransfer(QStringList("text/uri-list"));
configurer->ConfigureEditorAreaDropListener(dropTargetListener.data());
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::PostWindowOpen()
{
berry::WorkbenchWindowAdvisor::PostWindowOpen();
// Force Rendering Window Creation on startup.
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
ctkPluginContext* context = QmitkFlowApplicationPlugin::GetDefault()->GetPluginContext();
ctkServiceReference serviceRef = context->getServiceReference<mitk::IDataStorageService>();
if (serviceRef)
{
mitk::IDataStorageService *dsService = context->getService<mitk::IDataStorageService>(serviceRef);
if (dsService)
{
mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage();
mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dsRef));
mitk::WorkbenchUtil::OpenEditor(configurer->GetWindow()->GetActivePage(),dsInput);
}
}
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::onIntro()
{
QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack->onIntro();
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::onHelp()
{
QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack->onHelp();
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::onHelpOpenHelpPerspective()
{
QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack->onHelpOpenHelpPerspective();
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::onAbout()
{
QmitkFlowApplicationWorkbenchWindowAdvisorHack::undohack->onAbout();
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::HookTitleUpdateListeners(berry::IWorkbenchWindowConfigurer::Pointer configurer)
{
// hook up the listeners to update the window title
titlePartListener.reset(new PartListenerForTitle(this));
titlePerspectiveListener.reset(new PerspectiveListenerForTitle(this));
editorPropertyListener.reset(new berry::PropertyChangeIntAdapter<
QmitkFlowApplicationWorkbenchWindowAdvisor>(this,
&QmitkFlowApplicationWorkbenchWindowAdvisor::PropertyChange));
configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener.data());
configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener.data());
}
QString QmitkFlowApplicationWorkbenchWindowAdvisor::ComputeTitle()
{
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage();
berry::IEditorPart::Pointer activeEditor;
if (currentPage)
{
activeEditor = lastActiveEditor.Lock();
}
QString title;
berry::IProduct::Pointer product = berry::Platform::GetProduct();
if (product.IsNotNull())
{
title = product->GetName();
}
if (title.isEmpty())
{
// instead of the product name, we use a custom variable for now
title = productName;
}
if(showMitkVersionInfo)
{
QString mitkVersionInfo = MITK_REVISION_DESC;
if(mitkVersionInfo.isEmpty())
mitkVersionInfo = MITK_VERSION_STRING;
title += " " + mitkVersionInfo;
}
if (showVersionInfo)
{
// add version informatioin
QString versions = QString(" (ITK %1.%2.%3 | VTK %4.%5.%6 | Qt %7)")
.arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH)
.arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION)
.arg(QT_VERSION_STR);
title += versions;
}
if (currentPage)
{
if (activeEditor)
{
lastEditorTitle = activeEditor->GetTitleToolTip();
if (!lastEditorTitle.isEmpty())
title = lastEditorTitle + " - " + title;
}
berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective();
QString label = "";
if (persp)
{
label = persp->GetLabel();
}
berry::IAdaptable* input = currentPage->GetInput();
if (input && input != wbAdvisor->GetDefaultPageInput())
{
label = currentPage->GetLabel();
}
if (!label.isEmpty())
{
title = label + " - " + title;
}
}
title += " (Not for use in diagnosis or treatment of patients)";
return title;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::RecomputeTitle()
{
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
QString oldTitle = configurer->GetTitle();
QString newTitle = ComputeTitle();
if (newTitle != oldTitle)
{
configurer->SetTitle(newTitle);
}
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden)
{
berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer();
berry::IWorkbenchWindow::Pointer window = configurer->GetWindow();
berry::IEditorPart::Pointer activeEditor;
berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage();
berry::IPerspectiveDescriptor::Pointer persp;
berry::IAdaptable* input = nullptr;
if (currentPage)
{
activeEditor = currentPage->GetActiveEditor();
persp = currentPage->GetPerspective();
input = currentPage->GetInput();
}
if (editorHidden)
{
activeEditor = nullptr;
}
// Nothing to do if the editor hasn't changed
if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock()
&& persp == lastPerspective.Lock() && input == lastInput)
{
return;
}
auto lockedLastActiveEditor = lastActiveEditor.Lock();
if (lockedLastActiveEditor.IsNotNull())
{
lockedLastActiveEditor->RemovePropertyListener(editorPropertyListener.data());
}
lastActiveEditor = activeEditor;
lastActivePage = currentPage;
lastPerspective = persp;
lastInput = input;
if (activeEditor)
{
activeEditor->AddPropertyListener(editorPropertyListener.data());
}
RecomputeTitle();
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::PropertyChange(const berry::Object::Pointer& /*source*/, int propId)
{
if (propId == berry::IWorkbenchPartConstants::PROP_TITLE)
{
auto lockedLastActiveEditor = lastActiveEditor.Lock();
if (lockedLastActiveEditor.IsNotNull())
{
QString newTitle = lockedLastActiveEditor->GetPartName();
if (lastEditorTitle != newTitle)
{
RecomputeTitle();
}
}
}
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::SetPerspectiveExcludeList(const QList<QString>& v)
{
this->perspectiveExcludeList = v;
}
QList<QString> QmitkFlowApplicationWorkbenchWindowAdvisor::GetPerspectiveExcludeList()
{
return this->perspectiveExcludeList;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::SetViewExcludeList(const QList<QString>& v)
{
this->viewExcludeList = v;
}
QList<QString> QmitkFlowApplicationWorkbenchWindowAdvisor::GetViewExcludeList()
{
return this->viewExcludeList;
}
void QmitkFlowApplicationWorkbenchWindowAdvisor::PostWindowClose()
{
berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow();
QMainWindow* mainWindow = static_cast<QMainWindow*> (window->GetShell()->GetControl());
auto fileName = this->GetQSettingsFile();
if (!fileName.isEmpty())
{
QSettings settings(fileName, QSettings::IniFormat);
settings.setValue("ToolbarPosition", mainWindow->saveState());
}
}
QString QmitkFlowApplicationWorkbenchWindowAdvisor::GetQSettingsFile() const
{
QFileInfo settingsInfo = QmitkFlowApplicationPlugin::GetDefault()->GetPluginContext()->getDataFile(QT_SETTINGS_FILENAME);
return settingsInfo.canonicalFilePath();
}
//--------------------------------------------------------------------------------
// Ugly hack from here on. Feel free to delete when command framework
// and undo buttons are done.
//--------------------------------------------------------------------------------
QmitkFlowApplicationWorkbenchWindowAdvisorHack::QmitkFlowApplicationWorkbenchWindowAdvisorHack()
: QObject()
{
}
QmitkFlowApplicationWorkbenchWindowAdvisorHack::~QmitkFlowApplicationWorkbenchWindowAdvisorHack()
{
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onUndo()
{
mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel();
if (model)
{
if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast<mitk::VerboseLimitedLinearUndo*>(model))
{
mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions();
if (descriptions.size() >= 1)
{
MITK_INFO << "Undo " << descriptions.front().second;
}
}
model->Undo();
}
else
{
MITK_ERROR << "No undo model instantiated";
}
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onRedo()
{
mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel();
if (model)
{
if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast<mitk::VerboseLimitedLinearUndo*>(model))
{
mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions();
if (descriptions.size() >= 1)
{
MITK_INFO << "Redo " << descriptions.front().second;
}
}
model->Redo();
}
else
{
MITK_ERROR << "No undo model instantiated";
}
}
// safe calls to the complete chain
// berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator");
// to cover for all possible cases of closed pages etc.
static void SafeHandleNavigatorView(QString view_query_name)
{
berry::IWorkbench* wbench = berry::PlatformUI::GetWorkbench();
if (wbench == nullptr)
return;
berry::IWorkbenchWindow::Pointer wbench_window = wbench->GetActiveWorkbenchWindow();
if (wbench_window.IsNull())
return;
berry::IWorkbenchPage::Pointer wbench_page = wbench_window->GetActivePage();
if (wbench_page.IsNull())
return;
auto wbench_view = wbench_page->FindView(view_query_name);
if (wbench_view.IsNotNull())
{
bool isViewVisible = wbench_page->IsPartVisible(wbench_view);
if (isViewVisible)
{
wbench_page->HideView(wbench_view);
return;
}
}
wbench_page->ShowView(view_query_name);
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onImageNavigator()
{
// show/hide ImageNavigatorView
SafeHandleNavigatorView("org.mitk.views.imagenavigator");
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onEditPreferences()
{
QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow());
_PreferencesDialog.exec();
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onQuit()
{
berry::PlatformUI::GetWorkbench()->Close();
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onResetPerspective()
{
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective();
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onClosePerspective()
{
berry::IWorkbenchPage::Pointer page =
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage();
page->ClosePerspective(page->GetPerspective(), true, true);
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onIntro()
{
bool hasIntro =
berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro();
if (!hasIntro)
{
- QRegExp reg("(.*)<title>(\\n)*");
- QRegExp reg2("(\\n)*</title>(.*)");
+ QRegularExpression reg("(.*)<title>(\\n)*");
+ QRegularExpression reg2("(\\n)*</title>(.*)");
QFile file(":/org.mitk.gui.qt.ext/index.html");
file.open(QIODevice::ReadOnly | QIODevice::Text); //text file only for reading
QString text = QString(file.readAll());
file.close();
QString title = text;
title.replace(reg, "");
title.replace(reg2, "");
std::cout << title.toStdString() << std::endl;
QMessageBox::information(nullptr, title,
text, "Close");
}
else
{
berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro(
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false);
}
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onHelp()
{
ctkPluginContext* context = QmitkFlowApplicationPlugin::GetDefault()->GetPluginContext();
if (context == nullptr)
{
MITK_WARN << "Plugin context not set, unable to open context help";
return;
}
// Check if the org.blueberry.ui.qt.help plug-in is installed and started
QList<QSharedPointer<ctkPlugin> > plugins = context->getPlugins();
foreach(QSharedPointer<ctkPlugin> p, plugins)
{
if (p->getSymbolicName() == "org.blueberry.ui.qt.help")
{
if (p->getState() != ctkPlugin::ACTIVE)
{
// try to activate the plug-in explicitly
try
{
p->start(ctkPlugin::START_TRANSIENT);
}
catch (const ctkPluginException& pe)
{
MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what();
return;
}
}
}
}
ctkServiceReference eventAdminRef = context->getServiceReference<ctkEventAdmin>();
ctkEventAdmin* eventAdmin = nullptr;
if (eventAdminRef)
{
eventAdmin = context->getService<ctkEventAdmin>(eventAdminRef);
}
if (eventAdmin == nullptr)
{
MITK_WARN << "ctkEventAdmin service not found. Unable to open context help";
}
else
{
ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED");
eventAdmin->postEvent(ev);
}
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onHelpOpenHelpPerspective()
{
berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help",
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow());
}
void QmitkFlowApplicationWorkbenchWindowAdvisorHack::onAbout()
{
- auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(), nullptr);
+ auto aboutDialog = new QmitkAboutDialog(QApplication::activeWindow());
aboutDialog->open();
}
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/CMakeLists.txt b/Plugins/org.mitk.gui.qt.geometrytools/CMakeLists.txt
deleted file mode 100644
index 315504774f..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-project(org_mitk_gui_qt_geometrytools)
-
-mitk_create_plugin(
- EXPORT_DIRECTIVE GEOMETRYTOOLS_EXPORT
- EXPORTED_INCLUDE_SUFFIXES src
- MODULE_DEPENDS MitkQtWidgetsExt
-)
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/documentation/UserManual/Manual.dox b/Plugins/org.mitk.gui.qt.geometrytools/documentation/UserManual/Manual.dox
deleted file mode 100644
index 3baf2840a5..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/documentation/UserManual/Manual.dox
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
-\page org_mitk_gui_qt_geometrytools The Geometry Tools
-
-\imageMacro{geometrytools-dox.xpm,"Icon of Geometry Tools",2.00}
-
-\tableofcontents
-
-\section org_mitk_gui_qt_geometrytoolsOverview Overview
-
-A plugin to modify geometry of mitkBaseData via interaction. Currently, the following
-operations can be performed:
-
-<ul>
-<li>Translation
-<li>Rotation
-<li>Scaling (not supported for images, yet, and will not happen in coordinate origin)
-</ul>
-*/
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/documentation/UserManual/geometrytools-dox.xpm b/Plugins/org.mitk.gui.qt.geometrytools/documentation/UserManual/geometrytools-dox.xpm
deleted file mode 100644
index 7b3b16dec1..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/documentation/UserManual/geometrytools-dox.xpm
+++ /dev/null
@@ -1,896 +0,0 @@
-/* XPM */
-static char * geometrytools_color_xpm[] = {
-"100 97 796 2",
-" c None",
-". c #0070C0",
-"+ c #74B349",
-"@ c #466C2C",
-"# c #121C0C",
-"$ c #223516",
-"% c #60943D",
-"& c #42672A",
-"* c #111B0B",
-"= c #263B18",
-"- c #649A3F",
-"; c #73B149",
-"> c #3F6128",
-", c #10190A",
-"' c #2A401B",
-") c #679F41",
-"! c #71AF48",
-"~ c #3B5B26",
-"{ c #10180A",
-"] c #2D471D",
-"^ c #6AA443",
-"/ c #70AC47",
-"( c #375523",
-"_ c #0F180A",
-": c #314C1F",
-"< c #6EAA46",
-"[ c #74B34A",
-"} c #73B249",
-"| c #71AE48",
-"1 c #70AD47",
-"2 c #7ABD4D",
-"3 c #3F6229",
-"4 c #000000",
-"5 c #0A1305",
-"6 c #588C35",
-"7 c #71B245",
-"8 c #33521F",
-"9 c #0F1A08",
-"0 c #5D9338",
-"a c #6FB044",
-"b c #2E4B1C",
-"c c #14220B",
-"d c #61993B",
-"e c #6EAD43",
-"f c #2A4419",
-"g c #19290E",
-"h c #659F3D",
-"i c #6CAA41",
-"j c #253C16",
-"k c #1F3412",
-"l c #558634",
-"m c #41642A",
-"n c #476E2D",
-"o c #639D3D",
-"p c #6DAC42",
-"q c #6CAB42",
-"r c #6EAC44",
-"s c #0E1609",
-"t c #0A0B09",
-"u c #73876A",
-"v c #A6C39A",
-"w c #B9D9AC",
-"x c #8AA280",
-"y c #5C6C54",
-"z c #6F8367",
-"A c #AAC79E",
-"B c #B8D8AB",
-"C c #879E7D",
-"D c #5B6B54",
-"E c #ADCBA0",
-"F c #B7D6A9",
-"G c #839A7A",
-"H c #5A6A53",
-"I c #768B6E",
-"J c #B0CEA3",
-"K c #B5D5A8",
-"L c #809676",
-"M c #819878",
-"N c #63735C",
-"O c #141713",
-"P c #90A985",
-"Q c #B6D5A8",
-"R c #B7D6AB",
-"S c #97C37D",
-"T c #6DAC43",
-"U c #10120F",
-"V c #C7EBB7",
-"W c #B5D5A6",
-"X c #B4D4A4",
-"Y c #B7D8A8",
-"Z c #BBDCAB",
-"` c #B9DAAA",
-" . c #B4D4A5",
-".. c #B9DAA9",
-"+. c #B4D5A5",
-"@. c #B8D8A8",
-"#. c #B8D9A8",
-"$. c #BEE0AE",
-"%. c #6E8165",
-"&. c #0F110D",
-"*. c #252C22",
-"=. c #92AD86",
-"-. c #B6D6A7",
-";. c #B5D5A7",
-">. c #95C37B",
-",. c #3F6228",
-"'. c #365422",
-"). c #536A46",
-"!. c #BBDCAC",
-"~. c #B3D4A4",
-"{. c #A1BF94",
-"]. c #8AA37E",
-"^. c #90A984",
-"/. c #ABCA9C",
-"(. c #B4D4A6",
-"_. c #95C27A",
-":. c #72B248",
-"<. c #9AC880",
-"[. c #B2D3A3",
-"}. c #B6D8A7",
-"|. c #BCDEAC",
-"1. c #BADDAB",
-"2. c #73B248",
-"3. c #9BC980",
-"4. c #B5D7A6",
-"5. c #8EA882",
-"6. c #5E7057",
-"7. c #6A7E61",
-"8. c #A1BF93",
-"9. c #0C1208",
-"0. c #0B0D0B",
-"a. c #BFE3AE",
-"b. c #B1D3A2",
-"c. c #B8DBA8",
-"d. c #627459",
-"e. c #10130F",
-"f. c #8CA680",
-"g. c #B3D6A4",
-"h. c #B2D4A4",
-"i. c #94C279",
-"j. c #0D1408",
-"k. c #0D0F0C",
-"l. c #BEE2AD",
-"m. c #B1D2A1",
-"n. c #B6D9A6",
-"o. c #6E8465",
-"p. c #161A14",
-"q. c #2A3327",
-"r. c #91AD85",
-"s. c #B3D4A3",
-"t. c #94C179",
-"u. c #49712E",
-"v. c #416629",
-"w. c #5F7B4F",
-"x. c #B7D9A7",
-"y. c #B0D2A0",
-"z. c #A2C294",
-"A. c #90AC83",
-"B. c #94B187",
-"C. c #AACA9B",
-"D. c #B0D3A1",
-"E. c #93C278",
-"F. c #72B048",
-"G. c #71B047",
-"H. c #97C57C",
-"I. c #B1D2A2",
-"J. c #AFD19F",
-"K. c #B2D5A2",
-"L. c #B7DAA6",
-"M. c #B6D9A5",
-"N. c #B1D3A1",
-"O. c #93C178",
-"P. c #6FAC46",
-"Q. c #94C17A",
-"R. c #88A37C",
-"S. c #56664E",
-"T. c #627559",
-"U. c #9DBB8E",
-"V. c #B0D2A1",
-"W. c #0A1007",
-"X. c #090A09",
-"Y. c #BBE1AA",
-"Z. c #AED19E",
-"`. c #B5D9A4",
-" + c #5F7256",
-".+ c #0E100C",
-"++ c #89A47C",
-"@+ c #B0D4A0",
-"#+ c #AFD2A0",
-"$+ c #92C177",
-"%+ c #0C1207",
-"&+ c #0B0C0B",
-"*+ c #BBE0AA",
-"=+ c #AED09E",
-"-+ c #B3D6A2",
-";+ c #708666",
-">+ c #1D231B",
-",+ c #313A2C",
-"'+ c #90AD83",
-")+ c #AFD29F",
-"!+ c #AFD1A0",
-"~+ c #92C077",
-"{+ c #527F34",
-"]+ c #4D7730",
-"^+ c #6B8C58",
-"/+ c #ADD09C",
-"(+ c #AED19D",
-"_+ c #A3C493",
-":+ c #95B387",
-"<+ c #98B78A",
-"[+ c #A8CA98",
-"}+ c #ADD09D",
-"|+ c #92C076",
-"1+ c #71AE47",
-"2+ c #70AE46",
-"3+ c #AED09F",
-"4+ c #ACCF9C",
-"5+ c #AED29E",
-"6+ c #B1D5A0",
-"7+ c #ADD09E",
-"8+ c #91C076",
-"9+ c #6BA544",
-"0+ c #69A342",
-"a+ c #8CB772",
-"b+ c #AFD19E",
-"c+ c #ACCF9B",
-"d+ c #AFD39E",
-"e+ c #839E76",
-"f+ c #4C5C45",
-"g+ c #596C51",
-"h+ c #99B889",
-"i+ c #91C075",
-"j+ c #0A0F06",
-"k+ c #080908",
-"l+ c #B8DFA6",
-"m+ c #ABCF9A",
-"n+ c #B2D7A0",
-"o+ c #5D7053",
-"p+ c #0C0F0B",
-"q+ c #86A279",
-"r+ c #ADD19C",
-"s+ c #0B1007",
-"t+ c #B8DEA5",
-"u+ c #AACE99",
-"v+ c #AFD49E",
-"w+ c #718966",
-"x+ c #242C21",
-"y+ c #374231",
-"z+ c #8FAD81",
-"A+ c #ACD09B",
-"B+ c #90BF75",
-"C+ c #5B8D3A",
-"D+ c #578737",
-"E+ c #769B60",
-"F+ c #A3C693",
-"G+ c #99BA8A",
-"H+ c #9CBD8C",
-"I+ c #A7CA96",
-"J+ c #ABCF9B",
-"K+ c #90BF74",
-"L+ c #6FAD46",
-"M+ c #92C176",
-"N+ c #A9CE98",
-"O+ c #AACF99",
-"P+ c #ABD09A",
-"Q+ c #AACF9A",
-"R+ c #649B40",
-"S+ c #61973D",
-"T+ c #81AA69",
-"U+ c #ABD19B",
-"V+ c #A8CE97",
-"W+ c #ACD29A",
-"X+ c #7D9970",
-"Y+ c #43523C",
-"Z+ c #506248",
-"`+ c #93B584",
-" @ c #A9CF98",
-".@ c #A9CF99",
-"+@ c #8FBF73",
-"@@ c #B5DDA1",
-"#@ c #A8CD96",
-"$@ c #AED59B",
-"%@ c #5B6F51",
-"&@ c #0B0D0A",
-"*@ c #83A075",
-"=@ c #AAD098",
-"-@ c #A9CE97",
-";@ c #8FBF72",
-">@ c #C0EDAB",
-",@ c #B3DDA0",
-"'@ c #A8CF96",
-")@ c #A6CD94",
-"!@ c #A8D096",
-"~@ c #A7CE95",
-"{@ c #A9D197",
-"]@ c #A7CD95",
-"^@ c #AAD298",
-"/@ c #ACD399",
-"(@ c #B7E2A3",
-"_@ c #7F9C71",
-":@ c #2B3627",
-"<@ c #43533C",
-"[@ c #91B381",
-"}@ c #A8CE96",
-"|@ c #8EBF72",
-"1@ c #63993F",
-"2@ c #60963D",
-"3@ c #709659",
-"4@ c #0F110E",
-"5@ c #8FB17F",
-"6@ c #A6CD93",
-"7@ c #8DAE7D",
-"8@ c #0B0E0A",
-"9@ c #99BD88",
-"0@ c #A6CE94",
-"a@ c #81A073",
-"b@ c #0D100C",
-"c@ c #0C0E0B",
-"d@ c #A1C78F",
-"e@ c #A8CF95",
-"f@ c #759067",
-"g@ c #0F120D",
-"h@ c #A7CF94",
-"i@ c #A9D196",
-"j@ c #67805C",
-"k@ c #11150F",
-"l@ c #A2C990",
-"m@ c #526649",
-"n@ c #809E72",
-"o@ c #8EBF71",
-"p@ c #7EAA64",
-"q@ c #8BAC7B",
-"r@ c #A5CD92",
-"s@ c #88A978",
-"t@ c #96BA85",
-"u@ c #A5CE92",
-"v@ c #7B996D",
-"w@ c #9FC68D",
-"x@ c #6C8760",
-"y@ c #A6CF93",
-"z@ c #A8D195",
-"A@ c #5D7453",
-"B@ c #54694B",
-"C@ c #1B2218",
-"D@ c #8DBF70",
-"E@ c #81AF66",
-"F@ c #1A1F18",
-"G@ c #191F16",
-"H@ c #90B27F",
-"I@ c #A5CC92",
-"J@ c #8EB07E",
-"K@ c #181E15",
-"L@ c #99BD87",
-"M@ c #83A374",
-"N@ c #1A2017",
-"O@ c #181E16",
-"P@ c #A0C78E",
-"Q@ c #A6CE93",
-"R@ c #78946A",
-"S@ c #192017",
-"T@ c #A8CF94",
-"U@ c #6C865F",
-"V@ c #1D241A",
-"W@ c #1F271C",
-"X@ c #53684A",
-"Y@ c #030302",
-"Z@ c #1D2419",
-"`@ c #8EB17E",
-" # c #A8D094",
-".# c #8DBE70",
-"+# c #8FC172",
-"@# c #B1DC9E",
-"## c #AFDA9B",
-"$# c #A3CC91",
-"%# c #A4CD91",
-"&# c #A4CC91",
-"*# c #A3CC90",
-"=# c #A7D194",
-"-# c #A8D295",
-";# c #AFDA9A",
-"># c #A6D093",
-",# c #586F4E",
-"'# c #050604",
-")# c #86A776",
-"!# c #AAD496",
-"~# c #8CBE70",
-"{# c #8DBF71",
-"]# c #A3CC8F",
-"^# c #A2CB8E",
-"/# c #596F4E",
-"(# c #192016",
-"_# c #82A272",
-":# c #A9D394",
-"<# c #8CBE6F",
-"[# c #A2CC8E",
-"}# c #A5D091",
-"|# c #536A4A",
-"1# c #86AA77",
-"2# c #A4CE90",
-"3# c #728E65",
-"4# c #90C372",
-"5# c #8DBE6F",
-"6# c #A3CD8F",
-"7# c #A1CC8D",
-"8# c #AAD795",
-"9# c #506647",
-"0# c #1B2318",
-"a# c #8DB27B",
-"b# c #263021",
-"c# c #1D2319",
-"d# c #8FC371",
-"e# c #6FAC45",
-"f# c #A3CC8E",
-"g# c #A1CB8C",
-"h# c #A0CA8B",
-"i# c #A8D593",
-"j# c #556C4A",
-"k# c #020302",
-"l# c #11140F",
-"m# c #69934F",
-"n# c #71AF47",
-"o# c #8CBE6E",
-"p# c #A0CB8B",
-"q# c #A2CE8D",
-"r# c #546B49",
-"s# c #030303",
-"t# c #405F2C",
-"u# c #8CBE6D",
-"v# c #9FCB8A",
-"w# c #97C082",
-"x# c #2B3625",
-"y# c #233616",
-"z# c #6AA444",
-"A# c #8BBE6D",
-"B# c #A0CC8B",
-"C# c #9ECB89",
-"D# c #9FCD8A",
-"E# c #4D6343",
-"F# c #0C1308",
-"G# c #5C8D3A",
-"H# c #70AE47",
-"I# c #89BD6A",
-"J# c #9CC986",
-"K# c #9BC883",
-"L# c #9FCE87",
-"M# c #8EB979",
-"N# c #536D46",
-"O# c #1D2818",
-"P# c #0B1008",
-"Q# c #020401",
-"R# c #486E2E",
-"S# c #77B151",
-"T# c #7DB559",
-"U# c #7CB558",
-"V# c #7EB759",
-"W# c #83BE5E",
-"X# c #609040",
-"Y# c #3D5E26",
-"Z# c #203114",
-"`# c #334E20",
-" $ c #6DA845",
-".$ c #61963D",
-"+$ c #6FAB46",
-"@$ c #0070C2",
-"#$ c #2671AB",
-"$$ c #2F71A6",
-"%$ c #2771AB",
-"&$ c #41719C",
-"*$ c #3C719F",
-"=$ c #0F71B8",
-"-$ c #0070C1",
-";$ c #3171A5",
-">$ c #43719B",
-",$ c #0C70B9",
-"'$ c #ED7D31",
-")$ c #ED7D30",
-"!$ c #0B70BA",
-"~$ c #3271A5",
-"{$ c #40719C",
-"]$ c #ED7C2F",
-"^$ c #ED7B2D",
-"/$ c #EC7A2B",
-"($ c #EC792A",
-"_$ c #ED7F35",
-":$ c #ED7B2C",
-"<$ c #ED7A2C",
-"[$ c #ED7B2E",
-"}$ c #0770BC",
-"|$ c #ED7F34",
-"1$ c #F09053",
-"2$ c #F3A376",
-"3$ c #F6B290",
-"4$ c #F7BBA1",
-"5$ c #F7BDA3",
-"6$ c #F7BCA3",
-"7$ c #F6B495",
-"8$ c #F4A87F",
-"9$ c #F1965D",
-"0$ c #EE823B",
-"a$ c #ED7C31",
-"b$ c #ED7C30",
-"c$ c #EF8845",
-"d$ c #F3A172",
-"e$ c #F6B99E",
-"f$ c #F8BEA7",
-"g$ c #F7BCA4",
-"h$ c #F7BBA2",
-"i$ c #F7BEA6",
-"j$ c #F7BCA2",
-"k$ c #F4A77E",
-"l$ c #F08C4D",
-"m$ c #EE8138",
-"n$ c #EF8947",
-"o$ c #F2A274",
-"p$ c #F7BAA0",
-"q$ c #F7B99F",
-"r$ c #F7BAA1",
-"s$ c #F7BBA3",
-"t$ c #F08F51",
-"u$ c #EC7D31",
-"v$ c #88776E",
-"w$ c #3B3737",
-"x$ c #3B3838",
-"y$ c #F19862",
-"z$ c #F5B394",
-"A$ c #F6BAA2",
-"B$ c #F6B9A0",
-"C$ c #F6B99F",
-"D$ c #F6BCA5",
-"E$ c #F5B293",
-"F$ c #F5AE8C",
-"G$ c #F5AD89",
-"H$ c #F5B190",
-"I$ c #F6BAA1",
-"J$ c #F7BDA6",
-"K$ c #F6BBA3",
-"L$ c #F5B69A",
-"M$ c #F2A071",
-"N$ c #ED7E33",
-"O$ c #E17C38",
-"P$ c #70767C",
-"Q$ c #0570BD",
-"R$ c #F3A67D",
-"S$ c #F6B79C",
-"T$ c #F6B89F",
-"U$ c #F6B89E",
-"V$ c #F3A981",
-"W$ c #F09157",
-"X$ c #EE833C",
-"Y$ c #EE8037",
-"Z$ c #ED8036",
-"`$ c #EF8C4C",
-" % c #F3A276",
-".% c #F6B79B",
-"+% c #F4AE8A",
-"@% c #EE7C30",
-"#% c #E77D34",
-"$% c #F3A67C",
-"%% c #F6B79D",
-"&% c #F6B69B",
-"*% c #F5AA84",
-"=% c #EF8742",
-"-% c #EE8139",
-";% c #F29E6F",
-">% c #F6B498",
-",% c #F5B191",
-"'% c #EE8036",
-")% c #F3A175",
-"!% c #F4AE8C",
-"~% c #F08F53",
-"{% c #EC7A2C",
-"]% c #F4A880",
-"^% c #F4AB87",
-"/% c #3A3737",
-"(% c #F29C6B",
-"_% c #F6B59A",
-":% c #F6B69C",
-"<% c #F4A67D",
-"[% c #EE8541",
-"}% c #ED7C2E",
-"|% c #EE7D30",
-"1% c #EE7C2E",
-"2% c #F29C6A",
-"3% c #F6B59B",
-"4% c #F3A379",
-"5% c #3A3636",
-"6% c #434040",
-"7% c #595757",
-"8% c #393636",
-"9% c #3C3939",
-"0% c #5D5B5B",
-"a% c #F09055",
-"b% c #F6B49A",
-"c% c #F6B499",
-"d% c #F3A47C",
-"e% c #E87D34",
-"f% c #F07D2E",
-"g% c #ED7D32",
-"h% c #F19964",
-"i% c #F29B6A",
-"j% c #413F3F",
-"k% c #848484",
-"l% c #6D6C6C",
-"m% c #373434",
-"n% c #858585",
-"o% c #686767",
-"p% c #F5B297",
-"q% c #F5B498",
-"r% c #F5B59A",
-"s% c #F4AA85",
-"t% c #ED7E32",
-"u% c #1A71B0",
-"v% c #D17B42",
-"w% c #F07D2F",
-"x% c #F19E6F",
-"y% c #F5B599",
-"z% c #F5B59C",
-"A% c #EE8845",
-"B% c #423F3F",
-"C% c #878686",
-"D% c #929292",
-"E% c #6A6868",
-"F% c #363232",
-"G% c #868585",
-"H% c #959696",
-"I% c #605E5E",
-"J% c #F3A57C",
-"K% c #F5B397",
-"L% c #F5B499",
-"M% c #F4AC8A",
-"N% c #EE8137",
-"O% c #1D72AF",
-"P% c #F87D2A",
-"Q% c #EC7B2C",
-"R% c #F4A57D",
-"S% c #F4AA88",
-"T% c #454242",
-"U% c #808080",
-"V% c #939393",
-"W% c #8F8F8F",
-"X% c #8D8D8D",
-"Y% c #919191",
-"Z% c #969696",
-"`% c #5D5A5A",
-" & c #F5B194",
-".& c #F08D4F",
-"+& c #F4AC8C",
-"@& c #F5B398",
-"#& c #F5B49A",
-"$& c #F19865",
-"%& c #7B7A7A",
-"&& c #949494",
-"*& c #625F5F",
-"=& c #F3A37B",
-"-& c #F5B296",
-";& c #F5B195",
-">& c #F29D6E",
-",& c #EC7C30",
-"'& c #F08F54",
-")& c #F5B196",
-"!& c #F4AD8E",
-"~& c #EE833D",
-"{& c #444242",
-"]& c #7D7C7C",
-"^& c #909090",
-"/& c #656464",
-"(& c #3C3A3A",
-"_& c #EF8D4F",
-":& c #F5AF92",
-"<& c #F5B094",
-"[& c #F4AB8A",
-"}& c #EF8744",
-"|& c #EE823A",
-"1& c #F3A47D",
-"2& c #F5B093",
-"3& c #F19764",
-"4& c #3A3838",
-"5& c #383535",
-"6& c #6C6B6B",
-"7& c #8E8E8E",
-"8& c #888787",
-"9& c #4F4D4D",
-"0& c #F29C6D",
-"a& c #F29F71",
-"b& c #F09259",
-"c& c #F5AE91",
-"d& c #F5AF93",
-"e& c #F3A47E",
-"f& c #767575",
-"g& c #8C8C8C",
-"h& c #898989",
-"i& c #F5AB8A",
-"j& c #F6AF92",
-"k& c #F6AF91",
-"l& c #F6AD8E",
-"m& c #EF8743",
-"n& c #EE8038",
-"o& c #F4A57F",
-"p& c #F6AD8D",
-"q& c #F08D50",
-"r& c #3E3C3C",
-"s& c #737272",
-"t& c #8A8A8A",
-"u& c #8B8B8B",
-"v& c #363333",
-"w& c #F08E51",
-"x& c #F7B196",
-"y& c #F6AD8F",
-"z& c #F6AE91",
-"A& c #F4A27A",
-"B& c #ED7A2B",
-"C& c #F29A69",
-"D& c #F6AD90",
-"E& c #F6AF93",
-"F& c #F29967",
-"G& c #706F6F",
-"H& c #888888",
-"I& c #878787",
-"J& c #7D7D7D",
-"K& c #717070",
-"L& c #727171",
-"M& c #848383",
-"N& c #838383",
-"O& c #585656",
-"P& c #F39E71",
-"Q& c #F08A4A",
-"R& c #F6AC8C",
-"S& c #F6AE90",
-"T& c #F5A47D",
-"U& c #EE813A",
-"V& c #403D3D",
-"W& c #868686",
-"X& c #3E3B3B",
-"Y& c #413E3E",
-"Z& c #7B7B7B",
-"`& c #828282",
-" * c #555353",
-".* c #F6AB8C",
-"+* c #F6AC8D",
-"@* c #F7AD8E",
-"#* c #ED7E34",
-"$* c #F6A985",
-"%* c #F7AD8F",
-"&* c #EE8540",
-"** c #6E6D6D",
-"=* c #646363",
-"-* c #383434",
-";* c #EF8542",
-">* c #F8AD8F",
-",* c #F7AB8B",
-"'* c #F7AC8D",
-")* c #F59E73",
-"!* c #F29867",
-"~* c #F8AE90",
-"{* c #F18E52",
-"]* c #504E4E",
-"^* c #393535",
-"/* c #F29158",
-"(* c #F7AB8A",
-"_* c #F7AD8D",
-":* c #F2945F",
-"<* c #F08B4E",
-"[* c #F39968",
-"}* c #F39A69",
-"|* c #F7AA8A",
-"1* c #F7A988",
-"2* c #F8AC8E",
-"3* c #F08A4B",
-"4* c #EE823C",
-"5* c #F49C6E",
-"6* c #F7AA8B",
-"7* c #F7AA89",
-"8* c #F6A683",
-"9* c #F39662",
-"0* c #F59F75",
-"a* c #F7A987",
-"b* c #F7A887",
-"c* c #EF8846",
-"d* c #F7A784",
-"e* c #F7A580",
-"f* c #EF843F",
-"g* c #F6A57F",
-"h* c #F7A885",
-"i* c #F7A886",
-"j* c #F7A783",
-"k* c #EF843E",
-"l* c #F6A47F",
-"m* c #F6A782",
-"n* c #EF8642",
-"o* c #F7A37D",
-"p* c #F7A47E",
-"q* c #F7A47F",
-"r* c #F7A178",
-"s* c #F08948",
-"t* c #F08846",
-"u* c #F08744",
-" ",
-" . ",
-" . . ",
-" . . . ",
-" . . . . ",
-" . . . . . ",
-" . . . . . . ",
-" . . . . . . . + @ # $ % + & * = - ; > , ' ) ! ~ { ] ^ / ( _ : < [ } | 1 1 1 1 1 1 1 1 1 1 1 ",
-" . . . 2 3 4 5 6 7 8 4 9 0 a b 4 c d e f 4 g h i j 4 k l m n o p q q q q q q q r 1 1 ",
-" . . . s 4 t u v w x y z A B C D u E F G H I J K L H M N 4 O P B Q Q Q Q Q Q R S T 1 ",
-" . . . s 4 U V W X Y Z ` W .Y Z ..+. .@.Z ..+. .#.Z $.%.&.*.=.-. . . . . . .;.>.r 1 ",
-" . . . ,.'.).!.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.+.{.].^./.X ~.~.~.~.~.~.(._.r 1 ",
-" . . . ; :.<.(.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.}.|.1.+.[.[.[.[.[.[.[. ._.r 1 ",
-" . . . } 2.3.(.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.4.5.6.7.8.~.[.[.[.[.[.[. ._.r 1 ",
-" . . . 9.4 0.a.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.c.d.4 e.f.g.b.b.b.b.b.b.h.i.r 1 ",
-" . . . j.4 k.l.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.n.o.p.q.r.s.m.m.m.m.m.m.[.t.r 1 ",
-" . . . u.v.w.x.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.b.z.A.B.C.D.y.y.y.y.y.y.b.E.r 1 ",
-" . . . F.G.H.I.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.K.L.M.N.J.J.J.J.J.J.J.m.O.r 1 ",
-" . . . 1 P.Q.I.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.K.R.S.T.U.y.J.J.J.J.J.J.V.O.r 1 ",
-" . . . W.4 X.Y.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.`. +4 .+++@+Z.Z.Z.Z.Z.Z.#+$+r 1 ",
-" . . . %+4 &+*+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+-+;+>+,+'+)+=+=+=+=+=+=+!+~+r 1 ",
-" . . . {+]+^+-+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+(+_+:+<+[+}+/+/+/+/+/+/+Z.|+r 1 ",
-" . . . 1+2+i.3+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+5+6+@+}+4+4+4+4+4+4+4+7+8+r 1 ",
-" . . . 9+0+a+b+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+d+e+f+g+h+/+c+c+c+c+c+c+}+i+r 1 ",
-" . . . j+4 k+l+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+n+o+4 p+q+r+m+m+m+m+m+m+4+i+r 1 ",
-" . . . s+4 X.t+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+v+w+x+y+z+A+u+u+u+u+u+u+c+B+r 1 ",
-" . . . C+D+E+5+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+m+F+G+H+I+u+u+u+u+u+u+u+J+K+r 1 ",
-" . . . 1 L+M+J+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+O+P+P+N+N+N+N+N+N+N+N+Q+K+r 1 ",
-" . . . R+S+T+U+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+W+X+Y+Z+`+ @V+V+V+V+V+V+.@+@r 1 ",
-" . . . j+4 k+@@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@$@%@4 &@*@=@#@#@#@#@#@#@-@;@r 1 ",
-" . . . j+4 X.>@,@'@)@!@,@,@~@)@{@,@,@]@)@^@,@,@)@)@/@(@_@:@<@[@'@)@)@)@)@)@)@}@|@r 1 ",
-" . . . 1@2@3@4@p+5@6@7@p+8@9@0@a@b@c@d@e@f@g@b@h@i@j@k@&@l@m@n@i@6@6@6@6@6@6@~@o@r 1 ",
-" . . . 1 L+p@4 4 q@r@s@4 4 t@u@v@4 4 w@h@x@4 4 y@z@A@4 4 B@4 C@5@r@r@r@r@r@r@0@D@r 1 ",
-" . . . 1 L+E@F@G@H@I@J@G@K@L@I@M@N@O@P@Q@R@C@S@6@T@U@V@W@X@Y@4 Z@`@ #I@I@I@I@6@.#r 1 ",
-" . . . 1 L++#@###u@$#u@####%#$#y@####&#*#=#####*#*#-###;#>#,#'#4 C@)#!#*#$#$#r@~#r 1 ",
-" . . . 1 L+{#r@]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#*#^#/#Y@4 (#_#:#]#*#-#<#r 1 ",
-" . . . 1 L+{#%#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#}#|#4 4 (#1#2#[#3#4#r 1 ",
-" . . . 1 L+5#6#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#8#9#4 4 0#a#b#c#d#e#1 ",
-" . . . 1 L+<#f#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#h#i#j#'#4 k#4 l#m#n#1 ",
-" . . . 1 L+o#[#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#q#r#4 4 4 s#t#} 1 ",
-" . . . 1 L+u#7#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#w#x#4 4 4 4 y#z#1 ",
-" . . . 1 L+A#B#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#D#E#4 4 4 4 4 F#G#H# ",
-" . . . 1 L+I#J#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#L#M#N#O#P#Q#4 R#1 ",
-" . . . 1 1 S#T#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#V#W#W#X#Y#Z#`# $ ",
-" . . . 1 1 L+P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.L+! } $.$+$ ",
-" . . . 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 H#| 1 ",
-" . . . ",
-" . . . ",
-" @$@$@$ ",
-" #$$$%$ . . . ",
-" &$&$&$*$ . . . . . ",
-" &$&$&$&$*$=$-$. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-" ;$>$&$&$*$,$-$. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-" '$'$'$'$'$)$)$'$'$'$'$'$ . !$~${$&$ . . . . ",
-" '$'$'$'$]$^$/$($'$_$:$/$<$[$)$'$'$'$ . . . }$ . . ",
-" '$'$'$'$|$1$2$3$4$5$6$6$7$8$9$0$'$'$'$'$ . . . . ",
-" a$'$b$_$c$d$e$f$g$h$4$4$4$4$h$6$i$j$k$l$m$b$'$a$ -$. . . ",
-" '$'$[$n$o$e$g$p$q$q$p$r$4$h$r$p$q$q$p$s$g$8$t$'$)$u$v$. -$. w$ w$x$ ",
-" '$'$<$y$z$A$B$C$C$A$D$g$E$F$G$H$I$J$K$B$C$C$I$L$M$N$)$O$P$Q$ x$x$ x$x$ ",
-" '$)$b$R$S$T$U$U$C$B$V$W$X$Y$Y$Z$Y$m$`$ %.%B$U$U$T$U$+%Z$@%#% x$x$x$ x$x$x$ ",
-" '$'$Z$$%%%%%%%%%&%*%=%<$b$'$'$'$'$'$'$)$[$-%;%>%%%%%%%U$,%0$b$'$ x$x$x$x$ x$x$x$x$ ",
-" '$'$'%)%U$S$S$%%!%~%{%]$'$'$'$'$ '$'$'$'$)$($c$]%.%S$S$%%^%0$b$'$ x$/%x$x$x$ x$x$x$x$x$ ",
-" '$'$]$(%%%&%_%:%<%[%}%'$'$ '$|%1%_$2%>%&%3%:%4%Z$'$'$ x$5%6%7%8%x$ x$x$9%0%9%/%x$ ",
-" '$[$a%3%b%c%:%d%_$b$'$ e%f%g%h%c%c%b%3%i%'$'$'$ x$8%j%k%l%m%x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$9%n%o%x$x$x$ ",
-" '$b$X$p%q%q%r%s%t%'$'$ -$u%v%w%^$x%y%q%q%z%A%)$'$ x$/%B%C%D%E%F%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%x$G%H%I%9%x$x$ ",
-" '$[$J%K%K%L%M%N%'$'$ . . -$O%P%'$Q%R%L%K%q%S%'$'$'$ x$x$T%U%V%D%W%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%Y%D%Z%`%x$x$x$ ",
-" '$[$a% &p%p% &.&'$'$ . . . . '$)$-%+&@&p%#&$&^$'$ x$/%T%%&V%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%&&*&x$/%x$ ",
-" '$'$Y$=&-&;&-&>&N$'$,& . . . . '$'$'&@&)&;&!&~&b$'$ x$/%{&]&D%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%^&W%/&(&x$x$ ",
-" '$b$_&:&<&<&[&}&b$'$ . . . . '$'$|&1&)&<&2&3&<$'$ 4&x$5&6&D%7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&W%8&9&/%x$4& ",
-" '$_$0&;&:&:&a&:$'$ . . . . '$]$b&c&:&d&e&-%)$a$ x$x$x$f&7&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&h&0%5&x$/% ",
-" '$'$X$i&j&k&l&m&]$'$ . . . . '$)$n&o&k&k&p&q&b$'$ x$x$r&s&t&t&h&t&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&t&h&t&C%0%v&x$/% ",
-" '$'$w&x&y&z&A&B&'$ . . . . '${%C&y&D&E&F&N$'$ x$/%j%G&H&I&J&K&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&s&M&h&N&O&m%x$/% ",
-" '$b$P&z&l&j&~%}%'$ . . . . '$]$Q&R&l&S&T&U&'$'$ /%/%V&G&W&/&X&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&B%Z&`& */%x$/% ",
-" '$'$)$.*+*R&@*#*'$'$ . . . . '$'$}%$*R&R&%*&*'$'$ 4&x$9%**=*-*x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$9%f&O&/%x$/% ",
-" '$b$;*>*,*'*)*b$'$ . . . . '$'$'$'$'$^$!*'*,*~*{*'$'$'$'$'$'$ x$x$x$9&5%x$ x$x$x$]*^*x$/% ",
-" '$}%/*'*(*_*:*)$'$ . . . . '$'$'$'$N$<*'*(*'*[*'%N$'$'$'$ x$x$8%x$x$ x$x$8%x$/% ",
-" '$^$}*|*1*2*3*'$'$ . . . . '$'$b$4*5*6*1*7*8*9*'$'$'$ /%x$x$x$ x$x$x$/% ",
-" '$Q%0*a*b*|*~&'$'$ . . . . '$'$g%c*d*1*1*e*f*)$'$ /%x$x$ x$x$/% ",
-" '$/$g*h*i*j*|&'$'$ . . . . '$'$'$k*l*m*n*'$'$'$ x$x$ x$x$ ",
-" '${%o*p*q*r*m$'$'$ . . . . '$'$)$f*s*'$'$'$ x$ /% ",
-" '$'$t*t*t*u*N$'$'$ . . . . '$'$]$]$'$'$ ",
-" '$'$]$]$]$b$'$'$'$ . . . . '$'$'$ ",
-" '$'$'$'$'$'$'$'$ . . . . '$ ",
-" . . . . ",
-" . . . . ",
-" . . . . ",
-" . . . . ",
-" . . . . ",
-" . . . . . . ",
-" . . . . . . ",
-" . . . . . ",
-" . . . . . . ",
-" . . . . . . . ",
-" . . . . . ",
-" . . . ",
-" ",
-" "};
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/documentation/doxygen/modules.dox b/Plugins/org.mitk.gui.qt.geometrytools/documentation/doxygen/modules.dox
deleted file mode 100644
index 80ce9d8232..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/documentation/doxygen/modules.dox
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- \defgroup org_mitk_gui_qt_geometrytools org.mitk.gui.qt.geometrytools
- \ingroup MITKPlugins
-
- \brief A plugin to modify geometry of mitkBaseData via interaction. Currently, the following
-operations can be performed:
-
-<ul>
-<li>Translation
-<li>Rotation
-<li>Scaling (not supported for images, yet, and will not happen in coordinate origin)
-</ul>
-
-*/
-
-/**
- \defgroup org_mitk_gui_qt_geometrytools_internal Internal
- \ingroup org_mitk_gui_qt_geometrytools
-
- \brief This subcategory includes the internal classes of the org.mitk.gui.qt.geometrytools 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.geometrytools/files.cmake b/Plugins/org.mitk.gui.qt.geometrytools/files.cmake
deleted file mode 100644
index 599f90d2a6..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/files.cmake
+++ /dev/null
@@ -1,52 +0,0 @@
-set(SRC_CPP_FILES
-
-)
-
-set(INTERNAL_CPP_FILES
- org_mitk_gui_qt_geometrytools_Activator.cpp
- QmitkGeometryToolsView.cpp
-)
-
-set(UI_FILES
- src/internal/QmitkGeometryToolsViewControls.ui
-)
-
-set(MOC_H_FILES
- src/internal/org_mitk_gui_qt_geometrytools_Activator.h
- src/internal/QmitkGeometryToolsView.h
-)
-
-# list of resource files which can be used by the plug-in
-# system without loading the plug-ins shared library,
-# for example the icon used in the menu and tabs for the
-# plug-in views in the workbench
-set(CACHED_RESOURCE_FILES
- resources/icon.xpm
- resources/key_ctrl.png
- resources/key_alt.png
- resources/key_dash.png
- resources/key_down.png
- resources/key_left.png
- resources/key_plus.png
- resources/key_right.png
- resources/key_shift.png
- resources/key_up.png
-
- plugin.xml
-)
-
-# list of Qt .qrc files which contain additional resources
-# specific to this plugin
-set(QRC_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/org.mitk.gui.qt.geometrytools/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.geometrytools/manifest_headers.cmake
deleted file mode 100644
index 17165dc97f..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/manifest_headers.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(Plugin-Name "Geometry Tools")
-set(Plugin-Version "0.1")
-set(Plugin-Vendor "DKFZ")
-set(Plugin-ContactAddress "")
-set(Require-Plugin org.mitk.gui.qt.common)
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/plugin.xml b/Plugins/org.mitk.gui.qt.geometrytools/plugin.xml
deleted file mode 100644
index a9f448907a..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/plugin.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin>
-
- <extension point="org.blueberry.ui.views">
- <view id="org.mitk.views.geometrytools"
- name="Geometry Tools"
- class="QmitkGeometryToolsView"
- icon="resources/icon.xpm" >
- <description>Modify the geometry of objects</description>
- <keywordReference id="org.mitk.views.geometrytools.Keyword"/>
- </view>
- </extension>
- <extension point="org.blueberry.ui.keywords">
- <keyword label="Rotate" id="org.mitk.views.geometrytools.Keyword"/>
- <keyword label="Translate" id="org.mitk.views.geometrytools.Keyword"/>
- <keyword label="Geometry" id="org.mitk.views.geometrytools.Keyword"/>
- <keyword label="Interaction" id="org.mitk.views.geometrytools.Keyword"/>
- <keyword label="Move" id="org.mitk.views.geometrytools.Keyword"/>
- <keyword label="Shift" id="org.mitk.views.geometrytools.Keyword"/>
- </extension>
-</plugin>
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/icon.xpm b/Plugins/org.mitk.gui.qt.geometrytools/resources/icon.xpm
deleted file mode 100644
index 7b3b16dec1..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/resources/icon.xpm
+++ /dev/null
@@ -1,896 +0,0 @@
-/* XPM */
-static char * geometrytools_color_xpm[] = {
-"100 97 796 2",
-" c None",
-". c #0070C0",
-"+ c #74B349",
-"@ c #466C2C",
-"# c #121C0C",
-"$ c #223516",
-"% c #60943D",
-"& c #42672A",
-"* c #111B0B",
-"= c #263B18",
-"- c #649A3F",
-"; c #73B149",
-"> c #3F6128",
-", c #10190A",
-"' c #2A401B",
-") c #679F41",
-"! c #71AF48",
-"~ c #3B5B26",
-"{ c #10180A",
-"] c #2D471D",
-"^ c #6AA443",
-"/ c #70AC47",
-"( c #375523",
-"_ c #0F180A",
-": c #314C1F",
-"< c #6EAA46",
-"[ c #74B34A",
-"} c #73B249",
-"| c #71AE48",
-"1 c #70AD47",
-"2 c #7ABD4D",
-"3 c #3F6229",
-"4 c #000000",
-"5 c #0A1305",
-"6 c #588C35",
-"7 c #71B245",
-"8 c #33521F",
-"9 c #0F1A08",
-"0 c #5D9338",
-"a c #6FB044",
-"b c #2E4B1C",
-"c c #14220B",
-"d c #61993B",
-"e c #6EAD43",
-"f c #2A4419",
-"g c #19290E",
-"h c #659F3D",
-"i c #6CAA41",
-"j c #253C16",
-"k c #1F3412",
-"l c #558634",
-"m c #41642A",
-"n c #476E2D",
-"o c #639D3D",
-"p c #6DAC42",
-"q c #6CAB42",
-"r c #6EAC44",
-"s c #0E1609",
-"t c #0A0B09",
-"u c #73876A",
-"v c #A6C39A",
-"w c #B9D9AC",
-"x c #8AA280",
-"y c #5C6C54",
-"z c #6F8367",
-"A c #AAC79E",
-"B c #B8D8AB",
-"C c #879E7D",
-"D c #5B6B54",
-"E c #ADCBA0",
-"F c #B7D6A9",
-"G c #839A7A",
-"H c #5A6A53",
-"I c #768B6E",
-"J c #B0CEA3",
-"K c #B5D5A8",
-"L c #809676",
-"M c #819878",
-"N c #63735C",
-"O c #141713",
-"P c #90A985",
-"Q c #B6D5A8",
-"R c #B7D6AB",
-"S c #97C37D",
-"T c #6DAC43",
-"U c #10120F",
-"V c #C7EBB7",
-"W c #B5D5A6",
-"X c #B4D4A4",
-"Y c #B7D8A8",
-"Z c #BBDCAB",
-"` c #B9DAAA",
-" . c #B4D4A5",
-".. c #B9DAA9",
-"+. c #B4D5A5",
-"@. c #B8D8A8",
-"#. c #B8D9A8",
-"$. c #BEE0AE",
-"%. c #6E8165",
-"&. c #0F110D",
-"*. c #252C22",
-"=. c #92AD86",
-"-. c #B6D6A7",
-";. c #B5D5A7",
-">. c #95C37B",
-",. c #3F6228",
-"'. c #365422",
-"). c #536A46",
-"!. c #BBDCAC",
-"~. c #B3D4A4",
-"{. c #A1BF94",
-"]. c #8AA37E",
-"^. c #90A984",
-"/. c #ABCA9C",
-"(. c #B4D4A6",
-"_. c #95C27A",
-":. c #72B248",
-"<. c #9AC880",
-"[. c #B2D3A3",
-"}. c #B6D8A7",
-"|. c #BCDEAC",
-"1. c #BADDAB",
-"2. c #73B248",
-"3. c #9BC980",
-"4. c #B5D7A6",
-"5. c #8EA882",
-"6. c #5E7057",
-"7. c #6A7E61",
-"8. c #A1BF93",
-"9. c #0C1208",
-"0. c #0B0D0B",
-"a. c #BFE3AE",
-"b. c #B1D3A2",
-"c. c #B8DBA8",
-"d. c #627459",
-"e. c #10130F",
-"f. c #8CA680",
-"g. c #B3D6A4",
-"h. c #B2D4A4",
-"i. c #94C279",
-"j. c #0D1408",
-"k. c #0D0F0C",
-"l. c #BEE2AD",
-"m. c #B1D2A1",
-"n. c #B6D9A6",
-"o. c #6E8465",
-"p. c #161A14",
-"q. c #2A3327",
-"r. c #91AD85",
-"s. c #B3D4A3",
-"t. c #94C179",
-"u. c #49712E",
-"v. c #416629",
-"w. c #5F7B4F",
-"x. c #B7D9A7",
-"y. c #B0D2A0",
-"z. c #A2C294",
-"A. c #90AC83",
-"B. c #94B187",
-"C. c #AACA9B",
-"D. c #B0D3A1",
-"E. c #93C278",
-"F. c #72B048",
-"G. c #71B047",
-"H. c #97C57C",
-"I. c #B1D2A2",
-"J. c #AFD19F",
-"K. c #B2D5A2",
-"L. c #B7DAA6",
-"M. c #B6D9A5",
-"N. c #B1D3A1",
-"O. c #93C178",
-"P. c #6FAC46",
-"Q. c #94C17A",
-"R. c #88A37C",
-"S. c #56664E",
-"T. c #627559",
-"U. c #9DBB8E",
-"V. c #B0D2A1",
-"W. c #0A1007",
-"X. c #090A09",
-"Y. c #BBE1AA",
-"Z. c #AED19E",
-"`. c #B5D9A4",
-" + c #5F7256",
-".+ c #0E100C",
-"++ c #89A47C",
-"@+ c #B0D4A0",
-"#+ c #AFD2A0",
-"$+ c #92C177",
-"%+ c #0C1207",
-"&+ c #0B0C0B",
-"*+ c #BBE0AA",
-"=+ c #AED09E",
-"-+ c #B3D6A2",
-";+ c #708666",
-">+ c #1D231B",
-",+ c #313A2C",
-"'+ c #90AD83",
-")+ c #AFD29F",
-"!+ c #AFD1A0",
-"~+ c #92C077",
-"{+ c #527F34",
-"]+ c #4D7730",
-"^+ c #6B8C58",
-"/+ c #ADD09C",
-"(+ c #AED19D",
-"_+ c #A3C493",
-":+ c #95B387",
-"<+ c #98B78A",
-"[+ c #A8CA98",
-"}+ c #ADD09D",
-"|+ c #92C076",
-"1+ c #71AE47",
-"2+ c #70AE46",
-"3+ c #AED09F",
-"4+ c #ACCF9C",
-"5+ c #AED29E",
-"6+ c #B1D5A0",
-"7+ c #ADD09E",
-"8+ c #91C076",
-"9+ c #6BA544",
-"0+ c #69A342",
-"a+ c #8CB772",
-"b+ c #AFD19E",
-"c+ c #ACCF9B",
-"d+ c #AFD39E",
-"e+ c #839E76",
-"f+ c #4C5C45",
-"g+ c #596C51",
-"h+ c #99B889",
-"i+ c #91C075",
-"j+ c #0A0F06",
-"k+ c #080908",
-"l+ c #B8DFA6",
-"m+ c #ABCF9A",
-"n+ c #B2D7A0",
-"o+ c #5D7053",
-"p+ c #0C0F0B",
-"q+ c #86A279",
-"r+ c #ADD19C",
-"s+ c #0B1007",
-"t+ c #B8DEA5",
-"u+ c #AACE99",
-"v+ c #AFD49E",
-"w+ c #718966",
-"x+ c #242C21",
-"y+ c #374231",
-"z+ c #8FAD81",
-"A+ c #ACD09B",
-"B+ c #90BF75",
-"C+ c #5B8D3A",
-"D+ c #578737",
-"E+ c #769B60",
-"F+ c #A3C693",
-"G+ c #99BA8A",
-"H+ c #9CBD8C",
-"I+ c #A7CA96",
-"J+ c #ABCF9B",
-"K+ c #90BF74",
-"L+ c #6FAD46",
-"M+ c #92C176",
-"N+ c #A9CE98",
-"O+ c #AACF99",
-"P+ c #ABD09A",
-"Q+ c #AACF9A",
-"R+ c #649B40",
-"S+ c #61973D",
-"T+ c #81AA69",
-"U+ c #ABD19B",
-"V+ c #A8CE97",
-"W+ c #ACD29A",
-"X+ c #7D9970",
-"Y+ c #43523C",
-"Z+ c #506248",
-"`+ c #93B584",
-" @ c #A9CF98",
-".@ c #A9CF99",
-"+@ c #8FBF73",
-"@@ c #B5DDA1",
-"#@ c #A8CD96",
-"$@ c #AED59B",
-"%@ c #5B6F51",
-"&@ c #0B0D0A",
-"*@ c #83A075",
-"=@ c #AAD098",
-"-@ c #A9CE97",
-";@ c #8FBF72",
-">@ c #C0EDAB",
-",@ c #B3DDA0",
-"'@ c #A8CF96",
-")@ c #A6CD94",
-"!@ c #A8D096",
-"~@ c #A7CE95",
-"{@ c #A9D197",
-"]@ c #A7CD95",
-"^@ c #AAD298",
-"/@ c #ACD399",
-"(@ c #B7E2A3",
-"_@ c #7F9C71",
-":@ c #2B3627",
-"<@ c #43533C",
-"[@ c #91B381",
-"}@ c #A8CE96",
-"|@ c #8EBF72",
-"1@ c #63993F",
-"2@ c #60963D",
-"3@ c #709659",
-"4@ c #0F110E",
-"5@ c #8FB17F",
-"6@ c #A6CD93",
-"7@ c #8DAE7D",
-"8@ c #0B0E0A",
-"9@ c #99BD88",
-"0@ c #A6CE94",
-"a@ c #81A073",
-"b@ c #0D100C",
-"c@ c #0C0E0B",
-"d@ c #A1C78F",
-"e@ c #A8CF95",
-"f@ c #759067",
-"g@ c #0F120D",
-"h@ c #A7CF94",
-"i@ c #A9D196",
-"j@ c #67805C",
-"k@ c #11150F",
-"l@ c #A2C990",
-"m@ c #526649",
-"n@ c #809E72",
-"o@ c #8EBF71",
-"p@ c #7EAA64",
-"q@ c #8BAC7B",
-"r@ c #A5CD92",
-"s@ c #88A978",
-"t@ c #96BA85",
-"u@ c #A5CE92",
-"v@ c #7B996D",
-"w@ c #9FC68D",
-"x@ c #6C8760",
-"y@ c #A6CF93",
-"z@ c #A8D195",
-"A@ c #5D7453",
-"B@ c #54694B",
-"C@ c #1B2218",
-"D@ c #8DBF70",
-"E@ c #81AF66",
-"F@ c #1A1F18",
-"G@ c #191F16",
-"H@ c #90B27F",
-"I@ c #A5CC92",
-"J@ c #8EB07E",
-"K@ c #181E15",
-"L@ c #99BD87",
-"M@ c #83A374",
-"N@ c #1A2017",
-"O@ c #181E16",
-"P@ c #A0C78E",
-"Q@ c #A6CE93",
-"R@ c #78946A",
-"S@ c #192017",
-"T@ c #A8CF94",
-"U@ c #6C865F",
-"V@ c #1D241A",
-"W@ c #1F271C",
-"X@ c #53684A",
-"Y@ c #030302",
-"Z@ c #1D2419",
-"`@ c #8EB17E",
-" # c #A8D094",
-".# c #8DBE70",
-"+# c #8FC172",
-"@# c #B1DC9E",
-"## c #AFDA9B",
-"$# c #A3CC91",
-"%# c #A4CD91",
-"&# c #A4CC91",
-"*# c #A3CC90",
-"=# c #A7D194",
-"-# c #A8D295",
-";# c #AFDA9A",
-"># c #A6D093",
-",# c #586F4E",
-"'# c #050604",
-")# c #86A776",
-"!# c #AAD496",
-"~# c #8CBE70",
-"{# c #8DBF71",
-"]# c #A3CC8F",
-"^# c #A2CB8E",
-"/# c #596F4E",
-"(# c #192016",
-"_# c #82A272",
-":# c #A9D394",
-"<# c #8CBE6F",
-"[# c #A2CC8E",
-"}# c #A5D091",
-"|# c #536A4A",
-"1# c #86AA77",
-"2# c #A4CE90",
-"3# c #728E65",
-"4# c #90C372",
-"5# c #8DBE6F",
-"6# c #A3CD8F",
-"7# c #A1CC8D",
-"8# c #AAD795",
-"9# c #506647",
-"0# c #1B2318",
-"a# c #8DB27B",
-"b# c #263021",
-"c# c #1D2319",
-"d# c #8FC371",
-"e# c #6FAC45",
-"f# c #A3CC8E",
-"g# c #A1CB8C",
-"h# c #A0CA8B",
-"i# c #A8D593",
-"j# c #556C4A",
-"k# c #020302",
-"l# c #11140F",
-"m# c #69934F",
-"n# c #71AF47",
-"o# c #8CBE6E",
-"p# c #A0CB8B",
-"q# c #A2CE8D",
-"r# c #546B49",
-"s# c #030303",
-"t# c #405F2C",
-"u# c #8CBE6D",
-"v# c #9FCB8A",
-"w# c #97C082",
-"x# c #2B3625",
-"y# c #233616",
-"z# c #6AA444",
-"A# c #8BBE6D",
-"B# c #A0CC8B",
-"C# c #9ECB89",
-"D# c #9FCD8A",
-"E# c #4D6343",
-"F# c #0C1308",
-"G# c #5C8D3A",
-"H# c #70AE47",
-"I# c #89BD6A",
-"J# c #9CC986",
-"K# c #9BC883",
-"L# c #9FCE87",
-"M# c #8EB979",
-"N# c #536D46",
-"O# c #1D2818",
-"P# c #0B1008",
-"Q# c #020401",
-"R# c #486E2E",
-"S# c #77B151",
-"T# c #7DB559",
-"U# c #7CB558",
-"V# c #7EB759",
-"W# c #83BE5E",
-"X# c #609040",
-"Y# c #3D5E26",
-"Z# c #203114",
-"`# c #334E20",
-" $ c #6DA845",
-".$ c #61963D",
-"+$ c #6FAB46",
-"@$ c #0070C2",
-"#$ c #2671AB",
-"$$ c #2F71A6",
-"%$ c #2771AB",
-"&$ c #41719C",
-"*$ c #3C719F",
-"=$ c #0F71B8",
-"-$ c #0070C1",
-";$ c #3171A5",
-">$ c #43719B",
-",$ c #0C70B9",
-"'$ c #ED7D31",
-")$ c #ED7D30",
-"!$ c #0B70BA",
-"~$ c #3271A5",
-"{$ c #40719C",
-"]$ c #ED7C2F",
-"^$ c #ED7B2D",
-"/$ c #EC7A2B",
-"($ c #EC792A",
-"_$ c #ED7F35",
-":$ c #ED7B2C",
-"<$ c #ED7A2C",
-"[$ c #ED7B2E",
-"}$ c #0770BC",
-"|$ c #ED7F34",
-"1$ c #F09053",
-"2$ c #F3A376",
-"3$ c #F6B290",
-"4$ c #F7BBA1",
-"5$ c #F7BDA3",
-"6$ c #F7BCA3",
-"7$ c #F6B495",
-"8$ c #F4A87F",
-"9$ c #F1965D",
-"0$ c #EE823B",
-"a$ c #ED7C31",
-"b$ c #ED7C30",
-"c$ c #EF8845",
-"d$ c #F3A172",
-"e$ c #F6B99E",
-"f$ c #F8BEA7",
-"g$ c #F7BCA4",
-"h$ c #F7BBA2",
-"i$ c #F7BEA6",
-"j$ c #F7BCA2",
-"k$ c #F4A77E",
-"l$ c #F08C4D",
-"m$ c #EE8138",
-"n$ c #EF8947",
-"o$ c #F2A274",
-"p$ c #F7BAA0",
-"q$ c #F7B99F",
-"r$ c #F7BAA1",
-"s$ c #F7BBA3",
-"t$ c #F08F51",
-"u$ c #EC7D31",
-"v$ c #88776E",
-"w$ c #3B3737",
-"x$ c #3B3838",
-"y$ c #F19862",
-"z$ c #F5B394",
-"A$ c #F6BAA2",
-"B$ c #F6B9A0",
-"C$ c #F6B99F",
-"D$ c #F6BCA5",
-"E$ c #F5B293",
-"F$ c #F5AE8C",
-"G$ c #F5AD89",
-"H$ c #F5B190",
-"I$ c #F6BAA1",
-"J$ c #F7BDA6",
-"K$ c #F6BBA3",
-"L$ c #F5B69A",
-"M$ c #F2A071",
-"N$ c #ED7E33",
-"O$ c #E17C38",
-"P$ c #70767C",
-"Q$ c #0570BD",
-"R$ c #F3A67D",
-"S$ c #F6B79C",
-"T$ c #F6B89F",
-"U$ c #F6B89E",
-"V$ c #F3A981",
-"W$ c #F09157",
-"X$ c #EE833C",
-"Y$ c #EE8037",
-"Z$ c #ED8036",
-"`$ c #EF8C4C",
-" % c #F3A276",
-".% c #F6B79B",
-"+% c #F4AE8A",
-"@% c #EE7C30",
-"#% c #E77D34",
-"$% c #F3A67C",
-"%% c #F6B79D",
-"&% c #F6B69B",
-"*% c #F5AA84",
-"=% c #EF8742",
-"-% c #EE8139",
-";% c #F29E6F",
-">% c #F6B498",
-",% c #F5B191",
-"'% c #EE8036",
-")% c #F3A175",
-"!% c #F4AE8C",
-"~% c #F08F53",
-"{% c #EC7A2C",
-"]% c #F4A880",
-"^% c #F4AB87",
-"/% c #3A3737",
-"(% c #F29C6B",
-"_% c #F6B59A",
-":% c #F6B69C",
-"<% c #F4A67D",
-"[% c #EE8541",
-"}% c #ED7C2E",
-"|% c #EE7D30",
-"1% c #EE7C2E",
-"2% c #F29C6A",
-"3% c #F6B59B",
-"4% c #F3A379",
-"5% c #3A3636",
-"6% c #434040",
-"7% c #595757",
-"8% c #393636",
-"9% c #3C3939",
-"0% c #5D5B5B",
-"a% c #F09055",
-"b% c #F6B49A",
-"c% c #F6B499",
-"d% c #F3A47C",
-"e% c #E87D34",
-"f% c #F07D2E",
-"g% c #ED7D32",
-"h% c #F19964",
-"i% c #F29B6A",
-"j% c #413F3F",
-"k% c #848484",
-"l% c #6D6C6C",
-"m% c #373434",
-"n% c #858585",
-"o% c #686767",
-"p% c #F5B297",
-"q% c #F5B498",
-"r% c #F5B59A",
-"s% c #F4AA85",
-"t% c #ED7E32",
-"u% c #1A71B0",
-"v% c #D17B42",
-"w% c #F07D2F",
-"x% c #F19E6F",
-"y% c #F5B599",
-"z% c #F5B59C",
-"A% c #EE8845",
-"B% c #423F3F",
-"C% c #878686",
-"D% c #929292",
-"E% c #6A6868",
-"F% c #363232",
-"G% c #868585",
-"H% c #959696",
-"I% c #605E5E",
-"J% c #F3A57C",
-"K% c #F5B397",
-"L% c #F5B499",
-"M% c #F4AC8A",
-"N% c #EE8137",
-"O% c #1D72AF",
-"P% c #F87D2A",
-"Q% c #EC7B2C",
-"R% c #F4A57D",
-"S% c #F4AA88",
-"T% c #454242",
-"U% c #808080",
-"V% c #939393",
-"W% c #8F8F8F",
-"X% c #8D8D8D",
-"Y% c #919191",
-"Z% c #969696",
-"`% c #5D5A5A",
-" & c #F5B194",
-".& c #F08D4F",
-"+& c #F4AC8C",
-"@& c #F5B398",
-"#& c #F5B49A",
-"$& c #F19865",
-"%& c #7B7A7A",
-"&& c #949494",
-"*& c #625F5F",
-"=& c #F3A37B",
-"-& c #F5B296",
-";& c #F5B195",
-">& c #F29D6E",
-",& c #EC7C30",
-"'& c #F08F54",
-")& c #F5B196",
-"!& c #F4AD8E",
-"~& c #EE833D",
-"{& c #444242",
-"]& c #7D7C7C",
-"^& c #909090",
-"/& c #656464",
-"(& c #3C3A3A",
-"_& c #EF8D4F",
-":& c #F5AF92",
-"<& c #F5B094",
-"[& c #F4AB8A",
-"}& c #EF8744",
-"|& c #EE823A",
-"1& c #F3A47D",
-"2& c #F5B093",
-"3& c #F19764",
-"4& c #3A3838",
-"5& c #383535",
-"6& c #6C6B6B",
-"7& c #8E8E8E",
-"8& c #888787",
-"9& c #4F4D4D",
-"0& c #F29C6D",
-"a& c #F29F71",
-"b& c #F09259",
-"c& c #F5AE91",
-"d& c #F5AF93",
-"e& c #F3A47E",
-"f& c #767575",
-"g& c #8C8C8C",
-"h& c #898989",
-"i& c #F5AB8A",
-"j& c #F6AF92",
-"k& c #F6AF91",
-"l& c #F6AD8E",
-"m& c #EF8743",
-"n& c #EE8038",
-"o& c #F4A57F",
-"p& c #F6AD8D",
-"q& c #F08D50",
-"r& c #3E3C3C",
-"s& c #737272",
-"t& c #8A8A8A",
-"u& c #8B8B8B",
-"v& c #363333",
-"w& c #F08E51",
-"x& c #F7B196",
-"y& c #F6AD8F",
-"z& c #F6AE91",
-"A& c #F4A27A",
-"B& c #ED7A2B",
-"C& c #F29A69",
-"D& c #F6AD90",
-"E& c #F6AF93",
-"F& c #F29967",
-"G& c #706F6F",
-"H& c #888888",
-"I& c #878787",
-"J& c #7D7D7D",
-"K& c #717070",
-"L& c #727171",
-"M& c #848383",
-"N& c #838383",
-"O& c #585656",
-"P& c #F39E71",
-"Q& c #F08A4A",
-"R& c #F6AC8C",
-"S& c #F6AE90",
-"T& c #F5A47D",
-"U& c #EE813A",
-"V& c #403D3D",
-"W& c #868686",
-"X& c #3E3B3B",
-"Y& c #413E3E",
-"Z& c #7B7B7B",
-"`& c #828282",
-" * c #555353",
-".* c #F6AB8C",
-"+* c #F6AC8D",
-"@* c #F7AD8E",
-"#* c #ED7E34",
-"$* c #F6A985",
-"%* c #F7AD8F",
-"&* c #EE8540",
-"** c #6E6D6D",
-"=* c #646363",
-"-* c #383434",
-";* c #EF8542",
-">* c #F8AD8F",
-",* c #F7AB8B",
-"'* c #F7AC8D",
-")* c #F59E73",
-"!* c #F29867",
-"~* c #F8AE90",
-"{* c #F18E52",
-"]* c #504E4E",
-"^* c #393535",
-"/* c #F29158",
-"(* c #F7AB8A",
-"_* c #F7AD8D",
-":* c #F2945F",
-"<* c #F08B4E",
-"[* c #F39968",
-"}* c #F39A69",
-"|* c #F7AA8A",
-"1* c #F7A988",
-"2* c #F8AC8E",
-"3* c #F08A4B",
-"4* c #EE823C",
-"5* c #F49C6E",
-"6* c #F7AA8B",
-"7* c #F7AA89",
-"8* c #F6A683",
-"9* c #F39662",
-"0* c #F59F75",
-"a* c #F7A987",
-"b* c #F7A887",
-"c* c #EF8846",
-"d* c #F7A784",
-"e* c #F7A580",
-"f* c #EF843F",
-"g* c #F6A57F",
-"h* c #F7A885",
-"i* c #F7A886",
-"j* c #F7A783",
-"k* c #EF843E",
-"l* c #F6A47F",
-"m* c #F6A782",
-"n* c #EF8642",
-"o* c #F7A37D",
-"p* c #F7A47E",
-"q* c #F7A47F",
-"r* c #F7A178",
-"s* c #F08948",
-"t* c #F08846",
-"u* c #F08744",
-" ",
-" . ",
-" . . ",
-" . . . ",
-" . . . . ",
-" . . . . . ",
-" . . . . . . ",
-" . . . . . . . + @ # $ % + & * = - ; > , ' ) ! ~ { ] ^ / ( _ : < [ } | 1 1 1 1 1 1 1 1 1 1 1 ",
-" . . . 2 3 4 5 6 7 8 4 9 0 a b 4 c d e f 4 g h i j 4 k l m n o p q q q q q q q r 1 1 ",
-" . . . s 4 t u v w x y z A B C D u E F G H I J K L H M N 4 O P B Q Q Q Q Q Q R S T 1 ",
-" . . . s 4 U V W X Y Z ` W .Y Z ..+. .@.Z ..+. .#.Z $.%.&.*.=.-. . . . . . .;.>.r 1 ",
-" . . . ,.'.).!.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.+.{.].^./.X ~.~.~.~.~.~.(._.r 1 ",
-" . . . ; :.<.(.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.}.|.1.+.[.[.[.[.[.[.[. ._.r 1 ",
-" . . . } 2.3.(.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.[.4.5.6.7.8.~.[.[.[.[.[.[. ._.r 1 ",
-" . . . 9.4 0.a.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.b.c.d.4 e.f.g.b.b.b.b.b.b.h.i.r 1 ",
-" . . . j.4 k.l.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.m.n.o.p.q.r.s.m.m.m.m.m.m.[.t.r 1 ",
-" . . . u.v.w.x.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.y.b.z.A.B.C.D.y.y.y.y.y.y.b.E.r 1 ",
-" . . . F.G.H.I.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.K.L.M.N.J.J.J.J.J.J.J.m.O.r 1 ",
-" . . . 1 P.Q.I.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.J.K.R.S.T.U.y.J.J.J.J.J.J.V.O.r 1 ",
-" . . . W.4 X.Y.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.Z.`. +4 .+++@+Z.Z.Z.Z.Z.Z.#+$+r 1 ",
-" . . . %+4 &+*+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+-+;+>+,+'+)+=+=+=+=+=+=+!+~+r 1 ",
-" . . . {+]+^+-+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+/+(+_+:+<+[+}+/+/+/+/+/+/+Z.|+r 1 ",
-" . . . 1+2+i.3+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+4+5+6+@+}+4+4+4+4+4+4+4+7+8+r 1 ",
-" . . . 9+0+a+b+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+c+d+e+f+g+h+/+c+c+c+c+c+c+}+i+r 1 ",
-" . . . j+4 k+l+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+m+n+o+4 p+q+r+m+m+m+m+m+m+4+i+r 1 ",
-" . . . s+4 X.t+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+v+w+x+y+z+A+u+u+u+u+u+u+c+B+r 1 ",
-" . . . C+D+E+5+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+u+m+F+G+H+I+u+u+u+u+u+u+u+J+K+r 1 ",
-" . . . 1 L+M+J+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+N+O+P+P+N+N+N+N+N+N+N+N+Q+K+r 1 ",
-" . . . R+S+T+U+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+V+W+X+Y+Z+`+ @V+V+V+V+V+V+.@+@r 1 ",
-" . . . j+4 k+@@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@$@%@4 &@*@=@#@#@#@#@#@#@-@;@r 1 ",
-" . . . j+4 X.>@,@'@)@!@,@,@~@)@{@,@,@]@)@^@,@,@)@)@/@(@_@:@<@[@'@)@)@)@)@)@)@}@|@r 1 ",
-" . . . 1@2@3@4@p+5@6@7@p+8@9@0@a@b@c@d@e@f@g@b@h@i@j@k@&@l@m@n@i@6@6@6@6@6@6@~@o@r 1 ",
-" . . . 1 L+p@4 4 q@r@s@4 4 t@u@v@4 4 w@h@x@4 4 y@z@A@4 4 B@4 C@5@r@r@r@r@r@r@0@D@r 1 ",
-" . . . 1 L+E@F@G@H@I@J@G@K@L@I@M@N@O@P@Q@R@C@S@6@T@U@V@W@X@Y@4 Z@`@ #I@I@I@I@6@.#r 1 ",
-" . . . 1 L++#@###u@$#u@####%#$#y@####&#*#=#####*#*#-###;#>#,#'#4 C@)#!#*#$#$#r@~#r 1 ",
-" . . . 1 L+{#r@]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#]#*#^#/#Y@4 (#_#:#]#*#-#<#r 1 ",
-" . . . 1 L+{#%#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#[#}#|#4 4 (#1#2#[#3#4#r 1 ",
-" . . . 1 L+5#6#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#7#8#9#4 4 0#a#b#c#d#e#1 ",
-" . . . 1 L+<#f#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#g#h#i#j#'#4 k#4 l#m#n#1 ",
-" . . . 1 L+o#[#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#p#q#r#4 4 4 s#t#} 1 ",
-" . . . 1 L+u#7#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#v#w#x#4 4 4 4 y#z#1 ",
-" . . . 1 L+A#B#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#C#D#E#4 4 4 4 4 F#G#H# ",
-" . . . 1 L+I#J#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#K#L#M#N#O#P#Q#4 R#1 ",
-" . . . 1 1 S#T#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#U#V#W#W#X#Y#Z#`# $ ",
-" . . . 1 1 L+P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.P.L+! } $.$+$ ",
-" . . . 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 H#| 1 ",
-" . . . ",
-" . . . ",
-" @$@$@$ ",
-" #$$$%$ . . . ",
-" &$&$&$*$ . . . . . ",
-" &$&$&$&$*$=$-$. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-" ;$>$&$&$*$,$-$. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ",
-" '$'$'$'$'$)$)$'$'$'$'$'$ . !$~${$&$ . . . . ",
-" '$'$'$'$]$^$/$($'$_$:$/$<$[$)$'$'$'$ . . . }$ . . ",
-" '$'$'$'$|$1$2$3$4$5$6$6$7$8$9$0$'$'$'$'$ . . . . ",
-" a$'$b$_$c$d$e$f$g$h$4$4$4$4$h$6$i$j$k$l$m$b$'$a$ -$. . . ",
-" '$'$[$n$o$e$g$p$q$q$p$r$4$h$r$p$q$q$p$s$g$8$t$'$)$u$v$. -$. w$ w$x$ ",
-" '$'$<$y$z$A$B$C$C$A$D$g$E$F$G$H$I$J$K$B$C$C$I$L$M$N$)$O$P$Q$ x$x$ x$x$ ",
-" '$)$b$R$S$T$U$U$C$B$V$W$X$Y$Y$Z$Y$m$`$ %.%B$U$U$T$U$+%Z$@%#% x$x$x$ x$x$x$ ",
-" '$'$Z$$%%%%%%%%%&%*%=%<$b$'$'$'$'$'$'$)$[$-%;%>%%%%%%%U$,%0$b$'$ x$x$x$x$ x$x$x$x$ ",
-" '$'$'%)%U$S$S$%%!%~%{%]$'$'$'$'$ '$'$'$'$)$($c$]%.%S$S$%%^%0$b$'$ x$/%x$x$x$ x$x$x$x$x$ ",
-" '$'$]$(%%%&%_%:%<%[%}%'$'$ '$|%1%_$2%>%&%3%:%4%Z$'$'$ x$5%6%7%8%x$ x$x$9%0%9%/%x$ ",
-" '$[$a%3%b%c%:%d%_$b$'$ e%f%g%h%c%c%b%3%i%'$'$'$ x$8%j%k%l%m%x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$9%n%o%x$x$x$ ",
-" '$b$X$p%q%q%r%s%t%'$'$ -$u%v%w%^$x%y%q%q%z%A%)$'$ x$/%B%C%D%E%F%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%/%x$G%H%I%9%x$x$ ",
-" '$[$J%K%K%L%M%N%'$'$ . . -$O%P%'$Q%R%L%K%q%S%'$'$'$ x$x$T%U%V%D%W%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%X%Y%D%Z%`%x$x$x$ ",
-" '$[$a% &p%p% &.&'$'$ . . . . '$)$-%+&@&p%#&$&^$'$ x$/%T%%&V%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%Y%&&*&x$/%x$ ",
-" '$'$Y$=&-&;&-&>&N$'$,& . . . . '$'$'&@&)&;&!&~&b$'$ x$/%{&]&D%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%W%^&W%/&(&x$x$ ",
-" '$b$_&:&<&<&[&}&b$'$ . . . . '$'$|&1&)&<&2&3&<$'$ 4&x$5&6&D%7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&7&W%8&9&/%x$4& ",
-" '$_$0&;&:&:&a&:$'$ . . . . '$]$b&c&:&d&e&-%)$a$ x$x$x$f&7&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&g&h&0%5&x$/% ",
-" '$'$X$i&j&k&l&m&]$'$ . . . . '$)$n&o&k&k&p&q&b$'$ x$x$r&s&t&t&h&t&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&u&t&h&t&C%0%v&x$/% ",
-" '$'$w&x&y&z&A&B&'$ . . . . '${%C&y&D&E&F&N$'$ x$/%j%G&H&I&J&K&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&L&s&M&h&N&O&m%x$/% ",
-" '$b$P&z&l&j&~%}%'$ . . . . '$]$Q&R&l&S&T&U&'$'$ /%/%V&G&W&/&X&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&Y&B%Z&`& */%x$/% ",
-" '$'$)$.*+*R&@*#*'$'$ . . . . '$'$}%$*R&R&%*&*'$'$ 4&x$9%**=*-*x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$x$9%f&O&/%x$/% ",
-" '$b$;*>*,*'*)*b$'$ . . . . '$'$'$'$'$^$!*'*,*~*{*'$'$'$'$'$'$ x$x$x$9&5%x$ x$x$x$]*^*x$/% ",
-" '$}%/*'*(*_*:*)$'$ . . . . '$'$'$'$N$<*'*(*'*[*'%N$'$'$'$ x$x$8%x$x$ x$x$8%x$/% ",
-" '$^$}*|*1*2*3*'$'$ . . . . '$'$b$4*5*6*1*7*8*9*'$'$'$ /%x$x$x$ x$x$x$/% ",
-" '$Q%0*a*b*|*~&'$'$ . . . . '$'$g%c*d*1*1*e*f*)$'$ /%x$x$ x$x$/% ",
-" '$/$g*h*i*j*|&'$'$ . . . . '$'$'$k*l*m*n*'$'$'$ x$x$ x$x$ ",
-" '${%o*p*q*r*m$'$'$ . . . . '$'$)$f*s*'$'$'$ x$ /% ",
-" '$'$t*t*t*u*N$'$'$ . . . . '$'$]$]$'$'$ ",
-" '$'$]$]$]$b$'$'$'$ . . . . '$'$'$ ",
-" '$'$'$'$'$'$'$'$ . . . . '$ ",
-" . . . . ",
-" . . . . ",
-" . . . . ",
-" . . . . ",
-" . . . . ",
-" . . . . . . ",
-" . . . . . . ",
-" . . . . . ",
-" . . . . . . ",
-" . . . . . . . ",
-" . . . . . ",
-" . . . ",
-" ",
-" "};
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_alt.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_alt.png
deleted file mode 100644
index e18d3767bf..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_alt.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_ctrl.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_ctrl.png
deleted file mode 100644
index 4b8486046e..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_ctrl.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_dash.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_dash.png
deleted file mode 100644
index 245d42ec5f..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_dash.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_down.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_down.png
deleted file mode 100644
index 70a8550573..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_down.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_left.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_left.png
deleted file mode 100644
index 5fd44d92ad..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_left.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_plus.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_plus.png
deleted file mode 100644
index a6d6761a87..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_plus.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_right.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_right.png
deleted file mode 100644
index 0401161ea1..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_right.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_shift.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_shift.png
deleted file mode 100644
index 0ad24dc5ea..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_shift.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_up.png b/Plugins/org.mitk.gui.qt.geometrytools/resources/key_up.png
deleted file mode 100644
index 64fa3d8412..0000000000
Binary files a/Plugins/org.mitk.gui.qt.geometrytools/resources/key_up.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsView.cpp b/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsView.cpp
deleted file mode 100644
index 79f79e07be..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsView.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.
-
-============================================================================*/
-
-
-//Blueberry
-#include <berryISelectionService.h>
-#include <berryIWorkbenchWindow.h>
-
-//Qmitk
-#include "QmitkGeometryToolsView.h"
-
-//mitk
-#include <mitkImage.h>
-#include <mitkAffineBaseDataInteractor3D.h>
-
-//micro services
-#include <usModuleRegistry.h>
-#include <usGetModuleContext.h>
-
-const std::string QmitkGeometryToolsView::VIEW_ID = "org.mitk.views.geometrytools";
-
-void QmitkGeometryToolsView::SetFocus()
-{
- m_Controls.m_AddInteractor->setFocus();
-}
-
-void QmitkGeometryToolsView::CreateQtPartControl( QWidget *parent )
-{
- m_Controls.setupUi( parent );
- connect( m_Controls.m_AddInteractor, SIGNAL(clicked()), this, SLOT(AddInteractor()) );
- connect( m_Controls.m_RemoveInteractor, SIGNAL(clicked()), this, SLOT(RemoveInteractor()) );
- connect( m_Controls.m_TranslationStep, SIGNAL(valueChanged(double)), this, SLOT(OnTranslationSpinBoxChanged(double)) );
- connect( m_Controls.m_RotationStep, SIGNAL(valueChanged(double)), this, SLOT(OnRotationSpinBoxChanged(double)) );
- connect( m_Controls.m_ScaleFactor, SIGNAL(valueChanged(double)), this, SLOT(OnScaleSpinBoxChanged(double)) );
- connect( m_Controls.m_AnchorPointX, SIGNAL(valueChanged(double)), this, SLOT(OnAnchorPointChanged(double)) );
- connect( m_Controls.m_AnchorPointY, SIGNAL(valueChanged(double)), this, SLOT(OnAnchorPointChanged(double)) );
- connect( m_Controls.m_AnchorPointZ, SIGNAL(valueChanged(double)), this, SLOT(OnAnchorPointChanged(double)) );
- connect( m_Controls.m_UsageInfoCheckBox, SIGNAL(clicked(bool)), this, SLOT(OnUsageInfoBoxChanged(bool)) );
-
- connect( m_Controls.m_CustomAnchorPointRadioButton, SIGNAL(toggled(bool)), this, SLOT(OnCustomPointRadioButtonToggled(bool)) );
-
- connect( m_Controls.m_OriginPointRadioButton, SIGNAL(clicked(bool)), this, SLOT(OnOriginPointRadioButton(bool)) );
- connect( m_Controls.m_CenterPointRadioButton, SIGNAL(clicked(bool)), this, SLOT(OnCenterPointRadioButton(bool)) );
-
-
-
- m_Controls.m_UsageInfo->hide();
- m_Controls.m_CustomAnchorPoint->hide();
-
-}
-
-void QmitkGeometryToolsView::OnUsageInfoBoxChanged(bool flag)
-{
- m_Controls.m_UsageInfo->setVisible(flag);
-}
-
-void QmitkGeometryToolsView::OnSelectionChanged( berry::IWorkbenchPart::Pointer /*source*/,
- const QList<mitk::DataNode::Pointer>& nodes )
-{
- for (mitk::DataNode::Pointer node: nodes)
- {
- if( node.IsNotNull() )
- {
- m_Controls.m_AddInteractor->setEnabled( true );
- return;
- }
- }
- m_Controls.m_AddInteractor->setEnabled( false );
-}
-
-void QmitkGeometryToolsView::OnCustomPointRadioButtonToggled(bool status)
-{
- m_Controls.m_CustomAnchorPoint->setVisible(status);
- //change the anchor point to be the custom point
- OnAnchorPointChanged(0.0);
-}
-
-void QmitkGeometryToolsView::OnCenterPointRadioButton(bool)
-{
- QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
- foreach( mitk::DataNode::Pointer node, nodes )
- {
- if( node.IsNotNull() && (node->GetDataInteractor().IsNotNull()) )
- {
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point X", node->GetData()->GetGeometry()->GetCenter()[0]);
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point Y", node->GetData()->GetGeometry()->GetCenter()[1]);
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point Z", node->GetData()->GetGeometry()->GetCenter()[2]);
- }
- }
-}
-
-void QmitkGeometryToolsView::OnOriginPointRadioButton(bool)
-{
- QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
- foreach( mitk::DataNode::Pointer node, nodes )
- {
- if( node.IsNotNull() && (node->GetDataInteractor().IsNotNull()) )
- {
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point X", node->GetData()->GetGeometry()->GetOrigin()[0]);
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point Y", node->GetData()->GetGeometry()->GetOrigin()[1]);
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point Z", node->GetData()->GetGeometry()->GetOrigin()[2]);
- }
- }
-}
-
-
-void QmitkGeometryToolsView::AddInteractor()
-{
- QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
- foreach( mitk::DataNode::Pointer node, nodes )
- {
- if( node.IsNotNull() )
- {
-
- mitk::AffineBaseDataInteractor3D::Pointer affineDataInteractor = mitk::AffineBaseDataInteractor3D::New();
- if (m_Controls.m_KeyboardMode->isChecked())
- {
- affineDataInteractor->LoadStateMachine("AffineInteraction3D.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- affineDataInteractor->SetEventConfig("AffineKeyConfig.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- }
- else if(m_Controls.m_MouseMode->isChecked())
- {
- affineDataInteractor->LoadStateMachine("AffineInteraction3D.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- affineDataInteractor->SetEventConfig("AffineMouseConfig.xml", us::ModuleRegistry::GetModule("MitkDataTypesExt"));
- }
-
- affineDataInteractor->SetDataNode(node);
-
- node->SetBoolProperty("pickable", true);
- node->SetFloatProperty("AffineBaseDataInteractor3D.Translation Step Size", m_Controls.m_TranslationStep->value());
- node->SetFloatProperty("AffineBaseDataInteractor3D.Rotation Step Size", m_Controls.m_RotationStep->value());
- node->SetFloatProperty("AffineBaseDataInteractor3D.Scale Step Size", m_Controls.m_ScaleFactor->value());
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point X", m_Controls.m_AnchorPointX->value());
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point Y", m_Controls.m_AnchorPointY->value());
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point Z", m_Controls.m_AnchorPointZ->value());
- }
- }
-}
-
-void QmitkGeometryToolsView::RemoveInteractor()
-{
- QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
- foreach( mitk::DataNode::Pointer node, nodes )
- {
- if( (node.IsNotNull()) && (node->GetDataInteractor().IsNotNull()) )
- {
- node->SetDataInteractor(nullptr);
- }
- }
-}
-
-void QmitkGeometryToolsView::OnTranslationSpinBoxChanged(double step)
-{
- QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
- foreach( mitk::DataNode::Pointer node, nodes )
- {
- if( node.IsNotNull() && (node->GetDataInteractor().IsNotNull()) )
- {
- node->SetFloatProperty("AffineBaseDataInteractor3D.Translation Step Size", step);
- }
- }
-}
-
-void QmitkGeometryToolsView::OnRotationSpinBoxChanged(double step)
-{
- QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
- foreach( mitk::DataNode::Pointer node, nodes )
- {
- if( node.IsNotNull() && (node->GetDataInteractor().IsNotNull()) )
- {
- node->SetFloatProperty("AffineBaseDataInteractor3D.Rotation Step Size", step);
- }
- }
-}
-
-void QmitkGeometryToolsView::OnScaleSpinBoxChanged(double factor)
-{
- QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
- foreach( mitk::DataNode::Pointer node, nodes )
- {
- if( node.IsNotNull() && (node->GetDataInteractor().IsNotNull()) )
- {
- node->SetFloatProperty("AffineBaseDataInteractor3D.Scale Step Size", factor);
- }
- }
-}
-
-void QmitkGeometryToolsView::OnAnchorPointChanged(double /*value*/)
-{
- QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
- foreach( mitk::DataNode::Pointer node, nodes )
- {
- if( node.IsNotNull() && (node->GetDataInteractor().IsNotNull()) )
- {
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point X", m_Controls.m_AnchorPointX->value());
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point Y", m_Controls.m_AnchorPointY->value());
- node->SetFloatProperty("AffineBaseDataInteractor3D.Anchor Point Z", m_Controls.m_AnchorPointZ->value());
- }
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsView.h b/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsView.h
deleted file mode 100644
index 8da09f1922..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsView.h
+++ /dev/null
@@ -1,103 +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 QmitkGeometryToolsView_h
-#define QmitkGeometryToolsView_h
-
-#include <berryISelectionListener.h>
-
-#include <QmitkAbstractView.h>
-#include <mitkAffineBaseDataInteractor3D.h>
-
-#include "ui_QmitkGeometryToolsViewControls.h"
-
-/**
- \brief QmitkGeometryToolsView to modify geometry of mitkBaseData via interaction.
-
- \warning This is an experimental view to play with the geometry of all mitkBaseDatas.
- The current implementation allows to translate, rotate and scale objects with the
- keyboard.
-
- \warning Scaling is not supported for images, yet.
-
- \sa QmitkAbstractView
- \ingroup ${plugin_target}_internal
-*/
-class QmitkGeometryToolsView : public QmitkAbstractView
-{
- // this is needed for all Qt objects that should have a Qt meta-object
- // (everything that derives from QObject and wants to have signal/slots)
- Q_OBJECT
-
- public:
-
- static const std::string VIEW_ID;
-
-public slots:
-protected slots:
-
- /**
- * @brief Add/remove the affine interactor.
- */
- void AddInteractor();
- void RemoveInteractor();
-
- /**
- * @brief Slots to adapt the step size for interaction.
- */
- void OnRotationSpinBoxChanged(double step);
- void OnScaleSpinBoxChanged(double factor);
- void OnTranslationSpinBoxChanged(double step);
-
- /**
- * @brief OnUsageInfoBoxChanged show help.
- * @param flag yes/no.
- */
- void OnUsageInfoBoxChanged(bool flag);
-
- /**
- * @brief OnCustomPointRadioButtonToggled hide/show custom anchor point
- *
- */
- void OnCustomPointRadioButtonToggled(bool status);
-
- /**
- * @brief OnAnchorPointChanged sets the anchor point for rotation or translation.
- */
- void OnAnchorPointChanged(double);
-
- /**
- * @brief OnOriginPointRadioButton sets the anchor point to the origin of the
- * mitk::DataNode mitk::BaseGeometry.
- */
- void OnOriginPointRadioButton(bool);
-
- /**
- * @brief OnCenterPointRadioButton sets the anchor point to the center of the
- * mitk::DataNode mitk::BaseGeometry.
- */
- void OnCenterPointRadioButton(bool);
-protected:
-
- void CreateQtPartControl(QWidget *parent) override;
-
- void SetFocus() override;
-
- /// \brief called by QmitkAbstractView when DataManager's selection has changed
- void OnSelectionChanged( berry::IWorkbenchPart::Pointer source,
- const QList<mitk::DataNode::Pointer>& nodes ) override;
-
- Ui::QmitkGeometryToolsViewControls m_Controls;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsViewControls.ui b/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsViewControls.ui
deleted file mode 100644
index 4c93313294..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/QmitkGeometryToolsViewControls.ui
+++ /dev/null
@@ -1,588 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkGeometryToolsViewControls</class>
- <widget class="QWidget" name="QmitkGeometryToolsViewControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>369</width>
- <height>919</height>
- </rect>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="windowTitle">
- <string>QmitkTemplate</string>
- </property>
- <layout class="QGridLayout" name="gridLayout_2">
- <item row="6" column="0">
- <widget class="QLabel" name="label_2">
- <property name="text">
- <string>Rotation step size (°)</string>
- </property>
- </widget>
- </item>
- <item row="5" column="0">
- <widget class="QDoubleSpinBox" name="m_TranslationStep">
- <property name="decimals">
- <number>2</number>
- </property>
- <property name="maximum">
- <double>1000.000000000000000</double>
- </property>
- <property name="value">
- <double>1.000000000000000</double>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QRadioButton" name="m_KeyboardMode">
- <property name="text">
- <string>Keyboard Mode (default)</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="8" column="0">
- <widget class="QLabel" name="label_3">
- <property name="text">
- <string>Scale factor (%)</string>
- </property>
- </widget>
- </item>
- <item row="12" column="0">
- <widget class="QCheckBox" name="m_UsageInfoCheckBox">
- <property name="text">
- <string>Show usage information</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QRadioButton" name="m_MouseMode">
- <property name="text">
- <string>Mouse Mode (not implemented, yet)</string>
- </property>
- </widget>
- </item>
- <item row="7" column="0">
- <widget class="QDoubleSpinBox" name="m_RotationStep">
- <property name="maximum">
- <double>360.000000000000000</double>
- </property>
- <property name="value">
- <double>1.000000000000000</double>
- </property>
- </widget>
- </item>
- <item row="4" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Translation step size (mm)</string>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QPushButton" name="m_RemoveInteractor">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Remove Interactor</string>
- </property>
- </widget>
- </item>
- <item row="9" column="0">
- <widget class="QDoubleSpinBox" name="m_ScaleFactor">
- <property name="maximum">
- <double>200.000000000000000</double>
- </property>
- <property name="singleStep">
- <double>0.100000000000000</double>
- </property>
- <property name="value">
- <double>0.100000000000000</double>
- </property>
- </widget>
- </item>
- <item row="10" column="0">
- <widget class="QGroupBox" name="groupBox">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="title">
- <string>Anchor point (for scaling and rotation)</string>
- </property>
- <property name="checkable">
- <bool>false</bool>
- </property>
- <layout class="QGridLayout" name="gridLayout_4">
- <item row="0" column="0">
- <layout class="QHBoxLayout" name="horizontalLayout_4">
- <item>
- <widget class="QRadioButton" name="m_OriginPointRadioButton">
- <property name="text">
- <string>Origin</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="m_CenterPointRadioButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Center</string>
- </property>
- <property name="checked">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="m_CustomAnchorPointRadioButton">
- <property name="text">
- <string>Custom</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="1" column="0">
- <widget class="QWidget" name="m_CustomAnchorPoint" native="true">
- <layout class="QGridLayout" name="gridLayout_6">
- <item row="0" column="0">
- <layout class="QGridLayout" name="gridLayout_3">
- <item row="0" column="0">
- <widget class="QLabel" name="label_33">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>X:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QDoubleSpinBox" name="m_AnchorPointX">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimum">
- <double>-9999.989999999999782</double>
- </property>
- <property name="maximum">
- <double>9999.989999999999782</double>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_34">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Y:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QDoubleSpinBox" name="m_AnchorPointY">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimum">
- <double>-9999.989999999999782</double>
- </property>
- <property name="maximum">
- <double>9999.989999999999782</double>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_35">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Z:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QDoubleSpinBox" name="m_AnchorPointZ">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimum">
- <double>-9999.989999999999782</double>
- </property>
- <property name="maximum">
- <double>9999.989999999999782</double>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item row="0" column="0">
- <widget class="QPushButton" name="m_AddInteractor">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="toolTip">
- <string>Do image processing</string>
- </property>
- <property name="text">
- <string>Add Interactor</string>
- </property>
- </widget>
- </item>
- <item row="14" column="0" rowspan="3" colspan="2">
- <widget class="QWidget" name="m_UsageInfo" native="true">
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label_32">
- <property name="text">
- <string>Select a data node in the data storage and add an interactor. The color property will be set blue if the interactor is added. Next, pick the object you want move (in case there are multiple interactors) with the mouse in a render window. If it turns green, the interactor is active. Keyboard mode provides the following functions:</string>
- </property>
- <property name="wordWrap">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <layout class="QGridLayout" name="m_UsageInfoLayout">
- <item row="4" column="6">
- <widget class="QLabel" name="label_24">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_up.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="2" column="2">
- <widget class="QLabel" name="label_18">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_shift.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="3" column="3">
- <widget class="QLabel" name="label_7">
- <property name="text">
- <string>+</string>
- </property>
- </widget>
- </item>
- <item row="3" column="6">
- <widget class="QLabel" name="label_8">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_up.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="2" column="3">
- <widget class="QLabel" name="label_11">
- <property name="text">
- <string>+</string>
- </property>
- </widget>
- </item>
- <item row="1" column="4">
- <widget class="QLabel" name="label_12">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_right.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="1" column="2">
- <widget class="QLabel" name="label_16">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_left.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="1" column="3">
- <widget class="QLabel" name="label_14">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_up.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="4" column="5">
- <widget class="QLabel" name="label_28">
- <property name="text">
- <string>+</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_19">
- <property name="text">
- <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Translate &lt;br/&gt;Coronal&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
- </property>
- </widget>
- </item>
- <item row="1" column="5">
- <widget class="QLabel" name="label_13">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_down.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="4" column="2">
- <widget class="QLabel" name="label_25">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_ctrl.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="4" column="0">
- <widget class="QLabel" name="label_27">
- <property name="text">
- <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Rotate &lt;br/&gt;Coronal&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
- </property>
- </widget>
- </item>
- <item row="3" column="2">
- <widget class="QLabel" name="label_6">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_ctrl.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="3" column="7">
- <widget class="QLabel" name="label_9">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_down.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QLabel" name="label_10">
- <property name="text">
- <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Rotate &lt;br/&gt;Sagittal/Axial&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
- </property>
- </widget>
- </item>
- <item row="4" column="3">
- <widget class="QLabel" name="label_20">
- <property name="text">
- <string>+</string>
- </property>
- </widget>
- </item>
- <item row="3" column="5">
- <widget class="QLabel" name="label_5">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_down.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="2" column="5">
- <widget class="QLabel" name="label_21">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_down.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="4" column="7">
- <widget class="QLabel" name="label_22">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_down.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="4" column="4">
- <widget class="QLabel" name="label_26">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_shift.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="2" column="4">
- <widget class="QLabel" name="label_15">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_up.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_17">
- <property name="text">
- <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Translate &lt;br/&gt;Sagittal/Axial&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
- </property>
- </widget>
- </item>
- <item row="3" column="4">
- <widget class="QLabel" name="label_4">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_left.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="5" column="0">
- <widget class="QLabel" name="label_23">
- <property name="text">
- <string>Scale*</string>
- </property>
- </widget>
- </item>
- <item row="5" column="2">
- <widget class="QLabel" name="label_29">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_plus.png</pixmap>
- </property>
- </widget>
- </item>
- <item row="5" column="3">
- <widget class="QLabel" name="label_30">
- <property name="text">
- <string/>
- </property>
- <property name="pixmap">
- <pixmap resource="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc">:/org.mitk.gui.qt.geometrytools/resources/key_dash.png</pixmap>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_31">
- <property name="text">
- <string>*currently does not work with images</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item row="17" column="0">
- <spacer name="verticalSpacer">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>40</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- <layoutdefault spacing="6" margin="11"/>
- <tabstops>
- <tabstop>m_AddInteractor</tabstop>
- <tabstop>m_KeyboardMode</tabstop>
- <tabstop>m_MouseMode</tabstop>
- <tabstop>m_RemoveInteractor</tabstop>
- <tabstop>m_TranslationStep</tabstop>
- <tabstop>m_RotationStep</tabstop>
- <tabstop>m_ScaleFactor</tabstop>
- <tabstop>m_OriginPointRadioButton</tabstop>
- <tabstop>m_CenterPointRadioButton</tabstop>
- <tabstop>m_CustomAnchorPointRadioButton</tabstop>
- <tabstop>m_AnchorPointX</tabstop>
- <tabstop>m_AnchorPointY</tabstop>
- <tabstop>m_AnchorPointZ</tabstop>
- <tabstop>m_UsageInfoCheckBox</tabstop>
- </tabstops>
- <resources>
- <include location="../../../../../mitk-super-master-release/MITK-build/Plugins/org.mitk.gui.qt.geometrytools/org_mitk_gui_qt_geometrytools_cached.qrc"/>
- </resources>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/org_mitk_gui_qt_geometrytools_Activator.cpp b/Plugins/org.mitk.gui.qt.geometrytools/src/internal/org_mitk_gui_qt_geometrytools_Activator.cpp
deleted file mode 100644
index d57c5411e1..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/org_mitk_gui_qt_geometrytools_Activator.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*============================================================================
-
-The Medical Imaging Interaction Toolkit (MITK)
-
-Copyright (c) German Cancer Research Center (DKFZ)
-All rights reserved.
-
-Use of this source code is governed by a 3-clause BSD license that can be
-found in the LICENSE file.
-
-============================================================================*/
-
-#include "org_mitk_gui_qt_geometrytools_Activator.h"
-#include "QmitkGeometryToolsView.h"
-
-namespace mitk {
-
-void org_mitk_gui_qt_geometrytools_Activator::start(ctkPluginContext* context)
-{
- BERRY_REGISTER_EXTENSION_CLASS(QmitkGeometryToolsView, context)
-}
-
-void org_mitk_gui_qt_geometrytools_Activator::stop(ctkPluginContext* context)
-{
- Q_UNUSED(context)
-}
-
-}
diff --git a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/org_mitk_gui_qt_geometrytools_Activator.h b/Plugins/org.mitk.gui.qt.geometrytools/src/internal/org_mitk_gui_qt_geometrytools_Activator.h
deleted file mode 100644
index 455d85d4bc..0000000000
--- a/Plugins/org.mitk.gui.qt.geometrytools/src/internal/org_mitk_gui_qt_geometrytools_Activator.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 org_mitk_gui_qt_geometrytools_Activator_h
-#define org_mitk_gui_qt_geometrytools_Activator_h
-
-#include <ctkPluginActivator.h>
-
-namespace mitk {
-
-class org_mitk_gui_qt_geometrytools_Activator :
- public QObject, public ctkPluginActivator
-{
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_geometrytools")
- Q_INTERFACES(ctkPluginActivator)
-
-public:
-
- void start(ctkPluginContext* context) override;
- void stop(ctkPluginContext* context) override;
-
-}; // org_mitk_gui_qt_geometrytools_Activator
-
-}
-
-#endif // org_mitk_gui_qt_geometrytools_Activator_h
diff --git a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/QmitkUSNavigationCalibrationsDataModel.cpp b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/QmitkUSNavigationCalibrationsDataModel.cpp
index 9e6f972eef..ac12f4f207 100644
--- a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/QmitkUSNavigationCalibrationsDataModel.cpp
+++ b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/QmitkUSNavigationCalibrationsDataModel.cpp
@@ -1,244 +1,244 @@
/*============================================================================
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 "QmitkUSNavigationCalibrationsDataModel.h"
#include <mitkUSCombinedModality.h>
#include <mitkUSControlInterfaceBMode.h>
#include <QBrush>
#include <QColor>
#include <QIcon>
#include <QFont>
QmitkUSNavigationCalibrationsDataModel::QmitkUSNavigationCalibrationsDataModel(QObject *parent)
: QAbstractTableModel(parent),
m_ListenerDeviceChanged(this, &QmitkUSNavigationCalibrationsDataModel::OnDeviceChanged)
{
}
QmitkUSNavigationCalibrationsDataModel::~QmitkUSNavigationCalibrationsDataModel()
{
if ( m_CombinedModality.IsNotNull() )
{
m_CombinedModality->GetUltrasoundDevice()->RemovePropertyChangedListener(m_ListenerDeviceChanged);
}
}
void QmitkUSNavigationCalibrationsDataModel::SetCombinedModality(mitk::AbstractUltrasoundTrackerDevice::Pointer combinedModality)
{
if ( m_CombinedModality.IsNotNull() && m_CombinedModality->GetUltrasoundDevice().IsNotNull() )
{
m_CombinedModality->GetUltrasoundDevice()->RemovePropertyChangedListener(m_ListenerDeviceChanged);
}
m_CombinedModality = combinedModality;
if ( m_CombinedModality.IsNotNull() )
{
m_ControlInterfaceBMode = m_CombinedModality->GetControlInterfaceBMode();
// make sure that the combined modality is active as this may be
// necessary to get the available depths
if ( m_CombinedModality->GetUltrasoundDevice()->GetDeviceState() < mitk::USDevice::State_Connected ) { m_CombinedModality->GetUltrasoundDevice()->Connect(); }
if ( m_CombinedModality->GetUltrasoundDevice()->GetDeviceState() == mitk::USDevice::State_Connected ) { m_CombinedModality->GetUltrasoundDevice()->Activate(); }
if ( m_CombinedModality->GetUltrasoundDevice().IsNotNull() )
{
m_CombinedModality->GetUltrasoundDevice()->AddPropertyChangedListener(m_ListenerDeviceChanged);
}
}
// as the combined modality was changed, an old table model
// would not be valid anymore
this->beginResetModel();
this->endResetModel();
}
void QmitkUSNavigationCalibrationsDataModel::OnDeviceChanged(const std::string&, const std::string&)
{
this->beginResetModel();
this->endResetModel();
}
/** \brief Return number of rows of the model. */
int QmitkUSNavigationCalibrationsDataModel::rowCount ( const QModelIndex & ) const
{
if ( m_ControlInterfaceBMode.IsNull() )
{
return 1; // only one default depth can be assumed
}
else
{
return m_ControlInterfaceBMode->GetScanningDepthValues().size();
}
}
/** \brief Return number of columns (3) of the model. */
int QmitkUSNavigationCalibrationsDataModel::columnCount ( const QModelIndex & ) const
{
return 3;
}
/** \brief Return names for the columns, numbers for the rows and invalid for DisplayRole. */
QVariant QmitkUSNavigationCalibrationsDataModel::headerData ( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole ) { return QVariant(QVariant::Invalid); }
if ( orientation == Qt::Horizontal )
{
switch ( section )
{
case 0: return QVariant("Depth");
case 1: return QVariant("Calibrated");
case 2: return QVariant("");
}
}
return QVariant(QVariant::Invalid);
}
/** \brief Return selectable and enabled for column 1 (size); selectable, enabled and editable for every other column. */
Qt::ItemFlags QmitkUSNavigationCalibrationsDataModel::flags ( const QModelIndex & ) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
/** \brief Return model data of the selected cell. */
QVariant QmitkUSNavigationCalibrationsDataModel::data ( const QModelIndex & index, int role ) const
{
if ( m_CombinedModality.IsNull() ) { return QVariant(QVariant::Invalid); }
std::vector<double> scanningDepthValues = m_ControlInterfaceBMode.IsNull() ?
std::vector<double>(1,0) : m_ControlInterfaceBMode->GetScanningDepthValues();
// make sure that row and column index fit data borders
if (index.row() >= this->rowCount()
|| index.column() >= this->columnCount())
{
return QVariant(QVariant::Invalid);
}
double currentDepth = 0;
if ( m_ControlInterfaceBMode.IsNotNull() ) { currentDepth = m_ControlInterfaceBMode->GetScanningDepth(); }
bool isCalibratedForCurrentDepth =
m_CombinedModality->GetCalibration(QString::number(scanningDepthValues.at(index.row())).toStdString()).IsNotNull();
switch (role)
{
- case Qt::BackgroundColorRole:
+ case Qt::BackgroundRole:
{
if ( isCalibratedForCurrentDepth )
{
return QVariant(QBrush(QColor(125, 255, 125)));
}
else
{
return QVariant(QBrush(QColor(255, 125, 125)));
}
}
case Qt::FontRole:
{
if ( scanningDepthValues.at(index.row()) == currentDepth )
{
QFont qFont;
qFont.setBold(true);
return qFont;
}
else
{
return QVariant::Invalid;
}
}
case Qt::DecorationRole:
{
if ( index.column() == 2 )
{
if ( isCalibratedForCurrentDepth )
{
return QIcon(":/USNavigation/process-stop.png");
}
}
break;
}
case Qt::EditRole:
case Qt::DisplayRole:
{
switch ( index.column() )
{
case 0:
{
return QVariant::fromValue<double>(scanningDepthValues.at(index.row()));
}
case 1:
{
if ( m_ControlInterfaceBMode.IsNull() )
{
// use the current zoom level (which is assumed to be the only one),
// when no b mode controls are available
return QVariant(m_CombinedModality->GetCalibration().IsNotNull());
}
else
{
return QVariant(isCalibratedForCurrentDepth);
}
}
case 2:
{
return QVariant("");
}
}
break;
}
case Qt::ToolTipRole:
{
if ( index.column() == 2 && isCalibratedForCurrentDepth )
{
return QVariant(QString("Remove calibration for depth ") + QString::number(scanningDepthValues.at(index.row())) + " on mouse click.");
}
break;
}
}
return QVariant(QVariant::Invalid);
}
/** \brief Set model data for the selected cell. */
bool QmitkUSNavigationCalibrationsDataModel::setData ( const QModelIndex & index, const QVariant & value, int )
{
if ( m_CombinedModality.IsNull() || index.column() != 2 || value != false )
return false;
if ( m_ControlInterfaceBMode.IsNull() )
{
m_CombinedModality->RemoveCalibration();
}
else
{
m_CombinedModality->RemoveCalibration(QString::number(m_ControlInterfaceBMode->GetScanningDepthValues().at(index.row())).toStdString());
}
emit dataChanged(this->index(index.row(), 0), this->index(index.row(), 1));
return true;
}
/** \brief Remove given rows from the model.
* \param removeFromDataStorage zone nodes are removed from the data storage too, if this is set to true
*/
bool QmitkUSNavigationCalibrationsDataModel::removeRows ( int, int, const QModelIndex&, bool )
{
return false;
}
diff --git a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/QmitkUSZonesDataModel.cpp b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/QmitkUSZonesDataModel.cpp
index 9b75e10e90..0427f253f8 100644
--- a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/QmitkUSZonesDataModel.cpp
+++ b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/QmitkUSZonesDataModel.cpp
@@ -1,327 +1,327 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkUSZonesDataModel.h"
#include <QBrush>
#include "mitkMessage.h"
#include "mitkProperties.h"
#include "mitkRenderingManager.h"
#include "Interactors/mitkUSZonesInteractor.h"
QmitkUSZonesDataModel::QmitkUSZonesDataModel(QObject *parent) :
QAbstractTableModel(parent),
m_ListenerAddNode(this, &QmitkUSZonesDataModel::AddNode),
m_ListenerChangeNode(this, &QmitkUSZonesDataModel::ChangeNode),
m_ListenerRemoveNode(this, &QmitkUSZonesDataModel::RemoveNode)
{
}
QmitkUSZonesDataModel::~QmitkUSZonesDataModel()
{
if ( m_DataStorage.IsNotNull() )
{
m_DataStorage->AddNodeEvent.RemoveListener(m_ListenerAddNode);
m_DataStorage->ChangedNodeEvent.RemoveListener(m_ListenerChangeNode);
m_DataStorage->InteractorChangedNodeEvent.RemoveListener(m_ListenerChangeNode);
m_DataStorage->RemoveNodeEvent.RemoveListener(m_ListenerRemoveNode);
}
}
void QmitkUSZonesDataModel::SetDataStorage(mitk::DataStorage::Pointer dataStorage, mitk::DataNode::Pointer baseNode)
{
m_DataStorage = dataStorage;
m_BaseNode = baseNode;
if ( m_DataStorage.IsNotNull() )
{
m_DataStorage->AddNodeEvent.AddListener(m_ListenerAddNode);
m_DataStorage->RemoveNodeEvent.AddListener(m_ListenerRemoveNode);
m_DataStorage->ChangedNodeEvent.AddListener(m_ListenerChangeNode);
m_DataStorage->InteractorChangedNodeEvent.AddListener(m_ListenerChangeNode);
}
}
void QmitkUSZonesDataModel::AddNode(const mitk::DataNode* node)
{
if ( m_DataStorage.IsNull() )
{
MITK_ERROR << "DataStorage has to be set before adding the first zone node.";
mitkThrow() << "DataStorage has to be set before adding the first zone node.";
}
// do not add nodes, which aren't fully created yet
bool boolValue;
if ( ! (node->GetBoolProperty(mitk::USZonesInteractor::DATANODE_PROPERTY_CREATED, boolValue) && boolValue) )
{
return;
}
// get source node of given node and test if m_BaseNode is a source node
mitk::DataStorage::SetOfObjects::ConstPointer sourceNodes = m_DataStorage->GetSources(node);
mitk::DataStorage::SetOfObjects::ConstIterator baseNodeIt = sourceNodes->Begin();
while ( baseNodeIt != sourceNodes->End() && baseNodeIt->Value() != m_BaseNode ) { ++baseNodeIt; }
// only nodes below m_BaseNode should be added to the model
if ( baseNodeIt == sourceNodes->End() ) { return; }
int newRowIndex = this->rowCount();
this->insertRow(newRowIndex);
m_ZoneNodes.at(newRowIndex) = const_cast<mitk::DataNode*>(node);
// get row of the changed node and emit signal that the data of this row changed
emit dataChanged(this->index(newRowIndex, 0), this->index(newRowIndex, this->columnCount()));
}
void QmitkUSZonesDataModel::RemoveNode(const mitk::DataNode* node)
{
// find index of the given node in the nodes vector
unsigned int index = 0;
DataNodeVector::iterator current = m_ZoneNodes.begin();
while (current != m_ZoneNodes.end())
{
if ( *current == node ) { break; }
++index;
++current;
}
// remove node from model if it was found
if ( current != m_ZoneNodes.end() )
{
// remove node from the model and make sure that there will be no
// recursive removing calls (as removing node from data storage inside
// removeRows function will lead into another call of RemoveNode).
this->removeRows(index, 1, QModelIndex(), false);
}
}
void QmitkUSZonesDataModel::ChangeNode(const mitk::DataNode* node)
{
if ( static_cast<itk::SmartPointer<const mitk::DataNode> >(node).IsNull() ) { return; }
DataNodeVector::iterator oldNodeIt = find (m_ZoneNodes.begin(), m_ZoneNodes.end(), node);
if (oldNodeIt == m_ZoneNodes.end())
{
// if node was not added yet, but it's creation is finished -> add it now
bool boolValue;
if ( node->GetBoolProperty(mitk::USZonesInteractor::DATANODE_PROPERTY_CREATED, boolValue) && boolValue )
{
this->AddNode(node);
}
return;
}
// get row of the changed node and emit signal that the data of this row changed
unsigned int row = oldNodeIt - m_ZoneNodes.begin();
emit dataChanged(this->index(row, 0), this->index(row, this->columnCount()));
}
int QmitkUSZonesDataModel::rowCount ( const QModelIndex& /*parent*/ ) const
{
return m_ZoneNodes.size();
}
int QmitkUSZonesDataModel::columnCount ( const QModelIndex& /*parent*/ ) const
{
return 3;
}
QVariant QmitkUSZonesDataModel::headerData ( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole ) { return QVariant(QVariant::Invalid); }
if ( orientation == Qt::Horizontal )
{
switch ( section )
{
case 0: return QVariant("Name");
case 1: return QVariant("Size");
case 2: return QVariant("Color");
}
}
else
{
return QVariant(section+1);
}
return QVariant(QVariant::Invalid);
}
Qt::ItemFlags QmitkUSZonesDataModel::flags ( const QModelIndex& index ) const
{
if (index.column() == 1 || index.column() == 2) { return Qt::ItemIsSelectable | Qt::ItemIsEnabled; }
return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
}
QVariant QmitkUSZonesDataModel::data ( const QModelIndex& index, int role ) const
{
// make sure that row and column index fit data borders
if (static_cast<unsigned int>(index.row()) >= m_ZoneNodes.size()
|| index.column() >= this->columnCount())
{
return QVariant(QVariant::Invalid);
}
mitk::DataNode::Pointer curNode = m_ZoneNodes.at(index.row());
switch (role)
{
- case Qt::BackgroundColorRole:
+ case Qt::BackgroundRole:
{
float color[3];
if ( curNode->GetColor(color) )
{
QColor qColor(color[0] * 255, color[1] * 255, color[2] * 255);
if (qColor.isValid()) { return QVariant(QBrush(qColor)); }
}
break;
}
case Qt::EditRole:
case Qt::DisplayRole:
{
switch ( index.column() )
{
case 0:
{
return QString::fromStdString(curNode->GetName());
}
case 1:
{
float floatValue;
if ( curNode->GetFloatProperty(mitk::USZonesInteractor::DATANODE_PROPERTY_SIZE, floatValue) )
{
return static_cast<int>(floatValue);
}
else
{
return QVariant(QVariant::Invalid);
}
}
case 2:
{
float color[3];
if ( curNode->GetColor(color) )
{
QColor qColor(color[0] * 255, color[1] * 255, color[2] * 255);
if (qColor == Qt::darkGreen) { return QVariant("Green"); }
else if (qColor == Qt::red) { return QVariant("Red"); }
else if (qColor == Qt::blue) { return QVariant("Blue"); }
else if (qColor == Qt::yellow) { return QVariant("Yellow"); }
else { return QVariant(qColor.name()); }
}
else { return QVariant(QVariant::Invalid); }
}
}
break;
}
}
return QVariant(QVariant::Invalid);
}
bool QmitkUSZonesDataModel::setData ( const QModelIndex & index, const QVariant & value, int role )
{
if (role == Qt::EditRole)
{
if (static_cast<unsigned int>(index.row()) >= m_ZoneNodes.size()
|| index.column() >= this->columnCount())
{
return false;
}
mitk::DataNode::Pointer curNode = m_ZoneNodes.at(index.row());
switch ( index.column() )
{
case 0:
{
curNode->SetName(value.toString().toStdString());
break;
}
case 1:
{
curNode->SetFloatProperty(mitk::USZonesInteractor::DATANODE_PROPERTY_SIZE, value.toFloat());
if (curNode->GetData() != nullptr)
{
curNode->SetFloatProperty(mitk::USZonesInteractor::DATANODE_PROPERTY_SIZE, value.toFloat());
mitk::USZonesInteractor::UpdateSurface(curNode);
}
break;
}
case 2:
{
QColor color(value.toString());
curNode->SetColor(color.redF(), color.greenF(), color.blueF());
break;
}
default:
return false;
}
emit dataChanged(index, index);
}
// update the RenderWindow to show new points
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
return true;
}
bool QmitkUSZonesDataModel::insertRows ( int row, int count, const QModelIndex & parent )
{
this->beginInsertRows(parent, row, row+count-1);
for ( int n = 0; n < count; ++n )
{
m_ZoneNodes.insert(m_ZoneNodes.begin()+row, mitk::DataNode::New());
}
this->endInsertRows();
return true;
}
bool QmitkUSZonesDataModel::removeRows ( int row, int count, const QModelIndex & parent )
{
return this->removeRows(row, count, parent, true);
}
bool QmitkUSZonesDataModel::removeRows ( int row, int count, const QModelIndex & parent, bool removeFromDataStorage )
{
if ( static_cast<unsigned int>(row+count) > m_ZoneNodes.size() ) { return false; }
this->beginRemoveRows(parent, row, row+count-1);
for ( int n = count-1; n >= 0; --n )
{
DataNodeVector::iterator it = m_ZoneNodes.begin()+row+n;
mitk::DataNode::Pointer curNode = *it;
m_ZoneNodes.erase(it);
if ( removeFromDataStorage && m_DataStorage.IsNotNull() )
{
m_DataStorage->Remove(curNode);
}
}
this->endRemoveRows();
return true;
}
diff --git a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/SettingsWidgets/QmitkUSNavigationCombinedSettingsWidget.cpp b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/SettingsWidgets/QmitkUSNavigationCombinedSettingsWidget.cpp
index d3c51d5ec9..fa41fbe1cb 100644
--- a/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/SettingsWidgets/QmitkUSNavigationCombinedSettingsWidget.cpp
+++ b/Plugins/org.mitk.gui.qt.igt.app.ultrasoundtrackingnavigation/src/internal/SettingsWidgets/QmitkUSNavigationCombinedSettingsWidget.cpp
@@ -1,247 +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 "QmitkUSNavigationCombinedSettingsWidget.h"
#include "ui_QmitkUSNavigationCombinedSettingsWidget.h"
#include "mitkCommon.h"
#include "mitkDataNode.h"
#include <ctkDirectoryButton.h>
#include <QSettings>
QmitkUSNavigationCombinedSettingsWidget::QmitkUSNavigationCombinedSettingsWidget(QWidget *parent) :
QmitkUSNavigationAbstractSettingsWidget(parent),
ui(new Ui::QmitkUSNavigationCombinedSettingsWidget)
{
ui->setupUi(this);
ui->experimentResultsPathButton->setOptions(ctkDirectoryButton::ShowDirsOnly);
connect( ui->applicationComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnApplicationChanged(int)) );
}
QmitkUSNavigationCombinedSettingsWidget::~QmitkUSNavigationCombinedSettingsWidget()
{
delete ui;
}
void QmitkUSNavigationCombinedSettingsWidget::OnSetSettingsNode(itk::SmartPointer<mitk::DataNode> settingsNode, bool overwriteValues)
{
if ( overwriteValues )
{
settingsNode->SetStringProperty("settings.application", ui->applicationComboBox->currentText().toStdString().c_str());
settingsNode->SetStringProperty("settings.interaction-concept", this->InteractionNameToFile(ui->interactionConceptComboBox->currentText()).toStdString().c_str());
settingsNode->SetBoolProperty("settings.experiment-mode", ui->experimentModeCheckBox->isChecked());
settingsNode->SetStringProperty("settings.experiment-results-directory", ui->experimentResultsPathButton->directory().toStdString().c_str());
settingsNode->SetFloatProperty("settings.security-distance", ui->securityDistanceSpinBox->value());
settingsNode->SetIntProperty("settings.number-of-targets", ui->numberOfTargetsSpinBox->value());
settingsNode->SetBoolProperty("settings.use-planning-step", ui->planningStepUsageCheckBox->isChecked());
settingsNode->SetStringProperty("settings.needle-name-selected", ui->needleNameComboBox->currentText().toStdString().c_str());
settingsNode->SetStringProperty("settings.reference-name-selected", ui->referenceNameComboBox->currentText().toStdString().c_str());
}
else
{
std::string stringProperty;
float floatProperty;
bool boolProperty;
// load state of application setting combo box
if ( ! settingsNode->GetStringProperty("settings.application", stringProperty) ) { stringProperty = ""; }
int lastIndex = ui->applicationComboBox->findText(QString::fromStdString(stringProperty));
if (lastIndex == -1) { lastIndex = 0; }
ui->applicationComboBox->setCurrentIndex(lastIndex);
this->OnApplicationChanged(lastIndex);
// load state of interaction concept setting combo box
if ( ! settingsNode->GetStringProperty("settings.interaction-concept", stringProperty) ) { stringProperty = ""; }
lastIndex = ui->interactionConceptComboBox->findText(QString::fromStdString(stringProperty));
if (lastIndex == -1) { lastIndex = 0; }
ui->interactionConceptComboBox->setCurrentIndex(lastIndex);
if ( ! settingsNode->GetBoolProperty("settings.experiment-mode", boolProperty) ) { boolProperty = false; }
ui->experimentModeCheckBox->setChecked(boolProperty);
if ( ! settingsNode->GetStringProperty("settings.experiment-results-directory", stringProperty) ) { stringProperty = ""; }
ui->experimentResultsPathButton->setDirectory(QString::fromStdString(stringProperty));
if ( ! settingsNode->GetFloatProperty("settings.security-distance", floatProperty) ) { floatProperty = 2.0; }
ui->securityDistanceSpinBox->setValue(floatProperty);
if ( ! settingsNode->GetFloatProperty("settings.number-of-targets", floatProperty) ) { floatProperty = 3; }
ui->numberOfTargetsSpinBox->setValue(static_cast<int>(floatProperty));
if ( ! settingsNode->GetBoolProperty("settings.use-planning-step", boolProperty) ) { boolProperty = true; }
ui->planningStepUsageCheckBox->setChecked(boolProperty);
if ( ! settingsNode->GetStringProperty("settings.needle-names", stringProperty) ) { stringProperty = ""; }
QString needleNames = QString::fromStdString(stringProperty);
ui->needleNameComboBox->clear();
- ui->needleNameComboBox->addItems(needleNames.split(";", QString::SkipEmptyParts));
+ ui->needleNameComboBox->addItems(needleNames.split(";", Qt::SkipEmptyParts));
if ( ! settingsNode->GetStringProperty("settings.needle-name-selected", stringProperty) ) { stringProperty = ""; }
int index = ui->needleNameComboBox->findText(QString::fromStdString(stringProperty));
if (index == -1)
{
ui->needleNameComboBox->addItem(QString::fromStdString(stringProperty));
ui->needleNameComboBox->setCurrentIndex(ui->needleNameComboBox->count()-1);
}
else
{
ui->needleNameComboBox->setCurrentIndex(index);
}
if ( ! settingsNode->GetStringProperty("settings.reference-names", stringProperty) ) { stringProperty = ""; }
QString referenceNames = QString::fromStdString(stringProperty);
ui->referenceNameComboBox->clear();
- ui->referenceNameComboBox->addItems(referenceNames.split(";", QString::SkipEmptyParts));
+ ui->referenceNameComboBox->addItems(referenceNames.split(";", Qt::SkipEmptyParts));
if ( ! settingsNode->GetStringProperty("settings.reference-name-selected", stringProperty) ) { stringProperty = ""; }
index = ui->referenceNameComboBox->findText(QString::fromStdString(stringProperty));
if (index == -1)
{
ui->referenceNameComboBox->addItem(QString::fromStdString(stringProperty));
ui->referenceNameComboBox->setCurrentIndex(ui->referenceNameComboBox->count()-1);
}
else
{
ui->referenceNameComboBox->setCurrentIndex(index);
}
}
}
void QmitkUSNavigationCombinedSettingsWidget::OnSaveProcessing()
{
mitk::DataNode::Pointer settingsNode = this->GetSettingsNode();
QSettings settings;
settings.beginGroup("ultrasound-navigation");
settings.setValue("application", ui->applicationComboBox->currentText());
settingsNode->SetStringProperty("settings.application", ui->applicationComboBox->currentText().toStdString().c_str());
settings.setValue("interaction-concept", ui->interactionConceptComboBox->currentText());
settingsNode->SetStringProperty("settings.interaction-concept", this->InteractionNameToFile(ui->interactionConceptComboBox->currentText()).toStdString().c_str());
settings.setValue("experiment-mode", ui->experimentModeCheckBox->isChecked());
settingsNode->SetBoolProperty("settings.experiment-mode", ui->experimentModeCheckBox->isChecked());
settings.setValue("experiment-results-directory", ui->experimentResultsPathButton->directory());
settingsNode->SetStringProperty("settings.experiment-results-directory", ui->experimentResultsPathButton->directory().toStdString().c_str());
settings.setValue("security-distance", ui->securityDistanceSpinBox->value());
settingsNode->SetFloatProperty("settings.security-distance", ui->securityDistanceSpinBox->value());
settings.setValue("number-of-targets", ui->numberOfTargetsSpinBox->value());
settingsNode->SetIntProperty("settings.number-of-targets", ui->numberOfTargetsSpinBox->value());
settings.setValue("use-planning-step", ui->planningStepUsageCheckBox->isChecked());
settingsNode->SetBoolProperty("settings.use-planning-step", ui->planningStepUsageCheckBox->isChecked());
settings.setValue("needle-name-selected", ui->needleNameComboBox->currentText());
settingsNode->SetStringProperty("settings.needle-name-selected", ui->needleNameComboBox->currentText().toStdString().c_str());
settings.setValue("reference-name-selected", ui->referenceNameComboBox->currentText());
settingsNode->SetStringProperty("settings.reference-name-selected", ui->referenceNameComboBox->currentText().toStdString().c_str());
settings.endGroup();
}
void QmitkUSNavigationCombinedSettingsWidget::OnLoadSettingsProcessing()
{
QSettings settings;
settings.beginGroup("ultrasound-navigation");
// load state of application setting combo box
int lastIndex = ui->applicationComboBox->findText(settings.value("application").toString());
if (lastIndex == -1) { lastIndex = 0; }
ui->applicationComboBox->setCurrentIndex(lastIndex);
this->OnApplicationChanged(lastIndex);
// load state of interaction concept setting combo box
lastIndex = ui->interactionConceptComboBox->findText(settings.value("interaction-concept").toString());
if (lastIndex == -1) { lastIndex = 0; }
ui->interactionConceptComboBox->setCurrentIndex(lastIndex);
ui->experimentModeCheckBox->setChecked(settings.value("experiment-mode").toBool());
ui->experimentResultsPathButton->setDirectory(settings.value("experiment-results-directory").toString());
ui->securityDistanceSpinBox->setValue(settings.value("security-distance", 2.0).toDouble());
ui->numberOfTargetsSpinBox->setValue(settings.value("number-of-targets", 3).toInt());
ui->planningStepUsageCheckBox->setChecked(settings.value("use-planning-step", true).toBool());
ui->needleNameComboBox->clear();
ui->needleNameComboBox->addItems(settings.value("needle-names").toStringList());
QString selectedName = settings.value("needle-name-selected").toString();
int index = ui->needleNameComboBox->findText(selectedName);
if (index == -1)
{
ui->needleNameComboBox->addItem(selectedName);
ui->needleNameComboBox->setCurrentIndex(ui->needleNameComboBox->count()-1);
}
else
{
ui->needleNameComboBox->setCurrentIndex(index);
}
ui->referenceNameComboBox->clear();
ui->referenceNameComboBox->addItems(settings.value("reference-names").toStringList());
selectedName = settings.value("reference-name-selected").toString();
index = ui->referenceNameComboBox->findText(selectedName);
if (index == -1)
{
ui->referenceNameComboBox->addItem(selectedName);
ui->referenceNameComboBox->setCurrentIndex(ui->referenceNameComboBox->count()-1);
}
else
{
ui->referenceNameComboBox->setCurrentIndex(index);
}
settings.endGroup();
}
void QmitkUSNavigationCombinedSettingsWidget::OnApplicationChanged(int index)
{
if (index == 0)
{
ui->punctuationGroupBox->show();
ui->markerPlacementGroupBox->hide();
}
else if (index == 1)
{
ui->punctuationGroupBox->hide();
ui->markerPlacementGroupBox->show();
}
}
QString QmitkUSNavigationCombinedSettingsWidget::InteractionNameToFile(const QString& name) const
{
if (name == tr("Click, Move and Click"))
{
return QString("USZoneInteractions.xml");
}
else if (name == tr("Hold, Move and Release"))
{
return QString("USZoneInteractionsHold.xml");
}
else
{
return QString();
}
}
diff --git a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkConvertGeometryDataToROIAction.cpp b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkConvertGeometryDataToROIAction.cpp
index 5dd3020546..f982b5807e 100644
--- a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkConvertGeometryDataToROIAction.cpp
+++ b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkConvertGeometryDataToROIAction.cpp
@@ -1,154 +1,189 @@
/*============================================================================
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 "QmitkConvertGeometryDataToROIAction.h"
#include <mitkGeometryData.h>
#include <mitkImage.h>
#include <mitkNodePredicateDataType.h>
#include <mitkROI.h>
#include <QMessageBox>
namespace
{
- void handleInvalidNodeSelection()
+ void HandleInvalidNodeSelection()
{
- auto message = QStringLiteral("All selected bounding boxes must be child nodes of a single common reference image with a non-rotated geometry!");
+ auto message = QStringLiteral(
+ "All selected bounding boxes must be child nodes of a single common reference image "
+ "with a non-rotated geometry!");
+
MITK_ERROR << message;
QMessageBox::warning(nullptr, QStringLiteral("Convert to ROI"), message);
}
- bool isRotated(const mitk::BaseGeometry* geometry)
+ bool IsRotated(const mitk::BaseGeometry* geometry)
{
- const auto* matrix = geometry->GetVtkMatrix();
+ auto matrix = geometry->GetVtkMatrix();
for (int j = 0; j < 3; ++j)
{
for (int i = 0; i < 3; ++i)
{
- if (i != j && matrix->GetElement(i, j) > mitk::eps)
+ if (i != j && std::abs(matrix->GetElement(i, j)) > mitk::eps)
return true;
}
}
return false;
}
- std::pair<std::vector<const mitk::DataNode*>, mitk::DataNode*> getValidInput(const QList<mitk::DataNode::Pointer>& selectedNodes, const mitk::DataStorage* dataStorage)
+ void FlipAxis(mitk::BaseGeometry* geometry, int axis)
+ {
+ auto matrix = geometry->GetVtkMatrix();
+ matrix->SetElement(axis, axis, -matrix->GetElement(axis, axis));
+ matrix->SetElement(axis, 3, matrix->GetElement(axis, 3) - geometry->GetExtentInMM(axis));
+
+ geometry->SetIndexToWorldTransformByVtkMatrix(matrix);
+
+ auto bounds = geometry->GetBounds();
+ int minIndex = 2 * axis;
+ bounds[minIndex] *= -1;
+ bounds[minIndex + 1] += 2 * bounds[minIndex];
+
+ geometry->SetBounds(bounds);
+ }
+
+ mitk::BaseGeometry::Pointer RectifyGeometry(const mitk::BaseGeometry* geometry)
+ {
+ auto rectifiedGeometry = geometry->Clone();
+ auto matrix = rectifiedGeometry->GetVtkMatrix();
+
+ for (int axis = 0; axis < 3; ++axis)
+ {
+ if (matrix->GetElement(axis, axis) < 0.0)
+ FlipAxis(rectifiedGeometry, axis);
+ }
+
+ return rectifiedGeometry;
+ }
+
+ std::pair<std::vector<const mitk::DataNode*>, mitk::DataNode*> GetValidInput(const QList<mitk::DataNode::Pointer>& selectedNodes, const mitk::DataStorage* dataStorage)
{
std::pair<std::vector<const mitk::DataNode*>, mitk::DataNode*> result;
result.first.reserve(selectedNodes.size());
std::copy_if(selectedNodes.cbegin(), selectedNodes.cend(), std::back_inserter(result.first), [](const mitk::DataNode* node) {
return node != nullptr && dynamic_cast<mitk::GeometryData*>(node->GetData()) != nullptr;
});
for (auto node : result.first)
{
auto sourceNodes = dataStorage->GetSources(node, mitk::TNodePredicateDataType<mitk::Image>::New());
if (sourceNodes->size() != 1)
mitkThrow();
if (result.second == nullptr)
{
- if (isRotated(sourceNodes->front()->GetData()->GetGeometry()))
+ auto geometry = sourceNodes->front()->GetData()->GetGeometry();
+
+ if (IsRotated(geometry))
mitkThrow();
result.second = sourceNodes->front();
}
else if (result.second != sourceNodes->front())
{
mitkThrow();
}
}
return result;
}
}
QmitkConvertGeometryDataToROIAction::QmitkConvertGeometryDataToROIAction()
{
}
QmitkConvertGeometryDataToROIAction::~QmitkConvertGeometryDataToROIAction()
{
}
void QmitkConvertGeometryDataToROIAction::Run(const QList<mitk::DataNode::Pointer>& selectedNodes)
{
try
{
- auto [nodes, referenceNode] = getValidInput(selectedNodes, m_DataStorage);
+ auto [nodes, referenceNode] = GetValidInput(selectedNodes, m_DataStorage);
auto roi = mitk::ROI::New();
- roi->SetClonedGeometry(referenceNode->GetData()->GetGeometry());
+ roi->SetGeometry(RectifyGeometry(referenceNode->GetData()->GetGeometry()));
unsigned int id = 0;
for (auto node : nodes)
{
mitk::ROI::Element element(id++);
element.SetProperty("name", mitk::StringProperty::New(node->GetName()));
if (auto* color = node->GetProperty("Bounding Shape.Deselected Color"); color != nullptr)
element.SetProperty("color", color);
- const auto* geometry = node->GetData()->GetGeometry();
+ auto geometry = RectifyGeometry(node->GetData()->GetGeometry());
const auto origin = geometry->GetOrigin() - roi->GetGeometry()->GetOrigin();
const auto spacing = geometry->GetSpacing();
const auto bounds = geometry->GetBounds();
mitk::Point3D min;
mitk::Point3D max;
for (size_t i = 0; i < 3; ++i)
{
min[i] = origin[i] / spacing[i] + bounds[2 * i];
max[i] = origin[i] / spacing[i] + bounds[2 * i + 1] - 1;
}
element.SetMin(min);
element.SetMax(max);
roi->AddElement(element);
}
auto roiNode = mitk::DataNode::New();
roiNode->SetName(referenceNode->GetName() + " ROI" + (roi->GetNumberOfElements() > 1 ? "s" : ""));
roiNode->SetData(roi);
m_DataStorage->Add(roiNode, referenceNode);
}
catch (const mitk::Exception&)
{
- handleInvalidNodeSelection();
+ HandleInvalidNodeSelection();
}
}
void QmitkConvertGeometryDataToROIAction::SetDataStorage(mitk::DataStorage* dataStorage)
{
m_DataStorage = dataStorage;
}
void QmitkConvertGeometryDataToROIAction::SetFunctionality(berry::QtViewPart*)
{
}
void QmitkConvertGeometryDataToROIAction::SetSmoothed(bool)
{
}
void QmitkConvertGeometryDataToROIAction::SetDecimated(bool)
{
}
diff --git a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropperView.cpp b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropperView.cpp
index c8ae768dbd..df501800f1 100644
--- a/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropperView.cpp
+++ b/Plugins/org.mitk.gui.qt.imagecropper/src/internal/QmitkImageCropperView.cpp
@@ -1,510 +1,510 @@
/*============================================================================
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 "QmitkImageCropperView.h"
#include <mitkBoundingShapeCropper.h>
#include <mitkImageStatisticsHolder.h>
#include <mitkInteractionConst.h>
#include <mitkITKImageImport.h>
#include <mitkLabelSetImage.h>
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkNodePredicateFunction.h>
#include <mitkRenderingManager.h>
#include <usModuleRegistry.h>
#include <QMessageBox>
const std::string QmitkImageCropperView::VIEW_ID = "org.mitk.views.qmitkimagecropper";
QmitkImageCropperView::QmitkImageCropperView(QObject *)
: m_ParentWidget(nullptr)
, m_BoundingShapeInteractor(nullptr)
, m_CropOutsideValue(0)
{
CreateBoundingShapeInteractor(false);
}
QmitkImageCropperView::~QmitkImageCropperView()
{
//disable interactor
if (m_BoundingShapeInteractor != nullptr)
{
m_BoundingShapeInteractor->SetDataNode(nullptr);
m_BoundingShapeInteractor->EnableInteraction(false);
}
}
void QmitkImageCropperView::CreateQtPartControl(QWidget *parent)
{
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi(parent);
m_Controls.imageSelectionWidget->SetDataStorage(GetDataStorage());
m_Controls.imageSelectionWidget->SetNodePredicate(
mitk::NodePredicateAnd::New(mitk::TNodePredicateDataType<mitk::Image>::New(),
mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))));
m_Controls.imageSelectionWidget->SetSelectionIsOptional(true);
m_Controls.imageSelectionWidget->SetAutoSelectNewNodes(true);
m_Controls.imageSelectionWidget->SetEmptyInfo(QString("Please select an image node"));
m_Controls.imageSelectionWidget->SetPopUpTitel(QString("Select image node"));
connect(m_Controls.imageSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged,
this, &QmitkImageCropperView::OnImageSelectionChanged);
m_Controls.boundingBoxSelectionWidget->SetDataStorage(GetDataStorage());
m_Controls.boundingBoxSelectionWidget->SetNodePredicate(mitk::NodePredicateAnd::New(
mitk::TNodePredicateDataType<mitk::GeometryData>::New(),
mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))));
m_Controls.boundingBoxSelectionWidget->SetSelectionIsOptional(true);
m_Controls.boundingBoxSelectionWidget->SetAutoSelectNewNodes(true);
m_Controls.boundingBoxSelectionWidget->SetEmptyInfo(QString("Please select a bounding box"));
m_Controls.boundingBoxSelectionWidget->SetPopUpTitel(QString("Select bounding box node"));
connect(m_Controls.boundingBoxSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged,
this, &QmitkImageCropperView::OnBoundingBoxSelectionChanged);
connect(m_Controls.buttonCreateNewBoundingBox, SIGNAL(clicked()), this, SLOT(OnCreateNewBoundingBox()));
connect(m_Controls.buttonCropping, SIGNAL(clicked()), this, SLOT(OnCropping()));
connect(m_Controls.buttonMasking, SIGNAL(clicked()), this, SLOT(OnMasking()));
auto lambda = [this]()
{
m_Controls.groupImageSettings->setVisible(!m_Controls.groupImageSettings->isVisible());
};
connect(m_Controls.buttonAdvancedSettings, &ctkExpandButton::clicked, this, lambda);
connect(m_Controls.spinBoxOutsidePixelValue, SIGNAL(valueChanged(int)), this, SLOT(OnSliderValueChanged(int)));
SetDefaultGUI();
m_ParentWidget = parent;
this->OnImageSelectionChanged(m_Controls.imageSelectionWidget->GetSelectedNodes());
this->OnBoundingBoxSelectionChanged(m_Controls.boundingBoxSelectionWidget->GetSelectedNodes());
}
void QmitkImageCropperView::OnImageSelectionChanged(QList<mitk::DataNode::Pointer>)
{
bool rotationEnabled = false;
m_Controls.labelWarningRotation->setVisible(false);
auto imageNode = m_Controls.imageSelectionWidget->GetSelectedNode();
if (imageNode.IsNull())
{
SetDefaultGUI();
return;
}
auto image = dynamic_cast<mitk::Image*>(imageNode->GetData());
if (nullptr != image)
{
if (image->GetDimension() < 3)
{
QMessageBox::warning(nullptr,
tr("Invalid image selected"),
tr("ImageCropper only works with 3 or more dimensions."),
- QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
+ QMessageBox::Ok | QMessageBox::NoButton, QMessageBox::NoButton);
SetDefaultGUI();
return;
}
m_ParentWidget->setEnabled(true);
m_Controls.buttonCreateNewBoundingBox->setEnabled(true);
vtkSmartPointer<vtkMatrix4x4> imageMat = image->GetGeometry()->GetVtkMatrix();
// check whether the image geometry is rotated; if so, no pixel aligned cropping or masking can be performed
if ((imageMat->GetElement(1, 0) == 0.0) && (imageMat->GetElement(0, 1) == 0.0) &&
(imageMat->GetElement(1, 2) == 0.0) && (imageMat->GetElement(2, 1) == 0.0) &&
(imageMat->GetElement(2, 0) == 0.0) && (imageMat->GetElement(0, 2) == 0.0))
{
rotationEnabled = false;
m_Controls.labelWarningRotation->setVisible(false);
}
else
{
rotationEnabled = true;
m_Controls.labelWarningRotation->setStyleSheet(" QLabel { color: rgb(255, 0, 0) }");
m_Controls.labelWarningRotation->setVisible(true);
}
this->CreateBoundingShapeInteractor(rotationEnabled);
if (itk::IOPixelEnum::SCALAR == image->GetPixelType().GetPixelType())
{
// Might be changed with the upcoming new image statistics plugin
//(recomputation might be very expensive for large images ;) )
auto statistics = image->GetStatistics();
auto minPixelValue = statistics->GetScalarValueMin();
auto maxPixelValue = statistics->GetScalarValueMax();
if (minPixelValue < std::numeric_limits<int>::min())
{
minPixelValue = std::numeric_limits<int>::min();
}
if (maxPixelValue > std::numeric_limits<int>::max())
{
maxPixelValue = std::numeric_limits<int>::max();
}
m_Controls.spinBoxOutsidePixelValue->setEnabled(true);
m_Controls.spinBoxOutsidePixelValue->setMaximum(static_cast<int>(maxPixelValue));
m_Controls.spinBoxOutsidePixelValue->setMinimum(static_cast<int>(minPixelValue));
m_Controls.spinBoxOutsidePixelValue->setValue(static_cast<int>(minPixelValue));
}
else
{
m_Controls.spinBoxOutsidePixelValue->setEnabled(false);
}
unsigned int dim = image->GetDimension();
if (dim < 2 || dim > 4)
{
m_ParentWidget->setEnabled(false);
}
if (m_Controls.boundingBoxSelectionWidget->GetSelectedNode().IsNotNull())
{
m_Controls.buttonCropping->setEnabled(true);
m_Controls.buttonMasking->setEnabled(true);
m_Controls.buttonAdvancedSettings->setEnabled(true);
m_Controls.groupImageSettings->setEnabled(true);
}
}
}
void QmitkImageCropperView::OnBoundingBoxSelectionChanged(QList<mitk::DataNode::Pointer>)
{
auto boundingBoxNode = m_Controls.boundingBoxSelectionWidget->GetSelectedNode();
if (boundingBoxNode.IsNull())
{
SetDefaultGUI();
m_BoundingShapeInteractor->EnableInteraction(false);
m_BoundingShapeInteractor->SetDataNode(nullptr);
if (m_Controls.imageSelectionWidget->GetSelectedNode().IsNotNull())
{
m_Controls.buttonCreateNewBoundingBox->setEnabled(true);
}
return;
}
auto boundingBox = dynamic_cast<mitk::GeometryData*>(boundingBoxNode->GetData());
if (nullptr != boundingBox)
{
// node newly selected
boundingBoxNode->SetVisibility(true);
m_BoundingShapeInteractor->EnableInteraction(true);
m_BoundingShapeInteractor->SetDataNode(boundingBoxNode);
mitk::RenderingManager::GetInstance()->InitializeViews();
if (m_Controls.imageSelectionWidget->GetSelectedNode().IsNotNull())
{
m_Controls.buttonCropping->setEnabled(true);
m_Controls.buttonMasking->setEnabled(true);
m_Controls.buttonAdvancedSettings->setEnabled(true);
m_Controls.groupImageSettings->setEnabled(true);
}
}
}
void QmitkImageCropperView::OnCreateNewBoundingBox()
{
auto imageNode = m_Controls.imageSelectionWidget->GetSelectedNode();
if (imageNode.IsNull())
{
return;
}
if (nullptr == imageNode->GetData())
{
return;
}
QString name = QString::fromStdString(imageNode->GetName() + " Bounding Box");
auto boundingShape = this->GetDataStorage()->GetNode(mitk::NodePredicateFunction::New([&name](const mitk::DataNode *node)
{
return 0 == node->GetName().compare(name.toStdString());
}));
if (nullptr != boundingShape)
{
name = this->AdaptBoundingObjectName(name);
}
// get current timestep to support 3d+t images
auto renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategy::OPEN);
const mitk::TimePointType timePoint = renderWindowPart->GetSelectedTimePoint();
const auto imageGeometry = imageNode->GetData()->GetTimeGeometry()->GetGeometryForTimePoint(timePoint);
auto boundingBox = mitk::GeometryData::New();
boundingBox->SetGeometry(static_cast<mitk::Geometry3D*>(this->InitializeWithImageGeometry(imageGeometry)));
auto boundingBoxNode = mitk::DataNode::New();
boundingBoxNode->SetData(boundingBox);
boundingBoxNode->SetProperty("name", mitk::StringProperty::New(name.toStdString()));
boundingBoxNode->SetProperty("layer", mitk::IntProperty::New(99));
boundingBoxNode->AddProperty("Bounding Shape.Handle Size Factor", mitk::DoubleProperty::New(0.02));
boundingBoxNode->SetBoolProperty("pickable", true);
if (!this->GetDataStorage()->Exists(boundingBoxNode))
{
GetDataStorage()->Add(boundingBoxNode, imageNode);
}
m_Controls.boundingBoxSelectionWidget->SetCurrentSelectedNode(boundingBoxNode);
}
void QmitkImageCropperView::OnCropping()
{
this->ProcessImage(false);
}
void QmitkImageCropperView::OnMasking()
{
this->ProcessImage(true);
}
void QmitkImageCropperView::OnSliderValueChanged(int slidervalue)
{
m_CropOutsideValue = slidervalue;
}
void QmitkImageCropperView::CreateBoundingShapeInteractor(bool rotationEnabled)
{
if (m_BoundingShapeInteractor.IsNull())
{
m_BoundingShapeInteractor = mitk::BoundingShapeInteractor::New();
m_BoundingShapeInteractor->LoadStateMachine("BoundingShapeInteraction.xml", us::ModuleRegistry::GetModule("MitkBoundingShape"));
m_BoundingShapeInteractor->SetEventConfig("BoundingShapeMouseConfig.xml", us::ModuleRegistry::GetModule("MitkBoundingShape"));
}
m_BoundingShapeInteractor->SetRotationEnabled(rotationEnabled);
}
mitk::Geometry3D::Pointer QmitkImageCropperView::InitializeWithImageGeometry(const mitk::BaseGeometry* geometry) const
{
// convert a BaseGeometry into a Geometry3D (otherwise IO is not working properly)
if (geometry == nullptr)
mitkThrow() << "Geometry is not valid.";
auto boundingGeometry = mitk::Geometry3D::New();
boundingGeometry->SetBounds(geometry->GetBounds());
boundingGeometry->SetImageGeometry(geometry->GetImageGeometry());
boundingGeometry->SetOrigin(geometry->GetOrigin());
boundingGeometry->SetSpacing(geometry->GetSpacing());
boundingGeometry->SetIndexToWorldTransform(geometry->GetIndexToWorldTransform()->Clone());
boundingGeometry->Modified();
return boundingGeometry;
}
void QmitkImageCropperView::ProcessImage(bool mask)
{
auto renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategy::OPEN);
const auto timePoint = renderWindowPart->GetSelectedTimePoint();
auto imageNode = m_Controls.imageSelectionWidget->GetSelectedNode();
if (imageNode.IsNull())
{
QMessageBox::information(nullptr, "Warning", "Please load and select an image before starting image processing.");
return;
}
auto boundingBoxNode = m_Controls.boundingBoxSelectionWidget->GetSelectedNode();
if (boundingBoxNode.IsNull())
{
QMessageBox::information(nullptr, "Warning", "Please load and select a cropping object before starting image processing.");
return;
}
if (!imageNode->GetData()->GetTimeGeometry()->IsValidTimePoint(timePoint))
{
QMessageBox::information(nullptr, "Warning", "Please select a time point that is within the time bounds of the selected image.");
return;
}
const auto timeStep = imageNode->GetData()->GetTimeGeometry()->TimePointToTimeStep(timePoint);
auto image = dynamic_cast<mitk::Image*>(imageNode->GetData());
auto boundingBox = dynamic_cast<mitk::GeometryData*>(boundingBoxNode->GetData());
if (nullptr != image && nullptr != boundingBox)
{
// Check if initial node name is already in box name
std::string imagePrefix = "";
if (boundingBoxNode->GetName().find(imageNode->GetName()) != 0)
{
imagePrefix = imageNode->GetName() + "_";
}
QString imageName;
if (mask)
{
imageName = QString::fromStdString(imagePrefix + boundingBoxNode->GetName() + "_masked");
}
else
{
imageName = QString::fromStdString(imagePrefix + boundingBoxNode->GetName() + "_cropped");
}
if (m_Controls.checkBoxCropTimeStepOnly->isChecked())
{
imageName = imageName + "_T" + QString::number(timeStep);
}
// image and bounding shape ok, set as input
auto croppedImageNode = mitk::DataNode::New();
auto cutter = mitk::BoundingShapeCropper::New();
cutter->SetGeometry(boundingBox);
// adjustable in advanced settings
cutter->SetUseWholeInputRegion(mask); //either mask (mask=true) or crop (mask=false)
cutter->SetOutsideValue(m_CropOutsideValue);
cutter->SetUseCropTimeStepOnly(m_Controls.checkBoxCropTimeStepOnly->isChecked());
cutter->SetCurrentTimeStep(timeStep);
// TODO: Add support for MultiLayer (right now only Mulitlabel support)
auto labelsetImageInput = dynamic_cast<mitk::LabelSetImage*>(image);
if (nullptr != labelsetImageInput)
{
cutter->SetInput(labelsetImageInput);
// do the actual cutting
try
{
cutter->Update();
}
catch (const itk::ExceptionObject& e)
{
std::string message = std::string("The Cropping filter could not process because of: \n ") + e.GetDescription();
QMessageBox::warning(nullptr, tr("Cropping not possible!"), tr(message.c_str()),
- QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
+ QMessageBox::Ok | QMessageBox::NoButton, QMessageBox::NoButton);
return;
}
auto labelSetImage = mitk::LabelSetImage::New();
labelSetImage->InitializeByLabeledImage(cutter->GetOutput());
for (unsigned int i = 0; i < labelsetImageInput->GetNumberOfLayers(); i++)
{
labelSetImage->AddLabelSetToLayer(i, labelsetImageInput->GetLabelSet(i));
}
croppedImageNode->SetData(labelSetImage);
croppedImageNode->SetProperty("name", mitk::StringProperty::New(imageName.toStdString()));
//add cropping result to the current data storage as child node to the image node
if (!m_Controls.checkOverwriteImage->isChecked())
{
if (!this->GetDataStorage()->Exists(croppedImageNode))
{
this->GetDataStorage()->Add(croppedImageNode, imageNode);
}
}
else // original image will be overwritten by the result image and the bounding box of the result is adjusted
{
imageNode->SetData(labelSetImage);
imageNode->Modified();
// Adjust coordinate system by doing a reinit on
auto tempDataStorage = mitk::DataStorage::SetOfObjects::New();
tempDataStorage->InsertElement(0, imageNode);
// initialize the views to the bounding geometry
auto bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(tempDataStorage);
mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
}
}
else
{
cutter->SetInput(image);
// do the actual cutting
try
{
cutter->Update();
}
catch (const itk::ExceptionObject& e)
{
std::string message = std::string("The Cropping filter could not process because of: \n ") + e.GetDescription();
QMessageBox::warning(nullptr, tr("Cropping not possible!"), tr(message.c_str()),
- QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
+ QMessageBox::Ok | QMessageBox::NoButton, QMessageBox::NoButton);
return;
}
//add cropping result to the current data storage as child node to the image node
if (!m_Controls.checkOverwriteImage->isChecked())
{
croppedImageNode->SetData(cutter->GetOutput());
croppedImageNode->SetProperty("name", mitk::StringProperty::New(imageName.toStdString()));
croppedImageNode->SetProperty("color", mitk::ColorProperty::New(1.0, 1.0, 1.0));
mitk::LevelWindow levelWindow;
imageNode->GetLevelWindow(levelWindow);
croppedImageNode->SetLevelWindow(levelWindow);
if (!this->GetDataStorage()->Exists(croppedImageNode))
{
this->GetDataStorage()->Add(croppedImageNode, imageNode);
imageNode->SetVisibility(mask); // Give the user a visual clue that something happened when image was cropped
}
}
else // original image will be overwritten by the result image and the bounding box of the result is adjusted
{
mitk::LevelWindow levelWindow;
imageNode->GetLevelWindow(levelWindow);
imageNode->SetData(cutter->GetOutput());
imageNode->SetLevelWindow(levelWindow);
// Adjust coordinate system by doing a reinit on
auto tempDataStorage = mitk::DataStorage::SetOfObjects::New();
tempDataStorage->InsertElement(0, imageNode);
// initialize the views to the bounding geometry
auto bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(tempDataStorage);
mitk::RenderingManager::GetInstance()->InitializeViews(bounds);
}
}
}
else
{
QMessageBox::information(nullptr, "Warning", "Please load and select an image before starting image processing.");
}
}
void QmitkImageCropperView::SetDefaultGUI()
{
m_Controls.buttonCreateNewBoundingBox->setEnabled(false);
m_Controls.buttonCropping->setEnabled(false);
m_Controls.buttonMasking->setEnabled(false);
m_Controls.buttonAdvancedSettings->setEnabled(false);
m_Controls.groupImageSettings->setEnabled(false);
m_Controls.groupImageSettings->setVisible(false);
m_Controls.checkOverwriteImage->setChecked(false);
m_Controls.checkBoxCropTimeStepOnly->setChecked(false);
}
QString QmitkImageCropperView::AdaptBoundingObjectName(const QString& name) const
{
unsigned int counter = 2;
QString newName = QString("%1 %2").arg(name).arg(counter);
while (nullptr != this->GetDataStorage()->GetNode(mitk::NodePredicateFunction::New([&newName](const mitk::DataNode *node)
{
return 0 == node->GetName().compare(newName.toStdString());
})))
{
newName = QString("%1 %2").arg(name).arg(++counter);
}
return newName;
}
diff --git a/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.cpp b/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.cpp
index 84b00c4397..a34c9c62f6 100644
--- a/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.cpp
+++ b/Plugins/org.mitk.gui.qt.matchpoint.algorithm.browser/src/internal/QmitkMatchPointBrowser.cpp
@@ -1,269 +1,269 @@
/*============================================================================
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_matchpoint_algorithm_browser_Activator.h"
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// Qmitk
#include "QmitkMatchPointBrowser.h"
// Qt
#include <QMessageBox>
#include <QErrorMessage>
#include <QDir>
#include <QStringList>
//MITK
#include <mitkStatusBar.h>
#include "MatchPointBrowserConstants.h"
#include "mitkAlgorithmInfoSelectionProvider.h"
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
// MatchPoint
#include "mapRegistrationAlgorithmInterface.h"
#include "mapAlgorithmEvents.h"
#include "mapAlgorithmWrapperEvent.h"
#include "mapExceptionObjectMacros.h"
#include "mapDeploymentDLLDirectoryBrowser.h"
#include "mapDeploymentEvents.h"
const std::string QmitkMatchPointBrowser::VIEW_ID = "org.mitk.views.matchpoint.algorithm.browser";
QmitkMatchPointBrowser::QmitkMatchPointBrowser()
: m_Parent(nullptr), m_LoadedDLLHandle(nullptr), m_LoadedAlgorithm(nullptr)
{
}
QmitkMatchPointBrowser::~QmitkMatchPointBrowser()
{
}
void QmitkMatchPointBrowser::OnPreferencesChanged(const mitk::IPreferences* /*prefs*/)
{
this->OnSearchFolderButtonPushed();
}
void QmitkMatchPointBrowser::CreateConnections()
{
connect(m_Controls.m_pbSearchFolder, SIGNAL(clicked()), this, SLOT(OnSearchFolderButtonPushed()));
connect(m_Controls.m_algoTreeView, SIGNAL(clicked(const QModelIndex&)), this,
SLOT(OnAlgoListSelectionChanged(const QModelIndex&)));
connect(m_Controls.pbClearSearch, SIGNAL(clicked()), m_Controls.lineSearch, SLOT(clear()));
connect(m_Controls.lineSearch, SIGNAL(textChanged(const QString&)), this,
SLOT(OnSearchChanged(const QString&)));
}
void QmitkMatchPointBrowser::OnSearchFolderButtonPushed()
{
RetrieveAndStorePreferenceValues();
// test if some folder list non-empty
int folderCount = m_currentSearchPaths.count();
if (!folderCount)
{
Error(QString("No search folder selected for MatchPoint algorithm browser! Please set search paths in the MatchPoint preference page."));
m_DLLInfoList.clear();
}
else
{
map::deployment::DLLDirectoryBrowser::Pointer browser = map::deployment::DLLDirectoryBrowser::New();
auto validCommand = ::itk::MemberCommand<QmitkMatchPointBrowser>::New();
validCommand->SetCallbackFunction(this, &QmitkMatchPointBrowser::OnValidDeploymentEvent);
browser->AddObserver(::map::events::ValidDLLEvent(), validCommand);
auto invalidCommand = ::itk::MemberCommand<QmitkMatchPointBrowser>::New();
invalidCommand->SetCallbackFunction(this, &QmitkMatchPointBrowser::OnInvalidDeploymentEvent);
browser->AddObserver(::map::events::InvalidDLLEvent(), invalidCommand);
foreach(QString path, m_currentSearchPaths)
{
browser->addDLLSearchLocation(path.toStdString());
}
browser->update();
m_DLLInfoList = browser->getLibraryInfos();
}
m_Controls.groupWarning->setVisible(m_DLLInfoList.empty());
m_Controls.groupList->setVisible(!m_DLLInfoList.empty());
m_algModel->SetAlgorithms(m_DLLInfoList);
m_Controls.lineSearch->clear();
}
void QmitkMatchPointBrowser::OnAlgoListSelectionChanged(const QModelIndex& index)
{
QVariant vIndex = index.data(Qt::UserRole).toInt();
map::deployment::DLLInfo::ConstPointer currentItemInfo = nullptr;
if (vIndex.isValid())
{
std::size_t algListIndex = vIndex.toInt();
if (algListIndex < m_DLLInfoList.size())
{
currentItemInfo = m_DLLInfoList[algListIndex];
}
}
m_Controls.m_teAlgorithmDetails->updateInfo(currentItemInfo);
if (currentItemInfo)
{
//update selection provider
mitk::MAPAlgorithmInfoSelection::Pointer infoSelection = mitk::MAPAlgorithmInfoSelection::Pointer(
new mitk::MAPAlgorithmInfoSelection(currentItemInfo));
this->m_SelectionProvider->SetInfoSelection(infoSelection);
}
}
void QmitkMatchPointBrowser::OnSearchChanged(const QString& text)
{
- m_filterProxy->setFilterRegExp(text);
+ m_filterProxy->setFilterRegularExpression(text);
m_filterProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
};
void QmitkMatchPointBrowser::OnInvalidDeploymentEvent(const ::itk::Object *, const itk::EventObject &event)
{
auto deployEvent = dynamic_cast<const ::map::events::InvalidDLLEvent*>(&event);
this->Error(QString("Error when try to inspect deployed registration algorithm. Details: ")+QString::fromStdString(deployEvent->getComment()));
}
void QmitkMatchPointBrowser::OnValidDeploymentEvent(const ::itk::Object *, const itk::EventObject &event)
{
auto deployEvent = dynamic_cast<const ::map::events::ValidDLLEvent*>(&event);
auto info = static_cast<const ::map::deployment::DLLInfo*>(deployEvent->getData());
MITK_INFO << "Successfully inspected deployed registration algorithm. UID: " << info->getAlgorithmUID().toStr() << ". Path: " << info->getLibraryFilePath();
}
void QmitkMatchPointBrowser::CreateQtPartControl(QWidget* parent)
{
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi(parent);
m_Parent = parent;
m_algModel = new QmitkAlgorithmListModel(parent);
m_filterProxy = new QSortFilterProxyModel(parent);
//! [Qt Selection Provider registration]
// create new qt selection provider
m_SelectionProvider = new mitk::AlgorithmInfoSelectionProvider();
m_filterProxy->setSourceModel(m_algModel);
m_filterProxy->setDynamicSortFilter(true);
m_filterProxy->setFilterKeyColumn(-1);
m_Controls.m_algoTreeView->setModel(m_filterProxy);
m_Controls.m_algoTreeView->setSelectionMode(QAbstractItemView::SingleSelection);
m_Controls.m_algoTreeView->header()->setStretchLastSection(false);
m_Controls.m_algoTreeView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
m_Controls.m_algoTreeView->setColumnHidden(3, true);
this->CreateConnections();
}
void QmitkMatchPointBrowser::SetSelectionProvider()
{
this->GetSite()->SetSelectionProvider(m_SelectionProvider);
}
void QmitkMatchPointBrowser::SetFocus()
{
}
void QmitkMatchPointBrowser::Error(QString msg)
{
mitk::StatusBar::GetInstance()->DisplayErrorText(msg.toLatin1());
MITK_ERROR << msg.toStdString().c_str();
}
void QmitkMatchPointBrowser::RetrieveAndStorePreferenceValues()
{
auto* prefs = this->RetrievePreferences();
bool loadApplicationDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, true);
bool loadHomeDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, false);
bool loadCurrentDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, false);
bool loadAutoLoadDir = prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, false);
// Get some default application paths.
QStringList newPaths;
// Here we can use the preferences to set up the builder,
if (loadApplicationDir)
{
newPaths << QCoreApplication::applicationDirPath();
}
if (loadHomeDir)
{
newPaths << QDir::homePath();
}
if (loadCurrentDir)
{
newPaths << QDir::currentPath();
}
if (loadAutoLoadDir)
{
char* deployedAlgorithmLoadPath = getenv("MAP_MDRA_LOAD_PATH");
if (deployedAlgorithmLoadPath != nullptr)
{
// The load path may in fact be a semi-colon or colon separated list of directories, not just one.
QString paths(deployedAlgorithmLoadPath);
#ifdef Q_OS_WIN32
QString pathSeparator(";");
#else
QString pathSeparator(":");
#endif
- QStringList splitPath = paths.split(pathSeparator, QString::SkipEmptyParts);
+ QStringList splitPath = paths.split(pathSeparator, Qt::SkipEmptyParts);
foreach(QString path, splitPath)
{
QDir dir = QDir(path);
newPaths << dir.absolutePath();
}
}
}
// We get additional directory paths from preferences.
const auto pathString = QString::fromStdString(prefs->Get(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, ""));
- QStringList additionalPaths = pathString.split(";", QString::SkipEmptyParts);
+ QStringList additionalPaths = pathString.split(";", Qt::SkipEmptyParts);
newPaths << additionalPaths;
const auto additionalAlgorirthmsString = QString::fromStdString(prefs->Get(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, ""));
- additionalPaths = additionalAlgorirthmsString.split(";", QString::SkipEmptyParts);
+ additionalPaths = additionalAlgorirthmsString.split(";", Qt::SkipEmptyParts);
newPaths << additionalPaths;
m_currentSearchPaths = newPaths;
}
mitk::IPreferences* QmitkMatchPointBrowser::RetrievePreferences()
{
const auto id = "/" + MatchPointBrowserConstants::VIEW_ID;
return mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node(id);
}
diff --git a/Plugins/org.mitk.gui.qt.matchpoint.manipulator/src/internal/QmitkMatchPointRegistrationManipulator.cpp b/Plugins/org.mitk.gui.qt.matchpoint.manipulator/src/internal/QmitkMatchPointRegistrationManipulator.cpp
index 02e2705e6e..626f31964f 100644
--- a/Plugins/org.mitk.gui.qt.matchpoint.manipulator/src/internal/QmitkMatchPointRegistrationManipulator.cpp
+++ b/Plugins/org.mitk.gui.qt.matchpoint.manipulator/src/internal/QmitkMatchPointRegistrationManipulator.cpp
@@ -1,519 +1,519 @@
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// Mitk
#include <mitkStatusBar.h>
#include <mitkNodePredicateDataProperty.h>
#include <mitkMAPRegistrationWrapper.h>
#include "mitkRegVisPropertyTags.h"
#include "mitkMatchPointPropertyTags.h"
#include "mitkRegEvaluationObject.h"
#include "mitkRegistrationHelper.h"
#include "mitkRegEvaluationMapper2D.h"
#include <mitkMAPAlgorithmHelper.h>
#include <mitkResultNodeGenerationHelper.h>
#include <mitkUIDHelper.h>
#include "mitkProperties.h"
// Qmitk
#include "QmitkRenderWindow.h"
#include "QmitkMatchPointRegistrationManipulator.h"
#include <QmitkMappingJob.h>
// Qt
#include <QMessageBox>
#include <QErrorMessage>
#include <QTimer>
#include <QThreadPool>
//MatchPoint
#include <mapRegistrationManipulator.h>
#include <mapPreCachedRegistrationKernel.h>
#include <mapCombinedRegistrationKernel.h>
#include <mapNullRegistrationKernel.h>
#include <mapRegistrationCombinator.h>
#include <itkCompositeTransform.h>
#include <boost/math/constants/constants.hpp>
const std::string QmitkMatchPointRegistrationManipulator::VIEW_ID =
"org.mitk.views.matchpoint.registration.manipulator";
const std::string QmitkMatchPointRegistrationManipulator::HelperNodeName =
"RegistrationManipulationEvaluationHelper";
QmitkMatchPointRegistrationManipulator::QmitkMatchPointRegistrationManipulator()
: m_Parent(nullptr), m_activeManipulation(false),
m_currentSelectedTimePoint(0.), m_internalUpdate(false)
{
m_currentSelectedPosition.Fill(0.0);
}
QmitkMatchPointRegistrationManipulator::~QmitkMatchPointRegistrationManipulator()
{
if (this->m_EvalNode.IsNotNull() && this->GetDataStorage().IsNotNull())
{
this->GetDataStorage()->Remove(this->m_EvalNode);
}
}
void QmitkMatchPointRegistrationManipulator::SetFocus()
{
}
void QmitkMatchPointRegistrationManipulator::Error(QString msg)
{
mitk::StatusBar::GetInstance()->DisplayErrorText(msg.toLatin1());
MITK_ERROR << msg.toStdString().c_str();
}
void QmitkMatchPointRegistrationManipulator::CreateQtPartControl(QWidget* parent)
{
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi(parent);
m_Parent = parent;
this->m_Controls.registrationNodeSelector->SetDataStorage(this->GetDataStorage());
this->m_Controls.registrationNodeSelector->SetSelectionIsOptional(false);
this->m_Controls.movingNodeSelector->SetDataStorage(this->GetDataStorage());
this->m_Controls.movingNodeSelector->SetSelectionIsOptional(false);
this->m_Controls.targetNodeSelector->SetDataStorage(this->GetDataStorage());
this->m_Controls.targetNodeSelector->SetSelectionIsOptional(false);
this->m_Controls.registrationNodeSelector->SetInvalidInfo("Select base registration.");
this->m_Controls.registrationNodeSelector->SetPopUpTitel("Select registration.");
this->m_Controls.registrationNodeSelector->SetPopUpHint("Select a registration object that should be used as starting point for the manual manipulation.");
this->m_Controls.movingNodeSelector->SetInvalidInfo("Select moving image.");
this->m_Controls.movingNodeSelector->SetPopUpTitel("Select moving image.");
this->m_Controls.movingNodeSelector->SetPopUpHint("Select the moving image for the evaluation. This is the image that will be mapped by the registration.");
this->m_Controls.targetNodeSelector->SetInvalidInfo("Select target image.");
this->m_Controls.targetNodeSelector->SetPopUpTitel("Select target image.");
this->m_Controls.targetNodeSelector->SetPopUpHint("Select the target image for the evaluation.");
this->m_Controls.checkAutoSelect->setChecked(true);
this->ConfigureNodePredicates();
connect(m_Controls.pbStart, SIGNAL(clicked()), this, SLOT(OnStartBtnPushed()));
connect(m_Controls.pbCancel, SIGNAL(clicked()), this, SLOT(OnCancelBtnPushed()));
connect(m_Controls.pbStore, SIGNAL(clicked()), this, SLOT(OnStoreBtnPushed()));
connect(m_Controls.evalSettings, SIGNAL(SettingsChanged(mitk::DataNode*)), this, SLOT(OnSettingsChanged(mitk::DataNode*)));
connect(m_Controls.radioSelectedReg, SIGNAL(toggled(bool)), this, SLOT(OnRegSourceChanged()));
connect(m_Controls.comboCenter, SIGNAL(currentIndexChanged(int)), this, SLOT(OnCenterTypeChanged(int)));
connect(m_Controls.manipulationWidget, SIGNAL(RegistrationChanged(map::core::RegistrationBase*)), this, SLOT(OnRegistrationChanged()));
connect(m_Controls.registrationNodeSelector, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkMatchPointRegistrationManipulator::OnNodeSelectionChanged);
connect(m_Controls.movingNodeSelector, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkMatchPointRegistrationManipulator::OnNodeSelectionChanged);
connect(m_Controls.targetNodeSelector, &QmitkAbstractNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkMatchPointRegistrationManipulator::OnNodeSelectionChanged);
this->m_SliceChangeListener.RenderWindowPartActivated(this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN));
connect(&m_SliceChangeListener, SIGNAL(SliceChanged()), this, SLOT(OnSliceChanged()));
m_Controls.radioNewReg->setChecked(true);
m_EvalNode = this->GetDataStorage()->GetNamedNode(HelperNodeName);
this->CheckInputs();
this->StopSession();
this->ConfigureControls();
}
void QmitkMatchPointRegistrationManipulator::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
{
this->m_SliceChangeListener.RenderWindowPartActivated(renderWindowPart);
}
void QmitkMatchPointRegistrationManipulator::RenderWindowPartDeactivated(
mitk::IRenderWindowPart* renderWindowPart)
{
this->m_SliceChangeListener.RenderWindowPartDeactivated(renderWindowPart);
}
void QmitkMatchPointRegistrationManipulator::ConfigureNodePredicates()
{
this->m_Controls.registrationNodeSelector->SetNodePredicate(mitk::MITKRegistrationHelper::RegNodePredicate());
this->m_Controls.movingNodeSelector->SetNodePredicate(mitk::MITKRegistrationHelper::ImageNodePredicate());
this->m_Controls.targetNodeSelector->SetNodePredicate(mitk::MITKRegistrationHelper::ImageNodePredicate());
}
void QmitkMatchPointRegistrationManipulator::CheckInputs()
{
if (!m_activeManipulation)
{
bool autoSelectInput = m_Controls.checkAutoSelect->isChecked() && this->m_SelectedPreRegNode != this->m_Controls.registrationNodeSelector->GetSelectedNode();
this->m_SelectedPreRegNode = this->m_Controls.registrationNodeSelector->GetSelectedNode();
this->m_SelectedMovingNode = this->m_Controls.movingNodeSelector->GetSelectedNode();
this->m_SelectedTargetNode = this->m_Controls.targetNodeSelector->GetSelectedNode();
if (this->m_SelectedPreRegNode.IsNotNull())
{
mitk::MAPRegistrationWrapper* regWrapper = dynamic_cast<mitk::MAPRegistrationWrapper*>(m_SelectedPreRegNode->GetData());
if (regWrapper)
{
this->m_SelectedPreReg = dynamic_cast<MAPRegistrationType*>(regWrapper->GetRegistration());
}
}
if (this->m_SelectedPreRegNode.IsNotNull() && (this->m_SelectedMovingNode.IsNull() || autoSelectInput))
{
mitk::BaseProperty* uidProp = m_SelectedPreRegNode->GetData()->GetProperty(mitk::Prop_RegAlgMovingData);
if (uidProp)
{
//search for the moving node
mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New(mitk::Prop_UID,
uidProp);
mitk::DataNode::Pointer movingNode = this->GetDataStorage()->GetNode(predicate);
if (movingNode.IsNotNull())
{
this->m_SelectedMovingNode = movingNode;
QmitkSingleNodeSelectionWidget::NodeList selection({ movingNode });
this->m_Controls.movingNodeSelector->SetCurrentSelection(selection);
}
}
}
if (this->m_SelectedPreRegNode.IsNotNull() && (this->m_SelectedTargetNode.IsNull() || autoSelectInput))
{
mitk::BaseProperty* uidProp = m_SelectedPreRegNode->GetData()->GetProperty(mitk::Prop_RegAlgTargetData);
if (uidProp)
{
//search for the target node
mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New(mitk::Prop_UID,
uidProp);
mitk::DataNode::Pointer targetNode = this->GetDataStorage()->GetNode(predicate);
if (targetNode.IsNotNull())
{
this->m_SelectedTargetNode = targetNode;
QmitkSingleNodeSelectionWidget::NodeList selection({ targetNode });
this->m_Controls.targetNodeSelector->SetCurrentSelection(selection);
}
}
}
}
}
void QmitkMatchPointRegistrationManipulator::OnRegSourceChanged()
{
this->CheckInputs();
this->ConfigureControls();
}
void QmitkMatchPointRegistrationManipulator::OnNodeSelectionChanged(QList<mitk::DataNode::Pointer> /*nodes*/)
{
this->CheckInputs();
this->ConfigureControls();
}
void QmitkMatchPointRegistrationManipulator::NodeRemoved(const mitk::DataNode* node)
{
if (node == this->m_SelectedMovingNode
|| node == this->m_SelectedTargetNode
|| node == this->m_EvalNode)
{
if (node == this->m_EvalNode)
{
this->m_EvalNode = nullptr;
}
if (this->m_activeManipulation)
{
MITK_INFO << "Stopped current MatchPoint manual registration session, because at least one relevant node was removed from storage.";
}
this->OnCancelBtnPushed();
}
}
void QmitkMatchPointRegistrationManipulator::ConfigureControls()
{
if (!m_activeManipulation)
{
- QString name = "ManuelRegistration";
+ QString name = "ManualRegistration";
if (m_SelectedPreRegNode.IsNotNull())
{
name = QString::fromStdString(m_SelectedPreRegNode->GetName()) + " manual refined";
}
this->m_Controls.lbNewRegName->setText(name);
}
//config settings widget
this->m_Controls.groupReg->setEnabled(!m_activeManipulation);
this->m_Controls.pbStart->setEnabled(this->m_SelectedMovingNode.IsNotNull()
&& this->m_SelectedTargetNode.IsNotNull()
&& !m_activeManipulation
&& (this->m_Controls.radioNewReg->isChecked() || this->m_SelectedPreReg.IsNotNull()));
this->m_Controls.lbNewRegName->setEnabled(m_activeManipulation);
this->m_Controls.checkMapEntity->setEnabled(m_activeManipulation);
this->m_Controls.tabWidget->setEnabled(m_activeManipulation);
this->m_Controls.pbCancel->setEnabled(m_activeManipulation);
this->m_Controls.pbStore->setEnabled(m_activeManipulation);
this->m_Controls.registrationNodeSelector->setEnabled(!m_activeManipulation && this->m_Controls.radioSelectedReg->isChecked());
this->m_Controls.checkAutoSelect->setEnabled(!m_activeManipulation && this->m_Controls.radioSelectedReg->isChecked());
this->m_Controls.movingNodeSelector->setEnabled(!m_activeManipulation);
this->m_Controls.targetNodeSelector->setEnabled(!m_activeManipulation);
}
void QmitkMatchPointRegistrationManipulator::InitSession()
{
if (this->m_Controls.radioNewReg->isChecked())
{ //init to map the image centers
auto movingCenter = m_SelectedMovingNode->GetData()->GetTimeGeometry()->GetCenterInWorld();
auto targetCenter = m_SelectedTargetNode->GetData()->GetTimeGeometry()->GetCenterInWorld();
this->m_Controls.manipulationWidget->Initialize(movingCenter, targetCenter);
}
else
{ //use selected pre registration as baseline
m_Controls.manipulationWidget->Initialize(m_SelectedPreReg);
}
this->m_CurrentRegistration = m_Controls.manipulationWidget->GetInterimRegistration();
this->m_CurrentRegistrationWrapper = mitk::MAPRegistrationWrapper::New(m_CurrentRegistration);
this->m_Controls.comboCenter->setCurrentIndex(0);
this->OnCenterTypeChanged(0);
//reinit view
mitk::RenderingManager::GetInstance()->InitializeViews(m_SelectedTargetNode->GetData()->GetTimeGeometry());
//generate evaluation node
mitk::RegEvaluationObject::Pointer regEval = mitk::RegEvaluationObject::New();
regEval->SetRegistration(this->m_CurrentRegistrationWrapper);
regEval->SetTargetNode(this->m_SelectedTargetNode);
regEval->SetMovingNode(this->m_SelectedMovingNode);
this->m_EvalNode = mitk::DataNode::New();
this->m_EvalNode->SetData(regEval);
mitk::RegEvaluationMapper2D::SetDefaultProperties(this->m_EvalNode);
this->m_EvalNode->SetName(HelperNodeName);
this->m_EvalNode->SetBoolProperty("helper object", true);
this->GetDataStorage()->Add(this->m_EvalNode);
this->m_Controls.evalSettings->SetNode(this->m_EvalNode);
this->m_activeManipulation = true;
}
void QmitkMatchPointRegistrationManipulator::StopSession()
{
this->m_activeManipulation = false;
if (this->m_EvalNode.IsNotNull())
{
this->GetDataStorage()->Remove(this->m_EvalNode);
}
this->m_EvalNode = nullptr;
this->m_CurrentRegistration = nullptr;
this->m_CurrentRegistrationWrapper = nullptr;
m_Controls.manipulationWidget->Initialize();
}
void QmitkMatchPointRegistrationManipulator::OnRegistrationChanged()
{
if (this->m_EvalNode.IsNotNull())
{
this->m_EvalNode->Modified();
}
if (this->m_CurrentRegistrationWrapper.IsNotNull())
{
this->m_CurrentRegistrationWrapper->Modified();
}
auto* renderWindowPart = this->GetRenderWindowPart();
if (nullptr != renderWindowPart)
renderWindowPart->RequestUpdate();
}
void QmitkMatchPointRegistrationManipulator::OnSliceChanged()
{
auto* renderWindowPart = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN);
auto currentSelectedPosition = renderWindowPart->GetSelectedPosition(nullptr);
auto currentTimePoint = renderWindowPart->GetSelectedTimePoint();
if (m_currentSelectedPosition != currentSelectedPosition
|| m_currentSelectedTimePoint != currentTimePoint
|| m_selectedNodeTime > m_currentPositionTime)
{
//the current position has been changed or the selected node has been changed since the last position validation -> check position
m_currentSelectedPosition = currentSelectedPosition;
m_currentSelectedTimePoint = currentTimePoint;
m_currentPositionTime.Modified();
if (this->m_EvalNode.IsNotNull())
{
this->m_EvalNode->SetProperty(mitk::nodeProp_RegEvalCurrentPosition, mitk::Point3dProperty::New(currentSelectedPosition));
}
if (m_activeManipulation && m_Controls.comboCenter->currentIndex() == 2)
{ //update transform with the current position.
m_Controls.manipulationWidget->SetCenterOfRotation(m_currentSelectedPosition);
}
}
}
void QmitkMatchPointRegistrationManipulator::OnSettingsChanged(mitk::DataNode*)
{
auto* renderWindowPart = this->GetRenderWindowPart();
if (nullptr != renderWindowPart)
renderWindowPart->RequestUpdate();
}
void QmitkMatchPointRegistrationManipulator::OnStartBtnPushed()
{
this->InitSession();
this->OnSliceChanged();
auto* renderWindowPart = this->GetRenderWindowPart();
if (nullptr != renderWindowPart)
renderWindowPart->RequestUpdate();
this->CheckInputs();
this->ConfigureControls();
}
void QmitkMatchPointRegistrationManipulator::OnCancelBtnPushed()
{
this->StopSession();
this->CheckInputs();
this->ConfigureControls();
if (this->GetRenderWindowPart())
{
this->GetRenderWindowPart()->RequestUpdate();
}
}
void QmitkMatchPointRegistrationManipulator::OnStoreBtnPushed()
{
map::core::RegistrationBase::Pointer newReg = this->m_Controls.manipulationWidget->GenerateRegistration();
auto newRegWrapper = mitk::MAPRegistrationWrapper::New(newReg);
mitk::DataNode::Pointer spResultRegistrationNode = mitk::generateRegistrationResultNode(
this->m_Controls.lbNewRegName->text().toStdString(), newRegWrapper, "org.mitk::manual_registration",
mitk::EnsureUID(m_SelectedMovingNode->GetData()), mitk::EnsureUID(m_SelectedTargetNode->GetData()));
this->GetDataStorage()->Add(spResultRegistrationNode);
if (m_Controls.checkMapEntity->checkState() == Qt::Checked)
{
QmitkMappingJob* pMapJob = new QmitkMappingJob();
pMapJob->setAutoDelete(true);
pMapJob->m_spInputData = this->m_SelectedMovingNode->GetData();
pMapJob->m_InputDataUID = mitk::EnsureUID(m_SelectedMovingNode->GetData());
pMapJob->m_spRegNode = spResultRegistrationNode;
pMapJob->m_doGeometryRefinement = false;
pMapJob->m_spRefGeometry = this->m_SelectedTargetNode->GetData()->GetGeometry()->Clone().GetPointer();
pMapJob->m_MappedName = this->m_Controls.lbNewRegName->text().toStdString() + std::string(" mapped moving data");
pMapJob->m_allowUndefPixels = true;
pMapJob->m_paddingValue = 100;
pMapJob->m_allowUnregPixels = true;
pMapJob->m_errorValue = 200;
pMapJob->m_InterpolatorLabel = "Linear Interpolation";
pMapJob->m_InterpolatorType = mitk::ImageMappingInterpolator::Linear;
connect(pMapJob, SIGNAL(Error(QString)), this, SLOT(Error(QString)));
connect(pMapJob, SIGNAL(MapResultIsAvailable(mitk::BaseData::Pointer, const QmitkMappingJob*)),
this, SLOT(OnMapResultIsAvailable(mitk::BaseData::Pointer, const QmitkMappingJob*)),
Qt::BlockingQueuedConnection);
QThreadPool* threadPool = QThreadPool::globalInstance();
threadPool->start(pMapJob);
}
this->StopSession();
this->CheckInputs();
this->ConfigureControls();
auto* renderWindowPart = this->GetRenderWindowPart();
if (nullptr != renderWindowPart)
renderWindowPart->RequestUpdate();
}
void QmitkMatchPointRegistrationManipulator::OnMapResultIsAvailable(mitk::BaseData::Pointer spMappedData,
const QmitkMappingJob* job)
{
mitk::DataNode::Pointer spMappedNode = mitk::generateMappedResultNode(job->m_MappedName,
spMappedData, job->GetRegistration()->getRegistrationUID(), job->m_InputDataUID,
job->m_doGeometryRefinement, job->m_InterpolatorLabel);
this->GetDataStorage()->Add(spMappedNode);
auto* renderWindowPart = this->GetRenderWindowPart();
if (nullptr != renderWindowPart)
renderWindowPart->RequestUpdate();
}
void QmitkMatchPointRegistrationManipulator::OnCenterTypeChanged(int index)
{
ConfigureTransformCenter(index);
if (this->m_EvalNode.IsNotNull())
{
this->m_EvalNode->Modified();
}
if (this->m_CurrentRegistrationWrapper.IsNotNull())
{
this->m_CurrentRegistrationWrapper->Modified();
}
auto* renderWindowPart = this->GetRenderWindowPart();
if (nullptr != renderWindowPart)
renderWindowPart->RequestUpdate();
}
void QmitkMatchPointRegistrationManipulator::ConfigureTransformCenter(int centerType)
{
if (centerType == 0)
{ //image center
auto center = m_SelectedMovingNode->GetData()->GetTimeGeometry()->GetCenterInWorld();
m_Controls.manipulationWidget->SetCenterOfRotationIsRelativeToTarget(false);
m_Controls.manipulationWidget->SetCenterOfRotation(center);
}
else if (centerType == 1)
{ //world origin
mitk::Point3D center;
center.Fill(0.0);
m_Controls.manipulationWidget->SetCenterOfRotationIsRelativeToTarget(false);
m_Controls.manipulationWidget->SetCenterOfRotation(center);
}
else
{ //current selected point
m_Controls.manipulationWidget->SetCenterOfRotationIsRelativeToTarget(true);
m_Controls.manipulationWidget->SetCenterOfRotation(m_currentSelectedPosition);
}
}
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/CMakeLists.txt b/Plugins/org.mitk.gui.qt.materialeditor/CMakeLists.txt
deleted file mode 100644
index b8f112a380..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/CMakeLists.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-# The project name must correspond to the directory name of your plug-in
-# and must not contain periods.
-project(org_mitk_gui_qt_materialeditor)
-
-mitk_create_plugin(
- EXPORT_DIRECTIVE MATERIALEDITOR_EXPORTS
- EXPORTED_INCLUDE_SUFFIXES src
- MODULE_DEPENDS MitkQtWidgets
-)
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor.dox b/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor.dox
deleted file mode 100644
index 1a6935a94d..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor.dox
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
-\page org_surfacematerialeditor The Surface Material Editor
-
-\imageMacro{QmitkSurfaceMaterialEditor_Icon.png,"Icon of the Surface Material Editor",2.00}
-
-The Surface Material Editor shows the properties of the selected data that are relevant for the selected shader. These properties can be filtered to find a specific property. The preview window shows the representation of a neutral 3D object with the currently selected settings.
-
-\imageMacro{QmitkSurfaceMaterialEditor_Gui.png,"The Surface Material Editor",10.92}
-
-*/
\ No newline at end of file
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor_Gui.png b/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor_Gui.png
deleted file mode 100644
index 9b81744250..0000000000
Binary files a/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor_Gui.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor_Icon.png b/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor_Icon.png
deleted file mode 100644
index 9a660225a5..0000000000
Binary files a/Plugins/org.mitk.gui.qt.materialeditor/documentation/UserManual/QmitkSurfaceMaterialEditor_Icon.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/documentation/doxygen/modules.dox b/Plugins/org.mitk.gui.qt.materialeditor/documentation/doxygen/modules.dox
deleted file mode 100644
index 34c292bcfe..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/documentation/doxygen/modules.dox
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- \defgroup org_mitk_gui_qt_materialeditor org.mitk.gui.qt.materialeditor
- \ingroup MITKPlugins
-
- \brief Describe your plugin here.
-
-*/
-
-/**
- \defgroup org_mitk_gui_qt_materialeditor_internal Internal
- \ingroup org_mitk_gui_qt_materialeditor
-
- \brief This subcategory includes the internal classes of the org.mitk.gui.qt.materialeditor 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.materialeditor/files.cmake b/Plugins/org.mitk.gui.qt.materialeditor/files.cmake
deleted file mode 100644
index 81413caeb9..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/files.cmake
+++ /dev/null
@@ -1,34 +0,0 @@
-set(SRC_CPP_FILES
-
-)
-
-set(INTERNAL_CPP_FILES
- QmitkMITKSurfaceMaterialEditorView.cpp
- mitkMaterialEditorPluginActivator.cpp
-)
-
-set(UI_FILES
- src/internal/QmitkMITKSurfaceMaterialEditorViewControls.ui
-)
-
-set(MOC_H_FILES
- src/internal/QmitkMITKSurfaceMaterialEditorView.h
- src/internal/mitkMaterialEditorPluginActivator.h
-)
-
-set(CACHED_RESOURCE_FILES
- resources/SurfaceMaterialEditor.png
- plugin.xml
-)
-
-set(QRC_FILES
- resources/QmitkMITKSurfaceMaterialEditorView.qrc
-)
-
-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})
\ No newline at end of file
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.materialeditor/manifest_headers.cmake
deleted file mode 100644
index a76fffae0a..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/manifest_headers.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(Plugin-Name "MITK Material Editor")
-set(Plugin-Version "0.9")
-set(Plugin-Vendor "German Cancer Research Center (DKFZ)")
-set(Plugin-ContactAddress "https://www.mitk.org")
-set(Require-Plugin org.mitk.gui.qt.common)
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/plugin.xml b/Plugins/org.mitk.gui.qt.materialeditor/plugin.xml
deleted file mode 100644
index 2046abdd81..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/plugin.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin>
-
- <extension point="org.blueberry.ui.views">
- <view id="org.mitk.views.mitksurfacematerialeditor"
- name="Surface Material Editor"
- class="QmitkMITKSurfaceMaterialEditorView"
- icon="resources/SurfaceMaterialEditor.png" />
- </extension>
-
-</plugin>
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/resources/QmitkMITKSurfaceMaterialEditorView.qrc b/Plugins/org.mitk.gui.qt.materialeditor/resources/QmitkMITKSurfaceMaterialEditorView.qrc
deleted file mode 100644
index b8caba7494..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/resources/QmitkMITKSurfaceMaterialEditorView.qrc
+++ /dev/null
@@ -1,5 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
- <qresource prefix="/QmitkTemplate">
- <file>SurfaceMaterialEditor.png</file>
- </qresource>
- </RCC>
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/resources/SurfaceMaterialEditor.png b/Plugins/org.mitk.gui.qt.materialeditor/resources/SurfaceMaterialEditor.png
deleted file mode 100644
index 9a660225a5..0000000000
Binary files a/Plugins/org.mitk.gui.qt.materialeditor/resources/SurfaceMaterialEditor.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp
deleted file mode 100644
index c9771ad3a3..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp
+++ /dev/null
@@ -1,240 +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 "QmitkMITKSurfaceMaterialEditorView.h"
-
-#include "mitkBaseRenderer.h"
-#include "mitkNodePredicateDataType.h"
-#include "mitkProperties.h"
-#include "mitkIDataStorageService.h"
-#include "mitkDataNodeObject.h"
-
-#include "berryIEditorPart.h"
-#include "berryIWorkbenchPage.h"
-
-#include "QmitkDataStorageComboBox.h"
-
-#include <vtkSphereSource.h>
-#include <vtkPolyData.h>
-#include <vtkCamera.h>
-#include <vtkRenderer.h>
-#include <vtkTextActor.h>
-#include <vtkRenderer.h>
-#include <vtkTextProperty.h>
-#include <vtkCoordinate.h>
-#include <vtkActor.h>
-#include <vtkProperty.h>
-
-#include <mitkVtkPropRenderer.h>
-#include <mitkVtkLayerController.h>
-
-#include <qmessagebox.h>
-
-#include "mitkStandaloneDataStorage.h"
-
-
-
-const std::string QmitkMITKSurfaceMaterialEditorView::VIEW_ID = "org.mitk.views.mitksurfacematerialeditor";
-
-QmitkMITKSurfaceMaterialEditorView::QmitkMITKSurfaceMaterialEditorView()
-: QmitkAbstractView(),
- m_Controls(nullptr)
-{
- fixedProperties.push_back( "shader" );
- fixedProperties.push_back( "material.representation" );
- fixedProperties.push_back( "color" );
- fixedProperties.push_back( "opacity" );
- fixedProperties.push_back( "material.wireframeLineWidth" );
-
- fixedProperties.push_back( "material.ambientCoefficient" );
- fixedProperties.push_back( "material.diffuseCoefficient" );
- fixedProperties.push_back( "material.ambientColor" );
- fixedProperties.push_back( "material.diffuseColor" );
- fixedProperties.push_back( "material.specularColor" );
- fixedProperties.push_back( "material.specularCoefficient" );
- fixedProperties.push_back( "material.specularPower" );
- fixedProperties.push_back( "material.interpolation" );
-
- shaderProperties.push_back( "shader" );
- shaderProperties.push_back( "material.representation" );
- shaderProperties.push_back( "color" );
- shaderProperties.push_back( "opacity" );
- shaderProperties.push_back( "material.wireframeLineWidth" );
-
- observerAllocated = false;
-}
-
-QmitkMITKSurfaceMaterialEditorView::~QmitkMITKSurfaceMaterialEditorView()
-{
-}
-
-void QmitkMITKSurfaceMaterialEditorView::InitPreviewWindow()
-{
- usedTimer=0;
-
- vtkSphereSource* sphereSource = vtkSphereSource::New();
- sphereSource->SetThetaResolution(25);
- sphereSource->SetPhiResolution(25);
- sphereSource->Update();
-
- vtkPolyData* sphere = sphereSource->GetOutput();
-
- m_Surface = mitk::Surface::New();
- m_Surface->SetVtkPolyData( sphere );
-
- m_DataNode = mitk::DataNode::New();
- m_DataNode->SetData( m_Surface );
-
- m_DataTree = mitk::StandaloneDataStorage::New();
-
- m_DataTree->Add( m_DataNode , (mitk::DataNode *)nullptr );
-
- m_Controls->m_PreviewRenderWindow->GetRenderer()->SetDataStorage( m_DataTree );
- m_Controls->m_PreviewRenderWindow->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D );
-
- sphereSource->Delete();
-}
-
-
-void QmitkMITKSurfaceMaterialEditorView::RefreshPropertiesList()
-{
- mitk::DataNode* SrcND = m_SelectedDataNode;
- mitk::DataNode* DstND = m_DataNode;
-
- mitk::PropertyList* DstPL = DstND->GetPropertyList();
-
-
- m_Controls->m_ShaderPropertyList->SetPropertyList( nullptr );
-
- DstPL->Clear();
-
- if(observerAllocated)
- {
- observerAllocated=false;
- }
-
- if(SrcND)
- {
- mitk::PropertyList* SrcPL = SrcND->GetPropertyList();
-
- std::string shaderState = "fixed";
-
-// if(shaderEnum.IsNotNull())
-// {
-// shaderState = shaderEnum->GetValueAsString();
-
-// itk::MemberCommand<QmitkMITKSurfaceMaterialEditorView>::Pointer propertyModifiedCommand = itk::MemberCommand<QmitkMITKSurfaceMaterialEditorView>::New();
-// propertyModifiedCommand->SetCallbackFunction(this, &QmitkMITKSurfaceMaterialEditorView::shaderEnumChange);
-// observerIndex = shaderEnum->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand);
-// observedProperty = shaderEnum;
-// observerAllocated=true;
-// }
-
- MITK_INFO << "PROPERTIES SCAN BEGIN";
-
- for(mitk::PropertyList::PropertyMap::const_iterator it=SrcPL->GetMap()->begin(); it!=SrcPL->GetMap()->end(); it++)
- {
- std::string name=it->first;
- mitk::BaseProperty *p=it->second;
-
- // MITK_INFO << "property '" << name << "' found";
-
- if(shaderState.compare("fixed")==0)
- {
- if(std::find(fixedProperties.begin(), fixedProperties.end(), name) != fixedProperties.end())
- {
- DstPL->SetProperty(name,p);
- }
- }
- else
- {
- //if(std::find(shaderProperties.begin(), shaderProperties.end(), name) != shaderProperties.end())
- {
- DstPL->SetProperty(name,p);
- }
- }
- }
-
- MITK_INFO << "PROPERTIES SCAN END";
- }
-
- m_Controls->m_ShaderPropertyList->SetPropertyList( DstPL );
- //m_Controls->m_PreviewRenderWindow->GetRenderer()->GetVtkRenderer()->ResetCameraClippingRange();
-}
-
-void QmitkMITKSurfaceMaterialEditorView::CreateQtPartControl(QWidget *parent)
-{
- if (!m_Controls)
- {
- // create GUI widgets
- m_Controls = new Ui::QmitkMITKSurfaceMaterialEditorViewControls;
- m_Controls->setupUi(parent);
- this->CreateConnections();
-
- InitPreviewWindow();
- RefreshPropertiesList();
-
- }
-}
-
-void QmitkMITKSurfaceMaterialEditorView::SetFocus()
-{
- m_Controls->m_ShaderPropertyList->setFocus();
-}
-
-void QmitkMITKSurfaceMaterialEditorView::CreateConnections()
-{
-}
-
-void QmitkMITKSurfaceMaterialEditorView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer>& nodes)
-{
- if(!nodes.empty())
- {
- m_SelectedDataNode = nodes.at(0);
- MITK_INFO << "Node '" << m_SelectedDataNode->GetName() << "' selected";
- SurfaceSelected();
- }
-}
-
-void QmitkMITKSurfaceMaterialEditorView::SurfaceSelected()
-{
- postRefresh();
-}
-
-void QmitkMITKSurfaceMaterialEditorView::shaderEnumChange(const itk::Object * /*caller*/, const itk::EventObject & /*event*/)
-{
- postRefresh();
-}
-
-void QmitkMITKSurfaceMaterialEditorView::postRefresh()
-{
- if(usedTimer)
- return;
-
- usedTimer=startTimer(0);
-}
-
-void QmitkMITKSurfaceMaterialEditorView::timerEvent( QTimerEvent *e )
-{
- if(usedTimer!=e->timerId())
- {
- MITK_ERROR << "INTERNAL ERROR: usedTimer[" << usedTimer << "] != timerId[" << e->timerId() << "]";
- }
-
- if(usedTimer)
- {
- killTimer(usedTimer);
- usedTimer=0;
- }
-
- RefreshPropertiesList();
-}
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h
deleted file mode 100644
index e6429f6276..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h
+++ /dev/null
@@ -1,108 +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 QmitkMITKSurfaceMaterialEditorView_h
-#define QmitkMITKSurfaceMaterialEditorView_h
-
-#include <QmitkAbstractView.h>
-#include <berryIStructuredSelection.h>
-#include <string>
-
-#include "ui_QmitkMITKSurfaceMaterialEditorViewControls.h"
-
-/*
-#include <QtCore/QVariant>
-#include <QtGui/QAction>
-#include <QtGui/QApplication>
-#include <QtGui/QButtonGroup>
-#include <QtGui/QVBoxLayout>
-#include <QtGui/QWidget>
-#include "QtGui/QMenubarUpdatedEvent"
-*/
-
-#include "QmitkRenderWindow.h"
-#include "mitkCommon.h"
-#include "mitkDataStorage.h"
-#include "mitkDataNode.h"
-#include "mitkSurface.h"
-#include "vtkRenderer.h"
-#include "vtkTextActor.h"
-
-/*!
-
- \brief QmitkMITKSurfaceMaterialEditorView
-*/
-class QmitkMITKSurfaceMaterialEditorView : public QmitkAbstractView
-{
-
- // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
- Q_OBJECT
-
- public:
-
- static const std::string VIEW_ID;
-
- QmitkMITKSurfaceMaterialEditorView();
- ~QmitkMITKSurfaceMaterialEditorView() override;
-
- void CreateQtPartControl(QWidget *parent) override;
-
- /// \brief Creation of the connections of main and control widget
- virtual void CreateConnections();
-
- ///
- /// Sets the focus to an internal widget.
- ///
- void SetFocus() override;
-
- void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList<mitk::DataNode::Pointer>& nodes) override;
-
-protected slots:
-
- void SurfaceSelected();
-
-protected:
-
- Ui::QmitkMITKSurfaceMaterialEditorViewControls* m_Controls;
-
-private:
-
- mitk::Surface::Pointer m_Surface;
- mitk::DataStorage::Pointer m_DataTree;
- mitk::DataNode::Pointer m_DataNode;
- mitk::DataNode::Pointer m_SelectedDataNode;
-
- std::list<std::string> fixedProperties;
- std::list<std::string> shaderProperties;
-
- unsigned long observerIndex;
- bool observerAllocated;
-
- void InitPreviewWindow();
-
- int usedTimer;
-
- void timerEvent( QTimerEvent *e ) override;
-
- void RefreshPropertiesList();
-
- void postRefresh();
-
- void shaderEnumChange(const itk::Object *caller, const itk::EventObject &event);
-
- berry::IStructuredSelection::ConstPointer m_CurrentSelection;
-};
-
-
-
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorViewControls.ui b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorViewControls.ui
deleted file mode 100644
index ffd4094926..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorViewControls.ui
+++ /dev/null
@@ -1,74 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkMITKSurfaceMaterialEditorViewControls</class>
- <widget class="QWidget" name="QmitkMITKSurfaceMaterialEditorViewControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>240</width>
- <height>794</height>
- </rect>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="windowTitle">
- <string>QmitkTemplate</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QGroupBox" name="groupBox_Preview">
- <property name="title">
- <string>Preview</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_3">
- <item>
- <widget class="QmitkRenderWindow" name="m_PreviewRenderWindow">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="groupBox_ShaderSelect">
- <property name="title">
- <string>Properties</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_6">
- <item>
- <widget class="QmitkPropertiesTableEditor" name="m_ShaderPropertyList"/>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <layoutdefault spacing="6" margin="11"/>
- <customwidgets>
- <customwidget>
- <class>QmitkRenderWindow</class>
- <extends>QListView</extends>
- <header>QmitkRenderWindow.h</header>
- </customwidget>
- <customwidget>
- <class>QmitkPropertiesTableEditor</class>
- <extends>QListView</extends>
- <header>QmitkPropertiesTableEditor.h</header>
- </customwidget>
- </customwidgets>
- <includes>
- <include location="local">QmitkDataStorageComboBox.h</include>
- </includes>
- <resources/>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.cpp b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.cpp
deleted file mode 100644
index 48baa722c6..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*============================================================================
-
-The Medical Imaging Interaction Toolkit (MITK)
-
-Copyright (c) German Cancer Research Center (DKFZ)
-All rights reserved.
-
-Use of this source code is governed by a 3-clause BSD license that can be
-found in the LICENSE file.
-
-============================================================================*/
-
-#include "mitkMaterialEditorPluginActivator.h"
-#include "QmitkMITKSurfaceMaterialEditorView.h"
-
-namespace mitk {
-
- void MaterialEditorPluginActivator::start(ctkPluginContext* context)
- {
- BERRY_REGISTER_EXTENSION_CLASS(QmitkMITKSurfaceMaterialEditorView, context)
- }
-
- void MaterialEditorPluginActivator::stop(ctkPluginContext* context)
- {
- Q_UNUSED(context)
- }
-
-}
diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.h b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.h
deleted file mode 100644
index 49fb414956..0000000000
--- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/mitkMaterialEditorPluginActivator.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 mitkMaterialEditorPluginActivator_h
-#define mitkMaterialEditorPluginActivator_h
-
-#include <ctkPluginActivator.h>
-
-namespace mitk {
-
- class MaterialEditorPluginActivator :
- public QObject, public ctkPluginActivator
- {
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_materialeditor")
- Q_INTERFACES(ctkPluginActivator)
-
- public:
-
- void start(ctkPluginContext* context) override;
- void stop(ctkPluginContext* context) override;
-
- }; // MaterialEditorPluginActivator
-
-}
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp
index 9a32cb1f47..f0df3dcc23 100644
--- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp
+++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp
@@ -1,820 +1,821 @@
/*============================================================================
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 "QmitkMeasurementView.h"
#include <QAction>
+#include <QActionGroup>
#include <QApplication>
#include <QClipboard>
#include <QGridLayout>
#include <QToolBar>
#include <QTextBrowser>
#include <QCheckBox>
#include <QGroupBox>
#include <mitkCoreServices.h>
#include <mitkIPropertyFilters.h>
#include <mitkPropertyFilter.h>
#include <mitkVtkLayerController.h>
#include <mitkPlanarCircle.h>
#include <mitkPlanarEllipse.h>
#include <mitkPlanarPolygon.h>
#include <mitkPlanarAngle.h>
#include <mitkPlanarRectangle.h>
#include <mitkPlanarLine.h>
#include <mitkPlanarCross.h>
#include <mitkPlanarFourPointAngle.h>
#include <mitkPlanarDoubleEllipse.h>
#include <mitkPlanarBezierCurve.h>
#include <mitkPlanarSubdivisionPolygon.h>
#include <mitkPlanarFigureInteractor.h>
#include <mitkPlaneGeometry.h>
#include <mitkILinkedRenderWindowPart.h>
#include <mitkImage.h>
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateProperty.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateNot.h>
#include <QmitkRenderWindow.h>
#include <QmitkSingleNodeSelectionWidget.h>
#include "ctkDoubleSpinBox.h"
#include "mitkPluginActivator.h"
#include "usModuleRegistry.h"
#include "usGetModuleContext.h"
#include "usModuleContext.h"
#include <usModuleInitialization.h>
US_INITIALIZE_MODULE
struct QmitkPlanarFigureData
{
QmitkPlanarFigureData()
: m_EndPlacementObserverTag(0),
m_SelectObserverTag(0),
m_StartInteractionObserverTag(0),
m_EndInteractionObserverTag(0),
m_DuringInteractionObserverTag(0)
{
}
mitk::PlanarFigure::Pointer m_Figure;
unsigned int m_EndPlacementObserverTag;
unsigned int m_SelectObserverTag;
unsigned int m_StartInteractionObserverTag;
unsigned int m_EndInteractionObserverTag;
unsigned int m_DuringInteractionObserverTag;
};
struct QmitkMeasurementViewData
{
QmitkMeasurementViewData()
: m_LineCounter(0),
m_PathCounter(0),
m_AngleCounter(0),
m_FourPointAngleCounter(0),
m_CircleCounter(0),
m_EllipseCounter(0),
m_DoubleEllipseCounter(0),
m_RectangleCounter(0),
m_PolygonCounter(0),
m_BezierCurveCounter(0),
m_SubdivisionPolygonCounter(0),
m_UnintializedPlanarFigure(false),
m_Parent(nullptr),
m_SingleNodeSelectionWidget(nullptr),
m_DrawLine(nullptr),
m_DrawPath(nullptr),
m_DrawAngle(nullptr),
m_DrawFourPointAngle(nullptr),
m_DrawRectangle(nullptr),
m_DrawPolygon(nullptr),
m_DrawCircle(nullptr),
m_DrawEllipse(nullptr),
m_DrawDoubleEllipse(nullptr),
m_DrawBezierCurve(nullptr),
m_DrawSubdivisionPolygon(nullptr),
m_DrawActionsToolBar(nullptr),
m_DrawActionsGroup(nullptr),
m_SelectedPlanarFiguresText(nullptr),
m_CopyToClipboard(nullptr),
m_Layout(nullptr),
m_Radius(nullptr),
m_Thickness(nullptr),
m_FixedParameterBox(nullptr)
{
}
unsigned int m_LineCounter;
unsigned int m_PathCounter;
unsigned int m_AngleCounter;
unsigned int m_FourPointAngleCounter;
unsigned int m_CircleCounter;
unsigned int m_EllipseCounter;
unsigned int m_DoubleEllipseCounter;
unsigned int m_RectangleCounter;
unsigned int m_PolygonCounter;
unsigned int m_BezierCurveCounter;
unsigned int m_SubdivisionPolygonCounter;
QList<mitk::DataNode::Pointer> m_CurrentSelection;
std::map<mitk::DataNode::Pointer, QmitkPlanarFigureData> m_DataNodeToPlanarFigureData;
mitk::DataNode::Pointer m_SelectedImageNode;
bool m_UnintializedPlanarFigure;
QWidget* m_Parent;
QLabel* m_SelectedImageLabel;
QmitkSingleNodeSelectionWidget* m_SingleNodeSelectionWidget;
QAction* m_DrawLine;
QAction* m_DrawPath;
QAction* m_DrawAngle;
QAction* m_DrawFourPointAngle;
QAction* m_DrawRectangle;
QAction* m_DrawPolygon;
QAction* m_DrawCircle;
QAction* m_DrawEllipse;
QAction* m_DrawDoubleEllipse;
QAction* m_DrawBezierCurve;
QAction* m_DrawSubdivisionPolygon;
QToolBar* m_DrawActionsToolBar;
QActionGroup* m_DrawActionsGroup;
QTextBrowser* m_SelectedPlanarFiguresText;
QPushButton* m_CopyToClipboard;
QGridLayout* m_Layout;
ctkDoubleSpinBox* m_Radius;
ctkDoubleSpinBox* m_Thickness;
QGroupBox* m_FixedParameterBox;
};
const std::string QmitkMeasurementView::VIEW_ID = "org.mitk.views.measurement";
QmitkMeasurementView::QmitkMeasurementView()
: d(new QmitkMeasurementViewData)
{
}
QmitkMeasurementView::~QmitkMeasurementView()
{
auto planarFigures = this->GetAllPlanarFigures();
for (auto it = planarFigures->Begin(); it != planarFigures->End(); ++it)
this->NodeRemoved(it.Value());
delete d;
}
void QmitkMeasurementView::CreateQtPartControl(QWidget* parent)
{
d->m_Parent = parent;
d->m_SingleNodeSelectionWidget = new QmitkSingleNodeSelectionWidget();
d->m_SingleNodeSelectionWidget->SetDataStorage(GetDataStorage());
d->m_SingleNodeSelectionWidget->SetNodePredicate(mitk::NodePredicateAnd::New(
mitk::TNodePredicateDataType<mitk::Image>::New(),
mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))));
d->m_SingleNodeSelectionWidget->SetSelectionIsOptional(true);
d->m_SingleNodeSelectionWidget->SetEmptyInfo(QStringLiteral("Please select a reference image"));
d->m_SingleNodeSelectionWidget->SetPopUpTitel(QStringLiteral("Select a reference image"));
d->m_DrawActionsToolBar = new QToolBar;
d->m_DrawActionsGroup = new QActionGroup(this);
d->m_DrawActionsGroup->setExclusive(true);
auto* currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/line.png"), tr("Draw Line"));
currentAction->setCheckable(true);
d->m_DrawLine = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/path.png"), tr("Draw Path"));
currentAction->setCheckable(true);
d->m_DrawPath = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/angle.png"), tr("Draw Angle"));
currentAction->setCheckable(true);
d->m_DrawAngle = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/four-point-angle.png"), tr("Draw Four Point Angle"));
currentAction->setCheckable(true);
d->m_DrawFourPointAngle = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/circle.png"), tr("Draw Circle"));
currentAction->setCheckable(true);
d->m_DrawCircle = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/ellipse.png"), tr("Draw Ellipse"));
currentAction->setCheckable(true);
d->m_DrawEllipse = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/doubleellipse.png"), tr("Draw Double Ellipse"));
currentAction->setCheckable(true);
d->m_DrawDoubleEllipse = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/rectangle.png"), tr("Draw Rectangle"));
currentAction->setCheckable(true);
d->m_DrawRectangle = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/polygon.png"), tr("Draw Polygon"));
currentAction->setCheckable(true);
d->m_DrawPolygon = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/beziercurve.png"), tr("Draw Bezier Curve"));
currentAction->setCheckable(true);
d->m_DrawBezierCurve = currentAction;
currentAction = d->m_DrawActionsToolBar->addAction(QIcon(":/measurement/subdivisionpolygon.png"), tr("Draw Subdivision Polygon"));
currentAction->setCheckable(true);
d->m_DrawSubdivisionPolygon = currentAction;
d->m_DrawActionsToolBar->setEnabled(false);
// fixed parameter section
auto fixedLayout = new QGridLayout();
d->m_FixedParameterBox = new QGroupBox();
d->m_FixedParameterBox->setCheckable(true);
d->m_FixedParameterBox->setChecked(false);
d->m_FixedParameterBox->setEnabled(false);
d->m_FixedParameterBox->setTitle("Fixed sized circle/double ellipse");
d->m_FixedParameterBox->setToolTip("If activated, circles and double ellipses (as rings) figures will always be created with the set parameters as fixed size.");
d->m_FixedParameterBox->setAlignment(Qt::AlignLeft);
auto labelRadius1 = new QLabel(QString("Radius"));
d->m_Radius = new ctkDoubleSpinBox();
d->m_Radius->setMinimum(0);
d->m_Radius->setValue(10);
d->m_Radius->setSuffix(" mm");
d->m_Radius->setAlignment(Qt::AlignLeft);
d->m_Radius->setToolTip("Sets the radius for following planar figures: circle, double ellipse (as ring).");
auto labelThickness = new QLabel(QString("Thickness"));
d->m_Thickness = new ctkDoubleSpinBox();
d->m_Thickness->setMinimum(0);
d->m_Thickness->setMaximum(10);
d->m_Thickness->setValue(5);
d->m_Thickness->setSuffix(" mm");
d->m_Thickness->setAlignment(Qt::AlignLeft);
d->m_Thickness->setToolTip("Sets the thickness for following planar figures: double ellipse (as ring).");
fixedLayout->addWidget(labelRadius1,0,0);
fixedLayout->addWidget(d->m_Radius,0,1);
fixedLayout->addWidget(labelThickness,1,0);
fixedLayout->addWidget(d->m_Thickness,1,1);
d->m_FixedParameterBox->setLayout(fixedLayout);
// planar figure details text
d->m_SelectedPlanarFiguresText = new QTextBrowser;
// copy to clipboard button
d->m_CopyToClipboard = new QPushButton(tr("Copy to Clipboard"));
d->m_SelectedImageLabel = new QLabel("Selected Image");
d->m_Layout = new QGridLayout;
d->m_Layout->addWidget(d->m_SelectedImageLabel, 0, 0);
d->m_Layout->addWidget(d->m_SingleNodeSelectionWidget, 0, 1, 1, 1);
d->m_Layout->addWidget(d->m_DrawActionsToolBar, 1, 0, 1, 2);
d->m_Layout->addWidget(d->m_FixedParameterBox, 2, 0, 1, 2);
d->m_Layout->addWidget(d->m_SelectedPlanarFiguresText, 3, 0, 1, 2);
d->m_Layout->addWidget(d->m_CopyToClipboard, 4, 0, 1, 2);
d->m_Parent->setLayout(d->m_Layout);
this->CreateConnections();
this->AddAllInteractors();
// placed after CreateConnections to trigger update of the current selection
d->m_SingleNodeSelectionWidget->SetAutoSelectNewNodes(true);
}
void QmitkMeasurementView::CreateConnections()
{
connect(d->m_SingleNodeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged,
this, &QmitkMeasurementView::OnCurrentSelectionChanged);
connect(d->m_DrawLine, SIGNAL(triggered(bool)), this, SLOT(OnDrawLineTriggered(bool)));
connect(d->m_DrawPath, SIGNAL(triggered(bool)), this, SLOT(OnDrawPathTriggered(bool)));
connect(d->m_DrawAngle, SIGNAL(triggered(bool)), this, SLOT(OnDrawAngleTriggered(bool)));
connect(d->m_DrawFourPointAngle, SIGNAL(triggered(bool)), this, SLOT(OnDrawFourPointAngleTriggered(bool)));
connect(d->m_DrawCircle, SIGNAL(triggered(bool)), this, SLOT(OnDrawCircleTriggered(bool)));
connect(d->m_DrawEllipse, SIGNAL(triggered(bool)), this, SLOT(OnDrawEllipseTriggered(bool)));
connect(d->m_DrawDoubleEllipse, SIGNAL(triggered(bool)), this, SLOT(OnDrawDoubleEllipseTriggered(bool)));
connect(d->m_DrawRectangle, SIGNAL(triggered(bool)), this, SLOT(OnDrawRectangleTriggered(bool)));
connect(d->m_DrawPolygon, SIGNAL(triggered(bool)), this, SLOT(OnDrawPolygonTriggered(bool)));
connect(d->m_DrawBezierCurve, SIGNAL(triggered(bool)), this, SLOT(OnDrawBezierCurveTriggered(bool)));
connect(d->m_DrawSubdivisionPolygon, SIGNAL(triggered(bool)), this, SLOT(OnDrawSubdivisionPolygonTriggered(bool)));
connect(d->m_CopyToClipboard, SIGNAL(clicked(bool)), this, SLOT(OnCopyToClipboard(bool)));
connect(d->m_Radius, QOverload<double>::of(&ctkDoubleSpinBox::valueChanged), d->m_Thickness, &ctkDoubleSpinBox::setMaximum);
}
void QmitkMeasurementView::OnCurrentSelectionChanged(QList<mitk::DataNode::Pointer> nodes)
{
if (nodes.empty() || nodes.front().IsNull())
{
d->m_SelectedImageNode = nullptr;
d->m_DrawActionsToolBar->setEnabled(false);
d->m_FixedParameterBox->setEnabled(false);
}
else
{
d->m_SelectedImageNode = nodes.front();
d->m_DrawActionsToolBar->setEnabled(true);
d->m_FixedParameterBox->setEnabled(true);
}
}
void QmitkMeasurementView::NodeAdded(const mitk::DataNode* node)
{
// add observer for selection in renderwindow
mitk::PlanarFigure::Pointer planarFigure = dynamic_cast<mitk::PlanarFigure*>(node->GetData());
auto isPositionMarker = false;
node->GetBoolProperty("isContourMarker", isPositionMarker);
if (planarFigure.IsNotNull() && !isPositionMarker)
{
auto nonConstNode = const_cast<mitk::DataNode*>(node);
mitk::PlanarFigureInteractor::Pointer interactor = dynamic_cast<mitk::PlanarFigureInteractor*>(node->GetDataInteractor().GetPointer());
if (interactor.IsNull())
{
interactor = mitk::PlanarFigureInteractor::New();
auto planarFigureModule = us::ModuleRegistry::GetModule("MitkPlanarFigure");
interactor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule);
interactor->SetEventConfig("PlanarFigureConfig.xml", planarFigureModule);
}
interactor->SetDataNode(nonConstNode);
QmitkPlanarFigureData data;
data.m_Figure = planarFigure;
typedef itk::SimpleMemberCommand<QmitkMeasurementView> SimpleCommandType;
typedef itk::MemberCommand<QmitkMeasurementView> MemberCommandType;
// add observer for event when figure has been placed
auto initializationCommand = SimpleCommandType::New();
initializationCommand->SetCallbackFunction(this, &QmitkMeasurementView::PlanarFigureInitialized);
data.m_EndPlacementObserverTag = planarFigure->AddObserver(mitk::EndPlacementPlanarFigureEvent(), initializationCommand);
// add observer for event when figure is picked (selected)
auto selectCommand = MemberCommandType::New();
selectCommand->SetCallbackFunction(this, &QmitkMeasurementView::PlanarFigureSelected);
data.m_SelectObserverTag = planarFigure->AddObserver(mitk::SelectPlanarFigureEvent(), selectCommand);
// add observer for event during interaction when a point is moved
auto duringInteractionCommand = SimpleCommandType::New();
duringInteractionCommand->SetCallbackFunction(this, &QmitkMeasurementView::UpdateMeasurementText);
data.m_DuringInteractionObserverTag = planarFigure->AddObserver(mitk::PointMovedPlanarFigureEvent(), duringInteractionCommand);
// adding to the map of tracked planarfigures
d->m_DataNodeToPlanarFigureData[nonConstNode] = data;
}
}
void QmitkMeasurementView::NodeChanged(const mitk::DataNode* node)
{
auto it = std::find(d->m_CurrentSelection.begin(), d->m_CurrentSelection.end(), node);
if (it != d->m_CurrentSelection.end())
{
this->UpdateMeasurementText();
}
}
void QmitkMeasurementView::NodeRemoved(const mitk::DataNode* node)
{
auto nonConstNode = const_cast<mitk::DataNode*>(node);
auto it = d->m_DataNodeToPlanarFigureData.find(nonConstNode);
auto isFigureFinished = false;
auto isPlaced = false;
if (it != d->m_DataNodeToPlanarFigureData.end())
{
QmitkPlanarFigureData& data = it->second;
data.m_Figure->RemoveObserver(data.m_EndPlacementObserverTag);
data.m_Figure->RemoveObserver(data.m_SelectObserverTag);
data.m_Figure->RemoveObserver(data.m_StartInteractionObserverTag);
data.m_Figure->RemoveObserver(data.m_EndInteractionObserverTag);
data.m_Figure->RemoveObserver(data.m_DuringInteractionObserverTag);
isFigureFinished = data.m_Figure->GetPropertyList()->GetBoolProperty("initiallyplaced", isPlaced);
if (!isFigureFinished) // if the property does not yet exist or is false, drop the datanode
this->PlanarFigureInitialized(); // normally called when a figure is finished, to reset all buttons
d->m_DataNodeToPlanarFigureData.erase( it );
}
if (nonConstNode != nullptr)
nonConstNode->SetDataInteractor(nullptr);
auto isPlanarFigure = mitk::TNodePredicateDataType<mitk::PlanarFigure>::New();
auto nodes = this->GetDataStorage()->GetDerivations(node, isPlanarFigure);
for (unsigned int x = 0; x < nodes->size(); ++x)
{
mitk::PlanarFigure::Pointer planarFigure = dynamic_cast<mitk::PlanarFigure*>(nodes->at(x)->GetData());
if (planarFigure.IsNotNull())
{
isFigureFinished = planarFigure->GetPropertyList()->GetBoolProperty("initiallyplaced",isPlaced);
if (!isFigureFinished) // if the property does not yet exist or is false, drop the datanode
{
this->GetDataStorage()->Remove(nodes->at(x));
if (!d->m_DataNodeToPlanarFigureData.empty())
{
it = d->m_DataNodeToPlanarFigureData.find(nodes->at(x));
if (it != d->m_DataNodeToPlanarFigureData.end())
{
d->m_DataNodeToPlanarFigureData.erase(it);
this->PlanarFigureInitialized(); // normally called when a figure is finished, to reset all buttons
}
}
}
}
}
}
void QmitkMeasurementView::PlanarFigureSelected(itk::Object* object, const itk::EventObject&)
{
d->m_CurrentSelection.clear();
auto lambda = [&object](const std::pair<mitk::DataNode::Pointer, QmitkPlanarFigureData>& element)
{
return element.second.m_Figure == object;
};
auto it = std::find_if(d->m_DataNodeToPlanarFigureData.begin(), d->m_DataNodeToPlanarFigureData.end(), lambda);
if (it != d->m_DataNodeToPlanarFigureData.end())
{
d->m_CurrentSelection.push_back(it->first);
}
this->UpdateMeasurementText();
this->RequestRenderWindowUpdate();
}
void QmitkMeasurementView::PlanarFigureInitialized()
{
d->m_UnintializedPlanarFigure = false;
d->m_DrawActionsToolBar->setEnabled(true);
d->m_DrawLine->setChecked(false);
d->m_DrawPath->setChecked(false);
d->m_DrawAngle->setChecked(false);
d->m_DrawFourPointAngle->setChecked(false);
d->m_DrawCircle->setChecked(false);
d->m_DrawEllipse->setChecked(false);
d->m_DrawDoubleEllipse->setChecked(false);
d->m_DrawRectangle->setChecked(false);
d->m_DrawPolygon->setChecked(false);
d->m_DrawBezierCurve->setChecked(false);
d->m_DrawSubdivisionPolygon->setChecked(false);
}
void QmitkMeasurementView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& nodes)
{
d->m_CurrentSelection = nodes;
this->UpdateMeasurementText();
// bug 16600: deselecting all planarfigures by clicking on datamanager when no node is selected
if (d->m_CurrentSelection.size() == 0)
{
auto isPlanarFigure = mitk::TNodePredicateDataType<mitk::PlanarFigure>::New();
auto planarFigures = this->GetDataStorage()->GetSubset(isPlanarFigure);
// setting all planar figures which are not helper objects not selected
for (mitk::DataStorage::SetOfObjects::ConstIterator it = planarFigures->Begin(); it != planarFigures->End(); ++it)
{
auto node = it.Value();
auto isHelperObject = false;
node->GetBoolProperty("helper object", isHelperObject);
if (!isHelperObject)
node->SetSelected(false);
}
}
for (int i = d->m_CurrentSelection.size() - 1; i >= 0; --i)
{
auto node = d->m_CurrentSelection[i];
mitk::PlanarFigure::Pointer planarFigure = dynamic_cast<mitk::PlanarFigure*>(node->GetData());
// the last selected planar figure
if (planarFigure.IsNotNull() && planarFigure->GetPlaneGeometry())
{
auto planarFigureInitializedWindow = false;
auto linkedRenderWindow = dynamic_cast<mitk::ILinkedRenderWindowPart*>(this->GetRenderWindowPart());
QmitkRenderWindow* selectedRenderWindow;
if (!linkedRenderWindow)
return;
auto axialRenderWindow = linkedRenderWindow->GetQmitkRenderWindow("axial");
auto sagittalRenderWindow = linkedRenderWindow->GetQmitkRenderWindow("sagittal");
auto coronalRenderWindow = linkedRenderWindow->GetQmitkRenderWindow("coronal");
auto threeDimRenderWindow = linkedRenderWindow->GetQmitkRenderWindow("3d");
if (node->GetBoolProperty("planarFigureInitializedWindow", planarFigureInitializedWindow, axialRenderWindow->GetRenderer()))
{
selectedRenderWindow = axialRenderWindow;
}
else if (node->GetBoolProperty("planarFigureInitializedWindow", planarFigureInitializedWindow, sagittalRenderWindow->GetRenderer()))
{
selectedRenderWindow = sagittalRenderWindow;
}
else if (node->GetBoolProperty("planarFigureInitializedWindow", planarFigureInitializedWindow, coronalRenderWindow->GetRenderer()))
{
selectedRenderWindow = coronalRenderWindow;
}
else if (node->GetBoolProperty("planarFigureInitializedWindow", planarFigureInitializedWindow, threeDimRenderWindow->GetRenderer()))
{
selectedRenderWindow = threeDimRenderWindow;
}
else
{
selectedRenderWindow = nullptr;
}
auto planeGeometry = dynamic_cast<const mitk::PlaneGeometry*>(planarFigure->GetPlaneGeometry());
auto normal = planeGeometry->GetNormalVnl();
mitk::PlaneGeometry::ConstPointer axialPlane = axialRenderWindow->GetRenderer()->GetCurrentWorldPlaneGeometry();
auto axialNormal = axialPlane->GetNormalVnl();
mitk::PlaneGeometry::ConstPointer sagittalPlane = sagittalRenderWindow->GetRenderer()->GetCurrentWorldPlaneGeometry();
auto sagittalNormal = sagittalPlane->GetNormalVnl();
mitk::PlaneGeometry::ConstPointer coronalPlane = coronalRenderWindow->GetRenderer()->GetCurrentWorldPlaneGeometry();
auto coronalNormal = coronalPlane->GetNormalVnl();
normal[0] = fabs(normal[0]);
normal[1] = fabs(normal[1]);
normal[2] = fabs(normal[2]);
axialNormal[0] = fabs(axialNormal[0]);
axialNormal[1] = fabs(axialNormal[1]);
axialNormal[2] = fabs(axialNormal[2]);
sagittalNormal[0] = fabs(sagittalNormal[0]);
sagittalNormal[1] = fabs(sagittalNormal[1]);
sagittalNormal[2] = fabs(sagittalNormal[2]);
coronalNormal[0] = fabs(coronalNormal[0]);
coronalNormal[1] = fabs(coronalNormal[1]);
coronalNormal[2] = fabs(coronalNormal[2]);
auto ang1 = angle(normal, axialNormal);
auto ang2 = angle(normal, sagittalNormal);
auto ang3 = angle(normal, coronalNormal);
if (ang1 < ang2 && ang1 < ang3)
{
selectedRenderWindow = axialRenderWindow;
}
else
{
if (ang2 < ang3)
{
selectedRenderWindow = sagittalRenderWindow;
}
else
{
selectedRenderWindow = coronalRenderWindow;
}
}
// re-orient view
if (selectedRenderWindow)
selectedRenderWindow->GetSliceNavigationController()->ReorientSlices(planeGeometry->GetOrigin(), planeGeometry->GetNormal());
}
break;
}
this->RequestRenderWindowUpdate();
}
void QmitkMeasurementView::OnDrawLineTriggered(bool)
{
this->AddFigureToDataStorage(
mitk::PlanarLine::New(),
QString("Line%1").arg(++d->m_LineCounter));
}
void QmitkMeasurementView::OnDrawPathTriggered(bool)
{
mitk::CoreServicePointer<mitk::IPropertyFilters> propertyFilters(mitk::CoreServices::GetPropertyFilters());
mitk::PropertyFilter filter;
filter.AddEntry("ClosedPlanarPolygon", mitk::PropertyFilter::Blacklist);
propertyFilters->AddFilter(filter, "PlanarPolygon");
mitk::PlanarPolygon::Pointer planarFigure = mitk::PlanarPolygon::New();
planarFigure->ClosedOff();
auto node = this->AddFigureToDataStorage(
planarFigure,
QString("Path%1").arg(++d->m_PathCounter));
node->SetProperty("ClosedPlanarPolygon", mitk::BoolProperty::New(false));
node->SetProperty("planarfigure.isextendable", mitk::BoolProperty::New(true));
}
void QmitkMeasurementView::OnDrawAngleTriggered(bool)
{
this->AddFigureToDataStorage(
mitk::PlanarAngle::New(),
QString("Angle%1").arg(++d->m_AngleCounter));
}
void QmitkMeasurementView::OnDrawFourPointAngleTriggered(bool)
{
this->AddFigureToDataStorage(
mitk::PlanarFourPointAngle::New(),
QString("Four Point Angle%1").arg(++d->m_FourPointAngleCounter));
}
void QmitkMeasurementView::OnDrawCircleTriggered(bool)
{
auto circle = (d->m_FixedParameterBox->isChecked()) ? mitk::PlanarCircle::New(d->m_Radius->value()) : mitk::PlanarCircle::New();
this->AddFigureToDataStorage(circle, QString("Circle%1").arg(++d->m_CircleCounter));
}
void QmitkMeasurementView::OnDrawEllipseTriggered(bool)
{
this->AddFigureToDataStorage(
mitk::PlanarEllipse::New(),
QString("Ellipse%1").arg(++d->m_EllipseCounter));
}
void QmitkMeasurementView::OnDrawDoubleEllipseTriggered(bool)
{
auto ellipse = (d->m_FixedParameterBox->isChecked()) ? mitk::PlanarDoubleEllipse::New(d->m_Radius->value(),d->m_Thickness->value()) : mitk::PlanarDoubleEllipse::New();
this->AddFigureToDataStorage(ellipse, QString("DoubleEllipse%1").arg(++d->m_DoubleEllipseCounter));
}
void QmitkMeasurementView::OnDrawBezierCurveTriggered(bool)
{
this->AddFigureToDataStorage(
mitk::PlanarBezierCurve::New(),
QString("BezierCurve%1").arg(++d->m_BezierCurveCounter));
}
void QmitkMeasurementView::OnDrawSubdivisionPolygonTriggered(bool)
{
this->AddFigureToDataStorage(
mitk::PlanarSubdivisionPolygon::New(),
QString("SubdivisionPolygon%1").arg(++d->m_SubdivisionPolygonCounter));
}
void QmitkMeasurementView::OnDrawRectangleTriggered(bool)
{
this->AddFigureToDataStorage(
mitk::PlanarRectangle::New(),
QString("Rectangle%1").arg(++d->m_RectangleCounter));
}
void QmitkMeasurementView::OnDrawPolygonTriggered(bool)
{
auto planarFigure = mitk::PlanarPolygon::New();
planarFigure->ClosedOn();
auto node = this->AddFigureToDataStorage(
planarFigure,
QString("Polygon%1").arg(++d->m_PolygonCounter));
node->SetProperty("planarfigure.isextendable", mitk::BoolProperty::New(true));
}
void QmitkMeasurementView::OnCopyToClipboard(bool)
{
QApplication::clipboard()->setText(d->m_SelectedPlanarFiguresText->toPlainText(), QClipboard::Clipboard);
}
mitk::DataNode::Pointer QmitkMeasurementView::AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name)
{
auto newNode = mitk::DataNode::New();
newNode->SetName(name.toStdString());
newNode->SetData(figure);
newNode->SetSelected(true);
if (d->m_SelectedImageNode.IsNotNull())
{
this->GetDataStorage()->Add(newNode, d->m_SelectedImageNode);
}
else
{
this->GetDataStorage()->Add(newNode);
}
for (auto &node : d->m_CurrentSelection)
node->SetSelected(false);
d->m_CurrentSelection.clear();
d->m_CurrentSelection.push_back(newNode);
this->UpdateMeasurementText();
d->m_DrawActionsToolBar->setEnabled(false);
d->m_UnintializedPlanarFigure = true;
return newNode;
}
void QmitkMeasurementView::UpdateMeasurementText()
{
d->m_SelectedPlanarFiguresText->clear();
QString infoText;
QString plainInfoText;
int j = 1;
mitk::PlanarFigure::Pointer planarFigure;
mitk::PlanarAngle::Pointer planarAngle;
mitk::PlanarFourPointAngle::Pointer planarFourPointAngle;
mitk::DataNode::Pointer node;
for (int i = 0; i < d->m_CurrentSelection.size(); ++i, ++j)
{
plainInfoText.clear();
node = d->m_CurrentSelection[i];
planarFigure = dynamic_cast<mitk::PlanarFigure*>(node->GetData());
if (planarFigure.IsNull())
continue;
if (j > 1)
infoText.append("<br />");
infoText.append(QString("<b>%1</b><hr />").arg(QString::fromStdString(node->GetName())));
plainInfoText.append(QString("%1").arg(QString::fromStdString(node->GetName())));
planarAngle = dynamic_cast<mitk::PlanarAngle*> (planarFigure.GetPointer());
if (planarAngle.IsNull())
planarFourPointAngle = dynamic_cast<mitk::PlanarFourPointAngle*> (planarFigure.GetPointer());
double featureQuantity = 0.0;
for (unsigned int k = 0; k < planarFigure->GetNumberOfFeatures(); ++k)
{
if (!planarFigure->IsFeatureActive(k))
continue;
featureQuantity = planarFigure->GetQuantity(k);
if ((planarAngle.IsNotNull() && k == planarAngle->FEATURE_ID_ANGLE) || (planarFourPointAngle.IsNotNull() && k == planarFourPointAngle->FEATURE_ID_ANGLE))
featureQuantity = featureQuantity * 180 / vnl_math::pi;
infoText.append(QString("<i>%1</i>: %2 %3")
.arg(QString(planarFigure->GetFeatureName(k)))
.arg(featureQuantity, 0, 'f', 2)
.arg(QString(planarFigure->GetFeatureUnit(k))));
plainInfoText.append(QString("\n%1: %2 %3")
.arg(QString(planarFigure->GetFeatureName(k)))
.arg(featureQuantity, 0, 'f', 2)
.arg(QString(planarFigure->GetFeatureUnit(k))));
if (k + 1 != planarFigure->GetNumberOfFeatures())
infoText.append("<br />");
}
if (j != d->m_CurrentSelection.size())
infoText.append("<br />");
}
d->m_SelectedPlanarFiguresText->setHtml(infoText);
}
void QmitkMeasurementView::AddAllInteractors()
{
auto planarFigures = this->GetAllPlanarFigures();
for (auto it = planarFigures->Begin(); it != planarFigures->End(); ++it)
this->NodeAdded(it.Value());
}
mitk::DataStorage::SetOfObjects::ConstPointer QmitkMeasurementView::GetAllPlanarFigures() const
{
auto isPlanarFigure = mitk::TNodePredicateDataType<mitk::PlanarFigure>::New();
auto isNotHelperObject = mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(false));
auto isNotHelperButPlanarFigure = mitk::NodePredicateAnd::New( isPlanarFigure, isNotHelperObject );
return this->GetDataStorage()->GetSubset(isPlanarFigure);
}
diff --git a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/CMakeLists.txt b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/CMakeLists.txt
index a5fe978856..8dc6de92c0 100644
--- a/Plugins/org.mitk.gui.qt.mitkworkbench.intro/CMakeLists.txt
+++ b/Plugins/org.mitk.gui.qt.mitkworkbench.intro/CMakeLists.txt
@@ -1,7 +1,7 @@
project(org_mitk_gui_qt_mitkworkbench_intro)
mitk_create_plugin(
EXPORT_DIRECTIVE MITK_QT_EXTAPP
EXPORTED_INCLUDE_SUFFIXES src
- PACKAGE_DEPENDS Qt5|WebEngineWidgets
+ PACKAGE_DEPENDS Qt6|WebEngineWidgets
)
diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerPreferencePage.cpp b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerPreferencePage.cpp
index 5a598806e4..708220547a 100644
--- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerPreferencePage.cpp
+++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkMovieMakerPreferencePage.cpp
@@ -1,142 +1,142 @@
/*============================================================================
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 "QmitkMovieMakerPreferencePage.h"
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
#include <mitkVideoRecorder.h>
#include <QFileDialog>
#include <QStringList>
#include <QTextCodec>
#include <ui_QmitkMovieMakerPreferencePage.h>
namespace
{
mitk::IPreferences* GetPreferences()
{
auto* preferencesService = mitk::CoreServices::GetPreferencesService();
return preferencesService->GetSystemPreferences()->Node("org.mitk.views.moviemaker");
}
}
QmitkMovieMakerPreferencePage::QmitkMovieMakerPreferencePage()
: m_Ui(new Ui::QmitkMovieMakerPreferencePage),
m_Control(nullptr),
m_FFmpegProcess(nullptr)
{
}
QmitkMovieMakerPreferencePage::~QmitkMovieMakerPreferencePage()
{
}
void QmitkMovieMakerPreferencePage::Init(berry::IWorkbench::Pointer)
{
}
void QmitkMovieMakerPreferencePage::CreateQtControl(QWidget* parent)
{
using Self = QmitkMovieMakerPreferencePage;
m_Control = new QWidget(parent);
m_Ui->setupUi(m_Control);
m_Ui->formatButtonGroup->setId(m_Ui->vp9Button, static_cast<int>(mitk::VideoRecorder::OutputFormat::WebM_VP9));
m_Ui->formatButtonGroup->setId(m_Ui->h264Button, static_cast<int>(mitk::VideoRecorder::OutputFormat::MP4_H264));
connect(m_Ui->ffmpegButton, &QToolButton::clicked, this, &Self::OnFFmpegButtonClicked);
m_FFmpegProcess = new QProcess(m_Control);
- connect(m_FFmpegProcess, qOverload<QProcess::ProcessError>(&QProcess::error), this, &Self::OnFFmpegProcessError);
- connect(m_FFmpegProcess, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, &Self::OnFFmpegProcessFinished);
+ connect(m_FFmpegProcess, &QProcess::errorOccurred, this, &Self::OnFFmpegProcessError);
+ connect(m_FFmpegProcess, &QProcess::finished, this, &Self::OnFFmpegProcessFinished);
this->Update();
}
QWidget* QmitkMovieMakerPreferencePage::GetQtControl() const
{
return m_Control;
}
bool QmitkMovieMakerPreferencePage::PerformOk()
{
auto* prefs = GetPreferences();
prefs->Put("ffmpeg", m_Ui->ffmpegLineEdit->text().toStdString());
prefs->PutInt("format", m_Ui->formatButtonGroup->checkedId());
return true;
}
void QmitkMovieMakerPreferencePage::PerformCancel()
{
}
void QmitkMovieMakerPreferencePage::Update()
{
auto* prefs = GetPreferences();
m_FFmpegPath = QString::fromStdString(prefs->Get("ffmpeg", ""));
if (!m_FFmpegPath.isEmpty())
m_FFmpegProcess->start(m_FFmpegPath, QStringList() << "-version", QProcess::ReadOnly);
m_Ui->formatButtonGroup->button(prefs->GetInt("format", 0))->setChecked(true);
}
void QmitkMovieMakerPreferencePage::OnFFmpegButtonClicked()
{
QString filter = "FFmpeg executable ";
#if defined(WIN32)
filter += "(ffmpeg.exe)";
#else
filter += "(ffmpeg)";
#endif
auto ffmpegPath = QFileDialog::getOpenFileName(m_Control, "FFmpeg", "", filter);
if (!ffmpegPath.isEmpty())
{
m_FFmpegPath = ffmpegPath;
m_FFmpegProcess->start(ffmpegPath, QStringList() << "-version", QProcess::ReadOnly);
}
}
void QmitkMovieMakerPreferencePage::OnFFmpegProcessError(QProcess::ProcessError)
{
m_FFmpegPath.clear();
m_Ui->ffmpegLineEdit->clear();
}
void QmitkMovieMakerPreferencePage::OnFFmpegProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
if (exitStatus == QProcess::NormalExit && exitCode == 0)
{
auto ffmpegOutput = QTextCodec::codecForName("UTF-8")->toUnicode(m_FFmpegProcess->readAllStandardOutput());
if (ffmpegOutput.startsWith("ffmpeg"))
{
m_Ui->ffmpegLineEdit->setText(m_FFmpegPath);
return;
}
}
m_FFmpegPath.clear();
m_Ui->ffmpegLineEdit->clear();
}
diff --git a/Plugins/org.mitk.gui.qt.overlaymanager/src/internal/QmitkOverlayManagerView.cpp b/Plugins/org.mitk.gui.qt.overlaymanager/src/internal/QmitkOverlayManagerView.cpp
index 5a2270499a..061fecfaa5 100644
--- a/Plugins/org.mitk.gui.qt.overlaymanager/src/internal/QmitkOverlayManagerView.cpp
+++ b/Plugins/org.mitk.gui.qt.overlaymanager/src/internal/QmitkOverlayManagerView.cpp
@@ -1,531 +1,531 @@
/*============================================================================
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 <memory>
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// Qmitk
#include "QmitkAddNewPropertyDialog.h"
#include "QmitkOverlayManagerView.h"
#include "QmitkPropertyItemDelegate.h"
#include "QmitkPropertyItemModel.h"
#include <QmitkRenderWindow.h>
// Qt
#include <QMessageBox>
#include <QPainter>
#include <QSortFilterProxyModel>
#include "internal/org_mitk_gui_qt_overlaymanager_Activator.h"
#include "mitkAnnotationUtils.h"
#include "mitkGetPropertyService.h"
#include "mitkLayoutAnnotationRenderer.h"
#include "mitkManualPlacementAnnotationRenderer.h"
#include "mitkRenderingManager.h"
#include <mitkColorBarAnnotation.h>
#include <mitkIPropertyAliases.h>
#include <mitkIPropertyDescriptions.h>
#include <mitkIPropertyPersistence.h>
#include <mitkLabelAnnotation3D.h>
#include <mitkLogoAnnotation.h>
#include <mitkScaleLegendAnnotation.h>
#include <mitkTextAnnotation2D.h>
#include <mitkTextAnnotation3D.h>
const std::string QmitkOverlayManagerView::VIEW_ID = "org.mitk.views.overlaymanager";
QmitkOverlayManagerView::QmitkOverlayManagerView()
: m_Parent(nullptr),
m_PropertyNameChangedTag(0),
m_OverlayManagerObserverTag(0),
m_PropertyAliases(nullptr),
m_PropertyDescriptions(nullptr),
m_PropertyPersistence(nullptr),
m_ProxyModel(nullptr),
m_Model(nullptr),
m_Delegate(nullptr),
m_Renderer(nullptr),
m_AddOverlayMenu(nullptr)
{
}
QmitkOverlayManagerView::~QmitkOverlayManagerView()
{
}
void QmitkOverlayManagerView::SetFocus()
{
}
void QmitkOverlayManagerView::CreateQtPartControl(QWidget *parent)
{
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi(parent);
m_Controls.m_OverlayList->clear();
auto* renderWindowPart = this->GetRenderWindowPart();
if (renderWindowPart != nullptr)
{
QHash<QString, QmitkRenderWindow *> renderWindows = renderWindowPart->GetQmitkRenderWindows();
Q_FOREACH (QString renderWindow, renderWindows.keys())
{
if (!m_Renderer)
m_Renderer = renderWindows[renderWindow]->GetRenderer();
m_Controls.m_RendererCB->addItem(renderWindow);
}
}
InitializeAddOverlayMenu();
m_ProxyModel = new QSortFilterProxyModel(m_Controls.m_PropertyTree);
m_Model = new QmitkPropertyItemModel(m_ProxyModel);
m_ProxyModel->setSourceModel(m_Model);
m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
m_ProxyModel->setDynamicSortFilter(true);
m_Delegate = new QmitkPropertyItemDelegate(m_Controls.m_PropertyTree);
m_Controls.m_PropertyTree->setItemDelegateForColumn(1, m_Delegate);
m_Controls.m_PropertyTree->setModel(m_ProxyModel);
m_Controls.m_PropertyTree->setColumnWidth(0, 160);
m_Controls.m_PropertyTree->sortByColumn(0, Qt::AscendingOrder);
m_Controls.m_PropertyTree->setSelectionBehavior(QAbstractItemView::SelectRows);
m_Controls.m_PropertyTree->setSelectionMode(QAbstractItemView::SingleSelection);
m_Controls.m_PropertyTree->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked);
connect(m_Controls.m_RendererCB, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPropertyListChanged(int)));
connect(m_Controls.newButton, SIGNAL(clicked()), this, SLOT(OnAddNewProperty()));
connect(m_Controls.m_PropertyTree->selectionModel(),
SIGNAL(currentRowChanged(const QModelIndex &, const QModelIndex &)),
this,
SLOT(OnCurrentRowChanged(const QModelIndex &, const QModelIndex &)));
connect(m_Controls.m_OverlayList,
SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)),
this,
SLOT(OnOverlaySelectionChanged(QListWidgetItem *, QListWidgetItem *)));
connect(m_Controls.m_DeleteOverlay, SIGNAL(clicked()), this, SLOT(OnDelete()));
connect(m_Controls.m_AddOverlay, SIGNAL(clicked()), this, SLOT(OnAddOverlay()));
itk::MemberCommand<QmitkOverlayManagerView>::Pointer command = itk::MemberCommand<QmitkOverlayManagerView>::New();
command->SetCallbackFunction(this, &QmitkOverlayManagerView::OnFocusChanged);
m_RenderWindowFocusObserverTag =
mitk::RenderingManager::GetInstance()->AddObserver(mitk::FocusChangedEvent(), command);
}
void QmitkOverlayManagerView::OnFocusChanged(itk::Object * /*caller*/, const itk::EventObject &event)
{
const mitk::FocusChangedEvent *focusEvent = dynamic_cast<const mitk::FocusChangedEvent *>(&event);
if (focusEvent)
{
QHash<QString, QmitkRenderWindow *> renderWindows = this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindows();
m_Controls.m_RendererCB->clear();
Q_FOREACH (QString renderWindow, renderWindows.keys())
{
m_Controls.m_RendererCB->addItem(renderWindow);
if (renderWindows[renderWindow]->GetVtkRenderWindow() ==
mitk::RenderingManager::GetInstance()->GetFocusedRenderWindow())
{
m_Controls.m_RendererCB->setCurrentText(renderWindow);
}
}
this->OnActivateOverlayList();
}
}
QString QmitkOverlayManagerView::GetPropertyNameOrAlias(const QModelIndex &index)
{
QString propertyName;
if (index.isValid())
{
QModelIndex current = index;
while (current.isValid())
{
QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString();
propertyName.prepend(propertyName.isEmpty() ? name : name.append('.'));
current = current.parent();
}
}
return propertyName;
}
void QmitkOverlayManagerView::OnCurrentRowChanged(const QModelIndex &current, const QModelIndex &)
{
if (m_PropertyDescriptions != nullptr && current.isValid())
{
QString name = this->GetPropertyNameOrAlias(current);
if (!name.isEmpty())
{
QString alias;
bool isTrueName = true;
if (m_PropertyAliases != nullptr)
{
std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString());
if (trueName.empty() && !m_SelectionClassName.empty())
trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName);
if (!trueName.empty())
{
alias = name;
name = QString::fromStdString(trueName);
isTrueName = false;
}
}
QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString()));
std::vector<std::string> aliases;
if (!isTrueName && m_PropertyAliases != nullptr)
{
aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName);
if (aliases.empty() && !m_SelectionClassName.empty())
aliases = m_PropertyAliases->GetAliases(name.toStdString());
}
bool isPersistent = false;
// QString persistenceKey;
if (m_PropertyPersistence != nullptr)
{
isPersistent = m_PropertyPersistence->HasInfo(name.toStdString());
/*if (isPersistent)
{
persistenceKey = QString::fromStdString(m_PropertyPersistence->GetInfo(name.toStdString())->GetKey());
if (persistenceKey.isEmpty())
persistenceKey = name;
}*/
}
if (!description.isEmpty() || !aliases.empty() || isPersistent)
{
QString customizedDescription;
if (!description.isEmpty())
customizedDescription += "<p>" + description + "</p>";
if (!aliases.empty() || isPersistent)
{
customizedDescription += "<div align=\"right\">";
if (!aliases.empty())
{
customizedDescription += aliases.size() > 1 ?
"<img height=\"32\" src=\":/org_mitk_icons/icons/awesome/scalable/tags.svg\"/>" :
"<img height=\"32\" src=\":/org_mitk_icons/icons/awesome/scalable/tag.svg\"/>";
}
if (isPersistent)
customizedDescription +=
"<img height=\"32\" src=\":/org_mitk_icons/icons/awesome/scalable/actions/document-save.svg\"/>";
customizedDescription += "</div>";
}
return;
}
}
}
}
void QmitkOverlayManagerView::OnPropertyNameChanged(const itk::EventObject &)
{
mitk::PropertyList *propertyList = m_Model->GetPropertyList();
if (propertyList != nullptr)
{
mitk::BaseProperty *nameProperty = propertyList->GetProperty("name");
if (nameProperty != nullptr)
{
QString partName = "Properties (";
partName.append(QString::fromStdString(nameProperty->GetValueAsString())).append(')');
this->SetPartName(partName);
}
}
}
void QmitkOverlayManagerView::OnSelectionChanged(berry::IWorkbenchPart::Pointer,
const QList<mitk::DataNode::Pointer> &)
{
}
void QmitkOverlayManagerView::InitializeAddOverlayMenu()
{
m_AddOverlayMenu = new QMenu(m_Controls.m_AddOverlay);
m_AddOverlayMenu->addAction("TextAnnotation2D");
m_AddOverlayMenu->addAction("TextAnnotation3D");
m_AddOverlayMenu->addAction("LabelAnnotation");
m_AddOverlayMenu->addAction("ColorBarAnnotation");
m_AddOverlayMenu->addAction("ScaleLegendAnnotation");
m_AddOverlayMenu->addAction("LogoAnnotation");
}
void QmitkOverlayManagerView::Activated()
{
// this->OnActivateOverlayList();
}
void QmitkOverlayManagerView::Deactivated()
{
}
void QmitkOverlayManagerView::Visible()
{
this->OnActivateOverlayList();
}
void QmitkOverlayManagerView::Hidden()
{
}
void QmitkOverlayManagerView::OnPropertyListChanged(int index)
{
if (index == -1)
return;
QString renderer = m_Controls.m_RendererCB->itemText(index);
auto *renwin = this->GetRenderWindowPart()->GetQmitkRenderWindow(renderer);
m_Renderer = renwin ? renwin->GetRenderer() : nullptr;
this->OnOverlaySelectionChanged(m_Controls.m_OverlayList->currentItem(), nullptr);
this->OnActivateOverlayList();
}
void QmitkOverlayManagerView::OnAddNewProperty()
{
std::unique_ptr<QmitkAddNewPropertyDialog> dialog(
new QmitkAddNewPropertyDialog(m_SelectedOverlay, m_Renderer, m_Parent));
if (dialog->exec() == QDialog::Accepted)
this->m_Model->Update();
}
void QmitkOverlayManagerView::OnActivateOverlayList()
{
if (!m_Renderer)
return;
std::vector<mitk::AbstractAnnotationRenderer *> arList =
mitk::AnnotationUtils::GetAnnotationRenderer(m_Renderer->GetName());
m_Controls.m_OverlayList->clear();
for (auto ar : arList)
{
for (auto overlay : ar->GetServices())
{
QListWidgetItem *item = new QListWidgetItem();
item->setData(Qt::UserRole, QVariant(overlay->GetMicroserviceID().c_str()));
QString text(overlay->GetName().c_str());
if (text.length() > 0)
{
text.append(" : ");
}
text.append(overlay->GetNameOfClass());
item->setText(text);
m_Controls.m_OverlayList->addItem(item);
}
}
}
void QmitkOverlayManagerView::OnOverlaySelectionChanged(QListWidgetItem *current, QListWidgetItem *)
{
mitk::PropertyList *propertyList = m_Model->GetPropertyList();
if (propertyList != nullptr)
{
mitk::BaseProperty *nameProperty = propertyList->GetProperty("name");
if (nameProperty != nullptr)
nameProperty->RemoveObserver(m_PropertyNameChangedTag);
m_PropertyNameChangedTag = 0;
}
mitk::Annotation *overlay = nullptr;
QString oID;
if (current)
{
oID = current->data(Qt::UserRole).toString();
OverlayMapType::iterator it = m_OverlayMap.find(oID.toStdString());
if (it != m_OverlayMap.end())
overlay = it->second;
else
{
overlay = mitk::AnnotationUtils::GetAnnotation(oID.toStdString());
}
}
if (!overlay)
{
m_SelectedOverlay = nullptr;
this->SetPartName("Overlay Properties");
m_Model->SetPropertyList(nullptr);
m_Delegate->SetPropertyList(nullptr);
m_Controls.newButton->setEnabled(false);
}
else
{
m_SelectedOverlay = overlay;
QString selectionClassName = m_SelectedOverlay->GetNameOfClass();
m_SelectionClassName = selectionClassName.toStdString();
mitk::PropertyList::Pointer propertyList = overlay->GetPropertyList();
m_Model->SetPropertyList(propertyList, selectionClassName);
m_Delegate->SetPropertyList(propertyList);
OnPropertyNameChanged(itk::ModifiedEvent());
mitk::BaseProperty *nameProperty = m_SelectedOverlay->GetProperty("name");
if (nameProperty != nullptr)
{
itk::ReceptorMemberCommand<QmitkOverlayManagerView>::Pointer command =
itk::ReceptorMemberCommand<QmitkOverlayManagerView>::New();
command->SetCallbackFunction(this, &QmitkOverlayManagerView::OnPropertyNameChanged);
m_PropertyNameChangedTag = nameProperty->AddObserver(itk::ModifiedEvent(), command);
}
m_Controls.newButton->setEnabled(true);
}
- if (!m_ProxyModel->filterRegExp().isEmpty())
+ if (!m_ProxyModel->filterRegularExpression().pattern().isEmpty())
m_Controls.m_PropertyTree->expandAll();
}
void QmitkOverlayManagerView::OnDelete()
{
if (m_SelectedOverlay.IsNotNull())
{
m_OverlayMap.erase(m_SelectedOverlay->GetMicroserviceID());
m_SelectedOverlay = nullptr;
OnActivateOverlayList();
}
}
void QmitkOverlayManagerView::OnAddOverlay()
{
QAction *action = m_AddOverlayMenu->exec(QCursor::pos());
mitk::Annotation::Pointer overlay;
if (action != nullptr)
{
const QString widgetKey = action->text();
if (widgetKey == "TextAnnotation2D")
overlay = CreateTextOverlay2D();
else if (widgetKey == "TextAnnotation3D")
overlay = CreateTextOverlay3D();
else if (widgetKey == "LabelAnnotation")
overlay = CreateLabelOverlay();
else if (widgetKey == "ColorBarAnnotation")
overlay = CreateColorBarOverlay();
else if (widgetKey == "ScaleLegendAnnotation")
overlay = CreateScaleLegendOverlay();
else if (widgetKey == "LogoAnnotation")
overlay = CreateLogoOverlay();
mitk::BaseRenderer *renderer =
this->GetRenderWindowPart(mitk::WorkbenchUtil::OPEN)->GetQmitkRenderWindow(m_Controls.m_RendererCB->currentText())->GetRenderer();
mitk::LayoutAnnotationRenderer::AddAnnotation(overlay, renderer);
m_OverlayMap[overlay->GetMicroserviceID()] = overlay;
}
OnActivateOverlayList();
}
mitk::Annotation::Pointer QmitkOverlayManagerView::CreateTextOverlay2D()
{
mitk::TextAnnotation2D::Pointer to = mitk::TextAnnotation2D::New();
to->SetText("Test");
return to.GetPointer();
}
mitk::Annotation::Pointer QmitkOverlayManagerView::CreateTextOverlay3D()
{
mitk::TextAnnotation3D::Pointer to = mitk::TextAnnotation3D::New();
return to.GetPointer();
}
mitk::Annotation::Pointer QmitkOverlayManagerView::CreateLabelOverlay()
{
mitk::LabelAnnotation3D::Pointer to = mitk::LabelAnnotation3D::New();
return to.GetPointer();
}
mitk::Annotation::Pointer QmitkOverlayManagerView::CreateColorBarOverlay()
{
mitk::ColorBarAnnotation::Pointer to = mitk::ColorBarAnnotation::New();
return to.GetPointer();
}
mitk::Annotation::Pointer QmitkOverlayManagerView::CreateScaleLegendOverlay()
{
mitk::ScaleLegendAnnotation::Pointer to = mitk::ScaleLegendAnnotation::New();
return to.GetPointer();
}
mitk::Annotation::Pointer QmitkOverlayManagerView::CreateLogoOverlay()
{
mitk::LogoAnnotation::Pointer to = mitk::LogoAnnotation::New();
return to.GetPointer();
}
void QmitkOverlayManagerView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
{
if (m_Controls.m_RendererCB->count() == 0)
{
QHash<QString, QmitkRenderWindow *> renderWindows = renderWindowPart->GetQmitkRenderWindows();
Q_FOREACH (QString renderWindow, renderWindows.keys())
{
m_Controls.m_RendererCB->addItem(renderWindow);
}
}
OnActivateOverlayList();
}
void QmitkOverlayManagerView::RenderWindowPartDeactivated(mitk::IRenderWindowPart *)
{
if (m_Controls.m_RendererCB->count() > 0)
{
m_Controls.m_RendererCB->clear();
}
m_Controls.m_OverlayList->clear();
}
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/CMakeLists.txt b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/CMakeLists.txt
deleted file mode 100644
index 3b57c693bb..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-project(org_mitk_gui_qt_pointsetinteractionmultispectrum)
-
-mitk_create_plugin(
- EXPORT_DIRECTIVE POINTSETINTERACTIONMULTISPECTRUM_EXPORT
- EXPORTED_INCLUDE_SUFFIXES src
- MODULE_DEPENDS MitkQtWidgetsExt
-)
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/files.cmake b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/files.cmake
deleted file mode 100644
index 99f891e589..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/files.cmake
+++ /dev/null
@@ -1,42 +0,0 @@
-set(SRC_CPP_FILES
-
-)
-
-set(INTERNAL_CPP_FILES
- org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.cpp
- PointSetInteractionMultispectrum.cpp
-)
-
-set(UI_FILES
- src/internal/PointSetInteractionMultispectrumControls.ui
-)
-
-set(MOC_H_FILES
- src/internal/org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.h
- src/internal/PointSetInteractionMultispectrum.h
-)
-
-# list of resource files which can be used by the plug-in
-# system without loading the plug-ins shared library,
-# for example the icon used in the menu and tabs for the
-# plug-in views in the workbench
-set(CACHED_RESOURCE_FILES
- resources/icon.xpm
- plugin.xml
-)
-
-# list of Qt .qrc files which contain additional resources
-# specific to this plugin
-set(QRC_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/org.mitk.gui.qt.pointsetinteractionmultispectrum/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/manifest_headers.cmake
deleted file mode 100644
index 1fbc6f2c2b..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/manifest_headers.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(Plugin-Name "Pointsetinteractionmultispectrum")
-set(Plugin-Version "0.1")
-set(Plugin-Vendor "DKFZ")
-set(Plugin-ContactAddress "")
-set(Require-Plugin org.mitk.gui.qt.common)
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/plugin.xml b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/plugin.xml
deleted file mode 100644
index f36c5593f0..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/plugin.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin>
-
- <extension point="org.blueberry.ui.views">
- <view id="org.mitk.views.pointsetinteractionmultispectrum"
- name="Point Set Interaction Multispectrum"
- class="PointSetInteractionMultispectrum"
- icon="resources/icon.xpm" />
- </extension>
-
-</plugin>
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/resources/icon.xpm b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/resources/icon.xpm
deleted file mode 100644
index ae3d354bd7..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/resources/icon.xpm
+++ /dev/null
@@ -1,804 +0,0 @@
-/* XPM */
-static char * C:\m\MITK\Plugins\org_mitk_gui_qt_pointsetinteractionmultispectrum\resources\icon_xpm[] = {
-"48 48 753 2",
-" c None",
-". c #C4C3C1",
-"+ c #C3C2C0",
-"@ c #C4C3C2",
-"# c #C6C5C3",
-"$ c #C5C4C2",
-"% c #BBBAB8",
-"& c #C8C7C5",
-"* c #C2C1C0",
-"= c #C9C8C6",
-"- c #B8B7B5",
-"; c #C5C6C9",
-"> c #FFFFFF",
-", c #FFFFFE",
-"' c #FFFFFD",
-") c #FFFEFC",
-"! c #FDFFFE",
-"~ c #FEFEFE",
-"{ c #FDFFFF",
-"] c #FEFFFF",
-"^ c #FDFEFF",
-"/ c #FBFFFF",
-"( c #FCFFFF",
-"_ c #FAFFFF",
-": c #FBFEFF",
-"< c #FEFEFC",
-"[ c #FFFDFD",
-"} c #FFFBFD",
-"| c #FFF9FF",
-"1 c #FFFAFF",
-"2 c #FFFDFF",
-"3 c #F6FFFF",
-"4 c #F1FFFF",
-"5 c #FFFCFD",
-"6 c #FFFEFE",
-"7 c #F9FFFF",
-"8 c #E0FFED",
-"9 c #F5FBED",
-"0 c #FFF7F4",
-"a c #FFF1F2",
-"b c #F4FFFF",
-"c c #E2FFFF",
-"d c #EAFFFF",
-"e c #FFFEFF",
-"f c #FFF5FC",
-"g c #FFF4FA",
-"h c #FFFAF7",
-"i c #FDFFFB",
-"j c #FBFCFA",
-"k c #FCFFFC",
-"l c #FCFEFC",
-"m c #FEFFFC",
-"n c #FFFCFF",
-"o c #FFFBFF",
-"p c #F8FFFF",
-"q c #F0FDEC",
-"r c #FDFDF4",
-"s c #F1D7D9",
-"t c #FFF2F8",
-"u c #F0F0F1",
-"v c #EDFFFF",
-"w c #EFFFFF",
-"x c #FFF7FC",
-"y c #FFF8FA",
-"z c #FFFDF8",
-"A c #FDFFFC",
-"B c #FFFBFA",
-"C c #F7FFF9",
-"D c #F8FFFA",
-"E c #FAFFFC",
-"F c #FAFFFE",
-"G c #FEFDFF",
-"H c #FEF9EF",
-"I c #FFEFEF",
-"J c #8D535E",
-"K c #F9D4E0",
-"L c #FDF7FB",
-"M c #F6FFFD",
-"N c #FFFAFC",
-"O c #FFFFFA",
-"P c #F8FFF9",
-"Q c #F8FFFB",
-"R c #F8FFFC",
-"S c #F9FFFC",
-"T c #FBFFFE",
-"U c #FCFFFE",
-"V c #FFFCFC",
-"W c #FEFAFB",
-"X c #BA858E",
-"Y c #E09EAE",
-"Z c #C28D9E",
-"` c #FFF3FC",
-" . c #F5F0F2",
-".. c #FFFFFB",
-"+. c #F8FFFD",
-"@. c #FFF5F1",
-"#. c #FDFCF7",
-"$. c #FCFDF8",
-"%. c #FCFEF9",
-"&. c #F9FFFA",
-"*. c #F7FFFC",
-"=. c #FFF9F8",
-"-. c #FFF5F6",
-";. c #E3BBC1",
-">. c #CE9BA6",
-",. c #FFE8F8",
-"'. c #D392A3",
-"). c #FCDFE9",
-"!. c #FFFEFD",
-"~. c #FEFFFD",
-"{. c #FBFFFB",
-"]. c #F6FFFB",
-"^. c #FFF8F4",
-"/. c #FFF6F7",
-"(. c #FFF8F8",
-"_. c #FFFAF9",
-":. c #FEFDF9",
-"<. c #FBFFFA",
-"[. c #FDFDFB",
-"}. c #FFFCFB",
-"|. c #FFF6F6",
-"1. c #FFFDFC",
-"2. c #9B7074",
-"3. c #FEE6EE",
-"4. c #FFE7F1",
-"5. c #C599A3",
-"6. c #F4D6DF",
-"7. c #FFF8FC",
-"8. c #FFFDFB",
-"9. c #FBFFFD",
-"0. c #F9FFFD",
-"a. c #D5BCB8",
-"b. c #F6E7ED",
-"c. c #FFEBF0",
-"d. c #FFF4F7",
-"e. c #FEFCFA",
-"f. c #FBFCF8",
-"g. c #F8FEFB",
-"h. c #F4FFF9",
-"i. c #F4FFFB",
-"j. c #F3FBFA",
-"k. c #F5FEFC",
-"l. c #F2F8F6",
-"m. c #FCF4F2",
-"n. c #FFFAF8",
-"o. c #FFF2F2",
-"p. c #998684",
-"q. c #F4E5E3",
-"r. c #FFF5F4",
-"s. c #FFF3F4",
-"t. c #E6D1D4",
-"u. c #D1ADB2",
-"v. c #FFF8FB",
-"w. c #FEFFFB",
-"x. c #F8F9F7",
-"y. c #BDA9A5",
-"z. c #C09199",
-"A. c #CFB5BC",
-"B. c #FFF0F6",
-"C. c #FCF1F1",
-"D. c #F6F2F0",
-"E. c #F8FAF5",
-"F. c #F7FDFA",
-"G. c #EEF9F5",
-"H. c #F0FEFA",
-"I. c #E9FDF6",
-"J. c #EFFFFB",
-"K. c #FFFFFC",
-"L. c #FFFEFB",
-"M. c #F2EDE9",
-"N. c #FFF9F6",
-"O. c #FFEDEA",
-"P. c #B9A8A6",
-"Q. c #D1B8B7",
-"R. c #FBFEF9",
-"S. c #FCFCF4",
-"T. c #FDF2EE",
-"U. c #9A8081",
-"V. c #FFF3F5",
-"W. c #FFF5F5",
-"X. c #FAFCF6",
-"Y. c #FBFEFE",
-"Z. c #FFFAFD",
-"`. c #FDFCFF",
-" + c #FFFBF7",
-".+ c #FBE8ED",
-"++ c #D9B4B8",
-"@+ c #8E6B6F",
-"#+ c #E6CACF",
-"$+ c #FFF5F7",
-"%+ c #FBEDED",
-"&+ c #FFFCF9",
-"*+ c #F9FEFB",
-"=+ c #E9F6F0",
-"-+ c #F1FFFD",
-";+ c #E9FFF5",
-">+ c #FDF6F4",
-",+ c #FFECE9",
-"'+ c #F2E3E0",
-")+ c #B09490",
-"!+ c #FFF0EE",
-"~+ c #F1FCF5",
-"{+ c #E7F6EC",
-"]+ c #F6FFFA",
-"^+ c #FFFDF6",
-"/+ c #D3B9B8",
-"(+ c #DCBABD",
-"_+ c #F8F9F3",
-":+ c #F9FDFB",
-"<+ c #FDF8FF",
-"[+ c #F7EFED",
-"}+ c #FDF8F6",
-"|+ c #FFF8F7",
-"1+ c #AE8E91",
-"2+ c #B08990",
-"3+ c #F4DFE5",
-"4+ c #F4E5E7",
-"5+ c #FEF9F8",
-"6+ c #FAFCFA",
-"7+ c #F6FDFA",
-"8+ c #FDF5F2",
-"9+ c #FFF4EF",
-"0+ c #FFFAF6",
-"a+ c #9A807C",
-"b+ c #F1E3DF",
-"c+ c #FFF0ED",
-"d+ c #F5FBF8",
-"e+ c #EEFCF4",
-"f+ c #F2FFF7",
-"g+ c #FDF9F2",
-"h+ c #9A6E72",
-"i+ c #FFFAFB",
-"j+ c #F9F8F3",
-"k+ c #F4FFFC",
-"l+ c #F7FEFE",
-"m+ c #FFF8FF",
-"n+ c #FDF6FD",
-"o+ c #F9FBFA",
-"p+ c #F6F7EE",
-"q+ c #FCF8F1",
-"r+ c #FCF5F2",
-"s+ c #E6CCD2",
-"t+ c #CB9DA6",
-"u+ c #BB9099",
-"v+ c #FDE8F0",
-"w+ c #F8E8EC",
-"x+ c #FFF9FA",
-"y+ c #FCFCFA",
-"z+ c #FBFEFB",
-"A+ c #FAF5F3",
-"B+ c #FFF4F1",
-"C+ c #957F7A",
-"D+ c #DED0CB",
-"E+ c #FFF5F2",
-"F+ c #FFF1EE",
-"G+ c #FEF9FA",
-"H+ c #F1FBF1",
-"I+ c #FBF7F2",
-"J+ c #FFF4F6",
-"K+ c #C4848C",
-"L+ c #F4DADC",
-"M+ c #FEFDF5",
-"N+ c #F0FFFB",
-"O+ c #F2FCFB",
-"P+ c #FDF7FF",
-"Q+ c #F0FFF1",
-"R+ c #F6FEF3",
-"S+ c #FEF9F2",
-"T+ c #FFEEF3",
-"U+ c #FCE9F4",
-"V+ c #D7ACB9",
-"W+ c #D8A7B4",
-"X+ c #FFF3FB",
-"Y+ c #FCE8ED",
-"Z+ c #FFFCFE",
-"`+ c #FDF6F7",
-" @ c #FFF9F7",
-".@ c #CDBEBA",
-"+@ c #CCB4AF",
-"@@ c #FFF1ED",
-"#@ c #FFF1EC",
-"$@ c #F0EFEC",
-"%@ c #FEFFFA",
-"&@ c #FFE7EC",
-"*@ c #E9C5D0",
-"=@ c #D6AEB3",
-"-@ c #FFFFF8",
-";@ c #EBFFF9",
-">@ c #EAF7F6",
-",@ c #FDFAFF",
-"'@ c #FFFCFA",
-")@ c #FFF8F9",
-"!@ c #F9EEF0",
-"~@ c #A58F8D",
-"{@ c #FAF3F1",
-"]@ c #FFF2EF",
-"^@ c #FFFBF4",
-"/@ c #FDF4EF",
-"(@ c #FFF7FF",
-"_@ c #F4FEFD",
-":@ c #F8FEFD",
-"<@ c #FEFCFE",
-"[@ c #EEFFFD",
-"}@ c #DCFFFB",
-"|@ c #EBFFFC",
-"1@ c #FBFEFC",
-"2@ c #E7FFF7",
-"3@ c #FEF7FA",
-"4@ c #ECFCFE",
-"5@ c #F5FEFE",
-"6@ c #F3F0EF",
-"7@ c #FEF5F5",
-"8@ c #FFF2F1",
-"9@ c #F6EAEA",
-"0@ c #AC8D8D",
-"a@ c #F9EFF1",
-"b@ c #FFF4F5",
-"c@ c #FAF7F9",
-"d@ c #FEFEFF",
-"e@ c #FDFDFF",
-"f@ c #FFFDFA",
-"g@ c #F1E6E2",
-"h@ c #C8A9A9",
-"i@ c #FFF1F3",
-"j@ c #FFF2F5",
-"k@ c #FDF8F7",
-"l@ c #F5FCFB",
-"m@ c #FBFFFC",
-"n@ c #FFFAFA",
-"o@ c #FFF9F9",
-"p@ c #E1CDCC",
-"q@ c #998483",
-"r@ c #FFF5F0",
-"s@ c #FCFDF7",
-"t@ c #F2FCF7",
-"u@ c #FCFEFD",
-"v@ c #E9FFFC",
-"w@ c #F5FEFA",
-"x@ c #FFF5F8",
-"y@ c #F7FDF8",
-"z@ c #E3F9F2",
-"A@ c #FBF9F8",
-"B@ c #FFF6FD",
-"C@ c #FAFBF9",
-"D@ c #EEFEFD",
-"E@ c #EFF9FA",
-"F@ c #F6F8F9",
-"G@ c #F4EFEE",
-"H@ c #F8EDEC",
-"I@ c #997A7A",
-"J@ c #E2C8CA",
-"K@ c #FFFBF8",
-"L@ c #FEF5F2",
-"M@ c #AC908F",
-"N@ c #FFE8EA",
-"O@ c #FBF5F5",
-"P@ c #FFFEFA",
-"Q@ c #FFF8F6",
-"R@ c #B6A3A1",
-"S@ c #C8B9B8",
-"T@ c #FCEFEF",
-"U@ c #EAFFFB",
-"V@ c #F3FEFC",
-"W@ c #F8FEF9",
-"X@ c #FBF8F6",
-"Y@ c #FEF4F5",
-"Z@ c #FFF6FA",
-"`@ c #FEFAFD",
-" # c #FFF7F9",
-".# c #FDFAF8",
-"+# c #F9FCFC",
-"@# c #FBFDFD",
-"## c #FDFCFC",
-"$# c #FCF3F3",
-"%# c #CBB5B7",
-"&# c #B79A9B",
-"*# c #FFF9FC",
-"=# c #FFFBF9",
-"-# c #C5AFB0",
-";# c #DABDBF",
-"># c #FFF9FB",
-",# c #FDFEFC",
-"'# c #F4F9F8",
-")# c #FCFFFA",
-"!# c #FEFAF7",
-"~# c #AC8F90",
-"{# c #F9ECEF",
-"]# c #FDEAEC",
-"^# c #E6FFF6",
-"/# c #D5FFF2",
-"(# c #EFFCF4",
-"_# c #FFEFF7",
-":# c #FFF1F8",
-"<# c #FEF0F0",
-"[# c #F4CCD7",
-"}# c #EEAABC",
-"|# c #F3E5E8",
-"1# c #F8FDF8",
-"2# c #FBF2F2",
-"3# c #FFFBFC",
-"4# c #FDF5F5",
-"5# c #F4DEDE",
-"6# c #A58789",
-"7# c #FFF7FA",
-"8# c #FFF3F6",
-"9# c #FDF8FC",
-"0# c #F9FBFD",
-"a# c #F7FDFF",
-"b# c #FCFDFF",
-"c# c #FDFDFA",
-"d# c #FFF7F7",
-"e# c #FFEFF0",
-"f# c #967A7E",
-"g# c #F7FBF9",
-"h# c #FFFDFE",
-"i# c #FDFFFD",
-"j# c #FAFFF9",
-"k# c #F8F6F2",
-"l# c #DAC1C5",
-"m# c #D2B5BA",
-"n# c #FEEFF3",
-"o# c #E8FFF5",
-"p# c #F4FCF4",
-"q# c #FEFDF8",
-"r# c #FBDFE5",
-"s# c #E5ACBA",
-"t# c #CA96A1",
-"u# c #C29BA0",
-"v# c #B7959B",
-"w# c #FFDBDF",
-"x# c #FEF3F2",
-"y# c #FFF6F5",
-"z# c #BDA3A5",
-"A# c #DFC9CC",
-"B# c #FFEFF2",
-"C# c #FCFCFF",
-"D# c #F6FCFE",
-"E# c #F2FCFF",
-"F# c #FCFFFD",
-"G# c #FCFDFC",
-"H# c #A68B8E",
-"I# c #E6D3D6",
-"J# c #FEF6F5",
-"K# c #F7FFFE",
-"L# c #F3FFFC",
-"M# c #FCFEFA",
-"N# c #FDF0EF",
-"O# c #88636B",
-"P# c #FFE3EA",
-"Q# c #FBFEF5",
-"R# c #F4EEE7",
-"S# c #BF9E9F",
-"T# c #C89AA4",
-"U# c #FFE2E6",
-"V# c #FEFAF5",
-"W# c #EBCBCE",
-"X# c #9F6C74",
-"Y# c #DECDCA",
-"Z# c #F3D9D9",
-"`# c #937A7C",
-" $ c #EFEDF2",
-".$ c #F8FAFE",
-"+$ c #F5FDFF",
-"@$ c #F9EEF2",
-"#$ c #A38D91",
-"$$ c #FFF6F4",
-"%$ c #F3FFFE",
-"&$ c #F4FFFD",
-"*$ c #F3FEFA",
-"=$ c #F9FDF7",
-"-$ c #FFF1F4",
-";$ c #FFEBF2",
-">$ c #8D636C",
-",$ c #FFE6EF",
-"'$ c #FFF7F5",
-")$ c #EEDADB",
-"!$ c #85575D",
-"~$ c #F4DDDB",
-"{$ c #FEFAF6",
-"]$ c #FFF1F5",
-"^$ c #FDF8F0",
-"/$ c #B38F91",
-"($ c #D7B9B9",
-"_$ c #FCDBD9",
-":$ c #FFF1EF",
-"<$ c #795D5C",
-"[$ c #FFF5F9",
-"}$ c #F7FFFF",
-"|$ c #FFEFF3",
-"1$ c #B99FA2",
-"2$ c #F8E8EA",
-"3$ c #FCFAFA",
-"4$ c #F5FFFE",
-"5$ c #F7FEFB",
-"6$ c #FAFDF9",
-"7$ c #FFF6F8",
-"8$ c #FFF5FA",
-"9$ c #E0BAC1",
-"0$ c #DF9DB0",
-"a$ c #CD9CA4",
-"b$ c #BC9297",
-"c$ c #F4E4E6",
-"d$ c #FDF6F1",
-"e$ c #F1FFF4",
-"f$ c #F7FDF4",
-"g$ c #F7F7F1",
-"h$ c #FDF9F3",
-"i$ c #FFEFF1",
-"j$ c #BDA2A1",
-"k$ c #BEA09E",
-"l$ c #99807F",
-"m$ c #EBDADC",
-"n$ c #FEEFF1",
-"o$ c #FCF3F6",
-"p$ c #FEFBFC",
-"q$ c #FCF5F9",
-"r$ c #FFEDF4",
-"s$ c #D0BBC0",
-"t$ c #E9D8DA",
-"u$ c #FFECEB",
-"v$ c #B27080",
-"w$ c #EEB0C6",
-"x$ c #FDEAF2",
-"y$ c #F4FDF8",
-"z$ c #FFF8F5",
-"A$ c #F2FFF9",
-"B$ c #E3FFF8",
-"C$ c #F9F7F3",
-"D$ c #FFE7EE",
-"E$ c #FDF7F5",
-"F$ c #FFFCF8",
-"G$ c #F1D7D3",
-"H$ c #E0CAC8",
-"I$ c #F4E4E5",
-"J$ c #FCF6FA",
-"K$ c #FFFBFB",
-"L$ c #FFF9FD",
-"M$ c #E5D5D9",
-"N$ c #C4A6A8",
-"O$ c #FCF8F7",
-"P$ c #F7F8F8",
-"Q$ c #FDFCFA",
-"R$ c #FBF8F5",
-"S$ c #FFF1FB",
-"T$ c #FDF4F9",
-"U$ c #FFF2F4",
-"V$ c #E5EAE4",
-"W$ c #F1FEF6",
-"X$ c #F6FEF9",
-"Y$ c #F8F9F5",
-"Z$ c #FCF9F6",
-"`$ c #F6F1F3",
-" % c #F9F8FC",
-".% c #FFFFF9",
-"+% c #FAF0F5",
-"@% c #997B7D",
-"#% c #FCF8F6",
-"$% c #F7F8F5",
-"%% c #FAFFFD",
-"&% c #E9FDF7",
-"*% c #F4FAF6",
-"=% c #F5F0F0",
-"-% c #F6FEFB",
-";% c #E8FFFC",
-">% c #FAF4F2",
-",% c #FDF8FA",
-"'% c #FAFAFB",
-")% c #F6FAFB",
-"!% c #FFFEF7",
-"~% c #FFFEF5",
-"{% c #F9FEFF",
-"]% c #FEF9FD",
-"^% c #FFF8FE",
-"/% c #BB9FA0",
-"(% c #DFC1BF",
-"_% c #FEFBFD",
-":% c #FCF8F9",
-"<% c #F5FFFD",
-"[% c #E2FEFD",
-"}% c #F5FEFB",
-"|% c #E4FAF3",
-"1% c #FFEDF7",
-"2% c #FFFBFE",
-"3% c #F4FEFF",
-"4% c #EEFFFF",
-"5% c #FDFCF9",
-"6% c #F9F9FB",
-"7% c #FFFEF9",
-"8% c #FFFDF4",
-"9% c #FFFCF2",
-"0% c #F5FFFF",
-"a% c #FFEDF2",
-"b% c #FFF0F2",
-"c% c #937572",
-"d% c #FEFFFE",
-"e% c #FDF9FA",
-"f% c #FFF4FB",
-"g% c #FFF1FC",
-"h% c #C49CAA",
-"i% c #F5DEE2",
-"j% c #FCFEFE",
-"k% c #FFF6FC",
-"l% c #EBD0DC",
-"m% c #C5AEB2",
-"n% c #FBFCFC",
-"o% c #FAF5F7",
-"p% c #FDEBF2",
-"q% c #F8EDF7",
-"r% c #B9A1A4",
-"s% c #F9FBFB",
-"t% c #FEF9FB",
-"u% c #FEF2F6",
-"v% c #B9A4A6",
-"w% c #F5F5F5",
-"x% c #FDF5F8",
-"y% c #D1BDC0",
-"z% c #F5FAF8",
-"A% c #F5F8F8",
-"B% c #F5F7F6",
-"C% c #FEFDFD",
-"D% c #FCFCFC",
-"E% c #FAFAFA",
-"F% c #FDFDFD",
-"G% c #FBFBFB",
-"H% c #F8FCFB",
-"I% c #F9FDFC",
-"J% c #FEFCFD",
-"K% c #FDFEFE",
-"L% c #FAFDFC",
-"M% c #F9FCFB",
-"N% c #F9FDFD",
-"O% c #F7FCFB",
-"P% c #F8FCFC",
-"Q% c #FDFCFB",
-"R% c #FEFDFB",
-"S% c #F7F7F7",
-"T% c #F9F9F9",
-"U% c #FAF9F9",
-"V% c #FAF8F9",
-"W% c #FCFAFB",
-"X% c #FDFBFC",
-"Y% c #FCFBFC",
-"Z% c #FDF8F5",
-"`% c #BEBEBE",
-" & c #ACACAC",
-".& c #B8B8B8",
-"+& c #B6B6B6",
-"@& c #B0B0AF",
-"#& c #B5B4B4",
-"$& c #BABABA",
-"%& c #AFAEAE",
-"&& c #B8B8B7",
-"*& c #AEAEAE",
-"=& c #B1B1B1",
-"-& c #B7B7B7",
-";& c #B5B5B4",
-">& c #B4B4B4",
-",& c #B5B5B5",
-"'& c #B2B2B2",
-")& c #B1B0B0",
-"!& c #B3B3B2",
-"~& c #B7B6B6",
-"{& c #B9B8B8",
-"]& c #B3B3B3",
-"^& c #BDBDBD",
-"/& c #B3B2B2",
-"(& c #B9B9B8",
-"_& c #A5A5A5",
-":& c #B9BEBC",
-"<& c #B7BAB9",
-"[& c #BABAB9",
-"}& c #BDB9BA",
-"|& c #BEB7B9",
-"1& c #B7AFB2",
-"2& c #C1B8BB",
-"3& c #BCB4B6",
-"4& c #B3ADAE",
-"5& c #BAB4B6",
-"6& c #B3B1AD",
-"7& c #B4B8BB",
-"8& c #DBDFE2",
-"9& c #E5E9EC",
-"0& c #EAEEF1",
-"a& c #F1F4F8",
-"b& c #CFD3D5",
-"c& c #F5F8FC",
-"d& c #E3E7EA",
-"e& c #FAFEFF",
-"f& c #EFF2F5",
-"g& c #E3E7E9",
-"h& c #F2F6F9",
-"i& c #E8ECEF",
-"j& c #EBEFF2",
-"k& c #D7DBDE",
-"l& c #E4E8EB",
-"m& c #F2F5F8",
-"n& c #D5D9DC",
-"o& c #D2D6D9",
-"p& c #ECF0F3",
-"q& c #F2F6F8",
-"r& c #F4F8FB",
-"s& c #DEE3E5",
-"t& c #F9FAFB",
-"u& c #EEEFF1",
-"v& c #FBFCFD",
-"w& c #F9FAFC",
-"x& c #FCFCFD",
-"y& c #EFF0F2",
-"z& c #F5F6F8",
-"A& c #FBFBFC",
-"B& c #FCFDFE",
-"C& c #F1F2F4",
-"D& c #FAFBFC",
-"E& c #FCFDFD",
-"F& c #DDDDDD",
-"G& c #D3D3D3",
-"H& c #EFEFEF",
-"I& c #F8F8F8",
-"J& c #E8E9E9",
-"K& c #CDCDCD",
-"L& c #F9F9FA",
-"M& c #EEEEEE",
-"N& c #F6F6F5",
-"O& c #939392",
-"P& c #F8F8F7",
-"Q& c #898888",
-"R& c #F0F0F0",
-"S& c #FEFEFD",
-"T& c #FCFBFB",
-"U& c #C5C4C4",
-"V& c #A8A8A7",
-"W& c #F3F3F3",
-"X& c #FBFAFA",
-"Y& c #787777",
-"Z& c #D8D8D8",
-"`& c #FDFDFC",
-" * c #F2F5F7",
-".* c #DEDDDB",
-"+* c #DBDAD8",
-"@* c #FEFEFB",
-"#* c #DAD9D7",
-"$* c #FCFBF9",
-"%* c #FBFAF8",
-"&* c #F9F8F6",
-"** c #FAF9F6",
-"=* c #EFEFED",
-"-* c #DDDCDA",
-";* c #FCFAF8",
-">* c #FEFDFA",
-",* c #D5D4D2",
-"'* c #F9F9F7",
-")* c #FDFBF9",
-"!* c #F9F9F6",
-". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + @ # # $ . % & * = - ; ",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > , , , , , , > > > > > > ",
-"' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ) ) ) ) ) ) ' ' ' ' ' ! ",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > ~ ~ ~ ~ ~ ~ > > > > > { ",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > ~ ~ ~ ~ ~ ~ > > > > > { ",
-"] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ] ^ ^ ^ ^ ^ ^ ] ] ] ] ] / ",
-"( ( ( ( ( ( ( ( ( ( { { { ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( { ( / / ( { { ( ( ( ( _ ",
-": < ) [ } | 1 1 2 ( 3 4 4 > > > > > > > > > > > 5 [ 6 > ] / 7 _ _ ( { > 8 9 0 a b c d e f g h i ",
-"j k l m [ n o n 2 > ( 7 p > > > > > > > > > > > [ [ e > ] / / / / ( ] > q r s t u v w e x y z A ",
-"B C D E k , e e 2 2 2 2 2 > > > > > > > > > > > 2 2 e > { ( F ( { ] G G H I J K L M b e N B O E ",
-"h P C Q R S T ] e 2 1 | | > > > > > > > > > > > 2 e e > ] ( T U > > V W I X Y Z ` .( > V ..D +.",
-"@.#.$.%.&.R *.F { e o 1 | > > > > > > > > > > > e e e > ] ] l m ' [ =.-.;.>.,.'.).} !.' ~.{.].+.",
-"^./.(._.:.<.R +.7 ( > 2 2 > > > > > > > > > > > e e e > ] ' [.) ) }.|.1.2.3.4.5.6.7.8.~.9.0.0.F ",
-"a.b.c.d./.e.f.g.h.i.j.k.l.> > > > > > > > > > > e e > > , ' ..e.m.n.o.p.q.r.s.t.u.v.B w.].T x.] ",
-"y.z.A.B.7.C.D.E.F.G.H.I.J.> > > > > > > > > > > > > > > ' K.L.M.N.O.P.Q...R.S.T.U.V.W.X.R Y.Z.`.",
-" +.+++@+#+e $+%+&+*+=+-+;+> > > > > > > > > > > > > > > ' K. +>+,+'+)+!+~+{+]+^+/+(+(._+*.:+| <+",
-"[+}+|+-.1+2+3+g 4+5+6+7+M > > > > > > > > > > > ] ] ] > ' K.8+9+0+a+b+c+d+e+f+g+W.h+i+j+k+l+m+n+",
-"o+p+q+r+V.s+t+u+v+w+x+y+z+> > > > > > > > > > > ] ] ] > K.K.A+B+C+D+E+F+G+k H+I+J+K+L+M+N+O+| P+",
-": Q+R+S+W.T+U+V+W+X+Y+Z+`+> > > > > > > > > > > > > ] > ' .. @.@+@0+@@#@g $@%@^.&@*@=@-@;@>@1 ,@",
-"> 0.9...'@i+)@!@~@{@]@^@/@(@_@:@<@[@}@|@1@3 2@3@4@4 5@6@7@8@9@0@a@b@e c@d@^ e@f@0+g@h@i@j@k@/ l@",
-"> m@k L.f@n@o@x+p@q@> r@s@t@v.u@v@w@x@y@z@A@B@C@D@E@F@G@H@V I@J@)@i+5 G e ] ] ) K@L@M@N@v.O@{ _ ",
-"> A A < P@f@'@Q@V R@S@o@T@U@V@W@X@Y@x@Z@`@ #|..#+#@###$#5 %#&#Z.x@*#<@{ 2 e ] ) =#=#-#;#>#x+,#'#",
-"> ) < A A )#%@I+!#n@~#{#]#^#/#(#_#:#<#[#}#|#1#2#3# @4#Y@5#6#7#8#7.9#0#a#n G b#c# +d#e#f#v./.< g#",
-"> Z+h#i#S *.D j#k#W.l#m#n#o#p#q#n.r#s#t#u#v#w#'@ @x#y#8@z#A#x@B#n C#D#E#n G F#G#&+|+> H#I#b@J#! ",
-"> Z+h#U K#k+L#D M#N#o O#P#Q#s.|+R#S#T#U#V#W#X#Y#0 !+r.Z#`#x@x@o $.$+$3 n e ] U ) 3#i@@$#$[ $$G#",
-"> 2 e ( p %$&$*$=$V -$;$>$,$'$)$!$~$-@{$]$h ^$/$($_$:$<$2 [$1 n > ( 7 }$o e ] _ { [ 7.|$1$2$o@3$",
-"> e e ( p 3 4$5$6$8.7$8$9$0$a$b$c$d$e$f$g$h$P@i$j$k$l$m$n$o$n 2 e { / _ } 6 ( 7 / p$q$r$s$t$u$l ",
-"> e ] { _ p 7 S ~.!.i+/.d.v$w$x$y${.z$A$B$C$D$E$F$G$H$I$7$J$e > ] ] , ' K$) ( }$p ^ L$x M$N$|+O$",
-"> ( ( ( ( ( > P$, Q$!.R$ @S$T$U$!.V$].W$X$k Y$Z$$$ +$$e `$ %] ] > K.O .%i+1.( }$}$( +%m+c.@%_.#%",
-"> _ _ ] e e e <@e $%z+%%g.x.&%*%B@=%-+j 8$-%;%F m. @>%,%'%)%( ( ' O !%~%n@8.F#3 3 {%]%| ^%/%(%, ",
-"> p 7 { e n n _%:%A S <%-+[%/ }%|%h#1%2%3%Y.`.4%:+&+5%6%/ l+7 ( K.7%8%9%n@f@9.0%b {%,@| a%b%c%> ",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > 2 e > { ( d%e%o f%g%h%i%",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > 2 e > { ( j%~ *#k%(@l%m%",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > 2 e > { / / n%o%o p%q%r%",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > n e e { / / s%> t%u%^%v%",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > n e e { / / / { w%> x%y%",
-"> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > 2 e e ] / / K#z%A%B%C%x+",
-"> > D%> > E%> ~ > > ~ > > F%F%F%F%F%F%> > F%> ~ D%F%~ D%D%~ > ~ > ~ G%> Z+e e > ( 0.T / F H%I%3#",
-"~ > > > > F%> > > > ~ > > > > > > > ~ > > F%> > F%F%F%F%F%F%> G%~ > ~ > W J%h#K%L%M%N%O%P%N%+#Q%",
-"> > F%F%> F%E%~ G%D%> ~ G%F%F%F%F%F%F%F%F%D%F%F%~ > > > > > F%G%F%~ F%~ > > > > > > ] K%! ! ! R%",
-"S%~ > ~ ~ ~ > ~ > > ~ ~ > ~ ~ ~ ~ ~ > ~ ~ > ~ > ~ E%T%D%F%T%~ > > ~ ~ > E%T%T%U%V%W%X%W%Y%F%D%Z%",
-"> F%> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > ' ",
-"`% &.&+&@&#&$&%&&&+&*&=&.&-&;&>&+&#&,&=&'&+&)&!&.&;&!&~&{&]&^&/& &&&(&_&:&<&[&{&}&|&1&2&3&4&5&6&",
-"> 7&] > 8&( > 9&{ ( 0&a&> b&c&> d&e&> f&g&> h&i&> j&k&> e&d&( ] l&m&> n&> ( o&0&> p&q&_ j&r&( s&",
-"t&u&n%v&t&v&] w&] ] x&^ > y&z&] v&> ] > A&^ > v&B&^ C&^ K%> ] D&t&] > t&^ v&y&v&t&] E&B&D&E&> > ",
-"F&>&> F%G%> > ~ F%~ ~ F%T%G&H&D%D%D%E%~ > I&> F%> J&K&S%> F%> T%~ ~ I&> L&> ]&M&n%> > I&F%> G%{ ",
-"N&O&> F%w%> D%> > > ~ F%P&Q&R&> > > > S&> > T&> , U&V&W&, D%> > , > > X&> , Y&Z&~ > `&~ > G%, *",
-".*+*Q$[.R%) ' R%' ' R%Q$@*#*< $*%*Q$, &*R%R%**' > =*-*Q$) ' 5%' ;*R%, %*y+>*,*'*' )*%*' y+!*' U "};
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrum.cpp b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrum.cpp
deleted file mode 100644
index e7bec0d4df..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrum.cpp
+++ /dev/null
@@ -1,286 +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.
-
-============================================================================*/
-
-// Blueberry
-#include <berryISelectionService.h>
-#include <berryIWorkbenchWindow.h>
-// Qmitk
-#include "PointSetInteractionMultispectrum.h"
-#include "QmitkPointListWidget.h"
-#include "QmitkRenderWindow.h"
-
-// Qt
-#include <QMessageBox>
-#include <QApplication>
-#include <qwt_plot.h>
-#include <qwt_plot_curve.h>
-#include <qwt_plot_grid.h>
-#include <qwt_symbol.h>
-#include <qwt_legend.h>
-#include <QColor>
-#include <QString>
-
-//mitk image
-#include <mitkImage.h>
-#include <mitkImagePixelReadAccessor.h>
-
-// MITK
-#include "mitkITKImageImport.h"
-#include "mitkProperties.h"
-#include "mitkColorProperty.h"
-#include "mitkImageCast.h"
-#include <mitkVector.h>
-#include <mitkPoint.h>
-#include <mitkImageStatisticsHolder.h>
-// ITK
-#include <itkConnectedThresholdImageFilter.h>
-
-const std::string PointSetInteractionMultispectrum::VIEW_ID =
- "org.mitk.views.pointsetinteractionmultispectrum";
-
-PointSetInteractionMultispectrum::PointSetInteractionMultispectrum() :
- m_PointListWidget(nullptr)
-{
-
-}
-
-void PointSetInteractionMultispectrum::SetFocus()
-{
- m_Controls.buttonPerformImageProcessing->setFocus();
-}
-
-void PointSetInteractionMultispectrum::CreateQtPartControl(QWidget *parent)
-{
- // create GUI widgets from the Qt Designer's .ui file
- m_Controls.setupUi(parent);
- connect(m_Controls.buttonPerformImageProcessing, SIGNAL(clicked()), this,
- SLOT(DoImageProcessing()));
-
- //! [cpp-createqtpartcontrol]
- // create a QmitkPointListWidget and add it to the widget created from .ui file
- m_PointListWidget = new QmitkPointListWidget();
- m_Controls.verticalLayout->addWidget(m_PointListWidget, 1);
-
- // retrieve a possibly existing IRenderWindowPart
- if (mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart())
- {
- // let the point set widget know about the render window part (crosshair updates)
- RenderWindowPartActivated(renderWindowPart);
- }
-
- // create a new DataNode containing a PointSet with some interaction
- m_PointSet = mitk::PointSet::New();
- mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New();
- pointSetNode->SetData(m_PointSet);
- pointSetNode->SetName("points for displaying reflectance.");
- pointSetNode->SetProperty("helper object", mitk::BoolProperty::New(true));
- pointSetNode->SetProperty("layer", mitk::IntProperty::New(1024));
-
- // add the pointset to the data storage (for rendering and access by other modules)
- GetDataStorage()->Add(pointSetNode);
-
- // tell the GUI widget about the point set
- m_PointListWidget->SetPointSetNode(pointSetNode);
- //! [cpp-createqtpartcontrol]
-
- m_Plot = new QwtPlot();
-}
-
-
-void PointSetInteractionMultispectrum::OnSelectionChanged(
- berry::IWorkbenchPart::Pointer /*source*/,
- const QList<mitk::DataNode::Pointer>& nodes) {
- // iterate all selected objects, adjust warning visibility
- foreach( mitk::DataNode::Pointer node, nodes ){
- if( node.IsNotNull() && dynamic_cast<mitk::Image*>(node->GetData()) )
- {
- m_Controls.labelWarning->setVisible( false );
- m_Controls.buttonPerformImageProcessing->setEnabled( true );
- return;
- }
- }
-
- m_Controls.labelWarning->setVisible( true );
- m_Controls.buttonPerformImageProcessing->setEnabled( false );
-}
-
-
-void PointSetInteractionMultispectrum::RenderWindowPartActivated(
- mitk::IRenderWindowPart* renderWindowPart)
-{
- // let the point set widget know about the slice navigation controllers
- // in the active render window part (crosshair updates)
- foreach(QmitkRenderWindow* renderWindow, renderWindowPart->GetQmitkRenderWindows().values())
- {
- m_PointListWidget->AddSliceNavigationController(renderWindow->GetSliceNavigationController());
- }
-}
-
-void PointSetInteractionMultispectrum::RenderWindowPartDeactivated(
- mitk::IRenderWindowPart* renderWindowPart)
-{
- foreach(QmitkRenderWindow* renderWindow, renderWindowPart->GetQmitkRenderWindows().values())
- {
- m_PointListWidget->RemoveSliceNavigationController(renderWindow->GetSliceNavigationController());
- }
-}
-
-void PointSetInteractionMultispectrum::DoImageProcessing()
-{
- QList<mitk::DataNode::Pointer> DataManagerNodes =
- this->GetDataManagerSelection();
- if (DataManagerNodes.empty())
- return;
-
- mitk::DataNode* DataManagerNode = DataManagerNodes.front();
-
- if (!DataManagerNode)
- {
- // Nothing selected. Inform the user and return
- QMessageBox::information( nullptr, "Template",
- "Please load and select an image before starting image processing.");
- return;
- }
-
- // here we have a valid mitk::DataNode
- // a node itself is not very useful, we need its data item (the image).
- // notice that this is the 'BaseData' type.
-
- mitk::BaseData* data = DataManagerNode->GetData();
- if (data)
- {
- // test if this data item is an image or not (could also be a surface or something totally different)
- mitk::Image* image = dynamic_cast<mitk::Image*>(data);
- if (image)
- {
- //! [cpp-doimageprocessing]
- // So we have an image. Let's see if the user has set some seed points already
- if (m_PointSet->GetSize() == 0)
- {
- // no points there. Not good for region growing
- QMessageBox::information( nullptr,
- "Reflectance display functionality",
- "Please set some points inside the image first.\n"
- "(hold Shift key and click left mouse button inside the image.)");
- return;
- }
-
- // plot the reflectances //
- PlotReflectance(m_PointSet, DataManagerNodes);
-
- //! [cpp-doimageprocessing]
- }
- }
-}
-
-
-void PointSetInteractionMultispectrum::PlotReflectance(mitk::PointSet::Pointer m_PointSet, QList<mitk::DataNode::Pointer> dataManagerNodes)
-{
- mitk::PointSet::PointsIterator PtIterator; // The point iterator in the PointSet, which gets access to each point.
- mitk::Point3D Point; // The extracted point. Notice that a point has three components (x, y, z).
- itk::Index<3> index; // The 3D index, which is converted from the world coordinate
- itk::Index<2> index2; // The truncated version of the 3D index, for which only the first two components are extracted.
- itk::VectorImage<double, 2>::Pointer itkImage; // The itk vector image. This is used since the mitk::Image could not handle multi-channel images well.
-
-
- // //////////////// Qwt window configuration /////////////////////////////////////////////
- delete m_Plot;
- m_Plot = new QwtPlot(); // create a new plot //
- m_Plot->setAxisAutoScale(QwtPlot::xBottom); // automatical scale -x //
- m_Plot->setAxisAutoScale(QwtPlot::yLeft); // automatical scale -y //
- m_Plot->setTitle("Multispectral Reflectance"); // set the plot title //
- m_Plot->setCanvasBackground(Qt::white); // set the background color //
- m_Plot->insertLegend(new QwtLegend()); // set the legend //
- QwtPlotGrid* grid = new QwtPlotGrid(); // set the grid //
- grid->attach(m_Plot); // set the grid //
- m_Controls.verticalLayout->addWidget(m_Plot, 1); // put the plot into the workbench //
-
- // the number of the plotted curve
- int curveIdx = 0;
-
- // iterate selected datanodes:
- for (auto node = dataManagerNodes.begin(); node != dataManagerNodes.end(); ++node)
- {
- mitk::BaseData* data = node->GetPointer()->GetData();
-
- // the current number of examined data point:
- int pointIdx = 0;
-
- if (data)
- {
- std::string curveNameString = "";
-
- node->GetPointer()->GetStringProperty("name", curveNameString);
-
- curveNameString += " point ";
-
- // test if this data item is an image or not (could also be a surface or something totally different)
- mitk::Image* image = dynamic_cast<mitk::Image*>(data);
- if (image)
- {
- // convert the MITK image to the ITK image //
- mitk::CastToItkImage(image, itkImage);
-
-
- ////////////////////////// main loop /////////////////////////////////
- int reflectanceIdx;
- itk::VariableLengthVector<double> reflectance;
- int channels;
-
- // The loop goes through each point in the point set //
- for (PtIterator = m_PointSet->Begin(0); PtIterator != m_PointSet->End(0); PtIterator++)
- {
-
- // extract the reflectance on a given pixel //
- Point = PtIterator.Value();
- image->GetGeometry(0)->WorldToIndex(Point, index);
- index2[0] = index[0];
- index2[1] = index[1];
- reflectance = itkImage->GetPixel(index2);
- channels = reflectance.GetNumberOfElements();
-
- // plot the reflectance dynamically //
- // create colors for each element in pointset.
- // "randomly" select colors for each added point by multiplying with prime.
- QColor curveColor((200 + (41 * curveIdx)) % 255, (89 * curveIdx) % 255,
- (37 * curveIdx) % 255);
-
- QString curveName(curveNameString.c_str());
- curveName.append(QString::number(pointIdx));
-
- QPolygonF qwtPoints;
- QwtPlotCurve* curve = new QwtPlotCurve();
- curve->setTitle(curveName);
- curve->setPen(curveColor, 4);
- curve->setRenderHint(QwtPlotItem::RenderAntialiased, true);
- QwtSymbol *symbol = new QwtSymbol(QwtSymbol::Ellipse,
- QBrush(Qt::yellow), QPen(Qt::black, 2), QSize(10, 10));
-
- for (reflectanceIdx = 0; reflectanceIdx < channels; reflectanceIdx++)
- {
- qwtPoints<< QPointF((double) reflectanceIdx,reflectance.GetElement(reflectanceIdx));
- }
-
- curve->setSamples(qwtPoints);
- curve->setSymbol(symbol);
- curve->attach(m_Plot);
- m_Plot->show();
-
- ++curveIdx;
- ++pointIdx;
- }
- }
- }
- }
-
-}
-
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrum.h b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrum.h
deleted file mode 100644
index e43934a39d..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrum.h
+++ /dev/null
@@ -1,79 +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 PointSetInteractionMultispectrum_h
-#define PointSetInteractionMultispectrum_h
-
-#include <berryISelectionListener.h>
-
-#include <QmitkAbstractView.h>
-#include <qwt_plot.h>
-#include "ui_PointSetInteractionMultispectrumControls.h"
-
-/////////////added from the regiongrowing plugin//////////////
-#include "mitkPointSet.h" ///////
-#include "mitkIRenderWindowPartListener.h" ///////
-#include <itkImage.h> ///////
-//////////////////////////////////////////////////////////////
-/**
- \brief PointSetInteractionMultispectrum
-
- \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation.
-
- \sa QmitkAbstractView
- \ingroup ${plugin_target}_internal
-*/
-
-class QmitkPointListWidget;
-
-class PointSetInteractionMultispectrum : public QmitkAbstractView
-{
- Q_OBJECT
-
- public:
-
- static const std::string VIEW_ID;
- PointSetInteractionMultispectrum();
-
-
- protected slots:
-
- /// \brief Called when the user clicks the GUI button
- void DoImageProcessing();
-
- protected:
-
-
- void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart);
- void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart);
-
-
- void CreateQtPartControl(QWidget *parent) override;
-
- void SetFocus() override;
-
- void OnSelectionChanged( berry::IWorkbenchPart::Pointer source,
- const QList<mitk::DataNode::Pointer>& nodes ) override;
-
- Ui::PointSetInteractionMultispectrumControls m_Controls;
-
- private:
-
- void PlotReflectance(mitk::PointSet::Pointer m_PointSet, QList<mitk::DataNode::Pointer> dataManagerNodes);
-
- mitk::PointSet::Pointer m_PointSet;
- QmitkPointListWidget* m_PointListWidget;
- QwtPlot* m_Plot;
-
-};
-
-#endif // PointSetInteractionMultispectrum_h
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrumControls.ui b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrumControls.ui
deleted file mode 100644
index 8434f88266..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/PointSetInteractionMultispectrumControls.ui
+++ /dev/null
@@ -1,64 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>PointSetInteractionMultispectrumControls</class>
- <widget class="QWidget" name="PointSetInteractionMultispectrumControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>222</width>
- <height>161</height>
- </rect>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="windowTitle">
- <string>QmitkTemplate</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QLabel" name="labelWarning">
- <property name="styleSheet">
- <string notr="true">QLabel { color: rgb(255, 0, 0) }</string>
- </property>
- <property name="text">
- <string>Please select an image!</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonPerformImageProcessing">
- <property name="toolTip">
- <string>Do image processing</string>
- </property>
- <property name="text">
- <string>Plot</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="spacer1">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Expanding</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>220</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- <layoutdefault spacing="6" margin="11"/>
- <resources/>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.cpp b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.cpp
deleted file mode 100644
index 316f60f3e1..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.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 "org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.h"
-#include "PointSetInteractionMultispectrum.h"
-
-namespace mitk {
-
-void org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator::start(ctkPluginContext* context)
-{
- BERRY_REGISTER_EXTENSION_CLASS(PointSetInteractionMultispectrum, context)
-}
-
-void org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator::stop(ctkPluginContext* context)
-{
- Q_UNUSED(context)
-}
-
-}
diff --git a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.h b/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.h
deleted file mode 100644
index ad19f09da3..0000000000
--- a/Plugins/org.mitk.gui.qt.pointsetinteractionmultispectrum/src/internal/org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator.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 org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator_h
-#define org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator_h
-
-#include <ctkPluginActivator.h>
-
-namespace mitk {
-
-class org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator :
- public QObject, public ctkPluginActivator
-{
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_pointsetinteractionmultispectrum")
- Q_INTERFACES(ctkPluginActivator)
-
-public:
-
- void start(ctkPluginContext* context) override;
- void stop(ctkPluginContext* context) override;
-
-}; // org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator
-
-}
-
-#endif // org_mitk_gui_qt_pointsetinteractionmultispectrum_Activator_h
diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyItemSortFilterProxyModel.cpp b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyItemSortFilterProxyModel.cpp
index c0cceb0cdb..ae94c7b090 100644
--- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyItemSortFilterProxyModel.cpp
+++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyItemSortFilterProxyModel.cpp
@@ -1,54 +1,54 @@
/*============================================================================
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 "QmitkPropertyItemSortFilterProxyModel.h"
QmitkPropertyItemSortFilterProxyModel::QmitkPropertyItemSortFilterProxyModel(QObject* parent)
: QSortFilterProxyModel(parent)
{
}
QmitkPropertyItemSortFilterProxyModel::~QmitkPropertyItemSortFilterProxyModel()
{
}
bool QmitkPropertyItemSortFilterProxyModel::FilterAcceptsAnyChildRow(const QModelIndex& sourceParent) const
{
QString propertyName = this->sourceModel()->data(sourceParent).toString();
- if (propertyName.contains(this->filterRegExp()))
+ if (propertyName.contains(this->filterRegularExpression()))
return true;
if (this->sourceModel()->hasChildren(sourceParent))
{
for (int row = 0; row < this->sourceModel()->rowCount(sourceParent); ++row)
{
if(this->FilterAcceptsAnyChildRow(this->sourceModel()->index(row, 0, sourceParent)))
return true;
}
}
return false;
}
bool QmitkPropertyItemSortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
{
return this->FilterAcceptsAnyChildRow(this->sourceModel()->index(sourceRow, 0, sourceParent));
}
bool QmitkPropertyItemSortFilterProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const
{
QString leftString = this->sourceModel()->data(left).toString();
QString rightString = this->sourceModel()->data(right).toString();
return leftString.compare(rightString, this->sortCaseSensitivity()) < 0;
}
diff --git a/Plugins/org.mitk.gui.qt.renderwindowmanager/src/internal/QmitkRenderWindowManagerView.cpp b/Plugins/org.mitk.gui.qt.renderwindowmanager/src/internal/QmitkRenderWindowManagerView.cpp
index 4dfecdd956..f6c200a153 100644
--- a/Plugins/org.mitk.gui.qt.renderwindowmanager/src/internal/QmitkRenderWindowManagerView.cpp
+++ b/Plugins/org.mitk.gui.qt.renderwindowmanager/src/internal/QmitkRenderWindowManagerView.cpp
@@ -1,168 +1,169 @@
/*============================================================================
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.
============================================================================*/
// render window manager plugin
#include "QmitkRenderWindowManagerView.h"
// mitk core
#include <mitkBaseRenderer.h>
#include <mitkDataNode.h>
#include <QmitkRenderWindow.h>
// mitk qt widgets
#include <QmitkAbstractMultiWidget.h>
#include <QmitkRenderWindowWidget.h>
// mitk gui qt common plugin
#include <QmitkAbstractMultiWidgetEditor.h>
const std::string QmitkRenderWindowManagerView::VIEW_ID = "org.mitk.views.renderwindowmanager";
void QmitkRenderWindowManagerView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
{
if (m_RenderWindowPart != renderWindowPart)
{
m_RenderWindowPart = renderWindowPart;
this->SetControlledRenderer();
// if the render window part is an abstract multi widget editor we can receive the abstract multi widget and listen to the signal
auto abstractMultiWidgetEditor = dynamic_cast<QmitkAbstractMultiWidgetEditor*>(m_RenderWindowPart);
if (nullptr != abstractMultiWidgetEditor)
{
connect(abstractMultiWidgetEditor->GetMultiWidget(), &QmitkAbstractMultiWidget::ActiveRenderWindowChanged,
this, &QmitkRenderWindowManagerView::RenderWindowChanged);
}
}
}
void QmitkRenderWindowManagerView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart)
{
if (m_RenderWindowPart == renderWindowPart)
{
// if the render window part is an abstract multi widget editor we need to disconnect the signal before release the render window part
auto abstractMultiWidgetEditor = dynamic_cast<QmitkAbstractMultiWidgetEditor*>(m_RenderWindowPart);
if (nullptr != abstractMultiWidgetEditor)
{
disconnect(abstractMultiWidgetEditor->GetMultiWidget(), &QmitkAbstractMultiWidget::ActiveRenderWindowChanged,
this, &QmitkRenderWindowManagerView::RenderWindowChanged);
}
m_RenderWindowPart = nullptr;
this->SetControlledRenderer();
}
}
void QmitkRenderWindowManagerView::RenderWindowPartInputChanged(mitk::IRenderWindowPart* renderWindowPart)
{
if (m_RenderWindowPart == renderWindowPart)
{
this->SetControlledRenderer();
}
}
void QmitkRenderWindowManagerView::CreateQtPartControl(QWidget* parent)
{
m_Parent = parent;
// create GUI widgets
m_Controls.setupUi(parent);
// add custom render window manager UI widget to the 'renderWindowManagerTab'
m_RenderWindowInspector = new QmitkRenderWindowDataStorageInspector(parent);
m_RenderWindowInspector->SetDataStorage(GetDataStorage());
m_RenderWindowInspector->setObjectName(QStringLiteral("m_RenderWindowManipulatorWidget"));
m_Controls.verticalLayout->addWidget(m_RenderWindowInspector);
// data node context menu and menu actions
m_InspectorView = m_RenderWindowInspector->GetView();
m_DataNodeContextMenu = new QmitkDataNodeContextMenu(GetSite(), m_InspectorView);
m_DataNodeContextMenu->SetDataStorage(GetDataStorage());
//m_DataNodeContextMenu->SetSurfaceDecimation(m_SurfaceDecimation);
// connect objects
- connect(m_Controls.comboBoxRenderWindowSelection, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged),
- this, &QmitkRenderWindowManagerView::OnRenderWindowSelectionChanged);
+ connect(m_Controls.comboBoxRenderWindowSelection, &QComboBox::currentIndexChanged, [this](int index) {
+ OnRenderWindowSelectionChanged(m_Controls.comboBoxRenderWindowSelection->itemText(index));
+ });
connect(m_InspectorView, &QAbstractItemView::customContextMenuRequested,
m_DataNodeContextMenu, &QmitkDataNodeContextMenu::OnContextMenuRequested);
auto renderWindowPart = GetRenderWindowPart();
if (nullptr != renderWindowPart)
{
this->RenderWindowPartActivated(renderWindowPart);
}
// also sets the controlled renderer
this->SetControlledRenderer();
}
void QmitkRenderWindowManagerView::SetControlledRenderer()
{
QHash<QString, QmitkRenderWindow*> renderWindows;
if (nullptr != m_RenderWindowPart)
{
renderWindows = m_RenderWindowPart->GetQmitkRenderWindows();
}
mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer;
QStringList rendererNames;
m_Controls.comboBoxRenderWindowSelection->clear();
mitk::BaseRenderer* baseRenderer = nullptr;
for (const auto& renderWindow : renderWindows.values())
{
baseRenderer = mitk::BaseRenderer::GetInstance(renderWindow->GetVtkRenderWindow());
if (nullptr != baseRenderer)
{
controlledRenderer.push_back(baseRenderer);
rendererNames.append(baseRenderer->GetName());
}
}
m_RenderWindowInspector->SetControlledRenderer(controlledRenderer);
rendererNames.sort();
m_Controls.comboBoxRenderWindowSelection->addItems(rendererNames);
}
void QmitkRenderWindowManagerView::OnRenderWindowSelectionChanged(const QString& renderWindowId)
{
m_RenderWindowInspector->SetActiveRenderWindow(renderWindowId);
mitk::BaseRenderer* selectedRenderer = mitk::BaseRenderer::GetByName(renderWindowId.toStdString());
if (nullptr != selectedRenderer)
{
m_DataNodeContextMenu->SetBaseRenderer(selectedRenderer);
}
// if the render window part is an abstract multi widget editor we can set the active render window
auto abstractMultiWidgetEditor = dynamic_cast<QmitkAbstractMultiWidgetEditor*>(m_RenderWindowPart);
if (nullptr != abstractMultiWidgetEditor)
{
auto renderWindowWidget = abstractMultiWidgetEditor->GetMultiWidget()->GetRenderWindowWidget(renderWindowId);
abstractMultiWidgetEditor->GetMultiWidget()->SetActiveRenderWindowWidget(renderWindowWidget);
}
}
void QmitkRenderWindowManagerView::RenderWindowChanged()
{
auto abstractMultiWidget = dynamic_cast<QmitkAbstractMultiWidget*>(sender());
if (nullptr != abstractMultiWidget)
{
auto activeRenderWindowWidget = abstractMultiWidget->GetActiveRenderWindowWidget();
if (nullptr != activeRenderWindowWidget)
{
m_Controls.comboBoxRenderWindowSelection->setCurrentText(activeRenderWindowWidget->GetWidgetName());
}
}
}
QItemSelectionModel* QmitkRenderWindowManagerView::GetDataNodeSelectionModel() const
{
return m_InspectorView->selectionModel();
}
diff --git a/Plugins/org.mitk.gui.qt.segmentation/CMakeLists.txt b/Plugins/org.mitk.gui.qt.segmentation/CMakeLists.txt
index 92eac09671..34669b28da 100644
--- a/Plugins/org.mitk.gui.qt.segmentation/CMakeLists.txt
+++ b/Plugins/org.mitk.gui.qt.segmentation/CMakeLists.txt
@@ -1,10 +1,10 @@
project(org_mitk_gui_qt_segmentation)
include_directories(${CTK_INCLUDE_DIRS})
mitk_create_plugin(
EXPORT_DIRECTIVE MITK_QT_SEGMENTATION
EXPORTED_INCLUDE_SUFFIXES src
MODULE_DEPENDS MitkAppUtil MitkQtWidgetsExt MitkSegmentationUI
- PACKAGE_DEPENDS Qt5|OpenGL nlohmann_json
+ PACKAGE_DEPENDS Qt6|OpenGL nlohmann_json
)
diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp
index fce39a51d1..b93bb00172 100644
--- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp
+++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkNewSegmentationDialog.cpp
@@ -1,406 +1,406 @@
/*============================================================================
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 "QmitkNewSegmentationDialog.h"
#include <ui_QmitkNewSegmentationDialog.h>
#include <mitkAnatomicalStructureColorPresets.h>
#include <mitkBaseApplication.h>
#include <mitkLabelSetImage.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
#include <algorithm>
#include <vtkNew.h>
#include <QColorDialog>
#include <QPushButton>
#include <nlohmann/json.hpp>
namespace
{
// Get standard label name and color suggestions from embedded XML preset file for anatomical structures.
QmitkNewSegmentationDialog::SuggestionsType GetStandardSuggestions()
{
vtkNew<mitk::AnatomicalStructureColorPresets> presets;
presets->LoadPreset();
auto colorPresets = presets->GetColorPresets();
QmitkNewSegmentationDialog::SuggestionsType standardSuggestions;
standardSuggestions.reserve(colorPresets.size());
for (const auto& preset : colorPresets)
{
auto name = QString::fromStdString(preset.first);
auto color = QColor::fromRgbF(preset.second.GetRed(), preset.second.GetGreen(), preset.second.GetBlue());
standardSuggestions.emplace_back(name, color);
}
std::sort(begin(standardSuggestions), end(standardSuggestions), [](const auto& lhs, const auto& rhs) {
return lhs.first < rhs.first;
});
return standardSuggestions;
}
// Parse label name and color suggestions from a JSON file. An array of objects is expected, each consisting
// of a "name" string and an optional "color" string. If present, the "color" string must follow the conventions
// of QColor::setNamedColor(), i.e., #rrggbb or any SVG color keyword name like CornflowerBlue. Everything else
// in the JSON file is simply ignored. In case of any error, an empty map is returned.
QmitkNewSegmentationDialog::SuggestionsType ParseSuggestions(const std::string& filename)
{
std::ifstream file(filename);
if (!file.is_open())
{
MITK_ERROR << "Could not open \"" << filename << "\"!";
return {};
}
auto json = nlohmann::json::parse(file, nullptr, false);
if (json.is_discarded() || !json.is_array())
{
MITK_ERROR << "Could not parse \"" << filename << "\" as JSON array!";
return {};
}
QmitkNewSegmentationDialog::SuggestionsType parsedSuggestions;
for (const auto& obj : json)
{
if (!obj.is_object() || !obj.contains("name"))
continue;
auto name = QString::fromStdString(obj["name"]);
QColor color;
if (obj.contains("color"))
- color.setNamedColor(QString::fromStdString(obj["color"]));
+ color = QColor::fromString(QString::fromStdString(obj["color"]));
auto it = std::find_if(begin(parsedSuggestions), end(parsedSuggestions), [&name](const auto& suggestion) {
return name == suggestion.first;
});
// Ignore duplicates...
if (it != parsedSuggestions.end())
{
// unless we can complete the original suggestion with a valid color.
if (!it->second.isValid() && color.isValid())
{
it->second = color;
}
else
{
MITK_WARN << "Ignoring duplicate of suggestion \"" << name.toStdString() << "\"!";
}
continue;
}
parsedSuggestions.emplace_back(name, color);
}
if (parsedSuggestions.empty())
MITK_WARN << "Could not parse any suggestions from \"" << filename << "\"!";
return parsedSuggestions;
}
struct Preferences
{
std::string labelSuggestions;
bool replaceStandardSuggestions;
bool suggestOnce;
std::vector<std::byte> geometry;
};
// Get all relevant preferences and consider command-line arguments overrides.
Preferences GetPreferences()
{
auto* nodePrefs = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation");
Preferences prefs;
prefs.labelSuggestions = mitk::BaseApplication::instance().config().getString(mitk::BaseApplication::ARG_SEGMENTATION_LABEL_SUGGESTIONS.toStdString(), "");
if (prefs.labelSuggestions.empty())
prefs.labelSuggestions = nodePrefs->Get("label suggestions", "");
prefs.replaceStandardSuggestions = nodePrefs->GetBool("replace standard suggestions", true);
prefs.suggestOnce = nodePrefs->GetBool("suggest once", true);
prefs.geometry = nodePrefs->GetByteArray("QmitkNewSegmentationDialog geometry", nullptr, 0);
return prefs;
}
void SaveGeometry(const QByteArray& geometry)
{
auto* nodePrefs = mitk::CoreServices::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.segmentation");
nodePrefs->PutByteArray("QmitkNewSegmentationDialog geometry", reinterpret_cast<const std::byte*>(geometry.data()), geometry.size());
}
// Get names of all labels in all layers of a LabelSetImage.
QStringList GetExistingLabelNames(mitk::LabelSetImage* labelSetImage)
{
QStringList existingLabelNames;
existingLabelNames.reserve(labelSetImage->GetTotalNumberOfLabels());
const auto numLayers = labelSetImage->GetNumberOfLayers();
for (std::remove_const_t<decltype(numLayers)> layerIndex = 0; layerIndex < numLayers; ++layerIndex)
{
const auto* labelSet = labelSetImage->GetLabelSet(layerIndex);
for (auto labelIter = labelSet->IteratorConstBegin(); labelIter != labelSet->IteratorConstEnd(); ++labelIter)
{
auto name = QString::fromStdString(labelIter->second->GetName());
if (!name.isEmpty()) // Potential duplicates do not matter for our purpose
existingLabelNames.push_back(name);
}
}
return existingLabelNames;
}
// Remove blacklisted suggestions.
QmitkNewSegmentationDialog::SuggestionsType FilterSuggestions(const QmitkNewSegmentationDialog::SuggestionsType& suggestions, const QStringList& blacklist)
{
QmitkNewSegmentationDialog::SuggestionsType filteredSuggestions;
std::remove_copy_if(begin(suggestions), end(suggestions), std::inserter(filteredSuggestions, end(filteredSuggestions)), [&blacklist](const auto& suggestion) {
return blacklist.contains(suggestion.first);
});
return filteredSuggestions;
}
}
QmitkNewSegmentationDialog::QmitkNewSegmentationDialog(QWidget *parent, mitk::LabelSetImage* labelSetImage, Mode mode)
: QDialog(parent),
m_Ui(new Ui::QmitkNewSegmentationDialog),
m_SuggestOnce(true),
m_Color(Qt::red)
{
m_Ui->setupUi(this);
if (RenameLabel == mode)
{
this->setWindowTitle("Rename Label");
m_Ui->label->setText("New name and color of the label");
m_Ui->buttonBox->button(QDialogButtonBox::Ok)->setText("Rename label");
}
else
{
m_Ui->buttonBox->button(QDialogButtonBox::Ok)->setText("Create label");
}
m_Ui->nameLineEdit->setFocus();
connect(this, &QDialog::finished, this, &QmitkNewSegmentationDialog::OnFinished);
connect(m_Ui->colorButton, &QToolButton::clicked, this, &QmitkNewSegmentationDialog::OnColorButtonClicked);
connect(m_Ui->nameLineEdit, &QLineEdit::textChanged, this, &QmitkNewSegmentationDialog::OnTextChanged);
connect(m_Ui->nameList, &QListWidget::itemSelectionChanged, this, &QmitkNewSegmentationDialog::OnSuggestionSelected);
connect(m_Ui->nameList, &QListWidget::itemDoubleClicked, this, &QmitkNewSegmentationDialog::OnAccept);
connect(m_Ui->buttonBox, &QDialogButtonBox::accepted, this, &QmitkNewSegmentationDialog::OnAccept);
this->UpdateColorButtonBackground();
auto prefs = GetPreferences();
if (!prefs.labelSuggestions.empty())
{
auto suggestions = ParseSuggestions(prefs.labelSuggestions);
this->SetSuggestions(suggestions, prefs.replaceStandardSuggestions && !suggestions.empty());
}
else
{
this->SetSuggestions(GetStandardSuggestions(), true);
}
if (nullptr != labelSetImage && prefs.suggestOnce)
{
auto existingLabelNames = GetExistingLabelNames(labelSetImage);
m_Suggestions = FilterSuggestions(m_Suggestions, existingLabelNames);
this->UpdateNameList();
}
if (!(prefs.geometry.empty()))
this->restoreGeometry(QByteArray(reinterpret_cast<const char*>(prefs.geometry.data()), prefs.geometry.size()));
}
QmitkNewSegmentationDialog::~QmitkNewSegmentationDialog()
{
}
void QmitkNewSegmentationDialog::OnFinished(int)
{
SaveGeometry(this->saveGeometry());
}
void QmitkNewSegmentationDialog::UpdateColorButtonBackground()
{
m_Ui->colorButton->setStyleSheet("background-color:" + m_Color.name());
}
QString QmitkNewSegmentationDialog::GetName() const
{
return m_Name;
}
mitk::Color QmitkNewSegmentationDialog::GetColor() const
{
mitk::Color color;
if (m_Color.isValid())
{
color.SetRed(m_Color.redF());
color.SetGreen(m_Color.greenF());
color.SetBlue(m_Color.blueF());
}
else
{
color.Set(1.0f, 0.0f, 0.0f);
}
return color;
}
void QmitkNewSegmentationDialog::SetName(const QString& name)
{
m_Ui->nameLineEdit->setText(name);
}
void QmitkNewSegmentationDialog::SetColor(const mitk::Color& color)
{
m_Color.setRgbF(color.GetRed(), color.GetGreen(), color.GetBlue());
this->UpdateColorButtonBackground();
}
void QmitkNewSegmentationDialog::SetSuggestions(const SuggestionsType& suggestions, bool replaceStandardSuggestions)
{
m_Suggestions = suggestions;
if (!replaceStandardSuggestions)
{
auto standardSuggestions = GetStandardSuggestions();
// Append all standard suggestions with unique names to the list of custom suggestions
std::remove_copy_if(begin(standardSuggestions), end(standardSuggestions), std::inserter(m_Suggestions, end(m_Suggestions)), [this](const auto& suggestion) {
return m_Suggestions.end() != std::find_if(begin(m_Suggestions), end(m_Suggestions), [&suggestion](const auto& otherSuggestion) {
return suggestion.first == otherSuggestion.first;
});
});
}
this->UpdateNameList();
}
void QmitkNewSegmentationDialog::UpdateNameList()
{
QStringList names;
for (const auto& suggestion : m_Suggestions)
names << suggestion.first;
m_Ui->nameList->clear();
m_Ui->nameList->addItems(names);
}
void QmitkNewSegmentationDialog::OnAccept()
{
m_Name = m_Ui->nameLineEdit->text();
this->accept();
}
void QmitkNewSegmentationDialog::OnTextChanged(const QString& text)
{
auto finding = m_Ui->nameList->findItems(text, Qt::MatchFlag::MatchExactly);
if (!finding.isEmpty())
m_Ui->nameList->setCurrentItem(finding.first());
}
void QmitkNewSegmentationDialog::OnColorButtonClicked()
{
auto color = QColorDialog::getColor(m_Color);
if (color.isValid())
{
m_Color = color;
this->UpdateColorButtonBackground();
}
}
void QmitkNewSegmentationDialog::OnSuggestionSelected()
{
const auto* currentItem = m_Ui->nameList->currentItem();
if (currentItem == nullptr)
return;
auto row = m_Ui->nameList->selectionModel()->selectedIndexes().first().row();
m_Ui->nameLineEdit->setText(m_Suggestions[row].first);
auto color = m_Suggestions[row].second;
if (color.isValid())
{
m_Color = color;
this->UpdateColorButtonBackground();
}
}
bool QmitkNewSegmentationDialog::DoRenameLabel(mitk::Label* label, mitk::LabelSetImage* segmentation, QWidget* parent, Mode mode)
{
if (nullptr == label)
mitkThrow() << "Invalid call of QmitkNewSegmentationDialog::RenameLabel. Passed label is null.";
const auto labelValue = label->GetValue();
mitk::LabelSetImage::GroupIndexType groupIndex;
if (nullptr != segmentation && !segmentation->IsLabelInGroup(labelValue, groupIndex))
mitkThrow() << "Invalid call of QmitkNewSegmentationDialog::RenameLabel. Passed label value does not exist in segmentation.";
QmitkNewSegmentationDialog dialog(parent, segmentation, mode);
dialog.SetColor(label->GetColor());
dialog.SetName(QString::fromStdString(label->GetName()));
if (dialog.exec() == QDialog::Rejected)
return false;
auto name = dialog.GetName();
if (name.isEmpty())
name = "Unnamed";
if (nullptr != segmentation)
{
auto group = segmentation->GetLabelSet(groupIndex);
group->RenameLabel(labelValue, name.toStdString(), dialog.GetColor());
group->UpdateLookupTable(labelValue);
}
else
{
label->SetName(name.toStdString());
label->SetColor(dialog.GetColor());
}
return true;
}
diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentAnythingPreferencePage.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentAnythingPreferencePage.cpp
index 66bbb404e1..b580f620ab 100644
--- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentAnythingPreferencePage.cpp
+++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentAnythingPreferencePage.cpp
@@ -1,356 +1,356 @@
/*============================================================================
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 "QmitkSegmentAnythingPreferencePage.h"
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
#include <mitkProcessExecutor.h>
#include <itkCommand.h>
#include <QmitkSegmentAnythingToolGUI.h>
#include <QFileDialog>
#include <QmitkStyleManager.h>
#include <QDir>
#include <QDirIterator>
namespace
{
mitk::IPreferences* GetPreferences()
{
auto* preferencesService = mitk::CoreServices::GetPreferencesService();
return preferencesService->GetSystemPreferences()->Node("org.mitk.views.segmentation");
}
}
QmitkSegmentAnythingPreferencePage::QmitkSegmentAnythingPreferencePage()
: m_Ui(new Ui::QmitkSegmentAnythingPreferencePage),
m_Control(nullptr){}
QmitkSegmentAnythingPreferencePage::~QmitkSegmentAnythingPreferencePage(){}
void QmitkSegmentAnythingPreferencePage::Init(berry::IWorkbench::Pointer){}
void QmitkSegmentAnythingPreferencePage::CreateQtControl(QWidget* parent)
{
m_Control = new QWidget(parent);
m_Ui->setupUi(m_Control);
m_Ui->samModelTipLabel->hide(); // TODO: All models except for vit_b seem to be unsupported by SAM?
#ifndef _WIN32
m_Ui->sysPythonComboBox->addItem("/usr/bin");
#endif
this->AutoParsePythonPaths();
m_Ui->timeoutEdit->setValidator(new QIntValidator(0, 1000, this));
m_Ui->sysPythonComboBox->addItem("Select...");
m_Ui->sysPythonComboBox->setCurrentIndex(0);
connect(m_Ui->installSAMButton, SIGNAL(clicked()), this, SLOT(OnInstallBtnClicked()));
connect(m_Ui->clearSAMButton, SIGNAL(clicked()), this, SLOT(OnClearInstall()));
connect(m_Ui->sysPythonComboBox,
QOverload<int>::of(&QComboBox::activated),
[=](int index) { OnSystemPythonChanged(m_Ui->sysPythonComboBox->itemText(index)); });
QIcon deleteIcon =
QmitkStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/edit-delete.svg"));
m_Ui->clearSAMButton->setIcon(deleteIcon);
const QString storageDir = m_Installer.GetVirtualEnvPath();
bool isInstalled = QmitkSegmentAnythingToolGUI::IsSAMInstalled(storageDir);
QString welcomeText;
if (isInstalled)
{
m_PythonPath = QmitkSetupVirtualEnvUtil::GetExactPythonPath(storageDir).first;
m_Installer.SetVirtualEnvPath(m_PythonPath);
welcomeText += " Segment Anything tool is already found installed.";
m_Ui->installSAMButton->setEnabled(false);
}
else
{
welcomeText += " Segment Anything tool not installed. Please click on \"Install SAM\" above. \
The installation will create a new virtual environment using the System Python selected above.";
m_Ui->installSAMButton->setEnabled(true);
}
this->WriteStatusMessage(welcomeText);
m_Ui->samModelTypeComboBox->addItems(VALID_MODELS);
m_Ui->gpuComboBox->addItem(CPU_ID);
this->SetGPUInfo();
this->Update();
}
QWidget* QmitkSegmentAnythingPreferencePage::GetQtControl() const
{
return m_Control;
}
bool QmitkSegmentAnythingPreferencePage::PerformOk()
{
auto* prefs = GetPreferences();
prefs->Put("sam parent path", m_Installer.STORAGE_DIR.toStdString());
prefs->Put("sam python path", m_PythonPath.toStdString());
prefs->Put("sam modeltype", m_Ui->samModelTypeComboBox->currentText().toStdString());
prefs->PutInt("sam gpuid", FetchSelectedGPUFromUI());
prefs->PutInt("sam timeout", std::stoi(m_Ui->timeoutEdit->text().toStdString()));
return true;
}
void QmitkSegmentAnythingPreferencePage::PerformCancel(){}
void QmitkSegmentAnythingPreferencePage::Update()
{
auto* prefs = GetPreferences();
m_Ui->samModelTypeComboBox->setCurrentText(QString::fromStdString(prefs->Get("sam modeltype", "vit_b")));
m_Ui->timeoutEdit->setText(QString::number(prefs->GetInt("sam timeout", 300)));
int gpuId = prefs->GetInt("sam gpuid", -1);
if (gpuId == -1)
{
m_Ui->gpuComboBox->setCurrentText(CPU_ID);
}
else if (m_GpuLoader.GetGPUCount() == 0)
{
m_Ui->gpuComboBox->setCurrentText(QString::number(gpuId));
}
else
{
std::vector<QmitkGPUSpec> specs = m_GpuLoader.GetAllGPUSpecs();
QmitkGPUSpec gpuSpec = specs[gpuId];
m_Ui->gpuComboBox->setCurrentText(QString::number(gpuSpec.id) + ": " + gpuSpec.name + " (" + gpuSpec.memory + ")");
}
}
std::pair<QString, QString> QmitkSegmentAnythingPreferencePage::OnSystemPythonChanged(const QString &pyEnv)
{
std::pair<QString, QString> pyPath;
if (pyEnv == QString("Select..."))
{
QString path = QFileDialog::getExistingDirectory(m_Ui->sysPythonComboBox->parentWidget(), "Python Path", "dir");
if (!path.isEmpty())
{
this->OnSystemPythonChanged(path); // recall same function for new path validation
bool oldState = m_Ui->sysPythonComboBox->blockSignals(true); // block signal firing while inserting item
m_Ui->sysPythonComboBox->insertItem(0, path);
m_Ui->sysPythonComboBox->setCurrentIndex(0);
m_Ui->sysPythonComboBox->blockSignals(oldState); // unblock signal firing after inserting item. Remove this after Qt6 migration
}
}
else
{
QString uiPyPath = this->GetPythonPathFromUI(pyEnv);
pyPath = QmitkSetupVirtualEnvUtil::GetExactPythonPath(uiPyPath);
}
return pyPath;
}
QString QmitkSegmentAnythingPreferencePage::GetPythonPathFromUI(const QString &pyUI) const
{
QString fullPath = pyUI;
if (-1 != fullPath.indexOf(")"))
{
fullPath = fullPath.mid(fullPath.indexOf(")") + 2);
}
return fullPath.simplified();
}
void QmitkSegmentAnythingPreferencePage::AutoParsePythonPaths()
{
QString homeDir = QDir::homePath();
std::vector<QString> searchDirs;
#ifdef _WIN32
searchDirs.push_back(QString("C:") + QDir::separator() + QString("ProgramData") + QDir::separator() +
QString("anaconda3"));
#else
// Add search locations for possible standard python paths here
searchDirs.push_back(homeDir + QDir::separator() + "anaconda3");
searchDirs.push_back(homeDir + QDir::separator() + "miniconda3");
searchDirs.push_back(homeDir + QDir::separator() + "opt" + QDir::separator() + "miniconda3");
searchDirs.push_back(homeDir + QDir::separator() + "opt" + QDir::separator() + "anaconda3");
#endif
for (QString searchDir : searchDirs)
{
if (searchDir.endsWith("anaconda3", Qt::CaseInsensitive))
{
if (QDir(searchDir).exists())
{
m_Ui->sysPythonComboBox->addItem("(base): " + searchDir);
searchDir.append((QDir::separator() + QString("envs")));
}
}
for (QDirIterator subIt(searchDir, QDir::AllDirs, QDirIterator::NoIteratorFlags); subIt.hasNext();)
{
subIt.next();
QString envName = subIt.fileName();
if (!envName.startsWith('.')) // Filter out irrelevent hidden folders, if any.
{
m_Ui->sysPythonComboBox->addItem("(" + envName + "): " + subIt.filePath());
}
}
}
}
void QmitkSegmentAnythingPreferencePage::SetGPUInfo()
{
std::vector<QmitkGPUSpec> specs = m_GpuLoader.GetAllGPUSpecs();
for (const QmitkGPUSpec &gpuSpec : specs)
{
m_Ui->gpuComboBox->addItem(QString::number(gpuSpec.id) + ": " + gpuSpec.name + " (" + gpuSpec.memory + ")");
}
if (specs.empty())
{
m_Ui->gpuComboBox->setCurrentIndex(m_Ui->gpuComboBox->findText("cpu"));
}
else
{
m_Ui->gpuComboBox->setCurrentIndex(m_Ui->gpuComboBox->count()-1);
}
}
int QmitkSegmentAnythingPreferencePage::FetchSelectedGPUFromUI() const
{
QString gpuInfo = m_Ui->gpuComboBox->currentText();
if ("cpu" == gpuInfo)
{
return -1;
}
else if(m_GpuLoader.GetGPUCount() == 0)
{
return static_cast<int>(gpuInfo.toInt());
}
else
{
- QString gpuId = gpuInfo.split(":", QString::SplitBehavior::SkipEmptyParts).first();
+ QString gpuId = gpuInfo.split(":", Qt::SkipEmptyParts).first();
return static_cast<int>(gpuId.toInt());
}
}
void QmitkSegmentAnythingPreferencePage::OnInstallBtnClicked()
{
const auto [path, version] = OnSystemPythonChanged(m_Ui->sysPythonComboBox->currentText());
if (path.isEmpty())
{
this->WriteErrorMessage("<b>ERROR: </b>Couldn't find compatible Python.");
return;
}
//check if python 3.12 and ask for confirmation
if (version.startsWith("3.12") &&
QMessageBox::No == QMessageBox::question(nullptr,
"Installing Segment Anything",
QString("WARNING: This is an unsupported version of Python that may not work. "
"We recommend using a supported Python version between 3.9 and 3.11.\n\n"
"Continue anyway?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No))
{
return;
}
this->WriteStatusMessage("<b>STATUS: </b>Installing SAM...");
m_Ui->installSAMButton->setEnabled(false);
m_Installer.SetSystemPythonPath(path);
bool isInstalled = false;
if (m_Installer.SetupVirtualEnv(m_Installer.VENV_NAME))
{
isInstalled = QmitkSegmentAnythingToolGUI::IsSAMInstalled(m_Installer.GetVirtualEnvPath());
}
if (isInstalled)
{
m_PythonPath = QmitkSetupVirtualEnvUtil::GetExactPythonPath(m_Installer.GetVirtualEnvPath()).first;
this->WriteStatusMessage("<b>STATUS: </b>Successfully installed SAM.");
}
else
{
this->WriteErrorMessage("<b>ERROR: </b>Couldn't install SAM.");
m_Ui->installSAMButton->setEnabled(true);
}
}
void QmitkSegmentAnythingPreferencePage::OnClearInstall()
{
QDir folderPath(m_Installer.GetVirtualEnvPath());
bool isDeleted = folderPath.removeRecursively();
if (isDeleted)
{
this->WriteStatusMessage("Deleted SAM installation.");
m_Ui->installSAMButton->setEnabled(true);
m_PythonPath.clear();
}
else
{
MITK_ERROR << "The virtual environment couldn't be removed. Please check if you have the required access "
"privileges or, some other process is accessing the folders.";
}
}
void QmitkSegmentAnythingPreferencePage::WriteStatusMessage(const QString &message)
{
m_Ui->samInstallStatusLabel->setText(message);
m_Ui->samInstallStatusLabel->setStyleSheet("font-weight: bold; color: white");
qApp->processEvents();
}
void QmitkSegmentAnythingPreferencePage::WriteErrorMessage(const QString &message)
{
m_Ui->samInstallStatusLabel->setText(message);
m_Ui->samInstallStatusLabel->setStyleSheet("font-weight: bold; color: red");
qApp->processEvents();
}
QString QmitkSAMInstaller::GetVirtualEnvPath()
{
return STORAGE_DIR + VENV_NAME;
}
bool QmitkSAMInstaller::SetupVirtualEnv(const QString &venvName)
{
if (GetSystemPythonPath().isEmpty())
{
return false;
}
QDir folderPath(GetBaseDir());
folderPath.mkdir(venvName);
if (!folderPath.cd(venvName))
{
return false; // Check if directory creation was successful.
}
mitk::ProcessExecutor::ArgumentListType args;
auto spExec = mitk::ProcessExecutor::New();
auto spCommand = itk::CStyleCommand::New();
spCommand->SetCallback(&PrintProcessEvent);
spExec->AddObserver(mitk::ExternalProcessOutputEvent(), spCommand);
args.push_back("-m");
args.push_back("venv");
args.push_back(venvName.toStdString());
#ifdef _WIN32
QString pythonFile = GetSystemPythonPath() + QDir::separator() + "python.exe";
QString pythonExeFolder = "Scripts";
#else
QString pythonFile = GetSystemPythonPath() + QDir::separator() + "python3";
QString pythonExeFolder = "bin";
#endif
spExec->Execute(GetBaseDir().toStdString(), pythonFile.toStdString(), args); // Setup local virtual environment
if (folderPath.cd(pythonExeFolder))
{
this->SetPythonPath(folderPath.absolutePath());
this->SetPipPath(folderPath.absolutePath());
this->InstallPytorch();
for (auto &package : PACKAGES)
{
this->PipInstall(package.toStdString(), &PrintProcessEvent);
}
std::string pythonCode; // python syntax to check if torch is installed with CUDA.
pythonCode.append("import torch;");
pythonCode.append("print('Pytorch was installed with CUDA') if torch.cuda.is_available() else print('PyTorch was "
"installed WITHOUT CUDA');");
this->ExecutePython(pythonCode, &PrintProcessEvent);
return true;
}
return false;
}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/CMakeLists.txt b/Plugins/org.mitk.gui.qt.semanticrelations/CMakeLists.txt
deleted file mode 100644
index 970cb000dd..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-project(org_mitk_gui_qt_semanticrelations)
-
-mitk_create_plugin(
- EXPORT_DIRECTIVE MITK_GUI_SEMANTICRELATIONS_EXPORT
- EXPORTED_INCLUDE_SUFFIXES src
- MODULE_DEPENDS MitkPersistence MitkSemanticRelationsUI MitkRenderWindowManager MitkMultilabel MitkSegmentationUI
-)
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/files.cmake b/Plugins/org.mitk.gui.qt.semanticrelations/files.cmake
deleted file mode 100644
index 09421a5b1d..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/files.cmake
+++ /dev/null
@@ -1,52 +0,0 @@
-set(INTERNAL_CPP_FILES
- mitkPluginActivator.cpp
- QmitkDataNodeAddToSemanticRelationsAction.cpp
- QmitkDataNodeRemoveFromSemanticRelationsAction.cpp
- QmitkDataNodeUnlinkFromLesionAction.cpp
- QmitkDataNodeSetControlPointAction.cpp
- QmitkDataNodeSetInformationTypeAction.cpp
- QmitkDataSetOpenInAction.cpp
- QmitkFocusOnLesionAction.cpp
- QmitkLabelSetJumpToAction.cpp
- QmitkLesionInfoWidget.cpp
- QmitkSemanticRelationsContextMenu.cpp
- QmitkSemanticRelationsNodeSelectionDialog.cpp
- QmitkSemanticRelationsStatisticsView.cpp
- QmitkSemanticRelationsView.cpp
-)
-
-set(UI_FILES
- src/internal/QmitkLesionInfoWidgetControls.ui
- src/internal/QmitkSemanticRelationsControls.ui
- src/internal/QmitkSemanticRelationsStatisticsControls.ui
-)
-
-set(MOC_H_FILES
- src/internal/mitkPluginActivator.h
- src/internal/QmitkDataNodeAddToSemanticRelationsAction.h
- src/internal/QmitkDataNodeRemoveFromSemanticRelationsAction.h
- src/internal/QmitkDataNodeUnlinkFromLesionAction.h
- src/internal/QmitkDataNodeSetControlPointAction.h
- src/internal/QmitkDataNodeSetInformationTypeAction.h
- src/internal/QmitkDataSetOpenInAction.h
- src/internal/QmitkFocusOnLesionAction.h
- src/internal/QmitkLabelSetJumpToAction.h
- src/internal/QmitkLesionInfoWidget.h
- src/internal/QmitkSemanticRelationsContextMenu.h
- src/internal/QmitkSemanticRelationsNodeSelectionDialog.h
- src/internal/QmitkSemanticRelationsStatisticsView.h
- src/internal/QmitkSemanticRelationsView.h
-)
-
-set(CACHED_RESOURCE_FILES
- resources/SemanticRelations_48.png
- resources/SemanticRelationsStatistics_48.png
- plugin.xml
-)
-
-set(QRC_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.semanticrelations/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.semanticrelations/manifest_headers.cmake
deleted file mode 100644
index ed90be50bd..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/manifest_headers.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(Plugin-Name "MITK Semantic relations")
-set(Plugin-Version "0.1")
-set(Plugin-Vendor "DKFZ")
-set(Plugin-ContactAddress "https://www.mitk.org")
-set(Require-Plugin org.mitk.gui.qt.common org.mitk.gui.qt.application org.mitk.gui.qt.segmentation)
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/plugin.xml b/Plugins/org.mitk.gui.qt.semanticrelations/plugin.xml
deleted file mode 100644
index 618c2e82f1..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/plugin.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<plugin>
-
- <extension point="org.blueberry.ui.views">
- <view id="org.mitk.views.semanticrelations"
- name="Semantic Relations"
- class="QmitkSemanticRelationsView"
- icon="resources/SemanticRelations_48.png"
- category="Semantic Relations"/>
-
- <view id="org.mitk.views.semanticrelationsstatistics"
- name="Semantic Relations Statistics"
- class="QmitkSemanticRelationsStatisticsView"
- icon="resources/SemanticRelationsStatistics_48.png"
- category="Semantic Relations"/>
- </extension>
-
-</plugin>
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/resources/SemanticRelationsStatistics_48.png b/Plugins/org.mitk.gui.qt.semanticrelations/resources/SemanticRelationsStatistics_48.png
deleted file mode 100644
index 182a722caf..0000000000
Binary files a/Plugins/org.mitk.gui.qt.semanticrelations/resources/SemanticRelationsStatistics_48.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/resources/SemanticRelations_48.png b/Plugins/org.mitk.gui.qt.semanticrelations/resources/SemanticRelations_48.png
deleted file mode 100644
index fc0096e0ac..0000000000
Binary files a/Plugins/org.mitk.gui.qt.semanticrelations/resources/SemanticRelations_48.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeAddToSemanticRelationsAction.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeAddToSemanticRelationsAction.cpp
deleted file mode 100644
index e587cb8cc3..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeAddToSemanticRelationsAction.cpp
+++ /dev/null
@@ -1,249 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkDataNodeAddToSemanticRelationsAction.h"
-#include "QmitkDataNodeRemoveFromSemanticRelationsAction.h"
-
-// semantic relations module
-#include <mitkControlPointManager.h>
-#include <mitkDICOMHelper.h>
-#include <mitkNodePredicates.h>
-#include <mitkSemanticRelationsDataStorageAccess.h>
-#include <mitkSemanticRelationsInference.h>
-#include <mitkSemanticRelationsIntegration.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkRelationStorage.h>
-#include <mitkUIDGeneratorBoost.h>
-
-// mitk gui common plugin
-#include <mitkDataNodeSelection.h>
-
-// mitk core
-#include <mitkTemporoSpatialStringProperty.h>
-
-// qt
-#include <QMessageBox>
-
-// namespace that contains the concrete action
-namespace AddToSemanticRelationsAction
-{
- void Run(mitk::DataStorage* dataStorage, const mitk::DataNode* dataNode)
- {
- if (nullptr == dataStorage
- || nullptr == dataNode)
- {
- return;
- }
-
- if (mitk::NodePredicates::GetImagePredicate()->CheckNode(dataNode))
- {
- try
- {
- AddImage(dataStorage, dataNode);
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
- }
- else if (mitk::NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
- {
- try
- {
- AddSegmentation(dataStorage, dataNode);
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
- }
- }
-
- void AddImage(mitk::DataStorage* dataStorage, const mitk::DataNode* image)
- {
- mitk::SemanticTypes::InformationType informationType;
- mitk::SemanticTypes::ExaminationPeriod examinationPeriod;
- mitk::SemanticRelationsDataStorageAccess::DataNodeVector allSpecificImages;
- try
- {
- mitk::SemanticTypes::CaseID caseID = GetCaseIDFromDataNode(image);
- informationType = GetDICOMModalityFromDataNode(image);
- // see if the examination period - information type cell is already taken
- examinationPeriod = FindFittingExaminationPeriod(image);
- auto semanticRelationsDataStorageAccess = mitk::SemanticRelationsDataStorageAccess(dataStorage);
- try
- {
- allSpecificImages = semanticRelationsDataStorageAccess.GetAllSpecificImages(caseID, informationType, examinationPeriod);
- }
- catch (const mitk::SemanticRelationException&)
- {
- // just continue since an exception means that there is no specific image
- }
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
-
- if (!allSpecificImages.empty())
- {
- // examination period - information type cell is already taken
- // ask if cell should be overwritten
- QMessageBox::StandardButton answerButton =
- QMessageBox::question(nullptr,
- "Specific image already exists.",
- QString::fromStdString("Force overwriting existing image " + informationType + " at " + examinationPeriod.name + "?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
-
- if (answerButton == QMessageBox::Yes)
- {
- try
- {
- // remove already existent images at specific cell
- for (const auto& specificImage : allSpecificImages)
- {
- RemoveFromSemanticRelationsAction::Run(dataStorage, specificImage);
- }
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- return;
- }
- }
- else
- {
- // else case is: no overwriting
- return;
- }
- }
-
- // specific image does not exist or has been removed; adding the image should work
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- try
- {
- semanticRelationsIntegration.AddImage(image);
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
- }
-
- void AddSegmentation(mitk::DataStorage* dataStorage, const mitk::DataNode* segmentation)
- {
- if (nullptr == segmentation)
- {
- return;
- }
-
- mitk::BaseData* baseData = segmentation->GetData();
- if (nullptr == baseData)
- {
- return;
- }
-
- // continue with valid segmentation data
- // get parent node of the current segmentation node with the node predicate
- mitk::DataStorage::SetOfObjects::ConstPointer parentNodes = dataStorage->GetSources(segmentation, mitk::NodePredicates::GetImagePredicate(), false);
- if (parentNodes->empty())
- {
- // segmentation without corresponding image will not be added
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not add the selected segmentation.",
- "The program wasn't able to correctly add the selected segmentation.\n"
- "Reason: No parent image found");
- msgBox.exec();
- return;
- }
-
- // check for already existing, identifying base properties
- auto caseIDPropertyName = mitk::GetCaseIDDICOMProperty();
- auto nodeIDPropertyName = mitk::GetNodeIDDICOMProperty();
- mitk::BaseProperty* caseIDProperty = baseData->GetProperty(caseIDPropertyName.c_str());
- mitk::BaseProperty* nodeIDProperty = baseData->GetProperty(nodeIDPropertyName.c_str());
- if (nullptr == caseIDProperty || nullptr == nodeIDProperty)
- {
- MITK_INFO << "No DICOM tags for case and node identification found. Transferring DICOM tags from the parent node to the selected segmentation node.";
-
- mitk::SemanticTypes::CaseID caseID;
- mitk::SemanticTypes::ID nodeID;
- try
- {
- caseID = mitk::GetCaseIDFromDataNode(parentNodes->front());
- nodeID = mitk::GetIDFromDataNode(parentNodes->front());
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- return;
- }
-
- // transfer DICOM tags to the segmentation node
- baseData->SetProperty(caseIDPropertyName, mitk::TemporoSpatialStringProperty::New(caseID));
- // add UID to distinguish between different segmentations of the same parent node
- baseData->SetProperty(nodeIDPropertyName, mitk::TemporoSpatialStringProperty::New(nodeID + mitk::UIDGeneratorBoost::GenerateUID()));
- }
-
- // add the parent node if not already existent
- if (!mitk::SemanticRelationsInference::InstanceExists(parentNodes->front()))
- {
- AddImage(dataStorage, parentNodes->front());
- }
-
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- try
- {
- // add the segmentation with its parent image to the semantic relations storage
- semanticRelationsIntegration.AddSegmentation(segmentation, parentNodes->front());
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
- }
-}
-
-QmitkDataNodeAddToSemanticRelationsAction::QmitkDataNodeAddToSemanticRelationsAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(workbenchPartSite)
-{
- setText(tr("Add to semantic relations"));
- InitializeAction();
-}
-
-QmitkDataNodeAddToSemanticRelationsAction::QmitkDataNodeAddToSemanticRelationsAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
-{
- setText(tr("Add to semantic relations"));
- InitializeAction();
-}
-
-void QmitkDataNodeAddToSemanticRelationsAction::InitializeAction()
-{
- connect(this, &QAction::triggered, this, &QmitkDataNodeAddToSemanticRelationsAction::OnActionTriggered);
-}
-
-void QmitkDataNodeAddToSemanticRelationsAction::OnActionTriggered(bool /*checked*/)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- auto dataNode = GetSelectedNode();
- AddToSemanticRelationsAction::Run(dataStorage, dataNode);
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeAddToSemanticRelationsAction.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeAddToSemanticRelationsAction.h
deleted file mode 100644
index 9fbf842373..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeAddToSemanticRelationsAction.h
+++ /dev/null
@@ -1,69 +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 QmitkDataNodeAddToSemanticRelationsAction_h
-#define QmitkDataNodeAddToSemanticRelationsAction_h
-
-#include <org_mitk_gui_qt_semanticrelations_Export.h>
-
-// mitk gui qt application plugin
-#include <QmitkAbstractDataNodeAction.h>
-
-// qt
-#include <QAction>
-
-namespace AddToSemanticRelationsAction
-{
- /**
- * @brief The function checks whether the given node is an image or a segmentation and calls the corresponding add function.
- * The corresponding add functions will add the data node to the semantic relations storage.
- * If an image is added, the 'AddImage' function will check if another image at the fitting control-point - information type cell
- * already exists. If so, the user is prompted to overwrite the existing image or abort the process.
- * If the user wants to overwrite the existing image, the image and it's corresponding segmentation nodes will be removed from the semantic relations storage.
- * If a segmentation is added, the parent image node will also be to the semantic relations storage. If the segmentation does not contain the required DICOM information,
- * the DICOM information of the parent data will be transferred to the segmentation data.
- *
- * @pre The given dataStorage has to be valid (!nullptr).
- * @pre The given dataNode has to be valid (!nullptr).
- * The function simply returns if the preconditions are not met.
- *
- * @throw SemanticRelationException re-thrown.
- *
- * @param dataStorage The data storage to use for to remove the existing image and to check for the parent image node of a segmentation.
- * @param dataNode The data node to add.
- */
- MITK_GUI_SEMANTICRELATIONS_EXPORT void Run(mitk::DataStorage* dataStorage, const mitk::DataNode* image);
-
- void AddImage(mitk::DataStorage* dataStorage, const mitk::DataNode* image);
- void AddSegmentation(mitk::DataStorage* dataStorage, const mitk::DataNode* segmentation);
-}
-
-class MITK_GUI_SEMANTICRELATIONS_EXPORT QmitkDataNodeAddToSemanticRelationsAction : public QAction, public QmitkAbstractDataNodeAction
-{
- Q_OBJECT
-
-public:
-
- QmitkDataNodeAddToSemanticRelationsAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite);
- QmitkDataNodeAddToSemanticRelationsAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite);
-
-private Q_SLOTS:
-
- void OnActionTriggered(bool);
-
-protected:
-
- void InitializeAction() override;
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeRemoveFromSemanticRelationsAction.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeRemoveFromSemanticRelationsAction.cpp
deleted file mode 100644
index e7b33a31a6..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeRemoveFromSemanticRelationsAction.cpp
+++ /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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkDataNodeRemoveFromSemanticRelationsAction.h"
-
-// semantic relations module
-#include <mitkNodePredicates.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsIntegration.h>
-
-// mitk gui common plugin
-#include <mitkDataNodeSelection.h>
-
-// qt
-#include <QMessageBox>
-
-// namespace that contains the concrete action
-namespace RemoveFromSemanticRelationsAction
-{
- void Run(mitk::DataStorage* dataStorage, const mitk::DataNode* dataNode)
- {
- if (nullptr == dataStorage
- || nullptr == dataNode)
- {
- return;
- }
-
- if (mitk::NodePredicates::GetImagePredicate()->CheckNode(dataNode))
- {
- try
- {
- RemoveImage(dataStorage, dataNode);
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
- }
- else if (mitk::NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
- {
- try
- {
- RemoveSegmentation(dataNode);
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
- }
- }
-
- void RemoveImage(mitk::DataStorage* dataStorage, const mitk::DataNode* image)
- {
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- try
- {
- // remove each corresponding segmentation from the semantic relations storage
- mitk::DataStorage::SetOfObjects::ConstPointer childNodes = dataStorage->GetDerivations(image, mitk::NodePredicates::GetSegmentationPredicate(), false);
- for (auto it = childNodes->Begin(); it != childNodes->End(); ++it)
- {
- RemoveSegmentation(it->Value());
- }
- // remove the image from the semantic relations storage
- semanticRelationsIntegration.RemoveImage(image);
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
- }
-
- void RemoveSegmentation(const mitk::DataNode* segmentation)
- {
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- try
- {
- // remove the segmentation from the semantic relations storage
- semanticRelationsIntegration.RemoveSegmentation(segmentation);
- }
- catch (mitk::SemanticRelationException& e)
- {
- mitkReThrow(e);
- }
- }
-}
-
-QmitkDataNodeRemoveFromSemanticRelationsAction::QmitkDataNodeRemoveFromSemanticRelationsAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(workbenchPartSite)
-{
- setText(tr("Remove from semantic relations"));
- InitializeAction();
-}
-
-QmitkDataNodeRemoveFromSemanticRelationsAction::QmitkDataNodeRemoveFromSemanticRelationsAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
-{
- setText(tr("Remove from semantic relations"));
- InitializeAction();
-}
-
-void QmitkDataNodeRemoveFromSemanticRelationsAction::InitializeAction()
-{
- connect(this, &QAction::triggered, this, &QmitkDataNodeRemoveFromSemanticRelationsAction::OnActionTriggered);
-}
-
-void QmitkDataNodeRemoveFromSemanticRelationsAction::OnActionTriggered(bool /*checked*/)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- auto dataNode = GetSelectedNode();
- RemoveFromSemanticRelationsAction::Run(dataStorage, dataNode);
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeRemoveFromSemanticRelationsAction.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeRemoveFromSemanticRelationsAction.h
deleted file mode 100644
index 590449473a..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeRemoveFromSemanticRelationsAction.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 QmitkDataNodeRemoveFromSemanticRelationsAction_h
-#define QmitkDataNodeRemoveFromSemanticRelationsAction_h
-
-#include <org_mitk_gui_qt_semanticrelations_Export.h>
-
-// mitk gui qt application plugin
-#include <QmitkAbstractDataNodeAction.h>
-
-// qt
-#include <QAction>
-
-namespace RemoveFromSemanticRelationsAction
-{
- /**
- * @brief The function checks whether the given node is an image or a segmentation and calls the corresponding remove function.
- * The corresponding remove functions will remove the data node from the semantic relations storage.
- * If an image is removed, the child segmentation nodes will also be removed from the semantic relations storage.
- *
- * @pre The given dataStorage has to be valid (!nullptr).
- * @pre The given dataNode has to be valid (!nullptr).
- * The function simply returns if the preconditions are not met.
- *
- * @throw SemanticRelationException re-thrown.
- *
- * @param dataStorage The data storage to use to check for the child segmentation nodes of an image.
- * @param dataNode The data node to remove.
- */
- MITK_GUI_SEMANTICRELATIONS_EXPORT void Run(mitk::DataStorage* dataStorage, const mitk::DataNode* dataNode);
-
- void RemoveImage(mitk::DataStorage* dataStorage, const mitk::DataNode* image);
- void RemoveSegmentation(const mitk::DataNode* segmentation);
-}
-
-class MITK_GUI_SEMANTICRELATIONS_EXPORT QmitkDataNodeRemoveFromSemanticRelationsAction : public QAction, public QmitkAbstractDataNodeAction
-{
- Q_OBJECT
-
-public:
-
- QmitkDataNodeRemoveFromSemanticRelationsAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite);
- QmitkDataNodeRemoveFromSemanticRelationsAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite);
-
-private Q_SLOTS:
-
- void OnActionTriggered(bool);
-
-protected:
-
- void InitializeAction() override;
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetControlPointAction.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetControlPointAction.cpp
deleted file mode 100644
index 58a8521275..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetControlPointAction.cpp
+++ /dev/null
@@ -1,170 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkDataNodeSetControlPointAction.h"
-#include "QmitkDataNodeRemoveFromSemanticRelationsAction.h"
-
-// semantic relations module
-#include <mitkControlPointManager.h>
-#include <mitkDICOMHelper.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsDataStorageAccess.h>
-#include <mitkSemanticRelationsInference.h>
-#include <mitkSemanticRelationsIntegration.h>
-#include <mitkUIDGeneratorBoost.h>
-
-// semantic relations UI module
-#include "QmitkControlPointDialog.h"
-
-// qt
-#include <QInputDialog>
-#include <QMessageBox>
-
-QmitkDataNodeSetControlPointAction::QmitkDataNodeSetControlPointAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(workbenchPartSite)
-{
- setText(tr("Set control point"));
- m_Parent = parent;
- InitializeAction();
-}
-
-QmitkDataNodeSetControlPointAction::QmitkDataNodeSetControlPointAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
-{
- setText(tr("Set control point"));
- m_Parent = parent;
- InitializeAction();
-}
-
-void QmitkDataNodeSetControlPointAction::InitializeAction()
-{
- connect(this, &QAction::triggered, this, &QmitkDataNodeSetControlPointAction::OnActionTriggered);
-}
-
-void QmitkDataNodeSetControlPointAction::OnActionTriggered(bool /*checked*/)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- auto dataNode = GetSelectedNode();
- if (dataNode.IsNull())
- {
- return;
- }
-
- QmitkControlPointDialog* inputDialog = new QmitkControlPointDialog(m_Parent);
- inputDialog->setWindowTitle("Set control point");
- inputDialog->SetCurrentDate(mitk::SemanticRelationsInference::GetControlPointOfImage(dataNode));
-
- int dialogReturnValue = inputDialog->exec();
- if (QDialog::Rejected == dialogReturnValue)
- {
- return;
- }
-
- const QDate& userSelectedDate = inputDialog->GetCurrentDate();
- mitk::SemanticTypes::ControlPoint controlPoint;
- controlPoint.UID = mitk::UIDGeneratorBoost::GenerateUID();
- controlPoint.date = boost::gregorian::date(userSelectedDate.year(),
- userSelectedDate.month(),
- userSelectedDate.day());
-
- mitk::SemanticTypes::InformationType informationType;
- mitk::SemanticTypes::ExaminationPeriod examinationPeriod;
- mitk::SemanticRelationsDataStorageAccess::DataNodeVector allSpecificImages;
- try
- {
- mitk::SemanticTypes::CaseID caseID = mitk::GetCaseIDFromDataNode(dataNode);
- informationType = mitk::SemanticRelationsInference::GetInformationTypeOfImage(dataNode);
- // see if the examination period - information type cell is already taken
- examinationPeriod = mitk::FindFittingExaminationPeriod(caseID, controlPoint);
- auto semanticRelationsDataStorageAccess = mitk::SemanticRelationsDataStorageAccess(dataStorage);
- try
- {
- allSpecificImages = semanticRelationsDataStorageAccess.GetAllSpecificImages(caseID, informationType, examinationPeriod);
- }
- catch (const mitk::SemanticRelationException&)
- {
- // just continue since an exception means that there is no specific image
- }
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not set the control point.",
- "The program wasn't able to correctly set the control point.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
-
- if (!allSpecificImages.empty())
- {
- // examination period - information type cell is already taken
- // ask if cell should be overwritten
- QMessageBox::StandardButton answerButton =
- QMessageBox::question(nullptr,
- "Specific image already exists.",
- QString::fromStdString("Force overwriting existing image " + informationType + " at " + examinationPeriod.name + "?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
-
- if (answerButton == QMessageBox::Yes)
- {
- try
- {
- // remove already existent images at specific cell
- for (const auto& specificImage : allSpecificImages)
- {
- RemoveFromSemanticRelationsAction::Run(dataStorage, specificImage);
- }
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not set the control point.",
- "The program wasn't able to correctly set the control point.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
- }
- else
- {
- // else case is: no overwriting
- return;
- }
- }
-
- // specific image does not exist or has been removed; setting the control point should work
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- try
- {
- semanticRelationsIntegration.UnlinkImageFromControlPoint(dataNode);
- semanticRelationsIntegration.SetControlPointOfImage(dataNode, controlPoint);
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not set the control point.",
- "The program wasn't able to correctly set the control point.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetControlPointAction.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetControlPointAction.h
deleted file mode 100644
index edb0a0ec3c..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetControlPointAction.h
+++ /dev/null
@@ -1,43 +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 QmitkDataNodeSetControlPointAction_h
-#define QmitkDataNodeSetControlPointAction_h
-
-// mitk gui qt application plugin
-#include <QmitkAbstractDataNodeAction.h>
-
-// qt
-#include <QAction>
-
-class QmitkDataNodeSetControlPointAction : public QAction, public QmitkAbstractDataNodeAction
-{
- Q_OBJECT
-
-public:
-
- QmitkDataNodeSetControlPointAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite);
- QmitkDataNodeSetControlPointAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite);
-
-private Q_SLOTS:
-
- void OnActionTriggered(bool);
-
-protected:
-
- void InitializeAction() override;
-
- QWidget* m_Parent;
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetInformationTypeAction.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetInformationTypeAction.cpp
deleted file mode 100644
index 079475afee..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetInformationTypeAction.cpp
+++ /dev/null
@@ -1,161 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkDataNodeSetInformationTypeAction.h"
-#include "QmitkDataNodeRemoveFromSemanticRelationsAction.h"
-
-// semantic relations module
-#include <mitkControlPointManager.h>
-#include <mitkDICOMHelper.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsDataStorageAccess.h>
-#include <mitkSemanticRelationsInference.h>
-#include <mitkSemanticRelationsIntegration.h>
-
-// qt
-#include <QInputDialog>
-#include <QMessageBox>
-
-QmitkDataNodeSetInformationTypeAction::QmitkDataNodeSetInformationTypeAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(workbenchPartSite)
-{
- setText(tr("Set information type"));
- m_Parent = parent;
- InitializeAction();
-}
-
-QmitkDataNodeSetInformationTypeAction::QmitkDataNodeSetInformationTypeAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
-{
- setText(tr("Set information type"));
- m_Parent = parent;
- InitializeAction();
-}
-
-void QmitkDataNodeSetInformationTypeAction::InitializeAction()
-{
- connect(this, &QAction::triggered, this, &QmitkDataNodeSetInformationTypeAction::OnActionTriggered);
-}
-
-void QmitkDataNodeSetInformationTypeAction::OnActionTriggered(bool /*checked*/)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- auto dataNode = GetSelectedNode();
- if (dataNode.IsNull())
- {
- return;
- }
-
- QInputDialog* inputDialog = new QInputDialog(m_Parent);
- inputDialog->setWindowTitle(tr("Set information type of selected node"));
- inputDialog->setLabelText(tr("Information type:"));
- inputDialog->setTextValue(QString::fromStdString(mitk::SemanticRelationsInference::GetInformationTypeOfImage(dataNode)));
- inputDialog->setMinimumSize(250, 100);
-
- int dialogReturnValue = inputDialog->exec();
- if (QDialog::Rejected == dialogReturnValue)
- {
- return;
- }
-
- mitk::SemanticTypes::InformationType informationType = inputDialog->textValue().toStdString();
-
- mitk::SemanticTypes::ExaminationPeriod examinationPeriod;
- mitk::SemanticTypes::ControlPoint controlPoint;
- mitk::SemanticRelationsDataStorageAccess::DataNodeVector allSpecificImages;
- try
- {
- mitk::SemanticTypes::CaseID caseID = mitk::GetCaseIDFromDataNode(dataNode);
- controlPoint = mitk::SemanticRelationsInference::GetControlPointOfImage(dataNode);
- // see if the examination period - information type cell is already taken
- examinationPeriod = mitk::FindFittingExaminationPeriod(caseID, controlPoint);
- auto semanticRelationsDataStorageAccess = mitk::SemanticRelationsDataStorageAccess(dataStorage);
- try
- {
- allSpecificImages = semanticRelationsDataStorageAccess.GetAllSpecificImages(caseID, informationType, examinationPeriod);
- }
- catch (const mitk::SemanticRelationException&)
- {
- // just continue since an exception means that there is no specific image
- }
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not set the information type.",
- "The program wasn't able to correctly set the information type.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
-
- if (!allSpecificImages.empty())
- {
- // examination period - information type cell is already taken
- // ask if cell should be overwritten
- QMessageBox::StandardButton answerButton =
- QMessageBox::question(nullptr,
- "Specific image already exists.",
- QString::fromStdString("Force overwriting existing image " + informationType + " at " + examinationPeriod.name + "?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
-
- if (answerButton == QMessageBox::Yes)
- {
- try
- {
- // remove already existent images at specific cell
- for (const auto& specificImage : allSpecificImages)
- {
- RemoveFromSemanticRelationsAction::Run(dataStorage, specificImage);
- }
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not set the information type.",
- "The program wasn't able to correctly set the information type.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
- }
- else
- {
- // else case is: no overwriting
- return;
- }
- }
-
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- try
- {
- semanticRelationsIntegration.SetInformationType(dataNode, informationType);
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not set the information type.",
- "The program wasn't able to correctly set the information type.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetInformationTypeAction.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetInformationTypeAction.h
deleted file mode 100644
index 63bba50eb4..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeSetInformationTypeAction.h
+++ /dev/null
@@ -1,43 +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 QmitkDataNodeSetInformationTypeAction_h
-#define QmitkDataNodeSetInformationTypeAction_h
-
-// mitk gui qt application plugin
-#include <QmitkAbstractDataNodeAction.h>
-
-// qt
-#include <QAction>
-
-class QmitkDataNodeSetInformationTypeAction : public QAction, public QmitkAbstractDataNodeAction
-{
- Q_OBJECT
-
-public:
-
- QmitkDataNodeSetInformationTypeAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite);
- QmitkDataNodeSetInformationTypeAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite);
-
-private Q_SLOTS:
-
- void OnActionTriggered(bool);
-
-protected:
-
- void InitializeAction() override;
-
- QWidget* m_Parent;
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeUnlinkFromLesionAction.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeUnlinkFromLesionAction.cpp
deleted file mode 100644
index 5cd80458f0..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeUnlinkFromLesionAction.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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkDataNodeUnlinkFromLesionAction.h"
-
-// semantic relations module
-#include <mitkNodePredicates.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsIntegration.h>
-#include <mitkUIDGeneratorBoost.h>
-
-// mitk gui common plugin
-#include <mitkDataNodeSelection.h>
-
-// qt
-#include <QMessageBox>
-
-// namespace that contains the concrete action
-namespace UnlinkFromLesionAction
-{
- void Run(const mitk::DataNode* dataNode)
- {
- if (nullptr == dataNode)
- {
- return;
- }
-
- if (mitk::NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
- {
- mitk::SemanticRelationsIntegration semanticRelationsIntegration;
- try
- {
- semanticRelationsIntegration.UnlinkSegmentationFromLesion(dataNode);
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not unlink the selected segmentation.",
- "The program wasn't able to correctly unlink the selected segmentation.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str()));
- msgBox.exec();
- }
- }
- else
- {
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not unlink the selected data node.",
- "Please chose a valid segmentation to unlink from its represented lesion!");
- msgBox.exec();
- }
- }
-}
-
-QmitkDataNodeUnlinkFromLesionAction::QmitkDataNodeUnlinkFromLesionAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(workbenchPartSite)
-{
- setText(tr("Unlink from lesion"));
- InitializeAction();
-}
-
-QmitkDataNodeUnlinkFromLesionAction::QmitkDataNodeUnlinkFromLesionAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
-{
- setText(tr("Unlink from lesion"));
- InitializeAction();
-}
-
-void QmitkDataNodeUnlinkFromLesionAction::InitializeAction()
-{
- connect(this, &QAction::triggered, this, &QmitkDataNodeUnlinkFromLesionAction::OnActionTriggered);
-}
-
-void QmitkDataNodeUnlinkFromLesionAction::OnActionTriggered(bool /*checked*/)
-{
- auto dataNode = GetSelectedNode();
- UnlinkFromLesionAction::Run(dataNode);
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeUnlinkFromLesionAction.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeUnlinkFromLesionAction.h
deleted file mode 100644
index 35b89deba2..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataNodeUnlinkFromLesionAction.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 QmitkDataNodeUnlinkFromLesionAction_h
-#define QmitkDataNodeUnlinkFromLesionAction_h
-
-#include <org_mitk_gui_qt_semanticrelations_Export.h>
-
-// mitk gui qt application plugin
-#include <QmitkAbstractDataNodeAction.h>
-
-// qt
-#include <QAction>
-
-namespace UnlinkFromLesionAction
-{
- MITK_GUI_SEMANTICRELATIONS_EXPORT void Run(const mitk::DataNode* dataNode);
-}
-
-class MITK_GUI_SEMANTICRELATIONS_EXPORT QmitkDataNodeUnlinkFromLesionAction : public QAction, public QmitkAbstractDataNodeAction
-{
- Q_OBJECT
-
-public:
-
- QmitkDataNodeUnlinkFromLesionAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite);
- QmitkDataNodeUnlinkFromLesionAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite);
-
-private Q_SLOTS:
-
- void OnActionTriggered(bool);
-
-protected:
-
- void InitializeAction() override;
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataSetOpenInAction.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataSetOpenInAction.cpp
deleted file mode 100644
index 73ac1edd38..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataSetOpenInAction.cpp
+++ /dev/null
@@ -1,156 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkDataSetOpenInAction.h"
-
-// mitk core
-#include <mitkImage.h>
-#include <mitkRenderingManager.h>
-
-// render window manager module
-#include <mitkRenderWindowLayerController.h>
-#include <mitkRenderWindowLayerUtilities.h>
-
-// semantic relations module
-#include "mitkNodePredicates.h"
-
-// mitk gui qt application plugin
-#include <QmitkDataNodeReinitAction.h>
-
-// qt
-#include <QMessageBox>
-#include <QMenu>
-
-namespace OpenInAction
-{
- void Run(mitk::DataStorage::Pointer dataStorage, mitk::DataNode::Pointer imageNode, mitk::BaseRenderer* renderer /*= nullptr*/)
- {
- if (dataStorage.IsNull())
- {
- return;
- }
-
- if (imageNode.IsNull())
- {
- return;
- }
-
- auto renderWindowLayerController = std::make_unique<mitk::RenderWindowLayerController>();
- renderWindowLayerController->SetDataStorage(dataStorage);
-
- // get current layer stack of the specified renderer
- // remove them from the specified renderer
- auto layerStack = mitk::RenderWindowLayerUtilities::GetLayerStack(dataStorage, renderer);
- for (auto& layerNode : layerStack)
- {
- // hide all nodes of the specified renderer
- layerNode.second->SetVisibility(false, renderer);
- layerNode.second->Modified();
- }
-
- // make the selected data node visible
- imageNode->SetVisibility(true, renderer);
- imageNode->Modified();
- // move node to front, which also request a render update
- renderWindowLayerController->MoveNodeToFront(imageNode, renderer);
-
- QList<mitk::DataNode::Pointer> visibleNodes;
- visibleNodes.push_back(imageNode);
- // get all corresponding segmentations of this node
- mitk::DataStorage::SetOfObjects::ConstPointer segmentationNodes = dataStorage->GetDerivations(imageNode, mitk::NodePredicates::GetSegmentationPredicate(), false);
- for (auto it = segmentationNodes->Begin(); it != segmentationNodes->End(); ++it)
- {
- auto segmentation = it->Value();
- segmentation->SetVisibility(true, renderer);
- // move node to front, which also request a render update
- renderWindowLayerController->MoveNodeToFront(segmentation, renderer);
- visibleNodes.push_back(segmentation);
- }
-
- ReinitAction::Run(berry::IWorkbenchPartSite::Pointer(), dataStorage, visibleNodes, renderer);
- }
-}
-
-QmitkDataSetOpenInAction::QmitkDataSetOpenInAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
- : QmitkDataNodeOpenInAction(parent, workbenchPartSite)
-{
- setText(tr("Open in"));
- InitializeAction();
-}
-
-QmitkDataSetOpenInAction::QmitkDataSetOpenInAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
- : QmitkDataNodeOpenInAction(parent, berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
-{
- setText(tr("Open in"));
- InitializeAction();
-}
-
-void QmitkDataSetOpenInAction::InitializeAction()
-{
- setCheckable(true);
-
- setMenu(new QMenu);
- connect(menu(), &QMenu::aboutToShow, this, &QmitkDataSetOpenInAction::OnMenuAboutToShow);
-
- SetControlledRenderer();
-}
-
-void QmitkDataSetOpenInAction::OnMenuAboutToShow()
-{
- menu()->clear();
- QAction* action;
-
- QStringList rendererNames;
- for (const auto& renderer : m_ControlledRenderer)
- {
- rendererNames.append(renderer->GetName());
- }
-
- rendererNames.sort();
- for (const auto& rendererName : rendererNames)
- {
- action = menu()->addAction(rendererName);
- connect(action, &QAction::triggered, this, &QmitkDataSetOpenInAction::OnActionTriggered);
- }
-}
-
-void QmitkDataSetOpenInAction::OnActionTriggered(bool /*checked*/)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- auto dataNode = GetSelectedNode();
- if (dataNode.IsNull())
- {
- return;
- }
-
- QAction* senderAction = qobject_cast<QAction*>(QObject::sender());
- if (nullptr == senderAction)
- {
- return;
- }
-
- std::string selectedRenderer = senderAction->text().toStdString();
- mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetByName(selectedRenderer);
- if (nullptr == renderer)
- {
- return;
- }
-
- OpenInAction::Run(dataStorage, dataNode, renderer);
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataSetOpenInAction.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataSetOpenInAction.h
deleted file mode 100644
index cabfb865db..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkDataSetOpenInAction.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 QmitkDataSetOpenInAction_h
-#define QmitkDataSetOpenInAction_h
-
-#include "QmitkDataNodeOpenInAction.h"
-
-namespace OpenInAction
-{
- void Run(mitk::DataStorage::Pointer dataStorage,
- mitk::DataNode::Pointer imageNode,
- mitk::BaseRenderer* renderer = nullptr);
-}
-
-class QmitkDataSetOpenInAction : public QmitkDataNodeOpenInAction
-{
- Q_OBJECT
-
-public:
-
- QmitkDataSetOpenInAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite);
- QmitkDataSetOpenInAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite);
-
-private Q_SLOTS:
-
- void OnMenuAboutToShow();
- void OnActionTriggered(bool);
-
-protected:
-
- void InitializeAction() override;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkFocusOnLesionAction.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkFocusOnLesionAction.cpp
deleted file mode 100644
index d54629da0c..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkFocusOnLesionAction.cpp
+++ /dev/null
@@ -1,125 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkFocusOnLesionAction.h"
-#include "QmitkLabelSetJumpToAction.h"
-
-// mitk core
-#include <mitkImage.h>
-#include <mitkRenderingManager.h>
-
-// render window manager module
-#include <mitkRenderWindowLayerController.h>
-#include <mitkRenderWindowLayerUtilities.h>
-
-// semantic relations module
-#include <mitkDICOMHelper.h>
-#include <mitkSemanticRelationsInference.h>
-
-// qt
-#include <QMessageBox>
-#include <QMenu>
-
-QmitkFocusOnLesionAction::QmitkFocusOnLesionAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(workbenchPartSite)
-{
- setText(tr("Focus on lesion"));
- InitializeAction();
-}
-
-QmitkFocusOnLesionAction::QmitkFocusOnLesionAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
-{
- setText(tr("Focus on lesion"));
- InitializeAction();
-}
-
-void QmitkFocusOnLesionAction::SetSelectedLesion(mitk::SemanticTypes::Lesion selectedLesion)
-{
- m_Lesion = selectedLesion;
-}
-
-void QmitkFocusOnLesionAction::InitializeAction()
-{
- setCheckable(true);
- connect(this, &QAction::triggered, this, &QmitkFocusOnLesionAction::OnActionTriggered);
-
- SetControlledRenderer();
-}
-
-void QmitkFocusOnLesionAction::OnActionTriggered(bool /*checked*/)
-{
- auto workbenchPartSite = m_WorkbenchPartSite.Lock();
-
- if (workbenchPartSite.IsNull())
- {
- return;
- }
-
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- auto renderWindowLayerController = std::make_unique<mitk::RenderWindowLayerController>();
- renderWindowLayerController->SetDataStorage(dataStorage);
- // check each renderer to see if it contains a segmentation represented by the currently selected lesion
- for (const auto& renderer : m_ControlledRenderer)
- {
- // get currently fixed layer nodes of the specified renderer
- auto layerStack = mitk::RenderWindowLayerUtilities::GetLayerStack(dataStorage, renderer, true);
- // check each node to see if it is a segmentation represented by the currently selected lesion
- for (const auto& layer : layerStack)
- {
- auto dataNode = layer.second;
- bool isVisible = false;
- if (dataNode.IsNotNull())
- {
- dataNode->GetBoolProperty("visible", isVisible, renderer);
- }
-
- // only focus in renderer where the segmentation is visible
- if (!isVisible)
- {
- continue;
- }
-
- auto currentLesion = mitk::SemanticRelationsInference::GetLesionOfSegmentation(dataNode);
- if (currentLesion.UID == m_Lesion.UID)
- {
- // jump to this lesion in the specified renderer
- LabelSetJumpToAction::Run(workbenchPartSite, dataNode, renderer);
- }
- }
- }
-}
-
-void QmitkFocusOnLesionAction::SetControlledRenderer()
-{
- const mitk::RenderingManager::RenderWindowVector allRegisteredRenderWindows =
- mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows();
- mitk::BaseRenderer *baseRenderer = nullptr;
- m_ControlledRenderer.clear();
- for (const auto& renderWindow : allRegisteredRenderWindows)
- {
- baseRenderer = mitk::BaseRenderer::GetInstance(renderWindow);
- if (nullptr != baseRenderer)
- {
- m_ControlledRenderer.push_back(baseRenderer);
- }
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkFocusOnLesionAction.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkFocusOnLesionAction.h
deleted file mode 100644
index c5b8988164..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkFocusOnLesionAction.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 QmitkFocusOnLesionAction_h
-#define QmitkFocusOnLesionAction_h
-
-// mitk gui qt application plugin
-#include <QmitkAbstractDataNodeAction.h>
-
-// semantic relations module
-#include <mitkSemanticTypes.h>
-
-// qt
-#include <QAction>
-
-class QmitkFocusOnLesionAction : public QAction, public QmitkAbstractDataNodeAction
-{
- Q_OBJECT
-
-public:
-
- typedef std::vector<mitk::BaseRenderer*> RendererVector;
-
- QmitkFocusOnLesionAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite);
- QmitkFocusOnLesionAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite);
-
- void SetSelectedLesion(mitk::SemanticTypes::Lesion selectedLesion);
-
-private Q_SLOTS:
-
- void OnActionTriggered(bool);
-
-protected:
-
- void InitializeAction() override;
-
- void SetControlledRenderer();
-
- RendererVector m_ControlledRenderer;
- mitk::SemanticTypes::Lesion m_Lesion;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLabelSetJumpToAction.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLabelSetJumpToAction.cpp
deleted file mode 100644
index 3585dfc626..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLabelSetJumpToAction.cpp
+++ /dev/null
@@ -1,121 +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 gui qt application plugin
-#include "QmitkLabelSetJumpToAction.h"
-
-// mitk core
-#include <mitkImage.h>
-#include <mitkRenderingManager.h>
-#include <mitkWorkbenchUtil.h>
-
-// mitk multi label module
-#include <mitkLabelSetImage.h>
-
-// qt
-#include <QMessageBox>
-#include <QMenu>
-
-namespace LabelSetJumpToAction
-{
- void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite, const mitk::DataNode* dataNode, mitk::BaseRenderer* baseRenderer /*= nullptr*/)
- {
- if (workbenchPartSite.IsNull())
- {
- return;
- }
-
- if (nullptr == dataNode)
- {
- return;
- }
-
- mitk::LabelSetImage* labelSetImage = dynamic_cast<mitk::LabelSetImage*>(dataNode->GetData());
- if (nullptr == labelSetImage)
- {
- return;
- }
-
- unsigned int activeLayer = labelSetImage->GetActiveLayer();
- mitk::Label* activeLabel = labelSetImage->GetActiveLabel(activeLayer);
- labelSetImage->UpdateCenterOfMass(activeLabel->GetValue(), activeLayer);
- const mitk::Point3D& centerPosition = activeLabel->GetCenterOfMassCoordinates();
- if (centerPosition.GetVnlVector().max_value() > 0.0)
- {
- auto renderWindowPart = mitk::WorkbenchUtil::GetRenderWindowPart(workbenchPartSite->GetPage(), mitk::WorkbenchUtil::NONE);
- if (nullptr == renderWindowPart)
- {
- renderWindowPart = mitk::WorkbenchUtil::OpenRenderWindowPart(workbenchPartSite->GetPage(), false);
- if (nullptr == renderWindowPart)
- {
- // no render window available
- return;
- }
- }
-
- auto segmentation = dynamic_cast<mitk::LabelSetImage*>(dataNode->GetData());
- if (nullptr != segmentation)
- {
- if (nullptr == baseRenderer)
- {
- renderWindowPart->SetSelectedPosition(centerPosition);
- mitk::RenderingManager::GetInstance()->InitializeViews(segmentation->GetTimeGeometry());
- }
- else
- {
- renderWindowPart->SetSelectedPosition(centerPosition, baseRenderer->GetName());
- mitk::RenderingManager::GetInstance()->InitializeView(baseRenderer->GetRenderWindow(), segmentation->GetTimeGeometry());
- }
- }
- }
- }
-}
-
-QmitkLabelSetJumpToAction::QmitkLabelSetJumpToAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(workbenchPartSite)
-{
- setText(tr("Jump to"));
- InitializeAction();
-}
-
-QmitkLabelSetJumpToAction::QmitkLabelSetJumpToAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite)
- : QAction(parent)
- , QmitkAbstractDataNodeAction(berry::IWorkbenchPartSite::Pointer(workbenchPartSite))
-{
- setText(tr("Jump to"));
- InitializeAction();
-}
-
-void QmitkLabelSetJumpToAction::InitializeAction()
-{
- connect(this, &QAction::triggered, this, &QmitkLabelSetJumpToAction::OnActionTriggered);
-}
-
-void QmitkLabelSetJumpToAction::OnActionTriggered(bool /*checked*/)
-{
- auto workbenchPartSite = m_WorkbenchPartSite.Lock();
-
- if (workbenchPartSite.IsNull())
- {
- return;
- }
-
- auto dataNode = GetSelectedNode();
- if (dataNode.IsNull())
- {
- return;
- }
-
- mitk::BaseRenderer::Pointer baseRenderer = GetBaseRenderer();
- LabelSetJumpToAction::Run(workbenchPartSite, dataNode, baseRenderer);
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLabelSetJumpToAction.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLabelSetJumpToAction.h
deleted file mode 100644
index 9bb3405dca..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLabelSetJumpToAction.h
+++ /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.
-
-============================================================================*/
-
-#ifndef QmitkLabelSetJumpToAction_h
-#define QmitkLabelSetJumpToAction_h
-
-#include "QmitkAbstractDataNodeAction.h"
-
-// qt
-#include <QAction>
-
-namespace LabelSetJumpToAction
-{
- void Run(berry::IWorkbenchPartSite::Pointer workbenchPartSite,
- const mitk::DataNode* dataNode,
- mitk::BaseRenderer* baseRenderer = nullptr);
-}
-
-class QmitkLabelSetJumpToAction : public QAction, public QmitkAbstractDataNodeAction
-{
- Q_OBJECT
-
-public:
-
- QmitkLabelSetJumpToAction(QWidget* parent, berry::IWorkbenchPartSite::Pointer workbenchPartSite);
- QmitkLabelSetJumpToAction(QWidget* parent, berry::IWorkbenchPartSite* workbenchPartSite);
-
-private Q_SLOTS:
-
- void OnActionTriggered(bool);
-
-protected:
-
- void InitializeAction() override;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidget.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidget.cpp
deleted file mode 100644
index 4570a97efb..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidget.cpp
+++ /dev/null
@@ -1,495 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkLesionInfoWidget.h"
-#include "QmitkDataNodeAddToSemanticRelationsAction.h"
-#include "QmitkFocusOnLesionAction.h"
-#include "QmitkSemanticRelationsNodeSelectionDialog.h"
-
-// semantic relations UI module
-#include <QmitkLesionTextDialog.h>
-
-// semantic relations module
-#include <mitkLesionManager.h>
-#include <mitkNodePredicates.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsInference.h>
-#include <mitkRelationStorage.h>
-
-// segmentation
-#include <mitkLabelSetImage.h>
-#include <QmitkNewSegmentationDialog.h>
-
-// qt
-#include <QCompleter>
-#include <QListWidget>
-#include <QMenu>
-#include <QMessageBox>
-#include <QString>
-
-QmitkLesionInfoWidget::QmitkLesionInfoWidget(mitk::DataStorage* dataStorage,
- berry::IWorkbenchPartSite::Pointer workbenchPartSite,
- QWidget* parent /*= nullptr*/)
- : QWidget(parent)
- , m_DataStorage(dataStorage)
- , m_WorkbenchPartSite(workbenchPartSite)
- , m_SemanticRelationsDataStorageAccess(std::make_unique<mitk::SemanticRelationsDataStorageAccess>(dataStorage))
- , m_SemanticRelationsIntegration(std::make_unique<mitk::SemanticRelationsIntegration>())
-{
- Initialize();
-}
-
-void QmitkLesionInfoWidget::Initialize()
-{
- m_Controls.setupUi(this);
-
- m_Controls.lesionTreeView->setAlternatingRowColors(true);
- m_Controls.lesionTreeView->setSelectionMode(QAbstractItemView::SingleSelection);
- m_Controls.lesionTreeView->setSelectionBehavior(QAbstractItemView::SelectRows);
- m_Controls.lesionTreeView->setContextMenuPolicy(Qt::CustomContextMenu);
-
- m_StorageModel = new QmitkLesionTreeModel(m_Controls.lesionTreeView);
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- m_StorageModel->SetDataStorage(dataStorage);
- m_Controls.lesionTreeView->setModel(m_StorageModel);
-
- SetUpConnections();
-}
-
-void QmitkLesionInfoWidget::SetUpConnections()
-{
- connect(m_StorageModel, &QmitkLesionTreeModel::ModelUpdated, this, &QmitkLesionInfoWidget::OnModelUpdated);
- connect(m_Controls.addLesionPushButton, &QPushButton::clicked, this, &QmitkLesionInfoWidget::OnAddLesionButtonClicked);
- connect(m_Controls.lesionTreeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &QmitkLesionInfoWidget::OnSelectionChanged);
- connect(m_Controls.lesionTreeView, &QTreeView::customContextMenuRequested, this, &QmitkLesionInfoWidget::OnLesionListContextMenuRequested);
-}
-
-void QmitkLesionInfoWidget::SetCaseID(const mitk::SemanticTypes::CaseID& caseID)
-{
- m_CaseID = caseID;
- m_StorageModel->SetCaseID(caseID);
-}
-
-void QmitkLesionInfoWidget::SetDataNodeSelection(const QList<mitk::DataNode::Pointer>& dataNodeSelection)
-{
- m_StorageModel->SetDataNodeSelection(dataNodeSelection);
-}
-
-//////////////////////////////////////////////////////////////////////////
-// Implementation of the QT_SLOTS
-//////////////////////////////////////////////////////////////////////////
-void QmitkLesionInfoWidget::OnModelUpdated()
-{
- m_Controls.lesionTreeView->expandAll();
- int columns = m_Controls.lesionTreeView->model()->columnCount();
- for (int i = 0; i < columns; ++i)
- {
- m_Controls.lesionTreeView->resizeColumnToContents(i);
- }
-}
-
-void QmitkLesionInfoWidget::OnAddLesionButtonClicked()
-{
- if (m_CaseID.empty())
- {
- QMessageBox msgBox(QMessageBox::Warning,
- "No case ID set.",
- "In order to add a lesion, please specify the current case / patient.");
- msgBox.exec();
- return;
- }
-
- mitk::SemanticTypes::Lesion newLesion = mitk::GenerateNewLesion();
- try
- {
- m_SemanticRelationsIntegration->AddLesion(m_CaseID, newLesion);
- }
- catch (mitk::SemanticRelationException& e)
- {
- MITK_INFO << "Could not add a new lesion. " << e;
- }
-}
-
-void QmitkLesionInfoWidget::OnSelectionChanged(const QModelIndex& current, const QModelIndex& /*previous*/)
-{
- // only the UID is needed to identify a representing lesion
- QVariant data = m_StorageModel->data(current, Qt::UserRole);
- if (!data.canConvert<QmitkLesionTreeItem*>())
- {
- return;
- }
-
- auto lesion = data.value<QmitkLesionTreeItem*>()->GetData().GetLesion();
- if (false == mitk::SemanticRelationsInference::InstanceExists(m_CaseID, lesion))
- {
- // no UID of a existing lesion found; cannot create a lesion
- return;
- }
-
- // if selected data nodes are set, reset to empty list to
- // hide "selected data nodes presence background highlighting" in the model
- if (!m_StorageModel->GetSelectedDataNodes().isEmpty())
- {
- m_StorageModel->SetDataNodeSelection(QList<mitk::DataNode::Pointer>());
- }
-
- emit LesionSelectionChanged(lesion);
-}
-
-void QmitkLesionInfoWidget::OnLesionListContextMenuRequested(const QPoint& pos)
-{
- if (nullptr == m_SemanticRelationsIntegration)
- {
- return;
- }
-
- if (m_CaseID.empty())
- {
- QMessageBox msgBox(QMessageBox::Warning,
- "No case ID set.",
- "In order to access the context menu entries a case ID has to be set.");
- msgBox.exec();
- return;
- }
-
- QModelIndex index = m_Controls.lesionTreeView->indexAt(pos);
- if (!index.isValid())
- {
- // no item clicked; cannot retrieve the current lesion
- return;
- }
-
- QVariant data = m_StorageModel->data(index, Qt::UserRole);
- mitk::SemanticTypes::Lesion selectedLesion;
- if (data.canConvert<QmitkLesionTreeItem*>())
- {
- selectedLesion = data.value<QmitkLesionTreeItem*>()->GetData().GetLesion();
- }
- else
- {
- return;
- }
-
- QMenu* menu = new QMenu(m_Controls.lesionTreeView);
-
- QAction* linkToSegmentation = new QAction("Link to segmentation", this);
- linkToSegmentation->setEnabled(true);
- connect(linkToSegmentation, &QAction::triggered, [this, selectedLesion] { OnLinkToSegmentation(selectedLesion); });
- menu->addAction(linkToSegmentation);
-
- QAction* setLesionName = new QAction("Set lesion name", this);
- setLesionName->setEnabled(true);
- connect(setLesionName, &QAction::triggered, [this, selectedLesion] { OnSetLesionName(selectedLesion); });
- menu->addAction(setLesionName);
-
- QAction* setLesionClass = new QAction("Set lesion class", this);
- setLesionClass->setEnabled(true);
- connect(setLesionClass, &QAction::triggered, [this, selectedLesion] { OnSetLesionClass(selectedLesion); });
- menu->addAction(setLesionClass);
-
- QAction* createNewSegmentation = new QAction("Create new lesion", this);
- createNewSegmentation->setEnabled(true);
- connect(createNewSegmentation, &QAction::triggered, [this, selectedLesion] { OnCreateNewSegmentation(selectedLesion); });
- menu->addAction(createNewSegmentation);
-
- QAction* removeLesion = new QAction("Remove lesion", this);
- removeLesion->setEnabled(true);
- connect(removeLesion, &QAction::triggered, [this, selectedLesion] { OnRemoveLesion(selectedLesion); });
- menu->addAction(removeLesion);
-
- auto workbenchPartSite = m_WorkbenchPartSite.Lock();
-
- if (workbenchPartSite.IsNotNull())
- {
- QmitkFocusOnLesionAction* focusOnLesion = new QmitkFocusOnLesionAction(this, workbenchPartSite);
- focusOnLesion->SetDataStorage(m_DataStorage.Lock());
- focusOnLesion->SetSelectedLesion(selectedLesion);
- menu->addAction(focusOnLesion);
- }
-
- menu->popup(QCursor::pos());
-}
-
-void QmitkLesionInfoWidget::OnLinkToSegmentation(mitk::SemanticTypes::Lesion selectedLesion)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- QmitkSemanticRelationsNodeSelectionDialog* dialog = new QmitkSemanticRelationsNodeSelectionDialog(this, "Select segmentation to link to the selected lesion.", "");
- dialog->setWindowTitle("Select segmentation node");
- dialog->SetDataStorage(dataStorage);
- dialog->SetNodePredicate(mitk::NodePredicates::GetSegmentationPredicate());
- dialog->SetSelectOnlyVisibleNodes(true);
- dialog->SetCaseID(m_CaseID);
- // set the last added segmentation node as pre-selected data node
- const mitk::DataNode* lastSegmentation = m_StorageModel->GetLastSegmentation();
- QList<mitk::DataNode::Pointer> selectedDataNodes;
- if (nullptr != lastSegmentation)
- {
- selectedDataNodes.push_back(const_cast<mitk::DataNode*>(lastSegmentation));
- dialog->SetCurrentSelection(selectedDataNodes);
- }
-
- int dialogReturnValue = dialog->exec();
- if (QDialog::Rejected == dialogReturnValue)
- {
- return;
- }
-
- mitk::DataNode::Pointer selectedDataNode = nullptr;
- selectedDataNodes = dialog->GetSelectedNodes();
- if (!selectedDataNodes.isEmpty())
- {
- // only single selection allowed
- selectedDataNode = selectedDataNodes.front();
- }
-
- if (nullptr == selectedDataNode
- || false == mitk::NodePredicates::GetSegmentationPredicate()->CheckNode(selectedDataNode))
- {
- QMessageBox msgBox(QMessageBox::Warning,
- "No valid segmentation node selected.",
- "In order to link the selected lesion to a segmentation, please specify a valid segmentation node.");
- msgBox.exec();
- return;
- }
-
- mitk::BaseData* baseData = selectedDataNode->GetData();
- if (nullptr == baseData)
- {
- QMessageBox msgBox(QMessageBox::Warning,
- "No valid base data.",
- "In order to link the selected lesion to a segmentation, please specify a valid segmentation node.");
- msgBox.exec();
- return;
- }
-
- LinkSegmentationToLesion(selectedDataNode, selectedLesion);
-}
-
-void QmitkLesionInfoWidget::OnSetLesionName(mitk::SemanticTypes::Lesion selectedLesion)
-{
- // use the lesion information to set the input text for the dialog
- QmitkLesionTextDialog* inputDialog = new QmitkLesionTextDialog(this);
- inputDialog->setWindowTitle("Set lesion name");
- inputDialog->SetLineEditText(selectedLesion.name);
-
- int dialogReturnValue = inputDialog->exec();
- if (QDialog::Rejected == dialogReturnValue)
- {
- return;
- }
-
- selectedLesion.name = inputDialog->GetLineEditText().toStdString();
- m_SemanticRelationsIntegration->OverwriteLesion(m_CaseID, selectedLesion);
-}
-
-void QmitkLesionInfoWidget::OnSetLesionClass(mitk::SemanticTypes::Lesion selectedLesion)
-{
- // use the lesion information to set the input text for the dialog
- QmitkLesionTextDialog* inputDialog = new QmitkLesionTextDialog(this);
- inputDialog->setWindowTitle("Set lesion class");
- inputDialog->SetLineEditText(selectedLesion.lesionClass.classType);
-
- // prepare the completer for the dialogs input text field
- mitk::LesionClassVector allLesionClasses = mitk::SemanticRelationsInference::GetAllLesionClassesOfCase(m_CaseID);
-
- QStringList wordList;
- for (const auto& lesionClass : allLesionClasses)
- {
- wordList << QString::fromStdString(lesionClass.classType);
- }
- QCompleter* completer = new QCompleter(wordList, this);
- completer->setCaseSensitivity(Qt::CaseInsensitive);
- inputDialog->GetLineEdit()->setCompleter(completer);
-
- int dialogReturnValue = inputDialog->exec();
- if (QDialog::Rejected == dialogReturnValue)
- {
- return;
- }
-
- // retrieve the new input lesion class type and check for an already existing lesion class types
- std::string newLesionClassType = inputDialog->GetLineEditText().toStdString();
- mitk::SemanticTypes::LesionClass existingLesionClass = mitk::FindExistingLesionClass(m_CaseID, newLesionClassType);
- if (existingLesionClass.UID.empty())
- {
- // could not find lesion class information for the new lesion class type
- // create a new lesion class for the selected lesion
- existingLesionClass = mitk::GenerateNewLesionClass(newLesionClassType);
- }
-
- selectedLesion.lesionClass = existingLesionClass;
- m_SemanticRelationsIntegration->OverwriteLesion(m_CaseID, selectedLesion);
-}
-
-void QmitkLesionInfoWidget::OnCreateNewSegmentation(mitk::SemanticTypes::Lesion selectedLesion)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- QmitkSemanticRelationsNodeSelectionDialog* dialog = new QmitkSemanticRelationsNodeSelectionDialog(this, "Select image to segment lesion on.", "");
- dialog->setWindowTitle("Select image node");
- dialog->SetDataStorage(dataStorage);
- dialog->SetNodePredicate(mitk::NodePredicates::GetImagePredicate());
- dialog->SetSelectOnlyVisibleNodes(true);
- dialog->SetCaseID(m_CaseID);
- dialog->SetLesion(selectedLesion);
-
- int dialogReturnValue = dialog->exec();
- if (QDialog::Rejected == dialogReturnValue)
- {
- return;
- }
-
- auto nodes = dialog->GetSelectedNodes();
- mitk::DataNode::Pointer selectedDataNode = nullptr;
- if (!nodes.isEmpty())
- {
- // only single selection allowed
- selectedDataNode = nodes.front();
- }
-
- if (nullptr == selectedDataNode
- || false == mitk::NodePredicates::GetImagePredicate()->CheckNode(selectedDataNode))
- {
- QMessageBox msgBox(QMessageBox::Warning,
- "No valid image node selected.",
- "In order to create a new segmentation, please specify a valid image node.");
- msgBox.exec();
- return;
- }
-
- mitk::Image* selectedImage = dynamic_cast<mitk::Image*>(selectedDataNode->GetData());
- if (nullptr == selectedImage)
- {
- QMessageBox msgBox(QMessageBox::Warning,
- "No valid image.",
- "In order to create a new segmentation, please specify a valid image node.");
- msgBox.exec();
- return;
- }
-
- mitk::LabelSetImage::Pointer segmentation = mitk::LabelSetImage::New();
- try
- {
- segmentation->Initialize(selectedImage);
- }
- catch (mitk::Exception& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not initialize segmentation.",
- "The segmentation could not be correctly initialized with the selected image geometry.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str()));
- msgBox.exec();
- return;
- }
-
- auto segmentationDialog = new QmitkNewSegmentationDialog(this);
- segmentationDialog->setWindowTitle("New lesion segmentation");
-
- dialogReturnValue = segmentationDialog->exec();
- if (dialogReturnValue == QDialog::Rejected)
- {
- return;
- }
-
- QString segmentatioName = segmentationDialog->GetName();
- if (segmentatioName.isEmpty())
- {
- segmentatioName = "Unnamed";
- }
- segmentation->GetActiveLabelSet()->AddLabel(segmentatioName.toStdString(), segmentationDialog->GetColor());
-
- mitk::DataNode::Pointer segmentationNode = mitk::DataNode::New();
- segmentationNode->SetData(segmentation);
- segmentationNode->SetName(segmentatioName.toStdString());
- dataStorage->Add(segmentationNode, selectedDataNode);
-
- LinkSegmentationToLesion(segmentationNode, selectedLesion);
-}
-
-void QmitkLesionInfoWidget::OnRemoveLesion(mitk::SemanticTypes::Lesion selectedLesion)
-{
- try
- {
- m_SemanticRelationsIntegration->RemoveLesion(m_CaseID, selectedLesion);
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not remove the selected lesion.",
- "The program wasn't able to correctly remove the selected lesion from the semantic relations model.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str()));
- msgBox.exec();
- }
-}
-
-void QmitkLesionInfoWidget::LinkSegmentationToLesion(const mitk::DataNode* selectedDataNode, mitk::SemanticTypes::Lesion selectedLesion)
-{
- auto dataStorage = m_DataStorage.Lock();
-
- if (dataStorage.IsNull())
- {
- return;
- }
-
- // if the segmentation is not contained in the semantic relations, add it
- if (!mitk::SemanticRelationsInference::InstanceExists(selectedDataNode))
- {
- try
- {
- AddToSemanticRelationsAction::Run(dataStorage, selectedDataNode);
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not link the selected lesion.",
- "The program wasn't able to correctly link the selected lesion with the selected segmentation.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
- }
-
- // link the segmentation
- try
- {
- m_SemanticRelationsIntegration->LinkSegmentationToLesion(selectedDataNode, selectedLesion);
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not link the selected lesion.",
- "The program wasn't able to correctly link the selected lesion with the selected segmentation.\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str()));
- msgBox.exec();
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidget.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidget.h
deleted file mode 100644
index 7c7a123326..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidget.h
+++ /dev/null
@@ -1,103 +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 QmitkLesionInfoWidget_h
-#define QmitkLesionInfoWidget_h
-
-// semantic relations plugin
-#include <ui_QmitkLesionInfoWidgetControls.h>
-
-// semantic relations UI module
-#include <QmitkLesionTreeModel.h>
-
-// semantic relations module
-#include <mitkSemanticRelationsDataStorageAccess.h>
-#include <mitkSemanticRelationsIntegration.h>
-
-// mitk
-#include <mitkDataStorage.h>
-
-// berry
-#include <berryIWorkbenchPartSite.h>
-
-// qt
-#include <QWidget>
-
-/*
-* @brief The QmitkLesionInfoWidget is a widget that shows and modifies the currently available lesion data of the semantic relations model.
-*
-* The widget provides a dialogs to add nodes from the data storage to the semantic relations model.
-* It provides functionality to create new lesions and link them with segmentation nodes.
-*
-* The QmitkLesionInfoWidget provides three QListWidgets, that show the lesion data and the referenced segmentation data, as
-* well as the connected image data, depending on the selected lesion.
-*/
-class QmitkLesionInfoWidget : public QWidget
-{
- Q_OBJECT
-
-public:
-
- static const QBrush DEFAULT_BACKGROUND_COLOR;
- static const QBrush SELECTED_BACKGROUND_COLOR;
- static const QBrush CONNECTED_BACKGROUND_COLOR;
-
- QmitkLesionInfoWidget(mitk::DataStorage* dataStorage, berry::IWorkbenchPartSite::Pointer workbenchPartSite, QWidget* parent = nullptr);
-
- void SetCaseID(const mitk::SemanticTypes::CaseID& caseID);
-
- void SetDataNodeSelection(const QList<mitk::DataNode::Pointer>& dataNodeSelection);
-
-Q_SIGNALS:
-
- void LesionSelectionChanged(const mitk::SemanticTypes::Lesion&);
-
-private Q_SLOTS:
-
- void OnModelUpdated();
- /*
- * @brief Generates a new, empty lesion to add to the semantic relations model for the current case ID.
- */
- void OnAddLesionButtonClicked();
-
- // slots for the mouse click events of tree view's selection model
- void OnSelectionChanged(const QModelIndex& current, const QModelIndex& previous);
-
- void OnLesionListContextMenuRequested(const QPoint&);
-
- // slots for the context menu actions of the lesion list widget
- void OnLinkToSegmentation(mitk::SemanticTypes::Lesion);
- void OnSetLesionName(mitk::SemanticTypes::Lesion);
- void OnSetLesionClass(mitk::SemanticTypes::Lesion);
- void OnCreateNewSegmentation(mitk::SemanticTypes::Lesion);
- void OnRemoveLesion(mitk::SemanticTypes::Lesion);
-
-private:
-
- void Initialize();
- void SetUpConnections();
-
- void LinkSegmentationToLesion(const mitk::DataNode* selectedDataNode, mitk::SemanticTypes::Lesion selectedLesion);
-
- Ui::QmitkLesionInfoWidgetControls m_Controls;
- QmitkLesionTreeModel* m_StorageModel;
-
- mitk::SemanticTypes::CaseID m_CaseID;
-
- mitk::WeakPointer<mitk::DataStorage> m_DataStorage;
- berry::IWorkbenchPartSite::WeakPtr m_WorkbenchPartSite;
- std::unique_ptr<mitk::SemanticRelationsDataStorageAccess> m_SemanticRelationsDataStorageAccess;
- std::unique_ptr<mitk::SemanticRelationsIntegration> m_SemanticRelationsIntegration;
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidgetControls.ui b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidgetControls.ui
deleted file mode 100644
index 35ace22701..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkLesionInfoWidgetControls.ui
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkLesionInfoWidgetControls</class>
- <widget class="QWidget" name="QmitkLesionInfoWidgetControls">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>350</width>
- <height>300</height>
- </rect>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <property name="leftMargin">
- <number>0</number>
- </property>
- <property name="topMargin">
- <number>0</number>
- </property>
- <property name="rightMargin">
- <number>0</number>
- </property>
- <property name="bottomMargin">
- <number>0</number>
- </property>
- <item row="0" column="0">
- <widget class="QLabel" name="lesionInfoWidgetLabel">
- <property name="text">
- <string>Available lesions:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0" rowspan="2">
- <widget class="QTreeView" name="lesionTreeView"/>
- </item>
- <item row="1" column="1">
- <widget class="QPushButton" name="addLesionPushButton">
- <property name="text">
- <string>Add new lesion</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsContextMenu.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsContextMenu.cpp
deleted file mode 100644
index a05a72cfc4..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsContextMenu.cpp
+++ /dev/null
@@ -1,69 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkSemanticRelationsContextMenu.h"
-
-QmitkSemanticRelationsContextMenu::QmitkSemanticRelationsContextMenu(berry::IWorkbenchPartSite::Pointer workbenchPartSite, QWidget* parent)
- : QMenu(parent)
- , m_Parent(parent)
- , m_WorkbenchPartSite(workbenchPartSite)
-{
- InitDefaultActions();
-}
-
-void QmitkSemanticRelationsContextMenu::SetDataStorage(mitk::DataStorage* dataStorage)
-{
- if (m_DataStorage != dataStorage)
- {
- // set the new data storage - also for all actions
- m_DataStorage = dataStorage;
- m_ControlPointAction->SetDataStorage(m_DataStorage.Lock());
- m_InformationTypeAction->SetDataStorage(m_DataStorage.Lock());
- m_RemoveFromSemanticRelationsAction->SetDataStorage(m_DataStorage.Lock());
- m_DataSetOpenInAction->SetDataStorage(m_DataStorage.Lock());
- m_UnlinkFromLesionAction->SetDataStorage(m_DataStorage.Lock());
- }
-}
-
-void QmitkSemanticRelationsContextMenu::SetControlledRenderer(mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer)
-{
- if (m_ControlledRenderer != controlledRenderer)
- {
- // set the new set of controlled renderer
- m_ControlledRenderer = controlledRenderer;
- m_DataSetOpenInAction->SetControlledRenderer(m_ControlledRenderer);
- }
-}
-
-void QmitkSemanticRelationsContextMenu::OnContextMenuRequested(const QPoint& /*pos*/)
-{
- popup(QCursor::pos());
-}
-
-void QmitkSemanticRelationsContextMenu::InitDefaultActions()
-{
- m_ControlPointAction = new QmitkDataNodeSetControlPointAction(m_Parent, m_WorkbenchPartSite.Lock());
- addAction(m_ControlPointAction);
-
- m_InformationTypeAction = new QmitkDataNodeSetInformationTypeAction(m_Parent, m_WorkbenchPartSite.Lock());
- addAction(m_InformationTypeAction);
-
- m_UnlinkFromLesionAction = new QmitkDataNodeUnlinkFromLesionAction(m_Parent, m_WorkbenchPartSite.Lock());
- addAction(m_UnlinkFromLesionAction);
-
- m_RemoveFromSemanticRelationsAction = new QmitkDataNodeRemoveFromSemanticRelationsAction(m_Parent, m_WorkbenchPartSite.Lock());
- addAction(m_RemoveFromSemanticRelationsAction);
-
- m_DataSetOpenInAction = new QmitkDataSetOpenInAction(m_Parent, m_WorkbenchPartSite.Lock());
- addAction(m_DataSetOpenInAction);
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsContextMenu.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsContextMenu.h
deleted file mode 100644
index 9f7f456136..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsContextMenu.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 QmitkSemanticRelationsContextMenu_h
-#define QmitkSemanticRelationsContextMenu_h
-
-// semantic relations plugin
-#include "QmitkDataNodeSetControlPointAction.h"
-#include "QmitkDataNodeSetInformationTypeAction.h"
-#include "QmitkDataNodeUnlinkFromLesionAction.h"
-#include "QmitkDataNodeRemoveFromSemanticRelationsAction.h"
-#include "QmitkDataSetOpenInAction.h"
-
-// mitk core
-#include <mitkDataStorage.h>
-#include <mitkWeakPointer.h>
-
-// mitk render window manager module
-#include <mitkRenderWindowLayerUtilities.h>
-
-// blueberry ui qt plugin
-#include <berryIWorkbenchPartSite.h>
-
-//qt
-#include <QMenu>
-
-class QmitkSemanticRelationsContextMenu : public QMenu
-{
- Q_OBJECT
-
-public:
-
- QmitkSemanticRelationsContextMenu(berry::IWorkbenchPartSite::Pointer workbenchPartSite, QWidget* parent = nullptr);
-
- void SetDataStorage(mitk::DataStorage* dataStorage);
- void SetControlledRenderer(mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer);
-
-public Q_SLOTS:
-
- void OnContextMenuRequested(const QPoint&);
-
-private:
-
- void InitDefaultActions();
-
- QWidget* m_Parent;
- berry::IWorkbenchPartSite::WeakPtr m_WorkbenchPartSite;
- mitk::WeakPointer<mitk::DataStorage> m_DataStorage;
- mitk::RenderWindowLayerUtilities::RendererVector m_ControlledRenderer;
-
- QmitkDataNodeSetControlPointAction* m_ControlPointAction;
- QmitkDataNodeSetInformationTypeAction* m_InformationTypeAction;
- QmitkDataNodeUnlinkFromLesionAction* m_UnlinkFromLesionAction;
- QmitkDataNodeRemoveFromSemanticRelationsAction* m_RemoveFromSemanticRelationsAction;
- QmitkDataSetOpenInAction* m_DataSetOpenInAction;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsControls.ui b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsControls.ui
deleted file mode 100644
index bb178d3af5..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsControls.ui
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkSemanticRelationsControls</class>
- <widget class="QWidget" name="QmitkSemanticRelationsControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>350</width>
- <height>300</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Semantic relations plugin</string>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="caseIDLabel">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Maximum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Currently selected patient:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QComboBox" name="caseIDComboBox"/>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsNodeSelectionDialog.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsNodeSelectionDialog.cpp
deleted file mode 100644
index a49589c656..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsNodeSelectionDialog.cpp
+++ /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.
-
-============================================================================*/
-
-#include "QmitkSemanticRelationsNodeSelectionDialog.h"
-
-// semantic relations ui module
-#include <QmitkAbstractSemanticRelationsStorageInspector.h>
-
-// semantic relations ui module
-#include <QmitkPatientTableInspector.h>
-
-QmitkSemanticRelationsNodeSelectionDialog::QmitkSemanticRelationsNodeSelectionDialog(QWidget* parent, QString title, QString hint)
- : QmitkNodeSelectionDialog(parent, title, hint)
-{
- // nothing here
-}
-
-void QmitkSemanticRelationsNodeSelectionDialog::SetCaseID(const mitk::SemanticTypes::CaseID& caseID)
-{
- for (auto panel : m_Panels)
- {
- QmitkAbstractSemanticRelationsStorageInspector* semanticRelationsStorageInspector = dynamic_cast<QmitkAbstractSemanticRelationsStorageInspector*>(panel);
- if (nullptr != semanticRelationsStorageInspector)
- {
- semanticRelationsStorageInspector->SetCaseID(caseID);
- }
- }
-}
-
-void QmitkSemanticRelationsNodeSelectionDialog::SetLesion(const mitk::SemanticTypes::Lesion& lesion)
-{
- for (auto panel : m_Panels)
- {
- QmitkAbstractSemanticRelationsStorageInspector* semanticRelationsStorageInspector = dynamic_cast<QmitkAbstractSemanticRelationsStorageInspector*>(panel);
- if (nullptr != semanticRelationsStorageInspector)
- {
- semanticRelationsStorageInspector->SetLesion(lesion);
- }
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsNodeSelectionDialog.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsNodeSelectionDialog.h
deleted file mode 100644
index a767f61ed5..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsNodeSelectionDialog.h
+++ /dev/null
@@ -1,50 +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 QmitkSemanticRelationsNodeSelectionDialog_h
-#define QmitkSemanticRelationsNodeSelectionDialog_h
-
-// semantic relations module
-#include <mitkSemanticTypes.h>
-
-// org.mitk.gui.qt.common plugin
-#include <QmitkNodeSelectionDialog.h>
-
-/*
-* @brief The QmitkSemanticRelationsNodeSelectionDialog extends the QmitkNodeSelectionDialog so that a case ID and a lesion
-* can be set for each known panel that is of type 'QmitkSemanticRelationsStorageInspector'.
-*/
-class QmitkSemanticRelationsNodeSelectionDialog : public QmitkNodeSelectionDialog
-{
- Q_OBJECT
-
-public:
-
- explicit QmitkSemanticRelationsNodeSelectionDialog(QWidget* parent = nullptr, QString caption = "", QString hint = "");
- /**
- * @brief Extends the base class to allow setting the current case ID which is needed to access the
- * semantic relations storage. The function sets the case ID of each 'QmitkSemanticRelationsStorageInspector'.
- *
- * @param caseID A case ID as string
- */
- virtual void SetCaseID(const mitk::SemanticTypes::CaseID& caseID);
- /**
- * @brief Extends the base class to allow setting the current lesion which can be used to show on which images
- * the lesion is visible. The function sets the lesion of each 'QmitkSemanticRelationsStorageInspector'.
- *
- * @param lesion The selected lesion
- */
- virtual void SetLesion(const mitk::SemanticTypes::Lesion& lesion);
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsControls.ui b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsControls.ui
deleted file mode 100644
index 330e1d12c1..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsControls.ui
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkSemanticRelationsStatisticsControls</class>
- <widget class="QWidget" name="QmitkSemanticRelationsStatisticsControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>350</width>
- <height>300</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Semantic relations plugin</string>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="1" column="0">
- <widget class="QComboBox" name="caseIDComboBox"/>
- </item>
- <item row="0" column="0">
- <widget class="QLabel" name="caseIDLabel">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Maximum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Currently selected patient:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QTreeView" name="statisticsTreeView"/>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsView.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsView.cpp
deleted file mode 100644
index 9862b39146..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsView.cpp
+++ /dev/null
@@ -1,87 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkSemanticRelationsStatisticsView.h"
-
-// semantic relations module
-#include <mitkSemanticRelationsIntegration.h>
-#include <mitkRelationStorage.h>
-
-const std::string QmitkSemanticRelationsStatisticsView::VIEW_ID = "org.mitk.views.semanticrelationsstatistics";
-
-QmitkSemanticRelationsStatisticsView::~QmitkSemanticRelationsStatisticsView()
-{
- auto semanticRelationsIntegration = std::make_unique<mitk::SemanticRelationsIntegration>();
- semanticRelationsIntegration->RemoveObserver(this);
-}
-
-void QmitkSemanticRelationsStatisticsView::Update(const mitk::SemanticTypes::CaseID& caseID)
-{
- AddToComboBox(caseID);
-}
-
-void QmitkSemanticRelationsStatisticsView::SetFocus()
-{
- // nothing here
-}
-
-void QmitkSemanticRelationsStatisticsView::CreateQtPartControl(QWidget* parent)
-{
- // create GUI elements
- m_Controls.setupUi(parent);
-
- m_StatisticsTreeModel = new QmitkStatisticsTreeModel(parent);
- m_StatisticsTreeModel->SetDataStorage(GetDataStorage());
- m_Controls.statisticsTreeView->setModel(m_StatisticsTreeModel);
-
- auto semanticRelationsIntegration = std::make_unique<mitk::SemanticRelationsIntegration>();
- semanticRelationsIntegration->AddObserver(this);
-
- SetUpConnections();
- const auto& allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- for (const auto& caseID : allCaseIDs)
- {
- AddToComboBox(caseID);
- }
-}
-
-void QmitkSemanticRelationsStatisticsView::SetUpConnections()
-{
- connect(m_Controls.caseIDComboBox, static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::currentIndexChanged), this, &QmitkSemanticRelationsStatisticsView::OnCaseIDSelectionChanged);
- connect(m_StatisticsTreeModel, &QmitkStatisticsTreeModel::ModelUpdated, this, &QmitkSemanticRelationsStatisticsView::OnModelUpdated);
-}
-
-void QmitkSemanticRelationsStatisticsView::OnCaseIDSelectionChanged(const QString& caseID)
-{
- m_StatisticsTreeModel->SetCaseID(caseID.toStdString());
-}
-
-void QmitkSemanticRelationsStatisticsView::OnModelUpdated()
-{
- m_Controls.statisticsTreeView->expandAll();
- int columns = m_Controls.statisticsTreeView->model()->columnCount();
- for (int i = 0; i < columns; ++i)
- {
- m_Controls.statisticsTreeView->resizeColumnToContents(i);
- }
-}
-
-void QmitkSemanticRelationsStatisticsView::AddToComboBox(const mitk::SemanticTypes::CaseID& caseID)
-{
- int foundIndex = m_Controls.caseIDComboBox->findText(QString::fromStdString(caseID));
- if (-1 == foundIndex)
- {
- // add the caseID to the combo box, as it is not already contained
- m_Controls.caseIDComboBox->addItem(QString::fromStdString(caseID));
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsView.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsView.h
deleted file mode 100644
index 5fcafd7996..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsStatisticsView.h
+++ /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.
-
-============================================================================*/
-
-#ifndef QmitkSemanticRelationsStatisticsView_h
-#define QmitkSemanticRelationsStatisticsView_h
-
-// semantic relations plugin
-#include "ui_QmitkSemanticRelationsStatisticsControls.h"
-
-// semantic relations module
-#include <mitkSemanticTypes.h>
-
-// semantic relations ui module
-#include "QmitkStatisticsTreeModel.h"
-
-// mitk qt gui common plugin
-#include <QmitkAbstractView.h>
-
-/*
-* @brief The QmitkSemanticRelationsStatisticsView is an MITK view to combine and show the statistics tree view of the 'SemanticRelationsUI'-module.
-* It observes the semantic relations storage and displays the currently available case IDs in a combo box.
-* A 'QmitkStatisticsTreeModel' is created and set as the model of a QTreeView.
-*/
-class QmitkSemanticRelationsStatisticsView : public QmitkAbstractView, public mitk::ISemanticRelationsObserver
-{
- Q_OBJECT
-
-public:
-
- static const std::string VIEW_ID;
-
- ~QmitkSemanticRelationsStatisticsView() override;
-
- /*
- * @brief Update the view with the data from the semantic relations.
- *
- * Overridden from 'ISemanticRelationsObserver'.
- * In order for the Update-function to be called, this view has to be added as an observer of SemanticRelation
- * (e.g. m_SemanticRelations->AddObserver(this);)
- *
- * @par caseID The current case ID to identify the currently active patient / case.
- */
- void Update(const mitk::SemanticTypes::CaseID& caseID) override;
-
-protected:
-
- void SetFocus() override;
- void CreateQtPartControl(QWidget* parent) override;
-
-private Q_SLOTS:
-
- void OnCaseIDSelectionChanged(const QString&);
- void OnModelUpdated();
-
-private:
-
- void SetUpConnections();
- void AddToComboBox(const mitk::SemanticTypes::CaseID& caseID);
-
- Ui::QmitkSemanticRelationsStatisticsControls m_Controls;
-
- QmitkStatisticsTreeModel* m_StatisticsTreeModel;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsView.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsView.cpp
deleted file mode 100644
index b6e9ce7db4..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsView.cpp
+++ /dev/null
@@ -1,281 +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.
-
-============================================================================*/
-
-// semantic relations plugin
-#include "QmitkSemanticRelationsView.h"
-#include "QmitkDataNodeAddToSemanticRelationsAction.h"
-#include "QmitkDataNodeRemoveFromSemanticRelationsAction.h"
-#include "QmitkLabelSetJumpToAction.h"
-
-// semantic relations module
-#include <mitkDICOMHelper.h>
-#include <mitkNodePredicates.h>
-#include <mitkSemanticRelationException.h>
-#include <mitkSemanticRelationsInference.h>
-#include <mitkRelationStorage.h>
-
-// mitk core
-#include <mitkImage.h>
-
-// mitk qt widgets module
-#include <QmitkDnDDataNodeWidget.h>
-#include <QmitkRenderWindow.h>
-
-// berry
-#include <berryISelectionService.h>
-#include <berryIWorkbenchWindow.h>
-
-// qt
-#include <QMenu>
-#include <QMessageBox>
-#include <QTreeView>
-
-const std::string QmitkSemanticRelationsView::VIEW_ID = "org.mitk.views.semanticrelations";
-
-void QmitkSemanticRelationsView::SetFocus()
-{
- // nothing here
-}
-
-void QmitkSemanticRelationsView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)
-{
- if (m_RenderWindowPart != renderWindowPart)
- {
- m_RenderWindowPart = renderWindowPart;
- SetControlledRenderer();
- }
-}
-
-void QmitkSemanticRelationsView::RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart)
-{
- if (m_RenderWindowPart == renderWindowPart)
- {
- m_RenderWindowPart = nullptr;
- SetControlledRenderer();
- }
-}
-
-void QmitkSemanticRelationsView::RenderWindowPartInputChanged(mitk::IRenderWindowPart* renderWindowPart)
-{
- if (m_RenderWindowPart == renderWindowPart)
- {
- SetControlledRenderer();
- }
-}
-
-void QmitkSemanticRelationsView::CreateQtPartControl(QWidget* parent)
-{
- // create GUI widgets
- m_Controls.setupUi(parent);
-
- m_LesionInfoWidget = new QmitkLesionInfoWidget(GetDataStorage(), GetSite(), parent);
- m_Controls.gridLayout->addWidget(m_LesionInfoWidget);
-
- m_PatientTableInspector = new QmitkPatientTableInspector(parent);
- m_PatientTableInspector->SetDataStorage(GetDataStorage());
- m_Controls.gridLayout->addWidget(m_PatientTableInspector);
-
- QGridLayout* dndDataNodeWidgetLayout = new QGridLayout;
- dndDataNodeWidgetLayout->addWidget(m_PatientTableInspector, 0, 0);
- dndDataNodeWidgetLayout->setContentsMargins(0, 0, 0, 0);
-
- m_DnDDataNodeWidget = new QmitkDnDDataNodeWidget(parent);
- m_DnDDataNodeWidget->setLayout(dndDataNodeWidgetLayout);
-
- m_Controls.gridLayout->addWidget(m_DnDDataNodeWidget);
-
- m_ContextMenu = new QmitkSemanticRelationsContextMenu(GetSite(), m_PatientTableInspector);
- m_ContextMenu->SetDataStorage(GetDataStorage());
-
- mitk::IRenderWindowPart* renderWindowPart = GetRenderWindowPart();
- if (nullptr != renderWindowPart)
- {
- RenderWindowPartActivated(renderWindowPart);
- }
-
- SetUpConnections();
-
- const auto& allCaseIDs = mitk::RelationStorage::GetAllCaseIDs();
- for (const auto& caseID : allCaseIDs)
- {
- AddToComboBox(caseID);
- }
-}
-
-void QmitkSemanticRelationsView::SetUpConnections()
-{
- connect(m_Controls.caseIDComboBox, static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::currentIndexChanged), this, &QmitkSemanticRelationsView::OnCaseIDSelectionChanged);
- connect(m_LesionInfoWidget, &QmitkLesionInfoWidget::LesionSelectionChanged, this, &QmitkSemanticRelationsView::OnLesionSelectionChanged);
- connect(m_PatientTableInspector, &QmitkPatientTableInspector::CurrentSelectionChanged, this, &QmitkSemanticRelationsView::OnDataNodeSelectionChanged);
- connect(m_PatientTableInspector, &QmitkPatientTableInspector::DataNodeDoubleClicked, this, &QmitkSemanticRelationsView::OnDataNodeDoubleClicked);
- connect(m_DnDDataNodeWidget, &QmitkDnDDataNodeWidget::NodesDropped, this, &QmitkSemanticRelationsView::OnNodesAdded);
-
- connect(m_PatientTableInspector, &QmitkPatientTableInspector::OnContextMenuRequested, m_ContextMenu, &QmitkSemanticRelationsContextMenu::OnContextMenuRequested);
- connect(m_PatientTableInspector, &QmitkPatientTableInspector::OnNodeRemoved, this, &QmitkSemanticRelationsView::NodeRemoved);
-}
-
-QItemSelectionModel* QmitkSemanticRelationsView::GetDataNodeSelectionModel() const
-{
- return m_PatientTableInspector->GetSelectionModel();
-}
-
-void QmitkSemanticRelationsView::NodeRemoved(const mitk::DataNode* dataNode)
-{
- if (nullptr == dataNode)
- {
- return;
- }
-
- if (mitk::SemanticRelationsInference::InstanceExists(dataNode))
- {
- try
- {
- RemoveFromSemanticRelationsAction::Run(GetDataStorage(), dataNode);
- mitk::SemanticTypes::CaseID caseID = mitk::GetCaseIDFromDataNode(dataNode);
- RemoveFromComboBox(caseID);
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not remove the data node(s).",
- "The program wasn't able to correctly remove the selected data node(s).\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
- }
-}
-
-void QmitkSemanticRelationsView::OnLesionSelectionChanged(const mitk::SemanticTypes::Lesion& lesion)
-{
- m_PatientTableInspector->SetLesion(lesion);
-}
-
-void QmitkSemanticRelationsView::OnDataNodeSelectionChanged(const QList<mitk::DataNode::Pointer>& dataNodeSelection)
-{
- m_LesionInfoWidget->SetDataNodeSelection(dataNodeSelection);
-}
-
-void QmitkSemanticRelationsView::OnDataNodeDoubleClicked(const mitk::DataNode* dataNode)
-{
- if (nullptr == dataNode)
- {
- return;
- }
-
- if (mitk::NodePredicates::GetImagePredicate()->CheckNode(dataNode))
- {
- OpenInEditor(dataNode);
- }
- else if (mitk::NodePredicates::GetSegmentationPredicate()->CheckNode(dataNode))
- {
- LabelSetJumpToAction::Run(GetSite(), dataNode);
- }
-}
-
-void QmitkSemanticRelationsView::OnCaseIDSelectionChanged(const QString& caseID)
-{
- m_LesionInfoWidget->SetCaseID(caseID.toStdString());
- m_PatientTableInspector->SetCaseID(caseID.toStdString());
-}
-
-void QmitkSemanticRelationsView::OnNodesAdded(std::vector<mitk::DataNode*> nodes)
-{
- mitk::SemanticTypes::CaseID caseID = "";
- for (mitk::DataNode* dataNode : nodes)
- {
- try
- {
- AddToSemanticRelationsAction::Run(GetDataStorage(), dataNode);
- caseID = mitk::GetCaseIDFromDataNode(dataNode);
- AddToComboBox(caseID);
- }
- catch (const mitk::SemanticRelationException& e)
- {
- std::stringstream exceptionMessage; exceptionMessage << e;
- QMessageBox msgBox(QMessageBox::Warning,
- "Could not add the data node(s).",
- "The program wasn't able to correctly add the selected data node(s).\n"
- "Reason:\n" + QString::fromStdString(exceptionMessage.str() + "\n"));
- msgBox.exec();
- }
- }
-}
-
-void QmitkSemanticRelationsView::OnNodeRemoved(const mitk::DataNode* dataNode)
-{
- NodeRemoved(dataNode);
-}
-
-void QmitkSemanticRelationsView::AddToComboBox(const mitk::SemanticTypes::CaseID& caseID)
-{
- int foundIndex = m_Controls.caseIDComboBox->findText(QString::fromStdString(caseID));
- if (-1 == foundIndex)
- {
- // add the caseID to the combo box, as it is not already contained
- m_Controls.caseIDComboBox->addItem(QString::fromStdString(caseID));
- }
-}
-
-void QmitkSemanticRelationsView::RemoveFromComboBox(const mitk::SemanticTypes::CaseID& caseID)
-{
- std::vector<mitk::SemanticTypes::ControlPoint> allControlPoints = mitk::RelationStorage::GetAllControlPointsOfCase(caseID);
- int foundIndex = m_Controls.caseIDComboBox->findText(QString::fromStdString(caseID));
- if (allControlPoints.empty() && -1 != foundIndex)
- {
- // caseID does not contain any control points and therefore no data
- // remove the caseID, if it is still contained
- m_Controls.caseIDComboBox->removeItem(foundIndex);
- }
-}
-
-void QmitkSemanticRelationsView::OpenInEditor(const mitk::DataNode* dataNode)
-{
- auto renderWindowPart = GetRenderWindowPart();
- if (nullptr == renderWindowPart)
- {
- renderWindowPart = GetRenderWindowPart(mitk::WorkbenchUtil::IRenderWindowPartStrategy::BRING_TO_FRONT | mitk::WorkbenchUtil::IRenderWindowPartStrategy::OPEN);
- if (nullptr == renderWindowPart)
- {
- // no render window available
- return;
- }
- }
-
- auto image = dynamic_cast<mitk::Image*>(dataNode->GetData());
- if (nullptr != image)
- {
- mitk::RenderingManager::GetInstance()->InitializeViews(image->GetTimeGeometry());
- }
-}
-
-void QmitkSemanticRelationsView::SetControlledRenderer()
-{
- QHash<QString, QmitkRenderWindow*> renderWindows;
- if (m_RenderWindowPart != nullptr)
- {
- renderWindows = m_RenderWindowPart->GetQmitkRenderWindows();
- }
-
- mitk::RenderWindowLayerUtilities::RendererVector controlledRenderer;
- mitk::BaseRenderer* baseRenderer = nullptr;
- for (const auto& renderWindow : renderWindows.values())
- {
- baseRenderer = mitk::BaseRenderer::GetInstance(renderWindow->GetVtkRenderWindow());
- if (nullptr != baseRenderer)
- {
- controlledRenderer.push_back(baseRenderer);
- }
- }
-
- m_ContextMenu->SetControlledRenderer(controlledRenderer);
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsView.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsView.h
deleted file mode 100644
index 639d04c265..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/QmitkSemanticRelationsView.h
+++ /dev/null
@@ -1,106 +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 QmitkSemanticRelationsView_h
-#define QmitkSemanticRelationsView_h
-
-// semantic relations plugin
-#include "ui_QmitkSemanticRelationsControls.h"
-#include "QmitkLesionInfoWidget.h"
-#include "QmitkSemanticRelationsContextMenu.h"
-
-// semantic relations module
-#include <mitkSemanticTypes.h>
-
-// semantic relations UI module
-#include <QmitkPatientTableInspector.h>
-
-// mitk gui common plugin
-#include <mitkIRenderWindowPartListener.h>
-
-// berry
-#include <berryISelectionListener.h>
-
-// mitk qt gui common plugin
-#include <QmitkAbstractView.h>
-
-class QmitkDnDDataNodeWidget;
-class QMenu;
-
-/*
-* @brief The QmitkSemanticRelationsView is an MITK view to combine and show the widgets of the 'SemanticRelationsUI'-module and this semantic relations plugin.
-*
-* It allows the MITK user to see and modify the content of the SemanticRelations-session.
-* A combo box is used to select and show the current patient.
-*/
-class QmitkSemanticRelationsView : public QmitkAbstractView, public mitk::IRenderWindowPartListener
-{
- Q_OBJECT
-
-public:
-
- static const std::string VIEW_ID;
-
- void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) override;
- void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) override;
- void RenderWindowPartInputChanged(mitk::IRenderWindowPart* renderWindowPart) override;
-
-protected:
-
- void SetFocus() override;
- void CreateQtPartControl(QWidget* parent) override;
-
-private Q_SLOTS:
-
- void OnLesionSelectionChanged(const mitk::SemanticTypes::Lesion&);
- void OnDataNodeSelectionChanged(const QList<mitk::DataNode::Pointer>&);
- void OnDataNodeDoubleClicked(const mitk::DataNode*);
- void OnCaseIDSelectionChanged(const QString&);
-
- void OnNodesAdded(std::vector<mitk::DataNode*>);
- void OnNodeRemoved(const mitk::DataNode*);
-
-private:
-
- void SetUpConnections();
- /**
- * @brief Provide a QItemSelectionModel, which supports the data role 'QmitkDataNodeRole' (\see QmitkRenderWindowDataModel).
- *
- * The provided QItemSelectionModel is used in the QmitkAbstractView-base class as the selection model of
- * the selection provider (\see QmitkAbstractView::SetSelectionProvider()).
- * The default selection provider is a QmitkDataNodeSelectionProvider. Each time a selection in the provided
- * QItemSelectionModel is changed, a selection changed event is fired. All plugins (views), that subclass the
- * QmitkAbstractView will be informed about the selection changed via the OnSelectionChanged-function.
- */
- QItemSelectionModel* GetDataNodeSelectionModel() const override;
-
- void NodeRemoved(const mitk::DataNode* dataNode) override;
-
- void AddToComboBox(const mitk::SemanticTypes::CaseID& caseID);
- void RemoveFromComboBox(const mitk::SemanticTypes::CaseID& caseID);
-
- void OpenInEditor(const mitk::DataNode* dataNode);
-
- void SetControlledRenderer();
-
- Ui::QmitkSemanticRelationsControls m_Controls;
-
- mitk::IRenderWindowPart* m_RenderWindowPart;
-
- QmitkLesionInfoWidget* m_LesionInfoWidget;
- QmitkPatientTableInspector* m_PatientTableInspector;
- QmitkDnDDataNodeWidget* m_DnDDataNodeWidget;
-
- QmitkSemanticRelationsContextMenu* m_ContextMenu;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/mitkPluginActivator.cpp
deleted file mode 100644
index 883a0f8650..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/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 "QmitkSemanticRelationsStatisticsView.h"
-#include "QmitkSemanticRelationsView.h"
-
-#include <mitkPersistenceService.h>
-
-namespace mitk
-{
- void SemanticRelationsActivator::start(ctkPluginContext *context)
- {
- mitk::PersistenceService::LoadModule();
-
- BERRY_REGISTER_EXTENSION_CLASS(QmitkSemanticRelationsView, context)
- BERRY_REGISTER_EXTENSION_CLASS(QmitkSemanticRelationsStatisticsView, context)
- }
-
- void SemanticRelationsActivator::stop(ctkPluginContext *context) { Q_UNUSED(context) }
-}
diff --git a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/mitkPluginActivator.h
deleted file mode 100644
index e1bc611bd3..0000000000
--- a/Plugins/org.mitk.gui.qt.semanticrelations/src/internal/mitkPluginActivator.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 mitkPluginActivator_h
-#define mitkPluginActivator_h
-
-#include <ctkPluginActivator.h>
-
-namespace mitk
-{
- class SemanticRelationsActivator : public QObject, public ctkPluginActivator
- {
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_semanticrelations")
- Q_INTERFACES(ctkPluginActivator)
-
- public:
- void start(ctkPluginContext* context) override;
- void stop(ctkPluginContext* context) override;
-
- };
-}
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/CMakeLists.txt b/Plugins/org.mitk.gui.qt.tubegraph/CMakeLists.txt
deleted file mode 100644
index cb85bf6f41..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-PROJECT(org_mitk_gui_qt_tubegraph)
-
-mitk_create_plugin(
- EXPORT_DIRECTIVE TUBEGRAPH_EXPORT
- EXPORTED_INCLUDE_SUFFIXES src
- MODULE_DEPENDS MitkTubeGraph MitkQtWidgetsExt #QmitkExt MitkSegmentationUI
-)
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/files.cmake b/Plugins/org.mitk.gui.qt.tubegraph/files.cmake
deleted file mode 100644
index 53d078307a..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/files.cmake
+++ /dev/null
@@ -1,47 +0,0 @@
-SET(SRC_CPP_FILES
-
-)
-
-SET(INTERNAL_CPP_FILES
- mitkPluginActivator.cpp
- mitkTubeGraphDefaultLabelGroups.cpp
- QmitkTubeGraphView.cpp
- QmitkTubeGraphLabelWidget.cpp
- QmitkTubeGraphLabelGroupWidget.cpp
- QmitkTubeGraphDeleteLabelGroupDialog.cpp
- QmitkTubeGraphNewLabelGroupDialog.cpp
- QmitkTubeGraphNewAnnotationDialog.cpp
-)
-SET(UI_FILES
- src/internal/QmitkTubeGraphViewControls.ui
-)
-
-SET(MOC_H_FILES
- src/internal/mitkPluginActivator.h
- src/internal/QmitkTubeGraphView.h
- src/internal/QmitkTubeGraphLabelWidget.h
- src/internal/QmitkTubeGraphLabelGroupWidget.h
- src/internal/QmitkTubeGraphDeleteLabelGroupDialog.h
- src/internal/QmitkTubeGraphNewLabelGroupDialog.h
- src/internal/QmitkTubeGraphNewAnnotationDialog.h
-)
-
-SET(CACHED_RESOURCE_FILES
- resources/tubeGraph.png
- resources/icon_seedpoint.png
- plugin.xml
-)
-
-SET(QRC_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/org.mitk.gui.qt.tubegraph/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.tubegraph/manifest_headers.cmake
deleted file mode 100644
index 2b6a1b533c..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/manifest_headers.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(Plugin-Name "MITK Tube Graph")
-set(Plugin-Version "1.0.0")
-set(Plugin-Vendor "German Cancer Research Center (DKFZ)")
-set(Plugin-ContactAddress "https://www.mitk.org")
-set(Require-Plugin org.mitk.gui.qt.common)
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/plugin.xml b/Plugins/org.mitk.gui.qt.tubegraph/plugin.xml
deleted file mode 100644
index 91761a43b2..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/plugin.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?BlueBerry version="0.1"?>
-<plugin>
- <extension point="org.blueberry.ui.views">
- <view id="org.mitk.views.tubegraph"
- name="Tube Graph"
- icon="resources/tubeGraph.png"
- class="QmitkTubeGraphView" />
- </extension>
-</plugin>
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/resources/icon_seedpoint.png b/Plugins/org.mitk.gui.qt.tubegraph/resources/icon_seedpoint.png
deleted file mode 100644
index 6175c379fe..0000000000
Binary files a/Plugins/org.mitk.gui.qt.tubegraph/resources/icon_seedpoint.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/resources/tubeGraph.png b/Plugins/org.mitk.gui.qt.tubegraph/resources/tubeGraph.png
deleted file mode 100644
index 71ba043c1b..0000000000
Binary files a/Plugins/org.mitk.gui.qt.tubegraph/resources/tubeGraph.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphDeleteLabelGroupDialog.cpp b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphDeleteLabelGroupDialog.cpp
deleted file mode 100644
index 9e3665c522..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphDeleteLabelGroupDialog.cpp
+++ /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.
-
-============================================================================*/
-
-#include "QmitkTubeGraphDeleteLabelGroupDialog.h"
-
-#include <QAbstractItemView>
-#include <QPushButton>
-#include <QLayout>
-#include <QLabel>
-#include <QListWidget>
-
-
-
-QmitkTubeGraphDeleteLabelGroupDialog::QmitkTubeGraphDeleteLabelGroupDialog(QWidget* parent)
-:QDialog(parent)
-{
-
- QDialog::setFixedSize(400, 400);
-
- auto layout = new QVBoxLayout(this);
- layout->setMargin(5);
- layout->setSpacing(5);
-
- descriptionLabel = new QLabel("Which Label Group should be removed?", this);
- layout->addWidget(descriptionLabel);
-
- labelGroupListWidget = new QListWidget(this);
- labelGroupListWidget->setSelectionMode(QAbstractItemView::MultiSelection);
- layout->addWidget(labelGroupListWidget);
-
- auto buttonLayout = new QHBoxLayout();
-
- deleteButton = new QPushButton("Delete", this);
- buttonLayout->addWidget(deleteButton);
- connect( deleteButton, SIGNAL(clicked()), this, SLOT(OnDeleteLabelGroupClicked()) );
-
- cancleButton = new QPushButton("Cancel", this);
- buttonLayout->addWidget(cancleButton);
- connect( cancleButton, SIGNAL(clicked()), this, SLOT(reject()) );
-
- layout->addLayout(buttonLayout);
-
- deleteButton->setFocus();
-
-}
-
-QmitkTubeGraphDeleteLabelGroupDialog::~QmitkTubeGraphDeleteLabelGroupDialog()
-{
- delete descriptionLabel;
- delete labelGroupListWidget;
- delete deleteButton;
- delete cancleButton;
-}
-
-void QmitkTubeGraphDeleteLabelGroupDialog::OnDeleteLabelGroupClicked()
-{
- //get selected items and save it in vector
- m_LabelGroupList.clear();
- for (int i =0; i < labelGroupListWidget->count(); i++)
- {
- QListWidgetItem* newItem= labelGroupListWidget->item(i);
- if(newItem->isSelected()) //For all checked items
- {
- m_LabelGroupList.push_back(newItem->text());
- }
- }
-
- this->accept();
-}
-
-QStringList QmitkTubeGraphDeleteLabelGroupDialog::GetSelectedLabelGroups()
-{
- return m_LabelGroupList;
-}
-
-void QmitkTubeGraphDeleteLabelGroupDialog::SetLabelGroups(const QStringList &labelGroups)
-{
- for (const auto &labelGroup : labelGroups)
- labelGroupListWidget->addItem(labelGroup);
-}
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphDeleteLabelGroupDialog.h b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphDeleteLabelGroupDialog.h
deleted file mode 100644
index 5b86428900..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphDeleteLabelGroupDialog.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 QmitkTubeGraphDeleteLabelGroupDialog_h
-#define QmitkTubeGraphDeleteLabelGroupDialog_h
-
-
-#include <QDialog>
-
-class QPushButton;
-class QListWidget;
-class QLabel;
-class QWidget;
-
-class QmitkTubeGraphDeleteLabelGroupDialog : public QDialog
-{
- Q_OBJECT
-
-public:
-
- QmitkTubeGraphDeleteLabelGroupDialog(QWidget* parent = nullptr);
- ~QmitkTubeGraphDeleteLabelGroupDialog() override;
-
- QStringList GetSelectedLabelGroups();
- void SetLabelGroups(const QStringList &labelGroups);
-
-
- protected slots:
- void OnDeleteLabelGroupClicked();
-
-protected:
- QLabel* descriptionLabel;
- QListWidget* labelGroupListWidget;
- QPushButton* deleteButton;
- QPushButton* cancleButton;
-
- QStringList m_LabelGroupList;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelGroupWidget.cpp b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelGroupWidget.cpp
deleted file mode 100644
index 3498ecff66..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelGroupWidget.cpp
+++ /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.
-
-============================================================================*/
-
-#include "QmitkTubeGraphLabelGroupWidget.h"
-
-#include "QmitkTubeGraphLabelWidget.h"
-
-QmitkTubeGraphLabelGroupWidget::QmitkTubeGraphLabelGroupWidget(QWidget* parent, const char* name)
-:QWidget(parent)
-{
- m_GroupLayout = new QVBoxLayout();
- this->SetGroupName(QString(name));
- this->setLayout(m_GroupLayout);
-}
-
-QmitkTubeGraphLabelGroupWidget::~QmitkTubeGraphLabelGroupWidget()
-{
- //m_Labels.clear();
- delete m_GroupLayout;
-}
-
-void QmitkTubeGraphLabelGroupWidget::AddLabel(QString name, mitk::Color color)
-{
- auto label = new QmitkTubeGraphLabelWidget(this);
- label->SetLabelName(name);
- label->SetLabelColor(&color);
-
- m_GroupLayout->addWidget(label);
-
- connect(label, SIGNAL(SignalLabelVisibilityToggled(bool, QString)), this, SLOT(OnVisibilityToggled(bool, QString)));
- connect(label, SIGNAL(SignalLabelButtonClicked(QString)), this, SLOT(OnLabelButtonClicked(QString)));
- connect(label, SIGNAL(SignalLabelColorChanged(mitk::Color, QString)), this, SLOT(OnColoringButtonClicked(mitk::Color, QString)));
-}
-
-void QmitkTubeGraphLabelGroupWidget::SetGroupName(QString name)
-{
- m_GroupName = name;
-}
-
-QString QmitkTubeGraphLabelGroupWidget::GetGroupName()
-{
- return m_GroupName;
-}
-
-void QmitkTubeGraphLabelGroupWidget::OnVisibilityToggled(bool isVisible, QString labelName)
-{
- emit SignalLabelVisibilityInGroupToggled(isVisible, labelName, this->GetGroupName());
-}
-
-void QmitkTubeGraphLabelGroupWidget::OnLabelButtonClicked(QString labelName)
-{
- emit SignalLabelButtonInGroupClicked(labelName, this->GetGroupName());
-}
-
-void QmitkTubeGraphLabelGroupWidget::OnColoringButtonClicked(mitk::Color color, QString labelName)
-{
- emit SignalLabelColorInGroupChanged(color, labelName, this->GetGroupName());
-}
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelGroupWidget.h b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelGroupWidget.h
deleted file mode 100644
index 116fdd1d26..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelGroupWidget.h
+++ /dev/null
@@ -1,53 +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 QmitkTubeGraphLabelGroupWidget_h
-#define QmitkTubeGraphLabelGroupWidget_h
-
-#include "mitkColorProperty.h"
-
-#include <QVector>
-#include <QVBoxLayout>
-#include <QWidget>
-
-class QmitkTubeGraphLabelGroupWidget : public QWidget
-{
- Q_OBJECT
-
-public:
- QmitkTubeGraphLabelGroupWidget(QWidget *parent = nullptr, const char* name = nullptr);
- ~QmitkTubeGraphLabelGroupWidget() override;
-
- void SetGroupName(QString name);
- QString GetGroupName();
- void AddLabel(QString name, mitk::Color color);
-
-signals:
- void SignalLabelVisibilityInGroupToggled(bool, QString, QString);
- void SignalLabelButtonInGroupClicked(QString, QString);
- void SignalLabelColorInGroupChanged(mitk::Color, QString, QString);
-
- protected slots:
-
- void OnVisibilityToggled(bool isVisible, QString labelName);
- void OnLabelButtonClicked(QString labelName);
- void OnColoringButtonClicked(mitk::Color color, QString labelName);
-
-private:
-
- QString m_GroupName;
- QVBoxLayout* m_GroupLayout;
- //QVector<QmitkTubeGraphLabelWidget*> m_Labels;
-
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelWidget.cpp b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelWidget.cpp
deleted file mode 100644
index ca5289bc97..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelWidget.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 "QmitkTubeGraphLabelWidget.h"
-
-#include <QHBoxLayout>
-#include <QColorDialog>
-
-QmitkTubeGraphLabelWidget::QmitkTubeGraphLabelWidget(QWidget* parent)
-:QWidget(parent)
-{
- this->InitWidget();
-}
-
-QmitkTubeGraphLabelWidget::~QmitkTubeGraphLabelWidget()
-{
- delete m_VisibilityCheckBox;
- delete m_LabelPushButton;
- delete m_ColoringPushButton;
-}
-
-void QmitkTubeGraphLabelWidget::InitWidget()
-{
-
- m_VisibilityCheckBox = new QCheckBox("", this);
- m_VisibilityCheckBox->setChecked(true);
- m_VisibilityCheckBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
-
- m_LabelPushButton = new QPushButton("", this);
- //m_LabelPushButton->setCheckable(true);
- //m_LabelPushButton->setAutoExclusive(true);
-
- m_ColoringPushButton = new QPushButton(this);
- m_ColoringPushButton->setStyleSheet( QString("* { background-color: rgb(0,0,0)}"));
- m_ColoringPushButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
-
- auto layout = new QHBoxLayout;
-
- layout->addWidget(m_VisibilityCheckBox);
- layout->addWidget(m_LabelPushButton);
- layout->addWidget(m_ColoringPushButton);
-
- this->setLayout(layout);
-
- connect(m_VisibilityCheckBox, SIGNAL(toggled(bool)), this, SLOT(OnVisibilityToggled(bool)));
- connect(m_LabelPushButton, SIGNAL(clicked()), this, SLOT(OnLabelButtonClicked()));
-
- connect(m_ColoringPushButton, SIGNAL(clicked()), this, SLOT(OnColoringButtonClicked()));
- //connect(m_ColoringPushButton, SIGNAL(clicked()), this, SIGNAL(SignalLabelColorChanged(this->GetLabelName())));
-}
-
-void QmitkTubeGraphLabelWidget::SetLabelName(QString name)
-{
- m_LabelPushButton->setText(name);
-}
-
-QString QmitkTubeGraphLabelWidget::GetLabelName()
-{
- return m_LabelPushButton->text();
-}
-
-void QmitkTubeGraphLabelWidget::SetLabelColor(mitk::Color* color)
-{
- m_ColoringPushButton->setStyleSheet( QString("* { background-color: rgb(%1,%2,%3)}").arg(color->GetRed()).arg(color->GetGreen()).arg(color->GetBlue()) );
-}
-
-mitk::Color* QmitkTubeGraphLabelWidget::GetLabelColor()
-{
- //return the background color of the button
- const QColor color = m_ColoringPushButton->palette().color(QPalette::Button);
- auto rgb = new mitk::Color();
- rgb->Set(color.red(), color.green(), color.blue());
- return rgb;
-}
-
-void QmitkTubeGraphLabelWidget::OnVisibilityToggled(bool isVisible)
-{
- emit SignalLabelVisibilityToggled(isVisible, this->GetLabelName());
-}
-
-void QmitkTubeGraphLabelWidget::OnLabelButtonClicked()
-{
- emit SignalLabelButtonClicked(this->GetLabelName());
-}
-
-void QmitkTubeGraphLabelWidget::OnColoringButtonClicked()
-{
- QColor usersChoice = QColorDialog::getColor();
- mitk::Color color;
-
- if (usersChoice.spec() != 0)
- {
- color[0] = usersChoice.red();
- color[1] = usersChoice.green();
- color[2] = usersChoice.blue();
-
- this->SetLabelColor(&color);
- emit SignalLabelColorChanged(color, this->GetLabelName());
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelWidget.h b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelWidget.h
deleted file mode 100644
index 3953c3655b..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphLabelWidget.h
+++ /dev/null
@@ -1,58 +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 QmitkTubeGraphLabelWidget_h
-#define QmitkTubeGraphLabelWidget_h
-
-#include "mitkColorProperty.h"
-
-#include <QCheckBox>
-#include <QPushButton>
-
-class QmitkTubeGraphLabelWidget : public QWidget
-{
- Q_OBJECT
-
-public:
-
- QmitkTubeGraphLabelWidget(QWidget* parent = nullptr);
- //QmitkTubeGraphLabelWidget(QWidget* parent = 0, const char* name = 0, mitk::Color* color = 0 /*TODO*/);
- ~QmitkTubeGraphLabelWidget() override;
-
- void SetLabelName(QString name);
- QString GetLabelName();
- void SetLabelColor(mitk::Color* color);
- mitk::Color* GetLabelColor();
-
-signals:
-
- void SignalLabelVisibilityToggled(bool, QString);
- void SignalLabelButtonClicked(QString);
- void SignalLabelColorChanged(mitk::Color, QString);
-
- protected slots:
-
- void OnVisibilityToggled(bool isVisible);
- void OnLabelButtonClicked();
- void OnColoringButtonClicked();
-
-
-private:
-
- void InitWidget();
-
- QCheckBox* m_VisibilityCheckBox;
- QPushButton* m_LabelPushButton;
- QPushButton* m_ColoringPushButton;
-
-};
-#endif
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewAnnotationDialog.cpp b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewAnnotationDialog.cpp
deleted file mode 100644
index 42242f42f1..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewAnnotationDialog.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 "QmitkTubeGraphNewAnnotationDialog.h"
-
-#include <qpushbutton.h>
-#include <qlayout.h>
-#include <qlineedit.h>
-#include <qlabel.h>
-#include <qlistwidget.h>
-
-
-QmitkTubeGraphNewAnnotationDialog::QmitkTubeGraphNewAnnotationDialog(QWidget* parent)
-:QDialog(parent)
-{
- QDialog::setFixedSize(200, 200);
-
- layout = new QVBoxLayout(this);
- layout->setMargin(5);
- layout->setSpacing(5);
-
- annotationNameLabel = new QLabel("Enter the name of the annotation!", this);
- layout->addWidget(annotationNameLabel);
-
- annotationNameLineEdit = new QLineEdit(this);
- layout->addWidget(annotationNameLineEdit);
-
- annotationDescriptionLabel = new QLabel("Enter a description!", this);
- layout->addWidget(annotationDescriptionLabel);
-
- annotationDescriptionLineEdit = new QLineEdit(this);
- layout->addWidget(annotationDescriptionLineEdit);
-
- buttonLayout = new QHBoxLayout();
-
- okButton = new QPushButton("Ok", this);
- buttonLayout->addWidget(okButton, 0, Qt::AlignRight);
- connect( okButton, SIGNAL(clicked()), this, SLOT(OnAddingAnnotation()) );
-
- cancleButton = new QPushButton("Cancel", this);
- buttonLayout->addWidget(cancleButton, 0, Qt::AlignRight);
- connect( cancleButton, SIGNAL(clicked()), this, SLOT(reject()) );
-
- layout->addLayout(buttonLayout);
-
- annotationNameLineEdit->setFocus();
-}
-
-void QmitkTubeGraphNewAnnotationDialog::OnAddingAnnotation()
-{
- if (annotationNameLineEdit->text().isEmpty())
- {
- annotationNameLineEdit->setStyleSheet("border: 1px solid red");
- return;
- }
-
- m_NewAnnotationName = annotationNameLineEdit->text();
- m_NewAnnotationDescription = annotationDescriptionLineEdit->text();
-
- this->accept();
-}
-
-QmitkTubeGraphNewAnnotationDialog::~QmitkTubeGraphNewAnnotationDialog()
-{
- delete layout;
-
- delete okButton;
- delete cancleButton;
- // delete buttonLayout;
-
- delete annotationNameLabel;
- delete annotationNameLineEdit;
-
- delete annotationDescriptionLabel;
- delete annotationDescriptionLineEdit;
-}
-
-QString QmitkTubeGraphNewAnnotationDialog::GetAnnotationName()
-{
- return m_NewAnnotationName;
-}
-
-QString QmitkTubeGraphNewAnnotationDialog::GetAnnotationDescription()
-{
- return m_NewAnnotationDescription;
-}
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewAnnotationDialog.h b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewAnnotationDialog.h
deleted file mode 100644
index f9ff4fe7ed..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewAnnotationDialog.h
+++ /dev/null
@@ -1,58 +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 QmitkTubeGraphNewAnnotationDialog_h
-#define QmitkTubeGraphNewAnnotationDialog_h
-
-#include <qdialog.h>
-
-class QPushButton;
-class QVBoxLayout;
-class QHBoxLayout;
-class QLineEdit;
-class QLabel;
-
-class QmitkTubeGraphNewAnnotationDialog : public QDialog
-{
- Q_OBJECT
-
-public:
-
- QmitkTubeGraphNewAnnotationDialog(QWidget* parent = nullptr);
- ~QmitkTubeGraphNewAnnotationDialog() override;
-
- QString GetAnnotationName();
- QString GetAnnotationDescription();
-
-protected slots:
-
-void OnAddingAnnotation();
-
-protected:
-
- QVBoxLayout* layout;
- QHBoxLayout* buttonLayout;
-
- QPushButton* okButton;
- QPushButton* cancleButton;
-
- QLabel* annotationNameLabel;
- QLineEdit* annotationNameLineEdit;
-
- QLabel* annotationDescriptionLabel;
- QLineEdit* annotationDescriptionLineEdit;
-
- QString m_NewAnnotationName;
- QString m_NewAnnotationDescription;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewLabelGroupDialog.cpp b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewLabelGroupDialog.cpp
deleted file mode 100644
index d3559fc168..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewLabelGroupDialog.cpp
+++ /dev/null
@@ -1,270 +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 "QmitkTubeGraphNewLabelGroupDialog.h"
-
-#include <qpushbutton.h>
-#include <qlayout.h>
-#include <qlineedit.h>
-#include <qlabel.h>
-#include <qlistwidget.h>
-#include <qtreewidget.h>
-#include <qheaderview.h>
-
-#include "mitkTubeGraphDefaultLabelGroups.h"
-
-
-QmitkTubeGraphNewLabelGroupDialog::QmitkTubeGraphNewLabelGroupDialog(QWidget* parent)
-:QDialog(parent)
-,m_NewLabelGroup()
-{
- QDialog::setFixedSize(200, 200);
-
- layout = new QVBoxLayout(this);
- layout->setMargin(5);
- layout->setSpacing(5);
-
- newLabelGroupButton = new QPushButton("Create new label group", this);
- layout->addWidget(newLabelGroupButton, 0, Qt::AlignHCenter);
- connect( newLabelGroupButton, SIGNAL(clicked()), this, SLOT(OnCreateNewLabelGroup()) );
-
- standardLabelGroupButton = new QPushButton("Add standard label group", this);
- layout->addWidget(standardLabelGroupButton, 0, Qt::AlignHCenter);
- connect( standardLabelGroupButton, SIGNAL(clicked()), this, SLOT(OnAddStandardLabelGroup()) );
-
- spacer = new QSpacerItem( 20, 40, QSizePolicy::Minimum, QSizePolicy::Minimum );
- layout->addSpacerItem(spacer);
-
- buttonLayout = new QHBoxLayout();
-
- okButton = new QPushButton("Ok", this);
- buttonLayout->addWidget(okButton, 0, Qt::AlignRight);
- okButton->setVisible(false);
-
- cancleButton = new QPushButton("Cancel", this);
- buttonLayout->addWidget(cancleButton, 0, Qt::AlignRight);
- connect( cancleButton, SIGNAL(clicked()), this, SLOT(reject()) );
-
- layout->addLayout(buttonLayout);
-
- newLabelGroupButton->setFocus();
-
-}
-
-QmitkTubeGraphNewLabelGroupDialog::~QmitkTubeGraphNewLabelGroupDialog()
-{
- //delete layout;
- ////delete buttonLayout;
- //delete spacer;
- //delete okButton;
- //delete cancleButton;
-
- //delete labelGroupDescriptionLabel;
- /* delete labelGroupLineEdit;
-
- delete labelDescriptionLabel;
- delete labelLineEdit;
- delete addLabelButton;
- delete labelListWidget; */
- //delete labelGroupTreeWidget;
-}
-
-void QmitkTubeGraphNewLabelGroupDialog::OnCreateNewLabelGroup()
-{
- QDialog::setFixedSize(400, 200);
-
- layout->removeWidget(newLabelGroupButton);
- delete newLabelGroupButton;
-
- layout->removeWidget(standardLabelGroupButton);
- delete standardLabelGroupButton;
-
- layout->removeWidget(okButton);
- layout->removeWidget(cancleButton);
-
- layout->removeItem(spacer);
- layout->removeItem(buttonLayout);
-
- labelGroupDescriptionLabel = new QLabel("Enter the label group name!", this);
- layout->addWidget(labelGroupDescriptionLabel);
-
- labelGroupLineEdit = new QLineEdit(this);
- layout->addWidget(labelGroupLineEdit);
-
- labelDescriptionLabel = new QLabel("Enter a label name!", this);
- layout->addWidget(labelDescriptionLabel);
-
-
- auto labelLayout = new QHBoxLayout();
-
- labelLineEdit = new QLineEdit(this);
- labelLayout->addWidget(labelLineEdit);
-
- addLabelButton = new QPushButton("+", this);
- labelLayout->addWidget(addLabelButton);
- connect( addLabelButton, SIGNAL(clicked()), this, SLOT(OnAddingLabel()) );
-
- layout->addLayout(labelLayout);
-
- labelListWidget = new QListWidget(this);
- labelListWidget->setDragDropMode(QAbstractItemView::InternalMove);
- labelListWidget->addItem("Undefined");
- layout->addWidget(labelListWidget);
-
- layout->addLayout(buttonLayout);
- connect( okButton, SIGNAL(clicked()), this, SLOT(OnAddingNewLabelGroup()) );
-
- okButton->setVisible(true);
-}
-
-void QmitkTubeGraphNewLabelGroupDialog::OnAddStandardLabelGroup()
-{
- QDialog::setFixedSize(400, 200);
-
- layout->removeWidget(newLabelGroupButton);
- delete newLabelGroupButton;
-
- layout->removeWidget(standardLabelGroupButton);
- delete standardLabelGroupButton;
-
- layout->removeWidget(okButton);
- layout->removeWidget(cancleButton);
-
- layout->removeItem(spacer);
- layout->removeItem(buttonLayout);
-
- labelGroupDescriptionLabel = new QLabel("Choose one of the standard label group!", this);
- layout->addWidget(labelGroupDescriptionLabel);
-
- labelGroupTreeWidget = new QTreeWidget(this);
- labelGroupTreeWidget->header()->close();
-
-
- auto defaultLabelGroups = new mitk::TubeGraphDefaultLabelGroups();
-
- m_LabelGroupsLiver = defaultLabelGroups->GetLabelGroupForLiver();
- m_LabelGroupsLung = defaultLabelGroups->GetLabelGroupForLung();
-
- auto liverItem = new QTreeWidgetItem(labelGroupTreeWidget);
- liverItem->setText(0, tr("Liver"));
- QTreeWidgetItem* liverChildItem;
- for (unsigned int k = 0; k < m_LabelGroupsLiver.size(); k++)
- {
- liverChildItem = new QTreeWidgetItem(liverItem);
- liverChildItem->setText(0, QString::fromStdString(m_LabelGroupsLiver.at(k)->labelGroupName));
- }
- liverItem->setExpanded(true);
-
- auto lungItem = new QTreeWidgetItem(labelGroupTreeWidget);
- lungItem->setText(0, tr("Lung"));
- QTreeWidgetItem* lungChildItem;
- for (unsigned int k = 0; k < m_LabelGroupsLung.size(); k++)
- {
- lungChildItem = new QTreeWidgetItem(lungItem);
- lungChildItem->setText(0, QString::fromStdString(m_LabelGroupsLung.at(k)->labelGroupName));
- }
- lungItem->setExpanded(true);
-
-
- labelGroupTreeWidget->insertTopLevelItem(1,lungItem);
-
- delete defaultLabelGroups;
-
- layout->addWidget(labelGroupTreeWidget);
-
- layout->addLayout(buttonLayout);
- connect( okButton, SIGNAL(clicked()), this, SLOT(OnAddingStandardLabelGroup()) );
-
- okButton->setVisible(true);
-
-}
-
-void QmitkTubeGraphNewLabelGroupDialog::OnAddingLabel()
-{
- if (labelLineEdit->text().isEmpty())
- {
- labelLineEdit->setStyleSheet("border: 1px solid red");
- return;
- }
-
- labelListWidget->addItem(labelLineEdit->text());
- labelLineEdit->clear();
-}
-
-void QmitkTubeGraphNewLabelGroupDialog::OnAddingNewLabelGroup()
-{
- if (labelGroupLineEdit->text().isEmpty())
- {
- labelGroupLineEdit->setStyleSheet("border: 1px solid red");
- return;
- }
- m_NewLabelGroup = new LabelGroupType();
- m_NewLabelGroup->labelGroupName = (labelGroupLineEdit->text()).toStdString();
-
- for (int i =0; i < labelListWidget->count(); i++)
- {
- auto label = new LabelType();
- label->labelName = (labelListWidget->item(i)->text()).toStdString();
- mitk::Color color;
-
- if(label->labelName.compare("Undefined") == 0)
- {
- color[0] = 170; color[1] = 170; color[2] = 169;
- }
- else
- {
- color[0] = rand() % 255; color[1] = rand() % 255; color[2] = rand() % 255;
- }
- label->labelColor = color;
- label->isVisible = true;
- m_NewLabelGroup->labels.push_back(label);
- }
-
- this->accept();
-}
-
-void QmitkTubeGraphNewLabelGroupDialog::OnAddingStandardLabelGroup()
-{
- if (labelGroupTreeWidget->selectedItems().isEmpty())
- {
- labelGroupDescriptionLabel->setStyleSheet("border: 1px solid red");
- return;
- }
-
- if(labelGroupTreeWidget->selectedItems().at(0)->parent()->text(0) == "Lung")
- {
- for (unsigned int k = 0; k < m_LabelGroupsLung.size(); k++)
- {
- if(m_LabelGroupsLung.at(k)->labelGroupName == (labelGroupTreeWidget->selectedItems().at(0)->text(0)).toStdString())
- m_NewLabelGroup = m_LabelGroupsLung.at(k);
- }
- }
- else
- {
- for (unsigned int k = 0; k < m_LabelGroupsLiver.size(); k++)
- {
- if(m_LabelGroupsLiver.at(k)->labelGroupName == (labelGroupTreeWidget->selectedItems().at(0)->text(0)).toStdString())
- m_NewLabelGroup = m_LabelGroupsLiver.at(k);
- }
- }
- if (m_NewLabelGroup == nullptr)
- return;
-
-
- this->accept();
-
-}
-
-QmitkTubeGraphNewLabelGroupDialog::LabelGroupType* QmitkTubeGraphNewLabelGroupDialog::GetLabelGroup()
-{
- return m_NewLabelGroup;
-}
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewLabelGroupDialog.h b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewLabelGroupDialog.h
deleted file mode 100644
index 9f0a43f7df..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphNewLabelGroupDialog.h
+++ /dev/null
@@ -1,78 +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 QmitkTubeGraphNewLabelGroupDialog_h
-#define QmitkTubeGraphNewLabelGroupDialog_h
-
-#include <qdialog.h>
-#include <vector>
-#include "mitkTubeGraphProperty.h"
-
-class QSpacerItem;
-class QPushButton;
-class QVBoxLayout;
-class QHBoxLayout;
-class QLineEdit;
-class QLabel;
-class QListWidget;
-class QTreeWidget;
-
-class QmitkTubeGraphNewLabelGroupDialog : public QDialog
-{
- Q_OBJECT
-
- typedef mitk::TubeGraphProperty::LabelGroup LabelGroupType;
- typedef LabelGroupType::Label LabelType;
-
-public:
-
- QmitkTubeGraphNewLabelGroupDialog(QWidget* parent = nullptr);
- ~QmitkTubeGraphNewLabelGroupDialog() override;
-
- mitk::TubeGraphProperty::LabelGroup* GetLabelGroup();
-
- protected slots:
-
- void OnCreateNewLabelGroup();
- void OnAddStandardLabelGroup();
- void OnAddingNewLabelGroup();
- void OnAddingStandardLabelGroup();
- void OnAddingLabel();
-
-protected:
-
- QVBoxLayout* layout;
- QHBoxLayout* buttonLayout;
- QSpacerItem* spacer;
-
- QPushButton* newLabelGroupButton;
- QPushButton* standardLabelGroupButton;
-
- QPushButton* okButton;
- QPushButton* cancleButton;
-
- QLabel* labelGroupDescriptionLabel;
- QLineEdit* labelGroupLineEdit;
-
- QLabel* labelDescriptionLabel;
- QLineEdit* labelLineEdit;
- QPushButton* addLabelButton;
- QListWidget* labelListWidget;
-
- QTreeWidget* labelGroupTreeWidget;
-
- LabelGroupType* m_NewLabelGroup;
- std::vector<LabelGroupType*> m_LabelGroupsLiver;
- std::vector<LabelGroupType*> m_LabelGroupsLung;
-};
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphView.cpp b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphView.cpp
deleted file mode 100644
index 10ede762da..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphView.cpp
+++ /dev/null
@@ -1,621 +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 "QmitkTubeGraphView.h"
-
-#include "mitkDataStorage.h"
-#include "mitkRenderingManager.h"
-#include "mitkNodePredicateDataType.h"
-#include "usModuleRegistry.h"
-#include "QmitkTubeGraphLabelGroupWidget.h"
-#include "QmitkTubeGraphDeleteLabelGroupDialog.h"
-#include "QmitkTubeGraphNewLabelGroupDialog.h"
-#include "QmitkTubeGraphNewAnnotationDialog.h"
-
-const std::string QmitkTubeGraphView::VIEW_ID = "org.mitk.views.tubegraph";
-
-QmitkTubeGraphView::QmitkTubeGraphView()
- :QmitkAbstractView(),
- m_ActiveTubeGraph(),
- m_ActiveProperty(),
- m_ActivationMode(mitk::TubeGraphDataInteractor::None)
-{
-}
-
-QmitkTubeGraphView::~QmitkTubeGraphView()
-{
- //m_ActivationMode.mitk::TubeGraphDataInteractor::ActivationMode::~ActivationMode();
-
- //remove observer
- //if (m_ActiveInteractor.IsNotNull())
- //m_ActiveInteractor->RemoveObserver(m_InformationChangedObserverTag);
-
-}
-
-void QmitkTubeGraphView::SetFocus()
-{
- m_Controls.activeNodeGroupBox->setFocus();
-}
-
-void QmitkTubeGraphView::CreateQtPartControl(QWidget *parent)
-{
- // create GUI widgets
- m_Parent = parent;
- m_Controls.setupUi(parent);
- this->CreateConnections();
-}
-
-void QmitkTubeGraphView::NodeRemoved(const mitk::DataNode* /*node*/)
-{
-
-}
-
-void QmitkTubeGraphView::CreateConnections()
-{
- mitk::NodePredicateDataType::Pointer tubeGraphPred = mitk::NodePredicateDataType::New("TubeGraph");
- m_Controls.activeGraphComboBox->SetDataStorage(this->GetDataStorage());
- m_Controls.activeGraphComboBox->SetPredicate(tubeGraphPred);
-
- //activation mode
- connect( m_Controls.activeGraphComboBox, SIGNAL(currentIndexChanged (int)), this, SLOT(OnActiveGraphChanged(int)) );
- connect( m_Controls.noneModeRadioButton, SIGNAL(clicked()), this, SLOT(OnActivationModeChanged()));
- connect( m_Controls.singleModeRadioButton, SIGNAL(clicked()), this, SLOT(OnActivationModeChanged()));
- connect( m_Controls.multipleModeRadioButton, SIGNAL(clicked()), this, SLOT(OnActivationModeChanged()));
- connect( m_Controls.peripheryModeRadioButton, SIGNAL(clicked()), this, SLOT(OnActivationModeChanged()));
- connect( m_Controls.rootModeRadioButton, SIGNAL(clicked()), this, SLOT(OnActivationModeChanged()));
- connect( m_Controls.pointModeRadioButton, SIGNAL(clicked()), this, SLOT(OnActivationModeChanged()));
- connect( m_Controls.setRootButton, SIGNAL(toggled(bool)), this, SLOT(OnSetRootToggled(bool)));
-
- //deselect tubes
- connect( m_Controls.deselectAllButton, SIGNAL(clicked()), this, SLOT(OnDeselectAllTubes()));
-
- // tab switch
- connect( m_Controls.tubeGraphTabWidget, SIGNAL(currentChanged(int)), this, SLOT(OnTabSwitched(int)));
-
- //attributation tab
- connect( m_Controls.addLabelGroupButton, SIGNAL(clicked()), this, SLOT(OnAddingLabelGroup()));
- connect( m_Controls.removeLabelGroupButton, SIGNAL(clicked()), this, SLOT(OnRemoveLabelGroup()));
-
- //annotation tab
- connect( m_Controls.addAnnotationButton, SIGNAL(clicked()), this, SLOT(OnAddingAnnotation()));
- connect( m_Controls.deleteAnnotationButton, SIGNAL(clicked()), this, SLOT(OnRemoveAnnotation()));
-
- //edit tab
- connect( m_Controls.editSelectionNewButton, SIGNAL(clicked()), this, SLOT(OnAddTubeBetweenSelection()));
- connect( m_Controls.editSelectionSeperateButton, SIGNAL(clicked()), this, SLOT(OnSeperateSelection()));
- connect( m_Controls.editSelectionDeleteButton, SIGNAL(clicked()), this, SLOT(OnDeleteSelection()));
-
-
- this->SetTabsEnable(false);
-}
-
-void QmitkTubeGraphView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/, const QList<mitk::DataNode::Pointer>& nodes)
-{
- for (mitk::DataNode::Pointer node: nodes)
- {
- if( node.IsNotNull() && dynamic_cast< mitk::TubeGraph* >(node->GetData()) )
- {
- m_Controls.activeGraphComboBox->SetSelectedNode(node);
- m_ActiveTubeGraph = dynamic_cast< mitk::TubeGraph* >(node->GetData());
-
- m_ActiveProperty = dynamic_cast<mitk::TubeGraphProperty*>(m_ActiveTubeGraph->GetProperty( "Tube Graph.Visualization Information" ).GetPointer());
-
- this->UpdateActiveTubeGraphInInteractors();
- this->UpdateLabelGroups();
- this->UpdateAnnotation();
- }
- }
-}
-
-void QmitkTubeGraphView::OnActiveGraphChanged(int)
-{
- mitk::DataNode::Pointer selectedNode = m_Controls.activeGraphComboBox->GetSelectedNode();
-
- if(selectedNode.IsNotNull())
- {
- m_ActiveTubeGraph = dynamic_cast <mitk::TubeGraph* >( selectedNode->GetData() );
-
- m_ActiveProperty = dynamic_cast<mitk::TubeGraphProperty*>(m_ActiveTubeGraph->GetProperty("Tube Graph.Visualization Information" ).GetPointer());
- this->SetTabsEnable(true);
- this->UpdateGraphInformation();
- }
- else
- {
- m_ActiveTubeGraph = nullptr;
- m_ActiveProperty = nullptr;
- this->SetTabsEnable(false);
-
- }
- this->UpdateActiveTubeGraphInInteractors();
- this->UpdateLabelGroups();
- this->UpdateAnnotation();
-}
-
-void QmitkTubeGraphView::UpdateActiveTubeGraphInInteractors()
-{
- //
- // traverse all tube graphs and check, and add an interactor if needed...
- //
- mitk::NodePredicateDataType::Pointer tubeGraphPred = mitk::NodePredicateDataType::New("TubeGraph");
- mitk::DataStorage::SetOfObjects::ConstPointer tubeGraphs = this->GetDataStorage()->GetSubset(tubeGraphPred);
- for(mitk::DataStorage::SetOfObjects::ConstIterator it = tubeGraphs->Begin();
- it != tubeGraphs->End();
- ++it)
- {
- mitk::DataNode::Pointer node = it.Value().GetPointer();
- if ( node->GetDataInteractor().IsNull() )
- {
- mitk::TubeGraphDataInteractor::Pointer tubeGraphInteractor = mitk::TubeGraphDataInteractor::New();
- tubeGraphInteractor->LoadStateMachine("TubeGraphInteraction.xml", us::ModuleRegistry::GetModule("MitkTubeGraph"));
- tubeGraphInteractor->SetEventConfig("TubeGraphConfig.xml", us::ModuleRegistry::GetModule("MitkTubeGraph"));
- tubeGraphInteractor->SetActivationMode(m_ActivationMode);
- tubeGraphInteractor->SetDataNode(node);
- }
- }
-
- if (m_ActiveTubeGraph.IsNotNull())
- {
- //remove old observer
- // if (m_ActiveInteractor.IsNotNull())
- // m_ActiveInteractor->RemoveObserver(m_InformationChangedObserverTag);
-
- mitk::DataNode::Pointer node = m_Controls.activeGraphComboBox->GetSelectedNode();
- //set active interactor to interactor from selected node
- m_ActiveInteractor = dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer());
-
- m_ActiveInteractor->SetActivationMode(m_ActivationMode);
-
- //add observer to activeInteractor
- typedef itk::SimpleMemberCommand< QmitkTubeGraphView > SimpleCommandType;
- SimpleCommandType::Pointer changeInformationCommand = SimpleCommandType::New();
- changeInformationCommand->SetCallbackFunction(this, &QmitkTubeGraphView::SelectionInformationChanged);
- //m_InformationChangedObserverTag = m_ActiveInteractor->AddObserver(mitk::SelectionChangedTubeGraphEvent(), changeInformationCommand);
-
- ////Add selected node to all tube graph interactors as current node
- //mitk::TubeGraphDataInteractor::SetCurrentSelectedDataNode( node );
-
- if (m_ActiveProperty.IsNull())
- {
- mitk::TubeGraphProperty::Pointer newProperty = mitk::TubeGraphProperty::New();
- m_ActiveTubeGraph->SetProperty("Tube Graph.Visualization Information",newProperty);
- m_ActiveProperty = newProperty;
- }
- }
-}
-
-void QmitkTubeGraphView::UpdateLabelGroups()
-{
- for(int i = m_Controls.toolBox->count()- 1; i >= 0 ; i--)
- m_Controls.toolBox->removeItem(i);
-
- if (m_ActiveProperty.IsNotNull())
- {
- if(m_ActiveProperty->GetNumberOfLabelGroups()!= 0)
- {
- std::vector<LabelGroupType*> labelGroups = m_ActiveProperty->GetLabelGroups();
-
- for (unsigned int k = 0; k < labelGroups.size(); k++)
- this->CreateLabelGroupWidget(labelGroups.at(k));
- }
- }
-}
-
-void QmitkTubeGraphView::OnActivationModeChanged()
-{
- if (m_Controls.noneModeRadioButton->isChecked())
- m_ActivationMode = mitk::TubeGraphDataInteractor::None;
- else if (m_Controls.singleModeRadioButton->isChecked())
- m_ActivationMode = mitk::TubeGraphDataInteractor::Single;
- else if (m_Controls.multipleModeRadioButton->isChecked())
- m_ActivationMode = mitk::TubeGraphDataInteractor::Multiple;
- else if (m_Controls.rootModeRadioButton->isChecked())
- m_ActivationMode = mitk::TubeGraphDataInteractor::ToRoot;
- else if (m_Controls.peripheryModeRadioButton->isChecked())
- m_ActivationMode = mitk::TubeGraphDataInteractor::ToPeriphery;
- else if (m_Controls.pointModeRadioButton->isChecked())
- m_ActivationMode = mitk::TubeGraphDataInteractor::Points;
- else //normally not possible, but.... set to single mode
- m_ActivationMode = mitk::TubeGraphDataInteractor::Single;
-
- mitk::DataNode::Pointer node = m_Controls.activeGraphComboBox->GetSelectedNode();
- if(node.IsNotNull() && m_ActiveProperty.IsNotNull())
- {
- dynamic_cast< mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer())->SetActivationMode(m_ActivationMode);
-
- //m_ActiveTubeGraph->Modified();
- // render new selection
- mitk::RenderingManager::GetInstance()->RequestUpdateAll();
- }
-}
-
-mitk::TubeGraphDataInteractor::ActivationMode QmitkTubeGraphView::GetActivationMode ()
-{
- return m_ActivationMode;
-}
-
-void QmitkTubeGraphView::OnSetRootToggled(bool enable)
-{
- this->SetTabsEnable(!enable);
- if (m_ActiveTubeGraph.IsNotNull())
- {
- mitk::DataNode::Pointer node = m_Controls.activeGraphComboBox->GetSelectedNode();
- if(node.IsNotNull())
- {
- if (enable)
- dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer())->SetActionMode(mitk::TubeGraphDataInteractor::RootMode);
- else
- dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer())->SetActionMode(mitk::TubeGraphDataInteractor::AttributationMode);
- }
- }
-}
-
-void QmitkTubeGraphView::OnDeselectAllTubes()
-{
- mitk::DataNode::Pointer node = m_Controls.activeGraphComboBox->GetSelectedNode();
- if(node.IsNotNull())
- dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer())->ResetPickedTubes();
-
- if (m_ActiveProperty.IsNull())
- {
- MITK_ERROR << "Oho!No Property..mhhhh";
- return;
- }
- m_ActiveProperty->DeactivateAllTubes();
- m_ActiveTubeGraph->Modified();
- // render new selection
- mitk::RenderingManager::GetInstance()->RequestUpdateAll();
-}
-
-void QmitkTubeGraphView::OnTabSwitched(int tabIndex)
-{
- mitk::DataNode::Pointer node = m_Controls.activeGraphComboBox->GetSelectedNode();
- if(node.IsNotNull())
- {
- if (dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer()) == nullptr)
- {
- this->UpdateActiveTubeGraphInInteractors();
- /* if (dynamic_cast<mitk::TubeGraphDataInteractor::Pointer>(node->GetDataInteractor().GetPointer()).IsNull());*/
- return;
- }
-
- switch(tabIndex)
- {
- case 0:
- dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer())->SetActionMode(mitk::TubeGraphDataInteractor::AttributationMode);
- m_Controls.noneModeRadioButton->setEnabled(true);
- m_Controls.singleModeRadioButton->setEnabled(true);
- m_Controls.multipleModeRadioButton->setEnabled(true);
- m_Controls.peripheryModeRadioButton->setEnabled(true);
- m_Controls.rootModeRadioButton->setEnabled(true);
- m_Controls.pointModeRadioButton->setEnabled(true);
- break;
- case 1:
- dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer())->SetActionMode(mitk::TubeGraphDataInteractor::AnnotationMode);
- m_ActiveProperty->DeactivateAllTubes();
- m_Controls.noneModeRadioButton->setEnabled(true);
- m_Controls.singleModeRadioButton->setEnabled(true);
- m_Controls.multipleModeRadioButton->setEnabled(false);
- m_Controls.peripheryModeRadioButton->setEnabled(false);
- m_Controls.rootModeRadioButton->setEnabled(false);
- m_Controls.pointModeRadioButton->setEnabled(false);
- break;
- case 2:
- dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer())->SetActionMode(mitk::TubeGraphDataInteractor::EditMode);
- m_Controls.noneModeRadioButton->setEnabled(true);
- m_Controls.singleModeRadioButton->setEnabled(true);
- m_Controls.multipleModeRadioButton->setEnabled(true);
- m_Controls.peripheryModeRadioButton->setEnabled(true);
- m_Controls.rootModeRadioButton->setEnabled(true);
- m_Controls.pointModeRadioButton->setEnabled(true);
- break;
- case 3:
- dynamic_cast<mitk::TubeGraphDataInteractor*>(node->GetDataInteractor().GetPointer())->SetActionMode(mitk::TubeGraphDataInteractor::InformationMode);
- m_Controls.noneModeRadioButton->setEnabled(false);
- m_Controls.singleModeRadioButton->setEnabled(false);
- m_Controls.multipleModeRadioButton->setEnabled(false);
- m_Controls.peripheryModeRadioButton->setEnabled(false);
- m_Controls.rootModeRadioButton->setEnabled(false);
- m_Controls.pointModeRadioButton->setEnabled(false);
- this->UpdateGraphInformation();
- break;
- default:
- break;
- }
- }
-}
-
-void QmitkTubeGraphView::OnAddingLabelGroup()
-{
- QmitkTubeGraphNewLabelGroupDialog* dialog = new QmitkTubeGraphNewLabelGroupDialog( m_Parent );
-
- int dialogReturnValue = dialog->exec();
-
- LabelGroupType* newLabelGroup = dialog->GetLabelGroup();
- delete dialog;
-
- if ( dialogReturnValue != QDialog::Rejected ) // user doesn't clicked cancel or pressed Esc or something similar
- {
- m_ActiveProperty->AddLabelGroup(newLabelGroup, m_ActiveProperty->GetNumberOfLabelGroups());
- this->UpdateLabelGroups();
- }
-}
-
-void QmitkTubeGraphView::CreateLabelGroupWidget(LabelGroupType* labelGroup)
-{
- QmitkTubeGraphLabelGroupWidget* labelGroupWidget = new QmitkTubeGraphLabelGroupWidget(m_Controls.toolBox, (labelGroup->labelGroupName).c_str());
-
- for (std::vector<LabelType*>::iterator it = labelGroup->labels.begin(); it != labelGroup->labels.end(); it++)
- {
- labelGroupWidget->AddLabel(QString::fromStdString((*it)->labelName), (*it)->labelColor);
- }
-
- m_Controls.toolBox->addItem(labelGroupWidget, QString::fromStdString(labelGroup->labelGroupName));
-
- connect(labelGroupWidget, SIGNAL(SignalLabelVisibilityInGroupToggled(bool, QString, QString)), this, SLOT(OnLabelVisibilityChanged(bool, QString, QString)));
- connect(labelGroupWidget, SIGNAL(SignalLabelButtonInGroupClicked(QString, QString)), this, SLOT(OnLabelChanged(QString, QString)));
- connect(labelGroupWidget, SIGNAL(SignalLabelColorInGroupChanged(mitk::Color, QString, QString)), this, SLOT(OnLabelColorChanged(mitk::Color, QString, QString)));
-}
-
-void QmitkTubeGraphView::OnRemoveLabelGroup()
-{
- QStringList allLabelGroups;
- std::vector<LabelGroupType*> labelGroups = m_ActiveProperty->GetLabelGroups();
- for (unsigned int i = 0; i < labelGroups.size(); i++)
- allLabelGroups.push_back(QString::fromStdString(labelGroups.at(i)->labelGroupName));
-
- QmitkTubeGraphDeleteLabelGroupDialog* dialog = new QmitkTubeGraphDeleteLabelGroupDialog( m_Parent );
- dialog->SetLabelGroups(allLabelGroups);
-
- int dialogReturnValue = dialog->exec();
-
- QList<QString> toDeleteItemsList = dialog->GetSelectedLabelGroups();
-
- delete dialog;
-
- if ( dialogReturnValue != QDialog::Rejected ) // user clicked cancel or pressed Esc or something similar
- {
- for (QList<QString>::iterator it = toDeleteItemsList.begin(); it != toDeleteItemsList.end(); it++ )
- {
- std::string labelGroupName = (*it).toStdString();
- LabelGroupType* labelGroup = m_ActiveProperty->GetLabelGroupByName(labelGroupName);
- m_ActiveProperty->RemoveLabelGroup(labelGroup);
- }
- this->UpdateLabelGroups();
- }
-}
-
-void QmitkTubeGraphView::OnAddingAnnotation()
-{
- std::vector <mitk::TubeGraph::TubeDescriptorType> activeTubes = m_ActiveProperty->GetActiveTubes();
- if (activeTubes.size()!= 0)
- {
- QmitkTubeGraphNewAnnotationDialog* dialog = new QmitkTubeGraphNewAnnotationDialog( m_Parent );
-
- int dialogReturnValue = dialog->exec();
-
- QString newAnnotationName = dialog->GetAnnotationName();
- QString newDescription = dialog->GetAnnotationDescription();
- QString tubeString = QString("[%1,%2]").arg(activeTubes.begin()->first).arg(activeTubes.begin()->second);
-
- delete dialog;
-
- if ( dialogReturnValue != QDialog::Rejected ) // user doesn't clicked cancel or pressed Esc or something similar
- {
-
- mitk::TubeGraphProperty::Annotation* annotation = new mitk::TubeGraphProperty::Annotation();
- annotation->name = newAnnotationName.toStdString();
- annotation->description = newDescription.toStdString();
- annotation->tube = (*activeTubes.begin());
-
- m_ActiveProperty->AddAnnotation(annotation);
- this->UpdateAnnotation();
- }
- }
- else
- {
- MITK_INFO<< "No Tube select for annotation";
- }
-}
-
-void QmitkTubeGraphView::UpdateAnnotation()
-{
- m_Controls.annotationsTableWidget->clear();
- m_Controls.annotationsTableWidget->setRowCount(0);
- if (m_ActiveProperty.IsNotNull())
- {
- std::vector<mitk::TubeGraphProperty::Annotation*> annotations = m_ActiveProperty->GetAnnotations();
-
- if (annotations.size() != 0)
- {
- for (unsigned int k = 0; k < annotations.size(); k++)
- {
- m_Controls.annotationsTableWidget->setRowCount(k+1); // add one row
-
- QTableWidgetItem* annotationNameItem = new QTableWidgetItem(QString::fromStdString(annotations[k]->name));
- QTableWidgetItem* annotationDescriptionItem = new QTableWidgetItem(QString::fromStdString(annotations[k]->description));
- QString tubeString = QString("[%1,%2]").arg(annotations[k]->tube.first).arg(annotations[k]->tube.second);
- QTableWidgetItem* annotationTubeItem = new QTableWidgetItem(tubeString);
-
- m_Controls.annotationsTableWidget->setItem(k, 0, annotationNameItem);
- m_Controls.annotationsTableWidget->setItem(k, 1, annotationDescriptionItem);
- m_Controls.annotationsTableWidget->setItem(k, 2, annotationTubeItem);
- }
- }
- }
-}
-
-
-void QmitkTubeGraphView::OnRemoveAnnotation()
-{
- //m_Controls.annotationsTableWidget->removeRow(m_Controls.annotationsTableWidget->currentRow());
- int row = m_Controls.annotationsTableWidget->currentRow();
-
- if (row >= 0)
- {
- std::string name = m_Controls.annotationsTableWidget->item(row, 0)->text().toStdString();
-
- mitk::TubeGraphProperty::Annotation* annotation = m_ActiveProperty->GetAnnotationByName(name);
- m_ActiveProperty->RemoveAnnotation(annotation);
- this->UpdateAnnotation();
- }
-
-}
-
-
-void QmitkTubeGraphView::OnAddTubeBetweenSelection()
-{
-}
-
-void QmitkTubeGraphView::OnSeperateSelection()
-{
- std::vector <mitk::TubeGraph::TubeDescriptorType> activeTubes = m_ActiveProperty->GetActiveTubes();
- if (activeTubes.size()!= 0)
- {
- mitk::TubeGraph::Pointer subGraph = m_ActiveTubeGraph->CreateSubGraph(activeTubes);
-
- mitk::DataNode::Pointer originGraphNode = m_Controls.activeGraphComboBox->GetSelectedNode();
-
- mitk::DataNode::Pointer newGraphNode = mitk::DataNode::New();
- newGraphNode->SetData(subGraph);
- newGraphNode->SetName(originGraphNode->GetName() + "-SubGraph");
-
- mitk::TubeGraphDataInteractor::Pointer tubeGraphInteractor = mitk::TubeGraphDataInteractor::New();
- tubeGraphInteractor->LoadStateMachine("TubeGraphInteraction.xml", us::ModuleRegistry::GetModule("TubeGraph"));
- tubeGraphInteractor->SetEventConfig("TubeGraphConfig.xml", us::ModuleRegistry::GetModule("TubeGraph"));
- tubeGraphInteractor->SetDataNode(newGraphNode);
-
- mitk::TubeGraphProperty::Pointer newProperty = mitk::TubeGraphProperty::New();
- subGraph->SetProperty("Tube Graph.Visualization Information",newProperty);
-
- this->GetDataStorage()->Add(newGraphNode, originGraphNode);
- }
-}
-
-void QmitkTubeGraphView::OnDeleteSelection()
-{ //TODO Action for Interactor + undo/redo
-
- std::vector <mitk::TubeGraph::TubeDescriptorType> activeTubes = m_ActiveProperty->GetActiveTubes();
- m_ActiveTubeGraph->RemoveSubGraph(m_ActiveProperty->GetActiveTubes());
-}
-
-void QmitkTubeGraphView::OnLabelVisibilityChanged(bool isVisible, QString labelName, QString labelGroupName)
-{
- if (m_ActiveProperty.IsNull())
- {
- MITK_ERROR << "Oho!No Property..mhhhh";
- return;
- }
- LabelGroupType* labelGroup = m_ActiveProperty->GetLabelGroupByName(labelGroupName.toStdString());
- LabelType* label = m_ActiveProperty->GetLabelByName(labelGroup, labelName.toStdString());
-
- if(labelGroup == nullptr || label == nullptr )
- {
- MITK_ERROR << "This label group or label doesn't exist!";
- return;
- }
-
- m_ActiveProperty->SetLabelVisibility(label, isVisible);
- m_ActiveTubeGraph->Modified();
- mitk::RenderingManager::GetInstance()->RequestUpdateAll();
-}
-
-void QmitkTubeGraphView::OnLabelChanged(QString labelName, QString labelGroupName)
-{
- if (m_ActiveProperty.IsNull())
- {
- MITK_ERROR << "Oho!No Property..mhhhh";
- return;
- }
- LabelGroupType* labelGroup = m_ActiveProperty->GetLabelGroupByName(labelGroupName.toStdString());
- LabelType* label = m_ActiveProperty->GetLabelByName(labelGroup, labelName.toStdString());
- if(labelGroup == nullptr || label == nullptr )
- {
- MITK_ERROR << "This label group or label doesn't exist!";
- return;
- }
-
- m_ActiveProperty->SetLabelForActivatedTubes(labelGroup, label);
- m_ActiveTubeGraph->Modified();
- mitk::RenderingManager::GetInstance()->RequestUpdateAll();
-}
-
-void QmitkTubeGraphView::OnLabelColorChanged (mitk::Color color, QString labelName, QString labelGroupName)
-{
- if (m_ActiveProperty.IsNull())
- {
- MITK_ERROR << "Oho!No Property..mhhhh";
- return;
- }
-
- LabelGroupType* labelGroup = m_ActiveProperty->GetLabelGroupByName(labelGroupName.toStdString());
- LabelType* label = m_ActiveProperty->GetLabelByName(labelGroup, labelName.toStdString());
-
- if(labelGroup == nullptr || label == nullptr )
- {
- MITK_ERROR << "This label group or label doesn't exist!";
- return;
- }
-
- m_ActiveProperty->SetLabelColor(label, color);
- m_ActiveTubeGraph->Modified();
- mitk::RenderingManager::GetInstance()->RequestUpdateAll();
-}
-
-
-void QmitkTubeGraphView::SetTabsEnable(bool enable)
-{
- m_Controls.tubeGraphTabWidget->setTabEnabled(0, enable); //attributationTab
- m_Controls.tubeGraphTabWidget->setTabEnabled(1, enable);//annotationTab
- m_Controls.tubeGraphTabWidget->setTabEnabled(2, enable);//editTab
- m_Controls.tubeGraphTabWidget->setTabEnabled(3, enable);//informationTab
-}
-
-void QmitkTubeGraphView::UpdateGraphInformation()
-{
- mitk::TubeGraph::TubeDescriptorType root = m_ActiveTubeGraph->GetRootTube();
- mitk::BaseGeometry::Pointer geometry = m_ActiveTubeGraph->GetGeometry();
- mitk::Point3D origin = geometry->GetOrigin();
- mitk::Vector3D spacing = geometry->GetSpacing();
- QString information;
- information.append(QString("Number of Vertices: %1\n").arg(m_ActiveTubeGraph->GetNumberOfVertices()));
- information.append(QString("Number of Edges: %1\n").arg(m_ActiveTubeGraph->GetNumberOfEdges()));
- information.append(QString("Root Id: [%1,%2]\n\n").arg(root.first).arg(root.second));
- information.append(QString("Origin: [%1,%2,%3]\n").arg(origin[0]).arg(origin[1]).arg(origin[2]));
- information.append(QString("Spacing: [%1,%2,%3]").arg(spacing[0]).arg(spacing[1]).arg(spacing[2]));
-
- m_Controls.informationLabel->setText(information);
-}
-
-void QmitkTubeGraphView::SelectionInformationChanged()
-{
- std::vector <mitk::TubeGraph::TubeDescriptorType> activeTubes = m_ActiveProperty->GetActiveTubes();
- if(activeTubes.size()==0)
- m_Controls.shortInformationLabel->setText("");
- else
- {
- mitk::TubeGraph::TubeDescriptorType root = m_ActiveTubeGraph->GetRootTube();
- /*double averageDiameter;
- for (int i = 0; i < activeTubes.size(); i++)
- {
- mitk::TubeGraph::EdgeDescriptorType edgeDescriptor = m_ActiveTubeGraph->GetEdgeDescriptorByVerices(activeTubes.at(i).first, activeTubes.at(i).second);
- mitk::TubeGraphEdge edge = m_ActiveTubeGraph->GetEdge(edgeDescriptor);
- averageDiameter += edge.GetEdgeAverageDiameter(m_ActiveTubeGraph->GetVertex(activeTubes.at(i).first), m_ActiveTubeGraph->GetVertex(activeTubes.at(i).second));
- }
- averageDiameter = averageDiameter/activeTubes.size();*/
-
- QString information;
- information.append(QString("Number of Selected Tubes: %1\n").arg(activeTubes.size()));
- //information.append(QString("Average diameter\n").arg(averageDiameter));
- information.append(QString("Root Id: [%1,%2]").arg(root.first).arg(root.second));
- m_Controls.shortInformationLabel->setText(information);
- }
-}
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphView.h b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphView.h
deleted file mode 100644
index 4dcd6a76c0..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphView.h
+++ /dev/null
@@ -1,124 +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 QmitkTubeGraphView_h
-#define QmitkTubeGraphView_h
-
-#include "ui_QmitkTubeGraphViewControls.h"
-
-#include <QmitkAbstractView.h>
-
-#include "mitkColorProperty.h"
-#include "mitkTubeGraph.h"
-#include "mitkTubeGraphProperty.h"
-#include "mitkTubeGraphDataInteractor.h"
-
-#include <QCheckBox>
-#include <QSignalMapper>
-
-
-/*!
-*
-* \brief QmitkTubeGraphConverterView
-*
-*/
-class QmitkTubeGraphView: public QmitkAbstractView
-{
- // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject)
- Q_OBJECT
-
- typedef mitk::TubeGraphProperty::LabelGroup LabelGroupType;
- typedef LabelGroupType::Label LabelType;
-
-public:
-
- static const std::string VIEW_ID;
- /**
- * @brief Constructor.
- **/
- QmitkTubeGraphView();
-
- /**
- * @brief Destructor.
- */
- ~QmitkTubeGraphView() override;
-
- void CreateQtPartControl(QWidget *parent) override;
-
- /** \brief Method to create the connections for the component. This Method is obligatory even if no connections is needed*/
- virtual void CreateConnections();
-
- protected slots:
- //active tube graph
- void OnActiveGraphChanged(int);
-
- //activation mode
- void OnActivationModeChanged();
- void OnDeselectAllTubes();
- void OnSetRootToggled(bool);
-
- void OnTabSwitched(int);
-
- //attributation tab
- void OnAddingLabelGroup();
- void OnRemoveLabelGroup();
-
- //annotation tab
- void OnAddingAnnotation();
- void OnRemoveAnnotation();
-
- //edit tab
- void OnAddTubeBetweenSelection();
- void OnSeperateSelection();
- void OnDeleteSelection();
-
- //label group
- void OnLabelVisibilityChanged(bool, QString labelName, QString labelGroupName);
- void OnLabelChanged(QString labelName, QString labelGroupName);
- void OnLabelColorChanged(mitk::Color color, QString labelName, QString labelGroupName);
-
-protected:
-
- mitk::TubeGraphDataInteractor::ActivationMode GetActivationMode();
- void SetFocus() override;
- void NodeRemoved(const mitk::DataNode*) override;
- /// \brief called by QmitkAbstractView when DataManager's selection has changed
- void OnSelectionChanged(berry::IWorkbenchPart::Pointer source,const QList<mitk::DataNode::Pointer>& nodes) override;
-
- Ui::QmitkTubeGraphViewControls m_Controls;
- // the Qt parent of our GUI (NOT of this object)
- QWidget* m_Parent;
-
-private:
- void UpdateActiveTubeGraphInInteractors();
- void CreateLabelGroupWidget(LabelGroupType* labelGroup);
- void InitializeLabelGroups();
- void SetTabsEnable(bool enable);
- void UpdateLabelGroups();
- void UpdateAnnotation();
- void SelectionInformationChanged();
- void UpdateGraphInformation();
-
- mitk::TubeGraph::Pointer m_ActiveTubeGraph;
- mitk::TubeGraphProperty::Pointer m_ActiveProperty;
- mitk::TubeGraphDataInteractor::Pointer m_ActiveInteractor;
- mitk::TubeGraphDataInteractor::ActivationMode m_ActivationMode;
-
- /* std::vector<QString> m_LabelGroupName;
- std::vector<QString> m_LabelName;*/
-
- unsigned int m_InformationChangedObserverTag;
-
-};
-
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphViewControls.ui b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphViewControls.ui
deleted file mode 100644
index c1b48b36a4..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/QmitkTubeGraphViewControls.ui
+++ /dev/null
@@ -1,559 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkTubeGraphViewControls</class>
- <widget class="QWidget" name="QmitkTubeGraphViewControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>385</width>
- <height>739</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string/>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_5">
- <item>
- <widget class="QGroupBox" name="activeNodeGroupBox">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="title">
- <string>Active Tube Graph</string>
- </property>
- <property name="flat">
- <bool>false</bool>
- </property>
- <property name="checkable">
- <bool>false</bool>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_3">
- <property name="sizeConstraint">
- <enum>QLayout::SetDefaultConstraint</enum>
- </property>
- <item>
- <widget class="QmitkDataStorageComboBox" name="activeGraphComboBox">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="activationGroupBox">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="title">
- <string>Activation Mode</string>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout_3">
- <item>
- <layout class="QVBoxLayout" name="verticalLayout_4">
- <item>
- <widget class="QGroupBox" name="activationModeGroupBox">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="font">
- <font>
- <weight>50</weight>
- <bold>false</bold>
- </font>
- </property>
- <property name="title">
- <string/>
- </property>
- <property name="checkable">
- <bool>false</bool>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QRadioButton" name="noneModeRadioButton">
- <property name="text">
- <string>None</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- <attribute name="buttonGroup">
- <string>buttonGroup</string>
- </attribute>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="singleModeRadioButton">
- <property name="text">
- <string>Single</string>
- </property>
- <attribute name="buttonGroup">
- <string>buttonGroup</string>
- </attribute>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="multipleModeRadioButton">
- <property name="text">
- <string>Multiple</string>
- </property>
- <attribute name="buttonGroup">
- <string>buttonGroup</string>
- </attribute>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="peripheryModeRadioButton">
- <property name="text">
- <string>Periphery</string>
- </property>
- <attribute name="buttonGroup">
- <string>buttonGroup</string>
- </attribute>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="rootModeRadioButton">
- <property name="text">
- <string>Path to Root</string>
- </property>
- <attribute name="buttonGroup">
- <string>buttonGroup</string>
- </attribute>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="pointModeRadioButton">
- <property name="text">
- <string>Point to Point</string>
- </property>
- <attribute name="buttonGroup">
- <string>buttonGroup</string>
- </attribute>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QPushButton" name="setRootButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Minimum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="toolTip">
- <string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
-&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
-p, li { white-space: pre-wrap; }
-&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
-&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:8pt;&quot;&gt;Enable to select a new root with &lt;/span&gt;&lt;span style=&quot; font-size:8pt; font-weight:600;&quot;&gt;left mouse click&lt;/span&gt;&lt;span style=&quot; font-size:8pt;&quot;&gt; in the image.&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
- </property>
- <property name="text">
- <string/>
- </property>
- <property name="icon">
- <iconset>
- <normaloff>:/QmitkExt/icon_seedpoint.png</normaloff>:/QmitkExt/icon_seedpoint.png</iconset>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="flat">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="deselectAllButton">
- <property name="font">
- <font>
- <weight>50</weight>
- <bold>false</bold>
- </font>
- </property>
- <property name="text">
- <string>Deselect All</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QGroupBox" name="shortInformationGroupBox">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="font">
- <font>
- <weight>50</weight>
- <italic>true</italic>
- <bold>false</bold>
- </font>
- </property>
- <property name="title">
- <string>Short Information about Selection</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_9">
- <item>
- <widget class="QLabel" name="shortInformationLabel">
- <property name="font">
- <font>
- <italic>false</italic>
- </font>
- </property>
- <property name="text">
- <string/>
- </property>
- <property name="alignment">
- <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QTabWidget" name="tubeGraphTabWidget">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="contextMenuPolicy">
- <enum>Qt::DefaultContextMenu</enum>
- </property>
- <property name="autoFillBackground">
- <bool>true</bool>
- </property>
- <property name="locale">
- <locale language="English" country="UnitedStates"/>
- </property>
- <property name="tabShape">
- <enum>QTabWidget::Rounded</enum>
- </property>
- <property name="currentIndex">
- <number>3</number>
- </property>
- <widget class="QWidget" name="attributationTab">
- <attribute name="title">
- <string>Attributation</string>
- </attribute>
- <layout class="QVBoxLayout" name="verticalLayout_2">
- <item>
- <widget class="QToolBox" name="toolBox">
- <widget class="QWidget" name="page">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>343</width>
- <height>282</height>
- </rect>
- </property>
- <attribute name="label">
- <string/>
- </attribute>
- </widget>
- <widget class="QWidget" name="page_2">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>98</width>
- <height>28</height>
- </rect>
- </property>
- <attribute name="label">
- <string/>
- </attribute>
- </widget>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QPushButton" name="addLabelGroupButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>+</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="removeLabelGroupButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>-</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="annotationTab">
- <attribute name="title">
- <string>Annotation</string>
- </attribute>
- <layout class="QVBoxLayout" name="verticalLayout_6">
- <item>
- <widget class="QTableWidget" name="annotationsTableWidget">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="font">
- <font>
- <family>MS Shell Dlg 2</family>
- <kerning>true</kerning>
- </font>
- </property>
- <property name="frameShape">
- <enum>QFrame::WinPanel</enum>
- </property>
- <property name="dragEnabled">
- <bool>false</bool>
- </property>
- <property name="selectionBehavior">
- <enum>QAbstractItemView::SelectRows</enum>
- </property>
- <property name="showGrid">
- <bool>true</bool>
- </property>
- <column>
- <property name="text">
- <string>Name</string>
- </property>
- </column>
- <column>
- <property name="text">
- <string>Description</string>
- </property>
- </column>
- <column>
- <property name="text">
- <string>Tube</string>
- </property>
- </column>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_4">
- <item>
- <widget class="QPushButton" name="addAnnotationButton">
- <property name="text">
- <string>+</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="deleteAnnotationButton">
- <property name="text">
- <string>--</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="editTab">
- <attribute name="title">
- <string>Edit</string>
- </attribute>
- <layout class="QVBoxLayout" name="verticalLayout_7">
- <item>
- <widget class="QLabel" name="editDescriptionLabel">
- <property name="text">
- <string>Please select the region you want to interact with!</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_2">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Fixed</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="editSelectionNewButton">
- <property name="text">
- <string>Connect</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_5">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Fixed</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>40</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="editSelectionSeperateButton">
- <property name="text">
- <string>Separate</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="editSelectionDeleteButton">
- <property name="text">
- <string>Delete</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_3">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>40</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="informationTab">
- <attribute name="title">
- <string>Information</string>
- </attribute>
- <layout class="QVBoxLayout" name="verticalLayout_8">
- <item>
- <widget class="QLabel" name="informationLabel">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_4">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>345</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Preferred</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>QmitkDataStorageComboBox</class>
- <extends>QComboBox</extends>
- <header location="global">QmitkDataStorageComboBox.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
- <slots>
- <slot>OnActivationModeChanged()</slot>
- </slots>
- <buttongroups>
- <buttongroup name="buttonGroup"/>
- </buttongroups>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkPluginActivator.cpp
deleted file mode 100644
index 7ab0b75d0e..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkPluginActivator.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 "mitkPluginActivator.h"
-#include "src/internal/QmitkTubeGraphView.h"
-
-namespace mitk
-{
-
- ctkPluginContext* PluginActivator::m_context = nullptr;
-
- void PluginActivator::start(ctkPluginContext* context)
- {
- BERRY_REGISTER_EXTENSION_CLASS(QmitkTubeGraphView, context)
- this->m_context = context;
- }
-
- void PluginActivator::stop(ctkPluginContext*)
- {
- this->m_context = nullptr;
- }
-
- ctkPluginContext* PluginActivator::getContext()
- {
- return m_context;
- }
-
-} //namespace
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkPluginActivator.h
deleted file mode 100644
index 3fde9d75a1..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkPluginActivator.h
+++ /dev/null
@@ -1,42 +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
-
-// Parent classes
-#include <QObject>
-#include <ctkPluginActivator.h>
-
-namespace mitk {
-
- class PluginActivator :
- public QObject, public ctkPluginActivator
- {
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_tubegraph")
- Q_INTERFACES(ctkPluginActivator)
-
- public:
-
- void start(ctkPluginContext* context) override;
- void stop(ctkPluginContext* context) override;
-
- static ctkPluginContext* getContext();
-
- private:
-
- static ctkPluginContext* m_context;
- }; // PluginActivator
-
-}
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkTubeGraphDefaultLabelGroups.cpp b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkTubeGraphDefaultLabelGroups.cpp
deleted file mode 100644
index dcf083f9ec..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkTubeGraphDefaultLabelGroups.cpp
+++ /dev/null
@@ -1,181 +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 "mitkTubeGraphDefaultLabelGroups.h"
-
-#include "mitkColorProperty.h"
-
-mitk::TubeGraphDefaultLabelGroups::TubeGraphDefaultLabelGroups()
-{
- mitk::Color color;
-
- auto newLabelGroup = new LabelGroupType();
- newLabelGroup->labelGroupName = "Vessel Type";
-
- auto label = new LabelType();
- label->labelName = "Undefined";
- color[0] = 170; color[1] = 170; color[2] = 169;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "Artery";
- color[0] = 255; color[1] = 0; color[2] = 0;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "Hepatic Vein";
- color[0] = 255; color[1] = 0; color[2] = 0;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "Portal Vein";
- color[0] = 0; color[1] = 0; color[2] = 125;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "Bile Duct";
- color[0] = 0; color[1] = 255; color[2] = 0;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- m_labelGroupsLiver.push_back(newLabelGroup);
- /////////////////////////////////////////////////////////////////
- newLabelGroup = new LabelGroupType();
- newLabelGroup->labelGroupName = "Resection Status";
-
- label = new LabelType();
- label->labelName = "Undefined";
- color[0] = 170; color[1] = 170; color[2] = 169;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "to be resected";
- color[0] = 255; color[1] = 0; color[2] = 0;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "not to be resected";
- color[0] = 0; color[1] = 255; color[2] = 0;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "area at risk";
- color[0] = 255; color[1] = 255; color[2] = 0;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- m_labelGroupsLiver.push_back(newLabelGroup);
- ///////////////////////////////////////////////////////////
- newLabelGroup = new LabelGroupType();
- newLabelGroup->labelGroupName = "Segments (Portal)";
-
- label = new LabelType();
- label->labelName = "Undefined";
- color[0] = 170; color[1] = 170; color[2] = 169;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "I";
- color[0] = 95; color[1] = 158; color[2] = 160;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "II";
- color[0] = 122; color[1] = 197; color[2] = 205;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "III";
- color[0] = 0; color[1] = 154; color[2] =205;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "IVa";
- color[0] = 154; color[1] = 192; color[2] = 205;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "IVb";
- color[0] = 104; color[1] = 131; color[2] = 139;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "V";
- color[0] = 118; color[1] = 238; color[2] = 198;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "VI";
- color[0] = 102; color[1] = 205; color[2] = 170;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "VII";
- color[0] = 69; color[1] = 139; color[2] = 116;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- label = new LabelType();
- label->labelName = "VIII";
- color[0] = 46; color[1] = 139; color[2] = 87;
- label->labelColor = color;
- label->isVisible = true;
- newLabelGroup->labels.push_back(label);
-
- m_labelGroupsLiver.push_back(newLabelGroup);
-}
-mitk::TubeGraphDefaultLabelGroups::~TubeGraphDefaultLabelGroups()
-{
-}
-
-std::vector<mitk::TubeGraphProperty::LabelGroup*> mitk::TubeGraphDefaultLabelGroups::GetLabelGroupForLung()
-{
- return m_labelGroupsLung;
-}
-
-std::vector<mitk::TubeGraphProperty::LabelGroup*> mitk::TubeGraphDefaultLabelGroups::GetLabelGroupForLiver()
-{
- return m_labelGroupsLiver;
-}
diff --git a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkTubeGraphDefaultLabelGroups.h b/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkTubeGraphDefaultLabelGroups.h
deleted file mode 100644
index 72d7c1af4e..0000000000
--- a/Plugins/org.mitk.gui.qt.tubegraph/src/internal/mitkTubeGraphDefaultLabelGroups.h
+++ /dev/null
@@ -1,42 +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 mitkTubeGraphDefaultLabelGroups_h
-#define mitkTubeGraphDefaultLabelGroups_h
-
-#include "mitkTubeGraphProperty.h"
-
-#include <vector>
-
-namespace mitk
-{
- class TubeGraphDefaultLabelGroups
- {
-
- typedef TubeGraphProperty::LabelGroup LabelGroupType;
- typedef LabelGroupType::Label LabelType;
-
- public:
-
- TubeGraphDefaultLabelGroups();
- virtual ~TubeGraphDefaultLabelGroups();
-
- std::vector<LabelGroupType*> GetLabelGroupForLung();
- std::vector<LabelGroupType*> GetLabelGroupForLiver();
-
- private:
- std::vector<LabelGroupType*> m_labelGroupsLung;
- std::vector<LabelGroupType*> m_labelGroupsLiver;
-
- };
-}//namespace mitk
-#endif
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/CMakeLists.txt b/Plugins/org.mitk.gui.qt.ugvisualization/CMakeLists.txt
deleted file mode 100644
index ed165f14b4..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-project(org_mitk_gui_qt_ugvisualization)
-
-mitk_create_plugin(
- EXPORT_DIRECTIVE UGVISUALIZATION_EXPORT
- EXPORTED_INCLUDE_SUFFIXES src
- MODULE_DEPENDS MitkQtWidgetsExt
-)
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/documentation/doxygen/modules.dox b/Plugins/org.mitk.gui.qt.ugvisualization/documentation/doxygen/modules.dox
deleted file mode 100644
index cee668d667..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/documentation/doxygen/modules.dox
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- \defgroup org_mitk_gui_qt_ugvisualization org.mitk.gui.qt.ugvisualization
- \ingroup MITKPlugins
-
- \brief Describe your plugin here.
-
-*/
-
-/**
- \defgroup org_mitk_gui_qt_ugvisualization_internal Internal
- \ingroup org_mitk_gui_qt_ugvisualization
-
- \brief This subcategory includes the internal classes of the org.mitk.gui.qt.ugvisualization 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.ugvisualization/files.cmake b/Plugins/org.mitk.gui.qt.ugvisualization/files.cmake
deleted file mode 100644
index 5cb062a6b8..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/files.cmake
+++ /dev/null
@@ -1,37 +0,0 @@
-set(SRC_CPP_FILES
-
-)
-
-set(INTERNAL_CPP_FILES
- QmitkUGVisualizationView.cpp
- mitkPluginActivator.cpp
-)
-
-set(UI_FILES
- src/internal/QmitkUGVisualizationViewControls.ui
-)
-
-set(MOC_H_FILES
- src/internal/QmitkUGVisualizationView.h
- src/internal/mitkPluginActivator.h
-)
-
-set(CACHED_RESOURCE_FILES
- resources/icon.png
- plugin.xml
-)
-
-set(QRC_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/org.mitk.gui.qt.ugvisualization/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.ugvisualization/manifest_headers.cmake
deleted file mode 100644
index 04b75418be..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/manifest_headers.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(Plugin-Name "MITK UG Visualization")
-set(Plugin-Version "0.1")
-set(Plugin-Vendor "German Cancer Research Center (DKFZ)")
-set(Plugin-ContactAddress "https://www.mitk.org")
-set(Require-Plugin org.mitk.gui.qt.common)
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/plugin.xml b/Plugins/org.mitk.gui.qt.ugvisualization/plugin.xml
deleted file mode 100644
index 068fe5adbf..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/plugin.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?BlueBerry version="0.1"?>
-<plugin>
-
- <extension point="org.blueberry.ui.views">
- <view id="org.mitk.views.ugvisualization"
- name="UG Visualization"
- class="QmitkUGVisualizationView"
- icon="resources/icon.png" />
- </extension>
-
-</plugin>
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/resources/icon.png b/Plugins/org.mitk.gui.qt.ugvisualization/resources/icon.png
deleted file mode 100644
index 329ce3b355..0000000000
Binary files a/Plugins/org.mitk.gui.qt.ugvisualization/resources/icon.png and /dev/null differ
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp
deleted file mode 100644
index e9fc1015ac..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.cpp
+++ /dev/null
@@ -1,285 +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.
-
-============================================================================*/
-
-// Blueberry
-#include <berryISelectionService.h>
-#include <berryIWorkbenchWindow.h>
-
-// Qmitk
-#include "QmitkUGVisualizationView.h"
-
-#include <mitkUnstructuredGrid.h>
-#include <mitkGridRepresentationProperty.h>
-#include <mitkGridVolumeMapperProperty.h>
-#include <mitkVtkScalarModeProperty.h>
-#include <mitkPropertyObserver.h>
-
-#include <QmitkUGCombinedRepresentationPropertyWidget.h>
-#include <QmitkBoolPropertyWidget.h>
-
-#include <QWidgetAction>
-
-#include <QMenu>
-
-
-class UGVisVolumeObserver : public mitk::PropertyView
-{
-public:
-
- UGVisVolumeObserver(mitk::BoolProperty* property, QmitkUGVisualizationView* view)
- : PropertyView(property), m_View(view), m_BoolProperty(property)
- {
- }
-
-protected:
-
- void PropertyChanged() override
- {
- m_View->m_VolumeMode = m_BoolProperty->GetValue();
- m_View->UpdateEnablement();
- }
-
- void PropertyRemoved() override
- {
- m_View->m_VolumeMode = false;
- m_Property = nullptr;
- m_BoolProperty = nullptr;
- }
-
- QmitkUGVisualizationView* m_View;
- mitk::BoolProperty* m_BoolProperty;
-
-};
-
-
-const std::string QmitkUGVisualizationView::VIEW_ID = "org.mitk.views.ugvisualization";
-
-
-QmitkUGVisualizationView::QmitkUGVisualizationView()
-: QmitkAbstractView(), m_Outline2DAction(nullptr), m_Outline2DWidget(nullptr),
- m_LODAction(nullptr), m_ScalarVisibilityAction(nullptr), m_ScalarVisibilityWidget(nullptr),
- m_FirstVolumeRepId(-1), m_ShowTFGeneratorWidget(true), m_ShowScalarOpacityWidget(false),
- m_ShowColorWidget(true), m_ShowGradientOpacityWidget(false), m_ShowTFGeneratorAction(nullptr),
- m_ShowScalarOpacityAction(nullptr), m_ShowColorAction(nullptr), m_ShowGradientOpacityAction(nullptr),
- m_VolumeModeObserver(nullptr)
-{
-}
-
-QmitkUGVisualizationView::~QmitkUGVisualizationView()
-{
- delete m_VolumeModeObserver;
-}
-
-
-void QmitkUGVisualizationView::CreateQtPartControl( QWidget *parent )
-{
- m_Controls.setupUi( parent );
-
- m_Outline2DWidget = new QmitkBoolPropertyWidget("Outline 2D polygons", parent);
- m_Outline2DAction = new QWidgetAction(this);
- m_Outline2DAction->setDefaultWidget(m_Outline2DWidget);
-
- m_LODAction = new QAction("Enable LOD (Level Of Detail)", this);
- m_LODAction->setCheckable(true);
-
- m_ScalarVisibilityWidget = new QmitkBoolPropertyWidget("Visualize scalars", parent);
- m_ScalarVisibilityAction = new QWidgetAction(this);
- m_ScalarVisibilityAction->setDefaultWidget(m_ScalarVisibilityWidget);
-
- m_ShowColorAction = new QAction("Show color transfer function", this);
- m_ShowColorAction->setCheckable(true);
- m_ShowColorAction->setChecked(m_ShowColorWidget);
- m_ShowGradientOpacityAction = new QAction("Show gradient opacity function", this);
- m_ShowGradientOpacityAction->setCheckable(true);
- m_ShowGradientOpacityAction->setChecked(m_ShowGradientOpacityWidget);
- m_ShowScalarOpacityAction = new QAction("Show scalar opacity function", this);
- m_ShowScalarOpacityAction->setCheckable(true);
- m_ShowScalarOpacityAction->setChecked(m_ShowScalarOpacityWidget);
- m_ShowTFGeneratorAction = new QAction("Show transfer function generator", this);
- m_ShowTFGeneratorAction->setCheckable(true);
- m_ShowTFGeneratorAction->setChecked(m_ShowTFGeneratorWidget);
-
- QMenu* menu = new QMenu(parent);
- menu->addAction(m_ScalarVisibilityAction);
- menu->addAction(m_Outline2DAction);
- //menu->addAction(m_LODAction);
- menu->addSeparator();
- menu->addAction(m_ShowTFGeneratorAction);
- menu->addAction(m_ShowScalarOpacityAction);
- menu->addAction(m_ShowColorAction);
- menu->addAction(m_ShowGradientOpacityAction);
-
- m_Controls.m_OptionsButton->setMenu(menu);
-
- m_Controls.m_TransferFunctionWidget->SetScalarLabel("Scalar value");
-
-// const mitk::EnumerationProperty::EnumStringsContainerType& scalarStrings = scalarProp->GetEnumStrings();
-
-// for (mitk::EnumerationProperty::EnumStringsContainerType::const_iterator it = scalarStrings.begin();
-// it != scalarStrings.end(); ++it)
-// {
-// MITK_INFO << "ADding: " << it->first;
-// m_Controls.m_ScalarModeComboBox->addItem(QString::fromStdString(it->first), it->second);
-// }
-
- this->UpdateGUI();
-
- CreateConnections();
-}
-
-void QmitkUGVisualizationView::CreateConnections()
-{
- connect(m_Controls.m_ScalarModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateRenderWindow()));
- connect(m_Controls.m_RepresentationComboBox, SIGNAL(activated(int)), this, SLOT(UpdateRenderWindow()));
- connect(m_Outline2DWidget, SIGNAL(toggled(bool)), this, SLOT(UpdateRenderWindow()));
- connect(m_ScalarVisibilityWidget, SIGNAL(toggled(bool)), this, SLOT(UpdateRenderWindow()));
- connect(m_Controls.m_TransferFunctionGeneratorWidget, SIGNAL(SignalUpdateCanvas()), m_Controls.m_TransferFunctionWidget, SLOT(OnUpdateCanvas()));
-
- connect(m_ShowColorAction, SIGNAL(triggered(bool)), this, SLOT(ShowColorWidget(bool)));
- connect(m_ShowGradientOpacityAction, SIGNAL(triggered(bool)), this, SLOT(ShowGradientOpacityWidget(bool)));
- connect(m_ShowScalarOpacityAction, SIGNAL(triggered(bool)), this, SLOT(ShowScalarOpacityWidget(bool)));
- connect(m_ShowTFGeneratorAction, SIGNAL(triggered(bool)), this, SLOT(ShowTFGeneratorWidget(bool)));
-}
-
-void QmitkUGVisualizationView::SetFocus()
-{
- m_Controls.m_OptionsButton->setFocus();
-}
-
-void QmitkUGVisualizationView::UpdateRenderWindow()
-{
- mitk::RenderingManager::GetInstance()->RequestUpdateAll();
-}
-
-void QmitkUGVisualizationView::ShowTFGeneratorWidget(bool show)
-{
- m_ShowTFGeneratorWidget = show;
- UpdateEnablement();
-}
-
-void QmitkUGVisualizationView::ShowScalarOpacityWidget(bool show)
-{
- m_ShowScalarOpacityWidget = show;
- UpdateEnablement();
-}
-
-void QmitkUGVisualizationView::ShowColorWidget(bool show)
-{
- m_ShowColorWidget = show;
- UpdateEnablement();
-}
-
-void QmitkUGVisualizationView::ShowGradientOpacityWidget(bool show)
-{
- m_ShowGradientOpacityWidget = show;
- UpdateEnablement();
-}
-
-void QmitkUGVisualizationView::UpdateEnablement()
-{
- m_Controls.m_TransferFunctionGeneratorWidget->setVisible(m_ShowTFGeneratorWidget);
- m_Controls.m_TransferFunctionWidget->ShowScalarOpacityFunction(m_ShowScalarOpacityWidget);
- m_Controls.m_TransferFunctionWidget->ShowColorFunction(m_ShowColorWidget);
- m_Controls.m_TransferFunctionWidget->ShowGradientOpacityFunction(m_ShowGradientOpacityWidget);
-
- m_Controls.m_TransferFunctionGeneratorWidget->SetThresholdTabEnabled(m_ScalarVisibilityWidget->isChecked());
- m_Controls.m_TransferFunctionGeneratorWidget->SetBellTabEnabled(m_ScalarVisibilityWidget->isChecked());
- m_Controls.m_TransferFunctionWidget->SetScalarOpacityFunctionEnabled(m_ScalarVisibilityWidget->isChecked());
- m_Controls.m_TransferFunctionWidget->SetGradientOpacityFunctionEnabled(m_VolumeMode);
-}
-
-void QmitkUGVisualizationView::UpdateGUI()
-{
- bool enable = false;
-
- mitk::DataNode* node = nullptr;
- auto nodes = this->GetDataManagerSelection();
- if (!nodes.empty())
- {
- node = nodes.front();
-
- if (node)
- {
- // here we have a valid mitk::DataNode
-
- // a node itself is not very useful, we need its data item
- mitk::BaseData* data = node->GetData();
- if (data)
- {
- // test if this data item is an unstructured grid
- enable = dynamic_cast<mitk::UnstructuredGrid*>( data );
- }
- }
- }
-
- m_Controls.m_SelectedLabel->setVisible(enable);
- m_Controls.m_ErrorLabel->setVisible(!enable);
- m_Controls.m_ContainerWidget->setEnabled(enable);
- m_Controls.m_OptionsButton->setEnabled(enable);
-
- if (enable)
- {
- m_VolumeMode = false;
- node->GetBoolProperty("volumerendering", m_VolumeMode);
-
- m_Controls.m_SelectedLabel->setText(QString("Selected UG: ") + node->GetName().c_str());
-
- m_Controls.m_TransferFunctionGeneratorWidget->SetDataNode(node);
- m_Controls.m_TransferFunctionWidget->SetDataNode(node);
-
- mitk::BoolProperty* outlineProp = nullptr;
- node->GetProperty(outlineProp, "outline polygons");
- m_Outline2DWidget->SetProperty(outlineProp);
-
- mitk::BoolProperty* scalarVisProp = nullptr;
- node->GetProperty(scalarVisProp, "scalar visibility");
- m_ScalarVisibilityWidget->SetProperty(scalarVisProp);
-
- mitk::VtkScalarModeProperty* scalarProp = nullptr;
- if (node->GetProperty(scalarProp, "scalar mode"))
- {
- m_Controls.m_ScalarModeComboBox->SetProperty(scalarProp);
- }
-
- mitk::GridRepresentationProperty* gridRepProp = nullptr;
- mitk::GridVolumeMapperProperty* gridVolumeProp = nullptr;
- mitk::BoolProperty* volumeProp = nullptr;
- node->GetProperty(gridRepProp, "grid representation");
- node->GetProperty(gridVolumeProp, "volumerendering.mapper");
- node->GetProperty(volumeProp, "volumerendering");
- m_Controls.m_RepresentationComboBox->SetProperty(gridRepProp, gridVolumeProp, volumeProp);
-
- if (m_VolumeModeObserver)
- {
- delete m_VolumeModeObserver;
- m_VolumeModeObserver = nullptr;
- }
-
- if (volumeProp)
- {
- m_VolumeModeObserver = new UGVisVolumeObserver(volumeProp, this);
- }
- }
-
- UpdateEnablement();
-
-}
-
-
-void QmitkUGVisualizationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList<mitk::DataNode::Pointer>& /*nodes*/)
-{
- UpdateGUI();
-}
-
-
-
-
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h
deleted file mode 100644
index 5324e380c3..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationView.h
+++ /dev/null
@@ -1,108 +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 QmitkUGVisualizationView_h
-#define QmitkUGVisualizationView_h
-
-#include <berryISelectionListener.h>
-
-#include <QmitkAbstractView.h>
-
-#include "ui_QmitkUGVisualizationViewControls.h"
-
-class QWidgetAction;
-
-class QmitkBoolPropertyWidget;
-
-namespace mitk {
- class PropertyObserver;
-}
-
-/*!
- \brief QmitkUGVisualizationView
-
- \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation.
-*/
-class QmitkUGVisualizationView : public QmitkAbstractView
-{
- // this is needed for all Qt objects that should have a Qt meta-object
- // (everything that derives from QObject and wants to have signal/slots)
- Q_OBJECT
-
- public:
-
- static const std::string VIEW_ID;
-
- QmitkUGVisualizationView();
- ~QmitkUGVisualizationView() override;
-
- void CreateQtPartControl(QWidget *parent) override;
-
- ///
- /// Sets the focus to an internal widget.
- ///
- void SetFocus() override;
-
- protected slots:
-
- void UpdateRenderWindow();
-
- void ShowTFGeneratorWidget(bool show);
- void ShowScalarOpacityWidget(bool show);
- void ShowColorWidget(bool show);
- void ShowGradientOpacityWidget(bool show);
-
- protected:
-
- /// \brief called by QmitkAbstractView when DataManager's selection has changed
- void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList<mitk::DataNode::Pointer>& nodes) override;
-
- void CreateConnections();
-
- private:
-
- friend class UGVisVolumeObserver;
-
- void UpdateGUI();
-
- void UpdateEnablement();
-
- Ui::QmitkUGVisualizationViewControls m_Controls;
-
- QWidgetAction* m_Outline2DAction;
- QmitkBoolPropertyWidget* m_Outline2DWidget;
- QAction* m_LODAction;
- QWidgetAction* m_ScalarVisibilityAction;
- QmitkBoolPropertyWidget* m_ScalarVisibilityWidget;
-
- int m_FirstVolumeRepId;
- QHash<int, int> m_MapRepComboToEnumId;
-
- bool m_VolumeMode;
-
- bool m_ShowTFGeneratorWidget;
- bool m_ShowScalarOpacityWidget;
- bool m_ShowColorWidget;
- bool m_ShowGradientOpacityWidget;
-
- QAction* m_ShowTFGeneratorAction;
- QAction* m_ShowScalarOpacityAction;
- QAction* m_ShowColorAction;
- QAction* m_ShowGradientOpacityAction;
-
- mitk::PropertyObserver* m_VolumeModeObserver;
-
-};
-
-
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationViewControls.ui b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationViewControls.ui
deleted file mode 100644
index 30fb8ce503..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/QmitkUGVisualizationViewControls.ui
+++ /dev/null
@@ -1,182 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmitkUGVisualizationViewControls</class>
- <widget class="QWidget" name="QmitkUGVisualizationViewControls">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>465</width>
- <height>675</height>
- </rect>
- </property>
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="windowTitle">
- <string>QmitkTemplate</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QWidget" name="widget" native="true">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <property name="margin">
- <number>0</number>
- </property>
- <item>
- <widget class="QWidget" name="widget_3" native="true">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>1</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_3">
- <property name="margin">
- <number>0</number>
- </property>
- <item>
- <widget class="QLabel" name="m_ErrorLabel">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="styleSheet">
- <string notr="true">QLabel { color: rgb(255, 0, 0) }</string>
- </property>
- <property name="text">
- <string>Please select an unstructured grid!</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="m_SelectedLabel">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="m_OptionsButton">
- <property name="text">
- <string>Options</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QWidget" name="m_ContainerWidget" native="true">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>1</verstretch>
- </sizepolicy>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_2">
- <property name="margin">
- <number>0</number>
- </property>
- <item>
- <widget class="QWidget" name="widget_2" native="true">
- <layout class="QGridLayout" name="gridLayout">
- <property name="margin">
- <number>0</number>
- </property>
- <item row="0" column="1">
- <widget class="QmitkUGCombinedRepresentationPropertyWidget" name="m_RepresentationComboBox">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
- <horstretch>1</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QmitkEnumerationPropertyWidget" name="m_ScalarModeComboBox"/>
- </item>
- <item row="0" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Representation</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_2">
- <property name="text">
- <string>Scalar mode</string>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QmitkTransferFunctionGeneratorWidget" name="m_TransferFunctionGeneratorWidget" native="true">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QmitkTransferFunctionWidget" name="m_TransferFunctionWidget" native="true">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>1</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- </layout>
- </widget>
- <layoutdefault spacing="6" margin="11"/>
- <customwidgets>
- <customwidget>
- <class>QmitkTransferFunctionWidget</class>
- <extends>QWidget</extends>
- <header location="global">QmitkTransferFunctionWidget.h</header>
- </customwidget>
- <customwidget>
- <class>QmitkTransferFunctionGeneratorWidget</class>
- <extends>QWidget</extends>
- <header location="global">QmitkTransferFunctionGeneratorWidget.h</header>
- <container>1</container>
- </customwidget>
- <customwidget>
- <class>QmitkEnumerationPropertyWidget</class>
- <extends>QComboBox</extends>
- <header location="global">QmitkEnumerationPropertyWidget.h</header>
- </customwidget>
- <customwidget>
- <class>QmitkUGCombinedRepresentationPropertyWidget</class>
- <extends>QComboBox</extends>
- <header location="global">QmitkUGCombinedRepresentationPropertyWidget.h</header>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/mitkPluginActivator.cpp
deleted file mode 100644
index 84778c5f95..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/mitkPluginActivator.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*============================================================================
-
-The Medical Imaging Interaction Toolkit (MITK)
-
-Copyright (c) German Cancer Research Center (DKFZ)
-All rights reserved.
-
-Use of this source code is governed by a 3-clause BSD license that can be
-found in the LICENSE file.
-
-============================================================================*/
-
-#include "mitkPluginActivator.h"
-#include "QmitkUGVisualizationView.h"
-
-namespace mitk {
-
-void PluginActivator::start(ctkPluginContext* context)
-{
- BERRY_REGISTER_EXTENSION_CLASS(QmitkUGVisualizationView, context)
-}
-
-void PluginActivator::stop(ctkPluginContext* context)
-{
- Q_UNUSED(context)
-}
-
-}
diff --git a/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.ugvisualization/src/internal/mitkPluginActivator.h
deleted file mode 100644
index f822ca8e0a..0000000000
--- a/Plugins/org.mitk.gui.qt.ugvisualization/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 <ctkPluginActivator.h>
-
-namespace mitk {
-
-class PluginActivator :
- public QObject, public ctkPluginActivator
-{
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_ugvisualization")
- Q_INTERFACES(ctkPluginActivator)
-
-public:
-
- void start(ctkPluginContext* context) override;
- void stop(ctkPluginContext* context) override;
-
-}; // PluginActivator
-
-}
-
-#endif
diff --git a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/QmitkUltrasoundSupport.h b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/QmitkUltrasoundSupport.h
index cfc051fc7a..4dc07dd1f1 100644
--- a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/QmitkUltrasoundSupport.h
+++ b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/QmitkUltrasoundSupport.h
@@ -1,181 +1,181 @@
/*============================================================================
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 QmitkUltrasoundSupport_h
#define QmitkUltrasoundSupport_h
#include <mitkLookupTable.h>
#include <mitkLookupTableProperty.h>
#include <berryISelectionListener.h>
#include <QmitkAbstractView.h>
#include "ui_QmitkUltrasoundSupportControls.h"
#include "QmitkUSAbstractCustomWidget.h"
#include "QmitkUSControlsBModeWidget.h"
#include "QmitkUSControlsDopplerWidget.h"
#include "QmitkUSControlsProbesWidget.h"
#include <mitkBaseRenderer.h>
#include "QmitkRenderWindow.h"
#include <mitkStandaloneDataStorage.h>
#include <QmitkLevelWindowWidget.h>
#include <QmitkSliceWidget.h>
-#include <QTime>
+#include <QElapsedTimer>
#include <ctkServiceEvent.h>
/*!
\brief UltrasoundSupport
This plugin provides functionality to manage Ultrasound devices, create video devices and to view device images.
\ingroup ${plugin_target}_internal
*/
class QmitkUltrasoundSupport : public QmitkAbstractView
{
// this is needed for all Qt objects that should have a Qt meta-object
// (everything that derives from QObject and wants to have signal/slots)
Q_OBJECT
public:
void SetFocus() override;
static const std::string VIEW_ID;
void CreateQtPartControl(QWidget *parent) override;
QmitkUltrasoundSupport();
~QmitkUltrasoundSupport() override;
public slots:
/*
* \brief This is called when the newDeviceWidget is closed
*/
void OnNewDeviceWidgetDone();
protected slots:
void OnClickedAddNewDevice();
void OnChangedFramerateLimit();
void OnClickedEditDevice();
/*
*\brief Called, when the selection in the list of the active devices changes.
*/
void OnChangedActiveDevice();
void OnClickedFreezeButton();
void OnDeviceServiceEvent(const ctkServiceEvent event);
/*
* \brief This is the main imaging loop that updates the image and is called regularly during the imaging process
*/
void UpdateImage();
void RenderImage2d();
void RenderImage3d();
void StartTimers();
void StopTimers();
protected:
void CreateControlWidgets();
void RemoveControlWidgets();
Ui::UltrasoundSupportControls* m_Controls;
QmitkUSAbstractCustomWidget* m_ControlCustomWidget;
QmitkUSControlsBModeWidget* m_ControlBModeWidget;
QmitkUSControlsDopplerWidget* m_ControlDopplerWidget;
QmitkUSControlsProbesWidget* m_ControlProbesWidget;
bool m_ImageAlreadySetToNode;
unsigned int m_CurrentImageWidth;
unsigned int m_CurrentImageHeight;
/** Keeps track of the amount of output Nodes*/
unsigned int m_AmountOfOutputs;
/** The device that is currently used to acquire images */
mitk::USDevice::Pointer m_Device;
void SetTimerIntervals(int intervalPipeline, int interval2D, int interval3D);
/** This timer triggers periodic updates to the pipeline */
QTimer* m_UpdateTimer;
QTimer* m_RenderingTimer2d;
QTimer* m_RenderingTimer3d;
/** These clocks are used to compute the framerate in the methods DisplayImage(),RenderImage2d() and RenderImage3d(). */
- QTime m_Clock;
- QTime m_Clock2d;
- QTime m_Clock3d;
+ QElapsedTimer m_Clock;
+ QElapsedTimer m_Clock2d;
+ QElapsedTimer m_Clock3d;
/** A counter to compute the framerate. */
int m_FrameCounterPipeline;
int m_FrameCounter2d;
int m_FrameCounter3d;
int m_FPSPipeline, m_FPS2d, m_FPS3d;
/** Stores the properties of some QWidgets (and the tool storage file name) to QSettings.*/
void StoreUISettings();
/** Loads the properties of some QWidgets (and the tool storage file name) from QSettings.*/
void LoadUISettings();
/** The nodes that we feed images into.*/
std::vector<mitk::DataNode::Pointer> m_Node;
/** Adds a new node to the m_Nodes vector*/
void InitNewNode();
/** Destroys the last node in the m_Nodes vector */
void DestroyLastNode();
/** Checks the amount of slices in the image from the USDevice and creates as many Nodes as there are slices */
void UpdateAmountOfOutputs();
/** This function just checks how many nodes there are currently and sets the laser image to a jet transparent colormap. */
void UpdateLevelWindows();
bool m_ForceRequestUpdateAll;
void SetColormap(mitk::DataNode::Pointer node, mitk::LookupTable::LookupTableType type);
/** The separated slices from m_Image */
std::vector<mitk::Image::Pointer> m_curOutput;
/** The old geometry of m_Image. It is needed to check if the geometry changed (e.g. because
* the zoom factor was modified) and the image needs to be reinitialized. */
mitk::SlicedGeometry3D::Pointer m_OldGeometry;
QList<ctkServiceReference> m_CustomWidgetServiceReference;
double m_CurrentDynamicRange;
/* Spacing calibration variables and methods */
mitk::Point3D m_Xpoint1,m_Xpoint2,m_Ypoint1,m_Ypoint2;
double m_XSpacing, m_YSpacing;
double ComputeSpacing(mitk::Point3D p1, mitk::Point3D p2, double distance);
protected slots:
void SetXPoint1();
void SetXPoint2();
void SetYPoint1();
void SetYPoint2();
void WriteSpacingToDevice();
};
#endif
diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp
index d431fa5643..e4a7686adf 100644
--- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp
+++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp
@@ -1,730 +1,729 @@
/*============================================================================
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.
============================================================================*/
// View navigator plugin
#include <QmitkViewNavigatorWidget.h>
#include <QmitkPerspectiveItem.h>
#include <QmitkViewItem.h>
// Blueberry
#include <berryIWorkbenchWindow.h>
#include <berryIPerspectiveRegistry.h>
#include <berryPlatform.h>
#include <berryIWorkbenchPage.h>
#include <berryIExtensionRegistry.h>
#include <berryIHandlerService.h>
#include <berryIWorkbenchCommandConstants.h>
#include <berryUIElement.h>
// MITK
#include <mitkLog.h>
// Qt
#include <QHash>
#include <QInputDialog>
#include <QMessageBox>
#include <QStandardItem>
#include <QSortFilterProxyModel>
namespace
{
QFont getLargeFont()
{
QFont font = qApp->font();
font.setPointSizeF(font.pointSizeF() * 1.25f);
return font;
}
}
class KeywordRegistry
{
public:
KeywordRegistry()
{
berry::IExtensionRegistry* extensionPointService = berry::Platform::GetExtensionRegistry();
auto keywordExts = extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.keywords");
for (auto keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt)
{
QString keywordId = (*keywordExtsIt)->GetAttribute("id");
QString keywordLabels = (*keywordExtsIt)->GetAttribute("label");
m_Keywords[keywordId].push_back(keywordLabels);
}
}
QStringList GetKeywords(const QString& id)
{
return m_Keywords[id];
}
QStringList GetKeywords(const QStringList& ids)
{
QStringList result;
for (const auto& id : ids)
{
result.append(this->GetKeywords(id));
}
return result;
}
private:
QHash<QString, QStringList> m_Keywords;
};
class ClassFilterProxyModel : public QSortFilterProxyModel
{
public:
ClassFilterProxyModel(QObject* parent = nullptr)
: QSortFilterProxyModel(parent)
{
}
bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
return hasToBeDisplayed(index);
}
private:
bool displayElement(const QModelIndex index) const
{
QString type = sourceModel()->data(index, Qt::DisplayRole).toString();
QStandardItem* item = dynamic_cast<QStandardItemModel*>(sourceModel())->itemFromIndex(index);
- if (type.contains(filterRegExp()))
+ if (type.contains(filterRegularExpression()))
{
return true;
}
QmitkViewItem* viewItem = dynamic_cast<QmitkViewItem*>(item);
if (nullptr != viewItem)
{
for (const auto& tag : viewItem->m_Tags)
{
- if (tag.contains(filterRegExp()))
+ if (tag.contains(filterRegularExpression()))
{
return true;
}
}
- if (viewItem->m_Description.contains(filterRegExp()))
+ if (viewItem->m_Description.contains(filterRegularExpression()))
{
return true;
}
}
QmitkPerspectiveItem* perspectiveItem = dynamic_cast<QmitkPerspectiveItem*>(item);
if (nullptr != perspectiveItem)
{
for (const auto& tag : perspectiveItem->m_Tags)
{
- if (tag.contains(filterRegExp()))
+ if (tag.contains(filterRegularExpression()))
{
return true;
}
}
- if (perspectiveItem->m_Description.contains(filterRegExp()))
+ if (perspectiveItem->m_Description.contains(filterRegularExpression()))
{
return true;
}
}
return false;
}
bool hasToBeDisplayed(const QModelIndex index) const
{
bool result = false;
if (sourceModel()->rowCount(index) > 0)
{
for (int i = 0; i < sourceModel()->rowCount(index); i++)
{
QModelIndex childIndex = sourceModel()->index(i, 0, index);
if (!childIndex.isValid())
{
break;
}
result = hasToBeDisplayed(childIndex);
result |= displayElement(index);
if (result)
{
break;
}
}
}
else
{
result = displayElement(index);
}
return result;
}
};
class ViewNavigatorPerspectiveListener: public berry::IPerspectiveListener
{
public:
ViewNavigatorPerspectiveListener(QmitkViewNavigatorWidget* parent)
: m_ParentWidget(parent)
{
}
Events::Types GetPerspectiveEventTypes() const override
{
return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED
// remove the following line when command framework is finished
| Events::CLOSED | Events::OPENED | Events::PART_CHANGED;
}
void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
m_ParentWidget->UpdateTreeList();
}
void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/,
const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) override
{
m_ParentWidget->UpdateTreeList();
}
void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
m_ParentWidget->m_ActivePerspective = nullptr;
}
void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
m_ParentWidget->UpdateTreeList();
}
void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) override
{
m_ParentWidget->m_ActivePerspective = nullptr;
}
using IPerspectiveListener::PerspectiveChanged;
void PerspectiveChanged(const berry::IWorkbenchPage::Pointer& /*page*/,
const berry::IPerspectiveDescriptor::Pointer& /*perspective*/,
const berry::IWorkbenchPartReference::Pointer& partRef, const std::string& changeId)
{
if (changeId == "viewHide" && partRef->GetId() == "org.mitk.views.viewnavigator")
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->RemovePerspectiveListener(m_ParentWidget->m_PerspectiveListener.data());
else
m_ParentWidget->UpdateTreeList();
}
private:
QmitkViewNavigatorWidget* m_ParentWidget;
};
class ViewNavigatorViewListener: public berry::IPartListener
{
public:
ViewNavigatorViewListener(QmitkViewNavigatorWidget* parent)
: m_ParentWidget(parent)
{
}
Events::Types GetPartEventTypes() const override
{
return Events::OPENED | Events::CLOSED;
}
void PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef) override
{
if (partRef->GetId() != "org.mitk.views.viewnavigator")
{
m_ParentWidget->UpdateTreeList((partRef->GetPart(false)).GetPointer());
}
else
{
m_ParentWidget->FillTreeList();
m_ParentWidget->UpdateTreeList();
}
}
void PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) override
{
if (partRef->GetId() != "org.mitk.views.viewnavigator")
{
m_ParentWidget->UpdateTreeList();
}
}
private:
QmitkViewNavigatorWidget* m_ParentWidget;
};
bool compareViews(const berry::IViewDescriptor::Pointer& a, const berry::IViewDescriptor::Pointer& b)
{
if (a.IsNull() || b.IsNull())
{
return false;
}
return a->GetLabel().compare(b->GetLabel()) < 0;
}
bool comparePerspectives(const berry::IPerspectiveDescriptor::Pointer& a, const berry::IPerspectiveDescriptor::Pointer& b)
{
if (a.IsNull() || b.IsNull())
{
return false;
}
return a->GetLabel().compare(b->GetLabel()) < 0;
}
bool compareQStandardItems(const QStandardItem* a, const QStandardItem* b)
{
if (nullptr == a || nullptr== b)
{
return false;
}
return a->text().compare(b->text()) < 0;
}
QmitkViewNavigatorWidget::QmitkViewNavigatorWidget(berry::IWorkbenchWindow::Pointer window,
QWidget* parent,
Qt::WindowFlags)
: QWidget(parent)
, m_Window(window)
{
this->CreateQtPartControl(this);
}
QmitkViewNavigatorWidget::~QmitkViewNavigatorWidget()
{
m_Window->RemovePerspectiveListener(m_PerspectiveListener.data());
m_Window->GetPartService()->RemovePartListener(m_ViewPartListener.data());
}
void QmitkViewNavigatorWidget::SetFocus()
{
m_Controls.lineEdit->setFocus();
}
void QmitkViewNavigatorWidget::UpdateTreeList(berry::IWorkbenchPart* workbenchPart)
{
berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage();
if (page.IsNull())
{
return;
}
m_ActivePerspective = page->GetPerspective();
QList<berry::IViewPart::Pointer> viewParts = page->GetViews();
// iterate over all tree items
for (const auto& item : m_TreeModel->findItems("*", Qt::MatchWildcard | Qt::MatchRecursive))
{
QFont font = qApp->font();
// check if the item is a view item and if it is equal to any opened view
QmitkViewItem* viewItem = dynamic_cast<QmitkViewItem *>(item);
if (nullptr != viewItem)
{
if (nullptr != workbenchPart && workbenchPart->GetPartName() == viewItem->m_ItemDescriptor->GetLabel())
{
font.setBold(true);
}
else
{
for (const auto& viewPart : viewParts)
{
if (viewPart->GetPartName() == viewItem->m_ItemDescriptor->GetLabel())
{
font.setBold(true);
break;
}
}
}
viewItem->setFont(font);
}
else
{
// check if the item is a perspective item and if it is equal to the current perspective
QmitkPerspectiveItem* perspectiveItem = dynamic_cast<QmitkPerspectiveItem*>(item);
if (nullptr != perspectiveItem)
{
if (m_ActivePerspective.IsNotNull() && m_ActivePerspective->GetId() == perspectiveItem->m_ItemDescriptor->GetId())
{
font.setBold(true);
}
perspectiveItem->setFont(font);
}
}
}
}
bool QmitkViewNavigatorWidget::FillTreeList()
{
// initialize tree model
m_TreeModel->clear();
// add all available views
this->AddViewsToTree();
// add all available perspectives
this->AddPerspectivesToTree();
m_Controls.m_PluginTreeView->expandAll();
return true;
}
void QmitkViewNavigatorWidget::FilterChanged()
{
QString filterString = m_Controls.lineEdit->text();
m_Controls.m_PluginTreeView->expandAll();
- Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive;
QString strPattern = "^*" + filterString;
- QRegExp regExp(strPattern, caseSensitivity);
+ QRegularExpression regExp(strPattern, QRegularExpression::CaseInsensitiveOption);
- m_FilterProxyModel->setFilterRegExp(regExp);
+ m_FilterProxyModel->setFilterRegularExpression(regExp);
}
void QmitkViewNavigatorWidget::ItemClicked(const QModelIndex &index)
{
QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index));
QmitkPerspectiveItem* perspectiveItem = dynamic_cast<QmitkPerspectiveItem*>(item);
if (nullptr != perspectiveItem)
{
try
{
berry::PlatformUI::GetWorkbench()->ShowPerspective(
perspectiveItem->m_ItemDescriptor->GetId(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow());
}
catch (...)
{
QMessageBox::critical(nullptr, "Opening Perspective Failed",
QString("The requested perspective could not be opened.\nSee the log for details."));
}
return;
}
QmitkViewItem* viewItem = dynamic_cast<QmitkViewItem*>(item);
if (nullptr != viewItem)
{
berry::IWorkbenchPage::Pointer page =
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage();
if (page.IsNotNull())
{
try
{
page->ShowView(viewItem->m_ItemDescriptor->GetId());
}
catch (const berry::PartInitException& e)
{
BERRY_ERROR << "Error: " << e.what() << std::endl;
}
}
}
}
void QmitkViewNavigatorWidget::SaveCurrentPerspectiveAs()
{
berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage();
berry::IPerspectiveDescriptor::Pointer currentPerspective = page->GetPerspective();
bool ok = false;
QString perspectiveLabel = QInputDialog::getText(this, "Save perspective as ...",
"New perspective name:", QLineEdit::Normal,
"", &ok);
if (!ok)
{
return;
}
if (perspectiveLabel.isEmpty())
{
QMessageBox::information(this, "Save perspective as ...", "Please select a valid perspective name.");
return;
}
berry::IPerspectiveRegistry* perspectiveRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry();
berry::IPerspectiveDescriptor::Pointer newPerspective = perspectiveRegistry->CreatePerspective(perspectiveLabel, currentPerspective);
if (nullptr == newPerspective)
{
QMessageBox::information(this, "Save perspective as ...", "The selected perspective name is already in use.");
return;
}
page->SavePerspectiveAs(newPerspective);
this->FillTreeList();
this->UpdateTreeList();
}
void QmitkViewNavigatorWidget::ResetCurrentPerspective()
{
if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm",
"Do you really want to reset the current perspective?",
QMessageBox::Yes | QMessageBox::No).exec())
{
berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage();
page->ResetPerspective();
}
}
void QmitkViewNavigatorWidget::ClosePerspective()
{
if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm",
"Do you really want to close the current perspective?",
QMessageBox::Yes | QMessageBox::No).exec())
{
berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage();
page->ClosePerspective(page->GetPerspective(), true, true);
}
}
void QmitkViewNavigatorWidget::CloseAllPerspectives()
{
if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm",
"Do you really want to close all perspectives?",
QMessageBox::Yes | QMessageBox::No).exec())
{
berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage();
page->CloseAllPerspectives(true, true);
}
}
void QmitkViewNavigatorWidget::ExpandAll()
{
m_Controls.m_PluginTreeView->expandAll();
}
void QmitkViewNavigatorWidget::CollapseAll()
{
m_Controls.m_PluginTreeView->collapseAll();
}
void QmitkViewNavigatorWidget::CustomMenuRequested(QPoint pos)
{
QModelIndex index = m_Controls.m_PluginTreeView->indexAt(pos);
QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index));
if (nullptr == m_ContextMenu)
return;
m_ContextMenu->clear();
QmitkPerspectiveItem* perspectiveItem = dynamic_cast<QmitkPerspectiveItem*>(item);
if (nullptr != perspectiveItem)
{
berry::IPerspectiveDescriptor::Pointer perspectiveDescriptor = perspectiveItem->m_ItemDescriptor;
if (this->m_ActivePerspective.IsNotNull() && this->m_ActivePerspective == perspectiveDescriptor)
{
QAction* saveAsAction = new QAction("Save perspective as ...", this);
m_ContextMenu->addAction(saveAsAction);
connect(saveAsAction, SIGNAL(triggered()), SLOT(SaveCurrentPerspectiveAs()));
m_ContextMenu->addSeparator();
}
}
QAction* resetAction = new QAction("Reset current perspective", this);
m_ContextMenu->addAction(resetAction);
connect(resetAction, SIGNAL(triggered()), SLOT(ResetCurrentPerspective()));
QAction* closeAction = new QAction("Close perspective", this);
m_ContextMenu->addAction(closeAction);
connect(closeAction, SIGNAL(triggered()), SLOT(ClosePerspective()));
QAction* closeAllAction = new QAction("Close all perspectives", this);
m_ContextMenu->addAction(closeAllAction);
connect(closeAllAction, SIGNAL(triggered()), SLOT(CloseAllPerspectives()));
m_ContextMenu->addSeparator();
QAction* expandAction = new QAction("Expand tree", this);
m_ContextMenu->addAction(expandAction);
connect(expandAction, SIGNAL(triggered()), SLOT(ExpandAll()));
QAction* collapseAction = new QAction("Collapse tree", this);
m_ContextMenu->addAction(collapseAction);
connect(collapseAction, SIGNAL(triggered()), SLOT(CollapseAll()));
m_ContextMenu->popup(m_Controls.m_PluginTreeView->viewport()->mapToGlobal(pos));
}
void QmitkViewNavigatorWidget::CreateQtPartControl(QWidget* parent)
{
// active workbench window available?
if (m_Window.IsNull())
{
return;
}
m_Controls.setupUi(parent);
connect(m_Controls.m_PluginTreeView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(CustomMenuRequested(QPoint)));
connect(m_Controls.m_PluginTreeView, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(ItemClicked(const QModelIndex&)));
connect(m_Controls.lineEdit, SIGNAL(textChanged(QString)), SLOT(FilterChanged()));
m_ContextMenu = new QMenu(m_Controls.m_PluginTreeView);
m_Controls.m_PluginTreeView->setContextMenuPolicy(Qt::CustomContextMenu);
// Create a new TreeModel for the data
m_TreeModel = new QStandardItemModel();
m_FilterProxyModel = new ClassFilterProxyModel(this);
m_FilterProxyModel->setSourceModel(m_TreeModel);
m_Controls.m_PluginTreeView->setModel(m_FilterProxyModel);
m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(this));
m_Window->AddPerspectiveListener(m_PerspectiveListener.data());
m_ViewPartListener.reset(new ViewNavigatorViewListener(this));
m_Window->GetPartService()->AddPartListener(m_ViewPartListener.data());
}
void QmitkViewNavigatorWidget::AddPerspectivesToTree()
{
berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry();
QList<berry::IPerspectiveDescriptor::Pointer> perspectiveDescriptors(perspRegistry->GetPerspectives());
- qSort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives);
+ std::sort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives);
QStandardItem* perspectiveRootItem = new QStandardItem("Perspectives");
perspectiveRootItem->setFont(getLargeFont());
perspectiveRootItem->setEditable(false);
QStandardItem* treeRootItem = m_TreeModel->invisibleRootItem();
treeRootItem->appendRow(perspectiveRootItem);
this->AddItemsToTree<QList<berry::IPerspectiveDescriptor::Pointer>, QmitkPerspectiveItem>(
perspectiveDescriptors, perspectiveRootItem);
}
void QmitkViewNavigatorWidget::AddViewsToTree()
{
berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry();
QList<berry::IViewDescriptor::Pointer> viewDescriptors(viewRegistry->GetViews());
- qSort(viewDescriptors.begin(), viewDescriptors.end(), compareViews);
+ std::sort(viewDescriptors.begin(), viewDescriptors.end(), compareViews);
auto largeFont = getLargeFont();
QStandardItem* viewRootItem = new QStandardItem("Views");
viewRootItem->setFont(largeFont);
viewRootItem->setEditable(false);
QStandardItem* treeRootItem = m_TreeModel->invisibleRootItem();
treeRootItem->appendRow(viewRootItem);
QStandardItem* miscellaneousCategoryItem = new QStandardItem("Miscellaneous");
miscellaneousCategoryItem->setFont(largeFont);
miscellaneousCategoryItem->setEditable(false);
QStringList viewExcludeList;
// internal view used for the intro screen, will crash when opened directly, see T22352
viewExcludeList.append(QString("org.blueberry.ui.internal.introview"));
viewExcludeList.append(QString("org.mitk.views.controlvisualizationpropertiesview"));
viewExcludeList.append(QString("org.mitk.views.modules"));
viewExcludeList.append(QString("org.mitk.views.viewnavigator"));
this->AddItemsToTree<QList<berry::IViewDescriptor::Pointer>, QmitkViewItem>(
viewDescriptors, viewRootItem, miscellaneousCategoryItem, viewExcludeList);
}
template<typename D, typename I>
void QmitkViewNavigatorWidget::AddItemsToTree(D itemDescriptors, QStandardItem* rootItem,
QStandardItem* miscellaneousItem, const QStringList& itemExcludeList)
{
KeywordRegistry keywordRegistry;
std::vector<QStandardItem*> categoryItems;
for (const auto& itemDescriptor : itemDescriptors)
{
bool excludeView = itemExcludeList.contains(itemDescriptor->GetId());
if (excludeView)
{
continue;
}
QIcon icon = itemDescriptor->GetImageDescriptor();
I* item = new I(icon, itemDescriptor->GetLabel());
item->m_ItemDescriptor = itemDescriptor;
item->m_Description = itemDescriptor->GetDescription();
item->setToolTip(itemDescriptor->GetDescription());
QStringList keylist = itemDescriptor->GetKeywordReferences();
item->m_Tags = keywordRegistry.GetKeywords(keylist);
item->setEditable(false);
QStringList categoryPath = itemDescriptor->GetCategoryPath();
if (categoryPath.empty())
{
// If a root item for general / non-categorized item views is given, use it.
// Otherwise put the non-categorized item views into the top root item.
if (nullptr != miscellaneousItem)
{
miscellaneousItem->appendRow(item);
}
else
{
rootItem->appendRow(item);
}
}
else
{
QStandardItem* categoryItem = nullptr;
for (const auto& currentCategoryItem : categoryItems)
{
if (currentCategoryItem->text() == categoryPath.front())
{
categoryItem = currentCategoryItem;
break;
}
}
if (nullptr == categoryItem)
{
categoryItem = new QStandardItem(QIcon(), categoryPath.front());
categoryItems.push_back(categoryItem);
}
auto font = getLargeFont();
categoryItem->setFont(font);
categoryItem->setEditable(false);
categoryItem->appendRow(item);
}
}
std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems);
for (const auto& categoryItem : categoryItems)
{
rootItem->appendRow(categoryItem);
}
if (nullptr != miscellaneousItem && miscellaneousItem->hasChildren())
{
rootItem->appendRow(miscellaneousItem);
}
}
diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h
index c94f891395..c27effebe0 100644
--- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h
+++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h
@@ -1,87 +1,87 @@
/*============================================================================
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 QmitkViewNavigatorWidget_h
#define QmitkViewNavigatorWidget_h
#include "ui_QmitkViewNavigatorWidgetControls.h"
//QT headers
#include <QWidget>
#include <QStandardItemModel>
#include <QMenu>
#include <berryIPartListener.h>
#include <berryIPerspectiveListener.h>
#include <berryIWorkbenchWindow.h>
class ClassFilterProxyModel;
/**
* @brief
*
*/
class QmitkViewNavigatorWidget : public QWidget
{
Q_OBJECT
public:
QmitkViewNavigatorWidget(berry::IWorkbenchWindow::Pointer window,
QWidget* parent = nullptr,
- Qt::WindowFlags f = nullptr);
+ Qt::WindowFlags f = {});
~QmitkViewNavigatorWidget() override;
void SetFocus();
public Q_SLOTS:
void FilterChanged();
void ItemClicked(const QModelIndex& index);
void SaveCurrentPerspectiveAs();
void ResetCurrentPerspective();
void ClosePerspective();
void CloseAllPerspectives();
void ExpandAll();
void CollapseAll();
void CustomMenuRequested(QPoint pos);
protected:
friend class ViewNavigatorPerspectiveListener;
friend class ViewNavigatorViewListener;
berry::IPerspectiveDescriptor::Pointer m_ActivePerspective;
private:
void CreateQtPartControl(QWidget* parent);
bool FillTreeList();
void UpdateTreeList(berry::IWorkbenchPart* workbenchPart = nullptr);
void AddPerspectivesToTree();
void AddViewsToTree();
template<typename D, typename I>
void AddItemsToTree(D itemDescriptors, QStandardItem* rootItem,
QStandardItem* miscellaneousItem = nullptr, const QStringList& itemExcludeList = QStringList());
Ui::QmitkViewNavigatorWidgetControls m_Controls;
QStandardItemModel* m_TreeModel;
ClassFilterProxyModel* m_FilterProxyModel;
QMenu* m_ContextMenu;
QScopedPointer<berry::IPerspectiveListener> m_PerspectiveListener;
QScopedPointer<berry::IPartListener> m_ViewPartListener;
berry::IWorkbenchWindow::Pointer m_Window;
};
#endif
diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp
index 5eaf8a507d..7c69d7a407 100644
--- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp
+++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatConnectionPreferencePage.cpp
@@ -1,296 +1,296 @@
/*============================================================================
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 "QmitkXnatConnectionPreferencePage.h"
#include "QmitkXnatTreeBrowserView.h"
#include "org_mitk_gui_qt_xnatinterface_Activator.h"
#include <QFileDialog>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QGridLayout>
#include <QMessageBox>
#include <QApplication>
#include <QMap>
#include "ctkXnatSession.h"
#include "ctkXnatLoginProfile.h"
#include "ctkXnatException.h"
#include <mitkIOUtil.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
using namespace berry;
namespace
{
mitk::IPreferences* GetPreferences()
{
auto* preferencesService = mitk::CoreServices::GetPreferencesService();
return preferencesService->GetSystemPreferences()->Node(QmitkXnatTreeBrowserView::VIEW_ID.toStdString());
}
}
QmitkXnatConnectionPreferencePage::QmitkXnatConnectionPreferencePage()
: m_Control(nullptr)
{
}
void QmitkXnatConnectionPreferencePage::Init(berry::IWorkbench::Pointer)
{
}
void QmitkXnatConnectionPreferencePage::CreateQtControl(QWidget* parent)
{
m_Controls.setupUi(parent);
m_Control = new QWidget(parent);
m_Control->setLayout(m_Controls.gridLayout);
ctkXnatSession* session;
try
{
session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService(
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>());
}
catch (std::invalid_argument&)
{
session = nullptr;
}
if (session != nullptr && session->isOpen())
{
m_Controls.xnatTestConnectionLabel->setStyleSheet("color: green");
m_Controls.xnatTestConnectionLabel->setText("Already connected.");
m_Controls.xnatTestConnectionButton->setEnabled(false);
}
const QIntValidator *portV = new QIntValidator(0, 65535, parent);
m_Controls.inXnatPort->setValidator(portV);
- const QRegExp hostRx("^(https?)://[^ /](\\S)+$");
- const QRegExpValidator *hostV = new QRegExpValidator(hostRx, parent);
+ const QRegularExpression hostRx("^(https?)://[^ /](\\S)+$");
+ const QRegularExpressionValidator *hostV = new QRegularExpressionValidator(hostRx, parent);
m_Controls.inXnatHostAddress->setValidator(hostV);
connect(m_Controls.xnatTestConnectionButton, SIGNAL(clicked()), this, SLOT(TestConnection()));
connect(m_Controls.inXnatHostAddress, SIGNAL(editingFinished()), this, SLOT(UrlChanged()));
connect(m_Controls.inXnatDownloadPath, SIGNAL(editingFinished()), this, SLOT(DownloadPathChanged()));
connect(m_Controls.cbUseNetworkProxy, SIGNAL(toggled(bool)), this, SLOT(onUseNetworkProxy(bool)));
connect(m_Controls.btnDownloadPath, SIGNAL(clicked()), this, SLOT(OnDownloadPathButtonClicked()));
m_Controls.groupBoxProxySettings->setVisible(m_Controls.cbUseNetworkProxy->isChecked());
this->Update();
}
QWidget* QmitkXnatConnectionPreferencePage::GetQtControl() const
{
return m_Control;
}
bool QmitkXnatConnectionPreferencePage::PerformOk()
{
auto* prefs = GetPreferences();
if (prefs != nullptr)
{
prefs->Put(m_Controls.xnatHostAddressLabel->text().toStdString(), m_Controls.inXnatHostAddress->text().toStdString());
prefs->Put(m_Controls.xnatPortLabel->text().toStdString(), m_Controls.inXnatPort->text().toStdString());
prefs->Put(m_Controls.xnatUsernameLabel->text().toStdString(), m_Controls.inXnatUsername->text().toStdString());
prefs->Put(m_Controls.xnatPasswortLabel->text().toStdString(), m_Controls.inXnatPassword->text().toStdString());
prefs->Put(m_Controls.xnatDownloadPathLabel->text().toStdString(), m_Controls.inXnatDownloadPath->text().toStdString());
// Network proxy settings
prefs->PutBool(m_Controls.cbUseNetworkProxy->text().toStdString(), m_Controls.cbUseNetworkProxy->isChecked());
prefs->Put(m_Controls.proxyAddressLabel->text().toStdString(), m_Controls.inProxyAddress->text().toStdString());
prefs->Put(m_Controls.proxyPortLabel->text().toStdString(), m_Controls.inProxyPort->text().toStdString());
prefs->Put(m_Controls.proxyUsernameLabel->text().toStdString(), m_Controls.inProxyUsername->text().toStdString());
prefs->Put(m_Controls.proxyPasswordLabel->text().toStdString(), m_Controls.inProxyPassword->text().toStdString());
// Silent Mode
prefs->PutBool(m_Controls.cbUseSilentMode->text().toStdString(), m_Controls.cbUseSilentMode->isChecked());
//Write
prefs->Flush();
return true;
}
return false;
}
void QmitkXnatConnectionPreferencePage::PerformCancel()
{
}
bool QmitkXnatConnectionPreferencePage::UserInformationEmpty()
{
// To check empty QLineEdits in the following
QString errString;
if (m_Controls.inXnatHostAddress->text().isEmpty())
{
errString += "Server Address is empty.\n";
}
if (m_Controls.inXnatUsername->text().isEmpty())
{
errString += "Username is empty.\n";
}
if (m_Controls.inXnatPassword->text().isEmpty())
{
errString += "Password is empty.\n";
}
// if something is empty
if (!errString.isEmpty())
{
m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red");
m_Controls.xnatTestConnectionLabel->setText("Connecting failed.\n" + errString);
return true;
}
else
{
return false;
}
}
void QmitkXnatConnectionPreferencePage::Update()
{
auto* prefs = GetPreferences();
if (prefs != nullptr)
{
m_Controls.inXnatHostAddress->setText(QString::fromStdString(prefs->Get(m_Controls.xnatHostAddressLabel->text().toStdString(), m_Controls.inXnatHostAddress->text().toStdString())));
m_Controls.inXnatPort->setText(QString::fromStdString(prefs->Get(m_Controls.xnatPortLabel->text().toStdString(), m_Controls.inXnatPort->text().toStdString())));
m_Controls.inXnatUsername->setText(QString::fromStdString(prefs->Get(m_Controls.xnatUsernameLabel->text().toStdString(), m_Controls.inXnatUsername->text().toStdString())));
m_Controls.inXnatPassword->setText(QString::fromStdString(prefs->Get(m_Controls.xnatPasswortLabel->text().toStdString(), m_Controls.inXnatPassword->text().toStdString())));
m_Controls.inXnatDownloadPath->setText(QString::fromStdString(prefs->Get(m_Controls.xnatDownloadPathLabel->text().toStdString(), m_Controls.inXnatDownloadPath->text().toStdString())));
// Network proxy settings
m_Controls.cbUseNetworkProxy->setChecked(prefs->GetBool(m_Controls.cbUseNetworkProxy->text().toStdString(), false));
m_Controls.inProxyAddress->setText(QString::fromStdString(prefs->Get(m_Controls.proxyAddressLabel->text().toStdString(), m_Controls.inProxyAddress->text().toStdString())));
m_Controls.inProxyPort->setText(QString::fromStdString(prefs->Get(m_Controls.proxyPortLabel->text().toStdString(), m_Controls.inProxyPort->text().toStdString())));
m_Controls.inProxyUsername->setText(QString::fromStdString(prefs->Get(m_Controls.proxyUsernameLabel->text().toStdString(), m_Controls.inProxyUsername->text().toStdString())));
m_Controls.inProxyPassword->setText(QString::fromStdString(prefs->Get(m_Controls.proxyPasswordLabel->text().toStdString(), m_Controls.inProxyPassword->text().toStdString())));
// Silent Mode
m_Controls.cbUseSilentMode->setChecked(prefs->GetBool(m_Controls.cbUseSilentMode->text().toStdString(), false));
}
}
void QmitkXnatConnectionPreferencePage::UrlChanged()
{
m_Controls.inXnatHostAddress->setStyleSheet("");
QString str = m_Controls.inXnatHostAddress->text();
while (str.endsWith("/"))
{
str = str.left(str.length() - 1);
}
m_Controls.inXnatHostAddress->setText(str);
QUrl url(m_Controls.inXnatHostAddress->text());
if (!url.isValid())
{
m_Controls.inXnatHostAddress->setStyleSheet("background-color: red");
}
}
void QmitkXnatConnectionPreferencePage::DownloadPathChanged()
{
m_Controls.inXnatDownloadPath->setStyleSheet("");
QString downloadPath = m_Controls.inXnatDownloadPath->text();
if (!downloadPath.isEmpty())
{
if (downloadPath.lastIndexOf("/") != downloadPath.size() - 1)
{
downloadPath.append("/");
m_Controls.inXnatDownloadPath->setText(downloadPath);
}
QFileInfo path(m_Controls.inXnatDownloadPath->text());
if (!path.isDir())
{
m_Controls.inXnatDownloadPath->setStyleSheet("background-color: red");
}
}
}
void QmitkXnatConnectionPreferencePage::onUseNetworkProxy(bool status)
{
m_Controls.groupBoxProxySettings->setVisible(status);
}
void QmitkXnatConnectionPreferencePage::OnDownloadPathButtonClicked()
{
QString dir = QFileDialog::getExistingDirectory();
if (!dir.endsWith("/") || !dir.endsWith("\\"))
dir.append("/");
m_Controls.inXnatDownloadPath->setText(dir);
}
void QmitkXnatConnectionPreferencePage::TestConnection()
{
if(UserInformationEmpty())
{
return;
}
try
{
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService(
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>());
}
catch (const std::invalid_argument &)
{
if (!UserInformationEmpty())
{
PerformOk();
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CreateXnatSession();
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService(
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>());
}
}
try
{
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->OpenXnatSession();
m_Controls.xnatTestConnectionLabel->setStyleSheet("color: green");
m_Controls.xnatTestConnectionLabel->setText("Connecting successful.");
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession();
}
catch (const ctkXnatAuthenticationException& auth)
{
m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red");
m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nAuthentication error.");
MITK_INFO << auth.message().toStdString();
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession();
}
catch (const ctkException& e)
{
m_Controls.xnatTestConnectionLabel->setStyleSheet("color: red");
m_Controls.xnatTestConnectionLabel->setText("Connecting failed:\nInvalid Server Address\nPossibly due to missing OpenSSL for HTTPS connections");
MITK_INFO << e.message().toStdString();
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatSessionManager()->CloseXnatSession();
}
}
diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp
index 20d52799b8..7d393bfb13 100644
--- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp
+++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatEditor.cpp
@@ -1,571 +1,570 @@
/*============================================================================
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 "QmitkXnatEditor.h"
// Qmitk
#include "QmitkXnatObjectEditorInput.h"
#include "org_mitk_gui_qt_xnatinterface_Activator.h"
// CTK XNAT Core
#include "ctkXnatObject.h"
#include "ctkXnatDataModel.h"
#include "ctkXnatFile.h"
#include "ctkXnatResource.h"
#include "ctkXnatScan.h"
#include "ctkXnatScanFolder.h"
#include "ctkXnatAssessor.h"
#include "ctkXnatAssessorFolder.h"
#include "ctkXnatReconstruction.h"
#include "ctkXnatReconstructionFolder.h"
// CTK XNAT Widgets
#include "ctkXnatListModel.h"
// Blueberry
#include <berryQModelIndexObject.h>
#include <berryIWorkbenchPage.h>
// Qt
#include <QListView>
-#include <QRegExp>
#include <QModelIndex>
#include <QDir>
#include <QDirIterator>
#include <QMessageBox>
// MITK
#include <mitkDataStorage.h>
#include <QmitkIOUtil.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
// Poco
#include <Poco/Zip/Decompress.h>
const QString QmitkXnatEditor::EDITOR_ID = "org.mitk.editors.xnat.browser";
QmitkXnatEditor::QmitkXnatEditor() :
m_DownloadPath(QString::fromStdString(mitk::CoreServices::GetPreferencesService()->
GetSystemPreferences()->Node("/XnatConnection")->Get("Download Path", ""))),
m_ListModel(new ctkXnatListModel()),
m_Session(0),
m_DataStorageServiceTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()),
m_SelectionListener(new berry::SelectionChangedAdapter<QmitkXnatEditor>(this, &QmitkXnatEditor::SelectionChanged))
{
m_DataStorageServiceTracker.open();
if (m_DownloadPath.isEmpty())
{
QString xnatFolder = "XNAT_DOWNLOADS";
QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath());
dir.mkdir(xnatFolder);
dir.setPath(dir.path() + "/" + xnatFolder);
m_DownloadPath = dir.path() + "/";
}
}
QmitkXnatEditor::~QmitkXnatEditor()
{
delete m_ListModel;
berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService();
s->RemoveSelectionListener(m_SelectionListener.data());
m_DataStorageServiceTracker.close();
}
bool QmitkXnatEditor::IsDirty() const
{
return false;
}
bool QmitkXnatEditor::IsSaveAsAllowed() const
{
return false;
}
void QmitkXnatEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input)
{
this->SetSite(site);
berry::QtEditorPart::SetInput(input);
this->SetInput(input);
}
void QmitkXnatEditor::DoSave()
{
}
void QmitkXnatEditor::DoSaveAs()
{
}
void QmitkXnatEditor::SetInput(berry::IEditorInput::Pointer input)
{
QmitkXnatObjectEditorInput::Pointer oPtr = input.Cast<QmitkXnatObjectEditorInput>();
if (oPtr.IsNotNull())
{
berry::QtEditorPart::SetInput(oPtr);
this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();
}
}
void QmitkXnatEditor::SetFocus()
{
}
void QmitkXnatEditor::CreateQtPartControl(QWidget *parent)
{
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi(parent);
m_Controls.buttonDownload->setEnabled(false);
m_Controls.labelDownload->setText("Select a xnat file, resource, scan, or scan folder to download...");
GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener.data());
connect(m_Controls.treeView, SIGNAL(activated(const QModelIndex&)), this, SLOT(OnObjectActivated(const QModelIndex&)));
connect(m_Controls.buttonDownload, SIGNAL(clicked()), this, SLOT(DownloadResource()));
connect(m_Controls.buttonDataModel, SIGNAL(clicked()), this, SLOT(OnDataModelButtonClicked()));
connect(m_Controls.buttonProject, SIGNAL(clicked()), this, SLOT(OnProjectButtonClicked()));
connect(m_Controls.buttonSubject, SIGNAL(clicked()), this, SLOT(OnSubjectButtonClicked()));
connect(m_Controls.buttonExperiment, SIGNAL(clicked()), this, SLOT(OnExperimentButtonClicked()));
connect(m_Controls.buttonKindOfData, SIGNAL(clicked()), this, SLOT(OnKindOfDataButtonClicked()));
connect(m_Controls.buttonSession, SIGNAL(clicked()), this, SLOT(OnSessionButtonClicked()));
connect(m_Controls.buttonResource, SIGNAL(clicked()), this, SLOT(OnResourceButtonClicked()));
connect(m_Controls.treeView, SIGNAL(clicked(const QModelIndex&)), SLOT(itemSelected(const QModelIndex&)));
m_Tracker = new mitk::XnatSessionTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext());
connect(m_Tracker, SIGNAL(AboutToBeClosed(ctkXnatSession*)), this, SLOT(CleanListModel(ctkXnatSession*)));
connect(m_Tracker, SIGNAL(Opened(ctkXnatSession*)), this, SLOT(UpdateSession(ctkXnatSession*)));
m_Tracker->Open();
// Makes the breadcrumb feature invisible
for (int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count() - 1; i++)
{
QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
child->widget()->setVisible(false);
}
for (int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count() - 1; i++)
{
QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i);
child->widget()->setVisible(false);
}
QmitkXnatObjectEditorInput::Pointer oPtr = GetEditorInput().Cast<QmitkXnatObjectEditorInput>();
if (oPtr.IsNotNull())
{
UpdateList();
}
else
{
ctkXnatSession* session;
try
{
session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetService(
mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>());
}
catch (std::invalid_argument)
{
session = 0;
}
UpdateSession(session);
}
}
void QmitkXnatEditor::UpdateList()
{
QmitkXnatObjectEditorInput::Pointer xoPtr(GetEditorInput().Cast<QmitkXnatObjectEditorInput>());
if (xoPtr.IsNull())
return;
ctkXnatObject* inputObject = xoPtr->GetXnatObject();
if (inputObject == nullptr)
return;
m_Controls.treeView->setModel(m_ListModel);
m_ListModel->setRootObject(inputObject);
m_Controls.treeView->reset();
// recursive method to check parents of the inputObject
m_ParentCount = ParentChecker(inputObject);
// breadcrumb labels
for (int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count() - 1; i++)
{
QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
child->widget()->setVisible(false);
}
for (int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count() - 1; i++)
{
QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i);
child->widget()->setVisible(false);
}
ctkXnatObject* parent = nullptr;
for (int i = m_ParentCount * 2; i >= 0; i--)
{
if (i > 12)
break;
m_Controls.breadcrumbDescriptionLayout->itemAt(i)->widget()->setVisible(true);
QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
child->widget()->setVisible(true);
if (i > 0)
{
m_Controls.breadcrumbHorizontalLayout->itemAt(i - 1)->widget()->setVisible(true);
m_Controls.breadcrumbDescriptionLayout->itemAt(i - 1)->widget()->setVisible(true);
}
if (parent == nullptr)
{
parent = inputObject;
}
// create breadcrumb button
QPushButton* breadcrumbButton = dynamic_cast<QPushButton*>(child->widget());
breadcrumbButton->setText(parent->id());
parent = parent->parent();
i--;
}
m_Controls.buttonDataModel->setText("root");
m_Controls.buttonDownload->setEnabled(false);
m_Controls.labelDownload->setVisible(true);
}
void QmitkXnatEditor::SelectionChanged(const berry::IWorkbenchPart::Pointer& sourcepart,
const berry::ISelection::ConstPointer& selection)
{
// check for null selection
if (selection.IsNull())
{
return;
}
// exclude own selection events and check whether this kind of selection can be handled
if (sourcepart != this &&
selection.Cast<const berry::IStructuredSelection>())
{
berry::IStructuredSelection::ConstPointer currentSelection = selection.Cast<const berry::IStructuredSelection>();
// iterates over the selection
for (berry::IStructuredSelection::iterator itr = currentSelection->Begin();
itr != currentSelection->End(); ++itr)
{
if (berry::SmartPointer<berry::QModelIndexObject> objectPointer = itr->Cast<berry::QModelIndexObject>())
{
// get object of selected ListWidgetElement
ctkXnatObject* object = objectPointer->GetQModelIndex().data(Qt::UserRole).value<ctkXnatObject*>();
// if a file is selected, don't change the input and list view
if (dynamic_cast<ctkXnatFile*>(object) == nullptr)
{
QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(object));
berry::IEditorInput::Pointer editorInput(oPtr);
if (!(editorInput == this->GetEditorInput()))
this->SetInput(editorInput);
UpdateList();
}
}
}
}
}
void QmitkXnatEditor::DownloadResource()
{
if (!m_Controls.listView->selectionModel()->hasSelection())
return;
const QModelIndex index = m_Controls.listView->selectionModel()->currentIndex();
QVariant variant = m_ListModel->data(index, Qt::UserRole);
if (variant.isValid())
{
ctkXnatObject* resource = variant.value<ctkXnatObject*>();
if (dynamic_cast<ctkXnatFile*>(resource) == nullptr)
{
MITK_INFO << "Download started ...";
MITK_INFO << "...";
QString resourceName = m_ListModel->data(index, Qt::DisplayRole).toString();
QString resourcePath = m_DownloadPath + resourceName + ".zip";
resource->download(resourcePath);
// Testing if the path exists
QDir downDir(m_DownloadPath);
if (downDir.exists(resourceName + ".zip"))
{
MITK_INFO << "Download of " << resourceName.toStdString() << ".zip was completed!";
}
else
{
MITK_INFO << "Download of " << resourceName.toStdString() << ".zip failed!";
}
}
else
{
InternalFileDownload(index);
}
}
}
void QmitkXnatEditor::DownloadFile()
{
if (!m_Controls.listView->selectionModel()->hasSelection())
return;
const QModelIndex index = m_Controls.listView->selectionModel()->currentIndex();
InternalFileDownload(index);
}
void QmitkXnatEditor::ToHigherLevel()
{
ctkXnatObject* parent = GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->parent();
if (parent == nullptr)
{
return;
}
QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(parent));
berry::IEditorInput::Pointer editorInput(oPtr);
this->SetInput(editorInput);
UpdateList();
}
void QmitkXnatEditor::OnObjectActivated(const QModelIndex &index)
{
if (!index.isValid()) return;
ctkXnatObject* child = GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->children().at(index.row());
if (child != nullptr)
{
ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(child);
if (file != nullptr)
{
// Download file and put into datamanager
InternalFileDownload(index);
mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService();
if (dsService != nullptr)
{
QString name = file->property("Name");
QString filePath = m_DownloadPath + name;
if (file->property("collection") == "DICOM")
{
QDirIterator it(m_DownloadPath, QStringList() << name, QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()) {
it.next();
filePath = it.filePath();
}
}
mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService();
mitk::DataStorage::Pointer dataStorage = dsService->GetDataStorage()->GetDataStorage();
QStringList list;
list << filePath;
try
{
QmitkIOUtil::Load(list, *dataStorage);
}
catch (const mitk::Exception& e)
{
MITK_INFO << e;
return;
}
mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(
dsService->GetDataStorage()->GetDataStorage());
}
}
else
{
// Updates the root item
QmitkXnatObjectEditorInput::Pointer oPtr(new QmitkXnatObjectEditorInput(child));
berry::IEditorInput::Pointer editorInput(oPtr);
this->SetInput(editorInput);
this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();
UpdateList();
}
}
}
void QmitkXnatEditor::InternalFileDownload(const QModelIndex& index)
{
QVariant variant = m_ListModel->data(index, Qt::UserRole);
if (variant.isValid())
{
ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(variant.value<ctkXnatObject*>());
if (file != nullptr)
{
// Testing if the file exists
QDir downDir(m_DownloadPath);
if (downDir.exists(file->property("Name")))
{
MITK_INFO << "File exists already!";
return;
}
if (file->property("collection") == QString("DICOM"))
{
ctkXnatObject* parent = file->parent();
QString filePath = m_DownloadPath + parent->property("label") + ".zip";
parent->download(filePath);
std::ifstream in(filePath.toStdString().c_str(), std::ios::binary);
poco_assert(in);
// decompress to XNAT_DOWNLOAD dir
Poco::Zip::Decompress dec(in, Poco::Path(m_DownloadPath.toStdString()));
dec.decompressAllFiles();
in.close();
QFile::remove(filePath);
}
else
{
MITK_INFO << "Download started ...";
MITK_INFO << "...";
QString name = file->property("Name");
QString filePath = m_DownloadPath + name;
file->download(filePath);
// Testing if the file exists
QDir downDir(m_DownloadPath);
if (downDir.exists(name))
{
MITK_INFO << "Download of " << file->name().toStdString() << " was completed!";
}
else
{
MITK_INFO << "Download of " << file->name().toStdString() << " failed!";
}
}
}
else
{
MITK_INFO << "Selection was not a file!";
}
}
}
int QmitkXnatEditor::ParentChecker(ctkXnatObject* child)
{
int sum;
if (child->parent() == nullptr)
{
return 0;
}
else
{
sum = 1 + ParentChecker(child->parent());
}
return sum;
}
void QmitkXnatEditor::OnDataModelButtonClicked()
{
for (int i = m_ParentCount; i > 0; i--)
{
ToHigherLevel();
}
}
void QmitkXnatEditor::OnProjectButtonClicked()
{
for (int i = m_ParentCount - 1; i > 0; i--)
{
ToHigherLevel();
}
}
void QmitkXnatEditor::OnSubjectButtonClicked()
{
for (int i = m_ParentCount - 2; i > 0; i--)
{
ToHigherLevel();
}
}
void QmitkXnatEditor::OnExperimentButtonClicked()
{
for (int i = m_ParentCount - 3; i > 0; i--)
{
ToHigherLevel();
}
}
void QmitkXnatEditor::OnKindOfDataButtonClicked()
{
for (int i = m_ParentCount - 4; i > 0; i--)
{
ToHigherLevel();
}
}
void QmitkXnatEditor::OnSessionButtonClicked()
{
for (int i = m_ParentCount - 5; i > 0; i--)
{
ToHigherLevel();
}
}
void QmitkXnatEditor::OnResourceButtonClicked()
{
for (int i = m_ParentCount - 6; i > 0; i--)
{
ToHigherLevel();
}
}
void QmitkXnatEditor::UpdateSession(ctkXnatSession* session)
{
GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener.data());
if (session != 0 && session->isOpen())
{
m_Controls.labelInfo->setText("Current Position:");
m_Controls.labelInfo->setStyleSheet("QLabel { color: black; }");
// Fill model and show in the GUI
QmitkXnatObjectEditorInput::Pointer xoPtr(new QmitkXnatObjectEditorInput(session->dataModel()));
berry::IEditorInput::Pointer editorInput(xoPtr);
this->SetInput(editorInput);
this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();
UpdateList();
}
else
{
m_Controls.labelInfo->setText("Please check the Preferences of the XNAT Connection.\nMaybe they are not ok.");
m_Controls.labelInfo->setStyleSheet("QLabel { color: red; }");
}
GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener.data());
}
void QmitkXnatEditor::CleanListModel(ctkXnatSession* session)
{
if (session != 0)
{
m_Controls.listView->setModel(0);
m_ListModel->setRootObject(0);
m_Controls.treeView->reset();
}
}
void QmitkXnatEditor::itemSelected(const QModelIndex &index)
{
ctkXnatObject* xnatObject = m_ListModel->data(index, Qt::UserRole).value<ctkXnatObject*>();
bool downloadable = false;
downloadable |= dynamic_cast<ctkXnatFile*>(xnatObject) != nullptr;
downloadable |= dynamic_cast<ctkXnatScan*>(xnatObject) != nullptr;
downloadable |= dynamic_cast<ctkXnatScanFolder*>(xnatObject) != nullptr;
downloadable |= dynamic_cast<ctkXnatAssessor*>(xnatObject) != nullptr;
downloadable |= dynamic_cast<ctkXnatAssessorFolder*>(xnatObject) != nullptr;
downloadable |= dynamic_cast<ctkXnatResource*>(xnatObject) != nullptr;
downloadable |= dynamic_cast<ctkXnatReconstruction*>(xnatObject) != nullptr;
downloadable |= dynamic_cast<ctkXnatReconstructionFolder*>(xnatObject) != nullptr;
m_Controls.buttonDownload->setEnabled(downloadable);
m_Controls.labelDownload->setVisible(!downloadable);
}
diff --git a/Plugins/org.mitk.matchpoint.core.helper/CMakeLists.txt b/Plugins/org.mitk.matchpoint.core.helper/CMakeLists.txt
index 112a65a0f1..f44e3a3752 100644
--- a/Plugins/org.mitk.matchpoint.core.helper/CMakeLists.txt
+++ b/Plugins/org.mitk.matchpoint.core.helper/CMakeLists.txt
@@ -1,8 +1,8 @@
project(org_mitk_matchpoint_core_helper)
mitk_create_plugin(
EXPORT_DIRECTIVE MITK_MATCHPOINT_CORE_HELPER_EXPORT
EXPORTED_INCLUDE_SUFFIXES src
MODULE_DEPENDS MitkQtWidgets MitkQtWidgetsExt MitkMatchPointRegistration
- PACKAGE_DEPENDS Qt5|UiTools
+ PACKAGE_DEPENDS Qt6|UiTools
)
diff --git a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp
index e330be3d14..d759e669c0 100644
--- a/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp
+++ b/Plugins/org.mitk.matchpoint.core.helper/src/internal/MatchPointBrowserPreferencesPage.cpp
@@ -1,158 +1,158 @@
/*============================================================================
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 "MatchPointBrowserPreferencesPage.h"
#include "MatchPointBrowserConstants.h"
#include <QWidget>
#include <QLabel>
#include <QFormLayout>
#include <QCheckBox>
#include <QComboBox>
#include <QMessageBox>
#include <QSpinBox>
#include <ctkDirectoryButton.h>
#include <mitkCoreServices.h>
#include <mitkIPreferencesService.h>
#include <mitkIPreferences.h>
#include "QmitkDirectoryListWidget.h"
#include "QmitkFileListWidget.h"
namespace
{
mitk::IPreferences* GetPreferences()
{
auto* preferencesService = mitk::CoreServices::GetPreferencesService();
return preferencesService->GetSystemPreferences()->Node(MatchPointBrowserConstants::VIEW_ID);
}
}
//-----------------------------------------------------------------------------
MatchPointBrowserPreferencesPage::MatchPointBrowserPreferencesPage()
: m_MainControl(nullptr)
, m_AlgDirectories(nullptr)
, m_AlgFiles(nullptr)
, m_LoadFromHomeDir(nullptr)
, m_LoadFromCurrentDir(nullptr)
, m_LoadFromApplicationDir(nullptr)
, m_LoadFromAutoLoadPathDir(nullptr)
{
}
//-----------------------------------------------------------------------------
MatchPointBrowserPreferencesPage::~MatchPointBrowserPreferencesPage()
{
}
//-----------------------------------------------------------------------------
void MatchPointBrowserPreferencesPage::Init(berry::IWorkbench::Pointer )
{
}
//-----------------------------------------------------------------------------
void MatchPointBrowserPreferencesPage::CreateQtControl(QWidget* parent)
{
m_MainControl = new QWidget(parent);
m_AlgDirectories = new QmitkDirectoryListWidget(m_MainControl);
m_AlgDirectories->m_Label->setText("Select directories to scan:");
m_AlgFiles = new QmitkFileListWidget(m_MainControl);
m_AlgFiles->m_Label->setText("Select additional executables:");
m_DebugOutput = new QCheckBox(m_MainControl);
m_LoadFromAutoLoadPathDir = new QCheckBox(m_MainControl);
m_LoadFromApplicationDir = new QCheckBox(m_MainControl);
m_LoadFromHomeDir = new QCheckBox(m_MainControl);
m_LoadFromCurrentDir = new QCheckBox(m_MainControl);
QFormLayout *formLayout = new QFormLayout;
formLayout->addRow("show debug output:", m_DebugOutput);
formLayout->addRow("scan home directory:", m_LoadFromHomeDir);
formLayout->addRow("scan current directory:", m_LoadFromCurrentDir);
formLayout->addRow("scan installation directory:", m_LoadFromApplicationDir);
formLayout->addRow("scan MAP_MDRA_LOAD_PATH:", m_LoadFromAutoLoadPathDir);
formLayout->addRow("additional algorithm directories:", m_AlgDirectories);
formLayout->addRow("additional algorithms:", m_AlgFiles);
m_MainControl->setLayout(formLayout);
this->Update();
}
//-----------------------------------------------------------------------------
QWidget* MatchPointBrowserPreferencesPage::GetQtControl() const
{
return m_MainControl;
}
//-----------------------------------------------------------------------------
std::string MatchPointBrowserPreferencesPage::ConvertToString( const QStringList& list )
{
return list.join(';').toStdString();
}
//-----------------------------------------------------------------------------
bool MatchPointBrowserPreferencesPage::PerformOk()
{
auto* prefs = GetPreferences();
prefs->PutBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME, m_DebugOutput->isChecked());
prefs->PutBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, m_LoadFromApplicationDir->isChecked());
prefs->PutBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, m_LoadFromHomeDir->isChecked());
prefs->PutBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, m_LoadFromCurrentDir->isChecked());
prefs->PutBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, m_LoadFromAutoLoadPathDir->isChecked());
const auto paths = this->ConvertToString(m_AlgDirectories->directories());
prefs->Put(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, paths);
const auto modules = this->ConvertToString(m_AlgFiles->files());
prefs->Put(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, modules);
return true;
}
//-----------------------------------------------------------------------------
void MatchPointBrowserPreferencesPage::PerformCancel()
{
}
//-----------------------------------------------------------------------------
void MatchPointBrowserPreferencesPage::Update()
{
auto* prefs = GetPreferences();
m_DebugOutput->setChecked(prefs->GetBool(MatchPointBrowserConstants::DEBUG_OUTPUT_NODE_NAME, false));
m_LoadFromApplicationDir->setChecked(prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_APPLICATION_DIR, true));
m_LoadFromHomeDir->setChecked(prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_HOME_DIR, false));
m_LoadFromCurrentDir->setChecked(prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_CURRENT_DIR, false));
m_LoadFromAutoLoadPathDir->setChecked(prefs->GetBool(MatchPointBrowserConstants::LOAD_FROM_AUTO_LOAD_DIR, false));
QString paths = QString::fromStdString(prefs->Get(MatchPointBrowserConstants::MDAR_DIRECTORIES_NODE_NAME, ""));
- QStringList directoryList = paths.split(";", QString::SkipEmptyParts);
+ QStringList directoryList = paths.split(";", Qt::SkipEmptyParts);
m_AlgDirectories->setDirectories(directoryList);
QString files = QString::fromStdString(prefs->Get(MatchPointBrowserConstants::MDAR_FILES_NODE_NAME, ""));
- QStringList fileList = files.split(";", QString::SkipEmptyParts);
+ QStringList fileList = files.split(";", Qt::SkipEmptyParts);
m_AlgFiles->setFiles(fileList);
}
diff --git a/SuperBuild.cmake b/SuperBuild.cmake
index c02d3fc7b3..bd06fe812e 100644
--- a/SuperBuild.cmake
+++ b/SuperBuild.cmake
@@ -1,502 +1,508 @@
#-----------------------------------------------------------------------------
# Convenient macro allowing to download a file
#-----------------------------------------------------------------------------
if(NOT MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL)
set(MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL https://www.mitk.org/download/thirdparty)
endif()
macro(downloadFile url dest)
file(DOWNLOAD ${url} ${dest} STATUS status)
list(GET status 0 error_code)
list(GET status 1 error_msg)
if(error_code)
message(FATAL_ERROR "error: Failed to download ${url} - ${error_msg}")
endif()
endmacro()
#-----------------------------------------------------------------------------
# MITK Prerequisites
#-----------------------------------------------------------------------------
if(UNIX AND NOT APPLE)
include(mitkFunctionCheckPackageHeader)
# Check for libxt-dev
mitkFunctionCheckPackageHeader(StringDefs.h libxt-dev /usr/include/X11/)
# Check for libtiff4-dev
mitkFunctionCheckPackageHeader(tiff.h libtiff4-dev)
endif()
# We need a proper patch program. On Linux and MacOS, we assume
# that "patch" is available. On Windows, we download patch.exe
# if not patch program is found.
find_program(PATCH_COMMAND patch)
if((NOT PATCH_COMMAND OR NOT EXISTS ${PATCH_COMMAND}) AND WIN32)
downloadFile(${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/patch.exe
${CMAKE_CURRENT_BINARY_DIR}/patch.exe)
find_program(PATCH_COMMAND patch ${CMAKE_CURRENT_BINARY_DIR})
endif()
if(NOT PATCH_COMMAND)
message(FATAL_ERROR "No patch program found.")
endif()
#-----------------------------------------------------------------------------
# ExternalProjects
#-----------------------------------------------------------------------------
get_property(external_projects GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS)
if(MITK_CTEST_SCRIPT_MODE)
# Write a file containing the list of enabled external project targets.
# This file can be read by a ctest script to separately build projects.
set(SUPERBUILD_TARGETS )
foreach(proj ${external_projects})
if(MITK_USE_${proj})
list(APPEND SUPERBUILD_TARGETS ${proj})
endif()
endforeach()
file(WRITE "${CMAKE_BINARY_DIR}/SuperBuildTargets.cmake" "set(SUPERBUILD_TARGETS ${SUPERBUILD_TARGETS})")
endif()
# A list of "nice" external projects, playing well together with CMake
set(nice_external_projects ${external_projects})
list(REMOVE_ITEM nice_external_projects Boost)
foreach(proj ${nice_external_projects})
if(MITK_USE_${proj})
set(EXTERNAL_${proj}_DIR "${${proj}_DIR}" CACHE PATH "Path to ${proj} build directory")
mark_as_advanced(EXTERNAL_${proj}_DIR)
if(EXTERNAL_${proj}_DIR)
set(${proj}_DIR ${EXTERNAL_${proj}_DIR})
endif()
endif()
endforeach()
set(EXTERNAL_Boost_ROOT "${Boost_ROOT}" CACHE PATH "Path to Boost directory")
mark_as_advanced(EXTERNAL_Boost_ROOT)
if(EXTERNAL_Boost_ROOT)
set(Boost_ROOT ${EXTERNAL_Boost_ROOT})
endif()
if(BUILD_TESTING)
set(EXTERNAL_MITK_DATA_DIR "${MITK_DATA_DIR}" CACHE PATH "Path to the MITK data directory")
mark_as_advanced(EXTERNAL_MITK_DATA_DIR)
if(EXTERNAL_MITK_DATA_DIR)
set(MITK_DATA_DIR ${EXTERNAL_MITK_DATA_DIR})
endif()
endif()
#-----------------------------------------------------------------------------
# External project settings
#-----------------------------------------------------------------------------
include(ExternalProject)
include(mitkMacroQueryCustomEPVars)
include(mitkFunctionInstallExternalCMakeProject)
include(mitkFunctionCleanExternalProject)
option(MITK_AUTOCLEAN_EXTERNAL_PROJECTS "Experimental: Clean external project builds if updated" ON)
set(ep_prefix "${CMAKE_BINARY_DIR}/ep")
set_property(DIRECTORY PROPERTY EP_PREFIX ${ep_prefix})
# Compute -G arg for configuring external projects with the same CMake generator:
if(CMAKE_EXTRA_GENERATOR)
set(gen "${CMAKE_EXTRA_GENERATOR} - ${CMAKE_GENERATOR}")
else()
set(gen "${CMAKE_GENERATOR}")
endif()
set(gen_platform ${CMAKE_GENERATOR_PLATFORM})
# Use this value where semi-colons are needed in ep_add args:
set(sep "^^")
##
if(MSVC_VERSION)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /bigobj /MP")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj /MP")
endif()
# This is a workaround for passing linker flags
# actually down to the linker invocation
set(_cmake_required_flags_orig ${CMAKE_REQUIRED_FLAGS})
set(CMAKE_REQUIRED_FLAGS "-Wl,-rpath")
mitkFunctionCheckCompilerFlags(${CMAKE_REQUIRED_FLAGS} _has_rpath_flag)
set(CMAKE_REQUIRED_FLAGS ${_cmake_required_flags_orig})
set(_install_rpath_linkflag )
if(_has_rpath_flag)
if(APPLE)
set(_install_rpath_linkflag "-Wl,-rpath,@loader_path/../lib")
else()
- set(_install_rpath_linkflag "-Wl,-rpath='$ORIGIN/../lib'")
+ set(_install_rpath_linkflag "-Wl,-rpath='$ORIGIN/../lib")
+ if(Qt6_DIR)
+ set(_install_rpath_linkflag "${_install_rpath_linkflag}:${Qt6_DIR}/../..")
+ endif()
+ set(_install_rpath_linkflag "${_install_rpath_linkflag}'")
endif()
endif()
set(_install_rpath)
if(APPLE)
set(_install_rpath "@loader_path/../lib")
elseif(UNIX)
# this work for libraries as well as executables
set(_install_rpath "\$ORIGIN/../lib")
+ if(Qt6_DIR)
+ set(_install_rpath "${_install_rpath}:${Qt6_DIR}/../..")
+ endif()
endif()
set(ep_common_args
-DCMAKE_POLICY_DEFAULT_CMP0091:STRING=OLD
-DCMAKE_CXX_EXTENSIONS:STRING=${CMAKE_CXX_EXTENSIONS}
-DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD}
-DCMAKE_CXX_STANDARD_REQUIRED:BOOL=${CMAKE_CXX_STANDARD_REQUIRED}
-DCMAKE_MACOSX_RPATH:BOOL=TRUE
"-DCMAKE_INSTALL_RPATH:STRING=${_install_rpath}"
-DBUILD_TESTING:BOOL=OFF
-DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
-DBUILD_SHARED_LIBS:BOOL=ON
-DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}
-DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER}
-DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER}
-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS}
"-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} ${MITK_CXX${MITK_CXX_STANDARD}_FLAG}"
#debug flags
-DCMAKE_CXX_FLAGS_DEBUG:STRING=${CMAKE_CXX_FLAGS_DEBUG}
-DCMAKE_C_FLAGS_DEBUG:STRING=${CMAKE_C_FLAGS_DEBUG}
#release flags
-DCMAKE_CXX_FLAGS_RELEASE:STRING=${CMAKE_CXX_FLAGS_RELEASE}
-DCMAKE_C_FLAGS_RELEASE:STRING=${CMAKE_C_FLAGS_RELEASE}
#relwithdebinfo
-DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_CXX_FLAGS_RELWITHDEBINFO}
-DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_C_FLAGS_RELWITHDEBINFO}
#link flags
-DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS}
-DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS}
-DCMAKE_MODULE_LINKER_FLAGS:STRING=${CMAKE_MODULE_LINKER_FLAGS}
)
if(MSVC_VERSION)
list(APPEND ep_common_args
-DCMAKE_DEBUG_POSTFIX:STRING=d
)
set(DCMTK_CMAKE_DEBUG_POSTFIX d)
endif()
set(ep_common_cache_args
)
set(ep_common_cache_default_args
"-DCMAKE_PREFIX_PATH:PATH=<INSTALL_DIR>;${CMAKE_PREFIX_PATH}"
"-DCMAKE_INCLUDE_PATH:PATH=${CMAKE_INCLUDE_PATH}"
"-DCMAKE_LIBRARY_PATH:PATH=${CMAKE_LIBRARY_PATH}"
)
# Pass the CMAKE_OSX variables to external projects
if(APPLE)
set(MAC_OSX_ARCHITECTURE_ARGS
-DCMAKE_OSX_ARCHITECTURES:PATH=${CMAKE_OSX_ARCHITECTURES}
-DCMAKE_OSX_DEPLOYMENT_TARGET:PATH=${CMAKE_OSX_DEPLOYMENT_TARGET}
-DCMAKE_OSX_SYSROOT:PATH=${CMAKE_OSX_SYSROOT}
)
set(ep_common_args
${MAC_OSX_ARCHITECTURE_ARGS}
${ep_common_args}
)
endif()
set(mitk_superbuild_ep_args)
set(mitk_depends )
# Include external projects
include(CMakeExternals/MITKData.cmake)
foreach(p ${external_projects})
set(p_hash "")
set(p_file "${CMAKE_SOURCE_DIR}/CMakeExternals/${p}.cmake")
if(EXISTS ${p_file})
file(MD5 ${p_file} p_hash)
else()
foreach(MITK_EXTENSION_DIR ${MITK_ABSOLUTE_EXTENSION_DIRS})
set(MITK_CMAKE_EXTERNALS_EXTENSION_DIR "${MITK_EXTENSION_DIR}/CMakeExternals")
set(p_file "${MITK_CMAKE_EXTERNALS_EXTENSION_DIR}/${p}.cmake")
if(EXISTS "${p_file}")
file(MD5 "${p_file}" p_hash)
break()
endif()
endforeach()
endif()
if(p_hash)
set(p_hash_file "${ep_prefix}/tmp/${p}-hash.txt")
if(MITK_AUTOCLEAN_EXTERNAL_PROJECTS)
if(EXISTS "${p_hash_file}")
file(READ "${p_hash_file}" p_prev_hash)
if(NOT p_hash STREQUAL p_prev_hash)
mitkCleanExternalProject(${p})
endif()
endif()
endif()
file(WRITE "${p_hash_file}" ${p_hash})
endif()
include("${p_file}" OPTIONAL)
list(APPEND mitk_superbuild_ep_args
-DMITK_USE_${p}:BOOL=${MITK_USE_${p}}
)
get_property(_package GLOBAL PROPERTY MITK_${p}_PACKAGE)
if(_package)
list(APPEND mitk_superbuild_ep_args -D${p}_DIR:PATH=${${p}_DIR})
endif()
list(APPEND mitk_depends ${${p}_DEPENDS})
endforeach()
if (SWIG_EXECUTABLE)
list(APPEND mitk_superbuild_ep_args -DSWIG_EXECUTABLE=${SWIG_EXECUTABLE})
endif()
#-----------------------------------------------------------------------------
# Set superbuild boolean args
#-----------------------------------------------------------------------------
set(mitk_cmake_boolean_args
BUILD_SHARED_LIBS
WITH_COVERAGE
BUILD_TESTING
MITK_BUILD_ALL_PLUGINS
MITK_BUILD_ALL_APPS
MITK_BUILD_EXAMPLES
- MITK_USE_Qt5
+ MITK_USE_Qt6
MITK_USE_SYSTEM_Boost
MITK_USE_BLUEBERRY
- MITK_USE_OpenCL
MITK_USE_OpenMP
)
#-----------------------------------------------------------------------------
# Create the final variable containing superbuild boolean args
#-----------------------------------------------------------------------------
set(mitk_superbuild_boolean_args)
foreach(mitk_cmake_arg ${mitk_cmake_boolean_args})
list(APPEND mitk_superbuild_boolean_args -D${mitk_cmake_arg}:BOOL=${${mitk_cmake_arg}})
endforeach()
if(MITK_BUILD_ALL_PLUGINS)
list(APPEND mitk_superbuild_boolean_args -DBLUEBERRY_BUILD_ALL_PLUGINS:BOOL=ON)
endif()
#-----------------------------------------------------------------------------
# MITK Utilities
#-----------------------------------------------------------------------------
set(proj MITK-Utilities)
ExternalProject_Add(${proj}
DOWNLOAD_COMMAND ""
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
DEPENDS
${mitk_depends}
)
#-----------------------------------------------------------------------------
# Additional MITK CXX/C Flags
#-----------------------------------------------------------------------------
set(MITK_ADDITIONAL_C_FLAGS "" CACHE STRING "Additional C Flags for MITK")
set(MITK_ADDITIONAL_C_FLAGS_RELEASE "" CACHE STRING "Additional Release C Flags for MITK")
set(MITK_ADDITIONAL_C_FLAGS_DEBUG "" CACHE STRING "Additional Debug C Flags for MITK")
mark_as_advanced(MITK_ADDITIONAL_C_FLAGS MITK_ADDITIONAL_C_FLAGS_DEBUG MITK_ADDITIONAL_C_FLAGS_RELEASE)
set(MITK_ADDITIONAL_CXX_FLAGS "" CACHE STRING "Additional CXX Flags for MITK")
set(MITK_ADDITIONAL_CXX_FLAGS_RELEASE "" CACHE STRING "Additional Release CXX Flags for MITK")
set(MITK_ADDITIONAL_CXX_FLAGS_DEBUG "" CACHE STRING "Additional Debug CXX Flags for MITK")
mark_as_advanced(MITK_ADDITIONAL_CXX_FLAGS MITK_ADDITIONAL_CXX_FLAGS_DEBUG MITK_ADDITIONAL_CXX_FLAGS_RELEASE)
set(MITK_ADDITIONAL_EXE_LINKER_FLAGS "" CACHE STRING "Additional exe linker flags for MITK")
set(MITK_ADDITIONAL_SHARED_LINKER_FLAGS "" CACHE STRING "Additional shared linker flags for MITK")
set(MITK_ADDITIONAL_MODULE_LINKER_FLAGS "" CACHE STRING "Additional module linker flags for MITK")
mark_as_advanced(MITK_ADDITIONAL_EXE_LINKER_FLAGS MITK_ADDITIONAL_SHARED_LINKER_FLAGS MITK_ADDITIONAL_MODULE_LINKER_FLAGS)
#-----------------------------------------------------------------------------
# MITK Configure
#-----------------------------------------------------------------------------
if(MITK_INITIAL_CACHE_FILE)
set(mitk_initial_cache_arg -C "${MITK_INITIAL_CACHE_FILE}")
endif()
set(mitk_optional_cache_args )
foreach(type RUNTIME ARCHIVE LIBRARY)
if(DEFINED CTK_PLUGIN_${type}_OUTPUT_DIRECTORY)
list(APPEND mitk_optional_cache_args -DCTK_PLUGIN_${type}_OUTPUT_DIRECTORY:PATH=${CTK_PLUGIN_${type}_OUTPUT_DIRECTORY})
endif()
endforeach()
if(MITK_USE_OpenCV)
list(APPEND mitk_optional_cache_args "-DCMAKE_CONFIGURATION_TYPES:STRING=Debug$<SEMICOLON>Release")
endif()
# Optional python variables
if(MITK_USE_Python3)
list(APPEND mitk_optional_cache_args
-DMITK_USE_Python3:BOOL=${MITK_USE_Python3}
"-DPython3_EXECUTABLE:FILEPATH=${Python3_EXECUTABLE}"
"-DPython3_INCLUDE_DIR:PATH=${Python3_INCLUDE_DIRS}"
"-DPython3_LIBRARY:FILEPATH=${Python3_LIBRARY}"
"-DPython3_STDLIB:FILEPATH=${Python3_STDLIB}"
"-DPython3_SITELIB:FILEPATH=${Python3_SITELIB}"
)
endif()
if(OPENSSL_ROOT_DIR)
list(APPEND mitk_optional_cache_args
"-DOPENSSL_ROOT_DIR:PATH=${OPENSSL_ROOT_DIR}"
)
endif()
if(CMAKE_FRAMEWORK_PATH)
list(APPEND mitk_optional_cache_args
"-DCMAKE_FRAMEWORK_PATH:PATH=${CMAKE_FRAMEWORK_PATH}"
)
endif()
if(Eigen_INCLUDE_DIR)
list(APPEND mitk_optional_cache_args
-DEigen_INCLUDE_DIR:PATH=${Eigen_INCLUDE_DIR}
)
endif()
# Optional pass through of Doxygen
if(DOXYGEN_EXECUTABLE)
list(APPEND mitk_optional_cache_args
-DDOXYGEN_EXECUTABLE:FILEPATH=${DOXYGEN_EXECUTABLE}
)
endif()
if(MITK_DOXYGEN_BUILD_ALWAYS)
list(APPEND mitk_optional_cache_args
-DMITK_DOXYGEN_BUILD_ALWAYS:BOOL=${MITK_DOXYGEN_BUILD_ALWAYS}
)
endif()
set(proj MITK-Configure)
ExternalProject_Add(${proj}
LIST_SEPARATOR ${sep}
DOWNLOAD_COMMAND ""
CMAKE_GENERATOR ${gen}
CMAKE_GENERATOR_PLATFORM ${gen_platform}
CMAKE_CACHE_ARGS
# --------------- Build options ----------------
-DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_INSTALL_PREFIX}
-DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}
"-DCMAKE_PREFIX_PATH:PATH=${ep_prefix};${CMAKE_PREFIX_PATH}"
"-DCMAKE_LIBRARY_PATH:PATH=${CMAKE_LIBRARY_PATH}"
"-DCMAKE_INCLUDE_PATH:PATH=${CMAKE_INCLUDE_PATH}"
# --------------- Compile options ----------------
-DCMAKE_CXX_EXTENSIONS:STRING=${CMAKE_CXX_EXTENSIONS}
-DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD}
-DCMAKE_CXX_STANDARD_REQUIRED:BOOL=${CMAKE_CXX_STANDARD_REQUIRED}
-DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER}
-DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER}
"-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} ${MITK_ADDITIONAL_C_FLAGS}"
"-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} ${MITK_ADDITIONAL_CXX_FLAGS}"
# debug flags
"-DCMAKE_CXX_FLAGS_DEBUG:STRING=${CMAKE_CXX_FLAGS_DEBUG} ${MITK_ADDITIONAL_CXX_FLAGS_DEBUG}"
"-DCMAKE_C_FLAGS_DEBUG:STRING=${CMAKE_C_FLAGS_DEBUG} ${MITK_ADDITIONAL_C_FLAGS_DEBUG}"
# release flags
"-DCMAKE_CXX_FLAGS_RELEASE:STRING=${CMAKE_CXX_FLAGS_RELEASE} ${MITK_ADDITIONAL_CXX_FLAGS_RELEASE}"
"-DCMAKE_C_FLAGS_RELEASE:STRING=${CMAKE_C_FLAGS_RELEASE} ${MITK_ADDITIONAL_C_FLAGS_RELEASE}"
# relwithdebinfo
-DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_CXX_FLAGS_RELWITHDEBINFO}
-DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_C_FLAGS_RELWITHDEBINFO}
# link flags
"-DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS} ${MITK_ADDITIONAL_EXE_LINKER_FLAGS}"
"-DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS} ${MITK_ADDITIONAL_SHARED_LINKER_FLAGS}"
"-DCMAKE_MODULE_LINKER_FLAGS:STRING=${CMAKE_MODULE_LINKER_FLAGS} ${MITK_ADDITIONAL_MODULE_LINKER_FLAGS}"
# Output directories
-DMITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY}
-DMITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY}
-DMITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY}
# ------------- Boolean build options --------------
${mitk_superbuild_boolean_args}
${mitk_optional_cache_args}
-DMITK_USE_SUPERBUILD:BOOL=OFF
-DMITK_BUILD_CONFIGURATION:STRING=${MITK_BUILD_CONFIGURATION}
-DMITK_FAST_TESTING:BOOL=${MITK_FAST_TESTING}
-DMITK_XVFB_TESTING:BOOL=${MITK_XVFB_TESTING}
-DMITK_XVFB_TESTING_COMMAND:STRING=${MITK_XVFB_TESTING_COMMAND}
-DCTEST_USE_LAUNCHERS:BOOL=${CTEST_USE_LAUNCHERS}
# ----------------- Miscellaneous ---------------
-DCMAKE_LIBRARY_PATH:PATH=${CMAKE_LIBRARY_PATH}
-DCMAKE_INCLUDE_PATH:PATH=${CMAKE_INCLUDE_PATH}
-DMITK_CTEST_SCRIPT_MODE:STRING=${MITK_CTEST_SCRIPT_MODE}
-DMITK_SUPERBUILD_BINARY_DIR:PATH=${MITK_BINARY_DIR}
-DMITK_MODULES_TO_BUILD:INTERNAL=${MITK_MODULES_TO_BUILD}
-DMITK_WHITELIST:STRING=${MITK_WHITELIST}
-DMITK_WHITELISTS_EXTERNAL_PATH:STRING=${MITK_WHITELISTS_EXTERNAL_PATH}
-DMITK_WHITELISTS_INTERNAL_PATH:STRING=${MITK_WHITELISTS_INTERNAL_PATH}
-DMITK_EXTENSION_DIRS:STRING=${MITK_EXTENSION_DIRS}
-DMITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES}
-DMITK_ACCESSBYITK_FLOATING_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES}
-DMITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES}
-DMITK_ACCESSBYITK_VECTOR_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}
-DMITK_ACCESSBYITK_DIMENSIONS:STRING=${MITK_ACCESSBYITK_DIMENSIONS}
-DMITK_CUSTOM_REVISION_DESC:STRING=${MITK_CUSTOM_REVISION_DESC}
# --------------- External project options ---------------
-DMITK_DATA_DIR:PATH=${MITK_DATA_DIR}
-DMITK_EXTERNAL_PROJECT_PREFIX:PATH=${ep_prefix}
-DCppMicroServices_DIR:PATH=${CppMicroServices_DIR}
-DDCMTK_CMAKE_DEBUG_POSTFIX:STRING=${DCMTK_CMAKE_DEBUG_POSTFIX}
-DBoost_ROOT:PATH=${Boost_ROOT}
-DBOOST_LIBRARYDIR:PATH=${BOOST_LIBRARYDIR}
-DMITK_USE_Boost_LIBRARIES:STRING=${MITK_USE_Boost_LIBRARIES}
- -DQt5_DIR:PATH=${Qt5_DIR}
+ -DQt6_DIR:PATH=${Qt6_DIR}
CMAKE_ARGS
${mitk_initial_cache_arg}
${MAC_OSX_ARCHITECTURE_ARGS}
${mitk_superbuild_ep_args}
SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}
BINARY_DIR ${CMAKE_BINARY_DIR}/MITK-build
BUILD_COMMAND ""
INSTALL_COMMAND ""
DEPENDS
MITK-Utilities
)
mitkFunctionInstallExternalCMakeProject(${proj})
#-----------------------------------------------------------------------------
# MITK
#-----------------------------------------------------------------------------
if(CMAKE_GENERATOR MATCHES ".*Makefiles.*")
set(mitk_build_cmd "$(MAKE)")
else()
set(mitk_build_cmd ${CMAKE_COMMAND} --build ${CMAKE_CURRENT_BINARY_DIR}/MITK-build --config ${CMAKE_CFG_INTDIR})
endif()
if(NOT DEFINED SUPERBUILD_EXCLUDE_MITKBUILD_TARGET OR NOT SUPERBUILD_EXCLUDE_MITKBUILD_TARGET)
set(MITKBUILD_TARGET_ALL_OPTION "ALL")
else()
set(MITKBUILD_TARGET_ALL_OPTION "")
endif()
add_custom_target(MITK-build ${MITKBUILD_TARGET_ALL_OPTION}
COMMAND ${mitk_build_cmd}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/MITK-build
DEPENDS MITK-Configure
)
#-----------------------------------------------------------------------------
# Custom target allowing to drive the build of the MITK project itself
#-----------------------------------------------------------------------------
add_custom_target(MITK
COMMAND ${mitk_build_cmd}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/MITK-build
)
diff --git a/Utilities/qtsingleapplication/CMakeLists.txt b/Utilities/qtsingleapplication/CMakeLists.txt
index 39670bc08d..dca6fe58cb 100644
--- a/Utilities/qtsingleapplication/CMakeLists.txt
+++ b/Utilities/qtsingleapplication/CMakeLists.txt
@@ -1,7 +1,7 @@
mitk_create_module(
PACKAGE_DEPENDS
- PUBLIC Qt5|Widgets
- PRIVATE Qt5|Network
+ PUBLIC Qt6|Widgets
+ PRIVATE Qt6|Network
FORCE_STATIC
NO_INIT
)
diff --git a/Utilities/qtsingleapplication/qtlocalpeer.cpp b/Utilities/qtsingleapplication/qtlocalpeer.cpp
index 1f1c7f2b2b..99c89a0e99 100644
--- a/Utilities/qtsingleapplication/qtlocalpeer.cpp
+++ b/Utilities/qtsingleapplication/qtlocalpeer.cpp
@@ -1,202 +1,203 @@
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Solutions component.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
** of its contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtlocalpeer.h"
#include <QCoreApplication>
#include <QDataStream>
+#include <QRegularExpression>
#include <QTime>
#if defined(Q_OS_WIN)
#include <qt_windows.h>
#include <QLibrary>
typedef BOOL(WINAPI *PProcessIdToSessionId)(DWORD, DWORD *);
static PProcessIdToSessionId pProcessIdToSessionId = 0;
#endif
#if defined(Q_OS_UNIX)
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#endif
namespace QtLP_Private
{
#include "qtlockedfile.cpp"
#if defined(Q_OS_WIN)
#include "qtlockedfile_win.cpp"
#else
#include "qtlockedfile_unix.cpp"
#endif
}
const char *QtLocalPeer::ack = "ack";
QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId) : QObject(parent), id(appId)
{
QString prefix = id;
if (id.isEmpty())
{
id = QCoreApplication::applicationFilePath();
#if defined(Q_OS_WIN)
id = id.toLower();
#endif
prefix = id.section(QLatin1Char('/'), -1);
}
- prefix.remove(QRegExp("[^a-zA-Z]"));
+ prefix.remove(QRegularExpression("[^a-zA-Z]"));
prefix.truncate(6);
QByteArray idc = id.toUtf8();
- quint16 idNum = qChecksum(idc.constData(), idc.size());
+ quint16 idNum = qChecksum(idc);
socketName = QLatin1String("qtsingleapp-") + prefix + QLatin1Char('-') + QString::number(idNum, 16);
#if defined(Q_OS_WIN)
if (!pProcessIdToSessionId)
{
QLibrary lib("kernel32");
pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
}
if (pProcessIdToSessionId)
{
DWORD sessionId = 0;
pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
socketName += QLatin1Char('-') + QString::number(sessionId, 16);
}
#else
socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
#endif
server = new QLocalServer(this);
QString lockName = QDir(QDir::tempPath()).absolutePath() + QLatin1Char('/') + socketName + QLatin1String("-lockfile");
lockFile.setFileName(lockName);
lockFile.open(QIODevice::ReadWrite);
}
bool QtLocalPeer::isClient()
{
if (lockFile.isLocked())
return false;
if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
return true;
bool res = server->listen(socketName);
#if defined(Q_OS_UNIX)
// ### Workaround
if (!res && server->serverError() == QAbstractSocket::AddressInUseError)
{
QFile::remove(QDir::cleanPath(QDir::tempPath()) + QLatin1Char('/') + socketName);
res = server->listen(socketName);
}
#endif
if (!res)
qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
return false;
}
bool QtLocalPeer::sendMessage(const QByteArray &message, int timeout)
{
if (!isClient())
return false;
QLocalSocket socket;
bool connOk = false;
for (int i = 0; i < 2; i++)
{
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout / 2);
if (connOk || i)
break;
int ms = 250;
#if defined(Q_OS_WIN)
Sleep(DWORD(ms));
#else
struct timespec ts = {ms / 1000, (ms % 1000) * 1000 * 1000};
nanosleep(&ts, nullptr);
#endif
}
if (!connOk)
return false;
QDataStream ds(&socket);
ds.writeBytes(message.constData(), message.size());
bool res = socket.waitForBytesWritten(timeout);
if (res)
{
res &= socket.waitForReadyRead(timeout); // wait for ack
if (res)
res &= (socket.read(qstrlen(ack)) == ack);
}
return res;
}
void QtLocalPeer::receiveConnection()
{
QLocalSocket *socket = server->nextPendingConnection();
if (!socket)
return;
while (socket->bytesAvailable() < (int)sizeof(quint32))
socket->waitForReadyRead();
QDataStream ds(socket);
QByteArray uMsg;
quint32 remaining;
ds >> remaining;
uMsg.resize(remaining);
int got = 0;
char *uMsgBuf = uMsg.data();
do
{
got = ds.readRawData(uMsgBuf, remaining);
remaining -= got;
uMsgBuf += got;
} while (remaining && got >= 0 && socket->waitForReadyRead(2000));
if (got < 0)
{
qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
delete socket;
return;
}
socket->write(ack, qstrlen(ack));
socket->waitForBytesWritten(1000);
socket->waitForDisconnected(1000); // make sure client reads ack
delete socket;
emit messageReceived(uMsg); //### (might take a long time to return)
}
diff --git a/Wrapping/Python/PackageUtility/imagefiles/cmd.sh b/Wrapping/Python/PackageUtility/imagefiles/cmd.sh
index d876ad6cfc..782bf8e8d1 100755
--- a/Wrapping/Python/PackageUtility/imagefiles/cmd.sh
+++ b/Wrapping/Python/PackageUtility/imagefiles/cmd.sh
@@ -1,66 +1,66 @@
#!/bin/sh
set -x
export SRC_DIR="/tmp/mitk"
export BLD_DIR="/tmp/bin"
export OUT_DIR="/var/io"
MITK_GIT_TAG=T24046-SwigBasedPythonWrapping
PYTHON_VERSIONS=${PYTHON_VERSIONS:-$(ls /opt/python | sed -e 's/cp2[0-6][^ ]\+ \?//g')}
NPROC=$(grep -c processor /proc/cpuinfo)
export MAKEFLAGS="-j ${NPROC}"
function build_mitk {
echo "MITK_GIT_TAG: ${MITK_GIT_TAG}"
git clone https://phabricator.mitk.org/source/mitk.git ${SRC_DIR} &&
(cd ${SRC_DIR} && git checkout ${MITK_GIT_TAG} ) &&
rm -rf ${BLD_DIR} &&
mkdir -p ${BLD_DIR} && cd ${BLD_DIR} &&
cmake \
-DBUILD_TESTING:BOOL=OFF \
-DMITK_USE_SWIG:BOOL=ON \
- -DMITK_USE_Qt5:BOOL=OFF \
+ -DMITK_USE_Qt6:BOOL=OFF \
-DMITK_USE_CTK:BOOL=OFF \
-DMITK_USE_BLUEBERRY:BOOL=OFF \
-DCMAKE_C_COMPILER:FILEPATH=/usr/local/bin/gcc \
-DCMAKE_CXX_COMPILER:FILEPATH=/usr/local/bin/g++ \
-DMITK_WHITELIST:STRING=Wrapping \
-DCMAKE_BUILD_TYPE:STRING=Release \
${SRC_DIR} &&
make -j8
}
function build_mitk_python {
PYTHON_EXECUTABLE=/opt/python/${PYTHON}/bin/python
PYTHON_INCLUDE_DIR="$( find -L /opt/python/${PYTHON}/include/ -name Python.h -exec dirname {} \; )"
echo ""
echo "PYTHON_EXECUTABLE:${PYTHON_EXECUTABLE}"
echo "PYTHON_INCLUDE_DIR:${PYTHON_INCLUDE_DIR}"
echo "PYTHON_LIBRARY:${PYTHON_LIBRARY}"
cd ${BLD_DIR}/MITK-build &&
cmake \
-DWRAP_PYTHON:BOOL=ON \
-DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} \
-DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} \
.
make dist -B
}
build_mitk || exit 1
for PYTHON in ${PYTHON_VERSIONS}; do
build_mitk_python &&
auditwheel repair $(find ${BLD_DIR}/MITK-build/Wrapping/Python/dist -name pyMITK*.whl) -w ${OUT_DIR}/wheelhouse/
rm $(find ${BLD_DIR}/MITK-build/Wrapping/Python/dist/ -name pyMITK*.whl)
done
diff --git a/Wrapping/Python/PackageUtility/imagefiles/imagefiles/cmd.sh b/Wrapping/Python/PackageUtility/imagefiles/imagefiles/cmd.sh
index d876ad6cfc..782bf8e8d1 100755
--- a/Wrapping/Python/PackageUtility/imagefiles/imagefiles/cmd.sh
+++ b/Wrapping/Python/PackageUtility/imagefiles/imagefiles/cmd.sh
@@ -1,66 +1,66 @@
#!/bin/sh
set -x
export SRC_DIR="/tmp/mitk"
export BLD_DIR="/tmp/bin"
export OUT_DIR="/var/io"
MITK_GIT_TAG=T24046-SwigBasedPythonWrapping
PYTHON_VERSIONS=${PYTHON_VERSIONS:-$(ls /opt/python | sed -e 's/cp2[0-6][^ ]\+ \?//g')}
NPROC=$(grep -c processor /proc/cpuinfo)
export MAKEFLAGS="-j ${NPROC}"
function build_mitk {
echo "MITK_GIT_TAG: ${MITK_GIT_TAG}"
git clone https://phabricator.mitk.org/source/mitk.git ${SRC_DIR} &&
(cd ${SRC_DIR} && git checkout ${MITK_GIT_TAG} ) &&
rm -rf ${BLD_DIR} &&
mkdir -p ${BLD_DIR} && cd ${BLD_DIR} &&
cmake \
-DBUILD_TESTING:BOOL=OFF \
-DMITK_USE_SWIG:BOOL=ON \
- -DMITK_USE_Qt5:BOOL=OFF \
+ -DMITK_USE_Qt6:BOOL=OFF \
-DMITK_USE_CTK:BOOL=OFF \
-DMITK_USE_BLUEBERRY:BOOL=OFF \
-DCMAKE_C_COMPILER:FILEPATH=/usr/local/bin/gcc \
-DCMAKE_CXX_COMPILER:FILEPATH=/usr/local/bin/g++ \
-DMITK_WHITELIST:STRING=Wrapping \
-DCMAKE_BUILD_TYPE:STRING=Release \
${SRC_DIR} &&
make -j8
}
function build_mitk_python {
PYTHON_EXECUTABLE=/opt/python/${PYTHON}/bin/python
PYTHON_INCLUDE_DIR="$( find -L /opt/python/${PYTHON}/include/ -name Python.h -exec dirname {} \; )"
echo ""
echo "PYTHON_EXECUTABLE:${PYTHON_EXECUTABLE}"
echo "PYTHON_INCLUDE_DIR:${PYTHON_INCLUDE_DIR}"
echo "PYTHON_LIBRARY:${PYTHON_LIBRARY}"
cd ${BLD_DIR}/MITK-build &&
cmake \
-DWRAP_PYTHON:BOOL=ON \
-DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} \
-DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} \
.
make dist -B
}
build_mitk || exit 1
for PYTHON in ${PYTHON_VERSIONS}; do
build_mitk_python &&
auditwheel repair $(find ${BLD_DIR}/MITK-build/Wrapping/Python/dist -name pyMITK*.whl) -w ${OUT_DIR}/wheelhouse/
rm $(find ${BLD_DIR}/MITK-build/Wrapping/Python/dist/ -name pyMITK*.whl)
done

File Metadata

Mime Type
application/octet-stream
Expires
Wed, Oct 30, 10:53 AM (1 d, 23 h)
Storage Engine
chunks
Storage Format
Chunks
Storage Handle
.9VLhc0WZesI
Default Alt Text
(4 MB)

Event Timeline