diff --git a/Applications/PluginGenerator/ProjectTemplate/CMakeLists.txt b/Applications/PluginGenerator/ProjectTemplate/CMakeLists.txt index 572d4ebd54..f7afae7f5f 100644 --- a/Applications/PluginGenerator/ProjectTemplate/CMakeLists.txt +++ b/Applications/PluginGenerator/ProjectTemplate/CMakeLists.txt @@ -1,329 +1,329 @@ cmake_minimum_required(VERSION 3.18 FATAL_ERROR) # Change project and application name to your own set(MY_PROJECT_NAME $(project-name)) set(MY_APP_NAME $(project-app-name)) #----------------------------------------------------------------------------- -# Set the language standard (MITK requires C++14) +# Set the language standard (MITK requires C++17) #----------------------------------------------------------------------------- -set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED 1) set(CMAKE_CXX_EXTENSIONS 0) #----------------------------------------------------------------------------- # Set a default build type if none was specified #----------------------------------------------------------------------------- if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Debug' as none was specified.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() #----------------------------------------------------------------------------- # Superbuild Option - Enabled by default #----------------------------------------------------------------------------- option(${MY_PROJECT_NAME}_USE_SUPERBUILD "Build ${MY_PROJECT_NAME} and the projects it depends on via SuperBuild.cmake." ON) if(${MY_PROJECT_NAME}_USE_SUPERBUILD) project(${MY_PROJECT_NAME}-superbuild) set(${MY_PROJECT_NAME}_SOURCE_DIR ${PROJECT_SOURCE_DIR}) set(${MY_PROJECT_NAME}_BINARY_DIR ${PROJECT_BINARY_DIR}) else() project(${MY_PROJECT_NAME}) endif() #----------------------------------------------------------------------------- # See http://cmake.org/cmake/help/cmake-2-8-docs.html#section_Policies for details #----------------------------------------------------------------------------- set(project_policies CMP0001 # NEW: CMAKE_BACKWARDS_COMPATIBILITY should no longer be used. CMP0002 # NEW: Logical target names must be globally unique. CMP0003 # NEW: Libraries linked via full path no longer produce linker search paths. CMP0004 # NEW: Libraries linked may NOT have leading or trailing whitespace. CMP0005 # NEW: Preprocessor definition values are now escaped automatically. CMP0006 # NEW: Installing MACOSX_BUNDLE targets requires a BUNDLE DESTINATION. CMP0007 # NEW: List command no longer ignores empty elements. CMP0008 # NEW: Libraries linked by full-path must have a valid library file name. CMP0009 # NEW: FILE GLOB_RECURSE calls should not follow symlinks by default. CMP0010 # NEW: Bad variable reference syntax is an error. CMP0011 # NEW: Included scripts do automatic cmake_policy PUSH and POP. CMP0012 # NEW: if() recognizes numbers and boolean constants. CMP0013 # NEW: Duplicate binary directories are not allowed. CMP0014 # NEW: Input directories must have CMakeLists.txt CMP0020 # NEW: Automatically link Qt executables to qtmain target on Windows. CMP0028 # NEW: Double colon in target name means ALIAS or IMPORTED target. ) foreach(policy ${project_policies}) if(POLICY ${policy}) cmake_policy(SET ${policy} NEW) endif() endforeach() #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(CMAKE_MODULE_PATH ${${MY_PROJECT_NAME}_SOURCE_DIR}/CMake ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake Function(s) and Macro(s) #----------------------------------------------------------------------------- include(CTest) include(MacroEmptyExternalProject) #----------------------------------------------------------------------------- # Output directories. #----------------------------------------------------------------------------- foreach(type LIBRARY RUNTIME ARCHIVE) set(output_dir ${${MY_PROJECT_NAME}_BINARY_DIR}/bin) set(CMAKE_${type}_OUTPUT_DIRECTORY ${output_dir} CACHE INTERNAL "Single output directory for building all libraries.") mark_as_advanced(CMAKE_${type}_OUTPUT_DIRECTORY) endforeach() #----------------------------------------------------------------------------- # Additional Options (also shown during superbuild) #----------------------------------------------------------------------------- option(BUILD_SHARED_LIBS "Build ${MY_PROJECT_NAME} with shared libraries" ON) option(WITH_COVERAGE "Enable/Disable coverage" OFF) option(BUILD_TESTING "Test the project" ON) option(${MY_PROJECT_NAME}_BUILD_ALL_PLUGINS "Build all ${MY_PROJECT_NAME} plugins" OFF) mark_as_advanced(${MY_PROJECT_NAME}_INSTALL_RPATH_RELATIVE ${MY_PROJECT_NAME}_BUILD_ALL_PLUGINS ) #----------------------------------------------------------------------------- # Superbuild script #----------------------------------------------------------------------------- if(${MY_PROJECT_NAME}_USE_SUPERBUILD) include("${CMAKE_CURRENT_SOURCE_DIR}/SuperBuild.cmake") return() endif() #***************************************************************************** #**************************** END OF SUPERBUILD **************************** #***************************************************************************** #----------------------------------------------------------------------------- # Prerequesites #----------------------------------------------------------------------------- set(${PROJECT_NAME}_MODULES_PACKAGE_DEPENDS_DIR "${PROJECT_SOURCE_DIR}/CMake/PackageDepends") set(MODULES_PACKAGE_DEPENDS_DIRS ${${PROJECT_NAME}_MODULES_PACKAGE_DEPENDS_DIR}) find_package(MITK 2018.04.99 REQUIRED) if(COMMAND mitkFunctionCheckMitkCompatibility) mitkFunctionCheckMitkCompatibility(VERSIONS MITK_VERSION_PLUGIN_SYSTEM 1 REQUIRED) else() message(SEND_ERROR "Your MITK version is too old. Please use Git hash b86bf28 or newer") endif() link_directories(${MITK_LINK_DIRECTORIES}) #----------------------------------------------------------------------------- # CMake Function(s) and Macro(s) #----------------------------------------------------------------------------- set(CMAKE_MODULE_PATH ${MITK_SOURCE_DIR}/CMake ${CMAKE_MODULE_PATH} ) include(mitkFunctionCheckCompilerFlags) include(mitkFunctionGetGccVersion) include(mitkFunctionGetVersion) #----------------------------------------------------------------------------- # Set project specific options and variables (NOT available during superbuild) #----------------------------------------------------------------------------- set(${PROJECT_NAME}_VERSION_MAJOR "0") set(${PROJECT_NAME}_VERSION_MINOR "1") set(${PROJECT_NAME}_VERSION_PATCH "1") set(${PROJECT_NAME}_VERSION_STRING "${${PROJECT_NAME}_VERSION_MAJOR}.${${PROJECT_NAME}_VERSION_MINOR}.${${PROJECT_NAME}_VERSION_PATCH}") # Ask the user if a console window should be shown with the applications option(${PROJECT_NAME}_SHOW_CONSOLE_WINDOW "Use this to enable or disable the console window when starting GUI Applications" ON) mark_as_advanced(${PROJECT_NAME}_SHOW_CONSOLE_WINDOW) if(NOT UNIX) set(MITK_WIN32_FORCE_STATIC "STATIC") endif() #----------------------------------------------------------------------------- # Get project version info #----------------------------------------------------------------------------- mitkFunctionGetVersion(${PROJECT_SOURCE_DIR} ${PROJECT_NAME}) #----------------------------------------------------------------------------- # Installation preparation # # These should be set before any MITK install macros are used #----------------------------------------------------------------------------- # on macOS all CTK plugins get copied into every # application bundle (.app directory) specified here set(MACOSX_BUNDLE_NAMES) if(APPLE) list(APPEND MACOSX_BUNDLE_NAMES ${MY_APP_NAME}) endif(APPLE) #----------------------------------------------------------------------------- # Set symbol visibility Flags #----------------------------------------------------------------------------- if(CMAKE_COMPILER_IS_GNUCXX) # The MITK module build system does not yet support default hidden visibility set(VISIBILITY_CXX_FLAGS ) # "-fvisibility=hidden -fvisibility-inlines-hidden") endif() #----------------------------------------------------------------------------- # Set coverage Flags #----------------------------------------------------------------------------- if(WITH_COVERAGE) if(CMAKE_COMPILER_IS_GNUCXX) set(coverage_flags "-g -fprofile-arcs -ftest-coverage -O0 -DNDEBUG") set(COVERAGE_CXX_FLAGS ${coverage_flags}) set(COVERAGE_C_FLAGS ${coverage_flags}) endif() endif() #----------------------------------------------------------------------------- # Project C/CXX Flags #----------------------------------------------------------------------------- set(${PROJECT_NAME}_C_FLAGS "${MITK_C_FLAGS} ${COVERAGE_C_FLAGS}") set(${PROJECT_NAME}_C_FLAGS_DEBUG ${MITK_C_FLAGS_DEBUG}) set(${PROJECT_NAME}_C_FLAGS_RELEASE ${MITK_C_FLAGS_RELEASE}) set(${PROJECT_NAME}_CXX_FLAGS "${MITK_CXX_FLAGS} ${VISIBILITY_CXX_FLAGS} ${COVERAGE_CXX_FLAGS}") set(${PROJECT_NAME}_CXX_FLAGS_DEBUG ${MITK_CXX_FLAGS_DEBUG}) set(${PROJECT_NAME}_CXX_FLAGS_RELEASE ${MITK_CXX_FLAGS_RELEASE}) set(${PROJECT_NAME}_EXE_LINKER_FLAGS ${MITK_EXE_LINKER_FLAGS}) set(${PROJECT_NAME}_SHARED_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) set(${PROJECT_NAME}_MODULE_LINKER_FLAGS ${MITK_MODULE_LINKER_FLAGS}) #----------------------------------------------------------------------------- # Set C/CXX Flags #----------------------------------------------------------------------------- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${${PROJECT_NAME}_C_FLAGS}") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${${PROJECT_NAME}_C_FLAGS_DEBUG}") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${${PROJECT_NAME}_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${${PROJECT_NAME}_CXX_FLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${${PROJECT_NAME}_CXX_FLAGS_DEBUG}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${${PROJECT_NAME}_CXX_FLAGS_RELEASE}") set(CMAKE_EXE_LINKER_FLAGS ${${PROJECT_NAME}_EXE_LINKER_FLAGS}) set(CMAKE_SHARED_LINKER_FLAGS ${${PROJECT_NAME}_SHARED_LINKER_FLAGS}) set(CMAKE_MODULE_LINKER_FLAGS ${${PROJECT_NAME}_MODULE_LINKER_FLAGS}) #----------------------------------------------------------------------------- # Testing #----------------------------------------------------------------------------- if(BUILD_TESTING) # Configuration for the CMake-generated test driver set(CMAKE_TESTDRIVER_EXTRA_INCLUDES "#include ") set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN " try {") set(CMAKE_TESTDRIVER_AFTER_TESTMAIN " } catch (const std::exception& e) { fprintf(stderr, \"%s\\n\", e.what()); return EXIT_FAILURE; } catch (...) { printf(\"Exception caught in the test driver\\n\"); return EXIT_FAILURE; }") endif() #----------------------------------------------------------------------------- # ${MY_PROJECT_NAME}_SUPERBUILD_BINARY_DIR #----------------------------------------------------------------------------- # If ${MY_PROJECT_NAME}_SUPERBUILD_BINARY_DIR isn't defined, it means this project is # *NOT* build using Superbuild. In that specific case, ${MY_PROJECT_NAME}_SUPERBUILD_BINARY_DIR # should default to PROJECT_BINARY_DIR if(NOT DEFINED ${PROJECT_NAME}_SUPERBUILD_BINARY_DIR) set(${PROJECT_NAME}_SUPERBUILD_BINARY_DIR ${PROJECT_BINARY_DIR}) endif() #----------------------------------------------------------------------------- # MITK modules #----------------------------------------------------------------------------- #add_subdirectory(Modules) #----------------------------------------------------------------------------- # CTK plugins #----------------------------------------------------------------------------- # The CMake code in this section *must* be in the top-level CMakeLists.txt file macro(GetMyTargetLibraries all_target_libraries varname) set(re_ctkplugin "^$(project-plugin-base)_[a-zA-Z0-9_]+$") set(_tmp_list) list(APPEND _tmp_list ${all_target_libraries}) ctkMacroListFilter(_tmp_list re_ctkplugin OUTPUT_VARIABLE ${varname}) endmacro() include(${CMAKE_CURRENT_SOURCE_DIR}/Plugins/Plugins.cmake) ctkMacroSetupPlugins(${PROJECT_PLUGINS} BUILD_OPTION_PREFIX ${MY_PROJECT_NAME}_ BUILD_ALL ${${MY_PROJECT_NAME}_BUILD_ALL_PLUGINS}) #----------------------------------------------------------------------------- # Add subdirectories #----------------------------------------------------------------------------- add_subdirectory(Apps/$(project-app-name)) #----------------------------------------------------------------------------- # Installation #----------------------------------------------------------------------------- # set MITK cpack variables include(mitkSetupCPack) # Customize CPack variables for this project include(CPackSetup) list(APPEND CPACK_CREATE_DESKTOP_LINKS "${MY_APP_NAME}") configure_file(${MITK_SOURCE_DIR}/MITKCPackOptions.cmake.in ${PROJECT_BINARY_DIR}/${PROJECT_NAME}CPackOptions.cmake @ONLY) set(CPACK_PROJECT_CONFIG_FILE "${PROJECT_BINARY_DIR}/${PROJECT_NAME}CPackOptions.cmake") # include CPack model once all variables are set include(CPack) # Additional installation rules include(mitkInstallRules) #----------------------------------------------------------------------------- # Last configuration steps #----------------------------------------------------------------------------- diff --git a/CMake/mitkFunctionCreateModule.cmake b/CMake/mitkFunctionCreateModule.cmake index f7b334c80b..cfb328b7b4 100644 --- a/CMake/mitkFunctionCreateModule.cmake +++ b/CMake/mitkFunctionCreateModule.cmake @@ -1,651 +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 #! PUBLIC ITK|Watersheds #! \endcode #! #! The 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 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 #! \param DESCRIPTION A description for this module #! #! Multi-value Parameters (all optional): #! #! \param INCLUDE_DIRS Include directories for this module: #! \verbatim #! [[PUBLIC|PRIVATE|INTERFACE] ...]... #! \endverbatim #! The default scope for include directories is PUBLIC. #! \param DEPENDS List of module dependencies: #! \verbatim #! [[PUBLIC|PRIVATE|INTERFACE] ...]... #! \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] INTERNAL_INCLUDE_DIRS # include dirs internal to this module (DEPRECATED) DEPENDS # list of modules this module depends on: [PUBLIC|PRIVATE|INTERFACE] 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] TARGET_DEPENDS # list of CMake targets this module should depend on: [PUBLIC|PRIVATE|INTERFACE] 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] ) 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 ) # 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. # See http://comments.gmane.org/gmane.comp.compilers.clang.scm/50028 # and http://llvm.org/bugs/show_bug.cgi?id=10113 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", see # http://clang-developers.42468.n3.nabble.com/Wc-0x-static-nonintegral-init-gone-td3999651.html # # 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(UI_FILES) qt5_wrap_ui(Q${KITNAME}_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) endif() if(QRC_FILES) qt5_add_resources(Q${KITNAME}_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}) 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} ) 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} ${DOX_FILES} ${UI_FILES} ${QRC_FILES} ${WINDOWS_ICON_RESOURCE_FILE}) 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} ${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 $<$:${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 $<$:${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 $<$:${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 $<$:${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() - if(NOT MODULE_C_MODULE) - target_compile_features(${MODULE_TARGET} ${_module_property_type} ${MITK_CXX_FEATURES}) - 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/CMakeExternals/Boost.cmake b/CMakeExternals/Boost.cmake index 2a92b4030c..9c086d7ef2 100644 --- a/CMakeExternals/Boost.cmake +++ b/CMakeExternals/Boost.cmake @@ -1,342 +1,342 @@ #----------------------------------------------------------------------------- # Boost #----------------------------------------------------------------------------- include(mitkFunctionGetMSVCVersion) #[[ Sanity checks ]] if(DEFINED BOOST_ROOT AND NOT EXISTS ${BOOST_ROOT}) message(FATAL_ERROR "BOOST_ROOT variable is defined but corresponds to non-existing directory") endif() string(REPLACE "^^" ";" MITK_USE_Boost_LIBRARIES "${MITK_USE_Boost_LIBRARIES}") set(proj Boost) set(proj_DEPENDENCIES ) set(Boost_DEPENDS ${proj}) if(NOT DEFINED BOOST_ROOT AND NOT MITK_USE_SYSTEM_Boost) #[[ Reset variables. ]] set(patch_cmd "") set(configure_cmd "") set(install_cmd "") set(BOOST_ROOT ${ep_prefix}) if(WIN32) set(BOOST_LIBRARYDIR "${BOOST_ROOT}/lib") endif() #[[ If you update Boost, make sure that the FindBoost module of the minimum required version of CMake supports the new version of Boost. In case you are using a higher version of CMake, download at least the source code of the minimum required version of CMake to look into the right version of the FindBoost module: /share/cmake-/Modules/FindBoost.cmake Search for a list called _Boost_KNOWN_VERSIONS. If the new version is not included in this list, you have three options: * Update the minimum required version of CMake. This may require adaptions of other parts of our CMake scripts and has the most impact on other MITK developers. Yet this is the safest and cleanest option. * Set Boost_ADDITIONAL_VERSIONS (see the documentation of the FindBoost module). As Boost libraries and dependencies between them are hard-coded in the FindBoost module only for known versions, this may cause trouble for other MITK developers relying on new components of Boost or components with changed dependencies. * Copy a newer version of the FindBoost module into our CMake directory. Our CMake directory has a higher precedence than the default CMake module directory. Doublecheck if the minimum required version of CMake is able to process the newer version of the FindBoost module. Also, DO NOT FORGET to mention this option right above the call of cmake_minimum_required() in the top-level CMakeLists.txt file AND in this file right above the set(url) command below so if we update the minimum required version of CMake or use another option in the future, we do not forget to remove our copy of the FindBoost module again. ]] set(url "${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/boost_1_78_0_b1.tar.gz") set(md5 bbaa634603e3789d7dd0c21d0bdf4f09) if(MITK_USE_Boost_LIBRARIES) #[[ Boost has a two-step build process. In the first step, a bootstrap script is called to build b2, an executable that is used to actually build Boost in the second step. The bootstrap script expects a toolset (compiler) argument that is used to build the b2 executable. The scripts and their expected argument format differ between Windows and Unix. ]] if(WIN32) mitkFunctionGetMSVCVersion() if(VISUAL_STUDIO_VERSION_MINOR EQUAL 0) #[[ Use just the major version in the toolset name. ]] set(bootstrap_args vc${VISUAL_STUDIO_VERSION_MAJOR}) elseif(VISUAL_STUDIO_VERSION_MAJOR EQUAL 14 AND VISUAL_STUDIO_VERSION_MINOR LESS 20) #[[ Assume Visual Studio 2017. ]] set(bootstrap_args vc${VISUAL_STUDIO_VERSION_MAJOR}1) elseif(VISUAL_STUDIO_VERSION_MAJOR EQUAL 14 AND VISUAL_STUDIO_VERSION_MINOR LESS 30) #[[ Assume Visual Studio 2019. ]] set(bootstrap_args vc${VISUAL_STUDIO_VERSION_MAJOR}2) elseif(VISUAL_STUDIO_VERSION_MAJOR EQUAL 14 AND VISUAL_STUDIO_VERSION_MINOR LESS 40) #[[ Assume Visual Studio 2022. ]] set(bootstrap_args vc${VISUAL_STUDIO_VERSION_MAJOR}3) else() #[[ Fallback to the generic case. Be prepared to add another elseif branch above for future versions of Visual Studio. ]] set(bootstrap_args vc${VISUAL_STUDIO_VERSION_MAJOR}) endif() else() #[[ We support GCC and Clang on Unix. On macOS, the toolset must be set to clang. The actual compiler for all of these toolkits is set further below, after the bootstrap script but before b2. ]] if(CMAKE_CXX_COMPILER_ID STREQUAL GNU) set(toolset gcc) elseif(CMAKE_CXX_COMPILER_ID STREQUAL Clang OR APPLE) set(toolset clang) endif() if(toolset) set(bootstrap_args --with-toolset=${toolset}) endif() #[[ At least give it a shot if the toolset is something else and let the bootstrap script decide on the toolset by not passing any argument. ]] endif() #[[ The call of b2 is more complex. b2 arguments are grouped into options and properties. Options follow the standard format for arguments while properties are plain key-value pairs. ]] set(b2_options --build-dir= --stagedir= --ignore-site-config #[[ Build independent of any site.config file ]] -q #[[ Stop at first error ]] ) if(APPLE AND CMAKE_OSX_SYSROOT) #[[ Specify the macOS platform SDK to be used. ]] list(APPEND b2_options --sysroot=${CMAKE_OSX_SYSROOT}) endif() foreach(lib ${MITK_USE_Boost_LIBRARIES}) list(APPEND b2_options --with-${lib}) endforeach() set(b2_properties threading=multi runtime-link=shared - "cxxflags=${MITK_CXX14_FLAG} ${CMAKE_CXX_FLAGS}" + "cxxflags=${MITK_CXX${MITK_CXX_STANDARD}_FLAG} ${CMAKE_CXX_FLAGS}" ) if(CMAKE_SIZEOF_VOID_P EQUAL 8) list(APPEND b2_properties address-model=64) else() list(APPEND b2_properties address-model=32) endif() if(BUILD_SHARED_LIBS) list(APPEND b2_properties link=shared) else() list(APPEND b2_properties link=static) endif() list(APPEND b2_properties "\ $<$:variant=debug>\ $<$:variant=release>\ $<$:variant=release>\ $<$:variant=release>") if(WIN32) set(bootstrap_cmd if not exist b2.exe \( call bootstrap.bat ${bootstrap_args} \)) set(b2_cmd b2 ${b2_options} ${b2_properties} stage) else() set(bootstrap_cmd #[[ test -e ./b2 || ]] ./bootstrap.sh ${bootstrap_args}) set(b2_cmd ./b2 ${b2_options} ${b2_properties} stage) #[[ We already told Boost if we want to use GCC or Clang but so far we were not able to specify the exact same compiler we set in CMake when configuring the MITK superbuild for the first time. For example, this can be different from the system default when multiple versions of the same compiler are installed at the same time. The bootstrap script creates a configuration file for b2 that should be modified if necessary before b2 is called. We look for a line like using gcc ; and replace it with something more specific like using gcc : : /usr/bin/gcc-7.3 ; We use the stream editor sed for the replacement but since macOS is based on BSD Unix, we use the limited but portable BSD syntax instead of the more powerful GNU syntax. We also use | instead of the more commonly used / separator for sed because the replacement contains slashes. 2021/06/15: The custom project-config.jam does not work well with SDK paths on macOS anymore, so we use a custom project-config.jam only on Linux for now. ]] if(toolset AND NOT APPLE) set(configure_cmd sed -i.backup "\ s|\ using[[:space:]][[:space:]]*${toolset}[[:space:]]*$|\ using ${toolset} : : ${CMAKE_CXX_COMPILER} $|\ g" /project-config.jam ) endif() endif() endif() if(WIN32) set(dummy_cmd cd .) else() set(dummy_cmd true) #[[ "cd ." does not work reliably ]] endif() if(NOT patch_cmd) set(patch_cmd ${dummy_cmd}) #[[ Do nothing ]] endif() if(NOT configure_cmd) set(configure_cmd ${dummy_cmd}) #[[ Do nothing ]] endif() if(WIN32) set(install_cmd if not exist $ \( ${CMAKE_COMMAND} -E copy_directory /boost /include/boost \) ) else() set(install_cmd # test -e /include/boost/config.hpp || ${CMAKE_COMMAND} -E copy_directory /boost /include/boost ) endif() ExternalProject_Add(${proj} URL ${url} URL_MD5 ${md5} PATCH_COMMAND ${patch_cmd} CONFIGURE_COMMAND ${configure_cmd} BUILD_COMMAND "" INSTALL_COMMAND ${install_cmd} ) ExternalProject_Add_Step(${proj} bootstrap COMMAND ${bootstrap_cmd} DEPENDEES patch DEPENDERS configure WORKING_DIRECTORY ) ExternalProject_Add_Step(${proj} b2 COMMAND ${b2_cmd} DEPENDEES bootstrap DEPENDERS build WORKING_DIRECTORY ) if(WIN32) #[[ Reuse already extracted files. ]] set(stamp_dir ${ep_prefix}/src/Boost-stamp) configure_file( ${CMAKE_CURRENT_LIST_DIR}/extract-Boost.replacement.cmake ${stamp_dir}/extract-Boost.replacement.cmake COPYONLY) ExternalProject_Add_Step(${proj} pre_download COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_LIST_DIR}/Boost-pre_download.cmake DEPENDEES mkdir DEPENDERS download WORKING_DIRECTORY ${stamp_dir} ) endif() set(install_manifest_dependees install) if(MITK_USE_Boost_LIBRARIES) if(WIN32) #[[ Move DLLs from lib to bin directory. ]] ExternalProject_Add_Step(${proj} post_install COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_LIST_DIR}/Boost-post_install-WIN32.cmake DEPENDEES install WORKING_DIRECTORY /lib ) set(install_manifest_dependees post_install) elseif(APPLE) #[[ Boost does not follow the common practice of either using rpath or absolute paths for referencing dependencies. We have to use the install_name_tool to fix this. ]] ExternalProject_Add_Step(${proj} post_install COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_LIST_DIR}/Boost-post_install-APPLE.cmake DEPENDEES install WORKING_DIRECTORY /lib ) set(install_manifest_dependees post_install) endif() endif() ExternalProject_Add_Step(${proj} install_manifest COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_LIST_DIR}/Boost-install_manifest.cmake DEPENDEES ${install_manifest_dependees} WORKING_DIRECTORY ${ep_prefix} ) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/CMakeExternals/DCMTK.cmake b/CMakeExternals/DCMTK.cmake index 2f00eea2ef..5c2cec181a 100644 --- a/CMakeExternals/DCMTK.cmake +++ b/CMakeExternals/DCMTK.cmake @@ -1,70 +1,71 @@ #----------------------------------------------------------------------------- # DCMTK #----------------------------------------------------------------------------- if(MITK_USE_DCMTK) # Sanity checks if(DEFINED DCMTK_DIR AND NOT EXISTS ${DCMTK_DIR}) message(FATAL_ERROR "DCMTK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj DCMTK) set(proj_DEPENDENCIES ) set(DCMTK_DEPENDS ${proj}) if(NOT DEFINED DCMTK_DIR) if(DCMTK_DICOM_ROOT_ID) set(DCMTK_CXX_FLAGS "${DCMTK_CXX_FLAGS} -DSITE_UID_ROOT=\\\"${DCMTK_DICOM_ROOT_ID}\\\"") set(DCMTK_C_FLAGS "${DCMTK_CXX_FLAGS} -DSITE_UID_ROOT=\\\"${DCMTK_DICOM_ROOT_ID}\\\"") endif() set(additional_args ) if(CTEST_USE_LAUNCHERS) list(APPEND additional_args "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" ) endif() mitk_query_custom_ep_vars() ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/dcmtk-3.6.6.tar.gz URL_MD5 f815879d315b916366a9da71339c7575 CMAKE_GENERATOR ${gen} CMAKE_GENERATOR_PLATFORM ${gen_platform} CMAKE_ARGS ${ep_common_args} ${additional_args} "-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} ${DCMTK_CXX_FLAGS}" "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} ${DCMTK_C_FLAGS}" -DDCMTK_ENABLE_BUILTIN_DICTIONARY:BOOL=ON -DDCMTK_ENABLE_CXX11:BOOL=ON + -DDCMTK_CXX11_FLAGS:STRING=-std=c++${MITK_CXX_STANDARD} -DDCMTK_ENABLE_STL:BOOL=ON -DDCMTK_WITH_DOXYGEN:BOOL=OFF -DDCMTK_WITH_ZLIB:BOOL=OFF # see bug #9894 -DDCMTK_WITH_OPENSSL:BOOL=OFF # see bug #9894 -DDCMTK_WITH_PNG:BOOL=OFF # see bug #9894 -DDCMTK_WITH_TIFF:BOOL=OFF # see bug #9894 -DDCMTK_WITH_XML:BOOL=OFF # see bug #9894 -DDCMTK_WITH_ICONV:BOOL=OFF # see bug #9894 -DDCMTK_WITH_ICU:BOOL=OFF # see T26438 ${${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(DCMTK_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/PCRE.cmake b/CMakeExternals/PCRE.cmake index 9487afb1b1..c8a37b69c9 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 /./configure CC=${CMAKE_C_COMPILER}${CMAKE_C_COMPILER_ARG1} CFLAGS=-fPIC - "CXXFLAGS=-fPIC ${MITK_CXX14_FLAG} ${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE}" + "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= --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" ${configure_cmd} DEPENDS "${${proj}_DEPENDENCIES}" ) set(PCRE_DIR ${ep_prefix}) else() mitkMacroEmptyExternalProject(${proj} "${${proj}_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/Vigra.patch b/CMakeExternals/Vigra.patch index 3a2ed8e943..8238f59808 100644 --- a/CMakeExternals/Vigra.patch +++ b/CMakeExternals/Vigra.patch @@ -1,392 +1,416 @@ diff -urNb vigra-Version-1-10-0/CMakeLists.txt Vigra/CMakeLists.txt --- vigra-Version-1-10-0/CMakeLists.txt 2013-11-18 17:48:16.000000000 +0100 +++ Vigra/CMakeLists.txt 2015-03-03 10:13:57.693725000 +0100 @@ -70,7 +70,12 @@ IF(WITH_OPENEXR) ENDIF() IF(WITH_HDF5) + FIND_PACKAGE(HDF5 PATHS ${HDF5_DIR} PATH_SUFFIXES hdf5 NO_DEFAULT_PATH NO_MODULE) + IF(NOT HDF5_FOUND) VIGRA_FIND_PACKAGE(HDF5) + ENDIF() + # HDF5 changed their config, this ports the new style to the old style + set(HDF5_LIBRARIES ${HDF5_EXPORT_LIBRARIES}) ENDIF() IF(WITH_BOOST_GRAPH) @@ -395,3 +398,4 @@ ENDIF() MESSAGE( STATUS "---------------------------------------------------------" ) + diff -urNb vigra-Version-1-10-0/config/VigraConfig.cmake.in Vigra/config/VigraConfig.cmake.in --- vigra-Version-1-10-0/config/VigraConfig.cmake.in 2013-11-18 17:48:16.000000000 +0100 +++ Vigra/config/VigraConfig.cmake.in 2015-03-03 10:13:57.693725000 +0100 @@ -1,7 +1,9 @@ get_filename_component(SELF_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) get_filename_component(Vigra_TOP_DIR "${SELF_DIR}/../../" ABSOLUTE) -include(${SELF_DIR}/vigra-targets.cmake) +if(NOT TARGET vigraimpex) + include(${SELF_DIR}/vigra-targets.cmake) +endif() get_target_property(VIGRA_TYPE vigraimpex TYPE) if(${VIGRA_TYPE} STREQUAL "STATIC_LIBRARY") SET(VIGRA_STATIC_LIB True) @@ -12,3 +14,4 @@ IF(EXISTS ${SELF_DIR}/../vigranumpy/VigranumpyConfig.cmake) INCLUDE(${SELF_DIR}/../vigranumpy/VigranumpyConfig.cmake) ENDIF() + diff -urNb vigra-Version-1-10-0/include/vigra/random_forest/rf_common.hxx Vigra/include/vigra/random_forest/rf_common.hxx --- vigra-Version-1-10-0/include/vigra/random_forest/rf_common.hxx 2013-11-18 17:48:16.000000000 +0100 +++ Vigra/include/vigra/random_forest/rf_common.hxx 2015-07-08 18:55:16.000000000 +0200 @@ -558,6 +558,7 @@ int is_weighted_; // class_weights_ are used double precision_; // termination criterion for regression loss int response_size_; + int max_tree_depth; template void to_classlabel(int index, T & out) const @@ -583,7 +584,8 @@ EQUALS(class_weights_), EQUALS(is_weighted_), EQUALS(precision_), - EQUALS(response_size_) + EQUALS(response_size_), + EQUALS(max_tree_depth) { std::back_insert_iterator > iter(classes); @@ -604,7 +606,8 @@ EQUALS(class_weights_), EQUALS(is_weighted_), EQUALS(precision_), - EQUALS(response_size_) + EQUALS(response_size_), + EQUALS(max_tree_depth) { std::back_insert_iterator > iter(classes); @@ -624,7 +627,8 @@ EQUALS(used_); EQUALS(is_weighted_); EQUALS(precision_); - EQUALS(response_size_) + EQUALS(response_size_); + EQUALS(max_tree_depth) class_weights_.clear(); std::back_insert_iterator > iter2(class_weights_); @@ -648,7 +652,8 @@ EQUALS(used_); EQUALS(is_weighted_); EQUALS(precision_); - EQUALS(response_size_) + EQUALS(response_size_); + EQUALS(max_tree_depth) class_weights_.clear(); std::back_insert_iterator > iter2(class_weights_); @@ -677,7 +682,8 @@ COMPARE(used_); COMPARE(class_weights_); COMPARE(classes); - COMPARE(response_size_) + COMPARE(response_size_); + COMPARE(max_tree_depth) #undef COMPARE return result; } @@ -715,6 +721,7 @@ PULL(used_, int); PULL(precision_, double); PULL(response_size_, int); + PULL(max_tree_depth, int); if(is_weighted_) { vigra_precondition(end - begin == 10 + 2*class_count_, @@ -747,6 +754,7 @@ PUSH(used_); PUSH(precision_); PUSH(response_size_); + PUSH(max_tree_depth); if(is_weighted_) { std::copy(class_weights_.begin(), @@ -773,6 +781,7 @@ PULL(used_, int); PULL(precision_, double); PULL(response_size_, int); + PULL(max_tree_depth, int); class_weights_ = in["class_weights_"]; #undef PUSH } @@ -789,6 +798,7 @@ PUSH(used_); PUSH(precision_); PUSH(response_size_); + PUSH(max_tree_depth); in["class_weights_"] = class_weights_; #undef PUSH } @@ -805,7 +815,8 @@ used_(false), is_weighted_(false), precision_(0.0), - response_size_(1) + response_size_(1), + max_tree_depth(50) {} @@ -857,7 +868,7 @@ is_weighted_ = false; precision_ = 0.0; response_size_ = 0; - + max_tree_depth = 50; } bool used() const diff -urNb vigra-Version-1-10-0/include/vigra/random_forest/rf_decisionTree.hxx Vigra/include/vigra/random_forest/rf_decisionTree.hxx --- vigra-Version-1-10-0/include/vigra/random_forest/rf_decisionTree.hxx 2013-11-18 17:48:16.000000000 +0100 +++ Vigra/include/vigra/random_forest/rf_decisionTree.hxx 2015-07-08 18:55:16.000000000 +0200 @@ -90,6 +90,8 @@ ProblemSpec<> ext_param_; unsigned int classCount_; + std::map m_Parents; + public: /* \brief Create tree with parameters */ @@ -350,6 +352,22 @@ continueLearn(features,labels,stack_entry,split,stop,visitor,randint); } +template < class TRandomForest> +int GetTreeDepthForNode(int nodeIndex, TRandomForest* rf) +{ + int depth = 0; + while (true) + { + if (nodeIndex < 1) + { + break; + } + ++depth; + nodeIndex = rf->m_Parents[nodeIndex]; + } + return depth; +} + template < class U, class C, class U2, class C2, class StackEntry_t, @@ -374,6 +392,11 @@ size_t last_node_pos = 0; StackEntry_t top=stack.back(); + Split_t* splitPointer = &split; + bool isDepthSplitter = true; + + int maximumTreeDepth = splitPointer->GetMaximumTreeDepth(); + while(!stack.empty()) { @@ -392,7 +415,20 @@ //kind of node to make TreeInt NodeID; - if(stop(top)) + bool depthStop = false; + if (isDepthSplitter) + { + int currentDepthLevel; + if (top.leftParent != StackEntry_t::DecisionTreeNoParent) + currentDepthLevel = GetTreeDepthForNode(top.leftParent, this); + else + currentDepthLevel = GetTreeDepthForNode(top.rightParent, this); + + depthStop = (currentDepthLevel >= maximumTreeDepth); + } + if(stop(top) || (depthStop)) + + //if (stop(top) || currentDepthLevel >= MaximumSplitDepth(split)) NodeID = split.makeTerminalNode(features, labels, top, @@ -421,17 +457,20 @@ // Using InteriorNodeBase because exact parameter form not needed. // look at the Node base before getting scared. last_node_pos = topology_.size(); + m_Parents[last_node_pos] = StackEntry_t::DecisionTreeNoParent; if(top.leftParent != StackEntry_t::DecisionTreeNoParent) { NodeBase(topology_, parameters_, top.leftParent).child(0) = last_node_pos; + m_Parents[last_node_pos] = top.leftParent; } else if(top.rightParent != StackEntry_t::DecisionTreeNoParent) { NodeBase(topology_, parameters_, top.rightParent).child(1) = last_node_pos; + m_Parents[last_node_pos] = top.rightParent; } diff -urNb vigra-Version-1-10-0/include/vigra/random_forest/rf_nodeproxy.hxx Vigra/include/vigra/random_forest/rf_nodeproxy.hxx --- vigra-Version-1-10-0/include/vigra/random_forest/rf_nodeproxy.hxx 2013-11-18 17:48:16.000000000 +0100 +++ Vigra/include/vigra/random_forest/rf_nodeproxy.hxx 2015-07-08 18:55:16.000000000 +0200 @@ -50,7 +50,11 @@ namespace vigra { - +class DepthSplitterBase +{ +public: + virtual int GetMaximumTreeDepth() const = 0; +}; enum NodeTags { diff -urNb vigra-Version-1-10-0/include/vigra/random_forest/rf_split.hxx Vigra/include/vigra/random_forest/rf_split.hxx --- vigra-Version-1-10-0/include/vigra/random_forest/rf_split.hxx 2013-11-18 17:48:16.000000000 +0100 +++ Vigra/include/vigra/random_forest/rf_split.hxx 2015-07-08 18:55:16.000000000 +0200 @@ -108,6 +108,11 @@ \ref SplitBase::findBestSplit() or \ref SplitBase::makeTerminalNode(). **/ + virtual int GetMaximumTreeDepth() const + { + return ext_param_.max_tree_depth; + } + template void set_external_parameters(ProblemSpec const & in) { diff -urNb vigra-Version-1-10-0/include/vigra/random_forest.hxx Vigra/include/vigra/random_forest.hxx --- vigra-Version-1-10-0/include/vigra/random_forest.hxx 2013-11-18 17:48:16.000000000 +0100 +++ Vigra/include/vigra/random_forest.hxx 2015-07-15 14:08:18.548277915 +0200 @@ -165,6 +165,7 @@ ProblemSpec_t ext_param_; /*mutable ArrayVector tree_indices_;*/ rf::visitors::OnlineLearnVisitor online_visitor_; + bool multithreadPrediction; // enable/disable multithreaded predictProbabilities and predictLabels void reset() @@ -584,6 +585,18 @@ { vigra_precondition(features.shape(0) == labels.shape(0), "RandomForest::predictLabels(): Label array has wrong size."); + if (multithreadPrediction) + { +#pragma omp parallel for + for(int k=0; k::cast(predictLabel(rowVector(features, k), rf_default())); + } + } + else + { for(int k=0; k::cast(predictLabel(rowVector(features, k), rf_default())); } } + } /** \brief predict multiple labels with given features * @@ -1261,6 +1275,60 @@ } */ //Classify for each row. + if (multithreadPrediction) + { +#pragma omp parallel for + for(int row=0; row < rowCount(features); ++row) + { + MultiArrayView<2, U, StridedArrayTag> currentRow(rowVector(features, row)); + + // when the features contain an NaN, the instance doesn't belong to any class + // => indicate this by returning a zero probability array. + if(detail::contains_nan(currentRow)) + { + rowVector(prob, row).init(0.0); + continue; + } + + ArrayVector::const_iterator weights; + + //totalWeight == totalVoteCount! + double totalWeight = 0.0; + + //Let each tree classify... + for(int k=0; k::cast(totalWeight); + } + } + } + else + { for(int row=0; row < rowCount(features); ++row) { MultiArrayView<2, U, StridedArrayTag> currentRow(rowVector(features, row)); @@ -1309,6 +1377,7 @@ prob(row, l) /= detail::RequiresExplicitCast::cast(totalWeight); } } + } } diff -u -r Vigra.orig/include/vigra/imagecontainer.hxx Vigra/include/vigra/imagecontainer.hxx --- Vigra.orig/include/vigra/imagecontainer.hxx 2013-11-18 17:48:16.000000000 +0100 +++ Vigra/include/vigra/imagecontainer.hxx 2017-08-26 11:02:40.079669325 +0200 @@ -760,7 +760,7 @@ /** swap contents of this array with the contents of other (STL-Container interface) */ - void swap(const ImagePyramid &other) + void swap(ImagePyramid &other) { images_.swap(other.images_); std::swap(lowestLevel_, other.lowestLevel_); +diff -urNb vigra-Version-1-10-0/include/vigra/functortraits.hxx Vigra/include/vigra/functortraits.hxx +--- vigra-Version-1-10-0/include/vigra/functortraits.hxx 2013-11-18 17:48:16.000000000 +0100 ++++ Vigra/include/vigra/functortraits.hxx 2022-03-17 15:15:01.637026200 +0100 +@@ -195,8 +195,6 @@ + VIGRA_DEFINE_STL_FUNCTOR(std::negate, VigraTrueType, VigraFalseType) + VIGRA_DEFINE_STL_FUNCTOR(std::logical_not, VigraTrueType, VigraFalseType) + VIGRA_DEFINE_STL_FUNCTOR(std::unary_negate, VigraTrueType, VigraFalseType) +-VIGRA_DEFINE_STL_FUNCTOR(std::binder1st, VigraTrueType, VigraFalseType) +-VIGRA_DEFINE_STL_FUNCTOR(std::binder2nd, VigraTrueType, VigraFalseType) + #undef VIGRA_DEFINE_STL_FUNCTOR + + template +diff -urNb vigra-Version-1-10-0/src/impex/imageinfo.cxx Vigra/src/impex/imageinfo.cxx +--- vigra-Version-1-10-0/src/impex/imageinfo.cxx 2013-11-18 17:48:16.000000000 +0100 ++++ Vigra/src/impex/imageinfo.cxx 2022-03-17 15:22:20.975223000 +0100 +@@ -1016,7 +1016,7 @@ + do + { + numEndIt = std::find_if(numBeginIt, filename.rend(),(int (*)(int)) &isdigit); +- numBeginIt = std::find_if(numEndIt, filename.rend(), not1(std::ptr_fun((int (*)(int))&isdigit))); ++ numBeginIt = std::find_if(numEndIt, filename.rend(), std::not_fn((int (*)(int))&isdigit)); + + if(numEndIt != filename.rend()) + { diff --git a/CMakeLists.txt b/CMakeLists.txt index 0dc1206c93..8c66a1157d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,1445 +1,1421 @@ #[[ 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) #----------------------------------------------------------------------------- # 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 2021.10.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() #----------------------------------------------------------------------------- # Check miminum macOS version #----------------------------------------------------------------------------- # The minimum supported macOS version is 10.14. If you use a version less than # 10.14, there is no guarantee that the build still works. if(APPLE) exec_program(sw_vers ARGS -productVersion OUTPUT_VARIABLE macos_version) if (macos_version VERSION_LESS "10.14") message(WARNING "Detected macOS version \"${macos_version}\" is not supported anymore. Minimum required macOS version is at least 10.14.") endif() if (CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS 10.14) message(WARNING "Detected macOS deployment target \"${CMAKE_OSX_DEPLOYMENT_TARGET}\" is not supported anymore. Minimum required macOS version is at least 10.14.") endif() endif() #----------------------------------------------------------------------------- # Check miminum compiler versions #----------------------------------------------------------------------------- if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") # require at least gcc 4.9 as provided by ppa:ubuntu-toolchain-r/test for Ubuntu 14.04 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) message(FATAL_ERROR "GCC version must be at least 4.9 If you are using Ubuntu 14.04, you can easily install gcc and g++ 4.9 (or any later version available) in addition to your version ${CMAKE_CXX_COMPILER_VERSION}: sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update sudo apt-get install gcc-4.9 g++-4.9 Make sure to explicitly specify these compilers when configuring MITK: CMAKE_C_COMPILER:FILEPATH=/usr/bin/gcc-4.9 CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/g++-4.9 For more information on the proposed PPA see the Toolchain Updates section of https://wiki.ubuntu.com/ToolChain.") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") # require at least clang 3.4 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4) message(FATAL_ERROR "Clang version must be at least 3.4") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") # require at least clang 5.0 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) message(FATAL_ERROR "Apple Clang version must be at least 5.0") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") # require at least Visual Studio 2017 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) message(FATAL_ERROR "Microsoft Visual Studio 2017 or newer required") endif() else() message(WARNING "You are using an unsupported compiler! Compilation has only been tested with Clang (Linux or Apple), GCC and MSVC.") endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) else() set(GCC_VERSION 0) endif() -set(MITK_CXX_STANDARD 14) +set(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++14 flag for targets. -# However, compile flag checks also need to be done with -std=c++14. -# The MITK_CXX14_FLAG variable is also used for external projects +# CMAKE_CXX_STANDARD seems to only set the -std=c++ flag for targets. +# However, compile flag checks also need to be done with -std=c++. +# The MITK_CXX_FLAG variable is also used for external projects # build during the MITK super-build. -mitkFunctionCheckCompilerFlags("-std=c++14" MITK_CXX14_FLAG) +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) if(APPLE) list(APPEND MITK_QT5_COMPONENTS DBus) elseif(UNIX) list(APPEND MITK_QT5_COMPONENTS X11Extras) endif() # Hint at default install locations of Qt if(NOT Qt5_DIR) if(MSVC) set(_dir_candidates "C:/Qt") if(CMAKE_GENERATOR MATCHES "^Visual Studio [0-9]+ ([0-9]+)") set(_compilers "msvc${CMAKE_MATCH_1}") elseif(CMAKE_GENERATOR MATCHES "Ninja") include(mitkFunctionGetMSVCVersion) mitkFunctionGetMSVCVersion() if(VISUAL_STUDIO_PRODUCT_NAME MATCHES "^Visual Studio ([0-9]+)") set(_compilers "msvc${CMAKE_MATCH_1}") endif() endif() if(_compilers MATCHES "[0-9]+") if (CMAKE_MATCH_0 EQUAL 2022) list(APPEND _compilers "msvc2019" "msvc2017") # Binary compatible elseif (CMAKE_MATCH_0 EQUAL 2019) list(APPEND _compilers "msvc2017") # 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() foreach(_dir_candidate ${_dir_candidates}) get_filename_component(_dir_candidate ${_dir_candidate} REALPATH) foreach(_compiler ${_compilers}) set(_glob_expression "${_dir_candidate}/5.*/${_compiler}") file(GLOB _hints ${_glob_expression}) list(SORT _hints) list(APPEND MITK_QT5_HINTS ${_hints}) endforeach() endforeach() endif() find_package(Qt5 ${MITK_QT5_MINIMUM_VERSION} COMPONENTS ${MITK_QT5_COMPONENTS} REQUIRED HINTS ${MITK_QT5_HINTS}) endif() # ----------------------------------------- # Custom dependency logic if(WIN32 AND Qt5_DIR) set(_dir_candidate "${Qt5_DIR}/../../../../../Tools/OpenSSL/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) 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) if(NOT OpenSSL_FOUND) set(openssl_message "Could not find OpenSSL (dependency of C++ REST SDK).\n") if(UNIX) if(APPLE) set(openssl_message "${openssl_message}Please install it using your favorite package management " "system (i.e. Homebrew or MacPorts).\n") else() set(openssl_message "${openssl_message}Please install the dev package of OpenSSL (i.e. libssl-dev).\n") endif() else() set(openssl_message "${openssl_message}Please either install Win32 OpenSSL:\n" " https://slproweb.com/products/Win32OpenSSL.html\n" "Or use the Qt Maintenance tool to install:\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 AND CMAKE_FRAMEWORK_PATH AND CMAKE_FRAMEWORK_PATH MATCHES "python3\\.?([0-9]+)") find_package(Python3 3.${CMAKE_MATCH_1} EXACT REQUIRED COMPONENTS Interpreter Development NumPy) else() find_package(Python3 REQUIRED COMPONENTS Interpreter Development NumPy) endif() if(WIN32) string(REPLACE "\\" "/" Python3_STDARCH "${Python3_STDARCH}") string(REPLACE "\\" "/" Python3_STDLIB "${Python3_STDLIB}") string(REPLACE "\\" "/" Python3_SITELIB "${Python3_SITELIB}") endif() endif() if(BUILD_TESTING AND NOT MITK_USE_CppUnit) message("> Forcing MITK_USE_CppUnit to ON because BUILD_TESTING=ON") set(MITK_USE_CppUnit ON CACHE BOOL "Use CppUnit for unit tests" FORCE) endif() if(MITK_USE_BLUEBERRY) option(MITK_BUILD_ALL_PLUGINS "Build all MITK plugins" OFF) mark_as_advanced(MITK_BUILD_ALL_PLUGINS) if(NOT MITK_USE_CTK) message("> Forcing MITK_USE_CTK to ON because of MITK_USE_BLUEBERRY") set(MITK_USE_CTK ON CACHE BOOL "Use CTK in MITK" FORCE) endif() endif() #----------------------------------------------------------------------------- # Pixel type multiplexing #----------------------------------------------------------------------------- # Customize the default pixel types for multiplex macros set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") mark_as_advanced(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES MITK_ACCESSBYITK_DIMENSIONS ) # consistency checks if(NOT MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES) set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES) set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES) set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) string(REPLACE "," ";" _integral_types ${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES}) string(REPLACE "," ";" _floating_types ${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES}) foreach(_scalar_type ${_integral_types} ${_floating_types}) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}itk::VariableLengthVector<${_scalar_type}>,") endforeach() string(LENGTH "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" _length) math(EXPR _length "${_length} - 1") string(SUBSTRING "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" 0 ${_length} MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES ${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES} CACHE STRING "List of vector pixel types used in AccessByItk and InstantiateAccessFunction macros for itk::VectorImage types" FORCE) endif() if(NOT MITK_ACCESSBYITK_DIMENSIONS) set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") endif() 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(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 #----------------------------------------------------------------------------- -# Required and enabled C++14 features for all MITK code. -# These are added as PUBLIC compile features to all MITK modules. -set(MITK_CXX_FEATURES - cxx_auto_type - cxx_decltype - cxx_enum_forward_declarations - cxx_extended_friend_declarations - cxx_extern_templates - cxx_final - cxx_lambdas - cxx_local_type_template_args - cxx_long_long_type - cxx_nullptr - cxx_override - cxx_range_for - cxx_right_angle_brackets - cxx_rvalue_references - cxx_static_assert - cxx_strong_enums - cxx_template_template_parameters - cxx_trailing_return_types - cxx_variadic_macros -) - if(NOT DEFINED CMAKE_DEBUG_POSTFIX) # We can't do this yet because the CTK Plugin Framework # cannot cope with a postfix yet. #set(CMAKE_DEBUG_POSTFIX d) endif() #----------------------------------------------------------------------------- # Output directories. #----------------------------------------------------------------------------- set(_default_LIBRARY_output_dir lib) set(_default_RUNTIME_output_dir bin) set(_default_ARCHIVE_output_dir lib) foreach(type LIBRARY RUNTIME ARCHIVE) # Make sure the directory exists if(MITK_CMAKE_${type}_OUTPUT_DIRECTORY AND NOT EXISTS ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) message("Creating directory MITK_CMAKE_${type}_OUTPUT_DIRECTORY: ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") file(MAKE_DIRECTORY "${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") endif() if(MITK_CMAKE_${type}_OUTPUT_DIRECTORY) set(CMAKE_${type}_OUTPUT_DIRECTORY ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) else() set(CMAKE_${type}_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/${_default_${type}_output_dir}) set(MITK_CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY}) endif() set(CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY} CACHE INTERNAL "Output directory for ${type} files.") mark_as_advanced(CMAKE_${type}_OUTPUT_DIRECTORY) endforeach() #----------------------------------------------------------------------------- # Set MITK specific options and variables (NOT available during superbuild) #----------------------------------------------------------------------------- if(OpenSSL_FOUND AND WIN32) set(MITK_OPENSSL_SSL_DLL "" CACHE FILEPATH "") set(MITK_OPENSSL_CRYPTO_DLL "" CACHE FILEPATH "") 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_CXX14_FLAG}") +set(MITK_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${MITK_CXX17_FLAG}") set(MITK_CXX_FLAGS_DEBUG ) set(MITK_CXX_FLAGS_RELEASE ) set(MITK_EXE_LINKER_FLAGS ) set(MITK_SHARED_LINKER_FLAGS ) if(WIN32) set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} -DPOCO_NO_UNWINDOWS -DWIN32_LEAN_AND_MEAN -DNOMINMAX") mitkFunctionCheckCompilerFlags("/wd4005" MITK_CXX_FLAGS) # warning C4005: macro redefinition mitkFunctionCheckCompilerFlags("/wd4231" MITK_CXX_FLAGS) # warning C4231: nonstandard extension used : 'extern' before template explicit instantiation # the following line should be removed after fixing bug 17637 mitkFunctionCheckCompilerFlags("/wd4316" MITK_CXX_FLAGS) # warning C4316: object alignment on heap mitkFunctionCheckCompilerFlags("/wd4180" MITK_CXX_FLAGS) # warning C4180: qualifier applied to function type has no meaning mitkFunctionCheckCompilerFlags("/wd4251" MITK_CXX_FLAGS) # warning C4251: 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' endif() if(APPLE) set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} -DGL_SILENCE_DEPRECATION") # Apple deprecated OpenGL in macOS 10.14 endif() if(NOT MSVC_VERSION) foreach(_flag -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -Wno-error=gnu -Wno-error=unknown-pragmas # The strict-overflow warning is generated by ITK template code -Wno-error=strict-overflow -Woverloaded-virtual -Wstrict-null-sentinel #-Wold-style-cast #-Wsign-promo -Wno-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 # Config.cmake files pointed at by _DIR variables. # Otherwise, existing Find.cmake files could fail. if(DEFINED ${_package}_DIR) #we store the information because it will be overwritten by find_package #and would get lost for all EPs that use on Find.cmake instead of config #files. set(_temp_EP_${_package}_dir ${${_package}_DIR}) endif(DEFINED ${_package}_DIR) find_package(${_package} QUIET CONFIG) string(TOUPPER "${_package}" _package_uc) if(NOT (${_package}_FOUND OR ${_package_uc}_FOUND)) if(DEFINED _temp_EP_${_package}_dir) set(${_package}_DIR ${_temp_EP_${_package}_dir} CACHE PATH "externaly set dir of the package ${_package}" FORCE) endif(DEFINED _temp_EP_${_package}_dir) find_package(${_package} REQUIRED) endif() endif() endif() endforeach() # Ensure that the MITK CMake module path comes first set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR} ${CMAKE_MODULE_PATH} ) if(MITK_USE_DCMTK) 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_BLUEBERRY) option(BLUEBERRY_USE_QT_HELP "Enable support for integrating plugin documentation into Qt Help" ${DOXYGEN_FOUND}) mark_as_advanced(BLUEBERRY_USE_QT_HELP) # Sanity checks for in-application BlueBerry plug-in help generation if(BLUEBERRY_USE_QT_HELP) set(_force_blueberry_use_qt_help_to_off 0) if(NOT DOXYGEN_FOUND) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because Doxygen was not found.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(DOXYGEN_FOUND AND DOXYGEN_VERSION VERSION_LESS 1.8.7) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because Doxygen version 1.8.7 or newer not found.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT QT_HELPGENERATOR_EXECUTABLE) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because QT_HELPGENERATOR_EXECUTABLE is empty.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT MITK_USE_Qt5) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because MITK_USE_Qt5 is OFF.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT QT_XMLPATTERNS_EXECUTABLE) message("You have enabled Qt Help support, but QT_XMLPATTERNS_EXECUTABLE is empty") set(_force_blueberry_use_qt_help_to_off 1) endif() if(_force_blueberry_use_qt_help_to_off) set(BLUEBERRY_USE_QT_HELP OFF CACHE BOOL "Enable support for integrating plugin documentation into Qt Help" FORCE) endif() endif() if(BLUEBERRY_QT_HELP_REQUIRED AND NOT BLUEBERRY_USE_QT_HELP) message(FATAL_ERROR "BLUEBERRY_USE_QT_HELP is required to be set to ON") endif() endif() endif() #----------------------------------------------------------------------------- # Testing #----------------------------------------------------------------------------- if(BUILD_TESTING) #[[ See T27701 # Initial cache for ProjectTemplate and PluginGenerator tests configure_file( CMake/mitkTestInitialCache.txt.in ${MITK_BINARY_DIR}/mitkTestInitialCache.txt @ONLY )]] # Configuration for the CMake-generated test driver set(CMAKE_TESTDRIVER_EXTRA_INCLUDES "#include ") set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN " try {") set(CMAKE_TESTDRIVER_AFTER_TESTMAIN " } catch (const std::exception& 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 #----------------------------------------------------------------------------- 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/Modules/CMakeLists.txt b/Modules/CMakeLists.txt index b6f9fe8226..edec620255 100644 --- a/Modules/CMakeLists.txt +++ b/Modules/CMakeLists.txt @@ -1,28 +1,28 @@ #----------------------------------------------------------------------------- # Configure the CppMicroServices build #----------------------------------------------------------------------------- set(CppMicroServices_DIR_default "${CMAKE_CURRENT_BINARY_DIR}/CppMicroServices") if(NOT CppMicroServices_DIR) set(CppMicroServices_DIR ${CppMicroServices_DIR_default} CACHE PATH "Path to the CppMicroServices library" FORCE) endif() mark_as_advanced(CppMicroServices_DIR) if ("${CppMicroServices_DIR}" STREQUAL "${CppMicroServices_DIR_default}") set(US_ENABLE_AUTOLOADING_SUPPORT ON) set(US_ENABLE_THREADING_SUPPORT ON) # Don't create a "doc" target and don't install the documentation files set(US_NO_DOCUMENTATION ON) # Don't install anything for now (we use the CMake BundleUtilities script) set(US_NO_INSTALL 1) if(BUILD_TESTING) set(US_BUILD_TESTING ON) endif() - mitkFunctionCheckCompilerFlags("-std=c++14" US_CXX_FLAGS) + mitkFunctionCheckCompilerFlags("-std=c++${MITK_CXX_STANDARD}" US_CXX_FLAGS) add_subdirectory(CppMicroServices) endif() diff --git a/Modules/Classification/CLMiniApps/ManualSegmentationEvaluation.cpp b/Modules/Classification/CLMiniApps/ManualSegmentationEvaluation.cpp index 4339aa228f..92ffbb677f 100644 --- a/Modules/Classification/CLMiniApps/ManualSegmentationEvaluation.cpp +++ b/Modules/Classification/CLMiniApps/ManualSegmentationEvaluation.cpp @@ -1,360 +1,364 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include "mitkImage.h" #include #include #include "mitkCommandLineParser.h" #include #include #include #include #include // ITK #include // MITK #include // Classification #include #include #include #include #include #include #include #include #include #include #include #include #include +#include + using namespace mitk; std::vector m_FeatureImageVector; void ProcessFeatureImages(const mitk::Image::Pointer & raw_image, const mitk::Image::Pointer & brain_mask) { typedef itk::Image DoubleImageType; typedef itk::Image ShortImageType; typedef itk::ConstNeighborhoodIterator NeighborhoodType; // Neighborhood iterator to access image typedef itk::Functor::NeighborhoodFirstOrderStatistics FunctorType; typedef itk::NeighborhoodFunctorImageFilter FOSFilerType; m_FeatureImageVector.clear(); // RAW m_FeatureImageVector.push_back(raw_image); // GAUSS mitk::Image::Pointer smoothed; mitk::CLUtil::GaussianFilter(raw_image,smoothed,1); m_FeatureImageVector.push_back(smoothed); // Calculate Probability maps (parameters used from literatur) // CSF mitk::Image::Pointer csf_prob = mitk::Image::New(); mitk::CLUtil::ProbabilityMap(smoothed,13.9, 8.3,csf_prob); m_FeatureImageVector.push_back(csf_prob); // Lesion mitk::Image::Pointer les_prob = mitk::Image::New(); mitk::CLUtil::ProbabilityMap(smoothed,59, 11.6,les_prob); m_FeatureImageVector.push_back(les_prob); // Barin (GM/WM) mitk::Image::Pointer brain_prob = mitk::Image::New(); mitk::CLUtil::ProbabilityMap(smoothed,32, 5.6,brain_prob); m_FeatureImageVector.push_back(brain_prob); std::vector FOS_sizes; FOS_sizes.push_back(1); DoubleImageType::Pointer input; ShortImageType::Pointer mask; mitk::CastToItkImage(smoothed, input); mitk::CastToItkImage(brain_mask, mask); for(unsigned int i = 0 ; i < FOS_sizes.size(); i++) { FOSFilerType::Pointer filter = FOSFilerType::New(); filter->SetNeighborhoodSize(FOS_sizes[i]); filter->SetInput(input); filter->SetMask(mask); filter->Update(); FOSFilerType::DataObjectPointerArray array = filter->GetOutputs(); for( unsigned int i = 0; i < FunctorType::OutputCount; i++) { mitk::Image::Pointer featureimage; mitk::CastToMitkImage(dynamic_cast(array[i].GetPointer()),featureimage); m_FeatureImageVector.push_back(featureimage); // AddImageAsDataNode(featureimage,FunctorType::GetFeatureName(i))->SetVisibility(show_nodes); } } { itk::HessianMatrixEigenvalueImageFilter< DoubleImageType >::Pointer filter = itk::HessianMatrixEigenvalueImageFilter< DoubleImageType >::New(); filter->SetInput(input); filter->SetImageMask(mask); filter->SetSigma(3); filter->Update(); mitk::Image::Pointer o1,o2,o3; mitk::CastToMitkImage(filter->GetOutput(0),o1); mitk::CastToMitkImage(filter->GetOutput(1),o2); mitk::CastToMitkImage(filter->GetOutput(2),o3); m_FeatureImageVector.push_back(o1); m_FeatureImageVector.push_back(o2); m_FeatureImageVector.push_back(o3); } { itk::StructureTensorEigenvalueImageFilter< DoubleImageType >::Pointer filter = itk::StructureTensorEigenvalueImageFilter< DoubleImageType >::New(); filter->SetInput(input); filter->SetImageMask(mask); filter->SetInnerScale(1.5); filter->SetOuterScale(3); filter->Update(); mitk::Image::Pointer o1,o2,o3; mitk::CastToMitkImage(filter->GetOutput(0),o1); mitk::CastToMitkImage(filter->GetOutput(1),o2); mitk::CastToMitkImage(filter->GetOutput(2),o3); m_FeatureImageVector.push_back(o1); m_FeatureImageVector.push_back(o2); m_FeatureImageVector.push_back(o3); } { itk::LineHistogramBasedMassImageFilter< DoubleImageType >::Pointer filter = itk::LineHistogramBasedMassImageFilter< DoubleImageType >::New(); filter->SetInput(input); filter->SetImageMask(mask); filter->Update(); mitk::Image::Pointer o1; mitk::CastToMitkImage(filter->GetOutput(0),o1); m_FeatureImageVector.push_back(o1); } } std::vector PointSetToVector(const mitk::PointSet::Pointer & mps) { std::vector result; for(int i = 0 ; i < mps->GetSize(); i++) result.push_back(mps->GetPoint(i)); return result; } int main(int argc, char* argv[]) { mitkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); // required params parser.addArgument("inputdir", "i", mitkCommandLineParser::Directory, "Input Directory", "Contains input feature files.", us::Any(), false, false, false, mitkCommandLineParser::Input); parser.addArgument("outputdir", "o", mitkCommandLineParser::Directory, "Output Directory", "Destination of output files.", us::Any(), false, false, false, mitkCommandLineParser::Output); parser.addArgument("mitkprojectdata", "d", mitkCommandLineParser::File, "original class mask and raw image", "Orig. data.", us::Any(), false, false, false, mitkCommandLineParser::Input); parser.addArgument("csfmps", "csf", mitkCommandLineParser::File, "CSF Pointset", ".", us::Any(), false, false, false, mitkCommandLineParser::Input); parser.addArgument("lesmps", "les", mitkCommandLineParser::File, "LES Pointset", ".", us::Any(), false, false, false, mitkCommandLineParser::Input); parser.addArgument("bramps", "bra", mitkCommandLineParser::File, "BRA Pointset", ".", us::Any(), false, false, false, mitkCommandLineParser::Input); // parser.addArgument("points", "p", mitkCommandLineParser::Int, "Ensure that p points are selected", ".", us::Any(), false); // Miniapp Infos parser.setCategory("Classification Tools"); parser.setTitle("Evaluationtool for Manual-Segmentation"); parser.setDescription("Uses Datacollection to calculate DICE scores for CSF LES BRA"); parser.setContributor("German Cancer Research Center (DKFZ)"); // Params parsing std::map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; std::string inputdir = us::any_cast(parsedArgs["inputdir"]); std::string outputdir = us::any_cast(parsedArgs["outputdir"]); std::string mitkprojectdata = us::any_cast(parsedArgs["mitkprojectdata"]); std::string csf_mps_name = us::any_cast(parsedArgs["csfmps"]); std::string les_mps_name = us::any_cast(parsedArgs["lesmps"]); std::string bra_mps_name = us::any_cast(parsedArgs["bramps"]); mitk::Image::Pointer class_mask_sampled, raw_image, class_mask; mitk::PointSet::Pointer CSF_mps, LES_mps, BRA_mps; // Load from mitk-project auto so = mitk::IOUtil::Load(inputdir + "/" + mitkprojectdata); std::map map; mitk::CLUtil::CountVoxel(dynamic_cast(so[1].GetPointer()), map); raw_image = map.size() <= 7 ? dynamic_cast(so[0].GetPointer()) : dynamic_cast(so[1].GetPointer()); class_mask = map.size() <= 7 ? dynamic_cast(so[1].GetPointer()) : dynamic_cast(so[0].GetPointer()); CSF_mps = mitk::IOUtil::Load(inputdir + "/" + csf_mps_name); LES_mps = mitk::IOUtil::Load(inputdir + "/" + les_mps_name); BRA_mps = mitk::IOUtil::Load(inputdir + "/" + bra_mps_name); unsigned int num_points = CSF_mps->GetSize() + LES_mps->GetSize() + BRA_mps->GetSize(); MITK_INFO << "Found #" << num_points << " points over all classes."; ProcessFeatureImages(raw_image, class_mask); std::map tmpMap; tmpMap[0] = 0; tmpMap[1] = 1; tmpMap[2] = 1; tmpMap[3] = 1; tmpMap[4] = 2; tmpMap[5] = 3; tmpMap[6] = 3; mitk::CLUtil::MergeLabels( class_mask, tmpMap); class_mask_sampled = class_mask->Clone(); itk::Image::Pointer itk_classmask_sampled; mitk::CastToItkImage(class_mask_sampled,itk_classmask_sampled); itk::ImageRegionIteratorWithIndex >::IndexType index; itk::ImageRegionIteratorWithIndex > iit(itk_classmask_sampled,itk_classmask_sampled->GetLargestPossibleRegion()); std::ofstream myfile; myfile.open (inputdir + "/results_3.csv"); Eigen::MatrixXd X_test; unsigned int count_test = 0; mitk::CLUtil::CountVoxel(class_mask, count_test); X_test = Eigen::MatrixXd(count_test, m_FeatureImageVector.size()); unsigned int pos = 0; for( const auto & image : m_FeatureImageVector) { X_test.col(pos) = mitk::CLUtil::Transform(image,class_mask); ++pos; } + std::random_device rnd; + unsigned int runs = 20; for(unsigned int k = 0 ; k < runs; k++) { auto CSF_vec = PointSetToVector(CSF_mps); auto LES_vec = PointSetToVector(LES_mps); auto BRA_vec = PointSetToVector(BRA_mps); itk_classmask_sampled->FillBuffer(0); // initial draws - std::random_shuffle(CSF_vec.begin(), CSF_vec.end()); + std::shuffle(CSF_vec.begin(), CSF_vec.end(), std::mt19937(rnd())); class_mask->GetGeometry()->WorldToIndex(CSF_vec.back(),index); iit.SetIndex(index); iit.Set(1); CSF_vec.pop_back(); - std::random_shuffle(LES_vec.begin(), LES_vec.end()); + std::shuffle(LES_vec.begin(), LES_vec.end(), std::mt19937(rnd())); class_mask->GetGeometry()->WorldToIndex(LES_vec.back(),index); iit.SetIndex(index); iit.Set(2); LES_vec.pop_back(); - std::random_shuffle(BRA_vec.begin(), BRA_vec.end()); + std::shuffle(BRA_vec.begin(), BRA_vec.end(), std::mt19937(rnd())); class_mask->GetGeometry()->WorldToIndex(BRA_vec.back(),index); iit.SetIndex(index); iit.Set(3); BRA_vec.pop_back(); std::stringstream ss; while(!(CSF_vec.empty() && LES_vec.empty() && BRA_vec.empty())) { mitk::CastToMitkImage(itk_classmask_sampled, class_mask_sampled); // Train forest mitk::VigraRandomForestClassifier::Pointer classifier = mitk::VigraRandomForestClassifier::New(); classifier->SetTreeCount(40); classifier->SetSamplesPerTree(0.66); Eigen::MatrixXd X_train; unsigned int count_train = 0; mitk::CLUtil::CountVoxel(class_mask_sampled, count_train); X_train = Eigen::MatrixXd(count_train, m_FeatureImageVector.size() ); unsigned int pos = 0; for( const auto & image : m_FeatureImageVector) { X_train.col(pos) = mitk::CLUtil::Transform(image,class_mask_sampled); ++pos; } Eigen::MatrixXi Y = mitk::CLUtil::Transform(class_mask_sampled,class_mask_sampled); classifier->Train(X_train,Y); Eigen::MatrixXi Y_test = classifier->Predict(X_test); mitk::Image::Pointer result_mask = mitk::CLUtil::Transform(Y_test, class_mask); itk::Image::Pointer itk_result_mask, itk_class_mask; mitk::CastToItkImage(result_mask,itk_result_mask); mitk::CastToItkImage(class_mask, itk_class_mask); itk::LabelOverlapMeasuresImageFilter >::Pointer overlap_filter = itk::LabelOverlapMeasuresImageFilter >::New(); overlap_filter->SetInput(0,itk_result_mask); overlap_filter->SetInput(1,itk_class_mask); overlap_filter->Update(); MITK_INFO << "DICE (" << num_points - (CSF_vec.size() + LES_vec.size() + BRA_vec.size()) << "): " << overlap_filter->GetDiceCoefficient(); ss << overlap_filter->GetDiceCoefficient() <<","; // random class selection if(!CSF_vec.empty()) { - std::random_shuffle(CSF_vec.begin(), CSF_vec.end()); + std::shuffle(CSF_vec.begin(), CSF_vec.end(), std::mt19937(rnd())); class_mask->GetGeometry()->WorldToIndex(CSF_vec.back(),index); iit.SetIndex(index); iit.Set(1); CSF_vec.pop_back(); } if(!LES_vec.empty()) { - std::random_shuffle(LES_vec.begin(), LES_vec.end()); + std::shuffle(LES_vec.begin(), LES_vec.end(), std::mt19937(rnd())); class_mask->GetGeometry()->WorldToIndex(LES_vec.back(),index); iit.SetIndex(index); iit.Set(2); LES_vec.pop_back(); } if(!BRA_vec.empty()) { - std::random_shuffle(BRA_vec.begin(), BRA_vec.end()); + std::shuffle(BRA_vec.begin(), BRA_vec.end(), std::mt19937(rnd())); class_mask->GetGeometry()->WorldToIndex(BRA_vec.back(),index); iit.SetIndex(index); iit.Set(3); BRA_vec.pop_back(); } } myfile << ss.str() << "\n"; myfile.flush(); } myfile.close(); return EXIT_SUCCESS; } diff --git a/Modules/CppMicroServices/cmake/usGlobalConfig.h.in b/Modules/CppMicroServices/cmake/usGlobalConfig.h.in index 441e3eae5b..c1b6b630cc 100644 --- a/Modules/CppMicroServices/cmake/usGlobalConfig.h.in +++ b/Modules/CppMicroServices/cmake/usGlobalConfig.h.in @@ -1,206 +1,206 @@ /* USCONFIG.h this file is generated. Do not change! */ #ifndef USGLOBALCONFIG_H #define USGLOBALCONFIG_H #cmakedefine US_BUILD_SHARED_LIBS #cmakedefine US_ENABLE_THREADING_SUPPORT #cmakedefine US_GCC_RTTI_WORKAROUND_NEEDED #cmakedefine US_HAVE_VISIBILITY_ATTRIBUTE //------------------------------------------------------------------- // Header Availability //------------------------------------------------------------------- #cmakedefine US_HAVE_CXXABI_H #cmakedefine US_HAVE_STDINT_H #cmakedefine US_HAVE_TR1_UNORDERED_MAP_H #cmakedefine US_HAVE_TR1_UNORDERED_SET_H #cmakedefine US_HAVE_TR1_FUNCTIONAL_H #cmakedefine US_HAVE_UNORDERED_MAP_H #cmakedefine US_HAVE_UNORDERED_SET_H #cmakedefine US_HAVE_FUNCTIONAL_H #cmakedefine US_HAVE_TR1_UNORDERED_MAP #cmakedefine US_HAVE_TR1_UNORDERED_SET #cmakedefine US_HAVE_TR1_FUNCTION #cmakedefine US_HAVE_STD_UNORDERED_MAP #cmakedefine US_HAVE_STD_UNORDERED_SET #cmakedefine US_HAVE_STD_FUNCTION #cmakedefine US_HAVE_TR1_HASH #cmakedefine US_HAVE_TR1_HASH_STRUCT #cmakedefine US_HAVE_TR1_HASH_CLASS #cmakedefine US_HAVE_STD_HASH #cmakedefine US_HAVE_STD_HASH_STRUCT #cmakedefine US_HAVE_STD_HASH_CLASS ///------------------------------------------------------------------- // Version information //------------------------------------------------------------------- #define CppMicroServices_MAJOR_VERSION @CppMicroServices_MAJOR_VERSION@ #define CppMicroServices_MINOR_VERSION @CppMicroServices_MINOR_VERSION@ #define CppMicroServices_PATCH_VERSION @CppMicroServices_PATCH_VERSION@ #define CppMicroServices_VERSION @CppMicroServices_VERSION@ #define CppMicroServices_VERSION_STR "@CppMicroServices_VERSION@" #define US_MAJOR_VERSION @CppMicroServices_MAJOR_VERSION@ #define US_MINOR_VERSION @CppMicroServices_MINOR_VERSION@ #define US_PATCH_VERSION @CppMicroServices_PATCH_VERSION@ #define US_VERSION @CppMicroServices_VERSION@ #define US_VERSION_STR "@CppMicroServices_VERSION@" //------------------------------------------------------------------- // Namespace customization //------------------------------------------------------------------- #define US_NAMESPACE @US_NAMESPACE@ #ifndef US_NAMESPACE /* user namespace */ # define US_PREPEND_NAMESPACE(name) ::name # define US_USE_NAMESPACE # define US_BEGIN_NAMESPACE # define US_END_NAMESPACE # define US_FORWARD_DECLARE_CLASS(name) class name; # define US_FORWARD_DECLARE_STRUCT(name) struct name; #else /* user namespace */ # define US_PREPEND_NAMESPACE(name) ::US_NAMESPACE::name # define US_USE_NAMESPACE using namespace ::US_NAMESPACE; # define US_BEGIN_NAMESPACE namespace US_NAMESPACE { # define US_END_NAMESPACE } # define US_FORWARD_DECLARE_CLASS(name) \ US_BEGIN_NAMESPACE class name; US_END_NAMESPACE # define US_FORWARD_DECLARE_STRUCT(name) \ US_BEGIN_NAMESPACE struct name; US_END_NAMESPACE namespace US_NAMESPACE {} #endif /* user namespace */ //------------------------------------------------------------------- // Platform defines //------------------------------------------------------------------- #if defined(__APPLE__) #define US_PLATFORM_APPLE #endif #if defined(__linux__) #define US_PLATFORM_LINUX #endif #if defined(_WIN32) || defined(_WIN64) #define US_PLATFORM_WINDOWS #else #define US_PLATFORM_POSIX #endif ///------------------------------------------------------------------- // Macros for import/export declarations //------------------------------------------------------------------- #if defined(US_PLATFORM_WINDOWS) #define US_ABI_EXPORT __declspec(dllexport) #define US_ABI_IMPORT __declspec(dllimport) #define US_ABI_LOCAL #elif defined(US_HAVE_VISIBILITY_ATTRIBUTE) #define US_ABI_EXPORT __attribute__ ((visibility ("default"))) #define US_ABI_IMPORT __attribute__ ((visibility ("default"))) #define US_ABI_LOCAL __attribute__ ((visibility ("hidden"))) #else #define US_ABI_EXPORT #define US_ABI_IMPORT #define US_ABI_LOCAL #endif //------------------------------------------------------------------- // Macros for suppressing warnings //------------------------------------------------------------------- #ifdef _MSC_VER #define US_MSVC_PUSH_DISABLE_WARNING(wn) \ __pragma(warning(push)) \ __pragma(warning(disable:wn)) #define US_MSVC_POP_WARNING \ __pragma(warning(pop)) #define US_MSVC_DISABLE_WARNING(wn) \ __pragma(warning(disable:wn)) #else #define US_MSVC_PUSH_DISABLE_WARNING(wn) #define US_MSVC_POP_WARNING #define US_MSVC_DISABLE_WARNING(wn) #endif // Do not warn about the usage of deprecated unsafe functions US_MSVC_DISABLE_WARNING(4996) // Mark a variable or expression result as unused #define US_UNUSED(x) (void)(x) //------------------------------------------------------------------- // Hash Container //------------------------------------------------------------------- #ifdef US_HAVE_UNORDERED_MAP_H #include #elif defined(US_HAVE_TR1_UNORDERED_MAP_H) #include #endif #ifdef US_HAVE_UNORDERED_SET_H #include #elif defined(US_HAVE_TR1_UNORDERED_SET_H) #include #endif #ifdef US_HAVE_STD_UNORDERED_MAP #define US_UNORDERED_MAP_TYPE ::std::unordered_map #elif defined(US_HAVE_TR1_UNORDERED_MAP) #define US_UNORDERED_MAP_TYPE ::std::tr1::unordered_map #endif #ifdef US_HAVE_STD_UNORDERED_SET #define US_UNORDERED_SET_TYPE ::std::unordered_set #elif defined(US_HAVE_TR1_UNORDERED_SET) #define US_UNORDERED_SET_TYPE ::std::tr1::unordered_set #endif #ifdef US_HAVE_STD_HASH #define US_HASH_FUNCTION_NAMESPACE ::std #ifdef US_HAVE_STD_HASH_STRUCT #define US_HASH_FUNCTION_FRIEND(type) friend struct ::std::hash #elif defined(US_HAVE_STD_HASH_CLASS) #define US_HASH_FUNCTION_FRIEND(type) friend class ::std::hash #endif #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace std { #define US_HASH_FUNCTION_NAMESPACE_END } #elif defined(US_HAVE_TR1_HASH) #define US_HASH_FUNCTION_NAMESPACE ::std::tr1 #ifdef US_HAVE_TR1_HASH_STRUCT #define US_HASH_FUNCTION_FRIEND(type) friend struct ::std::tr1::hash #elif defined(US_HAVE_TR1_HASH_CLASS) #define US_HASH_FUNCTION_FRIEND(type) friend class ::std::tr1::hash #endif #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace std { namespace tr1 { #define US_HASH_FUNCTION_NAMESPACE_END }} #endif #define US_HASH_FUNCTION_BEGIN(type) \ template<> \ -struct hash : std::unary_function { \ +struct hash { \ std::size_t operator()(const type& arg) const { #define US_HASH_FUNCTION_END } }; #define US_HASH_FUNCTION(type, arg) hash()(arg) #endif // USGLOBALCONFIG_H diff --git a/Modules/CppMicroServices/core/src/util/usListenerFunctors_p.h b/Modules/CppMicroServices/core/src/util/usListenerFunctors_p.h index f8364127ac..6578eb7ed4 100644 --- a/Modules/CppMicroServices/core/src/util/usListenerFunctors_p.h +++ b/Modules/CppMicroServices/core/src/util/usListenerFunctors_p.h @@ -1,89 +1,88 @@ /*============================================================================ Library: CppMicroServices Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================*/ #ifndef USLISTENERFUNCTORS_P_H #define USLISTENERFUNCTORS_P_H #include #include #include #include #ifdef US_HAVE_STD_FUNCTION #ifdef US_HAVE_FUNCTIONAL_H #include #elif defined(US_HAVE_TR1_FUNCTIONAL_H) #include #endif #define US_FUNCTION_TYPE std::function #elif defined(US_HAVE_TR1_FUNCTION) #ifdef US_HAVE_TR1_FUNCTIONAL_H #include #elif defined(US_HAVE_FUNCTIONAL_H) #include #endif #define US_FUNCTION_TYPE std::tr1::function #endif #define US_MODULE_LISTENER_FUNCTOR US_FUNCTION_TYPE #define US_SERVICE_LISTENER_FUNCTOR US_FUNCTION_TYPE US_BEGIN_NAMESPACE template US_MODULE_LISTENER_FUNCTOR ModuleListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ModuleEvent))) { return std::bind(std::mem_fn(memFn), x, std::placeholders::_1); } - struct ModuleListenerCompare : std::binary_function, - std::pair, bool> + struct ModuleListenerCompare { bool operator()(const std::pair& p1, const std::pair& p2) const { return p1.second == p2.second && p1.first.target() == p2.first.target(); } }; template US_SERVICE_LISTENER_FUNCTOR ServiceListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ServiceEvent))) { return std::bind(std::mem_fn(memFn), x, std::placeholders::_1); } - struct ServiceListenerCompare : std::binary_function + struct ServiceListenerCompare { bool operator()(const US_SERVICE_LISTENER_FUNCTOR& f1, const US_SERVICE_LISTENER_FUNCTOR& f2) const { return f1.target() == f2.target(); } }; US_END_NAMESPACE US_HASH_FUNCTION_NAMESPACE_BEGIN US_HASH_FUNCTION_BEGIN(US_SERVICE_LISTENER_FUNCTOR) void(*targetFunc)(const US_PREPEND_NAMESPACE(ServiceEvent)&) = arg.target(); void* targetPtr = nullptr; std::memcpy(&targetPtr, &targetFunc, sizeof(void*)); return US_HASH_FUNCTION(void*, targetPtr); US_HASH_FUNCTION_END US_HASH_FUNCTION_NAMESPACE_END #endif // USLISTENERFUNCTORS_P_H diff --git a/Modules/QtWidgets/include/QmitkDataStorageTableModel.h b/Modules/QtWidgets/include/QmitkDataStorageTableModel.h index 0abd6382e4..67d76e2519 100644 --- a/Modules/QtWidgets/include/QmitkDataStorageTableModel.h +++ b/Modules/QtWidgets/include/QmitkDataStorageTableModel.h @@ -1,223 +1,223 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QmitkDataStorageTableModel_h #define QmitkDataStorageTableModel_h #include /// Own includes. #include "mitkBaseProperty.h" #include "mitkDataStorage.h" #include "mitkNodePredicateBase.h" #include "mitkWeakPointer.h" /// Toolkit includes. #include /// Forward declarations. /// /// \ingroup QmitkModule /// \class QmitkDataStorageTableModel /// /// \brief A table model for a set of DataNodes defined by a predicate. /// \todo make columns interchangeable, select which properties to show as columns /// class MITKQTWIDGETS_EXPORT QmitkDataStorageTableModel : public QAbstractTableModel { Q_OBJECT //#Ctors/Dtor public: /// /// Constructs a new QmitkDataStorageTableModel and sets a predicate that defines /// this list. /// \see setPredicate() /// QmitkDataStorageTableModel(mitk::DataStorage::Pointer _DataStorage, mitk::NodePredicateBase *_Predicate = nullptr, QObject *parent = nullptr); /// /// Standard dtor. Delete predicate, disconnect from DataStorage. /// ~QmitkDataStorageTableModel() override; //# Public GETTER public: /// /// Get the DataStorage. /// const mitk::DataStorage::Pointer GetDataStorage() const; /// /// Get the predicate. /// mitk::NodePredicateBase::Pointer GetPredicate() const; /// /// Get node at a specific model index. Another way to implement this, is /// by introducing a new role like "DateTreeNode" and capture /// that in the data function. /// mitk::DataNode::Pointer GetNode(const QModelIndex &index) const; /// /// Overridden from QAbstractTableModel. Returns the header data at section /// for given orientation and role. /// QVariant headerData(int section, Qt::Orientation orientation, int role) const override; /// /// Overridden from QAbstractTableModel. Returns what can be done /// with an item. /// Qt::ItemFlags flags(const QModelIndex &index) const override; /// /// Overridden from QAbstractTableModel. Returns the node count. /// int rowCount(const QModelIndex &parent) const override; /// /// Overridden from QAbstractTableModel. Returns the number of features (columns) to display. /// int columnCount(const QModelIndex &parent) const override; /// /// Overridden from QAbstractTableModel. Returns the data at index for given role. /// QVariant data(const QModelIndex &index, int role) const override; //# Public SETTERS public: /// /// Sets the DataStorage. /// void SetDataStorage(mitk::DataStorage::Pointer _DataStorage); /// /// Sets the predicate. QmitkDataStorageTableModel is owner of the predicate! /// void SetPredicate(mitk::NodePredicateBase *_Predicate); /// /// Adds a node to this model. /// There are two constraints for nodes in this model: /// 1. If a predicate is set (not null) the node will be checked against it. /// 2. The node has to have a data object (no one wants to see empty nodes). /// Also adds event listeners to the node. /// virtual void AddNode(const mitk::DataNode *node); /// /// Removes a node from this model. Also removes any event listener from the node. /// virtual void RemoveNode(const mitk::DataNode *node); /// /// Returns a copy of the node-vector that is shown by this model /// virtual std::vector GetNodeSet() const; /// /// \brief Called when a single property was changed. /// The function searches through the list of nodes in this model for the changed /// property. If the property was found a dataChanged signal is emitted forcing /// all observing views to request the data again. /// virtual void PropertyModified(const itk::Object *caller, const itk::EventObject &event); /// /// Overridden from QAbstractTableModel. Sets data at index for given role. /// bool setData(const QModelIndex &index, const QVariant &value, int role) override; /// /// \brief Reimplemented sort function from QAbstractTableModel to enable sorting on the table. /// void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; //#PROTECTED INNER CLASSES protected: /// /// \struct DataNodeCompareFunction - /// \brief A struct that inherits from std::binary_function. You can use it in std::sort algorithm for sorting the + /// \brief A struct that you can use in std::sort algorithm for sorting the /// node list elements. /// - struct DataNodeCompareFunction : public std::binary_function + struct DataNodeCompareFunction { /// /// \brief Specifies field of the property with which it will be sorted. /// enum CompareCriteria { CompareByName = 0, CompareByClassName, CompareByVisibility }; /// /// \brief Specifies Ascending/descending ordering. /// enum CompareOperator { Less = 0, Greater }; /// /// \brief Creates a PropertyDataSetCompareFunction. A CompareCriteria and a CompareOperator must be given. /// DataNodeCompareFunction(CompareCriteria _CompareCriteria = CompareByName, CompareOperator _CompareOperator = Less); /// /// \brief The reimplemented compare function. /// bool operator()(const mitk::DataNode::Pointer &_Left, const mitk::DataNode::Pointer &_Right) const; protected: CompareCriteria m_CompareCriteria; CompareOperator m_CompareOperator; }; //#Protected SETTER protected: /// /// Called when DataStorage or Predicate changed. Resets whole model and reads all nodes /// in again. /// virtual void Reset(); //#Protected MEMBER VARIABLES protected: /// /// Pointer to the DataStorage from which the nodes are selected (remember: in BlueBerry there /// might be more than one DataStorage). /// Store it in a weak pointer. This is a GUI class which should not hold a strong reference /// to any non-GUI Object. /// mitk::WeakPointer m_DataStorage; /// /// Holds the predicate that defines this SubSet of Nodes. If m_Predicate /// is nullptr all Nodes will be selected. /// mitk::NodePredicateBase::Pointer m_Predicate; /// /// Holds all selected Nodes. /// std::vector m_NodeSet; /// /// \brief Maps a property to an observer tag. /// std::map m_NamePropertyModifiedObserverTags; /// /// \brief Maps a property to an observer tag. /// std::map m_VisiblePropertyModifiedObserverTags; /// /// Saves if this model is currently working on events to prevent endless event loops. /// bool m_BlockEvents; /// /// \brief The property is true when the property list is sorted in descending order. /// bool m_SortDescending; }; #endif diff --git a/Modules/QtWidgets/include/QmitkPropertiesTableModel.h b/Modules/QtWidgets/include/QmitkPropertiesTableModel.h index 92ad8fd103..8dc13e55ca 100644 --- a/Modules/QtWidgets/include/QmitkPropertiesTableModel.h +++ b/Modules/QtWidgets/include/QmitkPropertiesTableModel.h @@ -1,249 +1,249 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ /// Header guard. #ifndef QmitkPropertiesTableModel_h #define QmitkPropertiesTableModel_h #include //# Own includes #include "mitkDataNode.h" #include "mitkWeakPointer.h" //# Toolkit includes #include #include #include //# Forward declarations /** * \ingroup QmitkModule * \brief A table model for showing and editing mitk::Properties. * * \see QmitkPropertyDelegate */ class MITKQTWIDGETS_EXPORT QmitkPropertiesTableModel : public QAbstractTableModel { //# PUBLIC CTORS,DTOR,TYPEDEFS,CONSTANTS public: static const int PROPERTY_NAME_COLUMN = 0; static const int PROPERTY_VALUE_COLUMN = 1; /// /// Typedef for the complete Property Datastructure, which may be written as follows: /// Name->(mitk::BaseProperty::Pointer) /// typedef std::pair PropertyDataSet; /// /// Constructs a new QmitkDataStorageTableModel /// and sets the DataNode for this TableModel. QmitkPropertiesTableModel(QObject *parent = nullptr, mitk::PropertyList::Pointer _PropertyList = nullptr); /// /// Standard dtor. Nothing to do here. ~QmitkPropertiesTableModel() override; //# PUBLIC GETTER public: /// /// Returns the property list of this table model. /// mitk::PropertyList::Pointer GetPropertyList() const; /// /// Overwritten from QAbstractTableModel. Returns the flags what can be done with the items (view, edit, ...) Qt::ItemFlags flags(const QModelIndex &index) const override; /// /// Overwritten from QAbstractTableModel. Returns the flags what can be done with the items (view, edit, ...) QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; /// /// Overwritten from QAbstractTableModel. Returns the flags what can be done with the items (view, edit, ...) QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; /// /// Overwritten from QAbstractTableModel. Returns the flags what can be done with the items (view, edit, ...) int rowCount(const QModelIndex &parent = QModelIndex()) const override; /// /// Overwritten from QAbstractTableModel. Returns the number of columns. That is usually two in this model: /// the properties name and its value. int columnCount(const QModelIndex &parent) const override; //# PUBLIC SETTER public: /// /// Sets the Property List to show. Resets the whole model. If _PropertyList is nullptr the model is empty. /// void SetPropertyList(mitk::PropertyList *_PropertyList); /// /// \brief Gets called when the list is about to be deleted. /// virtual void PropertyListDelete(); /// /// \brief Called when a single property was changed. Send a model changed event to the Qt-outer world. /// virtual void PropertyModified(const itk::Object *caller, const itk::EventObject &event); /// /// \brief Called when a single property was changed. Send a model changed event to the Qt-outer world. /// virtual void PropertyDelete(const itk::Object *caller, const itk::EventObject &event); /// /// \brief Set a keyword for filtering of properties. Only properties beginning with this string will be shown /// virtual void SetFilterPropertiesKeyWord(std::string _FilterKeyWord); /// /// Overridden from QAbstractTableModel. Sets data at index for given role. /// bool setData(const QModelIndex &index, const QVariant &value, int role) override; /// /// \brief Reimplemented sort function from QAbstractTableModel to enable sorting on the table. /// void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; //#PROTECTED INNER CLASSES protected: /// /// \struct PropertyDataSetCompareFunction - /// \brief A struct that inherits from std::binary_function. You can use it in std::sort algorithm for sorting the + /// \brief A struct that you can use in std::sort algorithm for sorting the /// property list elements. /// - struct PropertyDataSetCompareFunction : public std::binary_function + struct PropertyDataSetCompareFunction { /// /// \brief Specifies field of the property with which it will be sorted. /// enum CompareCriteria { CompareByName = 0, CompareByValue }; /// /// \brief Specifies Ascending/descending ordering. /// enum CompareOperator { Less = 0, Greater }; /// /// \brief Creates a PropertyDataSetCompareFunction. A CompareCriteria and a CompareOperator must be given. /// PropertyDataSetCompareFunction(CompareCriteria _CompareCriteria = CompareByName, CompareOperator _CompareOperator = Less); /// /// \brief The reimplemented compare function. /// bool operator()(const PropertyDataSet &_Left, const PropertyDataSet &_Right) const; protected: CompareCriteria m_CompareCriteria; CompareOperator m_CompareOperator; }; /// /// An unary function for selecting Properties in a vector by a key word. /// - struct PropertyListElementFilterFunction : public std::unary_function + struct PropertyListElementFilterFunction { PropertyListElementFilterFunction(const std::string &m_FilterKeyWord); /// /// \brief The reimplemented compare function. /// bool operator()(const PropertyDataSet &_Elem) const; protected: std::string m_FilterKeyWord; }; //# PROTECTED GETTER protected: /// /// \brief Searches for the specified property and returns the row of the element in this QTableModel. /// If any errors occur, the function returns -1. /// int FindProperty(const mitk::BaseProperty *_Property) const; //# PROTECTED SETTER protected: /// /// Adds a property dataset to the current selection. /// When a property is added a modified and delete listener /// is appended. /// void AddSelectedProperty(PropertyDataSet &_PropertyDataSet); /// /// Removes a property dataset from the current selection. /// When a property is removed the modified and delete listener /// are also removed. /// void RemoveSelectedProperty(unsigned int _Index); /// /// Reset is called when a new filter keyword is set or a new /// PropertyList is set. First of all, all priorly selected /// properties are removed. Then all properties to be /// selected (specified by the keyword) are added to the selection. /// void Reset(); //# PROTECTED MEMBERS protected: /// /// Holds the pointer to the properties list. Dont use smart pointers here. Instead: Listen /// to the delete event. mitk::WeakPointer m_PropertyList; /// /// Store the properties in a vector so that they may be sorted std::vector m_SelectedProperties; /// /// \brief Holds all tags of Modified Event Listeners. We need it to remove them again. /// std::vector m_PropertyModifiedObserverTags; /// /// \brief Holds all tags of Modified Event Listeners. We need it to remove them again. /// std::vector m_PropertyDeleteObserverTags; unsigned long m_PropertyListDeleteObserverTag; /// /// \brief Indicates if this class should neglect all incoming events because /// the class itself triggered the event (e.g. when a property was edited). /// bool m_BlockEvents; /// /// \brief The property is true when the property list is sorted in descending order. /// bool m_SortDescending; /// /// \brief If set to any value, only properties containing the specified keyword in their name will be shown. /// std::string m_FilterKeyWord; }; #endif /* QMITKPROPERTIESTABLEMODEL_H_ */ diff --git a/Modules/QtWidgets/src/QmitkIOUtil.cpp b/Modules/QtWidgets/src/QmitkIOUtil.cpp index f25869f0e2..abda3c7626 100644 --- a/Modules/QtWidgets/src/QmitkIOUtil.cpp +++ b/Modules/QtWidgets/src/QmitkIOUtil.cpp @@ -1,586 +1,586 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All 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 #include #include "QmitkFileReaderOptionsDialog.h" #include "QmitkFileWriterOptionsDialog.h" // QT #include #include #include #include #include // ITK #include #include 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)) { 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 : public std::unary_function +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 mimeTypeProvider(mitk::CoreServices::GetMimeTypeProvider()); std::vector categories = mimeTypeProvider->GetCategories(); for (std::vector::iterator cat = categories.begin(); cat != categories.end(); ++cat) { QSet filterExtensions; std::vector mimeTypes = mimeTypeProvider->GetMimeTypesForCategory(*cat); for (std::vector::iterator mt = mimeTypes.begin(); mt != mimeTypes.end(); ++mt) { std::vector extensions = mt->GetExtensions(); for (std::vector::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 QmitkIOUtil::Load(const QStringList &paths, QWidget *parent) { std::vector 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 qResult; for (std::vector::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 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 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 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 &data, const QStringList &defaultBaseNames, const QString &defaultPath, QWidget *parent, bool setPathProperty) { QStringList fileNames; QString currentPath = defaultPath; std::vector saveInfos; int counter = 0; for (std::vector::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(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 filterMimeTypes = filters.GetMimeTypes(); for (std::vector::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 mimeTypes = saveInfo.m_WriterSelector.GetMimeTypes(); for (std::vector::const_reverse_iterator iter = mimeTypes.rbegin(), iterEnd = mimeTypes.rend(); iter != iterEnd; ++iter) { QList filterExtensions; mitk::MimeType mimeType = *iter; std::vector 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 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 QmitkIOUtil::SaveFilter::GetMimeTypes() const { return d->m_MimeTypes; } QString QmitkIOUtil::SaveFilter::GetFilterForMimeType(const std::string &mimeType) const { std::vector::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(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/Plugins/org.blueberry.core.runtime/src/berryDebugUtil.cpp b/Plugins/org.blueberry.core.runtime/src/berryDebugUtil.cpp index 7490b5cb8a..7aadca18ea 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 #include #include #include #include #include #include #include #include #include #include #include #include #include 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 > DebugUtil::m_TraceIdToSmartPointerMap; QHash DebugUtil::m_TraceIdToObjectMap; QSet DebugUtil::m_TracedObjects; QSet DebugUtil::m_TracedClasses; -class NotClassName: public std::unary_function +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 DebugUtil::GetTracedObjects() { return m_TracedObjects; } const Object* DebugUtil::GetObject(unsigned int traceId) { return m_TraceIdToObjectMap[traceId]; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER QList DebugUtil::GetSmartPointerIDs( const Object* objectPointer, const QList& excludeList) { Q_ASSERT(objectPointer != 0); QList ids = m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()]; for (QList::const_iterator iter = excludeList.begin(); iter != excludeList.end(); ++iter) ids.removeAll(*iter); return ids; } #else QList DebugUtil::GetSmartPointerIDs( const Object* /*objectPointer*/, const QList& /*excludeList*/) { return QList(); } #endif QList DebugUtil::GetRegisteredObjects() { return m_TraceIdToObjectMap.values(); } void DebugUtil::PrintSmartPointerIDs(const Object* objectPointer, const QList& excludeList) { qDebug() << "SmartPointer IDs [ "; if (IsTraced(objectPointer)) { QList ids = GetSmartPointerIDs(objectPointer, excludeList); for (QList::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 names; for (auto object : qAsConst(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::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::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::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 (elementList->item(static_cast(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 (elementList->item(static_cast(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.ui.qt/src/internal/berryEditorRegistry.h b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.h index d0b9bedd82..3ac251dbc6 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryEditorRegistry.h @@ -1,760 +1,754 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYEDITORREGISTRY_H_ #define BERRYEDITORREGISTRY_H_ #include #include "berryIEditorRegistry.h" #include "berryIFileEditorMapping.h" #include "berryEditorDescriptor.h" #include "berryFileEditorMapping.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * Provides access to the collection of defined editors for resource types. */ class EditorRegistry : public IEditorRegistry { class RelatedRegistry { public: RelatedRegistry(EditorRegistry* editorRegistry); /** * Return the objects related to the type. * * @param type * @return the objects related to the type */ // public: QList GetRelatedObjects(IContentType type) { // IEditorDescriptor[] relatedObjects = (IEditorDescriptor[]) contentTypeToEditorMappings.get(type); // if (relatedObjects == null) { // return EMPTY; // } // return (IEditorDescriptor[]) WorkbenchActivityHelper.restrictArray(relatedObjects); // } /** * Return the objects related to the filename * @param fileName * @return the objects related to the filename */ public: QList GetRelatedObjects( const QString& fileName); private: EditorRegistry* editorRegistry; }; friend class RelatedRegistry; /** * Map of FileEditorMapping (extension to FileEditorMapping) Uses two * java.util.HashMap: one keeps the default which are set by the plugins and * the other keeps the changes made by the user through the preference page. */ class EditorMap { static QHash defaultMap; static QHash map; public: void Clear(); /** * Put a default mapping into the editor map. * * @param key the key to set * @param value the value to associate */ public: static void PutDefault(const QString& key, FileEditorMapping::Pointer value); /** * Put a mapping into the user editor map. * * @param key the key to set * @param value the value to associate */ public: void Put(const QString& key, FileEditorMapping::Pointer value); /** * Return the mapping associated to the key. First searches user * map, and then falls back to the default map if there is no match. May * return null * * @param key * the key to search for * @return the mapping associated to the key or null */ public: FileEditorMapping::Pointer Get(const QString& key); /** * Return all mappings. This will return default mappings overlayed with * user mappings. * * @return the mappings */ public: QList AllMappings(); /** * Return all user mappings. * * @return the mappings */ public: QList UserMappings(); }; - struct CmpFileEditorMapping : public std::binary_function + struct CmpFileEditorMapping { bool operator()(const FileEditorMapping::Pointer& x, const FileEditorMapping::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; - struct CmpIEditorDescriptor : public std::binary_function + struct CmpIEditorDescriptor { bool operator()(const IEditorDescriptor::Pointer& x, const IEditorDescriptor::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; - struct CmpEditorDescriptor : public std::binary_function + struct CmpEditorDescriptor { bool operator()(const EditorDescriptor::Pointer& x, const EditorDescriptor::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; //private: Map contentTypeToEditorMappings = new HashMap(); /* * Cached images - these include images from registered editors (via * plugins) and others hence this table is not one to one with the mappings * table. It is in fact a superset of the keys one would find in * typeEditorMappings */ //private: Map extensionImages = new HashMap(); /** * Vector of EditorDescriptor - all the editors loaded from plugin files. * The list is kept in order to be able to show in the editor selection * dialog of the resource associations page. This list is sorted based on the * human readable label of the editor descriptor. * * @see #comparer */ private: QList sortedEditorsFromPlugins; // Map of EditorDescriptor - map editor id to editor. private: QHash mapIDtoEditor; // Map of FileEditorMapping (extension to FileEditorMapping) private: EditorMap typeEditorMappings; /* * Compares the labels from two IEditorDescriptor objects */ //private: // static final Comparator comparer = new Comparator() // { // private Collator collator = Collator.getInstance(); // // public int compare(Object arg0, Object arg1) // { // String s1 = ((IEditorDescriptor) arg0).getLabel(); // String s2 = ((IEditorDescriptor) arg1).getLabel(); // return collator.compare(s1, s2); // } // }; private: RelatedRegistry relatedRegistry; public: static const QString EMPTY_EDITOR_ID; // = "org.blueberry.ui.internal.emptyEditorTab" /** * Return an instance of the receiver. Adds listeners into the extension * registry for dynamic UI purposes. */ public: EditorRegistry(); /** * Add an editor for the given extensions with the specified (possibly null) * extended type. The editor is being registered from a plugin * * @param editor * The description of the editor (as obtained from the plugin * file and built by the registry reader) * @param extensions * Collection of file extensions the editor applies to * @param filenames * Collection of filenames the editor applies to * @param contentTypeVector * @param bDefault * Indicates whether the editor should be made the default editor * and hence appear first inside a FileEditorMapping * * This method is not API and should not be called outside the workbench * code. */ public: void AddEditorFromPlugin(EditorDescriptor::Pointer editor, const QList& extensions, const QList& filenames, const QList& contentTypeVector, bool bDefault); /** * Add external editors to the editor mapping. */ private: void AddExternalEditorsToEditorMap(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ //public: void AddPropertyListener(IPropertyListener l) { // addListenerObject(l); // } /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: IEditorDescriptor::Pointer FindEditor(const QString& id) override; /** * Fires a property changed event to all registered listeners. * * @param type the type of event * @see IEditorRegistry#PROP_CONTENTS */ // private: void FirePropertyChange(final int type) { // Object[] array = getListeners(); // for (int nX = 0; nX < array.length; nX++) { // final IPropertyListener l = (IPropertyListener) array[nX]; // Platform.run(new SafeRunnable() { // public: void run() { // l.propertyChanged(EditorRegistry.this, type); // } // }); // } // } /* * (non-Javadoc) Method declared on IEditorRegistry. * * @deprecated */ public: IEditorDescriptor::Pointer GetDefaultEditor() override; /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: IEditorDescriptor::Pointer GetDefaultEditor(const QString& filename) override; /** * Return the (approximated) content type for a file with the given name. * * @param filename the filename * @return the content type or null if it could not be determined * @since 3.1 */ // private: IContentType::Pointer GuessAtContentType(const QString& filename) { // return Platform.getContentTypeManager().findContentTypeFor(filename); // } /** * Returns the default file image descriptor. * * @return the image descriptor */ // private: ImageDescriptor GetDefaultImage() { // // @issue what should be the default image? // return WorkbenchImages.getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: QList GetEditors(const QString& filename) override; /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: QList GetFileEditorMappings() override; /* * (non-Javadoc) Method declared on IEditorRegistry. */ // public: ImageDescriptor GetImageDescriptor(String filename) { // return getImageDescriptor(filename, guessAtContentType(filename)); // } /** * Find the file editor mapping for the file extension. Returns * null if not found. * * @param ext * the file extension * @return the mapping, or null */ private: FileEditorMapping::Pointer GetMappingFor(const QString& ext); /** * Find the file editor mappings for the given filename. *

* Return an array of two FileEditorMapping items, where the first mapping * is for the entire filename, and the second mapping is for the filename's * extension only. These items can be null if no mapping exist on the * filename and/or filename's extension.

* * @param filename the filename * @return the mappings */ private: QList GetMappingForFilename(const QString& filename); /** * Return the editor descriptors pulled from the OS. *

* WARNING! The image described by each editor descriptor is *not* known by * the workbench's graphic registry. Therefore clients must take care to * ensure that if they access any of the images held by these editors that * they also dispose them *

* @return the editor descriptors */ //public: QList GetSortedEditorsFromOS(); /** * Return the editors loaded from plugins. * * @return the sorted array of editors declared in plugins * @see #comparer */ public: QList GetSortedEditorsFromPlugins(); /** * Answer an intial id to editor map. This will create a new map and * populate it with the default system editors. * * @param initialSize * the initial size of the map * @return the new map */ private: void InitialIdToEditorMap(QHash& map); /** * Add the system editors to the provided map. This will always add an * editor with an id of {@link #SYSTEM_EXTERNAL_EDITOR_ID} and may also add * an editor with id of {@link #SYSTEM_INPLACE_EDITOR_ID} if the system * configuration supports it. * * @param map the map to augment */ private: void AddSystemEditors(QHash& map); /** * Initialize the registry state from plugin declarations and preference * overrides. */ private: void InitializeFromStorage(); /** * Set the default editors according to the preference store which can be * overwritten in the file properties.ini. In the form: *

* ext1:id1;ext2:id2;... *

* * @param defaultEditors the default editors to set */ private: void SetProductDefaults(const QString& defaultEditors); /** * Read the editors defined in the preferences store. * * @param editorTable * Editor table to store the editor definitions. * @return true if the table is built succesfully. */ private: bool ReadEditors(QHash& editorTable); /** * Read the file types and associate them to their defined editor(s). * * @param editorTable * The editor table containing the defined editors. * @param reader * Reader containing the preferences content for the resources. * * @throws WorkbenchException */ public: void ReadResources(QHash& editorTable, std::ostream& reader); /** * Determine if the editors list contains the editor descriptor. * * @param editorsArray * The list of editors * @param editorDescriptor * The editor descriptor * @return true if the editors list contains the editor descriptor */ private: bool Contains(const QList& editorsArray, IEditorDescriptor::Pointer editorDescriptor); /** * Creates the reader for the resources preferences defined in the * preference store. * * @param editorTable * The editor table containing the defined editors. * @return true if the resources are read succesfully. */ private: bool ReadResources(QHash& editorTable); /** * Load the serialized resource associations Return true if the operation * was successful, false otherwise */ private: bool LoadAssociations(); /** * Return a friendly version of the given key suitable for use in the editor * map. */ private: QString MappingKeyFor(const QString& type); /** * Return a key that combines the file's name and extension of the given * mapping * * @param mapping the mapping to generate a key for */ private: QString MappingKeyFor(FileEditorMapping::Pointer mapping); /** * Rebuild the editor map */ private: void RebuildEditorMap(); /** * Rebuild the internal editor mapping. */ private: void RebuildInternalEditorMap(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ // public: void RemovePropertyListener(IPropertyListener l) { // removeListenerObject(l); // } /** * Save the registry to the filesystem by serializing the current resource * associations. */ public: void SaveAssociations(); /** * Set the collection of FileEditorMappings. The given collection is * converted into the internal hash table for faster lookup Each mapping * goes from an extension to the collection of editors that work on it. This * operation will rebuild the internal editor mappings. * * @param newResourceTypes * te new file editor mappings. */ public: void SetFileEditorMappings(const QList& newResourceTypes); /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: void SetDefaultEditor(const QString& fileName, const QString& editorId) override; /** * Alphabetically sort the internal editors. * * @see #comparer */ private: QList SortEditors(const QList& unsortedList); /** * Alphabetically sort the internal editors. * * @see #comparer */ private: void SortInternalEditors(); /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#isSystemInPlaceEditorAvailable(String) */ public: bool IsSystemInPlaceEditorAvailable(const QString& filename) override; /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#isSystemExternalEditorAvailable(String) */ public: bool IsSystemExternalEditorAvailable(const QString& filename) override; /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#getSystemExternalEditorImageDescriptor(java.lang.String) */ // public: ImageDescriptor GetSystemExternalEditorImageDescriptor( // const QString& filename) { // Program externalProgram = null; // int extensionIndex = filename.lastIndexOf('.'); // if (extensionIndex >= 0) { // externalProgram = Program.findProgram(filename // .substring(extensionIndex)); // } // if (externalProgram == null) { // return null; // } // // return new ExternalProgramImageDescriptor(externalProgram); // } /** * Removes the entry with the value of the editor descriptor from the given * map. If the descriptor is the last descriptor in a given * FileEditorMapping then the mapping is removed from the map. * * @param map * the map to search * @param desc * the descriptor value to remove */ private: void RemoveEditorFromMapping(QHash& map, IEditorDescriptor::Pointer desc); private: IExtensionPoint::Pointer GetExtensionPointFilter(); /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getDefaultEditor(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: IEditorDescriptor::Pointer GetDefaultEditor(const QString& fileName, IContentType contentType) { // return getEditorForContentType(fileName, contentType); // } /** * Return the editor for a file with a given content type. * * @param filename the file name * @param contentType the content type * @return the editor for a file with a given content type * @since 3.1 */ private: IEditorDescriptor::Pointer GetEditorForContentType(const QString& filename /*IContentType contentType*/); /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getEditors(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: QList GetEditors(const QString& fileName, IContentType contentType) { // return findRelatedObjects(contentType, fileName, relatedRegistry); // } /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getImageDescriptor(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: ImageDescriptor GetImageDescriptor(const QString filename, IContentType contentType) { // if (filename == null) { // return getDefaultImage(); // } // // if (contentType != null) { // IEditorDescriptor desc = getEditorForContentType(filename, contentType); // if (desc != null) { // ImageDescriptor anImage = (ImageDescriptor) extensionImages.get(desc); // if (anImage != null) { // return anImage; // } // anImage = desc.getImageDescriptor(); // extensionImages.put(desc, anImage); // return anImage; // } // } // // Lookup in the cache first... // String key = mappingKeyFor(filename); // ImageDescriptor anImage = (ImageDescriptor) extensionImages.get(key); // if (anImage != null) { // return anImage; // } // // // See if we have a mapping for the filename or extension // FileEditorMapping[] mapping = getMappingForFilename(filename); // for (int i = 0; i < 2; i++) { // if (mapping[i] != null) { // // Lookup in the cache first... // String mappingKey = mappingKeyFor(mapping[i]); // ImageDescriptor mappingImage = (ImageDescriptor) extensionImages // .get(key); // if (mappingImage != null) { // return mappingImage; // } // // Create it and cache it // IEditorDescriptor editor = mapping[i].getDefaultEditor(); // if (editor != null) { // mappingImage = editor.getImageDescriptor(); // extensionImages.put(mappingKey, mappingImage); // return mappingImage; // } // } // } // // // Nothing - time to look externally for the icon // anImage = getSystemExternalEditorImageDescriptor(filename); // if (anImage == null) { // anImage = getDefaultImage(); // } // // for dynamic UI - comment out the next line // //extensionImages.put(key, anImage); // return anImage; // // } /** * Find objects related to the content type. * * This method is temporary and exists only to back us off of the * soon-to-be-removed IContentTypeManager.IRelatedRegistry API. * * @param type * @param fileName * @param registry * @return the related objects */ private: QList FindRelatedObjects(/*IContentType type,*/ const QString& fileName, RelatedRegistry& registry); /** * Return the editors bound to this content type, either directly or indirectly. * * @param type the content type to check * @return the editors * @since 3.1 * * TODO: this should be rolled in with the above findRelatedObjects code */ // public: QList GetEditorsForContentType(IContentType type) { // ArrayList allRelated = new ArrayList(); // if (type == null) { // return new IEditorDescriptor [0]; // } // // Object [] related = relatedRegistry.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]); // } // // } // } // // // now add any indirectly related objects, walking up the content type hierarchy // while ((type = type.getBaseType()) != null) { // related = relatedRegistry.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]); // } // } // } // } // // return (IEditorDescriptor[]) allRelated.toArray(new IEditorDescriptor[allRelated.size()]); // } /** * Get filemappings for all defined filetypes, including those defined by content type. * * @return the filetypes * @since 3.1 */ public: QList GetUnifiedMappings(); }; class MockMapping : public IFileEditorMapping { //private: IContentType contentType; private: QString extension; private: QString filename; MockMapping(/*IContentType type,*/const QString& name, const QString& ext); public: IEditorDescriptor::Pointer GetDefaultEditor() override; public: QList GetEditors() const override; public: QList GetDeletedEditors() const override; public: QString GetExtension() const override; // public: ImageDescriptor GetImageDescriptor() { // IEditorDescriptor editor = getDefaultEditor(); // if (editor == null) { // return WorkbenchImages // .getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } // // return editor.getImageDescriptor(); // } public: QString GetLabel() const override; public: QString GetName() const override; /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public: bool operator==(const Object* obj) const override; }; } #endif /*BERRYEDITORREGISTRY_H_*/ diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h index d5d7d52b3c..c1c9cf1bcd 100755 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h @@ -1,552 +1,552 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYPERSPECTIVEHELPER_H_ #define BERRYPERSPECTIVEHELPER_H_ #include "berryWorkbenchPage.h" #include "berryPartPlaceholder.h" #include "berryPerspective.h" #include "berryViewSashContainer.h" #include "berryPartPlaceholder.h" #include "berryDetachedWindow.h" #include "berryDetachedPlaceHolder.h" #include "berryIDragOverListener.h" #include "berryAbstractDropTarget.h" #include "berryPartPane.h" namespace berry { class WorkbenchPage; /** * A perspective presentation is a collection of parts with a layout. Each part * is parented to a main window, so you can create more than one presentation * on a set of parts and change the layout just by activating / deactivating a * presentation. * * In addition, the user can change the position of any part by mouse * manipulation (drag & drop). If a part is removed, we leave a placeholder * behind to indicate where it goes should the part be added back. */ class PerspectiveHelper { friend class PartStack; friend class ViewSashContainer; private: QScopedPointer tmpStackTrace; QString tmpViewId; WorkbenchPage* page; protected: Perspective* perspective; QWidget* parentWidget; private: ViewSashContainer::Pointer mainLayout; //private: PartStack maximizedStack; /** * If there is a ViewStack maximized on shutdown the id is * cached and restored into this field on 'restoreState'. * This is then used to bash the ViewStack's presentation state * into the correct value on activation (the startup life-cycle * is such that we have to use this 'latch' because the window * state isn't valid until the activate happens. */ //private: String maximizedStackId; private: typedef QList DetachedWindowsType; DetachedWindowsType detachedWindowList; typedef QList DetachedPlaceHoldersType; DetachedPlaceHoldersType detachedPlaceHolderList; /** * Maps a stack's id to its current bounds * this is used to capture the current bounds of all * stacks -before- starting a maximize (since the * iterative 'minimize' calls cause the intial stack's * bounds to change. */ QHash boundsMap; bool detachable; protected: bool active; // key is the LayoutPart object, value is the PartDragDrop object //private: IPartDropListener partDropListener; private: static const int MIN_DETACH_WIDTH; static const int MIN_DETACH_HEIGHT; struct DragOverListener: public IDragOverListener { DragOverListener(PerspectiveHelper* perspHelper); IDropTarget::Pointer Drag(QWidget* currentControl, const Object::Pointer& draggedObject, const QPoint& position, const QRect& dragRectangle) override; private: PerspectiveHelper* perspHelper; }; QScopedPointer dragTarget; struct ActualDropTarget: public AbstractDropTarget { berryObjectMacro(ActualDropTarget); /** * @param part * @param dragRectangle * @since 3.1 */ void SetTarget(PartPane::Pointer part, const QRect& dragRectangle); /** * @param part * @param dragRectangle * @since 3.1 */ void SetTarget(PartStack::Pointer part, const QRect& dragRectangle); ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const QRect& dragRectangle); ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer part, const QRect& dragRectangle); void Drop() override; CursorType GetCursor() override; private: PartPane::Pointer part; PartStack::Pointer stack; QRect dragRectangle; PerspectiveHelper* perspHelper; }; ActualDropTarget::Pointer dropTarget; private: struct MatchingPart { QString pid; QString sid; LayoutPart::Pointer part; bool hasWildcard; int len; MatchingPart(const QString& pid, const QString& sid, LayoutPart::Pointer part); }; - struct CompareMatchingParts: public std::binary_function + struct CompareMatchingParts { bool operator()(const MatchingPart& m1, const MatchingPart& m2) const; }; public: /** * Constructs a new object. */ PerspectiveHelper(WorkbenchPage* workbenchPage, ViewSashContainer::Pointer mainLayout, Perspective* perspective); /** * Show the presentation. */ void Activate(QWidget* parent); /** * Adds a part to the presentation. If a placeholder exists for the part * then swap the part in. Otherwise, add the part in the bottom right * corner of the presentation. */ void AddPart(LayoutPart::Pointer part); /** * Attaches a part that was previously detached to the mainLayout. * * @param ref */ void AttachPart(IViewReference::Pointer ref); /** * Return whether detachable parts can be supported. */ bool CanDetach(); /** * Bring a part forward so it is visible. * * @return true if the part was brought to top, false if not. */ bool BringPartToTop(LayoutPart::Pointer part); /** * Returns true if the given part is visible. * A part is visible if it's top-level (not in a tab folder) or if it is the top one * in a tab folder. */ bool IsPartVisible(IWorkbenchPartReference::Pointer partRef); /** * Returns true is not in a tab folder or if it is the top one in a tab * folder. */ bool WillPartBeVisible(const QString& partId); bool WillPartBeVisible(const QString& partId, const QString& secondaryId); /** * Answer a list of the view panes. */ void CollectViewPanes(QList& result); /** * Hide the presentation. */ void Deactivate(); ~PerspectiveHelper(); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. *

* This is only intended for use by test suites. *

* * @param buf */ void DescribeLayout(QString& buf) const; private: /** * Answer a list of the PartPlaceholder objects. */ QList CollectPlaceholders(); /** * Answer a list of the PartPlaceholder objects. */ QList CollectPlaceholders( const QList& parts); /** * Answer a list of the view panes. */ void CollectViewPanes(QList& result, const QList& parts); /** * Create a detached window containing a part. */ void DetachPart(LayoutPart::Pointer source, int x, int y); void Detach(LayoutPart::Pointer source, int x, int y); protected: /** * Deref a given part. Deconstruct its container as required. Do not remove * drag listeners. */ void DerefPart(LayoutPart::Pointer part); /** * Detached a part from the mainLayout. Presently this does not use placeholders * since the current implementation is not robust enough to remember a view's position * in more than one root container. For now the view is simply derefed and will dock * in the default position when attachPart is called. * * By default parts detached this way are set to float on top of the workbench * without docking. It is assumed that people that want to drag a part back onto * the WorkbenchWindow will detach it via drag and drop. * * @param ref */ public: void DetachPart(IViewReference::Pointer ref); /** * Create a detached window containing a part. */ public: void AddDetachedPart(LayoutPart::Pointer part); public: void AddDetachedPart(LayoutPart::Pointer part, const QRect& bounds); /** * disableDragging. */ private: void DisableAllDrag(); /** * enableDragging. */ private: void EnableAllDrag(); /** * Find the first part with a given ID in the presentation. * Wild cards now supported. */ private: LayoutPart::Pointer FindPart(const QString& id); /** * Find the first part that matches the specified * primary and secondary id pair. Wild cards * are supported. */ public: LayoutPart::Pointer FindPart(const QString& primaryId, const QString& secondaryId); /** * Find the first part with a given ID in the presentation. */ private: LayoutPart::Pointer FindPart(const QString& id, const QList& parts, QList& matchingParts); /** * Find the first part that matches the specified * primary and secondary id pair. Wild cards * are supported. */ private: LayoutPart::Pointer FindPart(const QString& primaryId, const QString& secondaryId, const QList& parts, QList& matchingParts); /** * Returns true if a placeholder exists for a given ID. */ public: bool HasPlaceholder(const QString& id); /** * Returns true if a placeholder exists for a given ID. * @since 3.0 */ public: bool HasPlaceholder(const QString& primaryId, const QString& secondaryId); /** * Returns the layout container. */ public: PartSashContainer::Pointer GetLayout() const; /** * Gets the active state. */ public: bool IsActive(); /** * Returns whether the presentation is zoomed. * * NOTE: As of 3.3 this method should always return 'false' * when using the new min/max behavior. It is only used for * legacy 'zoom' handling. */ // public: bool IsZoomed() { // return mainLayout.getZoomedPart() != null; // } /** * @return The currently maxmized stack (if any) */ // public: PartStack::Pointer GetMaximizedStack() { // return maximizedStack; // } /** * Sets the currently maximized stack. Used for query * and 'unZoom' purposes in the 3.3 presentation. * * @param stack The newly maximized stack */ // public: void SetMaximizedStack(PartStack::Pointer stack) { // if (stack == maximizedStack) // return; // // maximizedStack = stack; // } /** * Returns the ratio that should be used when docking the given source * part onto the given target * * @param source newly added part * @param target existing part being dragged over * @return the final size of the source part (wrt the current size of target) * after it is docked */ public: static float GetDockingRatio(LayoutPart::Pointer source, LayoutPart::Pointer target); /** * Returns whether changes to a part will affect zoom. There are a few * conditions for this .. - we are zoomed. - the part is contained in the * main window. - the part is not the zoom part - the part is not a fast * view - the part and the zoom part are not in the same editor workbook * - the part and the zoom part are not in the same view stack. */ // public: bool PartChangeAffectsZoom(LayoutPart::Pointer pane) { // return pane.isObscuredByZoom(); // } /** * Remove all references to a part. */ public: void RemovePart(LayoutPart::Pointer part); /** * Add a part to the presentation. * * Note: unlike all other LayoutParts, PartPlaceholders will still point to * their parent container even when it is inactive. This method relies on this * fact to locate the parent. */ public: void ReplacePlaceholderWithPart(LayoutPart::Pointer part); /** * @see org.blueberry.ui.IPersistable */ public: bool RestoreState(IMemento::Pointer memento); /** * @see org.blueberry.ui.IPersistable */ public: bool SaveState(IMemento::Pointer memento); /** * Zoom in on a particular layout part. */ // public: void zoomIn(IWorkbenchPartReference ref) { // PartPane pane = ((WorkbenchPartReference) ref).getPane(); // // // parentWidget.setRedraw(false); // try { // pane.requestZoomIn(); // } finally { // parentWidget.setRedraw(true); // } // } /** * Zoom out. */ // public: void zoomOut() { // // New 3.3 behavior // if (Perspective.useNewMinMax(perspective)) { // if (maximizedStack != null) // maximizedStack.setState(IStackPresentationSite.STATE_RESTORED); // return; // } // // LayoutPart zoomPart = mainLayout.getZoomedPart(); // if (zoomPart != null) { // zoomPart.requestZoomOut(); // } // } /** * Forces the perspective to have no zoomed or minimized parts. * This is used when switching to the 3.3 presentation... */ // public: void forceNoZoom() { // // Ensure that nobody's zoomed // zoomOut(); // // // Now, walk the layout ensuring that nothing is minimized // LayoutPart[] kids = mainLayout.getChildren(); // for (int i = 0; i < kids.length; i++) { // if (kids[i] instanceof ViewStack) { // ((ViewStack)kids[i]).setMinimized(false); // } // else if (kids[i] instanceof EditorSashContainer) { // LayoutPart[] editorStacks = ((EditorSashContainer)kids[i]).getChildren(); // for (int j = 0; j < editorStacks.length; j++) { // if (editorStacks[j] instanceof EditorStack) { // ((EditorStack)editorStacks[j]).setMinimized(false); // } // } // } // } // } /** * Captures the current bounds of all ViewStacks and the editor * area and puts them into an ID -> QRect map. This info is * used to cache the bounds so that we can correctly place minimized * stacks during a 'maximized' operation (where the iterative min's * affect the current layout while being performed. */ public: void UpdateBoundsMap(); /** * Resets the bounds map so that it won't interfere with normal minimize * operations */ public: void ResetBoundsMap(); public: QRect GetCachedBoundsFor(const QString& id); }; } #endif /* BERRYPERSPECTIVEHELPER_H_ */ diff --git a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h index f2abe33ad0..fe4c59e7ac 100644 --- a/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h +++ b/Plugins/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h @@ -1,1429 +1,1428 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef BERRYWORKBENCHPAGE_H_ #define BERRYWORKBENCHPAGE_H_ #include #include "berryIWorkbenchPage.h" #include "berryIWorkbenchPartReference.h" #include "berryIReusableEditor.h" #include "berryILayoutContainer.h" #include "berryIStickyViewManager.h" #include "berryWorkbenchPagePartList.h" #include "berryWorkbenchPartReference.h" #include "berryPageSelectionService.h" #include "berryEditorManager.h" #include "berryViewFactory.h" #include "berryPartPane.h" #include namespace berry { struct IExtensionPoint; struct IExtensionTracker; //class PartPane; //class PartPane::Sashes; class EditorAreaHelper; class WorkbenchWindow; class Perspective; class PerspectiveHelper; class PerspectiveDescriptor; class LayoutPartSash; class LayoutTree; class LayoutTreeNode; class PartService; /** * \ingroup org_blueberry_ui_internal * * A collection of views and editors in a workbench. */ class BERRY_UI_QT WorkbenchPage: public IWorkbenchPage { public: berryObjectMacro(WorkbenchPage); protected: //TODO Weakpointer WorkbenchWindow* window; friend class ViewFactory; friend class WorkbenchWindow; friend class EditorAreaHelper; friend class WWinPartService; private: /** * Manages editor contributions and action set part associations. */ class ActionSwitcher { public: ActionSwitcher(WorkbenchPage* page); /** * Updates the contributions given the new part as the active part. * * @param newPart * the new active part, may be null */ void UpdateActivePart(IWorkbenchPart::Pointer newPart); /** * Updates the contributions given the new part as the topEditor. * * @param newEditor * the new top editor, may be null */ void UpdateTopEditor(IEditorPart::Pointer newEditor); private: /** * Activates the contributions of the given part. If enable * is true the contributions are visible and enabled, * otherwise they are disabled. * * @param part * the part whose contributions are to be activated * @param enable * true the contributions are to be enabled, * not just visible. */ void ActivateContributions(IWorkbenchPart::Pointer part, bool enable); /** * Deactivates the contributions of the given part. If remove * is true the contributions are removed, otherwise they * are disabled. * * @param part * the part whose contributions are to be deactivated * @param remove * true the contributions are to be removed, * not just disabled. */ void DeactivateContributions(IWorkbenchPart::Pointer part, bool remove); WorkbenchPage* page; IWorkbenchPart::WeakPtr activePart; IEditorPart::WeakPtr topEditor; }; class ActivationList { public: //List of parts in the activation order (oldest first) typedef std::deque PartListType; typedef std::deque::iterator PartListIter; typedef std::deque::reverse_iterator PartListReverseIter; private: PartListType parts; WorkbenchPage* page; public: ActivationList(WorkbenchPage* page); /* * Add/Move the active part to end of the list; */ void SetActive(SmartPointer part); /* * Ensures that the given part appears AFTER any other part in the same * container. */ void BringToTop(SmartPointer ref); /* * Returns the last (most recent) iterator (index) of the given container in the activation list, or returns * end() if the given container does not appear in the activation list. */ PartListIter LastIndexOfContainer(SmartPointer container); /* * Add/Move the active part to end of the list; */ void SetActive(SmartPointer ref); /* * Add the active part to the beginning of the list. */ void Add(SmartPointer ref); /* * Return the active part. Filter fast views. */ SmartPointer GetActive(); /* * Return the previously active part. Filter fast views. */ SmartPointer GetPreviouslyActive(); SmartPointer GetActiveReference(bool editorsOnly); /* * Retuns the index of the part within the activation list. The higher * the index, the more recently it was used. */ PartListIter IndexOf(SmartPointer part); /* * Returns the index of the part reference within the activation list. * The higher the index, the more recent it was used. */ PartListIter IndexOf(SmartPointer ref); /* * Remove a part from the list */ bool Remove(SmartPointer ref); /* * Returns the topmost editor on the stack, or null if none. */ SmartPointer GetTopEditor(); /* * Returns the editors in activation order (oldest first). */ QList > GetEditors(); /* * Return a list with all parts (editors and views). */ QList > GetParts(); private: SmartPointer GetActive(PartListIter start); SmartPointer GetActiveReference(PartListIter start, bool editorsOnly); /* * Find a part in the list starting from the end and filter * and views from other perspectives. Will filter fast views * unless 'includeActiveFastViews' is true; */ SmartPointer GetActiveReference(PartListIter start, bool editorsOnly, bool skipPartsObscuredByZoom); }; /** * Helper class to keep track of all opened perspective. Both the opened * and used order is kept. */ struct PerspectiveList { public: typedef QList > PerspectiveListType; typedef PerspectiveListType::iterator iterator; private: /** * List of perspectives in the order they were opened; */ PerspectiveListType openedList; /** * List of perspectives in the order they were used. Last element is * the most recently used, and first element is the least recently * used. */ PerspectiveListType usedList; /** * The perspective explicitly set as being the active one */ SmartPointer active; void UpdateActionSets(SmartPointer oldPersp, SmartPointer newPersp); public: /** * Creates an empty instance of the perspective list */ PerspectiveList(); /** * Update the order of the perspectives in the opened list * * @param perspective * @param newLoc */ void Reorder(IPerspectiveDescriptor::Pointer perspective, int newLoc); /** * Return all perspectives in the order they were activated. * * @return an array of perspectives sorted by activation order, least * recently activated perspective last. */ PerspectiveListType GetSortedPerspectives(); /** * Adds a perspective to the list. No check is done for a duplicate when * adding. * @param perspective the perspective to add * @return boolean true if the perspective was added */ bool Add(SmartPointer perspective); /** * Returns an iterator on the perspective list in the order they were * opened. */ PerspectiveListType::iterator Begin(); PerspectiveListType::iterator End(); /** * Returns an array with all opened perspectives */ PerspectiveListType GetOpenedPerspectives(); /** * Removes a perspective from the list. */ bool Remove(SmartPointer perspective); /** * Swap the opened order of old perspective with the new perspective. */ void Swap(SmartPointer oldPerspective, SmartPointer newPerspective); /** * Returns whether the list contains any perspectives */ bool IsEmpty(); /** * Returns the most recently used perspective in the list. */ SmartPointer GetActive(); /** * Returns the next most recently used perspective in the list. */ SmartPointer GetNextActive(); /** * Returns the number of perspectives opened */ PerspectiveListType::size_type Size(); /** * Marks the specified perspective as the most recently used one in the * list. */ void SetActive(SmartPointer perspective); }; IAdaptable* input; QWidget* composite; //Could be delete. This information is in the active part list; ActivationList* activationList; EditorManager* editorMgr; EditorAreaHelper* editorPresentation; //ListenerList propertyChangeListeners = new ListenerList(); PageSelectionService* selectionService; QScopedPointer partList; // = new WorkbenchPagePartList(selectionService); //IActionBars actionBars; ViewFactory* viewFactory; PerspectiveList perspList; SmartPointer deferredActivePersp; //NavigationHistory navigationHistory = new NavigationHistory(this); IStickyViewManager::Pointer stickyViewMan; /** * Returns true if perspective with given id contains view with given id */ bool HasView(const QString& perspectiveId, const QString& viewId); /** * If we're in the process of activating a part, this points to the new part. * Otherwise, this is null. */ IWorkbenchPartReference::Pointer partBeingActivated; /** * Contains a list of perspectives that may be dirty due to plugin * installation and removal. */ std::set dirtyPerspectives; ActionSwitcher actionSwitcher; mutable QScopedPointer tracker; // Deferral count... delays disposing parts and sending certain events if nonzero int deferCount; // Parts waiting to be disposed QList pendingDisposals; SmartPointer GetPerspectiveExtensionPoint(); public: /** * Constructs a new page with a given perspective and input. * * @param w * the parent window * @param layoutID * must not be null * @param input * the page input * @throws WorkbenchException * on null layout id */ WorkbenchPage(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input); /** * Constructs a page. restoreState(IMemento) should be * called to restore this page from data stored in a persistance file. * * @param w * the parent window * @param input * the page input * @throws WorkbenchException */ WorkbenchPage(WorkbenchWindow* w, IAdaptable* input); ~WorkbenchPage() override; /** * Activates a part. The part will be brought to the front and given focus. * * @param part * the part to activate */ void Activate(IWorkbenchPart::Pointer part) override; /** * Adds an IPartListener to the part service. */ void AddPartListener(IPartListener* l) override; /* * (non-Javadoc) Method declared on ISelectionListener. */ void AddSelectionListener(ISelectionListener* listener) override; /* * (non-Javadoc) Method declared on ISelectionListener. */ void AddSelectionListener(const QString& partId, ISelectionListener* listener) override; /* * (non-Javadoc) Method declared on ISelectionListener. */ void AddPostSelectionListener(ISelectionListener* listener) override; /* * (non-Javadoc) Method declared on ISelectionListener. */ void AddPostSelectionListener(const QString& partId, ISelectionListener* listener) override; /** * Moves a part forward in the Z order of a perspective so it is visible. * If the part is in the same stack as the active part, the new part is * activated. * * @param part * the part to bring to move forward */ void BringToTop(IWorkbenchPart::Pointer part) override; private: /** * Activates a part. The part is given focus, the pane is hilighted. */ void ActivatePart(const IWorkbenchPart::Pointer part); ILayoutContainer::Pointer GetContainer(IWorkbenchPart::Pointer part); ILayoutContainer::Pointer GetContainer(IWorkbenchPartReference::Pointer part); SmartPointer GetPane(IWorkbenchPart::Pointer part); SmartPointer GetPane(IWorkbenchPartReference::Pointer part); /** * Brings a part to the front of its stack. Does not update the active part or * active editor. This should only be called if the caller knows that the part * is not in the same stack as the active part or active editor, or if the caller * is prepared to update activation after the call. * * @param part */ bool InternalBringToTop(IWorkbenchPartReference::Pointer part); /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. * * Assumes the busy cursor is active. */ void BusyResetPerspective(); /** * Implements setPerspective. * * Assumes that busy cursor is active. * * @param desc * identifies the new perspective. */ void BusySetPerspective(IPerspectiveDescriptor::Pointer desc); /* * Performs showing of the view in the given mode. */ void BusyShowView(IViewPart::Pointer part, int mode); /** * Returns whether a part exists in the current page. */ bool CertifyPart(IWorkbenchPart::Pointer part); protected: /** * Shows a view. * * Assumes that a busy cursor is active. */ IViewPart::Pointer BusyShowView(const QString& viewID, const QString& secondaryID, int mode); public: void UpdateActionBars(); /** * Removes the perspective which match the given description. * * @param desc * identifies the perspective to be removed. */ void RemovePerspective(IPerspectiveDescriptor::Pointer desc); /** * Closes the perspective. */ bool Close() override; /** * See IWorkbenchPage */ bool CloseAllSavedEditors(); /** * See IWorkbenchPage */ bool CloseAllEditors(bool save) override; /** * See IWorkbenchPage */ bool CloseEditors(const QList& refArray, bool save) override; private: void UpdateActivePart(); /** * Makes the given part active. Brings it in front if necessary. Permits null * (indicating that no part should be active). * * @param ref new active part (or null) */ void MakeActive(IWorkbenchPartReference::Pointer ref); /** * Makes the given editor active. Brings it to front if necessary. Permits null * (indicating that no editor is active). * * @param ref the editor to make active, or null for no active editor */ void MakeActiveEditor(IEditorReference::Pointer ref); /** * Enables or disables listener notifications. This is used to delay listener notifications until the * end of a public method. * * @param shouldDefer */ void DeferUpdates(bool shouldDefer); void StartDeferring(); void HandleDeferredEvents(); bool IsDeferred(); public: /** * See IWorkbenchPage#closeEditor */ bool CloseEditor(IEditorReference::Pointer editorRef, bool save); /** * See IWorkbenchPage#closeEditor */ bool CloseEditor(IEditorPart::Pointer editor, bool save) override; /** * Closes current perspective. If last perspective, then entire page * is closed. * * @param saveParts * whether the page's parts should be saved if closed * @param closePage * whether the page itself should be closed if last perspective */ void CloseCurrentPerspective(bool saveParts, bool closePage); /** * @see IWorkbenchPage#closePerspective(IPerspectiveDescriptor, boolean, boolean) */ void ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage) override; /** * @see IWorkbenchPage#closeAllPerspectives(boolean, boolean) */ void CloseAllPerspectives(bool saveEditors, bool closePage) override; protected: /** * Closes the specified perspective. If last perspective, then entire page * is closed. * * @param persp * the perspective to be closed * @param saveParts * whether the parts that are being closed should be saved * (editors if last perspective, views if not shown in other * parspectives) */ void ClosePerspective(SmartPointer persp, bool saveParts, bool closePage); /** * This is called by child objects after a part has been added to the page. * The page will in turn notify its listeners. */ void PartAdded(WorkbenchPartReference::Pointer ref); /** * This is called by child objects after a part has been added to the page. * The part will be queued for disposal after all listeners have been notified */ void PartRemoved(WorkbenchPartReference::Pointer ref); private: /** * Creates the client composite. */ void CreateClientComposite(); /** * Creates a new view set. Return null on failure. * * @param desc the perspective descriptor * @param notify whether to fire a perspective opened event */ SmartPointer CreatePerspective(SmartPointer desc, bool notify); void DisposePart(WorkbenchPartReference::Pointer ref); /** * Deactivates a part. The pane is unhilighted. */ void DeactivatePart(IWorkbenchPart::Pointer part); /** * Dispose a perspective. * * @param persp the perspective descriptor * @param notify whether to fire a perspective closed event */ void DisposePerspective(SmartPointer persp, bool notify); public: /** * Detaches a view from the WorkbenchWindow. */ void DetachView(IViewReference::Pointer ref); /** * Removes a detachedwindow. */ void AttachView(IViewReference::Pointer ref); /** * Returns the first view manager with given ID. */ SmartPointer FindPerspective(IPerspectiveDescriptor::Pointer desc); /** * See IWorkbenchPage@findView. */ IViewPart::Pointer FindView(const QString& id) override; /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ IViewReference::Pointer FindViewReference(const QString& viewId) override; /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ IViewReference::Pointer FindViewReference(const QString& viewId, const QString& secondaryId) override; /** * Notify property change listeners about a property change. * * @param changeId * the change id * @param oldValue * old property value * @param newValue * new property value */ //private: void FirePropertyChange(String changeId, Object oldValue, // Object newValue) { // // UIListenerLogging.logPagePropertyChanged(this, changeId, oldValue, newValue); // // Object[] listeners = propertyChangeListeners.getListeners(); // PropertyChangeEvent event = new PropertyChangeEvent(this, changeId, // oldValue, newValue); // // for (int i = 0; i < listeners.length; i++) { // ((IPropertyChangeListener) listeners[i]).propertyChange(event); // } // } /** * @see IWorkbenchPage */ IEditorPart::Pointer GetActiveEditor() override; /** * Returns the reference for the active editor, or null * if there is no active editor. * * @return the active editor reference or null */ IEditorReference::Pointer GetActiveEditorReference(); /* * (non-Javadoc) Method declared on IPartService */ IWorkbenchPart::Pointer GetActivePart() override; /* * (non-Javadoc) Method declared on IPartService */ IWorkbenchPartReference::Pointer GetActivePartReference() override; /** * Returns the active perspective for the page, null if * none. */ SmartPointer GetActivePerspective(); /** * Returns the client composite. */ QWidget* GetClientComposite(); // for dynamic UI - change access from private to protected // for testing purposes only, changed from protected to public /** * Answer the editor manager for this window. */ EditorManager* GetEditorManager(); /** * Answer the perspective presentation. */ PerspectiveHelper* GetPerspectivePresentation(); /** * Answer the editor presentation. */ EditorAreaHelper* GetEditorPresentation(); /** * Allow access to the part service for this page ... used internally to * propogate certain types of events to the page part listeners. * @return the part service for this page. */ PartService* GetPartService(); /** * See IWorkbenchPage. */ QList GetEditors() override; QList GetDirtyEditors() override; QList GetDirtyParts(); /** * See IWorkbenchPage. */ IEditorPart::Pointer FindEditor(IEditorInput::Pointer input) override; /** * See IWorkbenchPage. */ QList FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags) override; /** * See IWorkbenchPage. */ QList GetEditorReferences() override; /** * @see IWorkbenchPage */ IAdaptable* GetInput() override; /** * Returns the page label. This is a combination of the page input and * active perspective. */ QString GetLabel() override; /** * Returns the perspective. */ IPerspectiveDescriptor::Pointer GetPerspective() override; /* * (non-Javadoc) Method declared on ISelectionService */ ISelection::ConstPointer GetSelection() const override; /* * (non-Javadoc) Method declared on ISelectionService */ ISelection::ConstPointer GetSelection(const QString& partId) override; //public: // SelectionEvents& GetSelectionEvents(const QString& partId = ""); /* * Returns the view factory. */ ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ QList GetViewReferences() override; /** * See IWorkbenchPage. */ QList GetViews() override; protected: /** * Returns all view parts in the specified perspective * * @param persp the perspective * @return an array of view parts */ /*package*/ QList GetViews(SmartPointer persp, bool restore); /* package */ void RefreshActiveView(); public: /** * See IWorkbenchPage. */ IWorkbenchWindow::Pointer GetWorkbenchWindow() const override; /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#hideView(org.blueberry.ui.IViewReference) */ void HideView(IViewReference::Pointer ref) override; /** * See IPerspective */ void HideView(IViewPart::Pointer view) override; private: /** * Initialize the page. * * @param w * the parent window * @param layoutID * may be null if restoring from file * @param input * the page input * @param openExtras * whether to process the perspective extras preference */ void Init(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input, bool openExtras); /** * Opens the perspectives specified in the PERSPECTIVE_BAR_EXTRAS preference (see bug 84226). */ public: void OpenPerspectiveExtras(); /** * See IWorkbenchPage. */ bool IsPartVisible(IWorkbenchPart::Pointer part) override; /** * See IWorkbenchPage. */ bool IsEditorAreaVisible(); /** * Returns whether the view is fast. */ bool IsFastView(IViewReference::Pointer ref); /** * Return whether the view is closeable or not. * * @param ref the view reference to check. Must not be null. * @return true if the part is closeable. */ bool IsCloseable(IViewReference::Pointer ref); /** * Return whether the view is moveable or not. * * @param ref the view reference to check. Must not be null. * @return true if the part is moveable. */ bool IsMoveable(IViewReference::Pointer ref); /** * Returns whether the layout of the active * perspective is fixed. */ bool IsFixedLayout(); protected: /** * Return true if the perspective has a dirty editor. */ bool IsSaveNeeded(); /** * This method is called when the page is activated. */ void OnActivate(); /** * This method is called when the page is deactivated. */ void OnDeactivate(); public: /** * See IWorkbenchPage. */ void ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input) override; /** * See IWorkbenchPage. */ IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID) override; /** * See IWorkbenchPage. */ IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate) override; /** * See IWorkbenchPage. */ IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags) override; /** * This is not public API but for use internally. editorState can be null. */ IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * Opens a new editor using the given input and descriptor. (Normally, editors are opened using * an editor ID and an input.) */ IEditorPart::Pointer OpenEditorFromDescriptor(IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); private: /** * @see #openEditor(IEditorInput, String, boolean, int) */ IEditorPart::Pointer BusyOpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ IEditorPart::Pointer BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ IEditorPart::Pointer BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); public: void OpenEmptyTab(); /** * See IWorkbenchPage. */ bool IsEditorPinned(IEditorPart::Pointer editor) override; /** * Removes an IPartListener from the part service. */ void RemovePartListener(IPartListener* l) override; /* * (non-Javadoc) Method declared on ISelectionListener. */ void RemoveSelectionListener(ISelectionListener* listener) override; /* * (non-Javadoc) Method declared on ISelectionListener. */ void RemoveSelectionListener(const QString& partId, ISelectionListener* listener) override; /* * (non-Javadoc) Method declared on ISelectionListener. */ void RemovePostSelectionListener(ISelectionListener* listener) override; /* * (non-Javadoc) Method declared on ISelectionListener. */ void RemovePostSelectionListener(const QString& partId, ISelectionListener* listener) override; /** * This method is called when a part is activated by clicking within it. In * response, the part, the pane, and all of its actions will be activated. * * In the current design this method is invoked by the part pane when the * pane, the part, or any children gain focus. */ void RequestActivation(IWorkbenchPart::Pointer 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 ResetPerspective() override; /** * Restore this page from the memento and ensure that the active * perspective is equals the active descriptor otherwise create a new * perspective for that descriptor. If activeDescriptor is null active the * old perspective. */ /*IStatus*/bool RestoreState(IMemento::Pointer memento, IPerspectiveDescriptor::Pointer activeDescriptor); /** * See IWorkbenchPage */ bool SaveAllEditors(bool confirm) override; /** * @param confirm * @param addNonPartSources true if saveables from non-part sources should be saved too * @return false if the user cancelled * */ bool SaveAllEditors(bool confirm, bool addNonPartSources); /** * Saves an editors in the workbench. If confirm is true * the user is prompted to confirm the command. * * @param confirm * if user confirmation should be sought * @return true if the command succeeded, or false * if the user cancels the command */ bool SaveEditor(IEditorPart::Pointer editor, bool confirm) override; /** * Saves the current perspective. */ void SavePerspective() override; /** * Saves the perspective. */ void SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc) override; /** * Save the state of the page. */ /*IStatus*/bool SaveState(IMemento::Pointer memento); /** * See IWorkbenchPage. */ void SetEditorAreaVisible(bool showEditorArea); /** * Sets the perspective. * * @param desc * identifies the new perspective. */ void SetPerspective(IPerspectiveDescriptor::Pointer desc) override; /** * See IWorkbenchPage. */ IViewPart::Pointer ShowView(const QString& viewID) override; /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#showView(java.lang.String, * java.lang.String, int) */ IViewPart::Pointer ShowView(const QString& viewID, const QString& secondaryID, int mode) override; /* * Returns the editors in activation order (oldest first). */ QList GetSortedEditors(); /** * @see IWorkbenchPage#getOpenPerspectives() */ QList GetOpenPerspectives() override; protected: /** * Do not call this method. Use busyOpenEditor. * * @see IWorkbenchPage#openEditor(IEditorInput, String, boolean) */ IEditorPart::Pointer BusyOpenEditorBatched(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); void ShowEditor(bool activate, IEditorPart::Pointer editor); /* * Saves the workbench part. */ bool SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm); /** * Restore the toolbar layout for the active perspective. */ void ResetToolBarLayout(); /** * Return all open Perspective objects. * * @return all open Perspective objects */ /*package*/ QList > GetOpenInternalPerspectives(); /** * Checks perspectives in the order they were activiated * for the specfied part. The first sorted perspective * that contains the specified part is returned. * * @param part specified part to search for * @return the first sorted perspespective containing the part */ /*package*/ SmartPointer GetFirstPerspectiveWithView(IViewPart::Pointer part); // for dynamic UI void AddPerspective(SmartPointer persp); public: /** * Returns the perspectives in activation order (oldest first). */ QList GetSortedPerspectives() override; /* * Returns the parts in activation order (oldest first). */ QList GetSortedParts(); /** * Returns the reference to the given part, or null if it has no reference * (i.e. it is not a top-level part in this workbench page). * * @param part the part * @return the part's reference or null if the given part does not belong * to this workbench page */ IWorkbenchPartReference::Pointer GetReference(IWorkbenchPart::Pointer part) override; /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getViewStack(org.blueberry.ui.IViewPart) */ QList GetViewStack(IViewPart::Pointer part); /** * Allow for programmatically resizing a part. *

* EXPERIMENTAL *

*

* Known limitations: *

    *
  • currently applies only to views
  • *
  • has no effect when view is zoomed
  • *
*/ void ResizeView(IViewPart::Pointer part, int width, int height); /** * Sanity-checks the objects in this page. Throws an Assertation exception * if an object's internal state is invalid. ONLY INTENDED FOR USE IN THE * UI TEST SUITES. */ void TestInvariants(); IExtensionTracker* GetExtensionTracker() const override; /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() */ QList GetPerspectiveShortcuts() override; /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getShowViewShortcuts() */ QList GetShowViewShortcuts() override; bool IsPartVisible(IWorkbenchPartReference::Pointer reference); private: QString GetId(IWorkbenchPart::Pointer part); QString GetId(IWorkbenchPartReference::Pointer ref); /** * Sets the active part. */ void SetActivePart(IWorkbenchPart::Pointer newPart); /** * Sets the layout of the page. Assumes the new perspective is not null. * Keeps the active part if possible. Updates the window menubar and * toolbar if necessary. */ void SetPerspective(SmartPointer newPersp); /* * Update visibility state of all views. */ void UpdateVisibility(SmartPointer oldPersp, SmartPointer newPersp); /** * @param mode the mode to test * @return whether the mode is recognized */ bool CertifyMode(int mode); /** * Find the stack of view references stacked with this view part. * * @param part * the part * @return the stack of references */ QList GetViewReferenceStack( IViewPart::Pointer part); - struct ActivationOrderPred : std::binary_function + struct ActivationOrderPred { ActivationOrderPred(ActivationList* partList); ActivationList* activationList; bool operator()(const IViewReference::Pointer o1, const IViewReference::Pointer o2) const; }; // provides sash information for the given pane struct SashInfo { SmartPointer right; SmartPointer left; SmartPointer top; SmartPointer bottom; SmartPointer rightNode; SmartPointer leftNode; SmartPointer topNode; SmartPointer bottomNode; }; void FindSashParts(SmartPointer tree, const PartPane::Sashes& sashes, SashInfo& info); protected: /** * Returns all parts that are owned by this page * * @return */ QList GetAllParts(); /** * Returns all open parts that are owned by this page (that is, all parts * for which a part opened event would have been sent -- these would be * activated parts whose controls have already been created. */ QList GetOpenParts(); private: void SuggestReset(); }; } #endif /*BERRYWORKBENCHPAGE_H_*/