diff --git a/CMake/PackageDepends/MITK_ITK_Config.cmake b/CMake/PackageDepends/MITK_ITK_Config.cmake index e5fd53358f..e1f8ad0b4d 100644 --- a/CMake/PackageDepends/MITK_ITK_Config.cmake +++ b/CMake/PackageDepends/MITK_ITK_Config.cmake @@ -1,19 +1,21 @@ find_package(ITK REQUIRED) # # for some reason this does not work on windows, probably an ITK bug # ITK_BUILD_SHARED is OFF even in shared library builds # #if(ITK_FOUND AND NOT ITK_BUILD_SHARED) # message(FATAL_ERROR "MITK only supports a ITK which was built with shared libraries. Turn on BUILD_SHARED_LIBS in your ITK config.") #endif(ITK_FOUND AND NOT ITK_BUILD_SHARED) -set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 1) +if(NOT DEFINED ITK_NO_IO_FACTORY_REGISTER_MANAGER) + set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 1) +endif() include(${ITK_USE_FILE}) list(APPEND ALL_LIBRARIES ${ITK_LIBRARIES}) list(APPEND ALL_INCLUDE_DIRECTORIES ${ITK_INCLUDE_DIRS}) find_package(GDCM PATHS ${ITK_GDCM_DIR} REQUIRED) list(APPEND ALL_INCLUDE_DIRECTORIES ${GDCM_INCLUDE_DIRS}) list(APPEND ALL_LIBRARIES ${GDCM_LIBRARIES}) include(${GDCM_USE_FILE}) diff --git a/CMake/moduleConf.cmake.in b/CMake/moduleConf.cmake.in index e25ed8c860..63128525bb 100644 --- a/CMake/moduleConf.cmake.in +++ b/CMake/moduleConf.cmake.in @@ -1,9 +1,10 @@ set(@MODULE_NAME@_IS_ENABLED "@MODULE_IS_ENABLED@") if(@MODULE_NAME@_IS_ENABLED) + @MODULE_EXTRA_CMAKE_CODE@ set(@MODULE_NAME@_INCLUDE_DIRS "@MODULE_INCLUDE_DIRS@") set(@MODULE_NAME@_PROVIDES "@MODULE_PROVIDES@") set(@MODULE_NAME@_DEPENDS "@MODULE_DEPENDS@") set(@MODULE_NAME@_PACKAGE_DEPENDS "@MODULE_PACKAGE_DEPENDS@") set(@MODULE_NAME@_LIBRARY_DIRS "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@") endif(@MODULE_NAME@_IS_ENABLED) diff --git a/CMakeLists.txt b/CMakeLists.txt index 55b5440940..46d59dc028 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,949 +1,948 @@ if(APPLE) # With XCode 4.3, the SDK location changed. Older CMake # versions are not able to find it. cmake_minimum_required(VERSION 2.8.8) else() cmake_minimum_required(VERSION 2.8.5) endif() #----------------------------------------------------------------------------- # Set a default build type if none was specified #----------------------------------------------------------------------------- if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Debug' as none was specified.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() #----------------------------------------------------------------------------- # Superbuild Option - Enabled by default #----------------------------------------------------------------------------- option(MITK_USE_SUPERBUILD "Build MITK and the projects it depends on via SuperBuild.cmake." ON) if(MITK_USE_SUPERBUILD) project(MITK-superbuild) set(MITK_SOURCE_DIR ${PROJECT_SOURCE_DIR}) set(MITK_BINARY_DIR ${PROJECT_BINARY_DIR}) else() project(MITK) endif() #----------------------------------------------------------------------------- # 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 43) # _src_dir_length_max - strlen(ITK-src) 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() #----------------------------------------------------------------------------- # See http://cmake.org/cmake/help/cmake-2-8-docs.html#section_Policies for details #----------------------------------------------------------------------------- set(project_policies CMP0001 # NEW: CMAKE_BACKWARDS_COMPATIBILITY should no longer be used. CMP0002 # NEW: Logical target names must be globally unique. CMP0003 # NEW: Libraries linked via full path no longer produce linker search paths. CMP0004 # NEW: Libraries linked may NOT have leading or trailing whitespace. CMP0005 # NEW: Preprocessor definition values are now escaped automatically. CMP0006 # NEW: Installing MACOSX_BUNDLE targets requires a BUNDLE DESTINATION. CMP0007 # NEW: List command no longer ignores empty elements. CMP0008 # NEW: Libraries linked by full-path must have a valid library file name. CMP0009 # NEW: FILE GLOB_RECURSE calls should not follow symlinks by default. CMP0010 # NEW: Bad variable reference syntax is an error. CMP0011 # NEW: Included scripts do automatic cmake_policy PUSH and POP. CMP0012 # NEW: if() recognizes numbers and boolean constants. CMP0013 # NEW: Duplicate binary directories are not allowed. CMP0014 # NEW: Input directories must have CMakeLists.txt ) foreach(policy ${project_policies}) if(POLICY ${policy}) cmake_policy(SET ${policy} NEW) endif() endforeach() #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(CMAKE_MODULE_PATH ${MITK_SOURCE_DIR}/CMake ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- include(mitkMacroEmptyExternalProject) include(mitkFunctionGenerateProjectXml) include(mitkFunctionSuppressWarnings) SUPPRESS_VC_DEPRECATED_WARNINGS() #----------------------------------------------------------------------------- # Output directories. #----------------------------------------------------------------------------- foreach(type LIBRARY RUNTIME ARCHIVE) # Make sure the directory exists if(DEFINED MITK_CMAKE_${type}_OUTPUT_DIRECTORY AND NOT EXISTS ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) message("Creating directory MITK_CMAKE_${type}_OUTPUT_DIRECTORY: ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") file(MAKE_DIRECTORY "${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") endif() if(MITK_USE_SUPERBUILD) set(output_dir ${MITK_BINARY_DIR}/bin) if(NOT DEFINED MITK_CMAKE_${type}_OUTPUT_DIRECTORY) set(MITK_CMAKE_${type}_OUTPUT_DIRECTORY ${MITK_BINARY_DIR}/MITK-build/bin) endif() else() if(NOT DEFINED MITK_CMAKE_${type}_OUTPUT_DIRECTORY) set(output_dir ${MITK_BINARY_DIR}/bin) else() set(output_dir ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) endif() endif() set(CMAKE_${type}_OUTPUT_DIRECTORY ${output_dir} CACHE INTERNAL "Single output directory for building all libraries.") mark_as_advanced(CMAKE_${type}_OUTPUT_DIRECTORY) endforeach() #----------------------------------------------------------------------------- # Additional MITK Options (also shown during superbuild) #----------------------------------------------------------------------------- option(BUILD_SHARED_LIBS "Build MITK with shared libraries" ON) option(WITH_COVERAGE "Enable/Disable coverage" OFF) option(BUILD_TESTING "Test the project" ON) option(MITK_BUILD_ALL_APPS "Build all MITK applications" OFF) set(MITK_BUILD_TUTORIAL OFF CACHE INTERNAL "Deprecated! Use MITK_BUILD_EXAMPLES instead!") option(MITK_BUILD_EXAMPLES "Build the MITK Examples" ${MITK_BUILD_TUTORIAL}) option(MITK_USE_ACVD "Use Approximated Centroidal Voronoi Diagrams" OFF) option(MITK_USE_Boost "Use the Boost C++ library" OFF) option(MITK_USE_BLUEBERRY "Build the BlueBerry platform" ON) option(MITK_USE_CTK "Use CTK in MITK" ${MITK_USE_BLUEBERRY}) option(MITK_USE_QT "Use Nokia's Qt library" ${MITK_USE_CTK}) option(MITK_USE_DCMTK "EXPERIMENTAL, superbuild only: Use DCMTK in MITK" ${MITK_USE_CTK}) option(MITK_DCMTK_BUILD_SHARED_LIBS "EXPERIMENTAL, superbuild only: build DCMTK as shared libs" OFF) option(MITK_USE_OpenCV "Use Intel's OpenCV library" OFF) option(MITK_USE_OpenCL "Use OpenCL GPU-Computing library" OFF) option(MITK_USE_SOFA "Use Simulation Open Framework Architecture" OFF) option(MITK_USE_Python "Use Python wrapping in MITK" OFF) set(MITK_USE_CableSwig ${MITK_USE_Python}) if(MITK_USE_Python) FIND_PACKAGE(PythonLibs REQUIRED) FIND_PACKAGE(PythonInterp REQUIRED) endif() mark_as_advanced(MITK_BUILD_ALL_APPS MITK_USE_CTK MITK_USE_DCMTK ) if(MITK_USE_Boost) 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") 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() if(MITK_USE_CTK) if(NOT MITK_USE_QT) message("Forcing MITK_USE_QT to ON because of MITK_USE_CTK") set(MITK_USE_QT ON CACHE BOOL "Use Nokia's Qt library in MITK" FORCE) endif() if(NOT MITK_USE_DCMTK) message("Setting MITK_USE_DCMTK to ON because DCMTK needs to be build for CTK") set(MITK_USE_DCMTK ON CACHE BOOL "Use DCMTK in MITK" FORCE) endif() endif() if(MITK_USE_QT) # find the package at the very beginning, so that QT4_FOUND is available find_package(Qt4 4.6.2 REQUIRED) endif() if(MITK_USE_SOFA) set(SOFA_CMAKE_VERSION 2.8.8) if(${CMAKE_VERSION} VERSION_LESS ${SOFA_CMAKE_VERSION}) set(MITK_USE_SOFA OFF CACHE BOOL "" FORCE) message(WARNING "Switched off MITK_USE_SOFA\n Minimum required CMake version: ${SOFA_CMAKE_VERSION}\n Installed CMake version: ${CMAKE_VERSION}") endif() if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set(MITK_USE_SOFA OFF CACHE BOOL "" FORCE) message(WARNING "Switched off MITK_USE_SOFA\n Clang is not supported, use GCC instead.") endif() endif() # 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_DIMENSIONS) set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") endif() #----------------------------------------------------------------------------- # Project.xml #----------------------------------------------------------------------------- # A list of topologically ordered targets set(CTEST_PROJECT_SUBPROJECTS) if(MITK_USE_BLUEBERRY) list(APPEND CTEST_PROJECT_SUBPROJECTS BlueBerry) endif() list(APPEND CTEST_PROJECT_SUBPROJECTS MITK-Core MITK-CoreUI MITK-IGT MITK-ToF MITK-DTI MITK-Registration MITK-Modules # all modules not contained in a specific subproject MITK-Plugins # all plugins not contained in a specific subproject MITK-Examples Unlabeled # special "subproject" catching all unlabeled targets and tests ) # Configure CTestConfigSubProject.cmake that could be used by CTest scripts configure_file(${MITK_SOURCE_DIR}/CTestConfigSubProject.cmake.in ${MITK_BINARY_DIR}/CTestConfigSubProject.cmake) if(CTEST_PROJECT_ADDITIONAL_TARGETS) # those targets will be executed at the end of the ctest driver script # and they also get their own subproject label set(subproject_list "${CTEST_PROJECT_SUBPROJECTS};${CTEST_PROJECT_ADDITIONAL_TARGETS}") else() set(subproject_list "${CTEST_PROJECT_SUBPROJECTS}") endif() # Generate Project.xml file expected by the CTest driver script mitkFunctionGenerateProjectXml(${MITK_BINARY_DIR} MITK "${subproject_list}" ${MITK_USE_SUPERBUILD}) #----------------------------------------------------------------------------- # Superbuild script #----------------------------------------------------------------------------- if(MITK_USE_SUPERBUILD) include("${CMAKE_CURRENT_SOURCE_DIR}/SuperBuild.cmake") return() endif() #***************************************************************************** #**************************** END OF SUPERBUILD **************************** #***************************************************************************** #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- include(CheckCXXSourceCompiles) include(mitkFunctionCheckCompilerFlags) include(mitkFunctionGetGccVersion) include(MacroParseArguments) include(mitkFunctionSuppressWarnings) # includes several functions include(mitkFunctionOrganizeSources) include(mitkFunctionGetVersion) include(mitkFunctionGetVersionDescription) include(mitkFunctionCreateWindowsBatchScript) include(mitkFunctionInstallProvisioningFiles) include(mitkFunctionInstallAutoLoadModules) include(mitkFunctionGetLibrarySearchPaths) include(mitkFunctionCompileSnippets) include(mitkMacroCreateModuleConf) include(mitkMacroCreateModule) include(mitkMacroCheckModule) include(mitkMacroCreateModuleTests) include(mitkFunctionAddCustomModuleTest) include(mitkMacroUseModule) include(mitkMacroMultiplexPicType) include(mitkMacroInstall) include(mitkMacroInstallHelperApp) include(mitkMacroInstallTargets) include(mitkMacroGenerateToolsLibrary) include(mitkMacroGetLinuxDistribution) include(mitkMacroGetPMDPlatformString) #----------------------------------------------------------------------------- # Prerequesites #----------------------------------------------------------------------------- find_package(ITK REQUIRED) find_package(VTK REQUIRED) find_package(GDCM PATHS ${ITK_GDCM_DIR} REQUIRED) include(${GDCM_USE_FILE}) #----------------------------------------------------------------------------- # Set MITK specific options and variables (NOT available during superbuild) #----------------------------------------------------------------------------- # ASK THE USER TO SHOW THE CONSOLE WINDOW FOR CoreApp and mitkWorkbench option(MITK_SHOW_CONSOLE_WINDOW "Use this to enable or disable the console window when starting MITK GUI Applications" ON) mark_as_advanced(MITK_SHOW_CONSOLE_WINDOW) # TODO: check if necessary option(USE_ITKZLIB "Use the ITK zlib for pic compression." ON) mark_as_advanced(USE_ITKZLIB) if(NOT MITK_FAST_TESTING) if(DEFINED MITK_CTEST_SCRIPT_MODE AND (MITK_CTEST_SCRIPT_MODE STREQUAL "continuous" OR MITK_CTEST_SCRIPT_MODE STREQUAL "experimental") ) set(MITK_FAST_TESTING 1) endif() endif() #----------------------------------------------------------------------------- # Get MITK version info #----------------------------------------------------------------------------- mitkFunctionGetVersion(${MITK_SOURCE_DIR} MITK) mitkFunctionGetVersionDescription(${MITK_SOURCE_DIR} MITK) #----------------------------------------------------------------------------- # Installation preparation # # These should be set before any MITK install macros are used #----------------------------------------------------------------------------- # on Mac OSX all BlueBerry plugins get copied into every # application bundle (.app directory) specified here if(MITK_USE_BLUEBERRY AND APPLE) include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/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} ${app_name}) endif() endforeach() endif() #----------------------------------------------------------------------------- # Set symbol visibility Flags #----------------------------------------------------------------------------- # MinGW does not export all symbols automatically, so no need to set flags if(CMAKE_COMPILER_IS_GNUCXX AND NOT MINGW) set(VISIBILITY_CXX_FLAGS ) #"-fvisibility=hidden -fvisibility-inlines-hidden") endif() #----------------------------------------------------------------------------- # Set coverage Flags #----------------------------------------------------------------------------- if(WITH_COVERAGE) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") set(coverage_flags "-g -fprofile-arcs -ftest-coverage -O0 -DNDEBUG") set(COVERAGE_CXX_FLAGS ${coverage_flags}) set(COVERAGE_C_FLAGS ${coverage_flags}) endif() endif() #----------------------------------------------------------------------------- # MITK C/CXX Flags #----------------------------------------------------------------------------- set(MITK_C_FLAGS "${COVERAGE_C_FLAGS}") set(MITK_C_FLAGS_DEBUG ) set(MITK_C_FLAGS_RELEASE ) set(MITK_CXX_FLAGS "${VISIBILITY_CXX_FLAGS} ${COVERAGE_CXX_FLAGS}") set(MITK_CXX_FLAGS_DEBUG ) set(MITK_CXX_FLAGS_RELEASE ) set(MITK_EXE_LINKER_FLAGS ) set(MITK_SHARED_LINKER_FLAGS ) include(mitkSetupC++0xVariables) if(WIN32) set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} -D_WIN32_WINNT=0x0501 -DPOCO_NO_UNWINDOWS -DWIN32_LEAN_AND_MEAN") set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} /wd4231") # warning C4231: nonstandard extension used : 'extern' before template explicit instantiation endif() if(NOT MSVC_VERSION) foreach(_flag -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -Wno-error=gnu -Woverloaded-virtual -Wstrict-null-sentinel #-Wold-style-cast #-Wsign-promo # the following two lines should be removed after ITK-3097 has # been resolved, see also MITK bug 15279 -Wno-unused-local-typedefs -Wno-array-bounds -fdiagnostics-show-option ) mitkFunctionCheckCAndCXXCompilerFlags(${_flag} MITK_C_FLAGS MITK_CXX_FLAGS) endforeach() endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionCheckCompilerFlags("-Wl,--no-undefined" MITK_SHARED_LINKER_FLAGS) mitkFunctionCheckCompilerFlags("-Wl,--as-needed" MITK_SHARED_LINKER_FLAGS) if(MITK_USE_C++0x) mitkFunctionCheckCompilerFlags("-std=c++0x" MITK_CXX_FLAGS) endif() mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) # With older version of gcc supporting the flag -fstack-protector-all, an extra dependency to libssp.so # is introduced. If gcc is smaller than 4.4.0 and the build type is Release let's not include the flag. # Doing so should allow to build package made for distribution using older linux distro. if(${GCC_VERSION} VERSION_GREATER "4.4.0" OR (CMAKE_BUILD_TYPE STREQUAL "Debug" AND ${GCC_VERSION} VERSION_LESS "4.4.0")) mitkFunctionCheckCAndCXXCompilerFlags("-fstack-protector-all" MITK_C_FLAGS MITK_CXX_FLAGS) endif() if(MINGW) # suppress warnings about auto imported symbols set(MITK_SHARED_LINKER_FLAGS "-Wl,--enable-auto-import ${MITK_SHARED_LINKER_FLAGS}") endif() set(MITK_CXX_FLAGS_RELEASE "-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}) #----------------------------------------------------------------------------- # Testing #----------------------------------------------------------------------------- if(BUILD_TESTING) enable_testing() include(CTest) mark_as_advanced(TCL_TCLSH DART_ROOT) option(MITK_ENABLE_GUI_TESTING OFF "Enable the MITK GUI tests") # Setup file for setting custom ctest vars configure_file( CMake/CTestCustom.cmake.in ${MITK_BINARY_DIR}/CTestCustom.cmake @ONLY ) # Configuration for the CMake-generated test driver set(CMAKE_TESTDRIVER_EXTRA_INCLUDES "#include ") set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN " try {") set(CMAKE_TESTDRIVER_AFTER_TESTMAIN " } catch( std::exception & excp ) { fprintf(stderr,\"%s\\n\",excp.what()); return EXIT_FAILURE; } catch( ... ) { printf(\"Exception caught in the test driver\\n\"); return EXIT_FAILURE; } ") set(MITK_TEST_OUTPUT_DIR "${MITK_BINARY_DIR}/test_output") if(NOT EXISTS ${MITK_TEST_OUTPUT_DIR}) file(MAKE_DIRECTORY ${MITK_TEST_OUTPUT_DIR}) endif() # Test the external project template if(MITK_USE_BLUEBERRY) include(mitkTestProjectTemplate) endif() # 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() #----------------------------------------------------------------------------- # Compile Utilities and set-up MITK variables #----------------------------------------------------------------------------- include(mitkSetupVariables) #----------------------------------------------------------------------------- # Cleanup #----------------------------------------------------------------------------- file(GLOB _MODULES_CONF_FILES ${PROJECT_BINARY_DIR}/${MODULES_CONF_DIRNAME}/*.cmake) if(_MODULES_CONF_FILES) file(REMOVE ${_MODULES_CONF_FILES}) endif() add_subdirectory(Utilities) if(MITK_USE_BLUEBERRY) # We need to hack a little bit because MITK applications may need # to enable certain BlueBerry plug-ins. However, these plug-ins # are validated separately from the MITK plug-ins and know nothing # about potential MITK plug-in dependencies of the applications. Hence # we cannot pass the MITK application list to the BlueBerry # ctkMacroSetupPlugins call but need to extract the BlueBerry dependencies # from the applications and set them explicitly. include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") foreach(mitk_app ${MITK_APPS}) # extract target_dir and option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 target_dir) list(GET target_info_list 1 option_name) # check if the application is enabled and if target_libraries.cmake exists if((${option_name} OR MITK_BUILD_ALL_APPS) AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/target_libraries.cmake") include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/target_libraries.cmake") foreach(_target_dep ${target_libraries}) if(_target_dep MATCHES org_blueberry_) string(REPLACE _ . _app_bb_dep ${_target_dep}) # explicitly set the build option for the BlueBerry plug-in set(BLUEBERRY_BUILD_${_app_bb_dep} ON CACHE BOOL "Build the ${_app_bb_dep} plug-in") endif() endforeach() endif() endforeach() set(mbilog_DIR "${mbilog_BINARY_DIR}") if(MITK_BUILD_ALL_PLUGINS) set(BLUEBERRY_BUILD_ALL_PLUGINS ON) endif() set(BLUEBERRY_XPDOC_OUTPUT_DIR ${MITK_DOXYGEN_OUTPUT_DIR}/html/extension-points/html/) add_subdirectory(BlueBerry) set(BlueBerry_DIR ${CMAKE_CURRENT_BINARY_DIR}/BlueBerry CACHE PATH "The directory containing a CMake configuration file for BlueBerry" FORCE) include(mitkMacroCreateCTKPlugin) 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}") if(MITK_USE_QT) add_definitions(-DQWT_DLL) endif() #----------------------------------------------------------------------------- # Add custom targets representing CDash subprojects #----------------------------------------------------------------------------- foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) if(NOT TARGET ${subproject} AND NOT subproject MATCHES "Unlabeled") add_custom_target(${subproject}) endif() endforeach() #----------------------------------------------------------------------------- # Add subdirectories #----------------------------------------------------------------------------- link_directories(${MITK_LINK_DIRECTORIES}) add_subdirectory(Core) -include(${CMAKE_CURRENT_BINARY_DIR}/Core/Code/CppMicroServices/CppMicroServicesConfig.cmake) add_subdirectory(Modules) if(MITK_USE_BLUEBERRY) find_package(BlueBerry REQUIRED) set(MITK_DEFAULT_SUBPROJECTS MITK-Plugins) # Plug-in testing (needs some work to be enabled again) if(BUILD_TESTING) include(berryTestingHelpers) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp") get_target_property(_is_macosx_bundle CoreApp MACOSX_BUNDLE) if(APPLE AND _is_macosx_bundle) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp.app/Contents/MacOS/CoreApp") endif() set(BLUEBERRY_TEST_APP_ID "org.mitk.qt.coreapplication") endif() include("${CMAKE_CURRENT_SOURCE_DIR}/Plugins/PluginList.cmake") set(mitk_plugins_fullpath ) foreach(mitk_plugin ${MITK_EXT_PLUGINS}) list(APPEND mitk_plugins_fullpath Plugins/${mitk_plugin}) 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() # 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 OUTPUT_VARIABLE ${varname}) endmacro() # Get infos about application directories and build options include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") set(mitk_apps_fullpath ) foreach(mitk_app ${MITK_APPS}) list(APPEND mitk_apps_fullpath "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${mitk_app}") endforeach() ctkMacroSetupPlugins(${mitk_plugins_fullpath} BUILD_OPTION_PREFIX MITK_BUILD_ APPS ${mitk_apps_fullpath} BUILD_ALL ${MITK_BUILD_ALL_PLUGINS} COMPACT_OPTIONS) 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() # 11.3.13, change, muellerm: activate python bundle if python and blueberry is active if( MITK_USE_Python ) set(MITK_BUILD_org.mitk.gui.qt.python ON) endif() endif() #----------------------------------------------------------------------------- # Python Wrapping #----------------------------------------------------------------------------- option(MITK_USE_Python "Build Python integration for MITK (requires CableSwig)." OFF) #----------------------------------------------------------------------------- # Documentation #----------------------------------------------------------------------------- add_subdirectory(Documentation) #----------------------------------------------------------------------------- # Installation #----------------------------------------------------------------------------- # set MITK cpack variables # These are the default variables, which can be overwritten ( see below ) include(mitkSetupCPack) set(use_default_config ON) # MITK_APPS is set in Applications/AppList.cmake (included somewhere above # if MITK_USE_BLUEBERRY is set to ON). if(MITK_APPS) set(activated_apps_no 0) list(LENGTH MITK_APPS app_count) # Check how many apps have been enabled # If more than one app has been activated, the we use the # default CPack configuration. Otherwise that apps configuration # will be used, if present. 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) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) MATH(EXPR activated_apps_no "${activated_apps_no} + 1") endif() endforeach() 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 ${MITK_APPS}) # extract target_dir and option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 target_dir) list(GET target_info_list 1 option_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) # check whether application specific configuration files will be used if(use_project_cpack) # use files if they exist if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/CPackOptions.cmake") include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/CPackOptions.cmake") endif() if(EXISTS "${PROJECT_SOURCE_DIR}/Applications/${target_dir}/CPackConfig.cmake.in") set(CPACK_PROJECT_CONFIG_FILE "${PROJECT_BINARY_DIR}/Applications/${target_dir}/CPackConfig.cmake") configure_file(${PROJECT_SOURCE_DIR}/Applications/${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 "${target_dir}") endif() endforeach() endif() # 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 #----------------------------------------------------------------------------- # This is for installation support of external projects depending on # MITK plugins and modules. The export file should not be used for linking to MITK # libraries without using LINK_DIRECTORIES, since the exports are incomplete # yet (depending libraries are not exported). 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() endforeach() get_property(MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS_CONFIG GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS) 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) set(VISIBILITY_AVAILABLE 0) set(visibility_test_flag "") mitkFunctionCheckCompilerFlags("-fvisibility=hidden" visibility_test_flag) if(visibility_test_flag) # The compiler understands -fvisiblity=hidden (probably gcc >= 4 or Clang) set(VISIBILITY_AVAILABLE 1) endif() configure_file(mitkExportMacros.h.in ${MITK_BINARY_DIR}/mitkExportMacros.h) configure_file(mitkVersion.h.in ${MITK_BINARY_DIR}/mitkVersion.h) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) set(VECMATH_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/vecmath) set(IPFUNC_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/ipFunc) set(UTILITIES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities) file(GLOB _MODULES_CONF_FILES RELATIVE ${PROJECT_BINARY_DIR}/${MODULES_CONF_DIRNAME} ${PROJECT_BINARY_DIR}/${MODULES_CONF_DIRNAME}/*.cmake) set(MITK_MODULE_NAMES) foreach(_module ${_MODULES_CONF_FILES}) string(REPLACE Config.cmake "" _module_name ${_module}) list(APPEND MITK_MODULE_NAMES ${_module_name}) endforeach() configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) configure_file(MITKConfig.cmake.in ${MITK_BINARY_DIR}/MITKConfig.cmake @ONLY) # If we are under Windows, create two batch files which correctly # set up the environment for the application and for Visual Studio if(WIN32) include(mitkFunctionCreateWindowsBatchScript) set(VS_SOLUTION_FILE "${PROJECT_BINARY_DIR}/${PROJECT_NAME}.sln") foreach(VS_BUILD_TYPE debug release) mitkFunctionCreateWindowsBatchScript("${MITK_SOURCE_DIR}/CMake/StartVS.bat.in" ${PROJECT_BINARY_DIR}/StartVS_${VS_BUILD_TYPE}.bat ${VS_BUILD_TYPE}) endforeach() endif(WIN32) #----------------------------------------------------------------------------- # MITK Applications #----------------------------------------------------------------------------- # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Applications) #----------------------------------------------------------------------------- # 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() diff --git a/Core/CMakeLists.txt b/Core/CMakeLists.txt index 4f0042017b..7f43f70173 100644 --- a/Core/CMakeLists.txt +++ b/Core/CMakeLists.txt @@ -1,4 +1,38 @@ +#----------------------------------------------------------------------------- +# Configure the CppMicroServices build +#----------------------------------------------------------------------------- + +set(US_ENABLE_AUTOLOADING_SUPPORT ON) +set(US_ENABLE_THREADING_SUPPORT ON) +set(US_IS_EMBEDDED OFF) +set(US_NO_DOCUMENTATION ON) + +if(BUILD_TESTING) + set(US_BUILD_TESTING ON) +endif() + +add_subdirectory(CppMicroServices) +set(CppMicroServices_DIR ${CMAKE_CURRENT_BINARY_DIR}/CppMicroServices CACHE PATH "Path to the CppMicroServices library") +mark_as_advanced(CppMicroServices_DIR) + +# create a custom module conf file for CppMicroServices +function(_generate_cppmicroservices_conf) + set(MODULE_IS_ENABLED 1) + set(MODULE_NAME CppMicroServices) + set(MODULE_PROVIDES ${MODULE_NAME}) + set(MODULE_EXTRA_CMAKE_CODE "find_package(CppMicroServices NO_MODULE REQUIRED)") + set(MODULE_INCLUDE_DIRS "\${CppMicroServices_INCLUDE_DIRS}") + + set(CppMicroServices_CONFIG_FILE "${CMAKE_BINARY_DIR}/${MODULES_CONF_DIRNAME}/CppMicroServicesConfig.cmake" CACHE INTERNAL "Path to module config" FORCE) + configure_file(${MITK_SOURCE_DIR}/CMake/moduleConf.cmake.in ${CppMicroServices_CONFIG_FILE} @ONLY) +endfunction() + +_generate_cppmicroservices_conf() + +#----------------------------------------------------------------------------- +# Add the MITK Core library +#----------------------------------------------------------------------------- + set(MITK_DEFAULT_SUBPROJECTS MITK-Core) add_subdirectory(Code) - diff --git a/Core/Code/CMakeLists.txt b/Core/Code/CMakeLists.txt index 73c304bf8e..d5335f2556 100644 --- a/Core/Code/CMakeLists.txt +++ b/Core/Code/CMakeLists.txt @@ -1,72 +1,59 @@ #FIND_PACKAGE(OpenGL) #IF(NOT OPENGL_FOUND) # MESSAGE("GL is required for MITK rendering") #ENDIF(NOT OPENGL_FOUND ) -# Configure the C++ Micro Services Code for MITK -find_package(ITK REQUIRED) -include(${ITK_USE_FILE}) - -set(US_NAMESPACE "mitk") -set(US_HEADER_PREFIX "mitk") -set(US_BASECLASS_NAME "itk::LightObject") -set(US_BASECLASS_HEADER "mitkServiceBaseObject.h") -set(US_BASECLASS_PACKAGE "ITK") -set(US_ENABLE_THREADING_SUPPORT 1) -set(US_ENABLE_AUTOLOADING_SUPPORT 1) -set(US_EMBEDDING_LIBRARY Mitk) -set(US_BUILD_TESTING ${BUILD_TESTING}) -if(BUILD_TESTING) - include_directories(${CMAKE_CURRENT_SOURCE_DIR}/Common) - set(US_TEST_LABELS MITK-Core) -endif() - -add_subdirectory(CppMicroServices) - -include(${CMAKE_CURRENT_BINARY_DIR}/CppMicroServices/CppMicroServicesConfig.cmake) - set(TOOL_CPPS "") # temporary suppress warnings in the following files until image accessors are fully integrated. set_source_files_properties( DataManagement/mitkImage.cpp COMPILE_FLAGS -DMITK_NO_DEPRECATED_WARNINGS ) set_source_files_properties( Controllers/mitkSliceNavigationController.cpp COMPILE_FLAGS -DMITK_NO_DEPRECATED_WARNINGS ) +# In MITK_ITK_Config.cmake, we set ITK_NO_IO_FACTORY_REGISTER_MANAGER to 1 unless +# the variable is already defined. Setting it to 1 prevents multiple registrations/ +# unregistrations of ITK IO factories during library loading/unloading (of MITK +# libraries). However, we need "one" place where the IO factories are registered at +# least once. This could be the application executable, but every executable would +# need to take care of that itself. Instead, we allow the auto registration in the +# Mitk Core library. +set(ITK_NO_IO_FACTORY_REGISTER_MANAGER 0) + MITK_CREATE_MODULE( Mitk INCLUDE_DIRS ${CppMicroServices_INCLUDE_DIRS} Algorithms Common DataManagement Controllers Interactions Interfaces IO Rendering ${MITK_BINARY_DIR} INTERNAL_INCLUDE_DIRS ${OPENGL_INCLUDE_DIR} ${IPSEGMENTATION_INCLUDE_DIR} ${ANN_INCLUDE_DIR} ${CppMicroServices_INTERNAL_INCLUDE_DIRS} - DEPENDS mbilog tinyxml + DEPENDS mbilog tinyxml CppMicroServices DEPENDS_INTERNAL pic2vtk PACKAGE_DEPENDS ITK GDCM VTK OpenGL EXPORT_DEFINE MITK_CORE_EXPORT WARNINGS_AS_ERRORS ) # this is needed for libraries which link to Mitk and need # symbols from explicitly instantiated templates if(MINGW) get_target_property(_mitkCore_MINGW_linkflags Mitk LINK_FLAGS) if(NOT _mitkCore_MINGW_linkflags) set(_mitkCore_MINGW_linkflags "") endif(NOT _mitkCore_MINGW_linkflags) set_target_properties(Mitk PROPERTIES LINK_FLAGS "${_mitkCore_MINGW_linkflags} -Wl,--export-all-symbols") endif(MINGW) # replacing Mitk by Mitk [due to removing the PROVIDES macro TARGET_LINK_LIBRARIES(Mitk ${LIBRARIES_FOR_${KITNAME}_CORE} ${IPFUNC_LIBRARY} ipSegmentation ann) #TARGET_LINK_LIBRARIES(Mitk ${OPENGL_LIBRARIES} ) TARGET_LINK_LIBRARIES(Mitk gdcmCommon gdcmIOD gdcmDSED) if(MSVC_IDE OR MSVC_VERSION OR MINGW) target_link_libraries(Mitk psapi.lib) endif(MSVC_IDE OR MSVC_VERSION OR MINGW) # build tests? OPTION(BUILD_TESTING "Build the MITK Core tests." ON) IF(BUILD_TESTING) ENABLE_TESTING() ADD_SUBDIRECTORY(Testing) ENDIF(BUILD_TESTING) diff --git a/Core/Code/Common/mitkCoreServices.cpp b/Core/Code/Common/mitkCoreServices.cpp index cd12960ee9..410e697029 100644 --- a/Core/Code/Common/mitkCoreServices.cpp +++ b/Core/Code/Common/mitkCoreServices.cpp @@ -1,38 +1,75 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCoreServices.h" #include "mitkIShaderRepository.h" -#include "mitkGetModuleContext.h" -#include "mitkModuleContext.h" -#include "mitkServiceReference.h" +#include "usGetModuleContext.h" +#include "usModuleContext.h" +#include "usServiceReference.h" namespace mitk { -IShaderRepository* CoreServices::GetShaderRepository() +template +S* GetCoreService(us::ModuleContext* context, std::map >& csm) { - IShaderRepository* shaderRepo = NULL; - ServiceReference serviceRef = GetModuleContext()->GetServiceReference(); + S* coreService = NULL; + us::ServiceReference serviceRef = context->GetServiceReference(); if (serviceRef) { - shaderRepo = GetModuleContext()->GetService(serviceRef); + coreService = context->GetService(serviceRef); } - return shaderRepo; + + assert(coreService && "Asserting non-NULL MITK core service"); + csm[context].insert(std::make_pair(coreService,serviceRef)); + + return coreService; +} + +std::map > CoreServices::m_ContextToServicesMap; + +IShaderRepository* CoreServices::GetShaderRepository(us::ModuleContext* context) +{ + return GetCoreService(context, m_ContextToServicesMap); +} + +bool CoreServices::Unget(us::ModuleContext* context, const std::string& /*interfaceId*/, void* service) +{ + bool success = false; + + std::map >::iterator iter = m_ContextToServicesMap.find(context); + if (iter != m_ContextToServicesMap.end()) + { + std::map::iterator iter2 = iter->second.find(service); + if (iter2 != iter->second.end()) + { + us::ServiceReferenceU serviceRef = iter2->second; + if (serviceRef) + { + success = context->UngetService(serviceRef); + if (success) + { + iter->second.erase(iter2); + } + } + } + } + + return success; } } diff --git a/Core/Code/Common/mitkCoreServices.h b/Core/Code/Common/mitkCoreServices.h index b8b20f6385..4799f92bd2 100644 --- a/Core/Code/Common/mitkCoreServices.h +++ b/Core/Code/Common/mitkCoreServices.h @@ -1,48 +1,138 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKCORESERVICES_H #define MITKCORESERVICES_H +#include "MitkExports.h" + +#include + +#include +#include +#include +#include + namespace mitk { struct IShaderRepository; /** * @brief Access MITK core services. * - * This class can be used inside the MITK Core to conveniently access - * common service objects. + * This class can be used to conveniently access common + * MITK Core service objects. All getter methods are guaranteed + * to return a non-NULL service object. * - * It is not exported and not meant to be used by other MITK modules. + * To ensure that CoreServices::Unget() is called after the caller + * has finished using a service object, you should use the CoreServicePointer + * helper class which calls Unget() when it goes out of scope: + * + * \code + * CoreServicePointer shaderRepo(CoreServices::GetShaderRepository()); + * // Do something with shaderRepo + * \endcode + * + * @see CoreServicePointer */ -class CoreServices +class MITK_CORE_EXPORT CoreServices { public: - static IShaderRepository* GetShaderRepository(); + /** + * @brief Get a IShaderRepository instance. + * @param context The module context of the module getting the service. + * @return A non-NULL IShaderRepository instance. + */ + static IShaderRepository* GetShaderRepository(us::ModuleContext* context = us::GetModuleContext()); + + /** + * @brief Unget a previously acquired service instance. + * @param service The service instance to be released. + * @return \c true if ungetting the service was successful, \c false otherwise. + */ + template + static bool Unget(S* service, us::ModuleContext* context = us::GetModuleContext()) + { + return Unget(context, us_service_interface_iid(), service); + } private: + static bool Unget(us::ModuleContext* context, const std::string& interfaceId, void* service); + + static std::map > m_ContextToServicesMap; + // purposely not implemented CoreServices(); CoreServices(const CoreServices&); CoreServices& operator=(const CoreServices&); }; +/** + * @brief A RAII helper class for core service objects. + * + * This is class is intended for usage in local scopes; it calls + * CoreServices::Unget(S*) in its destructor. You should not construct + * multiple CoreServicePointer instances using the same service pointer, + * unless it is retrieved by a new call to a CoreServices getter method. + * + * @see CoreServices + */ +template +class CoreServicePointer +{ +public: + + explicit CoreServicePointer(S* service) + : m_service(service) + { + assert(m_service); + } + + ~CoreServicePointer() + { + try + { + CoreServices::Unget(m_service); + } + catch (const std::exception& e) + { + MITK_ERROR << e.what(); + } + catch (...) + { + MITK_ERROR << "Ungetting core service failed."; + } + } + + S* operator->() const + { + return m_service; + } + +private: + + // purposely not implemented + CoreServicePointer(const CoreServicePointer&); + CoreServicePointer& operator=(const CoreServicePointer&); + + S* const m_service; +}; + } #endif // MITKCORESERVICES_H diff --git a/Core/Code/Controllers/mitkCoreActivator.cpp b/Core/Code/Controllers/mitkCoreActivator.cpp index 180810703e..d1ff15e55c 100644 --- a/Core/Code/Controllers/mitkCoreActivator.cpp +++ b/Core/Code/Controllers/mitkCoreActivator.cpp @@ -1,224 +1,225 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkRenderingManager.h" #include "mitkPlanePositionManager.h" #include "mitkCoreDataNodeReader.h" #include "mitkShaderRepository.h" #include "mitkStandardFileLocations.h" -#include -#include -#include -#include -#include -#include - -void HandleMicroServicesMessages(mitk::MsgType type, const char* msg) +#include +#include +#include +#include +#include +#include +#include + +void HandleMicroServicesMessages(us::MsgType type, const char* msg) { switch (type) { - case mitk::DebugMsg: + case us::DebugMsg: MITK_DEBUG << msg; break; - case mitk::InfoMsg: + case us::InfoMsg: MITK_INFO << msg; break; - case mitk::WarningMsg: + case us::WarningMsg: MITK_WARN << msg; break; - case mitk::ErrorMsg: + case us::ErrorMsg: MITK_ERROR << msg; break; } } #if defined(_WIN32) || defined(_WIN64) std::string GetProgramPath() { char path[512]; std::size_t index = std::string(path, GetModuleFileName(NULL, path, 512)).find_last_of('\\'); return std::string(path, index); } #elif defined(__APPLE__) #include std::string GetProgramPath() { char path[512]; uint32_t size = sizeof(path); if (_NSGetExecutablePath(path, &size) == 0) { std::size_t index = std::string(path).find_last_of('/'); std::string strPath = std::string(path, index); const char* execPath = strPath.c_str(); mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch(execPath,false); return strPath; } return std::string(); } #else #include #include #include std::string GetProgramPath() { std::stringstream ss; ss << "/proc/" << getpid() << "/exe"; char proc[512] = {0}; ssize_t ch = readlink(ss.str().c_str(), proc, 512); if (ch == -1) return std::string(); std::size_t index = std::string(proc).find_last_of('/'); return std::string(proc, index); } #endif void AddMitkAutoLoadPaths(const std::string& programPath) { - mitk::ModuleSettings::AddAutoLoadPath(programPath); + us::ModuleSettings::AddAutoLoadPath(programPath); #ifdef __APPLE__ // Walk up three directories since that is where the .dylib files are located // for build trees. std::string additionalPath = programPath; bool addPath = true; for(int i = 0; i < 3; ++i) { std::size_t index = additionalPath.find_last_of('/'); if (index != std::string::npos) { additionalPath = additionalPath.substr(0, index); } else { addPath = false; break; } } if (addPath) { - mitk::ModuleSettings::AddAutoLoadPath(additionalPath); + us::ModuleSettings::AddAutoLoadPath(additionalPath); } #endif } /* * This is the module activator for the "Mitk" module. It registers core services * like ... */ -class MitkCoreActivator : public mitk::ModuleActivator +class MitkCoreActivator : public us::ModuleActivator { public: - void Load(mitk::ModuleContext* context) + void Load(us::ModuleContext* context) { // Handle messages from CppMicroServices - mitk::installMsgHandler(HandleMicroServicesMessages); + us::installMsgHandler(HandleMicroServicesMessages); // Add the current application directory to the auto-load paths. // This is useful for third-party executables. std::string programPath = GetProgramPath(); if (programPath.empty()) { MITK_WARN << "Could not get the program path."; } else { AddMitkAutoLoadPaths(programPath); } //m_RenderingManager = mitk::RenderingManager::New(); //context->RegisterService(renderingManager.GetPointer()); - m_PlanePositionManager = mitk::PlanePositionManagerService::New(); - context->RegisterService(m_PlanePositionManager); + m_PlanePositionManager.reset(new mitk::PlanePositionManagerService); + context->RegisterService(m_PlanePositionManager.get()); - m_CoreDataNodeReader = mitk::CoreDataNodeReader::New(); - context->RegisterService(m_CoreDataNodeReader); + m_CoreDataNodeReader.reset(new mitk::CoreDataNodeReader); + context->RegisterService(m_CoreDataNodeReader.get()); - m_ShaderRepository = mitk::ShaderRepository::New(); - context->RegisterService(m_ShaderRepository); + m_ShaderRepository.reset(new mitk::ShaderRepository); + context->RegisterService(m_ShaderRepository.get()); context->AddModuleListener(this, &MitkCoreActivator::HandleModuleEvent); /* There IS an option to exchange ALL vtkTexture instances against vtkNeverTranslucentTextureFactory. This code is left here as a reminder, just in case we might need to do that some time. vtkNeverTranslucentTextureFactory* textureFactory = vtkNeverTranslucentTextureFactory::New(); vtkObjectFactory::RegisterFactory( textureFactory ); textureFactory->Delete(); */ } - void Unload(mitk::ModuleContext* ) + void Unload(us::ModuleContext* ) { // The mitk::ModuleContext* argument of the Unload() method // will always be 0 for the Mitk library. It makes no sense // to use it at this stage anyway, since all libraries which // know about the module system have already been unloaded. } private: - void HandleModuleEvent(const mitk::ModuleEvent moduleEvent); + void HandleModuleEvent(const us::ModuleEvent moduleEvent); std::map > moduleIdToShaderIds; //mitk::RenderingManager::Pointer m_RenderingManager; - mitk::PlanePositionManagerService::Pointer m_PlanePositionManager; - mitk::CoreDataNodeReader::Pointer m_CoreDataNodeReader; - mitk::ShaderRepository::Pointer m_ShaderRepository; + std::auto_ptr m_PlanePositionManager; + std::auto_ptr m_CoreDataNodeReader; + std::auto_ptr m_ShaderRepository; }; -void MitkCoreActivator::HandleModuleEvent(const mitk::ModuleEvent moduleEvent) +void MitkCoreActivator::HandleModuleEvent(const us::ModuleEvent moduleEvent) { - if (moduleEvent.GetType() == mitk::ModuleEvent::LOADED) + if (moduleEvent.GetType() == us::ModuleEvent::LOADED) { // search and load shader files - std::vector shaderResoruces = + std::vector shaderResoruces = moduleEvent.GetModule()->FindResources("Shaders", "*.xml", true); - for (std::vector::iterator i = shaderResoruces.begin(); + for (std::vector::iterator i = shaderResoruces.begin(); i != shaderResoruces.end(); ++i) { if (*i) { - mitk::ModuleResourceStream rs(*i); + us::ModuleResourceStream rs(*i); int id = m_ShaderRepository->LoadShader(rs, i->GetBaseName()); if (id >= 0) { moduleIdToShaderIds[moduleEvent.GetModule()->GetModuleId()].push_back(id); } } } } - else if (moduleEvent.GetType() == mitk::ModuleEvent::UNLOADED) + else if (moduleEvent.GetType() == us::ModuleEvent::UNLOADED) { std::map >::iterator shaderIdsIter = moduleIdToShaderIds.find(moduleEvent.GetModule()->GetModuleId()); if (shaderIdsIter != moduleIdToShaderIds.end()) { for (std::vector::iterator idIter = shaderIdsIter->second.begin(); idIter != shaderIdsIter->second.end(); ++idIter) { m_ShaderRepository->UnloadShader(*idIter); } moduleIdToShaderIds.erase(shaderIdsIter); } } } US_EXPORT_MODULE_ACTIVATOR(Mitk, MitkCoreActivator) diff --git a/Core/Code/Controllers/mitkPlanePositionManager.cpp b/Core/Code/Controllers/mitkPlanePositionManager.cpp index 5b6fe07424..e22b217498 100644 --- a/Core/Code/Controllers/mitkPlanePositionManager.cpp +++ b/Core/Code/Controllers/mitkPlanePositionManager.cpp @@ -1,111 +1,106 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPlanePositionManager.h" #include "mitkInteractionConst.h" -#include -#include -#include - - mitk::PlanePositionManagerService::PlanePositionManagerService() { } mitk::PlanePositionManagerService::~PlanePositionManagerService() { for (unsigned int i = 0; i < m_PositionList.size(); ++i) delete m_PositionList[i]; } unsigned int mitk::PlanePositionManagerService::AddNewPlanePosition ( const Geometry2D* plane, unsigned int sliceIndex ) { for (unsigned int i = 0; i < m_PositionList.size(); ++i) { if (m_PositionList[i] != 0) { bool isSameMatrix(true); bool isSameOffset(true); isSameOffset = mitk::Equal(m_PositionList[i]->GetTransform()->GetOffset(), plane->GetIndexToWorldTransform()->GetOffset()); if(!isSameOffset || sliceIndex != m_PositionList[i]->GetPos()) continue; isSameMatrix = mitk::MatrixEqualElementWise(m_PositionList[i]->GetTransform()->GetMatrix(), plane->GetIndexToWorldTransform()->GetMatrix()); if(isSameMatrix) return i; } } AffineTransform3D::Pointer transform = AffineTransform3D::New(); Matrix3D matrix; matrix.GetVnlMatrix().set_column(0, plane->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(0)); matrix.GetVnlMatrix().set_column(1, plane->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(1)); matrix.GetVnlMatrix().set_column(2, plane->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)); transform->SetMatrix(matrix); transform->SetOffset(plane->GetIndexToWorldTransform()->GetOffset()); mitk::Vector3D direction; direction[0] = plane->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)[0]; direction[1] = plane->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)[1]; direction[2] = plane->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)[2]; direction.Normalize(); mitk::RestorePlanePositionOperation* newOp = new mitk::RestorePlanePositionOperation (OpRESTOREPLANEPOSITION, plane->GetExtent(0), plane->GetExtent(1), plane->GetSpacing(), sliceIndex, direction, transform); m_PositionList.push_back( newOp ); return GetNumberOfPlanePositions()-1; } bool mitk::PlanePositionManagerService::RemovePlanePosition( unsigned int ID ) { if (m_PositionList.size() > ID) { delete m_PositionList[ID]; m_PositionList.erase(m_PositionList.begin()+ID); return true; } else { return false; } } mitk::RestorePlanePositionOperation* mitk::PlanePositionManagerService::GetPlanePosition ( unsigned int ID ) { if ( ID < m_PositionList.size() ) { return m_PositionList[ID]; } else { MITK_WARN<<"GetPlanePosition returned NULL!"; return 0; } } unsigned int mitk::PlanePositionManagerService::GetNumberOfPlanePositions() { return m_PositionList.size(); } void mitk::PlanePositionManagerService::RemoveAllPlanePositions() { for (unsigned int i = 0; i < m_PositionList.size(); ++i) delete m_PositionList[i]; m_PositionList.clear(); } diff --git a/Core/Code/Controllers/mitkPlanePositionManager.h b/Core/Code/Controllers/mitkPlanePositionManager.h index c578ca4840..e9989f9686 100644 --- a/Core/Code/Controllers/mitkPlanePositionManager.h +++ b/Core/Code/Controllers/mitkPlanePositionManager.h @@ -1,103 +1,93 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkPlanePositionManager_h_Included #define mitkPlanePositionManager_h_Included #include "mitkCommon.h" -//#include "MitkExtExports.h" #include "mitkRestorePlanePositionOperation.h" #include "mitkDataStorage.h" -#include -#include -#include + +#include class MitkCoreActivator; namespace mitk { /** The mitk::PlanePositionManagerService holds and manages a list of certain planepositions. To store a new position you need to specify the first slice of your slicestack and the slicenumber you want to restore in the mitk::PlanePositionManager::AddNewPlanePosition() function. To restore a position call mitk::PlanePositionManagerService::GetPlanePosition(ID) where ID is the position in the plane positionlist (returned by AddNewPlanePostion). This will give a mitk::RestorePlanePositionOperation which can be executed by the SliceNavigationController of the slicestack. \sa QmitkSegmentationView.cpp */ - class MITK_CORE_EXPORT PlanePositionManagerService : public itk::LightObject + class MITK_CORE_EXPORT PlanePositionManagerService { public: + PlanePositionManagerService(); + ~PlanePositionManagerService(); + /** \brief Adds a new plane position to the list. If this geometry is identical to one of the list nothing will be added \a plane THE FIRST! slice of the slice stack \a sliceIndex the slice number of the selected slice \return returns the ID i.e. the position in the positionlist. If the PlaneGeometry which is to be added already exists the existing ID will be returned. */ unsigned int AddNewPlanePosition(const mitk::Geometry2D* plane, unsigned int sliceIndex = 0); /** \brief Removes the plane at the position \a ID from the list. \a ID the plane ID which should be removed, i.e. its position in the list \return true if the plane was removed successfully and false if it is an invalid ID */ bool RemovePlanePosition(unsigned int ID); /// \brief Clears the complete positionlist void RemoveAllPlanePositions(); /** \brief Getter for a specific plane position with a given ID \a ID the ID of the plane position \return Returns a RestorePlanePositionOperation which can be executed by th SliceNavigationController or NULL for an invalid ID */ mitk::RestorePlanePositionOperation* GetPlanePosition( unsigned int ID); /// \brief Getting the number of all stored planes unsigned int GetNumberOfPlanePositions(); - friend class ::MitkCoreActivator; - private: - - mitkClassMacro(PlanePositionManagerService, LightObject); - - itkFactorylessNewMacro(PlanePositionManagerService); - - PlanePositionManagerService(); - ~PlanePositionManagerService(); - // Disable copy constructor and assignment operator. PlanePositionManagerService(const PlanePositionManagerService&); PlanePositionManagerService& operator=(const PlanePositionManagerService&); - static PlanePositionManagerService* m_Instance; std::vector m_PositionList; }; } US_DECLARE_SERVICE_INTERFACE(mitk::PlanePositionManagerService, "org.mitk.PlanePositionManagerService") #endif diff --git a/Core/Code/CppMicroServices/CMake/MacroParseArguments.cmake b/Core/Code/CppMicroServices/CMake/MacroParseArguments.cmake deleted file mode 100644 index 8f61fdc704..0000000000 --- a/Core/Code/CppMicroServices/CMake/MacroParseArguments.cmake +++ /dev/null @@ -1,79 +0,0 @@ -# macro(MACRO_PARSE_ARGUMENTS prefix arg_names option_names) -# -# From http://www.cmake.org/Wiki/CMakeMacroParseArguments: -# -# The MACRO_PARSE_ARGUMENTS macro will take the arguments of another macro and -# define several variables: -# -# 1) The first argument to is a prefix to put on all variables it creates. -# 2) The second argument is a quoted list of names, -# 3) and the third argument is a quoted list of options. -# -# The rest of MACRO_PARSE_ARGUMENTS are arguments from another macro to be -# parsed. -# -# MACRO_PARSE_ARGUMENTS(prefix arg_names options arg1 arg2...) -# -# For each item in options, MACRO_PARSE_ARGUMENTS will create a variable -# with that name, prefixed with prefix_. So, for example, if prefix is -# MY_MACRO and options is OPTION1;OPTION2, then PARSE_ARGUMENTS will create -# the variables MY_MACRO_OPTION1 and MY_MACRO_OPTION2. These variables will -# be set to true if the option exists in the command line or false otherwise. -# -# For each item in arg_names, MACRO_PARSE_ARGUMENTS will create a variable -# with that name, prefixed with prefix_. Each variable will be filled with the -# arguments that occur after the given arg_name is encountered up to the next -# arg_name or the end of the arguments. All options are removed from these -# lists. -# -# MACRO_PARSE_ARGUMENTS also creates a prefix_DEFAULT_ARGS variable containing -# the list of all arguments up to the first arg_name encountered. - -if(NOT COMMAND MACRO_PARSE_ARGUMENTS) - -macro(MACRO_PARSE_ARGUMENTS prefix arg_names option_names) - - set(DEFAULT_ARGS) - - foreach(arg_name ${arg_names}) - set(${prefix}_${arg_name}) - endforeach(arg_name) - - foreach(option ${option_names}) - set(${prefix}_${option} FALSE) - endforeach(option) - - set(current_arg_name DEFAULT_ARGS) - set(current_arg_list) - - foreach(arg ${ARGN}) - - set(larg_names ${arg_names}) - list(FIND larg_names "${arg}" is_arg_name) - - if(is_arg_name GREATER -1) - - set(${prefix}_${current_arg_name} ${current_arg_list}) - set(current_arg_name "${arg}") - set(current_arg_list) - - else(is_arg_name GREATER -1) - - set(loption_names ${option_names}) - list(FIND loption_names "${arg}" is_option) - - if(is_option GREATER -1) - set(${prefix}_${arg} TRUE) - else(is_option GREATER -1) - set(current_arg_list ${current_arg_list} "${arg}") - endif(is_option GREATER -1) - - endif(is_arg_name GREATER -1) - - endforeach(arg ${ARGN}) - - set(${prefix}_${current_arg_name} ${current_arg_list}) - -endmacro(MACRO_PARSE_ARGUMENTS) - -endif(NOT COMMAND MACRO_PARSE_ARGUMENTS) diff --git a/Core/Code/CppMicroServices/CMake/usCTestScript.cmake b/Core/Code/CppMicroServices/CMake/usCTestScript.cmake deleted file mode 100644 index 7feac62e8e..0000000000 --- a/Core/Code/CppMicroServices/CMake/usCTestScript.cmake +++ /dev/null @@ -1,131 +0,0 @@ - -macro(build_and_test) - - set(CTEST_SOURCE_DIRECTORY ${US_SOURCE_DIR}) - set(CTEST_BINARY_DIRECTORY "${CTEST_DASHBOARD_ROOT}/${CTEST_PROJECT_NAME}_${CTEST_DASHBOARD_NAME}") - - #if(NOT CTEST_BUILD_NAME) - # set(CTEST_BUILD_NAME "${CMAKE_SYSTEM}_${CTEST_COMPILER}_${CTEST_DASHBOARD_NAME}") - #endif() - - ctest_empty_binary_directory(${CTEST_BINARY_DIRECTORY}) - - ctest_start("Experimental") - - if(NOT EXISTS "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt") - file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt" "${CTEST_INITIAL_CACHE}") - endif() - - ctest_configure(RETURN_VALUE res) - if (res) - message(FATAL_ERROR "CMake configure error") - endif() - ctest_build(RETURN_VALUE res) - if (res) - message(FATAL_ERROR "CMake build error") - endif() - - ctest_test(RETURN_VALUE res PARALLEL_LEVEL ${CTEST_PARALLEL_LEVEL}) - if (res) - message(FATAL_ERROR "CMake test error") - endif() - - - if(WITH_MEMCHECK AND CTEST_MEMORYCHECK_COMMAND) - ctest_memcheck() - endif() - - if(WITH_COVERAGE AND CTEST_COVERAGE_COMMAND) - ctest_coverage() - endif() - - #ctest_submit() - -endmacro() - -function(create_initial_cache var _shared _threading _sf _cxx11 _autoload) - - set(_initial_cache " - US_BUILD_TESTING:BOOL=ON - US_BUILD_SHARED_LIBS:BOOL=${_shared} - US_ENABLE_THREADING_SUPPORT:BOOL=${_threading} - US_ENABLE_SERVICE_FACTORY_SUPPORT:BOOL=${_sf} - US_USE_C++11:BOOL=${_cxx11} - US_ENABLE_AUTOLOADING_SUPPORT:BOOL=${_autoload} - ") - - set(${var} ${_initial_cache} PARENT_SCOPE) - - if(_shared) - set(CTEST_DASHBOARD_NAME "shared") - else() - set(CTEST_DASHBOARD_NAME "static") - endif() - - if(_threading) - set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-threading") - endif() - if(_sf) - set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-servicefactory") - endif() - if(_cxx11) - set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-cxx11") - endif() - if(_autoload) - set(CTEST_DASHBOARD_NAME "${CTEST_DASHBOARD_NAME}-autoloading") - endif() - - set(CTEST_DASHBOARD_NAME ${CTEST_DASHBOARD_NAME} PARENT_SCOPE) - -endfunction() - -#========================================================= - -set(CTEST_PROJECT_NAME CppMicroServices) - -if(NOT CTEST_PARALLEL_LEVEL) - set(CTEST_PARALLEL_LEVEL 1) -endif() - - -# SHARED THREADING SERVICE_FACTORY C++11 AUTOLOAD - -set(config0 0 0 0 0 0 ) -set(config1 0 0 0 0 1 ) -set(config2 0 0 0 1 0 ) -set(config3 0 0 0 1 1 ) -set(config4 0 0 1 0 0 ) -set(config5 0 0 1 0 1 ) -set(config6 0 0 1 1 0 ) -set(config7 0 0 1 1 1 ) -set(config8 0 1 0 0 0 ) -set(config9 0 1 0 0 1 ) -set(config10 0 1 0 1 0 ) -set(config11 0 1 0 1 1 ) -set(config12 0 1 1 0 0 ) -set(config13 0 1 1 0 1 ) -set(config14 0 1 1 1 0 ) -set(config15 0 1 1 1 1 ) -set(config16 1 0 0 0 0 ) -set(config17 1 0 0 0 1 ) -set(config18 1 0 0 1 0 ) -set(config19 1 0 0 1 1 ) -set(config20 1 0 1 0 0 ) -set(config21 1 0 1 0 1 ) -set(config22 1 0 1 1 0 ) -set(config23 1 0 1 1 1 ) -set(config24 1 1 0 0 0 ) -set(config25 1 1 0 0 1 ) -set(config26 1 1 0 1 0 ) -set(config27 1 1 0 1 1 ) -set(config28 1 1 1 0 0 ) -set(config29 1 1 1 0 1 ) -set(config30 1 1 1 1 0 ) -set(config31 1 1 1 1 1 ) - -foreach(i ${US_BUILD_CONFIGURATION}) - create_initial_cache(CTEST_INITIAL_CACHE ${config${i}}) - message("Testing build configuration: ${CTEST_DASHBOARD_NAME}") - build_and_test() -endforeach() - diff --git a/Core/Code/CppMicroServices/CMake/usCTestScript_custom.cmake b/Core/Code/CppMicroServices/CMake/usCTestScript_custom.cmake deleted file mode 100644 index 1a1faac564..0000000000 --- a/Core/Code/CppMicroServices/CMake/usCTestScript_custom.cmake +++ /dev/null @@ -1,25 +0,0 @@ - -find_program(CTEST_COVERAGE_COMMAND NAMES gcov) -find_program(CTEST_MEMORYCHECK_COMMAND NAMES valgrind) -find_program(CTEST_GIT_COMMAND NAMES git) - -set(CTEST_SITE "bigeye") -set(CTEST_DASHBOARD_ROOT "/tmp") -#set(CTEST_COMPILER "gcc-4.5") -set(CTEST_CMAKE_GENERATOR "Unix Makefiles") -set(CTEST_BUILD_FLAGS "-j") -set(CTEST_BUILD_CONFIGURATION Debug) -set(CTEST_PARALLEL_LEVEL 4) - -set(US_TEST_SHARED 1) -set(US_TEST_STATIC 1) - -set(US_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/../") - -set(US_BUILD_CONFIGURATION ) -foreach(i RANGE 31) - list(APPEND US_BUILD_CONFIGURATION ${i}) -endforeach() - -include(${US_SOURCE_DIR}/CMake/usCTestScript.cmake) - diff --git a/Core/Code/CppMicroServices/CMake/usCTestScript_travis.cmake b/Core/Code/CppMicroServices/CMake/usCTestScript_travis.cmake deleted file mode 100644 index 1cd1030b3c..0000000000 --- a/Core/Code/CppMicroServices/CMake/usCTestScript_travis.cmake +++ /dev/null @@ -1,18 +0,0 @@ - -find_program(CTEST_COVERAGE_COMMAND NAMES gcov) -find_program(CTEST_MEMORYCHECK_COMMAND NAMES valgrind) -find_program(CTEST_GIT_COMMAND NAMES git) - -set(CTEST_SITE "travis-ci") -set(CTEST_DASHBOARD_ROOT "/tmp") -#set(CTEST_COMPILER "gcc-4.5") -set(CTEST_CMAKE_GENERATOR "Unix Makefiles") -set(CTEST_BUILD_FLAGS "-j") -set(CTEST_BUILD_CONFIGURATION Release) - - -set(US_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/../") - -set(US_BUILD_CONFIGURATION $ENV{BUILD_CONFIGURATION}) -include(${US_SOURCE_DIR}/CMake/usCTestScript.cmake) - diff --git a/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake b/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake deleted file mode 100644 index 8e7e806576..0000000000 --- a/Core/Code/CppMicroServices/CMake/usFunctionCheckCompilerFlags.cmake +++ /dev/null @@ -1,53 +0,0 @@ -# -# Helper macro allowing to check if the given flags are supported -# by the underlying build tool -# -# If the flag(s) is/are supported, they will be appended to the string identified by RESULT_VAR -# -# Usage: -# usFunctionCheckCompilerFlags(FLAGS_TO_CHECK VALID_FLAGS_VAR) -# -# Example: -# -# set(myflags) -# usFunctionCheckCompilerFlags("-fprofile-arcs" myflags) -# message(1-myflags:${myflags}) -# usFunctionCheckCompilerFlags("-fauto-bugfix" myflags) -# message(2-myflags:${myflags}) -# usFunctionCheckCompilerFlags("-Wall" myflags) -# message(1-myflags:${myflags}) -# -# The output will be: -# 1-myflags: -fprofile-arcs -# 2-myflags: -fprofile-arcs -# 3-myflags: -fprofile-arcs -Wall - -include(TestCXXAcceptsFlag) - -function(usFunctionCheckCompilerFlags CXX_FLAG_TO_TEST RESULT_VAR) - - if(CXX_FLAG_TO_TEST STREQUAL "") - message(FATAL_ERROR "CXX_FLAG_TO_TEST shouldn't be empty") - endif() - - set(_test_flag ${CXX_FLAG_TO_TEST}) - CHECK_CXX_ACCEPTS_FLAG("-Werror=unknown-warning-option" HAS_FLAG_unknown-warning-option) - if(HAS_FLAG_unknown-warning-option) - set(_test_flag "-Werror=unknown-warning-option ${CXX_FLAG_TO_TEST}") - endif() - - # Internally, the macro CMAKE_CXX_ACCEPTS_FLAG calls TRY_COMPILE. To avoid - # the cost of compiling the test each time the project is configured, the variable set by - # the macro is added to the cache so that following invocation of the macro with - # the same variable name skip the compilation step. - # For that same reason, usFunctionCheckCompilerFlags function appends a unique suffix to - # the HAS_FLAG variable. This suffix is created using a 'clean version' of the flag to test. - string(REGEX REPLACE "-\\s\\$\\+\\*\\{\\}\\(\\)\\#" "" suffix ${CXX_FLAG_TO_TEST}) - CHECK_CXX_ACCEPTS_FLAG(${_test_flag} HAS_FLAG_${suffix}) - - if(HAS_FLAG_${suffix}) - set(${RESULT_VAR} "${${RESULT_VAR}} ${CXX_FLAG_TO_TEST}" PARENT_SCOPE) - endif() - -endfunction() - diff --git a/Core/Code/CppMicroServices/CMake/usFunctionCompileSnippets.cmake b/Core/Code/CppMicroServices/CMake/usFunctionCompileSnippets.cmake deleted file mode 100644 index 962e2e9c37..0000000000 --- a/Core/Code/CppMicroServices/CMake/usFunctionCompileSnippets.cmake +++ /dev/null @@ -1,49 +0,0 @@ -function(usFunctionCompileSnippets snippet_path) - - # get all files called "main.cpp" - file(GLOB_RECURSE main_cpp_list "${snippet_path}/main.cpp") - - foreach(main_cpp_file ${main_cpp_list}) - # get the directory containing the main.cpp file - get_filename_component(main_cpp_dir "${main_cpp_file}" PATH) - - set(snippet_src_files ) - - # If there exists a "files.cmake" file in the snippet directory, - # include it and assume it sets the variable "snippet_src_files" - # to a list of source files for the snippet. - if(EXISTS "${main_cpp_dir}/files.cmake") - include("${main_cpp_dir}/files.cmake") - set(_tmp_src_files ${snippet_src_files}) - set(snippet_src_files ) - foreach(_src_file ${_tmp_src_files}) - if(IS_ABSOLUTE ${_src_file}) - list(APPEND snippet_src_files ${_src_file}) - else() - list(APPEND snippet_src_files ${main_cpp_dir}/${_src_file}) - endif() - endforeach() - else() - # glob all files in the directory and add them to the snippet src list - file(GLOB_RECURSE snippet_src_files "${main_cpp_dir}/*") - endif() - - # Uset the top-level directory name as the executable name - string(REPLACE "/" ";" main_cpp_dir_tokens "${main_cpp_dir}") - list(GET main_cpp_dir_tokens -1 snippet_exec_name) - set(snippet_target_name "Snippet-${snippet_exec_name}") - add_executable(${snippet_target_name} ${snippet_src_files}) - if(ARGN) - target_link_libraries(${snippet_target_name} ${ARGN} ${snippet_link_libraries}) - endif() - set_target_properties(${snippet_target_name} PROPERTIES - LABELS Documentation - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/snippets" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/snippets" - LIBRARY_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/snippets" - OUTPUT_NAME ${snippet_exec_name} - ) - - endforeach() - -endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake b/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake deleted file mode 100644 index 6d90dc0ae4..0000000000 --- a/Core/Code/CppMicroServices/CMake/usFunctionCreateTestModule.cmake +++ /dev/null @@ -1,51 +0,0 @@ - -macro(_us_create_test_module_helper) - - if(_res_files) - usFunctionEmbedResources(_srcs LIBRARY_NAME ${name} ROOT_DIR ${_res_root} FILES ${_res_files}) - endif() - - add_library(${name} ${_srcs}) - if(NOT US_BUILD_SHARED_LIBS) - set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS US_STATIC_MODULE) - endif() - - if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64") - get_property(_compile_flags TARGET ${name} PROPERTY COMPILE_FLAGS) - set_property(TARGET ${name} PROPERTY COMPILE_FLAGS "${_compile_flags} -fPIC") - endif() - - target_link_libraries(${name} ${US_LINK_LIBRARIES}) - if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - target_link_libraries(${name} ${US_BASECLASS_LIBRARIES}) - endif() - - set(_us_test_module_libs "${_us_test_module_libs};${name}" CACHE INTERNAL "" FORCE) - -endmacro() - -function(usFunctionCreateTestModuleWithAutoLoadDir name autoload_dir) - set(_srcs ${ARGN}) - usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name} AUTOLOAD_DIR ${autoload_dir}) - _us_create_test_module_helper() -endfunction() - -function(usFunctionCreateTestModule name) - set(_srcs ${ARGN}) - set(_res_files ) - usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name}) - _us_create_test_module_helper() -endfunction() - -function(usFunctionCreateTestModuleWithResources name) - MACRO_PARSE_ARGUMENTS(US_TEST "SOURCES;RESOURCES;RESOURCES_ROOT" "" ${ARGN}) - set(_srcs ${US_TEST_SOURCES}) - set(_res_files ${US_TEST_RESOURCES}) - if(US_TEST_RESOURCES_ROOT) - set(_res_root ${US_TEST_RESOURCES_ROOT}) - else() - set(_res_root resources) - endif() - usFunctionGenerateModuleInit(_srcs NAME "${name} Module" LIBRARY_NAME ${name}) - _us_create_test_module_helper() -endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usFunctionEmbedResources.cmake b/Core/Code/CppMicroServices/CMake/usFunctionEmbedResources.cmake deleted file mode 100644 index c559177c5e..0000000000 --- a/Core/Code/CppMicroServices/CMake/usFunctionEmbedResources.cmake +++ /dev/null @@ -1,147 +0,0 @@ -#! Embed resources into a shared library or executable. -#! -#! This CMake function uses an external command line program to generate a source -#! file containing data from external resources such as text files or images. The path -#! to the generated source file is appended to the \c src_var variable. -#! -#! Each module can call this function (at most once) to embed resources and make them -#! available at runtime through the Module class. Resources can also be embedded into -#! executables, using the EXECUTABLE_NAME argument instead of LIBRARY_NAME. -#! -#! Example usage: -#! \verbatim -#! set(module_srcs ) -#! usFunctionEmbedResources(module_srcs -#! LIBRARY_NAME "mylib" -#! ROOT_DIR resources -#! FILES config.properties logo.png -#! ) -#! \endverbatim -#! -#! \param LIBRARY_NAME (required if EXECUTABLE_NAME is empty) The library name of the module -#! which will include the generated source file, without extension. -#! \param EXECUTABLE_NAME (required if LIBRARY_NAME is empty) The name of the executable -#! which will include the generated source file. -#! \param COMPRESSION_LEVEL (optional) The zip compression level. Defaults to the default zip -#! level. Level 0 disables compression. -#! \param COMPRESSION_THRESHOLD (optional) The compression threshold ranging from 0 to 100 for -#! actually compressing the resource data. The default threshold is 30, meaning a size -#! reduction of 30 percent or better results in the resource data being compressed. -#! \param ROOT_DIR (optional) The root path for all resources listed after the FILES argument. -#! If no or a relative path is given, it is considered relativ to the current CMake source directory. -#! \param FILES (optional) A list of resources (paths to external files in the file system) relative -#! to the ROOT_DIR argument or the current CMake source directory if ROOT_DIR is empty. -#! -#! The ROOT_DIR and FILES arguments may be repeated any number of times to merge files from -#! different root directories into the embedded resource tree (hence the relative file paths -#! after the FILES argument must be unique). -#! -function(usFunctionEmbedResources src_var) - - set(prefix US_RESOURCE) - set(arg_names LIBRARY_NAME EXECUTABLE_NAME COMPRESSION_LEVEL COMPRESSION_THRESHOLD ROOT_DIR FILES) - foreach(arg_name ${arg_names}) - set(${prefix}_${arg_name}) - endforeach(arg_name) - - set(cmd_line_args ) - set(absolute_res_files ) - set(current_arg_name DEFAULT_ARGS) - set(current_arg_list) - set(current_root_dir ${CMAKE_CURRENT_SOURCE_DIR}) - foreach(arg ${ARGN}) - - list(FIND arg_names "${arg}" is_arg_name) - - if(is_arg_name GREATER -1) - set(${prefix}_${current_arg_name} ${current_arg_list}) - set(current_arg_name "${arg}") - set(current_arg_list) - else() - set(current_arg_list ${current_arg_list} "${arg}") - if(current_arg_name STREQUAL "ROOT_DIR") - set(current_root_dir "${arg}") - if(NOT IS_ABSOLUTE ${current_root_dir}) - set(current_root_dir "${CMAKE_CURRENT_SOURCE_DIR}/${current_root_dir}") - endif() - if(NOT IS_DIRECTORY ${current_root_dir}) - message(SEND_ERROR "The ROOT_DIR argument is not a directory: ${current_root_dir}") - endif() - get_filename_component(current_root_dir "${current_root_dir}" REALPATH) - file(TO_NATIVE_PATH "${current_root_dir}" current_root_dir_native) - list(APPEND cmd_line_args -d "${current_root_dir_native}") - elseif(current_arg_name STREQUAL "FILES") - set(res_file "${current_root_dir}/${arg}") - file(TO_NATIVE_PATH "${res_file}" res_file_native) - if(IS_DIRECTORY ${res_file}) - message(SEND_ERROR "A resource cannot be a directory: ${res_file_native}") - endif() - if(NOT EXISTS ${res_file}) - message(SEND_ERROR "Resource does not exists: ${res_file_native}") - endif() - list(APPEND absolute_res_files ${res_file}) - file(TO_NATIVE_PATH "${arg}" res_filename_native) - list(APPEND cmd_line_args "${res_filename_native}") - endif() - endif(is_arg_name GREATER -1) - - endforeach(arg ${ARGN}) - - set(${prefix}_${current_arg_name} ${current_arg_list}) - - if(NOT src_var) - message(SEND_ERROR "Output variable name not specified.") - endif() - - if(US_RESOURCE_EXECUTABLE_NAME AND US_RESOURCE_LIBRARY_NAME) - message(SEND_ERROR "Only one of LIBRARY_NAME or EXECUTABLE_NAME can be specified.") - endif() - - if(NOT US_RESOURCE_LIBRARY_NAME AND NOT US_RESOURCE_EXECUTABLE_NAME) - message(SEND_ERROR "LIBRARY_NAME or EXECUTABLE_NAME argument not specified.") - endif() - - if(NOT US_RESOURCE_FILES) - message(WARNING "No FILES argument given. Skipping resource processing.") - return() - endif() - - list(GET cmd_line_args 0 first_arg) - if(NOT first_arg STREQUAL "-d") - set(cmd_line_args -d "${CMAKE_CURRENT_SOURCE_DIR}" ${cmd_line_args}) - endif() - - if(US_RESOURCE_COMPRESSION_LEVEL) - set(cmd_line_args -c ${US_RESOURCE_COMPRESSION_LEVEL} ${cmd_line_args}) - endif() - - if(US_RESOURCE_COMPRESSION_THRESHOLD) - set(cmd_line_args -t ${US_RESOURCE_COMPRESSION_THRESHOLD} ${cmd_line_args}) - endif() - - if(US_RESOURCE_LIBRARY_NAME) - set(us_cpp_resource_file "${CMAKE_CURRENT_BINARY_DIR}/${US_RESOURCE_LIBRARY_NAME}_resources.cpp") - set(us_lib_name ${US_RESOURCE_LIBRARY_NAME}) - else() - set(us_cpp_resource_file "${CMAKE_CURRENT_BINARY_DIR}/${US_RESOURCE_EXECUTABLE_NAME}_resources.cpp") - set(us_lib_name "\"\"") - endif() - - set(resource_compiler ${CppMicroServices_RCC_EXECUTABLE}) - if(TARGET ${CppMicroServices_RCC_EXECUTABLE_NAME}) - set(resource_compiler ${CppMicroServices_RCC_EXECUTABLE_NAME}) - elseif(NOT resource_compiler) - message(FATAL_ERROR "The CppMicroServices resource compiler was not found. Check the CppMicroServices_RCC_EXECUTABLE CMake variable.") - endif() - - add_custom_command( - OUTPUT ${us_cpp_resource_file} - COMMAND ${resource_compiler} "${us_lib_name}" ${us_cpp_resource_file} ${cmd_line_args} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - DEPENDS ${absolute_res_files} ${resource_compiler} - COMMENT "Generating embedded resource file ${us_cpp_resource_name}" - ) - - set(${src_var} "${${src_var}};${us_cpp_resource_file}" PARENT_SCOPE) - -endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake b/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake deleted file mode 100644 index a63b6e4d9c..0000000000 --- a/Core/Code/CppMicroServices/CMake/usFunctionGenerateModuleInit.cmake +++ /dev/null @@ -1,85 +0,0 @@ -#! Generate a source file which handles proper initialization of a module. -#! -#! This CMake function will store the path to a generated source file in the -#! src_var variable, which should be compiled into a module. Example usage: -#! -#! \verbatim -#! set(module_srcs ) -#! usFunctionGenerateModuleInit(module_srcs -#! NAME "My Module" -#! LIBRARY_NAME "mylib" -#! VERSION "1.2.0" -#! ) -#! add_library(mylib ${module_srcs}) -#! \endverbatim -#! -#! \param src_var (required) The name of a list variable to which the path of the generated -#! source file will be appended. -#! \param NAME (required) A human-readable name for the module. -#! \param LIBRARY_NAME (optional) The name of the module, without extension. If empty, the -#! NAME argument will be used. -#! \param AUTOLOAD_DIR (optional) The name of a directory relative to this modules library -#! location from which modules will be auto-loaded during activation of this module. -#! If unspecified, the LIBRARY_NAME argument will be used. If an empty string is provided, -#! auto-loading will be disabled for this module. -#! \param DEPENDS (optional) A string containing module dependencies. -#! \param VERSION (optional) A version string for the module. -#! \param EXECUTABLE (flag) A flag indicating that the initialization code is intended for -#! an executable. -#! -function(usFunctionGenerateModuleInit src_var) - -MACRO_PARSE_ARGUMENTS(US_MODULE "NAME;LIBRARY_NAME;AUTOLOAD_DIR;DEPENDS;VERSION" "EXECUTABLE" ${ARGN}) - -# sanity checks -if(NOT US_MODULE_NAME) - message(SEND_ERROR "NAME argument is mandatory") -endif() - -if(US_MODULE_EXECUTABLE AND US_MODULE_LIBRARY_NAME) - message("[Executable: ${US_MODULE_NAME}] Ignoring LIBRARY_NAME argument.") - set(US_MODULE_LIBRARY_NAME ) -endif() - -if(NOT US_MODULE_LIBRARY_NAME AND NOT US_MODULE_EXECUTABLE) - set(US_MODULE_LIBRARY_NAME ${US_MODULE_NAME}) -endif() - -set(_regex_validation "[a-zA-Z_-][a-zA-Z_0-9-]*") -if(US_MODULE_EXECUTABLE) - string(REGEX MATCH ${_regex_validation} _valid_chars ${US_MODULE_NAME}) - if(NOT _valid_chars STREQUAL US_MODULE_NAME) - message(FATAL_ERROR "[Executable: ${US_MODULE_NAME}] MODULE_NAME contains illegal characters.") - endif() -else() - string(REGEX MATCH ${_regex_validation} _valid_chars ${US_MODULE_LIBRARY_NAME}) - if(NOT _valid_chars STREQUAL US_MODULE_LIBRARY_NAME) - message(FATAL_ERROR "[Module: ${US_MODULE_NAME}] LIBRARY_NAME \"${US_MODULE_LIBRARY_NAME}\" contains illegal characters.") - endif() -endif() - -# The call to MACRO_PARSE_ARGUMENTS always defines variables for the argument names. -# Check manually if AUTOLOAD_DIR was provided or not. -list(FIND ARGN AUTOLOAD_DIR _is_autoload_dir_defined) -if(_is_autoload_dir_defined EQUAL -1) - set(US_MODULE_AUTOLOAD_DIR ${US_MODULE_LIBRARY_NAME}) -endif() - -# Create variables of the ModuleInfo object, created in CMake/usModuleInit.cpp -set(US_MODULE_DEPENDS_STR "") -foreach(_dep ${US_MODULE_DEPENDS}) - set(US_MODULE_DEPENDS_STR "${US_MODULE_DEPENDS_STR} ${_dep}") -endforeach() - -if(US_MODULE_LIBRARY_NAME) - set(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_MODULE_LIBRARY_NAME}_init.cpp") -else() - set(module_init_src_file "${CMAKE_CURRENT_BINARY_DIR}/${US_MODULE_NAME}_init.cpp") -endif() - -configure_file(${CppMicroServices_SOURCE_DIR}/CMake/usModuleInit.cpp ${module_init_src_file} @ONLY) - -set(_src ${${src_var}} ${module_init_src_file}) -set(${src_var} ${_src} PARENT_SCOPE) - -endfunction() diff --git a/Core/Code/CppMicroServices/CMake/usFunctionGetGccVersion.cmake b/Core/Code/CppMicroServices/CMake/usFunctionGetGccVersion.cmake deleted file mode 100644 index 053ef33b6b..0000000000 --- a/Core/Code/CppMicroServices/CMake/usFunctionGetGccVersion.cmake +++ /dev/null @@ -1,19 +0,0 @@ - -#! \brief Get the gcc version -function(usFunctionGetGccVersion path_to_gcc output_var) - if(CMAKE_COMPILER_IS_GNUCXX) - execute_process( - COMMAND ${path_to_gcc} -dumpversion - RESULT_VARIABLE result - OUTPUT_VARIABLE output - ERROR_VARIABLE error - OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_STRIP_TRAILING_WHITESPACE - ) - if(result) - message(FATAL_ERROR "Failed to obtain compiler version running [${path_to_gcc} -dumpversion]: ${error}") - endif() - set(${output_var} ${output} PARENT_SCOPE) - endif() -endfunction() - diff --git a/Core/Code/CppMicroServices/CMake/usModuleInit.cpp b/Core/Code/CppMicroServices/CMake/usModuleInit.cpp deleted file mode 100644 index f9c9ddbe1a..0000000000 --- a/Core/Code/CppMicroServices/CMake/usModuleInit.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR("@US_MODULE_NAME@", "@US_MODULE_LIBRARY_NAME@", "@US_MODULE_AUTOLOAD_DIR@", "@US_MODULE_DEPENDS_STR@", "@US_MODULE_VERSION@") diff --git a/Core/Code/CppMicroServices/CMake/usPublicHeaderWrapper.h.in b/Core/Code/CppMicroServices/CMake/usPublicHeaderWrapper.h.in deleted file mode 100644 index 556302f562..0000000000 --- a/Core/Code/CppMicroServices/CMake/usPublicHeaderWrapper.h.in +++ /dev/null @@ -1 +0,0 @@ -#include "@_us_public_header@" diff --git a/Core/Code/CppMicroServices/CMakeLists.txt b/Core/Code/CppMicroServices/CMakeLists.txt deleted file mode 100644 index bed7726a9c..0000000000 --- a/Core/Code/CppMicroServices/CMakeLists.txt +++ /dev/null @@ -1,357 +0,0 @@ -project(CppMicroServices) - -set(${PROJECT_NAME}_MAJOR_VERSION 0) -set(${PROJECT_NAME}_MINOR_VERSION 99) -set(${PROJECT_NAME}_PATCH_VERSION 0) -set(${PROJECT_NAME}_VERSION ${${PROJECT_NAME}_MAJOR_VERSION}.${${PROJECT_NAME}_MINOR_VERSION}.${${PROJECT_NAME}_PATCH_VERSION}) - -cmake_minimum_required(VERSION 2.8) - -#----------------------------------------------------------------------------- -# Update CMake module path -#------------------------------------------------------------------------------ - -set(CMAKE_MODULE_PATH - ${PROJECT_SOURCE_DIR}/CMake - ${CMAKE_MODULE_PATH} - ) - -#----------------------------------------------------------------------------- -# CMake function(s) and macro(s) -#----------------------------------------------------------------------------- - -include(MacroParseArguments) -include(CheckCXXSourceCompiles) -include(usFunctionCheckCompilerFlags) -include(usFunctionEmbedResources) -include(usFunctionGetGccVersion) -include(usFunctionGenerateModuleInit) - -#----------------------------------------------------------------------------- -# Init output directories -#----------------------------------------------------------------------------- - -set(US_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") -set(US_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") -set(US_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") - -foreach(_type ARCHIVE LIBRARY RUNTIME) - if(NOT CMAKE_${_type}_OUTPUT_DIRECTORY) - set(CMAKE_${_type}_OUTPUT_DIRECTORY ${US_${_type}_OUTPUT_DIRECTORY}) - endif() -endforeach() - -#----------------------------------------------------------------------------- -# 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() - -#----------------------------------------------------------------------------- -# CMake options -#----------------------------------------------------------------------------- - -function(us_cache_var _var_name _var_default _var_type _var_help) - set(_advanced 0) - set(_force) - foreach(_argn ${ARGN}) - if(_argn STREQUAL ADVANCED) - set(_advanced 1) - elseif(_argn STREQUAL FORCE) - set(_force FORCE) - endif() - endforeach() - - if(US_IS_EMBEDDED) - if(NOT DEFINED ${_var_name} OR _force) - set(${_var_name} ${_var_default} PARENT_SCOPE) - endif() - else() - set(${_var_name} ${_var_default} CACHE ${_var_type} "${_var_help}" ${_force}) - if(_advanced) - mark_as_advanced(${_var_name}) - endif() - endif() -endfunction() - -# Determine if we are being build inside a larger project -if(NOT DEFINED US_IS_EMBEDDED) - if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) - set(US_IS_EMBEDDED 0) - else() - set(US_IS_EMBEDDED 1) - set(CppMicroServices_EXPORTS 1) - endif() -endif() - -us_cache_var(US_ENABLE_AUTOLOADING_SUPPORT OFF BOOL "Enable module auto-loading support") -us_cache_var(US_ENABLE_SERVICE_FACTORY_SUPPORT ON BOOL "Enable Service Factory support" ADVANCED) -us_cache_var(US_ENABLE_THREADING_SUPPORT OFF BOOL "Enable threading support") -us_cache_var(US_ENABLE_DEBUG_OUTPUT OFF BOOL "Enable debug messages" ADVANCED) -us_cache_var(US_ENABLE_RESOURCE_COMPRESSION ON BOOL "Enable resource compression" ADVANCED) -us_cache_var(US_BUILD_SHARED_LIBS ON BOOL "Build shared libraries") -us_cache_var(US_BUILD_TESTING OFF BOOL "Build tests") - -if(MSVC10 OR MSVC11) - # Visual Studio 2010 and newer have support for C++11 enabled by default - set(US_USE_C++11 1) -else() - us_cache_var(US_USE_C++11 OFF BOOL "Enable the use of C++11 features" ADVANCED) -endif() - -us_cache_var(US_NAMESPACE "us" STRING "The namespace for the C++ micro services entities") -us_cache_var(US_HEADER_PREFIX "" STRING "The file name prefix for the public C++ micro services header files") -us_cache_var(US_BASECLASS_NAME "" STRING "The fully-qualified name of the base class") - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - us_cache_var(US_BASECLASS_PACKAGE "" STRING "The name of the package providing the base class definition" ADVANCED) - - set(bc_inc_d_doc "A list of include directories containing the header files for the base class") - us_cache_var(US_BASECLASS_INCLUDE_DIRS "" STRING "${bc_inc_d_doc}" ADVANCED) - - set(bc_lib_d_doc "A list of library directories for the base class") - us_cache_var(US_BASECLASS_LIBRARY_DIRS "" STRING "${bc_lib_d_doc}" ADVANCED) - - set(bc_lib_doc "A list of libraries needed for the base class") - us_cache_var(US_BASECLASS_LIBRARIES "" STRING "${bc_lib_doc}" ADVANCED) - - us_cache_var(US_BASECLASS_HEADER "" STRING "The name of the header file containing the base class declaration" ADVANCED) -endif() - -set(BUILD_SHARED_LIBS ${US_BUILD_SHARED_LIBS}) - -# Sanity checks - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT OR US_BUILD_TESTING) - if(US_BASECLASS_PACKAGE) - find_package(${US_BASECLASS_PACKAGE} REQUIRED) - - # Try to get the include dirs - foreach(_suffix DIRECTORIES DIRS DIRECTORY DIR) - if(${US_BASECLASS_PACKAGE}_INCLUDE_${_suffix} AND NOT US_BASECLASS_INCLUDE_DIRS) - us_cache_var(US_BASECLASS_INCLUDE_DIRS "${${US_BASECLASS_PACKAGE}_INCLUDE_${_suffix}}" STRING "${bc_inc_d_doc}" FORCE) - break() - endif() - endforeach() - - # Try to get the library dirs - foreach(_suffix DIRECTORIES DIRS DIRECTORY DIR) - if(${US_BASECLASS_PACKAGE}_LIBRARY_${_suffix} AND NOT US_BASECLASS_LIBRARY_DIRS) - us_cache_var(US_BASECLASS_LIBRARY_DIRS "${${US_BASECLASS_PACKAGE}_LIBRARY_${_suffix}}" STRING "${bc_lib_d_doc}" FORCE) - break() - endif() - endforeach() - - # Try to get the libraries - foreach(_suffix LIBRARIES LIBS LIBRARY LIB) - if(${US_BASECLASS_PACKAGE}_${_suffix} AND NOT US_BASECLASS_LIBRARIES) - us_cache_var(US_BASECLASS_LIBRARIES "${${US_BASECLASS_PACKAGE}_${_suffix}}" STRING "${bc_lib_doc}" FORCE) - break() - endif() - endforeach() - - if(NOT US_BASECLASS_NAME) - message(FATAL_ERROR "US_BASECLASS_NAME not set") - elseif(NOT US_BASECLASS_HEADER) - message(FATAL_ERROR "US_BASECLASS_HEADER not set") - endif() - endif() - - if(US_ENABLE_SERVICE_FACTORY_SUPPORT AND US_BASECLASS_NAME AND NOT US_BASECLASS_HEADER) - message(FATAL_ERROR "US_ENABLE_SERVICE_FACTORY_SUPPORT requires a US_BASECLASS_HEADER value") - endif() -endif() - -set(_us_baseclass_default 0) -if(NOT US_BASECLASS_NAME) - message(WARNING "Using build in base class \"::${US_NAMESPACE}::Base\"") - set(_us_baseclass_default 1) - set(US_BASECLASS_NAME "${US_NAMESPACE}::Base") - set(US_BASECLASS_HEADER "usBase.h") -endif() - -if(US_BUILD_TESTING AND US_BASECLASS_NAME AND NOT US_BASECLASS_HEADER) - message(FATAL_ERROR "US_BUILD_TESTING requires a US_BASECLASS_HEADER value") -endif() - -set(US_BASECLASS_INCLUDE "#include <${US_BASECLASS_HEADER}>") - -string(REPLACE "::" ";" _bc_token "${US_BASECLASS_NAME}") -list(GET _bc_token -1 _bc_name) -list(REMOVE_AT _bc_token -1) - -set(US_BASECLASS_FORWARD_DECLARATION "") -foreach(_namespace_tok ${_bc_token}) - if(_namespace_tok) - set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}namespace ${_namespace_tok} { ") - endif() -endforeach() -set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}class ${_bc_name}; ") -foreach(_namespace_tok ${_bc_token}) - if(_namespace_tok) - set(US_BASECLASS_FORWARD_DECLARATION "${US_BASECLASS_FORWARD_DECLARATION}}") - endif() -endforeach() - -#----------------------------------------------------------------------------- -# US C/CXX Flags -#----------------------------------------------------------------------------- - -set(US_C_FLAGS "${COVERAGE_C_FLAGS} ${ADDITIONAL_C_FLAGS}") -set(US_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${ADDITIONAL_CXX_FLAGS}") - -# This is used as a preprocessor define -set(US_USE_CXX11 ${US_USE_C++11}) - -# Set C++ compiler flags -if(NOT MSVC) - foreach(_cxxflag -Werror -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align - -Wwrite-strings -Woverloaded-virtual -Wnon-virtual-dtor -Wold-style-cast - -Wstrict-null-sentinel -Wsign-promo -fdiagnostics-show-option -D_FORTIFY_SOURCE=2) - usFunctionCheckCompilerFlags(${_cxxflag} US_CXX_FLAGS) - endforeach() - - if(US_USE_C++11) - usFunctionCheckCompilerFlags("-std=c++0x" US_CXX_FLAGS) - endif() -endif() - -if(CMAKE_COMPILER_IS_GNUCXX) - - usFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) - - # With older versions of gcc the flag -fstack-protector-all requires an extra dependency to libssp.so. - # If the gcc version is lower than 4.4.0 and the build type is Release let's not include the flag. - if(${GCC_VERSION} VERSION_GREATER "4.4.0" OR (CMAKE_BUILD_TYPE STREQUAL "Debug" AND ${GCC_VERSION} VERSION_LESS "4.4.0")) - usFunctionCheckCompilerFlags("-fstack-protector-all" US_CXX_FLAGS) - endif() - - if(MINGW) - # suppress warnings about auto imported symbols - set(US_CXX_FLAGS "-Wl,--enable-auto-import ${US_CXX_FLAGS}") - # we need to define a Windows version - set(US_CXX_FLAGS "-D_WIN32_WINNT=0x0500 ${US_CXX_FLAGS}") - else() - # Enable visibility support - if(NOT ${GCC_VERSION} VERSION_LESS "4.5") - usFunctionCheckCompilerFlags("-fvisibility=hidden -fvisibility-inlines-hidden" US_CXX_FLAGS) - endif() - endif() - -elseif(MSVC) - set(US_CXX_FLAGS "/MP /wd4996 ${US_CXX_FLAGS}") -endif() - -if(NOT US_IS_EMBEDDED) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${US_CXX_FLAGS}") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${US_C_FLAGS}") -endif() - -#----------------------------------------------------------------------------- -# US Link Flags -#----------------------------------------------------------------------------- - -set(US_LINK_FLAGS ) -if(NOT MSVC) - foreach(_linkflag -Wl,--no-undefined) - set(_add_flag) - usFunctionCheckCompilerFlags("${_linkflag}" _add_flag) - if(_add_flag) - set(US_LINK_FLAGS "${US_LINK_FLAGS} ${_linkflag}") - endif() - endforeach() -endif() - -#----------------------------------------------------------------------------- -# US Header Checks -#----------------------------------------------------------------------------- - -include(CheckIncludeFile) - -CHECK_INCLUDE_FILE(stdint.h HAVE_STDINT) - -#----------------------------------------------------------------------------- -# US include dirs and libraries -#----------------------------------------------------------------------------- - -set(US_INCLUDE_DIRS - ${PROJECT_BINARY_DIR}/include -) - -set(US_INTERNAL_INCLUDE_DIRS - ${PROJECT_BINARY_DIR}/include - ${CMAKE_CURRENT_SOURCE_DIR}/src/util - ${CMAKE_CURRENT_SOURCE_DIR}/src/service - ${CMAKE_CURRENT_SOURCE_DIR}/src/module -) - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - list(APPEND US_INTERNAL_INCLUDE_DIRS ${US_BASECLASS_INCLUDE_DIRS}) -endif() - -# link libraries for third party libs -if(US_IS_EMBEDDED) - set(US_LINK_LIBRARIES ${US_EMBEDDING_LIBRARY}) -else() - set(US_LINK_LIBRARIES ${PROJECT_NAME}) -endif() - -# link libraries for the CppMicroServices lib -set(_link_libraries ) -if(UNIX) - list(APPEND _link_libraries dl) -endif() -list(APPEND US_LINK_LIBRARIES ${_link_libraries}) - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - list(APPEND US_LINK_LIBRARIES ${US_BASECLASS_LIBRARIES}) -endif() - -set(US_LINK_DIRS ) -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - list(APPEND US_LINK_DIRS ${US_BASECLASS_LIBRARY_DIRS}) -endif() - -#----------------------------------------------------------------------------- -# Source directory -#----------------------------------------------------------------------------- - -set(us_config_h_file "${PROJECT_BINARY_DIR}/include/usConfig.h") -configure_file(usConfig.h.in ${us_config_h_file}) - -set(US_RCC_EXECUTABLE_NAME usResourceCompiler) -set(CppMicroServices_RCC_EXECUTABLE_NAME ${US_RCC_EXECUTABLE_NAME}) - -add_subdirectory(tools) - -add_subdirectory(src) - - -#----------------------------------------------------------------------------- -# US testing -#----------------------------------------------------------------------------- - -if(US_BUILD_TESTING) - enable_testing() - add_subdirectory(test) -endif() - -#----------------------------------------------------------------------------- -# Documentation -#----------------------------------------------------------------------------- - -add_subdirectory(documentation) - -#----------------------------------------------------------------------------- -# Last configuration steps -#----------------------------------------------------------------------------- - -configure_file(${PROJECT_NAME}Config.cmake.in ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake @ONLY) - diff --git a/Core/Code/CppMicroServices/CTestConfig.cmake b/Core/Code/CppMicroServices/CTestConfig.cmake deleted file mode 100644 index 65ff58f092..0000000000 --- a/Core/Code/CppMicroServices/CTestConfig.cmake +++ /dev/null @@ -1,7 +0,0 @@ -set(CTEST_PROJECT_NAME "CppMicroServices") -#set(CTEST_NIGHTLY_START_TIME "23:00:00 EDT") - -#set(CTEST_DROP_METHOD "http") -#set(CTEST_DROP_SITE "my.cdash.org") -#set(CTEST_DROP_LOCATION "/submit.php?project=${CTEST_PROJECT_NAME}") -#set(CTEST_DROP_SITE_CDASH TRUE) diff --git a/Core/Code/CppMicroServices/CppMicroServicesConfig.cmake.in b/Core/Code/CppMicroServices/CppMicroServicesConfig.cmake.in deleted file mode 100644 index 293031cb43..0000000000 --- a/Core/Code/CppMicroServices/CppMicroServicesConfig.cmake.in +++ /dev/null @@ -1,19 +0,0 @@ -set(@PROJECT_NAME@_INCLUDE_DIRS @US_INCLUDE_DIRS@) -set(@PROJECT_NAME@_INTERNAL_INCLUDE_DIRS @US_INTERNAL_INCLUDE_DIRS@) -set(@PROJECT_NAME@_LIBRARIES @US_LINK_LIBRARIES@) -set(@PROJECT_NAME@_LIBRARY_DIRS @CMAKE_LIBRARY_OUTPUT_DIRECTORY@) - -set(@PROJECT_NAME@_SOURCES @US_SOURCES@) -set(@PROJECT_NAME@_PUBLIC_HEADERS @US_PUBLIC_HEADERS@) -set(@PROJECT_NAME@_PRIVATE_HEADERS @US_PRIVATE_HEADERS@) - -set(@PROJECT_NAME@_SOURCE_DIR @CMAKE_CURRENT_SOURCE_DIR@) - -set(CppMicroServices_RCC_EXECUTABLE_NAME @CppMicroServices_RCC_EXECUTABLE_NAME@) - -find_program(CppMicroServices_RCC_EXECUTABLE ${CppMicroServices_RCC_EXECUTABLE_NAME} - PATHS "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@" - PATH_SUFFIXES Release Debug RelWithDebInfo MinSizeRel) - -include(@CMAKE_CURRENT_SOURCE_DIR@/CMake/usFunctionGenerateModuleInit.cmake) -include(@CMAKE_CURRENT_SOURCE_DIR@/CMake/usFunctionEmbedResources.cmake) diff --git a/Core/Code/CppMicroServices/LICENSE b/Core/Code/CppMicroServices/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/Core/Code/CppMicroServices/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/Core/Code/CppMicroServices/README.md b/Core/Code/CppMicroServices/README.md deleted file mode 100644 index 2470e5f9a3..0000000000 --- a/Core/Code/CppMicroServices/README.md +++ /dev/null @@ -1,89 +0,0 @@ -[![Build Status](https://secure.travis-ci.org/saschazelzer/CppMicroServices.png)](http://travis-ci.org/saschazelzer/CppMicroServices) - -C++ Micro Services -================== - -Introduction ------------- - -The C++ Micro Services library provides a dynamic service registry based on the -service layer as specified in the OSGi R4.2 specifications. It enables users to -realize a service oriented approach within their software stack. - -The advantages include higher reuse of components, looser coupling, better organization of -responsibilities, cleaner API contracts, etc. - -Requirements ------------- - -This is a pure C++ implementation of the OSGi service model and does not have any third-party -library dependencies. - -Supported Platforms -------------------- - -The library should compile on many different platforms. Below is a list of tested compiler/OS combinations: - - - GCC 4.5 (Ubuntu 11.04 and MacOS X 10.6) - - Visual Studio 2008 and 2010 - - Clang 3.0 (Ubuntu 11.04 and MacOS X 10.6) - -Legal ------ - -Copyright (c) German Cancer Research Center. Licensed under the [Apache License v2.0][apache_license]. - -Quick Start ------------ - -Essentially, the C++ Micro Services library provides you with a powerful dynamic service registry. -Each shared or static library has an associated `ModuleContext` object, through which the service -registry is accessed. - -To query the registry for a service object implementing one or more specific interfaces, the code -would look like this: - -```cpp -#include -#include - -using namespace us; - -void UseService(ModuleContext* context) -{ - ServiceReference serviceRef = context->GetServiceReference(); - if (serviceRef) - { - SomeInterface* service = context->GetService(serviceRef); - if (service) { /* do something */ } - } -} -``` - -Registering a service object against a certain interface looks like this: - -```cpp -#include -#include - -using namespace us; - -void RegisterSomeService(ModuleContext* context, SomeInterface* service) -{ - context->RegisterService(service); -} -``` - -The OSGi service model additionally allows to annotate services with properties and using these -properties during service look-ups. It also allows to track the life-cycle of service objects. -Please see the [Documentation](http://cppmicroservices.org/doc_latest/index.html) for more -examples and tutorials and the API reference. There is also a blog post about -[OSGi Lite for C++](http://blog.cppmicroservices.org/2012/04/15/osgi-lite-for-c++). - -Build Instructions ------------------- - -Please visit the [Build Instructions][bi_master] page online. - -[bi_master]: http://cppmicroservices.org/doc_latest/BuildInstructions.html -[apache_license]: http://www.apache.org/licenses/LICENSE-2.0 diff --git a/Core/Code/CppMicroServices/documentation/CMakeLists.txt b/Core/Code/CppMicroServices/documentation/CMakeLists.txt deleted file mode 100644 index 8ce17b7663..0000000000 --- a/Core/Code/CppMicroServices/documentation/CMakeLists.txt +++ /dev/null @@ -1,65 +0,0 @@ - -if(US_BUILD_TESTING) - include(usFunctionCompileSnippets) - # Compile source code snippets - add_subdirectory(snippets) -endif() - -if(NOT US_IS_EMBEDDED) - find_package(Doxygen) - - if(DOXYGEN_FOUND) - - option(US_DOCUMENTATION_FOR_WEBPAGE "Build Doxygen documentation for the webpage" OFF) - set(US_DOXYGEN_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE PATH "Doxygen output directory") - mark_as_advanced(US_DOCUMENTATION_FOR_WEBPAGE US_DOXYGEN_OUTPUT_DIR) - - set(US_HAVE_DOT "NO") - if(DOXYGEN_DOT_EXECUTABLE) - set(US_HAVE_DOT "YES") - endif() - - if(NOT DEFINED US_DOXYGEN_DOT_NUM_THREADS) - set(US_DOXYGEN_DOT_NUM_THREADS 4) - endif() - - # We are in standalone mode, so we generate a "mainpage" - set(US_DOXYGEN_MAIN_PAGE_CMD "\\mainpage") - set(US_DOXYGEN_ENABLED_SECTIONS "us_standalone") - - if(US_DOCUMENTATION_FOR_WEBPAGE) - configure_file(doxygen/header.html - ${CMAKE_CURRENT_BINARY_DIR}/header.html COPY_ONLY) - set(US_DOXYGEN_HEADER header.html) - - configure_file(doxygen/footer.html - ${CMAKE_CURRENT_BINARY_DIR}/footer.html COPY_ONLY) - set(US_DOXYGEN_FOOTER footer.html) - - configure_file(doxygen/doxygen.css - ${CMAKE_CURRENT_BINARY_DIR}/doxygen.css COPY_ONLY) - set(US_DOXYGEN_CSS doxygen.css) - - set(US_DOXYGEN_OUTPUT_DIR ${PROJECT_SOURCE_DIR}/gh-pages) - if(${PROJECT_NAME}_MINOR_VERSION EQUAL 99) - set(US_DOXYGEN_HTML_OUTPUT "doc_latest") - else() - set(US_DOXYGEN_HTML_OUTPUT "doc_${${PROJECT_NAME}_MAJOR_VERSION}_${${PROJECT_NAME}_MINOR_VERSION}") - endif() - else() - set(US_DOXYGEN_HEADER ) - set(US_DOXYGEN_FOOTER ) - set(US_DOXYGEN_CSS ) - set(US_DOXYGEN_HTML_OUTPUT "html") - endif() - - configure_file(doxygen.conf.in - ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf) - - add_custom_target(doc - ${DOXYGEN} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} - ) - endif() -endif() - diff --git a/Core/Code/CppMicroServices/documentation/doxygen.conf.in b/Core/Code/CppMicroServices/documentation/doxygen.conf.in deleted file mode 100644 index b3f88c4728..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen.conf.in +++ /dev/null @@ -1,1808 +0,0 @@ -# Doxyfile 1.8.1 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (" "). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all -# text before the first occurrence of this tag. Doxygen uses libiconv (or the -# iconv built into libc) for the transcoding. See -# http://www.gnu.org/software/libiconv for the list of possible encodings. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or sequence of words) that should -# identify the project. Note that if you do not use Doxywizard you need -# to put quotes around the project name if it contains spaces. - -PROJECT_NAME = "C++ Micro Services" - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. -# This could be handy for archiving the generated documentation or -# if some version control system is used. - -PROJECT_NUMBER = @CppMicroServices_VERSION@ - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer -# a quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = "A dynamic OSGi-like C++ service registry" - -# With the PROJECT_LOGO tag one can specify an logo or icon that is -# included in the documentation. The maximum height of the logo should not -# exceed 55 pixels and the maximum width should not exceed 200 pixels. -# Doxygen will copy the logo to the output directory. - -PROJECT_LOGO = - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) -# base path where the generated documentation will be put. -# If a relative path is entered, it will be relative to the location -# where doxygen was started. If left blank the current directory will be used. - -OUTPUT_DIRECTORY = @US_DOXYGEN_OUTPUT_DIR@ - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create -# 4096 sub-directories (in 2 levels) under the output directory of each output -# format and will distribute the generated files over these directories. -# Enabling this option can be useful when feeding doxygen a huge amount of -# source files, where putting all generated files in the same directory would -# otherwise cause performance problems for the file system. - -CREATE_SUBDIRS = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# The default language is English, other supported languages are: -# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, -# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, -# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English -# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, -# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, -# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will -# include brief member descriptions after the members that are listed in -# the file and class documentation (similar to JavaDoc). -# Set to NO to disable this. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend -# the brief description of a member or function before the detailed description. -# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator -# that is used to form the text in various listings. Each string -# in this list, if found as the leading text of the brief description, will be -# stripped from the text and the result after processing the whole list, is -# used as the annotated text. Otherwise, the brief description is used as-is. -# If left blank, the following values are used ("$name" is automatically -# replaced with the name of the entity): "The $name class" "The $name widget" -# "The $name file" "is" "provides" "specifies" "contains" -# "represents" "a" "an" "the" - -ABBREVIATE_BRIEF = - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# Doxygen will generate a detailed section even if there is only a brief -# description. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full -# path before files name in the file list and in the header files. If set -# to NO the shortest path that makes the file name unique will be used. - -FULL_PATH_NAMES = NO - -# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag -# can be used to strip a user-defined part of the path. Stripping is -# only done if one of the specified strings matches the left-hand part of -# the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the -# path to strip. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of -# the path mentioned in the documentation of a class, which tells -# the reader which header file to include in order to use a class. -# If left blank only the name of the header file containing the class -# definition is used. Otherwise one should specify the include paths that -# are normally passed to the compiler using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter -# (but less readable) file names. This can be useful if your file system -# doesn't support long names like on DOS, Mac, or CD-ROM. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen -# will interpret the first line (until the first dot) of a JavaDoc-style -# comment as the brief description. If set to NO, the JavaDoc -# comments will behave just like regular Qt-style comments -# (thus requiring an explicit @brief command for a brief description.) - -JAVADOC_AUTOBRIEF = NO - -# If the QT_AUTOBRIEF tag is set to YES then Doxygen will -# interpret the first line (until the first dot) of a Qt-style -# comment as the brief description. If set to NO, the comments -# will behave just like regular Qt-style comments (thus requiring -# an explicit \brief command for a brief description.) - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen -# treat a multi-line C++ special comment block (i.e. a block of //! or /// -# comments) as a brief description. This used to be the default behaviour. -# The new default is to treat a multi-line C++ comment block as a detailed -# description. Set this tag to YES if you prefer the old behaviour instead. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented -# member inherits the documentation from any documented member that it -# re-implements. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce -# a new page for each member. If set to NO, the documentation of a member will -# be part of the file/class/namespace that contains it. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. -# Doxygen uses this value to replace tabs by spaces in code fragments. - -TAB_SIZE = 2 - -# This tag can be used to specify a number of aliases that acts -# as commands in the documentation. An alias has the form "name=value". -# For example adding "sideeffect=\par Side Effects:\n" will allow you to -# put the command \sideeffect (or @sideeffect) in the documentation, which -# will result in a user-defined paragraph with heading "Side Effects:". -# You can put \n's in the value part of an alias to insert newlines. - -ALIASES = "FIXME=\par Fix Me's:\n" \ - "embmainpage{1}=@US_DOXYGEN_MAIN_PAGE_CMD@" - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding -# "class=itcl::class" will allow you to use the command class in the -# itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C -# sources only. Doxygen will then generate output that is more tailored for C. -# For instance, some of the names that are used will be different. The list -# of all members will be omitted, etc. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java -# sources only. Doxygen will then generate output that is more tailored for -# Java. For instance, namespaces will be presented as packages, qualified -# scopes will look different, etc. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources only. Doxygen will then generate output that is more tailored for -# Fortran. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for -# VHDL. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given extension. -# Doxygen has a built-in mapping, but you can override or extend it using this -# tag. The format is ext=language, where ext is a file extension, and language -# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, -# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make -# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C -# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions -# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all -# comments according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you -# can mix doxygen, HTML, and XML commands with Markdown formatting. -# Disable only in case of backward compatibilities issues. - -MARKDOWN_SUPPORT = YES - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should -# set this tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. -# func(std::string) {}). This also makes the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. - -BUILTIN_STL_SUPPORT = YES - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. -# Doxygen will parse them like normal C++ but will assume all classes use public -# instead of private inheritance when no explicit protection keyword is present. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate getter -# and setter methods for a property. Setting this option to YES (the default) -# will make doxygen replace the get and set methods by a property in the -# documentation. This will only work if the methods are indeed getting or -# setting a simple type. If this is not the case, or you want to show the -# methods anyway, you should set this option to NO. - -IDL_PROPERTY_SUPPORT = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES (the default) to allow class member groups of -# the same type (for instance a group of public functions) to be put as a -# subgroup of that type (e.g. under the Public Functions section). Set it to -# NO to prevent subgrouping. Alternatively, this can be done per class using -# the \nosubgrouping command. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and -# unions are shown inside the group in which they are included (e.g. using -# @ingroup) instead of on a separate page (for HTML and Man pages) or -# section (for LaTeX and RTF). - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and -# unions with only public data fields will be shown inline in the documentation -# of the scope in which they are defined (i.e. file, namespace, or group -# documentation), provided this scope is documented. If set to NO (the default), -# structs, classes, and unions are shown on a separate page (for HTML and Man -# pages) or section (for LaTeX and RTF). - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum -# is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically -# be useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. - -TYPEDEF_HIDES_STRUCT = NO - -# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to -# determine which symbols to keep in memory and which to flush to disk. -# When the cache is full, less often used symbols will be written to disk. -# For small to medium size projects (<1000 input files) the default value is -# probably good enough. For larger projects a too small cache size can cause -# doxygen to be busy swapping symbols to and from disk most of the time -# causing a significant performance penalty. -# If the system has enough physical memory increasing the cache will improve the -# performance by keeping more symbols in memory. Note that the value works on -# a logarithmic scale so increasing the size by one will roughly double the -# memory usage. The cache size is given by this formula: -# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, -# corresponding to a cache size of 2^16 = 65536 symbols. - -SYMBOL_CACHE_SIZE = 0 - -# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be -# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given -# their name and scope. Since this can be an expensive process and often the -# same symbol appear multiple times in the code, doxygen keeps a cache of -# pre-resolved symbols. If the cache is too small doxygen will become slower. -# If the cache is too large, memory is wasted. The cache size is given by this -# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, -# corresponding to a cache size of 2^16 = 65536 symbols. - -LOOKUP_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal scope will be included in the documentation. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = NO - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespaces are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = YES - -# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any -# documentation blocks found inside the body of a function. -# If set to NO (the default) these blocks will be appended to the -# function's detailed documentation block. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation -# that is typed after a \internal command is included. If the tag is set -# to NO (the default) then the documentation will be excluded. -# Set it to YES to include the internal documentation. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate -# file names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. - -CASE_SENSE_NAMES = YES - -# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen -# will show members with their full class and namespace scopes in the -# documentation. If set to YES the scope will be hidden. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen -# will put a list of the files that are included by a file in the documentation -# of that file. - -SHOW_INCLUDE_FILES = NO - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen -# will list include files with double quotes in the documentation -# rather than with sharp brackets. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] -# is inserted in the documentation for inline members. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen -# will sort the (detailed) documentation of file and class members -# alphabetically by member name. If set to NO the members will appear in -# declaration order. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the -# brief documentation of file, namespace and class members alphabetically -# by member name. If set to NO (the default) the members will appear in -# declaration order. - -SORT_BRIEF_DOCS = NO - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen -# will sort the (brief and detailed) documentation of class members so that -# constructors and destructors are listed first. If set to NO (the default) -# the constructors will appear in the respective orders defined by -# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. -# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO -# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the -# hierarchy of group names into alphabetical order. If set to NO (the default) -# the group names will appear in their defined order. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be -# sorted by fully-qualified names, including namespaces. If set to -# NO (the default), the class list will be sorted only by class name, -# not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the -# alphabetical list. - -SORT_BY_SCOPE_NAME = YES - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to -# do proper type resolution of all parameters of a function it will reject a -# match between the prototype and the implementation of a member function even -# if there is only one candidate or it is obvious which candidate to choose -# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen -# will still accept a match between prototype and implementation in such cases. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable (YES) or -# disable (NO) the todo list. This list is created by putting \todo -# commands in the documentation. - -GENERATE_TODOLIST = YES - -# The GENERATE_TESTLIST tag can be used to enable (YES) or -# disable (NO) the test list. This list is created by putting \test -# commands in the documentation. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable (YES) or -# disable (NO) the bug list. This list is created by putting \bug -# commands in the documentation. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or -# disable (NO) the deprecated list. This list is created by putting -# \deprecated commands in the documentation. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional -# documentation sections, marked by \if sectionname ... \endif. - -ENABLED_SECTIONS = @US_DOXYGEN_ENABLED_SECTIONS@ - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines -# the initial value of a variable or macro consists of for it to appear in -# the documentation. If the initializer consists of more lines than specified -# here it will be hidden. Use a value of 0 to hide initializers completely. -# The appearance of the initializer of individual variables and macros in the -# documentation can be controlled using \showinitializer or \hideinitializer -# command in the documentation regardless of this setting. - -MAX_INITIALIZER_LINES = 0 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated -# at the bottom of the documentation of classes and structs. If set to YES the -# list will mention the files that were used to generate the documentation. - -SHOW_USED_FILES = NO - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. -# This will remove the Files entry from the Quick Index and from the -# Folder Tree View (if specified). The default is YES. - -SHOW_FILES = NO - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the -# Namespaces page. -# This will remove the Namespaces entry from the Quick Index -# and from the Folder Tree View (if specified). The default is YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command , where is the value of -# the FILE_VERSION_FILTER tag, and is the name of an input file -# provided by doxygen. Whatever the program writes to standard output -# is used as the file version. See the manual for examples. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. The create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. -# You can optionally specify a file name after the option, if omitted -# DoxygenLayout.xml will be used as the name of the layout file. - -LAYOUT_FILE = - -# The CITE_BIB_FILES tag can be used to specify one or more bib files -# containing the references data. This must be a list of .bib files. The -# .bib extension is automatically appended if omitted. Using this command -# requires the bibtex tool to be installed. See also -# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style -# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this -# feature you need bibtex and perl available in the search path. - -CITE_BIB_FILES = - -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated -# by doxygen. Possible values are YES and NO. If left blank NO is used. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated by doxygen. Possible values are YES and NO. If left blank -# NO is used. - -WARNINGS = YES - -# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings -# for undocumented members. If EXTRACT_ALL is set to YES then this flag will -# automatically be disabled. - -WARN_IF_UNDOCUMENTED = YES - -# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some -# parameters in a documented function, or documenting parameters that -# don't exist or using markup commands wrongly. - -WARN_IF_DOC_ERROR = YES - -# The WARN_NO_PARAMDOC option can be enabled to get warnings for -# functions that are documented, but have no documentation for their parameters -# or return value. If set to NO (the default) doxygen will only warn about -# wrong or incomplete parameter documentation, but not about the absence of -# documentation. - -WARN_NO_PARAMDOC = YES - -# The WARN_FORMAT tag determines the format of the warning messages that -# doxygen can produce. The string should contain the $file, $line, and $text -# tags, which will be replaced by the file and line number from which the -# warning originated and the warning text. Optionally the format may contain -# $version, which will be replaced by the version of the file (if it could -# be obtained via FILE_VERSION_FILTER) - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning -# and error messages should be written. If left blank the output is written -# to stderr. - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag can be used to specify the files and/or directories that contain -# documented source files. You may enter file names like "myfile.cpp" or -# directories like "/usr/src/myproject". Separate the files or directories -# with spaces. - -INPUT = @PROJECT_SOURCE_DIR@ \ - @PROJECT_BINARY_DIR@/include/usConfig.h - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is -# also the default input encoding. Doxygen uses libiconv (or the iconv built -# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for -# the list of possible encodings. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank the following patterns are tested: -# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh -# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py -# *.f90 *.f *.for *.vhd *.vhdl - -FILE_PATTERNS = *.h \ - *.dox \ - *.md - -# The RECURSIVE tag can be used to turn specify whether or not subdirectories -# should be searched for input files as well. Possible values are YES and NO. -# If left blank NO is used. - -RECURSIVE = YES - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = @PROJECT_SOURCE_DIR@/README.md \ - @PROJECT_SOURCE_DIR@/documentation/snippets/ \ - @PROJECT_SOURCE_DIR@/test/ \ - @PROJECT_SOURCE_DIR@/gh-pages \ - @PROJECT_SOURCE_DIR@/.git/ - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. Note that the wildcards are matched -# against the file with absolute path, so to exclude all test directories -# for example use the pattern */test/* - -EXCLUDE_PATTERNS = */.git/* \ - *_p.h \ - *Private.* - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test - -EXCLUDE_SYMBOLS = us US_NAMESPACE - -# The EXAMPLE_PATH tag can be used to specify one or more files or -# directories that contain example code fragments that are included (see -# the \include command). - -EXAMPLE_PATH = @PROJECT_SOURCE_DIR@/documentation/snippets/ - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank all files are included. - -EXAMPLE_PATTERNS = - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude -# commands irrespective of the value of the RECURSIVE tag. -# Possible values are YES and NO. If left blank NO is used. - -EXAMPLE_RECURSIVE = YES - -# The IMAGE_PATH tag can be used to specify one or more files or -# directories that contain image that are included in the documentation (see -# the \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command , where -# is the value of the INPUT_FILTER tag, and is the name of an -# input file. Doxygen will then use the output that the filter program writes -# to standard output. -# If FILTER_PATTERNS is specified, this tag will be -# ignored. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. -# Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. -# The filters are a list of the form: -# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further -# info on how filters are used. If FILTER_PATTERNS is empty or if -# non of the patterns match the file name, INPUT_FILTER is applied. - -FILTER_PATTERNS = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will be used to filter the input files when producing source -# files to browse (i.e. when SOURCE_BROWSER is set to YES). - -FILTER_SOURCE_FILES = NO - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) -# and it is also possible to disable source filtering for a specific pattern -# using *.ext= (so without naming a filter). This option only has effect when -# FILTER_SOURCE_FILES is enabled. - -FILTER_SOURCE_PATTERNS = - -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will -# be generated. Documented entities will be cross-referenced with these sources. -# Note: To get rid of all source code in the generated output, make sure also -# VERBATIM_HEADERS is set to NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body -# of functions and classes directly in the documentation. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct -# doxygen to hide any special comment blocks from generated source code -# fragments. Normal C and C++ comments will always remain visible. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES -# then for each documented function all documented -# functions referencing it will be listed. - -REFERENCED_BY_RELATION = YES - -# If the REFERENCES_RELATION tag is set to YES -# then for each documented function all documented entities -# called/used by that function will be listed. - -REFERENCES_RELATION = YES - -# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) -# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from -# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will -# link to the source code. -# Otherwise they will link to the documentation. - -REFERENCES_LINK_SOURCE = YES - -# If the USE_HTAGS tag is set to YES then the references to source code -# will point to the HTML generated by the htags(1) tool instead of doxygen -# built-in source browser. The htags tool is part of GNU's global source -# tagging system (see http://www.gnu.org/software/global/global.html). You -# will need version 4.8.6 or higher. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen -# will generate a verbatim copy of the header file for each class for -# which an include is specified. Set to NO to disable this. - -VERBATIM_HEADERS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index -# of all compounds will be generated. Enable this if the project -# contains a lot of classes, structs, unions or interfaces. - -ALPHABETICAL_INDEX = YES - -# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then -# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns -# in which this list will be split (can be a number in the range [1..20]) - -COLS_IN_ALPHA_INDEX = 3 - -# In case all classes in a project start with a common prefix, all -# classes will be put under the same header in the alphabetical index. -# The IGNORE_PREFIX tag can be used to specify one or more prefixes that -# should be ignored while generating the index headers. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES (the default) Doxygen will -# generate HTML output. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `html' will be used as the default path. - -HTML_OUTPUT = @US_DOXYGEN_HTML_OUTPUT@ - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for -# each generated HTML page (for example: .htm,.php,.asp). If it is left blank -# doxygen will generate files with .html extension. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a personal HTML header for -# each generated HTML page. If it is left blank doxygen will generate a -# standard header. Note that when using a custom header you are responsible -# for the proper inclusion of any scripts and style sheets that doxygen -# needs, which is dependent on the configuration options used. -# It is advised to generate a default header using "doxygen -w html -# header.html footer.html stylesheet.css YourConfigFile" and then modify -# that header. Note that the header is subject to change so you typically -# have to redo this when upgrading to a newer version of doxygen or when -# changing the value of configuration settings such as GENERATE_TREEVIEW! - -HTML_HEADER = @US_DOXYGEN_HEADER@ - -# The HTML_FOOTER tag can be used to specify a personal HTML footer for -# each generated HTML page. If it is left blank doxygen will generate a -# standard footer. - -HTML_FOOTER = @US_DOXYGEN_FOOTER@ - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading -# style sheet that is used by each HTML page. It can be used to -# fine-tune the look of the HTML output. If the tag is left blank doxygen -# will generate a default style sheet. Note that doxygen will try to copy -# the style sheet file to the HTML output directory, so don't put your own -# style sheet in the HTML output directory as well, or it will be erased! - -HTML_STYLESHEET = @US_DOXYGEN_CSS@ - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that -# the files will be copied as-is; there are no commands or markers available. - -HTML_EXTRA_FILES = - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. -# Doxygen will adjust the colors in the style sheet and background images -# according to this color. Hue is specified as an angle on a colorwheel, -# see http://en.wikipedia.org/wiki/Hue for more information. -# For instance the value 0 represents red, 60 is yellow, 120 is green, -# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. -# The allowed range is 0 to 359. - -HTML_COLORSTYLE_HUE = 220 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of -# the colors in the HTML output. For a value of 0 the output will use -# grayscales only. A value of 255 will produce the most vivid colors. - -HTML_COLORSTYLE_SAT = 100 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to -# the luminance component of the colors in the HTML output. Values below -# 100 gradually make the output lighter, whereas values above 100 make -# the output darker. The value divided by 100 is the actual gamma applied, -# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, -# and 100 does not change the gamma. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting -# this to NO can help when comparing the output of multiple runs. - -HTML_TIMESTAMP = YES - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. - -HTML_DYNAMIC_SECTIONS = NO - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of -# entries shown in the various tree structured indices initially; the user -# can expand and collapse entries dynamically later on. Doxygen will expand -# the tree to such a level that at most the specified number of entries are -# visible (unless a fully collapsed tree already exceeds this amount). -# So setting the number of entries 1 will produce a full collapsed tree by -# default. 0 is a special value representing an infinite number of entries -# and will result in a full expanded tree by default. - -HTML_INDEX_NUM_ENTRIES = 100 - -# If the GENERATE_DOCSET tag is set to YES, additional index files -# will be generated that can be used as input for Apple's Xcode 3 -# integrated development environment, introduced with OSX 10.5 (Leopard). -# To create a documentation set, doxygen will generate a Makefile in the -# HTML output directory. Running make will produce the docset in that -# directory and running "make install" will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find -# it at startup. -# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. - -GENERATE_DOCSET = NO - -# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the -# feed. A documentation feed provides an umbrella under which multiple -# documentation sets from a single provider (such as a company or product suite) -# can be grouped. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that -# should uniquely identify the documentation set bundle. This should be a -# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen -# will append .docset to the name. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify -# the documentation publisher. This should be a reverse domain-name style -# string, e.g. com.mycompany.MyDocSet.documentation. - -DOCSET_PUBLISHER_ID = org.doxygen.Publisher - -# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. - -DOCSET_PUBLISHER_NAME = Publisher - -# If the GENERATE_HTMLHELP tag is set to YES, additional index files -# will be generated that can be used as input for tools like the -# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) -# of the generated HTML documentation. - -GENERATE_HTMLHELP = NO - -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can -# be used to specify the file name of the resulting .chm file. You -# can add a path in front of the file if the result should not be -# written to the html output directory. - -CHM_FILE = - -# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can -# be used to specify the location (absolute path including file name) of -# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run -# the HTML help compiler on the generated index.hhp. - -HHC_LOCATION = - -# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag -# controls if a separate .chi index file is generated (YES) or that -# it should be included in the master .chm file (NO). - -GENERATE_CHI = NO - -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING -# is used to encode HtmlHelp index (hhk), content (hhc) and project file -# content. - -CHM_INDEX_ENCODING = - -# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag -# controls whether a binary table of contents is generated (YES) or a -# normal table of contents (NO) in the .chm file. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members -# to the contents of the HTML help documentation and to the tree view. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and -# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated -# that can be used as input for Qt's qhelpgenerator to generate a -# Qt Compressed Help (.qch) of the generated HTML documentation. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can -# be used to specify the file name of the resulting .qch file. -# The path specified is relative to the HTML output folder. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating -# Qt Help Project output. For more information please see -# http://doc.trolltech.com/qthelpproject.html#namespace - -QHP_NAMESPACE = - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating -# Qt Help Project output. For more information please see -# http://doc.trolltech.com/qthelpproject.html#virtual-folders - -QHP_VIRTUAL_FOLDER = - -# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to -# add. For more information please see -# http://doc.trolltech.com/qthelpproject.html#custom-filters - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the -# custom filter to add. For more information please see -# -# Qt Help Project / Custom Filters. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this -# project's -# filter section matches. -# -# Qt Help Project / Filter Attributes. - -QHP_SECT_FILTER_ATTRS = - -# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can -# be used to specify the location of Qt's qhelpgenerator. -# If non-empty doxygen will try to run qhelpgenerator on the generated -# .qhp file. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files -# will be generated, which together with the HTML files, form an Eclipse help -# plugin. To install this plugin and make it available under the help contents -# menu in Eclipse, the contents of the directory containing the HTML and XML -# files needs to be copied into the plugins directory of eclipse. The name of -# the directory within the plugins directory should be the same as -# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before -# the help appears. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have -# this name. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) -# at top of each HTML page. The value NO (the default) enables the index and -# the value YES disables it. Since the tabs have the same information as the -# navigation tree you can set this option to NO if you already set -# GENERATE_TREEVIEW to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. -# If the tag value is set to YES, a side panel will be generated -# containing a tree-like index structure (just like the one that -# is generated for HTML Help). For this to work a browser that supports -# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). -# Windows users are probably better off using the HTML help feature. -# Since the tree basically has the same information as the tab index you -# could consider to set DISABLE_INDEX to NO when enabling this option. - -GENERATE_TREEVIEW = NO - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values -# (range [0,1..20]) that doxygen will group on one line in the generated HTML -# documentation. Note that a value of 0 will completely suppress the enum -# values from appearing in the overview section. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be -# used to set the initial width (in pixels) of the frame in which the tree -# is shown. - -TREEVIEW_WIDTH = 300 - -# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open -# links to external symbols imported via tag files in a separate window. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of Latex formulas included -# as images in the HTML documentation. The default is 10. Note that -# when you change the font size after a successful doxygen run you need -# to manually remove any form_*.png images from the HTML output directory -# to force them to be regenerated. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are -# not supported properly for IE 6.0, but are supported on all modern browsers. -# Note that when changing this option you need to delete any form_*.png files -# in the HTML output before the changes have effect. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax -# (see http://www.mathjax.org) which uses client side Javascript for the -# rendering instead of using prerendered bitmaps. Use this if you do not -# have LaTeX installed or if you want to formulas look prettier in the HTML -# output. When enabled you may also need to install MathJax separately and -# configure the path to it using the MATHJAX_RELPATH option. - -USE_MATHJAX = NO - -# When MathJax is enabled you need to specify the location relative to the -# HTML output directory using the MATHJAX_RELPATH option. The destination -# directory should contain the MathJax.js script. For instance, if the mathjax -# directory is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to -# the MathJax Content Delivery Network so you can quickly see the result without -# installing MathJax. -# However, it is strongly recommended to install a local -# copy of MathJax from http://www.mathjax.org before deployment. - -MATHJAX_RELPATH = http://www.mathjax.org/mathjax - -# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension -# names that should be enabled during MathJax rendering. - -MATHJAX_EXTENSIONS = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box -# for the HTML output. The underlying search engine uses javascript -# and DHTML and should work on any modern browser. Note that when using -# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets -# (GENERATE_DOCSET) there is already a search function so this one should -# typically be disabled. For large projects the javascript based search engine -# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. - -SEARCHENGINE = YES - -# When the SERVER_BASED_SEARCH tag is enabled the search engine will be -# implemented using a PHP enabled web server instead of at the web client -# using Javascript. Doxygen will generate the search PHP script and index -# file to put on the web server. The advantage of the server -# based approach is that it scales better to large projects and allows -# full text search. The disadvantages are that it is more difficult to setup -# and does not have live searching capabilities. - -SERVER_BASED_SEARCH = NO - -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- - -# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will -# generate Latex output. - -GENERATE_LATEX = NO - -# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `latex' will be used as the default path. - -LATEX_OUTPUT = latex - -# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be -# invoked. If left blank `latex' will be used as the default command name. -# Note that when enabling USE_PDFLATEX this option is only used for -# generating bitmaps for formulas in the HTML output, but not in the -# Makefile that is written to the output directory. - -LATEX_CMD_NAME = latex - -# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to -# generate index for LaTeX. If left blank `makeindex' will be used as the -# default command name. - -MAKEINDEX_CMD_NAME = makeindex - -# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact -# LaTeX documents. This may be useful for small projects and may help to -# save some trees in general. - -COMPACT_LATEX = NO - -# The PAPER_TYPE tag can be used to set the paper type that is used -# by the printer. Possible values are: a4, letter, legal and -# executive. If left blank a4wide will be used. - -PAPER_TYPE = a4wide - -# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX -# packages that should be included in the LaTeX output. - -EXTRA_PACKAGES = amssymb - -# The LATEX_HEADER tag can be used to specify a personal LaTeX header for -# the generated latex document. The header should contain everything until -# the first chapter. If it is left blank doxygen will generate a -# standard header. Notice: only use this tag if you know what you are doing! - -LATEX_HEADER = - -# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for -# the generated latex document. The footer should contain everything after -# the last chapter. If it is left blank doxygen will generate a -# standard footer. Notice: only use this tag if you know what you are doing! - -LATEX_FOOTER = - -# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated -# is prepared for conversion to pdf (using ps2pdf). The pdf file will -# contain links (just like the HTML output) instead of page references -# This makes the output suitable for online browsing using a pdf viewer. - -PDF_HYPERLINKS = NO - -# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of -# plain latex in the generated Makefile. Set this option to YES to get a -# higher quality PDF documentation. - -USE_PDFLATEX = NO - -# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. -# command to the generated LaTeX files. This will instruct LaTeX to keep -# running if errors occur, instead of asking the user for help. -# This option is also used when generating formulas in HTML. - -LATEX_BATCHMODE = NO - -# If LATEX_HIDE_INDICES is set to YES then doxygen will not -# include the index chapters (such as File Index, Compound Index, etc.) -# in the output. - -LATEX_HIDE_INDICES = NO - -# If LATEX_SOURCE_CODE is set to YES then doxygen will include -# source code with syntax highlighting in the LaTeX output. -# Note that which sources are shown also depends on other settings -# such as SOURCE_BROWSER. - -LATEX_SOURCE_CODE = NO - -# The LATEX_BIB_STYLE tag can be used to specify the style to use for the -# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See -# http://en.wikipedia.org/wiki/BibTeX for more info. - -LATEX_BIB_STYLE = plain - -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- - -# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output -# The RTF output is optimized for Word 97 and may not look very pretty with -# other RTF readers or editors. - -GENERATE_RTF = NO - -# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `rtf' will be used as the default path. - -RTF_OUTPUT = rtf - -# If the COMPACT_RTF tag is set to YES Doxygen generates more compact -# RTF documents. This may be useful for small projects and may help to -# save some trees in general. - -COMPACT_RTF = NO - -# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated -# will contain hyperlink fields. The RTF file will -# contain links (just like the HTML output) instead of page references. -# This makes the output suitable for online browsing using WORD or other -# programs which support those fields. -# Note: wordpad (write) and others do not support links. - -RTF_HYPERLINKS = NO - -# Load style sheet definitions from file. Syntax is similar to doxygen's -# config file, i.e. a series of assignments. You only have to provide -# replacements, missing definitions are set to their default value. - -RTF_STYLESHEET_FILE = - -# Set optional variables used in the generation of an rtf document. -# Syntax is similar to doxygen's config file. - -RTF_EXTENSIONS_FILE = - -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- - -# If the GENERATE_MAN tag is set to YES (the default) Doxygen will -# generate man pages - -GENERATE_MAN = NO - -# The MAN_OUTPUT tag is used to specify where the man pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `man' will be used as the default path. - -MAN_OUTPUT = man - -# The MAN_EXTENSION tag determines the extension that is added to -# the generated man pages (default is the subroutine's section .3) - -MAN_EXTENSION = .3 - -# If the MAN_LINKS tag is set to YES and Doxygen generates man output, -# then it will generate one additional man file for each entity -# documented in the real man page(s). These additional files -# only source the real man page, but without them the man command -# would be unable to find the correct page. The default is NO. - -MAN_LINKS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- - -# If the GENERATE_XML tag is set to YES Doxygen will -# generate an XML file that captures the structure of -# the code including all documentation. - -GENERATE_XML = NO - -# The XML_OUTPUT tag is used to specify where the XML pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `xml' will be used as the default path. - -XML_OUTPUT = xml - -# The XML_SCHEMA tag can be used to specify an XML schema, -# which can be used by a validating XML parser to check the -# syntax of the XML files. - -XML_SCHEMA = - -# The XML_DTD tag can be used to specify an XML DTD, -# which can be used by a validating XML parser to check the -# syntax of the XML files. - -XML_DTD = - -# If the XML_PROGRAMLISTING tag is set to YES Doxygen will -# dump the program listings (including syntax highlighting -# and cross-referencing information) to the XML output. Note that -# enabling this will significantly increase the size of the XML output. - -XML_PROGRAMLISTING = YES - -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- - -# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will -# generate an AutoGen Definitions (see autogen.sf.net) file -# that captures the structure of the code including all -# documentation. Note that this feature is still experimental -# and incomplete at the moment. - -GENERATE_AUTOGEN_DEF = NO - -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- - -# If the GENERATE_PERLMOD tag is set to YES Doxygen will -# generate a Perl module file that captures the structure of -# the code including all documentation. Note that this -# feature is still experimental and incomplete at the -# moment. - -GENERATE_PERLMOD = NO - -# If the PERLMOD_LATEX tag is set to YES Doxygen will generate -# the necessary Makefile rules, Perl scripts and LaTeX code to be able -# to generate PDF and DVI output from the Perl module output. - -PERLMOD_LATEX = NO - -# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be -# nicely formatted so it can be parsed by a human reader. -# This is useful -# if you want to understand what is going on. -# On the other hand, if this -# tag is set to NO the size of the Perl module output will be much smaller -# and Perl will parse it just the same. - -PERLMOD_PRETTY = YES - -# The names of the make variables in the generated doxyrules.make file -# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. -# This is useful so different doxyrules.make files included by the same -# Makefile don't overwrite each other's variables. - -PERLMOD_MAKEVAR_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- - -# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will -# evaluate all C-preprocessor directives found in the sources and include -# files. - -ENABLE_PREPROCESSING = YES - -# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro -# names in the source code. If set to NO (the default) only conditional -# compilation will be performed. Macro expansion can be done in a controlled -# way by setting EXPAND_ONLY_PREDEF to YES. - -MACRO_EXPANSION = YES - -# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES -# then the macro expansion is limited to the macros specified with the -# PREDEFINED and EXPAND_AS_DEFINED tags. - -EXPAND_ONLY_PREDEF = YES - -# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files -# pointed to by INCLUDE_PATH will be searched when a #include is found. - -SEARCH_INCLUDES = YES - -# The INCLUDE_PATH tag can be used to specify one or more directories that -# contain include files that are not input files but should be processed by -# the preprocessor. - -INCLUDE_PATH = @PROJECT_BINARY_DIR@/include/ - -# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard -# patterns (like *.h and *.hpp) to filter out the header-files in the -# directories. If left blank, the patterns specified with FILE_PATTERNS will -# be used. - -INCLUDE_FILE_PATTERNS = *.h - -# The PREDEFINED tag can be used to specify one or more macro names that -# are defined before the preprocessor is started (similar to the -D option of -# gcc). The argument of the tag is a list of macros of the form: name -# or name=definition (no spaces). If the definition and the = are -# omitted =1 is assumed. To prevent a macro definition from being -# undefined via #undef or recursively expanded use the := operator -# instead of the = operator. - -PREDEFINED = US_PREPEND_NAMESPACE(x)=x \ - US_BEGIN_NAMESPACE= \ - US_END_NAMESPACE= \ - "US_BASECLASS_NAME=@US_BASECLASS_NAME@" \ - US_EXPORT= \ - US_ABI_LOCAL= \ - US_MSVC_POP_WARNING= - -# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then -# this tag can be used to specify a list of macro names that should be expanded. -# The macro definition that is found in the sources will be used. -# Use the PREDEFINED tag if you want to use a different macro definition that -# overrules the definition found in the source code. - -EXPAND_AS_DEFINED = - -# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then -# doxygen's preprocessor will remove all references to function-like macros -# that are alone on a line, have an all uppercase name, and do not end with a -# semicolon, because these will confuse the parser if not removed. - -SKIP_FUNCTION_MACROS = YES - -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- - -# The TAGFILES option can be used to specify one or more tagfiles. For each -# tag file the location of the external documentation should be added. The -# format of a tag file without this location is as follows: -# -# TAGFILES = file1 file2 ... -# Adding location for the tag files is done as follows: -# -# TAGFILES = file1=loc1 "file2 = loc2" ... -# where "loc1" and "loc2" can be relative or absolute paths -# or URLs. Note that each tag file must have a unique name (where the name does -# NOT include the path). If a tag file is not located in the directory in which -# doxygen is run, you must also specify the path to the tagfile here. - -TAGFILES = - -# When a file name is specified after GENERATE_TAGFILE, doxygen will create -# a tag file that is based on the input files it reads. - -GENERATE_TAGFILE = - -# If the ALLEXTERNALS tag is set to YES all external classes will be listed -# in the class index. If set to NO only the inherited external classes -# will be listed. - -ALLEXTERNALS = NO - -# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed -# in the modules index. If set to NO, only the current project's groups will -# be listed. - -EXTERNAL_GROUPS = NO - -# The PERL_PATH should be the absolute path and name of the perl script -# interpreter (i.e. the result of `which perl'). - -PERL_PATH = /usr/bin/perl - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- - -# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will -# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base -# or super classes. Setting the tag to NO turns the diagrams off. Note that -# this option also works with HAVE_DOT disabled, but it is recommended to -# install and use dot, since it yields more powerful graphs. - -CLASS_DIAGRAMS = YES - -# You can define message sequence charts within doxygen comments using the \msc -# command. Doxygen will then run the mscgen tool (see -# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the -# documentation. The MSCGEN_PATH tag allows you to specify the directory where -# the mscgen tool resides. If left empty the tool is assumed to be found in the -# default search path. - -MSCGEN_PATH = - -# If set to YES, the inheritance and collaboration graphs will hide -# inheritance and usage relations if the target is undocumented -# or is not a class. - -HIDE_UNDOC_RELATIONS = YES - -# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is -# available from the path. This tool is part of Graphviz, a graph visualization -# toolkit from AT&T and Lucent Bell Labs. The other options in this section -# have no effect if this option is set to NO (the default) - -HAVE_DOT = @US_HAVE_DOT@ - -# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is -# allowed to run in parallel. When set to 0 (the default) doxygen will -# base this on the number of processors available in the system. You can set it -# explicitly to a value larger than 0 to get control over the balance -# between CPU load and processing speed. - -DOT_NUM_THREADS = @US_DOXYGEN_DOT_NUM_THREADS@ - -# By default doxygen will use the Helvetica font for all dot files that -# doxygen generates. When you want a differently looking font you can specify -# the font name using DOT_FONTNAME. You need to make sure dot is able to find -# the font, which can be done by putting it in a standard location or by setting -# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the -# directory containing the font. - -DOT_FONTNAME = FreeSans.ttf - -# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. -# The default size is 10pt. - -DOT_FONTSIZE = 10 - -# By default doxygen will tell dot to use the Helvetica font. -# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to -# set the path where dot can find it. - -DOT_FONTPATH = - -# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect inheritance relations. Setting this tag to YES will force the -# CLASS_DIAGRAMS tag to NO. - -CLASS_GRAPH = YES - -# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect implementation dependencies (inheritance, containment, and -# class references variables) of the class with other documented classes. - -COLLABORATION_GRAPH = YES - -# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for groups, showing the direct groups dependencies - -GROUP_GRAPHS = YES - -# If the UML_LOOK tag is set to YES doxygen will generate inheritance and -# collaboration diagrams in a style similar to the OMG's Unified Modeling -# Language. - -UML_LOOK = NO - -# If the UML_LOOK tag is enabled, the fields and methods are shown inside -# the class node. If there are many fields or methods and many nodes the -# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS -# threshold limits the number of items for each type to make the size more -# managable. Set this to 0 for no limit. Note that the threshold may be -# exceeded by 50% before the limit is enforced. - -UML_LIMIT_NUM_FIELDS = 10 - -# If set to YES, the inheritance and collaboration graphs will show the -# relations between templates and their instances. - -TEMPLATE_RELATIONS = YES - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT -# tags are set to YES then doxygen will generate a graph for each documented -# file showing the direct and indirect include dependencies of the file with -# other documented files. - -INCLUDE_GRAPH = NO - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and -# HAVE_DOT tags are set to YES then doxygen will generate a graph for each -# documented header file showing the documented files that directly or -# indirectly include this file. - -INCLUDED_BY_GRAPH = NO - -# If the CALL_GRAPH and HAVE_DOT options are set to YES then -# doxygen will generate a call dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable call graphs -# for selected functions only using the \callgraph command. - -CALL_GRAPH = NO - -# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then -# doxygen will generate a caller dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable caller -# graphs for selected functions only using the \callergraph command. - -CALLER_GRAPH = NO - -# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen -# will generate a graphical hierarchy of all classes instead of a textual one. - -GRAPHICAL_HIERARCHY = NO - -# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES -# then doxygen will show the dependencies a directory has on other directories -# in a graphical way. The dependency relations are determined by the #include -# relations between the files in the directories. - -DIRECTORY_GRAPH = NO - -# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images -# generated by dot. Possible values are svg, png, jpg, or gif. -# If left blank png will be used. If you choose svg you need to set -# HTML_FILE_EXTENSION to xhtml in order to make the SVG files -# visible in IE 9+ (other browsers do not have this requirement). - -DOT_IMAGE_FORMAT = png - -# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to -# enable generation of interactive SVG images that allow zooming and panning. -# Note that this requires a modern browser other than Internet Explorer. -# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you -# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files -# visible. Older versions of IE do not have SVG support. - -INTERACTIVE_SVG = NO - -# The tag DOT_PATH can be used to specify the path where the dot tool can be -# found. If left blank, it is assumed the dot tool can be found in the path. - -DOT_PATH = @US_DOXYGEN_DOT_PATH@ - -# The DOTFILE_DIRS tag can be used to specify one or more directories that -# contain dot files that are included in the documentation (see the -# \dotfile command). - -DOTFILE_DIRS = - -# The MSCFILE_DIRS tag can be used to specify one or more directories that -# contain msc files that are included in the documentation (see the -# \mscfile command). - -MSCFILE_DIRS = - -# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of -# nodes that will be shown in the graph. If the number of nodes in a graph -# becomes larger than this value, doxygen will truncate the graph, which is -# visualized by representing a node as a red box. Note that doxygen if the -# number of direct children of the root node in a graph is already larger than -# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note -# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. - -DOT_GRAPH_MAX_NODES = 50 - -# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the -# graphs generated by dot. A depth value of 3 means that only nodes reachable -# from the root by following a path via at most 3 edges will be shown. Nodes -# that lay further from the root node will be omitted. Note that setting this -# option to 1 or 2 may greatly reduce the computation time needed for large -# code bases. Also note that the size of a graph can be further restricted by -# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. - -MAX_DOT_GRAPH_DEPTH = 0 - -# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent -# background. This is disabled by default, because dot on Windows does not -# seem to support this out of the box. Warning: Depending on the platform used, -# enabling this option may lead to badly anti-aliased labels on the edges of -# a graph (i.e. they become hard to read). - -DOT_TRANSPARENT = NO - -# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output -# files in one run (i.e. multiple -o and -T options on the command line). This -# makes dot run faster, but since only newer versions of dot (>1.8.10) -# support this, this feature is disabled by default. - -DOT_MULTI_TARGETS = NO - -# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will -# generate a legend page explaining the meaning of the various boxes and -# arrows in the dot generated graphs. - -GENERATE_LEGEND = YES - -# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will -# remove the intermediate dot files that are used to generate -# the various graphs. - -DOT_CLEANUP = YES diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox deleted file mode 100644 index 8a7260e7be..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices.dox +++ /dev/null @@ -1,85 +0,0 @@ - -/** - -\defgroup MicroServices Micro Services Classes - -\brief This category includes classes related to the C++ Micro Services component. - -The C++ Micro Services component provides a dynamic service registry based on the service layer -as specified in the OSGi R4.2 specifications. - -*/ - -/** - -\defgroup MicroServicesUtils Utility Classes - -\brief This category includes utility classes which can be used by others. - -*/ - -/** - -\page MicroServices_Examples Examples - -This is a list of available examples: - -- \subpage MicroServices_DictionaryService - -*/ - -/** - -\page MicroServices_Tutorials Tutorials - -This is a list of available tutorials: - -- \subpage MicroServices_TheModuleContext -- \subpage MicroServices_Resources -- \subpage MicroServices_EmulateSingleton -- \subpage MicroServices_AutoLoading -- \subpage MicroServices_StaticModules - -*/ - -/** - -\embmainpage{MicroServices_Overview} The C++ Micro Services - -The C++ Micro Services component provides a dynamic service registry based on the service layer -as specified in the OSGi R4.2 specifications. It enables users to realize a service oriented -approach within their software stack. The advantages include higher reuse of components, looser -coupling, better organization of responsibilities, cleaner API contracts, etc. - -\if us_standalone -\section MicroServices_Overview_BI Build Instructions - -How to build the C++ Micro Services library is explained in detail on the \ref BuildInstructions page. -\endif - -

Examples

- -\if us_standalone -Here is a list of \ref MicroServices_Examples "examples": -\else -Here is a list of \subpage MicroServices_Examples "examples": -\endif - -- \ref MicroServices_DictionaryService - -

Tutorials

- -The following list contains use cases and common patterns in the form of -\if us_standalone -\ref MicroServices_Tutorials "tutorials": -\else -\subpage MicroServices_Tutorials "tutorials": -\endif - -- \ref MicroServices_TheModuleContext -- \ref MicroServices_EmulateSingleton -- \ref MicroServices_AutoLoading -- \ref MicroServices_StaticModules - - -*/ diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md deleted file mode 100644 index 7e2ca58433..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_AutoLoading.md +++ /dev/null @@ -1,78 +0,0 @@ -Auto Loading Modules {#MicroServices_AutoLoading} -==================== - -Auto-loading of modules is a feature of the CppMicroServices library to manage the loading -of modules which would normally not be loaded at runtime because of missing link-time -dependencies. - -The Problem ------------ - -Imagine that you have a module *A* which provides an interface for loading files and another -module *B* which registers a service implementing that interface for files of type *png*. -Your executable *E* uses the interface from *A* to query the service registry for available -services. Due to the link-time dependencies, this results in the following dependency graph: - -\dot -digraph linker_deps { - node [shape=record, fontname=Helvetica, fontsize=10]; - a [ label="Module A\n(Interfaces)" ]; - b [ label="Module B\n(service provider)" ]; - e [ label="Executable E\n(service consumer)" ]; - a -> e; - a -> b; -} -\enddot - -When the executable *E* is launched, the dynamic linker of your operating system loads -module *A* to satisfy the dependencies of *E*, but module *B* will not be loaded. Therefore, -the executable will not be able to consume any services from module *B*. - -The Solution ------------- - -The problem above is solved in the CppMicroServices library by automatically loading modules -from a list of configurable file-system locations. - -For each module being loaded, the following steps are taken: - - - If the module provides an activator, it's ModuleActivator::Load() method is called. - - If auto-loading is enabled, and the module declared a non-empty auto-load directory, the - auto-load paths returned from ModuleSettings::GetAutoLoadPaths() are processed. - - For each auto-load path, all modules in that path with the currently loaded module's - auto-load directory appended are explicitly loaded. - -See the ModuleSettings class for details about auto-load paths and the #US_INITIALIZE_MODULE -macro for details about a module's auto-load directory. - -If module *A* in the example above contains initialization code like - -\code -US_INITIALIZE_MODULE("Module A", "A", "", "1.0.0") -\endcode - -and the module's library is located at - - /myproject/libA.so - -all libraries located at - - /myproject/A/ - -will be automatically loaded (unless the auto-load paths have been modified). By ensuring that -module *B* from the example above is located at - - /myproject/A/libB.so - -it will be loaded when the executable *E* is started and is then able to register its services -before the executable queries the service registry. - -Environment Variables ---------------------- - -The following environment variables influence the runtime behavior of the CppMicroServices library: - - - *US_DISABLE_AUTOLOADING* If set, auto-loading of modules is disabled. - - *US_AUTOLOAD_PATHS* A `:` (Unix) or `;` (Windows) separated list of paths from which modules - should be auto-loaded. - diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox deleted file mode 100644 index 4e3c735c8f..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Debugging.dox +++ /dev/null @@ -1,70 +0,0 @@ - -/** - * \ingroup MicroServicesUtils - * - * \enum MsgType - * This enum describes the messages that can be sent to a message handler (MsgHandler). - * You can use the enum to identify and associate the various message types with the - * appropriate actions. - */ - -/** - * \ingroup MicroServicesUtils - * - * \var MsgType DebugMsg - * A debug message. - */ - -/** - * \ingroup MicroServicesUtils - * - * \var MsgType InfoMsg - * An informational message. - */ - -/** - * \ingroup MicroServicesUtils - * - * \var MsgType WarningMsg - * A warning message. - */ - -/** - * \ingroup MicroServicesUtils - * - * \var MsgType ErrorMsg - * An error message. - */ - -/** - * \ingroup MicroServicesUtils - * - * \typedef MsgHandler - * A message handler callback function. - */ - -/** - * \ingroup MicroServicesUtils - * - * \fn MsgHandler installMsgHandler(MsgHandler) - * \brief Installs a message handler which has been defined previously. - * - * Returns a pointer to the previous message handler (which may be 0). - * - * The message handler is a function that prints out debug messages, warnings, - * and fatal error messages. The C++ Micro Services library (debug mode) contains - * warning messages that are printed when internal errors (usually invalid function - * arguments) occur. The library built in release mode also contains such warnings - * unless US_NO_WARNING_OUTPUT has been set during compilation. In both debug and release mode - * debugging message are suppressed by default, unless US_ENABLE_DEBUGGING_OUTPUT - * has been set during compilation. If you implement your own message handler, - * you get total control of these messages. - * - * The default message handler prints the message to the standard output. If it is - * an error message, the application aborts immediately. - * - * Only one message handler can be defined, since this is usually done on an - * application-wide basis to control debug output. - * - * To restore the message handler, call installMsgHandler(0). - */ diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox deleted file mode 100644 index 0b3094f105..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_EmulateSingleton.dox +++ /dev/null @@ -1,91 +0,0 @@ -/** - -\page MicroServices_EmulateSingleton Emulating singletons with micro services - -\section MicroServices_EmulateSingleton_1 Meyers Singleton - -Singletons are a well known pattern to ensure that only one instance of a class exists -during the whole life-time of the application. A self-deleting variant is the "Meyers Singleton": - -\snippet uServices-singleton/SingletonOne.h s1 - -where the GetInstance() method is implemented as - -\snippet uServices-singleton/SingletonOne.cpp s1 - -If such a singleton is accessed during static deinitialization (which happens during unloading -of shared libraries or application termination), your program might crash or even worse, exhibit undefined -behavior, depending on your compiler and/or weekday. Such an access might happen in destructors of -other objects with static life-time. - -For example, suppose that SingletonOne needs to call a second Meyers singleton during destruction: - -\snippet uServices-singleton/SingletonOne.cpp s1d - -If SingletonTwo was destroyed before SingletonOne, this leads to the mentioned problems. Note that -this problem only occurs for static objects defined in the same shared library. - -Since you cannot reliably control the destruction order of global static objects, you must not -introduce dependencies between them during static deinitialization. This is one reason why one -should consider an alternative approach to singletons (unless you can absolutely make sure that nothing in -your shared library will introduce such dependencies. Never.) - -Of course you could use something like a "Phoenix singleton" but that will have other drawbacks in certain -scenarios. Returning pointers instead of references in GetInstance() would open up the possibility to -return NULL, but than again this would not help if you require a non-NULL instance in your destructor. - -Another reason for an alternative approach is that singletons are usually not meant to be singletons for eternity. -If your design evolves, you might hit a point where you suddenly need multiple instances of your singleton. - -\section MicroServices_EmulateSingleton_2 Singletons as a service - -The C++ Micro Services can be used to emulate the singleton pattern using a non-singleton class. This -leaves room for future extensions without the need for heavy refactoring. Additionally, it gives you -full control about the construction and destruction order of your "singletons" inside your shared library -or executable, making it possible to have dependencies between them during destruction. - -\subsection MicroServices_EmulateSingleton_2_1 Converting a classic singleton - -We modify the previous SingletonOne class such that it internally uses the micro services API. The changes -are discussed in detail below. - -\snippet uServices-singleton/SingletonOne.h ss1 - - - Inherit us::Base: All service implementations (not their interfaces) must inherit from us::Base or from the base - class as specified in the CMake configuration. - In the implementation above, the class SingletonOneService provides the implementation as well as the interface. - - Friend activator: We move the responsibility of constructing instances of SingletonOneService from the GetInstance() - method to the module activator. - - Service interface declaration: Because the SingletonOneService class introduces a new service interface, it must - be registered under a unique name using the helper macro US_DECLARE_SERVICE_INTERFACE. - -Let's have a look at the modified GetInstance() and ~SingletonOneService() methods. - -\snippet uServices-singleton/SingletonOne.cpp ss1gi - -The inline comments should explain the details. Note that we now had to change the return type to a pointer, instead -of a reference as in the classic singleton. This is necessary since we can no longer guarantee that an instance -always exists. Clients of the GetInstance() method must check for null pointers and react appropriately. - -\warning Newly created "singletons" should not expose a GetInstance() method. They should be handled as proper -services and hence should be retrieved by clients using the ModuleContext or ServiceTracker API. The -GetInstance() method is for migration purposes only. - -\snippet uServices-singleton/SingletonOne.cpp ss1d - -The SingletonTwoService::GetInstance() method is implemented exactly as in SingletonOneService. Because we know -that the module activator guarantees that a SingletonTwoService instance will always be available during the -life-time of a SingletonOneService instance (see below), we can assert a non-null pointer. Otherwise, we would -have to handle the null-pointer case. - -The order of construction/registration and destruction/unregistration of our singletons (or any other services) is -defined in the Load() and Unload() methods of the module activator. - -\snippet uServices-singleton/main.cpp 0 - -The Unload() method is defined as: - -\snippet uServices-singleton/main.cpp 1 - - -*/ diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md deleted file mode 100644 index da80b20349..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_Resources.md +++ /dev/null @@ -1,56 +0,0 @@ -The Resources System {#MicroServices_Resources} -==================== - -The C++ Micro Services library provides a generic resources system to embed arbitrary files into a -module's shared library (the current size limitation is based on the largest source code file size -your compiler can handle). - -The following features are supported: - - * Embed arbitrary data into shared or static modules or executables. - * Data is embedded in a compressed format if the size reduction exceeds a - configurable threshold. - * Resources are accessed via a Module instance, providing individual resource lookup and access - for each module. - * Resources are managed in a tree hierarchy, modeling the original child - parent relationship - on the file-system. - * The ModuleResource class provides a high-level API for accessing resource information and - traversing the resource tree. - * The ModuleResourceStream class provides an STL input stream derived class for the seamless usage - of embedded resource data in third-party libraries. - - -Embedding Resources in a %Module -------------------------------- - -Resources are embedded by compiling a source file generated by the `usResourceCompiler` executable -into a module's shared or static library (or into an executable). - -If you are using CMake, consider using the provided `usFunctionEmbedResources` CMake macro which -handles the invocation of the `usResourceCompiler` executable and sets up the correct file -dependencies. - -Accessing Resources at Runtime ------------------------------- - -Each module provides access to its embedded resources via the Module class which provides methods -returning ModuleResource objects. The ModuleResourceStream class provides a std::istream compatible -object to access the resource contents. - -The following example shows how to retrieve a resource from each currently loaded module whose path -is specified by a module property: - -\snippet uServices-resources/main.cpp 2 - -This example could be enhanced to dynamically react to modules being loaded and unloaded, making use -of the popular "extender pattern" from OSGi. - -Limitations ------------ - -Currently, the system has the following limitations: - - * At most one file generated by the `usResourceCompiler` executable can be compiled into a module's - shared library (you can work around this limitation by creating static modules and importing them). - * The size of embedded resources is limited by the file size your compiler can handle. However, the file - size is the sum of the size of all resources embedded into a module plus a small overhead. diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md deleted file mode 100644 index a62d196755..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_StaticModules.md +++ /dev/null @@ -1,92 +0,0 @@ -Static Modules {#MicroServices_StaticModules} -============== - -The normal and most flexible way to include a CppMicroServices module in an application is to compile -it into a shared library that is either linked by another library (or executable) or -\ref MicroServices_AutoLoading "auto-loaded" during runtime. - -However, modules can be linked statically to your application or shared library. This makes the deployment -of your application less error-prone and in the case of a complete static build also minimizes its binary -size and start-up time. The disadvantage is that no functionality can be added without a rebuild and -redistribution of the application. - -## Creating Static Modules - -Static modules are written just like shared modules - there are no differences in the usage of the -CppMicroServices API or the provided preprocessor macros. The only thing you need to make sure is that -the `US_STATIC_MODULE` preprocessor macro is defined when building a module statically. - -## Using Static Modules - -Static modules can be used (imported) in shared or other static libraries or in the executable itself. -Assuming that a static module makes use of the CppMicroServices API (e.g. by registering some services -using a ModuleContext), the importing library or executable needs to put a call to the `#US_INITIALIZE_MODULE` macro -somewhere in its source code. This ensures the availability of a module context which is shared with all -imported static libraries (see also \ref MicroServices_StaticModules_Context). - -\note Note that if your static module does not export a module activator by using the macro -`#US_EXPORT_MODULE_ACTIVATOR` or does not contain embedded resources (see \ref MicroServices_Resources) you -do not need to put the special import macros explained below into -your code. You can use and link the static module just like any other static library. - -For every static module you would like to import, you need to put a call to `#US_IMPORT_MODULE` into the -source code of the importing library. To make the static module's resources available to the importing module, -you must also call `#US_IMPORT_MODULE_RESOURCES`. Addidtionally, you need a call to `#US_LOAD_IMPORTED_MODULES` -which contains a space-deliminated list of module names in the importing libaries source code. This ensures -that the module activators of the imported static modules (if they exist) are called appropriately and that -the embedded resources are registered with the importing module. - -\note When importing a static module into another static module, the call to `#US_LOAD_IMPORTED_MODULES` in -the importing static module will have no effect. This macro can only be used in shared modules or executables. - -There are two main usage scenarios which are explained below together with some example code. - -### Using a Shared CppMicroServices Library - -Building the CppMicroServices library as a shared library allows you to import static modules into other -shared or static modules or into the executable. As noted above, the importing shared module or executable -needs to provide a module context by calling the `#US_INITIALIZE_MODULE` macro. Additionally, you must ensure -to use the `#US_LOAD_IMPORTED_MODULES_INTO_MAIN` macro instead of `#US_LOAD_IMPORTED_MODULES` when importing -static modules into an executable. - -Example code for importing the two static modules `MyStaticModule1` and `MyStaticModule2` into an executable: - -\snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoMain - -Importing the static module `MyStaticModule` into a shared or static module looks like this: - -\snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoLib - -Having a shared CppMicroServices library, the executable also needs some initialization code: - -\snippet uServices-staticmodules/main.cpp InitializeExecutable - -Note that shared (but not static) modules also need the `#US_INITIALIZE_MODULE` call when importing static modules, -but can omit the US_BUILD_SHARED_LIBS guard. - -### Using a Static CppMicroServices Library - -The CppMicroServices library can be build as a static library. In that case, creating shared modules is not supported. -If you create shared modules which link a static version of the CppMicroServices library, the runtime behavior is -undefined. - -In this usage scenario, every module will be statically build and linked to an executable. The executable needs to -import all the static modules, just like above: - -\snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoMain - -However, it can omit the `#US_INITIALIZE_MODULE` macro call (the module context from the CppMicroServices library -will be shared across all modules and the executable). - -## A Note About The Module Context {#MicroServices_StaticModules_Context} - -Modules using the CppMicroServices API frequently need a `ModuleContext` object to query, retrieve, and register services. -Static modules will never get their own module context but will share the context with their importing module or -executable. Therefore, the importing module or executable needs to ensure the availability of such a context (by using -the `#US_INITIALIZE_MODULE` macro). - -\note The CppMicroServices library will *always* provide a module context, independent of its library build mode. - -So in a completely statically build application, the CppMicroServices library provides a global module context for all -imported modules and the executable. - diff --git a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md b/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md deleted file mode 100644 index dc7b9cda42..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/MicroServices_TheModuleContext.md +++ /dev/null @@ -1,36 +0,0 @@ -The Module Context {#MicroServices_TheModuleContext} -=================== - -In the context of the C++ Micro Services library, we will call all supported "shared library" types -(DLL, DSO, DyLib, etc.) uniformly a *module*. A module accesses the C++ Micro Services API via a -ModuleContext object. While multiple modules could use the same ModuleContext, it is highly recommended -that each module gets its own (this will enable module specific service usage tracking and also allows -the C++ Micro Services framework to properly cleanup resources after a module has been unloaded). - -### Creating a ModuleContext - -To create a ModuleContext object for a specific library, you have two options. If your project uses -CMake as the build system, use the supplied `usFunctionGenerateModuleInit` CMake function to automatically -create a source file and add it to your module's sources: - - set(module_srcs ) - usFunctionGenerateModuleInit(module_srcs - NAME "My Module" - LIBRARY_NAME "mylibname" - VERSION "1.0.0" - ) - add_library(mylib ${module_srcs}) - -If you do not use CMake, you have to add a call to the macro `#US_INITIALIZE_MODULE` in one of the source -files of your module: - -\snippet uServices-modulecontext/main.cpp InitializeModule - -### Getting a ModuleContext - -To retrieve the module specific ModuleContext object from anywhere in your module, use the -`#GetModuleContext` function: - -\snippet uServices-modulecontext/main.cpp GetModuleContext - -Please note that the call to `#GetModuleContext` will fail if you did not create a module specific context. diff --git a/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css b/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css deleted file mode 100644 index 8d4e9bba34..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/doxygen.css +++ /dev/null @@ -1,1141 +0,0 @@ -/* The standard CSS for doxygen */ - -/* -body, table, div, p, dl { - font-family: Lucida Grande, Verdana, Geneva, Arial, sans-serif; - font-size: 13px; - line-height: 1.3; -} -*/ - -/* @group Heading Levels */ - -h1 { - font-size: 150%; -} - -.title { - font-size: 150%; - font-weight: bold; - margin: 10px 2px; -} - -h2 { - font-size: 120%; -} - -h3 { - font-size: 100%; -} - -h1, h2, h3, h4, h5, h6 { - -webkit-transition: text-shadow 0.5s linear; - -moz-transition: text-shadow 0.5s linear; - -ms-transition: text-shadow 0.5s linear; - -o-transition: text-shadow 0.5s linear; - transition: text-shadow 0.5s linear; - margin-right: 15px; -} - -h1.glow, h2.glow, h3.glow, h4.glow, h5.glow, h6.glow { - text-shadow: 0 0 15px cyan; -} - -dt { - font-weight: bold; -} - -div.multicol { - -moz-column-gap: 1em; - -webkit-column-gap: 1em; - -moz-column-count: 3; - -webkit-column-count: 3; -} - -p.startli, p.startdd, p.starttd { - margin-top: 2px; -} - -p.endli { - margin-bottom: 0px; -} - -p.enddd { - margin-bottom: 4px; -} - -p.endtd { - margin-bottom: 2px; -} - -/* @end */ - -caption { - font-weight: bold; -} - -span.legend { - font-size: 70%; - text-align: center; -} - -h3.version { - font-size: 90%; - text-align: center; -} - -div.qindex, div.navtab{ - border: 1px solid #e6e6e6; - text-align: center; -} - -div.qindex, div.navpath { - width: 100%; - padding: 0 10px; -} - -div.navtab { - margin-right: 15px; -} - -/* @group Link Styling */ - -a { - font-weight: normal; - text-decoration: none; -} - -.contents a:visited { - color: #4665A2; -} - -a.qindex { - font-weight: bold; -} - -a.qindexHL { - font-weight: bold; - background-color: #9CAFD4; - color: #ffffff; - border: 1px double #869DCA; -} - -.contents a.qindexHL:visited { - color: #ffffff; -} - -a.el { - font-weight: bold; -} - -a.elRef { -} - -a.code, a.code:visited { - color: #4665A2; -} - -a.codeRef, a.codeRef:visited { - color: #4665A2; -} - -/* @end */ - -dl.el { - margin-left: -1cm; -} - -pre.fragment { - border-top-style: solid; - border-bottom-style: solid; - border-width: 1px 0 1px 0; - border-color: #e6e6e6; - border-radius: 0; - padding: 4px 6px; - margin: 4px 8px 4px 2px; - overflow: auto; - word-wrap: break-word; - font-size: 9pt; - line-height: 125%; -} - -div.fragment { - padding: 4px 6px; - margin: 4px 8px 4px 2px; - border-top-style: solid; - border-bottom-style: solid; - border-width: 1px 0 1px 0; - border-color: #e6e6e6; - background-color: #F5F5F5; -} - -div.line { - font-family: monospace, fixed; - font-size: 13px; - min-height: 13px; - line-height: 1.0; - text-wrap: unrestricted; - white-space: -moz-pre-wrap; /* Moz */ - white-space: -pre-wrap; /* Opera 4-6 */ - white-space: -o-pre-wrap; /* Opera 7 */ - white-space: pre-wrap; /* CSS3 */ - word-wrap: break-word; /* IE 5.5+ */ - text-indent: -53px; - padding-left: 53px; - padding-bottom: 0px; - margin: 0px; -} - -span.lineno { - padding-right: 4px; - text-align: right; - border-right: 2px solid #0F0; - background-color: #E8E8E8; - white-space: pre; -} -span.lineno a { - background-color: #D8D8D8; -} - -span.lineno a:hover { - background-color: #C8C8C8; -} - -div.ah { - background-color: #f6f6f6; - font-weight: bold; - margin-bottom: 3px; - margin-top: 3px; - padding: 0.2em; - border: solid thin #e6e6e6; - border-radius: 0.5em; - -webkit-border-radius: .5em; - -moz-border-radius: .5em; -} - -div.groupHeader { - margin-left: 16px; - margin-top: 12px; - font-weight: bold; -} - -div.groupText { - margin-left: 16px; - font-style: italic; -} - -div.contents { - margin-top: 10px; - margin-left: 12px; - margin-right: 8px; -} - -td.indexkey { - font-weight: bold; - margin: 2px 0px 2px 0; - padding: 2px 10px; - white-space: nowrap; - vertical-align: top; -} - -td.indexvalue { - padding: 2px 10px; - margin: 2px 0px; -} - -tr.memlist { - background-color: #EEF1F7; -} - -p.formulaDsp { - text-align: center; -} - -img.formulaDsp { - -} - -img.formulaInl { - vertical-align: middle; -} - -div.center { - text-align: center; - margin-top: 0px; - margin-bottom: 0px; - padding: 0px; -} - -div.center img { - border: 0px; -} - -address.footer { - text-align: right; - padding-right: 12px; -} - -img.footer { - border: 0px; - vertical-align: middle; -} - -/* @group Code Colorization */ - -span.keyword { - color: #008000 -} - -span.keywordtype { - color: #604020 -} - -span.keywordflow { - color: #e08000 -} - -span.comment { - color: #800000 -} - -span.preprocessor { - color: #806020 -} - -span.stringliteral { - color: #002080 -} - -span.charliteral { - color: #008080 -} - -span.vhdldigit { - color: #ff00ff -} - -span.vhdlchar { - color: #000000 -} - -span.vhdlkeyword { - color: #700070 -} - -span.vhdllogic { - color: #ff0000 -} - -blockquote { - background-color: #F7F8FB; - border-left: 2px solid #9CAFD4; - margin: 0 24px 0 4px; - padding: 0 12px 0 16px; -} - -/* @end */ - -/* -.search { - color: #003399; - font-weight: bold; -} - -form.search { - margin-bottom: 0px; - margin-top: 0px; -} - -input.search { - font-size: 75%; - color: #000080; - font-weight: normal; - background-color: #e8eef2; -} -*/ - -td.tiny { - font-size: 75%; -} - -.dirtab { - padding: 4px; - border-collapse: collapse; - border: 1px solid #A3B4D7; -} - -th.dirtab { - background: #EBEFF6; - font-weight: bold; -} - -hr { - height: 0px; - border: none; - border-top: 1px solid #e6e6e6; -} - -hr.footer { - height: 1px; -} - -/* @group Member Descriptions */ - -table.memberdecls { - border-spacing: 0px; - padding: 0px; -} - -.memberdecls td { - -webkit-transition-property: background-color, box-shadow; - -webkit-transition-duration: 0.5s; - -moz-transition-property: background-color, box-shadow; - -moz-transition-duration: 0.5s; - -ms-transition-property: background-color, box-shadow; - -ms-transition-duration: 0.5s; - -o-transition-property: background-color, box-shadow; - -o-transition-duration: 0.5s; - transition-property: background-color, box-shadow; - transition-duration: 0.5s; -} - -.memberdecls td.glow { - background-color: cyan; - box-shadow: 0 0 15px cyan; -} - -.mdescLeft, .mdescRight, -.memItemLeft, .memItemRight, -.memTemplItemLeft, .memTemplItemRight, .memTemplParams { - /*background-color: #F9FAFC;*/ - border: none; - margin: 4px; - padding: 1px 0 0 8px; -} - -.mdescLeft, .mdescRight { - padding: 0px 8px 4px 8px; - color: #555; -} - -/* -.memItemLeft, .memItemRight, .memTemplParams { - border-top: 1px solid #C4CFE5; -} -*/ - -.memItemLeft, .memTemplItemLeft { - white-space: nowrap; -} - -.memItemRight { - width: 100%; -} - -.memTemplParams { - color: #4665A2; - white-space: nowrap; -} - -/* @end */ - -/* @group Member Details */ - -/* Styles for detailed member documentation */ - -.memtemplate { - font-size: 80%; - color: #4665A2; - font-weight: normal; - margin-left: 9px; -} - -.memnav { - background-color: #EBEFF6; - border: 1px solid #A3B4D7; - text-align: center; - margin: 2px; - margin-right: 15px; - padding: 2px; -} - -.mempage { - width: 100%; -} - -.memitem { - padding: 0; - margin-bottom: 10px; - margin-right: 5px; - -webkit-transition: box-shadow 0.5s linear; - -moz-transition: box-shadow 0.5s linear; - -ms-transition: box-shadow 0.5s linear; - -o-transition: box-shadow 0.5s linear; - transition: box-shadow 0.5s linear; -} - -.memitem.glow { - box-shadow: 0 0 15px cyan; -} - -.memname { - font-weight: bold; - margin-left: 6px; -} - -.memname td { - vertical-align: bottom; -} - -.memproto, dl.reflist dt { - border-top: 1px solid #e6e6e6; - border-left: 1px solid #e6e6e6; - border-right: 1px solid #e6e6e6; - padding: 6px 0px 6px 0px; - color: #253555; - font-weight: bold; - /* opera specific markup */ - border-top-right-radius: 8px; - border-top-left-radius: 8px; - /* firefox specific markup */ - -moz-border-radius-topright: 8px; - -moz-border-radius-topleft: 8px; - /* webkit specific markup */ - -webkit-border-top-right-radius: 8px; - -webkit-border-top-left-radius: 8px; - background-color: #f6f6f6; - -} - -.memdoc, dl.reflist dd { - border-bottom: 1px solid #e6e6e6; - border-left: 1px solid #e6e6e6; - border-right: 1px solid #e6e6e6; - padding: 2px 5px; - border-top-width: 0; - /* opera specific markup */ - border-bottom-left-radius: 8px; - border-bottom-right-radius: 8px; - /* firefox specific markup */ - -moz-border-radius-bottomleft: 8px; - -moz-border-radius-bottomright: 8px; - /* webkit specific markup */ - -webkit-border-bottom-left-radius: 8px; - -webkit-border-bottom-right-radius: 8px; -} - -dl.reflist dt { - padding: 5px; -} - -dl.reflist dd { - margin: 0px 0px 10px 0px; - padding: 5px; -} - -.paramkey { - text-align: right; -} - -.paramtype { - white-space: nowrap; -} - -.paramname { - color: #602020; - white-space: nowrap; -} -.paramname em { - font-style: normal; -} - -.params, .retval, .exception, .tparams { - margin-left: 0px; - padding-left: 0px; -} - -.params .paramname, .tparams .paramname, .retval .paramname { - font-weight: bold; - vertical-align: top; - padding-right: 10px; -} - -.params .paramtype { - font-style: italic; - vertical-align: top; -} - -.params .paramdir { - font-family: "courier new",courier,monospace; - vertical-align: top; -} - -table.mlabels { - border-spacing: 0px; -} - -td.mlabels-left { - width: 100%; - padding: 0px; -} - -td.mlabels-right { - vertical-align: bottom; - padding: 0px; - white-space: nowrap; -} - -span.mlabels { - margin-left: 8px; -} - -span.mlabel { - background-color: #728DC1; - border-top:1px solid #405C93; - border-left:1px solid #405C93; - border-right:1px solid #C4CFE5; - border-bottom:1px solid #C4CFE5; - text-shadow: none; - color: white; - margin-right: 4px; - padding: 2px 3px; - border-radius: 3px; - font-size: 7pt; - white-space: nowrap; -} - - - -/* @end */ - -/* these are for tree view when not used as main index */ - -div.directory { - margin: 10px 0px; - /*border-top: 1px solid #A8B8D9; - border-bottom: 1px solid #A8B8D9;*/ - width: 100%; -} - -.directory table { - border-collapse:collapse; -} - -.directory td { - margin: 0px; - padding: 0px; - vertical-align: baseline; -} - -.directory td.entry { - white-space: nowrap; - padding-right: 6px; -} - -.directory td.entry a { - outline:none; -} - -.directory td.desc { - width: 100%; - padding-left: 6px; - padding-right: 6px; - border-left: 1px solid rgba(0,0,0,0.05); -} - -.directory tr.even { - padding-left: 6px; - /*background-color: #F7F8FB;*/ -} - -.directory img { - vertical-align: -30%; -} - -.directory .levels { - white-space: nowrap; - width: 100%; - text-align: right; - font-size: 9pt; -} - -.directory .levels span { - cursor: pointer; - padding-left: 2px; - padding-right: 2px; - color: #3D578C; -} - -div.dynheader { - margin-top: 8px; -} - -address { - font-style: normal; - margin: 0; -} - -table.doxtable { - border-collapse:collapse; - margin-top: 4px; - margin-bottom: 4px; -} - -table.doxtable td, table.doxtable th { - border: 1px solid #2D4068; - padding: 3px 7px 2px; -} - -table.doxtable th { - background-color: #374F7F; - color: #FFFFFF; - font-size: 110%; - padding-bottom: 4px; - padding-top: 5px; -} - -table.fieldtable { - width: 100%; - margin-bottom: 10px; - border: 1px solid #A8B8D9; - border-spacing: 0px; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; - -webkit-box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15); - box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15); -} - -.fieldtable td, .fieldtable th { - padding: 3px 7px 2px; -} - -.fieldtable td.fieldtype, .fieldtable td.fieldname { - white-space: nowrap; - border-right: 1px solid #A8B8D9; - border-bottom: 1px solid #A8B8D9; - vertical-align: top; -} - -.fieldtable td.fielddoc { - border-bottom: 1px solid #A8B8D9; - width: 100%; -} - -.fieldtable tr:last-child td { - border-bottom: none; -} - -.fieldtable th { - background-image:url('nav_f.png'); - background-repeat:repeat-x; - background-color: #E2E8F2; - font-size: 90%; - color: #253555; - padding-bottom: 4px; - padding-top: 5px; - text-align:left; - -moz-border-radius-topleft: 4px; - -moz-border-radius-topright: 4px; - -webkit-border-top-left-radius: 4px; - -webkit-border-top-right-radius: 4px; - border-top-left-radius: 4px; - border-top-right-radius: 4px; - border-bottom: 1px solid #A8B8D9; -} - - -.tabsearch { - top: 0px; - left: 10px; - height: 36px; - background-image: url('tab_b.png'); - z-index: 101; - overflow: hidden; - font-size: 13px; -} - -.navpath ul -{ - font-size: 11px; - overflow:hidden; - margin:0px; - padding:0px; -} - -.navpath li -{ - list-style-type:none; - float:left; - padding-left:10px; - padding-right:15px; -} - -.navpath li.navelem a -{ - height:22px; - display:block; - text-decoration: none; - outline: none; - color: #999; -} - -.navpath li.navelem a:hover -{ - text-decoration: underline; -} - -.navpath li.footer -{ - list-style-type:none; - float:right; - padding-left:10px; - padding-right:15px; - background-image:none; - background-repeat:no-repeat; - background-position:right; - color:#364D7C; - font-size: 8pt; -} - - -div.summary -{ - float: right; - font-size: 8pt; - padding-right: 5px; - width: 50%; - text-align: right; -} - -div.summary a -{ - white-space: nowrap; -} - -div.ingroups -{ - margin-left: 5px; - font-size: 8pt; - padding-left: 5px; - width: 50%; - text-align: left; -} - -div.ingroups a -{ - white-space: nowrap; -} - -div.header -{ - margin: 0px; - border-bottom: 1px solid #333333; -} - -div.headertitle -{ - padding: 0px 5px 0px 7px; -} - -dl -{ - padding: 0 0 0 10px; -} - -/* dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug */ -dl.section -{ - margin-left: 0px; - padding-left: 0px; -} - -dl.note -{ - padding-left: 3px; - border-left:4px solid; - border-color: #D0C000; -} - -dl.warning, dl.attention -{ - padding-left: 3px; - border-left:4px solid; - border-color: #FF0000; -} - -dl.pre, dl.post, dl.invariant -{ - padding-left: 3px; - border-left:4px solid; - border-color: #00D000; -} - -dl.deprecated -{ - padding-left: 3px; - border-left:4px solid; - border-color: #505050; -} - -dl.todo -{ - padding-left: 3px; - border-left:4px solid; - border-color: #00C0E0; -} - -dl.test -{ - padding-left: 3px; - border-left:4px solid; - border-color: #3030E0; -} - -dl.bug -{ - padding-left: 3px; - border-left:4px solid; - border-color: #C08050; -} - -dl.section dd { - margin-bottom: 6px; -} - - -#projectlogo -{ - text-align: center; - vertical-align: bottom; - border-collapse: separate; -} - -#projectlogo img -{ - border: 0px none; -} - -#projectname -{ - font: 300% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 2px 0px; -} - -#projectbrief -{ - font: 120% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#projectnumber -{ - font: 50% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#titlearea -{ - padding: 0px; - margin: 0px; - width: 100%; - border-bottom: 1px solid #5373B4; -} - -.image -{ - text-align: center; -} - -.dotgraph -{ - text-align: center; -} - -.mscgraph -{ - text-align: center; -} - -.caption -{ - font-weight: bold; -} - -div.zoom -{ - border: 1px solid #90A5CE; -} - -dl.citelist { - margin-bottom:50px; -} - -dl.citelist dt { - color:#334975; - float:left; - font-weight:bold; - margin-right:10px; - padding:5px; -} - -dl.citelist dd { - margin:2px 0; - padding:5px 0; -} - -div.toc { - padding: 14px 25px; - background-color: #F4F6FA; - border: 1px solid #D8DFEE; - border-radius: 7px 7px 7px 7px; - float: right; - height: auto; - margin: 0 20px 10px 10px; - width: 200px; -} - -div.toc li { - background: url("bdwn.png") no-repeat scroll 0 5px transparent; - font: 10px/1.2 Verdana,DejaVu Sans,Geneva,sans-serif; - margin-top: 5px; - padding-left: 10px; - padding-top: 2px; -} - -div.toc h3 { - font: bold 12px/1.2 Arial,FreeSans,sans-serif; - color: #4665A2; - border-bottom: 0 none; - margin: 0; -} - -div.toc ul { - list-style: none outside none; - border: medium none; - padding: 0px; -} - -div.toc li.level1 { - margin-left: 0px; -} - -div.toc li.level2 { - margin-left: 15px; -} - -div.toc li.level3 { - margin-left: 30px; -} - -div.toc li.level4 { - margin-left: 45px; -} - -.inherit_header { - font-weight: bold; - color: gray; - cursor: pointer; - -webkit-touch-callout: none; - -webkit-user-select: none; - -khtml-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -.inherit_header td { - padding: 6px 0px 2px 5px; -} - -.inherit { - display: none; -} - -tr.heading h2 { - margin-top: 12px; - margin-bottom: 4px; -} - -@media print -{ - #top { display: none; } - #side-nav { display: none; } - #nav-path { display: none; } - body { overflow:visible; } - h1, h2, h3, h4, h5, h6 { page-break-after: avoid; } - .summary { display: none; } - .memitem { page-break-inside: avoid; } - #doc-content - { - margin-left:0 !important; - height:auto !important; - width:auto !important; - overflow:inherit; - display:inline; - } -} - -code { - background-color: none; - border: none; - color: #333333; - padding: 1; -} - -.doxygen-header { - background-color: #F5F5F5; - margin: -20px -20px 20px; -} - -.tabs, .tabs2, .tabs3 { - width: 100%; - font-size: 16px; - position: relative; -} - -.tabs2 { - font-size: 14px; -} -.tabs3 { - font-size: 12px; -} - -.tablist { - margin: 0; - padding: 0; - display: table; -} - -.tablist li { - float: left; - display: table-cell; - list-style: none; -} - -.tablist a { - display: block; - padding: 10px 20px; - font-weight: bold; - color: #999999; - text-decoration: none; - outline: none; -} - -.tabs3 .tablist a { - padding: 0 10px; -} - -.tablist a:hover { - text-decoration: underline; -} - -.tablist li.current a { - color: #fff; - background-color: #bbb; -} - diff --git a/Core/Code/CppMicroServices/documentation/doxygen/examples/MicroServices_DictionaryService.md b/Core/Code/CppMicroServices/documentation/doxygen/examples/MicroServices_DictionaryService.md deleted file mode 100644 index 827280b91e..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/examples/MicroServices_DictionaryService.md +++ /dev/null @@ -1,29 +0,0 @@ -Implementing A Dictionary Service {#MicroServices_DictionaryService} -================================= - -This example demonstrates how to implement a service object. First, we must define the service interface -and then we define an implementation of that interface. In this particular example, we will create a -dictionary service that we can use to check if a word exists, which indicates if the word is spelled -correctly or not. - -We start by defining the dictionary interface (for example in a file called DictionaryService.h): - -\include uServices-dictionaryservice/DictionaryService.h - -The service interface is quite simple, with only one method that needs to be implemented. Notice that the -file does only contain the interface declaration and no actual code. - -In the following source code, the module uses its module context to register the dictionary service. -We implement the dictionary service as an inner class of the module activator class, but we could have also -put it in a separate file. Also note that there is no need to explicityl export any symbols from the module. - -\snippet uServices-dictionaryservice/main.cpp Activator - -Note that we do not need to unregister the service in the `Unload` method, because it will be done automatically -for us during static de-initialization of the module. - -In the last line, we "export" the module activator, assuming that it is contained in a module named -`DictionaryServiceModule`. We can get the highest ranking service implementation for the DictionaryService interface -by querying the service registry via the module context: - -\snippet uServices-dictionaryservice/main.cpp GetDictionaryService diff --git a/Core/Code/CppMicroServices/documentation/doxygen/footer.html b/Core/Code/CppMicroServices/documentation/doxygen/footer.html deleted file mode 100644 index 38c8204a29..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/footer.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - diff --git a/Core/Code/CppMicroServices/documentation/doxygen/header.html b/Core/Code/CppMicroServices/documentation/doxygen/header.html deleted file mode 100644 index 847964d749..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/header.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -layout: default -title: $title ---- - - - - - - - - - $treeview - $search - $mathjax - - - - - -
- diff --git a/Core/Code/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md b/Core/Code/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md deleted file mode 100644 index 949489d93b..0000000000 --- a/Core/Code/CppMicroServices/documentation/doxygen/standalone/BuildInstructions.md +++ /dev/null @@ -1,83 +0,0 @@ -Build Instructions {#BuildInstructions} -================== - -The C++ Micro Services library provides [CMake][cmake] build scripts which allow the generation of -platform and IDE specific project files. - -The library should compile on many different platforms. Below is a list of tested compiler/OS combinations: - - - GCC 4.5 (Ubuntu 11.04 and MacOS X 10.6) - - Visual Studio 2008 and 2010 - - Clang 3.0 (Ubuntu 11.04 and MacOS X 10.6) - - -Prerequisites -------------- - -- [CMake][cmake] 2.8 (Visual Studio 2010 users should use the latest CMake version available) - - -Configuring the Build ---------------------- - -When building the C++ Micro Services library, you have a few configuration options at hand. - -### General build options - -- **US_BUILD_SHARED_LIBS** - Specify if the library should be build shared or static. See \ref MicroServices_StaticModules for detailed - information about static CppMicroServices modules. -- **US_BUILD_TESTING** - Build unit tests and code snippets. -- **US_ENABLE_AUTOLOADING_SUPPORT** - Enable auto-loading of modules located in special sup-directories. See \ref MicroServices_AutoLoading for - detailed information about this feature. -- **US_ENABLE_THREADING_SUPPORT** - Enable the use of synchronization primitives (atomics and pthread mutexes or Windows primitives) to make - the API thread-safe. If you are application is not multi-threaded, turn this option OFF to get maximum - performance. -- **US_USE_C++11 (advanced)** - Enable the usage of C++11 constructs -- **US_ENABLE_RESOURCE_COMPRESSION** - Enable compression of embedded resources. See \ref MicroServices_Resources for detailed information - about the resource system. - -### Customizing naming conventions - -- **US_NAMESPACE** - The default namespace is `us` but you may override this at will. -- **US_HEADER_PREFIX** - By default, all public headers have a "us" prefix. You may specify an arbitrary prefix to match your - naming conventions. - -The above options are mainly useful when embedding the C++ Micro Services source code in your own library and -you want to make it look like native source code. - -### Configure the service base class - -All service implementations must inherit from the same base class. The C++ Micro Services library provides -a trivial class called `us::Base` for that purpose. However, most applications already have a special base -class and you can configure the C++ Micro Services library to use that class. - -- **US_BASECLASS_NAME** - The fully-qualified name of the base class, e.g. `my::OwnBaseClass`. If you don't need support for service - factories (see below) and don't want to enable US_BUILD_TESTING, this is all you need. -- **US_ENABLE_SERVICE_FACTORY_SUPPORT (advanced)** - If you want support for service factories (they allow the customization of service objects for individual - modules, see OSGi Service Platform Core Specification Release 4, Version 4.3, Section 5.6), switch this - option to ON. If you also provided a custom US_BASECLASS_NAME, you need to set the US_BASECLASS_HEADER variable. -- **US_BASECLASS_HEADER (advanced)** - The name of the header file containing the declaration for the base class specified in US_BASECLASS_NAME, e.g. - `myOwnBaseClass.h`. You will also have to set US_BASECLASS_PACKAGE or US_BASECLASS_INCLUDE_DIRS and US_BASECLASS_LIBRARIES. -- **US_BASECLASS_PACKAGE (advanced)** - If your specified a custom base class from a library which can be found via a CMake `find_package` command, enter - the package name here. Most of the time, this will correctly set the values for US_BASECLASS_INCLUDE_DIRS, - US_BASECLASS_LIBRARIES, and US_BASECLASS_LIBRARY_DIRS. -- **US_BASECLASS_INCLUDE_DIRS (advanced)** - A list of include dirs needed to include the base class header file as specified in US_BASECLASS_HEADER. -- **US_BASECLASS_LIBRARIES (advanced)** - A list of libraries to link the C++ Micro Services library against for resolving symbols needed for a custom base class. -- **US_BASECLASS_LIBRARY_DIRS (advanced)** - A list of directories to look for the libraries specified in US_BASECLASS_LIBRARIES - -[cmake]: http://www.cmake.org diff --git a/Core/Code/CppMicroServices/documentation/snippets/CMakeLists.txt b/Core/Code/CppMicroServices/documentation/snippets/CMakeLists.txt deleted file mode 100644 index ce7de8a6b3..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ - -include_directories(${US_INCLUDE_DIRS}) -set(_link_libraries) -if(US_IS_EMBEDDED) - set(_link_libraries ${US_EMBEDDING_LIBRARY}) -else() - set(_link_libraries ${PROJECT_NAME}) -endif() - -usFunctionCompileSnippets("${CMAKE_CURRENT_SOURCE_DIR}" ${_link_libraries}) - diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp deleted file mode 100644 index c4ba6c25e7..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-activator/main.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include - -US_USE_NAMESPACE - -//! [0] -class MyActivator : public ModuleActivator -{ - -public: - - void Load(ModuleContext* /*context*/) - { /* register stuff */ } - - - void Unload(ModuleContext* /*context*/) - { /* cleanup */ } - -}; - -US_EXPORT_MODULE_ACTIVATOR(mylibname, MyActivator) -//![0] - -int main(int /*argc*/, char* /*argv*/[]) -{ - MyActivator ma; - return 0; -} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h b/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h deleted file mode 100644 index 304d76c6c3..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/DictionaryService.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef DICTIONARYSERVICE_H -#define DICTIONARYSERVICE_H - -#include - -#include - -/** - * A simple service interface that defines a dictionary service. - * A dictionary service simply verifies the existence of a word. - **/ -struct DictionaryService -{ - virtual ~DictionaryService() {} - - /** - * Check for the existence of a word. - * @param word the word to be checked. - * @return true if the word is in the dictionary, - * false otherwise. - **/ - virtual bool checkWord(const std::string& word) = 0; -}; - -US_DECLARE_SERVICE_INTERFACE(DictionaryService, "DictionaryService/1.0") - -#endif // DICTIONARYSERVICE_H diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp deleted file mode 100644 index bd714f6d54..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-dictionaryservice/main.cpp +++ /dev/null @@ -1,121 +0,0 @@ - -//! [Activator] -#include "DictionaryService.h" - -#include -#include -#include -#include - -// Replace that include with your own base class declaration -#include US_BASECLASS_HEADER - -#include -#include -#include - -US_USE_NAMESPACE - -/** - * This class implements a module activator that uses the module - * context to register an English language dictionary service - * with the C++ Micro Services registry during static initialization - * of the module. The dictionary service interface is - * defined in a separate file and is implemented by a nested class. - */ -class US_ABI_LOCAL MyActivator : public ModuleActivator -{ - -private: - - /** - * A private inner class that implements a dictionary service; - * see DictionaryService for details of the service. - */ - class DictionaryImpl : public US_BASECLASS_NAME, public DictionaryService - { - // The set of words contained in the dictionary. - std::set m_dictionary; - - public: - - DictionaryImpl() - { - m_dictionary.insert("welcome"); - m_dictionary.insert("to"); - m_dictionary.insert("the"); - m_dictionary.insert("micro"); - m_dictionary.insert("services"); - m_dictionary.insert("tutorial"); - } - - /** - * Implements DictionaryService.checkWord(). Determines - * if the passed in word is contained in the dictionary. - * @param word the word to be checked. - * @return true if the word is in the dictionary, - * false otherwise. - **/ - bool checkWord(const std::string& word) - { - std::string lword(word); - std::transform(lword.begin(), lword.end(), lword.begin(), ::tolower); - - return m_dictionary.find(lword) != m_dictionary.end(); - } - }; - - std::auto_ptr m_dictionaryService; - - -public: - - /** - * Implements ModuleActivator::Load(). Registers an - * instance of a dictionary service using the module context; - * attaches properties to the service that can be queried - * when performing a service look-up. - * @param context the context for the module. - */ - void Load(ModuleContext* context) - { - m_dictionaryService.reset(new DictionaryImpl); - ServiceProperties props; - props["Language"] = std::string("English"); - context->RegisterService(m_dictionaryService.get(), props); - } - - /** - * Implements ModuleActivator::Unload(). Does nothing since - * the C++ Micro Services library will automatically unregister any registered services. - * @param context the context for the module. - */ - void Unload(ModuleContext* /*context*/) - { - // NOTE: The service is automatically unregistered - } - -}; - -US_EXPORT_MODULE_ACTIVATOR(DictionaryServiceModule, MyActivator) -//![Activator] - -#include - -US_INITIALIZE_MODULE("DictionaryServiceModule", "", "", "1.0.0") - -int main(int /*argc*/, char* /*argv*/[]) -{ - //![GetDictionaryService] - ServiceReference dictionaryServiceRef = GetModuleContext()->GetServiceReference(); - if (dictionaryServiceRef) - { - DictionaryService* dictionaryService = GetModuleContext()->GetService(dictionaryServiceRef); - if (dictionaryService) - { - std::cout << "Dictionary contains 'Tutorial': " << dictionaryService->checkWord("Tutorial") << std::endl; - } - } - //![GetDictionaryService] - return 0; -} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp deleted file mode 100644 index b46013fe89..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-modulecontext/main.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include - -//! [GetModuleContext] -#include -#include -#include - -US_USE_NAMESPACE - -void RetrieveModuleContext() -{ - ModuleContext* context = GetModuleContext(); - Module* module = context->GetModule(); - std::cout << "Module name: " << module->GetName() << " [id: " << module->GetModuleId() << "]\n"; -} -//! [GetModuleContext] - -//! [InitializeModule] -#include - -US_INITIALIZE_MODULE("My Module", "mylibname", "", "1.0.0") -//! [InitializeModule] - -int main(int /*argc*/, char* /*argv*/[]) -{ - RetrieveModuleContext(); - return 0; -} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp deleted file mode 100644 index 78674294d6..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-resources/main.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include -#include -#include -#include -#include -#include - -US_USE_NAMESPACE - -void resourceExample() -{ - //! [1] - // Get this module's Module object - Module* module = GetModuleContext()->GetModule(); - - ModuleResource resource = module->GetResource("config.properties"); - if (resource.IsValid()) - { - // Create a ModuleResourceStream object - ModuleResourceStream resourceStream(resource); - - // Read the contents line by line - std::string line; - while (std::getline(resourceStream, line)) - { - // Process the content - std::cout << line << std::endl; - } - } - else - { - // Error handling - } - //! [1] -} - -void parseComponentDefinition(std::istream&) -{ -} - -void extenderPattern() -{ - //! [2] - // Get all loaded modules - std::vector modules; - ModuleRegistry::GetLoadedModules(modules); - - // Check if a module defines a "service-component" property - // and use its value to retrieve an embedded resource containing - // a component description. - for(std::size_t i = 0; i < modules.size(); ++i) - { - Module* const module = modules[i]; - std::string componentPath = module->GetProperty("service-component"); - if (!componentPath.empty()) - { - ModuleResource componentResource = module->GetResource(componentPath); - if (!componentResource.IsValid() || componentResource.IsDir()) continue; - - // Create a std::istream compatible object and parse the - // component description. - ModuleResourceStream resStream(componentResource); - parseComponentDefinition(resStream); - } - } - //! [2] -} - -int main(int /*argc*/, char* /*argv*/[]) -{ - //! [0] - ModuleContext* moduleContext = GetModuleContext(); - Module* module = moduleContext->GetModule(); - - // List all XML files in the config directory - std::vector xmlFiles = module->FindResources("config", "*.xml", false); - - // Find the resource named vertex_shader.txt starting at the root directory - std::vector shaders = module->FindResources("", "vertex_shader.txt", true); - //! [0] - - return 0; -} - -#ifdef US_BUILD_SHARED_LIBS -#include -US_INITIALIZE_MODULE("uServices-snippet-resources", "", "", "1.0.0") -#endif diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp deleted file mode 100644 index 7b7e777626..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include "SingletonOne.h" - -#include "SingletonTwo.h" - -#include -#include - -#include -#include - -US_USE_NAMESPACE - -//![s1] -SingletonOne& SingletonOne::GetInstance() -{ - static SingletonOne instance; - return instance; -} -//![s1] - -SingletonOne::SingletonOne() : a(1) -{ -} - -//![s1d] -SingletonOne::~SingletonOne() -{ - std::cout << "SingletonTwo::b = " << SingletonTwo::GetInstance().b << std::endl; -} -//![s1d] - -//![ss1gi] -SingletonOneService* SingletonOneService::GetInstance() -{ - static ServiceReference serviceRef; - static ModuleContext* context = GetModuleContext(); - - if (!serviceRef) - { - // This is either the first time GetInstance() was called, - // or a SingletonOneService instance has not yet been registered. - serviceRef = context->GetServiceReference(); - } - - if (serviceRef) - { - // We have a valid service reference. It always points to the service - // with the lowest id (usually the one which was registered first). - // This still might return a null pointer, if all SingletonOneService - // instances have been unregistered (during unloading of the library, - // for example). - return context->GetService(serviceRef); - } - else - { - // No SingletonOneService instance was registered yet. - return 0; - } -} -//![ss1gi] - -SingletonOneService::SingletonOneService() - : a(1) -{ - SingletonTwoService* singletonTwoService = SingletonTwoService::GetInstance(); - assert(singletonTwoService != 0); - std::cout << "SingletonTwoService::b = " << singletonTwoService->b << std::endl; -} - -//![ss1d] -SingletonOneService::~SingletonOneService() -{ - SingletonTwoService* singletonTwoService = SingletonTwoService::GetInstance(); - - // The module activator must ensure that a SingletonTwoService instance is - // available during destruction of a SingletonOneService instance. - assert(singletonTwoService != 0); - std::cout << "SingletonTwoService::b = " << singletonTwoService->b << std::endl; -} -//![ss1d] diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h deleted file mode 100644 index a8aa153e56..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonOne.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef SINGLETONONE_H -#define SINGLETONONE_H - -#include -#include -#include -#include - -#include US_BASECLASS_HEADER - - -//![s1] -class SingletonOne -{ -public: - - static SingletonOne& GetInstance(); - - // Just some member - int a; - -private: - - SingletonOne(); - ~SingletonOne(); - - // Disable copy constructor and assignment operator. - SingletonOne(const SingletonOne&); - SingletonOne& operator=(const SingletonOne&); -}; -//![s1] - -class SingletonTwoService; - -//![ss1] -class SingletonOneService : public US_BASECLASS_NAME -{ -public: - - // This will return a SingletonOneService instance with the - // lowest service id at the time this method was called the first - // time and returned a non-null value (which is usually the instance - // which was registered first). A null-pointer is returned if no - // instance was registered yet. - static SingletonOneService* GetInstance(); - - int a; - -private: - - // Only our module activator class should be able to instantiate - // a SingletonOneService object. - friend class MyActivator; - - SingletonOneService(); - ~SingletonOneService(); - - // Disable copy constructor and assignment operator. - SingletonOneService(const SingletonOneService&); - SingletonOneService& operator=(const SingletonOneService&); -}; - -US_DECLARE_SERVICE_INTERFACE(SingletonOneService, "org.cppmicroservices.snippet.SingletonOneService") -//![ss1] - -#endif // SINGLETONONE_H diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp deleted file mode 100644 index 84aeab43d5..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include "SingletonTwo.h" - -#include "SingletonOne.h" -#include - -#include -#include - -US_USE_NAMESPACE - -SingletonTwo& SingletonTwo::GetInstance() -{ - static SingletonTwo instance; - return instance; -} - -SingletonTwo::SingletonTwo() : b(2) -{ - std::cout << "Constructing SingletonTwo" << std::endl; -} - -SingletonTwo::~SingletonTwo() -{ - std::cout << "Deleting SingletonTwo" << std::endl; - std::cout << "SingletonOne::a = " << SingletonOne::GetInstance().a << std::endl; -} - -SingletonTwoService* SingletonTwoService::GetInstance() -{ - static ServiceReference serviceRef; - static ModuleContext* context = GetModuleContext(); - - if (!serviceRef) - { - // This is either the first time GetInstance() was called, - // or a SingletonTwoService instance has not yet been registered. - serviceRef = context->GetServiceReference(); - } - - if (serviceRef) - { - // We have a valid service reference. It always points to the service - // with the lowest id (usually the one which was registered first). - // This still might return a null pointer, if all SingletonTwoService - // instances have been unregistered (during unloading of the library, - // for example). - return context->GetService(serviceRef); - } - else - { - // No SingletonTwoService instance was registered yet. - return 0; - } -} - -SingletonTwoService::SingletonTwoService() : b(2) -{ - std::cout << "Constructing SingletonTwoService" << std::endl; -} - -SingletonTwoService::~SingletonTwoService() -{ - std::cout << "Deleting SingletonTwoService" << std::endl; -} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h deleted file mode 100644 index ab5444a2cc..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/SingletonTwo.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef SINGLETONTWO_H -#define SINGLETONTWO_H - -#include -#include - -#include US_BASECLASS_HEADER - -class SingletonTwo -{ -public: - - static SingletonTwo& GetInstance(); - - int b; - -private: - - SingletonTwo(); - ~SingletonTwo(); - - // Disable copy constructor and assignment operator. - SingletonTwo(const SingletonTwo&); - SingletonTwo& operator=(const SingletonTwo&); -}; - -class SingletonTwoService : public US_BASECLASS_NAME -{ -public: - - static SingletonTwoService* GetInstance(); - - int b; - -private: - - friend class MyActivator; - - SingletonTwoService(); - ~SingletonTwoService(); - - // Disable copy constructor and assignment operator. - SingletonTwoService(const SingletonTwoService&); - SingletonTwoService& operator=(const SingletonTwoService&); -}; - -US_DECLARE_SERVICE_INTERFACE(SingletonTwoService, "org.cppmicroservices.snippet.SingletonTwoService") - -#endif // SINGLETONTWO_H diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake deleted file mode 100644 index 640356da1a..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/files.cmake +++ /dev/null @@ -1,11 +0,0 @@ - -set(snippet_src_files - main.cpp - SingletonOne.cpp - SingletonTwo.cpp -) - -usFunctionGenerateModuleInit(snippet_src_files - NAME "uServices_singleton" - EXECUTABLE - ) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp deleted file mode 100644 index 6d44cdab86..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-singleton/main.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include -#include -#include - -#include "SingletonOne.h" -#include "SingletonTwo.h" - -US_USE_NAMESPACE - -class MyActivator : public ModuleActivator -{ - -public: - - //![0] - void Load(ModuleContext* context) - { - // The Load() method of the module activator is called during static - // initialization time of the shared library. - - // First create and register a SingletonTwoService instance. - m_SingletonTwo = new SingletonTwoService; - m_SingletonTwoReg = context->RegisterService(m_SingletonTwo); - - // Now the SingletonOneService constructor will get a valid - // SingletonTwoService instance. - m_SingletonOne = new SingletonOneService; - m_SingletonOneReg = context->RegisterService(m_SingletonOne); - } - //![0] - - //![1] - void Unload(ModuleContext* /*context*/) - { - // Services are automatically unregistered during unloading of - // the shared library after the call to Unload(ModuleContext*) - // has returned. - - // Since SingletonOneService needs a non-null SingletonTwoService - // instance in its destructor, we explicitly unregister and delete the - // SingletonOneService instance here. This way, the SingletonOneService - // destructor will still get a valid SingletonTwoService instance. - m_SingletonOneReg.Unregister(); - delete m_SingletonOne; - - // For singletonTwoService, we could rely on the automatic unregistering - // by the service registry and on automatic deletion if you used - // smart pointer reference counting. You must not delete service instances - // in this method without unregistering them first. - m_SingletonTwoReg.Unregister(); - delete m_SingletonTwo; - } - //![1] - -private: - - SingletonOneService* m_SingletonOne; - SingletonTwoService* m_SingletonTwo; - - ServiceRegistration m_SingletonOneReg; - ServiceRegistration m_SingletonTwoReg; - -}; - -US_EXPORT_MODULE_ACTIVATOR(uServices_singleton, MyActivator) - -int main() -{ -} diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp deleted file mode 100644 index f63af3272a..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/MyStaticModule.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#include - -US_USE_NAMESPACE - -struct MyStaticModuleActivator : public ModuleActivator -{ - void Load(ModuleContext* /*context*/) - { - std::cout << "Hello from a static module." << std::endl; - } - - void Unload(ModuleContext* /*context*/) {} -}; - -US_EXPORT_MODULE_ACTIVATOR(MyStaticModule, MyStaticModuleActivator) - -US_INITIALIZE_MODULE("My Static Module", "MyStaticModule", "", "1.0.0") - diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake b/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake deleted file mode 100644 index 2bf4c05a4b..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/files.cmake +++ /dev/null @@ -1,11 +0,0 @@ -set(snippet_src_files - main.cpp -) - -set(base_dir uServices-staticmodules) -add_library(MyStaticModule STATIC ${base_dir}/MyStaticModule.cpp) -set_property(TARGET MyStaticModule APPEND PROPERTY COMPILE_DEFINITIONS US_STATIC_MODULE) - -set(snippet_link_libraries - MyStaticModule -) diff --git a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp b/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp deleted file mode 100644 index 13364d4d34..0000000000 --- a/Core/Code/CppMicroServices/documentation/snippets/uServices-staticmodules/main.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include - -US_USE_NAMESPACE - -//! [ImportStaticModuleIntoLib] -#include - -US_IMPORT_MODULE(MyStaticModule) -US_LOAD_IMPORTED_MODULES(HostingModule, MyStaticModule) -//! [ImportStaticModuleIntoLib] - -// This is just for illustration purposes in code snippets -extern "C" ModuleActivator* _us_module_activator_instance_MyStaticModule1() { return NULL; } -extern "C" ModuleActivator* _us_module_activator_instance_MyStaticModule2() { return NULL; } -extern "C" ModuleActivator* _us_init_resources_MyStaticModule2() { return NULL; } - -//! [ImportStaticModuleIntoMain] -#include - -US_IMPORT_MODULE(MyStaticModule1) -US_IMPORT_MODULE(MyStaticModule2) -US_IMPORT_MODULE_RESOURCES(MyStaticModule2) -US_LOAD_IMPORTED_MODULES_INTO_MAIN(MyStaticModule1 MyStaticModule2) -//! [ImportStaticModuleIntoMain] - -int main(int /*argc*/, char* /*argv*/[]) -{ - return 0; -} - -//! [InitializeExecutable] -#ifdef US_BUILD_SHARED_LIBS -#include -US_INITIALIZE_MODULE("MyExecutable", "", "", "1.0.0") -#endif -//! [InitializeExecutable] diff --git a/Core/Code/CppMicroServices/src/CMakeLists.txt b/Core/Code/CppMicroServices/src/CMakeLists.txt deleted file mode 100644 index 45a9814854..0000000000 --- a/Core/Code/CppMicroServices/src/CMakeLists.txt +++ /dev/null @@ -1,184 +0,0 @@ -#----------------------------------------------------------------------------- -# US source files -#----------------------------------------------------------------------------- - -set(_srcs - util/usAny.cpp - util/usUncompressResourceData.c - util/usUncompressResourceData.cpp - util/usThreads.cpp - util/usUtils.cpp - - service/usLDAPExpr.cpp - service/usLDAPFilter.cpp - service/usServiceException.cpp - service/usServiceEvent.cpp - service/usServiceListenerEntry.cpp - service/usServiceListenerEntry_p.h - service/usServiceListeners.cpp - service/usServiceListeners_p.h - service/usServiceProperties.cpp - service/usServiceReference.cpp - service/usServiceReferencePrivate.cpp - service/usServiceRegistration.cpp - service/usServiceRegistrationPrivate.cpp - service/usServiceRegistry.cpp - service/usServiceRegistry_p.h - - module/usCoreModuleContext_p.h - module/usCoreModuleContext.cpp - module/usModuleContext.cpp - module/usModule.cpp - module/usModuleEvent.cpp - module/usModuleInfo.cpp - module/usModulePrivate.cpp - module/usModuleRegistry.cpp - module/usModuleResource.cpp - module/usModuleResourceBuffer.cpp - module/usModuleResourceStream.cpp - module/usModuleResourceTree.cpp - module/usModuleSettings.cpp - module/usModuleUtils.cpp - module/usModuleVersion.cpp -) - -set(_private_headers - util/usAtomicInt_p.h - util/usFunctor_p.h - util/usStaticInit_p.h - util/usThreads_p.h - util/usUtils_p.h - - util/dirent_win32_p.h - util/stdint_p.h - util/stdint_vc_p.h - - service/usServiceTracker.tpp - service/usServiceTrackerPrivate.h - service/usServiceTrackerPrivate.tpp - service/usTrackedService_p.h - service/usTrackedServiceListener_p.h - service/usTrackedService.tpp - - module/usModuleAbstractTracked_p.h - module/usModuleAbstractTracked.tpp - module/usModuleResourceBuffer_p.h - module/usModuleResourceTree_p.h - module/usModuleUtils_p.h -) - -set(_public_headers - util/usAny.h - util/usSharedData.h - util/usUncompressResourceData.h - - service/usLDAPFilter.h - service/usServiceEvent.h - service/usServiceException.h - service/usServiceInterface.h - service/usServiceProperties.h - service/usServiceReference.h - service/usServiceRegistration.h - service/usServiceTracker.h - service/usServiceTrackerCustomizer.h - - module/usGetModuleContext.h - module/usModule.h - module/usModuleActivator.h - module/usModuleContext.h - module/usModuleEvent.h - module/usModuleImport.h - module/usModuleInfo.h - module/usModuleInitialization.h - module/usModuleRegistry.h - module/usModuleResource.h - module/usModuleResourceStream.h - module/usModuleSettings.h - module/usModuleVersion.h -) - -if(_us_baseclass_default) - list(APPEND _public_headers util/usBase.h) -endif() - -if(US_ENABLE_SERVICE_FACTORY_SUPPORT) - list(APPEND _public_headers service/usServiceFactory.h) -endif() - -if(US_IS_EMBEDDED) - set(US_SOURCES ) - get_filename_component(_path_prefix "${PROJECT_SOURCE_DIR}" NAME) - set(_path_prefix "${_path_prefix}/src") - foreach(_src ${_srcs} ${_public_headers} ${_private_headers}) - list(APPEND US_SOURCES ${_path_prefix}/${_src}) - endforeach() - set(US_SOURCES ${US_SOURCES} PARENT_SCOPE) -endif() - -#----------------------------------------------------------------------------- -# Create library (only if not in embedded mode) -#----------------------------------------------------------------------------- - -if(NOT US_IS_EMBEDDED) - include_directories(${US_INTERNAL_INCLUDE_DIRS}) - if(US_LINK_DIRS) - link_directories(${US_LINK_DIRS}) - endif() - - usFunctionGenerateModuleInit(_srcs NAME ${PROJECT_NAME} VERSION "0.9.0") - - add_library(${PROJECT_NAME} ${_srcs} - ${_public_headers} ${_private_headers} ${us_config_h_file}) - if(NOT US_IS_EMBEDDED AND US_LINK_FLAGS) - set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "${US_LINK_FLAGS}") - endif() - set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY COMPILE_DEFINITIONS US_FORCE_MODULE_INIT) - set_property(TARGET ${PROJECT_NAME} PROPERTY FRAMEWORK 1) - if(US_LINK_LIBRARIES) - target_link_libraries(${PROJECT_NAME} ${_link_libraries}) - endif() -endif() - -#----------------------------------------------------------------------------- -# Configure public header wrappers -#----------------------------------------------------------------------------- - -set(US_PUBLIC_HEADERS ${_public_headers}) -if(US_HEADER_PREFIX) - set(US_PUBLIC_HEADERS ) - foreach(_public_header ${_public_headers}) - get_filename_component(_public_header_basename ${_public_header} NAME_WE) - set(_us_public_header ${_public_header_basename}.h) - string(SUBSTRING "${_public_header_basename}" 2 -1 _public_header_basename) - set(_header_wrapper "${PROJECT_BINARY_DIR}/include/${US_HEADER_PREFIX}${_public_header_basename}.h") - configure_file(${PROJECT_SOURCE_DIR}/CMake/usPublicHeaderWrapper.h.in ${_header_wrapper} @ONLY) - list(APPEND US_PUBLIC_HEADERS ${_header_wrapper}) - endforeach() -endif() - -foreach(_header ${_public_headers} ${_private_headers}) - get_filename_component(_header_name "${_header}" NAME) - configure_file(${CMAKE_CURRENT_SOURCE_DIR}/${_header} "${PROJECT_BINARY_DIR}/include/${_header_name}") -endforeach() - -if(NOT US_IS_EMBEDDED) - set_property(TARGET ${PROJECT_NAME} PROPERTY PUBLIC_HEADER ${US_PUBLIC_HEADERS}) - set_property(TARGET ${PROJECT_NAME} PROPERTY PRIVATE_HEADER ${_private_headers} ${us_config_h_file}) -else() - set(US_PUBLIC_HEADERS ${US_PUBLIC_HEADERS} PARENT_SCOPE) - set(US_PRIVATE_HEADERS ${US_PRIVATE_HEADERS} PARENT_SCOPE) -endif() - -#----------------------------------------------------------------------------- -# Install support (only if not in embedded mode) -#----------------------------------------------------------------------------- - -if(NOT US_IS_EMBEDDED) - install(TARGETS ${PROJECT_NAME} FRAMEWORK DESTINATION . - RUNTIME DESTINATION bin - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib - PUBLIC_HEADER DESTINATION include - PRIVATE_HEADER DESTINATION include) -endif() - diff --git a/Core/Code/CppMicroServices/src/module/usCoreModuleContext.cpp b/Core/Code/CppMicroServices/src/module/usCoreModuleContext.cpp deleted file mode 100644 index b2d4d9896c..0000000000 --- a/Core/Code/CppMicroServices/src/module/usCoreModuleContext.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include -#include "usCoreModuleContext_p.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4355) -#endif - -US_BEGIN_NAMESPACE - -CoreModuleContext::CoreModuleContext() - : services(this) -{ -} - -CoreModuleContext::~CoreModuleContext() -{ -} - -US_END_NAMESPACE - -#ifdef _MSC_VER -#pragma warning(pop) -#endif diff --git a/Core/Code/CppMicroServices/src/module/usCoreModuleContext_p.h b/Core/Code/CppMicroServices/src/module/usCoreModuleContext_p.h deleted file mode 100644 index 7f230f9ee5..0000000000 --- a/Core/Code/CppMicroServices/src/module/usCoreModuleContext_p.h +++ /dev/null @@ -1,60 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USCOREMODULECONTEXT_H -#define USCOREMODULECONTEXT_H - -#include "usServiceListeners_p.h" -#include "usServiceRegistry_p.h" - -US_BEGIN_NAMESPACE - -/** - * This class is not part of the public API. - */ -class CoreModuleContext -{ -public: - - /** - * All listeners in this framework. - */ - ServiceListeners listeners; - - /** - * All registered services in this framework. - */ - ServiceRegistry services; - - /** - * Contruct a core context - * - */ - CoreModuleContext(); - - ~CoreModuleContext(); - -}; - -US_END_NAMESPACE - -#endif // USCOREMODULECONTEXT_H diff --git a/Core/Code/CppMicroServices/src/module/usGetModuleContext.h b/Core/Code/CppMicroServices/src/module/usGetModuleContext.h deleted file mode 100644 index b6b56971d6..0000000000 --- a/Core/Code/CppMicroServices/src/module/usGetModuleContext.h +++ /dev/null @@ -1,54 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USGETMODULECONTEXT_H -#define USGETMODULECONTEXT_H - -#include - -US_BEGIN_NAMESPACE - -class ModuleContext; - -/** - * \ingroup MicroServices - * - * \brief Returns the module context of the calling module. - * - * This function allows easy access to the ModuleContext instance from - * inside a C++ Micro Services module. - * - * \return The ModuleContext of the calling module. - * - * \internal - * - * Note that the corresponding function definition is provided for each - * module by the usModuleInit.cpp file. This file is customized via CMake - * configure_file(...) and automatically compiled into each module. - * Consequently, the GetModuleContext function is not exported, since each - * module gets its "own version". - */ -US_ABI_LOCAL ModuleContext* GetModuleContext(); - -US_END_NAMESPACE - -#endif // USGETMODULECONTEXT_H diff --git a/Core/Code/CppMicroServices/src/module/usModule.cpp b/Core/Code/CppMicroServices/src/module/usModule.cpp deleted file mode 100644 index dbe528c288..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModule.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usModule.h" - -#include "usModuleContext.h" -#include "usModuleActivator.h" -#include "usModulePrivate.h" -#include "usModuleResource.h" -#include "usModuleSettings.h" -#include "usCoreModuleContext_p.h" - - -US_BEGIN_NAMESPACE - -const std::string& Module::PROP_ID() -{ - static const std::string s("module.id"); - return s; -} -const std::string& Module::PROP_NAME() -{ - static const std::string s("module.name"); - return s; -} -const std::string& Module::PROP_LOCATION() -{ - static const std::string s("module.location"); - return s; -} -const std::string& Module::PROP_MODULE_DEPENDS() -{ - static const std::string s("module.module_depends"); - return s; -} -const std::string& Module::PROP_LIB_DEPENDS() -{ - static const std::string s("module.lib_depends"); - return s; -} -const std::string& Module::PROP_VERSION() -{ - static const std::string s("module.version"); - return s; -} - -Module::Module() -: d(0) -{ - -} - -Module::~Module() -{ - delete d; -} - -void Module::Init(CoreModuleContext* coreCtx, - ModuleInfo* info) -{ - ModulePrivate* mp = new ModulePrivate(this, coreCtx, info); - std::swap(mp, d); - delete mp; -} - -void Module::Uninit() -{ - if (d->moduleContext) - { - delete d->moduleContext; - d->moduleContext = 0; - } - d->moduleActivator = 0; -} - -bool Module::IsLoaded() const -{ - return d->moduleContext != 0; -} - -void Module::Start() -{ - - if (d->moduleContext) - { - US_WARN << "Module " << d->info.name << " already started."; - return; - } - - d->moduleContext = new ModuleContext(this->d); - -// try -// { - d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::LOADING, this)); - // try to get a ModuleActivator instance - if (d->info.activatorHook) - { - try - { - d->moduleActivator = d->info.activatorHook(); - } - catch (...) - { - US_ERROR << "Creating the module activator of " << d->info.name << " failed"; - throw; - } - - d->moduleActivator->Load(d->moduleContext); - } - - d->StartStaticModules(); - -#ifdef US_ENABLE_AUTOLOADING_SUPPORT - if (ModuleSettings::IsAutoLoadingEnabled()) - { - AutoLoadModules(d->info); - } -#endif - - d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::LOADED, this)); -// } -// catch (...) -// { -// d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADING, this)); -// d->RemoveModuleResources(); - -// delete d->moduleContext; -// d->moduleContext = 0; - -// d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); -// US_ERROR << "Calling the module activator Load() method of " << d->info.name << " failed!"; -// throw; -// } -} - -void Module::Stop() -{ - if (d->moduleContext == 0) - { - US_WARN << "Module " << d->info.name << " already stopped."; - return; - } - - try - { - d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADING, this)); - - d->StopStaticModules(); - - if (d->moduleActivator) - { - d->moduleActivator->Unload(d->moduleContext); - } - } - catch (...) - { - US_WARN << "Calling the module activator Unload() method of " << d->info.name << " failed!"; - - try - { - d->RemoveModuleResources(); - } - catch (...) {} - - delete d->moduleContext; - d->moduleContext = 0; - - d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); - - throw; - } - - d->RemoveModuleResources(); - delete d->moduleContext; - d->moduleContext = 0; - d->coreCtx->listeners.ModuleChanged(ModuleEvent(ModuleEvent::UNLOADED, this)); -} - -ModuleContext* Module::GetModuleContext() const -{ - return d->moduleContext; -} - -long Module::GetModuleId() const -{ - return d->info.id; -} - -std::string Module::GetLocation() const -{ - return d->info.location; -} - -std::string Module::GetName() const -{ - return d->info.name; -} - -ModuleVersion Module::GetVersion() const -{ - return d->version; -} - -std::string Module::GetProperty(const std::string& key) const -{ - if (d->properties.count(key) == 0) return ""; - return d->properties[key]; -} - -ModuleResource Module::GetResource(const std::string& path) const -{ - if (d->resourceTreePtrs.empty()) - { - return ModuleResource(); - } - - for (std::size_t i = 0; i < d->resourceTreePtrs.size(); ++i) - { - if (!d->resourceTreePtrs[i]->IsValid()) continue; - ModuleResource result(path, d->resourceTreePtrs[i], d->resourceTreePtrs); - if (result) return result; - } - return ModuleResource(); -} - -std::vector Module::FindResources(const std::string& path, const std::string& filePattern, - bool recurse) const -{ - std::vector result; - if (d->resourceTreePtrs.empty()) return result; - - for (std::size_t i = 0; i < d->resourceTreePtrs.size(); ++i) - { - if (!d->resourceTreePtrs[i]->IsValid()) continue; - - std::vector nodes; - d->resourceTreePtrs[i]->FindNodes(path, filePattern, recurse, nodes); - for (std::vector::iterator nodeIter = nodes.begin(); - nodeIter != nodes.end(); ++nodeIter) - { - result.push_back(ModuleResource(*nodeIter, d->resourceTreePtrs[i], d->resourceTreePtrs)); - } - } - return result; -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -std::ostream& operator<<(std::ostream& os, const Module& module) -{ - os << "Module[" << "id=" << module.GetModuleId() << - ", loc=" << module.GetLocation() << - ", name=" << module.GetName() << "]"; - return os; -} - -std::ostream& operator<<(std::ostream& os, Module const * module) -{ - return operator<<(os, *module); -} diff --git a/Core/Code/CppMicroServices/src/module/usModule.h b/Core/Code/CppMicroServices/src/module/usModule.h deleted file mode 100644 index de8aede10f..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModule.h +++ /dev/null @@ -1,267 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USMODULE_H -#define USMODULE_H - -#include "usModuleVersion.h" - -#include - -US_BEGIN_NAMESPACE - -class CoreModuleContext; -struct ModuleInfo; -class ModuleContext; -class ModuleResource; -class ModulePrivate; - -/** - * \ingroup MicroServices - * - * Represents a CppMicroServices module. - * - *

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

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

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

    - *
  • LOADED - *
  • UNLOADED - *
- *

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

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

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

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

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

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

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

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

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

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

- * This method continues to return this module's version while - * this module is in the UNLOADED state. - * - * @return The version of this module. - */ - ModuleVersion GetVersion() const; - - /** - * Returns the value of the specified property for this module. The - * method returns an empty string if the property is not found. - * - * @param key The name of the requested property. - * @return The value of the requested property, or an empty string - * if the property is undefined. - */ - std::string GetProperty(const std::string& key) const; - - /** - * Returns the resource at the specified \c path in this module. - * The specified \c path is always relative to the root of this module and may - * begin with '/'. A path value of "/" indicates the root of this module. - * - * \note In case of other modules being statically linked into this module, - * the \c path can be ambiguous and returns the first resource matching the - * provided \c path according to the order of the static module names in the - * #US_LOAD_IMPORTED_MODULES macro. - * - * @param path The path name of the resource. - * @return A ModuleResource object for the given \c path. If the \c path cannot - * be found in this module or the module's state is \c UNLOADED, an invalid - * ModuleResource object is returned. - */ - ModuleResource GetResource(const std::string& path) const; - - /** - * Returns resources in this module and its statically linked modules. - * - * This method is intended to be used to obtain configuration, setup, localization - * and other information from this module. - * - * This method can either return only resources in the specified \c path or recurse - * into subdirectories returning resources in the directory tree beginning at the - * specified path. - * - * Examples: - * \snippet uServices-resources/main.cpp 0 - * - * \note In case of modules statically linked into this module, the returned - * ModuleResource objects can represent the same resource path, coming from - * different static modules. The order of the ModuleResource objects in the - * returned container matches the order of the static module names in the - * #US_LOAD_IMPORTED_MODULES macro. - * - * @param path The path name in which to look. The path is always relative to the root - * of this module and may begin with '/'. A path value of "/" indicates the root of this module. - * @param filePattern The resource name pattern for selecting entries in the specified path. - * The pattern is only matched against the last element of the resource path. Substring - * matching is supported using the wildcard charachter ('*'). If \c filePattern is empty, - * this is equivalent to "*" and matches all resources. - * @param recurse If \c true, recurse into subdirectories. Otherwise only return resources - * from the specified path. - * @return A vector of ModuleResource objects for each matching entry. The objects are sorted - * such that resources from this module are returned first followed by the resources from - * statically linked modules in the load order as specified in #US_LOAD_IMPORTED_MODULES. - */ - std::vector FindResources(const std::string& path, const std::string& filePattern, bool recurse) const; - -private: - - friend class ModuleRegistry; - friend class ServiceReferencePrivate; - - ModulePrivate* d; - - Module(); - - void Init(CoreModuleContext* coreCtx, ModuleInfo* info); - void Uninit(); - - void Start(); - void Stop(); - - // purposely not implemented - Module(const Module &); - Module& operator=(const Module&); - -}; - -US_END_NAMESPACE - -/** - * \ingroup MicroServices - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(Module)& module); -/** - * \ingroup MicroServices - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, US_PREPEND_NAMESPACE(Module) const * module); - -#endif // USMODULE_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp b/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp deleted file mode 100644 index d344538f03..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked.tpp +++ /dev/null @@ -1,314 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -US_BEGIN_NAMESPACE - -template -const bool ModuleAbstractTracked::DEBUG_OUTPUT = false; - -template -ModuleAbstractTracked::ModuleAbstractTracked() -{ - closed = false; -} - -template -ModuleAbstractTracked::~ModuleAbstractTracked() -{ - -} - -template -void ModuleAbstractTracked::SetInitial(const std::list& initiallist) -{ - initial = initiallist; - - if (DEBUG_OUTPUT) - { - for(typename std::list::const_iterator item = initiallist.begin(); - item != initiallist.end(); ++item) - { - US_DEBUG << "ModuleAbstractTracked::setInitial: " << (*item); - } - } -} - -template -void ModuleAbstractTracked::TrackInitial() -{ - while (true) - { - S item(0); - { - typename Self::Lock l(this); - if (closed || (initial.size() == 0)) - { - /* - * if there are no more initial items - */ - return; /* we are done */ - } - /* - * move the first item from the initial list to the adding list - * within this synchronized block. - */ - item = initial.front(); - initial.pop_front(); - if (tracked[item]) - { - /* if we are already tracking this item */ - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackInitial[already tracked]: " << item; - continue; /* skip this item */ - } - if (std::find(adding.begin(), adding.end(), item) != adding.end()) - { - /* - * if this item is already in the process of being added. - */ - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackInitial[already adding]: " << item; - continue; /* skip this item */ - } - adding.push_back(item); - } - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackInitial: " << item; - TrackAdding(item, R()); - /* - * Begin tracking it. We call trackAdding - * since we have already put the item in the - * adding list. - */ - } -} - -template -void ModuleAbstractTracked::Close() -{ - closed = true; -} - -template -void ModuleAbstractTracked::Track(S item, R related) -{ - T object(0); - { - typename Self::Lock l(this); - if (closed) - { - return; - } - object = tracked[item]; - if (!object) - { /* we are not tracking the item */ - if (std::find(adding.begin(), adding.end(),item) != adding.end()) - { - /* if this item is already in the process of being added. */ - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::track[already adding]: " << item; - return; - } - adding.push_back(item); /* mark this item is being added */ - } - else - { /* we are currently tracking this item */ - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::track[modified]: " << item; - Modified(); /* increment modification count */ - } - } - - if (!object) - { /* we are not tracking the item */ - TrackAdding(item, related); - } - else - { - /* Call customizer outside of synchronized region */ - CustomizerModified(item, related, object); - /* - * If the customizer throws an unchecked exception, it is safe to - * let it propagate - */ - } -} - -template -void ModuleAbstractTracked::Untrack(S item, R related) -{ - T object(0); - { - typename Self::Lock l(this); - std::size_t initialSize = initial.size(); - initial.remove(item); - if (initialSize != initial.size()) - { /* if this item is already in the list - * of initial references to process - */ - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::untrack[removed from initial]: " << item; - return; /* we have removed it from the list and it will not be - * processed - */ - } - - std::size_t addingSize = adding.size(); - adding.remove(item); - if (addingSize != adding.size()) - { /* if the item is in the process of - * being added - */ - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::untrack[being added]: " << item; - return; /* - * in case the item is untracked while in the process of - * adding - */ - } - object = tracked[item]; - /* - * must remove from tracker before - * calling customizer callback - */ - tracked.erase(item); - if (!object) - { /* are we actually tracking the item */ - return; - } - Modified(); /* increment modification count */ - } - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::untrack[removed]: " << item; - /* Call customizer outside of synchronized region */ - CustomizerRemoved(item, related, object); - /* - * If the customizer throws an unchecked exception, it is safe to let it - * propagate - */ -} - -template -std::size_t ModuleAbstractTracked::Size() const -{ - return tracked.size(); -} - -template -bool ModuleAbstractTracked::IsEmpty() const -{ - return tracked.empty(); -} - -template -T ModuleAbstractTracked::GetCustomizedObject(S item) const -{ - typename TrackingMap::const_iterator i = tracked.find(item); - if (i != tracked.end()) return i->second; - return T(); -} - -template -void ModuleAbstractTracked::GetTracked(std::list& items) const -{ - for (typename TrackingMap::const_iterator i = tracked.begin(); - i != tracked.end(); ++i) - { - items.push_back(i->first); - } -} - -template -void ModuleAbstractTracked::Modified() -{ - trackingCount.Ref(); -} - -template -int ModuleAbstractTracked::GetTrackingCount() const -{ - return trackingCount; -} - -template -void ModuleAbstractTracked::CopyEntries(TrackingMap& map) const -{ - map.insert(tracked.begin(), tracked.end()); -} - -template -bool ModuleAbstractTracked::CustomizerAddingFinal(S item, const T& custom) -{ - typename Self::Lock l(this); - std::size_t addingSize = adding.size(); - adding.remove(item); - if (addingSize != adding.size() && !closed) - { - /* - * if the item was not untracked during the customizer - * callback - */ - if (custom) - { - tracked[item] = custom; - Modified(); /* increment modification count */ - this->NotifyAll(); /* notify any waiters */ - } - return false; - } - else - { - return true; - } -} - -template -void ModuleAbstractTracked::TrackAdding(S item, R related) -{ - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackAdding:" << item; - T object(0); - bool becameUntracked = false; - /* Call customizer outside of synchronized region */ - try - { - object = CustomizerAdding(item, related); - becameUntracked = this->CustomizerAddingFinal(item, object); - } - catch (...) - { - /* - * If the customizer throws an exception, it will - * propagate after the cleanup code. - */ - this->CustomizerAddingFinal(item, object); - throw; - } - - /* - * The item became untracked during the customizer callback. - */ - if (becameUntracked && object) - { - US_DEBUG(DEBUG_OUTPUT) << "ModuleAbstractTracked::trackAdding[removed]: " << item; - /* Call customizer outside of synchronized region */ - CustomizerRemoved(item, related, object); - /* - * If the customizer throws an unchecked exception, it is safe to - * let it propagate - */ - } -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h b/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h deleted file mode 100644 index ccdc3627d4..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleAbstractTracked_p.h +++ /dev/null @@ -1,291 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USMODULEABSTRACTTRACKED_H -#define USMODULEABSTRACTTRACKED_H - -#include - -#include "usAtomicInt_p.h" -#include "usAny.h" - -US_BEGIN_NAMESPACE - -/** - * This class is not intended to be used directly. It is exported to support - * the CppMicroServices module system. - * - * Abstract class to track items. If a Tracker is reused (closed then reopened), - * then a new ModuleAbstractTracked object is used. This class acts as a map of tracked - * item -> customized object. Subclasses of this class will act as the listener - * object for the tracker. This class is used to synchronize access to the - * tracked items. This is not a public class. It is only for use by the - * implementation of the Tracker class. - * - * @tparam S The tracked item. It is the key. - * @tparam T The value mapped to the tracked item. - * @tparam R The reason the tracked item is being tracked or untracked. - * @ThreadSafe - */ -template -class ModuleAbstractTracked : public US_DEFAULT_THREADING > -{ - -public: - - /* set this to true to compile in debug messages */ - static const bool DEBUG_OUTPUT; // = false; - - typedef std::map TrackingMap; - - /** - * ModuleAbstractTracked constructor. - */ - ModuleAbstractTracked(); - - virtual ~ModuleAbstractTracked(); - - /** - * Set initial list of items into tracker before events begin to be - * received. - * - * This method must be called from Tracker's open method while synchronized - * on this object in the same synchronized block as the add listener call. - * - * @param list The initial list of items to be tracked. null - * entries in the list are ignored. - * @GuardedBy this - */ - void SetInitial(const std::list& list); - - /** - * Track the initial list of items. This is called after events can begin to - * be received. - * - * This method must be called from Tracker's open method while not - * synchronized on this object after the add listener call. - * - */ - void TrackInitial(); - - /** - * Called by the owning Tracker object when it is closed. - */ - void Close(); - - /** - * Begin to track an item. - * - * @param item S to be tracked. - * @param related Action related object. - */ - void Track(S item, R related); - - /** - * Discontinue tracking the item. - * - * @param item S to be untracked. - * @param related Action related object. - */ - void Untrack(S item, R related); - - /** - * Returns the number of tracked items. - * - * @return The number of tracked items. - * - * @GuardedBy this - */ - std::size_t Size() const; - - /** - * Returns if the tracker is empty. - * - * @return Whether the tracker is empty. - * - * @GuardedBy this - */ - bool IsEmpty() const; - - /** - * Return the customized object for the specified item - * - * @param item The item to lookup in the map - * @return The customized object for the specified item. - * - * @GuardedBy this - */ - T GetCustomizedObject(S item) const; - - /** - * Return the list of tracked items. - * - * @return The tracked items. - * @GuardedBy this - */ - void GetTracked(std::list& items) const; - - /** - * Increment the modification count. If this method is overridden, the - * overriding method MUST call this method to increment the tracking count. - * - * @GuardedBy this - */ - virtual void Modified(); - - /** - * Returns the tracking count for this ServiceTracker object. - * - * The tracking count is initialized to 0 when this object is opened. Every - * time an item is added, modified or removed from this object the tracking - * count is incremented. - * - * @GuardedBy this - * @return The tracking count for this object. - */ - int GetTrackingCount() const; - - /** - * Copy the tracked items and associated values into the specified map. - * - * @param map The map into which to copy the tracked items and associated - * values. This map must not be a user provided map so that user code - * is not executed while synchronized on this. - * @return The specified map. - * @GuardedBy this - */ - void CopyEntries(TrackingMap& map) const; - - /** - * Call the specific customizer adding method. This method must not be - * called while synchronized on this object. - * - * @param item S to be tracked. - * @param related Action related object. - * @return Customized object for the tracked item or null if - * the item is not to be tracked. - */ - virtual T CustomizerAdding(S item, const R& related) = 0; - - /** - * Call the specific customizer modified method. This method must not be - * called while synchronized on this object. - * - * @param item Tracked item. - * @param related Action related object. - * @param object Customized object for the tracked item. - */ - virtual void CustomizerModified(S item, const R& related, - T object) = 0; - - /** - * Call the specific customizer removed method. This method must not be - * called while synchronized on this object. - * - * @param item Tracked item. - * @param related Action related object. - * @param object Customized object for the tracked item. - */ - virtual void CustomizerRemoved(S item, const R& related, - T object) = 0; - - /** - * List of items in the process of being added. This is used to deal with - * nesting of events. Since events may be synchronously delivered, events - * can be nested. For example, when processing the adding of a service and - * the customizer causes the service to be unregistered, notification to the - * nested call to untrack that the service was unregistered can be made to - * the track method. - * - * Since the std::vector implementation is not synchronized, all access to - * this list must be protected by the same synchronized object for - * thread-safety. - * - * @GuardedBy this - */ - std::list adding; - - /** - * true if the tracked object is closed. - * - * This field is volatile because it is set by one thread and read by - * another. - */ - volatile bool closed; - - /** - * Initial list of items for the tracker. This is used to correctly process - * the initial items which could be modified before they are tracked. This - * is necessary since the initial set of tracked items are not "announced" - * by events and therefore the event which makes the item untracked could be - * delivered before we track the item. - * - * An item must not be in both the initial and adding lists at the same - * time. An item must be moved from the initial list to the adding list - * "atomically" before we begin tracking it. - * - * Since the LinkedList implementation is not synchronized, all access to - * this list must be protected by the same synchronized object for - * thread-safety. - * - * @GuardedBy this - */ - std::list initial; - - /** - * Common logic to add an item to the tracker used by track and - * trackInitial. The specified item must have been placed in the adding list - * before calling this method. - * - * @param item S to be tracked. - * @param related Action related object. - */ - void TrackAdding(S item, R related); - -private: - - typedef ModuleAbstractTracked Self; - - /** - * Map of tracked items to customized objects. - * - * @GuardedBy this - */ - TrackingMap tracked; - - /** - * Modification count. This field is initialized to zero and incremented by - * modified. - * - * @GuardedBy this - */ - AtomicInt trackingCount; - - bool CustomizerAddingFinal(S item, const T& custom); - -}; - -US_END_NAMESPACE - -#include "usModuleAbstractTracked.tpp" - -#endif // USMODULEABSTRACTTRACKED_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleActivator.h b/Core/Code/CppMicroServices/src/module/usModuleActivator.h deleted file mode 100644 index c131c70ed5..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleActivator.h +++ /dev/null @@ -1,137 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USMODULEACTIVATOR_H_ -#define USMODULEACTIVATOR_H_ - -#include - -US_BEGIN_NAMESPACE - -class ModuleContext; - -/** - * \ingroup MicroServices - * - * Customizes the starting and stopping of a CppMicroServices module. - *

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

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

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

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

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

- * This method must complete and return to its caller in a timely manner. - * - * @param context The execution context of the module being unloaded. - * @throws std::exception If this method throws an exception, the - * module is still marked as unloaded, and the framework will remove - * the module's listeners, unregister all services registered by the - * module, and release all services used by the module. - */ - virtual void Unload(ModuleContext* context) = 0; - -}; - -US_END_NAMESPACE - -#define US_MODULE_ACTIVATOR_INSTANCE_FUNCTION(type) \ - struct ScopedPointer \ - { \ - ScopedPointer(US_PREPEND_NAMESPACE(ModuleActivator)* activator = 0) : m_Activator(activator) {} \ - ~ScopedPointer() { delete m_Activator; } \ - US_PREPEND_NAMESPACE(ModuleActivator)* m_Activator; \ - }; \ - \ - static ScopedPointer activatorPtr; \ - if (activatorPtr.m_Activator == 0) activatorPtr.m_Activator = new type; \ - return activatorPtr.m_Activator; - -/** - * \ingroup MicroServices - * - * \brief Export a module activator class. - * - * \param _module_libname The physical name of the module, without prefix or suffix. - * \param _activator_type The fully-qualified type-name of the module activator class. - * - * Call this macro after the definition of your module activator to make it - * accessible by the CppMicroServices library. - * - * Example: - * \snippet uServices-activator/main.cpp 0 - * - * \note If you use this macro in a source file compiled into an executable, additional - * requirements for the macro arguments apply: - * - The \c _module_libname argument must match the value of \c _module_name used in the - * \c #US_INITIALIZE_MODULE macro call. - */ -#define US_EXPORT_MODULE_ACTIVATOR(_module_libname, _activator_type) \ - extern "C" US_ABI_EXPORT US_PREPEND_NAMESPACE(ModuleActivator)* _us_module_activator_instance_ ## _module_libname () \ - { \ - US_MODULE_ACTIVATOR_INSTANCE_FUNCTION(_activator_type) \ - } - -#endif /* USMODULEACTIVATOR_H_ */ diff --git a/Core/Code/CppMicroServices/src/module/usModuleContext.cpp b/Core/Code/CppMicroServices/src/module/usModuleContext.cpp deleted file mode 100644 index 2164370632..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleContext.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include "usModuleContext.h" - -#include "usModuleRegistry.h" -#include "usModulePrivate.h" -#include "usCoreModuleContext_p.h" -#include "usServiceRegistry_p.h" -#include "usServiceReferencePrivate.h" - -US_BEGIN_NAMESPACE - -class ModuleContextPrivate { - -public: - - ModuleContextPrivate(ModulePrivate* module) - : module(module) - {} - - ModulePrivate* module; -}; - - -ModuleContext::ModuleContext(ModulePrivate* module) - : d(new ModuleContextPrivate(module)) -{} - -ModuleContext::~ModuleContext() -{ - delete d; -} - -Module* ModuleContext::GetModule() const -{ - return d->module->q; -} - -Module* ModuleContext::GetModule(long id) const -{ - return ModuleRegistry::GetModule(id); -} - -void ModuleContext::GetModules(std::vector& modules) const -{ - ModuleRegistry::GetModules(modules); -} - -ServiceRegistration ModuleContext::RegisterService(const std::list& clazzes, - US_BASECLASS_NAME* service, - const ServiceProperties& properties) -{ - return d->module->coreCtx->services.RegisterService(d->module, clazzes, service, properties); -} - -ServiceRegistration ModuleContext::RegisterService(const char* clazz, US_BASECLASS_NAME* service, - const ServiceProperties& properties) -{ - std::list clazzes; - clazzes.push_back(clazz); - return d->module->coreCtx->services.RegisterService(d->module, clazzes, service, properties); -} - -std::list ModuleContext::GetServiceReferences(const std::string& clazz, - const std::string& filter) -{ - std::list result; - d->module->coreCtx->services.Get(clazz, filter, 0, result); - return result; -} - -ServiceReference ModuleContext::GetServiceReference(const std::string& clazz) -{ - return d->module->coreCtx->services.Get(d->module, clazz); -} - -US_BASECLASS_NAME* ModuleContext::GetService(const ServiceReference& reference) -{ - if (!reference) - { - throw std::invalid_argument("Default constructed ServiceReference is not a valid input to getService()"); - } - ServiceReference internalRef(reference); - return internalRef.d->GetService(d->module->q); -} - -bool ModuleContext::UngetService(const ServiceReference& reference) -{ - ServiceReference ref = reference; - return ref.d->UngetService(d->module->q, true); -} - -void ModuleContext::AddServiceListener(const ServiceListener& delegate, - const std::string& filter) -{ - d->module->coreCtx->listeners.AddServiceListener(this, delegate, NULL, filter); -} - -void ModuleContext::RemoveServiceListener(const ServiceListener& delegate) -{ - d->module->coreCtx->listeners.RemoveServiceListener(this, delegate, NULL); -} - -void ModuleContext::AddModuleListener(const ModuleListener& delegate) -{ - d->module->coreCtx->listeners.AddModuleListener(this, delegate, NULL); -} - -void ModuleContext::RemoveModuleListener(const ModuleListener& delegate) -{ - d->module->coreCtx->listeners.RemoveModuleListener(this, delegate, NULL); -} - -void ModuleContext::AddServiceListener(const ServiceListener& delegate, void* data, - const std::string &filter) -{ - d->module->coreCtx->listeners.AddServiceListener(this, delegate, data, filter); -} - -void ModuleContext::RemoveServiceListener(const ServiceListener& delegate, void* data) -{ - d->module->coreCtx->listeners.RemoveServiceListener(this, delegate, data); -} - -void ModuleContext::AddModuleListener(const ModuleListener& delegate, void* data) -{ - d->module->coreCtx->listeners.AddModuleListener(this, delegate, data); -} - -void ModuleContext::RemoveModuleListener(const ModuleListener& delegate, void* data) -{ - d->module->coreCtx->listeners.RemoveModuleListener(this, delegate, data); -} - -US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/module/usModuleContext.h b/Core/Code/CppMicroServices/src/module/usModuleContext.h deleted file mode 100644 index 0138a27842..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleContext.h +++ /dev/null @@ -1,649 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USMODULECONTEXT_H_ -#define USMODULECONTEXT_H_ - -#include "usUtils_p.h" -#include "usServiceInterface.h" -#include "usServiceEvent.h" -#include "usServiceRegistration.h" -#include "usServiceException.h" -#include "usModuleEvent.h" - -US_BEGIN_NAMESPACE - -typedef US_SERVICE_LISTENER_FUNCTOR ServiceListener; -typedef US_MODULE_LISTENER_FUNCTOR ModuleListener; - -class ModuleContextPrivate; - -/** - * \ingroup MicroServices - * - * A module's execution context within the framework. The context is used to - * grant access to other methods so that this module can interact with the - * Micro Services Framework. - * - *

- * ModuleContext methods allow a module to: - *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

- * If the (receiver,callback) pair is not contained in this - * context module's list of listeners, this method does nothing. - * - * @tparam R The type of the receiver (containing the member function to be removed) - * @param receiver The object from which to disconnect. - * @param callback The member function pointer to remove. - * @throws std::logic_error If this ModuleContext is no - * longer valid. - * @see AddModuleListener() - */ - template - void RemoveModuleListener(R* receiver, void(R::*callback)(const ModuleEvent)) - { - RemoveModuleListener(ModuleListenerMemberFunctor(receiver, callback), - static_cast(receiver)); - } - - -private: - - friend class Module; - friend class ModulePrivate; - - ModuleContext(ModulePrivate* module); - - // purposely not implemented - ModuleContext(const ModuleContext&); - ModuleContext& operator=(const ModuleContext&); - - void AddServiceListener(const ServiceListener& delegate, void* data, - const std::string& filter); - void RemoveServiceListener(const ServiceListener& delegate, void* data); - - void AddModuleListener(const ModuleListener& delegate, void* data); - void RemoveModuleListener(const ModuleListener& delegate, void* data); - - ModuleContextPrivate * const d; -}; - -US_END_NAMESPACE - -#endif /* USMODULECONTEXT_H_ */ diff --git a/Core/Code/CppMicroServices/src/module/usModuleEvent.cpp b/Core/Code/CppMicroServices/src/module/usModuleEvent.cpp deleted file mode 100644 index bad71db5ad..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleEvent.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usModuleEvent.h" - -#include "usModule.h" - -US_BEGIN_NAMESPACE - -class ModuleEventData : public SharedData -{ -public: - - ModuleEventData(ModuleEvent::Type type, Module* module) - : type(type), module(module) - { - - } - - ModuleEventData(const ModuleEventData& other) - : SharedData(other), type(other.type), module(other.module) - { - - } - - const ModuleEvent::Type type; - Module* const module; - -private: - - // purposely not implemented - ModuleEventData& operator=(const ModuleEventData&); -}; - -ModuleEvent::ModuleEvent() - : d(0) -{ - -} - -ModuleEvent::~ModuleEvent() -{ - -} - -bool ModuleEvent::IsNull() const -{ - return !d; -} - -ModuleEvent::ModuleEvent(Type type, Module* module) - : d(new ModuleEventData(type, module)) -{ - -} - -ModuleEvent::ModuleEvent(const ModuleEvent& other) - : d(other.d) -{ - -} - -ModuleEvent& ModuleEvent::operator=(const ModuleEvent& other) -{ - d = other.d; - return *this; -} - -Module* ModuleEvent::GetModule() const -{ - return d->module; -} - -ModuleEvent::Type ModuleEvent::GetType() const -{ - return d->type; -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -std::ostream& operator<<(std::ostream& os, ModuleEvent::Type eventType) -{ - switch (eventType) - { - case ModuleEvent::LOADED: return os << "LOADED"; - case ModuleEvent::UNLOADED: return os << "UNLOADED"; - case ModuleEvent::LOADING: return os << "LOADING"; - case ModuleEvent::UNLOADING: return os << "UNLOADING"; - - default: return os << "Unknown module event type (" << static_cast(eventType) << ")"; - } -} - -std::ostream& operator<<(std::ostream& os, const ModuleEvent& event) -{ - if (event.IsNull()) return os << "NONE"; - - Module* m = event.GetModule(); - os << event.GetType() << " #" << m->GetModuleId() << " (" << m->GetLocation() << ")"; - return os; -} diff --git a/Core/Code/CppMicroServices/src/module/usModuleEvent.h b/Core/Code/CppMicroServices/src/module/usModuleEvent.h deleted file mode 100644 index 0e1f076758..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleEvent.h +++ /dev/null @@ -1,162 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USMODULEEVENT_H -#define USMODULEEVENT_H - -#include - -#include "usSharedData.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4251) -#endif - -US_BEGIN_NAMESPACE - -class Module; -class ModuleEventData; - -/** - * \ingroup MicroServices - * - * An event from the Micro Services framework describing a module lifecycle change. - *

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

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

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

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

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

    - *
  • {@link #LOADING} - *
  • {@link #LOADED} - *
  • {@link #UNLOADING} - *
  • {@link #UNLOADED} - *
- * - * @return The type of lifecycle event. - */ - Type GetType() const; - -}; - -US_END_NAMESPACE - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -/** - * \ingroup MicroServices - * @{ - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, US_PREPEND_NAMESPACE(ModuleEvent::Type) eventType); -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ModuleEvent)& event); -/** @}*/ - -#endif // USMODULEEVENT_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleImport.h b/Core/Code/CppMicroServices/src/module/usModuleImport.h deleted file mode 100644 index a5f7c99056..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleImport.h +++ /dev/null @@ -1,158 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USMODULEIMPORT_H -#define USMODULEIMPORT_H - -#include - -#include - -US_BEGIN_NAMESPACE - -struct ModuleActivator; - -US_END_NAMESPACE - -/** - * \ingroup MicroServices - * - * \brief Import a static module. - * - * \param _import_module_libname The physical name of the module to import, without prefix or suffix. - * - * This macro imports the static module named \c _import_module_libname. - * - * Inserting this macro into your application's source code will allow you to make use of - * a static module. Do not forget to list the imported module when calling the macro - * #US_LOAD_IMPORTED_MODULES and to actually link the static module to the importing - * executable or shared library. - * - * Example: - * \snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoLib - * - * \sa US_LOAD_IMPORTED_MODULES - * \sa \ref MicroServices_StaticModules - */ -#define US_IMPORT_MODULE(_import_module_libname) \ - extern "C" US_PREPEND_NAMESPACE(ModuleActivator)* _us_module_activator_instance_ ## _import_module_libname (); \ - void _dummy_reference_to_ ## _import_module_libname ## _activator() \ - { \ - _us_module_activator_instance_ ## _import_module_libname(); \ - } - -/** - * \ingroup MicroServices - * - * \brief Import a static module's resources. - * - * \param _import_module_libname The physical name of the module to import, without prefix or suffix. - * - * This macro imports the resources of the static module named \c _import_module_libname. - * - * Inserting this macro into your application's source code will allow you to make use of - * the resources embedded in a static module. Do not forget to list the imported module when - * calling the macro #US_LOAD_IMPORTED_MODULES and to actually link the static module to the - * importing executable or shared library. - * - * \sa US_IMPORT_MODULE - * \sa US_LOAD_IMPORTED_MODULES - * \sa \ref MicroServices_StaticModules - */ -#define US_IMPORT_MODULE_RESOURCES(_import_module_libname) \ - extern "C" US_PREPEND_NAMESPACE(ModuleActivator)* _us_init_resources_ ## _import_module_libname (); \ - void _dummy_reference_to_ ## _import_module_libname ## _init_resources() \ - { \ - _us_init_resources_ ## _import_module_libname(); \ - } - -/** - * \ingroup MicroServices - * \def US_LOAD_IMPORTED_MODULES_INTO_MAIN(_static_modules) - * - * \brief Import a list of static modules into an executable. - * - * \param _static_modules A space-deliminated list of physical module names, without prefix - * or suffix. - * - * This macro ensures that the ModuleActivator::Load(ModuleContext*) function is called - * for each imported static module when the importing executable is loaded (if the static - * module provides an activator). If the static module provides embedded resources and - * the US_IMPORT_MODULE_RESOURCES macro was called, the resources will be made available - * through the importing module. - * - * There must be exactly one call of this macro in the executable which is - * importing static modules. - * - * Example: - * \snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoMain - * - * \sa US_IMPORT_MODULE - * \sa US_LOAD_IMPORTED_MODULES - * \sa \ref MicroServices_StaticModules - */ - -#ifdef US_BUILD_SHARED_LIBS -#define US_LOAD_IMPORTED_MODULES_INTO_MAIN(_static_modules) \ - extern "C" US_ABI_EXPORT const char* _us_get_imported_modules_for_() \ - { \ - return #_static_modules; \ - } -#else -#define US_LOAD_IMPORTED_MODULES_INTO_MAIN(_static_modules) \ - extern "C" US_ABI_EXPORT const char* _us_get_imported_modules_for_CppMicroServices() \ - { \ - return #_static_modules; \ - } -#endif - -/** - * \ingroup MicroServices - * - * \brief Import a list of static modules into a shared library. - * - * \param _module_libname The physical name of the importing module, without prefix or suffix. - * \param _static_modules A space-deliminated list of physical module names, without prefix - * or suffix. - * - * This macro ensures that the ModuleActivator::Load(ModuleContext*) function is called - * for each imported static module when the importing shared library is loaded (if the static - * module provides an activator). If the static module provides embedded resources and - * the US_IMPORT_MODULE_RESOURCES macro was called, the resources will be made available - * through the importing module. - * - * There must be exactly one call of this macro in the shared library which is - * importing static modules. - * - * Example: - * \snippet uServices-staticmodules/main.cpp ImportStaticModuleIntoLib - * - * \sa US_IMPORT_MODULE - * \sa US_LOAD_IMPORTED_MODULES_INTO_MAIN - * \sa \ref MicroServices_StaticModules - */ -#define US_LOAD_IMPORTED_MODULES(_module_libname, _static_modules) \ - extern "C" US_ABI_EXPORT const char* _us_get_imported_modules_for_ ## _module_libname () \ - { \ - return #_static_modules; \ - } - -#endif // USMODULEREGISTRY_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleInfo.cpp b/Core/Code/CppMicroServices/src/module/usModuleInfo.cpp deleted file mode 100644 index 669c333b67..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleInfo.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usModuleInfo.h" - -US_BEGIN_NAMESPACE - -ModuleInfo::ModuleInfo(const std::string& name, const std::string& libName, - const std::string& autoLoadDir, const std::string& moduleDeps, - const std::string& version) - : name(name) - , libName(libName) - , moduleDeps(moduleDeps) - , version(version) - , autoLoadDir(autoLoadDir) - , id(0) - , activatorHook(NULL) -{} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleInfo.h b/Core/Code/CppMicroServices/src/module/usModuleInfo.h deleted file mode 100644 index da9da07803..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleInfo.h +++ /dev/null @@ -1,80 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USMODULEINFO_H -#define USMODULEINFO_H - -#include - -#include -#include - -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4251) -#endif - -US_BEGIN_NAMESPACE - -struct ModuleActivator; - -/** - * This class is not intended to be used directly. It is exported to support - * the CppMicroServices module system. - */ -struct US_EXPORT ModuleInfo -{ - ModuleInfo(const std::string& name, const std::string& libName, const std::string& autoLoadDir, - const std::string& moduleDeps, const std::string& version); - - typedef ModuleActivator*(*ModuleActivatorHook)(void); - typedef int(*InitResourcesHook)(ModuleInfo*); - typedef const unsigned char* ModuleResourceData; - - std::string name; - std::string libName; - std::string moduleDeps; - std::string version; - - std::string location; - - std::string autoLoadDir; - - long id; - - ModuleActivatorHook activatorHook; - - // In case of statically linked (imported) modules, there could - // be more than one set of ModuleResourceData pointers. We aggregate - // all pointers here. - std::vector resourceData; - std::vector resourceNames; - std::vector resourceTree; -}; - -US_END_NAMESPACE - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -#endif // USMODULEINFO_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleInitialization.h b/Core/Code/CppMicroServices/src/module/usModuleInitialization.h deleted file mode 100644 index 96b9a60b8f..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleInitialization.h +++ /dev/null @@ -1,170 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include -#include -#include -#include -#include - -#ifndef USMODULEINITIALIZATION_H -#define USMODULEINITIALIZATION_H - -/** - * \ingroup MicroServices - * - * \brief Creates initialization code for a module. - * - * Each module which wants to register itself with the CppMicroServices library - * has to put a call to this macro (or to #US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR) - * in one of its source files. - * - * Example call for a module with file-name "libmylibname.so". - * \code - * US_INITIALIZE_MODULE("My Service Implementation", "mylibname", "", "1.0.0") - * \endcode - * - * This will initialize the module for use with the CppMicroServices library, using a default - * auto-load directory named after the provided library name in \c _module_libname. - * - * \sa US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR - * - * \remarks If you are using CMake, consider using the provided CMake macro - * usFunctionGenerateModuleInit(). - * - * \param _module_name A human-readable name for the module. - * If you use this macro in a source file for an executable, the module name must - * be a valid C-identifier (no spaces etc.). - * \param _module_libname The physical name of the module, withou prefix or suffix. - * \param _module_depends A list of module dependencies. This is meta-data only. - * \param _module_version A version string in the form of "...". - * - * \note If you use this macro in a source file compiled into an executable, additional - * requirements for the macro arguments apply: - * - The \c _module_name argument must be a valid C-identifier (no spaces etc.). - * - The \c _module_libname argument must be an empty string. - * - */ -#define US_INITIALIZE_MODULE(_module_name, _module_libname, _module_depends, _module_version) \ - US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR(_module_name, _module_libname, _module_libname, _module_depends, _module_version) - -/** - * \ingroup MicroServices - * - * \brief Creates initialization code for a module using a custom auto-load directory. - * - * Each module which wants to register itself with the CppMicroServices library - * has to put a call to this macro (or to #US_INITIALIZE_MODULE) in one of its source files. - * - * Example call for a module with file-name "libmylibname.so". - * \code - * US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR("My Service Implementation", "mylibname", "autoload_mysublibs", "", "1.0.0") - * \endcode - * - * \remarks If you are using CMake, consider using the provided CMake macro - * usFunctionGenerateModuleInit(). - * - * \param _module_name A human-readable name for the module. - * If you use this macro in a source file for an executable, the module name must - * be a valid C-identifier (no spaces etc.). - * \param _module_libname The physical name of the module, withou prefix or suffix. - * \param _module_autoload_dir A directory name relative to this modules library location from which - * modules will be auto-loaded during activation of this module. Provide an empty string to - * disable auto-loading for this module. - * \param _module_depends A list of module dependencies. This is meta-data only. - * \param _module_version A version string in the form of "...". - */ -#define US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR(_module_name, _module_libname, _module_autoload_dir, _module_depends, _module_version) \ -US_BEGIN_NAMESPACE \ - \ -/* Declare a file scoped ModuleInfo object */ \ -US_GLOBAL_STATIC_WITH_ARGS(ModuleInfo, moduleInfo, (_module_name, _module_libname, _module_autoload_dir, _module_depends, _module_version)) \ - \ -/* This class is used to statically initialize the library within the C++ Micro services \ - library. It looks up a library specific C-style function returning an instance \ - of the ModuleActivator interface. */ \ -class US_ABI_LOCAL ModuleInitializer { \ - \ -public: \ - \ - ModuleInitializer() \ - { \ - std::string location = ModuleUtils::GetLibraryPath(moduleInfo()->libName, \ - reinterpret_cast(moduleInfo)); \ - std::string activator_func = "_us_module_activator_instance_"; \ - if(moduleInfo()->libName.empty()) \ - { \ - activator_func.append(moduleInfo()->name); \ - } \ - else \ - { \ - activator_func.append(moduleInfo()->libName); \ - } \ - \ - moduleInfo()->location = location; \ - \ - if (moduleInfo()->libName.empty()) \ - { \ - /* make sure we retrieve symbols from the executable, if "libName" is empty */ \ - location.clear(); \ - } \ - moduleInfo()->activatorHook = reinterpret_cast(ModuleUtils::GetSymbol(location, activator_func.c_str())); \ - \ - Register(); \ - } \ - \ - static void Register() \ - { \ - ModuleRegistry::Register(moduleInfo()); \ - } \ - \ - ~ModuleInitializer() \ - { \ - ModuleRegistry::UnRegister(moduleInfo()); \ - } \ - \ -}; \ - \ -US_ABI_LOCAL ModuleContext* GetModuleContext() \ -{ \ - /* make sure the module is registered */ \ - if (moduleInfo()->id == 0) \ - { \ - ModuleInitializer::Register(); \ - } \ - \ - return ModuleRegistry::GetModule(moduleInfo()->id)->GetModuleContext(); \ -} \ - \ -US_END_NAMESPACE \ - \ -static US_PREPEND_NAMESPACE(ModuleInitializer) _InitializeModule; - -// Static modules usually don't get initialization code. They are initialized within the -// module importing the static module(s). -#if defined(US_STATIC_MODULE) && !defined(US_FORCE_MODULE_INIT) -#undef US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR -#define US_INITIALIZE_MODULE_WITH_CUSTOM_AUTOLOADDIR(_a,_b,_c,_d,_e) -#endif - -#endif // USMODULEINITIALIZATION_H diff --git a/Core/Code/CppMicroServices/src/module/usModulePrivate.cpp b/Core/Code/CppMicroServices/src/module/usModulePrivate.cpp deleted file mode 100644 index 77e10d4464..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModulePrivate.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include "usModulePrivate.h" - -#include "usModule.h" -#include "usModuleActivator.h" -#include "usModuleUtils_p.h" -#include "usCoreModuleContext_p.h" -#include "usServiceRegistration.h" -#include "usServiceReferencePrivate.h" - -#include -#include -#include - -US_BEGIN_NAMESPACE - -AtomicInt ModulePrivate::idCounter; - -ModulePrivate::ModulePrivate(Module* qq, CoreModuleContext* coreCtx, - ModuleInfo* info) - : coreCtx(coreCtx) - , info(*info) - , moduleContext(0) - , moduleActivator(0) - , q(qq) -{ - // Parse the statically imported module library names - typedef const char*(*GetImportedModulesFunc)(void); - - std::string getImportedModulesSymbol("_us_get_imported_modules_for_"); - getImportedModulesSymbol += this->info.libName; - - std::string location = this->info.location; - if (this->info.libName.empty()) - { - /* make sure we retrieve symbols from the executable, if "libName" is empty */ - location.clear(); - } - - GetImportedModulesFunc getImportedModulesFunc = reinterpret_cast( - ModuleUtils::GetSymbol(location, getImportedModulesSymbol.c_str())); - if (getImportedModulesFunc != NULL) - { - std::string importedStaticModuleLibNames = getImportedModulesFunc(); - - std::istringstream iss(importedStaticModuleLibNames); - std::copy(std::istream_iterator(iss), std::istream_iterator(), - std::back_inserter >(this->staticModuleLibNames)); - } - - InitializeResources(location); - - std::stringstream propId; - propId << this->info.id; - properties[Module::PROP_ID()] = propId.str(); - - std::stringstream propModuleDepends; - std::stringstream propLibDepends; - - int counter = 0; - int counter2 = 0; - std::stringstream ss(this->info.moduleDeps); - while (ss) - { - std::string moduleDep; - ss >> moduleDep; - if (!moduleDep.empty()) - { - Module* dep = ModuleRegistry::GetModule(moduleDep); - if (dep) - { - requiresIds.push_back(dep->GetModuleId()); - if (counter > 0) propModuleDepends << ", "; - propModuleDepends << moduleDep; - ++counter; - } - else - { - requiresLibs.push_back(moduleDep); - if (counter2 > 0) propLibDepends << ", "; - propLibDepends << moduleDep; - ++counter2; - } - } - } - - properties[Module::PROP_MODULE_DEPENDS()] = propModuleDepends.str(); - properties[Module::PROP_LIB_DEPENDS()] = propLibDepends.str(); - - if (!this->info.version.empty()) - { - try - { - version = ModuleVersion(this->info.version); - properties[Module::PROP_VERSION()] = this->info.version; - } - catch (const std::exception& e) - { - throw std::invalid_argument(std::string("CppMicroServices module does not specify a valid version identifier. Got exception: ") + e.what()); - } - } - - properties[Module::PROP_LOCATION()] = this->info.location; - properties[Module::PROP_NAME()] = this->info.name; -} - -ModulePrivate::~ModulePrivate() -{ - delete moduleContext; - - for (std::size_t i = 0; i < this->resourceTreePtrs.size(); ++i) - { - delete resourceTreePtrs[i]; - } -} - -void ModulePrivate::RemoveModuleResources() -{ - coreCtx->listeners.RemoveAllListeners(moduleContext); - - std::list srs; - coreCtx->services.GetRegisteredByModule(this, srs); - for (std::list::iterator i = srs.begin(); - i != srs.end(); ++i) - { - try - { - i->Unregister(); - } - catch (const std::logic_error& /*ignore*/) - { - // Someone has unregistered the service after stop completed. - // This should not occur, but we don't want get stuck in - // an illegal state so we catch it. - } - } - - srs.clear(); - coreCtx->services.GetUsedByModule(q, srs); - for (std::list::const_iterator i = srs.begin(); - i != srs.end(); ++i) - { - i->GetReference().d->UngetService(q, false); - } - - for (std::size_t i = 0; i < resourceTreePtrs.size(); ++i) - { - resourceTreePtrs[i]->Invalidate(); - } -} - -void ModulePrivate::StartStaticModules() -{ - std::string location = this->info.location; - if (this->info.libName.empty()) - { - /* make sure we retrieve symbols from the executable, if "libName" is empty */ - location.clear(); - } - - for (std::vector::iterator i = staticModuleLibNames.begin(); - i != staticModuleLibNames.end(); ++i) - { - std::string staticActivatorSymbol = "_us_module_activator_instance_"; - staticActivatorSymbol += *i; - ModuleInfo::ModuleActivatorHook staticActivator = - reinterpret_cast(ModuleUtils::GetSymbol(location, staticActivatorSymbol.c_str())); - if (staticActivator) - { - US_DEBUG << "Loading static activator " << *i; - staticActivators.push_back(staticActivator); - staticActivator()->Load(moduleContext); - } - else - { - US_DEBUG << "Could not find an activator for the static module " << (*i) - << ". It propably does not provide an activator on purpose.\n Or you either " - "forgot a US_IMPORT_MODULE macro call in " << info.libName - << " or to link " << (*i) << " to " << info.libName << "."; - } - } - -} - -void ModulePrivate::StopStaticModules() -{ - for (std::list::iterator i = staticActivators.begin(); - i != staticActivators.end(); ++i) - { - (*i)()->Unload(moduleContext); - } -} - -void ModulePrivate::InitializeResources(const std::string& location) -{ - // Get the resource data from static modules and this module - std::vector moduleLibNames; - moduleLibNames.push_back(this->info.libName); - moduleLibNames.insert(moduleLibNames.end(), - this->staticModuleLibNames.begin(), this->staticModuleLibNames.end()); - - std::string initResourcesSymbolPrefix = "_us_init_resources_"; - for (std::size_t i = 0; i < moduleLibNames.size(); ++i) - { - std::string initResourcesSymbol = initResourcesSymbolPrefix + moduleLibNames[i]; - ModuleInfo::InitResourcesHook initResourcesFunc = reinterpret_cast( - ModuleUtils::GetSymbol(location, initResourcesSymbol.c_str())); - if (initResourcesFunc) - { - initResourcesFunc(&this->info); - } - } - - // Initialize this modules resource trees - assert(this->info.resourceData.size() == this->info.resourceNames.size()); - assert(this->info.resourceNames.size() == this->info.resourceTree.size()); - for (std::size_t i = 0; i < this->info.resourceData.size(); ++i) - { - resourceTreePtrs.push_back(new ModuleResourceTree(this->info.resourceTree[i], - this->info.resourceNames[i], - this->info.resourceData[i])); - } -} - -US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/module/usModulePrivate.h b/Core/Code/CppMicroServices/src/module/usModulePrivate.h deleted file mode 100644 index 6d1f4e4a07..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModulePrivate.h +++ /dev/null @@ -1,105 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USMODULEPRIVATE_H -#define USMODULEPRIVATE_H - -#include -#include - -#include "usModuleRegistry.h" -#include "usModuleVersion.h" -#include "usModuleInfo.h" -#include "usModuleResourceTree_p.h" - -#include "usAtomicInt_p.h" - -US_BEGIN_NAMESPACE - -class CoreModuleContext; -class ModuleContext; -struct ModuleActivator; - -/** - * \ingroup MicroServices - */ -class ModulePrivate { - -public: - - /** - * Construct a new module based on a ModuleInfo object. - */ - ModulePrivate(Module* qq, CoreModuleContext* coreCtx, ModuleInfo* info); - - virtual ~ModulePrivate(); - - void RemoveModuleResources(); - - void StartStaticModules(); - - void StopStaticModules(); - - CoreModuleContext* const coreCtx; - - std::vector requiresIds; - - std::vector requiresLibs; - - std::vector staticModuleLibNames; - - /** - * Module version - */ - ModuleVersion version; - - ModuleInfo info; - - std::vector resourceTreePtrs; - - /** - * ModuleContext for the module - */ - ModuleContext* moduleContext; - - ModuleActivator* moduleActivator; - - std::map properties; - - Module* const q; - -private: - - void InitializeResources(const std::string& location); - - std::list staticActivators; - - static AtomicInt idCounter; - - // purposely not implemented - ModulePrivate(const ModulePrivate&); - ModulePrivate& operator=(const ModulePrivate&); - -}; - -US_END_NAMESPACE - -#endif // USMODULEPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp b/Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp deleted file mode 100644 index 44060b559c..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleRegistry.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include "usModuleRegistry.h" - -#include "usModule.h" -#include "usModuleInfo.h" -#include "usModuleContext.h" -#include "usModuleActivator.h" -#include "usCoreModuleContext_p.h" -#include "usGetModuleContext.h" -#include "usStaticInit_p.h" - -#include -#include - - -US_BEGIN_NAMESPACE - -typedef Mutex MutexType; -typedef MutexLock MutexLocker; - -typedef US_UNORDERED_MAP_TYPE ModuleMap; - -US_GLOBAL_STATIC(CoreModuleContext, coreModuleContext) - -template -struct ModuleDeleter -{ - void operator()(GlobalStatic& globalStatic) const - { - ModuleMap* moduleMap = globalStatic.pointer; - for (ModuleMap::const_iterator i = moduleMap->begin(); - i != moduleMap->end(); ++i) - { - delete i->second; - } - DefaultGlobalStaticDeleter defaultDeleter; - defaultDeleter(globalStatic); - } -}; - -/** - * Table of all installed modules in this framework. - * Key is the module id. - */ -US_GLOBAL_STATIC_WITH_DELETER(ModuleMap, modules, ModuleDeleter) - -/** - * Lock for protecting the modules object - */ -US_GLOBAL_STATIC(MutexType, modulesLock) - -/** - * Lock for protecting the register count - */ -US_GLOBAL_STATIC(MutexType, countLock) - - -void ModuleRegistry::Register(ModuleInfo* info) -{ - static long regCount = 0; - if (info->id > 0) - { - // The module was already registered - Module* module = 0; - { - MutexLocker lock(*modulesLock()); - module = modules()->operator[](info->id); - assert(module != 0); - } - module->Start(); - } - else - { - Module* module = 0; - // check if the module is reloaded - { - MutexLocker lock(*modulesLock()); - ModuleMap* map = modules(); - for (ModuleMap::const_iterator i = map->begin(); - i != map->end(); ++i) - { - if (i->second->GetLocation() == info->location) - { - module = i->second; - info->id = module->GetModuleId(); - } - } - } - - if (!module) - { - module = new Module(); - countLock()->Lock(); - info->id = ++regCount; - countLock()->Unlock(); - - module->Init(coreModuleContext(), info); - - MutexLocker lock(*modulesLock()); - ModuleMap* map = modules(); - map->insert(std::make_pair(info->id, module)); - } - else - { - module->Init(coreModuleContext(), info); - } - - module->Start(); - } -} - -void ModuleRegistry::UnRegister(const ModuleInfo* info) -{ - // If we are unregistering the core module, we just call - // the module activators Unload() method (if there is a - // module activator). Since we cannot be sure that the - // ModuleContext for the core library is still valid, we - // just pass a null-pointer. Using the module context during - // static deinitalization time of the core library makes - // no sense anyway. - if (info->id == 1) - { - // Remove listeners from static modules if they have forgotten to do so - coreModuleContext()->listeners.RemoveAllListeners(GetModuleContext()); - - if (info->activatorHook) - { - info->activatorHook()->Unload(0); - } - return; - } - - Module* curr = 0; - { - MutexLocker lock(*modulesLock()); - curr = modules()->operator[](info->id); - assert(curr != 0); - } - - curr->Stop(); - - curr->Uninit(); -} - -Module* ModuleRegistry::GetModule(long id) -{ - MutexLocker lock(*modulesLock()); - - ModuleMap::const_iterator iter = modules()->find(id); - if (iter != modules()->end()) - { - return iter->second; - } - return 0; -} - -Module* ModuleRegistry::GetModule(const std::string& name) -{ - MutexLocker lock(*modulesLock()); - - ModuleMap::const_iterator iter = modules()->begin(); - ModuleMap::const_iterator iterEnd = modules()->end(); - for (; iter != iterEnd; ++iter) - { - if (iter->second->GetName() == name) - { - return iter->second; - } - } - - return 0; -} - -void ModuleRegistry::GetModules(std::vector& m) -{ - MutexLocker lock(*modulesLock()); - - ModuleMap* map = modules(); - ModuleMap::const_iterator iter = map->begin(); - ModuleMap::const_iterator iterEnd = map->end(); - for (; iter != iterEnd; ++iter) - { - m.push_back(iter->second); - } -} - -void ModuleRegistry::GetLoadedModules(std::vector& m) -{ - MutexLocker lock(*modulesLock()); - - ModuleMap::const_iterator iter = modules()->begin(); - ModuleMap::const_iterator iterEnd = modules()->end(); - for (; iter != iterEnd; ++iter) - { - if (iter->second->IsLoaded()) - { - m.push_back(iter->second); - } - } -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleRegistry.h b/Core/Code/CppMicroServices/src/module/usModuleRegistry.h deleted file mode 100644 index d9c8bd975b..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleRegistry.h +++ /dev/null @@ -1,92 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USMODULEREGISTRY_H -#define USMODULEREGISTRY_H - -#include -#include - -#include - -US_BEGIN_NAMESPACE - -class Module; -struct ModuleInfo; -struct ModuleActivator; - -/** - * \ingroup MicroServices - * - * Here we handle all the modules that are loaded in the framework. - */ -class US_EXPORT ModuleRegistry { - -public: - - /** - * Get the module that has the specified module identifier. - * - * @param id The identifier of the module to get. - * @return Module or null - * if the module was not found. - */ - static Module* GetModule(long id); - - /** - * Get the module that has specified module name. - * - * @param name The name of the module to get. - * @return Module or null. - */ - static Module* GetModule(const std::string& name); - - /** - * Get all known modules. - * - * @param modules A list which is filled with all known modules. - */ - static void GetModules(std::vector& modules); - - /** - * Get all modules currently in module state LOADED. - * - * @param modules A list which is filled with all modules in - * state LOADED - */ - static void GetLoadedModules(std::vector& modules); - -private: - - friend class ModuleInitializer; - - // disabled - ModuleRegistry(); - - static void Register(ModuleInfo* info); - - static void UnRegister(const ModuleInfo* info); - -}; - -US_END_NAMESPACE - -#endif // USMODULEREGISTRY_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleResource.cpp b/Core/Code/CppMicroServices/src/module/usModuleResource.cpp deleted file mode 100644 index 55215a0bda..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleResource.cpp +++ /dev/null @@ -1,271 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usModuleResource.h" - -#include "usAtomicInt_p.h" -#include "usModuleResourceTree_p.h" - -#include - -US_BEGIN_NAMESPACE - -class ModuleResourcePrivate -{ - -public: - - ModuleResourcePrivate() - : associatedResourceTree(NULL) - , node(-1) - , size(0) - , data(NULL) - , isFile(false) - , isCompressed(false) - , ref(1) - {} - - std::string fileName; - std::string path; - std::string filePath; - - std::vector resourceTrees; - const ModuleResourceTree* associatedResourceTree; - - int node; - int32_t size; - const unsigned char* data; - unsigned char* uncompressedData; - - mutable std::vector children; - - bool isFile; - bool isCompressed; - - /** - * Reference count for implicitly shared private implementation. - */ - AtomicInt ref; -}; - -ModuleResource::ModuleResource() - : d(new ModuleResourcePrivate) -{ -} - -ModuleResource::ModuleResource(const ModuleResource &resource) - : d(resource.d) -{ - d->ref.Ref(); -} - -ModuleResource::ModuleResource(const std::string& _file, ModuleResourceTree* associatedResourceTree, - const std::vector& resourceTrees) - : d(new ModuleResourcePrivate) -{ - d->resourceTrees = resourceTrees; - d->associatedResourceTree = associatedResourceTree; - - std::string file = _file; - if (file.empty()) file = "/"; - if (file[0] != '/') file = std::string("/") + file; - - std::size_t index = file.find_last_of('/'); - if (index < file.size()-1) - { - d->fileName = file.substr(index+1); - } - std::string rawPath = file.substr(0,index+1); - - // remove duplicate / - std::string::value_type lastChar = 0; - for (std::size_t i = 0; i < rawPath.size(); ++i) - { - if (rawPath[i] == '/' && lastChar == '/') - { - continue; - } - lastChar = rawPath[i]; - d->path.push_back(lastChar); - } - - d->filePath = d->path + d->fileName; - - d->node = d->associatedResourceTree->FindNode(GetResourcePath()); - if (d->node != -1) - { - d->isFile = !d->associatedResourceTree->IsDir(d->node); - if (d->isFile) - { - d->data = d->associatedResourceTree->GetData(d->node, &d->size); - d->isCompressed = d->associatedResourceTree->IsCompressed(d->node); - } - } -} - -ModuleResource::~ModuleResource() -{ - if (!d->ref.Deref()) - delete d; -} - -ModuleResource& ModuleResource::operator =(const ModuleResource& resource) -{ - ModuleResourcePrivate* curr_d = d; - d = resource.d; - d->ref.Ref(); - - if (!curr_d->ref.Deref()) - delete curr_d; - - return *this; -} - -bool ModuleResource::operator <(const ModuleResource& resource) const -{ - return this->GetResourcePath() < resource.GetResourcePath(); -} - -bool ModuleResource::operator ==(const ModuleResource& resource) const -{ - return d->associatedResourceTree == resource.d->associatedResourceTree && - this->GetResourcePath() == resource.GetResourcePath(); -} - -bool ModuleResource::operator !=(const ModuleResource &resource) const -{ - return !(*this == resource); -} - -bool ModuleResource::IsValid() const -{ - return d->associatedResourceTree && d->associatedResourceTree->IsValid() && d->node > -1; -} - -bool ModuleResource::IsCompressed() const -{ - return d->isCompressed; -} - -ModuleResource::operator bool() const -{ - return IsValid(); -} - -std::string ModuleResource::GetName() const -{ - return d->fileName; -} - -std::string ModuleResource::GetPath() const -{ - return d->path; -} - -std::string ModuleResource::GetResourcePath() const -{ - return d->filePath; -} - -std::string ModuleResource::GetBaseName() const -{ - return d->fileName.substr(0, d->fileName.find_first_of('.')); -} - -std::string ModuleResource::GetCompleteBaseName() const -{ - return d->fileName.substr(0, d->fileName.find_last_of('.')); -} - -std::string ModuleResource::GetSuffix() const -{ - std::size_t index = d->fileName.find_last_of('.'); - return index < d->fileName.size()-1 ? d->fileName.substr(index+1) : std::string(""); -} - -std::string ModuleResource::GetCompleteSuffix() const -{ - std::size_t index = d->fileName.find_first_of('.'); - return index < d->fileName.size()-1 ? d->fileName.substr(index+1) : std::string(""); -} - -bool ModuleResource::IsDir() const -{ - return !d->isFile; -} - -bool ModuleResource::IsFile() const -{ - return d->isFile; -} - -std::vector ModuleResource::GetChildren() const -{ - if (d->isFile || !IsValid()) return d->children; - - if (!d->children.empty()) return d->children; - - bool indexPastAssociatedResTree = false; - for (std::size_t i = 0; i < d->resourceTrees.size(); ++i) - { - if (d->resourceTrees[i] == d->associatedResourceTree) - { - indexPastAssociatedResTree = true; - d->associatedResourceTree->GetChildren(d->node, d->children); - } - else if (indexPastAssociatedResTree) - { - int nodeIndex = d->resourceTrees[i]->FindNode(GetPath()); - if (nodeIndex > -1) - { - d->resourceTrees[i]->GetChildren(d->node, d->children); - } - } - } - return d->children; -} - -int ModuleResource::GetSize() const -{ - return d->size; -} - -const unsigned char* ModuleResource::GetData() const -{ - if (!IsValid()) return NULL; - return d->data; -} - -std::size_t ModuleResource::Hash() const -{ - using namespace US_HASH_FUNCTION_NAMESPACE; - return US_HASH_FUNCTION(std::string, this->GetResourcePath()); -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -std::ostream& operator<<(std::ostream& os, const ModuleResource& resource) -{ - return os << resource.GetResourcePath(); -} diff --git a/Core/Code/CppMicroServices/src/module/usModuleResource.h b/Core/Code/CppMicroServices/src/module/usModuleResource.h deleted file mode 100644 index 9c6f4e9ec9..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleResource.h +++ /dev/null @@ -1,304 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USMODULERESOURCE_H -#define USMODULERESOURCE_H - -#include - -#include -#include - -US_MSVC_PUSH_DISABLE_WARNING(4396) - -US_BEGIN_NAMESPACE - -class ModuleResourcePrivate; -class ModuleResourceTree; - -/** - * \ingroup MicroServices - * - * Represents a resource (text file, image, etc.) embedded in a CppMicroServices module. - * - * A \c %ModuleResource object provides information about a resource (external file) which - * was embedded into this module's shared library. \c %ModuleResource objects can be obtained - * be calling Module#GetResource or Module#FindResources. - * - * Example code for retreiving a resource object and reading its contents: - * \snippet uServices-resources/main.cpp 1 - * - * %ModuleResource objects have value semantics and copies are very inexpensive. - * - * \see ModuleResourceStream - * \see \ref MicroServices_Resources - */ -class US_EXPORT ModuleResource -{ - -public: - - /** - * Creates in invalid %ModuleResource object. - */ - ModuleResource(); - /** - * Copy constructor. - * @param resource The object to be copied. - */ - ModuleResource(const ModuleResource& resource); - - ~ModuleResource(); - - /** - * Assignment operator. - * - * @param resource The %ModuleResource object which is assigned to this instance. - * @return A reference to this %ModuleResource instance. - */ - ModuleResource& operator=(const ModuleResource& resource); - - /** - * A less then operator using the full resource path as returned by - * GetResourcePath() to define the ordering. - * - * @param resource The object to which this %ModuleResource object is compared to. - * @return \c true if this %ModuleResource object is less then \c resource, - * \c false otherwise. - */ - bool operator<(const ModuleResource& resource) const; - - /** - * Equality operator for %ModuleResource objects. - * - * @param resource The object for testing equality. - * @return \c true if this %ModuleResource object is equal to \c resource, i.e. - * they are coming from the same module (shared or static) and have an equal - * resource path, \c false otherwise. - */ - bool operator==(const ModuleResource& resource) const; - - /** - * Inequality operator for %ModuleResource objects. - * - * @param resource The object for testing inequality. - * @return The result of !(*this == resource). - */ - bool operator!=(const ModuleResource& resource) const; - - /** - * Tests this %ModuleResource object for validity. - * - * Invalid %ModuleResource objects are created by the default constructor or - * can be returned by the Module class if the resource path is not found. If a - * module from which %ModuleResource objects have been obtained is un-loaded, - * these objects become invalid. - * - * @return \c true if this %ModuleReource object is valid and can safely be used, - * \c false otherwise. - */ - bool IsValid() const; - - /** - * Returns \c true if the resource represents a file and the resource data - * is in a compressed format, \c false otherwise. - * - * @return \c true if the resource data is compressed, \c false otherwise. - */ - bool IsCompressed() const; - - /** - * Boolean conversion operator using IsValid(). - */ - operator bool() const; - - /** - * Returns the name of the resource, excluding the path. - * - * Example: - * \code - * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); - * std::string name = resource.GetName(); // name = "archive.tar.gz" - * \endcode - * - * @return The resource name. - * @see GetPath(), GetResourcePath() - */ - std::string GetName() const; - - /** - * Returns the resource's path, without the file name. - * - * Example: - * \code - * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); - * std::string path = resource.GetPath(); // path = "/data" - * \endcode - * - * @return The resource path without the name. - * @see GetResourcePath(), GetName() and IsDir() - */ - std::string GetPath() const; - - /** - * Returns the resource name including the path. - * - * @return The resource path include the name. - * @see GetPath(), GetName() and IsDir() - */ - std::string GetResourcePath() const; - - /** - * Returns the base name of the resource without the path. - * - * Example: - * \code - * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); - * std::string base = resource.GetBaseName(); // base = "archive" - * \endcode - * - * @return The resource base name. - * @see GetName(), GetSuffix(), GetCompleteSuffix() and GetCompleteBaseName() - */ - std::string GetBaseName() const; - - /** - * Returns the complete base name of the resource without the path. - * - * Example: - * \code - * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); - * std::string base = resource.GetCompleteBaseName(); // base = "archive.tar" - * \endcode - * - * @return The resource's complete base name. - * @see GetName(), GetSuffix(), GetCompleteSuffix(), and GetBaseName() - */ - std::string GetCompleteBaseName() const; - - /** - * Returns the suffix of the resource. - * - * The suffix consists of all characters in the resource name after (but not - * including) the last '.'. - * - * Example: - * \code - * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); - * std::string suffix = resource.GetSuffix(); // suffix = "gz" - * \endcode - * - * @return The resource name suffix. - * @see GetName(), GetCompleteSuffix(), GetBaseName() and GetCompleteBaseName() - */ - std::string GetSuffix() const; - - /** - * Returns the complete suffix of the resource. - * - * The suffix consists of all characters in the resource name after (but not - * including) the first '.'. - * - * Example: - * \code - * ModuleResource resource = module->GetResource("/data/archive.tar.gz"); - * std::string suffix = resource.GetCompleteSuffix(); // suffix = "tar.gz" - * \endcode - * - * @return The resource name suffix. - * @see GetName(), GetSuffix(), GetBaseName(), and GetCompleteBaseName() - */ - std::string GetCompleteSuffix() const; - - /** - * Returns \c true if this %ModuleResource object points to a directory and thus - * may have child resources. - * - * @return \c true if this object points to a directory, \c false otherwise. - */ - bool IsDir() const; - - /** - * Returns \c true if this %ModuleResource object points to a file resource. - * - * @return \c true if this object points to an embedded file, \c false otherwise. - */ - bool IsFile() const; - - /** - * Returns a list of resource names which are children of this object. - * - * The returned names are relative to the path of this %ModuleResource object and - * may contain duplicates in case of modules which are statically linked into the - * module from which this object was retreived. - * - * @return A list of child resource names. - */ - std::vector GetChildren() const; - - /** - * Returns the size of the raw embedded data for this %ModuleResource object. - * - * @return The resource data size. - */ - int GetSize() const; - - /** - * Returns a data pointer pointing to the raw data of this %ModuleResource object. - * If the resource is compressed the data returned is compressed and UncompressResourceData() - * must be used to access the data. If the resource represents a directory \c 0 is returned. - * - * @return A raw pointer to the embedded data, or \c 0 if the resource is not a file resource. - */ - const unsigned char* GetData() const; - -private: - - ModuleResource(const std::string& file, ModuleResourceTree* resourceTree, - const std::vector& resourceTrees); - - friend class Module; - - US_HASH_FUNCTION_FRIEND(ModuleResource); - - std::size_t Hash() const; - - ModuleResourcePrivate* d; - -}; - -US_END_NAMESPACE - -US_MSVC_POP_WARNING - -/** - * \ingroup MicroServices - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ModuleResource)& resource); - -US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ModuleResource)) - return arg.Hash(); -US_HASH_FUNCTION_END -US_HASH_FUNCTION_NAMESPACE_END - -#endif // USMODULERESOURCE_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer.cpp b/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer.cpp deleted file mode 100644 index 214ef231b8..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer.cpp +++ /dev/null @@ -1,305 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "usModuleResourceBuffer_p.h" -#include "usUncompressResourceData.h" - -#include "stdint_p.h" - -#include -#include - -#ifdef US_PLATFORM_WINDOWS -#define DATA_NEEDS_NEWLINE_CONVERSION 1 -#undef REMOVE_LAST_NEWLINE_IN_TEXT_MODE -#else -#undef DATA_NEEDS_NEWLINE_CONVERSION -#define REMOVE_LAST_NEWLINE_IN_TEXT_MODE 1 -#endif - -US_BEGIN_NAMESPACE - -static const std::size_t BUFFER_SIZE = 1024; - -class ModuleResourceBufferPrivate -{ -public: - - ModuleResourceBufferPrivate(const char* begin, std::size_t size, std::ios_base::openmode mode) - : begin(begin) - , end(begin + size) - , current(begin) - , mode(mode) - #ifdef US_ENABLE_RESOURCE_COMPRESSION - , uncompressedData(NULL) - #endif - #ifdef DATA_NEEDS_NEWLINE_CONVERSION - , pos(0) - #endif - { - } - - ~ModuleResourceBufferPrivate() - { -#ifdef US_ENABLE_RESOURCE_COMPRESSION - delete[] uncompressedData; -#endif - } - - const char* const begin; - const char* const end; - const char* current; - - const std::ios_base::openmode mode; - -#ifdef US_ENABLE_RESOURCE_COMPRESSION - const unsigned char* uncompressedData; -#endif - -#ifdef DATA_NEEDS_NEWLINE_CONVERSION - // records the stream position ignoring CR characters - std::streambuf::pos_type pos; -#endif - -}; - -ModuleResourceBuffer::ModuleResourceBuffer(const unsigned char* data, std::size_t _size, - std::ios_base::openmode mode, bool compressed) - : d(NULL) -{ - assert(_size < static_cast(std::numeric_limits::max())); - // assert(data != NULL); - - if (compressed && _size) - { -#ifdef US_ENABLE_RESOURCE_COMPRESSION - data = UncompressResourceData(data, _size, &_size); -#else - assert(!"CppMicroServices built without support for resource compression"); -#endif - } - - const char* begin = reinterpret_cast(data); - std::size_t size = _size; - -#ifdef DATA_NEEDS_NEWLINE_CONVERSION - if (data != NULL && !(mode & std::ios_base::binary) && begin[0] == '\r') - { - ++begin; - --size; - } -#endif - -#ifdef REMOVE_LAST_NEWLINE_IN_TEXT_MODE - if (data != NULL && !(mode & std::ios_base::binary) && begin[size-1] == '\n') - { - --size; - } -#endif - - d = new ModuleResourceBufferPrivate(begin, size, mode); -#ifdef US_ENABLE_RESOURCE_COMPRESSION - if (compressed) - { - d->uncompressedData = data; - } -#endif -} - -ModuleResourceBuffer::~ModuleResourceBuffer() -{ - delete d; -} - -ModuleResourceBuffer::int_type ModuleResourceBuffer::underflow() -{ - if (d->current == d->end) - return traits_type::eof(); - -#ifdef DATA_NEEDS_NEWLINE_CONVERSION - char c = *d->current; - if (!(d->mode & std::ios_base::binary)) - { - if (c == '\r') - { - if (d->current + 1 == d->end) - { - return traits_type::eof(); - } - c = d->current[1]; - } - } - return traits_type::to_int_type(c); -#else - return traits_type::to_int_type(*d->current); -#endif -} - -ModuleResourceBuffer::int_type ModuleResourceBuffer::uflow() -{ - if (d->current == d->end) - return traits_type::eof(); - -#ifdef DATA_NEEDS_NEWLINE_CONVERSION - char c = *d->current++; - if (!(d->mode & std::ios_base::binary)) - { - if (c == '\r') - { - if (d->current == d->end) - { - return traits_type::eof(); - } - c = *d->current++; - } - } - return traits_type::to_int_type(c); -#else - return traits_type::to_int_type(*d->current++); -#endif -} - -ModuleResourceBuffer::int_type ModuleResourceBuffer::pbackfail(int_type ch) -{ - int backOffset = -1; -#ifdef DATA_NEEDS_NEWLINE_CONVERSION - if (!(d->mode & std::ios_base::binary)) - { - while ((d->current - backOffset) >= d->begin && d->current[backOffset] == '\r') - { - --backOffset; - } - // d->begin always points to a character != '\r' - } -#endif - if (d->current == d->begin || (ch != traits_type::eof() && ch != d->current[backOffset])) - { - return traits_type::eof(); - } - - d->current += backOffset; - return traits_type::to_int_type(*d->current); -} - -std::streamsize ModuleResourceBuffer::showmanyc() -{ - assert(d->current <= d->end); - -#ifdef DATA_NEEDS_NEWLINE_CONVERSION - std::streamsize ssize = 0; - std::size_t chunkSize = d->end - d->current; - for (std::size_t i = 0; i < chunkSize; ++i) - { - if (d->current[i] != '\r') - { - ++ssize; - } - } - return ssize; -#else - return d->end - d->current; -#endif -} - -std::streambuf::pos_type ModuleResourceBuffer::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*which*/) -{ -#ifdef DATA_NEEDS_NEWLINE_CONVERSION - std::streambuf::off_type step = 1; - if (way == std::ios_base::beg) - { - d->current = d->begin; - } - else if (way == std::ios_base::end) - { - d->current = d->end; - step = -1; - } - - if (!(d->mode & std::ios_base::binary)) - { - if (way == std::ios_base::beg) - { - d->pos = 0; - } - else if (way == std::ios_base::end) - { - d->current -= 1; - } - - std::streambuf::off_type i = 0; - // scan through off amount of characters excluding '\r' - while (i != off) - { - if (*d->current != '\r') - { - i += step; - d->pos += step; - } - d->current += step; - } - - // adjust the position in case of a "backwards" seek - if (way == std::ios_base::end) - { - // fix pointer from previous while loop - d->current += 1; - d->pos = 0; - i = 0; - const std::streampos currInternalPos = d->current - d->begin; - while (i != currInternalPos) - { - if (d->begin[i] != '\r') - { - d->pos += 1; - } - ++i; - } - } - } - else - { - d->current += off; - d->pos = d->current - d->begin; - } - return d->pos; -#else - if (way == std::ios_base::beg) - { - d->current = d->begin + off; - return off; - } - else if (way == std::ios_base::cur) - { - d->current += off; - return d->current - d->begin; - } - else - { - d->current = d->end + off; - return d->current - d->begin; - } -#endif -} - -std::streambuf::pos_type ModuleResourceBuffer::seekpos(std::streambuf::pos_type sp, - std::ios_base::openmode /*which*/) -{ - return this->seekoff(sp, std::ios_base::beg); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer_p.h b/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer_p.h deleted file mode 100644 index 95797022d4..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleResourceBuffer_p.h +++ /dev/null @@ -1,63 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef USMODULERESOURCEBUFFER_P_H -#define USMODULERESOURCEBUFFER_P_H - -#include - -#include - -US_BEGIN_NAMESPACE - -class ModuleResourceBufferPrivate; - -class US_EXPORT ModuleResourceBuffer: public std::streambuf -{ - -public: - - explicit ModuleResourceBuffer(const unsigned char* data, std::size_t size, - std::ios_base::openmode mode, bool compressed); - - ~ModuleResourceBuffer(); - -private: - - int_type underflow(); - - int_type uflow(); - - int_type pbackfail(int_type ch); - - std::streamsize showmanyc(); - - pos_type seekoff (off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out); - pos_type seekpos (pos_type sp, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out); - - // purposely not implemented - ModuleResourceBuffer(const ModuleResourceBuffer&); - ModuleResourceBuffer& operator=(const ModuleResourceBuffer&); - -private: - - ModuleResourceBufferPrivate* d; - -}; - -US_END_NAMESPACE - -#endif // USMODULERESOURCEBUFFER_P_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceStream.cpp b/Core/Code/CppMicroServices/src/module/usModuleResourceStream.cpp deleted file mode 100644 index fd6fa8a448..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleResourceStream.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "usModuleResourceStream.h" - -#include "usModuleResource.h" - -// 'this' used in base member initializer list -US_MSVC_PUSH_DISABLE_WARNING(4355) - -US_BEGIN_NAMESPACE - -ModuleResourceStream::ModuleResourceStream(const ModuleResource& resource, std::ios_base::openmode mode) - : ModuleResourceBuffer(resource.GetData(), resource.GetSize(), mode | std::ios_base::in, - resource.IsCompressed()) - , std::istream(this) -{ -} - -US_END_NAMESPACE - -US_MSVC_POP_WARNING diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceStream.h b/Core/Code/CppMicroServices/src/module/usModuleResourceStream.h deleted file mode 100644 index 7c4610e1dc..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleResourceStream.h +++ /dev/null @@ -1,65 +0,0 @@ -/*=================================================================== - -BlueBerry Platform - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef USMODULERESOURCESTREAM_H -#define USMODULERESOURCESTREAM_H - -#include "usModuleResourceBuffer_p.h" - -#include - -US_BEGIN_NAMESPACE - -class ModuleResource; - -/** - * \ingroup MicroServices - * - * An input stream class for ModuleResource objects. - * - * This class provides access to the resource data embedded in a module's - * shared library via a STL input stream interface. - * - * \see ModuleResource for an example how to use this class. - */ -class US_EXPORT ModuleResourceStream : private ModuleResourceBuffer, public std::istream -{ - -public: - - /** - * Construct a %ModuleResourceStream object. - * - * @param resource The ModuleResource object for which an input stream - * should be constructed. - * @param mode The open mode of the stream. If \c std::ios_base::binary - * is used, the resource data will be treated as binary data, otherwise - * the data is interpreted as text data and the usual platform specific - * end-of-line translations take place. - */ - ModuleResourceStream(const ModuleResource& resource, - std::ios_base::openmode mode = std::ios_base::in); - -private: - - // purposely not implemented - ModuleResourceStream(const ModuleResourceStream&); - ModuleResourceStream& operator=(const ModuleResourceStream&); -}; - -US_END_NAMESPACE - -#endif // USMODULERESOURCESTREAM_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceTree.cpp b/Core/Code/CppMicroServices/src/module/usModuleResourceTree.cpp deleted file mode 100644 index 3c760e91a8..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleResourceTree.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usModuleResourceTree_p.h" - -#include "usUtils_p.h" -#include "stdint_p.h" - -#include -#include - -//#define DEBUG_RESOURCE_MATCH - -US_BEGIN_NAMESPACE - -US_EXPORT bool RegisterResourceData(int, ModuleInfo* moduleInfo, - ModuleInfo::ModuleResourceData resourceTree, - ModuleInfo::ModuleResourceData resourceNames, - ModuleInfo::ModuleResourceData resourceData) -{ - moduleInfo->resourceTree.push_back(resourceTree); - moduleInfo->resourceNames.push_back(resourceNames); - moduleInfo->resourceData.push_back(resourceData); - return true; -} - - -ModuleResourceTree::ModuleResourceTree(ModuleInfo::ModuleResourceData resourceTree, - ModuleInfo::ModuleResourceData resourceNames, - ModuleInfo::ModuleResourceData resourceData) - : isValid(resourceTree && resourceNames && resourceData) - , tree(resourceTree) - , names(resourceNames) - , payloads(resourceData) -{ -} - -bool ModuleResourceTree::IsValid() const -{ - return isValid; -} - -void ModuleResourceTree::Invalidate() -{ - isValid = false; -} - -inline std::string ModuleResourceTree::GetName(int node) const -{ - if(!node) // root - return std::string(); - - const int offset = FindOffset(node); - - std::string ret; - int nameOffset = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - const int16_t nameLength = (names[nameOffset+0] << 8) + - (names[nameOffset+1] << 0); - nameOffset += 2; // jump past name length - nameOffset += 4; // jump past hash - - ret.resize(nameLength); - for(int i = 0; i < nameLength; ++i) - { - ret[i] = names[nameOffset+i]; - } - return ret; -} - -int ModuleResourceTree::FindNode(const std::string& _path) const -{ - std::string path = _path.empty() ? "/" : _path; - -#ifdef DEBUG_RESOURCE_MATCH - US_DEBUG << "***" << " START " << path; -#endif - - if(path == "/") - return 0; - - // the root node is always first - int childCount = (tree[6] << 24) + (tree[7] << 16) + - (tree[8] << 8) + (tree[9] << 0); - int child = (tree[10] << 24) + (tree[11] << 16) + - (tree[12] << 8) + (tree[13] << 0); - - int node = -1; - - // split the full path into segments - std::vector segments; - { - std::stringstream ss(path); - std::string item; - while(std::getline(ss, item, '/')) - { - if (item.empty()) continue; - segments.push_back(item); - } - } - - //now iterate up the path hierarchy - for (std::size_t i = 0; i < segments.size() && childCount; ++i) - { - const std::string& segment = segments[i]; - -#ifdef DEBUG_RESOURCE_MATCH - US_DEBUG << " CHILDREN " << segment; - for(int j = 0; j < childCount; ++j) - { - US_DEBUG << " " << child+j << " :: " << GetName(child+j); - } -#endif - - // get the hash value for the current segment - const uint32_t currHash = static_cast(US_HASH_FUNCTION_NAMESPACE::US_HASH_FUNCTION(std::string,segment)); - - // do a binary search for the hash - int l = 0; - int r = childCount-1; - int subNode = (l+r+1)/2; - while(r != l) - { - const uint32_t subNodeHash = GetHash(child+subNode); - if(currHash == subNodeHash) - break; - else if(currHash < subNodeHash) - r = subNode - 1; - else - l = subNode; - subNode = (l+r+1) / 2; - } - subNode += child; - - // now check fo collisions and do compare using equality - bool found = false; - if(GetHash(subNode) == currHash) - { - while(subNode > child && GetHash(subNode-1) == currHash) // walk up to include all collisions - --subNode; - for(; subNode < child+childCount && GetHash(subNode) == currHash; ++subNode) - { - // now test using name comparison - if(GetName(subNode) == segment) - { - found = true; - int offset = FindOffset(subNode); -#ifdef DEBUG_RESOURCE_MATCH - US_DEBUG << " TRY " << subNode << " " << GetName(subNode) << " " << offset; -#endif - offset += 4; // jump past name - - const short flags = (tree[offset+0] << 8) + (tree[offset+1] << 0); - offset += 2; - - if(i == segments.size()-1) - { -#ifdef DEBUG_RESOURCE_MATCH - US_DEBUG << "!!!!" << " FINISHED " << subNode; -#endif - return subNode; - } - - // if we are not at the end of the resource path and the current - // segment is not a directory, return "not found" (this shouldn't happen). - if(!(flags & Directory)) - return -1; - - childCount = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - offset += 4; - child = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - break; - } - } - } - if(!found) - { - break; - } - } -#ifdef DEBUG_RESOURCE_MATCH - US_DEBUG << "***" << " FINISHED " << node; -#endif - return node; -} - -void ModuleResourceTree::FindNodes(const std::string& _path, - const std::string& _filePattern, - bool recurse, std::vector& result) -{ - std::string path = _path.empty() ? std::string("/") : _path; - if (path[path.size()-1] != '/') path.append("/"); - - std::string filePattern = _filePattern.empty() ? std::string("*") : _filePattern; - - int rootNode = FindNode(path); - if (rootNode > -1) - { - this->FindNodes(result, path, rootNode, filePattern, recurse); - } -} - -short ModuleResourceTree::GetFlags(int node) const -{ - if(node == -1) - return 0; - const int offset = FindOffset(node) + 4; //jump past name - return (tree[offset+0] << 8) + (tree[offset+1] << 0); -} - -void ModuleResourceTree::FindNodes(std::vector &result, const std::string& path, - const int rootNode, - const std::string &filePattern, bool recurse) -{ - int offset = FindOffset(rootNode) + 6; // jump past name and type - - const int childCount = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - offset += 4; - const int childNode = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - - for(int i = childNode; i < childNode+childCount; ++i) - { - const int childOffset = FindOffset(i); - const short childFlags = (tree[childOffset+4] << 8) + (tree[childOffset+5] << 0); - if (!(childFlags & Directory)) - { - const std::string name = GetName(i); - if (this->Matches(name, filePattern)) - { - result.push_back(path + name); - } - } - else if (recurse) - { - this->FindNodes(result, path + GetName(i) + "/", i, filePattern, recurse); - } - } -} - -uint32_t ModuleResourceTree::GetHash(int node) const -{ - if(!node) // root node - return 0; - - const int offset = FindOffset(node); - int nameOffset = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - nameOffset += 2; // jump past name length - return (names[nameOffset+0] << 24) + (names[nameOffset+1] << 16) + - (names[nameOffset+2] << 8) + (names[nameOffset+3] << 0); -} - -bool ModuleResourceTree::Matches(const std::string &name, const std::string &filePattern) -{ - // short-cut - if (filePattern == "*") return true; - - std::stringstream ss(filePattern); - std::string tok; - std::size_t pos = 0; - while(std::getline(ss, tok, '*')) - { - std::size_t index = name.find(tok, pos); - if (index == std::string::npos) return false; - pos = index + tok.size(); - } - return true; -} - -const unsigned char* ModuleResourceTree::GetData(int node, int32_t* size) const -{ - if(node == -1) - { - *size = 0; - return 0; - } - int offset = FindOffset(node) + 4; // jump past name - - const short flags = (tree[offset+0] << 8) + (tree[offset+1] << 0); - offset += 2; - - offset += 4; // jump past the padding - - if(!(flags & Directory)) - { - const int dataOffset = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - const int32_t dataLength = (payloads[dataOffset+0] << 24) + (payloads[dataOffset+1] << 16) + - (payloads[dataOffset+2] << 8) + (payloads[dataOffset+3] << 0); - const unsigned char* ret = payloads+dataOffset+4; - *size = dataLength; - return ret; - } - *size = 0; - return 0; -} - -void ModuleResourceTree::GetChildren(int node, std::vector& ret) const -{ - if(node == -1) - return; - - int offset = FindOffset(node) + 4; // jump past name - - const short flags = (tree[offset+0] << 8) + (tree[offset+1] << 0); - offset += 2; - - if(flags & Directory) - { - const int childCount = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - offset += 4; - const int childOffset = (tree[offset+0] << 24) + (tree[offset+1] << 16) + - (tree[offset+2] << 8) + (tree[offset+3] << 0); - for(int i = childOffset; i < childOffset+childCount; ++i) - { - ret.push_back(GetName(i)); - } - } -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleResourceTree_p.h b/Core/Code/CppMicroServices/src/module/usModuleResourceTree_p.h deleted file mode 100644 index 038e3434ed..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleResourceTree_p.h +++ /dev/null @@ -1,98 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USMODULERESOURCETREE_H -#define USMODULERESOURCETREE_H - -#include - -#include "usModuleInfo.h" -#include "stdint_p.h" - -#include - -US_BEGIN_NAMESPACE - -struct ModuleInfo; - -/* - * This class represents the triple of data pointers - * (us_resource_data, us_resource_name, us_resource_tree) generate by - * the resource compiler. - * - * Each module owns zero or one such triple but in case of a statically - * linked (imported) module, the resource trees are "merged" together. - */ -class ModuleResourceTree -{ - -private: - - enum Flags - { - Directory = 0x01, - Compressed = 0x02 - }; - - bool isValid; - const unsigned char *tree, *names, *payloads; - - // Returns the offset in the us_resource_tree array for a given node index - inline int FindOffset(int node) const { return node * 14; } // sizeof each tree element - - std::string GetName(int node) const; - short GetFlags(int node) const; - - void FindNodes(std::vector& result, const std::string& path, - const int rootNode, - const std::string& filePattern, bool recurse); - - uint32_t GetHash(int node) const; - - bool Matches(const std::string& name, const std::string& filePattern); - -public: - - ModuleResourceTree(ModuleInfo::ModuleResourceData resourceTree, - ModuleInfo::ModuleResourceData resourceNames, - ModuleInfo::ModuleResourceData resourceData); - - bool IsValid() const; - void Invalidate(); - - // Returns an index enumerating the info entries in the us_resource_tree array for - // the given resource path. - int FindNode(const std::string& path) const; - - void FindNodes(const std::string& path, const std::string& filePattern, - bool recurse, std::vector& result); - - inline bool IsCompressed(int node) const {return GetFlags(node) & Compressed ? true : false; } - inline bool IsDir(int node) const { return GetFlags(node) & Directory ? true : false; } - const unsigned char* GetData(int node, int32_t *size) const; - void GetChildren(int node, std::vector& children) const; - -}; - -US_END_NAMESPACE - -#endif // USMODULERESOURCETREE_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleSettings.cpp b/Core/Code/CppMicroServices/src/module/usModuleSettings.cpp deleted file mode 100644 index 6e82cc89a1..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleSettings.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usModuleSettings.h" -#include "usThreads_p.h" -#include "usStaticInit_p.h" - -#include -#include -#include -#include -#include - -US_BEGIN_NAMESPACE - -namespace { - - std::string RemoveTrailingPathSeparator(const std::string& in) - { -#ifdef US_PLATFORM_WINDOWS - const char separator = '\\'; -#else - const char separator = '/'; -#endif - if (in.empty()) return in; - std::string::const_iterator lastChar = --in.end(); - while (lastChar != in.begin() && std::isspace(*lastChar)) lastChar--; - if (*lastChar != separator) lastChar++; - std::string::const_iterator firstChar = in.begin(); - while (firstChar < lastChar && std::isspace(*firstChar)) firstChar++; - return std::string(firstChar, lastChar); - } - -} - -std::string ModuleSettings::CURRENT_MODULE_PATH() -{ - static const std::string var = "us_current_module_path"; - return var; -} - -struct ModuleSettingsPrivate : public US_DEFAULT_THREADING -{ - ModuleSettingsPrivate() - : autoLoadPaths() - #ifdef US_ENABLE_AUTOLOADING_SUPPORT - , autoLoadingEnabled(true) - #else - , autoLoadingEnabled(false) - #endif - , autoLoadingDisabled(false) - { - autoLoadPaths.insert(ModuleSettings::CURRENT_MODULE_PATH()); - - char* envPaths = getenv("US_AUTOLOAD_PATHS"); - if (envPaths != NULL) - { - std::stringstream ss(envPaths); - std::string envPath; -#ifdef US_PLATFORM_WINDOWS - const char separator = ';'; -#else - const char separator = ':'; -#endif - while (std::getline(ss, envPath, separator)) - { - std::string normalizedEnvPath = RemoveTrailingPathSeparator(envPath); - if (!normalizedEnvPath.empty()) - { - extraPaths.insert(normalizedEnvPath); - } - } - } - - if (getenv("US_DISABLE_AUTOLOADING")) - { - autoLoadingDisabled = true; - } - } - - std::set autoLoadPaths; - std::set extraPaths; - bool autoLoadingEnabled; - bool autoLoadingDisabled; -}; - -US_GLOBAL_STATIC(ModuleSettingsPrivate, moduleSettingsPrivate) - -bool ModuleSettings::IsThreadingSupportEnabled() -{ -#ifdef US_ENABLE_THREADING_SUPPORT - return true; -#else - return false; -#endif -} - -bool ModuleSettings::IsServiceFactorySupportEnabled() -{ -#ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - return true; -#else - return false; -#endif -} - -bool ModuleSettings::IsAutoLoadingEnabled() -{ - ModuleSettingsPrivate::Lock l(moduleSettingsPrivate()); -#ifdef US_ENABLE_AUTOLOADING_SUPPORT - return !moduleSettingsPrivate()->autoLoadingDisabled && - moduleSettingsPrivate()->autoLoadingEnabled; -#else - return false; -#endif -} - -void ModuleSettings::SetAutoLoadingEnabled(bool enable) -{ - ModuleSettingsPrivate::Lock l(moduleSettingsPrivate()); - moduleSettingsPrivate()->autoLoadingEnabled = enable; -} - -ModuleSettings::PathList ModuleSettings::GetAutoLoadPaths() -{ - ModuleSettingsPrivate::Lock l(moduleSettingsPrivate()); - ModuleSettings::PathList paths(moduleSettingsPrivate()->autoLoadPaths.begin(), - moduleSettingsPrivate()->autoLoadPaths.end()); - paths.insert(paths.end(), moduleSettingsPrivate()->extraPaths.begin(), - moduleSettingsPrivate()->extraPaths.end()); - std::sort(paths.begin(), paths.end()); - paths.erase(std::unique(paths.begin(), paths.end()), paths.end()); - return paths; -} - -void ModuleSettings::SetAutoLoadPaths(const PathList& paths) -{ - PathList normalizedPaths; - normalizedPaths.resize(paths.size()); - std::transform(paths.begin(), paths.end(), normalizedPaths.begin(), RemoveTrailingPathSeparator); - - ModuleSettingsPrivate::Lock l(moduleSettingsPrivate()); - moduleSettingsPrivate()->autoLoadPaths.clear(); - moduleSettingsPrivate()->autoLoadPaths.insert(normalizedPaths.begin(), normalizedPaths.end()); -} - -void ModuleSettings::AddAutoLoadPath(const std::string& path) -{ - ModuleSettingsPrivate::Lock l(moduleSettingsPrivate()); - moduleSettingsPrivate()->autoLoadPaths.insert(RemoveTrailingPathSeparator(path)); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleSettings.h b/Core/Code/CppMicroServices/src/module/usModuleSettings.h deleted file mode 100644 index 0a687e2793..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleSettings.h +++ /dev/null @@ -1,137 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USMODULESETTINGS_H -#define USMODULESETTINGS_H - -#include "usConfig.h" - -#include -#include - -US_BEGIN_NAMESPACE - -/** - * \ingroup MicroServices - * - * Query and set certain properties of the CppMicroServices library. - * - * The following environment variables influence the runtime behavior - * of the CppMicroServices library: - * - * - \e US_DISABLE_AUTOLOADING If set, auto-loading of modules is disabled. - * - \e US_AUTOLOAD_PATHS A ':' (Unix) or ';' (Windows) separated list of paths - * from which modules should be auto-loaded. - * - * \remarks This class is thread safe. - */ -class US_EXPORT ModuleSettings -{ -public: - - typedef std::vector PathList; - - /** - * Returns a special string which can be used as an argument for a - * AddAutoLoadPath() call. - * - * When a module is loaded and this string has been added as a path - * to the list of auto-load paths the CppMicroServices library will - * auto-load all modules from the currently being loaded module's - * auto-load directory. - * - * \return A string to be used in AddAutoLoadPath(). - * - * \remarks The returned string is contained in the default set of - * auto-load paths, unless a new set of paths is given by a call to - * SetAutoLoadPaths(). - * - * \sa MicroServices_AutoLoading - * \sa US_INITIALIZE_MODULE - */ - static std::string CURRENT_MODULE_PATH(); - - /** - * \return \c true if threading support has been configured into the - * CppMicroServices library, \c false otherwise. - */ - static bool IsThreadingSupportEnabled(); - - /** - * \return \c true if support for service factories has been configured into the - * CppMicroServices library, \c false otherwise. - */ - static bool IsServiceFactorySupportEnabled(); - - /** - * \return \c true if support for module auto-loading is enabled, - * \c false otherwise. - * - * \remarks This method will always return \c false if support for auto-loading - * has not been configured into the CppMicroServices library or if it has been - * disabled by defining the US_DISABLE_AUTOLOADING environment variable. - */ - static bool IsAutoLoadingEnabled(); - - /** - * Enable or disable auto-loading support. - * - * \param enable If \c true, enable auto-loading support, disable it otherwise. - * - * \remarks Calling this method will have no effect if support for - * auto-loading has not been configured into the CppMicroServices library of it - * it has been disabled by defining the US_DISABLE_AUTOLOADING envrionment variable. - */ - static void SetAutoLoadingEnabled(bool enable); - - /** - * \return A list of paths in the file-system from which modules will be - * auto-loaded. - */ - static PathList GetAutoLoadPaths(); - - /** - * Set a list of paths in the file-system from which modules should be - * auto-loaded. - * @param paths A list of absolute file-system paths. - */ - static void SetAutoLoadPaths(const PathList& paths); - - /** - * Add a path in the file-system to the list of paths from which modules - * will be auto-loaded. - * - * @param path The additional absolute auto-load path in the file-system. - */ - static void AddAutoLoadPath(const std::string& path); - -private: - - // purposely not implemented - ModuleSettings(); - ModuleSettings(const ModuleSettings&); - ModuleSettings& operator=(const ModuleSettings&); -}; - -US_END_NAMESPACE - -#endif // USMODULESETTINGS_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp b/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp deleted file mode 100644 index 29c64d4c52..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleUtils.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usModuleUtils_p.h" -#include - -US_BEGIN_NAMESPACE - -namespace { -#ifdef US_BUILD_SHARED_LIBS - const bool sharedLibMode = true; -#else - const bool sharedLibMode = false; -#endif -} - -#ifdef __GNUC__ - -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif - -#include - -std::string GetLibraryPath_impl(const std::string& /*libName*/, void* symbol) -{ - Dl_info info; - if (dladdr(symbol, &info)) - { - return info.dli_fname; - } - else - { - US_DEBUG << "GetLibraryPath_impl() dladdr() failed: " << dlerror(); - } - return ""; -} - -void* GetSymbol_impl(const std::string& libName, const char* symbol) -{ - // Clear the last error message - dlerror(); - - void* selfHandle = 0; - if (libName.empty() || !sharedLibMode) - { - // Get the handle of the executable - selfHandle = dlopen(0, RTLD_LAZY); - } - else - { - selfHandle = dlopen(libName.c_str(), RTLD_LAZY); - } - - if (selfHandle) - { - void* addr = dlsym(selfHandle, symbol); - if (!addr) - { - const char* dlerrorMsg = dlerror(); - if (dlerrorMsg) - { - US_DEBUG << "GetSymbol_impl() failed: " << dlerrorMsg; - } - } - dlclose(selfHandle); - return addr; - } - else - { - US_DEBUG << "GetSymbol_impl() dlopen() failed: " << dlerror(); - } - return 0; -} - -#elif _WIN32 - -#include - -std::string GetLibraryPath_impl(const std::string& libName, void *symbol) -{ - HMODULE handle = 0; - if (libName.empty() || !sharedLibMode) - { - // get the handle for the executable - handle = GetModuleHandle(NULL); - } - else - { - handle = GetModuleHandle(libName.c_str()); - } - if (!handle) - { - // Test - US_DEBUG << "GetLibraryPath_impl():GetModuleHandle() " << GetLastErrorStr(); - return ""; - } - - char modulePath[512]; - if (GetModuleFileName(handle, modulePath, 512)) - { - return modulePath; - } - - US_DEBUG << "GetLibraryPath_impl():GetModuleFileName() " << GetLastErrorStr(); - return ""; -} - -void* GetSymbol_impl(const std::string& libName, const char* symbol) -{ - HMODULE handle = NULL; - if (libName.empty() || !sharedLibMode) - { - handle = GetModuleHandle(NULL); - } - else - { - handle = GetModuleHandle(libName.c_str()); - } - - if (!handle) - { - US_DEBUG << "GetSymbol_impl():GetModuleHandle() " << GetLastErrorStr(); - return 0; - } - - void* addr = (void*)GetProcAddress(handle, symbol); - if (!addr) - { - US_DEBUG << "GetSymbol_impl():GetProcAddress(handle," << symbol << ") " << GetLastErrorStr(); - } - return addr; -} -#else -std::string GetLibraryPath_impl(const std::string& libName, void* symbol) -{ - return ""; -} - -void* GetSymbol_impl(const std::string& libName, const char* symbol) -{ - return 0; -} -#endif - -std::string ModuleUtils::GetLibraryPath(const std::string& libName, void* symbol) -{ - return GetLibraryPath_impl(libName, symbol); -} - -void* ModuleUtils::GetSymbol(const std::string& libName, const char* symbol) -{ - return GetSymbol_impl(libName, symbol); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/module/usModuleUtils_p.h b/Core/Code/CppMicroServices/src/module/usModuleUtils_p.h deleted file mode 100644 index 5ce9bd4abf..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleUtils_p.h +++ /dev/null @@ -1,45 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USMODULEUTILS_H -#define USMODULEUTILS_H - -#include - -#include - -US_BEGIN_NAMESPACE - -/** - * This class is not intended to be used directly. It is exported to support - * the CppMicroServices module system. - */ -struct US_EXPORT ModuleUtils -{ - static std::string GetLibraryPath(const std::string& libName, void* symbol); - - static void* GetSymbol(const std::string& libName, const char* symbol); -}; - -US_END_NAMESPACE - -#endif // USMODULEUTILS_H diff --git a/Core/Code/CppMicroServices/src/module/usModuleVersion.cpp b/Core/Code/CppMicroServices/src/module/usModuleVersion.cpp deleted file mode 100644 index 53550b3ea2..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleVersion.cpp +++ /dev/null @@ -1,276 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usModuleVersion.h" - -#include -#include -#include -#include -#include - -US_BEGIN_NAMESPACE - -const char ModuleVersion::SEPARATOR = '.'; - -bool IsInvalidQualifier(char c) -{ - return !(std::isalnum(c) || c == '_' || c == '-'); -} - -ModuleVersion ModuleVersion::EmptyVersion() -{ - static ModuleVersion emptyV(false); - return emptyV; -} - -ModuleVersion ModuleVersion::UndefinedVersion() -{ - static ModuleVersion undefinedV(true); - return undefinedV; -} - -ModuleVersion& ModuleVersion::operator=(const ModuleVersion& v) -{ - majorVersion = v.majorVersion; - minorVersion = v.minorVersion; - microVersion = v.microVersion; - qualifier = v.qualifier; - undefined = v.undefined; - return *this; -} - -ModuleVersion::ModuleVersion(bool undefined) - : majorVersion(0), minorVersion(0), microVersion(0), qualifier(""), undefined(undefined) -{ - -} - -void ModuleVersion::Validate() -{ - if (std::find_if(qualifier.begin(), qualifier.end(), IsInvalidQualifier) != qualifier.end()) - throw std::invalid_argument(std::string("invalid qualifier: ") + qualifier); - - undefined = false; -} - -ModuleVersion::ModuleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion) - : majorVersion(majorVersion), minorVersion(minorVersion), microVersion(microVersion), qualifier(""), - undefined(false) -{ - -} - -ModuleVersion::ModuleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion, const std::string& qualifier) - : majorVersion(majorVersion), minorVersion(minorVersion), microVersion(microVersion), qualifier(qualifier), - undefined(true) -{ - this->Validate(); -} - -ModuleVersion::ModuleVersion(const std::string& version) - : majorVersion(0), minorVersion(0), microVersion(0), undefined(true) -{ - unsigned int maj = 0; - unsigned int min = 0; - unsigned int mic = 0; - std::string qual(""); - - std::vector st; - std::stringstream ss(version); - std::string token; - while(std::getline(ss, token, SEPARATOR)) - { - st.push_back(token); - } - - if (st.empty()) return; - - bool ok = true; - ss.clear(); - ss.str(st[0]); - ss >> maj; - ok = !ss.fail(); - - if (st.size() > 1) - { - ss.clear(); - ss.str(st[1]); - ss >> min; - ok = !ss.fail(); - if (st.size() > 2) - { - ss.clear(); - ss.str(st[2]); - ss >> mic; - ok = !ss.fail(); - if (st.size() > 3) - { - qual = st[3]; - if (st.size() > 4) - { - ok = false; - } - } - } - } - - if (!ok) throw std::invalid_argument("invalid format"); - - majorVersion = maj; - minorVersion = min; - microVersion = mic; - qualifier = qual; - this->Validate(); -} - -ModuleVersion::ModuleVersion(const ModuleVersion& version) -: majorVersion(version.majorVersion), minorVersion(version.minorVersion), - microVersion(version.microVersion), qualifier(version.qualifier), - undefined(version.undefined) -{ - -} - -ModuleVersion ModuleVersion::ParseVersion(const std::string& version) -{ - if (version.empty()) - { - return EmptyVersion(); - } - - std::string version2(version); - version2.erase(0, version2.find_first_not_of(' ')); - version2.erase(version2.find_last_not_of(' ')+1); - if (version2.empty()) - { - return EmptyVersion(); - } - - return ModuleVersion(version2); -} - -bool ModuleVersion::IsUndefined() const -{ - return undefined; -} - -unsigned int ModuleVersion::GetMajor() const -{ - if (undefined) throw std::logic_error("Version undefined"); - return majorVersion; -} - -unsigned int ModuleVersion::GetMinor() const -{ - if (undefined) throw std::logic_error("Version undefined"); - return minorVersion; -} - -unsigned int ModuleVersion::GetMicro() const -{ - if (undefined) throw std::logic_error("Version undefined"); - return microVersion; -} - -std::string ModuleVersion::GetQualifier() const -{ - if (undefined) throw std::logic_error("Version undefined"); - return qualifier; -} - -std::string ModuleVersion::ToString() const -{ - if (undefined) return "undefined"; - - std::string result; - std::stringstream ss(result); - ss << majorVersion << SEPARATOR << minorVersion << SEPARATOR << microVersion; - if (!qualifier.empty()) - { - ss << SEPARATOR << qualifier; - } - return result; -} - -bool ModuleVersion::operator==(const ModuleVersion& other) const -{ - if (&other == this) - { // quicktest - return true; - } - - if (other.undefined && this->undefined) return true; - if (this->undefined) throw std::logic_error("Version undefined"); - if (other.undefined) return false; - - return (majorVersion == other.majorVersion) && (minorVersion == other.minorVersion) && (microVersion - == other.microVersion) && qualifier == other.qualifier; -} - -int ModuleVersion::Compare(const ModuleVersion& other) const -{ - if (&other == this) - { // quicktest - return 0; - } - - if (this->undefined || other.undefined) - throw std::logic_error("Cannot compare undefined version"); - - if (majorVersion < other.majorVersion) - { - return -1; - } - - if (majorVersion == other.majorVersion) - { - - if (minorVersion < other.minorVersion) - { - return -1; - } - - if (minorVersion == other.minorVersion) - { - - if (microVersion < other.microVersion) - { - return -1; - } - - if (microVersion == other.microVersion) - { - return qualifier.compare(other.qualifier); - } - } - } - return 1; -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -std::ostream& operator<<(std::ostream& os, const ModuleVersion& v) -{ - return os << v.ToString(); -} diff --git a/Core/Code/CppMicroServices/src/module/usModuleVersion.h b/Core/Code/CppMicroServices/src/module/usModuleVersion.h deleted file mode 100644 index 930dc724c1..0000000000 --- a/Core/Code/CppMicroServices/src/module/usModuleVersion.h +++ /dev/null @@ -1,263 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USMODULEVERSION_H -#define USMODULEVERSION_H - -#include - -#include - -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4251) -#endif - -US_BEGIN_NAMESPACE - -/** - * \ingroup MicroServices - * - * Version identifier for CppMicroServices modules. - * - *

- * Version identifiers have four components. - *

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

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

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

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

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

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

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

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

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

- * A version is considered to be equal to another version if the - * majorVersion, minorVersion and microVersion components are equal and the qualifier component - * is equal. - * - * @param object The ModuleVersion object to be compared. - * @return A negative integer, zero, or a positive integer if this object is - * less than, equal to, or greater than the specified - * ModuleVersion object. - */ - int Compare(const ModuleVersion& object) const; - -}; - -US_END_NAMESPACE - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -/** - * \ingroup MicroServices - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ModuleVersion)& v); - -#endif // USMODULEVERSION_H diff --git a/Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp b/Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp deleted file mode 100644 index 39d83c1705..0000000000 --- a/Core/Code/CppMicroServices/src/service/usLDAPExpr.cpp +++ /dev/null @@ -1,778 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usLDAPExpr_p.h" - -#include -#include -#include -#include - -US_BEGIN_NAMESPACE - -const int LDAPExpr::AND = 0; -const int LDAPExpr::OR = 1; -const int LDAPExpr::NOT = 2; -const int LDAPExpr::EQ = 4; -const int LDAPExpr::LE = 8; -const int LDAPExpr::GE = 16; -const int LDAPExpr::APPROX = 32; -const int LDAPExpr::COMPLEX = LDAPExpr::AND | LDAPExpr::OR | LDAPExpr::NOT; -const int LDAPExpr::SIMPLE = LDAPExpr::EQ | LDAPExpr::LE | LDAPExpr::GE | LDAPExpr::APPROX; - -const LDAPExpr::Byte LDAPExpr::WILDCARD = std::numeric_limits::max(); -const std::string LDAPExpr::WILDCARD_STRING = std::string(1, LDAPExpr::WILDCARD ); -const std::string LDAPExpr::NULLQ = "Null query"; -const std::string LDAPExpr::GARBAGE = "Trailing garbage"; -const std::string LDAPExpr::EOS = "Unexpected end of query"; -const std::string LDAPExpr::MALFORMED = "Malformed query"; -const std::string LDAPExpr::OPERATOR = "Undefined operator"; - -bool stricomp(const std::string::value_type& v1, const std::string::value_type& v2) -{ - return ::tolower(v1) == ::tolower(v2); -} - -//! Contains the current parser position and parsing utility methods. -class LDAPExpr::ParseState -{ - -private: - - std::size_t m_pos; - std::string m_str; - -public: - - ParseState(const std::string &str); - - //! Move m_pos to remove the prefix \a pre - bool prefix(const std::string &pre); - - /** Peek a char at m_pos - \note If index out of bounds, throw exception - */ - LDAPExpr::Byte peek(); - - //! Increment m_pos by n - void skip(int n); - - //! return string from m_pos until the end - std::string rest() const; - - //! Move m_pos until there's no spaces - void skipWhite(); - - //! Get string until special chars. Move m_pos - std::string getAttributeName(); - - //! Get string and convert * to WILDCARD - std::string getAttributeValue(); - - //! Throw InvalidSyntaxException exception - void error(const std::string &m) const; - -}; - - -class LDAPExprData : public SharedData -{ -public: - - LDAPExprData( int op, const std::vector& args ) - : m_operator(op), m_args(args), m_attrName(), m_attrValue() - { - } - - LDAPExprData( int op, std::string attrName, const std::string& attrValue ) - : m_operator(op), m_args(), m_attrName(attrName), m_attrValue(attrValue) - { - } - - LDAPExprData( const LDAPExprData& other ) - : SharedData(other), m_operator(other.m_operator), - m_args(other.m_args), m_attrName(other.m_attrName), - m_attrValue(other.m_attrValue) - { - } - - int m_operator; - std::vector m_args; - std::string m_attrName; - std::string m_attrValue; -}; - -LDAPExpr::LDAPExpr() : d() -{ -} - -LDAPExpr::LDAPExpr( const std::string &filter ) : d() -{ - ParseState ps(filter); - try - { - LDAPExpr expr = ParseExpr(ps); - - if (!Trim(ps.rest()).empty()) - { - ps.error(GARBAGE + " '" + ps.rest() + "'"); - } - - d = expr.d; - } - catch (const std::out_of_range&) - { - ps.error(EOS); - } -} - -LDAPExpr::LDAPExpr( int op, const std::vector& args ) - : d(new LDAPExprData(op, args)) -{ -} - -LDAPExpr::LDAPExpr( int op, const std::string &attrName, const std::string &attrValue ) - : d(new LDAPExprData(op, attrName, attrValue)) -{ -} - -LDAPExpr::LDAPExpr( const LDAPExpr& other ) - : d(other.d) -{ -} - -LDAPExpr& LDAPExpr::operator=(const LDAPExpr& other) -{ - d = other.d; - return *this; -} - -LDAPExpr::~LDAPExpr() -{ -} - -std::string LDAPExpr::Trim(std::string str) -{ - str.erase(0, str.find_first_not_of(' ')); - str.erase(str.find_last_not_of(' ')+1); - return str; -} - -bool LDAPExpr::GetMatchedObjectClasses(ObjectClassSet& objClasses) const -{ - if (d->m_operator == EQ) - { - if (d->m_attrName.length() == ServiceConstants::OBJECTCLASS().length() && - std::equal(d->m_attrName.begin(), d->m_attrName.end(), ServiceConstants::OBJECTCLASS().begin(), stricomp) && - d->m_attrValue.find(WILDCARD) == std::string::npos) - { - objClasses.insert( d->m_attrValue ); - return true; - } - return false; - } - else if (d->m_operator == AND) - { - bool result = false; - for (std::size_t i = 0; i < d->m_args.size( ); i++) - { - LDAPExpr::ObjectClassSet r; - if (d->m_args[i].GetMatchedObjectClasses(r)) - { - result = true; - if (objClasses.empty()) - { - objClasses = r; - } - else - { - // if AND op and classes in several operands, - // then only the intersection is possible. - LDAPExpr::ObjectClassSet::iterator it1 = objClasses.begin(); - LDAPExpr::ObjectClassSet::iterator it2 = r.begin(); - while ( (it1 != objClasses.end()) && (it2 != r.end()) ) - { - if (*it1 < *it2) - { - objClasses.erase(it1++); - } - else if (*it2 < *it1) - { - ++it2; - } - else - { // *it1 == *it2 - ++it1; - ++it2; - } - } - // Anything left in set_1 from here on did not appear in set_2, - // so we remove it. - objClasses.erase(it1, objClasses.end()); - } - } - } - return result; - } - else if (d->m_operator == OR) - { - for (std::size_t i = 0; i < d->m_args.size( ); i++) - { - LDAPExpr::ObjectClassSet r; - if (d->m_args[i].GetMatchedObjectClasses(r)) - { - std::copy(r.begin(), r.end(), std::inserter(objClasses, objClasses.begin())); - } - else - { - objClasses.clear(); - return false; - } - } - return true; - } - return false; -} - -std::string LDAPExpr::ToLower(const std::string& str) -{ - std::string lowerStr(str); - std::transform(str.begin(), str.end(), lowerStr.begin(), ::tolower); - return lowerStr; -} - -bool LDAPExpr::IsSimple(const StringList& keywords, LocalCache& cache, - bool matchCase ) const -{ - if (cache.empty()) - { - cache.resize(keywords.size()); - } - - if (d->m_operator == EQ) - { - StringList::const_iterator index; - if ((index = std::find(keywords.begin(), keywords.end(), matchCase ? d->m_attrName : ToLower(d->m_attrName))) != keywords.end() && - d->m_attrValue.find_first_of(WILDCARD) == std::string::npos) - { - cache[index - keywords.begin()] = StringList(1, d->m_attrValue); - return true; - } - } - else if (d->m_operator == OR) - { - for (std::size_t i = 0; i < d->m_args.size( ); i++) - { - if (!d->m_args[i].IsSimple(keywords, cache, matchCase)) - return false; - } - return true; - } - return false; -} - -bool LDAPExpr::IsNull() const -{ - return !d; -} - -bool LDAPExpr::Query( const std::string &filter, const ServiceProperties &pd ) -{ - return LDAPExpr(filter).Evaluate(pd, false); -} - -bool LDAPExpr::Evaluate( const ServiceProperties& p, bool matchCase ) const -{ - if ((d->m_operator & SIMPLE) != 0) - { - Any propVal; - ServiceProperties::const_iterator it = p.find(d->m_attrName); - if (it != p.end() && (matchCase ? d->m_attrName == static_cast(it->first) : true)) - { - propVal = it->second; - } - return Compare(propVal, d->m_operator, d->m_attrValue); - } - else - { // (d->m_operator & COMPLEX) != 0 - switch (d->m_operator) - { - case AND: - for (std::size_t i = 0; i < d->m_args.size(); i++) - { - if (!d->m_args[i].Evaluate(p, matchCase)) - return false; - } - return true; - case OR: - for (std::size_t i = 0; i < d->m_args.size(); i++) - { - if (d->m_args[i].Evaluate(p, matchCase)) - return true; - } - return false; - case NOT: - return !d->m_args[0].Evaluate(p, matchCase); - default: - return false; // Cannot happen - } - } -} - -bool LDAPExpr::Compare( const Any& obj, int op, const std::string& s ) const -{ - if (obj.Empty()) - return false; - if (op == EQ && s == WILDCARD_STRING) - return true; - - try - { - const std::type_info& objType = obj.Type(); - if (objType == typeid(std::string)) - { - return CompareString(ref_any_cast(obj), op, s); - } - else if (objType == typeid(std::vector)) - { - const std::vector& list = ref_any_cast >(obj); - for (std::size_t it = 0; it != list.size(); it++) - { - if (CompareString(list[it], op, s)) - return true; - } - } - else if (objType == typeid(std::list)) - { - const std::list& list = ref_any_cast >(obj); - for (std::list::const_iterator it = list.begin(); - it != list.end(); ++it) - { - if (CompareString(*it, op, s)) - return true; - } - } - else if (objType == typeid(char)) - { - return CompareString(std::string(1, ref_any_cast(obj)), op, s); - } - else if (objType == typeid(bool)) - { - if (op==LE || op==GE) - return false; - - std::string boolVal = any_cast(obj) ? "true" : "false"; - return std::equal(s.begin(), s.end(), boolVal.begin(), stricomp); - } - else if (objType == typeid(Byte) || objType == typeid(int)) - { - int sInt; - std::stringstream ss(s); - ss >> sInt; - int intVal = any_cast(obj); - - switch(op) - { - case LE: - return intVal <= sInt; - case GE: - return intVal >= sInt; - default: /*APPROX and EQ*/ - return intVal == sInt; - } - } - else if (objType == typeid(float)) - { - float sFloat; - std::stringstream ss(s); - ss >> sFloat; - float floatVal = any_cast(obj); - - switch(op) - { - case LE: - return floatVal <= sFloat; - case GE: - return floatVal >= sFloat; - default: /*APPROX and EQ*/ - float diff = floatVal - sFloat; - return (diff < std::numeric_limits::epsilon()) && (diff > -std::numeric_limits::epsilon()); - } - } - else if (objType == typeid(double)) - { - double sDouble; - std::stringstream ss(s); - ss >> sDouble; - double doubleVal = any_cast(obj); - - switch(op) - { - case LE: - return doubleVal <= sDouble; - case GE: - return doubleVal >= sDouble; - default: /*APPROX and EQ*/ - double diff = doubleVal - sDouble; - return (diff < std::numeric_limits::epsilon()) && (diff > -std::numeric_limits::epsilon()); - } - } - else if (objType == typeid(long long int)) - { - long long int sLongInt; - std::stringstream ss(s); - ss >> sLongInt; - long long int longIntVal = any_cast(obj); - - switch(op) - { - case LE: - return longIntVal <= sLongInt; - case GE: - return longIntVal >= sLongInt; - default: /*APPROX and EQ*/ - return longIntVal == sLongInt; - } - } - else if (objType == typeid(std::vector)) - { - const std::vector& list = ref_any_cast >(obj); - for (std::size_t it = 0; it != list.size(); it++) - { - if (Compare(list[it], op, s)) - return true; - } - } - } - catch (...) - { - // This might happen if a std::string-to-datatype conversion fails - // Just consider it a false match and ignore the exception - } - return false; -} - -bool LDAPExpr::CompareString( const std::string& s1, int op, const std::string& s2 ) -{ - switch(op) - { - case LE: - return s1.compare(s2) <= 0; - case GE: - return s1.compare(s2) >= 0; - case EQ: - return PatSubstr(s1,s2); - case APPROX: - return FixupString(s2) == FixupString(s1); - default: - return false; - } -} - -std::string LDAPExpr::FixupString( const std::string& s ) -{ - std::string sb; - std::size_t len = s.length(); - for(std::size_t i=0; im_operator - - std::vector v; - do - { - v.push_back(ParseExpr(ps)); - ps.skipWhite(); - } while (ps.peek() == '('); - - std::size_t n = v.size(); - if (!ps.prefix(")") || n == 0 || (op == NOT && n > 1)) - ps.error(MALFORMED); - - return LDAPExpr(op, v); -} - -LDAPExpr LDAPExpr::ParseSimple( ParseState &ps ) -{ - std::string attrName = ps.getAttributeName(); - if (attrName.empty()) - ps.error(MALFORMED); - int op = 0; - if (ps.prefix("=")) - op = EQ; - else if (ps.prefix("<=")) - op = LE; - else if(ps.prefix(">=")) - op = GE; - else if(ps.prefix("~=")) - op = APPROX; - else - { - // System.out.println("undef op='" + ps.peek() + "'"); - ps.error(OPERATOR); // Does not return - } - std::string attrValue = ps.getAttributeValue(); - if (!ps.prefix(")")) - ps.error(MALFORMED); - return LDAPExpr(op, attrName, attrValue); -} - -const std::string LDAPExpr::ToString() const -{ - std::string res; - res.append("("); - if ((d->m_operator & SIMPLE) != 0) - { - res.append(d->m_attrName); - switch (d->m_operator) - { - case EQ: - res.append("="); - break; - case LE: - res.append("<="); - break; - case GE: - res.append(">="); - break; - case APPROX: - res.append("~="); - break; - } - - for (std::size_t i = 0; i < d->m_attrValue.length(); i++) - { - Byte c = d->m_attrValue.at(i); - if (c == '(' || c == ')' || c == '*' || c == '\\') - { - res.append(1, '\\'); - } - else if (c == WILDCARD) - { - c = '*'; - } - res.append(1, c); - } - } - else - { - switch (d->m_operator) - { - case AND: - res.append("&"); - break; - case OR: - res.append("|"); - break; - case NOT: - res.append("!"); - break; - } - for (std::size_t i = 0; i < d->m_args.size(); i++) - { - res.append(d->m_args[i].ToString()); - } - } - res.append(")"); - return res; -} - -LDAPExpr::ParseState::ParseState( const std::string& str ) - : m_pos(0), m_str() -{ - if (str.empty()) - { - error(NULLQ); - } - - m_str = str; -} - -bool LDAPExpr::ParseState::prefix( const std::string& pre ) -{ - std::string::iterator startIter = m_str.begin() + m_pos; - if (!std::equal(pre.begin(), pre.end(), startIter)) - return false; - m_pos += pre.size(); - return true; -} - -char LDAPExpr::ParseState::peek() -{ - if ( m_pos >= m_str.size() ) - { - throw std::out_of_range( "LDAPExpr" ); - } - return m_str.at(m_pos); -} - -void LDAPExpr::ParseState::skip( int n ) -{ - m_pos += n; -} - -std::string LDAPExpr::ParseState::rest() const -{ - return m_str.substr(m_pos); -} - -void LDAPExpr::ParseState::skipWhite() -{ - while (std::isspace(peek())) - { - m_pos++; - } -} - -std::string LDAPExpr::ParseState::getAttributeName() -{ - std::size_t start = m_pos; - std::size_t n = 0; - bool nIsSet = false; - for(;; m_pos++) - { - Byte c = peek(); - if (c == '(' || c == ')' || - c == '<' || c == '>' || - c == '=' || c == '~') { - break; - } - else if (!std::isspace(c)) - { - n = m_pos - start + 1; - nIsSet = true; - } - } - if (!nIsSet) - { - return std::string(); - } - return m_str.substr(start, n); -} - -std::string LDAPExpr::ParseState::getAttributeValue() -{ - std::string sb; - bool exit = false; - while( !exit ) { - Byte c = peek( ); - switch(c) - { - case '(': - case ')': - exit = true; - break; - case '*': - sb.append(1, WILDCARD); - break; - case '\\': - sb.append(1, m_str.at(++m_pos)); - break; - default: - sb.append(1, c); - break; - } - - if ( !exit ) - { - m_pos++; - } - } - return sb; -} - -void LDAPExpr::ParseState::error( const std::string &m ) const -{ - std::string errorStr = m + ": " + (m_str.empty() ? "" : m_str.substr(m_pos)); - throw std::invalid_argument(errorStr); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usLDAPExpr_p.h b/Core/Code/CppMicroServices/src/service/usLDAPExpr_p.h deleted file mode 100644 index d6dcb67d10..0000000000 --- a/Core/Code/CppMicroServices/src/service/usLDAPExpr_p.h +++ /dev/null @@ -1,183 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USLDAPEXPR_H -#define USLDAPEXPR_H - -#include - -#include "usSharedData.h" -#include "usServiceProperties.h" - -#include -#include - -US_BEGIN_NAMESPACE - -class LDAPExprData; - -/** - * This class is not part of the public API. - */ -class LDAPExpr { - -public: - - const static int AND; // = 0; - const static int OR; // = 1; - const static int NOT; // = 2; - const static int EQ; // = 4; - const static int LE; // = 8; - const static int GE; // = 16; - const static int APPROX; // = 32; - const static int COMPLEX; // = AND | OR | NOT; - const static int SIMPLE; // = EQ | LE | GE | APPROX; - - typedef char Byte; - typedef std::vector StringList; - typedef std::vector LocalCache; - typedef US_UNORDERED_SET_TYPE ObjectClassSet; - - - /** - * Creates an invalid LDAPExpr object. Use with care. - * - * @see IsNull() - */ - LDAPExpr(); - - LDAPExpr(const std::string& filter); - - LDAPExpr(const LDAPExpr& other); - - LDAPExpr& operator=(const LDAPExpr& other); - - ~LDAPExpr(); - - /** - * Get object class set matched by this LDAP expression. This will not work - * with wildcards and NOT expressions. If a set can not be determined return false. - * - * \param objClasses The set of matched classes will be added to objClasses. - * \return If the set cannot be determined, false is returned, true otherwise. - */ - bool GetMatchedObjectClasses(ObjectClassSet& objClasses) const; - - /** - * Checks if this LDAP expression is "simple". The definition of - * a simple filter is: - *

    - *
  • (name=value) is simple if - * name is a member of the provided keywords, - * and value does not contain a wildcard character;
  • - *
  • (| EXPR+ ) is simple if all EXPR - * expressions are simple;
  • - *
  • No other expressions are simple.
  • - *
- * If the filter is found to be simple, the cache is - * filled with mappings from the provided keywords to lists - * of attribute values. The keyword-value-pairs are the ones that - * satisfy this expression, for the given keywords. - * - * @param keywords The keywords to look for. - * @param cache An array (indexed by the keyword indexes) of lists to - * fill in with values saturating this expression. - * @return true if this expression is simple, - * false otherwise. - */ - bool IsSimple( - const StringList& keywords, - LocalCache& cache, - bool matchCase) const; - - /** - * Returns true if this instance is invalid, i.e. it was - * constructed using LDAPExpr(). - * - * @return true if the expression is invalid, - * false otherwise. - */ - bool IsNull() const; - - //! - static bool Query(const std::string& filter, const ServiceProperties& pd); - - //! Evaluate this LDAP filter. - bool Evaluate(const ServiceProperties& p, bool matchCase) const; - - //! - const std::string ToString() const; - - -private: - - class ParseState; - - //! - LDAPExpr(int op, const std::vector& args); - - //! - LDAPExpr(int op, const std::string& attrName, const std::string& attrValue); - - //! - static LDAPExpr ParseExpr(ParseState& ps); - - //! - static LDAPExpr ParseSimple(ParseState& ps); - - static std::string Trim(std::string str); - - static std::string ToLower(const std::string& str); - - //! - bool Compare(const Any& obj, int op, const std::string& s) const; - - //! - static bool CompareString(const std::string& s1, int op, const std::string& s2); - - //! - static std::string FixupString(const std::string &s); - - //! - static bool PatSubstr(const std::string& s, const std::string& pat); - - //! - static bool PatSubstr(const std::string& s, int si, const std::string& pat, int pi); - - - const static Byte WILDCARD; // = 65535; - const static std::string WILDCARD_STRING;// = std::string( WILDCARD ); - - const static std::string NULLQ; // = "Null query"; - const static std::string GARBAGE; // = "Trailing garbage"; - const static std::string EOS; // = "Unexpected end of query"; - const static std::string MALFORMED; // = "Malformed query"; - const static std::string OPERATOR; // = "Undefined m_operator"; - - //! Shared pointer - SharedDataPointer d; - -}; - -US_END_NAMESPACE - -#endif // USLDAPEXPR_H diff --git a/Core/Code/CppMicroServices/src/service/usLDAPFilter.cpp b/Core/Code/CppMicroServices/src/service/usLDAPFilter.cpp deleted file mode 100644 index c8a94d656e..0000000000 --- a/Core/Code/CppMicroServices/src/service/usLDAPFilter.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usLDAPFilter.h" -#include "usLDAPExpr_p.h" -#include "usServiceReferencePrivate.h" - -#include - -US_BEGIN_NAMESPACE - -class LDAPFilterData : public SharedData -{ -public: - - LDAPFilterData() : ldapExpr() - {} - - LDAPFilterData(const std::string& filter) - : ldapExpr(filter) - {} - - LDAPFilterData(const LDAPFilterData& other) - : SharedData(other), ldapExpr(other.ldapExpr) - {} - - LDAPExpr ldapExpr; -}; - -LDAPFilter::LDAPFilter() - : d(0) -{ -} - -LDAPFilter::LDAPFilter(const std::string& filter) - : d(0) -{ - try - { - d = new LDAPFilterData(filter); - } - catch (const std::exception& e) - { - throw std::invalid_argument(e.what()); - } -} - -LDAPFilter::LDAPFilter(const LDAPFilter& other) - : d(other.d) -{ -} - -LDAPFilter::~LDAPFilter() -{ -} - -LDAPFilter::operator bool() const -{ - return d.ConstData() != 0; -} - -bool LDAPFilter::Match(const ServiceReference& reference) const -{ - return d->ldapExpr.Evaluate(reference.d->GetProperties(), true); -} - -bool LDAPFilter::Match(const ServiceProperties& dictionary) const -{ - return d->ldapExpr.Evaluate(dictionary, false); -} - -bool LDAPFilter::MatchCase(const ServiceProperties& dictionary) const -{ - return d->ldapExpr.Evaluate(dictionary, true); -} - -std::string LDAPFilter::ToString() const -{ - return d->ldapExpr.ToString(); -} - -bool LDAPFilter::operator==(const LDAPFilter& other) const -{ - return d->ldapExpr.ToString() == other.d->ldapExpr.ToString(); -} - -LDAPFilter& LDAPFilter::operator=(const LDAPFilter& filter) -{ - d = filter.d; - - return *this; -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -std::ostream& operator<<(std::ostream& os, const LDAPFilter& filter) -{ - return os << filter.ToString(); -} diff --git a/Core/Code/CppMicroServices/src/service/usLDAPFilter.h b/Core/Code/CppMicroServices/src/service/usLDAPFilter.h deleted file mode 100644 index c8355fc3be..0000000000 --- a/Core/Code/CppMicroServices/src/service/usLDAPFilter.h +++ /dev/null @@ -1,174 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USLDAPFILTER_H -#define USLDAPFILTER_H - -#include "usServiceReference.h" -#include "usServiceProperties.h" - -#include "usSharedData.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4251) -#endif - -US_BEGIN_NAMESPACE - -class LDAPFilterData; - -/** - * \ingroup MicroServices - * - * An RFC 1960-based Filter. - * - *

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

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

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

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

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

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

- * This implementation returns the result of calling - * this->ToString() == other.ToString(). - * - * @param other The object to compare against this LDAPFilter. - * @return Returns the result of calling - * this->ToString() == other.ToString(). - */ - bool operator==(const LDAPFilter& other) const; - - LDAPFilter& operator=(const LDAPFilter& filter); - -protected: - - SharedDataPointer d; - -}; - -US_END_NAMESPACE - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -/** - * \ingroup MicroServices - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(LDAPFilter)& filter); - -#endif // USLDAPFILTER_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceEvent.cpp b/Core/Code/CppMicroServices/src/service/usServiceEvent.cpp deleted file mode 100644 index 7582409df8..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceEvent.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usServiceEvent.h" - -#include "usServiceProperties.h" - -US_BEGIN_NAMESPACE - -class ServiceEventData : public SharedData -{ -public: - - ServiceEventData(const ServiceEvent::Type& type, const ServiceReference& reference) - : type(type), reference(reference) - { - - } - - ServiceEventData(const ServiceEventData& other) - : SharedData(other), type(other.type), reference(other.reference) - { - - } - - const ServiceEvent::Type type; - const ServiceReference reference; - -private: - - // purposely not implemented - ServiceEventData& operator=(const ServiceEventData&); -}; - -ServiceEvent::ServiceEvent() - : d(0) -{ - -} - -ServiceEvent::~ServiceEvent() -{ - -} - -bool ServiceEvent::IsNull() const -{ - return !d; -} - -ServiceEvent::ServiceEvent(Type type, const ServiceReference& reference) - : d(new ServiceEventData(type, reference)) -{ - -} - -ServiceEvent::ServiceEvent(const ServiceEvent& other) - : d(other.d) -{ - -} - -ServiceEvent& ServiceEvent::operator=(const ServiceEvent& other) -{ - d = other.d; - return *this; -} - -ServiceReference ServiceEvent::GetServiceReference() const -{ - return d->reference; -} - -ServiceEvent::Type ServiceEvent::GetType() const -{ - return d->type; -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -std::ostream& operator<<(std::ostream& os, const ServiceEvent::Type& type) -{ - switch(type) - { - case ServiceEvent::MODIFIED: return os << "MODIFIED"; - case ServiceEvent::MODIFIED_ENDMATCH: return os << "MODIFIED_ENDMATCH"; - case ServiceEvent::REGISTERED: return os << "REGISTERED"; - case ServiceEvent::UNREGISTERING: return os << "UNREGISTERING"; - - default: return os << "unknown service event type (" << static_cast(type) << ")"; - } -} - -std::ostream& operator<<(std::ostream& os, const ServiceEvent& event) -{ - if (event.IsNull()) return os << "NONE"; - - os << event.GetType(); - - ServiceReference sr = event.GetServiceReference(); - if (sr) - { - // Some events will not have a service reference - long int sid = any_cast(sr.GetProperty(ServiceConstants::SERVICE_ID())); - os << " " << sid; - - Any classes = sr.GetProperty(ServiceConstants::OBJECTCLASS()); - os << " objectClass=" << classes << ")"; - } - - return os; -} diff --git a/Core/Code/CppMicroServices/src/service/usServiceEvent.h b/Core/Code/CppMicroServices/src/service/usServiceEvent.h deleted file mode 100644 index 1d181deed2..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceEvent.h +++ /dev/null @@ -1,191 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USSERVICEEVENT_H -#define USSERVICEEVENT_H - -#ifdef REGISTERED -#ifdef _WIN32 -#error The REGISTERED preprocessor define clashes with the ServiceEvent::REGISTERED\ - enum type. Try to reorder your includes, compile with WIN32_LEAN_AND_MEAN, or undef\ - the REGISTERED macro befor including this header. -#else -#error The REGISTERED preprocessor define clashes with the ServiceEvent::REGISTERED\ - enum type. Try to reorder your includes or undef the REGISTERED macro befor including\ - this header. -#endif -#endif - -#include "usSharedData.h" - -#include "usServiceReference.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4251) -#endif - -US_BEGIN_NAMESPACE - -class ServiceEventData; - -/** - * \ingroup MicroServices - * - * An event from the Micro Services framework describing a service lifecycle change. - *

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

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

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

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

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

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

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

    - *
  • {@link #REGISTERED}
  • - *
  • {@link #MODIFIED}
  • - *
  • {@link #MODIFIED_ENDMATCH}
  • - *
  • {@link #UNREGISTERING}
  • - *
- * - * @return Type of service lifecycle change. - */ - Type GetType() const; - -}; - -US_END_NAMESPACE - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -/** - * \ingroup MicroServices - * @{ - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceEvent::Type)& type); -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceEvent)& event); -/** @}*/ - -#endif // USSERVICEEVENT_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceException.cpp b/Core/Code/CppMicroServices/src/service/usServiceException.cpp deleted file mode 100644 index 89e9e19bc2..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceException.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usServiceException.h" - -#include - -US_BEGIN_NAMESPACE - -ServiceException::ServiceException(const std::string& msg, const Type& type) - : std::runtime_error(msg), type(type) -{ - -} - -ServiceException::ServiceException(const ServiceException& o) - : std::runtime_error(o), type(o.type) -{ - -} - -ServiceException& ServiceException::operator=(const ServiceException& o) -{ - std::runtime_error::operator=(o); - this->type = o.type; - return *this; -} - -ServiceException::Type ServiceException::GetType() const -{ - return type; -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -std::ostream& operator<<(std::ostream& os, const ServiceException& exc) -{ - return os << "ServiceException: " << exc.what(); -} diff --git a/Core/Code/CppMicroServices/src/service/usServiceException.h b/Core/Code/CppMicroServices/src/service/usServiceException.h deleted file mode 100644 index 210697801b..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceException.h +++ /dev/null @@ -1,126 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICEEXCEPTION_H -#define USSERVICEEXCEPTION_H - -#include - -#include - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4275) -#endif - -US_BEGIN_NAMESPACE - -/** - * \ingroup MicroServices - * - * A service exception used to indicate that a service problem occurred. - * - *

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

- * This exception conforms to the general purpose exception chaining mechanism. - */ -class US_EXPORT ServiceException : public std::runtime_error -{ -public: - - enum Type { - /** - * No exception type is unspecified. - */ - UNSPECIFIED = 0, - /** - * The service has been unregistered. - */ - UNREGISTERED = 1, - /** - * The service factory produced an invalid service object. - */ - FACTORY_ERROR = 2, - /** - * The service factory threw an exception. - */ - FACTORY_EXCEPTION = 3, - /** - * An error occurred invoking a remote service. - */ - REMOTE = 5, - /** - * The service factory resulted in a recursive call to itself for the - * requesting module. - */ - FACTORY_RECURSION = 6 - }; - - /** - * Creates a ServiceException with the specified message, - * type and exception cause. - * - * @param msg The associated message. - * @param type The type for this exception. - */ - ServiceException(const std::string& msg, const Type& type = UNSPECIFIED); - - ServiceException(const ServiceException& o); - ServiceException& operator=(const ServiceException& o); - - ~ServiceException() throw() { } - - /** - * Returns the type for this exception or UNSPECIFIED if the - * type was unspecified or unknown. - * - * @return The type of this exception. - */ - Type GetType() const; - -private: - - /** - * Type of service exception. - */ - Type type; - -}; - -US_END_NAMESPACE - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -/** - * \ingroup MicroServices - * @{ - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceException)& exc); -/** @}*/ - -#endif // USSERVICEEXCEPTION_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceFactory.h b/Core/Code/CppMicroServices/src/service/usServiceFactory.h deleted file mode 100644 index 84c589e768..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceFactory.h +++ /dev/null @@ -1,111 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usServiceRegistration.h" - -US_BEGIN_NAMESPACE - -/** - * \ingroup MicroServices - * - * Allows services to provide customized service objects in the module - * environment. - * - *

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

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

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

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

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

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

- * The framework invokes this method when a service has been released by a - * module. The service object may then be destroyed. - * - * @param module The Module releasing the service. - * @param registration The ServiceRegistration object for the - * service. - * @param service The service object returned by a previous call to the - * ServiceFactory::GetService method. - * @see ModuleContext#UngetService - */ - virtual void UngetService(Module* module, const ServiceRegistration& registration, - US_BASECLASS_NAME* service) = 0; -}; - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceInterface.h b/Core/Code/CppMicroServices/src/service/usServiceInterface.h deleted file mode 100644 index abe6632457..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceInterface.h +++ /dev/null @@ -1,104 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICEINTERFACE_H -#define USSERVICEINTERFACE_H - -#include - -/** - * \ingroup MicroServices - * - * Returns a unique id for a given type. - * - * This template method is specialized in the macro - * #US_DECLARE_SERVICE_INTERFACE to return a unique id - * for each service interface. - * - * @tparam T The service interface type. - * @return A unique id for the service interface type T. - */ -template inline const char* us_service_interface_iid() -{ return 0; } - -template inline const char* us_service_impl_name(T* /*impl*/) -{ return "(unknown implementation)"; } - -#if defined(QT_DEBUG) || defined(QT_NO_DEBUG) -#include -#include US_BASECLASS_HEADER - -#define US_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id) \ - template<> inline const char* qobject_interface_iid<_service_interface_type *>() \ - { return _service_interface_id; } \ - template<> inline const char* us_service_interface_iid<_service_interface_type *>() \ - { return _service_interface_id; } \ - template<> inline _service_interface_type *qobject_cast<_service_interface_type *>(QObject *object) \ - { return dynamic_cast<_service_interface_type*>(reinterpret_cast((object ? object->qt_metacast(_service_interface_id) : 0))); } \ - template<> inline _service_interface_type *qobject_cast<_service_interface_type *>(const QObject *object) \ - { return dynamic_cast<_service_interface_type*>(reinterpret_cast((object ? const_cast(object)->qt_metacast(_service_interface_id) : 0))); } - -#else - -/** - * \ingroup MicroServices - * - * \brief Declare a CppMicroServices service interface. - * - * This macro associates the given identifier \e _service_interface_id (a string literal) to the - * interface class called _service_interface_type. The Identifier must be unique. For example: - * - * \code - * #include - * - * struct ISomeInterace { ... }; - * - * US_DECLARE_SERVICE_INTERFACE(ISomeInterface, "com.mycompany.service.ISomeInterface/1.0") - * \endcode - * - * This macro is normally used right after the class definition for _service_interface_type, in a header file. - * - * If you want to use #US_DECLARE_SERVICE_INTERFACE with interface classes declared in a - * namespace then you have to make sure the #US_DECLARE_SERVICE_INTERFACE macro call is not - * inside a namespace though. For example: - * - * \code - * #include - * - * namespace Foo - * { - * struct ISomeInterface { ... }; - * } - * - * US_DECLARE_SERVICE_INTERFACE(Foo::ISomeInterface, "com.mycompany.service.ISomeInterface/1.0") - * \endcode - * - * @param _service_interface_type The service interface type. - * @param _service_interface_id A string literal representing a globally unique identifier. - */ -#define US_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id) \ - template<> inline const char* us_service_interface_iid<_service_interface_type *>() \ - { return _service_interface_id; } \ - -#endif - -#endif // USSERVICEINTERFACE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp b/Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp deleted file mode 100644 index 9dab41cd6b..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usServiceListenerEntry_p.h" - -US_BEGIN_NAMESPACE - -class ServiceListenerEntryData : public SharedData -{ -public: - - ServiceListenerEntryData(Module* mc, const ServiceListenerEntry::ServiceListener& l, - void* data, const std::string& filter) - : mc(mc), listener(l), data(data), bRemoved(false), ldap() - { - if (!filter.empty()) - { - ldap = LDAPExpr(filter); - } - } - - ~ServiceListenerEntryData() - { - - } - - Module* const mc; - ServiceListenerEntry::ServiceListener listener; - void* data; - bool bRemoved; - LDAPExpr ldap; - - /** - * The elements of "simple" filters are cached, for easy lookup. - * - * The grammar for simple filters is as follows: - * - *

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

- * The index of the vector determines which key the cache is for - * (see ServiceListenerState#hashedKeys). For each key, there is - * a vector pointing out the values which are accepted by this - * ServiceListenerEntry's filter. This cache is maintained to make - * it easy to remove this service listener. - */ - LDAPExpr::LocalCache local_cache; - -private: - - // purposely not implemented - ServiceListenerEntryData(const ServiceListenerEntryData&); - ServiceListenerEntryData& operator=(const ServiceListenerEntryData&); -}; - -ServiceListenerEntry::ServiceListenerEntry(const ServiceListenerEntry& other) - : d(other.d) -{ - -} - -ServiceListenerEntry::~ServiceListenerEntry() -{ - -} - -ServiceListenerEntry& ServiceListenerEntry::operator=(const ServiceListenerEntry& other) -{ - d = other.d; - return *this; -} - -bool ServiceListenerEntry::operator==(const ServiceListenerEntry& other) const -{ - return ((d->mc == 0 || other.d->mc == 0) || d->mc == other.d->mc) && - (d->data == other.d->data) && ServiceListenerCompare()(d->listener, other.d->listener); -} - -bool ServiceListenerEntry::operator<(const ServiceListenerEntry& other) const -{ - return (d->mc == other.d->mc) ? (d->data < other.d->data) : (d->mc < other.d->mc); -} - -void ServiceListenerEntry::SetRemoved(bool removed) const -{ - d->bRemoved = removed; -} - -bool ServiceListenerEntry::IsRemoved() const -{ - return d->bRemoved; -} - -ServiceListenerEntry::ServiceListenerEntry(Module* mc, const ServiceListener& l, - void* data, const std::string& filter) - : d(new ServiceListenerEntryData(mc, l, data, filter)) -{ - -} - -Module* ServiceListenerEntry::GetModule() const -{ - return d->mc; -} - -std::string ServiceListenerEntry::GetFilter() const -{ - return d->ldap.IsNull() ? std::string() : d->ldap.ToString(); -} - -LDAPExpr ServiceListenerEntry::GetLDAPExpr() const -{ - return d->ldap; -} - -LDAPExpr::LocalCache& ServiceListenerEntry::GetLocalCache() const -{ - return d->local_cache; -} - -void ServiceListenerEntry::CallDelegate(const ServiceEvent& event) const -{ - d->listener(event); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h b/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h deleted file mode 100644 index ebcf167272..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceListenerEntry_p.h +++ /dev/null @@ -1,97 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICELISTENERENTRY_H -#define USSERVICELISTENERENTRY_H - -#include -#include - -#include "usLDAPExpr_p.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4396) -#endif - -US_BEGIN_NAMESPACE - -class Module; -class ServiceListenerEntryData; - -/** - * Data structure for saving service listener info. Contains - * the optional service listener filter, in addition to the info - * in ListenerEntry. - */ -class ServiceListenerEntry -{ - -public: - - typedef US_SERVICE_LISTENER_FUNCTOR ServiceListener; - - ServiceListenerEntry(const ServiceListenerEntry& other); - ~ServiceListenerEntry(); - ServiceListenerEntry& operator=(const ServiceListenerEntry& other); - - bool operator==(const ServiceListenerEntry& other) const; - - bool operator<(const ServiceListenerEntry& other) const; - - void SetRemoved(bool removed) const; - bool IsRemoved() const; - - ServiceListenerEntry(Module* mc, const ServiceListener& l, void* data, const std::string& filter = ""); - - Module* GetModule() const; - - std::string GetFilter() const; - - LDAPExpr GetLDAPExpr() const; - - LDAPExpr::LocalCache& GetLocalCache() const; - - void CallDelegate(const ServiceEvent& event) const; - -private: - - US_HASH_FUNCTION_FRIEND(ServiceListenerEntry); - - ExplicitlySharedDataPointer d; -}; - -US_END_NAMESPACE - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceListenerEntry)) - -return US_HASH_FUNCTION(const US_PREPEND_NAMESPACE(ServiceListenerEntryData)*, arg.d.ConstData()); - -US_HASH_FUNCTION_END -US_HASH_FUNCTION_NAMESPACE_END - -#endif // USSERVICELISTENERENTRY_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp b/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp deleted file mode 100644 index c9036c83db..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceListeners.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usUtils_p.h" - -#include "usServiceListeners_p.h" -#include "usServiceReferencePrivate.h" - -#include "usModule.h" - -//#include - -US_BEGIN_NAMESPACE - -const int ServiceListeners::OBJECTCLASS_IX = 0; -const int ServiceListeners::SERVICE_ID_IX = 1; - -ServiceListeners::ServiceListeners() -{ - hashedServiceKeys.push_back(ServiceConstants::OBJECTCLASS()); - hashedServiceKeys.push_back(ServiceConstants::SERVICE_ID()); -} - -void ServiceListeners::AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, - void* data, const std::string& filter) -{ - MutexLocker lock(mutex); - - ServiceListenerEntry sle(mc->GetModule(), listener, data, filter); - if (serviceSet.find(sle) != serviceSet.end()) - { - RemoveServiceListener_unlocked(sle); - } - serviceSet.insert(sle); - CheckSimple(sle); -} - -void ServiceListeners::RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, - void* data) -{ - ServiceListenerEntry entryToRemove(mc->GetModule(), listener, data); - - MutexLocker lock(mutex); - RemoveServiceListener_unlocked(entryToRemove); -} - -void ServiceListeners::RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove) -{ - for (ServiceListenerEntries::iterator it = serviceSet.begin(); - it != serviceSet.end(); ++it) - { - if (it->operator ==(entryToRemove)) - { - it->SetRemoved(true); - RemoveFromCache(*it); - serviceSet.erase(it); - break; - } - } -} - -void ServiceListeners::AddModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) -{ - MutexLocker lock(moduleListenerMapMutex); - ModuleListenerMap::value_type::second_type& listeners = moduleListenerMap[mc]; - if (std::find_if(listeners.begin(), listeners.end(), std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))) == listeners.end()) - { - listeners.push_back(std::make_pair(listener, data)); - } -} - -void ServiceListeners::RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) -{ - MutexLocker lock(moduleListenerMapMutex); - moduleListenerMap[mc].remove_if(std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))); -} - -void ServiceListeners::ModuleChanged(const ModuleEvent& evt) -{ - MutexLocker lock(moduleListenerMapMutex); - for(ModuleListenerMap::iterator i = moduleListenerMap.begin(); - i != moduleListenerMap.end(); ++i) - { - for(std::list >::iterator j = i->second.begin(); - j != i->second.end(); ++j) - { - (j->first)(evt); - } - } -} - -void ServiceListeners::RemoveAllListeners(ModuleContext* mc) -{ - { - MutexLocker lock(mutex); - for (ServiceListenerEntries::iterator it = serviceSet.begin(); - it != serviceSet.end(); ) - { - - if (it->GetModule() == mc->GetModule()) - { - RemoveFromCache(*it); - serviceSet.erase(it++); - } - else - { - ++it; - } - } - } - - { - MutexLocker lock(moduleListenerMapMutex); - moduleListenerMap.erase(mc); - } -} - -void ServiceListeners::ServiceChanged(const ServiceListenerEntries& receivers, - const ServiceEvent& evt) -{ - ServiceListenerEntries matchBefore; - ServiceChanged(receivers, evt, matchBefore); -} - -void ServiceListeners::ServiceChanged(const ServiceListenerEntries& receivers, - const ServiceEvent& evt, - ServiceListenerEntries& matchBefore) -{ - ServiceReference sr = evt.GetServiceReference(); - int n = 0; - - for (ServiceListenerEntries::const_iterator l = receivers.begin(); - l != receivers.end(); ++l) - { - if (!matchBefore.empty()) - { - matchBefore.erase(*l); - } - - if (!l->IsRemoved()) - { - try - { - ++n; - l->CallDelegate(evt); - } - catch (...) - { - US_WARN << "Service listener" - #ifdef US_MODULE_SUPPORT_ENABLED - << " in " << l->GetModule()->GetName() - #endif - << " threw an exception!"; - } - } - } - - //US_DEBUG << "Notified " << n << " listeners"; -} - -void ServiceListeners::GetMatchingServiceListeners(const ServiceReference& sr, ServiceListenerEntries& set, - bool lockProps) -{ - MutexLocker lock(mutex); - - // Check complicated or empty listener filters - int n = 0; - for (std::list::const_iterator sse = complicatedListeners.begin(); - sse != complicatedListeners.end(); ++sse) - { - ++n; - if (sse->GetLDAPExpr().IsNull() || - sse->GetLDAPExpr().Evaluate(sr.d->GetProperties(), false)) - { - set.insert(*sse); - } - } - - //US_DEBUG << "Added " << set.size() << " out of " << n - // << " listeners with complicated filters"; - - // Check the cache - const std::list c(any_cast > - (sr.d->GetProperty(ServiceConstants::OBJECTCLASS(), lockProps))); - for (std::list::const_iterator objClass = c.begin(); - objClass != c.end(); ++objClass) - { - AddToSet(set, OBJECTCLASS_IX, *objClass); - } - - long service_id = any_cast(sr.d->GetProperty(ServiceConstants::SERVICE_ID(), lockProps)); - std::stringstream ss; - ss << service_id; - AddToSet(set, SERVICE_ID_IX, ss.str()); -} - -void ServiceListeners::RemoveFromCache(const ServiceListenerEntry& sle) -{ - if (!sle.GetLocalCache().empty()) - { - for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) - { - CacheType& keymap = cache[i]; - std::vector& l = sle.GetLocalCache()[i]; - for (std::vector::const_iterator it = l.begin(); - it != l.end(); ++it) - { - std::list& sles = keymap[*it]; - sles.remove(sle); - if (sles.empty()) - { - keymap.erase(*it); - } - } - } - } - else - { - complicatedListeners.remove(sle); - } -} - - void ServiceListeners::CheckSimple(const ServiceListenerEntry& sle) { - if (sle.GetLDAPExpr().IsNull()) - { - complicatedListeners.push_back(sle); - } - else - { - LDAPExpr::LocalCache local_cache; - if (sle.GetLDAPExpr().IsSimple(hashedServiceKeys, local_cache, false)) - { - sle.GetLocalCache() = local_cache; - for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) - { - for (std::vector::const_iterator it = local_cache[i].begin(); - it != local_cache[i].end(); ++it) - { - std::list& sles = cache[i][*it]; - sles.push_back(sle); - } - } - } - else - { - //US_DEBUG << "Too complicated filter: " << sle.GetFilter(); - complicatedListeners.push_back(sle); - } - } - } - -void ServiceListeners::AddToSet(ServiceListenerEntries& set, - int cache_ix, const std::string& val) -{ - std::list& l = cache[cache_ix][val]; - if (!l.empty()) - { - //US_DEBUG << hashedServiceKeys[cache_ix] << " matches " << l.size(); - - for (std::list::const_iterator entry = l.begin(); - entry != l.end(); ++entry) - { - set.insert(*entry); - } - } - else - { - //US_DEBUG << hashedServiceKeys[cache_ix] << " matches none"; - } -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceListeners_p.h b/Core/Code/CppMicroServices/src/service/usServiceListeners_p.h deleted file mode 100644 index 771f45bc0c..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceListeners_p.h +++ /dev/null @@ -1,176 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICELISTENERS_H -#define USSERVICELISTENERS_H - -#include -#include -#include - -#include - -#include "usServiceListenerEntry_p.h" - -US_BEGIN_NAMESPACE - -class CoreModuleContext; -class ModuleContext; - -/** - * Here we handle all listeners that modules have registered. - * - */ -class ServiceListeners { - -private: - - typedef Mutex MutexType; - typedef MutexLock MutexLocker; - -public: - - typedef US_MODULE_LISTENER_FUNCTOR ModuleListener; - typedef US_UNORDERED_MAP_TYPE > > ModuleListenerMap; - ModuleListenerMap moduleListenerMap; - MutexType moduleListenerMapMutex; - - typedef US_UNORDERED_MAP_TYPE > CacheType; - typedef US_UNORDERED_SET_TYPE ServiceListenerEntries; - -private: - - std::vector hashedServiceKeys; - static const int OBJECTCLASS_IX; // = 0; - static const int SERVICE_ID_IX; // = 1; - - /* Service listeners with complicated or empty filters */ - std::list complicatedListeners; - - /* Service listeners with "simple" filters are cached. */ - CacheType cache[2]; - - ServiceListenerEntries serviceSet; - - MutexType mutex; - -public: - - ServiceListeners(); - - /** - * Add a new service listener. If an old one exists, and it has the - * same owning module, the old listener is removed first. - * - * @param mc The module context adding this listener. - * @param listener The service listener to add. - * @param data Additional data to distinguish ServiceListener objects. - * @param filter An LDAP filter string to check when a service is modified. - * @exception org.osgi.framework.InvalidSyntaxException - * If the filter is not a correct LDAP expression. - */ - void AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, - void* data, const std::string& filter); - - /** - * Remove service listener from current framework. Silently ignore - * if listener doesn't exist. If listener is registered more than - * once remove all instances. - * - * @param mc The module context who wants to remove listener. - * @param listener Object to remove. - * @param data Additional data to distinguish ServiceListener objects. - */ - void RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, - void* data); - - /** - * Add a new module listener. - * - * @param mc The module context adding this listener. - * @param listener The module listener to add. - * @param data Additional data to distinguish ModuleListener objects. - */ - void AddModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data); - - /** - * Remove module listener from current framework. Silently ignore - * if listener doesn't exist. - * - * @param mc The module context who wants to remove listener. - * @param listener Object to remove. - * @param data Additional data to distinguish ModuleListener objects. - */ - void RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data); - - void ModuleChanged(const ModuleEvent& evt); - - /** - * Remove all listener registered by a module in the current framework. - * - * @param mc Module context which listeners we want to remove. - */ - void RemoveAllListeners(ModuleContext* mc); - - /** - * Receive notification that a service has had a change occur in its lifecycle. - * - * @see org.osgi.framework.ServiceListener#serviceChanged - */ - void ServiceChanged(const ServiceListenerEntries& receivers, - const ServiceEvent& evt, - ServiceListenerEntries& matchBefore); - - void ServiceChanged(const ServiceListenerEntries& receivers, - const ServiceEvent& evt); - - /** - * - * - */ - void GetMatchingServiceListeners(const ServiceReference& sr, ServiceListenerEntries& listeners, - bool lockProps = true); - - -private: - - void RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove); - - /** - * Remove all references to a service listener from the service listener - * cache. - */ - void RemoveFromCache(const ServiceListenerEntry& sle); - - /** - * Checks if the specified service listener's filter is simple enough - * to cache. - */ - void CheckSimple(const ServiceListenerEntry& sle); - - void AddToSet(ServiceListenerEntries& set, int cache_ix, const std::string& val); - -}; - -US_END_NAMESPACE - -#endif // USSERVICELISTENERS_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceProperties.cpp b/Core/Code/CppMicroServices/src/service/usServiceProperties.cpp deleted file mode 100644 index 61ee48daf9..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceProperties.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usServiceProperties.h" -#include - -#include - -US_BEGIN_NAMESPACE - -const std::string& ServiceConstants::OBJECTCLASS() -{ - static const std::string s("objectclass"); - return s; -} - -const std::string& ServiceConstants::SERVICE_ID() -{ - static const std::string s("service.id"); - return s; -} - -const std::string& ServiceConstants::SERVICE_RANKING() -{ - static const std::string s("service.ranking"); - return s; -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -// make sure all static locals get constructed, so that they -// can be used in destructors of global statics. -std::string tmp1 = ServiceConstants::OBJECTCLASS(); -std::string tmp2 = ServiceConstants::SERVICE_ID(); -std::string tmp3 = ServiceConstants::SERVICE_RANKING(); diff --git a/Core/Code/CppMicroServices/src/service/usServiceProperties.h b/Core/Code/CppMicroServices/src/service/usServiceProperties.h deleted file mode 100644 index a2d4a4a472..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceProperties.h +++ /dev/null @@ -1,199 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef US_SERVICE_PROPERTIES_H -#define US_SERVICE_PROPERTIES_H - - -#include - -#include - -#include "usAny.h" - -/// \cond -US_BEGIN_NAMESPACE - -struct ci_char_traits : public std::char_traits - // just inherit all the other functions - // that we don't need to override -{ - - static bool eq(char c1, char c2) - { - return std::toupper(c1) == std::toupper(c2); - } - - static bool ne(char c1, char c2) - { - return std::toupper(c1) != std::toupper(c2); - } - - static bool lt(char c1, char c2) - { - return std::toupper(c1) < std::toupper(c2); - } - - static bool gt(char c1, char c2) - { - return std::toupper(c1) > std::toupper(c2); - } - - static int compare(const char* s1, const char* s2, std::size_t n) - { - while (n-- > 0) - { - if (lt(*s1, *s2)) return -1; - if (gt(*s1, *s2)) return 1; - ++s1; ++s2; - } - return 0; - } - - static const char* find(const char* s, int n, char a) - { - while (n-- > 0 && std::toupper(*s) != std::toupper(a)) - { - ++s; - } - return s; - } - -}; - -class ci_string : public std::basic_string -{ -private: - - typedef std::basic_string Super; - -public: - - inline ci_string() : Super() {} - inline ci_string(const ci_string& cistr) : Super(cistr) {} - inline ci_string(const ci_string& cistr, size_t pos, size_t n) : Super(cistr, pos, n) {} - inline ci_string(const char* s, size_t n) : Super(s, n) {} - inline ci_string(const char* s) : Super(s) {} - inline ci_string(size_t n, char c) : Super(n, c) {} - - inline ci_string(const std::string& str) : Super(str.begin(), str.end()) {} - - template ci_string(InputIterator b, InputIterator e) - : Super(b, e) - {} - - inline operator std::string () const - { - return std::string(begin(), end()); - } -}; - -US_END_NAMESPACE - -US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ci_string)) - - std::string ls(arg); - std::transform(ls.begin(), ls.end(), ls.begin(), ::tolower); - - using namespace US_HASH_FUNCTION_NAMESPACE; - return US_HASH_FUNCTION(std::string, ls); - -US_HASH_FUNCTION_END -US_HASH_FUNCTION_NAMESPACE_END - -/// \endcond - -US_BEGIN_NAMESPACE - -/** - * \ingroup MicroServices - * - * A hash table based map class with case-insensitive keys. This class - * uses ci_string as key type and Any as values. Due - * to the conversion capabilities of ci_string, std::string objects - * can be used transparantly to insert or retrieve key-value pairs. - * - *

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

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

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

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

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

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

- * If the supplied property value is not of type int, it is - * deemed to have a ranking value of zero. - */ -US_EXPORT const std::string& SERVICE_RANKING(); // = "service.ranking" - -} - -US_END_NAMESPACE - -#endif // US_SERVICE_PROPERTIES_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceReference.cpp b/Core/Code/CppMicroServices/src/service/usServiceReference.cpp deleted file mode 100644 index 68d5c696ec..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceReference.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usServiceReference.h" -#include "usServiceReferencePrivate.h" -#include "usServiceRegistrationPrivate.h" - -#include "usModule.h" -#include "usModulePrivate.h" - - -US_BEGIN_NAMESPACE - -typedef ServiceRegistrationPrivate::MutexType MutexType; -typedef MutexLock MutexLocker; - -ServiceReference::ServiceReference() - : d(new ServiceReferencePrivate(0)) -{ - -} - -ServiceReference::ServiceReference(const ServiceReference& ref) - : d(ref.d) -{ - d->ref.Ref(); -} - -ServiceReference::ServiceReference(ServiceRegistrationPrivate* reg) - : d(new ServiceReferencePrivate(reg)) -{ - -} - -ServiceReference::operator bool() const -{ - return GetModule() != 0; -} - -ServiceReference& ServiceReference::operator=(int null) -{ - if (null == 0) - { - if (!d->ref.Deref()) - delete d; - d = new ServiceReferencePrivate(0); - } - return *this; -} - -ServiceReference::~ServiceReference() -{ - if (!d->ref.Deref()) - delete d; -} - -Any ServiceReference::GetProperty(const std::string& key) const -{ - MutexLocker lock(d->registration->propsLock); - - ServiceProperties::const_iterator iter = d->registration->properties.find(key); - if (iter != d->registration->properties.end()) - return iter->second; - return Any(); -} - -void ServiceReference::GetPropertyKeys(std::vector& keys) const -{ - MutexLocker lock(d->registration->propsLock); - - ServiceProperties::const_iterator iterEnd = d->registration->properties.end(); - for (ServiceProperties::const_iterator iter = d->registration->properties.begin(); - iter != iterEnd; ++iter) - { - keys.push_back(iter->first); - } -} - -Module* ServiceReference::GetModule() const -{ - if (d->registration == 0 || d->registration->module == 0) - { - return 0; - } - - return d->registration->module->q; -} - -void ServiceReference::GetUsingModules(std::vector& modules) const -{ - MutexLocker lock(d->registration->propsLock); - - ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator end = d->registration->dependents.end(); - for (ServiceRegistrationPrivate::ModuleToRefsMap::const_iterator iter = d->registration->dependents.begin(); - iter != end; ++iter) - { - modules.push_back(iter->first); - } -} - -bool ServiceReference::operator<(const ServiceReference& reference) const -{ - int r1 = 0; - int r2 = 0; - - Any anyR1 = GetProperty(ServiceConstants::SERVICE_RANKING()); - Any anyR2 = reference.GetProperty(ServiceConstants::SERVICE_RANKING()); - if (anyR1.Type() == typeid(int)) r1 = any_cast(anyR1); - if (anyR2.Type() == typeid(int)) r2 = any_cast(anyR2); - - if (r1 != r2) - { - // use ranking if ranking differs - return r1 < r2; - } - else - { - long int id1 = any_cast(GetProperty(ServiceConstants::SERVICE_ID())); - long int id2 = any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())); - - // otherwise compare using IDs, - // is less than if it has a higher ID. - return id2 < id1; - } -} - -bool ServiceReference::operator==(const ServiceReference& reference) const -{ - return d->registration == reference.d->registration; -} - -ServiceReference& ServiceReference::operator=(const ServiceReference& reference) -{ - ServiceReferencePrivate* curr_d = d; - d = reference.d; - d->ref.Ref(); - - if (!curr_d->ref.Deref()) - delete curr_d; - - return *this; -} - -std::size_t ServiceReference::Hash() const -{ - using namespace US_HASH_FUNCTION_NAMESPACE; - return US_HASH_FUNCTION(ServiceRegistrationPrivate*, this->d->registration); -} - -US_END_NAMESPACE - -US_USE_NAMESPACE - -std::ostream& operator<<(std::ostream& os, const ServiceReference& serviceRef) -{ - os << "Reference for service object registered from " - << serviceRef.GetModule()->GetName() << " " << serviceRef.GetModule()->GetVersion() - << " ("; - std::vector keys; - serviceRef.GetPropertyKeys(keys); - size_t keySize = keys.size(); - for(size_t i = 0; i < keySize; ++i) - { - os << keys[i] << "=" << serviceRef.GetProperty(keys[i]); - if (i < keySize-1) os << ","; - } - os << ")"; - - return os; -} - diff --git a/Core/Code/CppMicroServices/src/service/usServiceReference.h b/Core/Code/CppMicroServices/src/service/usServiceReference.h deleted file mode 100644 index c692f80cb7..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceReference.h +++ /dev/null @@ -1,223 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USSERVICEREFERENCE_H -#define USSERVICEREFERENCE_H - -#include - -US_MSVC_PUSH_DISABLE_WARNING(4396) - -US_BEGIN_NAMESPACE - -class Module; -class ServiceRegistrationPrivate; -class ServiceReferencePrivate; - -/** - * \ingroup MicroServices - * - * A reference to a service. - * - *

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

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

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

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

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

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

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

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

- * If this ServiceReference and the specified - * ServiceReference have the same \link ServiceConstants::SERVICE_ID() - * service id\endlink they are equal. This ServiceReference is less - * than the specified ServiceReference if it has a lower - * {@link ServiceConstants::SERVICE_RANKING service ranking} and greater if it has a - * higher service ranking. Otherwise, if this ServiceReference - * and the specified ServiceReference have the same - * {@link ServiceConstants::SERVICE_RANKING service ranking}, this - * ServiceReference is less than the specified - * ServiceReference if it has a higher - * {@link ServiceConstants::SERVICE_ID service id} and greater if it has a lower - * service id. - * - * @param reference The ServiceReference to be compared. - * @return Returns a false or true if this - * ServiceReference is less than or greater - * than the specified ServiceReference. - */ - bool operator<(const ServiceReference& reference) const; - - bool operator==(const ServiceReference& reference) const; - - ServiceReference& operator=(const ServiceReference& reference); - - -private: - - friend class ModulePrivate; - friend class ModuleContext; - friend class ServiceFilter; - friend class ServiceRegistrationPrivate; - friend class ServiceListeners; - friend class LDAPFilter; - - template friend class ServiceTracker; - template friend class ServiceTrackerPrivate; - template friend class ModuleAbstractTracked; - - US_HASH_FUNCTION_FRIEND(ServiceReference); - - std::size_t Hash() const; - - ServiceReference(ServiceRegistrationPrivate* reg); - - ServiceReferencePrivate* d; - -}; - -US_END_NAMESPACE - -US_MSVC_POP_WARNING - -/** - * \ingroup MicroServices - */ -US_EXPORT std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceReference)& serviceRef); - -US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceReference)) - return arg.Hash(); -US_HASH_FUNCTION_END -US_HASH_FUNCTION_NAMESPACE_END - -#endif // USSERVICEREFERENCE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.cpp b/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.cpp deleted file mode 100644 index 71bd9387a0..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include -#ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT -#include US_BASECLASS_HEADER -#endif - -#include "usServiceReferencePrivate.h" - -#include "usServiceFactory.h" -#include "usServiceException.h" -#include "usServiceRegistry_p.h" -#include "usServiceRegistrationPrivate.h" - -#include "usModule.h" -#include "usModulePrivate.h" - -#include - -US_BEGIN_NAMESPACE - -typedef ServiceRegistrationPrivate::MutexLocker MutexLocker; - -ServiceReferencePrivate::ServiceReferencePrivate(ServiceRegistrationPrivate* reg) - : ref(1), registration(reg) -{ - if(registration) registration->ref.Ref(); -} - -ServiceReferencePrivate::~ServiceReferencePrivate() -{ - if (registration && !registration->ref.Deref()) - delete registration; -} - -US_BASECLASS_NAME* ServiceReferencePrivate::GetService(Module* module) -{ - US_BASECLASS_NAME* s = 0; - { - MutexLocker lock(registration->propsLock); - if (registration->available) - { - int count = registration->dependents[module]; - if (count == 0) - { - registration->dependents[module] = 1; - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - const std::list& classes = - ref_any_cast >(registration->properties[ServiceConstants::OBJECTCLASS()]); - if (ServiceFactory* serviceFactory = dynamic_cast(registration->GetService())) - { - try - { - s = serviceFactory->GetService(module, ServiceRegistration(registration)); - } - catch (...) - { - US_WARN << "ServiceFactory threw an exception"; - return 0; - } - if (s == 0) { - US_WARN << "ServiceFactory produced null"; - return 0; - } - for (std::list::const_iterator i = classes.begin(); - i != classes.end(); ++i) - { - if (!registration->module->coreCtx->services.CheckServiceClass(s, *i)) - { - US_WARN << "ServiceFactory produced an object " - "that did not implement: " << (*i); - return 0; - } - } - registration->serviceInstances.insert(std::make_pair(module, s)); - } - else - #endif - { - s = registration->GetService(); - } - } - else - { - registration->dependents.insert(std::make_pair(module, count + 1)); - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - if (dynamic_cast(registration->GetService())) - { - s = registration->serviceInstances[module]; - } - else - #endif - { - s = registration->GetService(); - } - } - } - } - return s; -} - -bool ServiceReferencePrivate::UngetService(Module* module, bool checkRefCounter) -{ - MutexLocker lock(registration->propsLock); - bool hadReferences = false; - bool removeService = false; - - int count= registration->dependents[module]; - if (count > 0) - { - hadReferences = true; - } - - if(checkRefCounter) - { - if (count > 1) - { - registration->dependents[module] = count - 1; - } - else if(count == 1) - { - removeService = true; - } - } - else - { - removeService = true; - } - - if (removeService) - { - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - US_BASECLASS_NAME* sfi = registration->serviceInstances[module]; - registration->serviceInstances.erase(module); - if (sfi != 0) - { - try - { - dynamic_cast( - registration->GetService())->UngetService(module, ServiceRegistration(registration), sfi); - } - catch (const std::exception& /*e*/) - { - US_WARN << "ServiceFactory threw an exception"; - } - } - #endif - registration->dependents.erase(module); - } - - return hadReferences; -} - -ServiceProperties ServiceReferencePrivate::GetProperties() const -{ - return registration->properties; -} - -Any ServiceReferencePrivate::GetProperty(const std::string& key, bool lock) const -{ - if (lock) - { - MutexLocker lock(registration->propsLock); - ServiceProperties::const_iterator iter = registration->properties.find(key); - if (iter != registration->properties.end()) - return iter->second; - } - else - { - ServiceProperties::const_iterator iter = registration->properties.find(key); - if (iter != registration->properties.end()) - return iter->second; - } - return Any(); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h b/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h deleted file mode 100644 index 5dfc241a84..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceReferencePrivate.h +++ /dev/null @@ -1,118 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICEREFERENCEPRIVATE_H -#define USSERVICEREFERENCEPRIVATE_H - -#include "usAtomicInt_p.h" - -#include "usServiceProperties.h" - - -US_BEGIN_NAMESPACE - -class Module; -class ServiceRegistrationPrivate; -class ServiceReferencePrivate; - - -/** - * \ingroup MicroServices - */ -class ServiceReferencePrivate -{ -public: - - ServiceReferencePrivate(ServiceRegistrationPrivate* reg); - - ~ServiceReferencePrivate(); - - /** - * Get the service object. - * - * @param module requester of service. - * @return Service requested or null in case of failure. - */ - US_BASECLASS_NAME* GetService(Module* module); - - /** - * Unget the service object. - * - * @param module Module who wants remove service. - * @param checkRefCounter If true decrement refence counter and remove service - * if we reach zero. If false remove service without - * checking refence counter. - * @return True if service was remove or false if only refence counter was - * decremented. - */ - bool UngetService(Module* module, bool checkRefCounter); - - /** - * Get all properties registered with this service. - * - * @return A ServiceProperties object containing properties or being empty - * if service has been removed. - */ - ServiceProperties GetProperties() const; - - /** - * Returns the property value to which the specified property key is mapped - * in the properties ServiceProperties object of the service - * referenced by this ServiceReference object. - * - *

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

- * This method must continue to return property values after the service has - * been unregistered. This is so references to unregistered services can - * still be interrogated. - * - * @param key The property key. - * @param lock If true, access of the properties of the service - * referenced by this ServiceReference object will be - * synchronized. - * @return The property value to which the key is mapped; an invalid Any - * if there is no property named after the key. - */ - Any GetProperty(const std::string& key, bool lock) const; - - /** - * Reference count for implicitly shared private implementation. - */ - AtomicInt ref; - - /** - * Link to registration object for this reference. - */ - ServiceRegistrationPrivate* const registration; - -private: - - // purposely not implemented - ServiceReferencePrivate(const ServiceReferencePrivate&); - ServiceReferencePrivate& operator=(const ServiceReferencePrivate&); -}; - -US_END_NAMESPACE - -#endif // USSERVICEREFERENCEPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp b/Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp deleted file mode 100644 index 6884c9e1c4..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistration.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT -#include US_BASECLASS_HEADER -#endif - -#include "usServiceRegistration.h" -#include "usServiceRegistrationPrivate.h" -#include "usServiceListenerEntry_p.h" -#include "usServiceRegistry_p.h" -#include "usServiceFactory.h" - -#include "usModulePrivate.h" -#include "usCoreModuleContext_p.h" - -#include - -US_BEGIN_NAMESPACE - -typedef ServiceRegistrationPrivate::MutexLocker MutexLocker; - -ServiceRegistration::ServiceRegistration() - : d(0) -{ - -} - -ServiceRegistration::ServiceRegistration(const ServiceRegistration& reg) - : d(reg.d) -{ - if (d) d->ref.Ref(); -} - -ServiceRegistration::ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate) - : d(registrationPrivate) -{ - if (d) d->ref.Ref(); -} - -ServiceRegistration::ServiceRegistration(ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props) - : d(new ServiceRegistrationPrivate(module, service, props)) -{ - -} - -ServiceRegistration::operator bool() const -{ - return d != 0; -} - -ServiceRegistration& ServiceRegistration::operator=(int null) -{ - if (null == 0) - { - if (d && !d->ref.Deref()) - { - delete d; - } - d = 0; - } - return *this; -} - -ServiceRegistration::~ServiceRegistration() -{ - if (d && !d->ref.Deref()) - delete d; -} - -ServiceReference ServiceRegistration::GetReference() const -{ - if (!d) throw std::logic_error("ServiceRegistration object invalid"); - if (!d->available) throw std::logic_error("Service is unregistered"); - - return d->reference; -} - -void ServiceRegistration::SetProperties(const ServiceProperties& props) -{ - if (!d) throw std::logic_error("ServiceRegistration object invalid"); - - MutexLocker lock(d->eventLock); - - ServiceListeners::ServiceListenerEntries before; - // TBD, optimize the locking of services - { - //MutexLocker lock2(d->module->coreCtx->globalFwLock); - - if (d->available) - { - // NYI! Optimize the MODIFIED_ENDMATCH code - int old_rank = 0; - int new_rank = 0; - - std::list classes; - { - MutexLocker lock3(d->propsLock); - - Any any = d->properties[ServiceConstants::SERVICE_RANKING()]; - if (any.Type() == typeid(int)) old_rank = any_cast(any); - - d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, before, false); - classes = ref_any_cast >(d->properties[ServiceConstants::OBJECTCLASS()]); - long int sid = any_cast(d->properties[ServiceConstants::SERVICE_ID()]); - d->properties = ServiceRegistry::CreateServiceProperties(props, classes, sid); - - any = d->properties[ServiceConstants::SERVICE_RANKING()]; - if (any.Type() == typeid(int)) new_rank = any_cast(any); - } - - if (old_rank != new_rank) - { - d->module->coreCtx->services.UpdateServiceRegistrationOrder(*this, classes); - } - } - else - { - throw std::logic_error("Service is unregistered"); - } - } - ServiceListeners::ServiceListenerEntries matchingListeners; - d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, matchingListeners); - d->module->coreCtx->listeners.ServiceChanged(matchingListeners, - ServiceEvent(ServiceEvent::MODIFIED, d->reference), - before); - - d->module->coreCtx->listeners.ServiceChanged(before, - ServiceEvent(ServiceEvent::MODIFIED_ENDMATCH, d->reference)); -} - -void ServiceRegistration::Unregister() -{ - if (!d) throw std::logic_error("ServiceRegistration object invalid"); - - if (d->unregistering) return; // Silently ignore redundant unregistration. - { - MutexLocker lock(d->eventLock); - if (d->unregistering) return; - d->unregistering = true; - - if (d->available) - { - if (d->module) - { - d->module->coreCtx->services.RemoveServiceRegistration(*this); - } - } - else - { - throw std::logic_error("Service is unregistered"); - } - } - - if (d->module) - { - ServiceListeners::ServiceListenerEntries listeners; - d->module->coreCtx->listeners.GetMatchingServiceListeners(d->reference, listeners); - d->module->coreCtx->listeners.ServiceChanged( - listeners, - ServiceEvent(ServiceEvent::UNREGISTERING, d->reference)); - } - - { - MutexLocker lock(d->eventLock); - { - MutexLocker lock2(d->propsLock); - d->available = false; - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - if (d->module) - { - ServiceRegistrationPrivate::ModuleToServicesMap::const_iterator end = d->serviceInstances.end(); - for (ServiceRegistrationPrivate::ModuleToServicesMap::const_iterator i = d->serviceInstances.begin(); - i != end; ++i) - { - US_BASECLASS_NAME* obj = i->second; - try - { - // NYI, don't call inside lock - dynamic_cast(d->service)->UngetService(i->first, - *this, - obj); - } - catch (const std::exception& /*ue*/) - { - US_WARN << "ServiceFactory UngetService implementation threw an exception"; - } - } - } - #endif - d->module = 0; - d->dependents.clear(); - d->service = 0; - d->serviceInstances.clear(); - // increment the reference count, since "d->reference" was used originally - // to keep d alive. - d->ref.Ref(); - d->reference = 0; - d->unregistering = false; - } - } -} - -bool ServiceRegistration::operator<(const ServiceRegistration& o) const -{ - if (!d) return true; - return d->reference <(o.d->reference); -} - -bool ServiceRegistration::operator==(const ServiceRegistration& registration) const -{ - return d == registration.d; -} - -ServiceRegistration& ServiceRegistration::operator=(const ServiceRegistration& registration) -{ - ServiceRegistrationPrivate* curr_d = d; - d = registration.d; - if (d) d->ref.Ref(); - - if (curr_d && !curr_d->ref.Deref()) - delete curr_d; - - return *this; -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistration.h b/Core/Code/CppMicroServices/src/service/usServiceRegistration.h deleted file mode 100644 index 0203adedd2..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistration.h +++ /dev/null @@ -1,191 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USSERVICEREGISTRATION_H -#define USSERVICEREGISTRATION_H - -#include "usServiceProperties.h" -#include "usServiceReference.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4396) -#endif - -US_BEGIN_NAMESPACE - -class ModulePrivate; - -/** - * \ingroup MicroServices - * - * A registered service. - * - *

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

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

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

- * The ServiceConstants#OBJECTCLASS and ServiceConstants#SERVICE_ID keys - * cannot be modified by this method. These values are set by the framework - * when the service is registered in the environment. - * - *

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

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

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

    - *
  1. The service is removed from the framework service registry so that - * it can no longer be obtained. - *
  2. A service event of type ServiceEvent#UNREGISTERING is fired - * so that modules using this service can release their use of the service. - * Once delivery of the service event is complete, the - * ServiceRegistration objects for the service may no longer be - * used to get a service object for the service. - *
  3. For each module whose use count for this service is greater than - * zero:
    - * The module's use count for this service is set to zero.
    - * If the service was registered with a ServiceFactory object, the - * ServiceFactory#UngetService method is called to release - * the service object for the module. - *
- * - * @throws std::logic_error If this - * ServiceRegistration object has already been - * unregistered or if it is invalid. - * @see ModuleContext#UngetService - * @see ServiceFactory#UngetService - */ - void Unregister(); - - bool operator<(const ServiceRegistration& o) const; - - bool operator==(const ServiceRegistration& registration) const; - - ServiceRegistration& operator=(const ServiceRegistration& registration); - - -private: - - friend class ServiceRegistry; - friend class ServiceReferencePrivate; - US_HASH_FUNCTION_FRIEND(ServiceRegistration); - - ServiceRegistration(ServiceRegistrationPrivate* registrationPrivate); - - ServiceRegistration(ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props); - - ServiceRegistrationPrivate* d; - -}; - -US_END_NAMESPACE - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -US_HASH_FUNCTION_NAMESPACE_BEGIN -US_HASH_FUNCTION_BEGIN(US_PREPEND_NAMESPACE(ServiceRegistration)) - return US_HASH_FUNCTION(US_PREPEND_NAMESPACE(ServiceRegistrationPrivate)*, arg.d); -US_HASH_FUNCTION_END -US_HASH_FUNCTION_NAMESPACE_END - - -inline std::ostream& operator<<(std::ostream& os, const US_PREPEND_NAMESPACE(ServiceRegistration)& /*reg*/) -{ - return os << "US_PREPEND_NAMESPACE(ServiceRegistration) object"; -} - -#endif // USSERVICEREGISTRATION_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp b/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp deleted file mode 100644 index da050082e1..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usServiceRegistrationPrivate.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4355) -#endif - -US_BEGIN_NAMESPACE - -ServiceRegistrationPrivate::ServiceRegistrationPrivate( - ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props) - : ref(0), service(service), module(module), reference(this), - properties(props), available(true), unregistering(false) -{ - // The reference counter is initialized to 0 because it will be - // incremented by the "reference" member. -} - -ServiceRegistrationPrivate::~ServiceRegistrationPrivate() -{ - -} - -bool ServiceRegistrationPrivate::IsUsedByModule(Module* p) -{ - return dependents.find(p) != dependents.end(); -} - -US_BASECLASS_NAME* ServiceRegistrationPrivate::GetService() -{ - return service; -} - -US_END_NAMESPACE - -#ifdef _MSC_VER -#pragma warning(pop) -#endif diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h b/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h deleted file mode 100644 index a2099c07f0..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistrationPrivate.h +++ /dev/null @@ -1,143 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICEREGISTRATIONPRIVATE_H -#define USSERVICEREGISTRATIONPRIVATE_H - -#include "usServiceReference.h" -#include "usServiceProperties.h" -#include "usAtomicInt_p.h" - -US_BEGIN_NAMESPACE - -class ModulePrivate; -class ServiceRegistration; - -/** - * \ingroup MicroServices - */ -class ServiceRegistrationPrivate -{ - -protected: - - friend class ServiceRegistration; - - // The ServiceReferencePrivate class holds a pointer to a - // ServiceRegistrationPrivate instance and needs to manipulate - // its reference count. This way it can keep the ServiceRegistrationPrivate - // instance alive and keep returning service properties for - // unregistered service instances. - friend class ServiceReferencePrivate; - - /** - * Reference count for implicitly shared private implementation. - */ - AtomicInt ref; - - /** - * Service or ServiceFactory object. - */ - US_BASECLASS_NAME* service; - -public: - - typedef Mutex MutexType; - typedef MutexLock MutexLocker; - - typedef US_UNORDERED_MAP_TYPE ModuleToRefsMap; - typedef US_UNORDERED_MAP_TYPE ModuleToServicesMap; - - /** - * Modules dependent on this service. Integer is used as - * reference counter, counting number of unbalanced getService(). - */ - ModuleToRefsMap dependents; - - /** - * Object instances that factory has produced. - */ - ModuleToServicesMap serviceInstances; - - /** - * Module registering this service. - */ - ModulePrivate* module; - - /** - * Reference object to this service registration. - */ - ServiceReference reference; - - /** - * Service properties. - */ - ServiceProperties properties; - - /** - * Is service available. I.e., if true then holders - * of a ServiceReference for the service are allowed to get it. - */ - volatile bool available; - - /** - * Avoid recursive unregistrations. I.e., if true then - * unregistration of this service has started but is not yet - * finished. - */ - volatile bool unregistering; - - /** - * Lock object for synchronous event delivery. - */ - MutexType eventLock; - - // needs to be recursive - MutexType propsLock; - - ServiceRegistrationPrivate(ModulePrivate* module, US_BASECLASS_NAME* service, - const ServiceProperties& props); - - ~ServiceRegistrationPrivate(); - - /** - * Check if a module uses this service - * - * @param p Module to check - * @return true if module uses this service - */ - bool IsUsedByModule(Module* m); - - US_BASECLASS_NAME* GetService(); - -private: - - // purposely not implemented - ServiceRegistrationPrivate(const ServiceRegistrationPrivate&); - ServiceRegistrationPrivate& operator=(const ServiceRegistrationPrivate&); - -}; - -US_END_NAMESPACE - - -#endif // USSERVICEREGISTRATIONPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp b/Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp deleted file mode 100644 index 5a49cdc7dd..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistry.cpp +++ /dev/null @@ -1,327 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include -#include - -#ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT -#include US_BASECLASS_HEADER -#endif - -#include "usServiceRegistry_p.h" -#include "usServiceFactory.h" -#include "usServiceRegistry_p.h" -#include "usServiceRegistrationPrivate.h" -#include "usModulePrivate.h" -#include "usCoreModuleContext_p.h" - - -US_BEGIN_NAMESPACE - -typedef MutexLock MutexLocker; - - -ServiceProperties ServiceRegistry::CreateServiceProperties(const ServiceProperties& in, - const std::list& classes, - long sid) -{ - static long nextServiceID = 1; - ServiceProperties props(in); - - if (!classes.empty()) - { - props.insert(std::make_pair(ServiceConstants::OBJECTCLASS(), classes)); - } - - props.insert(std::make_pair(ServiceConstants::SERVICE_ID(), sid != -1 ? sid : nextServiceID++)); - - return props; -} - -ServiceRegistry::ServiceRegistry(CoreModuleContext* coreCtx) - : core(coreCtx) -{ - -} - -ServiceRegistry::~ServiceRegistry() -{ - Clear(); -} - -void ServiceRegistry::Clear() -{ - services.clear(); - serviceRegistrations.clear(); - classServices.clear(); - core = 0; -} - -ServiceRegistration ServiceRegistry::RegisterService(ModulePrivate* module, - const std::list& classes, - US_BASECLASS_NAME* service, - const ServiceProperties& properties) -{ - if (service == 0) - { - throw std::invalid_argument("Can't register 0 as a service"); - } - - // Check if service implements claimed classes and that they exist. - for (std::list::const_iterator i = classes.begin(); - i != classes.end(); ++i) - { - if (i->empty()) - { - throw std::invalid_argument("Can't register as null class"); - } - - #ifdef US_ENABLE_SERVICE_FACTORY_SUPPORT - if (!(dynamic_cast(service))) - #endif - { - if (!CheckServiceClass(service, *i)) - { - std::string msg; - std::stringstream ss(msg); - ss << "Service class " << us_service_impl_name(service) << " is not an instance of " - << (*i) << ". Maybe you forgot to export the RTTI information for the interface."; - throw std::invalid_argument(msg); - } - } - } - - ServiceRegistration res(module, service, - CreateServiceProperties(properties, classes)); - { - MutexLocker lock(mutex); - services.insert(std::make_pair(res, classes)); - serviceRegistrations.push_back(res); - for (std::list::const_iterator i = classes.begin(); - i != classes.end(); ++i) - { - std::list& s = classServices[*i]; - std::list::iterator ip = - std::lower_bound(s.begin(), s.end(), res); - s.insert(ip, res); - } - } - - ServiceReference r = res.GetReference(); - ServiceListeners::ServiceListenerEntries listeners; - module->coreCtx->listeners.GetMatchingServiceListeners(r, listeners); - module->coreCtx->listeners.ServiceChanged(listeners, - ServiceEvent(ServiceEvent::REGISTERED, r)); - return res; -} - -void ServiceRegistry::UpdateServiceRegistrationOrder(const ServiceRegistration& sr, - const std::list& classes) -{ - MutexLocker lock(mutex); - for (std::list::const_iterator i = classes.begin(); - i != classes.end(); ++i) - { - std::list& s = classServices[*i]; - s.erase(std::remove(s.begin(), s.end(), sr), s.end()); - s.insert(std::lower_bound(s.begin(), s.end(), sr), sr); - } -} - -bool ServiceRegistry::CheckServiceClass(US_BASECLASS_NAME* , const std::string& ) const -{ - //return service->inherits(cls.toAscii()); - // No possibility to check inheritance based on string literals. - return true; -} - -void ServiceRegistry::Get(const std::string& clazz, - std::list& serviceRegs) const -{ - MutexLocker lock(mutex); - MapClassServices::const_iterator i = classServices.find(clazz); - if (i != classServices.end()) - { - serviceRegs = i->second; - } -} - -ServiceReference ServiceRegistry::Get(ModulePrivate* module, const std::string& clazz) const -{ - MutexLocker lock(mutex); - try - { - std::list srs; - Get_unlocked(clazz, "", module, srs); - US_DEBUG << "get service ref " << clazz << " for module " - << module->info.name << " = " << srs.size() << " refs"; - - if (!srs.empty()) - { - return srs.back(); - } - } - catch (const std::invalid_argument& ) - { } - - return ServiceReference(); -} - -void ServiceRegistry::Get(const std::string& clazz, const std::string& filter, - ModulePrivate* module, std::list& res) const -{ - MutexLocker lock(mutex); - Get_unlocked(clazz, filter, module, res); -} - -void ServiceRegistry::Get_unlocked(const std::string& clazz, const std::string& filter, - ModulePrivate* /*module*/, std::list& res) const -{ - std::list::const_iterator s; - std::list::const_iterator send; - std::list v; - LDAPExpr ldap; - if (clazz.empty()) - { - if (!filter.empty()) - { - ldap = LDAPExpr(filter); - LDAPExpr::ObjectClassSet matched; - if (ldap.GetMatchedObjectClasses(matched)) - { - v.clear(); - for(LDAPExpr::ObjectClassSet::const_iterator className = matched.begin(); - className != matched.end(); ++className) - { - MapClassServices::const_iterator i = classServices.find(*className); - if (i != classServices.end()) - { - std::copy(i->second.begin(), i->second.end(), std::back_inserter(v)); - } - } - if (!v.empty()) - { - s = v.begin(); - send = v.end(); - } - else - { - return; - } - } - else - { - s = serviceRegistrations.begin(); - send = serviceRegistrations.end(); - } - } - else - { - s = serviceRegistrations.begin(); - send = serviceRegistrations.end(); - } - } - else - { - MapClassServices::const_iterator it = classServices.find(clazz); - if (it != classServices.end()) - { - s = it->second.begin(); - send = it->second.end(); - } - else - { - return; - } - if (!filter.empty()) - { - ldap = LDAPExpr(filter); - } - } - - for (; s != send; ++s) - { - ServiceReference sri = s->GetReference(); - - if (filter.empty() || ldap.Evaluate(s->d->properties, false)) - { - res.push_back(sri); - } - } -} - -void ServiceRegistry::RemoveServiceRegistration(const ServiceRegistration& sr) -{ - MutexLocker lock(mutex); - - const std::list& classes = ref_any_cast >( - sr.d->properties[ServiceConstants::OBJECTCLASS()]); - services.erase(sr); - serviceRegistrations.remove(sr); - for (std::list::const_iterator i = classes.begin(); - i != classes.end(); ++i) - { - std::list& s = classServices[*i]; - if (s.size() > 1) - { - s.erase(std::remove(s.begin(), s.end(), sr), s.end()); - } - else - { - classServices.erase(*i); - } - } -} - -void ServiceRegistry::GetRegisteredByModule(ModulePrivate* p, - std::list& res) const -{ - MutexLocker lock(mutex); - - for (std::list::const_iterator i = serviceRegistrations.begin(); - i != serviceRegistrations.end(); ++i) - { - if (i->d->module == p) - { - res.push_back(*i); - } - } -} - -void ServiceRegistry::GetUsedByModule(Module* p, - std::list& res) const -{ - MutexLocker lock(mutex); - - for (std::list::const_iterator i = serviceRegistrations.begin(); - i != serviceRegistrations.end(); ++i) - { - if (i->d->IsUsedByModule(p)) - { - res.push_back(*i); - } - } -} - -US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h b/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h deleted file mode 100644 index 49af448db6..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceRegistry_p.h +++ /dev/null @@ -1,196 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICEREGISTRY_H -#define USSERVICEREGISTRY_H - -#include - -#include "usServiceRegistration.h" -#include "usServiceProperties.h" - -#include "usThreads_p.h" - -US_BEGIN_NAMESPACE - -class CoreModuleContext; -class ModulePrivate; - - -/** - * Here we handle all the CppMicroServices services that are registered. - */ -class ServiceRegistry -{ - -public: - - typedef Mutex MutexType; - - mutable MutexType mutex; - - /** - * Creates a new ServiceProperties object containing in - * with the keys converted to lower case. - * - * @param classes A list of class names which will be added to the - * created ServiceProperties object under the key - * ModuleConstants::OBJECTCLASS. - * @param sid A service id which will be used instead of a default one. - */ - static ServiceProperties CreateServiceProperties(const ServiceProperties& in, - const std::list& classes = std::list(), - long sid = -1); - - typedef US_UNORDERED_MAP_TYPE > MapServiceClasses; - typedef US_UNORDERED_MAP_TYPE > MapClassServices; - - /** - * All registered services in the current framework. - * Mapping of registered service to class names under which - * the service is registerd. - */ - MapServiceClasses services; - - std::list serviceRegistrations; - - /** - * Mapping of classname to registered service. - * The List of registered services are ordered with the highest - * ranked service first. - */ - MapClassServices classServices; - - CoreModuleContext* core; - - ServiceRegistry(CoreModuleContext* coreCtx); - - ~ServiceRegistry(); - - void Clear(); - - /** - * Register a service in the framework wide register. - * - * @param module The module registering the service. - * @param classes The class names under which the service can be located. - * @param service The service object. - * @param properties The properties for this service. - * @return A ServiceRegistration object. - * @exception std::invalid_argument If one of the following is true: - *
    - *
  • The service object is 0.
  • - *
  • The service parameter is not a ServiceFactory or an - * instance of all the named classes in the classes parameter.
  • - *
- */ - ServiceRegistration RegisterService(ModulePrivate* module, - const std::list& clazzes, - US_BASECLASS_NAME* service, - const ServiceProperties& properties); - - /** - * Service ranking changed, reorder registered services - * according to ranking. - * - * @param serviceRegistration The ServiceRegistrationPrivate object. - * @param rank New rank of object. - */ - void UpdateServiceRegistrationOrder(const ServiceRegistration& sr, - const std::list& classes); - - /** - * Checks that a given service object is an instance of the given - * class name. - * - * @param service The service object to check. - * @param cls The class name to check for. - */ - bool CheckServiceClass(US_BASECLASS_NAME* service, const std::string& cls) const; - - /** - * Get all services implementing a certain class. - * Only used internally by the framework. - * - * @param clazz The class name of the requested service. - * @return A sorted list of {@link ServiceRegistrationPrivate} objects. - */ - void Get(const std::string& clazz, std::list& serviceRegs) const; - - /** - * Get a service implementing a certain class. - * - * @param module The module requesting reference - * @param clazz The class name of the requested service. - * @return A {@link ServiceReference} object. - */ - ServiceReference Get(ModulePrivate* module, const std::string& clazz) const; - - /** - * Get all services implementing a certain class and then - * filter these with a property filter. - * - * @param clazz The class name of requested service. - * @param filter The property filter. - * @param module The module requesting reference. - * @return A list of {@link ServiceReference} object. - */ - void Get(const std::string& clazz, const std::string& filter, - ModulePrivate* module, std::list& serviceRefs) const; - - /** - * Remove a registered service. - * - * @param sr The ServiceRegistration object that is registered. - */ - void RemoveServiceRegistration(const ServiceRegistration& sr) ; - - /** - * Get all services that a module has registered. - * - * @param p The module - * @return A set of {@link ServiceRegistration} objects - */ - void GetRegisteredByModule(ModulePrivate* m, std::list& serviceRegs) const; - - /** - * Get all services that a module uses. - * - * @param p The module - * @return A set of {@link ServiceRegistration} objects - */ - void GetUsedByModule(Module* m, std::list& serviceRegs) const; - -private: - - void Get_unlocked(const std::string& clazz, const std::string& filter, - ModulePrivate* module, std::list& serviceRefs) const; - - // purposely not implemented - ServiceRegistry(const ServiceRegistry&); - ServiceRegistry& operator=(const ServiceRegistry&); - -}; - -US_END_NAMESPACE - -#endif // USSERVICEREGISTRY_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTracker.h b/Core/Code/CppMicroServices/src/service/usServiceTracker.h deleted file mode 100644 index 0915ec51f9..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceTracker.h +++ /dev/null @@ -1,433 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICETRACKER_H -#define USSERVICETRACKER_H - -#include - -#include "usServiceReference.h" -#include "usServiceTrackerCustomizer.h" -#include "usLDAPFilter.h" - -US_BEGIN_NAMESPACE - -template class TrackedService; -template class ServiceTrackerPrivate; -class ModuleContext; - -/** - * \ingroup MicroServices - * - * The ServiceTracker class simplifies using services from the - * framework's service registry. - *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

- * This method can be overridden in a subclass. If the default - * implementation of \link AddingService(const ServiceReference&) AddingService\endlink - * method was used, this method must unget the service. - * - * @param reference The reference to removed service. - * @param service The service object for the removed service. - * @see ServiceTrackerCustomizer::RemovedService(const ServiceReference&, T) - */ - void RemovedService(const ServiceReference& reference, T service); - -private: - - typedef ServiceTracker _ServiceTracker; - typedef TrackedService _TrackedService; - typedef ServiceTrackerPrivate _ServiceTrackerPrivate; - typedef ServiceTrackerCustomizer _ServiceTrackerCustomizer; - - friend class TrackedService; - friend class ServiceTrackerPrivate; - - _ServiceTrackerPrivate* const d; -}; - -US_END_NAMESPACE - -#include "usServiceTracker.tpp" - -#endif // USSERVICETRACKER_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp b/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp deleted file mode 100644 index 608c628c61..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceTracker.tpp +++ /dev/null @@ -1,448 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usServiceTrackerPrivate.h" -#include "usTrackedService_p.h" -#include "usServiceException.h" -#include "usModuleContext.h" - -#include -#include - -US_BEGIN_NAMESPACE - -template -ServiceTracker::~ServiceTracker() -{ - Close(); - delete d; -} - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4355) -#endif - -template -ServiceTracker::ServiceTracker(ModuleContext* context, - const ServiceReference& reference, - _ServiceTrackerCustomizer* customizer) - : d(new _ServiceTrackerPrivate(this, context, reference, customizer)) -{ -} - -template -ServiceTracker::ServiceTracker(ModuleContext* context, const std::string& clazz, - _ServiceTrackerCustomizer* customizer) - : d(new _ServiceTrackerPrivate(this, context, clazz, customizer)) -{ -} - -template -ServiceTracker::ServiceTracker(ModuleContext* context, const LDAPFilter& filter, - _ServiceTrackerCustomizer* customizer) - : d(new _ServiceTrackerPrivate(this, context, filter, customizer)) -{ -} - -template -ServiceTracker::ServiceTracker(ModuleContext *context, ServiceTrackerCustomizer *customizer) - : d(new _ServiceTrackerPrivate(this, context, us_service_interface_iid(), customizer)) -{ - const char* clazz = us_service_interface_iid(); - if (clazz == 0) throw ServiceException("The service interface class has no US_DECLARE_SERVICE_INTERFACE macro"); -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -template -void ServiceTracker::Open() -{ - _TrackedService* t; - { - typename _ServiceTrackerPrivate::Lock l(d); - if (d->trackedService) - { - return; - } - - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::Open: " << d->filter; - - t = new _TrackedService(this, d->customizer); - { - typename _TrackedService::Lock l(*t); - try { - d->context->AddServiceListener(t, &_TrackedService::ServiceChanged, d->listenerFilter); - std::list references; - if (!d->trackClass.empty()) - { - references = d->GetInitialReferences(d->trackClass, std::string()); - } - else - { - if (d->trackReference.GetModule() != 0) - { - references.push_back(d->trackReference); - } - else - { /* user supplied filter */ - references = d->GetInitialReferences(std::string(), - (d->listenerFilter.empty()) ? d->filter.ToString() : d->listenerFilter); - } - } - /* set tracked with the initial references */ - t->SetInitial(references); - } - catch (const std::invalid_argument& e) - { - throw std::runtime_error(std::string("unexpected std::invalid_argument exception: ") - + e.what()); - } - } - d->trackedService = t; - } - /* Call tracked outside of synchronized region */ - t->TrackInitial(); /* process the initial references */ -} - -template -void ServiceTracker::Close() -{ - _TrackedService* outgoing; - std::list references; - { - typename _ServiceTrackerPrivate::Lock l(d); - outgoing = d->trackedService; - if (outgoing == 0) - { - return; - } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::close:" << d->filter; - outgoing->Close(); - GetServiceReferences(references); - d->trackedService = 0; - try - { - d->context->RemoveServiceListener(outgoing, &_TrackedService::ServiceChanged); - } - catch (const std::logic_error& /*e*/) - { - /* In case the context was stopped. */ - } - } - d->Modified(); /* clear the cache */ - { - typename _TrackedService::Lock l(outgoing); - outgoing->NotifyAll(); /* wake up any waiters */ - } - for(std::list::const_iterator ref = references.begin(); - ref != references.end(); ++ref) - { - outgoing->Untrack(*ref, ServiceEvent()); - } - - if (d->DEBUG_OUTPUT) - { - typename _ServiceTrackerPrivate::Lock l(d); - if ((d->cachedReference.GetModule() == 0) && (d->cachedService == 0)) - { - US_DEBUG(true) << "ServiceTracker::close[cached cleared]:" - << d->filter; - } - } - - delete outgoing; - d->trackedService = 0; -} - -template -T ServiceTracker::WaitForService(unsigned long timeoutMillis) -{ - T object = GetService(); - while (object == 0) - { - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return 0; - } - { - typename _TrackedService::Lock l(t); - if (t->Size() == 0) - { - t->Wait(timeoutMillis); - } - } - object = GetService(); - } - return object; -} - -template -void ServiceTracker::GetServiceReferences(std::list& refs) const -{ - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return; - } - { - typename _TrackedService::Lock l(t); - d->GetServiceReferences_unlocked(refs, t); - } -} - -template -ServiceReference ServiceTracker::GetServiceReference() const -{ - ServiceReference reference(0); - { - typename _ServiceTrackerPrivate::Lock l(d); - reference = d->cachedReference; - } - if (reference.GetModule() != 0) - { - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference[cached]:" - << d->filter; - return reference; - } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getServiceReference:" << d->filter; - std::list references; - GetServiceReferences(references); - std::size_t length = references.size(); - if (length == 0) - { /* if no service is being tracked */ - throw ServiceException("No service is being tracked"); - } - std::list::const_iterator selectedRef; - if (length > 1) - { /* if more than one service, select highest ranking */ - std::vector rankings(length); - int count = 0; - int maxRanking = std::numeric_limits::min(); - std::list::const_iterator refIter = references.begin(); - for (std::size_t i = 0; i < length; i++) - { - Any rankingAny = refIter->GetProperty(ServiceConstants::SERVICE_RANKING()); - int ranking = 0; - if (rankingAny.Type() == typeid(int)) - { - ranking = any_cast(rankingAny); - } - - rankings[i] = ranking; - if (ranking > maxRanking) - { - selectedRef = refIter; - maxRanking = ranking; - count = 1; - } - else - { - if (ranking == maxRanking) - { - count++; - } - } - ++refIter; - } - if (count > 1) - { /* if still more than one service, select lowest id */ - long int minId = std::numeric_limits::max(); - refIter = references.begin(); - for (std::size_t i = 0; i < length; i++) - { - if (rankings[i] == maxRanking) - { - Any idAny = refIter->GetProperty(ServiceConstants::SERVICE_ID()); - long int id = 0; - if (idAny.Type() == typeid(long int)) - { - id = any_cast(idAny); - } - if (id < minId) - { - selectedRef = refIter; - minId = id; - } - } - ++refIter; - } - } - } - - { - typename _ServiceTrackerPrivate::Lock l(d); - d->cachedReference = *selectedRef; - return d->cachedReference; - } -} - -template -T ServiceTracker::GetService(const ServiceReference& reference) const -{ - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return 0; - } - { - typename _TrackedService::Lock l(t); - return t->GetCustomizedObject(reference); - } -} - -template -void ServiceTracker::GetServices(std::list& services) const -{ - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return; - } - { - typename _TrackedService::Lock l(t); - std::list references; - d->GetServiceReferences_unlocked(references, t); - for(std::list::const_iterator ref = references.begin(); - ref != references.end(); ++ref) - { - services.push_back(t->GetCustomizedObject(*ref)); - } - } -} - -template -T ServiceTracker::GetService() const -{ - T service = d->cachedService; - if (service != 0) - { - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService[cached]:" - << d->filter; - return service; - } - US_DEBUG(d->DEBUG_OUTPUT) << "ServiceTracker::getService:" << d->filter; - - try - { - ServiceReference reference = GetServiceReference(); - if (reference.GetModule() == 0) - { - return 0; - } - return d->cachedService = GetService(reference); - } - catch (const ServiceException&) - { - return 0; - } -} - -template -void ServiceTracker::Remove(const ServiceReference& reference) -{ - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return; - } - t->Untrack(reference, ServiceEvent()); -} - -template -int ServiceTracker::Size() const -{ - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return 0; - } - { - typename _TrackedService::Lock l(t); - return static_cast(t->Size()); - } -} - -template -int ServiceTracker::GetTrackingCount() const -{ - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return -1; - } - { - typename _TrackedService::Lock l(t); - return t->GetTrackingCount(); - } -} - -template -void ServiceTracker::GetTracked(TrackingMap& map) const -{ - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return; - } - { - typename _TrackedService::Lock l(t); - t->CopyEntries(map); - } -} - -template -bool ServiceTracker::IsEmpty() const -{ - _TrackedService* t = d->Tracked(); - if (t == 0) - { /* if ServiceTracker is not open */ - return true; - } - { - typename _TrackedService::Lock l(t); - return t->IsEmpty(); - } -} - -template -T ServiceTracker::AddingService(const ServiceReference& reference) -{ - return dynamic_cast(d->context->GetService(reference)); -} - -template -void ServiceTracker::ModifiedService(const ServiceReference& /*reference*/, T /*service*/) -{ - /* do nothing */ -} - -template -void ServiceTracker::RemovedService(const ServiceReference& reference, T /*service*/) -{ - d->context->UngetService(reference); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h b/Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h deleted file mode 100644 index f3704a7930..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerCustomizer.h +++ /dev/null @@ -1,113 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICETRACKERCUSTOMIZER_H -#define USSERVICETRACKERCUSTOMIZER_H - -#include "usServiceReference.h" - -US_BEGIN_NAMESPACE - -/** - * \ingroup MicroServices - * - * The ServiceTrackerCustomizer interface allows a - * ServiceTracker to customize the service objects that are - * tracked. A ServiceTrackerCustomizer is called when a service is - * being added to a ServiceTracker. The - * ServiceTrackerCustomizer can then return an object for the - * tracked service. A ServiceTrackerCustomizer is also called when - * a tracked service is modified or has been removed from a - * ServiceTracker. - * - *

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

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

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

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

- * This method is called after a service is no longer being tracked by the - * ServiceTracker. - * - * @param reference The reference to the service that has been removed. - * @param service The service object for the specified referenced service. - */ - virtual void RemovedService(const ServiceReference& reference, T service) = 0; -}; - -US_END_NAMESPACE - -#endif // USSERVICETRACKERCUSTOMIZER_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h b/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h deleted file mode 100644 index 1229b68ca0..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.h +++ /dev/null @@ -1,172 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICETRACKERPRIVATE_H -#define USSERVICETRACKERPRIVATE_H - -#include "usServiceReference.h" -#include "usLDAPFilter.h" - - -US_BEGIN_NAMESPACE - -/** - * \ingroup MicroServices - */ -template -class ServiceTrackerPrivate : US_DEFAULT_THREADING > -{ - -public: - - ServiceTrackerPrivate(ServiceTracker* st, - ModuleContext* context, - const ServiceReference& reference, - ServiceTrackerCustomizer* customizer); - - ServiceTrackerPrivate(ServiceTracker* st, - ModuleContext* context, const std::string& clazz, - ServiceTrackerCustomizer* customizer); - - ServiceTrackerPrivate(ServiceTracker* st, - ModuleContext* context, const LDAPFilter& filter, - ServiceTrackerCustomizer* customizer); - - ~ServiceTrackerPrivate(); - - /** - * Returns the list of initial ServiceReferences that will be - * tracked by this ServiceTracker. - * - * @param className The class name with which the service was registered, or - * null for all services. - * @param filterString The filter criteria or null for all - * services. - * @return The list of initial ServiceReferences. - * @throws std::invalid_argument If the specified filterString has an - * invalid syntax. - */ - std::list GetInitialReferences(const std::string& className, - const std::string& filterString); - - void GetServiceReferences_unlocked(std::list& refs, TrackedService* t) const; - - /* set this to true to compile in debug messages */ - static const bool DEBUG_OUTPUT; // = false; - - /** - * The Module Context used by this ServiceTracker. - */ - ModuleContext* const context; - - /** - * The filter used by this ServiceTracker which specifies the - * search criteria for the services to track. - */ - LDAPFilter filter; - - /** - * The ServiceTrackerCustomizer for this tracker. - */ - ServiceTrackerCustomizer* customizer; - - /** - * Filter string for use when adding the ServiceListener. If this field is - * set, then certain optimizations can be taken since we don't have a user - * supplied filter. - */ - std::string listenerFilter; - - /** - * Class name to be tracked. If this field is set, then we are tracking by - * class name. - */ - std::string trackClass; - - /** - * Reference to be tracked. If this field is set, then we are tracking a - * single ServiceReference. - */ - ServiceReference trackReference; - - /** - * Tracked services: ServiceReference -> customized Object and - * ServiceListenerEntry object - */ - TrackedService* trackedService; - - /** - * Accessor method for the current TrackedService object. This method is only - * intended to be used by the unsynchronized methods which do not modify the - * trackedService field. - * - * @return The current Tracked object. - */ - TrackedService* Tracked() const; - - /** - * Called by the TrackedService object whenever the set of tracked services is - * modified. Clears the cache. - */ - /* - * This method must not be synchronized since it is called by TrackedService while - * TrackedService is synchronized. We don't want synchronization interactions - * between the listener thread and the user thread. - */ - void Modified(); - - /** - * Cached ServiceReference for getServiceReference. - */ - mutable ServiceReference cachedReference; - - /** - * Cached service object for GetService. - * - * This field is volatile since it is accessed by multiple threads. - */ - mutable T volatile cachedService; - - -private: - - inline ServiceTracker* q_func() - { - return static_cast *>(q_ptr); - } - - inline const ServiceTracker* q_func() const - { - return static_cast *>(q_ptr); - } - - friend class ServiceTracker; - - ServiceTracker * const q_ptr; - -}; - -US_END_NAMESPACE - -#include "usServiceTrackerPrivate.tpp" - -#endif // USSERVICETRACKERPRIVATE_H diff --git a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp b/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp deleted file mode 100644 index e48033f6a1..0000000000 --- a/Core/Code/CppMicroServices/src/service/usServiceTrackerPrivate.tpp +++ /dev/null @@ -1,144 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "usTrackedService_p.h" - -#include "usModuleContext.h" -#include "usLDAPFilter.h" - -#include - -US_BEGIN_NAMESPACE - -template -const bool ServiceTrackerPrivate::DEBUG_OUTPUT = true; - -template -ServiceTrackerPrivate::ServiceTrackerPrivate( - ServiceTracker* st, ModuleContext* context, - const ServiceReference& reference, - ServiceTrackerCustomizer* customizer) - : context(context), customizer(customizer), trackReference(reference), - trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) -{ - this->customizer = customizer ? customizer : q_func(); - std::stringstream ss; - ss << "(" << ServiceConstants::SERVICE_ID() << "=" - << any_cast(reference.GetProperty(ServiceConstants::SERVICE_ID())) << ")"; - this->listenerFilter = ss.str(); - try - { - this->filter = LDAPFilter(listenerFilter); - } - catch (const std::invalid_argument& e) - { - /* - * we could only get this exception if the ServiceReference was - * invalid - */ - std::invalid_argument ia(std::string("unexpected std::invalid_argument exception: ") + e.what()); - throw ia; - } -} - -template -ServiceTrackerPrivate::ServiceTrackerPrivate( - ServiceTracker* st, - ModuleContext* context, const std::string& clazz, - ServiceTrackerCustomizer* customizer) - : context(context), customizer(customizer), trackClass(clazz), - trackReference(0), trackedService(0), cachedReference(0), - cachedService(0), q_ptr(st) -{ - this->customizer = customizer ? customizer : q_func(); - this->listenerFilter = std::string("(") + US_PREPEND_NAMESPACE(ServiceConstants)::OBJECTCLASS() + "=" - + clazz + ")"; - try - { - this->filter = LDAPFilter(listenerFilter); - } - catch (const std::invalid_argument& e) - { - /* - * we could only get this exception if the clazz argument was - * malformed - */ - std::invalid_argument ia( - std::string("unexpected std::invalid_argument exception: ") + e.what()); - throw ia; - } -} - -template -ServiceTrackerPrivate::ServiceTrackerPrivate( - ServiceTracker* st, - ModuleContext* context, const LDAPFilter& filter, - ServiceTrackerCustomizer* customizer) - : context(context), filter(filter), customizer(customizer), - listenerFilter(filter.ToString()), trackReference(0), - trackedService(0), cachedReference(0), cachedService(0), q_ptr(st) -{ - this->customizer = customizer ? customizer : q_func(); - if (context == 0) - { - throw std::invalid_argument("The module context cannot be null."); - } -} - -template -ServiceTrackerPrivate::~ServiceTrackerPrivate() -{ - -} - -template -std::list ServiceTrackerPrivate::GetInitialReferences( - const std::string& className, const std::string& filterString) -{ - return context->GetServiceReferences(className, filterString); -} - -template -void ServiceTrackerPrivate::GetServiceReferences_unlocked(std::list& refs, TrackedService* t) const -{ - if (t->Size() == 0) - { - return; - } - t->GetTracked(refs); -} - -template -TrackedService* ServiceTrackerPrivate::Tracked() const -{ - return trackedService; -} - -template -void ServiceTrackerPrivate::Modified() -{ - cachedReference = 0; /* clear cached value */ - cachedService = 0; /* clear cached value */ - US_DEBUG(DEBUG_OUTPUT) << "ServiceTracker::Modified(): " << filter; -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usTrackedService.tpp b/Core/Code/CppMicroServices/src/service/usTrackedService.tpp deleted file mode 100644 index 8917c200fd..0000000000 --- a/Core/Code/CppMicroServices/src/service/usTrackedService.tpp +++ /dev/null @@ -1,123 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -US_BEGIN_NAMESPACE - -template -TrackedService::TrackedService(ServiceTracker* serviceTracker, - ServiceTrackerCustomizer* customizer) - : serviceTracker(serviceTracker), customizer(customizer) -{ - -} - -template -void TrackedService::ServiceChanged(const ServiceEvent event) -{ - /* - * Check if we had a delayed call (which could happen when we - * close). - */ - if (this->closed) - { - return; - } - - ServiceReference reference = event.GetServiceReference(); - US_DEBUG(serviceTracker->d->DEBUG_OUTPUT) << "TrackedService::ServiceChanged[" - << event.GetType() << "]: " << reference; - - switch (event.GetType()) - { - case ServiceEvent::REGISTERED : - case ServiceEvent::MODIFIED : - { - if (!serviceTracker->d->listenerFilter.empty()) - { // service listener added with filter - this->Track(reference, event); - /* - * If the customizer throws an unchecked exception, it - * is safe to let it propagate - */ - } - else - { // service listener added without filter - if (serviceTracker->d->filter.Match(reference)) - { - this->Track(reference, event); - /* - * If the customizer throws an unchecked exception, - * it is safe to let it propagate - */ - } - else - { - this->Untrack(reference, event); - /* - * If the customizer throws an unchecked exception, - * it is safe to let it propagate - */ - } - } - break; - } - case ServiceEvent::MODIFIED_ENDMATCH : - case ServiceEvent::UNREGISTERING : - this->Untrack(reference, event); - /* - * If the customizer throws an unchecked exception, it is - * safe to let it propagate - */ - break; - } -} - -template -void TrackedService::Modified() -{ - Superclass::Modified(); /* increment the modification count */ - serviceTracker->d->Modified(); -} - -template -T TrackedService::CustomizerAdding(ServiceReference item, - const ServiceEvent& /*related*/) -{ - return customizer->AddingService(item); -} - -template -void TrackedService::CustomizerModified(ServiceReference item, - const ServiceEvent& /*related*/, - T object) -{ - customizer->ModifiedService(item, object); -} - -template -void TrackedService::CustomizerRemoved(ServiceReference item, - const ServiceEvent& /*related*/, - T object) -{ - customizer->RemovedService(item, object); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h b/Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h deleted file mode 100644 index f70aa53365..0000000000 --- a/Core/Code/CppMicroServices/src/service/usTrackedServiceListener_p.h +++ /dev/null @@ -1,51 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTRACKEDSERVICELISTENER_H -#define USTRACKEDSERVICELISTENER_H - -#include "usServiceEvent.h" - -US_BEGIN_NAMESPACE - -/** - * This class is not intended to be used directly. It is exported to support - * the CppMicroServices module system. - */ -struct TrackedServiceListener // : public US_BASECLASS_NAME -{ - virtual ~TrackedServiceListener() {} - - /** - * Slot connected to service events for the - * ServiceTracker class. This method must NOT be - * synchronized to avoid deadlock potential. - * - * @param event ServiceEvent object from the framework. - */ - virtual void ServiceChanged(const ServiceEvent event) = 0; - -}; - -US_END_NAMESPACE - -#endif // USTRACKEDSERVICELISTENER_H diff --git a/Core/Code/CppMicroServices/src/service/usTrackedService_p.h b/Core/Code/CppMicroServices/src/service/usTrackedService_p.h deleted file mode 100644 index 79b366e217..0000000000 --- a/Core/Code/CppMicroServices/src/service/usTrackedService_p.h +++ /dev/null @@ -1,107 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTRACKEDSERVICE_H -#define USTRACKEDSERVICE_H - -#include "usTrackedServiceListener_p.h" -#include "usModuleAbstractTracked_p.h" -#include "usServiceEvent.h" - -US_BEGIN_NAMESPACE - -/** - * This class is not intended to be used directly. It is exported to support - * the CppMicroServices module system. - */ -template -class TrackedService : public TrackedServiceListener, - public ModuleAbstractTracked -{ - -public: - TrackedService(ServiceTracker* serviceTracker, - ServiceTrackerCustomizer* customizer); - - /** - * Method connected to service events for the - * ServiceTracker class. This method must NOT be - * synchronized to avoid deadlock potential. - * - * @param event ServiceEvent object from the framework. - */ - void ServiceChanged(const ServiceEvent event); - -private: - - typedef ModuleAbstractTracked Superclass; - - ServiceTracker* serviceTracker; - ServiceTrackerCustomizer* customizer; - - /** - * Increment the tracking count and tell the tracker there was a - * modification. - * - * @GuardedBy this - */ - void Modified(); - - /** - * Call the specific customizer adding method. This method must not be - * called while synchronized on this object. - * - * @param item Item to be tracked. - * @param related Action related object. - * @return Customized object for the tracked item or null - * if the item is not to be tracked. - */ - T CustomizerAdding(ServiceReference item, const ServiceEvent& related); - - /** - * Call the specific customizer modified method. This method must not be - * called while synchronized on this object. - * - * @param item Tracked item. - * @param related Action related object. - * @param object Customized object for the tracked item. - */ - void CustomizerModified(ServiceReference item, - const ServiceEvent& related, T object) ; - - /** - * Call the specific customizer removed method. This method must not be - * called while synchronized on this object. - * - * @param item Tracked item. - * @param related Action related object. - * @param object Customized object for the tracked item. - */ - void CustomizerRemoved(ServiceReference item, - const ServiceEvent& related, T object) ; -}; - -US_END_NAMESPACE - -#include "usTrackedService.tpp" - -#endif // USTRACKEDSERVICE_H diff --git a/Core/Code/CppMicroServices/src/util/dirent_win32_p.h b/Core/Code/CppMicroServices/src/util/dirent_win32_p.h deleted file mode 100644 index d7dd7fc048..0000000000 --- a/Core/Code/CppMicroServices/src/util/dirent_win32_p.h +++ /dev/null @@ -1,374 +0,0 @@ -/***************************************************************************** - * dirent.h - dirent API for Microsoft Visual Studio - * - * Copyright (C) 2006 Toni Ronkko - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * ``Software''), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - * - * Mar 15, 2011, Toni Ronkko - * Defined FILE_ATTRIBUTE_DEVICE for MSVC 6.0. - * - * Aug 11, 2010, Toni Ronkko - * Added d_type and d_namlen fields to dirent structure. The former is - * especially useful for determining whether directory entry represents a - * file or a directory. For more information, see - * http://www.delorie.com/gnu/docs/glibc/libc_270.html - * - * Aug 11, 2010, Toni Ronkko - * Improved conformance to the standards. For example, errno is now set - * properly on failure and assert() is never used. Thanks to Peter Brockam - * for suggestions. - * - * Aug 11, 2010, Toni Ronkko - * Fixed a bug in rewinddir(): when using relative directory names, change - * of working directory no longer causes rewinddir() to fail. - * - * Dec 15, 2009, John Cunningham - * Added rewinddir member function - * - * Jan 18, 2008, Toni Ronkko - * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string - * between multi-byte and unicode representations. This makes the - * code simpler and also allows the code to be compiled under MingW. Thanks - * to Azriel Fasten for the suggestion. - * - * Mar 4, 2007, Toni Ronkko - * Bug fix: due to the strncpy_s() function this file only compiled in - * Visual Studio 2005. Using the new string functions only when the - * compiler version allows. - * - * Nov 2, 2006, Toni Ronkko - * Major update: removed support for Watcom C, MS-DOS and Turbo C to - * simplify the file, updated the code to compile cleanly on Visual - * Studio 2005 with both unicode and multi-byte character strings, - * removed rewinddir() as it had a bug. - * - * Aug 20, 2006, Toni Ronkko - * Removed all remarks about MSVC 1.0, which is antiqued now. Simplified - * comments by removing SGML tags. - * - * May 14 2002, Toni Ronkko - * Embedded the function definitions directly to the header so that no - * source modules need to be included in the Visual Studio project. Removed - * all the dependencies to other projects so that this very header can be - * used independently. - * - * May 28 1998, Toni Ronkko - * First version. - *****************************************************************************/ -#ifndef DIRENT_H -#define DIRENT_H - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include -#include -#include -#include -#include - -/* Entries missing from MSVC 6.0 */ -#if !defined(FILE_ATTRIBUTE_DEVICE) -# define FILE_ATTRIBUTE_DEVICE 0x40 -#endif - -/* File type and permission flags for stat() */ -#if defined(_MSC_VER) && !defined(S_IREAD) -# define S_IFMT _S_IFMT /* file type mask */ -# define S_IFDIR _S_IFDIR /* directory */ -# define S_IFCHR _S_IFCHR /* character device */ -# define S_IFFIFO _S_IFFIFO /* pipe */ -# define S_IFREG _S_IFREG /* regular file */ -# define S_IREAD _S_IREAD /* read permission */ -# define S_IWRITE _S_IWRITE /* write permission */ -# define S_IEXEC _S_IEXEC /* execute permission */ -#endif -#define S_IFBLK 0 /* block device */ -#define S_IFLNK 0 /* link */ -#define S_IFSOCK 0 /* socket */ - -#if defined(_MSC_VER) -# define S_IRUSR S_IREAD /* read, user */ -# define S_IWUSR S_IWRITE /* write, user */ -# define S_IXUSR 0 /* execute, user */ -# define S_IRGRP 0 /* read, group */ -# define S_IWGRP 0 /* write, group */ -# define S_IXGRP 0 /* execute, group */ -# define S_IROTH 0 /* read, others */ -# define S_IWOTH 0 /* write, others */ -# define S_IXOTH 0 /* execute, others */ -#endif - -/* Indicates that d_type field is available in dirent structure */ -#define _DIRENT_HAVE_D_TYPE - -/* File type flags for d_type */ -#define DT_UNKNOWN 0 -#define DT_REG S_IFREG -#define DT_DIR S_IFDIR -#define DT_FIFO S_IFFIFO -#define DT_SOCK S_IFSOCK -#define DT_CHR S_IFCHR -#define DT_BLK S_IFBLK - -/* Macros for converting between st_mode and d_type */ -#define IFTODT(mode) ((mode) & S_IFMT) -#define DTTOIF(type) (type) - -/* - * File type macros. Note that block devices, sockets and links cannot be - * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are - * only defined for compatibility. These macros should always return false - * on Windows. - */ -#define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFFIFO) -#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) -#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) -#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) -#define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) -#define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) -#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef struct dirent -{ - char d_name[MAX_PATH + 1]; /* File name */ - size_t d_namlen; /* Length of name without \0 */ - int d_type; /* File type */ -} dirent; - - -typedef struct DIR -{ - dirent curentry; /* Current directory entry */ - WIN32_FIND_DATAA find_data; /* Private file data */ - int cached; /* True if data is valid */ - HANDLE search_handle; /* Win32 search handle */ - char patt[MAX_PATH + 3]; /* Initial directory name */ -} DIR; - - -/* Forward declarations */ -static DIR *opendir(const char *dirname); -static struct dirent *readdir(DIR *dirp); -static int closedir(DIR *dirp); -static void rewinddir(DIR* dirp); - - -/* Use the new safe string functions introduced in Visual Studio 2005 */ -#if defined(_MSC_VER) && _MSC_VER >= 1400 -# define DIRENT_STRNCPY(dest,src,size) strncpy_s((dest),(size),(src),_TRUNCATE) -#else -# define DIRENT_STRNCPY(dest,src,size) strncpy((dest),(src),(size)) -#endif - -/* Set errno variable */ -#if defined(_MSC_VER) -#define DIRENT_SET_ERRNO(x) _set_errno (x) -#else -#define DIRENT_SET_ERRNO(x) (errno = (x)) -#endif - - -/***************************************************************************** - * Open directory stream DIRNAME for read and return a pointer to the - * internal working area that is used to retrieve individual directory - * entries. - */ -static DIR *opendir(const char *dirname) -{ - DIR *dirp; - - /* ensure that the resulting search pattern will be a valid file name */ - if (dirname == NULL) { - DIRENT_SET_ERRNO (ENOENT); - return NULL; - } - if (strlen (dirname) + 3 >= MAX_PATH) { - DIRENT_SET_ERRNO (ENAMETOOLONG); - return NULL; - } - - /* construct new DIR structure */ - dirp = (DIR*) malloc (sizeof (struct DIR)); - if (dirp != NULL) { - int error; - - /* - * Convert relative directory name to an absolute one. This - * allows rewinddir() to function correctly when the current working - * directory is changed between opendir() and rewinddir(). - */ - if (GetFullPathNameA (dirname, MAX_PATH, dirp->patt, NULL)) { - char *p; - - /* append the search pattern "\\*\0" to the directory name */ - p = strchr (dirp->patt, '\0'); - if (dirp->patt < p && *(p-1) != '\\' && *(p-1) != ':') { - *p++ = '\\'; - } - *p++ = '*'; - *p = '\0'; - - /* open directory stream and retrieve the first entry */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->find_data); - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - /* a directory entry is now waiting in memory */ - dirp->cached = 1; - error = 0; - } else { - /* search pattern is not a directory name? */ - DIRENT_SET_ERRNO (ENOENT); - error = 1; - } - } else { - /* buffer too small */ - DIRENT_SET_ERRNO (ENOMEM); - error = 1; - } - - if (error) { - free (dirp); - dirp = NULL; - } - } - - return dirp; -} - - -/***************************************************************************** - * Read a directory entry, and return a pointer to a dirent structure - * containing the name of the entry in d_name field. Individual directory - * entries returned by this very function include regular files, - * sub-directories, pseudo-directories "." and "..", but also volume labels, - * hidden files and system files may be returned. - */ -static struct dirent *readdir(DIR *dirp) -{ - DWORD attr; - if (dirp == NULL) { - /* directory stream did not open */ - DIRENT_SET_ERRNO (EBADF); - return NULL; - } - - /* get next directory entry */ - if (dirp->cached != 0) { - /* a valid directory entry already in memory */ - dirp->cached = 0; - } else { - /* get the next directory entry from stream */ - if (dirp->search_handle == INVALID_HANDLE_VALUE) { - return NULL; - } - if (FindNextFileA (dirp->search_handle, &dirp->find_data) == FALSE) { - /* the very last entry has been processed or an error occured */ - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - return NULL; - } - } - - /* copy as a multibyte character string */ - DIRENT_STRNCPY ( dirp->curentry.d_name, - dirp->find_data.cFileName, - sizeof(dirp->curentry.d_name) ); - dirp->curentry.d_name[MAX_PATH] = '\0'; - - /* compute the length of name */ - dirp->curentry.d_namlen = strlen (dirp->curentry.d_name); - - /* determine file type */ - attr = dirp->find_data.dwFileAttributes; - if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { - dirp->curentry.d_type = DT_CHR; - } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { - dirp->curentry.d_type = DT_DIR; - } else { - dirp->curentry.d_type = DT_REG; - } - return &dirp->curentry; -} - - -/***************************************************************************** - * Close directory stream opened by opendir() function. Close of the - * directory stream invalidates the DIR structure as well as any previously - * read directory entry. - */ -static int closedir(DIR *dirp) -{ - if (dirp == NULL) { - /* invalid directory stream */ - DIRENT_SET_ERRNO (EBADF); - return -1; - } - - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - dirp->search_handle = INVALID_HANDLE_VALUE; - } - - /* release directory structure */ - free (dirp); - return 0; -} - - -/***************************************************************************** - * Resets the position of the directory stream to which dirp refers to the - * beginning of the directory. It also causes the directory stream to refer - * to the current state of the corresponding directory, as a call to opendir() - * would have done. If dirp does not refer to a directory stream, the effect - * is undefined. - */ -static void rewinddir(DIR* dirp) -{ - if (dirp != NULL) { - /* release search handle */ - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - FindClose (dirp->search_handle); - } - - /* open new search handle and retrieve the first entry */ - dirp->search_handle = FindFirstFileA (dirp->patt, &dirp->find_data); - if (dirp->search_handle != INVALID_HANDLE_VALUE) { - /* a directory entry is now waiting in memory */ - dirp->cached = 1; - } else { - /* failed to re-open directory: no directory entry in memory */ - dirp->cached = 0; - } - } -} - - -#ifdef __cplusplus -} -#endif -#endif /*DIRENT_H*/ diff --git a/Core/Code/CppMicroServices/src/util/stdint_p.h b/Core/Code/CppMicroServices/src/util/stdint_p.h deleted file mode 100644 index 242332bac2..0000000000 --- a/Core/Code/CppMicroServices/src/util/stdint_p.h +++ /dev/null @@ -1,33 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USSTDINT_H -#define USSTDINT_H - -#ifdef HAVE_STDINT -#include -#elif defined(_MSC_VER) -#include "stdint_vc_p.h" -#else -#error The stdint.h header is not available -#endif - -#endif // USSTDINT_H diff --git a/Core/Code/CppMicroServices/src/util/stdint_vc_p.h b/Core/Code/CppMicroServices/src/util/stdint_vc_p.h deleted file mode 100644 index c660849c42..0000000000 --- a/Core/Code/CppMicroServices/src/util/stdint_vc_p.h +++ /dev/null @@ -1,235 +0,0 @@ -/* ISO C9x 7.18 Integer types - * Based on ISO/IEC SC22/WG14 9899 Committee draft (SC22 N2794) - * - * THIS SOFTWARE IS NOT COPYRIGHTED - * - * Contributor: Danny Smith - * - * This source code is offered for use in the public domain. You may - * use, modify or distribute it freely. - * - * This code is distributed in the hope that it will be useful but - * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY - * DISCLAIMED. This includes but is not limited to warranties of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * Date: 2000-12-02 - * - * mwb: This was modified in the following ways: - * - * - make it compatible with Visual C++ 6 (which uses - * non-standard keywords and suffixes for 64-bit types) - * - some environments need stddef.h included (for wchar stuff?) - * - handle the fact that Microsoft's limits.h header defines - * SIZE_MAX - * - make corrections for SIZE_MAX, INTPTR_MIN, INTPTR_MAX, UINTPTR_MAX, - * PTRDIFF_MIN, PTRDIFF_MAX, SIG_ATOMIC_MIN, and SIG_ATOMIC_MAX - * to be 64-bit aware. - */ - - -#ifndef _STDINT_H -#define _STDINT_H -#define __need_wint_t -#define __need_wchar_t -#include -#include - -#if _MSC_VER && (_MSC_VER < 1300) -/* using MSVC 6 or earlier - no "long long" type, but might have _int64 type */ -#define __STDINT_LONGLONG __int64 -#define __STDINT_LONGLONG_SUFFIX i64 -#else -#define __STDINT_LONGLONG long long -#define __STDINT_LONGLONG_SUFFIX LL -#endif - -#if !defined( PASTE) -#define PASTE2( x, y) x##y -#define PASTE( x, y) PASTE2( x, y) -#endif /* PASTE */ - - -/* 7.18.1.1 Exact-width integer types */ -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef short int16_t; -typedef unsigned short uint16_t; -typedef int int32_t; -typedef unsigned uint32_t; -typedef __STDINT_LONGLONG int64_t; -typedef unsigned __STDINT_LONGLONG uint64_t; - -/* 7.18.1.2 Minimum-width integer types */ -typedef signed char int_least8_t; -typedef unsigned char uint_least8_t; -typedef short int_least16_t; -typedef unsigned short uint_least16_t; -typedef int int_least32_t; -typedef unsigned uint_least32_t; -typedef __STDINT_LONGLONG int_least64_t; -typedef unsigned __STDINT_LONGLONG uint_least64_t; - -/* 7.18.1.3 Fastest minimum-width integer types - * Not actually guaranteed to be fastest for all purposes - * Here we use the exact-width types for 8 and 16-bit ints. - */ -typedef char int_fast8_t; -typedef unsigned char uint_fast8_t; -typedef short int_fast16_t; -typedef unsigned short uint_fast16_t; -typedef int int_fast32_t; -typedef unsigned int uint_fast32_t; -typedef __STDINT_LONGLONG int_fast64_t; -typedef unsigned __STDINT_LONGLONG uint_fast64_t; - -/* 7.18.1.4 Integer types capable of holding object pointers */ -#ifndef _INTPTR_T_DEFINED -#define _INTPTR_T_DEFINED -#ifdef _WIN64 -typedef __STDINT_LONGLONG intptr_t -#else -typedef int intptr_t; -#endif /* _WIN64 */ -#endif /* _INTPTR_T_DEFINED */ - -#ifndef _UINTPTR_T_DEFINED -#define _UINTPTR_T_DEFINED -#ifdef _WIN64 -typedef unsigned __STDINT_LONGLONG uintptr_t -#else -typedef unsigned int uintptr_t; -#endif /* _WIN64 */ -#endif /* _UINTPTR_T_DEFINED */ - -/* 7.18.1.5 Greatest-width integer types */ -typedef __STDINT_LONGLONG intmax_t; -typedef unsigned __STDINT_LONGLONG uintmax_t; - -/* 7.18.2 Limits of specified-width integer types */ -#if !defined ( __cplusplus) || defined (__STDC_LIMIT_MACROS) - -/* 7.18.2.1 Limits of exact-width integer types */ -#define INT8_MIN (-128) -#define INT16_MIN (-32768) -#define INT32_MIN (-2147483647 - 1) -#define INT64_MIN (PASTE( -9223372036854775807, __STDINT_LONGLONG_SUFFIX) - 1) - -#define INT8_MAX 127 -#define INT16_MAX 32767 -#define INT32_MAX 2147483647 -#define INT64_MAX (PASTE( 9223372036854775807, __STDINT_LONGLONG_SUFFIX)) - -#define UINT8_MAX 0xff /* 255U */ -#define UINT16_MAX 0xffff /* 65535U */ -#define UINT32_MAX 0xffffffff /* 4294967295U */ -#define UINT64_MAX (PASTE( 0xffffffffffffffffU, __STDINT_LONGLONG_SUFFIX)) /* 18446744073709551615ULL */ - -/* 7.18.2.2 Limits of minimum-width integer types */ -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST64_MIN INT64_MIN - -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MAX INT64_MAX - -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -/* 7.18.2.3 Limits of fastest minimum-width integer types */ -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST64_MIN INT64_MIN - -#define INT_FAST8_MAX INT8_MAX -#define INT_FAST16_MAX INT16_MAX -#define INT_FAST32_MAX INT32_MAX -#define INT_FAST64_MAX INT64_MAX - -#define UINT_FAST8_MAX UINT8_MAX -#define UINT_FAST16_MAX UINT16_MAX -#define UINT_FAST32_MAX UINT32_MAX -#define UINT_FAST64_MAX UINT64_MAX - -/* 7.18.2.4 Limits of integer types capable of holding - object pointers */ -#ifdef _WIN64 -#define INTPTR_MIN INT64_MIN -#define INTPTR_MAX INT64_MAX -#define UINTPTR_MAX UINT64_MAX -#else -#define INTPTR_MIN INT32_MIN -#define INTPTR_MAX INT32_MAX -#define UINTPTR_MAX UINT32_MAX -#endif /* _WIN64 */ - -/* 7.18.2.5 Limits of greatest-width integer types */ -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -/* 7.18.3 Limits of other integer types */ -#define PTRDIFF_MIN INTPTR_MIN -#define PTRDIFF_MAX INTPTR_MAX - -#define SIG_ATOMIC_MIN INTPTR_MIN -#define SIG_ATOMIC_MAX INTPTR_MAX - -/* we need to check for SIZE_MAX already defined because MS defines it in limits.h */ -#ifndef SIZE_MAX -#define SIZE_MAX UINTPTR_MAX -#endif - -#ifndef WCHAR_MIN /* also in wchar.h */ -#define WCHAR_MIN 0 -#define WCHAR_MAX ((wchar_t)-1) /* UINT16_MAX */ -#endif - -/* - * wint_t is unsigned short for compatibility with MS runtime - */ -#define WINT_MIN 0 -#define WINT_MAX ((wint_t)-1) /* UINT16_MAX */ - -#endif /* !defined ( __cplusplus) || defined __STDC_LIMIT_MACROS */ - - -/* 7.18.4 Macros for integer constants */ -#if !defined ( __cplusplus) || defined (__STDC_CONSTANT_MACROS) - -/* 7.18.4.1 Macros for minimum-width integer constants - - Accoding to Douglas Gwyn : -"This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC -9899:1999 as initially published, the expansion was required -to be an integer constant of precisely matching type, which -is impossible to accomplish for the shorter types on most -platforms, because C99 provides no standard way to designate -an integer constant with width less than that of type int. -TC1 changed this to require just an integer constant -*expression* with *promoted* type." -*/ - -#define INT8_C(val) ((int8_t) + (val)) -#define UINT8_C(val) ((uint8_t) + (val##U)) -#define INT16_C(val) ((int16_t) + (val)) -#define UINT16_C(val) ((uint16_t) + (val##U)) - -#define INT32_C(val) val##L -#define UINT32_C(val) val##UL -#define INT64_C(val) (PASTE( val, __STDINT_LONGLONG_SUFFIX)) -#define UINT64_C(val)(PASTE( PASTE( val, U), __STDINT_LONGLONG_SUFFIX)) - -/* 7.18.4.2 Macros for greatest-width integer constants */ -#define INTMAX_C(val) INT64_C(val) -#define UINTMAX_C(val) UINT64_C(val) - -#endif /* !defined ( __cplusplus) || defined __STDC_CONSTANT_MACROS */ - -#endif diff --git a/Core/Code/CppMicroServices/src/util/tinfl.c b/Core/Code/CppMicroServices/src/util/tinfl.c deleted file mode 100644 index a17a156b6c..0000000000 --- a/Core/Code/CppMicroServices/src/util/tinfl.c +++ /dev/null @@ -1,592 +0,0 @@ -/* tinfl.c v1.11 - public domain inflate with zlib header parsing/adler32 checking (inflate-only subset of miniz.c) - See "unlicense" statement at the end of this file. - Rich Geldreich , last updated May 20, 2011 - Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt - - The entire decompressor coroutine is implemented in tinfl_decompress(). The other functions are optional high-level helpers. -*/ -#ifndef TINFL_HEADER_INCLUDED -#define TINFL_HEADER_INCLUDED - -#include - -typedef unsigned char mz_uint8; -typedef signed short mz_int16; -typedef unsigned short mz_uint16; -typedef unsigned int mz_uint32; -typedef unsigned int mz_uint; -typedef unsigned long long mz_uint64; - -#if defined(_M_IX86) || defined(_M_X64) -// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 if integer loads and stores to unaligned addresses are acceptable on the target platform (slightly faster). -#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 -// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. -#define MINIZ_LITTLE_ENDIAN 1 -#endif - -#if defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) -// Set MINIZ_HAS_64BIT_REGISTERS to 1 if the processor has 64-bit general purpose registers (enables 64-bit bitbuffer in inflator) -#define MINIZ_HAS_64BIT_REGISTERS 1 -#endif - -// Works around MSVC's spammy "warning C4127: conditional expression is constant" message. -#ifdef _MSC_VER - #define MZ_MACRO_END while (0, 0) -#else - #define MZ_MACRO_END while (0) -#endif - -// Decompression flags used by tinfl_decompress(). -// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. -// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. -// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). -// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. -enum -{ - TINFL_FLAG_PARSE_ZLIB_HEADER = 1, - TINFL_FLAG_HAS_MORE_INPUT = 2, - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, - TINFL_FLAG_COMPUTE_ADLER32 = 8 -}; - -// High level decompression functions: -// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). -// On entry: -// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. -// On return: -// Function returns a pointer to the decompressed data, or NULL on failure. -// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. -// The caller must free() the returned block when it's no longer needed. -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); - -// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. -// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. -#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); - -// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. -// Returns 1 on success or 0 on failure. -typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); - -struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; - -// Max size of LZ dictionary. -#define TINFL_LZ_DICT_SIZE 32768 - -// Return status. -typedef enum -{ - TINFL_STATUS_BAD_PARAM = -3, - TINFL_STATUS_ADLER32_MISMATCH = -2, - TINFL_STATUS_FAILED = -1, - TINFL_STATUS_DONE = 0, - TINFL_STATUS_NEEDS_MORE_INPUT = 1, - TINFL_STATUS_HAS_MORE_OUTPUT = 2 -} tinfl_status; - -// Initializes the decompressor to its initial state. -#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END -#define tinfl_get_adler32(r) (r)->m_check_adler32 - -// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. -// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. -tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); - -// Internal/private bits follow. -enum -{ - TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, - TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS -}; - -typedef struct -{ - mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; - mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; -} tinfl_huff_table; - -#if MINIZ_HAS_64BIT_REGISTERS - #define TINFL_USE_64BIT_BITBUF 1 -#endif - -#if TINFL_USE_64BIT_BITBUF - typedef mz_uint64 tinfl_bit_buf_t; - #define TINFL_BITBUF_SIZE (64) -#else - typedef mz_uint32 tinfl_bit_buf_t; - #define TINFL_BITBUF_SIZE (32) -#endif - -struct tinfl_decompressor_tag -{ - mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; - tinfl_bit_buf_t m_bit_buf; - size_t m_dist_from_out_buf_start; - tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; - mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; -}; - -#endif // #ifdef TINFL_HEADER_INCLUDED - -// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) - -#ifndef TINFL_HEADER_FILE_ONLY - -#include - -// MZ_MALLOC, etc. are only used by the optional high-level helper functions. -#ifdef MINIZ_NO_MALLOC - #define MZ_MALLOC(x) NULL - #define MZ_FREE(x) x, ((void)0) - #define MZ_REALLOC(p, x) NULL -#else - #define MZ_MALLOC(x) malloc(x) - #define MZ_FREE(x) free(x) - #define MZ_REALLOC(p, x) realloc(p, x) -#endif - -#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) -#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) -#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) - #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) -#else - #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) - #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) -#endif - -#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) -#define TINFL_MEMSET(p, c, l) memset(p, c, l) - -#define TINFL_CR_BEGIN switch(r->m_state) { case 0: -#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END -#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END -#define TINFL_CR_FINISH } - -// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never -// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. -#define TINFL_GET_BYTE(state_index, c) do { \ - if (pIn_buf_cur >= pIn_buf_end) { \ - for ( ; ; ) { \ - if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ - TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ - if (pIn_buf_cur < pIn_buf_end) { \ - c = *pIn_buf_cur++; \ - break; \ - } \ - } else { \ - c = 0; \ - break; \ - } \ - } \ - } else c = *pIn_buf_cur++; } MZ_MACRO_END - -#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) -#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END -#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END - -// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. -// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a -// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the -// bit buffer contains >=15 bits (deflate's max. Huffman code size). -#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ - do { \ - temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ - if (temp >= 0) { \ - code_len = temp >> 9; \ - if ((code_len) && (num_bits >= code_len)) \ - break; \ - } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ - code_len = TINFL_FAST_LOOKUP_BITS; \ - do { \ - temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ - } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ - } while (num_bits < 15); - -// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read -// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully -// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. -// The slow path is only executed at the very end of the input buffer. -#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ - int temp; mz_uint code_len, c; \ - if (num_bits < 15) { \ - if ((pIn_buf_end - pIn_buf_cur) < 2) { \ - TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ - } else { \ - bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ - } \ - } \ - if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ - code_len = temp >> 9, temp &= 511; \ - else { \ - code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ - } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END - -tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) -{ - static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; - static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; - static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; - static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; - static const int s_min_table_sizes[3] = { 257, 1, 4 }; - - tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; - const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; - mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; - size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; - - // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). - if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } - - num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; - TINFL_CR_BEGIN - - bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); - counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); - if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); - if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } - } - - do - { - TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; - if (r->m_type == 0) - { - TINFL_SKIP_BITS(5, num_bits & 7); - for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } - if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } - while ((counter) && (num_bits)) - { - TINFL_GET_BITS(51, dist, 8); - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } - *pOut_buf_cur++ = (mz_uint8)dist; - counter--; - } - while (counter) - { - size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } - while (pIn_buf_cur >= pIn_buf_end) - { - if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) - { - TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); - } - else - { - TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); - } - } - n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); - TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; - } - } - else if (r->m_type == 3) - { - TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); - } - else - { - if (r->m_type == 1) - { - mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; - r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); - for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; - } - else - { - for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } - MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } - r->m_table_sizes[2] = 19; - } - for ( ; (int)r->m_type >= 0; r->m_type--) - { - int tree_next, tree_cur; tinfl_huff_table *pTable; - mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); - for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; - used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; - for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } - if ((65536 != total) && (used_syms > 1)) - { - TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); - } - for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) - { - mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; - cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); - if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } - if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } - rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); - for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) - { - tree_cur -= ((rev_code >>= 1) & 1); - if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; - } - tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; - } - if (r->m_type == 2) - { - for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) - { - mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } - if ((dist == 16) && (!counter)) - { - TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); - } - num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; - TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; - } - if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) - { - TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); - } - TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); - } - } - for ( ; ; ) - { - mz_uint8 *pSrc; - for ( ; ; ) - { - if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) - { - TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); - if (counter >= 256) - break; - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } - *pOut_buf_cur++ = (mz_uint8)counter; - } - else - { - int sym2; mz_uint code_len; -#if TINFL_USE_64BIT_BITBUF - if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } -#else - if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } -#endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); - } - counter = sym2; bit_buf >>= code_len; num_bits -= code_len; - if (counter & 256) - break; - -#if !TINFL_USE_64BIT_BITBUF - if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } -#endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); - } - bit_buf >>= code_len; num_bits -= code_len; - - pOut_buf_cur[0] = (mz_uint8)counter; - if (sym2 & 256) - { - pOut_buf_cur++; - counter = sym2; - break; - } - pOut_buf_cur[1] = (mz_uint8)sym2; - pOut_buf_cur += 2; - } - } - if ((counter &= 511) == 256) break; - - num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; - if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } - - TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); - num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; - if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } - - dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; - if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) - { - TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); - } - - pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); - - if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) - { - while (counter--) - { - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } - *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; - } - continue; - } -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - else if ((counter >= 9) && (counter <= dist)) - { - const mz_uint8 *pSrc_end = pSrc + (counter & ~7); - do - { - ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; - ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; - pOut_buf_cur += 8; - } while ((pSrc += 8) < pSrc_end); - if ((counter &= 7) < 3) - { - if (counter) - { - pOut_buf_cur[0] = pSrc[0]; - if (counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - continue; - } - } -#endif - do - { - pOut_buf_cur[0] = pSrc[0]; - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur[2] = pSrc[2]; - pOut_buf_cur += 3; pSrc += 3; - } while ((int)(counter -= 3) > 2); - if ((int)counter > 0) - { - pOut_buf_cur[0] = pSrc[0]; - if ((int)counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - } - } - } while (!(r->m_final & 1)); - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } - } - TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); - TINFL_CR_FINISH - -common_exit: - r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; - *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; - if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) - { - const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; - mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; - while (buf_len) - { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) - { - s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; - } - for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; - } - r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; - } - return status; -} - -// Higher level helper functions. -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) -{ - tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; - *pOut_len = 0; - tinfl_init(&decomp); - for ( ; ; ) - { - size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; - tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, - (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) - { - MZ_FREE(pBuf); *pOut_len = 0; return NULL; - } - src_buf_ofs += src_buf_size; - *pOut_len += dst_buf_size; - if (status == TINFL_STATUS_DONE) break; - new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; - pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); - if (!pNew_buf) - { - MZ_FREE(pBuf); *pOut_len = 0; return NULL; - } - pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; - } - return pBuf; -} - -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) -{ - tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); - status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; -} - -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - int result = 0; - tinfl_decompressor decomp; - mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; - if (!pDict) - return TINFL_STATUS_FAILED; - tinfl_init(&decomp); - for ( ; ; ) - { - size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; - tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, - (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); - in_buf_ofs += in_buf_size; - if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) - break; - if (status != TINFL_STATUS_HAS_MORE_OUTPUT) - { - result = (status == TINFL_STATUS_DONE); - break; - } - dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); - } - MZ_FREE(pDict); - *pIn_buf_size = in_buf_ofs; - return result; -} - -#endif // #ifndef TINFL_HEADER_FILE_ONLY - -/* - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - - For more information, please refer to -*/ diff --git a/Core/Code/CppMicroServices/src/util/usAny.cpp b/Core/Code/CppMicroServices/src/util/usAny.cpp deleted file mode 100644 index fbfd8eb1ab..0000000000 --- a/Core/Code/CppMicroServices/src/util/usAny.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usAny.h" - -US_BEGIN_NAMESPACE - -template -std::string container_to_string(Iterator i1, Iterator i2) -{ - std::stringstream ss; - ss << "("; - const Iterator begin = i1; - for ( ; i1 != i2; ++i1) - { - if (i1 == begin) ss << *i1; - else ss << "," << *i1; - } - ss << ")"; - return ss.str(); -} - -std::string any_value_to_string(const std::vector& val) -{ - return container_to_string(val.begin(), val.end()); -} - -std::string any_value_to_string(const std::list& val) -{ - return container_to_string(val.begin(), val.end()); -} - -std::string any_value_to_string(const std::vector& val) -{ - return container_to_string(val.begin(), val.end()); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/util/usAny.h b/Core/Code/CppMicroServices/src/util/usAny.h deleted file mode 100644 index 8c0e4df75d..0000000000 --- a/Core/Code/CppMicroServices/src/util/usAny.h +++ /dev/null @@ -1,400 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - -Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. -Extracted from Boost 1.46.1 and adapted for CppMicroServices. - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - -=========================================================================*/ - -#ifndef US_ANY_H -#define US_ANY_H - -#include -#include -#include -#include -#include - -#include - -US_BEGIN_NAMESPACE - -template -std::string any_value_to_string(const T& val); - -US_EXPORT std::string any_value_to_string(const std::vector& val); -US_EXPORT std::string any_value_to_string(const std::list& val); - -/** - * \ingroup MicroServicesUtils - * - * An Any class represents a general type and is capable of storing any type, supporting type-safe extraction - * of the internally stored data. - * - * Code taken from the Boost 1.46.1 library. Original copyright by Kevlin Henney. Modified for CppMicroServices. - */ -class Any -{ -public: - - /** - * Creates an empty any type. - */ - Any(): _content(0) - { } - - /** - * Creates an Any which stores the init parameter inside. - * - * \param value The content of the Any - * - * Example: - * \code - * Any a(13); - * Any a(string("12345")); - * \endcode - */ - template - Any(const ValueType& value) - : _content(new Holder(value)) - { } - - /** - * Copy constructor, works with empty Anys and initialized Any values. - * - * \param other The Any to copy - */ - Any(const Any& other) - : _content(other._content ? other._content->Clone() : 0) - { } - - ~Any() - { - delete _content; - } - - /** - * Swaps the content of the two Anys. - * - * \param rhs The Any to swap this Any with. - */ - Any& Swap(Any& rhs) - { - std::swap(_content, rhs._content); - return *this; - } - - /** - * Assignment operator for all types != Any. - * - * \param rhs The value which should be assigned to this Any. - * - * Example: - * \code - * Any a = 13; - * Any a = string("12345"); - * \endcode - */ - template - Any& operator = (const ValueType& rhs) - { - Any(rhs).Swap(*this); - return *this; - } - - /** - * Assignment operator for Any. - * - * \param rhs The Any which should be assigned to this Any. - */ - Any& operator = (const Any& rhs) - { - Any(rhs).Swap(*this); - return *this; - } - - /** - * returns true if the Any is empty - */ - bool Empty() const - { - return !_content; - } - - /** - * Returns a string representation for the content. - * - * Custom types should either provide a std::ostream& operator<<(std::ostream& os, const CustomType& ct) - * function or specialize the any_value_to_string template function for meaningful output. - */ - std::string ToString() const - { - return _content->ToString(); - } - - /** - * Returns the type information of the stored content. - * If the Any is empty typeid(void) is returned. - * It is suggested to always query an Any for its type info before trying to extract - * data via an any_cast/ref_any_cast. - */ - const std::type_info& Type() const - { - return _content ? _content->Type() : typeid(void); - } - -private: - - class Placeholder - { - public: - virtual ~Placeholder() - { } - - virtual std::string ToString() const = 0; - - virtual const std::type_info& Type() const = 0; - virtual Placeholder* Clone() const = 0; - }; - - template - class Holder: public Placeholder - { - public: - Holder(const ValueType& value) - : _held(value) - { } - - virtual std::string ToString() const - { - return any_value_to_string(_held); - } - - virtual const std::type_info& Type() const - { - return typeid(ValueType); - } - - virtual Placeholder* Clone() const - { - return new Holder(_held); - } - - ValueType _held; - - private: // intentionally left unimplemented - Holder& operator=(const Holder &); - }; - -private: - template - friend ValueType* any_cast(Any*); - - template - friend ValueType* unsafe_any_cast(Any*); - - Placeholder* _content; -}; - -class BadAnyCastException : public std::bad_cast -{ -public: - - BadAnyCastException(const std::string& msg = "") - : std::bad_cast(), _msg(msg) - {} - - ~BadAnyCastException() throw() {} - - virtual const char * what() const throw() - { - if (_msg.empty()) - return "US_PREPEND_NAMESPACE(BadAnyCastException): " - "failed conversion using US_PREPEND_NAMESPACE(any_cast)"; - else - return _msg.c_str(); - } - -private: - - std::string _msg; -}; - -/** - * any_cast operator used to extract the ValueType from an Any*. Will return a pointer - * to the stored value. - * - * Example Usage: - * \code - * MyType* pTmp = any_cast(pAny) - * \endcode - * Will return NULL if the cast fails, i.e. types don't match. - */ -template -ValueType* any_cast(Any* operand) -{ - return operand && operand->Type() == typeid(ValueType) - ? &static_cast*>(operand->_content)->_held - : 0; -} - -/** - * any_cast operator used to extract a const ValueType pointer from an const Any*. Will return a const pointer - * to the stored value. - * - * Example Usage: - * \code - * const MyType* pTmp = any_cast(pAny) - * \endcode - * Will return NULL if the cast fails, i.e. types don't match. - */ -template -const ValueType* any_cast(const Any* operand) -{ - return any_cast(const_cast(operand)); -} - -/** - * any_cast operator used to extract a copy of the ValueType from an const Any&. - * - * Example Usage: - * \code - * MyType tmp = any_cast(anAny) - * \endcode - * Will throw a BadCastException if the cast fails. - * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... - * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in - * these cases. - */ -template -ValueType any_cast(const Any& operand) -{ - ValueType* result = any_cast(const_cast(&operand)); - if (!result) throw BadAnyCastException("Failed to convert between const Any types"); - return *result; -} - -/** - * any_cast operator used to extract a copy of the ValueType from an Any&. - * - * Example Usage: - * \code - * MyType tmp = any_cast(anAny) - * \endcode - * Will throw a BadCastException if the cast fails. - * Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... - * Some compilers will accept this code although a copy is returned. Use the ref_any_cast in - * these cases. - */ -template -ValueType any_cast(Any& operand) -{ - ValueType* result = any_cast(&operand); - if (!result) throw BadAnyCastException("Failed to convert between Any types"); - return *result; -} - -/** - * ref_any_cast operator used to return a const reference to the internal data. - * - * Example Usage: - * \code - * const MyType& tmp = ref_any_cast(anAny); - * \endcode - */ -template -const ValueType& ref_any_cast(const Any & operand) -{ - ValueType* result = any_cast(const_cast(&operand)); - if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between const Any types"); - return *result; -} - -/** - * ref_any_cast operator used to return a reference to the internal data. - * - * Example Usage: - * \code - * MyType& tmp = ref_any_cast(anAny); - * \endcode - */ -template -ValueType& ref_any_cast(Any& operand) -{ - ValueType* result = any_cast(&operand); - if (!result) throw BadAnyCastException("RefAnyCast: Failed to convert between Any types"); - return *result; -} - -/** - * \internal - * - * The "unsafe" versions of any_cast are not part of the - * public interface and may be removed at any time. They are - * required where we know what type is stored in the any and can't - * use typeid() comparison, e.g., when our types may travel across - * different shared libraries. - */ -template -ValueType* unsafe_any_cast(Any* operand) -{ - return &static_cast*>(operand->_content)->_held; -} - -/** - * \internal - * - * The "unsafe" versions of any_cast are not part of the - * public interface and may be removed at any time. They are - * required where we know what type is stored in the any and can't - * use typeid() comparison, e.g., when our types may travel across - * different shared libraries. - */ -template -const ValueType* unsafe_any_cast(const Any* operand) -{ - return any_cast(const_cast(operand)); -} - -US_EXPORT std::string any_value_to_string(const std::vector& val); - -template -std::string any_value_to_string(const T& val) -{ - std::stringstream ss; - ss << val; - return ss.str(); -} - -US_END_NAMESPACE - -inline std::ostream& operator<< (std::ostream& os, const US_PREPEND_NAMESPACE(Any)& any) -{ - return os << any.ToString(); -} - -#endif // US_ANY_H diff --git a/Core/Code/CppMicroServices/src/util/usAtomicInt_p.h b/Core/Code/CppMicroServices/src/util/usAtomicInt_p.h deleted file mode 100644 index 4bc954ec02..0000000000 --- a/Core/Code/CppMicroServices/src/util/usAtomicInt_p.h +++ /dev/null @@ -1,83 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USATOMICINT_H -#define USATOMICINT_H - -#include -#include "usThreads_p.h" - -US_BEGIN_NAMESPACE - -/** - * This class acts as an atomic integer. - * - * The integer value represented by this class can be incremented - * and decremented atomically. This is often useful in reference - * counting scenarios to minimize locking overhead in multi-threaded - * environments. - */ -class AtomicInt : private US_DEFAULT_THREADING -{ - -public: - - AtomicInt(int value = 0) : m_ReferenceCount(value) {} - - /** - * Increase the reference count atomically by 1. - * - * \return true if the new value is unequal to zero, false - * otherwise. - */ - inline bool Ref() const - { return AtomicIncrement(m_ReferenceCount) != 0; } - - /** - * Decrease the reference count atomically by 1. - * - * \return true if the new value is unequal to zero, false - * otherwise. - */ - inline bool Deref() const - { return AtomicDecrement(m_ReferenceCount) != 0; } - - /** - * Returns the current value. - * - */ - inline operator int() const - { - IntType curr(0); - AtomicAssign(curr, m_ReferenceCount); - return curr; - } - -private: - - mutable IntType m_ReferenceCount; - -}; - -US_END_NAMESPACE - -#endif // USATOMICINT_H diff --git a/Core/Code/CppMicroServices/src/util/usBase.h b/Core/Code/CppMicroServices/src/util/usBase.h deleted file mode 100644 index ba57661d3f..0000000000 --- a/Core/Code/CppMicroServices/src/util/usBase.h +++ /dev/null @@ -1,45 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USBASE_H -#define USBASE_H - -#include -#include - -US_BEGIN_NAMESPACE - -class Base -{ - -public: - - virtual ~Base() {} - virtual const char* GetNameOfClass() const { return "US_PREPEND_NAMESPACE(Base)"; } -}; - -US_END_NAMESPACE - -template<> inline const char* us_service_impl_name(US_PREPEND_NAMESPACE(Base)* impl) -{ return impl->GetNameOfClass(); } - -#endif // USBASE_H diff --git a/Core/Code/CppMicroServices/src/util/usFunctor_p.h b/Core/Code/CppMicroServices/src/util/usFunctor_p.h deleted file mode 100644 index dfdd608d0f..0000000000 --- a/Core/Code/CppMicroServices/src/util/usFunctor_p.h +++ /dev/null @@ -1,139 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USFUNCTOR_H -#define USFUNCTOR_H - -#include - -US_BEGIN_NAMESPACE - -template -class FunctorImpl -{ -public: - - virtual void operator()(Arg) = 0; - virtual FunctorImpl* Clone() const = 0; - - bool operator==(const FunctorImpl& o) const - { return typeid(*this) == typeid(o) && IsEqual(o); } - - virtual ~FunctorImpl() {} - -private: - - virtual bool IsEqual(const FunctorImpl& o) const = 0; -}; - -template -class FunctorHandler : public FunctorImpl -{ -public: - - FunctorHandler(const Fun& fun) : m_Fun(fun) {} - - FunctorHandler* Clone() const - { return new FunctorHandler(*this); } - - void operator()(Arg a) - { m_Fun(a); } - -private: - - bool IsEqual(const FunctorImpl& o) const - { return this->m_Fun == static_cast(o).m_Fun; } - - Fun m_Fun; -}; - -template -class MemFunHandler : public FunctorImpl -{ -public: - - MemFunHandler(const PointerToObj& pObj, PointerToMemFn pMemFn) - : m_pObj(pObj), m_pMemFn(pMemFn) - {} - - MemFunHandler* Clone() const - { return new MemFunHandler(*this); } - - void operator()(Arg a) - { ((*m_pObj).*m_pMemFn)(a); } - -private: - - bool IsEqual(const FunctorImpl& o) const - { return this->m_pObj == static_cast(o).m_pObj && - this->m_pMemFn == static_cast(o).m_pMemFn; } - - PointerToObj m_pObj; - PointerToMemFn m_pMemFn; - -}; - -template -class Functor -{ -public: - - Functor() : m_Impl(0) {} - - template - Functor(const Fun& fun) - : m_Impl(new FunctorHandler(fun)) - {} - - template - Functor(const PtrObj& p, MemFn memFn) - : m_Impl(new MemFunHandler(p, memFn)) - {} - - Functor(const Functor& f) : m_Impl(f.m_Impl->Clone()) {} - - Functor& operator=(const Functor& f) - { - Impl* tmp = f.m_Impl->Clone(); - std::swap(tmp, m_Impl); - delete tmp; - } - - bool operator==(const Functor& f) const - { return (*m_Impl) == (*f.m_Impl); } - - ~Functor() { delete m_Impl; } - - void operator()(Arg a) - { - (*m_Impl)(a); - } - -private: - - typedef FunctorImpl Impl; - Impl* m_Impl; -}; - -US_END_NAMESPACE - -#endif // USFUNCTOR_H diff --git a/Core/Code/CppMicroServices/src/util/usSharedData.h b/Core/Code/CppMicroServices/src/util/usSharedData.h deleted file mode 100644 index f3a6dfc82f..0000000000 --- a/Core/Code/CppMicroServices/src/util/usSharedData.h +++ /dev/null @@ -1,274 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - -Modified version of qshareddata.h from Qt 4.7.3 for CppMicroServices. -Original copyright (c) Nokia Corporation. Usage covered by the -GNU Lesser General Public License version 2.1 -(http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) and the Nokia Qt -LGPL Exception version 1.1 (file LGPL_EXCEPTION.txt in Qt 4.7.3 package). - -=========================================================================*/ - -#ifndef USSHAREDDATA_H -#define USSHAREDDATA_H - -#include "usAtomicInt_p.h" - -#include -#include - -US_BEGIN_NAMESPACE - -/** - * \ingroup MicroServicesUtils - */ -class SharedData -{ -public: - mutable AtomicInt ref; - - inline SharedData() : ref(0) { } - inline SharedData(const SharedData&) : ref(0) { } - -private: - // using the assignment operator would lead to corruption in the ref-counting - SharedData& operator=(const SharedData&); -}; - -/** - * \ingroup MicroServicesUtils - */ -template -class SharedDataPointer -{ -public: - typedef T Type; - typedef T* pointer; - - inline void Detach() { if (d && d->ref != 1) Detach_helper(); } - inline T& operator*() { Detach(); return *d; } - inline const T& operator*() const { return *d; } - inline T* operator->() { Detach(); return d; } - inline const T* operator->() const { return d; } - inline operator T*() { Detach(); return d; } - inline operator const T*() const { return d; } - inline T* Data() { Detach(); return d; } - inline const T* Data() const { return d; } - inline const T* ConstData() const { return d; } - - inline bool operator==(const SharedDataPointer& other) const { return d == other.d; } - inline bool operator!=(const SharedDataPointer& other) const { return d != other.d; } - - inline SharedDataPointer() : d(0) { } - inline ~SharedDataPointer() { if (d && !d->ref.Deref()) delete d; } - - explicit SharedDataPointer(T* data); - inline SharedDataPointer(const SharedDataPointer& o) : d(o.d) { if (d) d->ref.Ref(); } - - inline SharedDataPointer & operator=(const SharedDataPointer& o) - { - if (o.d != d) - { - if (o.d) - o.d->ref.Ref(); - T *old = d; - d = o.d; - if (old && !old->ref.Deref()) - delete old; - } - return *this; - } - - inline SharedDataPointer &operator=(T *o) - { - if (o != d) - { - if (o) - o->ref.Ref(); - T *old = d; - d = o; - if (old && !old->ref.Deref()) - delete old; - } - return *this; - } - - inline bool operator!() const { return !d; } - - inline void Swap(SharedDataPointer& other) - { - using std::swap; - swap(d, other.d); - } - -protected: - T* Clone(); - -private: - void Detach_helper(); - - T *d; -}; - -/** - * \ingroup MicroServicesUtils - */ -template class ExplicitlySharedDataPointer -{ -public: - typedef T Type; - typedef T* pointer; - - inline T& operator*() const { return *d; } - inline T* operator->() { return d; } - inline T* operator->() const { return d; } - inline T* Data() const { return d; } - inline const T* ConstData() const { return d; } - - inline void Detach() { if (d && d->ref != 1) Detach_helper(); } - - inline void Reset() - { - if(d && !d->ref.Deref()) - delete d; - - d = 0; - } - - inline operator bool () const { return d != 0; } - - inline bool operator==(const ExplicitlySharedDataPointer& other) const { return d == other.d; } - inline bool operator!=(const ExplicitlySharedDataPointer& other) const { return d != other.d; } - inline bool operator==(const T* ptr) const { return d == ptr; } - inline bool operator!=(const T* ptr) const { return d != ptr; } - - inline ExplicitlySharedDataPointer() { d = 0; } - inline ~ExplicitlySharedDataPointer() { if (d && !d->ref.Deref()) delete d; } - - explicit ExplicitlySharedDataPointer(T* data); - inline ExplicitlySharedDataPointer(const ExplicitlySharedDataPointer &o) - : d(o.d) { if (d) d->ref.Ref(); } - - template - inline ExplicitlySharedDataPointer(const ExplicitlySharedDataPointer& o) - : d(static_cast(o.Data())) - { - if(d) - d->ref.Ref(); - } - - inline ExplicitlySharedDataPointer& operator=(const ExplicitlySharedDataPointer& o) - { - if (o.d != d) - { - if (o.d) - o.d->ref.Ref(); - T *old = d; - d = o.d; - if (old && !old->ref.Deref()) - delete old; - } - return *this; - } - - inline ExplicitlySharedDataPointer& operator=(T* o) - { - if (o != d) - { - if (o) - o->ref.Ref(); - T *old = d; - d = o; - if (old && !old->ref.Deref()) - delete old; - } - return *this; - } - - inline bool operator!() const { return !d; } - - inline void Swap(ExplicitlySharedDataPointer& other) - { - using std::swap; - swap(d, other.d); - } - -protected: - T* Clone(); - -private: - void Detach_helper(); - - T *d; -}; - - -template -SharedDataPointer::SharedDataPointer(T* adata) : d(adata) -{ if (d) d->ref.Ref(); } - -template -T* SharedDataPointer::Clone() -{ - return new T(*d); -} - -template -void SharedDataPointer::Detach_helper() -{ - T *x = Clone(); - x->ref.Ref(); - if (!d->ref.Deref()) - delete d; - d = x; -} - -template -T* ExplicitlySharedDataPointer::Clone() -{ - return new T(*d); -} - -template -void ExplicitlySharedDataPointer::Detach_helper() -{ - T *x = Clone(); - x->ref.Ref(); - if (!d->ref.Deref()) - delete d; - d = x; -} - -template -ExplicitlySharedDataPointer::ExplicitlySharedDataPointer(T* adata) - : d(adata) -{ if (d) d->ref.Ref(); } - -template -void swap(US_PREPEND_NAMESPACE(SharedDataPointer& p1, US_PREPEND_NAMESPACE(SharedDataPointer& p2) -{ p1.Swap(p2); } - -template -void swap(US_PREPEND_NAMESPACE(ExplicitlySharedDataPointer& p1, US_PREPEND_NAMESPACE(ExplicitlySharedDataPointer& p2) -{ p1.Swap(p2); } - -US_END_NAMESPACE - -#endif // USSHAREDDATA_H diff --git a/Core/Code/CppMicroServices/src/util/usStaticInit_p.h b/Core/Code/CppMicroServices/src/util/usStaticInit_p.h deleted file mode 100644 index b69d45c61d..0000000000 --- a/Core/Code/CppMicroServices/src/util/usStaticInit_p.h +++ /dev/null @@ -1,166 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - -Extracted from qglobal.h from Qt 4.7.3 and adapted for CppMicroServices. -Original copyright (c) Nokia Corporation. Usage covered by the -GNU Lesser General Public License version 2.1 -(http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html) and the Nokia Qt -LGPL Exception version 1.1 (file LGPL_EXCEPTION.txt in Qt 4.7.3 package). - -=========================================================================*/ - -#ifndef US_STATIC_INIT_H -#define US_STATIC_INIT_H - -#include -#include "usThreads_p.h" - -US_BEGIN_NAMESPACE - -// POD for US_GLOBAL_STATIC -template -class GlobalStatic : public US_DEFAULT_THREADING > -{ -public: - - GlobalStatic(T* p = 0, bool destroyed = false) : pointer(p), destroyed(destroyed) {} - - T* pointer; - bool destroyed; - -private: - - // purposely not implemented - GlobalStatic(const GlobalStatic&); - GlobalStatic& operator=(const GlobalStatic&); -}; - -template -struct DefaultGlobalStaticDeleter -{ - void operator()(GlobalStatic& globalStatic) const - { - delete globalStatic.pointer; - globalStatic.pointer = 0; - globalStatic.destroyed = true; - } -}; - -// Created as a function-local static to delete a GlobalStatic -template class Deleter = DefaultGlobalStaticDeleter> -class GlobalStaticDeleter -{ -public: - GlobalStatic &globalStatic; - - GlobalStaticDeleter(GlobalStatic &_globalStatic) - : globalStatic(_globalStatic) - { } - - inline ~GlobalStaticDeleter() - { - Deleter deleter; - deleter(globalStatic); - } -}; - -US_END_NAMESPACE - - -#define US_GLOBAL_STATIC_INIT(TYPE, NAME) \ - static US_PREPEND_NAMESPACE(GlobalStatic)& this_##NAME() \ - { \ - static US_PREPEND_NAMESPACE(GlobalStatic) l; \ - return l; \ - } - -#define US_GLOBAL_STATIC(TYPE, NAME) \ - US_GLOBAL_STATIC_INIT(TYPE, NAME) \ - static TYPE *NAME() \ - { \ - if (!this_##NAME().pointer && !this_##NAME().destroyed) \ - { \ - TYPE *x = new TYPE; \ - bool ok = false; \ - { \ - US_PREPEND_NAMESPACE(GlobalStatic)::Lock lock(this_##NAME()); \ - if (!this_##NAME().pointer) \ - { \ - this_##NAME().pointer = x; \ - ok = true; \ - } \ - } \ - if (!ok) \ - delete x; \ - else \ - static US_PREPEND_NAMESPACE(GlobalStaticDeleter) cleanup(this_##NAME()); \ - } \ - return this_##NAME().pointer; \ - } - -#define US_GLOBAL_STATIC_WITH_DELETER(TYPE, NAME, DELETER) \ - US_GLOBAL_STATIC_INIT(TYPE, NAME) \ - static TYPE *NAME() \ - { \ - if (!this_##NAME().pointer && !this_##NAME().destroyed) \ - { \ - TYPE *x = new TYPE; \ - bool ok = false; \ - { \ - US_PREPEND_NAMESPACE(GlobalStatic)::Lock lock(this_##NAME()); \ - if (!this_##NAME().pointer) \ - { \ - this_##NAME().pointer = x; \ - ok = true; \ - } \ - } \ - if (!ok) \ - delete x; \ - else \ - static US_PREPEND_NAMESPACE(GlobalStaticDeleter) cleanup(this_##NAME()); \ - } \ - return this_##NAME().pointer; \ - } - -#define US_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS) \ - US_GLOBAL_STATIC_INIT(TYPE, NAME) \ - static TYPE *NAME() \ - { \ - if (!this_##NAME().pointer && !this_##NAME().destroyed) \ - { \ - TYPE *x = new TYPE ARGS; \ - bool ok = false; \ - { \ - US_PREPEND_NAMESPACE(GlobalStatic)::Lock lock(this_##NAME()); \ - if (!this_##NAME().pointer) \ - { \ - this_##NAME().pointer = x; \ - ok = true; \ - } \ - } \ - if (!ok) \ - delete x; \ - else \ - static US_PREPEND_NAMESPACE(GlobalStaticDeleter) cleanup(this_##NAME()); \ - } \ - return this_##NAME().pointer; \ - } - -#endif // US_STATIC_INIT_H diff --git a/Core/Code/CppMicroServices/src/util/usThreads.cpp b/Core/Code/CppMicroServices/src/util/usThreads.cpp deleted file mode 100644 index f26bc0c023..0000000000 --- a/Core/Code/CppMicroServices/src/util/usThreads.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usThreads_p.h" - -#include "usUtils_p.h" - -#ifdef US_PLATFORM_POSIX -#include -#include -#endif - -US_BEGIN_NAMESPACE - -WaitCondition::WaitCondition() -{ -#ifdef US_ENABLE_THREADING_SUPPORT - #ifdef US_PLATFORM_POSIX - pthread_cond_init(&m_WaitCondition, 0); - #else - m_NumberOfWaiters = 0; - m_WasNotifyAll = 0; - m_Semaphore = CreateSemaphore(0, // no security - 0, // initial value - 0x7fffffff, // max count - 0); // unnamed - InitializeCriticalSection(&m_NumberOfWaitersLock); - m_WaitersAreDone = CreateEvent(0, // no security - FALSE, // auto-reset - FALSE, // non-signaled initially - 0 ); // unnamed - #endif -#endif -} - -WaitCondition::~WaitCondition() -{ -#ifdef US_ENABLE_THREADING_SUPPORT - #ifdef US_PLATFORM_POSIX - pthread_cond_destroy(&m_WaitCondition); - #else - CloseHandle(m_Semaphore); - CloseHandle(m_WaitersAreDone); - DeleteCriticalSection(&m_NumberOfWaitersLock); - #endif -#endif -} - -void WaitCondition::Notify() -{ -#ifdef US_ENABLE_THREADING_SUPPORT - #ifdef US_PLATFORM_POSIX - pthread_cond_signal(&m_WaitCondition); - #else - EnterCriticalSection(&m_NumberOfWaitersLock); - int haveWaiters = m_NumberOfWaiters > 0; - LeaveCriticalSection(&m_NumberOfWaitersLock); - - // if there were not any waiters, then this is a no-op - if (haveWaiters) - { - ReleaseSemaphore(m_Semaphore, 1, 0); - } - #endif -#endif -} - -void WaitCondition::NotifyAll() -{ -#ifdef US_ENABLE_THREADING_SUPPORT - #ifdef US_PLATFORM_POSIX - pthread_cond_broadcast(&m_WaitCondition); - #else - // This is needed to ensure that m_NumberOfWaiters and m_WasNotifyAll are - // consistent - EnterCriticalSection(&m_NumberOfWaitersLock); - int haveWaiters = 0; - - if (m_NumberOfWaiters > 0) - { - // We are broadcasting, even if there is just one waiter... - // Record that we are broadcasting, which helps optimize Notify() - // for the non-broadcast case - m_WasNotifyAll = 1; - haveWaiters = 1; - } - - if (haveWaiters) - { - // Wake up all waiters atomically - ReleaseSemaphore(m_Semaphore, m_NumberOfWaiters, 0); - - LeaveCriticalSection(&m_NumberOfWaitersLock); - - // Wait for all the awakened threads to acquire the counting - // semaphore - WaitForSingleObject(m_WaitersAreDone, INFINITE); - // This assignment is ok, even without the m_NumberOfWaitersLock held - // because no other waiter threads can wake up to access it. - m_WasNotifyAll = 0; - } - else - { - LeaveCriticalSection(&m_NumberOfWaitersLock); - } - #endif -#endif -} - -bool WaitCondition::Wait(MutexType* mutex, unsigned long timeoutMillis) -{ - return Wait(*mutex, timeoutMillis); -} - -#ifdef US_ENABLE_THREADING_SUPPORT -bool WaitCondition::Wait(MutexType& mutex, unsigned long timeoutMillis) -{ - #ifdef US_PLATFORM_POSIX - struct timespec ts, * pts = 0; - if (timeoutMillis) - { - pts = &ts; - struct timeval tv; - int error = gettimeofday(&tv, NULL); - if (error) - { - US_ERROR << "gettimeofday error: " << GetLastErrorStr(); - return false; - } - ts.tv_sec = tv.tv_sec; - ts.tv_nsec = tv.tv_usec * 1000; - ts.tv_sec += timeoutMillis / 1000; - ts.tv_nsec += (timeoutMillis % 1000) * 1000000; - ts.tv_sec += ts.tv_nsec / 1000000000; - ts.tv_nsec = ts.tv_nsec % 1000000000; - } - - if (pts) - { - int error = pthread_cond_timedwait(&m_WaitCondition, &mutex.m_Mtx, pts); - if (error == 0) - { - return true; - } - else - { - if (error != ETIMEDOUT) - { - US_ERROR << "pthread_cond_timedwait error: " << GetLastErrorStr(); - } - return false; - } - } - else - { - int error = pthread_cond_wait(&m_WaitCondition, &mutex.m_Mtx); - if (error) - { - US_ERROR << "pthread_cond_wait error: " << GetLastErrorStr(); - return false; - } - return true; - } - - #else - - // Avoid race conditions - EnterCriticalSection(&m_NumberOfWaitersLock); - m_NumberOfWaiters++; - LeaveCriticalSection(&m_NumberOfWaitersLock); - - DWORD dw; - bool result = true; - - // This call atomically releases the mutex and waits on the - // semaphore until signaled - dw = SignalObjectAndWait(mutex.m_Mtx, m_Semaphore, timeoutMillis ? timeoutMillis : INFINITE, FALSE); - if (dw == WAIT_TIMEOUT) - { - result = false; - } - else if (dw == WAIT_FAILED) - { - result = false; - US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); - } - - // Reacquire lock to avoid race conditions - EnterCriticalSection(&m_NumberOfWaitersLock); - - // We're no longer waiting.... - m_NumberOfWaiters--; - - // Check to see if we're the last waiter after the broadcast - int lastWaiter = m_WasNotifyAll && m_NumberOfWaiters == 0; - - LeaveCriticalSection(&m_NumberOfWaitersLock); - - // If we're the last waiter thread during this particular broadcast - // then let the other threads proceed - if (lastWaiter) - { - // This call atomically signals the m_WaitersAreDone event and waits - // until it can acquire the external mutex. This is required to - // ensure fairness - dw = SignalObjectAndWait(m_WaitersAreDone, mutex.m_Mtx, - INFINITE, FALSE); - if (result && dw == WAIT_FAILED) - { - result = false; - US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); - } - } - else - { - // Always regain the external mutex since that's the guarentee we - // give to our callers - dw = WaitForSingleObject(mutex.m_Mtx, INFINITE); - if (result && dw == WAIT_FAILED) - { - result = false; - US_ERROR << "SignalObjectAndWait failed: " << GetLastErrorStr(); - } - } - - return result; - #endif -} -#else -bool WaitCondition::Wait(MutexType&, unsigned long) -{ - return true; -} -#endif - -US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/src/util/usThreads_p.h b/Core/Code/CppMicroServices/src/util/usThreads_p.h deleted file mode 100644 index 8c77a24781..0000000000 --- a/Core/Code/CppMicroServices/src/util/usThreads_p.h +++ /dev/null @@ -1,430 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTHREADINGMODEL_H -#define USTHREADINGMODEL_H - -#include - -#ifdef US_ENABLE_THREADING_SUPPORT - - // Atomic compiler intrinsics - - #if defined(US_PLATFORM_APPLE) - // OSAtomic.h optimizations only used in 10.5 and later - #include - #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 - #include - #define US_ATOMIC_OPTIMIZATION_APPLE - #endif - - #elif defined(__GLIBCPP__) || defined(__GLIBCXX__) - - #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) - # include - #else - # include - #endif - #define US_ATOMIC_OPTIMIZATION_GNUC - - #endif - - // Mutex support - - #ifdef US_PLATFORM_WINDOWS - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #ifndef NOMINMAX - #define NOMINMAX - #endif - #include - - #define US_THREADS_MUTEX(x) HANDLE (x); - #define US_THREADS_MUTEX_INIT(x) - #define US_THREADS_MUTEX_CTOR(x) : x(::CreateMutex(NULL, FALSE, NULL)) - #define US_THREADS_MUTEX_DELETE(x) ::CloseHandle (x) - #define US_THREADS_MUTEX_LOCK(x) ::WaitForSingleObject (x, INFINITE) - #define US_THREADS_MUTEX_UNLOCK(x) ::ReleaseMutex (x) - #define US_THREADS_LONG LONG - - #define US_ATOMIC_OPTIMIZATION - #define US_ATOMIC_INCREMENT(x) IntType n = InterlockedIncrement(x) - #define US_ATOMIC_DECREMENT(x) IntType n = InterlockedDecrement(x) - #define US_ATOMIC_ASSIGN(l, r) InterlockedExchange(l, r) - - #elif defined(US_PLATFORM_POSIX) - - #include - - #define US_THREADS_MUTEX(x) pthread_mutex_t (x); - #define US_THREADS_MUTEX_INIT(x) ::pthread_mutex_init(&x, 0) - #define US_THREADS_MUTEX_CTOR(x) : x() - #define US_THREADS_MUTEX_DELETE(x) ::pthread_mutex_destroy (&x) - #define US_THREADS_MUTEX_LOCK(x) ::pthread_mutex_lock (&x) - #define US_THREADS_MUTEX_UNLOCK(x) ::pthread_mutex_unlock (&x) - - #define US_ATOMIC_OPTIMIZATION - #if defined(US_ATOMIC_OPTIMIZATION_APPLE) - #if defined (__LP64__) && __LP64__ - #define US_THREADS_LONG volatile int64_t - #define US_ATOMIC_INCREMENT(x) IntType n = OSAtomicIncrement64Barrier(x) - #define US_ATOMIC_DECREMENT(x) IntType n = OSAtomicDecrement64Barrier(x) - #define US_ATOMIC_ASSIGN(l, v) OSAtomicCompareAndSwap64Barrier(*l, v, l) - #else - #define US_THREADS_LONG volatile int32_t - #define US_ATOMIC_INCREMENT(x) IntType n = OSAtomicIncrement32Barrier(x) - #define US_ATOMIC_DECREMENT(x) IntType n = OSAtomicDecrement32Barrier(x) - #define US_ATOMIC_ASSIGN(l, v) OSAtomicCompareAndSwap32Barrier(*l, v, l) - #endif - #elif defined(US_ATOMIC_OPTIMIZATION_GNUC) - #define US_THREADS_LONG _Atomic_word - #define US_ATOMIC_INCREMENT(x) IntType n = __sync_add_and_fetch(x, 1) - #define US_ATOMIC_DECREMENT(x) IntType n = __sync_add_and_fetch(x, -1) - #define US_ATOMIC_ASSIGN(l, v) __sync_val_compare_and_swap(l, *l, v) - #else - #define US_THREADS_LONG long - #undef US_ATOMIC_OPTIMIZATION - #define US_ATOMIC_INCREMENT(x) m_AtomicMtx.Lock(); \ - IntType n = ++(*x); \ - m_AtomicMtx.Unlock() - #define US_ATOMIC_DECREMENT(x) m_AtomicMtx.Lock(); \ - IntType n = --(*x); \ - m_AtomicMtx.Unlock() - #define US_ATOMIC_ASSIGN(l, v) m_AtomicMtx.Lock(); \ - *l = v; \ - m_AtomicMtx.Unlock() - #endif - - #endif - -#else - - // single threaded - #define US_THREADS_MUTEX(x) - #define US_THREADS_MUTEX_INIT(x) - #define US_THREADS_MUTEX_CTOR(x) - #define US_THREADS_MUTEX_DELETE(x) - #define US_THREADS_MUTEX_LOCK(x) - #define US_THREADS_MUTEX_UNLOCK(x) - #define US_THREADS_LONG - -#endif - -#ifndef US_DEFAULT_MUTEX - #define US_DEFAULT_MUTEX US_PREPEND_NAMESPACE(Mutex) -#endif - - -US_BEGIN_NAMESPACE - -class Mutex -{ -public: - - Mutex() US_THREADS_MUTEX_CTOR(m_Mtx) - { - US_THREADS_MUTEX_INIT(m_Mtx); - } - - ~Mutex() - { - US_THREADS_MUTEX_DELETE(m_Mtx); - } - - void Lock() - { - US_THREADS_MUTEX_LOCK(m_Mtx); - } - void Unlock() - { - US_THREADS_MUTEX_UNLOCK(m_Mtx); - } - -private: - - friend class WaitCondition; - - // Copy-constructor not implemented. - Mutex(const Mutex &); - // Copy-assignement operator not implemented. - Mutex & operator = (const Mutex &); - - US_THREADS_MUTEX(m_Mtx) -}; - -template -class MutexLock -{ -public: - typedef MutexPolicy MutexType; - - MutexLock(MutexType& mtx) : m_Mtx(&mtx) { m_Mtx->Lock(); } - ~MutexLock() { m_Mtx->Unlock(); } - -private: - MutexType* m_Mtx; - - // purposely not implemented - MutexLock(const MutexLock&); - MutexLock& operator=(const MutexLock&); -}; - -typedef MutexLock<> DefaultMutexLock; - - -/** - * \brief A thread synchronization object used to suspend execution until some - * condition on shared data is met. - * - * A thread calls Wait() to suspend its execution until the condition is - * met. Each call to Notify() from an executing thread will then cause a single - * waiting thread to be released. A call to Notify() means, "signal - * that the condition is true." NotifyAll() releases all threads waiting on - * the condition variable. - * - * The WaitCondition implementation is consistent with the standard - * definition and use of condition variables in pthreads and other common - * thread libraries. - * - * IMPORTANT: A condition variable always requires an associated mutex - * object. The mutex object is used to avoid a dangerous race condition when - * Wait() and Notify() are called simultaneously from two different - * threads. - * - * On systems using pthreads, this implementation abstracts the - * standard calls to the pthread condition variable. On Win32 - * systems, there is no system provided condition variable. This - * class implements a condition variable using a critical section, a - * semphore, an event and a number of counters. The implementation is - * almost an extract translation of the implementation presented by - * Douglas C Schmidt and Irfan Pyarali in "Strategies for Implementing - * POSIX Condition Variables on Win32". This article can be found at - * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html - * - */ -class US_EXPORT WaitCondition -{ -public: - - typedef US_DEFAULT_MUTEX MutexType; - - WaitCondition(); - ~WaitCondition(); - - /** Suspend execution of this thread until the condition is signaled. The - * argument is a SimpleMutex object that must be locked prior to calling - * this method. */ - bool Wait(MutexType& mutex, unsigned long time = 0); - - bool Wait(MutexType* mutex, unsigned long time = 0); - - /** Notify that the condition is true and release one waiting thread */ - void Notify(); - - /** Notify that the condition is true and release all waiting threads */ - void NotifyAll(); - -private: - - // purposely not implemented - WaitCondition(const WaitCondition& other); - const WaitCondition& operator=(const WaitCondition&); - -#ifdef US_ENABLE_THREADING_SUPPORT - #ifdef US_PLATFORM_POSIX - pthread_cond_t m_WaitCondition; - #else - - int m_NumberOfWaiters; // number of waiting threads - CRITICAL_SECTION m_NumberOfWaitersLock; // Serialize access to - // m_NumberOfWaiters - - HANDLE m_Semaphore; // Semaphore to queue threads - HANDLE m_WaitersAreDone; // Auto-reset event used by the - // broadcast/signal thread to - // wait for all the waiting - // threads to wake up and - // release the semaphore - - std::size_t m_WasNotifyAll; // Keeps track of whether we - // were broadcasting or signaling - #endif - -#endif -}; - -US_END_NAMESPACE - -#ifdef US_ENABLE_THREADING_SUPPORT - -US_BEGIN_NAMESPACE - -template -class MultiThreaded -{ - mutable MutexPolicy m_Mtx; - WaitCondition m_Cond; - - #if !defined(US_ATOMIC_OPTIMIZATION) - mutable MutexPolicy m_AtomicMtx; - #endif - -public: - - MultiThreaded() : m_Mtx(), m_Cond() {} - MultiThreaded(const MultiThreaded&) : m_Mtx(), m_Cond() {} - virtual ~MultiThreaded() {} - - class Lock; - friend class Lock; - - class Lock - { - public: - - // Lock object - explicit Lock(const MultiThreaded& host) : m_Host(host) - { - m_Host.m_Mtx.Lock(); - } - - // Lock object - explicit Lock(const MultiThreaded* host) : m_Host(*host) - { - m_Host.m_Mtx.Lock(); - } - - // Unlock object - ~Lock() - { - m_Host.m_Mtx.Unlock(); - } - - private: - - // private by design - Lock(); - Lock(const Lock&); - Lock& operator=(const Lock&); - const MultiThreaded& m_Host; - - }; - - typedef volatile Host VolatileType; - typedef US_THREADS_LONG IntType; - - bool Wait(unsigned long timeoutMillis = 0) - { - return m_Cond.Wait(m_Mtx, timeoutMillis); - } - - void Notify() - { - m_Cond.Notify(); - } - - void NotifyAll() - { - m_Cond.NotifyAll(); - } - - IntType AtomicIncrement(volatile IntType& lval) const - { - US_ATOMIC_INCREMENT(&lval); - return n; - } - - IntType AtomicDecrement(volatile IntType& lval) const - { - US_ATOMIC_DECREMENT(&lval); - return n; - } - - void AtomicAssign(volatile IntType& lval, const IntType val) const - { - US_ATOMIC_ASSIGN(&lval, val); - } - -}; - -US_END_NAMESPACE - -#endif - - -US_BEGIN_NAMESPACE - -template -class SingleThreaded -{ -public: - - virtual ~SingleThreaded() {} - - // Dummy Lock class - struct Lock - { - Lock() {} - explicit Lock(const SingleThreaded&) {} - explicit Lock(const SingleThreaded*) {} - }; - - typedef Host VolatileType; - typedef int IntType; - - bool Wait(unsigned long = 0) - { return false; } - - void Notify() {} - - void NotifyAll() {} - - static IntType AtomicAdd(volatile IntType& lval, const IntType val) - { return lval += val; } - - static IntType AtomicSubtract(volatile IntType& lval, const IntType val) - { return lval -= val; } - - static IntType AtomicMultiply(volatile IntType& lval, const IntType val) - { return lval *= val; } - - static IntType AtomicDivide(volatile IntType& lval, const IntType val) - { return lval /= val; } - - static IntType AtomicIncrement(volatile IntType& lval) - { return ++lval; } - - static IntType AtomicDecrement(volatile IntType& lval) - { return --lval; } - - static void AtomicAssign(volatile IntType & lval, const IntType val) - { lval = val; } - - static void AtomicAssign(IntType & lval, volatile IntType & val) - { lval = val; } - -}; - -US_END_NAMESPACE - -#endif // USTHREADINGMODEL_H diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.c b/Core/Code/CppMicroServices/src/util/usUncompressResourceData.c deleted file mode 100644 index 310491ed82..0000000000 --- a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.c +++ /dev/null @@ -1,59 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include "tinfl.c" - -#include - -static char us_uncompress_error_msg[256]; - -const char* us_uncompress_resource_error() -{ - return us_uncompress_error_msg; -} - -void us_uncompress_resource_data(const unsigned char* data, size_t size, - unsigned char* uncompressedData, size_t uncompressedSize) -{ - size_t bytesWritten = 0; - - memset(us_uncompress_error_msg, 0, sizeof(us_uncompress_error_msg)); - - if (data == NULL) - { - return; - } - - if (uncompressedData == NULL) - { - sprintf(us_uncompress_error_msg, "us_uncompress_resource_data: Buffer for uncomcpressing data is NULL"); - return; - } - - bytesWritten = tinfl_decompress_mem_to_mem(uncompressedData, uncompressedSize, - data, size, - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - if (bytesWritten != uncompressedSize) - { - sprintf(us_uncompress_error_msg, "us_uncompress_resource_data: tinfl_decompress_mem_to_mem failed"); - } -} diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.cpp b/Core/Code/CppMicroServices/src/util/usUncompressResourceData.cpp deleted file mode 100644 index dbc383145d..0000000000 --- a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usUncompressResourceData.h" - -#ifdef US_ENABLE_RESOURCE_COMPRESSION -#include "usUtils_p.h" - -extern "C" { -const char* us_uncompress_resource_error(); -void us_uncompress_resource_data(const unsigned char*, size_t, unsigned char*, size_t); -} - -US_BEGIN_NAMESPACE - -unsigned char* UncompressResourceData(const unsigned char* data, std::size_t size, - std::size_t* uncompressedSize) -{ - if (size <= 4) - { - if (size < 4 || (data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 0)) - { - US_WARN << "UncompressResourceData: Input data is corrupted"; - return NULL; - } - } - std::size_t expectedSize = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; - try - { - unsigned char* uncompressedData = new unsigned char[expectedSize]; - us_uncompress_resource_data(data+4, size-4, uncompressedData, expectedSize); - if (us_uncompress_resource_error()[0] != 0) - { - US_WARN << us_uncompress_resource_error(); - delete[] uncompressedData; - return NULL; - } - - if (uncompressedSize != NULL) - { - *uncompressedSize = expectedSize; - } - - return uncompressedData; - } - catch (const std::bad_alloc&) - { - US_WARN << "UncompressResourceData: Could not allocate enough memory for uncompressing resource data"; - return NULL; - } - - return NULL; -} - -US_END_NAMESPACE - -#else - -US_BEGIN_NAMESPACE - -unsigned char* UncompressResourceData(const unsigned char*, std::size_t, std::size_t*) -{ - return 0; -} - -US_END_NAMESPACE - -#endif // US_ENABLE_RESOURCE_COMPRESSION diff --git a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h b/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h deleted file mode 100644 index a3e82f3679..0000000000 --- a/Core/Code/CppMicroServices/src/util/usUncompressResourceData.h +++ /dev/null @@ -1,33 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USUNCOMPRESSRESOURCEDATA_H -#define USUNCOMPRESSRESOURCEDATA_H - -#include "usConfig.h" - -US_BEGIN_NAMESPACE - -US_EXPORT unsigned char* UncompressResourceData(const unsigned char* data, std::size_t size, std::size_t* uncompressedSize); - -US_END_NAMESPACE - -#endif // USUNCOMPRESSRESOURCEDATA_H diff --git a/Core/Code/CppMicroServices/src/util/usUtils.cpp b/Core/Code/CppMicroServices/src/util/usUtils.cpp deleted file mode 100644 index 5cfb254075..0000000000 --- a/Core/Code/CppMicroServices/src/util/usUtils.cpp +++ /dev/null @@ -1,270 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usUtils_p.h" - -#include "usModuleInfo.h" -#include "usModuleSettings.h" - -#include - -#ifdef US_PLATFORM_POSIX - #include - #include - #include - #include -#else - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #include - #include - #include "dirent_win32_p.h" -#endif - -//------------------------------------------------------------------- -// Module auto-loading -//------------------------------------------------------------------- - -namespace { - -#if !defined(US_PLATFORM_LINUX) -std::string library_suffix() -{ -#ifdef US_PLATFORM_WINDOWS - return ".dll"; -#elif defined(US_PLATFORM_APPLE) - return ".dylib"; -#else - return ".so"; -#endif -} -#endif - -#ifdef US_PLATFORM_POSIX - -const char DIR_SEP = '/'; - -bool load_impl(const std::string& modulePath) -{ - void* handle = dlopen(modulePath.c_str(), RTLD_NOW | RTLD_LOCAL); - return (handle != NULL); -} - -#elif defined(US_PLATFORM_WINDOWS) - -const char DIR_SEP = '\\'; - -bool load_impl(const std::string& modulePath) -{ - void* handle = LoadLibrary(modulePath.c_str()); - return (handle != NULL); -} - -#else - - #ifdef US_ENABLE_AUTOLOADING_SUPPORT - #error "Missing load_impl implementation for this platform." - #else -bool load_impl(const std::string&) { return false; } - #endif - -#endif - -} - -US_BEGIN_NAMESPACE - -void AutoLoadModulesFromPath(const std::string& absoluteBasePath, const std::string& subDir) -{ - std::string loadPath = absoluteBasePath + DIR_SEP + subDir; - - DIR* dir = opendir(loadPath.c_str()); -#ifdef CMAKE_INTDIR - // Try intermediate output directories - if (dir == NULL) - { - std::size_t indexOfLastSeparator = absoluteBasePath.find_last_of(DIR_SEP); - if (indexOfLastSeparator != -1) - { - if (absoluteBasePath.substr(indexOfLastSeparator+1) == CMAKE_INTDIR) - { - loadPath = absoluteBasePath.substr(0, indexOfLastSeparator+1) + subDir + DIR_SEP + CMAKE_INTDIR; - dir = opendir(loadPath.c_str()); - } - } - } -#endif - - if (dir != NULL) - { - struct dirent *ent = NULL; - while ((ent = readdir(dir)) != NULL) - { - bool loadFile = true; -#ifdef _DIRENT_HAVE_D_TYPE - if (ent->d_type != DT_UNKNOWN && ent->d_type != DT_REG) - { - loadFile = false; - } -#endif - - std::string entryFileName(ent->d_name); - - // On Linux, library file names can have version numbers appended. On other platforms, we - // check the file ending. This could be refined for Linux in the future. -#if !defined(US_PLATFORM_LINUX) - if (entryFileName.rfind(library_suffix()) != (entryFileName.size() - library_suffix().size())) - { - loadFile = false; - } -#endif - if (!loadFile) continue; - - std::string libPath = loadPath; - if (!libPath.empty() && libPath.find_last_of(DIR_SEP) != libPath.size() -1) - { - libPath += DIR_SEP; - } - libPath += entryFileName; - US_INFO << "Auto-loading module " << libPath; - - if (!load_impl(libPath)) - { - US_WARN << "Auto-loading of module " << libPath << " failed: " << GetLastErrorStr(); - } - } - closedir(dir); - } -} - -void AutoLoadModules(const ModuleInfo& moduleInfo) -{ - if (moduleInfo.autoLoadDir.empty()) - { - return; - } - - ModuleSettings::PathList autoLoadPaths = ModuleSettings::GetAutoLoadPaths(); - - std::size_t indexOfLastSeparator = moduleInfo.location.find_last_of(DIR_SEP); - std::string moduleBasePath = moduleInfo.location.substr(0, indexOfLastSeparator); - - for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin(); - i != autoLoadPaths.end(); ++i) - { - if (*i == ModuleSettings::CURRENT_MODULE_PATH()) - { - // Load all modules from a directory located relative to this modules location - // and named after this modules library name. - *i = moduleBasePath; - } - } - - // We could have introduced a duplicate above, so remove it. - std::sort(autoLoadPaths.begin(), autoLoadPaths.end()); - autoLoadPaths.erase(std::unique(autoLoadPaths.begin(), autoLoadPaths.end()), autoLoadPaths.end()); - for (ModuleSettings::PathList::iterator i = autoLoadPaths.begin(); - i != autoLoadPaths.end(); ++i) - { - if (i->empty()) continue; - AutoLoadModulesFromPath(*i, moduleInfo.autoLoadDir); - } -} - -US_END_NAMESPACE - -//------------------------------------------------------------------- -// Error handling -//------------------------------------------------------------------- - -US_BEGIN_NAMESPACE - -std::string GetLastErrorStr() -{ -#ifdef US_PLATFORM_POSIX - return std::string(strerror(errno)); -#else - // Retrieve the system error message for the last-error code - LPVOID lpMsgBuf; - DWORD dw = GetLastError(); - - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - dw, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR) &lpMsgBuf, - 0, NULL ); - - std::string errMsg((LPCTSTR)lpMsgBuf); - - LocalFree(lpMsgBuf); - - return errMsg; -#endif -} - -static MsgHandler handler = 0; - -MsgHandler installMsgHandler(MsgHandler h) -{ - MsgHandler old = handler; - handler = h; - return old; -} - -void message_output(MsgType msgType, const char *buf) -{ - if (handler) - { - (*handler)(msgType, buf); - } - else - { - fprintf(stderr, "%s\n", buf); - fflush(stderr); - } - - if (msgType == ErrorMsg) - { - #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) - // get the current report mode - int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); - _CrtSetReportMode(_CRT_ERROR, reportMode); - int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, CppMicroServices_VERSION_STR, buf); - if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW) - return; // ignore - else if (ret == 1) - _CrtDbgBreak(); - #endif - - #ifdef US_PLATFORM_POSIX - abort(); // trap; generates core dump - #else - exit(1); // goodbye cruel world - #endif - } -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/src/util/usUtils_p.h b/Core/Code/CppMicroServices/src/util/usUtils_p.h deleted file mode 100644 index 32c88713e2..0000000000 --- a/Core/Code/CppMicroServices/src/util/usUtils_p.h +++ /dev/null @@ -1,225 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USUTILS_H -#define USUTILS_H - -#include - -#include -#include -#include - - -//------------------------------------------------------------------- -// Logging -//------------------------------------------------------------------- - -US_BEGIN_NAMESPACE - -US_EXPORT void message_output(MsgType, const char* buf); - -struct LogMsg { - - LogMsg(int t, const char* file, int ln, const char* func) - : type(static_cast(t)), enabled(true), buffer() - { buffer << "In " << func << " at " << file << ":" << ln << " : "; } - - ~LogMsg() { if(enabled) message_output(type, buffer.str().c_str()); } - - template - LogMsg& operator<<(T t) - { - if (enabled) buffer << t; - return *this; - } - - LogMsg& operator()(bool flag) - { - this->enabled = flag; - return *this; - } - -private: - - MsgType type; - bool enabled; - std::stringstream buffer; -}; - -struct NoLogMsg { - - template - NoLogMsg& operator<<(T) - { - return *this; - } - - NoLogMsg& operator()(bool) - { - return *this; - } - -}; - -US_END_NAMESPACE - -#if defined(US_ENABLE_DEBUG_OUTPUT) - #define US_DEBUG US_PREPEND_NAMESPACE(LogMsg)(0, __FILE__, __LINE__, __FUNCTION__) -#else - #define US_DEBUG true ? US_PREPEND_NAMESPACE(NoLogMsg)() : US_PREPEND_NAMESPACE(NoLogMsg)() -#endif - -#if !defined(US_NO_INFO_OUTPUT) - #define US_INFO US_PREPEND_NAMESPACE(LogMsg)(1, __FILE__, __LINE__, __FUNCTION__) -#else - #define US_INFO true ? US_PREPEND_NAMESPACE(NoLogMsg)() : US_PREPEND_NAMESPACE(NoLogMsg)() -#endif - -#if !defined(US_NO_WARNING_OUTPUT) - #define US_WARN US_PREPEND_NAMESPACE(LogMsg)(2, __FILE__, __LINE__, __FUNCTION__) -#else - #define US_WARN true ? US_PREPEND_NAMESPACE(LogMsg)() : US_PREPEND_NAMESPACE(LogMsg)() -#endif - -#define US_ERROR US_PREPEND_NAMESPACE(LogMsg)(3, __FILE__, __LINE__, __FUNCTION__) - -//------------------------------------------------------------------- -// Module auto-loading -//------------------------------------------------------------------- - -US_BEGIN_NAMESPACE - -struct ModuleInfo; - -void AutoLoadModules(const ModuleInfo& moduleInfo); - -US_END_NAMESPACE - -//------------------------------------------------------------------- -// Error handling -//------------------------------------------------------------------- - -US_BEGIN_NAMESPACE - -US_EXPORT std::string GetLastErrorStr(); - -US_END_NAMESPACE - - -//------------------------------------------------------------------- -// Functors -//------------------------------------------------------------------- - -#include -#include - -#if defined(US_USE_CXX11) || defined(__GNUC__) - - #ifdef US_USE_CXX11 - #include - #define US_MODULE_LISTENER_FUNCTOR std::function - #define US_SERVICE_LISTENER_FUNCTOR std::function - #else - #include - #define US_MODULE_LISTENER_FUNCTOR std::tr1::function - #define US_SERVICE_LISTENER_FUNCTOR std::tr1::function - #endif - - US_BEGIN_NAMESPACE - template - US_MODULE_LISTENER_FUNCTOR ModuleListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ModuleEvent))) - { return std::bind1st(std::mem_fun(memFn), x); } - US_END_NAMESPACE - - US_BEGIN_NAMESPACE - struct ModuleListenerCompare : std::binary_function, - std::pair, bool> - { - bool operator()(const std::pair& p1, - const std::pair& p2) const - { - return p1.second == p2.second && - p1.first.target() == p2.first.target(); - } - }; - US_END_NAMESPACE - - US_BEGIN_NAMESPACE - template - US_SERVICE_LISTENER_FUNCTOR ServiceListenerMemberFunctor(X* x, void (X::*memFn)(const US_PREPEND_NAMESPACE(ServiceEvent))) - { return std::bind1st(std::mem_fun(memFn), x); } - US_END_NAMESPACE - - US_BEGIN_NAMESPACE - struct ServiceListenerCompare : std::binary_function - { - bool operator()(const US_SERVICE_LISTENER_FUNCTOR& f1, - const US_SERVICE_LISTENER_FUNCTOR& f2) const - { - return f1.target() == f2.target(); - } - }; - US_END_NAMESPACE - -#else - - #include - - #define US_MODULE_LISTENER_FUNCTOR US_PREPEND_NAMESPACE(Functor) - - US_BEGIN_NAMESPACE - template - US_MODULE_LISTENER_FUNCTOR ModuleListenerMemberFunctor(X* x, MemFn memFn) - { return Functor(x, memFn); } - US_END_NAMESPACE - - US_BEGIN_NAMESPACE - struct ModuleListenerCompare : std::binary_function, - std::pair, bool> - { - bool operator()(const std::pair& p1, - const std::pair& p2) const - { return p1.second == p2.second && p1.first == p2.first; } - }; - US_END_NAMESPACE - - #define US_SERVICE_LISTENER_FUNCTOR US_PREPEND_NAMESPACE(Functor) - - US_BEGIN_NAMESPACE - template - US_SERVICE_LISTENER_FUNCTOR ServiceListenerMemberFunctor(X* x, MemFn memFn) - { return Functor(x, memFn); } - US_END_NAMESPACE - - US_BEGIN_NAMESPACE - struct ServiceListenerCompare : std::binary_function - { - bool operator()(const US_SERVICE_LISTENER_FUNCTOR& f1, - const US_SERVICE_LISTENER_FUNCTOR& f2) const - { return f1 == f2; } - }; - US_END_NAMESPACE - -#endif - -#endif // USUTILS_H diff --git a/Core/Code/CppMicroServices/test/CMakeLists.txt b/Core/Code/CppMicroServices/test/CMakeLists.txt deleted file mode 100644 index c762ed9048..0000000000 --- a/Core/Code/CppMicroServices/test/CMakeLists.txt +++ /dev/null @@ -1,102 +0,0 @@ - -#----------------------------------------------------------------------------- -# Configure files, include dirs, etc. -#----------------------------------------------------------------------------- - -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/usTestingConfig.h.in" "${PROJECT_BINARY_DIR}/include/usTestingConfig.h") - -include_directories(${US_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR}) -if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - include_directories(${US_BASECLASS_INCLUDE_DIRS}) -endif() - -link_directories(${US_LINK_DIRS}) -if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - link_directories(${US_BASECLASS_LIBRARY_DIRS}) -endif() - -#----------------------------------------------------------------------------- -# Create test modules -#----------------------------------------------------------------------------- - -include(usFunctionCreateTestModule) - -set(_us_test_module_libs "" CACHE INTERNAL "" FORCE) -add_subdirectory(modules) - -#----------------------------------------------------------------------------- -# Add unit tests -#----------------------------------------------------------------------------- - -set(_tests - usDebugOutputTest - usLDAPFilterTest - usModuleTest - usModuleResourceTest - usServiceRegistryTest - usServiceTrackerTest - usStaticModuleResourceTest - usStaticModuleTest -) - -if(US_BUILD_SHARED_LIBS) - list(APPEND _tests usServiceListenerTest) - if(US_ENABLE_AUTOLOADING_SUPPORT) - list(APPEND _tests usModuleAutoLoadTest) - endif() -endif() - -set(_additional_srcs - usTestManager.cpp - usTestUtilModuleListener.cpp - usTestUtilSharedLibrary.cpp -) - -set(_test_driver ${PROJECT_NAME}TestDriver) -set(_test_sourcelist_extra_args ) -create_test_sourcelist(_srcs ${_test_driver}.cpp ${_tests} ${_test_sourcelist_extra_args}) - -usFunctionEmbedResources(_srcs EXECUTABLE_NAME ${_test_driver} FILES usTestResource.txt) - -# Generate a custom "module init" file for the test driver executable -set(MODULE_DEPENDS_STR ) -foreach(_dep ${US_LINK_LIBRARIES}) - set(MODULE_DEPENDS_STR "${MODULE_DEPENDS_STR} ${_dep}") -endforeach() - -if(US_BUILD_SHARED_LIBS) - usFunctionGenerateModuleInit(_srcs - NAME ${_test_driver} - DEPENDS "${MODULE_DEPENDS_STR}" - VERSION "0.1.0" - EXECUTABLE - ) -endif() - -add_executable(${_test_driver} ${_srcs} ${_additional_srcs}) -if(NOT US_BUILD_SHARED_LIBS) - target_link_libraries(${_test_driver} ${_us_test_module_libs}) -endif() -target_link_libraries(${_test_driver} ${US_LINK_LIBRARIES}) - -if(NOT US_ENABLE_SERVICE_FACTORY_SUPPORT) - target_link_libraries(${_test_driver} ${US_BASECLASS_LIBRARIES}) -endif() - -# Register tests -foreach(_test ${_tests}) - add_test(NAME ${_test} COMMAND ${_test_driver} ${_test}) -endforeach() -if(US_TEST_LABELS) - set_tests_properties(${_tests} PROPERTIES LABELS "${US_TEST_LABELS}") -endif() - -#----------------------------------------------------------------------------- -# Add dependencies for shared libraries -#----------------------------------------------------------------------------- - -if(US_BUILD_SHARED_LIBS) - foreach(_test_module ${_us_test_module_libs}) - add_dependencies(${_test_driver} ${_test_module}) - endforeach() -endif() diff --git a/Core/Code/CppMicroServices/test/modules/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/CMakeLists.txt deleted file mode 100644 index 6d02314c68..0000000000 --- a/Core/Code/CppMicroServices/test/modules/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -add_subdirectory(libA) -add_subdirectory(libA2) -add_subdirectory(libAL) -add_subdirectory(libAL2) -add_subdirectory(libBWithStatic) -add_subdirectory(libS) -add_subdirectory(libSL1) -add_subdirectory(libSL3) -add_subdirectory(libSL4) - -add_subdirectory(libRWithResources) diff --git a/Core/Code/CppMicroServices/test/modules/libA/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libA/CMakeLists.txt deleted file mode 100644 index c3b4969f7b..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libA/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ - -usFunctionCreateTestModule(TestModuleA usTestModuleA.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp b/Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp deleted file mode 100644 index e2333c2bee..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleA.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usTestModuleAService.h" - -#include -#include -#include - -#include US_BASECLASS_HEADER - -US_BEGIN_NAMESPACE - -struct TestModuleA : public US_BASECLASS_NAME, public TestModuleAService -{ - - TestModuleA(ModuleContext* mc) - { - US_INFO << "Registering TestModuleAService"; - sr = mc->RegisterService(this); - } - - void Unregister() - { - if (sr) - { - sr.Unregister(); - sr = 0; - } - } - -private: - - ServiceRegistration sr; - -}; - -class TestModuleAActivator : public ModuleActivator -{ -public: - - TestModuleAActivator() : s(0) {} - ~TestModuleAActivator() { delete s; } - - void Load(ModuleContext* context) - { - s = new TestModuleA(context); - } - - void Unload(ModuleContext*) - { - } - -private: - - TestModuleA* s; -}; - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleA, US_PREPEND_NAMESPACE(TestModuleAActivator)) - diff --git a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleAService.h b/Core/Code/CppMicroServices/test/modules/libA/usTestModuleAService.h deleted file mode 100644 index 9ff99bb92e..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libA/usTestModuleAService.h +++ /dev/null @@ -1,40 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTESTMODULEASERVICE_H -#define USTESTMODULEASERVICE_H - -#include -#include - -US_BEGIN_NAMESPACE - -struct TestModuleAService -{ - virtual ~TestModuleAService() {} -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleAService), "org.cppmicroservices.TestModuleAService") - -#endif // USTESTMODULEASERVICE_H diff --git a/Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt deleted file mode 100644 index 28340c7d2c..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libA2/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ - -usFunctionCreateTestModule(TestModuleA2 usTestModuleA2.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp b/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp deleted file mode 100644 index 187870044f..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usTestModuleA2Service.h" - -#include -#include - -#include US_BASECLASS_HEADER - -US_BEGIN_NAMESPACE - -struct TestModuleA2 : public US_BASECLASS_NAME, public TestModuleA2Service -{ - - TestModuleA2(ModuleContext* mc) - { - US_INFO << "Registering TestModuleA2Service"; - sr = mc->RegisterService(this); - } - - void Unregister() - { - if (sr) - { - sr.Unregister(); - } - } - -private: - - ServiceRegistration sr; -}; - -class TestModuleA2Activator : public ModuleActivator -{ -public: - - TestModuleA2Activator() : s(0) {} - - ~TestModuleA2Activator() { delete s; } - - void Load(ModuleContext* context) - { - s = new TestModuleA2(context); - } - - void Unload(ModuleContext* /*context*/) - { - s->Unregister(); - } - -private: - - TestModuleA2* s; -}; - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleA2, US_PREPEND_NAMESPACE(TestModuleA2Activator)) - diff --git a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h b/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h deleted file mode 100644 index ce6c51a506..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libA2/usTestModuleA2Service.h +++ /dev/null @@ -1,40 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTESTMODULEA2SERVICE_H -#define USTESTMODULEA2SERVICE_H - -#include -#include - -US_BEGIN_NAMESPACE - -struct TestModuleA2Service -{ - virtual ~TestModuleA2Service() {} -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleA2Service), "org.us.TestModuleA2Service") - -#endif // USTESTMODULEA2SERVICE_H diff --git a/Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt deleted file mode 100644 index 83a38c679b..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ - -usFunctionCreateTestModule(TestModuleAL usTestModuleAL.cpp) - -add_subdirectory(libAL_1) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt deleted file mode 100644 index 11c58a935f..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ - -foreach(_type ARCHIVE LIBRARY RUNTIME) - set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CMAKE_${_type}_OUTPUT_DIRECTORY}/TestModuleAL) -endforeach() - -usFunctionCreateTestModule(TestModuleAL_1 usTestModuleAL_1.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp b/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp deleted file mode 100644 index 1c0ca73f54..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL/libAL_1/usTestModuleAL_1.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -US_BEGIN_NAMESPACE - -struct US_ABI_EXPORT TestModuleAL_1_Dummy -{ -}; - -US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp b/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp deleted file mode 100644 index 9b0abf1b25..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL/usTestModuleAL.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -US_BEGIN_NAMESPACE - -struct TestModuleAL_Dummy -{ -}; - -US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libAL2/CMakeLists.txt deleted file mode 100644 index bea2af0245..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL2/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ - -usFunctionCreateTestModuleWithAutoLoadDir(TestModuleAL2 "autoload_al2" usTestModuleAL2.cpp) - -add_subdirectory(libAL2_1) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt deleted file mode 100644 index 074d20f014..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ - -foreach(_type ARCHIVE LIBRARY RUNTIME) - set(CMAKE_${_type}_OUTPUT_DIRECTORY ${CMAKE_${_type}_OUTPUT_DIRECTORY}/autoload_al2) -endforeach() - -usFunctionCreateTestModule(TestModuleAL2_1 usTestModuleAL2_1.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp b/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp deleted file mode 100644 index 684e38c5d3..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL2/libAL2_1/usTestModuleAL2_1.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -US_BEGIN_NAMESPACE - -struct US_ABI_EXPORT TestModuleAL2_1_Dummy -{ -}; - -US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp b/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp deleted file mode 100644 index 6f81242b11..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libAL2/usTestModuleAL2.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -US_BEGIN_NAMESPACE - -struct TestModuleAL2_Dummy -{ -}; - -US_END_NAMESPACE - diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt deleted file mode 100644 index 30b9cf7be6..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ - -usFunctionCreateTestModuleWithResources(TestModuleB - SOURCES usTestModuleB.cpp - RESOURCES dynamic.txt res.txt) - -set(BUILD_SHARED_LIBS 0) -usFunctionCreateTestModuleWithResources(TestModuleImportedByB - SOURCES usTestModuleImportedByB.cpp - RESOURCES static.txt res.txt - RESOURCES_ROOT resources_static) - -target_link_libraries(TestModuleB TestModuleImportedByB) diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt b/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt deleted file mode 100644 index 380a834a99..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/dynamic.txt +++ /dev/null @@ -1 +0,0 @@ -dynamic diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/res.txt b/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/res.txt deleted file mode 100644 index 21f035c230..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources/res.txt +++ /dev/null @@ -1 +0,0 @@ -dynamic resource diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt b/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt deleted file mode 100644 index 68f9caa9f2..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/res.txt +++ /dev/null @@ -1 +0,0 @@ -static resource diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt b/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt deleted file mode 100644 index 7b4d4ba2e6..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/resources_static/static.txt +++ /dev/null @@ -1 +0,0 @@ -static diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp b/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp deleted file mode 100644 index 1b18b2a4c8..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleB.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usTestModuleBService.h" - -#include -#include -#include -#include - -#include US_BASECLASS_HEADER - -US_BEGIN_NAMESPACE - -struct TestModuleB : public US_BASECLASS_NAME, public TestModuleBService -{ - - TestModuleB(ModuleContext* mc) - { - US_INFO << "Registering TestModuleBService"; - mc->RegisterService(this); - } - -}; - -class TestModuleBActivator : public ModuleActivator -{ -public: - - TestModuleBActivator() : s(0) {} - ~TestModuleBActivator() { delete s; } - - void Load(ModuleContext* context) - { - s = new TestModuleB(context); - } - - void Unload(ModuleContext*) - { - } - -private: - - TestModuleB* s; -}; - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleB, US_PREPEND_NAMESPACE(TestModuleBActivator)) - - -US_IMPORT_MODULE(TestModuleImportedByB) -US_IMPORT_MODULE_RESOURCES(TestModuleImportedByB) - -US_LOAD_IMPORTED_MODULES(TestModuleB, TestModuleImportedByB) diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h b/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h deleted file mode 100644 index ababe97398..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleBService.h +++ /dev/null @@ -1,40 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTESTMODULEBSERVICE_H -#define USTESTMODULEBSERVICE_H - -#include -#include - -US_BEGIN_NAMESPACE - -struct TestModuleBService -{ - virtual ~TestModuleBService() {} -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleBService), "org.cppmicroservices.TestModuleBService") - -#endif // USTESTMODULEASERVICE_H diff --git a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp b/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp deleted file mode 100644 index 34459640f1..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libBWithStatic/usTestModuleImportedByB.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usTestModuleBService.h" - -#include -#include -#include - -#include US_BASECLASS_HEADER - -US_BEGIN_NAMESPACE - -struct TestModuleImportedByB : public US_BASECLASS_NAME, public TestModuleBService -{ - - TestModuleImportedByB(ModuleContext* mc) - { - US_INFO << "Registering TestModuleImportedByB"; - mc->RegisterService(this); - } - -}; - -class TestModuleImportedByBActivator : public ModuleActivator -{ -public: - - TestModuleImportedByBActivator() : s(0) {} - ~TestModuleImportedByBActivator() { delete s; } - - void Load(ModuleContext* context) - { - s = new TestModuleImportedByB(context); - } - - void Unload(ModuleContext*) - { - } - -private: - - TestModuleImportedByB* s; -}; - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleImportedByB, US_PREPEND_NAMESPACE(TestModuleImportedByBActivator)) - diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt deleted file mode 100644 index c39359ab09..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ - -set(resource_files - icons/compressable.bmp - icons/cppmicroservices.png - icons/readme.txt - foo.txt - special_chars.dummy.txt - test.xml -) - -usFunctionCreateTestModuleWithResources(TestModuleR - SOURCES usTestModuleR.cpp - RESOURCES ${resource_files}) - diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/foo.txt b/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/foo.txt deleted file mode 100644 index f004091c6b..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/foo.txt +++ /dev/null @@ -1,3 +0,0 @@ -foo and -bar - diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp b/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp deleted file mode 100644 index 96c6caba90..0000000000 Binary files a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/compressable.bmp and /dev/null differ diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png b/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png deleted file mode 100644 index e115492256..0000000000 Binary files a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/cppmicroservices.png and /dev/null differ diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt b/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt deleted file mode 100644 index 30af5fe09c..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/icons/readme.txt +++ /dev/null @@ -1 +0,0 @@ -icons diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt b/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt deleted file mode 100644 index 47bfa90dd0..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/special_chars.dummy.txt +++ /dev/null @@ -1,2 +0,0 @@ -German Füße (feet) -French garçon de café (waiter) diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml b/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml deleted file mode 100644 index 23208713be..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/resources/test.xml +++ /dev/null @@ -1,4 +0,0 @@ - - -hi - diff --git a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp b/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp deleted file mode 100644 index 602caaf82f..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libRWithResources/usTestModuleR.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include - -US_BEGIN_NAMESPACE - -class TestModuleRActivator : public ModuleActivator -{ -public: - - void Load(ModuleContext*) - { - } - - void Unload(ModuleContext*) - { - } - -}; - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleR, US_PREPEND_NAMESPACE(TestModuleRActivator)) - diff --git a/Core/Code/CppMicroServices/test/modules/libS/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libS/CMakeLists.txt deleted file mode 100644 index 1b97fc79ad..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libS/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ - -usFunctionCreateTestModule(TestModuleS usTestModuleS.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp b/Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp deleted file mode 100644 index 6ced8e1eb3..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleS.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "../../usServiceControlInterface.h" - -#include "usTestModuleSService0.h" -#include "usTestModuleSService1.h" -#include "usTestModuleSService2.h" -#include "usTestModuleSService3.h" - -#include -#include -#include -#include - -#include US_BASECLASS_HEADER - -US_BEGIN_NAMESPACE - -class TestModuleS : public US_BASECLASS_NAME, - public ServiceControlInterface, - public TestModuleSService0, - public TestModuleSService1, - public TestModuleSService2, - public TestModuleSService3 -{ - -public: - - TestModuleS(ModuleContext* mc) - : mc(mc) - { - for(int i = 0; i <= 3; ++i) - { - servregs.push_back(ServiceRegistration()); - } - sreg = mc->RegisterService(this); - } - - virtual const char* GetNameOfClass() const - { - return "TestModuleS"; - } - - void ServiceControl(int offset, const std::string& operation, int ranking) - { - if (0 <= offset && offset <= 3) - { - if (operation == "register") - { - if (!servregs[offset]) - { - std::stringstream servicename; - servicename << SERVICE << offset; - ServiceProperties props; - props.insert(std::make_pair(ServiceConstants::SERVICE_RANKING(), Any(ranking))); - servregs[offset] = mc->RegisterService(servicename.str().c_str(), this, props); - } - } - if (operation == "unregister") - { - if (servregs[offset]) - { - ServiceRegistration sr1 = servregs[offset]; - sr1.Unregister(); - servregs[offset] = 0; - } - } - } - } - - void Unregister() - { - if (sreg) - { - sreg.Unregister(); - } - } - -private: - - static const std::string SERVICE; // = "org.cppmicroservices.TestModuleSService" - - ModuleContext* mc; - std::vector servregs; - ServiceRegistration sreg; -}; - -const std::string TestModuleS::SERVICE = "org.cppmicroservices.TestModuleSService"; - -class TestModuleSActivator : public ModuleActivator -{ - -public: - - TestModuleSActivator() : s(0) {} - ~TestModuleSActivator() { delete s; } - - void Load(ModuleContext* context) - { - s = new TestModuleS(context); - } - - void Unload(ModuleContext* /*context*/) - { - #ifndef US_BUILD_SHARED_LIBS - s->Unregister(); - #endif - } - -private: - - TestModuleS* s; - -}; - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleS, US_PREPEND_NAMESPACE(TestModuleSActivator)) diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService0.h b/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService0.h deleted file mode 100644 index 5208c16775..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService0.h +++ /dev/null @@ -1,39 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTESTMODULESSERVICE0_H -#define USTESTMODULESSERVICE0_H - -#include - -US_BEGIN_NAMESPACE - -struct TestModuleSService0 -{ - virtual ~TestModuleSService0() {} -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleSService0), "org.cppmicroservices.TestModuleSService0") - -#endif // USTESTMODULESSERVICE0_H diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService1.h b/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService1.h deleted file mode 100644 index 2fadbe121c..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService1.h +++ /dev/null @@ -1,39 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTESTMODULESSERVICE1_H -#define USTESTMODULESSERVICE1_H - -#include - -US_BEGIN_NAMESPACE - -struct TestModuleSService1 -{ - virtual ~TestModuleSService1() {} -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleSService1), "org.cppmicroservices.TestModuleSService1") - -#endif // USTESTMODULESSERVICE1_H diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService2.h b/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService2.h deleted file mode 100644 index 901bd463a0..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService2.h +++ /dev/null @@ -1,39 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTESTMODULESSERVICE2_H -#define USTESTMODULESSERVICE2_H - -#include - -US_BEGIN_NAMESPACE - -struct TestModuleSService2 -{ - virtual ~TestModuleSService2() {} -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleSService2), "org.cppmicroservices.TestModuleSService2") - -#endif // USTESTMODULESSERVICE0_H diff --git a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService3.h b/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService3.h deleted file mode 100644 index 57b0230e05..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libS/usTestModuleSService3.h +++ /dev/null @@ -1,39 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USTESTMODULESSERVICE3_H -#define USTESTMODULESSERVICE3_H - -#include - -US_BEGIN_NAMESPACE - -struct TestModuleSService3 -{ - virtual ~TestModuleSService3() {} -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(TestModuleSService3), "org.cppmicroservices.TestModuleSService3") - -#endif // USTESTMODULESSERVICE0_H diff --git a/Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt deleted file mode 100644 index caabb07644..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libSL1/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ - -usFunctionCreateTestModule(TestModuleSL1 usActivatorSL1.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp b/Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp deleted file mode 100644 index 70d429e6b2..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libSL1/usActivatorSL1.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include -#include - -#include -#include - -#include "usFooService.h" - -#include US_BASECLASS_HEADER - -US_BEGIN_NAMESPACE - -class ActivatorSL1 : - public US_BASECLASS_NAME, public ModuleActivator, public ModulePropsInterface, - public ServiceTrackerCustomizer -{ - -public: - - ActivatorSL1() - : tracker(0), context(0) - { - - } - - ~ActivatorSL1() - { - delete tracker; - } - - void Load(ModuleContext* context) - { - this->context = context; - - sr = context->RegisterService("ActivatorSL1", this); - - delete tracker; - tracker = new FooTracker(context, this); - tracker->Open(); - } - - void Unload(ModuleContext* /*context*/) - { - tracker->Close(); - } - - const Properties& GetProperties() const - { - return props; - } - - FooService* AddingService(const ServiceReference& reference) - { - props["serviceAdded"] = true; - - FooService* fooService = context->GetService(reference); - fooService->foo(); - return fooService; - } - - void ModifiedService(const ServiceReference& /*reference*/, FooService* /*service*/) - {} - - void RemovedService(const ServiceReference& /*reference*/, FooService* /*service*/) - { - props["serviceRemoved"] = true; - } - -private: - - ModulePropsInterface::Properties props; - - ServiceRegistration sr; - - typedef ServiceTracker FooTracker; - - FooTracker* tracker; - ModuleContext* context; - -}; // ActivatorSL1 - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleSL1, US_PREPEND_NAMESPACE(ActivatorSL1)) - - diff --git a/Core/Code/CppMicroServices/test/modules/libSL1/usFooService.h b/Core/Code/CppMicroServices/test/modules/libSL1/usFooService.h deleted file mode 100644 index 461cf12af0..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libSL1/usFooService.h +++ /dev/null @@ -1,40 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USFOOSERVICE_H -#define USFOOSERVICE_H - -#include - -US_BEGIN_NAMESPACE - -struct FooService -{ - virtual ~FooService() {} - virtual void foo() = 0; -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(FooService), "org.us.testing.FooService") - -#endif // USFOOSERVICE_H diff --git a/Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt deleted file mode 100644 index 6d11053a64..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libSL3/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../libSL1) - -usFunctionCreateTestModule(TestModuleSL3 usActivatorSL3.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp b/Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp deleted file mode 100644 index 965b5d4b01..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libSL3/usActivatorSL3.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#include -#include -#include -#include -#include - -#include US_BASECLASS_HEADER - -US_BEGIN_NAMESPACE - -class ActivatorSL3 : - public US_BASECLASS_NAME, public ModuleActivator, public ModulePropsInterface, - public ServiceTrackerCustomizer -{ - -public: - - ActivatorSL3() : tracker(0), context(0) {} - - ~ActivatorSL3() - { delete tracker; } - - void Load(ModuleContext* context) - { - this->context = context; - - sr = context->RegisterService("ActivatorSL3", this); - delete tracker; - tracker = new FooTracker(context, this); - tracker->Open(); - } - - void Unload(ModuleContext* /*context*/) - { - tracker->Close(); - } - - const ModulePropsInterface::Properties& GetProperties() const - { - return props; - } - - FooService* AddingService(const ServiceReference& reference) - { - props["serviceAdded"] = true; - US_INFO << "SL3: Adding reference =" << reference; - - FooService* fooService = context->GetService(reference); - fooService->foo(); - return fooService; - } - - void ModifiedService(const ServiceReference& /*reference*/, FooService* /*service*/) - { - - } - - void RemovedService(const ServiceReference& reference, FooService* /*service*/) - { - props["serviceRemoved"] = true; - US_INFO << "SL3: Removing reference =" << reference; - } - -private: - - typedef ServiceTracker FooTracker; - FooTracker* tracker; - ModuleContext* context; - - ServiceRegistration sr; - - ModulePropsInterface::Properties props; - -}; - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleSL3, US_PREPEND_NAMESPACE(ActivatorSL3)) - - diff --git a/Core/Code/CppMicroServices/test/modules/libSL4/CMakeLists.txt b/Core/Code/CppMicroServices/test/modules/libSL4/CMakeLists.txt deleted file mode 100644 index b81486fc62..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libSL4/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../libSL1) - -usFunctionCreateTestModule(TestModuleSL4 usActivatorSL4.cpp) - diff --git a/Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp b/Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp deleted file mode 100644 index a048128d83..0000000000 --- a/Core/Code/CppMicroServices/test/modules/libSL4/usActivatorSL4.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#include -#include -#include -#include - -#include - -#include US_BASECLASS_HEADER - -US_BEGIN_NAMESPACE - -class ActivatorSL4 : - public US_BASECLASS_NAME, public ModuleActivator, public FooService -{ - -public: - - ~ActivatorSL4() - { - - } - - void foo() - { - US_INFO << "TestModuleSL4: Doing foo"; - } - - void Load(ModuleContext* context) - { - sr = context->RegisterService(this); - US_INFO << "TestModuleSL4: Registered " << sr; - } - - void Unload(ModuleContext* /*context*/) - { - } - -private: - - ServiceRegistration sr; -}; - -US_END_NAMESPACE - -US_EXPORT_MODULE_ACTIVATOR(TestModuleSL4, US_PREPEND_NAMESPACE(ActivatorSL4)) diff --git a/Core/Code/CppMicroServices/test/usDebugOutputTest.cpp b/Core/Code/CppMicroServices/test/usDebugOutputTest.cpp deleted file mode 100644 index c3aab61b92..0000000000 --- a/Core/Code/CppMicroServices/test/usDebugOutputTest.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include "usTestingMacros.h" - -US_USE_NAMESPACE - -static int lastMsgType = -1; -static std::string lastMsg; - -void handleMessages(MsgType type, const char* msg) -{ - lastMsgType = type; - lastMsg.assign(msg); -} - -void resetLastMsg() -{ - lastMsgType = -1; - lastMsg.clear(); -} - -int usDebugOutputTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("DebugOutputTest"); - - // Use the default message handler - { - US_DEBUG << "Msg"; - US_DEBUG(false) << "Msg"; - US_INFO << "Msg"; - US_INFO(false) << "Msg"; - US_WARN << "Msg"; - US_WARN(false) << "Msg"; - } - US_TEST_CONDITION(lastMsg.empty(), "Testing default message handler"); - - resetLastMsg(); - - installMsgHandler(handleMessages); - { - US_DEBUG << "Msg"; - } -#if !defined(US_ENABLE_DEBUG_OUTPUT) - US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing suppressed debug message") -#else - US_TEST_CONDITION(lastMsgType == 0 && lastMsg.find("Msg") != std::string::npos, "Testing debug message") -#endif - resetLastMsg(); - - { - US_DEBUG(false) << "No msg"; - } - US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing disabled debug message") - resetLastMsg(); - - { - US_INFO << "Info msg"; - } - US_TEST_CONDITION(lastMsgType == 1 && lastMsg.find("Info msg") != std::string::npos, "Testing informational message") - resetLastMsg(); - - { - US_WARN << "Warn msg"; - } - US_TEST_CONDITION(lastMsgType == 2 && lastMsg.find("Warn msg") != std::string::npos, "Testing warning message") - resetLastMsg(); - - // We cannot test US_ERROR since it will call abort(). - - installMsgHandler(0); - - { - US_INFO << "Info msg"; - } - US_TEST_CONDITION(lastMsgType == -1 && lastMsg.empty(), "Testing message handler reset") - - US_TEST_END() -} - diff --git a/Core/Code/CppMicroServices/test/usLDAPFilterTest.cpp b/Core/Code/CppMicroServices/test/usLDAPFilterTest.cpp deleted file mode 100644 index 7b2f9b2165..0000000000 --- a/Core/Code/CppMicroServices/test/usLDAPFilterTest.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include "usTestingMacros.h" - -#include - -US_USE_NAMESPACE - -int TestParsing() -{ - // WELL FORMED Expr - try - { - US_TEST_OUTPUT(<< "Parsing (cn=Babs Jensen)") - LDAPFilter ldap( "(cn=Babs Jensen)" ); - US_TEST_OUTPUT(<< "Parsing (!(cn=Tim Howes))") - ldap = LDAPFilter( "(!(cn=Tim Howes))" ); - US_TEST_OUTPUT(<< "Parsing " << std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))") - ldap = LDAPFilter( std::string("(&(") + ServiceConstants::OBJECTCLASS() + "=Person)(|(sn=Jensen)(cn=Babs J*)))" ); - US_TEST_OUTPUT(<< "Parsing (o=univ*of*mich*)") - ldap = LDAPFilter( "(o=univ*of*mich*)" ); - } - catch (const std::invalid_argument& e) - { - US_TEST_OUTPUT(<< e.what()); - return EXIT_FAILURE; - } - - - // MALFORMED Expr - try - { - US_TEST_OUTPUT( << "Parsing malformed expr: cn=Babs Jensen)") - LDAPFilter ldap( "cn=Babs Jensen)" ); - return EXIT_FAILURE; - } - catch (const std::invalid_argument&) - { - } - - return EXIT_SUCCESS; -} - - -int TestEvaluate() -{ - // EVALUATE - try - { - LDAPFilter ldap( "(Cn=Babs Jensen)" ); - ServiceProperties props; - bool eval = false; - - // Several values - props["cn"] = std::string("Babs Jensen"); - props["unused"] = std::string("Jansen"); - US_TEST_OUTPUT(<< "Evaluating expr: " << ldap.ToString()) - eval = ldap.Match(props); - if (!eval) - { - return EXIT_FAILURE; - } - - // WILDCARD - ldap = LDAPFilter( "(cn=Babs *)" ); - props.clear(); - props["cn"] = std::string("Babs Jensen"); - US_TEST_OUTPUT(<< "Evaluating wildcard expr: " << ldap.ToString()) - eval = ldap.Match(props); - if ( !eval ) - { - return EXIT_FAILURE; - } - - // NOT FOUND - ldap = LDAPFilter( "(cn=Babs *)" ); - props.clear(); - props["unused"] = std::string("New"); - US_TEST_OUTPUT(<< "Expr not found test: " << ldap.ToString()) - eval = ldap.Match(props); - if ( eval ) - { - return EXIT_FAILURE; - } - - // std::vector with integer values - ldap = LDAPFilter( " ( |(cn=Babs *)(sn=1) )" ); - props.clear(); - std::vector list; - list.push_back(std::string("Babs Jensen")); - list.push_back(std::string("1")); - props["sn"] = list; - US_TEST_OUTPUT(<< "Evaluating vector expr: " << ldap.ToString()) - eval = ldap.Match(props); - if (!eval) - { - return EXIT_FAILURE; - } - - // wrong case - ldap = LDAPFilter( "(cN=Babs *)" ); - props.clear(); - props["cn"] = std::string("Babs Jensen"); - US_TEST_OUTPUT(<< "Evaluating case sensitive expr: " << ldap.ToString()) - eval = ldap.MatchCase(props); - if (eval) - { - return EXIT_FAILURE; - } - } - catch (const std::invalid_argument& e) - { - US_TEST_OUTPUT( << e.what() ) - return EXIT_FAILURE; - } - - return EXIT_SUCCESS; -} - -int usLDAPFilterTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("LDAPFilterTest"); - - US_TEST_CONDITION(TestParsing() == EXIT_SUCCESS, "Parsing LDAP expressions: ") - US_TEST_CONDITION(TestEvaluate() == EXIT_SUCCESS, "Evaluating LDAP expressions: ") - - US_TEST_END() -} - diff --git a/Core/Code/CppMicroServices/test/usModuleAutoLoadTest.cpp b/Core/Code/CppMicroServices/test/usModuleAutoLoadTest.cpp deleted file mode 100644 index 0fb0042ca3..0000000000 --- a/Core/Code/CppMicroServices/test/usModuleAutoLoadTest.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#include -#include -#include -#include -#include - -#include - -#include "usTestUtilSharedLibrary.h" -#include "usTestUtilModuleListener.h" -#include "usTestingMacros.h" - -#include - -US_USE_NAMESPACE - -namespace { - -void testDefaultAutoLoadPath(bool autoLoadEnabled) -{ - ModuleContext* mc = GetModuleContext(); - assert(mc); - TestModuleListener listener(mc); - - try - { - mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); - throw; - } - - SharedLibraryHandle libAL("TestModuleAL"); - - try - { - libAL.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) - } - - Module* moduleAL = ModuleRegistry::GetModule("TestModuleAL Module"); - US_TEST_CONDITION_REQUIRED(moduleAL != NULL, "Test for existing module TestModuleAL") - - US_TEST_CONDITION(moduleAL->GetName() == "TestModuleAL Module", "Test module name") - - // check the listeners for events - std::vector pEvts; - pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL)); - - Module* moduleAL_1 = ModuleRegistry::GetModule("TestModuleAL_1 Module"); - if (autoLoadEnabled) - { - US_TEST_CONDITION_REQUIRED(moduleAL_1 != NULL, "Test for existing auto-loaded module TestModuleAL_1") - US_TEST_CONDITION(moduleAL_1->GetName() == "TestModuleAL_1 Module", "Test module name") - - pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL_1)); - pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL_1)); - } - else - { - US_TEST_CONDITION_REQUIRED(moduleAL_1 == NULL, "Test for non-existing auto-loaded module TestModuleAL_1") - } - - pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL)); - - US_TEST_CONDITION(listener.CheckListenerEvents(pEvts), "Test for unexpected events"); - - mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); - - libAL.Unload(); -} - -void testCustomAutoLoadPath() -{ - ModuleContext* mc = GetModuleContext(); - assert(mc); - TestModuleListener listener(mc); - - try - { - mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); - throw; - } - - SharedLibraryHandle libAL2("TestModuleAL2"); - - try - { - libAL2.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) - } - - Module* moduleAL2 = ModuleRegistry::GetModule("TestModuleAL2 Module"); - US_TEST_CONDITION_REQUIRED(moduleAL2 != NULL, "Test for existing module TestModuleAL2") - - US_TEST_CONDITION(moduleAL2->GetName() == "TestModuleAL2 Module", "Test module name") - - // check the listeners for events - std::vector pEvts; - pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL2)); - - Module* moduleAL2_1 = ModuleRegistry::GetModule("TestModuleAL2_1 Module"); -#ifdef US_ENABLE_AUTOLOADING_SUPPORT - US_TEST_CONDITION_REQUIRED(moduleAL2_1 != NULL, "Test for existing auto-loaded module TestModuleAL2_1") - US_TEST_CONDITION(moduleAL2_1->GetName() == "TestModuleAL2_1 Module", "Test module name") - - pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleAL2_1)); - pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL2_1)); -#else - US_TEST_CONDITION_REQUIRED(moduleAL2_1 == NULL, "Test for non-existing aut-loaded module TestModuleAL2_1") -#endif - - pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleAL2)); - - US_TEST_CONDITION(listener.CheckListenerEvents(pEvts), "Test for unexpected events"); - - mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); -} - -} // end unnamed namespace - - -int usModuleAutoLoadTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("ModuleLoaderTest"); - - ModuleSettings::SetAutoLoadingEnabled(false); - testDefaultAutoLoadPath(false); - ModuleSettings::SetAutoLoadingEnabled(true); - - testDefaultAutoLoadPath(true); - - testCustomAutoLoadPath(); - - US_TEST_END() -} diff --git a/Core/Code/CppMicroServices/test/usModulePropsInterface.h b/Core/Code/CppMicroServices/test/usModulePropsInterface.h deleted file mode 100644 index 27bd6e7568..0000000000 --- a/Core/Code/CppMicroServices/test/usModulePropsInterface.h +++ /dev/null @@ -1,44 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USMODULEPROPSINTERFACE_H -#define USMODULEPROPSINTERFACE_H - -#include -#include - -US_BEGIN_NAMESPACE - -struct ModulePropsInterface -{ - typedef ServiceProperties Properties; - - virtual ~ModulePropsInterface() {} - - virtual const Properties& GetProperties() const = 0; -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(ModulePropsInterface), "org.us.testing.ModulePropsInterface") - -#endif // USMODULEPROPSINTERFACE_H diff --git a/Core/Code/CppMicroServices/test/usModuleResourceTest.cpp b/Core/Code/CppMicroServices/test/usModuleResourceTest.cpp deleted file mode 100644 index 4185701c8a..0000000000 --- a/Core/Code/CppMicroServices/test/usModuleResourceTest.cpp +++ /dev/null @@ -1,534 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#include -#include -#include -#include -#include - -#include - -#include "usTestUtilSharedLibrary.h" -#include "usTestingMacros.h" - -#include - -#include - -US_USE_NAMESPACE - -namespace { - -void checkResourceInfo(const ModuleResource& res, const std::string& path, - const std::string& baseName, - const std::string& completeBaseName, const std::string& suffix, - const std::string& completeSuffix, - int size, bool children = false, bool compressed = false) -{ - US_TEST_CONDITION_REQUIRED(res.IsValid(), "Valid resource") - US_TEST_CONDITION(res.GetBaseName() == baseName, "GetBaseName()") - US_TEST_CONDITION(res.GetChildren().empty() == !children, "No children") - US_TEST_CONDITION(res.GetCompleteBaseName() == completeBaseName, "GetCompleteBaseName()") - US_TEST_CONDITION(res.GetName() == completeBaseName + "." + suffix, "GetName()") - US_TEST_CONDITION(res.GetResourcePath() == path + completeBaseName + "." + suffix, "GetResourcePath()") - US_TEST_CONDITION(res.GetPath() == path, "GetPath()") - US_TEST_CONDITION(res.GetSize() == size, "Data size") - US_TEST_CONDITION(res.GetSuffix() == suffix, "Suffix") - US_TEST_CONDITION(res.GetCompleteSuffix() == completeSuffix, "Complete suffix") - US_TEST_CONDITION(res.IsCompressed() == compressed, "Compression flag") -} - -void testTextResource(Module* module) -{ - ModuleResource res = module->GetResource("foo.txt"); -#ifdef US_PLATFORM_WINDOWS - checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 16, false); - const std::streampos ssize(13); - const std::string fileData = "foo and\nbar\n\n"; -#else - checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 13, false); - const std::streampos ssize(12); - const std::string fileData = "foo and\nbar\n"; -#endif - - ModuleResourceStream rs(res); - - rs.seekg(0, std::ios::end); - US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); - rs.seekg(0, std::ios::beg); - - std::string content; - content.reserve(res.GetSize()); - char buffer[1024]; - while (rs.read(buffer, sizeof(buffer))) - { - content.append(buffer, sizeof(buffer)); - } - content.append(buffer, static_cast(rs.gcount())); - - US_TEST_CONDITION(rs.eof(), "EOF check"); - US_TEST_CONDITION(content == fileData, "Resource content"); - - rs.clear(); - rs.seekg(0); - - US_TEST_CONDITION_REQUIRED(rs.tellg() == std::streampos(0), "Move to start") - US_TEST_CONDITION_REQUIRED(rs.good(), "Start re-reading"); - - std::vector lines; - std::string line; - while (std::getline(rs, line)) - { - lines.push_back(line); - } - US_TEST_CONDITION_REQUIRED(lines.size() > 1, "Number of lines") - US_TEST_CONDITION(lines[0] == "foo and", "Check first line") - US_TEST_CONDITION(lines[1] == "bar", "Check second line") -} - -void testTextResourceAsBinary(Module* module) -{ - ModuleResource res = module->GetResource("foo.txt"); - -#ifdef US_PLATFORM_WINDOWS - checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 16, false); - const std::streampos ssize(16); - const std::string fileData = "foo and\r\nbar\r\n\r\n"; -#else - checkResourceInfo(res, "/", "foo", "foo", "txt", "txt", 13, false); - const std::streampos ssize(13); - const std::string fileData = "foo and\nbar\n\n"; -#endif - - - ModuleResourceStream rs(res, std::ios_base::binary); - - rs.seekg(0, std::ios::end); - US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); - rs.seekg(0, std::ios::beg); - - std::string content; - content.reserve(res.GetSize()); - char buffer[1024]; - while (rs.read(buffer, sizeof(buffer))) - { - content.append(buffer, sizeof(buffer)); - } - content.append(buffer, static_cast(rs.gcount())); - - US_TEST_CONDITION(rs.eof(), "EOF check"); - US_TEST_CONDITION(content == fileData, "Resource content"); -} - -#ifdef US_BUILD_SHARED_LIBS -void testInvalidResource(Module* module) -{ - ModuleResource res = module->GetResource("invalid"); - US_TEST_CONDITION_REQUIRED(res.IsValid() == false, "Check invalid resource") - US_TEST_CONDITION(res.GetName().empty(), "Check empty name") - US_TEST_CONDITION(res.GetPath().empty(), "Check empty path") - US_TEST_CONDITION(res.GetResourcePath().empty(), "Check empty resource path") - US_TEST_CONDITION(res.GetBaseName().empty(), "Check empty base name") - US_TEST_CONDITION(res.GetCompleteBaseName().empty(), "Check empty complete base name") - US_TEST_CONDITION(res.GetSuffix().empty(), "Check empty suffix") - - US_TEST_CONDITION(res.GetChildren().empty(), "Check empty children") - US_TEST_CONDITION(res.GetSize() == 0, "Check zero size") - US_TEST_CONDITION(res.GetData() == NULL, "Check NULL data") - - ModuleResourceStream rs(res); - US_TEST_CONDITION(rs.good() == true, "Check invalid resource stream") - rs.ignore(); - US_TEST_CONDITION(rs.good() == false, "Check invalid resource stream") - US_TEST_CONDITION(rs.eof() == true, "Check invalid resource stream") -} -#endif - -void testSpecialCharacters(Module* module) -{ - ModuleResource res = module->GetResource("special_chars.dummy.txt"); -#ifdef US_PLATFORM_WINDOWS - checkResourceInfo(res, "/", "special_chars", "special_chars.dummy", "txt", "dummy.txt", 56, false); - const std::streampos ssize(54); - const std::string fileData = "German Füße (feet)\nFrench garçon de café (waiter)\n"; -#else - checkResourceInfo(res, "/", "special_chars", "special_chars.dummy", "txt", "dummy.txt", 54, false); - const std::streampos ssize(53); - const std::string fileData = "German Füße (feet)\nFrench garçon de café (waiter)"; -#endif - - ModuleResourceStream rs(res); - - rs.seekg(0, std::ios_base::end); - US_TEST_CONDITION(rs.tellg() == ssize, "Stream content length"); - rs.seekg(0, std::ios_base::beg); - - std::string content; - content.reserve(res.GetSize()); - char buffer[1024]; - while (rs.read(buffer, sizeof(buffer))) - { - content.append(buffer, sizeof(buffer)); - } - content.append(buffer, static_cast(rs.gcount())); - - US_TEST_CONDITION(rs.eof(), "EOF check"); - US_TEST_CONDITION(content == fileData, "Resource content"); -} - -void testBinaryResource(Module* module) -{ - ModuleResource res = module->GetResource("/icons/cppmicroservices.png"); - checkResourceInfo(res, "/icons/", "cppmicroservices", "cppmicroservices", "png", "png", 2424, false); - - ModuleResourceStream rs(res, std::ios_base::binary); - rs.seekg(0, std::ios_base::end); - std::streampos resLength = rs.tellg(); - rs.seekg(0); - - std::ifstream png(CppMicroServices_SOURCE_DIR "/test/modules/libRWithResources/resources/icons/cppmicroservices.png", - std::ifstream::in | std::ifstream::binary); - - US_TEST_CONDITION_REQUIRED(png.is_open(), "Open reference file") - - png.seekg(0, std::ios_base::end); - std::streampos pngLength = png.tellg(); - png.seekg(0); - US_TEST_CONDITION(res.GetSize() == resLength, "Check resource size") - US_TEST_CONDITION_REQUIRED(resLength == pngLength, "Compare sizes") - - char c1 = 0; - char c2 = 0; - bool isEqual = true; - int count = 0; - while (png.get(c1) && rs.get(c2)) - { - ++count; - if (c1 != c2) - { - isEqual = false; - break; - } - } - - US_TEST_CONDITION_REQUIRED(count == pngLength, "Check if everything was read"); - US_TEST_CONDITION_REQUIRED(isEqual, "Equal binary contents"); - US_TEST_CONDITION(png.eof(), "EOF check"); -} - -#ifdef US_ENABLE_RESOURCE_COMPRESSION -void testCompressedResource(Module* module) -{ - ModuleResource res = module->GetResource("/icons/compressable.bmp"); - checkResourceInfo(res, "/icons/", "compressable", "compressable", "bmp", "bmp", 411, false, true); - - ModuleResourceStream rs(res, std::ios_base::binary); - rs.seekg(0, std::ios_base::end); - std::streampos resLength = rs.tellg(); - rs.seekg(0); - - std::ifstream bmp(CppMicroServices_SOURCE_DIR "/test/modules/libRWithResources/resources/icons/compressable.bmp", - std::ifstream::in | std::ifstream::binary); - - US_TEST_CONDITION_REQUIRED(bmp.is_open(), "Open reference file") - - bmp.seekg(0, std::ios_base::end); - std::streampos bmpLength = bmp.tellg(); - bmp.seekg(0); - US_TEST_CONDITION(300122 == resLength, "Check resource size") - US_TEST_CONDITION_REQUIRED(resLength == bmpLength, "Compare sizes") - - char c1 = 0; - char c2 = 0; - bool isEqual = true; - int count = 0; - while (bmp.get(c1) && rs.get(c2)) - { - ++count; - if (c1 != c2) - { - isEqual = false; - break; - } - } - - US_TEST_CONDITION_REQUIRED(count == bmpLength, "Check if everything was read"); - US_TEST_CONDITION_REQUIRED(isEqual, "Equal binary contents"); - US_TEST_CONDITION(bmp.eof(), "EOF check"); -} -#endif - -struct ResourceComparator { - bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const - { - return mr1 < mr2; - } -}; - -#ifdef US_BUILD_SHARED_LIBS -void testResourceTree(Module* module) -{ - ModuleResource res = module->GetResource(""); - US_TEST_CONDITION(res.GetResourcePath() == "/", "Check root file path") - US_TEST_CONDITION(res.IsDir() == true, "Check type") - - std::vector children = res.GetChildren(); - std::sort(children.begin(), children.end()); - US_TEST_CONDITION_REQUIRED(children.size() == 4, "Check child count") - US_TEST_CONDITION(children[0] == "foo.txt", "Check child name") - US_TEST_CONDITION(children[1] == "icons", "Check child name") - US_TEST_CONDITION(children[2] == "special_chars.dummy.txt", "Check child name") - US_TEST_CONDITION(children[3] == "test.xml", "Check child name") - - - ModuleResource readme = module->GetResource("/icons/readme.txt"); - US_TEST_CONDITION(readme.IsFile() && readme.GetChildren().empty(), "Check file resource") - - ModuleResource icons = module->GetResource("icons"); - US_TEST_CONDITION(icons.IsDir() && !icons.IsFile() && !icons.GetChildren().empty(), "Check directory resource") - - children = icons.GetChildren(); - US_TEST_CONDITION_REQUIRED(children.size() == 3, "Check icons child count") - std::sort(children.begin(), children.end()); - US_TEST_CONDITION(children[0] == "compressable.bmp", "Check child name") - US_TEST_CONDITION(children[1] == "cppmicroservices.png", "Check child name") - US_TEST_CONDITION(children[2] == "readme.txt", "Check child name") - - ResourceComparator resourceComparator; - - // find all .txt files - std::vector nodes = module->FindResources("", "*.txt", false); - std::sort(nodes.begin(), nodes.end(), resourceComparator); - US_TEST_CONDITION_REQUIRED(nodes.size() == 2, "Found child count") - US_TEST_CONDITION(nodes[0].GetResourcePath() == "/foo.txt", "Check child name") - US_TEST_CONDITION(nodes[1].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") - - nodes = module->FindResources("", "*.txt", true); - std::sort(nodes.begin(), nodes.end(), resourceComparator); - US_TEST_CONDITION_REQUIRED(nodes.size() == 3, "Found child count") - US_TEST_CONDITION(nodes[0].GetResourcePath() == "/foo.txt", "Check child name") - US_TEST_CONDITION(nodes[1].GetResourcePath() == "/icons/readme.txt", "Check child name") - US_TEST_CONDITION(nodes[2].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") - - // find all resources - nodes = module->FindResources("", "", true); - US_TEST_CONDITION(nodes.size() == 6, "Total resource number") - nodes = module->FindResources("", "**", true); - US_TEST_CONDITION(nodes.size() == 6, "Total resource number") - - - // test pattern matching - nodes.clear(); - nodes = module->FindResources("/icons", "*micro*.png", false); - US_TEST_CONDITION(nodes.size() == 1 && nodes[0].GetResourcePath() == "/icons/cppmicroservices.png", "Check file pattern matches") - - nodes.clear(); - nodes = module->FindResources("", "*.txt", true); - US_TEST_CONDITION(nodes.size() == 3, "Check recursive pattern matches") -} - -#else - -void testResourceTree(Module* module) -{ - ModuleResource res = module->GetResource(""); - US_TEST_CONDITION(res.GetResourcePath() == "/", "Check root file path") - US_TEST_CONDITION(res.IsDir() == true, "Check type") - - std::vector children = res.GetChildren(); - std::sort(children.begin(), children.end()); - US_TEST_CONDITION_REQUIRED(children.size() == 8, "Check child count") - US_TEST_CONDITION(children[0] == "dynamic.txt", "Check dynamic.txt child name") - US_TEST_CONDITION(children[1] == "foo.txt", "Check foo.txt child name") - US_TEST_CONDITION(children[2] == "icons", "Check icons child name") - US_TEST_CONDITION(children[3] == "res.txt", "Check res.txt child name") - US_TEST_CONDITION(children[4] == "res.txt", "Check res.txt child name") - US_TEST_CONDITION(children[5] == "special_chars.dummy.txt", "Check special_chars.dummy.txt child name") - US_TEST_CONDITION(children[6] == "static.txt", "Check static.txt child name") - US_TEST_CONDITION(children[7] == "test.xml", "Check test.xml child name") - - - ModuleResource readme = module->GetResource("/icons/readme.txt"); - US_TEST_CONDITION(readme.IsFile() && readme.GetChildren().empty(), "Check file resource") - - ModuleResource icons = module->GetResource("icons"); - US_TEST_CONDITION(icons.IsDir() && !icons.IsFile() && !icons.GetChildren().empty(), "Check directory resource") - - children = icons.GetChildren(); - US_TEST_CONDITION_REQUIRED(children.size() == 3, "Check icons child count") - std::sort(children.begin(), children.end()); - US_TEST_CONDITION(children[0] == "compressable.bmp", "Check child name") - US_TEST_CONDITION(children[1] == "cppmicroservices.png", "Check child name") - US_TEST_CONDITION(children[2] == "readme.txt", "Check child name") - - ResourceComparator resourceComparator; - - // find all .txt files - std::vector nodes = module->FindResources("", "*.txt", false); - std::sort(nodes.begin(), nodes.end(), resourceComparator); - US_TEST_CONDITION_REQUIRED(nodes.size() == 6, "Found child count") - US_TEST_CONDITION(nodes[0].GetResourcePath() == "/dynamic.txt", "Check dynamic.txt child name") - US_TEST_CONDITION(nodes[1].GetResourcePath() == "/foo.txt", "Check child name") - US_TEST_CONDITION(nodes[2].GetResourcePath() == "/res.txt", "Check res.txt child name") - US_TEST_CONDITION(nodes[3].GetResourcePath() == "/res.txt", "Check res.txt child name") - US_TEST_CONDITION(nodes[4].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") - US_TEST_CONDITION(nodes[5].GetResourcePath() == "/static.txt", "Check static.txt child name") - - nodes = module->FindResources("", "*.txt", true); - std::sort(nodes.begin(), nodes.end(), resourceComparator); - US_TEST_CONDITION_REQUIRED(nodes.size() == 7, "Found child count") - US_TEST_CONDITION(nodes[0].GetResourcePath() == "/dynamic.txt", "Check dynamic.txt child name") - US_TEST_CONDITION(nodes[1].GetResourcePath() == "/foo.txt", "Check child name") - US_TEST_CONDITION(nodes[2].GetResourcePath() == "/icons/readme.txt", "Check child name") - US_TEST_CONDITION(nodes[3].GetResourcePath() == "/res.txt", "Check res.txt child name") - US_TEST_CONDITION(nodes[4].GetResourcePath() == "/res.txt", "Check res.txt child name") - US_TEST_CONDITION(nodes[5].GetResourcePath() == "/special_chars.dummy.txt", "Check child name") - US_TEST_CONDITION(nodes[6].GetResourcePath() == "/static.txt", "Check static.txt child name") - - // find all resources - nodes = module->FindResources("", "", true); - US_TEST_CONDITION(nodes.size() == 10, "Total resource number") - nodes = module->FindResources("", "**", true); - US_TEST_CONDITION(nodes.size() == 10, "Total resource number") - - - // test pattern matching - nodes.clear(); - nodes = module->FindResources("/icons", "*micro*.png", false); - US_TEST_CONDITION(nodes.size() == 1 && nodes[0].GetResourcePath() == "/icons/cppmicroservices.png", "Check file pattern matches") - - nodes.clear(); - nodes = module->FindResources("", "*.txt", true); - US_TEST_CONDITION(nodes.size() == 7, "Check recursive pattern matches") -} - -#endif - -void testResourceOperators(Module* module) -{ - ModuleResource invalid = module->GetResource("invalid"); - ModuleResource foo = module->GetResource("foo.txt"); - US_TEST_CONDITION_REQUIRED(foo.IsValid() && foo, "Check valid resource") - ModuleResource foo2(foo); - US_TEST_CONDITION(foo == foo, "Check equality operator") - US_TEST_CONDITION(foo == foo2, "Check copy constructor and equality operator") - US_TEST_CONDITION(foo != invalid, "Check inequality with invalid resource") - - ModuleResource xml = module->GetResource("/test.xml"); - US_TEST_CONDITION_REQUIRED(xml.IsValid() && xml, "Check valid resource") - US_TEST_CONDITION(foo != xml, "Check inequality") - US_TEST_CONDITION(foo < xml, "Check operator<") - - // check operator< by using a set - std::set resources; - resources.insert(foo); - resources.insert(foo); - resources.insert(xml); - US_TEST_CONDITION(resources.size() == 2, "Check operator< with set") - - // check hash function specialization - US_UNORDERED_SET_TYPE resources2; - resources2.insert(foo); - resources2.insert(foo); - resources2.insert(xml); - US_TEST_CONDITION(resources2.size() == 2, "Check operator< with unordered set") - - // check operator<< - std::ostringstream oss; - oss << foo; - US_TEST_CONDITION(oss.str() == foo.GetResourcePath(), "Check operator<<") -} - -#ifdef US_BUILD_SHARED_LIBS -void testResourceFromExecutable(Module* module) -{ - ModuleResource resource = module->GetResource("usTestResource.txt"); - US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid executable resource") - - std::string line; - ModuleResourceStream rs(resource); - std::getline(rs, line); - US_TEST_CONDITION(line == "meant to be compiled into the test driver", "Check executable resource content") -} -#endif - -} // end unnamed namespace - - -int usModuleResourceTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("ModuleResourceTest"); - - ModuleContext* mc = GetModuleContext(); - assert(mc); - -#ifdef US_BUILD_SHARED_LIBS - SharedLibraryHandle libR("TestModuleR"); - - try - { - libR.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) - } - - Module* moduleR = ModuleRegistry::GetModule("TestModuleR Module"); - US_TEST_CONDITION_REQUIRED(moduleR != NULL, "Test for existing module TestModuleR") - - US_TEST_CONDITION(moduleR->GetName() == "TestModuleR Module", "Test module name") - - testInvalidResource(moduleR); - testResourceFromExecutable(mc->GetModule()); -#else - Module* moduleR = mc->GetModule(); - US_TEST_CONDITION_REQUIRED(moduleR != NULL, "Test for existing module 0") - - US_TEST_CONDITION(moduleR->GetName() == "CppMicroServices", "Test module name") -#endif - - testResourceTree(moduleR); - - testResourceOperators(moduleR); - - testTextResource(moduleR); - testTextResourceAsBinary(moduleR); - testSpecialCharacters(moduleR); - - testBinaryResource(moduleR); - -#ifdef US_ENABLE_RESOURCE_COMPRESSION - testCompressedResource(moduleR); -#endif - -#ifdef US_BUILD_SHARED_LIBS - ModuleResource foo = moduleR->GetResource("foo.txt"); - US_TEST_CONDITION(foo.IsValid() == true, "Valid resource") - libR.Unload(); - US_TEST_CONDITION(foo.IsValid() == false, "Invalidated resource") - US_TEST_CONDITION(foo.GetData() == NULL, "NULL data") -#endif - - US_TEST_END() -} diff --git a/Core/Code/CppMicroServices/test/usModuleTest.cpp b/Core/Code/CppMicroServices/test/usModuleTest.cpp deleted file mode 100644 index 7958a1891e..0000000000 --- a/Core/Code/CppMicroServices/test/usModuleTest.cpp +++ /dev/null @@ -1,317 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#include -#include -#include -#include -#include -#include - -#include US_BASECLASS_HEADER - -#include "usTestUtilSharedLibrary.h" -#include "usTestUtilModuleListener.h" -#include "usTestingMacros.h" - -US_USE_NAMESPACE - -namespace { - - -// Verify that the same member function pointers registered as listeners -// with different receivers works. -void frame02a() -{ - ModuleContext* mc = GetModuleContext(); - - TestModuleListener listener1(mc); - TestModuleListener listener2(mc); - - try - { - mc->RemoveModuleListener(&listener1, &TestModuleListener::ModuleChanged); - mc->AddModuleListener(&listener1, &TestModuleListener::ModuleChanged); - mc->RemoveModuleListener(&listener2, &TestModuleListener::ModuleChanged); - mc->AddModuleListener(&listener2, &TestModuleListener::ModuleChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_FAILED_MSG( << "module listener registration failed " << ise.what() - << " : frameSL02a:FAIL" ); - } - - SharedLibraryHandle target("TestModuleA"); - - // Start the test target - try - { - target.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG( << "Failed to load module, got exception: " - << e.what() << " + in frameSL02a:FAIL" ); - } - -#ifdef US_BUILD_SHARED_LIBS - Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); - US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing module TestModuleA") -#endif - - std::vector pEvts; -#ifdef US_BUILD_SHARED_LIBS - pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleA)); - pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleA)); -#endif - - std::vector seEvts; - - US_TEST_CONDITION(listener1.CheckListenerEvents(pEvts, seEvts), "Check first module listener") - US_TEST_CONDITION(listener2.CheckListenerEvents(pEvts, seEvts), "Check second module listener") - - mc->RemoveModuleListener(&listener1, &TestModuleListener::ModuleChanged); - mc->RemoveModuleListener(&listener2, &TestModuleListener::ModuleChanged); - - target.Unload(); -} - -// Verify information from the ModuleInfo struct -void frame005a(ModuleContext* mc) -{ - Module* m = mc->GetModule(); - - // check expected headers - -#ifdef US_BUILD_SHARED_LIBS - US_TEST_CONDITION("CppMicroServicesTestDriver" == m->GetName(), "Test module name"); - US_TEST_CONDITION(ModuleVersion(0,1,0) == m->GetVersion(), "Test module version") -#else - US_TEST_CONDITION("CppMicroServices" == m->GetName(), "Test module name"); - US_TEST_CONDITION(ModuleVersion(0,9,0) == m->GetVersion(), "Test module version") -#endif -} - -// Get context id, location and status of the module -void frame010a(ModuleContext* mc) -{ - Module* m = mc->GetModule(); - - long int contextid = m->GetModuleId(); - US_DEBUG << "CONTEXT ID:" << contextid; - - std::string location = m->GetLocation(); - US_DEBUG << "LOCATION:" << location; - US_TEST_CONDITION(!location.empty(), "Test for non-empty module location") - - US_TEST_CONDITION(m->IsLoaded(), "Test for loaded flag") -} - -//---------------------------------------------------------------------------- -//Test result of GetService(ServiceReference()). Should throw std::invalid_argument -void frame018a(ModuleContext* mc) -{ - try - { - US_BASECLASS_NAME* obj = mc->GetService(ServiceReference()); - US_DEBUG << "Got service object = " << us_service_impl_name(obj) << ", expected std::invalid_argument exception"; - US_TEST_FAILED_MSG(<< "Got service object, excpected std::invalid_argument exception") - } - catch (const std::invalid_argument& ) - {} - catch (...) - { - US_TEST_FAILED_MSG(<< "Got wrong exception, expected std::invalid_argument") - } -} - -// Load libA and check that it exists and that the service it registers exists, -// also check that the expected events occur -void frame020a(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libA) -{ - try - { - libA.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) - } - -#ifdef US_BUILD_SHARED_LIBS - Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); - US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for existing module TestModuleA") - - US_TEST_CONDITION(moduleA->GetName() == "TestModuleA Module", "Test module name") -#endif - - // Check if libA registered the expected service - try - { - ServiceReference sr1 = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); - US_BASECLASS_NAME* o1 = mc->GetService(sr1); - US_TEST_CONDITION(o1 != 0, "Test if service object found"); - - try - { - US_TEST_CONDITION(mc->UngetService(sr1), "Test if Service UnGet returns true"); - } - catch (const std::logic_error le) - { - US_TEST_FAILED_MSG(<< "UnGetService exception: " << le.what()) - } - - // check the listeners for events - std::vector pEvts; -#ifdef US_BUILD_SHARED_LIBS - pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleA)); - pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleA)); -#endif - - std::vector seEvts; -#ifdef US_BUILD_SHARED_LIBS - seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, sr1)); -#endif - - US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); - - } - catch (const ServiceException& /*se*/) - { - US_TEST_FAILED_MSG(<< "test module, expected service not found"); - } - -#ifdef US_BUILD_SHARED_LIBS - US_TEST_CONDITION(moduleA->IsLoaded() == true, "Test if loaded correctly"); -#endif -} - - -// Unload libA and check for correct events -void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libA) -{ -#ifdef US_BUILD_SHARED_LIBS - Module* moduleA = ModuleRegistry::GetModule("TestModuleA Module"); - US_TEST_CONDITION_REQUIRED(moduleA != 0, "Test for non-null module") -#endif - - ServiceReference sr1 - = mc->GetServiceReference("org.cppmicroservices.TestModuleAService"); - US_TEST_CONDITION(sr1, "Test for valid service reference") - - try - { - libA.Unload(); -#ifdef US_BUILD_SHARED_LIBS - US_TEST_CONDITION(moduleA->IsLoaded() == false, "Test for unloaded state") -#endif - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG(<< "UnLoad module exception: " << e.what()) - } - - std::vector pEvts; -#ifdef US_BUILD_SHARED_LIBS - pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADING, moduleA)); - pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADED, moduleA)); -#endif - - std::vector seEvts; -#ifdef US_BUILD_SHARED_LIBS - seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, sr1)); -#endif - - US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); -} - - -struct LocalListener { - void ServiceChanged(const ServiceEvent) {} -}; - -// Add a service listener with a broken LDAP filter to Get an exception -void frame045a(ModuleContext* mc) -{ - LocalListener sListen1; - std::string brokenFilter = "A broken LDAP filter"; - - try - { - mc->AddServiceListener(&sListen1, &LocalListener::ServiceChanged, brokenFilter); - } - catch (const std::invalid_argument& /*ia*/) - { - //assertEquals("InvalidSyntaxException.GetFilter should be same as input string", brokenFilter, ise.GetFilter()); - } - catch (...) - { - US_TEST_FAILED_MSG(<< "test module, wrong exception on broken LDAP filter:"); - } -} - -} // end unnamed namespace - -int usModuleTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("ModuleTest"); - - frame02a(); - - ModuleContext* mc = GetModuleContext(); - TestModuleListener listener(mc); - - try - { - mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); - throw; - } - - try - { - mc->AddServiceListener(&listener, &TestModuleListener::ServiceChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); - throw; - } - - frame005a(mc); - frame010a(mc); - frame018a(mc); - - SharedLibraryHandle libA("TestModuleA"); - frame020a(mc, listener, libA); - frame030b(mc, listener, libA); - - frame045a(mc); - - mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); - mc->RemoveServiceListener(&listener, &TestModuleListener::ServiceChanged); - - US_TEST_END() -} diff --git a/Core/Code/CppMicroServices/test/usServiceControlInterface.h b/Core/Code/CppMicroServices/test/usServiceControlInterface.h deleted file mode 100644 index 129832ff12..0000000000 --- a/Core/Code/CppMicroServices/test/usServiceControlInterface.h +++ /dev/null @@ -1,45 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - - -#ifndef USSERVICECONTROLINTERFACE_H -#define USSERVICECONTROLINTERFACE_H - -#include -#include - -#include - -US_BEGIN_NAMESPACE - -struct ServiceControlInterface -{ - - virtual ~ServiceControlInterface() {} - - virtual void ServiceControl(int service, const std::string& operation, int ranking) = 0; -}; - -US_END_NAMESPACE - -US_DECLARE_SERVICE_INTERFACE(US_PREPEND_NAMESPACE(ServiceControlInterface), "org.us.testing.ServiceControlInterface") - -#endif // USSERVICECONTROLINTERFACE_H diff --git a/Core/Code/CppMicroServices/test/usServiceListenerTest.cpp b/Core/Code/CppMicroServices/test/usServiceListenerTest.cpp deleted file mode 100644 index c49d2ca0d9..0000000000 --- a/Core/Code/CppMicroServices/test/usServiceListenerTest.cpp +++ /dev/null @@ -1,561 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include - -#include -#include -#include - -#include US_BASECLASS_HEADER - -#include - -#include "usTestUtilSharedLibrary.h" - -US_USE_NAMESPACE - -class TestServiceListener -{ - -private: - - friend bool runLoadUnloadTest(const std::string&, int cnt, SharedLibraryHandle&, - const std::vector&); - - const bool checkUsingModules; - std::vector events; - - bool teststatus; - - ModuleContext* mc; - -public: - - TestServiceListener(ModuleContext* mc, bool checkUsingModules = true) - : checkUsingModules(checkUsingModules), events(), teststatus(true), mc(mc) - {} - - bool getTestStatus() const - { - return teststatus; - } - - void clearEvents() - { - events.clear(); - } - - bool checkEvents(const std::vector& eventTypes) - { - if (events.size() != eventTypes.size()) - { - dumpEvents(eventTypes); - return false; - } - - for (std::size_t i=0; i < eventTypes.size(); ++i) - { - if (eventTypes[i] != events[i].GetType()) - { - dumpEvents(eventTypes); - return false; - } - } - return true; - } - - void serviceChanged(const ServiceEvent evt) - { - events.push_back(evt); - US_TEST_OUTPUT( << "ServiceEvent: " << evt ); - if (ServiceEvent::UNREGISTERING == evt.GetType()) - { - ServiceReference sr = evt.GetServiceReference(); - - // Validate that no module is marked as using the service - std::vector usingModules; - sr.GetUsingModules(usingModules); - if (checkUsingModules && !usingModules.empty()) - { - teststatus = false; - printUsingModules(sr, "*** Using modules (unreg) should be empty but is: "); - } - - // Check if the service can be fetched - US_BASECLASS_NAME* service = mc->GetService(sr); - sr.GetUsingModules(usingModules); - // if (UNREGISTERSERVICE_VALID_DURING_UNREGISTERING) { - // In this mode the service shall be obtainable during - // unregistration. - if (service == 0) - { - teststatus = false; - US_TEST_OUTPUT( << "*** Service should be available to ServiceListener " - << "while handling unregistering event." ); - } - US_TEST_OUTPUT( << "Service (unreg): " << us_service_impl_name(service) ); - if (checkUsingModules && usingModules.size() != 1) - { - teststatus = false; - printUsingModules(sr, "*** One using module expected " - "(unreg, after getService), found: "); - } - else - { - printUsingModules(sr, "Using modules (unreg, after getService): "); - } - // } else { - // // In this mode the service shall NOT be obtainable during - // // unregistration. - // if (null!=service) { - // teststatus = false; - // out.print("*** Service should not be available to ServiceListener " - // +"while handling unregistering event."); - // } - // if (checkUsingBundles && null!=usingBundles) { - // teststatus = false; - // printUsingBundles(sr, - // "*** Using bundles (unreg, after getService), " - // +"should be null but is: "); - // } else { - // printUsingBundles(sr, - // "Using bundles (unreg, after getService): null"); - // } - // } - mc->UngetService(sr); - - // Check that the UNREGISTERING service can not be looked up - // using the service registry. - try - { - long sid = any_cast(sr.GetProperty(ServiceConstants::SERVICE_ID())); - std::stringstream ss; - ss << "(" << ServiceConstants::SERVICE_ID() << "=" << sid << ")"; - std::list srs = mc->GetServiceReferences("", ss.str()); - if (srs.empty()) - { - US_TEST_OUTPUT( << "ServiceReference for UNREGISTERING service is not" - " found in the service registry; ok." ); - } - else - { - teststatus = false; - US_TEST_OUTPUT( << "*** ServiceReference for UNREGISTERING service," - << sr << ", not found in the service registry; fail." ); - US_TEST_OUTPUT( << "Found the following Service references:") ; - for(std::list::const_iterator sr = srs.begin(); - sr != srs.end(); ++sr) - { - US_TEST_OUTPUT( << (*sr) ); - } - } - } - catch (const std::exception& e) - { - teststatus = false; - US_TEST_OUTPUT( << "*** Unexpected excpetion when trying to lookup a" - " service while it is in state UNREGISTERING: " - << e.what() ); - } - } - } - - void printUsingModules(const ServiceReference& sr, const std::string& caption) - { - std::vector usingModules; - sr.GetUsingModules(usingModules); - - US_TEST_OUTPUT( << (caption.empty() ? "Using modules: " : caption) ); - for(std::vector::const_iterator module = usingModules.begin(); - module != usingModules.end(); ++module) - { - US_TEST_OUTPUT( << " -" << (*module) ); - } - } - - // Print expected and actual service events. - void dumpEvents(const std::vector& eventTypes) - { - std::size_t max = events.size() > eventTypes.size() ? events.size() : eventTypes.size(); - US_TEST_OUTPUT( << "Expected event type -- Actual event" ); - for (std::size_t i=0; i < max; ++i) - { - ServiceEvent evt = i < events.size() ? events[i] : ServiceEvent(); - if (i < eventTypes.size()) - { - US_TEST_OUTPUT( << " " << eventTypes[i] << "--" << evt ); - } - else - { - US_TEST_OUTPUT( << " " << "- NONE - " << "--" << evt ); - } - } - } - -}; // end of class ServiceListener - -bool runLoadUnloadTest(const std::string& name, int cnt, SharedLibraryHandle& target, - const std::vector& events) -{ - bool teststatus = true; - - ModuleContext* mc = GetModuleContext(); - - for (int i = 0; i < cnt && teststatus; ++i) - { - TestServiceListener sListen(mc); - try - { - mc->AddServiceListener(&sListen, &TestServiceListener::serviceChanged); - //mc->AddServiceListener(MessageDelegate1(&sListen, &ServiceListener::serviceChanged)); - } - catch (const std::logic_error& ise) - { - teststatus = false; - US_TEST_FAILED_MSG( << "service listener registration failed " << ise.what() - << " :" << name << ":FAIL" ); - } - - // Start the test target to get a service published. - try - { - target.Load(); - } - catch (const std::exception& e) - { - teststatus = false; - US_TEST_FAILED_MSG( << "Failed to load module, got exception: " - << e.what() << " + in " << name << ":FAIL" ); - } - - // Stop the test target to get a service unpublished. - try - { - target.Unload(); - } - catch (const std::exception& e) - { - teststatus = false; - US_TEST_FAILED_MSG( << "Failed to unload module, got exception: " - << e.what() << " + in " << name << ":FAIL" ); - } - - if (teststatus && !sListen.checkEvents(events)) - { - teststatus = false; - US_TEST_FAILED_MSG( << "Service listener event notification error :" - << name << ":FAIL" ); - } - - try - { - mc->RemoveServiceListener(&sListen, &TestServiceListener::serviceChanged); - teststatus &= sListen.teststatus; - sListen.clearEvents(); - } - catch (const std::logic_error& ise) - { - teststatus = false; - US_TEST_FAILED_MSG( << "service listener removal failed " << ise.what() - << " :" << name << ":FAIL" ); - } - } - return teststatus; -} - -void frameSL02a() -{ - ModuleContext* mc = GetModuleContext(); - - TestServiceListener listener1(mc); - TestServiceListener listener2(mc); - - try - { - mc->RemoveServiceListener(&listener1, &TestServiceListener::serviceChanged); - mc->AddServiceListener(&listener1, &TestServiceListener::serviceChanged); - mc->RemoveServiceListener(&listener2, &TestServiceListener::serviceChanged); - mc->AddServiceListener(&listener2, &TestServiceListener::serviceChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_FAILED_MSG( << "service listener registration failed " << ise.what() - << " : frameSL02a:FAIL" ); - } - - SharedLibraryHandle target("TestModuleA"); - - // Start the test target to get a service published. - try - { - target.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG( << "Failed to load module, got exception: " - << e.what() << " + in frameSL02a:FAIL" ); - } - - std::vector events; - events.push_back(ServiceEvent::REGISTERED); - - US_TEST_CONDITION(listener1.checkEvents(events), "Check first service listener") - US_TEST_CONDITION(listener2.checkEvents(events), "Check second service listener") - - mc->RemoveServiceListener(&listener1, &TestServiceListener::serviceChanged); - mc->RemoveServiceListener(&listener2, &TestServiceListener::serviceChanged); - - target.Unload(); -} - -void frameSL05a() -{ - std::vector events; - events.push_back(ServiceEvent::REGISTERED); - events.push_back(ServiceEvent::UNREGISTERING); - SharedLibraryHandle libA("TestModuleA"); - bool testStatus = runLoadUnloadTest("FrameSL05a", 1, libA, events); - US_TEST_CONDITION(testStatus, "FrameSL05a") -} - -void frameSL10a() -{ - std::vector events; - events.push_back(ServiceEvent::REGISTERED); - events.push_back(ServiceEvent::UNREGISTERING); - SharedLibraryHandle libA2("TestModuleA2"); - bool testStatus = runLoadUnloadTest("FrameSL10a", 1, libA2, events); - US_TEST_CONDITION(testStatus, "FrameSL10a") -} - -void frameSL25a() -{ - ModuleContext* mc = GetModuleContext(); - - TestServiceListener sListen(mc, false); - try - { - mc->AddServiceListener(&sListen, &TestServiceListener::serviceChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); - throw; - } - - SharedLibraryHandle libSL1("TestModuleSL1"); - SharedLibraryHandle libSL3("TestModuleSL3"); - SharedLibraryHandle libSL4("TestModuleSL4"); - - std::vector expectedServiceEventTypes; - - // Startup - expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // at start of libSL1 - expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // FooService at start of libSL4 - expectedServiceEventTypes.push_back(ServiceEvent::REGISTERED); // at start of libSL3 - - // Stop libSL4 - expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // FooService at first stop of libSL4 - -#ifdef US_BUILD_SHARED_LIBS - // Shutdown - expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // at stop of libSL1 - expectedServiceEventTypes.push_back(ServiceEvent::UNREGISTERING); // at stop of libSL3 -#endif - - // Start libModuleTestSL1 to ensure that the Service interface is available. - try - { - US_TEST_OUTPUT( << "Starting libModuleTestSL1: " << libSL1.GetAbsolutePath() ); - libSL1.Load(); - } - catch (const std::exception& e) - { - US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); - throw; - } - - // Start libModuleTestSL4 that will require the serivce interface and publish - // us::FooService - try - { - US_TEST_OUTPUT( << "Starting libModuleTestSL4: " << libSL4.GetAbsolutePath() ); - libSL4.Load(); - } - catch (const std::exception& e) - { - US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); - throw; - } - - // Start libModuleTestSL3 that will require the serivce interface and get the service - try - { - US_TEST_OUTPUT( << "Starting libModuleTestSL3: " << libSL3.GetAbsolutePath() ); - libSL3.Load(); - } - catch (const std::exception& e) - { - US_TEST_OUTPUT( << "Failed to load module, got exception: " << e.what() ); - throw; - } - - // Check that libSL3 has been notified about the FooService. - US_TEST_OUTPUT( << "Check that FooService is added to service tracker in libSL3" ); - try - { - ServiceReference libSL3SR = mc->GetServiceReference("ActivatorSL3"); - US_BASECLASS_NAME* libSL3Activator = mc->GetService(libSL3SR); - US_TEST_CONDITION_REQUIRED(libSL3Activator, "ActivatorSL3 service != 0"); - - ModulePropsInterface* propsInterface = dynamic_cast(libSL3Activator); - US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); - - ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceAdded"); - US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceAdded"); - Any serviceAddedField3 = i->second; - US_TEST_CONDITION_REQUIRED(!serviceAddedField3.Empty() && any_cast(serviceAddedField3), - "libSL3 notified about presence of FooService"); - mc->UngetService(libSL3SR); - } - catch (const ServiceException& se) - { - US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); - } - - // Check that libSL1 has been notified about the FooService. - US_TEST_OUTPUT( << "Check that FooService is added to service tracker in libSL1" ); - try - { - ServiceReference libSL1SR = mc->GetServiceReference("ActivatorSL1"); - US_BASECLASS_NAME* libSL1Activator = mc->GetService(libSL1SR); - US_TEST_CONDITION_REQUIRED(libSL1Activator, "ActivatorSL1 service != 0"); - - ModulePropsInterface* propsInterface = dynamic_cast(libSL1Activator); - US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); - - ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceAdded"); - US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceAdded"); - Any serviceAddedField1 = i->second; - US_TEST_CONDITION_REQUIRED(!serviceAddedField1.Empty() && any_cast(serviceAddedField1), - "libSL1 notified about presence of FooService"); - mc->UngetService(libSL1SR); - } - catch (const ServiceException& se) - { - US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); - } - - // Stop the service provider: libSL4 - try - { - US_TEST_OUTPUT( << "Stop libSL4: " << libSL4.GetAbsolutePath() ); - libSL4.Unload(); - } - catch (const std::exception& e) - { - US_TEST_OUTPUT( << "Failed to unload module, got exception:" << e.what() ); - throw; - } - - // Check that libSL3 has been notified about the removal of FooService. - US_TEST_OUTPUT( << "Check that FooService is removed from service tracker in libSL3" ); - try - { - ServiceReference libSL3SR = mc->GetServiceReference("ActivatorSL3"); - US_BASECLASS_NAME* libSL3Activator = mc->GetService(libSL3SR); - US_TEST_CONDITION_REQUIRED(libSL3Activator, "ActivatorSL3 service != 0"); - - ModulePropsInterface* propsInterface = dynamic_cast(libSL3Activator); - US_TEST_CONDITION_REQUIRED(propsInterface, "Cast to ModulePropsInterface"); - - ModulePropsInterface::Properties::const_iterator i = propsInterface->GetProperties().find("serviceRemoved"); - US_TEST_CONDITION_REQUIRED(i != propsInterface->GetProperties().end(), "Property serviceRemoved"); - - Any serviceRemovedField3 = i->second; - US_TEST_CONDITION(!serviceRemovedField3.Empty() && any_cast(serviceRemovedField3), - "libSL3 notified about removal of FooService"); - mc->UngetService(libSL3SR); - } - catch (const ServiceException& se) - { - US_TEST_FAILED_MSG( << "Failed to get service reference:" << se ); - } - - // Stop libSL1 - try - { - US_TEST_OUTPUT( << "Stop libSL1:" << libSL1.GetAbsolutePath() ); - libSL1.Unload(); - } - catch (const std::exception& e) - { - US_TEST_OUTPUT( << "Failed to unload module got exception" << e.what() ); - throw; - } - - // Stop pSL3 - try - { - US_TEST_OUTPUT( << "Stop libSL3:" << libSL3.GetAbsolutePath() ); - libSL3.Unload(); - } - catch (const std::exception& e) - { - US_TEST_OUTPUT( << "Failed to unload module got exception" << e.what() ); - throw; - } - - // Check service events seen by this class - US_TEST_OUTPUT( << "Checking ServiceEvents(ServiceListener):" ); - if (!sListen.checkEvents(expectedServiceEventTypes)) - { - US_TEST_FAILED_MSG( << "Service listener event notification error" ); - } - - US_TEST_CONDITION_REQUIRED(sListen.getTestStatus(), "Service listener checks"); - try - { - mc->RemoveServiceListener(&sListen, &TestServiceListener::serviceChanged); - sListen.clearEvents(); - } - catch (const std::logic_error& ise) - { - US_TEST_FAILED_MSG( << "service listener removal failed: " << ise.what() ); - } - -} - -int usServiceListenerTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("ServiceListenerTest"); - - frameSL02a(); - frameSL05a(); - frameSL10a(); - frameSL25a(); - - US_TEST_END() -} - diff --git a/Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp b/Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp deleted file mode 100644 index a2cbdf3507..0000000000 --- a/Core/Code/CppMicroServices/test/usServiceRegistryTest.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include - -#include "usTestingMacros.h" -#include -#include -#include - -#include US_BASECLASS_HEADER - -#include - -US_USE_NAMESPACE - -struct ITestServiceA -{ - virtual ~ITestServiceA() {} -}; - -US_DECLARE_SERVICE_INTERFACE(ITestServiceA, "org.cppmicroservices.testing.ITestServiceA") - -int TestMultipleServiceRegistrations() -{ - struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA - { - }; - - ModuleContext* context = GetModuleContext(); - - TestServiceA s1; - TestServiceA s2; - - ServiceRegistration reg1 = context->RegisterService(&s1); - ServiceRegistration reg2 = context->RegisterService(&s2); - - std::list refs = context->GetServiceReferences(); - US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Testing for two registered ITestServiceA services") - - reg2.Unregister(); - refs = context->GetServiceReferences(); - US_TEST_CONDITION_REQUIRED(refs.size() == 1, "Testing for one registered ITestServiceA services") - - reg1.Unregister(); - refs = context->GetServiceReferences(); - US_TEST_CONDITION_REQUIRED(refs.empty(), "Testing for no ITestServiceA services") - - return EXIT_SUCCESS; -} - -int TestServicePropertiesUpdate() -{ - struct TestServiceA : public US_BASECLASS_NAME, public ITestServiceA - { - }; - - ModuleContext* context = GetModuleContext(); - - TestServiceA s1; - ServiceProperties props; - props["string"] = std::string("A std::string"); - props["bool"] = false; - const char* str = "A const char*"; - props["const char*"] = str; - - ServiceRegistration reg1 = context->RegisterService(&s1, props); - ServiceReference ref1 = context->GetServiceReference(); - - US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().size() == 1, "Testing service count") - US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty("bool")) == false, "Testing bool property") - - // register second service with higher rank - TestServiceA s2; - ServiceProperties props2; - props2[ServiceConstants::SERVICE_RANKING()] = 50; - - ServiceRegistration reg2 = context->RegisterService(&s2, props2); - - // Get the service with the highest rank, this should be s2. - ServiceReference ref2 = context->GetServiceReference(); - TestServiceA* service = dynamic_cast(context->GetService(ref2)); - US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank") - - props["bool"] = true; - // change the service ranking - props[ServiceConstants::SERVICE_RANKING()] = 100; - reg1.SetProperties(props); - - US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().size() == 2, "Testing service count") - US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty("bool")) == true, "Testing bool property") - US_TEST_CONDITION_REQUIRED(any_cast(ref1.GetProperty(ServiceConstants::SERVICE_RANKING())) == 100, "Testing updated ranking") - - // Service with the highest ranking should now be s1 - service = dynamic_cast(context->GetService(ref1)); - US_TEST_CONDITION_REQUIRED(service == &s1, "Testing highest service rank") - - reg1.Unregister(); - US_TEST_CONDITION_REQUIRED(context->GetServiceReferences("").size() == 1, "Testing service count") - - service = dynamic_cast(context->GetService(ref2)); - US_TEST_CONDITION_REQUIRED(service == &s2, "Testing highest service rank") - - reg2.Unregister(); - US_TEST_CONDITION_REQUIRED(context->GetServiceReferences().empty(), "Testing service count") - - return EXIT_SUCCESS; -} - - -int usServiceRegistryTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("ServiceRegistryTest"); - - US_TEST_CONDITION(TestMultipleServiceRegistrations() == EXIT_SUCCESS, "Testing service registrations: ") - US_TEST_CONDITION(TestServicePropertiesUpdate() == EXIT_SUCCESS, "Testing service property update: ") - - US_TEST_END() -} - diff --git a/Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp b/Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp deleted file mode 100644 index cf1ad82485..0000000000 --- a/Core/Code/CppMicroServices/test/usServiceTrackerTest.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include - -#include - -#include -#include -#include -#include -#include - -#include US_BASECLASS_HEADER - -#include "usServiceControlInterface.h" -#include "usTestUtilSharedLibrary.h" - -#include - -US_USE_NAMESPACE - -int usServiceTrackerTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("ServiceTrackerTest") - - ModuleContext* mc = GetModuleContext(); - SharedLibraryHandle libS("TestModuleS"); - - // Start the test target to get a service published. - try - { - libS.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() ); - } - - // 1. Create a ServiceTracker with ServiceTrackerCustomizer == null - - std::string s1("org.cppmicroservices.TestModuleSService"); - ServiceReference servref = mc->GetServiceReference(s1 + "0"); - - US_TEST_CONDITION_REQUIRED(servref != 0, "Test if registered service of id org.cppmicroservices.TestModuleSService0"); - - ServiceControlInterface* serviceController = mc->GetService(servref); - US_TEST_CONDITION_REQUIRED(serviceController != 0, "Test valid service controller"); - - std::auto_ptr > st1(new ServiceTracker<>(mc, servref)); - - // 2. Check the size method with an unopened service tracker - - US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Test if size == 0"); - - // 3. Open the service tracker and see what it finds, - // expect to find one instance of the implementation, - // "org.cppmicroservices.TestModuleSService0" - - st1->Open(); - std::string expName = "TestModuleS"; - std::list sa2; - st1->GetServiceReferences(sa2); - - US_TEST_CONDITION_REQUIRED(sa2.size() == 1, "Checking ServiceTracker size"); - std::string name(us_service_impl_name(mc->GetService(sa2.front()))); - US_TEST_CONDITION_REQUIRED(name == expName, "Checking service implementation name"); - - // 5. Close this service tracker - st1->Close(); - - // 6. Check the size method, now when the servicetracker is closed - US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Checking ServiceTracker size"); - - // 7. Check if we still track anything , we should get null - sa2.clear(); - st1->GetServiceReferences(sa2); - US_TEST_CONDITION_REQUIRED(sa2.empty(), "Checking ServiceTracker size"); - - // 8. A new Servicetracker, this time with a filter for the object - std::string fs = std::string("(") + ServiceConstants::OBJECTCLASS() + "=" + s1 + "*" + ")"; - LDAPFilter f1(fs); - st1.reset(new ServiceTracker<>(mc, f1)); - // add a service - serviceController->ServiceControl(1, "register", 7); - - // 9. Open the service tracker and see what it finds, - // expect to find two instances of references to - // "org.cppmicroservices.TestModuleSService*" - // i.e. they refer to the same piece of code - - st1->Open(); - sa2.clear(); - st1->GetServiceReferences(sa2); - US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Checking service reference count"); - for (std::list::const_iterator i = sa2.begin(); i != sa2.end(); ++i) - { - std::string name(mc->GetService(*i)->GetNameOfClass()); - US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); - } - - // 10. Get libTestModuleS to register one more service and see if it appears - serviceController->ServiceControl(2, "register", 1); - sa2.clear(); - st1->GetServiceReferences(sa2); - US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); - for (std::list::const_iterator i = sa2.begin(); i != sa2.end(); ++i) - { - std::string name(mc->GetService(*i)->GetNameOfClass()); - US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); - } - - // 11. Get libTestModuleS to register one more service and see if it appears - serviceController->ServiceControl(3, "register", 2); - sa2.clear(); - st1->GetServiceReferences(sa2); - US_TEST_CONDITION_REQUIRED(sa2.size() == 4, "Checking service reference count"); - for (std::list::const_iterator i = sa2.begin(); i != sa2.end(); ++i) - { - std::string name = mc->GetService(*i)->GetNameOfClass(); - US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); - } - - // 12. Get libTestModuleS to unregister one service and see if it disappears - serviceController->ServiceControl(3, "unregister", 0); - sa2.clear(); - st1->GetServiceReferences(sa2); - US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); - for (std::list::const_iterator i = sa2.begin(); i != sa2.end(); ++i) - { - std::string name = mc->GetService(*i)->GetNameOfClass(); - US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); - } - - // 13. Get the highest ranking service reference, it should have ranking 7 - ServiceReference h1 = st1->GetServiceReference(); - int rank = any_cast(h1.GetProperty(ServiceConstants::SERVICE_RANKING())); - US_TEST_CONDITION_REQUIRED(rank == 7, "Check service rank"); - - // 14. Get the service of the highest ranked service reference - - US_BASECLASS_NAME* o1 = st1->GetService(h1); - US_TEST_CONDITION_REQUIRED(o1 != 0, "Check for non-null service"); - - // 14a Get the highest ranked service, directly this time - US_BASECLASS_NAME* o3 = st1->GetService(); - US_TEST_CONDITION_REQUIRED(o3 != 0, "Check for non-null service"); - US_TEST_CONDITION_REQUIRED(o1 == o3, "Check for equal service instances"); - - // 15. Now release the tracking of that service and then try to get it - // from the servicetracker, which should yield a null object - serviceController->ServiceControl(1, "unregister", 7); - US_BASECLASS_NAME* o2 = st1->GetService(h1); - US_TEST_CONDITION_REQUIRED(o2 == 0, "Checkt that service is null"); - - // 16. Get all service objects this tracker tracks, it should be 2 - std::list ts1; - st1->GetServices(ts1); - US_TEST_CONDITION_REQUIRED(ts1.size() == 2, "Check service count"); - - // 17. Test the remove method. - // First register another service, then remove it being tracked - serviceController->ServiceControl(1, "register", 7); - h1 = st1->GetServiceReference(); - std::list sa3; - st1->GetServiceReferences(sa3); - US_TEST_CONDITION_REQUIRED(sa3.size() == 3, "Check service reference count"); - for (std::list::const_iterator i = sa3.begin(); i != sa3.end(); ++i) - { - std::string name = mc->GetService(*i)->GetNameOfClass(); - US_TEST_CONDITION_REQUIRED(name == expName, "Checking for expected class name"); - } - - st1->Remove(h1); // remove tracking on one servref - sa2.clear(); - st1->GetServiceReferences(sa2); - US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Check service reference count"); - - // 18. Test the addingService method,add a service reference - - // 19. Test the removedService method, remove a service reference - - - // 20. Test the waitForService method - US_BASECLASS_NAME* o9 = st1->WaitForService(50); - US_TEST_CONDITION_REQUIRED(o9 != 0, "Checking WaitForService method"); - - US_TEST_END() -} diff --git a/Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp b/Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp deleted file mode 100644 index 2405f4572a..0000000000 --- a/Core/Code/CppMicroServices/test/usStaticModuleResourceTest.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#include -#include -#include -#include -#include - -#include - -#include "usTestUtilSharedLibrary.h" -#include "usTestingMacros.h" - -#include - -#include - -US_USE_NAMESPACE - -namespace { - -std::string GetResourceContent(const ModuleResource& resource) -{ - std::string line; - ModuleResourceStream rs(resource); - std::getline(rs, line); - return line; -} - -struct ResourceComparator { - bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const - { - return mr1 < mr2; - } -}; - -void testResourceOperators(Module* module) -{ - std::vector resources = module->FindResources("", "res.txt", false); - US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count") - US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources") -} - -void testResourcesWithStaticImport(Module* module) -{ - ModuleResource resource = module->GetResource("res.txt"); - US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource") - std::string line = GetResourceContent(resource); - US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content") - - resource = module->GetResource("dynamic.txt"); - US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource") - line = GetResourceContent(resource); - US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content") - - resource = module->GetResource("static.txt"); - US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") - line = GetResourceContent(resource); - US_TEST_CONDITION(line == "static", "Check dynamic resource content") - - std::vector resources = module->FindResources("", "*.txt", false); - std::stable_sort(resources.begin(), resources.end(), ResourceComparator()); -#ifdef US_BUILD_SHARED_LIBS - US_TEST_CONDITION(resources.size() == 4, "Check imported resource count") - line = GetResourceContent(resources[0]); - US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") - line = GetResourceContent(resources[1]); - US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") - line = GetResourceContent(resources[2]); - US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") - line = GetResourceContent(resources[3]); - US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") -#else - US_TEST_CONDITION(resources.size() == 6, "Check imported resource count") - line = GetResourceContent(resources[0]); - US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content") - // skip foo.txt - line = GetResourceContent(resources[2]); - US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content") - line = GetResourceContent(resources[3]); - US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content") - // skip special_chars.dummy.txt - line = GetResourceContent(resources[5]); - US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content") -#endif -} - -} // end unnamed namespace - - -int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("StaticModuleResourceTest"); - - assert(GetModuleContext()); - - -#ifdef US_BUILD_SHARED_LIBS - SharedLibraryHandle libB("TestModuleB"); - - try - { - libB.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) - } - - Module* module = ModuleRegistry::GetModule("TestModuleB Module"); - US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB") - - US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name") -#else - Module* module = GetModuleContext()->GetModule(); -#endif - - testResourceOperators(module); - testResourcesWithStaticImport(module); - -#ifdef US_BUILD_SHARED_LIBS - ModuleResource resource = module->GetResource("static.txt"); - US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource") - - libB.Unload(); - - US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource") -#endif - - US_TEST_END() -} diff --git a/Core/Code/CppMicroServices/test/usStaticModuleTest.cpp b/Core/Code/CppMicroServices/test/usStaticModuleTest.cpp deleted file mode 100644 index 4baec3fedb..0000000000 --- a/Core/Code/CppMicroServices/test/usStaticModuleTest.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#include -#include -#include -#include -#include -#include - -#include US_BASECLASS_HEADER - -#include "usTestUtilSharedLibrary.h" -#include "usTestUtilModuleListener.h" -#include "usTestingMacros.h" - -US_USE_NAMESPACE - -namespace { - - -// Load libTestModuleB and check that it exists and that the service it registers exists, -// also check that the expected events occur -void frame020a(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libB) -{ - try - { - libB.Load(); - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG(<< "Load module exception: " << e.what()) - } - -#ifdef US_BUILD_SHARED_LIBS - Module* moduleB = ModuleRegistry::GetModule("TestModuleB Module"); - US_TEST_CONDITION_REQUIRED(moduleB != 0, "Test for existing module TestModuleB") - - US_TEST_CONDITION(moduleB->GetName() == "TestModuleB Module", "Test module name") -#endif - - // Check if libB registered the expected service - try - { - std::list refs = mc->GetServiceReferences("org.cppmicroservices.TestModuleBService"); - US_TEST_CONDITION_REQUIRED(refs.size() == 2, "Test that both the service from the shared and imported library are regsitered"); - - US_BASECLASS_NAME* o1 = mc->GetService(refs.front()); - US_TEST_CONDITION(o1 != 0, "Test if first service object found"); - - US_BASECLASS_NAME* o2 = mc->GetService(refs.back()); - US_TEST_CONDITION(o2 != 0, "Test if second service object found"); - - try - { - US_TEST_CONDITION(mc->UngetService(refs.front()), "Test if Service UnGet for first service returns true"); - US_TEST_CONDITION(mc->UngetService(refs.back()), "Test if Service UnGet for second service returns true"); - } - catch (const std::logic_error le) - { - US_TEST_FAILED_MSG(<< "UnGetService exception: " << le.what()) - } - - // check the listeners for events - std::vector pEvts; -#ifdef US_BUILD_SHARED_LIBS - pEvts.push_back(ModuleEvent(ModuleEvent::LOADING, moduleB)); - pEvts.push_back(ModuleEvent(ModuleEvent::LOADED, moduleB)); -#endif - - std::vector seEvts; -#ifdef US_BUILD_SHARED_LIBS - seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, refs.back())); - seEvts.push_back(ServiceEvent(ServiceEvent::REGISTERED, refs.front())); -#endif - - US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); - - } - catch (const ServiceException& /*se*/) - { - US_TEST_FAILED_MSG(<< "test module, expected service not found"); - } - -#ifdef US_BUILD_SHARED_LIBS - US_TEST_CONDITION(moduleB->IsLoaded() == true, "Test if loaded correctly"); -#endif -} - - -// Unload libB and check for correct events -void frame030b(ModuleContext* mc, TestModuleListener& listener, SharedLibraryHandle& libB) -{ -#ifdef US_BUILD_SHARED_LIBS - Module* moduleB = ModuleRegistry::GetModule("TestModuleB Module"); - US_TEST_CONDITION_REQUIRED(moduleB != 0, "Test for non-null module") -#endif - - std::list refs - = mc->GetServiceReferences("org.cppmicroservices.TestModuleBService"); - US_TEST_CONDITION(refs.front(), "Test for first valid service reference") - US_TEST_CONDITION(refs.back(), "Test for second valid service reference") - - try - { - libB.Unload(); -#ifdef US_BUILD_SHARED_LIBS - US_TEST_CONDITION(moduleB->IsLoaded() == false, "Test for unloaded state") -#endif - } - catch (const std::exception& e) - { - US_TEST_FAILED_MSG(<< "UnLoad module exception: " << e.what()) - } - - std::vector pEvts; -#ifdef US_BUILD_SHARED_LIBS - pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADING, moduleB)); - pEvts.push_back(ModuleEvent(ModuleEvent::UNLOADED, moduleB)); -#endif - - std::vector seEvts; -#ifdef US_BUILD_SHARED_LIBS - seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, refs.back())); - seEvts.push_back(ServiceEvent(ServiceEvent::UNREGISTERING, refs.front())); -#endif - - US_TEST_CONDITION(listener.CheckListenerEvents(pEvts, seEvts), "Test for unexpected events"); -} - -} // end unnamed namespace - -int usStaticModuleTest(int /*argc*/, char* /*argv*/[]) -{ - US_TEST_BEGIN("StaticModuleTest"); - - ModuleContext* mc = GetModuleContext(); - TestModuleListener listener(mc); - - try - { - mc->AddModuleListener(&listener, &TestModuleListener::ModuleChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_OUTPUT( << "module listener registration failed " << ise.what() ); - throw; - } - - try - { - mc->AddServiceListener(&listener, &TestModuleListener::ServiceChanged); - } - catch (const std::logic_error& ise) - { - US_TEST_OUTPUT( << "service listener registration failed " << ise.what() ); - throw; - } - - SharedLibraryHandle libB("TestModuleB"); - frame020a(mc, listener, libB); - frame030b(mc, listener, libB); - - mc->RemoveModuleListener(&listener, &TestModuleListener::ModuleChanged); - mc->RemoveServiceListener(&listener, &TestModuleListener::ServiceChanged); - - US_TEST_END() -} diff --git a/Core/Code/CppMicroServices/test/usTestManager.cpp b/Core/Code/CppMicroServices/test/usTestManager.cpp deleted file mode 100644 index 4d0a2a29a0..0000000000 --- a/Core/Code/CppMicroServices/test/usTestManager.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usTestManager.h" - -#include "usModuleImport.h" - -US_BEGIN_NAMESPACE - -TestManager& TestManager::GetInstance() -{ - static TestManager instance; - return instance; -} - -void TestManager::Initialize() -{ - m_FailedTests = 0; - m_PassedTests = 0; -} - -int TestManager::NumberOfFailedTests() -{ - return m_FailedTests; -} - -int TestManager::NumberOfPassedTests() -{ - return m_PassedTests; -} - -void TestManager::TestFailed() -{ - m_FailedTests++; -} - -void TestManager::TestPassed() -{ - m_PassedTests++; -} - -US_END_NAMESPACE - -#ifndef US_BUILD_SHARED_LIBS -US_IMPORT_MODULE(TestModuleA) -US_IMPORT_MODULE(TestModuleA2) -US_IMPORT_MODULE(TestModuleB) -US_IMPORT_MODULE_RESOURCES(TestModuleB) -US_IMPORT_MODULE(TestModuleR) -US_IMPORT_MODULE_RESOURCES(TestModuleR) -US_IMPORT_MODULE(TestModuleS) -US_IMPORT_MODULE(TestModuleSL1) -US_IMPORT_MODULE(TestModuleSL3) -US_IMPORT_MODULE(TestModuleSL4) - -US_LOAD_IMPORTED_MODULES_INTO_MAIN( - TestModuleA TestModuleA2 TestModuleB TestModuleImportedByB TestModuleR - TestModuleS TestModuleSL1 TestModuleSL3 TestModuleSL4 - ) -#endif diff --git a/Core/Code/CppMicroServices/test/usTestManager.h b/Core/Code/CppMicroServices/test/usTestManager.h deleted file mode 100644 index 080198ef5b..0000000000 --- a/Core/Code/CppMicroServices/test/usTestManager.h +++ /dev/null @@ -1,57 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef US_TESTMANAGER_H_INCLUDED -#define US_TESTMANAGER_H_INCLUDED - -#include - -US_BEGIN_NAMESPACE - -class TestManager -{ -public: - - TestManager() : m_FailedTests(0), m_PassedTests(0) {} - virtual ~TestManager() {} - - static TestManager& GetInstance(); - - /** \brief Must be called at the beginning of a test run. */ - void Initialize(); - - int NumberOfFailedTests(); - int NumberOfPassedTests(); - - /** \brief Tell manager a subtest failed */ - void TestFailed(); - - /** \brief Tell manager a subtest passed */ - void TestPassed(); - -protected: - int m_FailedTests; - int m_PassedTests; -}; - -US_END_NAMESPACE - -#endif // US_TESTMANAGER_H_INCLUDED diff --git a/Core/Code/CppMicroServices/test/usTestResource.txt b/Core/Code/CppMicroServices/test/usTestResource.txt deleted file mode 100644 index b5125a157a..0000000000 --- a/Core/Code/CppMicroServices/test/usTestResource.txt +++ /dev/null @@ -1 +0,0 @@ -meant to be compiled into the test driver diff --git a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp b/Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp deleted file mode 100644 index 2983b0e750..0000000000 --- a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usTestUtilModuleListener.h" - -#include "usUtils_p.h" - -US_BEGIN_NAMESPACE - -TestModuleListener::TestModuleListener(ModuleContext* mc) - : mc(mc), serviceEvents(), moduleEvents() -{} - -void TestModuleListener::ModuleChanged(const ModuleEvent event) -{ - moduleEvents.push_back(event); - US_DEBUG << "ModuleEvent:" << event; -} - -void TestModuleListener::ServiceChanged(const ServiceEvent event) -{ - serviceEvents.push_back(event); - US_DEBUG << "ServiceEvent:" << event; -} - -ModuleEvent TestModuleListener::GetModuleEvent() const -{ - if (moduleEvents.empty()) - { - return ModuleEvent(); - } - return moduleEvents.back(); -} - -ServiceEvent TestModuleListener::GetServiceEvent() const -{ - if (serviceEvents.empty()) - { - return ServiceEvent(); - } - return serviceEvents.back(); -} - -bool TestModuleListener::CheckListenerEvents( - bool pexp, ModuleEvent::Type ptype, - bool sexp, ServiceEvent::Type stype, - Module* moduleX, ServiceReference* servX) -{ - std::vector pEvts; - std::vector seEvts; - - if (pexp) pEvts.push_back(ModuleEvent(ptype, moduleX)); - if (sexp) seEvts.push_back(ServiceEvent(stype, *servX)); - - return CheckListenerEvents(pEvts, seEvts); -} - -bool TestModuleListener::CheckListenerEvents(const std::vector& pEvts) -{ - bool listenState = true; // assume everything will work - - if (pEvts.size() != moduleEvents.size()) - { - listenState = false; - US_DEBUG << "*** Module event mismatch: expected " - << pEvts.size() << " event(s), found " - << moduleEvents.size() << " event(s)."; - - const std::size_t max = pEvts.size() > moduleEvents.size() ? pEvts.size() : moduleEvents.size(); - for (std::size_t i = 0; i < max; ++i) - { - const ModuleEvent& pE = i < pEvts.size() ? pEvts[i] : ModuleEvent(); - const ModuleEvent& pR = i < moduleEvents.size() ? moduleEvents[i] : ModuleEvent(); - US_DEBUG << " " << pE << " - " << pR; - } - } - else - { - for (std::size_t i = 0; i < pEvts.size(); ++i) - { - const ModuleEvent& pE = pEvts[i]; - const ModuleEvent& pR = moduleEvents[i]; - if (pE.GetType() != pR.GetType() - || pE.GetModule() != pR.GetModule()) - { - listenState = false; - US_DEBUG << "*** Wrong module event: " << pR << " expected " << pE; - } - } - } - - moduleEvents.clear(); - return listenState; -} - -bool TestModuleListener::CheckListenerEvents(const std::vector& seEvts) -{ - bool listenState = true; // assume everything will work - - if (seEvts.size() != serviceEvents.size()) - { - listenState = false; - US_DEBUG << "*** Service event mismatch: expected " - << seEvts.size() << " event(s), found " - << serviceEvents.size() << " event(s)."; - - const std::size_t max = seEvts.size() > serviceEvents.size() ? seEvts.size() : serviceEvents.size(); - for (std::size_t i = 0; i < max; ++i) - { - const ServiceEvent& seE = i < seEvts.size() ? seEvts[i] : ServiceEvent(); - const ServiceEvent& seR = i < serviceEvents.size() ? serviceEvents[i] : ServiceEvent(); - US_DEBUG << " " << seE << " - " << seR; - } - } - else - { - for (std::size_t i = 0; i < seEvts.size(); ++i) - { - const ServiceEvent& seE = seEvts[i]; - const ServiceEvent& seR = serviceEvents[i]; - if (seE.GetType() != seR.GetType() - || (!(seE.GetServiceReference() == seR.GetServiceReference()))) - { - listenState = false; - US_DEBUG << "*** Wrong service event: " << seR << " expected " << seE; - } - } - } - - serviceEvents.clear(); - return listenState; -} - -bool TestModuleListener::CheckListenerEvents( - const std::vector& pEvts, - const std::vector& seEvts) -{ - if (!CheckListenerEvents(pEvts)) return false; - return CheckListenerEvents(seEvts); -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.h b/Core/Code/CppMicroServices/test/usTestUtilModuleListener.h deleted file mode 100644 index eadf26a530..0000000000 --- a/Core/Code/CppMicroServices/test/usTestUtilModuleListener.h +++ /dev/null @@ -1,70 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USTESTUTILMODULELISTENER_H -#define USTESTUTILMODULELISTENER_H - -#include "usConfig.h" - -#include "usModuleEvent.h" -#include "usServiceEvent.h" - -US_BEGIN_NAMESPACE - -class ModuleContext; - -class TestModuleListener { - -public: - - TestModuleListener(ModuleContext* mc); - - void ModuleChanged(const ModuleEvent event); - - void ServiceChanged(const ServiceEvent event); - - ModuleEvent GetModuleEvent() const; - - ServiceEvent GetServiceEvent() const; - - bool CheckListenerEvents( - bool pexp, ModuleEvent::Type ptype, - bool sexp, ServiceEvent::Type stype, - Module* moduleX, ServiceReference* servX); - - bool CheckListenerEvents(const std::vector& pEvts); - - bool CheckListenerEvents(const std::vector& seEvts); - - bool CheckListenerEvents(const std::vector& pEvts, - const std::vector& seEvts); - -private: - - ModuleContext* const mc; - - std::vector serviceEvents; - std::vector moduleEvents; -}; - -US_END_NAMESPACE - -#endif // USTESTUTILMODULELISTENER_H diff --git a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp b/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp deleted file mode 100644 index 68be2b5a4c..0000000000 --- a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usTestUtilSharedLibrary.h" - -#include - -#include -#include -#include -#include - - -#if defined(US_PLATFORM_POSIX) - #include -#elif defined(US_PLATFORM_WINDOWS) - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #include - #include -#else - #error Unsupported platform -#endif - - -US_BEGIN_NAMESPACE - -SharedLibraryHandle::SharedLibraryHandle() : m_Handle(0) {} - -SharedLibraryHandle::SharedLibraryHandle(const std::string& name) - : m_Name(name), m_Handle(0) -{} - -SharedLibraryHandle::~SharedLibraryHandle() -{} - -void SharedLibraryHandle::Load() -{ - Load(m_Name); -} - -void SharedLibraryHandle::Load(const std::string& name) -{ -#ifdef US_BUILD_SHARED_LIBS - if (m_Handle) throw std::logic_error(std::string("Library already loaded: ") + name); - std::string libPath = GetAbsolutePath(name); -#ifdef US_PLATFORM_POSIX - m_Handle = dlopen(libPath.c_str(), RTLD_LAZY | RTLD_GLOBAL); - if (!m_Handle) - { - const char* err = dlerror(); - throw std::runtime_error(err ? std::string(err) : libPath); - } -#else - m_Handle = LoadLibrary(libPath.c_str()); - if (!m_Handle) - { - std::string errMsg = "Loading "; - errMsg.append(libPath).append("failed with error: ").append(GetLastErrorStr()); - - throw std::runtime_error(errMsg); - } -#endif - -#endif - - m_Name = name; -} - -void SharedLibraryHandle::Unload() -{ -#ifdef US_BUILD_SHARED_LIBS - if (m_Handle) - { -#ifdef US_PLATFORM_POSIX - dlclose(m_Handle); -#else - FreeLibrary((HMODULE)m_Handle); -#endif - m_Handle = 0; - } -#endif -} - -std::string SharedLibraryHandle::GetAbsolutePath(const std::string& name) -{ - return GetLibraryPath() + "/" + Prefix() + name + Suffix(); -} - -std::string SharedLibraryHandle::GetAbsolutePath() -{ - return GetLibraryPath() + "/" + Prefix() + m_Name + Suffix(); -} - -std::string SharedLibraryHandle::GetLibraryPath() -{ -#ifdef US_PLATFORM_WINDOWS - return std::string(US_RUNTIME_OUTPUT_DIRECTORY); -#else - return std::string(US_LIBRARY_OUTPUT_DIRECTORY); -#endif -} - -std::string SharedLibraryHandle::Suffix() -{ -#ifdef US_PLATFORM_WINDOWS - return ".dll"; -#elif defined(US_PLATFORM_APPLE) - return ".dylib"; -#else - return ".so"; -#endif -} - -std::string SharedLibraryHandle::Prefix() -{ -#if defined(US_PLATFORM_POSIX) - return "lib"; -#else - return ""; -#endif -} - -US_END_NAMESPACE diff --git a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h b/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h deleted file mode 100644 index 80b1faa73b..0000000000 --- a/Core/Code/CppMicroServices/test/usTestUtilSharedLibrary.h +++ /dev/null @@ -1,68 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#ifndef USTESTUTILSHAREDLIBRARY_H -#define USTESTUTILSHAREDLIBRARY_H - -#include "usConfig.h" - -#include - -US_BEGIN_NAMESPACE - -class SharedLibraryHandle -{ -public: - - SharedLibraryHandle(); - - SharedLibraryHandle(const std::string& name); - - virtual ~SharedLibraryHandle(); - - void Load(); - - void Load(const std::string& name); - - void Unload(); - - std::string GetAbsolutePath(const std::string& name); - - std::string GetAbsolutePath(); - - static std::string GetLibraryPath(); - - static std::string Suffix(); - - static std::string Prefix(); - -private: - - SharedLibraryHandle(const SharedLibraryHandle&); - SharedLibraryHandle& operator = (const SharedLibraryHandle&); - - std::string m_Name; - void* m_Handle; -}; - -US_END_NAMESPACE - -#endif // USTESTUTILSHAREDLIBRARY_H diff --git a/Core/Code/CppMicroServices/test/usTestingConfig.h.in b/Core/Code/CppMicroServices/test/usTestingConfig.h.in deleted file mode 100644 index 5750e36123..0000000000 --- a/Core/Code/CppMicroServices/test/usTestingConfig.h.in +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef USTESTINGCONFIG_H -#define USTESTINGCONFIG_H - -#ifdef CMAKE_INTDIR -#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@/" CMAKE_INTDIR -#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@/" CMAKE_INTDIR -#else -#define US_LIBRARY_OUTPUT_DIRECTORY "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@" -#define US_RUNTIME_OUTPUT_DIRECTORY "@CMAKE_RUNTIME_OUTPUT_DIRECTORY@" -#endif - -#endif // USTESTINGCONFIG_H diff --git a/Core/Code/CppMicroServices/test/usTestingMacros.h b/Core/Code/CppMicroServices/test/usTestingMacros.h deleted file mode 100644 index 4dce9000f8..0000000000 --- a/Core/Code/CppMicroServices/test/usTestingMacros.h +++ /dev/null @@ -1,133 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include -#include -#include - -#include "usTestManager.h" - -US_BEGIN_NAMESPACE - /** \brief Indicate a failed test. */ - class TestFailedException : public std::exception { - public: - TestFailedException() {} - }; -US_END_NAMESPACE - -/** - * - * \brief Output some text without generating a terminating newline. - * - * */ -#define US_TEST_OUTPUT_NO_ENDL(x) \ - std::cout x << std::flush; - -/** \brief Output some text. */ -#define US_TEST_OUTPUT(x) \ - US_TEST_OUTPUT_NO_ENDL(x << "\n") - -/** \brief Do some general test preparations. Must be called first in the - main test function. */ -#define US_TEST_BEGIN(testName) \ - std::string usTestName(#testName); \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().Initialize(); \ - try { - -/** \brief Fail and finish test with message MSG */ -#define US_TEST_FAILED_MSG(MSG) \ - US_TEST_OUTPUT(MSG) \ - throw US_PREPEND_NAMESPACE(TestFailedException)(); - -/** \brief Must be called last in the main test function. */ -#define US_TEST_END() \ - } catch (US_PREPEND_NAMESPACE(TestFailedException) ex) { \ - US_TEST_OUTPUT(<< "Further test execution skipped.") \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ - } catch (std::exception ex) { \ - US_TEST_OUTPUT(<< "std::exception occured " << ex.what()) \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ - } \ - if (US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfFailedTests() > 0) { \ - US_TEST_OUTPUT(<< usTestName << ": [DONE FAILED] , subtests passed: " << \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfPassedTests() << " failed: " << \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfFailedTests() ) \ - return EXIT_FAILURE; \ - } else { \ - US_TEST_OUTPUT(<< usTestName << ": " \ - << US_PREPEND_NAMESPACE(TestManager)::GetInstance().NumberOfPassedTests() \ - << " tests [DONE PASSED]") \ - return EXIT_SUCCESS; \ - } - -#define US_TEST_CONDITION(COND,MSG) \ - US_TEST_OUTPUT_NO_ENDL(<< MSG) \ - if ( ! (COND) ) { \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ - US_TEST_OUTPUT(<< " [FAILED]\n" << "In " << __FILE__ \ - << ", line " << __LINE__ \ - << ": " #COND " : [FAILED]") \ - } else { \ - US_TEST_OUTPUT(<< " [PASSED]") \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ - } - -#define US_TEST_CONDITION_REQUIRED(COND,MSG) \ - US_TEST_OUTPUT_NO_ENDL(<< MSG) \ - if ( ! (COND) ) { \ - US_TEST_FAILED_MSG(<< " [FAILED]\n" << " +--> in " << __FILE__ \ - << ", line " << __LINE__ \ - << ", expression is false: \"" #COND "\"") \ - } else { \ - US_TEST_OUTPUT(<< " [PASSED]") \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ - } - -/** - * \brief Begin block which should be checked for exceptions - * - * This macro, together with US_TEST_FOR_EXCEPTION_END, can be used - * to test whether a code block throws an expected exception. The test FAILS if the - * exception is NOT thrown. - */ -#define US_TEST_FOR_EXCEPTION_BEGIN(EXCEPTIONCLASS) \ - try { - -#define US_TEST_FOR_EXCEPTION_END(EXCEPTIONCLASS) \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestFailed(); \ - US_TEST_OUTPUT( << "Expected an '" << #EXCEPTIONCLASS << "' exception. [FAILED]") \ - } \ - catch (EXCEPTIONCLASS) { \ - US_TEST_OUTPUT(<< "Caught an expected '" << #EXCEPTIONCLASS \ - << "' exception. [PASSED]") \ - US_PREPEND_NAMESPACE(TestManager)::GetInstance().TestPassed(); \ - } - - -/** - * \brief Simplified version of US_TEST_FOR_EXCEPTION_BEGIN / END for - * a single statement - */ -#define US_TEST_FOR_EXCEPTION(EXCEPTIONCLASS, STATEMENT) \ - US_TEST_FOR_EXCEPTION_BEGIN(EXCEPTIONCLASS) \ - STATEMENT ; \ - US_TEST_FOR_EXCEPTION_END(EXCEPTIONCLASS) - diff --git a/Core/Code/CppMicroServices/tools/CMakeLists.txt b/Core/Code/CppMicroServices/tools/CMakeLists.txt deleted file mode 100644 index 066a9f5207..0000000000 --- a/Core/Code/CppMicroServices/tools/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ - -include_directories(${US_INCLUDE_DIRS}) - -add_definitions(-DUS_RCC_EXECUTABLE_NAME=\"${US_RCC_EXECUTABLE_NAME}\") - -set(srcs usResourceCompiler.cpp) -if(US_ENABLE_RESOURCE_COMPRESSION) - list(APPEND srcs usResourceCompressor.c) -endif() - -add_executable(${US_RCC_EXECUTABLE_NAME} ${srcs}) -if(WIN32) - target_link_libraries(${US_RCC_EXECUTABLE_NAME} Shlwapi) -endif() diff --git a/Core/Code/CppMicroServices/tools/miniz.c b/Core/Code/CppMicroServices/tools/miniz.c deleted file mode 100644 index 39a1752410..0000000000 --- a/Core/Code/CppMicroServices/tools/miniz.c +++ /dev/null @@ -1,4766 +0,0 @@ -/* miniz.c v1.14 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing - See "unlicense" statement at the end of this file. - Rich Geldreich , last updated May 20, 2012 - Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt - - Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define - MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). - - * Change History - 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). - 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly - "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). - 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. - level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. - 5/28/11 v1.11 - Added statement from unlicense.org - 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large - drop in throughput on some files). - 5/15/11 v1.09 - Initial stable release. - - * Low-level Deflate/Inflate implementation notes: - - Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or - greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses - approximately as well as zlib. - - Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function - coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory - block large enough to hold the entire file. - - The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. - - * zlib-style API notes: - - miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in - zlib replacement in many apps: - The z_stream struct, optional memory allocation callbacks - deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound - inflateInit/inflateInit2/inflate/inflateEnd - compress, compress2, compressBound, uncompress - CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. - Supports raw deflate streams or standard zlib streams with adler-32 checking. - - Limitations: - The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. - I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but - there are no guarantees that miniz.c pulls this off perfectly. - - * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by - Alex Evans. Supports 1-4 bytes/pixel images. - - * ZIP archive API notes: - - The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to - get the job done with minimal fuss. There are simple API's to retrieve file information, read files from - existing archives, create new archives, append new files to existing archives, or clone archive data from - one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), - or you can specify custom file read/write callbacks. - - - Archive reading: Just call this function to read a single file from a disk archive: - - void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, - size_t *pSize, mz_uint zip_flags); - - For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central - directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - - - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: - - int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); - - The locate operation can optionally check file comments too, which (as one example) can be used to identify - multiple versions of the same file in an archive. This function uses a simple linear search through the central - directory, so it's not very fast. - - Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and - retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - - - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data - to disk and builds an exact image of the central directory in memory. The central directory image is written - all at once at the end of the archive file when the archive is finalized. - - The archive writer can optionally align each file's local header and file data to any power of 2 alignment, - which can be useful when the archive will be read from optical media. Also, the writer supports placing - arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still - readable by any ZIP tool. - - - Archive appending: The simple way to add a single file to an archive is to call this function: - - mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, - const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); - - The archive will be created if it doesn't already exist, otherwise it'll be appended to. - Note the appending is done in-place and is not an atomic operation, so if something goes wrong - during the operation it's possible the archive could be left without a central directory (although the local - file headers and file data will be fine, so the archive will be recoverable). - - For more complex archive modification scenarios: - 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to - preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the - compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and - you're done. This is safe but requires a bunch of temporary disk space or heap memory. - - 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), - append new files as needed, then finalize the archive which will write an updated central directory to the - original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a - possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - - - ZIP archive support limitations: - No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. - Requires streams capable of seeking. - - * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the - below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. - - * Important: For best perf. be sure to customize the below macros for your target platform: - #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 - #define MINIZ_LITTLE_ENDIAN 1 - #define MINIZ_HAS_64BIT_REGISTERS 1 -*/ - -#ifndef MINIZ_HEADER_INCLUDED -#define MINIZ_HEADER_INCLUDED - -#include - -#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) -#include -#endif - -// Defines to completely disable specific portions of miniz.c: -// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. - -// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. -//#define MINIZ_NO_STDIO - -// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or -// get/set file times. -//#define MINIZ_NO_TIME - -// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. -//#define MINIZ_NO_ARCHIVE_APIS - -// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. -//#define MINIZ_NO_ARCHIVE_WRITING_APIS - -// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. -//#define MINIZ_NO_ZLIB_APIS - -// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. -//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES - -// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. -// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc -// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user -// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. -//#define MINIZ_NO_MALLOC - -#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) -// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. -#define MINIZ_X86_OR_X64_CPU 1 -#endif - -#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU -// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. -#define MINIZ_LITTLE_ENDIAN 1 -#endif - -#if MINIZ_X86_OR_X64_CPU -// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. -#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 -#endif - -#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) -// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). -#define MINIZ_HAS_64BIT_REGISTERS 1 -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// ------------------- zlib-style API Definitions. - -// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! -typedef unsigned long mz_ulong; - -// Heap allocation callbacks. -// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. -typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); -typedef void (*mz_free_func)(void *opaque, void *address); -typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); - -#define MZ_ADLER32_INIT (1) -// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. -mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); - -#define MZ_CRC32_INIT (0) -// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. -mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); - -// Compression strategies. -enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; - -// Method -#define MZ_DEFLATED 8 - -#ifndef MINIZ_NO_ZLIB_APIS - -#define MZ_VERSION "9.1.14" -#define MZ_VERNUM 0x91E0 -#define MZ_VER_MAJOR 9 -#define MZ_VER_MINOR 1 -#define MZ_VER_REVISION 14 -#define MZ_VER_SUBREVISION 0 - -// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). -enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; - -// Return status codes. MZ_PARAM_ERROR is non-standard. -enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; - -// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. -enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; - -// Window bits -#define MZ_DEFAULT_WINDOW_BITS 15 - -struct mz_internal_state; - -// Compression/decompression stream struct. -typedef struct mz_stream_s -{ - const unsigned char *next_in; // pointer to next byte to read - unsigned int avail_in; // number of bytes available at next_in - mz_ulong total_in; // total number of bytes consumed so far - - unsigned char *next_out; // pointer to next byte to write - unsigned int avail_out; // number of bytes that can be written to next_out - mz_ulong total_out; // total number of bytes produced so far - - char *msg; // error msg (unused) - struct mz_internal_state *state; // internal state, allocated by zalloc/zfree - - mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) - mz_free_func zfree; // optional heap free function (defaults to free) - void *opaque; // heap alloc function user pointer - - int data_type; // data_type (unused) - mz_ulong adler; // adler32 of the source or uncompressed data - mz_ulong reserved; // not used -} mz_stream; - -typedef mz_stream *mz_streamp; - -// Returns the version string of miniz.c. -const char *mz_version(void); - -// mz_deflateInit() initializes a compressor with default options: -// Parameters: -// pStream must point to an initialized mz_stream struct. -// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. -// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. -// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) -// Return values: -// MZ_OK on success. -// MZ_STREAM_ERROR if the stream is bogus. -// MZ_PARAM_ERROR if the input parameters are bogus. -// MZ_MEM_ERROR on out of memory. -int mz_deflateInit(mz_streamp pStream, int level); - -// mz_deflateInit2() is like mz_deflate(), except with more control: -// Additional parameters: -// method must be MZ_DEFLATED -// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) -// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) -int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); - -// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). -int mz_deflateReset(mz_streamp pStream); - -// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. -// Parameters: -// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. -// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. -// Return values: -// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). -// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. -// MZ_STREAM_ERROR if the stream is bogus. -// MZ_PARAM_ERROR if one of the parameters is invalid. -// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) -int mz_deflate(mz_streamp pStream, int flush); - -// mz_deflateEnd() deinitializes a compressor: -// Return values: -// MZ_OK on success. -// MZ_STREAM_ERROR if the stream is bogus. -int mz_deflateEnd(mz_streamp pStream); - -// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. -mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); - -// Single-call compression functions mz_compress() and mz_compress2(): -// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. -int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); -int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); - -// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). -mz_ulong mz_compressBound(mz_ulong source_len); - -// Initializes a decompressor. -int mz_inflateInit(mz_streamp pStream); - -// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: -// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). -int mz_inflateInit2(mz_streamp pStream, int window_bits); - -// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. -// Parameters: -// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. -// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. -// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). -// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. -// Return values: -// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. -// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. -// MZ_STREAM_ERROR if the stream is bogus. -// MZ_DATA_ERROR if the deflate stream is invalid. -// MZ_PARAM_ERROR if one of the parameters is invalid. -// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again -// with more input data, or with more room in the output buffer (except when using single call decompression, described above). -int mz_inflate(mz_streamp pStream, int flush); - -// Deinitializes a decompressor. -int mz_inflateEnd(mz_streamp pStream); - -// Single-call decompression. -// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. -int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); - -// Returns a string description of the specified error code, or NULL if the error code is invalid. -const char *mz_error(int err); - -// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. -// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. -#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES - typedef unsigned char Byte; - typedef unsigned int uInt; - typedef mz_ulong uLong; - typedef Byte Bytef; - typedef uInt uIntf; - typedef char charf; - typedef int intf; - typedef void *voidpf; - typedef uLong uLongf; - typedef void *voidp; - typedef void *const voidpc; - #define Z_NULL 0 - #define Z_NO_FLUSH MZ_NO_FLUSH - #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH - #define Z_SYNC_FLUSH MZ_SYNC_FLUSH - #define Z_FULL_FLUSH MZ_FULL_FLUSH - #define Z_FINISH MZ_FINISH - #define Z_BLOCK MZ_BLOCK - #define Z_OK MZ_OK - #define Z_STREAM_END MZ_STREAM_END - #define Z_NEED_DICT MZ_NEED_DICT - #define Z_ERRNO MZ_ERRNO - #define Z_STREAM_ERROR MZ_STREAM_ERROR - #define Z_DATA_ERROR MZ_DATA_ERROR - #define Z_MEM_ERROR MZ_MEM_ERROR - #define Z_BUF_ERROR MZ_BUF_ERROR - #define Z_VERSION_ERROR MZ_VERSION_ERROR - #define Z_PARAM_ERROR MZ_PARAM_ERROR - #define Z_NO_COMPRESSION MZ_NO_COMPRESSION - #define Z_BEST_SPEED MZ_BEST_SPEED - #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION - #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION - #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY - #define Z_FILTERED MZ_FILTERED - #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY - #define Z_RLE MZ_RLE - #define Z_FIXED MZ_FIXED - #define Z_DEFLATED MZ_DEFLATED - #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS - #define alloc_func mz_alloc_func - #define free_func mz_free_func - #define internal_state mz_internal_state - #define z_stream mz_stream - #define deflateInit mz_deflateInit - #define deflateInit2 mz_deflateInit2 - #define deflateReset mz_deflateReset - #define deflate mz_deflate - #define deflateEnd mz_deflateEnd - #define deflateBound mz_deflateBound - #define compress mz_compress - #define compress2 mz_compress2 - #define compressBound mz_compressBound - #define inflateInit mz_inflateInit - #define inflateInit2 mz_inflateInit2 - #define inflate mz_inflate - #define inflateEnd mz_inflateEnd - #define uncompress mz_uncompress - #define crc32 mz_crc32 - #define adler32 mz_adler32 - #define MAX_WBITS 15 - #define MAX_MEM_LEVEL 9 - #define zError mz_error - #define ZLIB_VERSION MZ_VERSION - #define ZLIB_VERNUM MZ_VERNUM - #define ZLIB_VER_MAJOR MZ_VER_MAJOR - #define ZLIB_VER_MINOR MZ_VER_MINOR - #define ZLIB_VER_REVISION MZ_VER_REVISION - #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION - #define zlibVersion mz_version - #define zlib_version mz_version() -#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES - -#endif // MINIZ_NO_ZLIB_APIS - -// ------------------- Types and macros - -typedef unsigned char mz_uint8; -typedef signed short mz_int16; -typedef unsigned short mz_uint16; -typedef unsigned int mz_uint32; -typedef unsigned int mz_uint; -typedef long long mz_int64; -typedef unsigned long long mz_uint64; -typedef int mz_bool; - -#define MZ_FALSE (0) -#define MZ_TRUE (1) - -// Works around MSVC's spammy "warning C4127: conditional expression is constant" message. -#ifdef _MSC_VER - #define MZ_MACRO_END while (0, 0) -#else - #define MZ_MACRO_END while (0) -#endif - -// ------------------- ZIP archive reading/writing - -#ifndef MINIZ_NO_ARCHIVE_APIS - -enum -{ - MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, - MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, - MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 -}; - -typedef struct -{ - mz_uint32 m_file_index; - mz_uint32 m_central_dir_ofs; - mz_uint16 m_version_made_by; - mz_uint16 m_version_needed; - mz_uint16 m_bit_flag; - mz_uint16 m_method; -#ifndef MINIZ_NO_TIME - time_t m_time; -#endif - mz_uint32 m_crc32; - mz_uint64 m_comp_size; - mz_uint64 m_uncomp_size; - mz_uint16 m_internal_attr; - mz_uint32 m_external_attr; - mz_uint64 m_local_header_ofs; - mz_uint32 m_comment_size; - char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; - char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; -} mz_zip_archive_file_stat; - -typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); -typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); - -struct mz_zip_internal_state_tag; -typedef struct mz_zip_internal_state_tag mz_zip_internal_state; - -typedef enum -{ - MZ_ZIP_MODE_INVALID = 0, - MZ_ZIP_MODE_READING = 1, - MZ_ZIP_MODE_WRITING = 2, - MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 -} mz_zip_mode; - -typedef struct -{ - mz_uint64 m_archive_size; - mz_uint64 m_central_directory_file_ofs; - mz_uint m_total_files; - mz_zip_mode m_zip_mode; - - mz_uint m_file_offset_alignment; - - mz_alloc_func m_pAlloc; - mz_free_func m_pFree; - mz_realloc_func m_pRealloc; - void *m_pAlloc_opaque; - - mz_file_read_func m_pRead; - mz_file_write_func m_pWrite; - void *m_pIO_opaque; - - mz_zip_internal_state *m_pState; - -} mz_zip_archive; - -typedef enum -{ - MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, - MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, - MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, - MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 -} mz_zip_flags; - -// ZIP archive reading - -// Inits a ZIP archive reader. -// These functions read and validate the archive's central directory. -mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); -mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); -#endif - -// Returns the total number of files in the archive. -mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); - -// Returns detailed information about an archive file entry. -mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); - -// Determines if an archive file entry is a directory entry. -mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); -mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); - -// Retrieves the filename of an archive file entry. -// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. -mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); - -// Attempts to locates a file in the archive's central directory. -// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH -// Returns -1 if the file cannot be found. -int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); - -// Extracts a archive file to a memory buffer using no memory allocation. -mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); -mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); - -// Extracts a archive file to a memory buffer. -mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); - -// Extracts a archive file to a dynamically allocated heap buffer. -void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); -void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); - -// Extracts a archive file using a callback function to output the file's data. -mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); - -#ifndef MINIZ_NO_STDIO -// Extracts a archive file to a disk file and sets its last accessed and modified times. -// This function only extracts files, not archive directory records. -mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); -mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); -#endif - -// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. -mz_bool mz_zip_reader_end(mz_zip_archive *pZip); - -// ZIP archive writing - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -// Inits a ZIP archive writer. -mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); -mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); -#endif - -// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. -// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. -// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). -// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. -// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before -// the archive is finalized the file's central directory will be hosed. -mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); - -// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. -// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. -mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); -mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); - -#ifndef MINIZ_NO_STDIO -// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. -mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); -#endif - -// Adds a file to an archive by fully cloning the data from another archive. -// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. -mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); - -// Finalizes the archive by writing the central directory records followed by the end of central directory record. -// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). -// An archive must be manually finalized by calling this function for it to be valid. -mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); -mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); - -// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. -// Note for the archive to be valid, it must have been finalized before ending. -mz_bool mz_zip_writer_end(mz_zip_archive *pZip); - -// Misc. high-level helper functions: - -// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. -mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); - -// Reads a single file from an archive into a heap block. -// Returns NULL on failure. -void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); - -#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -#endif // #ifndef MINIZ_NO_ARCHIVE_APIS - -// ------------------- Low-level Decompression API Definitions - -// Decompression flags used by tinfl_decompress(). -// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. -// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. -// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). -// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. -enum -{ - TINFL_FLAG_PARSE_ZLIB_HEADER = 1, - TINFL_FLAG_HAS_MORE_INPUT = 2, - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, - TINFL_FLAG_COMPUTE_ADLER32 = 8 -}; - -// High level decompression functions: -// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). -// On entry: -// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. -// On return: -// Function returns a pointer to the decompressed data, or NULL on failure. -// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. -// The caller must free() the returned block when it's no longer needed. -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); - -// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. -// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. -#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); - -// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. -// Returns 1 on success or 0 on failure. -typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); - -struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; - -// Max size of LZ dictionary. -#define TINFL_LZ_DICT_SIZE 32768 - -// Return status. -typedef enum -{ - TINFL_STATUS_BAD_PARAM = -3, - TINFL_STATUS_ADLER32_MISMATCH = -2, - TINFL_STATUS_FAILED = -1, - TINFL_STATUS_DONE = 0, - TINFL_STATUS_NEEDS_MORE_INPUT = 1, - TINFL_STATUS_HAS_MORE_OUTPUT = 2 -} tinfl_status; - -// Initializes the decompressor to its initial state. -#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END -#define tinfl_get_adler32(r) (r)->m_check_adler32 - -// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. -// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. -tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); - -// Internal/private bits follow. -enum -{ - TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, - TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS -}; - -typedef struct -{ - mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; - mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; -} tinfl_huff_table; - -#if MINIZ_HAS_64BIT_REGISTERS - #define TINFL_USE_64BIT_BITBUF 1 -#endif - -#if TINFL_USE_64BIT_BITBUF - typedef mz_uint64 tinfl_bit_buf_t; - #define TINFL_BITBUF_SIZE (64) -#else - typedef mz_uint32 tinfl_bit_buf_t; - #define TINFL_BITBUF_SIZE (32) -#endif - -struct tinfl_decompressor_tag -{ - mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; - tinfl_bit_buf_t m_bit_buf; - size_t m_dist_from_out_buf_start; - tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; - mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; -}; - -// ------------------- Low-level Compression API Definitions - -// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). -#define TDEFL_LESS_MEMORY 0 - -// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): -// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). -enum -{ - TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF -}; - -// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. -// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). -// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. -// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). -// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) -// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. -// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. -// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. -enum -{ - TDEFL_WRITE_ZLIB_HEADER = 0x01000, - TDEFL_COMPUTE_ADLER32 = 0x02000, - TDEFL_GREEDY_PARSING_FLAG = 0x04000, - TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, - TDEFL_RLE_MATCHES = 0x10000, - TDEFL_FILTER_MATCHES = 0x20000, - TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, - TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 -}; - -// High level compression functions: -// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). -// On entry: -// pSrc_buf, src_buf_len: Pointer and size of source block to compress. -// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. -// On return: -// Function returns a pointer to the compressed data, or NULL on failure. -// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. -// The caller must free() the returned block when it's no longer needed. -void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); - -// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. -// Returns 0 on failure. -size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); - -// Compresses an image to a compressed PNG file in memory. -// On entry: -// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. -// On return: -// Function returns a pointer to the compressed data, or NULL on failure. -// *pLen_out will be set to the size of the PNG image file. -// The caller must free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. -void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); - -// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. -typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); - -// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. -mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); - -enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; - -// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). -#if TDEFL_LESS_MEMORY -enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; -#else -enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; -#endif - -// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. -typedef enum -{ - TDEFL_STATUS_BAD_PARAM = -2, - TDEFL_STATUS_PUT_BUF_FAILED = -1, - TDEFL_STATUS_OKAY = 0, - TDEFL_STATUS_DONE = 1, -} tdefl_status; - -// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums -typedef enum -{ - TDEFL_NO_FLUSH = 0, - TDEFL_SYNC_FLUSH = 2, - TDEFL_FULL_FLUSH = 3, - TDEFL_FINISH = 4 -} tdefl_flush; - -// tdefl's compression state structure. -typedef struct -{ - tdefl_put_buf_func_ptr m_pPut_buf_func; - void *m_pPut_buf_user; - mz_uint m_flags, m_max_probes[2]; - int m_greedy_parsing; - mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; - mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; - mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; - mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; - tdefl_status m_prev_return_status; - const void *m_pIn_buf; - void *m_pOut_buf; - size_t *m_pIn_buf_size, *m_pOut_buf_size; - tdefl_flush m_flush; - const mz_uint8 *m_pSrc; - size_t m_src_buf_left, m_out_buf_ofs; - mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; - mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; - mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; - mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; - mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; -} tdefl_compressor; - -// Initializes the compressor. -// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. -// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. -// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. -// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) -tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); - -// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. -tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); - -// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. -// tdefl_compress_buffer() always consumes the entire input buffer. -tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); - -tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); -mz_uint32 tdefl_get_adler32(tdefl_compressor *d); - -// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. -#ifndef MINIZ_NO_ZLIB_APIS -// Create tdefl_compress() flags given zlib-style compression parameters. -// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) -// window_bits may be -15 (raw deflate) or 15 (zlib) -// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED -mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); -#endif // #ifndef MINIZ_NO_ZLIB_APIS - -#ifdef __cplusplus -} -#endif - -#endif // MINIZ_HEADER_INCLUDED - -// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) - -#ifndef MINIZ_HEADER_FILE_ONLY - -typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1]; -typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1]; -typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1]; - -#include -#include - -#define MZ_ASSERT(x) assert(x) - -#ifdef MINIZ_NO_MALLOC - #define MZ_MALLOC(x) NULL - #define MZ_FREE(x) (void)x, ((void)0) - #define MZ_REALLOC(p, x) NULL -#else - #define MZ_MALLOC(x) malloc(x) - #define MZ_FREE(x) free(x) - #define MZ_REALLOC(p, x) realloc(p, x) -#endif - -#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) -#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) -#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) - #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) -#else - #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) - #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) -#endif - -#ifdef _MSC_VER - #define MZ_FORCEINLINE __forceinline -#elif defined(__GNUC__) - #define MZ_FORCEINLINE __attribute__((__always_inline__)) -#else - #define MZ_FORCEINLINE inline -#endif - -#ifdef __cplusplus - extern "C" { -#endif - -// ------------------- zlib-style API's - -mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) -{ - mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; - if (!ptr) return MZ_ADLER32_INIT; - while (buf_len) { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { - s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; - } - for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; - } - return (s2 << 16) + s1; -} - -// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ -mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) -{ - static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, - 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; - mz_uint32 crcu32 = (mz_uint32)crc; - if (!ptr) return MZ_CRC32_INIT; - crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } - return ~crcu32; -} - -#ifndef MINIZ_NO_ZLIB_APIS - -static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } -static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } -static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } - -const char *mz_version(void) -{ - return MZ_VERSION; -} - -int mz_deflateInit(mz_streamp pStream, int level) -{ - return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); -} - -int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) -{ - tdefl_compressor *pComp; - mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); - - if (!pStream) return MZ_STREAM_ERROR; - if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; - - pStream->data_type = 0; - pStream->adler = MZ_ADLER32_INIT; - pStream->msg = NULL; - pStream->reserved = 0; - pStream->total_in = 0; - pStream->total_out = 0; - if (!pStream->zalloc) pStream->zalloc = def_alloc_func; - if (!pStream->zfree) pStream->zfree = def_free_func; - - pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); - if (!pComp) - return MZ_MEM_ERROR; - - pStream->state = (struct mz_internal_state *)pComp; - - if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) - { - mz_deflateEnd(pStream); - return MZ_PARAM_ERROR; - } - - return MZ_OK; -} - -int mz_deflateReset(mz_streamp pStream) -{ - if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; - pStream->total_in = pStream->total_out = 0; - tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags); - return MZ_OK; -} - -int mz_deflate(mz_streamp pStream, int flush) -{ - size_t in_bytes, out_bytes; - mz_ulong orig_total_in, orig_total_out; - int mz_status = MZ_OK; - - if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; - if (!pStream->avail_out) return MZ_BUF_ERROR; - - if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; - - if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) - return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; - - orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; - for ( ; ; ) - { - tdefl_status defl_status; - in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; - - defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); - pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); - - pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; - pStream->total_out += (mz_uint)out_bytes; - - if (defl_status < 0) - { - mz_status = MZ_STREAM_ERROR; - break; - } - else if (defl_status == TDEFL_STATUS_DONE) - { - mz_status = MZ_STREAM_END; - break; - } - else if (!pStream->avail_out) - break; - else if ((!pStream->avail_in) && (flush != MZ_FINISH)) - { - if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) - break; - return MZ_BUF_ERROR; // Can't make forward progress without some input. - } - } - return mz_status; -} - -int mz_deflateEnd(mz_streamp pStream) -{ - if (!pStream) return MZ_STREAM_ERROR; - if (pStream->state) - { - pStream->zfree(pStream->opaque, pStream->state); - pStream->state = NULL; - } - return MZ_OK; -} - -mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) -{ - (void)pStream; - // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) - return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); -} - -int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) -{ - int status; - mz_stream stream; - memset(&stream, 0, sizeof(stream)); - - // In case mz_ulong is 64-bits (argh I hate longs). - if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; - - stream.next_in = pSource; - stream.avail_in = (mz_uint32)source_len; - stream.next_out = pDest; - stream.avail_out = (mz_uint32)*pDest_len; - - status = mz_deflateInit(&stream, level); - if (status != MZ_OK) return status; - - status = mz_deflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) - { - mz_deflateEnd(&stream); - return (status == MZ_OK) ? MZ_BUF_ERROR : status; - } - - *pDest_len = stream.total_out; - return mz_deflateEnd(&stream); -} - -int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) -{ - return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); -} - -mz_ulong mz_compressBound(mz_ulong source_len) -{ - return mz_deflateBound(NULL, source_len); -} - -typedef struct -{ - tinfl_decompressor m_decomp; - mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; - mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; - tinfl_status m_last_status; -} inflate_state; - -int mz_inflateInit2(mz_streamp pStream, int window_bits) -{ - inflate_state *pDecomp; - if (!pStream) return MZ_STREAM_ERROR; - if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; - - pStream->data_type = 0; - pStream->adler = 0; - pStream->msg = NULL; - pStream->total_in = 0; - pStream->total_out = 0; - pStream->reserved = 0; - if (!pStream->zalloc) pStream->zalloc = def_alloc_func; - if (!pStream->zfree) pStream->zfree = def_free_func; - - pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); - if (!pDecomp) return MZ_MEM_ERROR; - - pStream->state = (struct mz_internal_state *)pDecomp; - - tinfl_init(&pDecomp->m_decomp); - pDecomp->m_dict_ofs = 0; - pDecomp->m_dict_avail = 0; - pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; - pDecomp->m_first_call = 1; - pDecomp->m_has_flushed = 0; - pDecomp->m_window_bits = window_bits; - - return MZ_OK; -} - -int mz_inflateInit(mz_streamp pStream) -{ - return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); -} - -int mz_inflate(mz_streamp pStream, int flush) -{ - inflate_state* pState; - mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; - size_t in_bytes, out_bytes, orig_avail_in; - tinfl_status status; - - if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; - if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; - if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; - - pState = (inflate_state*)pStream->state; - if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; - orig_avail_in = pStream->avail_in; - - first_call = pState->m_first_call; pState->m_first_call = 0; - if (pState->m_last_status < 0) return MZ_DATA_ERROR; - - if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; - pState->m_has_flushed |= (flush == MZ_FINISH); - - if ((flush == MZ_FINISH) && (first_call)) - { - // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. - decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; - in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; - status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); - pState->m_last_status = status; - pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; - pStream->adler = tinfl_get_adler32(&pState->m_decomp); - pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; - - if (status < 0) - return MZ_DATA_ERROR; - else if (status != TINFL_STATUS_DONE) - { - pState->m_last_status = TINFL_STATUS_FAILED; - return MZ_BUF_ERROR; - } - return MZ_STREAM_END; - } - // flush != MZ_FINISH then we must assume there's more input. - if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; - - if (pState->m_dict_avail) - { - n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); - memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; - pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; - } - - for ( ; ; ) - { - in_bytes = pStream->avail_in; - out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; - - status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); - pState->m_last_status = status; - - pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); - - pState->m_dict_avail = (mz_uint)out_bytes; - - n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); - memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; - pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - - if (status < 0) - return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). - else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) - return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. - else if (flush == MZ_FINISH) - { - // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. - if (status == TINFL_STATUS_DONE) - return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; - // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. - else if (!pStream->avail_out) - return MZ_BUF_ERROR; - } - else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) - break; - } - - return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; -} - -int mz_inflateEnd(mz_streamp pStream) -{ - if (!pStream) - return MZ_STREAM_ERROR; - if (pStream->state) - { - pStream->zfree(pStream->opaque, pStream->state); - pStream->state = NULL; - } - return MZ_OK; -} - -int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) -{ - mz_stream stream; - int status; - memset(&stream, 0, sizeof(stream)); - - // In case mz_ulong is 64-bits (argh I hate longs). - if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; - - stream.next_in = pSource; - stream.avail_in = (mz_uint32)source_len; - stream.next_out = pDest; - stream.avail_out = (mz_uint32)*pDest_len; - - status = mz_inflateInit(&stream); - if (status != MZ_OK) - return status; - - status = mz_inflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) - { - mz_inflateEnd(&stream); - return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; - } - *pDest_len = stream.total_out; - - return mz_inflateEnd(&stream); -} - -const char *mz_error(int err) -{ - static struct { int m_err; const char *m_pDesc; } s_error_descs[] = - { - { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, - { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } - }; - mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; - return NULL; -} - -#endif //MINIZ_NO_ZLIB_APIS - -// ------------------- Low-level Decompression (completely independent from all compression API's) - -#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) -#define TINFL_MEMSET(p, c, l) memset(p, c, l) - -#define TINFL_CR_BEGIN switch(r->m_state) { case 0: -#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END -#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END -#define TINFL_CR_FINISH } - -// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never -// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. -#define TINFL_GET_BYTE(state_index, c) do { \ - if (pIn_buf_cur >= pIn_buf_end) { \ - for ( ; ; ) { \ - if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ - TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ - if (pIn_buf_cur < pIn_buf_end) { \ - c = *pIn_buf_cur++; \ - break; \ - } \ - } else { \ - c = 0; \ - break; \ - } \ - } \ - } else c = *pIn_buf_cur++; } MZ_MACRO_END - -#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) -#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END -#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END - -// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. -// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a -// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the -// bit buffer contains >=15 bits (deflate's max. Huffman code size). -#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ - do { \ - temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ - if (temp >= 0) { \ - code_len = temp >> 9; \ - if ((code_len) && (num_bits >= code_len)) \ - break; \ - } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ - code_len = TINFL_FAST_LOOKUP_BITS; \ - do { \ - temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ - } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ - } while (num_bits < 15); - -// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read -// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully -// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. -// The slow path is only executed at the very end of the input buffer. -#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ - int temp; mz_uint code_len, c; \ - if (num_bits < 15) { \ - if ((pIn_buf_end - pIn_buf_cur) < 2) { \ - TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ - } else { \ - bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ - } \ - } \ - if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ - code_len = temp >> 9, temp &= 511; \ - else { \ - code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ - } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END - -tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) -{ - static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; - static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; - static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; - static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; - static const int s_min_table_sizes[3] = { 257, 1, 4 }; - - tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; - const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; - mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; - size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; - - // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). - if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } - - num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; - TINFL_CR_BEGIN - - bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); - counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); - if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); - if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } - } - - do - { - TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; - if (r->m_type == 0) - { - TINFL_SKIP_BITS(5, num_bits & 7); - for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } - if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } - while ((counter) && (num_bits)) - { - TINFL_GET_BITS(51, dist, 8); - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } - *pOut_buf_cur++ = (mz_uint8)dist; - counter--; - } - while (counter) - { - size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } - while (pIn_buf_cur >= pIn_buf_end) - { - if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) - { - TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); - } - else - { - TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); - } - } - n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); - TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; - } - } - else if (r->m_type == 3) - { - TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); - } - else - { - if (r->m_type == 1) - { - mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; - r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); - for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; - } - else - { - for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } - MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } - r->m_table_sizes[2] = 19; - } - for ( ; (int)r->m_type >= 0; r->m_type--) - { - int tree_next, tree_cur; tinfl_huff_table *pTable; - mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); - for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; - used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; - for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } - if ((65536 != total) && (used_syms > 1)) - { - TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); - } - for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) - { - mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; - cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); - if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } - if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } - rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); - for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) - { - tree_cur -= ((rev_code >>= 1) & 1); - if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; - } - tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; - } - if (r->m_type == 2) - { - for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) - { - mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } - if ((dist == 16) && (!counter)) - { - TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); - } - num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; - TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; - } - if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) - { - TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); - } - TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); - } - } - for ( ; ; ) - { - mz_uint8 *pSrc; - for ( ; ; ) - { - if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) - { - TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); - if (counter >= 256) - break; - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } - *pOut_buf_cur++ = (mz_uint8)counter; - } - else - { - int sym2; mz_uint code_len; -#if TINFL_USE_64BIT_BITBUF - if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } -#else - if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } -#endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); - } - counter = sym2; bit_buf >>= code_len; num_bits -= code_len; - if (counter & 256) - break; - -#if !TINFL_USE_64BIT_BITBUF - if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } -#endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); - } - bit_buf >>= code_len; num_bits -= code_len; - - pOut_buf_cur[0] = (mz_uint8)counter; - if (sym2 & 256) - { - pOut_buf_cur++; - counter = sym2; - break; - } - pOut_buf_cur[1] = (mz_uint8)sym2; - pOut_buf_cur += 2; - } - } - if ((counter &= 511) == 256) break; - - num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; - if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } - - TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); - num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; - if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } - - dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; - if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) - { - TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); - } - - pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); - - if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) - { - while (counter--) - { - while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } - *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; - } - continue; - } -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - else if ((counter >= 9) && (counter <= dist)) - { - const mz_uint8 *pSrc_end = pSrc + (counter & ~7); - do - { - ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; - ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; - pOut_buf_cur += 8; - } while ((pSrc += 8) < pSrc_end); - if ((counter &= 7) < 3) - { - if (counter) - { - pOut_buf_cur[0] = pSrc[0]; - if (counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - continue; - } - } -#endif - do - { - pOut_buf_cur[0] = pSrc[0]; - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur[2] = pSrc[2]; - pOut_buf_cur += 3; pSrc += 3; - } while ((int)(counter -= 3) > 2); - if ((int)counter > 0) - { - pOut_buf_cur[0] = pSrc[0]; - if ((int)counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - } - } - } while (!(r->m_final & 1)); - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } - } - TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); - TINFL_CR_FINISH - -common_exit: - r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; - *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; - if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) - { - const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; - mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; - while (buf_len) - { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) - { - s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; - } - for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; - } - r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; - } - return status; -} - -// Higher level helper functions. -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) -{ - tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; - *pOut_len = 0; - tinfl_init(&decomp); - for ( ; ; ) - { - size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; - tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, - (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) - { - MZ_FREE(pBuf); *pOut_len = 0; return NULL; - } - src_buf_ofs += src_buf_size; - *pOut_len += dst_buf_size; - if (status == TINFL_STATUS_DONE) break; - new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; - pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); - if (!pNew_buf) - { - MZ_FREE(pBuf); *pOut_len = 0; return NULL; - } - pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; - } - return pBuf; -} - -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) -{ - tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); - status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; -} - -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - int result = 0; - tinfl_decompressor decomp; - mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; - if (!pDict) - return TINFL_STATUS_FAILED; - tinfl_init(&decomp); - for ( ; ; ) - { - size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; - tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, - (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); - in_buf_ofs += in_buf_size; - if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) - break; - if (status != TINFL_STATUS_HAS_MORE_OUTPUT) - { - result = (status == TINFL_STATUS_DONE); - break; - } - dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); - } - MZ_FREE(pDict); - *pIn_buf_size = in_buf_ofs; - return result; -} - -// ------------------- Low-level Compression (independent from all decompression API's) - -// Purposely making these tables static for faster init and thread safety. -static const mz_uint16 s_tdefl_len_sym[256] = { - 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, - 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, - 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, - 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, - 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, - 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, - 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, - 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; - -static const mz_uint8 s_tdefl_len_extra[256] = { - 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, - 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; - -static const mz_uint8 s_tdefl_small_dist_sym[512] = { - 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, - 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, - 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, - 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, - 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, - 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, - 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, - 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, - 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, - 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, - 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, - 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; - -static const mz_uint8 s_tdefl_small_dist_extra[512] = { - 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, - 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, - 7,7,7,7,7,7,7,7 }; - -static const mz_uint8 s_tdefl_large_dist_sym[128] = { - 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, - 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, - 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; - -static const mz_uint8 s_tdefl_large_dist_extra[128] = { - 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, - 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, - 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; - -// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. -typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; -static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) -{ - mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); - for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } - while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; - for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) - { - const mz_uint32* pHist = &hist[pass << 8]; - mz_uint offsets[256], cur_ofs = 0; - for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } - for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; - { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } - } - return pCur_syms; -} - -// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. -static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) -{ - int root, leaf, next, avbl, used, dpth; - if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } - A[0].m_key += A[1].m_key; root = 0; leaf = 2; - for (next=1; next < n-1; next++) - { - if (leaf>=n || A[root].m_key=n || (root=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; - avbl = 1; used = dpth = 0; root = n-2; next = n-1; - while (avbl>0) - { - while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } - while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } - avbl = 2*used; dpth++; used = 0; - } -} - -// Limits canonical Huffman code table's max code size. -enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; -static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) -{ - int i; mz_uint32 total = 0; if (code_list_len <= 1) return; - for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; - for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); - while (total != (1UL << max_code_size)) - { - pNum_codes[max_code_size]--; - for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } - total--; - } -} - -static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) -{ - int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); - if (static_table) - { - for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; - } - else - { - tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; - int num_used_syms = 0; - const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; - for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } - - pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); - - for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; - - tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); - - MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); - for (i = 1, j = num_used_syms; i <= code_size_limit; i++) - for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); - } - - next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); - - for (i = 0; i < table_len; i++) - { - mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; - code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); - d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; - } -} - -#define TDEFL_PUT_BITS(b, l) do { \ - mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ - d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ - while (d->m_bits_in >= 8) { \ - if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ - *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ - d->m_bit_buffer >>= 8; \ - d->m_bits_in -= 8; \ - } \ -} MZ_MACRO_END - -#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ - if (rle_repeat_count < 3) { \ - d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ - while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ - } else { \ - d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ -} rle_repeat_count = 0; } } - -#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ - if (rle_z_count < 3) { \ - d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ - } else if (rle_z_count <= 10) { \ - d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ - } else { \ - d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ -} rle_z_count = 0; } } - -static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; - -static void tdefl_start_dynamic_block(tdefl_compressor *d) -{ - int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; - mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; - - d->m_huff_count[0][256] = 1; - - tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); - tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); - - for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; - for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; - - memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); - memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); - total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; - - memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); - for (i = 0; i < total_code_sizes_to_pack; i++) - { - mz_uint8 code_size = code_sizes_to_pack[i]; - if (!code_size) - { - TDEFL_RLE_PREV_CODE_SIZE(); - if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } - } - else - { - TDEFL_RLE_ZERO_CODE_SIZE(); - if (code_size != prev_code_size) - { - TDEFL_RLE_PREV_CODE_SIZE(); - d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; - } - else if (++rle_repeat_count == 6) - { - TDEFL_RLE_PREV_CODE_SIZE(); - } - } - prev_code_size = code_size; - } - if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } - - tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); - - TDEFL_PUT_BITS(2, 2); - - TDEFL_PUT_BITS(num_lit_codes - 257, 5); - TDEFL_PUT_BITS(num_dist_codes - 1, 5); - - for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; - num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); - for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); - - for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) - { - mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); - TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); - if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); - } -} - -static void tdefl_start_static_block(tdefl_compressor *d) -{ - mz_uint i; - mz_uint8 *p = &d->m_huff_code_sizes[0][0]; - - for (i = 0; i <= 143; ++i) *p++ = 8; - for ( ; i <= 255; ++i) *p++ = 9; - for ( ; i <= 279; ++i) *p++ = 7; - for ( ; i <= 287; ++i) *p++ = 8; - - memset(d->m_huff_code_sizes[1], 5, 32); - - tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); - tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); - - TDEFL_PUT_BITS(1, 2); -} - -static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS -static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) -{ - mz_uint flags; - mz_uint8 *pLZ_codes; - mz_uint8 *pOutput_buf = d->m_pOutput_buf; - mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; - mz_uint64 bit_buffer = d->m_bit_buffer; - mz_uint bits_in = d->m_bits_in; - -#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } - - flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) - { - if (flags == 1) - flags = *pLZ_codes++ | 0x100; - - if (flags & 1) - { - mz_uint s0, s1, n0, n1, sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; - - MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); - - // This sequence coaxes MSVC into using cmov's vs. jmp's. - s0 = s_tdefl_small_dist_sym[match_dist & 511]; - n0 = s_tdefl_small_dist_extra[match_dist & 511]; - s1 = s_tdefl_large_dist_sym[match_dist >> 8]; - n1 = s_tdefl_large_dist_extra[match_dist >> 8]; - sym = (match_dist < 512) ? s0 : s1; - num_extra_bits = (match_dist < 512) ? n0 : n1; - - MZ_ASSERT(d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); - } - else - { - mz_uint lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) - { - flags >>= 1; - lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) - { - flags >>= 1; - lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - } - } - } - - if (pOutput_buf >= d->m_pOutput_buf_end) - return MZ_FALSE; - - *(mz_uint64*)pOutput_buf = bit_buffer; - pOutput_buf += (bits_in >> 3); - bit_buffer >>= (bits_in & ~7); - bits_in &= 7; - } - -#undef TDEFL_PUT_BITS_FAST - - d->m_pOutput_buf = pOutput_buf; - d->m_bits_in = 0; - d->m_bit_buffer = 0; - - while (bits_in) - { - mz_uint32 n = MZ_MIN(bits_in, 16); - TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); - bit_buffer >>= n; - bits_in -= n; - } - - TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); - - return (d->m_pOutput_buf < d->m_pOutput_buf_end); -} -#else -static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) -{ - mz_uint flags; - mz_uint8 *pLZ_codes; - - flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) - { - if (flags == 1) - flags = *pLZ_codes++ | 0x100; - if (flags & 1) - { - mz_uint sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; - - MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); - - if (match_dist < 512) - { - sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; - } - else - { - sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; - } - MZ_ASSERT(d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); - } - else - { - mz_uint lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - } - } - - TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); - - return (d->m_pOutput_buf < d->m_pOutput_buf_end); -} -#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS - -static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) -{ - if (static_block) - tdefl_start_static_block(d); - else - tdefl_start_dynamic_block(d); - return tdefl_compress_lz_codes(d); -} - -static int tdefl_flush_block(tdefl_compressor *d, int flush) -{ - mz_uint saved_bit_buf, saved_bits_in; - mz_uint8 *pSaved_output_buf; - mz_bool comp_block_succeeded = MZ_FALSE; - int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; - mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; - - d->m_pOutput_buf = pOutput_buf_start; - d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; - - MZ_ASSERT(!d->m_output_flush_remaining); - d->m_output_flush_ofs = 0; - d->m_output_flush_remaining = 0; - - *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); - d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); - - if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) - { - TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); - } - - TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); - - pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; - - if (!use_raw_block) - comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); - - // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. - if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && - ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) - { - mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; - TDEFL_PUT_BITS(0, 2); - if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } - for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) - { - TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); - } - for (i = 0; i < d->m_total_lz_bytes; ++i) - { - TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); - } - } - // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. - else if (!comp_block_succeeded) - { - d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; - tdefl_compress_block(d, MZ_TRUE); - } - - if (flush) - { - if (flush == TDEFL_FINISH) - { - if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } - if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } - } - else - { - mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } - } - } - - MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); - - memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; - - if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) - { - if (d->m_pPut_buf_func) - { - *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; - if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) - return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); - } - else if (pOutput_buf_start == d->m_output_buf) - { - int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); - memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); - d->m_out_buf_ofs += bytes_to_copy; - if ((n -= bytes_to_copy) != 0) - { - d->m_output_flush_ofs = bytes_to_copy; - d->m_output_flush_remaining = n; - } - } - else - { - d->m_out_buf_ofs += n; - } - } - - return d->m_output_flush_remaining; -} - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES -#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) -static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) -{ - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; - mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q; - mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); - MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; - for ( ; ; ) - { - for ( ; ; ) - { - if (--num_probes_left == 0) return; - #define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; - TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; - } - if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; - do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && - (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); - if (!probe_len) - { - *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; - } - else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len) - { - *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; - c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); - } - } -} -#else -static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) -{ - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; - mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint8 *s = d->m_dict + pos, *p, *q; - mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; - MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; - for ( ; ; ) - { - for ( ; ; ) - { - if (--num_probes_left == 0) return; - #define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; - TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; - } - if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; - if (probe_len > match_len) - { - *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; - c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; - } - } -} -#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN -static mz_bool tdefl_compress_fast(tdefl_compressor *d) -{ - // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. - mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; - mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; - mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - - while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) - { - const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; - mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; - mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); - d->m_src_buf_left -= num_bytes_to_process; - lookahead_size += num_bytes_to_process; - - while (num_bytes_to_process) - { - mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); - memcpy(d->m_dict + dst_pos, d->m_pSrc, n); - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); - d->m_pSrc += n; - dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; - num_bytes_to_process -= n; - } - - dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); - if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; - - while (lookahead_size >= 4) - { - mz_uint cur_match_dist, cur_match_len = 1; - mz_uint8 *pCur_dict = d->m_dict + cur_pos; - mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; - mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; - mz_uint probe_pos = d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16)lookahead_pos; - - if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) - { - const mz_uint16 *p = (const mz_uint16 *)pCur_dict; - const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); - mz_uint32 probe_len = 32; - do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && - (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); - cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); - if (!probe_len) - cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; - - if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) - { - cur_match_len = 1; - *pLZ_code_buf++ = (mz_uint8)first_trigram; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - d->m_huff_count[0][(mz_uint8)first_trigram]++; - } - else - { - mz_uint32 s0, s1; - cur_match_len = MZ_MIN(cur_match_len, lookahead_size); - - MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); - - cur_match_dist--; - - pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); - *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; - pLZ_code_buf += 3; - *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); - - s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; - s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; - d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; - - d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; - } - } - else - { - *pLZ_code_buf++ = (mz_uint8)first_trigram; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - d->m_huff_count[0][(mz_uint8)first_trigram]++; - } - - if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } - - total_lz_bytes += cur_match_len; - lookahead_pos += cur_match_len; - dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); - cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; - MZ_ASSERT(lookahead_size >= cur_match_len); - lookahead_size -= cur_match_len; - - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - { - int n; - d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; - } - } - - while (lookahead_size) - { - mz_uint8 lit = d->m_dict[cur_pos]; - - total_lz_bytes++; - *pLZ_code_buf++ = lit; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } - - d->m_huff_count[0][lit]++; - - lookahead_pos++; - dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); - cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; - lookahead_size--; - - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - { - int n; - d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; - } - } - } - - d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; - return MZ_TRUE; -} -#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - -static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) -{ - d->m_total_lz_bytes++; - *d->m_pLZ_code_buf++ = lit; - *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } - d->m_huff_count[0][lit]++; -} - -static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) -{ - mz_uint32 s0, s1; - - MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); - - d->m_total_lz_bytes += match_len; - - d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); - - match_dist -= 1; - d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); - d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; - - *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } - - s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; - d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; - - if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; -} - -static mz_bool tdefl_compress_normal(tdefl_compressor *d) -{ - const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; - tdefl_flush flush = d->m_flush; - - while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) - { - mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; - // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. - if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) - { - mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; - mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; - mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); - const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; - src_buf_left -= num_bytes_to_process; - d->m_lookahead_size += num_bytes_to_process; - while (pSrc != pSrc_end) - { - mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); - dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; - } - } - else - { - while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) - { - mz_uint8 c = *pSrc++; - mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; - src_buf_left--; - d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) - { - mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; - mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); - } - } - } - d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); - if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) - break; - - // Simple lazy/greedy parsing state machine. - len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) - { - if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) - { - mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; - cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } - if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; - } - } - else - { - tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); - } - if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) - { - cur_match_dist = cur_match_len = 0; - } - if (d->m_saved_match_len) - { - if (cur_match_len > d->m_saved_match_len) - { - tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); - if (cur_match_len >= 128) - { - tdefl_record_match(d, cur_match_len, cur_match_dist); - d->m_saved_match_len = 0; len_to_move = cur_match_len; - } - else - { - d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; - } - } - else - { - tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); - len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; - } - } - else if (!cur_match_dist) - tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); - else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) - { - tdefl_record_match(d, cur_match_len, cur_match_dist); - len_to_move = cur_match_len; - } - else - { - d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; - } - // Move the lookahead forward by len_to_move bytes. - d->m_lookahead_pos += len_to_move; - MZ_ASSERT(d->m_lookahead_size >= len_to_move); - d->m_lookahead_size -= len_to_move; - d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); - // Check if it's time to flush the current LZ codes to the internal output buffer. - if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || - ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) - { - int n; - d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - } - } - - d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; - return MZ_TRUE; -} - -static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) -{ - if (d->m_pIn_buf_size) - { - *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; - } - - if (d->m_pOut_buf_size) - { - size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); - memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); - d->m_output_flush_ofs += (mz_uint)n; - d->m_output_flush_remaining -= (mz_uint)n; - d->m_out_buf_ofs += n; - - *d->m_pOut_buf_size = d->m_out_buf_ofs; - } - - return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; -} - -tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) -{ - if (!d) - { - if (pIn_buf_size) *pIn_buf_size = 0; - if (pOut_buf_size) *pOut_buf_size = 0; - return TDEFL_STATUS_BAD_PARAM; - } - - d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; - d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; - d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; - d->m_out_buf_ofs = 0; - d->m_flush = flush; - - if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || - (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) - { - if (pIn_buf_size) *pIn_buf_size = 0; - if (pOut_buf_size) *pOut_buf_size = 0; - return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); - } - d->m_wants_to_finish |= (flush == TDEFL_FINISH); - - if ((d->m_output_flush_remaining) || (d->m_finished)) - return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && - ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && - ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) - { - if (!tdefl_compress_fast(d)) - return d->m_prev_return_status; - } - else -#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - { - if (!tdefl_compress_normal(d)) - return d->m_prev_return_status; - } - - if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) - d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); - - if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) - { - if (tdefl_flush_block(d, flush) < 0) - return d->m_prev_return_status; - d->m_finished = (flush == TDEFL_FINISH); - if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } - } - - return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); -} - -tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) -{ - MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); -} - -tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; - d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; - d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; - if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); - d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; - d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; - d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; - d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; - d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; - d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; - d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; - memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - return TDEFL_STATUS_OKAY; -} - -tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) -{ - return d->m_prev_return_status; -} - -mz_uint32 tdefl_get_adler32(tdefl_compressor *d) -{ - return d->m_adler32; -} - -mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) -{ - tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; - pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; - succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); - succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); - MZ_FREE(pComp); return succeeded; -} - -typedef struct -{ - size_t m_size, m_capacity; - mz_uint8 *m_pBuf; - mz_bool m_expandable; -} tdefl_output_buffer; - -static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) -{ - tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; - size_t new_size = p->m_size + len; - if (new_size > p->m_capacity) - { - size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; - do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); - pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; - p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; - } - memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; - return MZ_TRUE; -} - -void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) -{ - tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); - if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; - out_buf.m_expandable = MZ_TRUE; - if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; - *pOut_len = out_buf.m_size; return out_buf.m_pBuf; -} - -size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) -{ - tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); - if (!pOut_buf) return 0; - out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len; - if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; - return out_buf.m_size; -} - -#ifndef MINIZ_NO_ZLIB_APIS -static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; - -// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). -mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) -{ - mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); - if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; - - if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; - else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; - else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; - else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; - else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; - - return comp_flags; -} -#endif //MINIZ_NO_ZLIB_APIS - -#ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) -#endif - -// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at -// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. -void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) -{ - tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; - if (!pComp) return NULL; - MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } - // write dummy header - for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); - // compress image data - tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, TDEFL_DEFAULT_MAX_PROBES | TDEFL_WRITE_ZLIB_HEADER); - for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + y * bpl, bpl, TDEFL_NO_FLUSH); } - if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } - // write real header - *pLen_out = out_buf.m_size-41; - { - mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, - 0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,"\0\0\04\02\06"[num_chans],0,0,0,0,0,0,0, - (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54}; - c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24); - memcpy(out_buf.m_pBuf, pnghdr, 41); - } - // write footer (IDAT CRC-32, followed by IEND chunk) - if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } - c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24); - // compute final size of file, grab compressed data buffer and return - *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; -} - -#ifdef _MSC_VER -#pragma warning (pop) -#endif - -// ------------------- .ZIP archive reading - -#ifndef MINIZ_NO_ARCHIVE_APIS - -#ifdef MINIZ_NO_STDIO - #define MZ_FILE void * -#else - #include - #include - #if defined(_MSC_VER) || defined(__MINGW64__) - #include - #define MZ_FILE FILE - #define MZ_FOPEN fopen - #define MZ_FCLOSE fclose - #define MZ_FREAD fread - #define MZ_FWRITE fwrite - #define MZ_FTELL64 _ftelli64 - #define MZ_FSEEK64 _fseeki64 - #define MZ_FILE_STAT_STRUCT _stat - #define MZ_FILE_STAT _stat - #define MZ_FFLUSH fflush - #define MZ_FREOPEN freopen - #define MZ_DELETE_FILE remove - #elif defined(__MINGW32__) - #include - #define MZ_FILE FILE - #define MZ_FOPEN fopen - #define MZ_FCLOSE fclose - #define MZ_FREAD fread - #define MZ_FWRITE fwrite - #define MZ_FTELL64 ftello64 - #define MZ_FSEEK64 fseeko64 - #define MZ_FILE_STAT_STRUCT _stat - #define MZ_FILE_STAT _stat - #define MZ_FFLUSH fflush - #define MZ_FREOPEN freopen - #define MZ_DELETE_FILE remove - #else - #include - #define MZ_FILE FILE - #define MZ_FOPEN fopen - #define MZ_FCLOSE fclose - #define MZ_FREAD fread - #define MZ_FWRITE fwrite - #define MZ_FTELL64 ftello - #define MZ_FSEEK64 fseeko - #define MZ_FILE_STAT_STRUCT stat - #define MZ_FILE_STAT stat - #define MZ_FFLUSH fflush - #define MZ_FREOPEN freopen - #define MZ_DELETE_FILE remove - #endif // #ifdef _MSC_VER -#endif // #ifdef MINIZ_NO_STDIO - -#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) - -// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. -enum -{ - // ZIP archive identifiers and record sizes - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, - // Central directory header record offsets - MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, - MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, - MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, - MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, - // Local directory header offsets - MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, - MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, - MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, - // End of central directory offsets - MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, - MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, -}; - -typedef struct -{ - void *m_p; - size_t m_size, m_capacity; - mz_uint m_element_size; -} mz_zip_array; - -struct mz_zip_internal_state_tag -{ - mz_zip_array m_central_dir; - mz_zip_array m_central_dir_offsets; - mz_zip_array m_sorted_central_dir_offsets; - MZ_FILE *m_pFile; - void *m_pMem; - size_t m_mem_size; - size_t m_mem_capacity; -}; - -#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size -#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] - -static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) -{ - pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); - memset(pArray, 0, sizeof(mz_zip_array)); -} - -static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) -{ - void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; - if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } - if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; - pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) -{ - if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) -{ - if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } - pArray->m_size = new_size; - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) -{ - return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) -{ - size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; - memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); - return MZ_TRUE; -} - -#ifndef MINIZ_NO_TIME -static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) -{ - struct tm tm; - memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; - tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; - tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; - return mktime(&tm); -} - -static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) -{ - struct tm *tm = localtime(&time); - *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); - *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); -} -#endif - -#ifndef MINIZ_NO_STDIO -static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) -{ -#ifdef MINIZ_NO_TIME - (void)pFilename; *pDOS_date = *pDOS_time = 0; -#else - struct MZ_FILE_STAT_STRUCT file_stat; if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; - mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); -#endif // #ifdef MINIZ_NO_TIME - return MZ_TRUE; -} - -static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) -{ -#ifndef MINIZ_NO_TIME - struct utimbuf t; t.actime = access_time; t.modtime = modified_time; - return !utime(pFilename, &t); -#else - pFilename, access_time, modified_time; - return MZ_TRUE; -#endif // #ifndef MINIZ_NO_TIME -} -#endif - -static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) -{ - (void)flags; - if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) - return MZ_FALSE; - - if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; - if (!pZip->m_pFree) pZip->m_pFree = def_free_func; - if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; - - pZip->m_zip_mode = MZ_ZIP_MODE_READING; - pZip->m_archive_size = 0; - pZip->m_central_directory_file_ofs = 0; - pZip->m_total_files = 0; - - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) - return MZ_FALSE; - memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) -{ - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; - const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); - mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); - mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) - { - if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) - break; - pL++; pR++; - } - return (pL == pE) ? (l_len < r_len) : (l < r); -} - -#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END - -// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) -static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) -{ - mz_zip_internal_state *pState = pZip->m_pState; - const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; - const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); - const int size = pZip->m_total_files; - int start = (size - 2) >> 1, end; - while (start >= 0) - { - int child, root = start; - for ( ; ; ) - { - if ((child = (root << 1) + 1) >= size) - break; - child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) - break; - MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; - } - start--; - } - - end = size - 1; - while (end > 0) - { - int child, root = 0; - MZ_SWAP_UINT32(pIndices[end], pIndices[0]); - for ( ; ; ) - { - if ((child = (root << 1) + 1) >= end) - break; - child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) - break; - MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; - } - end--; - } -} - -static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) -{ - mz_uint cdir_size, num_this_disk, cdir_disk_index; - mz_uint64 cdir_ofs; - mz_int64 cur_file_ofs; - const mz_uint8 *p; - mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; - // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. - if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return MZ_FALSE; - // Find the end of central directory record by scanning the file from the end towards the beginning. - cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); - for ( ; ; ) - { - int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) - return MZ_FALSE; - for (i = n - 4; i >= 0; --i) - if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) - break; - if (i >= 0) - { - cur_file_ofs += i; - break; - } - if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) - return MZ_FALSE; - cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); - } - // Read and verify the end of central directory record. - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return MZ_FALSE; - if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || - ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) - return MZ_FALSE; - - num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); - cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); - if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) - return MZ_FALSE; - - if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) - return MZ_FALSE; - - cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); - if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) - return MZ_FALSE; - - pZip->m_central_directory_file_ofs = cdir_ofs; - - if (pZip->m_total_files) - { - mz_uint i, n; - // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. - if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || - (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) || - (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) - return MZ_FALSE; - if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) - return MZ_FALSE; - - // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). - p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; - for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) - { - mz_uint total_header_size, comp_size, decomp_size, disk_index; - if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) - return MZ_FALSE; - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; - comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) - return MZ_FALSE; - disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); - if ((disk_index != num_this_disk) && (disk_index != 1)) - return MZ_FALSE; - if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) - return MZ_FALSE; - if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) - return MZ_FALSE; - n -= total_header_size; p += total_header_size; - } - } - - if ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) - mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); - - return MZ_TRUE; -} - -mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) -{ - if ((!pZip) || (!pZip->m_pRead)) - return MZ_FALSE; - if (!mz_zip_reader_init_internal(pZip, flags)) - return MZ_FALSE; - pZip->m_archive_size = size; - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { - mz_zip_reader_end(pZip); - return MZ_FALSE; - } - return MZ_TRUE; -} - -static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) -{ - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); - memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); - return s; -} - -mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) -{ - if (!mz_zip_reader_init_internal(pZip, flags)) - return MZ_FALSE; - pZip->m_archive_size = size; - pZip->m_pRead = mz_zip_mem_read_func; - pZip->m_pIO_opaque = pZip; - pZip->m_pState->m_pMem = (void *)pMem; - pZip->m_pState->m_mem_size = size; - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { - mz_zip_reader_end(pZip); - return MZ_FALSE; - } - return MZ_TRUE; -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) -{ - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) - return 0; - return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); -} - -mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) -{ - mz_uint64 file_size; - MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); - if (!pFile) - return MZ_FALSE; - if (MZ_FSEEK64(pFile, 0, SEEK_END)) - return MZ_FALSE; - file_size = MZ_FTELL64(pFile); - if (!mz_zip_reader_init_internal(pZip, flags)) - { - MZ_FCLOSE(pFile); - return MZ_FALSE; - } - pZip->m_pRead = mz_zip_file_read_func; - pZip->m_pIO_opaque = pZip; - pZip->m_pState->m_pFile = pFile; - pZip->m_archive_size = file_size; - if (!mz_zip_reader_read_central_dir(pZip, flags)) - { - mz_zip_reader_end(pZip); - return MZ_FALSE; - } - return MZ_TRUE; -} -#endif // #ifndef MINIZ_NO_STDIO - -mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) -{ - return pZip ? pZip->m_total_files : 0; -} - -static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) -{ - if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return NULL; - return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); -} - -mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) -{ - mz_uint m_bit_flag; - const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); - if (!p) - return MZ_FALSE; - m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - return (m_bit_flag & 1); -} - -mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) -{ - mz_uint filename_len, internal_attr, external_attr; - const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); - if (!p) - return MZ_FALSE; - - internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); - external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - if ((!internal_attr) && ((external_attr & 0x10) != 0)) - return MZ_TRUE; - - filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_len) - { - if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') - return MZ_TRUE; - } - - return MZ_FALSE; -} - -mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) -{ - mz_uint n; - const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); - if ((!p) || (!pStat)) - return MZ_FALSE; - - // Unpack the central directory record. - pStat->m_file_index = file_index; - pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); - pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); - pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); - pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); -#ifndef MINIZ_NO_TIME - pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); -#endif - pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); - pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); - pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - - // Copy as much of the filename and comment as possible. - n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); - memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; - - n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); - pStat->m_comment_size = n; - memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; - - return MZ_TRUE; -} - -mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) -{ - mz_uint n; - const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); - if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } - n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_buf_size) - { - n = MZ_MIN(n, filename_buf_size - 1); - memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); - pFilename[n] = '\0'; - } - return n + 1; -} - -static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) -{ - mz_uint i; - if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) - return 0 == memcmp(pA, pB, len); - for (i = 0; i < len; ++i) - if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) - return MZ_FALSE; - return MZ_TRUE; -} - -static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) -{ - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; - mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); - mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) - { - if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) - break; - pL++; pR++; - } - return (pL == pE) ? (int)(l_len - r_len) : (l - r); -} - -static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) -{ - mz_zip_internal_state *pState = pZip->m_pState; - const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; - const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); - const int size = pZip->m_total_files; - const mz_uint filename_len = (mz_uint)strlen(pFilename); - int l = 0, h = size - 1; - while (l <= h) - { - int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); - if (!comp) - return file_index; - else if (comp < 0) - l = m + 1; - else - h = m - 1; - } - return -1; -} - -int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) -{ - mz_uint file_index; size_t name_len, comment_len; - if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return -1; - if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_p)) - return mz_zip_reader_locate_file_binary_search(pZip, pName); - name_len = strlen(pName); if (name_len > 0xFFFF) return -1; - comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; - for (file_index = 0; file_index < pZip->m_total_files; file_index++) - { - const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); - mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); - const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - if (filename_len < name_len) - continue; - if (comment_len) - { - mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); - const char *pFile_comment = pFilename + filename_len + file_extra_len; - if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) - continue; - } - if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) - { - int ofs = filename_len - 1; - do - { - if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) - break; - } while (--ofs >= 0); - ofs++; - pFilename += ofs; filename_len -= ofs; - } - if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) - return file_index; - } - return -1; -} - -mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) -{ - int status = TINFL_STATUS_DONE; - mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; - mz_zip_archive_file_stat file_stat; - void *pRead_buf; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - tinfl_decompressor inflator; - - if ((buf_size) && (!pBuf)) - return MZ_FALSE; - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - if (!file_stat.m_comp_size) - return MZ_TRUE; - - // Encryption and patch files are not supported. - if (file_stat.m_bit_flag & (1 | 32)) - return MZ_FALSE; - - // This function only supports stored and deflate. - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) - return MZ_FALSE; - - // Ensure supplied output buffer is large enough. - needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; - if (buf_size < needed_size) - return MZ_FALSE; - - // Read and parse the local directory entry. - cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return MZ_FALSE; - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return MZ_FALSE; - - cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) - return MZ_FALSE; - - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) - { - // The file is stored or the caller has requested the compressed data. - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) - return MZ_FALSE; - return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); - } - - // Decompress the file either directly from memory or from a file input buffer. - tinfl_init(&inflator); - - if (pZip->m_pState->m_pMem) - { - // Read directly from the archive in memory. - pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; - read_buf_size = read_buf_avail = file_stat.m_comp_size; - comp_remaining = 0; - } - else if (pUser_read_buf) - { - // Use a user provided read buffer. - if (!user_read_buf_size) - return MZ_FALSE; - pRead_buf = (mz_uint8 *)pUser_read_buf; - read_buf_size = user_read_buf_size; - read_buf_avail = 0; - comp_remaining = file_stat.m_uncomp_size; - } - else - { - // Temporarily allocate a read buffer. - read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); -#ifdef _MSC_VER - if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) -#else - if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) -#endif - return MZ_FALSE; - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) - return MZ_FALSE; - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - - do - { - size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) - { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - break; - } - cur_file_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - read_buf_ofs = 0; - } - in_buf_size = (size_t)read_buf_avail; - status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); - read_buf_avail -= in_buf_size; - read_buf_ofs += in_buf_size; - out_buf_ofs += out_buf_size; - } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); - - if (status == TINFL_STATUS_DONE) - { - // Make sure the entire file was decompressed, and check its CRC. - if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) - status = TINFL_STATUS_FAILED; - } - - if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - - return status == TINFL_STATUS_DONE; -} - -mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) -{ - int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); - if (file_index < 0) - return MZ_FALSE; - return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); -} - -mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) -{ - return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); -} - -mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) -{ - return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); -} - -void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) -{ - mz_uint64 comp_size, uncomp_size, alloc_size; - const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); - void *pBuf; - - if (pSize) - *pSize = 0; - if (!p) - return NULL; - - comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - - alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; -#ifdef _MSC_VER - if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) -#else - if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) -#endif - return NULL; - if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) - return NULL; - - if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return NULL; - } - - if (pSize) *pSize = (size_t)alloc_size; - return pBuf; -} - -void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) -{ - int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); - if (file_index < 0) - { - if (pSize) *pSize = 0; - return MZ_FALSE; - } - return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); -} - -mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) -{ - int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; - mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; - mz_zip_archive_file_stat file_stat; - void *pRead_buf = NULL; void *pWrite_buf = NULL; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - if (!file_stat.m_comp_size) - return MZ_TRUE; - - // Encryption and patch files are not supported. - if (file_stat.m_bit_flag & (1 | 32)) - return MZ_FALSE; - - // This function only supports stored and deflate. - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) - return MZ_FALSE; - - // Read and parse the local directory entry. - cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return MZ_FALSE; - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return MZ_FALSE; - - cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) - return MZ_FALSE; - - // Decompress the file either directly from memory or from a file input buffer. - if (pZip->m_pState->m_pMem) - { - pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; - read_buf_size = read_buf_avail = file_stat.m_comp_size; - comp_remaining = 0; - } - else - { - read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) - return MZ_FALSE; - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) - { - // The file is stored or the caller has requested the compressed data. - if (pZip->m_pState->m_pMem) - { -#ifdef _MSC_VER - if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) -#else - if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) -#endif - return MZ_FALSE; - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) - status = TINFL_STATUS_FAILED; - else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); - cur_file_ofs += file_stat.m_comp_size; - out_buf_ofs += file_stat.m_comp_size; - comp_remaining = 0; - } - else - { - while (comp_remaining) - { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - break; - } - - if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); - - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - break; - } - cur_file_ofs += read_buf_avail; - out_buf_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - } - } - } - else - { - tinfl_decompressor inflator; - tinfl_init(&inflator); - - if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) - status = TINFL_STATUS_FAILED; - else - { - do - { - mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) - { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - break; - } - cur_file_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - read_buf_ofs = 0; - } - - in_buf_size = (size_t)read_buf_avail; - status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); - read_buf_avail -= in_buf_size; - read_buf_ofs += in_buf_size; - - if (out_buf_size) - { - if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) - { - status = TINFL_STATUS_FAILED; - break; - } - file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); - if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) - { - status = TINFL_STATUS_FAILED; - break; - } - } - } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); - } - } - - if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) - { - // Make sure the entire file was decompressed, and check its CRC. - if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) - status = TINFL_STATUS_FAILED; - } - - if (!pZip->m_pState->m_pMem) - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - if (pWrite_buf) - pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); - - return status == TINFL_STATUS_DONE; -} - -mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) -{ - int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); - if (file_index < 0) - return MZ_FALSE; - return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) -{ - (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); -} - -mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) -{ - mz_bool status; - mz_zip_archive_file_stat file_stat; - MZ_FILE *pFile; - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - pFile = MZ_FOPEN(pDst_filename, "wb"); - if (!pFile) - return MZ_FALSE; - status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); - if (MZ_FCLOSE(pFile) == EOF) - return MZ_FALSE; -#ifndef MINIZ_NO_TIME - if (status) - mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); -#endif - return status; -} -#endif // #ifndef MINIZ_NO_STDIO - -mz_bool mz_zip_reader_end(mz_zip_archive *pZip) -{ - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return MZ_FALSE; - - if (pZip->m_pState) - { - mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; - mz_zip_array_clear(pZip, &pState->m_central_dir); - mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); - -#ifndef MINIZ_NO_STDIO - if (pState->m_pFile) - { - MZ_FCLOSE(pState->m_pFile); - pState->m_pFile = NULL; - } -#endif // #ifndef MINIZ_NO_STDIO - - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - } - pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; - - return MZ_TRUE; -} - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) -{ - int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); - if (file_index < 0) - return MZ_FALSE; - return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); -} -#endif - -// ------------------- .ZIP archive writing - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } -static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } -#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) -#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) - -mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) -{ - if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) - return MZ_FALSE; - - if (pZip->m_file_offset_alignment) - { - // Ensure user specified file offset alignment is a power of 2. - if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) - return MZ_FALSE; - } - - if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; - if (!pZip->m_pFree) pZip->m_pFree = def_free_func; - if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; - - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; - pZip->m_archive_size = existing_size; - pZip->m_central_directory_file_ofs = 0; - pZip->m_total_files = 0; - - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) - return MZ_FALSE; - memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); - return MZ_TRUE; -} - -static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) -{ - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_zip_internal_state *pState = pZip->m_pState; - mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); -#ifdef _MSC_VER - if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) -#else - if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) -#endif - return 0; - if (new_size > pState->m_mem_capacity) - { - void *pNew_block; - size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; - if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) - return 0; - pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; - } - memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); - pState->m_mem_size = (size_t)new_size; - return n; -} - -mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) -{ - pZip->m_pWrite = mz_zip_heap_write_func; - pZip->m_pIO_opaque = pZip; - if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) - return MZ_FALSE; - if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) - { - if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) - { - mz_zip_writer_end(pZip); - return MZ_FALSE; - } - pZip->m_pState->m_mem_capacity = initial_allocation_size; - } - return MZ_TRUE; -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) -{ - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) - return 0; - return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); -} - -mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) -{ - MZ_FILE *pFile; - pZip->m_pWrite = mz_zip_file_write_func; - pZip->m_pIO_opaque = pZip; - if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) - return MZ_FALSE; - if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) - { - mz_zip_writer_end(pZip); - return MZ_FALSE; - } - pZip->m_pState->m_pFile = pFile; - if (size_to_reserve_at_beginning) - { - mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); - do - { - size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) - { - mz_zip_writer_end(pZip); - return MZ_FALSE; - } - cur_ofs += n; size_to_reserve_at_beginning -= n; - } while (size_to_reserve_at_beginning); - } - return MZ_TRUE; -} -#endif // #ifndef MINIZ_NO_STDIO - -mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) -{ - mz_zip_internal_state *pState; - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return MZ_FALSE; - // No sense in trying to write to an archive that's already at the support max size - if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) - return MZ_FALSE; - - pState = pZip->m_pState; - - if (pState->m_pFile) - { -#ifdef MINIZ_NO_STDIO - pFilename; return MZ_FALSE; -#else - // Archive is being read from stdio - try to reopen as writable. - if (pZip->m_pIO_opaque != pZip) - return MZ_FALSE; - if (!pFilename) - return MZ_FALSE; - pZip->m_pWrite = mz_zip_file_write_func; - if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) - { - // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. - mz_zip_reader_end(pZip); - return MZ_FALSE; - } -#endif // #ifdef MINIZ_NO_STDIO - } - else if (pState->m_pMem) - { - // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. - if (pZip->m_pIO_opaque != pZip) - return MZ_FALSE; - pState->m_mem_capacity = pState->m_mem_size; - pZip->m_pWrite = mz_zip_heap_write_func; - } - // Archive is being read via a user provided read function - make sure the user has specified a write function too. - else if (!pZip->m_pWrite) - return MZ_FALSE; - - // Start writing new files at the archive's current central directory location. - pZip->m_archive_size = pZip->m_central_directory_file_ofs; - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; - pZip->m_central_directory_file_ofs = 0; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) -{ - return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); -} - -typedef struct -{ - mz_zip_archive *m_pZip; - mz_uint64 m_cur_archive_file_ofs; - mz_uint64 m_comp_size; -} mz_zip_writer_add_state; - -static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser) -{ - mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; - if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) - return MZ_FALSE; - pState->m_cur_archive_file_ofs += len; - pState->m_comp_size += len; - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) -{ - (void)pZip; - memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) -{ - (void)pZip; - memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) -{ - mz_zip_internal_state *pState = pZip->m_pState; - mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; - size_t orig_central_dir_size = pState->m_central_dir.m_size; - mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - - // No zip64 support yet - if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) - return MZ_FALSE; - - if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) - return MZ_FALSE; - - if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) - { - // Try to push the central directory array back into its original state. - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) -{ - // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. - if (*pArchive_name == '/') - return MZ_FALSE; - while (*pArchive_name) - { - if ((*pArchive_name == '\\') || (*pArchive_name == ':')) - return MZ_FALSE; - pArchive_name++; - } - return MZ_TRUE; -} - -static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) -{ - mz_uint32 n; - if (!pZip->m_file_offset_alignment) - return 0; - n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); - return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); -} - -static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) -{ - char buf[4096]; - memset(buf, 0, MZ_MIN(sizeof(buf), n)); - while (n) - { - mz_uint32 s = MZ_MIN(sizeof(buf), n); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) - return MZ_FALSE; - cur_file_ofs += s; n -= s; - } - return MZ_TRUE; -} - -mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) -{ - mz_uint16 method = 0, dos_time = 0, dos_date = 0; - mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; - mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; - size_t archive_name_size; - mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - tdefl_compressor *pComp = NULL; - mz_bool store_data_uncompressed; - mz_zip_internal_state *pState; - - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - level = level_and_flags & 0xF; - store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) - return MZ_FALSE; - - pState = pZip->m_pState; - - if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) - return MZ_FALSE; - // No zip64 support yet - if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) - return MZ_FALSE; - if (!mz_zip_writer_validate_archive_name(pArchive_name)) - return MZ_FALSE; - -#ifndef MINIZ_NO_TIME - { - time_t cur_time; time(&cur_time); - mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); - } -#endif // #ifndef MINIZ_NO_TIME - - archive_name_size = strlen(pArchive_name); - if (archive_name_size > 0xFFFF) - return MZ_FALSE; - - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) - return MZ_FALSE; - - if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) - { - // Set DOS Subdirectory attribute bit. - ext_attributes |= 0x10; - // Subdirectories cannot contain data. - if ((buf_size) || (uncomp_size)) - return MZ_FALSE; - } - - // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) - if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) - return MZ_FALSE; - - if ((!store_data_uncompressed) && (buf_size)) - { - if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) - return MZ_FALSE; - } - - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } - cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); - - MZ_CLEAR_OBJ(local_dir_header); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - cur_archive_file_ofs += archive_name_size; - - if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - { - uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); - uncomp_size = buf_size; - if (uncomp_size <= 3) - { - level = 0; - store_data_uncompressed = MZ_TRUE; - } - } - - if (store_data_uncompressed) - { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - - cur_archive_file_ofs += buf_size; - comp_size = buf_size; - - if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) - method = MZ_DEFLATED; - } - else if (buf_size) - { - mz_zip_writer_add_state state; - - state.m_pZip = pZip; - state.m_cur_archive_file_ofs = cur_archive_file_ofs; - state.m_comp_size = 0; - - if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || - (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - - comp_size = state.m_comp_size; - cur_archive_file_ofs = state.m_cur_archive_file_ofs; - - method = MZ_DEFLATED; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - pComp = NULL; - - // no zip64 support yet - if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) - return MZ_FALSE; - - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) - return MZ_FALSE; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) - return MZ_FALSE; - - if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) - return MZ_FALSE; - - pZip->m_total_files++; - pZip->m_archive_size = cur_archive_file_ofs; - - return MZ_TRUE; -} - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) -{ - mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; - mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; - mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; - size_t archive_name_size; - mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - MZ_FILE *pSrc_file = NULL; - - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - level = level_and_flags & 0xF; - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) - return MZ_FALSE; - if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) - return MZ_FALSE; - if (!mz_zip_writer_validate_archive_name(pArchive_name)) - return MZ_FALSE; - - archive_name_size = strlen(pArchive_name); - if (archive_name_size > 0xFFFF) - return MZ_FALSE; - - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) - return MZ_FALSE; - - if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) - return MZ_FALSE; - - pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); - if (!pSrc_file) - return MZ_FALSE; - MZ_FSEEK64(pSrc_file, 0, SEEK_END); - uncomp_size = MZ_FTELL64(pSrc_file); - MZ_FSEEK64(pSrc_file, 0, SEEK_SET); - - if (uncomp_size > 0xFFFFFFFF) - { - // No zip64 support yet - MZ_FCLOSE(pSrc_file); - return MZ_FALSE; - } - if (uncomp_size <= 3) - level = 0; - - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) - return MZ_FALSE; - local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } - cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); - - MZ_CLEAR_OBJ(local_dir_header); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) - { - MZ_FCLOSE(pSrc_file); - return MZ_FALSE; - } - cur_archive_file_ofs += archive_name_size; - - if (uncomp_size) - { - mz_uint64 uncomp_remaining = uncomp_size; - void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); - if (!pRead_buf) - { - MZ_FCLOSE(pSrc_file); - return MZ_FALSE; - } - - if (!level) - { - while (uncomp_remaining) - { - mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); - if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - MZ_FCLOSE(pSrc_file); - return MZ_FALSE; - } - uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); - uncomp_remaining -= n; - cur_archive_file_ofs += n; - } - comp_size = uncomp_size; - } - else - { - mz_bool result = MZ_FALSE; - mz_zip_writer_add_state state; - tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); - if (!pComp) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - MZ_FCLOSE(pSrc_file); - return MZ_FALSE; - } - - state.m_pZip = pZip; - state.m_cur_archive_file_ofs = cur_archive_file_ofs; - state.m_comp_size = 0; - - if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - MZ_FCLOSE(pSrc_file); - return MZ_FALSE; - } - - for ( ; ; ) - { - size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); - tdefl_status status; - - if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) - break; - - uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); - uncomp_remaining -= in_buf_size; - - status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); - if (status == TDEFL_STATUS_DONE) - { - result = MZ_TRUE; - break; - } - else if (status != TDEFL_STATUS_OKAY) - break; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - - if (!result) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - MZ_FCLOSE(pSrc_file); - return MZ_FALSE; - } - - comp_size = state.m_comp_size; - cur_archive_file_ofs = state.m_cur_archive_file_ofs; - - method = MZ_DEFLATED; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - } - - MZ_FCLOSE(pSrc_file); pSrc_file = NULL; - - // no zip64 support yet - if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) - return MZ_FALSE; - - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) - return MZ_FALSE; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) - return MZ_FALSE; - - if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) - return MZ_FALSE; - - pZip->m_total_files++; - pZip->m_archive_size = cur_archive_file_ofs; - - return MZ_TRUE; -} -#endif // #ifndef MINIZ_NO_STDIO - -mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) -{ - mz_uint n, bit_flags, num_alignment_padding_bytes; - mz_uint64 comp_bytes_remaining, local_dir_header_ofs; - mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; - mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - size_t orig_central_dir_size; - mz_zip_internal_state *pState; - void *pBuf; const mz_uint8 *pSrc_central_header; - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) - return MZ_FALSE; - if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) - return MZ_FALSE; - pState = pZip->m_pState; - - num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) - return MZ_FALSE; - - cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - cur_dst_file_ofs = pZip->m_archive_size; - - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return MZ_FALSE; - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return MZ_FALSE; - cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - - if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) - return MZ_FALSE; - cur_dst_file_ofs += num_alignment_padding_bytes; - local_dir_header_ofs = cur_dst_file_ofs; - if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return MZ_FALSE; - cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - - n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - - if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) - return MZ_FALSE; - - while (comp_bytes_remaining) - { - n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return MZ_FALSE; - } - cur_src_file_ofs += n; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return MZ_FALSE; - } - cur_dst_file_ofs += n; - - comp_bytes_remaining -= n; - } - - bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); - if (bit_flags & 8) - { - // Copy data descriptor - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return MZ_FALSE; - } - - n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return MZ_FALSE; - } - - cur_src_file_ofs += n; - cur_dst_file_ofs += n; - } - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - - // no zip64 support yet - if (cur_dst_file_ofs > 0xFFFFFFFF) - return MZ_FALSE; - - orig_central_dir_size = pState->m_central_dir.m_size; - - memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) - return MZ_FALSE; - - n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) - { - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return MZ_FALSE; - } - - if (pState->m_central_dir.m_size > 0xFFFFFFFF) - return MZ_FALSE; - n = (mz_uint32)pState->m_central_dir.m_size; - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) - { - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); - return MZ_FALSE; - } - - pZip->m_total_files++; - pZip->m_archive_size = cur_dst_file_ofs; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) -{ - mz_zip_internal_state *pState; - mz_uint64 central_dir_ofs, central_dir_size; - mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) - return MZ_FALSE; - - pState = pZip->m_pState; - - // no zip64 support yet - if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) - return MZ_FALSE; - - central_dir_ofs = 0; - central_dir_size = 0; - if (pZip->m_total_files) - { - // Write central directory - central_dir_ofs = pZip->m_archive_size; - central_dir_size = pState->m_central_dir.m_size; - pZip->m_central_directory_file_ofs = central_dir_ofs; - if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) - return MZ_FALSE; - pZip->m_archive_size += central_dir_size; - } - - // Write end of central directory record - MZ_CLEAR_OBJ(hdr); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); - MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) - return MZ_FALSE; -#ifndef MINIZ_NO_STDIO - if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) - return MZ_FALSE; -#endif // #ifndef MINIZ_NO_STDIO - - pZip->m_archive_size += sizeof(hdr); - - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; - return MZ_TRUE; -} - -mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) -{ - if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) - return MZ_FALSE; - if (pZip->m_pWrite != mz_zip_heap_write_func) - return MZ_FALSE; - if (!mz_zip_writer_finalize_archive(pZip)) - return MZ_FALSE; - - *pBuf = pZip->m_pState->m_pMem; - *pSize = pZip->m_pState->m_mem_size; - pZip->m_pState->m_pMem = NULL; - pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; - return MZ_TRUE; -} - -mz_bool mz_zip_writer_end(mz_zip_archive *pZip) -{ - mz_zip_internal_state *pState; - mz_bool status = MZ_TRUE; - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) - return MZ_FALSE; - - pState = pZip->m_pState; - pZip->m_pState = NULL; - mz_zip_array_clear(pZip, &pState->m_central_dir); - mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); - -#ifndef MINIZ_NO_STDIO - if (pState->m_pFile) - { - MZ_FCLOSE(pState->m_pFile); - pState->m_pFile = NULL; - } -#endif // #ifndef MINIZ_NO_STDIO - - if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) - { - pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); - pState->m_pMem = NULL; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; - return status; -} - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) -{ - mz_bool status, created_new_archive = MZ_FALSE; - mz_zip_archive zip_archive; - struct MZ_FILE_STAT_STRUCT file_stat; - MZ_CLEAR_OBJ(zip_archive); - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) - return MZ_FALSE; - if (!mz_zip_writer_validate_archive_name(pArchive_name)) - return MZ_FALSE; - if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) - { - // Create a new archive. - if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) - return MZ_FALSE; - created_new_archive = MZ_TRUE; - } - else - { - // Append to an existing archive. - if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) - return MZ_FALSE; - if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) - { - mz_zip_reader_end(&zip_archive); - return MZ_FALSE; - } - } - status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); - // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) - if (!mz_zip_writer_finalize_archive(&zip_archive)) - status = MZ_FALSE; - if (!mz_zip_writer_end(&zip_archive)) - status = MZ_FALSE; - if ((!status) && (created_new_archive)) - { - // It's a new archive and something went wrong, so just delete it. - int ignoredStatus = MZ_DELETE_FILE(pZip_filename); - (void)ignoredStatus; - } - return status; -} - -void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) -{ - int file_index; - mz_zip_archive zip_archive; - void *p = NULL; - - if (pSize) - *pSize = 0; - - if ((!pZip_filename) || (!pArchive_name)) - return NULL; - - MZ_CLEAR_OBJ(zip_archive); - if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) - return NULL; - - if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) - p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); - - mz_zip_reader_end(&zip_archive); - return p; -} - -#endif // #ifndef MINIZ_NO_STDIO - -#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -#endif // #ifndef MINIZ_NO_ARCHIVE_APIS - -#ifdef __cplusplus -} -#endif - -#endif // MINIZ_HEADER_FILE_ONLY - -/* - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - - For more information, please refer to -*/ diff --git a/Core/Code/CppMicroServices/tools/usResourceCompiler.cpp b/Core/Code/CppMicroServices/tools/usResourceCompiler.cpp deleted file mode 100644 index 443cd9c46f..0000000000 --- a/Core/Code/CppMicroServices/tools/usResourceCompiler.cpp +++ /dev/null @@ -1,827 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#include "usConfig.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "stdint_p.h" - -#include "usConfig.h" - -#ifdef US_ENABLE_RESOURCE_COMPRESSION -extern "C" { -const char* us_resource_compressor_error(); -unsigned char* us_resource_compressor(FILE*, long, int level, long* out_size); -} -#endif // US_ENABLE_RESOURCE_COMPRESSION - -#ifdef US_PLATFORM_WINDOWS -static const char DIR_SEP = '\\'; -#else -static const char DIR_SEP = '/'; -#endif - -class ResourceWriter; - -class Resource -{ - -public: - - enum Flags - { - NoFlags = 0x00, - Directory = 0x01, - Compressed = 0x02 - }; - - Resource(const std::string& name, const std::string& path = std::string(), unsigned int flags = NoFlags); - ~Resource(); - - std::string GetResourcePath() const; - - int64_t WriteName(ResourceWriter& writer, int64_t offset); - void WriteTreeInfo(ResourceWriter& writer); - int64_t WritePayload(ResourceWriter& writer, int64_t offset, std::string* errorMessage); - - std::string name; - std::string path; - unsigned int flags; - Resource* parent; - std::map children; - std::map sortedChildren; - - int64_t nameOffset; - int64_t dataOffset; - int64_t childOffset; - -}; - -class ResourceWriter -{ - -public: - - ResourceWriter(const std::string& fileName, const std::string& libName, - int compressionLevel, int compressionThreshold); - ~ResourceWriter(); - - bool AddFiles(const std::vector& files, const std::string& basePath); - bool Write(); - -private: - - friend class Resource; - - bool AddFile(const std::string& alias, const Resource& file); - - bool WriteHeader(); - bool WritePayloads(); - bool WriteNames(); - bool WriteDataTree(); - bool WriteRegistrationCode(); - - void WriteString(const std::string& str); - void WriteChar(char c); - void WriteHex(uint8_t tmp); - void WriteNumber2(uint16_t number); - void WriteNumber4(uint32_t number); - - std::ofstream out; - std::vector files; - - std::string libName; - std::string fileName; - - int compressionLevel; - int compressionThreshold; - - Resource* root; -}; - -Resource::Resource(const std::string& name, const std::string& path, unsigned int flags) - : name(name) - , path(path) - , flags(flags) - , parent(NULL) - , nameOffset(0) - , dataOffset(0) - , childOffset(0) -{ -} - -Resource::~Resource() -{ - for (std::map::iterator i = children.begin(); - i != children.end(); ++i) - { - delete i->second; - } -} - -std::string Resource::GetResourcePath() const -{ - std::string resource = name; - for (Resource* p = parent; p; p = p->parent) - { - resource = resource.insert(0, p->name + '/'); - } - return resource; -} - -int64_t Resource::WriteName(ResourceWriter& writer, int64_t offset) -{ - // capture the offset - nameOffset = offset; - - // write the resource name as a comment - writer.WriteString(" // "); - writer.WriteString(name); - writer.WriteString("\n "); - - // write the length of the name - writer.WriteNumber2(static_cast(name.size())); - writer.WriteString("\n "); - offset += 2; - - // write the hash value - writer.WriteNumber4(static_cast(US_HASH_FUNCTION_NAMESPACE::US_HASH_FUNCTION(std::string, name))); - writer.WriteString("\n "); - offset += 4; - - // write the name itself - for (std::size_t i = 0; i < name.length(); ++i) - { - writer.WriteHex(name[i]); - if (i != 0 && i % 32 == 0) - writer.WriteString("\n "); - } - offset += name.length(); - - // done - writer.WriteString("\n "); - return offset; -} - -void Resource::WriteTreeInfo(ResourceWriter& writer) -{ - // write the resource path as a comment - writer.WriteString(" // "); - writer.WriteString(GetResourcePath()); - writer.WriteString("\n "); - - if (flags & Directory) - { - // name offset (in the us_resource_name array) - writer.WriteNumber4(static_cast(nameOffset)); - - // flags - writer.WriteNumber2(flags); - - // child count - writer.WriteNumber4(static_cast(children.size())); - - // first child offset (in the us_resource_tree array) - writer.WriteNumber4(static_cast(childOffset)); - } - else - { - // name offset - writer.WriteNumber4(static_cast(nameOffset)); - - // flags - writer.WriteNumber2(flags); - - // padding (not used) - writer.WriteNumber4(0); - - // data offset - writer.WriteNumber4(static_cast(dataOffset)); - } - writer.WriteChar('\n'); -} - -int64_t Resource::WritePayload(ResourceWriter& writer, int64_t offset, std::string* errorMessage) -{ - // capture the offset - dataOffset = offset; - - // open the resource file on the file system - FILE* file = fopen(path.c_str(), "rb"); - if (!file) - { - *errorMessage = "File could not be opened: " + path; - return 0; - } - - // get the file size - fseek(file, 0, SEEK_END); - const long fileSize = ftell(file); - fseek(file, 0, SEEK_SET); - - unsigned char* fileBuffer = NULL; - long fileBufferSize = 0; - -#ifdef US_ENABLE_RESOURCE_COMPRESSION - // try compression - if (writer.compressionLevel != 0 && fileSize != 0) - { - long compressedSize = 0; - unsigned char* compressedBuffer = us_resource_compressor(file, fileSize, writer.compressionLevel, &compressedSize); - if (compressedBuffer == NULL) - { - *errorMessage = us_resource_compressor_error(); - return 0; - } - - int compressRatio = static_cast((100.0 * (fileSize - compressedSize)) / fileSize); - if (compressRatio >= writer.compressionThreshold) - { - fileBuffer = compressedBuffer; - fileBufferSize = compressedSize; - flags |= Compressed; - } - else - { - free(compressedBuffer); - } - } - - if (!(flags & Compressed)) -#endif // US_ENABLE_RESOURCE_COMPRESSION - { - fileBuffer = static_cast(malloc(sizeof(unsigned char)*fileSize)); - if (fileBuffer == NULL) - { - *errorMessage = "Could not allocate memory buffer for resource file " + path; - return 0; - } - if (fseek(file, 0, SEEK_SET) != 0) - { - free(fileBuffer); - *errorMessage = "Could not set stream position for resource file " + path; - return 0; - } - if (fread(fileBuffer, 1, fileSize, file) != static_cast(fileSize)) - { - free(fileBuffer); - *errorMessage = "Error reading resource file " + path; - return 0; - } - fileBufferSize = fileSize; - } - - if (fclose(file)) - { - *errorMessage = "Error closing resource file " + path; - free(fileBuffer); - return 0; - } - - // write the full path of the resource in the file system as a comment - writer.WriteString(" // "); - writer.WriteString(path); - writer.WriteString("\n "); - - // write the length - writer.WriteNumber4(static_cast(fileBufferSize)); - writer.WriteString("\n "); - offset += 4; - - // write the actual payload - int charsLeft = 16; - for (long i = 0; i < fileBufferSize; ++i) - { - --charsLeft; - writer.WriteHex(static_cast(fileBuffer[i])); - if (charsLeft == 0) - { - writer.WriteString("\n "); - charsLeft = 16; - } - } - - offset += fileBufferSize; - - free(fileBuffer); - - // done - writer.WriteString("\n "); - return offset; -} - -ResourceWriter::ResourceWriter(const std::string& fileName, const std::string& libName, - int compressionLevel, int compressionThreshold) - : libName(libName) - , fileName(fileName) - , compressionLevel(compressionLevel) - , compressionThreshold(compressionThreshold) - , root(NULL) -{ - out.exceptions(std::ofstream::goodbit); - out.open(fileName.c_str()); -} - -ResourceWriter::~ResourceWriter() -{ - delete root; -} - -bool ResourceWriter::AddFiles(const std::vector& files, const std::string& basePath) -{ - bool success = true; - for (std::size_t i = 0; i < files.size(); ++i) - { - const std::string& file = files[i]; - if (file.size() <= basePath.size() || file.substr(0, basePath.size()) != basePath) - { - std::cerr << "File " << file << " is not an absolute path starting with " << basePath << std::endl; - success = false; - } - else - { - const std::string relativePath = file.substr(basePath.size()); - std::string name = relativePath; - std::size_t index = relativePath.find_last_of(DIR_SEP); - if (index != std::string::npos) - { - name = relativePath.substr(index+1); - } - success &= AddFile(relativePath, Resource(name, file)); - } - } - return success; -} - -bool ResourceWriter::Write() -{ - if (!WriteHeader()) - { - std::cerr << "Could not write header." << std::endl; - return false; - } - if (!WritePayloads()) - { - std::cerr << "Could not write data blobs." << std::endl; - return false; - } - if (!WriteNames()) - { - std::cerr << "Could not write file names." << std::endl; - return false; - } - if (!WriteDataTree()) - { - std::cerr << "Could not write data tree." << std::endl; - return false; - } - if (!WriteRegistrationCode()) - { - std::cerr << "Could not write footer" << std::endl; - return false; - } - - return true; -} - -bool ResourceWriter::AddFile(const std::string& alias, const Resource& file) -{ - std::ifstream in(file.path.c_str(), std::ifstream::in | std::ifstream::binary); - if (!in) - { - std::cerr << "File could not be opened: " << file.path << std::endl; - return false; - } - in.seekg(0, std::ifstream::end); - std::ifstream::pos_type size = in.tellg(); - in.close(); - - if (size > 0xffffffff) - { - std::cerr << "File too big: " << file.path << std::endl; - return false; - } - - if (!root) - { - root = new Resource(std::string(), std::string(), Resource::Directory); - } - - Resource* parent = root; - std::stringstream ss(alias); - std::vector nodes; - { - std::string node; - while (std::getline(ss, node, DIR_SEP)) - { - if (node.empty()) - continue; - nodes.push_back(node); - } - } - - for(std::size_t i = 0; i < nodes.size()-1; ++i) - { - const std::string& node = nodes[i]; - if (parent->children.find(node) == parent->children.end()) - { - Resource* s = new Resource(node, std::string(), Resource::Directory); - s->parent = parent; - parent->children.insert(std::make_pair(node, s)); - parent->sortedChildren.insert(std::make_pair(static_cast(US_HASH_FUNCTION_NAMESPACE::US_HASH_FUNCTION(std::string, node)), s)); - parent = s; - } - else - { - parent = parent->children[node]; - } - } - - const std::string filename = nodes.back(); - Resource* s = new Resource(file); - s->parent = parent; - parent->children.insert(std::make_pair(filename, s)); - parent->sortedChildren.insert(std::make_pair(static_cast(US_HASH_FUNCTION_NAMESPACE::US_HASH_FUNCTION(std::string, filename)), s)); - return true; -} - -bool ResourceWriter::WriteHeader() -{ - std::stringstream ss; - std::time_t now = time(0); - ss << std::ctime(&now); - - WriteString("/*=============================================================================\n"); - WriteString(" Resource object code\n"); - WriteString("\n"); - WriteString(" Created: "); - WriteString(ss.str()); - WriteString(" by: The Resource Compiler for CppMicroServices version "); - WriteString(CppMicroServices_VERSION_STR); - WriteString("\n\n"); - WriteString(" WARNING! All changes made in this file will be lost!\n"); - WriteString( "=============================================================================*/\n\n"); - WriteString("#include \n"); - WriteString("#include \n\n"); - return true; -} - -bool ResourceWriter::WritePayloads() -{ - if (!root) - return false; - - WriteString("static const unsigned char us_resource_data[] = {\n"); - std::stack pending; - - pending.push(root); - int64_t offset = 0; - std::string errorMessage; - while (!pending.empty()) - { - Resource* file = pending.top(); - pending.pop(); - for (std::map::iterator i = file->children.begin(); - i != file->children.end(); ++i) - { - Resource* child = i->second; - if (child->flags & Resource::Directory) - { - pending.push(child); - } - else - { - offset = child->WritePayload(*this, offset, &errorMessage); - if (offset == 0) - { - std::cerr << errorMessage << std::endl; - return false; - } - } - } - } - WriteString("\n};\n\n"); - return true; -} - -bool ResourceWriter::WriteNames() -{ - if (!root) - return false; - - WriteString("static const unsigned char us_resource_name[] = {\n"); - - std::map names; - std::stack pending; - - pending.push(root); - int64_t offset = 0; - while (!pending.empty()) - { - Resource* file = pending.top(); - pending.pop(); - for (std::map::iterator it = file->children.begin(); - it != file->children.end(); ++it) - { - Resource* child = it->second; - if (child->flags & Resource::Directory) - { - pending.push(child); - } - if (names.find(child->name) != names.end()) - { - child->nameOffset = names[child->name]; - } - else - { - names.insert(std::make_pair(child->name, offset)); - offset = child->WriteName(*this, offset); - } - } - } - WriteString("\n};\n\n"); - return true; -} - -bool ResourceWriter::WriteDataTree() -{ - if (!root) - return false; - - WriteString("static const unsigned char us_resource_tree[] = {\n"); - std::stack pending; - - // calculate the child offsets in the us_resource_tree array - pending.push(root); - int offset = 1; - while (!pending.empty()) - { - Resource* file = pending.top(); - pending.pop(); - file->childOffset = offset; - - // calculate the offset now - for (std::map::iterator i = file->sortedChildren.begin(); - i != file->sortedChildren.end(); ++i) - { - Resource* child = i->second; - ++offset; - if (child->flags & Resource::Directory) - { - pending.push(child); - } - } - } - - // write the tree structure - pending.push(root); - root->WriteTreeInfo(*this); - while (!pending.empty()) - { - Resource *file = pending.top(); - pending.pop(); - - // write the actual data now - for (std::map::iterator i = file->sortedChildren.begin(); - i != file->sortedChildren.end(); ++i) - { - Resource *child = i->second; - child->WriteTreeInfo(*this); - if (child->flags & Resource::Directory) - { - pending.push(child); - } - } - } - WriteString("\n};\n\n"); - - return true; -} - -bool ResourceWriter::WriteRegistrationCode() -{ - WriteString("US_BEGIN_NAMESPACE\n\n"); - WriteString("extern US_EXPORT bool RegisterResourceData(int, ModuleInfo*, ModuleInfo::ModuleResourceData, ModuleInfo::ModuleResourceData, ModuleInfo::ModuleResourceData);\n\n"); - WriteString("US_END_NAMESPACE\n\n"); - - WriteString(std::string("extern \"C\" US_ABI_EXPORT int _us_init_resources_") + libName + - "(US_PREPEND_NAMESPACE(ModuleInfo)* moduleInfo)\n"); - WriteString("{\n"); - WriteString(" US_PREPEND_NAMESPACE(RegisterResourceData)(0x01, moduleInfo, us_resource_tree, us_resource_name, us_resource_data);\n"); - WriteString(" return 1;\n"); - WriteString("}\n"); - - return true; -} - -void ResourceWriter::WriteString(const std::string& str) -{ - out << str; -} - -void ResourceWriter::WriteChar(char c) -{ - out << c; -} - -void ResourceWriter::WriteHex(uint8_t tmp) -{ - const char* const digits = "0123456789abcdef"; - WriteChar('0'); - WriteChar('x'); - if (tmp < 16) - { - WriteChar(digits[tmp]); - } - else - { - WriteChar(digits[tmp >> 4]); - WriteChar(digits[tmp & 0xf]); - } - WriteChar(','); -} - -void ResourceWriter::WriteNumber2(uint16_t number) -{ - WriteHex(number >> 8); - WriteHex(static_cast(number)); -} - -void ResourceWriter::WriteNumber4(uint32_t number) -{ - WriteHex(number >> 24); - WriteHex(number >> 16); - WriteHex(number >> 8); - WriteHex(number); -} - - -#ifdef US_PLATFORM_POSIX -#include -std::string GetCurrentDir() -{ - char currDir[512]; - if (!getcwd(currDir, sizeof(currDir))) - { - std::cerr << "Getting the current directory failed." << std::endl; - exit(EXIT_FAILURE); - } - return std::string(currDir); -} - -bool IsAbsolutePath(const std::string& path) -{ - return path.find_first_of('/') == 0; -} -#else -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include -std::string GetCurrentDir() -{ - TCHAR currDir[512]; - DWORD dwRet; - dwRet = GetCurrentDirectory(sizeof(currDir), currDir); - - if( dwRet == 0 || dwRet > 512) - { - std::cerr << "Getting the current directory failed." << std::endl; - exit(EXIT_FAILURE); - } - return std::string(currDir); -} - -bool IsAbsolutePath(const std::string& path) -{ - return !PathIsRelative(path.c_str()); -} -#endif - -int main(int argc, char** argv) -{ - if (argc < 4) - { - std::cout << US_RCC_EXECUTABLE_NAME " - A resource compiler for C++ Micro Services modules\n" - "\n" - "Usage: " US_RCC_EXECUTABLE_NAME " LIBNAME OUTPUT INPUT... " - "[-c COMPRESSION_LEVEL] [-t COMPRESSION_THRESHOLD] [-d ROOT_DIR INPUT...]...\n\n" - "Convert all INPUT files into hex code written to OUTPUT.\n" - "\n" - " LIBNAME The modules library name as it is specified in the US_INITIALIZE_MODULE macro\n" - " OUTPUT Absolute path for the generated source file\n" - " INPUT Path to the resource file, relative to the current working directory or" - " the preceeding ROOT_DIR argument\n" - " -c The Zip compression level (0-9) or -1 [defaults to -1, the default level]\n" - " -t Size reduction threshold (0-100) to trigger compression [defaults to 30]\n" - " -d Absolute path to a directory containing resource files. All following INPUT" - " files must be relative to this root path\n"; - exit(EXIT_SUCCESS); - } - - std::string libName(argv[1]); - std::string fileName(argv[2]); - - // default zlib compression level - int compressionLevel = -1; - - // use compressed data if 30% reduction or better - int compressionThreshold = 30; - - std::map > inputFiles; - inputFiles.insert(std::make_pair(GetCurrentDir(), std::vector())); - - std::vector* currFiles = &inputFiles.begin()->second; - std::string currRootDir = inputFiles.begin()->first; - for (int i = 3; i < argc; i++) - { - if (std::strcmp(argv[i], "-d") == 0) - { - if (i == argc-1) - { - std::cerr << "No argument after -d given." << std::endl; - exit(EXIT_FAILURE); - } - currRootDir = argv[++i]; - inputFiles.insert(std::make_pair(currRootDir, std::vector())); - currFiles = &inputFiles[currRootDir]; - } - else if(std::strcmp(argv[i], "-c") == 0) - { - if (i == argc-1) - { - std::cerr << "No argument after -c given." << std::endl; - exit(EXIT_FAILURE); - } - compressionLevel = atoi(argv[++i]); - if (compressionLevel < -1 || compressionLevel > 10) - { - compressionLevel = -1; - } - } - else if(std::strcmp(argv[i], "-t") == 0) - { - if (i == argc-1) - { - std::cerr << "No argument after -t given." << std::endl; - exit(EXIT_FAILURE); - } - compressionThreshold = atoi(argv[++i]); - } - else - { - const std::string inputFile = argv[i]; - if (IsAbsolutePath(inputFile)) - { - currFiles->push_back(inputFile); - } - else - { - currFiles->push_back(currRootDir + DIR_SEP + inputFile); - } - } - } - - ResourceWriter writer(fileName, libName, compressionLevel, compressionThreshold); - for(std::map >::iterator i = inputFiles.begin(); - i != inputFiles.end(); ++i) - { - if (i->second.empty()) continue; - - if (!writer.AddFiles(i->second, i->first)) - { - return EXIT_FAILURE; - } - } - - return writer.Write() ? EXIT_SUCCESS : EXIT_FAILURE; -} diff --git a/Core/Code/CppMicroServices/tools/usResourceCompressor.c b/Core/Code/CppMicroServices/tools/usResourceCompressor.c deleted file mode 100644 index 31e0ec28d6..0000000000 --- a/Core/Code/CppMicroServices/tools/usResourceCompressor.c +++ /dev/null @@ -1,141 +0,0 @@ -/*============================================================================= - - Library: CppMicroServices - - Copyright (c) German Cancer Research Center, - Division of Medical and Biological Informatics - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -=============================================================================*/ - -#define MINIZ_NO_TIME -#define MINIZ_NO_ARCHIVE_APIS -#include "miniz.c" - -#include -#include - -typedef unsigned char uint8; -typedef unsigned int uint; - -#define COMPRESS_MSG_BUFFER_SIZE 1024 -static char us_compress_error[COMPRESS_MSG_BUFFER_SIZE]; - -#define my_max(a,b) (((a) > (b)) ? (a) : (b)) -#define my_min(a,b) (((a) < (b)) ? (a) : (b)) - -#define BUF_SIZE (1024 * 1024) -static uint8 s_inbuf[BUF_SIZE]; - - -const char* us_resource_compressor_error() -{ - return us_compress_error; -} - -unsigned char* us_resource_compressor(FILE* pInfile, long file_loc, int level, long* out_size) -{ - const uint infile_size = (uint)file_loc; - z_stream stream; - uint infile_remaining = infile_size; - long bytes_written = 0; - unsigned char* s_outbuf = NULL; - - memset(us_compress_error, 0, COMPRESS_MSG_BUFFER_SIZE); - - if (file_loc < 0 || file_loc > INT_MAX) - { - sprintf(us_compress_error, "Resource too large to be processed."); - return NULL; - } - - s_outbuf = (unsigned char*)malloc(sizeof(unsigned char)*(infile_size+4)); - if (s_outbuf == NULL) - { - sprintf(us_compress_error, "Failed to allocate %d bytes for compression buffer.", infile_size); - return NULL; - } - - // Init the z_stream - memset(&stream, 0, sizeof(stream)); - stream.next_in = s_inbuf; - stream.avail_in = 0; - stream.next_out = s_outbuf+4; - stream.avail_out = infile_size; - - // Compression. - if (deflateInit2(&stream, level, MZ_DEFLATED, -MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY) != Z_OK) - { - sprintf(us_compress_error, "deflateInit() failed."); - free(s_outbuf); - return NULL; - } - - // Write the uncompressed file size in the first four bytes - s_outbuf[0] = (unsigned char)((file_loc & 0xff000000) >> 24); - s_outbuf[1] = (unsigned char)((file_loc & 0x00ff0000) >> 16); - s_outbuf[2] = (unsigned char)((file_loc & 0x0000ff00) >> 8); - s_outbuf[3] = (unsigned char)(file_loc & 0x000000ff); - - bytes_written = 4; - for ( ; ; ) - { - int status; - if (!stream.avail_in) - { - // Input buffer is empty, so read more bytes from input file. - uint n = my_min(BUF_SIZE, infile_remaining); - - if (fread(s_inbuf, 1, n, pInfile) != n) - { - sprintf(us_compress_error, "Failed reading from input file."); - free(s_outbuf); - return NULL; - } - - stream.next_in = s_inbuf; - stream.avail_in = n; - - infile_remaining -= n; - } - - status = deflate(&stream, infile_remaining ? Z_NO_FLUSH : Z_FINISH); - - if ((status == Z_STREAM_END) || (!stream.avail_out)) - { - // Output buffer is full, or compression is done. - bytes_written += infile_size - stream.avail_out; - break; - } - else if (status != Z_OK) - { - sprintf(us_compress_error, "deflate() failed with status %i.", status); - free(s_outbuf); - return NULL; - } - } - - if (deflateEnd(&stream) != Z_OK) - { - sprintf(us_compress_error, "deflateEnd() failed."); - free(s_outbuf); - return NULL; - } - - if (out_size != NULL) - { - *out_size = bytes_written; - } - return s_outbuf; -} diff --git a/Core/Code/CppMicroServices/usConfig.h.in b/Core/Code/CppMicroServices/usConfig.h.in deleted file mode 100644 index 9489a2ccc3..0000000000 --- a/Core/Code/CppMicroServices/usConfig.h.in +++ /dev/null @@ -1,252 +0,0 @@ -/* - USCONFIG.h - this file is generated. Do not change! -*/ - -#ifndef USCONFIG_H -#define USCONFIG_H - -#cmakedefine US_BUILD_SHARED_LIBS -#cmakedefine CppMicroServices_EXPORTS -#cmakedefine US_ENABLE_AUTOLOADING_SUPPORT -#cmakedefine US_ENABLE_THREADING_SUPPORT -#cmakedefine US_ENABLE_SERVICE_FACTORY_SUPPORT -#cmakedefine US_ENABLE_RESOURCE_COMPRESSION -#cmakedefine US_USE_CXX11 - -///------------------------------------------------------------------- -// Version information -//------------------------------------------------------------------- - -#define CppMicroServices_VERSION_MAJOR @CppMicroServices_VERSION_MAJOR@ -#define CppMicroServices_VERSION_MINOR @CppMicroServices_VERSION_MINOR@ -#define CppMicroServices_VERSION_PATH @CppMicroServices_VERSION_PATCH@ -#define CppMicroServices_VERSION @CppMicroServices_VERSION@ -#define CppMicroServices_VERSION_STR "@CppMicroServices_VERSION@" - -///------------------------------------------------------------------- -// Macros used by the unit tests -//------------------------------------------------------------------- - -#define CppMicroServices_SOURCE_DIR "@CppMicroServices_SOURCE_DIR@" - -///------------------------------------------------------------------- -// Macros for import/export declarations -//------------------------------------------------------------------- - -#if defined(WIN32) - #define US_ABI_EXPORT __declspec(dllexport) - #define US_ABI_IMPORT __declspec(dllimport) - #define US_ABI_LOCAL -#else - #if __GNUC__ >= 4 - #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 -#endif - -#ifdef US_BUILD_SHARED_LIBS - // We are building a shared lib - #ifdef CppMicroServices_EXPORTS - #define US_EXPORT US_ABI_EXPORT - #else - #define US_EXPORT US_ABI_IMPORT - #endif -#else - // We are building a static lib - #if __GNUC__ >= 4 - // Don't hide RTTI symbols of definitions in the C++ Micro Services - // headers that are included in DSOs with hidden visibility - #define US_EXPORT US_ABI_EXPORT - #else - #define US_EXPORT - #endif -#endif - -//------------------------------------------------------------------- -// 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 */ - -#define US_BASECLASS_NAME @US_BASECLASS_NAME@ -#define US_BASECLASS_HEADER <@US_BASECLASS_HEADER@> - -// base class forward declaration -@US_BASECLASS_FORWARD_DECLARATION@ - -//------------------------------------------------------------------- -// 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 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) - -//------------------------------------------------------------------- -// Debuging & Logging -//------------------------------------------------------------------- - -#cmakedefine US_ENABLE_DEBUG_OUTPUT - -US_BEGIN_NAMESPACE - enum MsgType { DebugMsg = 0, InfoMsg = 1, WarningMsg = 2, ErrorMsg = 3 }; - typedef void (*MsgHandler)(MsgType, const char *); - US_EXPORT MsgHandler installMsgHandler(MsgHandler); -US_END_NAMESPACE - -//------------------------------------------------------------------- -// Hash Container -//------------------------------------------------------------------- - -#ifdef US_USE_CXX11 - - #include - #include - - #define US_HASH_FUNCTION_BEGIN(type) \ - template<> \ - struct hash : std::unary_function { \ - std::size_t operator()(const type& arg) const { - - #define US_HASH_FUNCTION_END } }; - - #define US_HASH_FUNCTION(type, arg) hash()(arg) - - #if defined(US_PLATFORM_WINDOWS) && (_MSC_VER < 1700) - #define US_HASH_FUNCTION_FRIEND(type) friend class ::std::hash - #else - #define US_HASH_FUNCTION_FRIEND(type) friend struct ::std::hash - #endif - - #define US_UNORDERED_MAP_TYPE ::std::unordered_map - #define US_UNORDERED_SET_TYPE ::std::unordered_set - - #define US_HASH_FUNCTION_NAMESPACE ::std - #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace std { - #define US_HASH_FUNCTION_NAMESPACE_END } - -#elif defined(__GNUC__) - - #include - #include - - #define US_HASH_FUNCTION_BEGIN(type) \ - template<> \ - struct hash : std::unary_function { \ - std::size_t operator()(const type& arg) const { - - #define US_HASH_FUNCTION_END } }; - - #define US_HASH_FUNCTION(type, arg) hash()(arg) - #define US_HASH_FUNCTION_FRIEND(type) friend struct ::std::tr1::hash - - #define US_UNORDERED_MAP_TYPE ::std::tr1::unordered_map - #define US_UNORDERED_SET_TYPE ::std::tr1::unordered_set - - #define US_HASH_FUNCTION_NAMESPACE ::std::tr1 - #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace std { namespace tr1 { - #define US_HASH_FUNCTION_NAMESPACE_END }} - -#elif _MSC_VER <= 1500 // Visual Studio 2008 and lower - - #include - #include - - #define US_HASH_FUNCTION_BEGIN(type) \ - template<> \ - inline std::size_t hash_value(const type& arg) { - - #define US_HASH_FUNCTION_END } - - #define US_HASH_FUNCTION(type, arg) hash_value(arg) - #define US_HASH_FUNCTION_FRIEND(type) friend std::size_t stdext::hash_value(const type&) - - #define US_UNORDERED_MAP_TYPE ::stdext::hash_map - #define US_UNORDERED_SET_TYPE ::stdext::hash_set - - #define US_HASH_FUNCTION_NAMESPACE ::stdext - #define US_HASH_FUNCTION_NAMESPACE_BEGIN namespace stdext { - #define US_HASH_FUNCTION_NAMESPACE_END } - -#endif - - -//------------------------------------------------------------------- -// Threading Configuration -//------------------------------------------------------------------- - -#ifdef US_ENABLE_THREADING_SUPPORT - #define US_DEFAULT_THREADING US_PREPEND_NAMESPACE(MultiThreaded) -#else - #define US_DEFAULT_THREADING US_PREPEND_NAMESPACE(SingleThreaded) -#endif - -//------------------------------------------------------------------- -// Header Availability -//------------------------------------------------------------------- - -#cmakedefine HAVE_STDINT - -#endif // USCONFIG_H diff --git a/Core/Code/DataManagement/mitkApplicationCursor.cpp b/Core/Code/DataManagement/mitkApplicationCursor.cpp index a4de3a11aa..8400f73cab 100644 --- a/Core/Code/DataManagement/mitkApplicationCursor.cpp +++ b/Core/Code/DataManagement/mitkApplicationCursor.cpp @@ -1,115 +1,112 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkApplicationCursor.h" #include #include -//us -#include "mitkModuleResource.h" - mitk::ApplicationCursorImplementation* mitk::ApplicationCursor::m_Implementation = NULL; namespace mitk { ApplicationCursor::ApplicationCursor() { } ApplicationCursor* ApplicationCursor::GetInstance() { static ApplicationCursor* m_Instance = NULL; if (!m_Instance) { m_Instance = new ApplicationCursor(); } return m_Instance; } void ApplicationCursor::RegisterImplementation(ApplicationCursorImplementation* implementation) { m_Implementation = implementation; } -void ApplicationCursor::PushCursor(const ModuleResource resource, int hotspotX, int hotspotY) +void ApplicationCursor::PushCursor(std::istream& cursor, int hotspotX, int hotspotY) { if (m_Implementation) { - m_Implementation->PushCursor(resource, hotspotX, hotspotY); + m_Implementation->PushCursor(cursor, hotspotX, hotspotY); } else { MITK_ERROR << "in mitk::ApplicationCursor::PushCursor(): no implementation registered." << std::endl; throw std::logic_error("No implementation registered for mitk::ApplicationCursor."); } } void ApplicationCursor::PushCursor(const char* XPM[], int hotspotX, int hotspotY) { if (m_Implementation) { m_Implementation->PushCursor(XPM, hotspotX, hotspotY); } else { MITK_ERROR << "in mitk::ApplicationCursor::PushCursor(): no implementation registered." << std::endl; throw std::logic_error("No implementation registered for mitk::ApplicationCursor."); } } void ApplicationCursor::PopCursor() { if (m_Implementation) { m_Implementation->PopCursor(); } else { MITK_ERROR << "in mitk::ApplicationCursor::PopCursor(): no implementation registered." << std::endl; throw std::logic_error("No implementation registered for mitk::ApplicationCursor."); } } const Point2I ApplicationCursor::GetCursorPosition() { if (m_Implementation) { return m_Implementation->GetCursorPosition(); } else { MITK_ERROR << "in mitk::ApplicationCursor::GetCursorPosition(): no implementation registered." << std::endl; throw std::logic_error("No implementation registered for mitk::ApplicationCursor."); } } void ApplicationCursor::SetCursorPosition(const Point2I& p) { if (m_Implementation) { m_Implementation->SetCursorPosition(p); } else { MITK_ERROR << "in mitk::ApplicationCursor::SetCursorPosition(): no implementation registered." << std::endl; throw std::logic_error("No implementation registered for mitk::ApplicationCursor."); } } } // namespace diff --git a/Core/Code/DataManagement/mitkApplicationCursor.h b/Core/Code/DataManagement/mitkApplicationCursor.h index 341a93ad22..780cf7d945 100644 --- a/Core/Code/DataManagement/mitkApplicationCursor.h +++ b/Core/Code/DataManagement/mitkApplicationCursor.h @@ -1,111 +1,109 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITK_APPLICATION_CURSOR_H_DEFINED_AND_ALL_IS_GOOD #define MITK_APPLICATION_CURSOR_H_DEFINED_AND_ALL_IS_GOOD #include #include "mitkVector.h" namespace mitk { -class ModuleResource; - /*! \brief Toolkit specific implementation of mitk::ApplicationCursor For any toolkit, this class has to be sub-classed. One instance of that sub-class has to be registered with mitk::ApplicationCursor. See the (very simple) implmentation of QmitkApplicationCursor for an example. */ class MITK_CORE_EXPORT ApplicationCursorImplementation { public: /// Change the current application cursor virtual void PushCursor(const char* XPM[], int hotspotX, int hotspotY) = 0; /// Change the current application cursor - virtual void PushCursor(const ModuleResource, int hotspotX, int hotspotY) = 0; + virtual void PushCursor(std::istream&, int hotspotX, int hotspotY) = 0; /// Restore the previous cursor virtual void PopCursor() = 0; /// Get absolute mouse position on screen virtual const Point2I GetCursorPosition() = 0; /// Set absolute mouse position on screen virtual void SetCursorPosition(const Point2I&) = 0; - virtual ~ApplicationCursorImplementation() {}; + virtual ~ApplicationCursorImplementation() {} protected: private: }; /*! \brief Allows to override the application's cursor. Base class for classes that allow to override the applications cursor with context dependent cursors. Accepts cursors in the XPM format. The behaviour is stack-like. You can push your cursor on top of the stack and later pop it to reset the cursor to its former state. This is mimicking Qt's Application::setOverrideCuror() behaviour, but should be ok for most cases where you want to switch a cursor. */ class MITK_CORE_EXPORT ApplicationCursor { public: /// This class is a singleton. static ApplicationCursor* GetInstance(); /// To be called by a toolkit specific ApplicationCursorImplementation. static void RegisterImplementation(ApplicationCursorImplementation* implementation); /// Change the current application cursor void PushCursor(const char* XPM[], int hotspotX = -1, int hotspotY = -1); /// Change the current application cursor - void PushCursor(const ModuleResource, int hotspotX = -1, int hotspotY = -1); + void PushCursor(std::istream&, int hotspotX = -1, int hotspotY = -1); /// Restore the previous cursor void PopCursor(); /// Get absolute mouse position on screen /// \return (-1, -1) if querying mouse position is not possible const Point2I GetCursorPosition(); /// Set absolute mouse position on screen void SetCursorPosition(const Point2I&); protected: /// Purposely hidden - singleton ApplicationCursor(); private: static ApplicationCursorImplementation* m_Implementation; }; } // namespace #endif diff --git a/Core/Code/DataManagement/mitkLevelWindowPreset.cpp b/Core/Code/DataManagement/mitkLevelWindowPreset.cpp index 06a4ead1ed..cc1dbf0cc7 100644 --- a/Core/Code/DataManagement/mitkLevelWindowPreset.cpp +++ b/Core/Code/DataManagement/mitkLevelWindowPreset.cpp @@ -1,144 +1,144 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkLevelWindowPreset.h" #include -#include "mitkGetModuleContext.h" -#include "mitkModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" +#include "usGetModuleContext.h" +#include "usModuleContext.h" +#include "usModule.h" +#include "usModuleResource.h" +#include "usModuleResourceStream.h" namespace mitk { const std::string LevelWindowPreset::PRESET = "preset"; vtkStandardNewMacro(LevelWindowPreset); LevelWindowPreset::LevelWindowPreset() { } LevelWindowPreset::~LevelWindowPreset() { } bool LevelWindowPreset::LoadPreset() { - ModuleResource presetResource = GetModuleContext()->GetModule()->GetResource("mitkLevelWindowPresets.xml"); + us::ModuleResource presetResource = us::GetModuleContext()->GetModule()->GetResource("mitkLevelWindowPresets.xml"); if (!presetResource) return false; - ModuleResourceStream presetStream(presetResource); + us::ModuleResourceStream presetStream(presetResource); vtkXMLParser::SetStream(&presetStream); if ( !vtkXMLParser::Parse() ) { #ifdef INTERDEBUG MITK_INFO<<"LevelWindowPreset::LoadPreset xml file cannot parse!"<& LevelWindowPreset::getLevelPresets() { return m_Level; } std::map& LevelWindowPreset::getWindowPresets() { return m_Window; } void LevelWindowPreset::save() { //XMLWriter writer(m_XmlFileName.c_str()); //saveXML(writer); } void LevelWindowPreset::newPresets(std::map newLevel, std::map newWindow) { m_Level = newLevel; m_Window = newWindow; save(); } } diff --git a/Core/Code/DataManagement/mitkShaderProperty.cpp b/Core/Code/DataManagement/mitkShaderProperty.cpp index d61ce949e6..828e95cc55 100644 --- a/Core/Code/DataManagement/mitkShaderProperty.cpp +++ b/Core/Code/DataManagement/mitkShaderProperty.cpp @@ -1,120 +1,118 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "mitkShaderProperty.h" #include "mitkCoreServices.h" #include "mitkIShaderRepository.h" #include #include mitk::ShaderProperty::ShaderProperty( ) { AddShaderTypes(); SetShader( (IdType)0 ); } mitk::ShaderProperty::ShaderProperty(const ShaderProperty& other) : mitk::EnumerationProperty(other) , shaderList(other.shaderList) { } mitk::ShaderProperty::ShaderProperty( const IdType& value ) { AddShaderTypes(); SetShader(value); } mitk::ShaderProperty::ShaderProperty( const std::string& value ) { AddShaderTypes(); SetShader(value); } void mitk::ShaderProperty::SetShader( const IdType& value ) { if ( IsValidEnumerationValue( value ) ) SetValue( value ); else SetValue( (IdType)0 ); } void mitk::ShaderProperty::SetShader( const std::string& value ) { if ( IsValidEnumerationValue( value ) ) SetValue( value ); else SetValue( (IdType)0 ); } mitk::EnumerationProperty::IdType mitk::ShaderProperty::GetShaderId() { return GetValueAsId(); } std::string mitk::ShaderProperty::GetShaderName() { return GetValueAsString(); } void mitk::ShaderProperty::AddShaderTypes() { AddEnum( "fixed" ); - IShaderRepository* shaderRepo = CoreServices::GetShaderRepository(); - if (shaderRepo == NULL) return; + CoreServicePointer shaderRepo(CoreServices::GetShaderRepository()); std::list l = shaderRepo->GetShaders(); - std::list::const_iterator i = l.begin(); while( i != l.end() ) { AddEnum( (*i)->GetName() ); i++; } } bool mitk::ShaderProperty::AddEnum( const std::string& name ,const IdType& /*id*/) { Element e; e.name=name; bool success=Superclass::AddEnum( e.name, (IdType)shaderList.size() ); shaderList.push_back(e); return success; } bool mitk::ShaderProperty::Assign(const BaseProperty &property) { Superclass::Assign(property); this->shaderList = static_cast(property).shaderList; return true; } itk::LightObject::Pointer mitk::ShaderProperty::InternalClone() const { itk::LightObject::Pointer result(new Self(*this)); return result; } diff --git a/Core/Code/IO/mitkCoreDataNodeReader.h b/Core/Code/IO/mitkCoreDataNodeReader.h index 61ff18e225..a396f45d8e 100644 --- a/Core/Code/IO/mitkCoreDataNodeReader.h +++ b/Core/Code/IO/mitkCoreDataNodeReader.h @@ -1,36 +1,34 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKCOREDATANODEREADER_H #define MITKCOREDATANODEREADER_H #include namespace mitk { -class CoreDataNodeReader : public itk::LightObject, public mitk::IDataNodeReader +class CoreDataNodeReader : public mitk::IDataNodeReader { public: - itkNewMacro(CoreDataNodeReader) - int Read(const std::string& fileName, mitk::DataStorage& storage); }; } #endif // MITKCOREDATANODEREADER_H diff --git a/Core/Code/IO/mitkIOUtil.cpp b/Core/Code/IO/mitkIOUtil.cpp index 56cd909554..c0f99e5072 100644 --- a/Core/Code/IO/mitkIOUtil.cpp +++ b/Core/Code/IO/mitkIOUtil.cpp @@ -1,381 +1,381 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkIOUtil.h" #include "mitkDataNodeFactory.h" #include "mitkImageWriter.h" #include "mitkPointSetWriter.h" #include "mitkSurfaceVtkWriter.h" -#include -#include +#include +#include #include #include #include #include //ITK #include //VTK #include #include #include namespace mitk { const std::string IOUtil::DEFAULTIMAGEEXTENSION = ".nrrd"; const std::string IOUtil::DEFAULTSURFACEEXTENSION = ".stl"; const std::string IOUtil::DEFAULTPOINTSETEXTENSION = ".mps"; int IOUtil::LoadFiles(const std::vector &fileNames, DataStorage &ds) { // Get the set of registered mitk::IDataNodeReader services - ModuleContext* context = mitk::GetModuleContext(); - const std::list refs = context->GetServiceReferences(); + us::ModuleContext* context = us::GetModuleContext(); + const std::vector > refs = context->GetServiceReferences(); std::vector services; services.reserve(refs.size()); - for (std::list::const_iterator i = refs.begin(); + for (std::vector >::const_iterator i = refs.begin(); i != refs.end(); ++i) { - IDataNodeReader* s = context->GetService(*i); + IDataNodeReader* s = context->GetService(*i); if (s != 0) { services.push_back(s); } } mitk::ProgressBar::GetInstance()->AddStepsToDo(2*fileNames.size()); // Iterate over all file names and use the IDataNodeReader services // to load them. int nodesRead = 0; for (std::vector::const_iterator i = fileNames.begin(); i != fileNames.end(); ++i) { for (std::vector::const_iterator readerIt = services.begin(); readerIt != services.end(); ++readerIt) { try { int n = (*readerIt)->Read(*i, ds); nodesRead += n; if (n > 0) break; } catch (const std::exception& e) { MITK_WARN << e.what(); } } mitk::ProgressBar::GetInstance()->Progress(2); } - for (std::list::const_iterator i = refs.begin(); + for (std::vector >::const_iterator i = refs.begin(); i != refs.end(); ++i) { context->UngetService(*i); } return nodesRead; } DataStorage::Pointer IOUtil::LoadFiles(const std::vector& fileNames) { mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); LoadFiles(fileNames, *ds); return ds.GetPointer(); } DataNode::Pointer IOUtil::LoadDataNode(const std::string path) { mitk::DataNodeFactory::Pointer reader = mitk::DataNodeFactory::New(); try { reader->SetFileName( path ); reader->Update(); if((reader->GetNumberOfOutputs()<1)) { MITK_ERROR << "Could not find data '" << path << "'"; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says could not find data."; } mitk::DataNode::Pointer node = reader->GetOutput(); if(node.IsNull()) { MITK_ERROR << "Could not find path: '" << path << "'" << " datanode is NULL" ; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says datanode is NULL."; } return reader->GetOutput( 0 ); } catch ( itk::ExceptionObject & e ) { MITK_ERROR << "Exception occured during load data of '" << path << "': Exception: " << e.what(); mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: " << e.what(); } } Image::Pointer IOUtil::LoadImage(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::Image::Pointer image = dynamic_cast(node->GetData()); if(image.IsNull()) { MITK_ERROR << "Image is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the image " << path << ". Exception says: Image is NULL."; } return image; } Surface::Pointer IOUtil::LoadSurface(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::Surface::Pointer surface = dynamic_cast(node->GetData()); if(surface.IsNull()) { MITK_ERROR << "Surface is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: Surface is NULL."; } return surface; } PointSet::Pointer IOUtil::LoadPointSet(const std::string path) { mitk::DataNode::Pointer node = LoadDataNode(path); mitk::PointSet::Pointer pointset = dynamic_cast(node->GetData()); if(pointset.IsNull()) { MITK_ERROR << "PointSet is NULL '" << path << "'"; mitkThrow() << "An exception occured during loading the file " << path << ". Exception says: Pointset is NULL."; } return pointset; } bool IOUtil::SaveImage(mitk::Image::Pointer image, const std::string path) { std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutExtension( path ); std::string extension = itksys::SystemTools::GetFilenameExtension( path ); if (dir == "") dir = "."; std::string finalFileName = dir + "/" + baseFilename; mitk::ImageWriter::Pointer imageWriter = mitk::ImageWriter::New(); //check if an extension is given, else use the defaul extension if( extension == "" ) { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTIMAGEEXTENSION; extension = DEFAULTIMAGEEXTENSION; } // check if extension is suitable for writing image data if (!imageWriter->IsExtensionValid(extension)) { MITK_WARN << extension << " extension is unknown. Extension set to default: " << finalFileName << DEFAULTIMAGEEXTENSION; extension = DEFAULTIMAGEEXTENSION; } try { //write the data imageWriter->SetInput(image); imageWriter->SetFileName(finalFileName.c_str()); imageWriter->SetExtension(extension.c_str()); imageWriter->Write(); } catch ( std::exception& e ) { MITK_ERROR << " during attempt to write '" << finalFileName + extension << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; } bool IOUtil::SaveSurface(Surface::Pointer surface, const std::string path) { std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( path ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( path ); if (dir == "") dir = "."; std::string finalFileName = dir + "/" + baseFilename; if (extension == "") // if no extension has been set we use the default extension { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTSURFACEEXTENSION; extension = DEFAULTSURFACEEXTENSION; } try { finalFileName += extension; if(extension == ".stl" ) { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); // check if surface actually consists of triangles; if not, the writer will not do anything; so, convert to triangles... vtkPolyData* polys = surface->GetVtkPolyData(); if( polys->GetNumberOfStrips() > 0 ) { vtkSmartPointer triangleFilter = vtkSmartPointer::New(); triangleFilter->SetInput(polys); triangleFilter->Update(); polys = triangleFilter->GetOutput(); polys->Register(NULL); surface->SetVtkPolyData(polys); } surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->GetVtkWriter()->SetFileTypeToBinary(); surfaceWriter->Write(); } else if(extension == ".vtp") { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->GetVtkWriter()->SetDataModeToBinary(); surfaceWriter->Write(); } else if(extension == ".vtk") { mitk::SurfaceVtkWriter::Pointer surfaceWriter = mitk::SurfaceVtkWriter::New(); surfaceWriter->SetInput( surface ); surfaceWriter->SetFileName( finalFileName.c_str() ); surfaceWriter->Write(); } else { // file extension not suitable for writing specified data type MITK_ERROR << "File extension is not suitable for writing'" << finalFileName; mitkThrow() << "An exception occured during writing the file " << finalFileName << ". File extension " << extension << " is not suitable for writing."; } } catch(std::exception& e) { MITK_ERROR << " during attempt to write '" << finalFileName << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; } bool IOUtil::SavePointSet(PointSet::Pointer pointset, const std::string path) { mitk::PointSetWriter::Pointer pointSetWriter = mitk::PointSetWriter::New(); std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutLastExtension( path ); std::string extension = itksys::SystemTools::GetFilenameLastExtension( path ); if (dir == "") dir = "."; std::string finalFileName = dir + "/" + baseFilename; if (extension == "") // if no extension has been entered manually into the filename { MITK_WARN << extension << " extension is not set. Extension set to default: " << finalFileName << DEFAULTPOINTSETEXTENSION; extension = DEFAULTPOINTSETEXTENSION; } // check if extension is valid if (!pointSetWriter->IsExtensionValid(extension)) { MITK_WARN << extension << " extension is unknown. Extension set to default: " << finalFileName << DEFAULTPOINTSETEXTENSION; extension = DEFAULTPOINTSETEXTENSION; } try { pointSetWriter->SetInput( pointset ); finalFileName += extension; pointSetWriter->SetFileName( finalFileName.c_str() ); pointSetWriter->Update(); } catch( std::exception& e ) { MITK_ERROR << " during attempt to write '" << finalFileName << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } return true; } bool IOUtil::SaveBaseData( mitk::BaseData* data, const std::string& path ) { if (data == NULL || path.empty()) return false; std::string dir = itksys::SystemTools::GetFilenamePath( path ); std::string baseFilename = itksys::SystemTools::GetFilenameWithoutExtension( path ); std::string extension = itksys::SystemTools::GetFilenameExtension( path ); if (dir == "") dir = "."; std::string fileNameWithoutExtension = dir + "/" + baseFilename; mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(data) ) { // Ensure a valid filename if(baseFilename=="") { baseFilename = (*it)->GetDefaultFilename(); } // Check if an extension exists already and if not, append the default extension if (extension=="" ) { extension=(*it)->GetDefaultExtension(); } else { if (!(*it)->IsExtensionValid(extension)) { MITK_WARN << extension << " extension is unknown"; continue; } } std::string finalFileName = fileNameWithoutExtension + extension; try { (*it)->SetFileName( finalFileName.c_str() ); (*it)->DoWrite( data ); return true; } catch( const std::exception& e ) { MITK_ERROR << " during attempt to write '" << finalFileName << "' Exception says:"; MITK_ERROR << e.what(); mitkThrow() << "An exception occured during writing the file " << finalFileName << ". Exception says " << e.what(); } } } return false; } } diff --git a/Core/Code/Interactions/mitkBindDispatcherInteractor.cpp b/Core/Code/Interactions/mitkBindDispatcherInteractor.cpp index 49267dffdf..f848b3df2b 100644 --- a/Core/Code/Interactions/mitkBindDispatcherInteractor.cpp +++ b/Core/Code/Interactions/mitkBindDispatcherInteractor.cpp @@ -1,112 +1,112 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBindDispatcherInteractor.h" #include "mitkMessage.h" #include // us -#include "mitkGetModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleRegistry.h" +#include "usGetModuleContext.h" +#include "usModule.h" +#include "usModuleRegistry.h" mitk::BindDispatcherInteractor::BindDispatcherInteractor( const std::string& rendererName ) : m_DataStorage(NULL) { - ModuleContext* context = ModuleRegistry::GetModule(1)->GetModuleContext(); + us::ModuleContext* context = us::ModuleRegistry::GetModule(1)->GetModuleContext(); if (context == NULL) { MITK_ERROR<< "BindDispatcherInteractor() - Context could not be obtained."; return; } m_Dispatcher = Dispatcher::New(rendererName); } void mitk::BindDispatcherInteractor::SetDataStorage(mitk::DataStorage::Pointer dataStorage) { // Set/Change Datastorage. This registers BDI to listen for events of DataStorage, to be informed when // a DataNode with a Interactor is added/modified/removed. // clean up events from previous datastorage UnRegisterDataStorageEvents(); m_DataStorage = dataStorage; RegisterDataStorageEvents(); } mitk::BindDispatcherInteractor::~BindDispatcherInteractor() { if (m_DataStorage.IsNotNull()) { UnRegisterDataStorageEvents(); } } void mitk::BindDispatcherInteractor::RegisterInteractor(const mitk::DataNode* dataNode) { if (m_Dispatcher.IsNotNull()) { m_Dispatcher->AddDataInteractor(dataNode); } } void mitk::BindDispatcherInteractor::RegisterDataStorageEvents() { if (m_DataStorage.IsNotNull()) { m_DataStorage->AddNodeEvent.AddListener( MessageDelegate1(this, &BindDispatcherInteractor::RegisterInteractor)); m_DataStorage->RemoveNodeEvent.AddListener( MessageDelegate1(this, &BindDispatcherInteractor::UnRegisterInteractor)); m_DataStorage->InteractorChangedNodeEvent.AddListener( MessageDelegate1(this, &BindDispatcherInteractor::RegisterInteractor)); } } void mitk::BindDispatcherInteractor::UnRegisterInteractor(const DataNode* dataNode) { if (m_Dispatcher.IsNotNull()) { m_Dispatcher->RemoveDataInteractor(dataNode); } } mitk::Dispatcher::Pointer mitk::BindDispatcherInteractor::GetDispatcher() const { return m_Dispatcher; } void mitk::BindDispatcherInteractor::SetDispatcher(Dispatcher::Pointer dispatcher) { m_Dispatcher = dispatcher; } void mitk::BindDispatcherInteractor::UnRegisterDataStorageEvents() { if (m_DataStorage.IsNotNull()) { m_DataStorage->AddNodeEvent.RemoveListener( MessageDelegate1(this, &BindDispatcherInteractor::RegisterInteractor)); m_DataStorage->RemoveNodeEvent.RemoveListener( MessageDelegate1(this, &BindDispatcherInteractor::UnRegisterInteractor)); m_DataStorage->ChangedNodeEvent.RemoveListener( MessageDelegate1(this, &BindDispatcherInteractor::RegisterInteractor)); } } diff --git a/Core/Code/Interactions/mitkDispatcher.cpp b/Core/Code/Interactions/mitkDispatcher.cpp index 30aafd46bd..4944a409a7 100644 --- a/Core/Code/Interactions/mitkDispatcher.cpp +++ b/Core/Code/Interactions/mitkDispatcher.cpp @@ -1,250 +1,251 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkDispatcher.h" #include "mitkInteractionEvent.h" #include "mitkInternalEvent.h" // MicroServices -#include "mitkGetModuleContext.h" +#include "usGetModuleContext.h" #include "mitkInteractionEventObserver.h" mitk::Dispatcher::Dispatcher( const std::string& rendererName ) : m_ProcessingMode(REGULAR) { // LDAP filter string to find all listeners specific for the renderer // corresponding to this dispatcher std::string specificRenderer = "(rendererName=" + rendererName +")"; // LDAP filter string to find all listeners that are not specific // to any renderer std::string anyRenderer = "(!(rendererName=*))"; // LDAP filter string to find only instances of InteractionEventObserver // The '*' is needed because of some namespace issues - std::string classInteractionEventObserver = "(" + ServiceConstants::OBJECTCLASS() + "=*InteractionEventObserver)"; + std::string classInteractionEventObserver = "(" + us::ServiceConstants::OBJECTCLASS() + "=*InteractionEventObserver)"; // Configure the LDAP filter to find all instances of InteractionEventObserver // that are specific to this dispatcher or unspecific to any dispatchers (real global listener) - LDAPFilter filter( "(&(|"+ specificRenderer + anyRenderer + ")"+classInteractionEventObserver+")" ); + us::LDAPFilter filter( "(&(|"+ specificRenderer + anyRenderer + ")"+classInteractionEventObserver+")" ); // Give the filter to the ObserverTracker - m_EventObserverTracker = new mitk::ServiceTracker(GetModuleContext(), filter); + m_EventObserverTracker = new us::ServiceTracker(us::GetModuleContext(), filter); m_EventObserverTracker->Open(); } void mitk::Dispatcher::AddDataInteractor(const DataNode* dataNode) { RemoveDataInteractor(dataNode); RemoveOrphanedInteractors(); DataInteractor::Pointer dataInteractor = dataNode->GetDataInteractor(); if (dataInteractor.IsNotNull()) { m_Interactors.push_back(dataInteractor); } } /* * Note: One DataInteractor can only have one DataNode and vice versa, * BUT the m_Interactors list may contain another DataInteractor that is still connected to this DataNode, * in this case we have to remove >1 DataInteractor. (Some special case of switching DataNodes between DataInteractors and registering a * DataNode to a DataStorage after assigning it to an DataInteractor) */ void mitk::Dispatcher::RemoveDataInteractor(const DataNode* dataNode) { for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();) { if ((*it)->GetDataNode() == dataNode) { it = m_Interactors.erase(it); } else { ++it; } } } size_t mitk::Dispatcher::GetNumberOfInteractors() { return m_Interactors.size(); } mitk::Dispatcher::~Dispatcher() { m_EventObserverTracker->Close(); delete m_EventObserverTracker; m_Interactors.clear(); } bool mitk::Dispatcher::ProcessEvent(InteractionEvent* event) { InteractionEvent::Pointer p = event; //MITK_INFO << event->GetEventClass(); bool eventIsHandled = false; /* Filter out and handle Internal Events separately */ InternalEvent* internalEvent = dynamic_cast(event); if (internalEvent != NULL) { eventIsHandled = HandleInternalEvent(internalEvent); // InternalEvents that are handled are not sent to the listeners if (eventIsHandled) { return true; } } switch (m_ProcessingMode) { case CONNECTEDMOUSEACTION: // finished connected mouse action if (std::strcmp(p->GetNameOfClass(), "MouseReleaseEvent") == 0) { m_ProcessingMode = REGULAR; eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()); } // give event to selected interactor if (eventIsHandled == false) { eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()); } break; case GRABINPUT: eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()); SetEventProcessingMode(m_SelectedInteractor); break; case PREFERINPUT: if (m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()) == true) { SetEventProcessingMode(m_SelectedInteractor); eventIsHandled = true; } break; case REGULAR: break; } // Standard behavior. Is executed in STANDARD mode and PREFERINPUT mode, if preferred interactor rejects event. if (m_ProcessingMode == REGULAR || (m_ProcessingMode == PREFERINPUT && eventIsHandled == false)) { m_Interactors.sort(cmp()); // sorts interactors by layer (descending); // copy the list to prevent iterator invalidation as executing actions // in HandleEvent() can cause the m_Interactors list to be updated std::list tmpInteractorList( m_Interactors ); std::list::iterator it; for ( it=tmpInteractorList.begin(); it!=tmpInteractorList.end(); it++ ) { DataInteractor::Pointer dataInteractor = *it; if ( (*it)->HandleEvent(event, dataInteractor->GetDataNode()) ) { // if an event is handled several properties are checked, in order to determine the processing mode of the dispatcher SetEventProcessingMode(dataInteractor); if (std::strcmp(p->GetNameOfClass(), "MousePressEvent") == 0 && m_ProcessingMode == REGULAR) { m_SelectedInteractor = dataInteractor; m_ProcessingMode = CONNECTEDMOUSEACTION; } eventIsHandled = true; break; } } } /* Notify InteractionEventObserver */ - std::list listEventObserver; + std::vector > listEventObserver; m_EventObserverTracker->GetServiceReferences(listEventObserver); - for (std::list::iterator it = listEventObserver.begin(); it != listEventObserver.end(); ++it) + for (std::vector >::iterator it = listEventObserver.begin(); + it != listEventObserver.end(); ++it) { InteractionEventObserver* interactionEventObserver = m_EventObserverTracker->GetService(*it); if (interactionEventObserver != NULL) { if (interactionEventObserver->IsEnabled()) { interactionEventObserver->Notify(event, eventIsHandled); } } } // Process event queue if (!m_QueuedEvents.empty()) { InteractionEvent::Pointer e = m_QueuedEvents.front(); m_QueuedEvents.pop_front(); ProcessEvent(e); } return eventIsHandled; } /* * Checks if DataNodes associated with DataInteractors point back to them. * If not remove the DataInteractors. (This can happen when s.o. tries to set DataNodes to multiple DataInteractors) */ void mitk::Dispatcher::RemoveOrphanedInteractors() { for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();) { DataNode::Pointer dn = (*it)->GetDataNode(); if (dn.IsNull()) { it = m_Interactors.erase(it); } else { DataInteractor::Pointer interactor = dn->GetDataInteractor(); if (interactor != it->GetPointer()) { it = m_Interactors.erase(it); } else { ++it; } } } } void mitk::Dispatcher::QueueEvent(InteractionEvent* event) { m_QueuedEvents.push_back(event); } void mitk::Dispatcher::SetEventProcessingMode(DataInteractor::Pointer dataInteractor) { m_ProcessingMode = dataInteractor->GetMode(); if (dataInteractor->GetMode() != REGULAR) { m_SelectedInteractor = dataInteractor; } } bool mitk::Dispatcher::HandleInternalEvent(InternalEvent* internalEvent) { if (internalEvent->GetSignalName() == DataInteractor::IntDeactivateMe && internalEvent->GetTargetInteractor() != NULL) { internalEvent->GetTargetInteractor()->GetDataNode()->SetDataInteractor(NULL); internalEvent->GetTargetInteractor()->SetDataNode(NULL); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } return false; } diff --git a/Core/Code/Interactions/mitkDispatcher.h b/Core/Code/Interactions/mitkDispatcher.h index cd68c7a32f..719da91dfd 100644 --- a/Core/Code/Interactions/mitkDispatcher.h +++ b/Core/Code/Interactions/mitkDispatcher.h @@ -1,131 +1,131 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkDispatcher_h #define mitkDispatcher_h #include "itkLightObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkDataNode.h" #include "mitkDataInteractor.h" #include #include -#include "mitkServiceTracker.h" +#include "usServiceTracker.h" namespace mitk { class InternalEvent; class InteractionEvent; struct InteractionEventObserver; /** * \class Dispatcher * \brief Manages event distribution * * Receives Events (Mouse-,Key-, ... Events) and dispatches them to the registered DataInteractor Objects. * The order in which DataInteractors are offered to handle an event is determined by layer of their associated DataNode. * Higher layers are preferred. * * \ingroup Interaction */ class MITK_CORE_EXPORT Dispatcher: public itk::LightObject { public: mitkClassMacro(Dispatcher, itk::LightObject); mitkNewMacro1Param(Self, const std::string&); typedef std::list ListInteractorType; typedef std::list > ListEventsType; /** * To post new Events which are to be handled by the Dispatcher. * * @return Returns true if the event has been handled by an DataInteractor, and false else. */ bool ProcessEvent(InteractionEvent* event); /** * Adds an Event to the Dispatchers EventQueue, these events will be processed after a a regular posted event has been fully handled. * This allows DataInteractors to post their own events without interrupting regular Dispatching workflow. * It is important to note that the queued events will be processed AFTER the state change of a current transition (which queued the events) * is performed. * * \note 1) If an event is added from an other source than an DataInteractor / Observer its execution will be delayed until the next regular event * comes in. * \note 2) Make sure you're not causing infinite loops! */ void QueueEvent(InteractionEvent* event); /** * Adds the DataInteractor that is associated with the DataNode to the Dispatcher Queue. * If there already exists an DataInteractor that has a reference to the same DataNode, it is removed. * Note that within this method also all other DataInteractors are checked and removed if they are no longer active, * and were not removed properly. */ void AddDataInteractor(const DataNode* dataNode); /** * Remove all DataInteractors related to this Node, to prevent double entries and dead references. */ void RemoveDataInteractor(const DataNode* dataNode); size_t GetNumberOfInteractors(); // DEBUG TESTING protected: Dispatcher(const std::string& rendererName); virtual ~Dispatcher(); private: struct cmp{ bool operator()(DataInteractor::Pointer d1, DataInteractor::Pointer d2){ return (d1->GetLayer() > d2->GetLayer()); } }; std::list m_Interactors; ListEventsType m_QueuedEvents; /** * Removes all Interactors without a DataNode pointing to them, this is necessary especially when a DataNode is assigned to a new Interactor */ void RemoveOrphanedInteractors(); /** * See \ref DataInteractionTechnicalPage_DispatcherEventDistSection for a description of ProcessEventModes */ ProcessEventMode m_ProcessingMode; DataInteractor::Pointer m_SelectedInteractor; void SetEventProcessingMode(DataInteractor::Pointer); /** * Function to handle special internal events, * such as events that are directed at a specific DataInteractor, * or the request to delete an Interactor and its DataNode. */ bool HandleInternalEvent(InternalEvent* internalEvent); /** * Hold microservice reference to object that takes care of informing the InteractionEventObservers about InteractionEvents */ - mitk::ServiceTracker* m_EventObserverTracker; + us::ServiceTracker* m_EventObserverTracker; }; } /* namespace mitk */ #endif /* mitkDispatcher_h */ diff --git a/Core/Code/Interactions/mitkEventConfig.cpp b/Core/Code/Interactions/mitkEventConfig.cpp index 46e8dee4be..d27904ac6f 100755 --- a/Core/Code/Interactions/mitkEventConfig.cpp +++ b/Core/Code/Interactions/mitkEventConfig.cpp @@ -1,425 +1,425 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkEventConfig.h" #include "mitkEventFactory.h" #include "mitkInteractionEvent.h" #include "mitkInternalEvent.h" #include "mitkInteractionKeyEvent.h" #include "mitkInteractionEventConst.h" // VTK #include #include // us -#include "mitkGetModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" +#include "usGetModuleContext.h" +#include "usModule.h" +#include "usModuleResource.h" +#include "usModuleResourceStream.h" namespace mitk { class EventConfigXMLParser : public vtkXMLParser { public: EventConfigXMLParser(EventConfigPrivate* d); protected: /** * @brief Derived from XMLReader **/ void StartElement(const char* elementName, const char **atts); /** * @brief Derived from XMLReader **/ void EndElement(const char* elementName); std::string ReadXMLStringAttribute(const std::string& name, const char** atts); bool ReadXMLBooleanAttribute(const std::string& name, const char** atts); private: EventConfigPrivate* const d; }; -struct EventConfigPrivate : public SharedData +struct EventConfigPrivate : public us::SharedData { EventConfigPrivate(); EventConfigPrivate(const EventConfigPrivate& other); struct EventMapping { std::string variantName; InteractionEvent::ConstPointer interactionEvent; }; typedef std::list EventListType; /** * Checks if mapping with the same parameters already exists, if so, it is replaced, * else the new mapping added */ void InsertMapping(const EventMapping& mapping); void CopyMapping( const EventListType ); /** * @brief List of all global properties of the config object. */ PropertyList::Pointer m_PropertyList; /** * @brief Temporal list of all prMousePressEventoperties of a Event. Used to parse an Input-Event and collect all parameters between the two * and tags. */ PropertyList::Pointer m_EventPropertyList; EventMapping m_CurrEventMapping; /** * Stores InteractionEvents and their corresponding VariantName */ EventListType m_EventList; bool m_Errors; // use member, because of inheritance from vtkXMLParser we can't return a success value for parsing the file. EventConfigXMLParser m_XmlParser; }; } mitk::EventConfigPrivate::EventConfigPrivate() : m_PropertyList(PropertyList::New()) , m_EventPropertyList( PropertyList::New() ) , m_Errors(false) , m_XmlParser(this) { // Avoid VTK warning: Trying to delete object with non-zero reference count. m_XmlParser.SetReferenceCount(0); } mitk::EventConfigPrivate::EventConfigPrivate(const EventConfigPrivate& other) - : SharedData(other) + : us::SharedData(other) , m_PropertyList(other.m_PropertyList->Clone()) , m_EventPropertyList(other.m_EventPropertyList->Clone()) , m_CurrEventMapping(other.m_CurrEventMapping) , m_EventList(other.m_EventList) , m_Errors(other.m_Errors) , m_XmlParser(this) { // Avoid VTK warning: Trying to delete object with non-zero reference count. m_XmlParser.SetReferenceCount(0); } void mitk::EventConfigPrivate::InsertMapping(const EventMapping& mapping) { for (EventListType::iterator it = m_EventList.begin(); it != m_EventList.end(); ++it) { if (*(it->interactionEvent) == *mapping.interactionEvent) { //MITK_INFO<< "Configuration overwritten:" << (*it).variantName; m_EventList.erase(it); break; } } m_EventList.push_back(mapping); } void mitk::EventConfigPrivate::CopyMapping( const EventListType eventList ) { EventListType::const_iterator iter; for( iter=eventList.begin(); iter!=eventList.end(); iter++ ) { InsertMapping( *(iter) ); } } mitk::EventConfigXMLParser::EventConfigXMLParser(EventConfigPrivate *d) : d(d) { } void mitk::EventConfigXMLParser::StartElement(const char* elementName, const char **atts) { std::string name(elementName); if (name == InteractionEventConst::xmlTagConfigRoot()) { // } else if (name == InteractionEventConst::xmlTagParam()) { std::string name = ReadXMLStringAttribute(InteractionEventConst::xmlParameterName(), atts); std::string value = ReadXMLStringAttribute(InteractionEventConst::xmlParameterValue(), atts); d->m_PropertyList->SetStringProperty(name.c_str(), value.c_str()); } else if (name == InteractionEventConst::xmlTagEventVariant()) { std::string eventClass = ReadXMLStringAttribute(InteractionEventConst::xmlParameterEventClass(), atts); std::string eventVariant = ReadXMLStringAttribute(InteractionEventConst::xmlParameterName(), atts); // New list in which all parameters are stored that are given within the tag d->m_EventPropertyList = PropertyList::New(); d->m_EventPropertyList->SetStringProperty(InteractionEventConst::xmlParameterEventClass().c_str(), eventClass.c_str()); d->m_EventPropertyList->SetStringProperty(InteractionEventConst::xmlParameterEventVariant().c_str(), eventVariant.c_str()); d->m_CurrEventMapping.variantName = eventVariant; } else if (name == InteractionEventConst::xmlTagAttribute()) { // Attributes that describe an Input Event, such as which MouseButton triggered the event,or which modifier keys are pressed std::string name = ReadXMLStringAttribute(InteractionEventConst::xmlParameterName(), atts); std::string value = ReadXMLStringAttribute(InteractionEventConst::xmlParameterValue(), atts); d->m_EventPropertyList->SetStringProperty(name.c_str(), value.c_str()); } } void mitk::EventConfigXMLParser::EndElement(const char* elementName) { std::string name(elementName); // At end of input section, all necessary infos are collected to created an interaction event. if (name == InteractionEventConst::xmlTagEventVariant()) { InteractionEvent::Pointer event = EventFactory::CreateEvent(d->m_EventPropertyList); if (event.IsNotNull()) { d->m_CurrEventMapping.interactionEvent = event; d->InsertMapping(d->m_CurrEventMapping); } else { MITK_WARN<< "EventConfig: Unknown Event-Type in config. Entry skipped: " << name; } } } std::string mitk::EventConfigXMLParser::ReadXMLStringAttribute(const std::string& name, const char** atts) { if (atts) { const char** attsIter = atts; while (*attsIter) { if (name == *attsIter) { attsIter++; return *attsIter; } attsIter += 2; } } return std::string(); } bool mitk::EventConfigXMLParser::ReadXMLBooleanAttribute(const std::string& name, const char** atts) { std::string s = ReadXMLStringAttribute(name, atts); std::transform(s.begin(), s.end(), s.begin(), ::toupper); return s == "TRUE"; } mitk::EventConfig::EventConfig() : d(new EventConfigPrivate) { } mitk::EventConfig::EventConfig(const EventConfig &other) : d(other.d) { } -mitk::EventConfig::EventConfig(const std::string& filename, const Module* module) +mitk::EventConfig::EventConfig(const std::string& filename, const us::Module* module) : d(new EventConfigPrivate) { if (module == NULL) { - module = GetModuleContext()->GetModule(); + module = us::GetModuleContext()->GetModule(); } - mitk::ModuleResource resource = module->GetResource("Interactions/" + filename); + us::ModuleResource resource = module->GetResource("Interactions/" + filename); if (!resource.IsValid()) { MITK_ERROR << "Resource not valid. State machine pattern in module " << module->GetName() << " not found: /Interactions/" << filename; return; } EventConfig newConfig; - mitk::ModuleResourceStream stream(resource); + us::ModuleResourceStream stream(resource); newConfig.d->m_XmlParser.SetStream(&stream); bool success = newConfig.d->m_XmlParser.Parse() && !newConfig.d->m_Errors; if (success) { *this = newConfig; } } mitk::EventConfig::EventConfig(std::istream &inputStream) : d(new EventConfigPrivate) { EventConfig newConfig; newConfig.d->m_XmlParser.SetStream(&inputStream); bool success = newConfig.d->m_XmlParser.Parse() && !newConfig.d->m_Errors; if (success) { *this = newConfig; } } mitk::EventConfig::EventConfig(const std::vector &configDescription) : d(new EventConfigPrivate) { std::vector::const_iterator it_end = configDescription.end(); for (std::vector::const_iterator it = configDescription.begin(); it != it_end; ++it) { std::string typeVariant; (*it)->GetStringProperty(InteractionEventConst::xmlTagEventVariant().c_str(), typeVariant); if ( typeVariant != "" ) { InteractionEvent::Pointer event = EventFactory::CreateEvent(*it); if (event.IsNotNull()) { d->m_CurrEventMapping.interactionEvent = event; std::string eventVariant; (*it)->GetStringProperty(InteractionEventConst::xmlTagEventVariant().c_str(), eventVariant); d->m_CurrEventMapping.variantName = eventVariant; d->InsertMapping(d->m_CurrEventMapping); } else { MITK_WARN<< "EventConfig: Unknown Event-Type in config. When constructing from PropertyList."; } } else { (*it)->GetStringProperty(InteractionEventConst::xmlTagParam().c_str(), typeVariant); if ( typeVariant != "" ) { std::string name, value; (*it)->GetStringProperty(InteractionEventConst::xmlParameterName().c_str(), name); (*it)->GetStringProperty(InteractionEventConst::xmlParameterValue().c_str(), value); d->m_PropertyList->SetStringProperty(name.c_str(), value.c_str()); } } } } mitk::EventConfig& mitk::EventConfig::operator =(const mitk::EventConfig& other) { d = other.d; return *this; } mitk::EventConfig::~EventConfig() { } bool mitk::EventConfig::IsValid() const { return !( d->m_EventList.empty() && d->m_PropertyList->IsEmpty() ); } -bool mitk::EventConfig::AddConfig(const std::string& fileName, const Module* module) +bool mitk::EventConfig::AddConfig(const std::string& fileName, const us::Module* module) { if (module == NULL) { - module = GetModuleContext()->GetModule(); + module = us::GetModuleContext()->GetModule(); } - mitk::ModuleResource resource = module->GetResource("Interactions/" + fileName); + us::ModuleResource resource = module->GetResource("Interactions/" + fileName); if (!resource.IsValid()) { MITK_ERROR << "Resource not valid. State machine pattern in module " << module->GetName() << " not found: /Interactions/" << fileName; return false; } EventConfig newConfig(*this); - mitk::ModuleResourceStream stream(resource); + us::ModuleResourceStream stream(resource); newConfig.d->m_XmlParser.SetStream(&stream); bool success = newConfig.d->m_XmlParser.Parse() && !newConfig.d->m_Errors; if (success) { *this = newConfig; } return success; } bool mitk::EventConfig::AddConfig(const EventConfig& config) { if (!config.IsValid()) return false; d->m_PropertyList->ConcatenatePropertyList(config.d->m_PropertyList->Clone(), true); d->m_EventPropertyList = config.d->m_EventPropertyList->Clone(); d->m_CurrEventMapping = config.d->m_CurrEventMapping; d->CopyMapping( config.d->m_EventList ); return true; } mitk::PropertyList::Pointer mitk::EventConfig::GetAttributes() const { return d->m_PropertyList; } std::string mitk::EventConfig::GetMappedEvent(const EventType& interactionEvent) const { // internal events are excluded from mapping if (std::strcmp(interactionEvent->GetNameOfClass(), "InternalEvent") == 0) { InternalEvent* internalEvent = dynamic_cast(interactionEvent.GetPointer()); return internalEvent->GetSignalName(); } for (EventConfigPrivate::EventListType::const_iterator it = d->m_EventList.begin(); it != d->m_EventList.end(); ++it) { if (*(it->interactionEvent) == *interactionEvent) { return (*it).variantName; } } // if this part is reached, no mapping has been found, // so here we handle key events and map a key event to the string "Std" + letter/code // so "A" will be returned as "StdA" if (std::strcmp(interactionEvent->GetNameOfClass(), "InteractionKeyEvent") == 0) { InteractionKeyEvent* keyEvent = dynamic_cast(interactionEvent.GetPointer()); return ("Std" + keyEvent->GetKey()); } return ""; } void mitk::EventConfig::ClearConfig() { d->m_PropertyList->Clear(); d->m_EventPropertyList->Clear(); d->m_CurrEventMapping.variantName.clear(); d->m_CurrEventMapping.interactionEvent = NULL; d->m_EventList.clear(); d->m_Errors = false; } diff --git a/Core/Code/Interactions/mitkEventConfig.h b/Core/Code/Interactions/mitkEventConfig.h index 16e3ec18f2..c852cbf127 100755 --- a/Core/Code/Interactions/mitkEventConfig.h +++ b/Core/Code/Interactions/mitkEventConfig.h @@ -1,184 +1,187 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkStateMachineConfig_h #define mitkStateMachineConfig_h #include -#include "mitkSharedData.h" +#include "usSharedData.h" #include "mitkPropertyList.h" #include "itkSmartPointer.h" +namespace us { +class Module; +} + namespace mitk { class InteractionEvent; - class Module; struct EventConfigPrivate; /** * \class EventConfig * \brief Configuration Object for Statemachines. * * Reads given config file, which translates specific user inputs (InteractionEvents) into EventVariants that can be processed * by the StateMachine. * Refer to \ref ConfigFileDescriptionSection . * * @ingroup Interaction **/ class MITK_CORE_EXPORT EventConfig { public: typedef itk::SmartPointer EventType; /** * @brief Constructs an invalid EventConfig object. * * Call LoadConfig to create a valid configuration object. */ EventConfig(); EventConfig(const EventConfig& other); /** * @brief Construct an EventConfig object based on a XML configuration file. * * Uses the specified resource file containing an XML event configuration to * construct an EventConfig object. If the resource is invalid, the created * EventConfig object will also be invalid. * * @param filename The resource name relative to the Interactions resource folder. * @param module */ - EventConfig(const std::string& filename, const Module* module = NULL); + EventConfig(const std::string& filename, const us::Module* module = NULL); /** * @brief Construct an EventConfig object based on a XML configuration file. * * Uses the specified istream refering to a file containing an XML event configuration to * construct an EventConfig object. If the resource is invalid, the created * EventConfig object will also be invalid. * * @param inputStream std::ifstream to XML configuration file */ EventConfig(std::istream &inputStream); /** * @brief Construct an EventConfig object based on a vector of mitk::PropertyLists * * Constructs the EventObject based on a description provided by vector of property values, where each mitk::PropertyList describes * one Event. * Example \code #include "mitkPropertyList.h" #include "mitkInteractionEventConst.h" #include "mitkEventConfig.h" // First event mitk::PropertyList::Pointer propertyList1 = mitk::PropertyList::New(); // Setting the EventClass property to 'MousePressEvent' propertyList1->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass.c_str(), "MousePressEvent"); // Setting the Event variant value to 'MousePressEventVariantÄ propertyList1->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant.c_str(), "MousePressEventVariant"); // set control and alt buttons as modifiers propertyList1->SetStringProperty("Modifiers","CTRL,ALT"); // Second event mitk::PropertyList::Pointer propertyList2 = mitk::PropertyList::New(); propertyList2->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass.c_str(), "MouseReleaseEvent"); propertyList2->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant.c_str(), "MouseReleaseEventVariant"); propertyList2->SetStringProperty("Modifiers","SHIFT"); // putting both descriptions in a vector std::vector* configDescription = new std::vector(); configDescription->push_back(propertyList1); configDescription->push_back(propertyList2); // create the config object mitk::EventConfig newConfig(configDescription); \endcode */ EventConfig(const std::vector& configDescription ); EventConfig& operator=(const EventConfig& other); ~EventConfig(); /** * @brief Checks wether this EventConfig object is valid. * @return Returns \c true if a configuration was successfully loaded, \c false otherwise. */ bool IsValid() const; /** * @brief This method \e extends this configuration. * * The configuration from the resource provided is loaded and only the ones conflicting are replaced by the new one. * This way several configuration files can be combined. * * @see AddConfig(const EventConfig&) * @see InteractionEventHandler::AddEventConfig(const std::string&, const Module*) * * @param filename The resource name relative to the Interactions resource folder. * @param module The module containing the resource. Defaults to the Mitk module. * @return \c true if the configuration was successfully added, \c false otherwise. */ - bool AddConfig(const std::string& filename, const Module* module = NULL); + bool AddConfig(const std::string& filename, const us::Module* module = NULL); /** * @brief This method \e extends this configuration. * The configuration from the EventConfig object is loaded and only the ones conflicting are replaced by the new one. * This way several configurations can be combined. * * @see AddConfig(const std::string&, const Module*) * @see InteractionEventHandler::AddEventConfig(const EventConfig&) * * @param config The EventConfig object whose configuration should be added. * @return \c true if the configuration was successfully added, \c false otherwise. */ bool AddConfig(const EventConfig& config); /** * @brief Reset this EventConfig object, rendering it invalid. */ void ClearConfig(); /** * Returns a PropertyList that contains the properties set in the configuration file. * All properties are stored as strings. */ PropertyList::Pointer GetAttributes() const; /** * Checks if the config object has a definition for the given event. If it has, the corresponding variant name is returned, else * an empty string is returned. * \note mitk::InternalEvent is handled differently. Their signal name is returned as event variant. So there is no need * to configure them in a config file. * \note mitk::InteractionKeyEvent may have a defined event variant, if this is the case, this function returns it. If no * such definition is found key events are mapped to Std + Key , so an 'A' will be return as 'StdA' . */ std::string GetMappedEvent(const EventType& interactionEvent) const; private: - SharedDataPointer d; + us::SharedDataPointer d; }; } // namespace mitk #endif /* mitkStateMachineConfig_h */ diff --git a/Core/Code/Interactions/mitkEventMapper.cpp b/Core/Code/Interactions/mitkEventMapper.cpp index bc3ff68433..192fd0a6f8 100644 --- a/Core/Code/Interactions/mitkEventMapper.cpp +++ b/Core/Code/Interactions/mitkEventMapper.cpp @@ -1,706 +1,705 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /** * EventMapping: * This class maps the Events, usually given by the OS or here by QT, to a MITK internal EventId. * It loads all information from the xml-file (possible, understandable Events with the mitkEventID). * If an event appears, the method MapEvent is called with the event params. * This Method looks up the event params, and tries to find an mitkEventId to it. * If yes, then sends the event and the found ID to the globalStateMachine, which handles all * further operations of that event. * */ #include "mitkEventMapper.h" #include "mitkInteractionConst.h" #include "mitkStateEvent.h" #include "mitkOperationEvent.h" #include "mitkGlobalInteraction.h" #include #include "mitkStandardFileLocations.h" //#include #include "mitkConfig.h" #include "mitkCoreObjectFactory.h" #include #include #include #include // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" -#include "mitkModuleRegistry.h" -#include -#include +#include "usModule.h" +#include "usModuleResource.h" +#include "usModuleResourceStream.h" +#include +#include namespace mitk { vtkStandardNewMacro(EventMapper); } #ifdef MBI_INTERNAL_CONFERENCE #include #include #include #include #include #endif //MBI_INTERNAL_CONFERENCE //XML Event const std::string mitk::EventMapper::STYLE = "STYLE"; const std::string mitk::EventMapper::NAME = "NAME"; const std::string mitk::EventMapper::ID = "ID"; const std::string mitk::EventMapper::TYPE = "TYPE"; const std::string mitk::EventMapper::BUTTON = "BUTTON"; const std::string mitk::EventMapper::BUTTONSTATE = "BUTTONSTATE"; const std::string mitk::EventMapper::KEY = "KEY"; const std::string mitk::EventMapper::EVENTS = "events"; const std::string mitk::EventMapper::EVENT = "event"; mitk::EventMapper::EventDescriptionVec mitk::EventMapper::m_EventDescriptions; std::string mitk::EventMapper::m_XmlFileName; mitk::StateEvent mitk::EventMapper::m_StateEvent; std::string mitk::EventMapper::m_StyleName; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; mitk::EventMapper::EventMapper() { //map with string to key for mapping string from xml-file to int m_EventConstMap["Type_None"] = mitk::Type_None; // invalid event m_EventConstMap["Type_Timer"] = mitk::Type_Timer; // timer event m_EventConstMap["Type_MouseButtonPress"] = mitk::Type_MouseButtonPress; // mouse button pressed m_EventConstMap["Type_MouseButtonRelease"] = mitk::Type_MouseButtonRelease; // mouse button released m_EventConstMap["Type_MouseButtonDblClick"] = mitk::Type_MouseButtonDblClick; // mouse button double click m_EventConstMap["Type_MouseMove"] = mitk::Type_MouseMove; // mouse move m_EventConstMap["Type_KeyPress"] = mitk::Type_KeyPress; // key pressed m_EventConstMap["Type_KeyRelease"] = mitk::Type_KeyRelease; // key released m_EventConstMap["Type_FocusIn"] = 8; // keyboard focus received m_EventConstMap["Type_FocusOut"] = 9; // keyboard focus lost m_EventConstMap["Type_Enter"] = 10; // mouse enters widget m_EventConstMap["Type_Leave"] = 11; // mouse leaves widget m_EventConstMap["Type_Paint"] = 12; // paint widget m_EventConstMap["Type_Move"] = 13; // move widget m_EventConstMap["Type_Resize"] = 14; // resize widget m_EventConstMap["Type_Create"] = 15; // after object creation m_EventConstMap["Type_Destroy"] = 16; // during object destruction m_EventConstMap["Type_Show"] = 17; // widget is shown m_EventConstMap["Type_Hide"] = 18; // widget is hidden m_EventConstMap["Type_Close"] = 19; // request to close widget m_EventConstMap["Type_Quit"] = 20; // request to quit application m_EventConstMap["Type_Reparent"] = 21; // widget has been reparented m_EventConstMap["Type_ShowMinimized"] = 22; // widget is shown minimized m_EventConstMap["Type_ShowNormal"] = 23; // widget is shown normal m_EventConstMap["Type_WindowActivate"] = 24; // window was activated m_EventConstMap["Type_WindowDeactivate"] = 25; // window was deactivated m_EventConstMap["Type_ShowToParent"] = 26; // widget is shown to parent m_EventConstMap["Type_HideToParent"] = 27; // widget is hidden to parent m_EventConstMap["Type_ShowMaximized"] = 28; // widget is shown maximized m_EventConstMap["Type_ShowFullScreen"] = 29; // widget is shown full-screen m_EventConstMap["Type_Accel"] = 30; // accelerator event m_EventConstMap["Type_Wheel"] = 31; // wheel event m_EventConstMap["Type_AccelAvailable"] = 32; // accelerator available event m_EventConstMap["Type_CaptionChange"] = 33; // caption changed m_EventConstMap["Type_IconChange"] = 34; // icon changed m_EventConstMap["Type_ParentFontChange"] = 35; // parent font changed m_EventConstMap["Type_ApplicationFontChange"] = 36;// application font changed m_EventConstMap["Type_ParentPaletteChange"] = 37; // parent palette changed m_EventConstMap["Type_ApplicationPaletteChange"] = 38;// application palette changed m_EventConstMap["Type_PaletteChange"] = 39; // widget palette changed m_EventConstMap["Type_Clipboard"] = 40; // internal clipboard event m_EventConstMap["Type_Speech"] = 42; // reserved for speech input m_EventConstMap["Type_SockAct"] = 50; // socket activation m_EventConstMap["Type_AccelOverride"] = 51; // accelerator override event m_EventConstMap["Type_DeferredDelete"] = 52; // deferred delete event m_EventConstMap["Type_DragEnter"] = 60; // drag moves into widget m_EventConstMap["Type_DragMove"] = 61; // drag moves in widget m_EventConstMap["Type_DragLeave"] = 62; // drag leaves or is cancelled m_EventConstMap["Type_Drop"] = 63; // actual drop m_EventConstMap["Type_DragResponse"] = 64; // drag accepted/rejected m_EventConstMap["Type_ChildInserted"] = 70; // new child widget m_EventConstMap["Type_ChildRemoved"] = 71; // deleted child widget m_EventConstMap["Type_LayoutHint"] = 72; // child min/max size changed m_EventConstMap["Type_ShowWindowRequest"] = 73; // widget's window should be mapped m_EventConstMap["Type_ActivateControl"] = 80; // ActiveX activation m_EventConstMap["Type_DeactivateControl"] = 81; // ActiveX deactivation m_EventConstMap["Type_ContextMenu"] = 82; // context popup menu m_EventConstMap["Type_IMStart"] = 83; // input method composition start m_EventConstMap["Type_IMCompose"] = 84; // input method composition m_EventConstMap["Type_IMEnd"] = 85; // input method composition end m_EventConstMap["Type_Accessibility"] = 86; // accessibility information is requested m_EventConstMap["Type_TabletMove"] = 87; // Wacom tablet event m_EventConstMap["Type_LocaleChange"] = 88; // the system locale changed m_EventConstMap["Type_LanguageChange"] = 89; // the application language changed m_EventConstMap["Type_LayoutDirectionChange"] = 90; // the layout direction changed m_EventConstMap["Type_Style"] = 91; // internal style event m_EventConstMap["Type_TabletPress"] = 92; // tablet press m_EventConstMap["Type_TabletRelease"] = 93; // tablet release // apparently not necessary, since the IDs can be assigned earlier (in the AddOns after they are generated in the driver) //m_EventConstMap["Type_TDMouseInput"] = mitk::Type_TDMouseInput; // 3D mouse input occured m_EventConstMap["Type_User"] = 1000; // first user event id m_EventConstMap["Type_MaxUser"] = 65535; // last user event id //ButtonState m_EventConstMap["BS_NoButton"] = mitk::BS_NoButton;//0x0000 m_EventConstMap["BS_LeftButton"] = mitk::BS_LeftButton;//0x0001 m_EventConstMap["BS_RightButton"] = mitk::BS_RightButton;//0x0002 m_EventConstMap["BS_MidButton"] = mitk::BS_MidButton;//0x0004 m_EventConstMap["BS_MouseButtonMask"] = mitk::BS_MouseButtonMask;//0x0007 m_EventConstMap["BS_ShiftButton"] = mitk::BS_ShiftButton;//0x0008 m_EventConstMap["BS_ControlButton"] = mitk::BS_ControlButton;//0x0010 m_EventConstMap["BS_AltButton"] = mitk::BS_AltButton;//0x0020 m_EventConstMap["BS_KeyButtonMask"] = mitk::BS_KeyButtonMask;//0x0038 m_EventConstMap["BS_Keypad"] = mitk::BS_Keypad;//0x4000 //Modifier m_EventConstMap["Mod_SHIFT"] = 0x00200000; m_EventConstMap["Mod_CTRL"] = 0x00400000; m_EventConstMap["Mod_ALT"] = 0x00800000; m_EventConstMap["Mod_MODIFIER_MASK"] = 0x00e00000; m_EventConstMap["Mod_UNICODE_ACCEL"] = 0x10000000; m_EventConstMap["Mod_ASCII_ACCEL"] = 0x10000000; //Key m_EventConstMap["Key_Escape"] = 0x1000; m_EventConstMap["Key_Tab"] = 0x1001; m_EventConstMap["Key_Backtab"] = 0x1002; m_EventConstMap["Key_BackTab"] = 0x1002; m_EventConstMap["Key_Backspace"] = 0x1003; m_EventConstMap["Key_BackSpace"] = 0x1003; m_EventConstMap["Key_Return"] = 0x1004; m_EventConstMap["Key_Enter"] = 0x1005; m_EventConstMap["Key_Insert"] = 0x1006; m_EventConstMap["Key_Delete"] = 0x1007; m_EventConstMap["Key_Pause"] = 0x1008; m_EventConstMap["Key_Print"] = 0x1009; m_EventConstMap["Key_SysReq"] = 0x100a; m_EventConstMap["Key_Home"] = 0x1010; m_EventConstMap["Key_End"] = 0x1011; m_EventConstMap["Key_Left"] = 0x1012; m_EventConstMap["Key_Up"] = 0x1013; m_EventConstMap["Key_Right"] = 0x1014; m_EventConstMap["Key_Down"] = 0x1015; m_EventConstMap["Key_Prior"] = 0x1016; m_EventConstMap["Key_PageUp"] = 0x1016; m_EventConstMap["Key_Next"] = 0x1017; m_EventConstMap["Key_PageDown"] = 0x1017; m_EventConstMap["Key_Shift"] = 0x1020; m_EventConstMap["Key_Control"] = 0x1021; m_EventConstMap["Key_Meta"] = 0x1022; m_EventConstMap["Key_Alt"] = 0x1023; m_EventConstMap["Key_CapsLock"] = 0x1024; m_EventConstMap["Key_NumLock"] = 0x1025; m_EventConstMap["Key_ScrollLock"] = 0x1026; m_EventConstMap["Key_F1"] = 0x1030; m_EventConstMap["Key_F2"] = 0x1031; m_EventConstMap["Key_F3"] = 0x1032; m_EventConstMap["Key_F4"] = 0x1033; m_EventConstMap["Key_F5"] = 0x1034; m_EventConstMap["Key_F6"] = 0x1035; m_EventConstMap["Key_F7"] = 0x1036; m_EventConstMap["Key_F8"] = 0x1037; m_EventConstMap["Key_F9"] = 0x1038; m_EventConstMap["Key_F10"] = 0x1039; m_EventConstMap["Key_F11"] = 0x103a; m_EventConstMap["Key_F12"] = 0x103b; m_EventConstMap["Key_F13"] = 0x103c; m_EventConstMap["Key_F14"] = 0x103d; m_EventConstMap["Key_F15"] = 0x103e; m_EventConstMap["Key_F16"] = 0x103f; m_EventConstMap["Key_F17"] = 0x1040; m_EventConstMap["Key_F18"] = 0x1041; m_EventConstMap["Key_F19"] = 0x1042; m_EventConstMap["Key_F20"] = 0x1043; m_EventConstMap["Key_F21"] = 0x1044; m_EventConstMap["Key_F22"] = 0x1045; m_EventConstMap["Key_F23"] = 0x1046; m_EventConstMap["Key_F24"] = 0x1047; m_EventConstMap["Key_F25"] = 0x1048; m_EventConstMap["Key_F26"] = 0x1049; m_EventConstMap["Key_F27"] = 0x104a; m_EventConstMap["Key_F28"] = 0x104b; m_EventConstMap["Key_F29"] = 0x104c; m_EventConstMap["Key_F30"] = 0x104d; m_EventConstMap["Key_F31"] = 0x104e; m_EventConstMap["Key_F32"] = 0x104f; m_EventConstMap["Key_F33"] = 0x1050; m_EventConstMap["Key_F34"] = 0x1051; m_EventConstMap["Key_F35"] = 0x1052; m_EventConstMap["Key_Super_L"] = 0x1053; m_EventConstMap["Key_Super_R"] = 0x1054; m_EventConstMap["Key_Menu"] = 0x1055; m_EventConstMap["Key_Hyper_L"] = 0x1056; m_EventConstMap["Key_Hyper_R"] = 0x1057; m_EventConstMap["Key_Help"] = 0x1058; m_EventConstMap["Key_Muhenkan"] = 0x1122; m_EventConstMap["Key_Henkan"] = 0x1123; m_EventConstMap["Key_Hiragana_Katakana"] = 0x1127; m_EventConstMap["Key_Zenkaku_Hankaku"] = 0x112A; m_EventConstMap["Key_Space"] = 0x20; m_EventConstMap["Key_Any"] = 0x20; m_EventConstMap["Key_Exclam"] = 0x21; m_EventConstMap["Key_QuoteDbl"] = 0x22; m_EventConstMap["Key_NumberSign"] = 0x23; m_EventConstMap["Key_Dollar"] = 0x24; m_EventConstMap["Key_Percent"] = 0x25; m_EventConstMap["Key_Ampersand"] = 0x26; m_EventConstMap["Key_Apostrophe"] = 0x27; m_EventConstMap["Key_ParenLeft"] = 0x28; m_EventConstMap["Key_ParenRight"] = 0x29; m_EventConstMap["Key_Asterisk"] = 0x2a; m_EventConstMap["Key_Plus"] = 0x2b; m_EventConstMap["Key_Comma"] = 0x2c; m_EventConstMap["Key_Minus"] = 0x2d; m_EventConstMap["Key_Period"] = 0x2e; m_EventConstMap["Key_Slash"] = 0x2f; m_EventConstMap["Key_0"] = 0x30; m_EventConstMap["Key_1"] = 0x31; m_EventConstMap["Key_2"] = 0x32; m_EventConstMap["Key_3"] = 0x33; m_EventConstMap["Key_4"] = 0x34; m_EventConstMap["Key_5"] = 0x35; m_EventConstMap["Key_6"] = 0x36; m_EventConstMap["Key_7"] = 0x37; m_EventConstMap["Key_8"] = 0x38; m_EventConstMap["Key_9"] = 0x39; m_EventConstMap["Key_Colon"] = 0x3a; m_EventConstMap["Key_Semicolon"] = 0x3b; m_EventConstMap["Key_Less"] = 0x3c; m_EventConstMap["Key_Equal"] = 0x3d; m_EventConstMap["Key_Greater"] = 0x3e; m_EventConstMap["Key_Question"] = 0x3f; m_EventConstMap["Key_At"] = 0x40; m_EventConstMap["Key_A"] = 0x41; m_EventConstMap["Key_B"] = 0x42; m_EventConstMap["Key_C"] = 0x43; m_EventConstMap["Key_D"] = 0x44; m_EventConstMap["Key_E"] = 0x45; m_EventConstMap["Key_F"] = 0x46; m_EventConstMap["Key_G"] = 0x47; m_EventConstMap["Key_H"] = 0x48; m_EventConstMap["Key_I"] = 0x49; m_EventConstMap["Key_J"] = 0x4a; m_EventConstMap["Key_K"] = 0x4b; m_EventConstMap["Key_L"] = 0x4c; m_EventConstMap["Key_M"] = 0x4d; m_EventConstMap["Key_N"] = 0x4e; m_EventConstMap["Key_O"] = 0x4f; m_EventConstMap["Key_P"] = 0x50; m_EventConstMap["Key_Q"] = 0x51; m_EventConstMap["Key_R"] = 0x52; m_EventConstMap["Key_S"] = 0x53; m_EventConstMap["Key_T"] = 0x54; m_EventConstMap["Key_U"] = 0x55; m_EventConstMap["Key_V"] = 0x56; m_EventConstMap["Key_W"] = 0x57; m_EventConstMap["Key_X"] = 0x58; m_EventConstMap["Key_Y"] = 0x59; m_EventConstMap["Key_Z"] = 0x5a; m_EventConstMap["Key_BracketLeft"] = 0x5b; m_EventConstMap["Key_Backslash"] = 0x5c; m_EventConstMap["Key_BracketRight"] = 0x5d; m_EventConstMap["Key_AsciiCircum"] = 0x5e; m_EventConstMap["Key_Underscore"] = 0x5f; m_EventConstMap["Key_QuoteLeft"] = 0x60; m_EventConstMap["Key_BraceLeft"] = 0x7b; m_EventConstMap["Key_Bar"] = 0x7c; m_EventConstMap["Key_BraceRight"] = 0x7d; m_EventConstMap["Key_AsciiTilde"] = 0x7e; m_EventConstMap["Key_nobreakspace"] = 0x0a0; m_EventConstMap["Key_exclamdown"] = 0x0a1; m_EventConstMap["Key_cent"] = 0x0a2; m_EventConstMap["Key_sterling"] = 0x0a3; m_EventConstMap["Key_currency"] = 0x0a4; m_EventConstMap["Key_yen"] = 0x0a5; m_EventConstMap["Key_brokenbar"] = 0x0a6; m_EventConstMap["Key_section"] = 0x0a7; m_EventConstMap["Key_diaeresis"] = 0x0a8; m_EventConstMap["Key_copyright"] = 0x0a9; m_EventConstMap["Key_ordfeminine"] = 0x0aa; m_EventConstMap["Key_guillemotleft"] = 0x0ab; m_EventConstMap["Key_notsign"] = 0x0ac; m_EventConstMap["Key_hyphen"] = 0x0ad; m_EventConstMap["Key_registered"] = 0x0ae; m_EventConstMap["Key_macron"] = 0x0af; m_EventConstMap["Key_degree"] = 0x0b0; m_EventConstMap["Key_plusminus"] = 0x0b1; m_EventConstMap["Key_twosuperior"] = 0x0b2; m_EventConstMap["Key_threesuperior"] = 0x0b3; m_EventConstMap["Key_acute"] = 0x0b4; m_EventConstMap["Key_mu"] = 0x0b5; m_EventConstMap["Key_paragraph"] = 0x0b6; m_EventConstMap["Key_periodcentered"] = 0x0b7; m_EventConstMap["Key_cedilla"] = 0x0b8; m_EventConstMap["Key_onesuperior"] = 0x0b9; m_EventConstMap["Key_masculine"] = 0x0ba; m_EventConstMap["Key_guillemotright"] = 0x0bb; m_EventConstMap["Key_onequarter"] = 0x0bc; m_EventConstMap["Key_onehalf"] = 0x0bd; m_EventConstMap["Key_threequarters"] = 0x0be; m_EventConstMap["Key_questiondown"] = 0x0bf; m_EventConstMap["Key_Agrave"] = 0x0c0; m_EventConstMap["Key_Aacute"] = 0x0c1; m_EventConstMap["Key_Acircumflex"] = 0x0c2; m_EventConstMap["Key_Atilde"] = 0x0c3; m_EventConstMap["Key_Adiaeresis"] = 0x0c4; m_EventConstMap["Key_Aring"] = 0x0c5; m_EventConstMap["Key_AE"] = 0x0c6; m_EventConstMap["Key_Ccedilla"] = 0x0c7; m_EventConstMap["Key_Egrave"] = 0x0c8; m_EventConstMap["Key_Eacute"] = 0x0c9; m_EventConstMap["Key_Ecircumflex"] = 0x0ca; m_EventConstMap["Key_Ediaeresis"] = 0x0cb; m_EventConstMap["Key_Igrave"] = 0x0cc; m_EventConstMap["Key_Iacute"] = 0x0cd; m_EventConstMap["Key_Icircumflex"] = 0x0ce; m_EventConstMap["Key_Idiaeresis"] = 0x0cf; m_EventConstMap["Key_ETH"] = 0x0d0; m_EventConstMap["Key_Ntilde"] = 0x0d1; m_EventConstMap["Key_Ograve"] = 0x0d2; m_EventConstMap["Key_Oacute"] = 0x0d3; m_EventConstMap["Key_Ocircumflex"] = 0x0d4; m_EventConstMap["Key_Otilde"] = 0x0d5; m_EventConstMap["Key_Odiaeresis"] = 0x0d6; m_EventConstMap["Key_multiply"] = 0x0d7; m_EventConstMap["Key_Ooblique"] = 0x0d8; m_EventConstMap["Key_Ugrave"] = 0x0d9; m_EventConstMap["Key_Uacute"] = 0x0da; m_EventConstMap["Key_Ucircumflex"] = 0x0db; m_EventConstMap["Key_Udiaeresis"] = 0x0dc; m_EventConstMap["Key_Yacute"] = 0x0dd; m_EventConstMap["Key_THORN"] = 0x0de; m_EventConstMap["Key_ssharp"] = 0x0df; m_EventConstMap["Key_agrave"] = 0x0e0; m_EventConstMap["Key_aacute"] = 0x0e1; m_EventConstMap["Key_acircumflex"] = 0x0e2; m_EventConstMap["Key_atilde"] = 0x0e3; m_EventConstMap["Key_adiaeresis"] = 0x0e4; m_EventConstMap["Key_aring"] = 0x0e5; m_EventConstMap["Key_ae"] = 0x0e6; m_EventConstMap["Key_ccedilla"] = 0x0e7; m_EventConstMap["Key_egrave"] = 0x0e8; m_EventConstMap["Key_eacute"] = 0x0e9; m_EventConstMap["Key_ecircumflex"] = 0x0ea; m_EventConstMap["Key_ediaeresis"] = 0x0eb; m_EventConstMap["Key_igrave"] = 0x0ec; m_EventConstMap["Key_iacute"] = 0x0ed; m_EventConstMap["Key_icircumflex"] = 0x0ee; m_EventConstMap["Key_idiaeresis"] = 0x0ef; m_EventConstMap["Key_eth"] = 0x0f0; m_EventConstMap["Key_ntilde"] = 0x0f1; m_EventConstMap["Key_ograve"] = 0x0f2; m_EventConstMap["Key_oacute"] = 0x0f3; m_EventConstMap["Key_ocircumflex"] = 0x0f4; m_EventConstMap["Key_otilde"] = 0x0f5; m_EventConstMap["Key_odiaeresis"] = 0x0f6; m_EventConstMap["Key_division"] = 0x0f7; m_EventConstMap["Key_oslash"] = 0x0f8; m_EventConstMap["Key_ugrave"] = 0x0f9; m_EventConstMap["Key_uacute"] = 0x0fa; m_EventConstMap["Key_ucircumflex"] = 0x0fb; m_EventConstMap["Key_udiaeresis"] = 0x0fc; m_EventConstMap["Key_yacute"] = 0x0fd; m_EventConstMap["Key_thorn"] = 0x0fe; m_EventConstMap["Key_ydiaeresis"] = 0x0ff; m_EventConstMap["Key_unknown"] = 0xffff; m_EventConstMap["Key_none"] = 0xffff; } mitk::EventMapper::~EventMapper() { } //##Documentation //## searches for the event in m_EventDescription and adds the corresponding eventID //## bool mitk::EventMapper::MapEvent(Event* event, GlobalInteraction* globalInteraction, int mitkPostedEventID ) { int eventID = mitkPostedEventID; if( mitkPostedEventID == 0 ) { //search the event in the list of event descriptions, if found, then take the number and produce a stateevent EventDescriptionVecIter iter; for (iter = m_EventDescriptions.begin(); iter!=m_EventDescriptions.end();iter++) { if (*iter == *event) break; } if (iter == m_EventDescriptions.end())//not found return false; eventID = (*iter).GetId(); } //set the Menger_Var m_StateEvent and send to StateMachine, which does everything further! m_StateEvent.Set( eventID, event ); /* Group and Object EventId: then EventMapper has the power to decide which operations hang together; each event causes n (n e N) operations (e.g. StateChanges, data-operations...). Undo must recall all these coherent operations, so all of the same objectId. But Undo has also the power to recall more operationsets, for example a set for building up a new object, so that a newly build up object is deleted after a Undo and not only the latest set point. The StateMachines::ExecuteAction have the power to descide weather a new GroupID has to be calculated (by example after the editing of a new object) A user interaction with the mouse is started by a mousePressEvent, continues with a MouseMove and finishes with a MouseReleaseEvent */ switch (event->GetType()) { case mitk::Type_MouseButtonPress://Increase mitk::OperationEvent::IncCurrObjectEventId(); break; case mitk::Type_MouseMove://same break; case mitk::Type_MouseButtonRelease://same break; case mitk::Type_User://same break; case mitk::Type_KeyPress://Increase mitk::OperationEvent::IncCurrObjectEventId(); break; default://increase mitk::OperationEvent::IncCurrObjectEventId(); } #ifdef MBI_INTERNAL_CONFERENCE //Conference - pass local events through if ( mitkPostedEventID == 0 ) { mitk::CoreObjectFactory::GetInstance()->MapEvent(event,eventID); } #endif //MBI_INTERNAL_CONFERENCE mitk::OperationEvent::ExecuteIncrement(); if ( globalInteraction != NULL ) { return globalInteraction->HandleEvent( &m_StateEvent ); } else { return mitk::GlobalInteraction::GetInstance()->HandleEvent(&m_StateEvent); } } bool mitk::EventMapper::LoadBehavior(std::string fileName) { if ( fileName.empty() ) return false; if (m_XmlFileName.length() > 0) { if (fileName.compare(m_XmlFileName) == 0) return true; // this is nothing bad, we already loaded this file. } this->SetFileName( fileName.c_str() ); m_XmlFileName = fileName.c_str(); return ( this->Parse() ); } bool mitk::EventMapper::LoadBehaviorString(std::string xmlString) { if ( xmlString.empty() ) return false; return ( this->Parse(xmlString.c_str(), xmlString.length()) ); } bool mitk::EventMapper::LoadStandardBehavior() { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Interactions/Legacy/StateMachine.xml"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Interactions/Legacy/StateMachine.xml"); if (!resource.IsValid()) { mitkThrow()<< ("Resource not valid. State machine pattern not found:Interactions/Legacy/StateMachine.xml" ); } - mitk::ModuleResourceStream stream(resource); + us::ModuleResourceStream stream(resource); std::string patternString((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); return this->LoadBehaviorString(patternString); } //##Documentation //## @brief converts the given const String declared in the xml-file //## to the defined const int inline int mitk::EventMapper::convertConstString2ConstInt(std::string input) { ConstMapIter tempIt = m_EventConstMap.find(input.c_str()); if (tempIt != m_EventConstMap.end()) { return (tempIt)->second; } //mitk::StatusBar::GetInstance()->DisplayText("Warning! from mitkEventMapper.cpp: Couldn't find matching Event Int from Event String in XML-File"); return -1;//for didn't find anything } void mitk::EventMapper::StartElement (const char *elementName, const char **atts) { if ( elementName == EVENT ) { // EventDescription(int type, int button, int buttonState,int key, std::string name, int id) EventDescription eventDescr( convertConstString2ConstInt( ReadXMLStringAttribut( TYPE, atts )), convertConstString2ConstInt( ReadXMLStringAttribut( BUTTON, atts )), ReadXMLIntegerAttribut( BUTTONSTATE, atts ), convertConstString2ConstInt( ReadXMLStringAttribut( KEY, atts )), ReadXMLStringAttribut( NAME, atts ), ReadXMLIntegerAttribut( ID, atts )); //check for a double entry unless it is an event for internal usage if (eventDescr.GetType()!= mitk::Type_User) { for (EventDescriptionVecIter iter = m_EventDescriptions.begin(); iter!=m_EventDescriptions.end(); iter++) { if (*iter == eventDescr) { MITK_DEBUG << "Event description " << eventDescr.GetName() << " already present! Skipping event description"; return; } } } m_EventDescriptions.push_back(eventDescr); } else if ( elementName == EVENTS ) m_StyleName = ReadXMLStringAttribut( STYLE, atts ); } std::string mitk::EventMapper::GetStyleName() const { return m_StyleName; } std::string mitk::EventMapper::ReadXMLStringAttribut( std::string name, const char** atts ) { if(atts) { const char** attsIter = atts; while(*attsIter) { if ( name == *attsIter ) { attsIter++; return *attsIter; } attsIter++; attsIter++; } } return std::string(); } int mitk::EventMapper::ReadXMLIntegerAttribut( std::string name, const char** atts ) { std::string s = ReadXMLStringAttribut( name, atts ); static const std::string hex = "0x"; int result; if ( s[0] == hex[0] && s[1] == hex[1] ) result = strtol( s.c_str(), NULL, 16 ); else result = atoi( s.c_str() ); return result; } void mitk::EventMapper::SetStateEvent(mitk::Event* event) { m_StateEvent.Set( m_StateEvent.GetId(), event ); } bool mitk::EventMapper::RefreshStateEvent(mitk::StateEvent* stateEvent) { //search the event within stateEvent in the list of event descriptions, if found adapt stateEvent ID EventDescriptionVecIter iter; for (iter = m_EventDescriptions.begin(); iter!=m_EventDescriptions.end(); iter++) { if (*iter == *(stateEvent->GetEvent())) break; } if (iter != m_EventDescriptions.end())//found { stateEvent->Set((*iter).GetId(), stateEvent->GetEvent()); return true; } else return false; return false; } void mitk::EventMapper::AddEventMapperAddOn(mitk::EventMapperAddOn* newAddOn) { bool addOnAlreadyAdded = false; for(AddOnVectorType::const_iterator it = this->m_AddOnVector.begin();it != m_AddOnVector.end();it++) { if(*it == newAddOn) { addOnAlreadyAdded = true; break; } } if(!addOnAlreadyAdded) { m_AddOnVector.push_back(newAddOn); MITK_INFO << "AddOn Count: " << m_AddOnVector.size(); } } void mitk::EventMapper::RemoveEventMapperAddOn(mitk::EventMapperAddOn* unusedAddOn) { for(AddOnVectorType::iterator it = this->m_AddOnVector.begin();it != m_AddOnVector.end();it++) { if(*it == unusedAddOn) { m_AddOnVector.erase(it); break; } } } diff --git a/Core/Code/Interactions/mitkEventStateMachine.cpp b/Core/Code/Interactions/mitkEventStateMachine.cpp index 9d75d07af2..2bfd32e03f 100644 --- a/Core/Code/Interactions/mitkEventStateMachine.cpp +++ b/Core/Code/Interactions/mitkEventStateMachine.cpp @@ -1,315 +1,310 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkEventStateMachine.h" #include "mitkStateMachineContainer.h" #include "mitkInteractionEvent.h" #include "mitkStateMachineAction.h" #include "mitkStateMachineCondition.h" #include "mitkStateMachineTransition.h" #include "mitkStateMachineState.h" -// us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" -#include "mitkModuleRegistry.h" mitk::EventStateMachine::EventStateMachine() : m_StateMachineContainer(NULL), m_CurrentState(NULL) { } -bool mitk::EventStateMachine::LoadStateMachine(const std::string& filename, const Module* module) +bool mitk::EventStateMachine::LoadStateMachine(const std::string& filename, const us::Module* module) { if (m_StateMachineContainer != NULL) { m_StateMachineContainer->Delete(); } m_StateMachineContainer = StateMachineContainer::New(); if (m_StateMachineContainer->LoadBehavior(filename, module)) { m_CurrentState = m_StateMachineContainer->GetStartState(); for(ConditionDelegatesMapType::iterator i = m_ConditionDelegatesMap.begin(); i != m_ConditionDelegatesMap.end(); ++i) { delete i->second; } m_ConditionDelegatesMap.clear(); // clear actions map ,and connect all actions as declared in sub-class for(std::map::iterator i = m_ActionFunctionsMap.begin(); i != m_ActionFunctionsMap.end(); ++i) { delete i->second; } m_ActionFunctionsMap.clear(); for(ActionDelegatesMapType::iterator i = m_ActionDelegatesMap.begin(); i != m_ActionDelegatesMap.end(); ++i) { delete i->second; } m_ActionDelegatesMap.clear(); ConnectActionsAndFunctions(); return true; } else { MITK_WARN<< "Unable to load StateMachine from file: " << filename; return false; } } mitk::EventStateMachine::~EventStateMachine() { if (m_StateMachineContainer != NULL) { m_StateMachineContainer->Delete(); } } void mitk::EventStateMachine::AddActionFunction(const std::string& action, mitk::TActionFunctor* functor) { if (!functor) return; // make sure double calls for same action won't cause memory leaks delete m_ActionFunctionsMap[action]; ActionDelegatesMapType::iterator i = m_ActionDelegatesMap.find(action); if (i != m_ActionDelegatesMap.end()) { delete i->second; m_ActionDelegatesMap.erase(i); } m_ActionFunctionsMap[action] = functor; } void mitk::EventStateMachine::AddActionFunction(const std::string& action, const ActionFunctionDelegate& delegate) { std::map::iterator i = m_ActionFunctionsMap.find(action); if (i != m_ActionFunctionsMap.end()) { delete i->second; m_ActionFunctionsMap.erase(i); } delete m_ActionDelegatesMap[action]; m_ActionDelegatesMap[action] = delegate.Clone(); } void mitk::EventStateMachine::AddConditionFunction(const std::string& condition, const ConditionFunctionDelegate& delegate) { m_ConditionDelegatesMap[condition] = delegate.Clone(); } bool mitk::EventStateMachine::HandleEvent(InteractionEvent* event, DataNode* dataNode) { if (!FilterEvents(event, dataNode)) { return false; } // Get the transition that can be executed mitk::StateMachineTransition::Pointer transition = GetExecutableTransition( event ); // check if the current state holds a transition that works with the given event. if ( transition.IsNotNull() ) { // all conditions are fulfilled so we can continue with the actions m_CurrentState = transition->GetNextState(); // iterate over all actions in this transition and execute them ActionVectorType actions = transition->GetActions(); for (ActionVectorType::iterator it = actions.begin(); it != actions.end(); ++it) { try { ExecuteAction(*it, event); } catch( const std::exception& e ) { MITK_ERROR << "Unhandled excaption caught in ExecuteAction(): " << e.what(); return false; } catch( ... ) { MITK_ERROR << "Unhandled excaption caught in ExecuteAction()"; return false; } } return true; } return false; } void mitk::EventStateMachine::ConnectActionsAndFunctions() { MITK_WARN<< "ConnectActionsAndFunctions in DataInteractor not implemented.\n DataInteractor will not be able to process any events."; } bool mitk::EventStateMachine::CheckCondition( const StateMachineCondition& condition, const InteractionEvent* event) { bool retVal = false; ConditionDelegatesMapType::iterator delegateIter = m_ConditionDelegatesMap.find(condition.GetConditionName()); if (delegateIter != m_ConditionDelegatesMap.end()) { retVal = delegateIter->second->Execute(event); } else { MITK_WARN << "No implementation of condition '" << condition.GetConditionName() << "' has been found."; } return retVal; } bool mitk::EventStateMachine::ExecuteAction(StateMachineAction* action, InteractionEvent* event) { if (action == NULL) { return false; } bool retVal = false; // Maps Action-Name to Functor and executes the Functor. ActionDelegatesMapType::iterator delegateIter = m_ActionDelegatesMap.find(action->GetActionName()); if (delegateIter != m_ActionDelegatesMap.end()) { retVal = delegateIter->second->Execute(action, event); } else { // try the legacy system std::map::iterator functionIter = m_ActionFunctionsMap.find(action->GetActionName()); if (functionIter != m_ActionFunctionsMap.end()) { retVal = functionIter->second->DoAction(action, event); } else { MITK_WARN << "No implementation of action '" << action->GetActionName() << "' has been found."; } } return retVal; } mitk::StateMachineState* mitk::EventStateMachine::GetCurrentState() const { return m_CurrentState.GetPointer(); } bool mitk::EventStateMachine::FilterEvents(InteractionEvent* interactionEvent, DataNode* dataNode) { if (dataNode == NULL) { MITK_WARN<< "EventStateMachine: Empty DataNode received along with this Event " << interactionEvent; return false; } bool visible = false; if (dataNode->GetPropertyList()->GetBoolProperty("visible", visible) == false) { //property doesn't exist return false; } return visible; } mitk::StateMachineTransition* mitk::EventStateMachine::GetExecutableTransition( mitk::InteractionEvent* event ) { // Map that will contain all conditions that are possibly used by the // transitions std::map conditionsMap; // Get a list of all transitions that match the given event mitk::StateMachineState::TransitionVector transitionList = m_CurrentState->GetTransitionList( event->GetNameOfClass(), MapToEventVariant(event) ); // if there are not transitions, we can return NULL here. if ( transitionList.empty() ) { return NULL; } StateMachineState::TransitionVector::iterator transitionIter; ConditionVectorType::iterator conditionIter; for( transitionIter=transitionList.begin(); transitionIter!=transitionList.end(); ++transitionIter ) { bool allConditionsFulfilled(true); // Get all conditions for the current transition ConditionVectorType conditions = (*transitionIter)->GetConditions(); for (conditionIter = conditions.begin(); conditionIter != conditions.end(); ++conditionIter) { bool currentConditionFulfilled(false); // sequentially check all conditions that we have evaluated above std::string conditionName = (*conditionIter).GetConditionName(); // Check if the condition has already been evaluated if ( conditionsMap.find(conditionName) == conditionsMap.end() ) { // if the condition has not been evaluated yet, do it now and store // the result in the map try { currentConditionFulfilled = CheckCondition( (*conditionIter), event ); conditionsMap.insert( std::pair(conditionName, currentConditionFulfilled) ); } catch (const std::exception& e) { MITK_ERROR << "Unhandled excaption caught in CheckCondition(): " << e.what(); currentConditionFulfilled = false; break; } catch (...) { MITK_ERROR << "Unhandled excaption caught in CheckCondition()"; currentConditionFulfilled = false; break; } } else { // if the condition has been evaluated before, use that result currentConditionFulfilled = conditionsMap[conditionName]; } // set 'allConditionsFulfilled' under consideration of a possible // inversion of the condition if ( currentConditionFulfilled == (*conditionIter).IsInverted() ) { allConditionsFulfilled = false; break; } } // If all conditions are fulfilled, we execute this transition if ( allConditionsFulfilled ) { return (*transitionIter); } } // We have found no transition that can be executed, return NULL return NULL; } diff --git a/Core/Code/Interactions/mitkEventStateMachine.h b/Core/Code/Interactions/mitkEventStateMachine.h index a86b7a9e93..8ef9aed728 100644 --- a/Core/Code/Interactions/mitkEventStateMachine.h +++ b/Core/Code/Interactions/mitkEventStateMachine.h @@ -1,220 +1,223 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKEVENTSTATEMACHINE_H_ #define MITKEVENTSTATEMACHINE_H_ #include "itkObject.h" #include "mitkCommon.h" #include "mitkMessage.h" #include "mitkInteractionEventHandler.h" #include #include +namespace us { +class Module; +} + namespace mitk { class StateMachineTransition; class StateMachineContainer; class StateMachineAction; class StateMachineCondition; class InteractionEvent; class StateMachineState; class DataNode; - class Module; /** * \class TActionFunctor * \brief Base class of ActionFunctors, to provide an easy to connect actions with functions. * * \deprecatedSince{2013_03} Use mitk::Message classes instead. */ class TActionFunctor { public: virtual bool DoAction(StateMachineAction*, InteractionEvent*)=0; virtual ~TActionFunctor() { } }; /** * \class TSpecificActionFunctor * Specific implementation of ActionFunctor class, implements a reference to the function which is to be executed. It takes two arguments: * StateMachineAction - the action by which the function call is invoked, InteractionEvent - the event that caused the transition. */ template class DEPRECATED() TSpecificActionFunctor : public TActionFunctor { public: TSpecificActionFunctor(T* object, bool (T::*memberFunctionPointer)(StateMachineAction*, InteractionEvent*)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~TSpecificActionFunctor() { } virtual bool DoAction(StateMachineAction* action, InteractionEvent* event) { return (*m_Object.*m_MemberFunctionPointer)(action, event);// executes member function } private: T* m_Object; bool (T::*m_MemberFunctionPointer)(StateMachineAction*, InteractionEvent*); }; /** Macro that can be used to connect a StateMachineAction with a function. * It assumes that there is a typedef Classname Self in classes that use this macro, as is provided by e.g. mitkClassMacro */ #define CONNECT_FUNCTION(a, f) \ EventStateMachine::AddActionFunction(a, MessageDelegate2(this, &Self::f)); #define CONNECT_CONDITION(a, f) \ EventStateMachine::AddConditionFunction(a, MessageDelegate1(this, &Self::f)); /** * \class EventStateMachine * * \brief Super-class that provides the functionality of a StateMachine to DataInteractors. * * A state machine is created by loading a state machine pattern. It consists of states, transitions and action. * The state represent the current status of the interaction, transitions are means to switch between states. Each transition * is triggered by an event and it is associated with actions that are to be executed when the state change is performed. * */ class MITK_CORE_EXPORT EventStateMachine : public mitk::InteractionEventHandler { public: mitkClassMacro(EventStateMachine, InteractionEventHandler) itkNewMacro(Self) typedef std::map DEPRECATED(ActionFunctionsMapType); typedef itk::SmartPointer StateMachineStateType; /** * @brief Loads XML resource * * Loads a XML resource file from the given module. * Default is the Mitk module (core). * The files have to be placed in the Resources/Interaction folder of their respective module. **/ - bool LoadStateMachine(const std::string& filename, const Module* module = NULL); + bool LoadStateMachine(const std::string& filename, const us::Module* module = NULL); /** * Receives Event from Dispatcher. * Event is mapped using the EventConfig Object to a variant, then it is checked if the StateMachine is listening for * such an Event. If this is the case, the transition to the next state it performed and all actions associated with the transition executed, * and true is returned to the caller. * If the StateMachine can't handle this event false is returned. * Attention: * If a transition is associated with multiple actions - "true" is returned if one action returns true, * and the event is treated as HANDLED even though some actions might not have been executed! So be sure that all actions that occur within * one transitions have the same conditions. */ bool HandleEvent(InteractionEvent* event, DataNode* dataNode); protected: EventStateMachine(); virtual ~EventStateMachine(); typedef MessageAbstractDelegate2 ActionFunctionDelegate; typedef MessageAbstractDelegate1 ConditionFunctionDelegate; /** * Connects action from StateMachine (String in XML file) with a function that is called when this action is to be executed. */ DEPRECATED(void AddActionFunction(const std::string& action, TActionFunctor* functor)); void AddActionFunction(const std::string& action, const ActionFunctionDelegate& delegate); void AddConditionFunction(const std::string& condition, const ConditionFunctionDelegate& delegate); StateMachineState* GetCurrentState() const; /** * Is called after loading a statemachine. * Overwrite this function in specific interactor implementations. * Connect actions and functions using the CONNECT_FUNCTION macro within this function. */ virtual void ConnectActionsAndFunctions(); virtual bool CheckCondition( const StateMachineCondition& condition, const InteractionEvent* interactionEvent ); /** * Looks up function that is associated with action and executes it. * To implement your own execution scheme overwrite this in your DataInteractor. */ virtual bool ExecuteAction(StateMachineAction* action, InteractionEvent* interactionEvent); /** * Implements filter scheme for events. * Standard implementation accepts events from 2d and 3d windows, * and rejects events if DataNode is not visible. * \return true if event is accepted, else false * * Overwrite this function to adapt for your own needs, for example to filter out events from * 3d windows like this: \code bool mitk::EventStateMachine::FilterEvents(InteractionEvent* interactionEvent, DataNode*dataNode) { return interactionEvent->GetSender()->GetMapperID() == BaseRenderer::Standard2D; // only 2D mappers } \endcode * or to enforce that the interactor only reacts when the corresponding DataNode is selected in the DataManager view.. */ virtual bool FilterEvents(InteractionEvent* interactionEvent, DataNode* dataNode); /** * \brief Returns the executable transition for the given event. * * This method takes a list of transitions that correspond to the given * event from the current state. * * This method iterates through all transitions and checks all * corresponding conditions. The results of each condition in stored in * map, as other transitions may need the same condition again. * * As soon as a transition is found for which all conditions are * fulfilled, this instance is returned. * * If a transition has no condition, it is automatically returned. * If no executable transition is found, NULL is returned. */ StateMachineTransition* GetExecutableTransition( InteractionEvent* event ); private: typedef std::map ActionDelegatesMapType; typedef std::map ConditionDelegatesMapType; StateMachineContainer* m_StateMachineContainer; // storage of all states, action, transitions on which the statemachine operates. std::map m_ActionFunctionsMap; // stores association between action string ActionDelegatesMapType m_ActionDelegatesMap; ConditionDelegatesMapType m_ConditionDelegatesMap; StateMachineStateType m_CurrentState; }; } /* namespace mitk */ #endif /* MITKEVENTSTATEMACHINE_H_ */ diff --git a/Core/Code/Interactions/mitkInteractionEventHandler.cpp b/Core/Code/Interactions/mitkInteractionEventHandler.cpp index 6d28d8da60..d1ba5eaa24 100644 --- a/Core/Code/Interactions/mitkInteractionEventHandler.cpp +++ b/Core/Code/Interactions/mitkInteractionEventHandler.cpp @@ -1,118 +1,118 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkInteractionEventHandler.h" #include "mitkInteractionEvent.h" mitk::InteractionEventHandler::InteractionEventHandler() : m_EventConfig() { } mitk::InteractionEventHandler::~InteractionEventHandler() { } -bool mitk::InteractionEventHandler::SetEventConfig(const std::string& filename, const Module* module) +bool mitk::InteractionEventHandler::SetEventConfig(const std::string& filename, const us::Module* module) { EventConfig newConfig(filename, module); if (newConfig.IsValid()) { m_EventConfig = newConfig; // notify sub-classes that new config is set ConfigurationChanged(); return true; } return false; } bool mitk::InteractionEventHandler::SetEventConfig(const EventConfig& config) { if (config.IsValid()) { m_EventConfig = config; // notify sub-classes that new config is set ConfigurationChanged(); return true; } return false; } mitk::EventConfig mitk::InteractionEventHandler::GetEventConfig() const { return m_EventConfig; } -bool mitk::InteractionEventHandler::AddEventConfig(const std::string& filename, const Module* module) +bool mitk::InteractionEventHandler::AddEventConfig(const std::string& filename, const us::Module* module) { if (!m_EventConfig.IsValid()) { MITK_ERROR<< "SetEventConfig has to be called before AddEventConfig can be used."; return false; } // notify sub-classes that new config is set bool success = m_EventConfig.AddConfig(filename, module); if (success) { ConfigurationChanged(); } return success; } bool mitk::InteractionEventHandler::AddEventConfig(const EventConfig& config) { if (!m_EventConfig.IsValid()) { MITK_ERROR<< "SetEventConfig has to be called before AddEventConfig can be used."; return false; } // notify sub-classes that new config is set bool success = m_EventConfig.AddConfig(config); if (success) { ConfigurationChanged(); } return success; } mitk::PropertyList::Pointer mitk::InteractionEventHandler::GetAttributes() const { if (m_EventConfig.IsValid()) { return m_EventConfig.GetAttributes(); } else { MITK_ERROR << "InteractionEventHandler::GetAttributes() requested, but not configuration loaded."; return NULL; } } std::string mitk::InteractionEventHandler::MapToEventVariant(InteractionEvent* interactionEvent) { if (m_EventConfig.IsValid()) { return m_EventConfig.GetMappedEvent(interactionEvent); } else { return ""; } } void mitk::InteractionEventHandler::ConfigurationChanged() { } diff --git a/Core/Code/Interactions/mitkInteractionEventHandler.h b/Core/Code/Interactions/mitkInteractionEventHandler.h index e2cc0e7273..566be8f2b2 100644 --- a/Core/Code/Interactions/mitkInteractionEventHandler.h +++ b/Core/Code/Interactions/mitkInteractionEventHandler.h @@ -1,133 +1,135 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKEVENTHANDLER_H_ #define MITKEVENTHANDLER_H_ #include "itkLightObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include #include "mitkEventConfig.h" #include "mitkPropertyList.h" #include +namespace us { +class Module; +} namespace mitk { - class Module; /** * \class EventHandler * Serves as a base class for all objects and classes that handle mitk::InteractionEvents. * * It provides an interface to load configuration objects map of events to variant names. */ class InteractionEvent; class MITK_CORE_EXPORT InteractionEventHandler : public itk::LightObject { public: mitkClassMacro(InteractionEventHandler, itk::LightObject) itkNewMacro(Self) /** * @brief Loads a configuration from an XML resource. * * Loads an event configuration from an XML resource file contained in the given module. * Default is the Mitk module (core). * The files have to be placed in the Resources/Interactions folder of their respective module. * This method will remove all existing configuration and replaces it with the new one. * * @see SetEventConfig(const EventConfig&) * * @param filename The resource name relative to the Interactions resource folder. * @param module The module containing the resource. Defaults to the Mitk module. * @return \c true if the resource was successfully loaded, \c false otherwise. */ - bool SetEventConfig(const std::string& filename, const Module* module = NULL); + bool SetEventConfig(const std::string& filename, const us::Module* module = NULL); /** * @brief Loads a configuration from an EventConfig object. * * Loads an event configuration from the given EventConfig object. This method will remove * all existing configuration and replaces it with the new one. * * @see SetEventConfig(const std::string&, const Module*) * * @param config The EventConfig object containing the new configuration. * @return \c true if the configuration was successfully loaded, \c false otherwise. */ bool SetEventConfig(const EventConfig& config); /** * @brief Returns the current configuration. * @return A EventConfig object representing the current event configuration. */ EventConfig GetEventConfig() const; /** * @brief This method \e extends the configuration. * * The configuration from the resource provided is loaded and only the ones conflicting are replaced by the new one. * This way several configuration files can be combined. * * @see AddEventConfig(const EventConfig&) * * @param filename The resource name relative to the Interactions resource folder. * @param module The module containing the resource. Defaults to the Mitk module. * @return \c true if the configuration was successfully added, \c false otherwise. */ - bool AddEventConfig(const std::string& filename, const Module* module = NULL); + bool AddEventConfig(const std::string& filename, const us::Module* module = NULL); /** * @brief This method \e extends the configuration. * The configuration from the EventConfig object is loaded and only the ones conflicting are replaced by the new one. * This way several configurations can be combined. * * @see AddEventConfig(const std::string&, const Module*) * * @param config The EventConfig object whose configuration should be added. * @return \c true if the configuration was successfully added, \c false otherwise. */ bool AddEventConfig(const EventConfig& config); protected: InteractionEventHandler(); virtual ~InteractionEventHandler(); /** * Returns a PropertyList in which the parameters defined in the config file are listed. */ PropertyList::Pointer GetAttributes() const; std::string MapToEventVariant(InteractionEvent* interactionEvent); /** * Is called whenever a new config object ist set. * Overwrite this method e.g. to initialize EventHandler with parameters in configuration file. */ virtual void ConfigurationChanged(); private: EventConfig m_EventConfig; }; } /* namespace mitk */ #endif /* MITKEVENTHANDLER_H_ */ diff --git a/Core/Code/Interactions/mitkMouseModeSwitcher.cpp b/Core/Code/Interactions/mitkMouseModeSwitcher.cpp index 5abf241d42..19fe9ddd6d 100644 --- a/Core/Code/Interactions/mitkMouseModeSwitcher.cpp +++ b/Core/Code/Interactions/mitkMouseModeSwitcher.cpp @@ -1,113 +1,113 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkMouseModeSwitcher.h" // us -#include "mitkGetModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleRegistry.h" +#include "usGetModuleContext.h" +#include "usModuleContext.h" + #include "mitkInteractionEventObserver.h" mitk::MouseModeSwitcher::MouseModeSwitcher() : m_ActiveInteractionScheme(MITK), m_ActiveMouseMode(MousePointer), m_CurrentObserver(NULL) { this->InitializeListeners(); this->SetInteractionScheme(m_ActiveInteractionScheme); } mitk::MouseModeSwitcher::~MouseModeSwitcher() { m_ServiceRegistration.Unregister(); } void mitk::MouseModeSwitcher::InitializeListeners() { if (m_CurrentObserver.IsNull()) { m_CurrentObserver = mitk::DisplayInteractor::New(); m_CurrentObserver->LoadStateMachine("DisplayInteraction.xml"); m_CurrentObserver->SetEventConfig("DisplayConfigMITK.xml"); // Register as listener via micro services - ServiceProperties props; + us::ServiceProperties props; props["name"] = std::string("DisplayInteractor"); - m_ServiceRegistration = GetModuleContext()->RegisterService( + m_ServiceRegistration = us::GetModuleContext()->RegisterService( m_CurrentObserver.GetPointer(),props); } } void mitk::MouseModeSwitcher::SetInteractionScheme(InteractionScheme scheme) { switch (scheme) { case MITK: { m_CurrentObserver->SetEventConfig("DisplayConfigMITK.xml"); } break; case PACS: { m_CurrentObserver->SetEventConfig("DisplayConfigPACS.xml"); } break; } m_ActiveInteractionScheme = scheme; this->InvokeEvent(MouseModeChangedEvent()); } void mitk::MouseModeSwitcher::SelectMouseMode(MouseMode mode) { if (m_ActiveInteractionScheme != PACS) return; switch (mode) { case MousePointer: { m_CurrentObserver->SetEventConfig("DisplayConfigPACS.xml"); break; } // case 0 case Scroll: { m_CurrentObserver->AddEventConfig("DisplayConfigPACSScroll.xml"); break; } case LevelWindow: { m_CurrentObserver->AddEventConfig("DisplayConfigPACSLevelWindow.xml"); break; } case Zoom: { m_CurrentObserver->AddEventConfig("DisplayConfigPACSZoom.xml"); break; } case Pan: { m_CurrentObserver->AddEventConfig("DisplayConfigPACSPan.xml"); break; } } // end switch (mode) m_ActiveMouseMode = mode; this->InvokeEvent(MouseModeChangedEvent()); } mitk::MouseModeSwitcher::MouseMode mitk::MouseModeSwitcher::GetCurrentMouseMode() const { return m_ActiveMouseMode; } diff --git a/Core/Code/Interactions/mitkMouseModeSwitcher.h b/Core/Code/Interactions/mitkMouseModeSwitcher.h index c3d54cf19b..d52a127439 100644 --- a/Core/Code/Interactions/mitkMouseModeSwitcher.h +++ b/Core/Code/Interactions/mitkMouseModeSwitcher.h @@ -1,129 +1,129 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKMouseModeSwitcher_H_HEADER_INCLUDED_C10DC4EB #define MITKMouseModeSwitcher_H_HEADER_INCLUDED_C10DC4EB #include "MitkExports.h" #include #include "mitkDisplayInteractor.h" namespace mitk { /*********************************************************************** * * \brief Class that offers a convenient way to switch between different * interaction schemes * * This class offers the possibility to switch between the two different * interaction schemes that are available: * - MITK : The original interaction scheme * - left mouse button : setting the cross position in the MPR view * - middle mouse button : panning * - right mouse button : zooming * * * - PACS : an alternative interaction scheme that behaves more like a * PACS workstation * - left mouse button : behavior depends on current MouseMode * - middle mouse button : fast scrolling * - right mouse button : level-window * - ctrl + right button : zooming * - shift+ right button : panning * * There are 5 different MouseModes that are available in the PACS scheme. * Each MouseMode defines the interaction that is performed on a left * mouse button click: * - Pointer : sets the cross position for the MPR * - Scroll * - Level-Window * - Zoom * - Pan * * When the interaction scheme or the MouseMode is changed, this class * manages the adding and removing of the relevant listeners offering * a convenient way to modify the interaction behavior. * ***********************************************************************/ class MITK_CORE_EXPORT MouseModeSwitcher : public itk::Object { public: #pragma GCC visibility push(default) /** \brief Can be observed by GUI class to update button states when mode is changed programatically. */ itkEventMacro( MouseModeChangedEvent, itk::AnyEvent ); #pragma GCC visibility pop mitkClassMacro( MouseModeSwitcher, itk::Object ); itkNewMacro(Self); // enum of the different interaction schemes that are available enum InteractionScheme { PACS = 0, MITK = 1 }; // enum of available mouse modes for PACS interaction scheme enum MouseMode { MousePointer = 0, Scroll, LevelWindow, Zoom, Pan }; /** * \brief Setter for interaction scheme */ void SetInteractionScheme( InteractionScheme ); /** * \brief Setter for mouse mode */ void SelectMouseMode( MouseMode mode ); /** * \brief Returns the current mouse mode */ MouseMode GetCurrentMouseMode() const; protected: MouseModeSwitcher(); virtual ~MouseModeSwitcher(); private: /** * \brief Initializes the listener with the MITK default behavior. */ void InitializeListeners(); InteractionScheme m_ActiveInteractionScheme; MouseMode m_ActiveMouseMode; DisplayInteractor::Pointer m_CurrentObserver; /** * Reference to the service registration of the observer, * it is needed to unregister the observer on unload. */ - ServiceRegistration m_ServiceRegistration; + us::ServiceRegistration m_ServiceRegistration; }; } // namespace mitk #endif /* MITKMouseModeSwitcher_H_HEADER_INCLUDED_C10DC4EB */ diff --git a/Core/Code/Interactions/mitkStateMachineContainer.cpp b/Core/Code/Interactions/mitkStateMachineContainer.cpp index 34304668b7..aaf4bfdb91 100755 --- a/Core/Code/Interactions/mitkStateMachineContainer.cpp +++ b/Core/Code/Interactions/mitkStateMachineContainer.cpp @@ -1,246 +1,246 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStateMachineContainer.h" #include #include #include #include // us -#include "mitkGetModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" +#include "usGetModuleContext.h" +#include "usModule.h" +#include "usModuleResource.h" +#include "usModuleResourceStream.h" /** * @brief This class builds up all the necessary structures for a statemachine. * and stores one start-state for all built statemachines. **/ //XML StateMachine Tags const std::string NAME = "name"; const std::string CONFIG = "statemachine"; const std::string STATE = "state"; const std::string STATEMODE = "state_mode"; const std::string TRANSITION = "transition"; const std::string EVENTCLASS = "event_class"; const std::string EVENTVARIANT = "event_variant"; const std::string STARTSTATE = "startstate"; const std::string TARGET = "target"; const std::string ACTION = "action"; const std::string CONDITION = "condition"; const std::string INVERTED = "inverted"; namespace mitk { vtkStandardNewMacro(StateMachineContainer); } mitk::StateMachineContainer::StateMachineContainer() : m_StartStateFound(false), m_errors(false) { } mitk::StateMachineContainer::~StateMachineContainer() { } /** * @brief Loads the xml file filename and generates the necessary instances. **/ -bool mitk::StateMachineContainer::LoadBehavior(const std::string& fileName, const Module* module) +bool mitk::StateMachineContainer::LoadBehavior(const std::string& fileName, const us::Module* module) { if (module == NULL) { - module = GetModuleContext()->GetModule(); + module = us::GetModuleContext()->GetModule(); } - mitk::ModuleResource resource = module->GetResource("Interactions/" + fileName); + us::ModuleResource resource = module->GetResource("Interactions/" + fileName); if (!resource.IsValid() ) { mitkThrow() << ("Resource not valid. State machine pattern not found:" + fileName); } - mitk::ModuleResourceStream stream(resource); + us::ModuleResourceStream stream(resource); this->SetStream(&stream); m_Filename = fileName; return this->Parse() && !m_errors; } mitk::StateMachineState::Pointer mitk::StateMachineContainer::GetStartState() const { return m_StartState; } /** * @brief sets the pointers in Transition (setNextState(..)) according to the extracted xml-file content **/ void mitk::StateMachineContainer::ConnectStates() { for (StateMachineCollectionType::iterator it = m_States.begin(); it != m_States.end(); ++it) { if ((*it)->ConnectTransitions(&m_States) == false) m_errors = true; } } void mitk::StateMachineContainer::StartElement(const char* elementName, const char **atts) { std::string name(elementName); if (name == CONFIG) { // } else if (name == STATE) { std::string stateName = ReadXMLStringAttribut(NAME, atts); std::transform(stateName.begin(), stateName.end(), stateName.begin(), ::toupper); std::string stateMode = ReadXMLStringAttribut(STATEMODE, atts); std::transform(stateMode.begin(), stateMode.end(), stateMode.begin(), ::toupper); bool isStartState = ReadXMLBooleanAttribut(STARTSTATE, atts); if (isStartState) { m_StartStateFound = true; } // sanitize state modes if (stateMode == "" || stateMode == "REGULAR") { stateMode = "REGULAR"; } else if (stateMode != "GRAB_INPUT" && stateMode != "PREFER_INPUT") { MITK_WARN<< "Invalid State Modus " << stateMode << ". Mode assumed to be REGULAR"; stateMode = "REGULAR"; } m_CurrState = mitk::StateMachineState::New(stateName, stateMode); if (isStartState) m_StartState = m_CurrState; } else if (name == TRANSITION) { std::string eventClass = ReadXMLStringAttribut(EVENTCLASS, atts); std::string eventVariant = ReadXMLStringAttribut(EVENTVARIANT, atts); std::string target = ReadXMLStringAttribut(TARGET, atts); std::transform(target.begin(), target.end(), target.begin(), ::toupper); mitk::StateMachineTransition::Pointer transition = mitk::StateMachineTransition::New(target, eventClass, eventVariant); if (m_CurrState) { m_CurrState->AddTransition(transition); } else { MITK_WARN<< "Malformed Statemachine Pattern. Transition has no origin. \n Will be ignored."; MITK_WARN<< "Malformed Transition details: target="<< target << ", event class:" << eventClass << ", event variant:"<< eventVariant ; } m_CurrTransition = transition; } else if (name == ACTION) { std::string actionName = ReadXMLStringAttribut(NAME, atts); mitk::StateMachineAction::Pointer action = mitk::StateMachineAction::New(actionName); if (m_CurrTransition) m_CurrTransition->AddAction(action); else MITK_WARN<< "Malformed state machine Pattern. Action without transition. \n Will be ignored."; } else if (name == CONDITION) { if (!m_CurrTransition) MITK_WARN<< "Malformed state machine Pattern. Condition without transition. \n Will be ignored."; std::string conditionName = ReadXMLStringAttribut(NAME, atts); std::string inverted = ReadXMLStringAttribut(INVERTED, atts); if ( inverted == "" || inverted == "false" ) { m_CurrTransition->AddCondition( mitk::StateMachineCondition( conditionName, false ) ); } else { m_CurrTransition->AddCondition( mitk::StateMachineCondition( conditionName, true ) ); } } } void mitk::StateMachineContainer::EndElement(const char* elementName) { std::string name(elementName); if (name == CONFIG) { if (m_StartState.IsNull()) { MITK_ERROR << "State machine pattern has no start state and cannot be used: " << m_Filename; } ConnectStates(); } else if (name == TRANSITION) { m_CurrTransition = NULL; } else if (name == ACTION) { // } else if (name == CONDITION) { // } else if (name == STATE) { m_States.push_back(m_CurrState); m_CurrState = NULL; } } std::string mitk::StateMachineContainer::ReadXMLStringAttribut(std::string name, const char** atts) { if (atts) { const char** attsIter = atts; while (*attsIter) { if (name == *attsIter) { attsIter++; return *attsIter; } attsIter++; attsIter++; } } return std::string(); } bool mitk::StateMachineContainer::ReadXMLBooleanAttribut(std::string name, const char** atts) { std::string s = ReadXMLStringAttribut(name, atts); std::transform(s.begin(), s.end(), s.begin(), ::toupper); if (s == "TRUE") return true; else return false; } diff --git a/Core/Code/Interactions/mitkStateMachineContainer.h b/Core/Code/Interactions/mitkStateMachineContainer.h index 1d89e3fe00..805df4af23 100755 --- a/Core/Code/Interactions/mitkStateMachineContainer.h +++ b/Core/Code/Interactions/mitkStateMachineContainer.h @@ -1,120 +1,122 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef STATEMACHINECONTAINER_H_HEADER_INCLUDED_C19AEDDD #define STATEMACHINECONTAINER_H_HEADER_INCLUDED_C19AEDDD #include #include #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkCommon.h" #include "mitkStateMachineState.h" #include "mitkStateMachineTransition.h" #include "mitkStateMachineAction.h" -namespace mitk { +namespace us { +class Module; +} - class Module; +namespace mitk { /** *@brief * * @ingroup Interaction **/ class StateMachineContainer : public vtkXMLParser { public: static StateMachineContainer *New(); vtkTypeMacro(StateMachineContainer,vtkXMLParser); /** * @brief This type holds all states of one statemachine. **/ typedef std::vector StateMachineCollectionType; /** * @brief Returns the StartState of the StateMachine. **/ StateMachineState::Pointer GetStartState() const; /** * @brief Loads XML resource * * Loads a XML resource file in the given module context. * The files have to be placed in the Resources/Interaction folder of their respective module. **/ - bool LoadBehavior(const std::string& fileName , const Module* module); + bool LoadBehavior(const std::string& fileName , const us::Module* module); /** * brief To enable StateMachine to access states **/ friend class InteractionStateMachine; protected: StateMachineContainer(); virtual ~StateMachineContainer(); /** * @brief Derived from XMLReader **/ void StartElement (const char* elementName, const char **atts); /** * @brief Derived from XMLReader **/ void EndElement (const char* elementName); private: /** * @brief Derived from XMLReader **/ std::string ReadXMLStringAttribut( std::string name, const char** atts); /** * @brief Derived from XMLReader **/ bool ReadXMLBooleanAttribut( std::string name, const char** atts ); /** * @brief Sets the pointers in Transition (setNextState(..)) according to the extracted xml-file content **/ void ConnectStates(); StateMachineState::Pointer m_StartState; StateMachineState::Pointer m_CurrState; StateMachineTransition::Pointer m_CurrTransition; StateMachineCollectionType m_States; bool m_StartStateFound; bool m_errors; // use member, because of inheritance from vtkXMLParser we can't return a success value for parsing the file. std::string m_Filename; // store file name for debug purposes. }; } // namespace mitk #endif /* STATEMACHINECONTAINER_H_HEADER_INCLUDED_C19AEDDD */ diff --git a/Core/Code/Interactions/mitkStateMachineFactory.cpp b/Core/Code/Interactions/mitkStateMachineFactory.cpp index 68c855cb0d..e795f66651 100755 --- a/Core/Code/Interactions/mitkStateMachineFactory.cpp +++ b/Core/Code/Interactions/mitkStateMachineFactory.cpp @@ -1,478 +1,479 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkStateMachineFactory.h" #include "mitkGlobalInteraction.h" #include #include #include #include #include // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" -#include "mitkModuleRegistry.h" +#include "usGetModuleContext.h" +#include "usModuleContext.h" +#include "usModule.h" +#include "usModuleResource.h" +#include "usModuleResourceStream.h" /** * @brief This class builds up all the necessary structures for a statemachine. * and stores one start-state for all built statemachines. **/ //mitk::StateMachineFactory::StartStateMap mitk::StateMachineFactory::m_StartStates; //mitk::StateMachineFactory::AllStateMachineMapType mitk::StateMachineFactory::m_AllStateMachineMap; //std::string mitk::StateMachineFactory::s_LastLoadedBehavior; //XML StateMachine const std::string STYLE = "STYLE"; const std::string NAME = "NAME"; const std::string ID = "ID"; const std::string START_STATE = "START_STATE"; const std::string NEXT_STATE_ID = "NEXT_STATE_ID"; const std::string EVENT_ID = "EVENT_ID"; const std::string SIDE_EFFECT_ID = "SIDE_EFFECT_ID"; const std::string ISTRUE = "TRUE"; const std::string ISFALSE = "FALSE"; const std::string CONFIG = "stateMachine"; const std::string STATE = "state"; const std::string TRANSITION = "transition"; const std::string STATE_MACHINE_NAME = "stateMachine"; const std::string ACTION = "action"; const std::string BOOL_PARAMETER = "boolParameter"; const std::string INT_PARAMETER = "intParameter"; const std::string FLOAT_PARAMETER = "floatParameter"; const std::string DOUBLE_PARAMETER = "doubleParameter"; const std::string STRING_PARAMETER = "stringParameter"; const std::string VALUE = "VALUE"; #include namespace mitk { vtkStandardNewMacro(StateMachineFactory); } mitk::StateMachineFactory::StateMachineFactory() : m_AktTransition(NULL) , m_AktStateMachineName("") , m_SkipStateMachine(false) { } mitk::StateMachineFactory::~StateMachineFactory() { //free memory while (!m_AllStateMachineMap.empty()) { StateMachineMapType* temp = m_AllStateMachineMap.begin()->second; m_AllStateMachineMap.erase(m_AllStateMachineMap.begin()); delete temp; } //should not be necessary due to SmartPointers m_StartStates.clear(); } /** * @brief Returns NULL if no entry with string type is found. **/ mitk::State* mitk::StateMachineFactory::GetStartState(const char * type) { StartStateMapIter tempState = m_StartStates.find(type); if (tempState != m_StartStates.end()) return (tempState)->second.GetPointer(); MITK_ERROR<< "Error in StateMachineFactory: StartState for pattern \""<< type<< "\"not found! StateMachine might not work!\n"; return NULL; } /** * @brief Loads the xml file filename and generates the necessary instances. **/ bool mitk::StateMachineFactory::LoadBehavior(std::string fileName) { if (fileName.empty()) return false; m_LastLoadedBehavior = fileName; this->SetFileName(fileName.c_str()); return this->Parse(); } /** * @brief Loads the xml string and generates the necessary instances. **/ bool mitk::StateMachineFactory::LoadBehaviorString(std::string xmlString) { if (xmlString.empty()) return false; m_LastLoadedBehavior = "String"; return (this->Parse(xmlString.c_str(), (unsigned int) xmlString.length())); } bool mitk::StateMachineFactory::LoadStandardBehavior() { - Module* module = ModuleRegistry::GetModule("Mitk"); - ModuleResource resource = module->GetResource("Interactions/Legacy/StateMachine.xml"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Interactions/Legacy/StateMachine.xml"); if (!resource.IsValid()) { mitkThrow()<< ("Resource not valid. State machine pattern not found:Interactions/Legacy/StateMachine.xml" ); } - mitk::ModuleResourceStream stream(resource); + us::ModuleResourceStream stream(resource); std::string patternString((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); return this->LoadBehaviorString(patternString); } /** * @brief Recursive method, that parses this brand of * the stateMachine; if the history has the same * size at the end, then the StateMachine is correct **/ bool mitk::StateMachineFactory::RParse(mitk::State::StateMap* states, mitk::State::StateMapIter thisState, HistorySet *history) { history->insert((thisState->second)->GetId()); //log our path //or thisState->first. but this seems safer std::set nextStatesSet = (thisState->second)->GetAllNextStates(); //remove loops in nextStatesSet; //nether do we have to go there, nor will it clear a deadlock std::set::iterator position = nextStatesSet.find((thisState->second)->GetId()); //look for the same state in nextStateSet if (position != nextStatesSet.end()) { //found the same state we are in! nextStatesSet.erase(position); //delete it, cause, we don't have to go there a second time! } //nextStatesSet is empty, so deadlock! if (nextStatesSet.empty()) { MITK_INFO<::iterator i = nextStatesSet.begin(); i != nextStatesSet.end(); i++) { if (history->find(*i) == history->end()) //if we haven't been in this nextstate { mitk::State::StateMapIter nextState = states->find(*i); //search the iterator for our nextState if (nextState == states->end()) { MITK_INFO<size() > 1) //only one state; don't have to be parsed for deadlocks! { //parse all the given states an check for deadlock or not connected states HistorySet *history = new HistorySet; mitk::State::StateMapIter firstState = states->begin(); //parse through all the given states, log the parsed elements in history bool ok = RParse(states, firstState, history); if ((states->size() == history->size()) && ok) { delete history; } else //ether !ok or sizeA!=sizeB { delete history; MITK_INFO<begin(); tempState != states->end(); tempState++) { //searched through the States and Connects all Transitions bool tempbool = ( ( tempState->second )->ConnectTransitions( states ) ); if ( tempbool == false ) { MITK_INFO< ok = m_AllStatesOfOneStateMachine.insert(mitk::State::StateMap::value_type(id , m_AktState)); if ( ok.second == false ) { MITK_INFO<AddTransition( transition )) { delete transition; m_AktTransition = const_cast(m_AktState->GetTransition(eventId)); } else { m_AktTransition = transition; } } } else if ( name == ACTION && m_AktTransition) { int actionId = ReadXMLIntegerAttribut( ID, atts ); m_AktAction = Action::New( actionId ); m_AktTransition->AddAction( m_AktAction ); } else if ( name == BOOL_PARAMETER ) { if ( !m_AktAction ) return; bool value = ReadXMLBooleanAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), BoolProperty::New( value ) ); } else if ( name == INT_PARAMETER ) { if ( !m_AktAction ) return; int value = ReadXMLIntegerAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), IntProperty::New( value ) ); } else if ( name == FLOAT_PARAMETER ) { if ( !m_AktAction ) return; float value = ReadXMLIntegerAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), FloatProperty::New( value ) ); } else if ( name == DOUBLE_PARAMETER ) { if ( !m_AktAction ) return; double value = ReadXMLDoubleAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), DoubleProperty::New( value ) ); } else if ( name == STRING_PARAMETER ) { if ( !m_AktAction ) return; std::string value = ReadXMLStringAttribut( VALUE, atts ); std::string name = ReadXMLStringAttribut( NAME, atts ); m_AktAction->AddProperty( name.c_str(), StringProperty::New( value ) ); } } void mitk::StateMachineFactory::EndElement(const char* elementName) { //bool ok = true; std::string name(elementName); //skip the state machine pattern because the name was not unique! if (m_SkipStateMachine && (name != CONFIG)) return; if (name == STATE_MACHINE_NAME) { if (m_SkipStateMachine) { m_SkipStateMachine = false; return; } /*ok =*/ConnectStates(&m_AllStatesOfOneStateMachine); m_AllStatesOfOneStateMachine.clear(); } else if (name == CONFIG) { //doesn't have to be done } else if (name == TRANSITION) { m_AktTransition = NULL; //pointer stored in its state. memory will be freed in destructor of class state } else if (name == ACTION) { m_AktAction = NULL; } else if (name == STATE) { m_AktState = NULL; } } std::string mitk::StateMachineFactory::ReadXMLStringAttribut(std::string name, const char** atts) { if (atts) { const char** attsIter = atts; while (*attsIter) { if (name == *attsIter) { attsIter++; return *attsIter; } attsIter++; attsIter++; } } return std::string(); } int mitk::StateMachineFactory::ReadXMLIntegerAttribut(std::string name, const char** atts) { std::string s = ReadXMLStringAttribut(name, atts); return atoi(s.c_str()); } float mitk::StateMachineFactory::ReadXMLFloatAttribut(std::string name, const char** atts) { std::string s = ReadXMLStringAttribut(name, atts); return (float) atof(s.c_str()); } double mitk::StateMachineFactory::ReadXMLDoubleAttribut(std::string name, const char** atts) { std::string s = ReadXMLStringAttribut(name, atts); return atof(s.c_str()); } bool mitk::StateMachineFactory::ReadXMLBooleanAttribut(std::string name, const char** atts) { std::string s = ReadXMLStringAttribut(name, atts); if (s == ISTRUE) return true; else return false; } mitk::State* mitk::StateMachineFactory::GetState(const char * type, int StateId) { //check if the state exists AllStateMachineMapType::iterator i = m_AllStateMachineMap.find(type); if (i == m_AllStateMachineMap.end()) return NULL; //get the statemachine of the state StateMachineMapType* sm = m_AllStateMachineMap[type]; //get the state from its statemachine if (sm != NULL) return (*sm)[StateId].GetPointer(); else return NULL; } bool mitk::StateMachineFactory::AddStateMachinePattern(const char * type, mitk::State* startState, mitk::StateMachineFactory::StateMachineMapType* allStatesOfStateMachine) { if (startState == NULL || allStatesOfStateMachine == NULL) return false; //check if the pattern has already been added StartStateMapIter tempState = m_StartStates.find(type); if (tempState != m_StartStates.end()) { MITK_WARN<< "Pattern " << type << " has already been added!\n"; return false; } //add the start state m_StartStates.insert(StartStateMap::value_type(type, startState)); //add all states of the new pattern to hold their references m_AllStateMachineMap.insert(AllStateMachineMapType::value_type(type, allStatesOfStateMachine)); return true; } diff --git a/Core/Code/Interfaces/mitkIDataNodeReader.h b/Core/Code/Interfaces/mitkIDataNodeReader.h index 5bbc13b399..f9b198674c 100644 --- a/Core/Code/Interfaces/mitkIDataNodeReader.h +++ b/Core/Code/Interfaces/mitkIDataNodeReader.h @@ -1,58 +1,58 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKIDATANODEREADER_H #define MITKIDATANODEREADER_H #include -#include +#include namespace mitk { class DataStorage; /** * \ingroup MicroServices_Interfaces * * This interface provides methods to load data from the local filesystem * into a given mitk::DataStorage. */ struct IDataNodeReader { virtual ~IDataNodeReader() {} /** * Reads the local file given by fileName and constructs one or more * mitk::DataNode instances which are added to the given mitk::DataStorage storage. * * \param fileName The absolute path to a local file. * \param storage The mitk::DataStorage which will contain the constructed data nodes. * \return The number of constructed mitk::DataNode instances. * * \note Errors during reading the file or constructing the data node should be expressed by * throwing appropriate exceptions. * * \see mitk::DataNodeFactory */ virtual int Read(const std::string& fileName, mitk::DataStorage& storage) = 0; }; } US_DECLARE_SERVICE_INTERFACE(mitk::IDataNodeReader, "org.mitk.IDataNodeReader") #endif // MITKIDATANODEREADER_H diff --git a/Core/Code/Interfaces/mitkIShaderRepository.h b/Core/Code/Interfaces/mitkIShaderRepository.h index ffa16dfdc6..3f8d8328ed 100644 --- a/Core/Code/Interfaces/mitkIShaderRepository.h +++ b/Core/Code/Interfaces/mitkIShaderRepository.h @@ -1,132 +1,132 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKISHADERREPOSITORY_H #define MITKISHADERREPOSITORY_H #include #include "mitkCommon.h" -#include "mitkServiceInterface.h" +#include "usServiceInterface.h" #include class vtkActor; namespace mitk { class DataNode; class BaseRenderer; /** * \brief Management class for vtkShader XML descriptions. * * Loads XML shader files from std::istream objects and adds default properties * for each shader object (shader uniforms) to the specified mitk::DataNode. * * Additionally, it provides a utility function for applying properties for shaders * in mappers. */ struct MITK_CORE_EXPORT IShaderRepository { struct ShaderPrivate; class MITK_CORE_EXPORT Shader : public itk::LightObject { public: mitkClassMacro( Shader, itk::Object ) itkFactorylessNewMacro( Self ) ~Shader(); int GetId() const; std::string GetName() const; std::string GetMaterialXml() const; protected: Shader(); void SetId(int id); void SetName(const std::string& name); void SetMaterialXml(const std::string& xml); private: // not implemented Shader(const Shader&); Shader& operator=(const Shader&); ShaderPrivate* d; }; virtual ~IShaderRepository(); virtual std::list GetShaders() const = 0; /** * \brief Return the named shader. * * \param name The shader name. * \return A Shader object. * * Names might not be unique. Use the shader id to uniquely identify a shader. */ virtual Shader::Pointer GetShader(const std::string& name) const = 0; /** * \brief Return the shader identified by the given id. * @param id The shader id. * @return The shader object or null if the id is unknown. */ virtual Shader::Pointer GetShader(int id) const = 0; /** \brief Adds all parsed shader uniforms to property list of the given DataNode; * used by mappers. */ virtual void AddDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) const = 0; /** \brief Applies shader and shader specific variables of the specified DataNode * to the VTK object by updating the shader variables of its vtkProperty. */ virtual void ApplyProperties(mitk::DataNode* node, vtkActor* actor, mitk::BaseRenderer* renderer, itk::TimeStamp& MTime) const = 0; /** \brief Loads a shader from a given file. Make sure that this stream is in the XML shader format. * * \return A unique id for the loaded shader which can be used to unload it. */ virtual int LoadShader(std::istream& stream, const std::string& name) = 0; /** * \brief Unload a previously loaded shader. * \param id The unique shader id returned by LoadShader. * \return \c true if the shader id was found and the shader was successfully unloaded, * \c false otherwise. */ virtual bool UnloadShader(int id) = 0; }; } US_DECLARE_SERVICE_INTERFACE(mitk::IShaderRepository, "org.mitk.services.IShaderRepository/1.0") #endif // MITKISHADERREPOSITORY_H diff --git a/Core/Code/Interfaces/mitkInteractionEventObserver.h b/Core/Code/Interfaces/mitkInteractionEventObserver.h index fc22d9567a..328b1e5eed 100644 --- a/Core/Code/Interfaces/mitkInteractionEventObserver.h +++ b/Core/Code/Interfaces/mitkInteractionEventObserver.h @@ -1,69 +1,69 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef InteractionEventObserver_h #define InteractionEventObserver_h #include -#include "mitkServiceInterface.h" +#include "usServiceInterface.h" #include "mitkInteractionEvent.h" namespace mitk { /** * \class InteractionEventObserver * \brief Base class to implement InteractionEventObservers. * * This class also provides state machine infrastructure, * but usage thereof is optional. See the Notify method for more information. */ struct MITK_CORE_EXPORT InteractionEventObserver { InteractionEventObserver(); virtual ~InteractionEventObserver(); /** * By this method all registered EventObersers are notified about every InteractionEvent, * the isHandled flag indicates if a DataInteractor has already handled that event. * InteractionEventObserver that trigger an action when observing an event may consider * this in order to not confuse the user by, triggering several independent action with one * single user event (such as a mouse click) * * If you want to use the InteractionEventObserver as a state machine give the event to the state machine by implementing, e.g. \code void mitk::InteractionEventObserver::Notify(InteractionEvent::Pointer interactionEvent, bool isHandled) { if (!isHandled) { this->HandleEvent(interactionEvent, NULL); } } \endcode * This overwrites the FilterEvents function of the EventStateMachine to ignore the DataNode, since InteractionEventObservers are not associated with one. virtual bool FilterEvents(InteractionEvent* interactionEvent, DataNode* dataNode); */ virtual void Notify(InteractionEvent* interactionEvent,bool isHandled) = 0; void Disable(); void Enable(); bool IsEnabled() const; private: bool m_IsEnabled; }; } /* namespace mitk */ US_DECLARE_SERVICE_INTERFACE(mitk::InteractionEventObserver, "org.mitk.InteractionEventObserver") #endif /* InteractionEventObserver_h */ diff --git a/Core/Code/Rendering/mitkShaderRepository.cpp b/Core/Code/Rendering/mitkShaderRepository.cpp index 20e1fd81b3..6d44c6a411 100644 --- a/Core/Code/Rendering/mitkShaderRepository.cpp +++ b/Core/Code/Rendering/mitkShaderRepository.cpp @@ -1,520 +1,454 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #define SR_INFO MITK_INFO("shader.repository") #define SR_WARN MITK_WARN("shader.repository") #define SR_ERROR MITK_ERROR("shader.repository") #include "mitkShaderRepository.h" #include "mitkShaderProperty.h" #include "mitkProperties.h" #include "mitkDataNode.h" #include #include #include #include #include #include #include int mitk::ShaderRepository::shaderId = 0; const bool mitk::ShaderRepository::debug = false; mitk::ShaderRepository::ShaderRepository() { LoadShaders(); } mitk::ShaderRepository::~ShaderRepository() { } -mitk::ShaderRepository *mitk::ShaderRepository::GetGlobalShaderRepository() -{ - static mitk::ShaderRepository::Pointer i; - - if(i.IsNull()) - { - i=mitk::ShaderRepository::New(); - } - - return i; -} - - void mitk::ShaderRepository::LoadShaders() { itk::Directory::Pointer dir = itk::Directory::New(); std::string dirPath = "./vtk_shader"; if( dir->Load( dirPath.c_str() ) ) { int n = dir->GetNumberOfFiles(); for(int r=0;rGetFile( r ); std::string extension = itksys::SystemTools::GetFilenameExtension(filename); if(extension.compare(".xml")==0) { Shader::Pointer element=Shader::New(); element->SetName(itksys::SystemTools::GetFilenameWithoutExtension(filename)); std::string filePath = dirPath + std::string("/") + element->GetName() + std::string(".xml"); - element->path = filePath; SR_INFO << "found shader '" << element->GetName() << "'"; - element->LoadProperties(filePath); + std::ifstream fileStream(filePath.c_str()); + element->LoadProperties(fileStream); shaders.push_back(element); } } } } mitk::ShaderRepository::Shader::Pointer mitk::ShaderRepository::GetShaderImpl(const std::string &name) const { std::list::const_iterator i = shaders.begin(); while( i != shaders.end() ) { if( (*i)->GetName() == name) return (*i); i++; } return Shader::Pointer(); } -int mitk::ShaderRepository::LoadShader(const std::string& filename) -{ - std::string extension = itksys::SystemTools::GetFilenameExtension(filename); - if (extension.compare(".xml")==0) - { - Shader::Pointer element=Shader::New(); - element->SetName(itksys::SystemTools::GetFilenameWithoutExtension(filename)); - element->name = element->GetName(); - element->path = filename; - element->SetId(shaderId++); - element->LoadProperties(filename); - shaders.push_back(element); - SR_INFO(debug) << "found shader '" << element->GetName() << "'"; - return element->GetId(); - } - else - { - SR_INFO(debug) << "Error: no xml shader file!"; - return -1; - } -} - int mitk::ShaderRepository::LoadShader(std::istream& stream, const std::string& filename) { Shader::Pointer element=Shader::New(); element->SetName(filename); - element->name = filename; element->SetId(shaderId++); element->LoadProperties(stream); shaders.push_back(element); SR_INFO(debug) << "found shader '" << element->GetName() << "'"; return element->GetId(); } bool mitk::ShaderRepository::UnloadShader(int id) { for (std::list::iterator i = shaders.begin(); i != shaders.end(); ++i) { if ((*i)->GetId() == id) { shaders.erase(i); return true; } } return false; } mitk::ShaderRepository::Shader::Shader() { } mitk::ShaderRepository::Shader::~Shader() { } -void mitk::ShaderRepository::Shader::LoadPropertiesFromPath() -{ - LoadProperties(path); -} - void mitk::ShaderRepository::Shader::LoadProperties(vtkProperty* p) { vtkXMLMaterial *m=p->GetMaterial(); if (m == NULL) return; // Vertexshader uniforms { vtkXMLShader *s=m->GetVertexShader(); if (s) { vtkXMLDataElement *x=s->GetRootElement(); int n=x->GetNumberOfNestedElements(); for(int r=0;rGetNestedElement(r); if(!strcmp(y->GetName(),"ApplicationUniform")) { Uniform::Pointer element=Uniform::New(); element->LoadFromXML(y); uniforms.push_back(element); } } } } // Fragmentshader uniforms { vtkXMLShader *s=m->GetFragmentShader(); if (s) { vtkXMLDataElement *x=s->GetRootElement(); int n=x->GetNumberOfNestedElements(); for(int r=0;rGetNestedElement(r); if(!strcmp(y->GetName(),"ApplicationUniform")) { Uniform::Pointer element=Uniform::New(); element->LoadFromXML(y); uniforms.push_back(element); } } } } } -void mitk::ShaderRepository::Shader::LoadProperties(const std::string& path) -{ - vtkProperty *p = vtkProperty::New(); - p->LoadMaterial(path.c_str()); - LoadProperties(p); - p->Delete(); -} - void mitk::ShaderRepository::Shader::LoadProperties(std::istream& stream) { std::string content; content.reserve(2048); char buffer[2048]; while (stream.read(buffer, sizeof(buffer))) { content.append(buffer, sizeof(buffer)); } content.append(buffer, static_cast(stream.gcount())); if (content.empty()) return; this->SetMaterialXml(content); vtkProperty *p = vtkProperty::New(); p->LoadMaterialFromString(content.c_str()); LoadProperties(p); p->Delete(); } mitk::ShaderRepository::Shader::Uniform::Uniform() { } mitk::ShaderRepository::Shader::Uniform::~Uniform() { } -mitk::ShaderRepository::Shader *mitk::ShaderRepository::GetShader(const char *id) const -{ - std::list::const_iterator i = shaders.begin(); - - while( i != shaders.end() ) - { - if( (*i)->GetName() ==id) - return (*i); - - i++; - } - - return 0; -} - - void mitk::ShaderRepository::Shader::Uniform::LoadFromXML(vtkXMLDataElement *y) { //MITK_INFO << "found uniform '" << y->GetAttribute("name") << "' type=" << y->GetAttribute("type");// << " default=" << y->GetAttribute("value"); name = y->GetAttribute("name"); const char *sType=y->GetAttribute("type"); if(!strcmp(sType,"float")) type=glsl_float; else if(!strcmp(sType,"vec2")) type=glsl_vec2; else if(!strcmp(sType,"vec3")) type=glsl_vec3; else if(!strcmp(sType,"vec4")) type=glsl_vec4; else if(!strcmp(sType,"int")) type=glsl_int; else if(!strcmp(sType,"ivec2")) type=glsl_ivec2; else if(!strcmp(sType,"ivec3")) type=glsl_ivec3; else if(!strcmp(sType,"ivec4")) type=glsl_ivec4; else { type=glsl_none; SR_WARN << "unknown type for uniform '" << name << "'" ; } defaultFloat[0]=defaultFloat[1]=defaultFloat[2]=defaultFloat[3]=0; - /* + /* const char *sDefault=y->GetAttribute("value"); switch(type) { case glsl_float: sscanf(sDefault,"%f",&defaultFloat[0]); break; case glsl_vec2: sscanf(sDefault,"%f %f",&defaultFloat[0],&defaultFloat[1]); break; case glsl_vec3: sscanf(sDefault,"%f %f %f",&defaultFloat[0],&defaultFloat[1],&defaultFloat[2]); break; case glsl_vec4: sscanf(sDefault,"%f %f %f %f",&defaultFloat[0],&defaultFloat[1],&defaultFloat[2],&defaultFloat[3]); break; - } */ + } + */ } - - void mitk::ShaderRepository::AddDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) const { node->AddProperty( "shader", mitk::ShaderProperty::New(), renderer, overwrite ); std::list::const_iterator i = shaders.begin(); while( i != shaders.end() ) { std::list *l = (*i)->GetUniforms(); std::string shaderName = (*i)->GetName(); std::list::const_iterator j = l->begin(); while( j != l->end() ) { std::string propertyName = "shader." + shaderName + "." + (*j)->name; switch( (*j)->type ) { case Shader::Uniform::glsl_float: node->AddProperty( propertyName.c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[0] ), renderer, overwrite ); break; case Shader::Uniform::glsl_vec2: node->AddProperty( (propertyName+".x").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[0] ), renderer, overwrite ); node->AddProperty( (propertyName+".y").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[1] ), renderer, overwrite ); break; case Shader::Uniform::glsl_vec3: node->AddProperty( (propertyName+".x").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[0] ), renderer, overwrite ); node->AddProperty( (propertyName+".y").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[1] ), renderer, overwrite ); node->AddProperty( (propertyName+".z").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[2] ), renderer, overwrite ); break; case Shader::Uniform::glsl_vec4: node->AddProperty( (propertyName+".x").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[0] ), renderer, overwrite ); node->AddProperty( (propertyName+".y").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[1] ), renderer, overwrite ); node->AddProperty( (propertyName+".z").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[2] ), renderer, overwrite ); node->AddProperty( (propertyName+".w").c_str(), mitk::FloatProperty::New( (*j)->defaultFloat[3] ), renderer, overwrite ); break; default: break; } j++; } i++; } } void mitk::ShaderRepository::ApplyProperties(mitk::DataNode* node, vtkActor *actor, mitk::BaseRenderer* renderer,itk::TimeStamp &MTime) const { bool setMTime = false; vtkProperty* property = actor->GetProperty(); unsigned long ts = MTime.GetMTime(); mitk::ShaderProperty *sep= dynamic_cast(node->GetProperty("shader",renderer)); if(!sep) { property->ShadingOff(); return; } std::string shader=sep->GetValueAsString(); // Need update pipeline mode if(sep->GetMTime() > ts) { if(shader.compare("fixed")==0) { //MITK_INFO << "disabling shader"; property->ShadingOff(); } else { Shader::Pointer s=GetShaderImpl(shader); if(s.IsNotNull()) { //MITK_INFO << "enabling shader"; property->ShadingOn(); property->LoadMaterialFromString(s->GetMaterialXml().c_str()); } } setMTime = true; } if(shader.compare("fixed")!=0) { Shader::Pointer s=GetShaderImpl(shader); if(s.IsNull()) return; std::list::const_iterator j = s->uniforms.begin(); while( j != s->uniforms.end() ) { std::string propertyName = "shader." + s->GetName() + "." + (*j)->name; // MITK_INFO << "querying property: " << propertyName; // mitk::BaseProperty *p = node->GetProperty( propertyName.c_str(), renderer ); // if( p && p->GetMTime() > MTime.GetMTime() ) { float fval[4]; // MITK_INFO << "copying property " << propertyName << " ->->- " << (*j)->name << " type=" << (*j)->type ; switch( (*j)->type ) { case Shader::Uniform::glsl_float: node->GetFloatProperty( propertyName.c_str(), fval[0], renderer ); property->AddShaderVariable( (*j)->name.c_str(), 1 , fval ); break; case Shader::Uniform::glsl_vec2: node->GetFloatProperty( (propertyName+".x").c_str(), fval[0], renderer ); node->GetFloatProperty( (propertyName+".y").c_str(), fval[1], renderer ); property->AddShaderVariable( (*j)->name.c_str(), 2 , fval ); break; case Shader::Uniform::glsl_vec3: node->GetFloatProperty( (propertyName+".x").c_str(), fval[0], renderer ); node->GetFloatProperty( (propertyName+".y").c_str(), fval[1], renderer ); node->GetFloatProperty( (propertyName+".z").c_str(), fval[2], renderer ); property->AddShaderVariable( (*j)->name.c_str(), 3 , fval ); break; case Shader::Uniform::glsl_vec4: node->GetFloatProperty( (propertyName+".x").c_str(), fval[0], renderer ); node->GetFloatProperty( (propertyName+".y").c_str(), fval[1], renderer ); node->GetFloatProperty( (propertyName+".z").c_str(), fval[2], renderer ); node->GetFloatProperty( (propertyName+".w").c_str(), fval[3], renderer ); property->AddShaderVariable( (*j)->name.c_str(), 4 , fval ); break; default: break; } //setMTime=true; } j++; } } if(setMTime) MTime.Modified(); } std::list mitk::ShaderRepository::GetShaders() const { std::list result; for (std::list::const_iterator i = shaders.begin(); i != shaders.end(); ++i) { result.push_back(i->GetPointer()); } return result; } mitk::IShaderRepository::Shader::Pointer mitk::ShaderRepository::GetShader(const std::string& name) const { for (std::list::const_iterator i = shaders.begin(); i != shaders.end(); ++i) { if ((*i)->GetName() == name) return i->GetPointer(); } return IShaderRepository::Shader::Pointer(); } mitk::IShaderRepository::Shader::Pointer mitk::ShaderRepository::GetShader(int id) const { for (std::list::const_iterator i = shaders.begin(); i != shaders.end(); ++i) { if ((*i)->GetId() == id) return i->GetPointer(); } return IShaderRepository::Shader::Pointer(); } diff --git a/Core/Code/Rendering/mitkShaderRepository.h b/Core/Code/Rendering/mitkShaderRepository.h index 905352bf9c..abe926baab 100644 --- a/Core/Code/Rendering/mitkShaderRepository.h +++ b/Core/Code/Rendering/mitkShaderRepository.h @@ -1,197 +1,162 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITKSHADERREPOSITORY_H_ #define _MITKSHADERREPOSITORY_H_ -#include - #include "mitkIShaderRepository.h" class vtkXMLDataElement; class vtkProperty; namespace mitk { /** * \brief Management class for vtkShader XML descriptions. * * Looks for all XML shader files in a given directory and adds default properties * for each shader object (shader uniforms) to the specified mitk::DataNode. * * Additionally, it provides a utility function for applying properties for shaders * in mappers. - * - * \deprecatedSince{2013_03} Use the micro service interface IShaderRepository instead. */ -class MITK_CORE_EXPORT ShaderRepository : public itk::LightObject, public IShaderRepository +class ShaderRepository : public IShaderRepository { -public: - - mitkClassMacro( ShaderRepository, itk::LightObject ) - itkFactorylessNewMacro( Self ) - - DEPRECATED(static ShaderRepository *GetGlobalShaderRepository()); +protected: - /** - * \deprecatedSince{2013_03} Use IShaderRepository::Shader instead. - */ class Shader : public IShaderRepository::Shader { public: mitkClassMacro( Shader, itk::Object ) itkFactorylessNewMacro( Self ) class Uniform : public itk::Object { public: mitkClassMacro( Uniform, itk::Object ) itkFactorylessNewMacro( Self ) enum Type { glsl_none, glsl_float, glsl_vec2, glsl_vec3, glsl_vec4, glsl_int, glsl_ivec2, glsl_ivec3, glsl_ivec4 }; /** * Constructor */ Uniform(); /** * Destructor */ ~Uniform(); Type type; std::string name; int defaultInt[4]; float defaultFloat[4]; void LoadFromXML(vtkXMLDataElement *e); }; std::list uniforms; /** * Constructor */ Shader(); /** * Destructor */ ~Shader(); - // DEPRECATED since 2013.03 - std::string name; - // DEPRECATED since 2013.03 - std::string path; - - DEPRECATED(void LoadPropertiesFromPath()); - Uniform *GetUniform(char * /*id*/) { return 0; } std::list *GetUniforms() { return &uniforms; } private: friend class ShaderRepository; void LoadProperties(vtkProperty* prop); - void LoadProperties(const std::string& path); void LoadProperties(std::istream& stream); }; + void LoadShaders(); + Shader::Pointer GetShaderImpl(const std::string& name) const; -protected: +private: std::list shaders; - void LoadShaders(); + static int shaderId; + static const bool debug; - Shader::Pointer GetShaderImpl(const std::string& name) const; +public: /** * Constructor */ ShaderRepository(); /** * Destructor */ ~ShaderRepository(); -private: - - static int shaderId; - static const bool debug; - -public: - - DEPRECATED(std::list *GetShaders()) - { - return &shaders; - } - - DEPRECATED(Shader *GetShader(const char *id) const); - std::list GetShaders() const; IShaderRepository::Shader::Pointer GetShader(const std::string& name) const; IShaderRepository::Shader::Pointer GetShader(int id) const; /** \brief Adds all parsed shader uniforms to property list of the given DataNode; * used by mappers. */ void AddDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) const; /** \brief Applies shader and shader specific variables of the specified DataNode * to the VTK object by updating the shader variables of its vtkProperty. */ void ApplyProperties(mitk::DataNode* node, vtkActor *actor, mitk::BaseRenderer* renderer,itk::TimeStamp &MTime) const; - /** \brief Loads a shader from a given file. Make sure that this file is in the XML shader format. - */ - DEPRECATED(int LoadShader(const std::string& filename)); - int LoadShader(std::istream& stream, const std::string& name); bool UnloadShader(int id); }; } //end of namespace mitk #endif diff --git a/Core/Code/Rendering/mitkSurfaceVtkMapper3D.cpp b/Core/Code/Rendering/mitkSurfaceVtkMapper3D.cpp index 307a06e52d..e347a0166c 100644 --- a/Core/Code/Rendering/mitkSurfaceVtkMapper3D.cpp +++ b/Core/Code/Rendering/mitkSurfaceVtkMapper3D.cpp @@ -1,511 +1,503 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSurfaceVtkMapper3D.h" #include "mitkDataNode.h" #include "mitkProperties.h" #include "mitkColorProperty.h" #include "mitkLookupTableProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkScalarModeProperty.h" #include "mitkClippingProperty.h" #include "mitkSmartPointerProperty.h" #include "mitkShaderProperty.h" #include "mitkIShaderRepository.h" #include #include #include //VTK #include #include #include #include #include #include #include #include const mitk::Surface* mitk::SurfaceVtkMapper3D::GetInput() { return static_cast ( GetDataNode()->GetData() ); } mitk::SurfaceVtkMapper3D::SurfaceVtkMapper3D() { // m_Prop3D = vtkActor::New(); m_GenerateNormals = false; } mitk::SurfaceVtkMapper3D::~SurfaceVtkMapper3D() { // m_Prop3D->Delete(); } void mitk::SurfaceVtkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer* renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if(!visible) { ls->m_Actor->VisibilityOff(); return; } // // set the input-object at time t for the mapper // mitk::Surface::Pointer input = const_cast< mitk::Surface* >( this->GetInput() ); vtkPolyData * polydata = input->GetVtkPolyData( this->GetTimestep() ); if(polydata == NULL) { ls->m_Actor->VisibilityOff(); return; } if ( m_GenerateNormals ) { ls->m_VtkPolyDataNormals->SetInput( polydata ); ls->m_VtkPolyDataMapper->SetInput( ls->m_VtkPolyDataNormals->GetOutput() ); } else { ls->m_VtkPolyDataMapper->SetInput( polydata ); } // // apply properties read from the PropertyList // ApplyAllProperties(renderer, ls->m_Actor); if(visible) ls->m_Actor->VisibilityOn(); } void mitk::SurfaceVtkMapper3D::ResetMapper( BaseRenderer* renderer ) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); ls->m_Actor->VisibilityOff(); } void mitk::SurfaceVtkMapper3D::ApplyMitkPropertiesToVtkProperty(mitk::DataNode *node, vtkProperty* property, mitk::BaseRenderer* renderer) { // Backface culling { mitk::BoolProperty::Pointer p; node->GetProperty(p, "Backface Culling", renderer); bool useCulling = false; if(p.IsNotNull()) useCulling = p->GetValue(); property->SetBackfaceCulling(useCulling); } // Colors { double ambient [3] = { 0.5,0.5,0.0 }; double diffuse [3] = { 0.5,0.5,0.0 }; double specular[3] = { 1.0,1.0,1.0 }; float coeff_ambient = 0.5f; float coeff_diffuse = 0.5f; float coeff_specular= 0.5f; float power_specular=10.0f; // Color { mitk::ColorProperty::Pointer p; node->GetProperty(p, "color", renderer); if(p.IsNotNull()) { mitk::Color c = p->GetColor(); ambient[0]=c.GetRed(); ambient[1]=c.GetGreen(); ambient[2]=c.GetBlue(); diffuse[0]=c.GetRed(); diffuse[1]=c.GetGreen(); diffuse[2]=c.GetBlue(); // Setting specular color to the same, make physically no real sense, however vtk rendering slows down, if these colors are different. specular[0]=c.GetRed(); specular[1]=c.GetGreen(); specular[2]=c.GetBlue(); } } // Ambient { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.ambientColor", renderer); if(p.IsNotNull()) { mitk::Color c = p->GetColor(); ambient[0]=c.GetRed(); ambient[1]=c.GetGreen(); ambient[2]=c.GetBlue(); } } // Diffuse { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.diffuseColor", renderer); if(p.IsNotNull()) { mitk::Color c = p->GetColor(); diffuse[0]=c.GetRed(); diffuse[1]=c.GetGreen(); diffuse[2]=c.GetBlue(); } } // Specular { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.specularColor", renderer); if(p.IsNotNull()) { mitk::Color c = p->GetColor(); specular[0]=c.GetRed(); specular[1]=c.GetGreen(); specular[2]=c.GetBlue(); } } // Ambient coeff { node->GetFloatProperty("material.ambientCoefficient", coeff_ambient, renderer); } // Diffuse coeff { node->GetFloatProperty("material.diffuseCoefficient", coeff_diffuse, renderer); } // Specular coeff { node->GetFloatProperty("material.specularCoefficient", coeff_specular, renderer); } // Specular power { node->GetFloatProperty("material.specularPower", power_specular, renderer); } property->SetAmbient( coeff_ambient ); property->SetDiffuse( coeff_diffuse ); property->SetSpecular( coeff_specular ); property->SetSpecularPower( power_specular ); property->SetAmbientColor( ambient ); property->SetDiffuseColor( diffuse ); property->SetSpecularColor( specular ); } // Render mode { // Opacity { float opacity = 1.0f; if( node->GetOpacity(opacity,renderer) ) property->SetOpacity( opacity ); } // Wireframe line width { float lineWidth = 1; node->GetFloatProperty("material.wireframeLineWidth", lineWidth, renderer); property->SetLineWidth( lineWidth ); } // Representation { mitk::VtkRepresentationProperty::Pointer p; node->GetProperty(p, "material.representation", renderer); if(p.IsNotNull()) property->SetRepresentation( p->GetVtkRepresentation() ); } // Interpolation { mitk::VtkInterpolationProperty::Pointer p; node->GetProperty(p, "material.interpolation", renderer); if(p.IsNotNull()) property->SetInterpolation( p->GetVtkInterpolation() ); } } } void mitk::SurfaceVtkMapper3D::ApplyAllProperties( mitk::BaseRenderer* renderer, vtkActor* /*actor*/) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); // Applying shading properties - { - Superclass::ApplyColorAndOpacityProperties( renderer, ls->m_Actor ) ; - // VTK Properties - ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer ); - // Shaders - IShaderRepository* shaderRepo = CoreServices::GetShaderRepository(); - if (shaderRepo != NULL) - { - shaderRepo->ApplyProperties(this->GetDataNode(),ls->m_Actor,renderer,ls->m_ShaderTimestampUpdate); - } - } + Superclass::ApplyColorAndOpacityProperties( renderer, ls->m_Actor ) ; + // VTK Properties + ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer ); + // Shaders + CoreServicePointer shaderRepo(CoreServices::GetShaderRepository()); + shaderRepo->ApplyProperties(this->GetDataNode(),ls->m_Actor,renderer,ls->m_ShaderTimestampUpdate); mitk::LookupTableProperty::Pointer lookupTableProp; this->GetDataNode()->GetProperty(lookupTableProp, "LookupTable", renderer); if (lookupTableProp.IsNotNull() ) { ls->m_VtkPolyDataMapper->SetLookupTable(lookupTableProp->GetLookupTable()->GetVtkLookupTable()); } mitk::LevelWindow levelWindow; if(this->GetDataNode()->GetLevelWindow(levelWindow, renderer, "levelWindow")) { ls->m_VtkPolyDataMapper->SetScalarRange(levelWindow.GetLowerWindowBound(),levelWindow.GetUpperWindowBound()); } else if(this->GetDataNode()->GetLevelWindow(levelWindow, renderer)) { ls->m_VtkPolyDataMapper->SetScalarRange(levelWindow.GetLowerWindowBound(),levelWindow.GetUpperWindowBound()); } bool scalarVisibility = false; this->GetDataNode()->GetBoolProperty("scalar visibility", scalarVisibility); ls->m_VtkPolyDataMapper->SetScalarVisibility( (scalarVisibility ? 1 : 0) ); if(scalarVisibility) { mitk::VtkScalarModeProperty* scalarMode; if(this->GetDataNode()->GetProperty(scalarMode, "scalar mode", renderer)) { ls->m_VtkPolyDataMapper->SetScalarMode(scalarMode->GetVtkScalarMode()); } else ls->m_VtkPolyDataMapper->SetScalarModeToDefault(); bool colorMode = false; this->GetDataNode()->GetBoolProperty("color mode", colorMode); ls->m_VtkPolyDataMapper->SetColorMode( (colorMode ? 1 : 0) ); float scalarsMin = 0; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum")) != NULL) scalarsMin = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum"))->GetValue(); float scalarsMax = 1.0; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum")) != NULL) scalarsMax = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum"))->GetValue(); ls->m_VtkPolyDataMapper->SetScalarRange(scalarsMin,scalarsMax); } mitk::SmartPointerProperty::Pointer imagetextureProp; imagetextureProp = dynamic_cast< mitk::SmartPointerProperty * >( GetDataNode()->GetProperty("Surface.Texture", renderer)); if(imagetextureProp.IsNotNull()) { mitk::Image* miktTexture = dynamic_cast< mitk::Image* >( imagetextureProp->GetSmartPointer().GetPointer() ); vtkSmartPointer vtkTxture = vtkSmartPointer::New(); //Either select the first slice of a volume if(miktTexture->GetDimension(2) > 1) { MITK_WARN << "3D Textures are not supported by VTK and MITK. The first slice of the volume will be used instead!"; mitk::ImageSliceSelector::Pointer sliceselector = mitk::ImageSliceSelector::New(); sliceselector->SetSliceNr(0); sliceselector->SetChannelNr(0); sliceselector->SetTimeNr(0); sliceselector->SetInput(miktTexture); sliceselector->Update(); vtkTxture->SetInput(sliceselector->GetOutput()->GetVtkImageData()); } else //or just use the 2D image { vtkTxture->SetInput(miktTexture->GetVtkImageData()); } //pass the texture to the actor ls->m_Actor->SetTexture(vtkTxture); if(ls->m_VtkPolyDataMapper->GetInput()->GetPointData()->GetTCoords() == NULL) { MITK_ERROR << "Surface.Texture property was set, but there are no texture coordinates. Please provide texture coordinates for the vtkPolyData via vtkPolyData->GetPointData()->SetTCoords()."; } } // deprecated settings bool deprecatedUseCellData = false; this->GetDataNode()->GetBoolProperty("deprecated useCellDataForColouring", deprecatedUseCellData); bool deprecatedUsePointData = false; this->GetDataNode()->GetBoolProperty("deprecated usePointDataForColouring", deprecatedUsePointData); if (deprecatedUseCellData) { ls->m_VtkPolyDataMapper->SetColorModeToDefault(); ls->m_VtkPolyDataMapper->SetScalarRange(0,255); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_VtkPolyDataMapper->SetScalarModeToUseCellData(); ls->m_Actor->GetProperty()->SetSpecular (1); ls->m_Actor->GetProperty()->SetSpecularPower (50); ls->m_Actor->GetProperty()->SetInterpolationToPhong(); } else if (deprecatedUsePointData) { float scalarsMin = 0; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum")) != NULL) scalarsMin = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum"))->GetValue(); float scalarsMax = 0.1; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum")) != NULL) scalarsMax = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum"))->GetValue(); ls->m_VtkPolyDataMapper->SetScalarRange(scalarsMin,scalarsMax); ls->m_VtkPolyDataMapper->SetColorModeToMapScalars(); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_Actor->GetProperty()->SetSpecular (1); ls->m_Actor->GetProperty()->SetSpecularPower (50); ls->m_Actor->GetProperty()->SetInterpolationToPhong(); } int deprecatedScalarMode = VTK_COLOR_MODE_DEFAULT; if(this->GetDataNode()->GetIntProperty("deprecated scalar mode", deprecatedScalarMode, renderer)) { ls->m_VtkPolyDataMapper->SetScalarMode(deprecatedScalarMode); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_Actor->GetProperty()->SetSpecular (1); ls->m_Actor->GetProperty()->SetSpecularPower (50); //m_Actor->GetProperty()->SetInterpolationToPhong(); } // Check whether one or more ClippingProperty objects have been defined for // this node. Check both renderer specific and global property lists, since // properties in both should be considered. const PropertyList::PropertyMap *rendererProperties = this->GetDataNode()->GetPropertyList( renderer )->GetMap(); const PropertyList::PropertyMap *globalProperties = this->GetDataNode()->GetPropertyList( NULL )->GetMap(); // Add clipping planes (if any) ls->m_ClippingPlaneCollection->RemoveAllItems(); PropertyList::PropertyMap::const_iterator it; for ( it = rendererProperties->begin(); it != rendererProperties->end(); ++it ) { this->CheckForClippingProperty( renderer,(*it).second.GetPointer() ); } for ( it = globalProperties->begin(); it != globalProperties->end(); ++it ) { this->CheckForClippingProperty( renderer,(*it).second.GetPointer() ); } if ( ls->m_ClippingPlaneCollection->GetNumberOfItems() > 0 ) { ls->m_VtkPolyDataMapper->SetClippingPlanes( ls->m_ClippingPlaneCollection ); } else { ls->m_VtkPolyDataMapper->RemoveAllClippingPlanes(); } } vtkProp *mitk::SurfaceVtkMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); return ls->m_Actor; } void mitk::SurfaceVtkMapper3D::CheckForClippingProperty( mitk::BaseRenderer* renderer, mitk::BaseProperty *property ) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); // m_Prop3D = ls->m_Actor; ClippingProperty *clippingProperty = dynamic_cast< ClippingProperty * >( property ); if ( (clippingProperty != NULL) && (clippingProperty->GetClippingEnabled()) ) { const Point3D &origin = clippingProperty->GetOrigin(); const Vector3D &normal = clippingProperty->GetNormal(); vtkPlane *clippingPlane = vtkPlane::New(); clippingPlane->SetOrigin( origin[0], origin[1], origin[2] ); clippingPlane->SetNormal( normal[0], normal[1], normal[2] ); ls->m_ClippingPlaneCollection->AddItem( clippingPlane ); clippingPlane->UnRegister( NULL ); } } void mitk::SurfaceVtkMapper3D::SetDefaultPropertiesForVtkProperty(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { // Shading { node->AddProperty( "material.wireframeLineWidth", mitk::FloatProperty::New(1.0f) , renderer, overwrite ); node->AddProperty( "material.ambientCoefficient" , mitk::FloatProperty::New(0.05f) , renderer, overwrite ); node->AddProperty( "material.diffuseCoefficient" , mitk::FloatProperty::New(0.9f) , renderer, overwrite ); node->AddProperty( "material.specularCoefficient", mitk::FloatProperty::New(1.0f) , renderer, overwrite ); node->AddProperty( "material.specularPower" , mitk::FloatProperty::New(16.0f) , renderer, overwrite ); //node->AddProperty( "material.ambientColor" , mitk::ColorProperty::New(1.0f,1.0f,1.0f), renderer, overwrite ); //node->AddProperty( "material.diffuseColor" , mitk::ColorProperty::New(1.0f,1.0f,1.0f), renderer, overwrite ); //node->AddProperty( "material.specularColor" , mitk::ColorProperty::New(1.0f,1.0f,1.0f), renderer, overwrite ); node->AddProperty( "material.representation" , mitk::VtkRepresentationProperty::New() , renderer, overwrite ); node->AddProperty( "material.interpolation" , mitk::VtkInterpolationProperty::New() , renderer, overwrite ); } // Shaders - IShaderRepository* shaderRepo = CoreServices::GetShaderRepository(); - if (shaderRepo) - { - shaderRepo->AddDefaultProperties(node,renderer,overwrite); - } + CoreServicePointer shaderRepo(CoreServices::GetShaderRepository()); + shaderRepo->AddDefaultProperties(node,renderer,overwrite); } void mitk::SurfaceVtkMapper3D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { node->AddProperty( "color", mitk::ColorProperty::New(1.0f,1.0f,1.0f), renderer, overwrite ); node->AddProperty( "opacity", mitk::FloatProperty::New(1.0), renderer, overwrite ); mitk::SurfaceVtkMapper3D::SetDefaultPropertiesForVtkProperty(node,renderer,overwrite); // Shading node->AddProperty( "scalar visibility", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "color mode", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "scalar mode", mitk::VtkScalarModeProperty::New(), renderer, overwrite ); mitk::Surface::Pointer surface = dynamic_cast(node->GetData()); if(surface.IsNotNull()) { if((surface->GetVtkPolyData() != 0) && (surface->GetVtkPolyData()->GetPointData() != NULL) && (surface->GetVtkPolyData()->GetPointData()->GetScalars() != 0)) { node->AddProperty( "scalar visibility", mitk::BoolProperty::New(true), renderer, overwrite ); node->AddProperty( "color mode", mitk::BoolProperty::New(true), renderer, overwrite ); } } // Backface culling node->AddProperty( "Backface Culling", mitk::BoolProperty::New(false), renderer, overwrite ); Superclass::SetDefaultProperties(node, renderer, overwrite); } void mitk::SurfaceVtkMapper3D::SetImmediateModeRenderingOn(int /*on*/) { /* if (m_VtkPolyDataMapper != NULL) m_VtkPolyDataMapper->SetImmediateModeRendering(on); */ } diff --git a/Core/Code/Testing/files.cmake b/Core/Code/Testing/files.cmake index 9b4d7653a4..c999a6a859 100644 --- a/Core/Code/Testing/files.cmake +++ b/Core/Code/Testing/files.cmake @@ -1,154 +1,151 @@ # tests with no extra command line parameter set(MODULE_TESTS mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkDispatcherTest.cpp mitkEnumerationPropertyTest.cpp mitkEventTest.cpp mitkFocusManagerTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkGlobalInteractionTest.cpp mitkImageDataItemTest.cpp #mitkImageMapper2DTest.cpp mitkImageGeneratorTest.cpp mitkBaseDataTest.cpp #mitkImageToItkTest.cpp mitkImportItkImageTest.cpp mitkGrabItkImageMemoryTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkInteractorTest.cpp #mitkITKThreadingTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp #mitkPipelineSmartPointerCorrectnessTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetTest.cpp mitkPointSetWriterTest.cpp mitkPointSetReaderTest.cpp mitkPointSetInteractorTest.cpp mitkPropertyTest.cpp mitkPropertyListTest.cpp #mitkRegistrationBaseTest.cpp #mitkSegmentationInterpolationTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkStateMachineTest.cpp ##mitkStateMachineContainerTest.cpp ## rewrite test, indirect since no longer exported Bug 14529 mitkStateTest.cpp mitkSurfaceTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeSlicedGeometryTest.cpp mitkTransitionTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp #mitkAbstractTransformGeometryTest.cpp mitkStepperTest.cpp itkTotalVariationDenoisingImageFilterTest.cpp mitkRenderingManagerTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp mitkExceptionTest.cpp mitkExtractSliceFilterTest.cpp mitkLogTest.cpp mitkImageDimensionConverterTest.cpp mitkLoggingAdapterTest.cpp mitkUIDGeneratorTest.cpp mitkShaderRepositoryTest.cpp mitkPlanePositionManagerTest.cpp ) # test with image filename as an extra command line parameter set(MODULE_IMAGE_TESTS mitkImageTimeSelectorTest.cpp #only runs on images mitkImageAccessorTest.cpp #only runs on images mitkDataNodeFactoryTest.cpp #runs on all types of data ) set(MODULE_SURFACE_TESTS mitkSurfaceVtkWriterTest.cpp #only runs on surfaces mitkDataNodeFactoryTest.cpp #runs on all types of data ) # list of images for which the tests are run set(MODULE_TESTIMAGES US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd Png2D-bw.png ) set(MODULE_TESTSURFACES binary.stl ball.stl ) set(MODULE_CUSTOM_TESTS #mitkLabeledImageToSurfaceFilterTest.cpp #mitkExternalToolsTest.cpp mitkDataStorageTest.cpp mitkDataNodeTest.cpp mitkDicomSeriesReaderTest.cpp mitkDICOMLocaleTest.cpp mitkEventMapperTest.cpp mitkEventConfigTest.cpp mitkNodeDependentPointSetInteractorTest.cpp mitkStateMachineFactoryTest.cpp mitkPointSetLocaleTest.cpp mitkImageTest.cpp mitkImageWriterTest.cpp mitkImageVtkMapper2DTest.cpp mitkImageVtkMapper2DLevelWindowTest.cpp mitkImageVtkMapper2DOpacityTest.cpp mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp mitkImageVtkMapper2DColorTest.cpp mitkImageVtkMapper2DSwivelTest.cpp mitkImageVtkMapper2DTransferFunctionTest.cpp mitkIOUtilTest.cpp mitkSurfaceVtkMapper3DTest mitkSurfaceVtkMapper3DTexturedSphereTest.cpp mitkSurfaceGLMapper2DColorTest.cpp mitkSurfaceGLMapper2DOpacityTest.cpp mitkVolumeCalculatorTest.cpp mitkLevelWindowManagerTest.cpp mitkPointSetVtkMapper2DTest.cpp mitkPointSetVtkMapper2DImageTest.cpp mitkPointSetVtkMapper2DGlyphTypeTest.cpp ) set(MODULE_RESOURCE_FILES Interactions/AddAndRemovePoints.xml Interactions/globalConfig.xml Interactions/StatemachineTest.xml Interactions/StatemachineConfigTest.xml ) # Create an artificial module initializing class for # the usServiceListenerTest.cpp -usFunctionGenerateModuleInit(testdriver_init_file - NAME ${MODULE_NAME}TestDriver - DEPENDS "Mitk" - VERSION "0.1.0" - EXECUTABLE - ) +usFunctionGenerateExecutableInit(testdriver_init_file + IDENTIFIER ${MODULE_NAME}TestDriver + ) # Embed the resources set(testdriver_resources ) usFunctionEmbedResources(testdriver_resources EXECUTABLE_NAME ${MODULE_NAME}TestDriver ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Resources FILES ${MODULE_RESOURCE_FILES} ) set(TEST_CPP_FILES ${testdriver_init_file} ${testdriver_resources}) diff --git a/Core/Code/Testing/mitkEventConfigTest.cpp b/Core/Code/Testing/mitkEventConfigTest.cpp index f3db0b9efd..746bc2f33d 100644 --- a/Core/Code/Testing/mitkEventConfigTest.cpp +++ b/Core/Code/Testing/mitkEventConfigTest.cpp @@ -1,151 +1,151 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkEventConfig.h" #include "mitkPropertyList.h" #include "mitkInteractionEvent.h" #include "mitkInteractionEventConst.h" #include "mitkMouseMoveEvent.h" #include "mitkMouseWheelEvent.h" #include "mitkMouseReleaseEvent.h" #include "mitkInteractionKeyEvent.h" #include "mitkMousePressEvent.h" -#include "mitkModule.h" -#include "mitkGetModuleContext.h" +#include "usModule.h" +#include "usGetModuleContext.h" #include #include #include int mitkEventConfigTest(int argc, char* argv[]) { MITK_TEST_BEGIN("EventConfig") if (argc != 2) { MITK_ERROR << "Test needs configuration test file as parameter."; return -1; } /* * Loads a test a Config file and test if Config is build up correctly, * and if mapping from mitkEvents to EventVariant names works properly. * Indirectly this also tests the EventFactory Class, since we also test if the events have been constructed properly. * * The configuration object is constructed in three different ways, * each one is tested here. */ // Construction using compiled-in resrouces: - mitk::Module *module = mitk::GetModuleContext()->GetModule(); + us::Module *module = us::GetModuleContext()->GetModule(); mitk::EventConfig newConfig("StatemachineConfigTest.xml",module); MITK_TEST_CONDITION_REQUIRED( newConfig.IsValid() == true , "01 Check if file can be loaded and is valid" ); /* * Test the global properties: * Test if stored values match the ones in the test config file. */ mitk::PropertyList::Pointer properties = newConfig.GetAttributes(); std::string prop1, prop2; MITK_TEST_CONDITION_REQUIRED( properties->GetStringProperty("property1",prop1) && prop1 == "yes" && properties->GetStringProperty("scrollModus",prop2) && prop2 == "leftright" , "02 Check Global Properties"); /* * Check if Events get mapped to the proper Variants */ mitk::Point2D pos; mitk::MousePressEvent::Pointer mpe1 = mitk::MousePressEvent::New(NULL,pos,mitk::InteractionEvent::MiddleMouseButton | mitk::InteractionEvent::LeftMouseButton ,mitk::InteractionEvent::ControlKey | mitk::InteractionEvent::AltKey,mitk::InteractionEvent::LeftMouseButton ); mitk::MousePressEvent::Pointer standard1 = mitk::MousePressEvent::New(NULL,pos,mitk::InteractionEvent::LeftMouseButton,mitk::InteractionEvent::NoKey ,mitk::InteractionEvent::LeftMouseButton ); mitk::MouseMoveEvent::Pointer mme1 = mitk::MouseMoveEvent::New(NULL,pos,mitk::InteractionEvent::RightMouseButton | mitk::InteractionEvent::LeftMouseButton,mitk::InteractionEvent::ShiftKey ); mitk::MouseMoveEvent::Pointer mme2 = mitk::MouseMoveEvent::New(NULL,pos,mitk::InteractionEvent::RightMouseButton,mitk::InteractionEvent::ShiftKey ); mitk::MouseWheelEvent::Pointer mwe1 = mitk::MouseWheelEvent::New(NULL,pos,mitk::InteractionEvent::RightMouseButton,mitk::InteractionEvent::ShiftKey,-2 ); mitk::InteractionKeyEvent::Pointer ke = mitk::InteractionKeyEvent::New(NULL,"l",mitk::InteractionEvent::NoKey ); MITK_TEST_CONDITION_REQUIRED( newConfig.GetMappedEvent(mpe1.GetPointer()) == "Variant1" && newConfig.GetMappedEvent(standard1.GetPointer()) == "Standard1" && newConfig.GetMappedEvent(mme1.GetPointer()) == "Move2" && newConfig.GetMappedEvent(ke.GetPointer()) == "Key1" && newConfig.GetMappedEvent(mme2.GetPointer()) == "" // does not exist in file , "03 Check Mouse- and Key-Events " ); // Construction providing a input stream std::ifstream configStream(argv[1]); mitk::EventConfig newConfig2(configStream); MITK_TEST_CONDITION_REQUIRED( newConfig2.IsValid() == true , "01 Check if file can be loaded and is valid" ); /* * Test the global properties: * Test if stored values match the ones in the test config file. */ properties = newConfig2.GetAttributes(); MITK_TEST_CONDITION_REQUIRED( properties->GetStringProperty("property1",prop1) && prop1 == "yes" && properties->GetStringProperty("scrollModus",prop2) && prop2 == "leftright" , "02 Check Global Properties"); /* * Check if Events get mapped to the proper Variants */ MITK_TEST_CONDITION_REQUIRED( newConfig2.GetMappedEvent(mpe1.GetPointer()) == "Variant1" && newConfig2.GetMappedEvent(standard1.GetPointer()) == "Standard1" && newConfig2.GetMappedEvent(mme1.GetPointer()) == "Move2" && newConfig2.GetMappedEvent(ke.GetPointer()) == "Key1" && newConfig2.GetMappedEvent(mme2.GetPointer()) == "" // does not exist in file , "03 Check Mouse- and Key-Events " ); // always end with this! // Construction providing a property list mitk::PropertyList::Pointer propertyList1 = mitk::PropertyList::New(); propertyList1->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass().c_str(), "MousePressEvent"); propertyList1->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant().c_str(), "MousePressEventVariant"); propertyList1->SetStringProperty("Modifiers","CTRL,ALT"); mitk::PropertyList::Pointer propertyList2 = mitk::PropertyList::New(); propertyList2->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass().c_str(), "MOUSERELEASEEVENT"); propertyList2->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant().c_str(), "MouseReleaseEventVariant"); propertyList2->SetStringProperty("Modifiers","SHIFT"); std::vector* configDescription = new std::vector(); configDescription->push_back(propertyList1); configDescription->push_back(propertyList2); mitk::EventConfig newConfig3(*configDescription); mitk::MousePressEvent::Pointer mousePress1 = mitk::MousePressEvent::New(NULL,pos,mitk::InteractionEvent::NoButton,mitk::InteractionEvent::AltKey | mitk::InteractionEvent::ControlKey ,mitk::InteractionEvent::NoButton ); mitk::MouseReleaseEvent::Pointer mousePress2 = mitk::MouseReleaseEvent::New(NULL,pos,mitk::InteractionEvent::NoButton,mitk::InteractionEvent::ShiftKey ,mitk::InteractionEvent::NoButton ); MITK_TEST_CONDITION_REQUIRED( newConfig3.GetMappedEvent(mousePress1.GetPointer()) == "MousePressEventVariant" && newConfig3.GetMappedEvent(mousePress2.GetPointer()) == "MouseReleaseEventVariant" , "04 Check Mouseevents from PropertyLists" ); MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkPlanePositionManagerTest.cpp b/Core/Code/Testing/mitkPlanePositionManagerTest.cpp index 30638faf26..798f137a67 100644 --- a/Core/Code/Testing/mitkPlanePositionManagerTest.cpp +++ b/Core/Code/Testing/mitkPlanePositionManagerTest.cpp @@ -1,271 +1,274 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkRotationOperation.h" #include "mitkTestingMacros.h" #include "mitkPlanePositionManager.h" #include "mitkSliceNavigationController.h" #include "mitkGeometry3D.h" #include "mitkPlaneGeometry.h" #include "mitkImage.h" #include "mitkSurface.h" #include "mitkStandaloneDataStorage.h" #include "mitkDataNode.h" #include "mitkStringProperty.h" #include "mitkBaseProperty.h" #include "mitkInteractionConst.h" #include "vnl/vnl_vector.h" #include -#include "mitkGetModuleContext.h" +#include "usGetModuleContext.h" +#include "usModuleContext.h" +#include "usServiceReference.h" std::vector m_Geometries; std::vector m_SliceIndices; mitk::PlanePositionManagerService* m_Service; int SetUpBeforeTest() { //Getting Service - mitk::ServiceReference serviceRef = mitk::GetModuleContext()->GetServiceReference(); - m_Service = dynamic_cast(mitk::GetModuleContext()->GetService(serviceRef)); + us::ServiceReference serviceRef = + us::GetModuleContext()->GetServiceReference(); + m_Service = us::GetModuleContext()->GetService(serviceRef); if (m_Service == 0) return EXIT_FAILURE; //Creating different Geometries m_Geometries.reserve(100); mitk::PlaneGeometry::PlaneOrientation views[] = {mitk::PlaneGeometry::Axial, mitk::PlaneGeometry::Sagittal, mitk::PlaneGeometry::Frontal}; for (unsigned int i = 0; i < 100; ++i) { mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); mitk::ScalarType width = 256+(0.01*i); mitk::ScalarType height = 256+(0.002*i); mitk::Vector3D right; mitk::Vector3D down; right[0] = 1; right[1] = i; right[2] = 0.5; down[0] = i*0.02; down[1] = 1; down[2] = i*0.03; mitk::Vector3D spacing; mitk::FillVector3D(spacing, 1.0*0.02*i, 1.0*0.15*i, 1.0); mitk::Vector3D rightVector; mitk::FillVector3D(rightVector, 0.02*(i+1), 0+(0.05*i), 1.0); mitk::Vector3D downVector; mitk::FillVector3D(downVector, 1, 3-0.01*i, 0.0345*i); vnl_vector normal = vnl_cross_3d(rightVector.GetVnlVector(), downVector.GetVnlVector()); normal.normalize(); normal *= 1.5; mitk::Vector3D origin; origin.Fill(1); origin[0] = 12 + 0.03*i; mitk::AffineTransform3D::Pointer transform = mitk::AffineTransform3D::New(); mitk::Matrix3D matrix; matrix.GetVnlMatrix().set_column(0, rightVector.GetVnlVector()); matrix.GetVnlMatrix().set_column(1, downVector.GetVnlVector()); matrix.GetVnlMatrix().set_column(2, normal); transform->SetMatrix(matrix); transform->SetOffset(origin); plane->InitializeStandardPlane(width, height, transform, views[i%3], i, true, false); m_Geometries.push_back(plane); } return EXIT_SUCCESS; } int testAddPlanePosition() { MITK_TEST_OUTPUT(<<"Starting Test: ######### A d d P l a n e P o s i t i o n #########"); MITK_TEST_CONDITION(m_Service != NULL, "Testing getting of PlanePositionManagerService"); unsigned int currentID(m_Service->AddNewPlanePosition(m_Geometries.at(0),0)); bool error = ((m_Service->GetNumberOfPlanePositions() != 1)||(currentID != 0)); if(error) { MITK_TEST_CONDITION(m_Service->GetNumberOfPlanePositions() == 1,"Checking for correct number of planepositions"); MITK_TEST_CONDITION(currentID == 0, "Testing for correct ID"); return EXIT_FAILURE; } //Adding new planes for(unsigned int i = 1; i < m_Geometries.size(); ++i) { unsigned int newID = m_Service->AddNewPlanePosition(m_Geometries.at(i),i); error = ((m_Service->GetNumberOfPlanePositions() != i+1)||(newID != (currentID+1))); if (error) { MITK_TEST_CONDITION(m_Service->GetNumberOfPlanePositions() == i+1,"Checking for correct number of planepositions"); MITK_TEST_CONDITION(newID == (currentID+1), "Testing for correct ID"); MITK_TEST_OUTPUT(<<"New: "<GetNumberOfPlanePositions(); //Adding existing planes -> nothing should change for(unsigned int i = 0; i < (m_Geometries.size()-1)*0.5; ++i) { unsigned int newID = m_Service->AddNewPlanePosition(m_Geometries.at(i*2),i*2); error = ((m_Service->GetNumberOfPlanePositions() != numberOfPlanePos)||(newID != i*2)); if (error) { MITK_TEST_CONDITION( m_Service->GetNumberOfPlanePositions() == numberOfPlanePos, "Checking for correct number of planepositions"); MITK_TEST_CONDITION(newID == i*2, "Testing for correct ID"); return EXIT_FAILURE; } } return EXIT_SUCCESS; } int testGetPlanePosition() { mitk::PlaneGeometry* plane; mitk::RestorePlanePositionOperation* op; bool error(true); MITK_TEST_OUTPUT(<<"Starting Test: ######### G e t P l a n e P o s i t i o n #########"); //Testing for existing planepositions for (unsigned int i = 0; i < m_Geometries.size(); ++i) { plane = m_Geometries.at(i); op = m_Service->GetPlanePosition(i); error = ( !mitk::Equal(op->GetHeight(),plane->GetExtent(1)) || !mitk::Equal(op->GetWidth(),plane->GetExtent(0)) || !mitk::Equal(op->GetSpacing(),plane->GetSpacing()) || !mitk::Equal(op->GetTransform()->GetOffset(),plane->GetIndexToWorldTransform()->GetOffset()) || !mitk::Equal(op->GetDirectionVector().GetVnlVector(),plane->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2).normalize()) || !mitk::MatrixEqualElementWise(op->GetTransform()->GetMatrix(), plane->GetIndexToWorldTransform()->GetMatrix()) ); if( error ) { MITK_TEST_OUTPUT(<<"Iteration: "<GetHeight(),plane->GetExtent(1)) && mitk::Equal(op->GetWidth(),plane->GetExtent(0)), "Checking for correct extent"); MITK_TEST_CONDITION( mitk::Equal(op->GetSpacing(),plane->GetSpacing()), "Checking for correct spacing"); MITK_TEST_CONDITION( mitk::Equal(op->GetTransform()->GetOffset(),plane->GetIndexToWorldTransform()->GetOffset()), "Checking for correct offset"); MITK_INFO<<"Op: "<GetDirectionVector()<<" plane: "<GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)<<"\n"; MITK_TEST_CONDITION( mitk::Equal(op->GetDirectionVector().GetVnlVector(),plane->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2)), "Checking for correct direction"); MITK_TEST_CONDITION( mitk::MatrixEqualElementWise(op->GetTransform()->GetMatrix(), plane->GetIndexToWorldTransform()->GetMatrix()), "Checking for correct matrix"); return EXIT_FAILURE; } } //Testing for not existing planepositions error = ( m_Service->GetPlanePosition(100000000) != 0 || m_Service->GetPlanePosition(-1) != 0 ); if (error) { MITK_TEST_CONDITION(m_Service->GetPlanePosition(100000000) == 0, "Trying to get non existing pos"); MITK_TEST_CONDITION(m_Service->GetPlanePosition(-1) == 0, "Trying to get non existing pos"); return EXIT_FAILURE; } return EXIT_SUCCESS; } int testRemovePlanePosition() { MITK_TEST_OUTPUT(<<"Starting Test: ######### R e m o v e P l a n e P o s i t i o n #########"); unsigned int size = m_Service->GetNumberOfPlanePositions(); bool removed (true); //Testing for invalid IDs removed = m_Service->RemovePlanePosition( -1 ); removed = m_Service->RemovePlanePosition( 1000000 ); unsigned int size2 = m_Service->GetNumberOfPlanePositions(); if (removed) { MITK_TEST_CONDITION(removed == false, "Testing remove not existing planepositions"); MITK_TEST_CONDITION(size == size2, "Testing remove not existing planepositions"); return EXIT_FAILURE; } //Testing for valid IDs for (unsigned int i = 0; i < m_Geometries.size()*0.5; i++) { removed = m_Service->RemovePlanePosition( i ); unsigned int size2 = m_Service->GetNumberOfPlanePositions(); removed = (size2 == (size-(i+1))); if (!removed) { MITK_TEST_CONDITION(removed == true, "Testing remove existing planepositions"); MITK_TEST_CONDITION(size == (size-i+1), "Testing remove existing planepositions"); return EXIT_FAILURE; } } return EXIT_SUCCESS; } int testRemoveAll() { MITK_TEST_OUTPUT(<<"Starting Test: ######### R e m o v e A l l #########"); unsigned int numPos = m_Service->GetNumberOfPlanePositions(); MITK_INFO<RemoveAllPlanePositions(); bool error (true); error = (m_Service->GetNumberOfPlanePositions() != 0 || m_Service->GetPlanePosition(60) != 0); if (error) { MITK_TEST_CONDITION(m_Service->GetNumberOfPlanePositions() == 0, "Testing remove all pos"); MITK_TEST_CONDITION(m_Service->GetPlanePosition(60) == 0, "Testing remove all pos"); return EXIT_FAILURE; } return EXIT_SUCCESS; } int mitkPlanePositionManagerTest(int, char* []) { MITK_TEST_OUTPUT(<<"Starting Test PlanePositionManager"); SetUpBeforeTest(); int result; MITK_TEST_CONDITION_REQUIRED( (result = testAddPlanePosition()) == EXIT_SUCCESS, ""); MITK_TEST_CONDITION_REQUIRED( (result = testGetPlanePosition()) == EXIT_SUCCESS, ""); MITK_TEST_CONDITION_REQUIRED( (result = testRemovePlanePosition()) == EXIT_SUCCESS, ""); MITK_TEST_CONDITION_REQUIRED( (result = testRemoveAll()) == EXIT_SUCCESS, ""); return EXIT_SUCCESS; } diff --git a/Core/Code/Testing/mitkShaderRepositoryTest.cpp b/Core/Code/Testing/mitkShaderRepositoryTest.cpp index 397ae506c2..ca8cdd5b1c 100644 --- a/Core/Code/Testing/mitkShaderRepositoryTest.cpp +++ b/Core/Code/Testing/mitkShaderRepositoryTest.cpp @@ -1,73 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkIShaderRepository.h" -#include "mitkGetModuleContext.h" -#include "mitkModuleContext.h" -#include "mitkServiceReference.h" + +#include "usGetModuleContext.h" +#include "usModuleContext.h" +#include "usServiceReference.h" #include "mitkTestingMacros.h" #include int mitkShaderRepositoryTest(int /*argc*/, char* /*argv*/[]) { MITK_TEST_BEGIN("ShaderRepository") - mitk::ModuleContext* context = mitk::GetModuleContext(); - mitk::ServiceReference serviceRef = context->GetServiceReference(); + us::ModuleContext* context = us::GetModuleContext(); + us::ServiceReference serviceRef = context->GetServiceReference(); MITK_TEST_CONDITION_REQUIRED(serviceRef, "IShaderRepository service ref") - mitk::IShaderRepository* shaderRepo = context->GetService(serviceRef); + mitk::IShaderRepository* shaderRepo = context->GetService(serviceRef); MITK_TEST_CONDITION_REQUIRED(shaderRepo, "Check non-empty IShaderRepositry") mitk::IShaderRepository::Shader::Pointer shader = shaderRepo->GetShader("mitkShaderLighting"); MITK_TEST_CONDITION_REQUIRED(shader.IsNotNull(), "Non-null mitkShaderLighting shader") MITK_TEST_CONDITION(shader->GetName() == "mitkShaderLighting", "Shader name") MITK_TEST_CONDITION(!shader->GetMaterialXml().empty(), "Shader content") const std::string testShader = "" "" "" "" ""; const std::size_t shaderCount = shaderRepo->GetShaders().size(); std::stringstream testShaderStream(testShader); const std::string testShaderName = "SmoothPlastic"; int id = shaderRepo->LoadShader(testShaderStream, testShaderName); MITK_TEST_CONDITION_REQUIRED(id > -1, "New shader id") MITK_TEST_CONDITION(shaderRepo->GetShaders().size() == shaderCount+1, "Shader count") mitk::IShaderRepository::Shader::Pointer shader2 = shaderRepo->GetShader(testShaderName); MITK_TEST_CONDITION_REQUIRED(shader2.IsNotNull(), "Non-null shader") MITK_TEST_CONDITION(shader2->GetId() == id, "Shader id") MITK_TEST_CONDITION(shader2->GetName() == testShaderName, "Shader name") mitk::IShaderRepository::Shader::Pointer shader3 = shaderRepo->GetShader(id); MITK_TEST_CONDITION_REQUIRED(shader3.IsNotNull(), "Non-null shader") MITK_TEST_CONDITION(shader3->GetId() == id, "Shader id") MITK_TEST_CONDITION(shader3->GetName() == testShaderName, "Shader name") MITK_TEST_CONDITION_REQUIRED(shaderRepo->UnloadShader(id), "Unload shader") MITK_TEST_CONDITION(shaderRepo->GetShader(testShaderName).IsNull(), "Null shader") MITK_TEST_CONDITION(shaderRepo->GetShader(id).IsNull(), "Null shader") MITK_TEST_END() } diff --git a/Core/Code/Testing/mitkSliceNavigationControllerTest.cpp b/Core/Code/Testing/mitkSliceNavigationControllerTest.cpp index aac7d81e95..43bfb4e87d 100644 --- a/Core/Code/Testing/mitkSliceNavigationControllerTest.cpp +++ b/Core/Code/Testing/mitkSliceNavigationControllerTest.cpp @@ -1,577 +1,581 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSliceNavigationController.h" #include "mitkPlaneGeometry.h" #include "mitkSlicedGeometry3D.h" #include "mitkTimeSlicedGeometry.h" #include "mitkRotationOperation.h" #include "mitkInteractionConst.h" #include "mitkPlanePositionManager.h" #include "mitkTestingMacros.h" -#include "mitkGetModuleContext.h" + +#include "usGetModuleContext.h" +#include "usModuleContext.h" +#include "usServiceReference.h" #include #include #include bool operator==(const mitk::Geometry3D & left, const mitk::Geometry3D & right) { mitk::BoundingBox::BoundsArrayType leftbounds, rightbounds; leftbounds =left.GetBounds(); rightbounds=right.GetBounds(); unsigned int i; for(i=0;i<6;++i) if(mitk::Equal(leftbounds[i],rightbounds[i])==false) return false; const mitk::Geometry3D::TransformType::MatrixType & leftmatrix = left.GetIndexToWorldTransform()->GetMatrix(); const mitk::Geometry3D::TransformType::MatrixType & rightmatrix = right.GetIndexToWorldTransform()->GetMatrix(); unsigned int j; for(i=0;i<3;++i) { const mitk::Geometry3D::TransformType::MatrixType::ValueType* leftvector = leftmatrix[i]; const mitk::Geometry3D::TransformType::MatrixType::ValueType* rightvector = rightmatrix[i]; for(j=0;j<3;++j) if(mitk::Equal(leftvector[i],rightvector[i])==false) return false; } const mitk::Geometry3D::TransformType::OffsetType & leftoffset = left.GetIndexToWorldTransform()->GetOffset(); const mitk::Geometry3D::TransformType::OffsetType & rightoffset = right.GetIndexToWorldTransform()->GetOffset(); for(i=0;i<3;++i) if(mitk::Equal(leftoffset[i],rightoffset[i])==false) return false; return true; } int compareGeometry(const mitk::Geometry3D & geometry, const mitk::ScalarType& width, const mitk::ScalarType& height, const mitk::ScalarType& numSlices, const mitk::ScalarType& widthInMM, const mitk::ScalarType& heightInMM, const mitk::ScalarType& thicknessInMM, const mitk::Point3D& cornerpoint0, const mitk::Vector3D& right, const mitk::Vector3D& bottom, const mitk::Vector3D& normal) { std::cout << "Testing width, height and thickness (in units): "; if((mitk::Equal(geometry.GetExtent(0),width)==false) || (mitk::Equal(geometry.GetExtent(1),height)==false) || (mitk::Equal(geometry.GetExtent(2),numSlices)==false) ) { std::cout<<"[FAILED]"<GetCornerPoint(0), cornerpoint0)==false) { std::cout<<"[FAILED]"<SetInputWorldGeometry(geometry); std::cout<<"[PASSED]"<SetViewDirection(mitk::SliceNavigationController::Axial); std::cout<<"[PASSED]"<Update(); std::cout<<"[PASSED]"<GetCreatedWorldGeometry(), width, height, numSlices, widthInMM, heightInMM, thicknessInMM*numSlices, axialcornerpoint0, right, bottom*(-1.0), normal*(-1.0)); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<SetViewDirection(mitk::SliceNavigationController::Frontal); std::cout<<"[PASSED]"<Update(); std::cout<<"[PASSED]"<GetAxisVector(1)*(+0.5/geometry->GetExtent(1)); result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), width, numSlices, height, widthInMM, thicknessInMM*numSlices, heightInMM, frontalcornerpoint0, right, normal, bottom); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<SetViewDirection(mitk::SliceNavigationController::Sagittal); std::cout<<"[PASSED]"<Update(); std::cout<<"[PASSED]"<GetAxisVector(0)*(+0.5/geometry->GetExtent(0)); result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), height, numSlices, width, heightInMM, thicknessInMM*numSlices, widthInMM, sagittalcornerpoint0, bottom, normal, right); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<InitializeStandardPlane(right.GetVnlVector(), bottom.GetVnlVector(), &spacing); planegeometry->SetOrigin(origin); //Create SlicedGeometry3D out of planeGeometry mitk::SlicedGeometry3D::Pointer slicedgeometry1 = mitk::SlicedGeometry3D::New(); unsigned int numSlices = 20; slicedgeometry1->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); //Create another slicedgeo which will be rotated mitk::SlicedGeometry3D::Pointer slicedgeometry2 = mitk::SlicedGeometry3D::New(); slicedgeometry2->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); //Create geo3D as reference mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetBounds(slicedgeometry1->GetBounds()); geometry->SetIndexToWorldTransform(slicedgeometry1->GetIndexToWorldTransform()); //Initialize planes for (int i=0; i < (int)numSlices; i++) { mitk::PlaneGeometry::Pointer geo2d = mitk::PlaneGeometry::New(); geo2d->Initialize(); geo2d->SetReferenceGeometry(geometry); slicedgeometry1->SetGeometry2D(geo2d,i); } for (int i=0; i < (int)numSlices; i++) { mitk::PlaneGeometry::Pointer geo2d = mitk::PlaneGeometry::New(); geo2d->Initialize(); geo2d->SetReferenceGeometry(geometry); slicedgeometry2->SetGeometry2D(geo2d,i); } slicedgeometry1->SetReferenceGeometry(geometry); slicedgeometry2->SetReferenceGeometry(geometry); //Create SNC mitk::SliceNavigationController::Pointer sliceCtrl1 = mitk::SliceNavigationController::New(); sliceCtrl1->SetInputWorldGeometry(slicedgeometry1); sliceCtrl1->Update(); mitk::SliceNavigationController::Pointer sliceCtrl2 = mitk::SliceNavigationController::New(); sliceCtrl2->SetInputWorldGeometry(slicedgeometry2); sliceCtrl2->Update(); slicedgeometry1->SetSliceNavigationController(sliceCtrl1); slicedgeometry2->SetSliceNavigationController(sliceCtrl2); // Whats current geometry? MITK_INFO << "center: " << sliceCtrl1->GetCurrentPlaneGeometry()->GetCenter(); MITK_INFO << "normal: " << sliceCtrl1->GetCurrentPlaneGeometry()->GetNormal(); MITK_INFO << "origin: " << sliceCtrl1->GetCurrentPlaneGeometry()->GetOrigin(); MITK_INFO << "axis0 : " << sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(0); MITK_INFO << "aixs1 : " << sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(1); // // Now reorient slices (ONE POINT, ONE NORMAL) mitk::Point3D oldCenter, oldOrigin; mitk::Vector3D oldAxis0, oldAxis1; oldCenter = sliceCtrl1->GetCurrentPlaneGeometry()->GetCenter(); oldOrigin = sliceCtrl1->GetCurrentPlaneGeometry()->GetOrigin(); oldAxis0 = sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(0); oldAxis1 = sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(1); mitk::Point3D orientCenter; mitk::Vector3D orientNormal; orientCenter = oldCenter; mitk::FillVector3D(orientNormal, 0.3, 0.1, 0.8); orientNormal.Normalize(); sliceCtrl1->ReorientSlices(orientCenter,orientNormal); mitk::Point3D newCenter, newOrigin; mitk::Vector3D newNormal; newCenter = sliceCtrl1->GetCurrentPlaneGeometry()->GetCenter(); newOrigin = sliceCtrl1->GetCurrentPlaneGeometry()->GetOrigin(); newNormal = sliceCtrl1->GetCurrentPlaneGeometry()->GetNormal(); newNormal.Normalize(); itk::Index<3> orientCenterIdx; itk::Index<3> newCenterIdx; sliceCtrl1->GetCurrentGeometry3D()->WorldToIndex(orientCenter, orientCenterIdx); sliceCtrl1->GetCurrentGeometry3D()->WorldToIndex(newCenter, newCenterIdx); if ( (newCenterIdx != orientCenterIdx) || ( !mitk::Equal(orientNormal, newNormal) ) ) { MITK_INFO << "Reorient Planes (1 point, 1 vector) not working as it should"; MITK_INFO << "orientCenterIdx: " << orientCenterIdx; MITK_INFO << "newCenterIdx: " << newCenterIdx; MITK_INFO << "orientNormal: " << orientNormal; MITK_INFO << "newNormal: " << newNormal; return EXIT_FAILURE; } // // Now reorient slices (center, vec0, vec1 ) mitk::Vector3D orientAxis0, orientAxis1, newAxis0, newAxis1; mitk::FillVector3D(orientAxis0, 1.0, 0.0, 0.0); mitk::FillVector3D(orientAxis1, 0.0, 1.0, 0.0); orientAxis0.Normalize(); orientAxis1.Normalize(); sliceCtrl1->ReorientSlices(orientCenter,orientAxis0, orientAxis1); newAxis0 = sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(0); newAxis1 = sliceCtrl1->GetCurrentPlaneGeometry()->GetAxisVector(1); newCenter = sliceCtrl1->GetCurrentPlaneGeometry()->GetCenter(); newAxis0.Normalize(); newAxis1.Normalize(); sliceCtrl1->GetCurrentGeometry3D()->WorldToIndex(orientCenter, orientCenterIdx); sliceCtrl1->GetCurrentGeometry3D()->WorldToIndex(newCenter, newCenterIdx); if ( (newCenterIdx != orientCenterIdx) || ( !mitk::Equal(orientAxis0, newAxis0) ) || ( !mitk::Equal(orientAxis1, newAxis1) ) ) { MITK_INFO << "Reorient Planes (point, vec, vec) not working as it should"; MITK_INFO << "orientCenterIdx: " << orientCenterIdx; MITK_INFO << "newCenterIdx: " << newCenterIdx; MITK_INFO << "orientAxis0: " << orientAxis0; MITK_INFO << "newAxis0: " << newAxis0; MITK_INFO << "orientAxis1: " << orientAxis1; MITK_INFO << "newAxis1: " << newAxis1; return EXIT_FAILURE; } return EXIT_SUCCESS; } int testRestorePlanePostionOperation () { //Create PlaneGeometry mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); mitk::Point3D origin; mitk::Vector3D right, bottom, normal; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM, thicknessInMM; width = 100; widthInMM = width; height = 200; heightInMM = height; thicknessInMM = 1.5; mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); mitk::FillVector3D(normal, 0, 0, thicknessInMM); mitk::Vector3D spacing; normal.Normalize(); normal *= thicknessInMM; mitk::FillVector3D(spacing, 1.0, 1.0, thicknessInMM); planegeometry->InitializeStandardPlane(right.GetVnlVector(), bottom.GetVnlVector(), &spacing); planegeometry->SetOrigin(origin); //Create SlicedGeometry3D out of planeGeometry mitk::SlicedGeometry3D::Pointer slicedgeometry1 = mitk::SlicedGeometry3D::New(); unsigned int numSlices = 300; slicedgeometry1->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); //Create another slicedgeo which will be rotated mitk::SlicedGeometry3D::Pointer slicedgeometry2 = mitk::SlicedGeometry3D::New(); slicedgeometry2->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); //Create geo3D as reference mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetBounds(slicedgeometry1->GetBounds()); geometry->SetIndexToWorldTransform(slicedgeometry1->GetIndexToWorldTransform()); //Initialize planes for (int i=0; i < (int)numSlices; i++) { mitk::PlaneGeometry::Pointer geo2d = mitk::PlaneGeometry::New(); geo2d->Initialize(); geo2d->SetReferenceGeometry(geometry); slicedgeometry1->SetGeometry2D(geo2d,i); } for (int i=0; i < (int)numSlices; i++) { mitk::PlaneGeometry::Pointer geo2d = mitk::PlaneGeometry::New(); geo2d->Initialize(); geo2d->SetReferenceGeometry(geometry); slicedgeometry2->SetGeometry2D(geo2d,i); } slicedgeometry1->SetReferenceGeometry(geometry); slicedgeometry2->SetReferenceGeometry(geometry); //Create SNC mitk::SliceNavigationController::Pointer sliceCtrl1 = mitk::SliceNavigationController::New(); sliceCtrl1->SetInputWorldGeometry(slicedgeometry1); sliceCtrl1->Update(); mitk::SliceNavigationController::Pointer sliceCtrl2 = mitk::SliceNavigationController::New(); sliceCtrl2->SetInputWorldGeometry(slicedgeometry2); sliceCtrl2->Update(); slicedgeometry1->SetSliceNavigationController(sliceCtrl1); slicedgeometry2->SetSliceNavigationController(sliceCtrl2); //Rotate slicedgeo2 double angle = 63.84; mitk::Vector3D rotationVector; mitk::FillVector3D( rotationVector, 0.5, 0.95, 0.23 ); mitk::Point3D center = slicedgeometry2->GetCenter(); mitk::RotationOperation* op = new mitk::RotationOperation( mitk::OpROTATE, center, rotationVector, angle ); slicedgeometry2->ExecuteOperation(op); sliceCtrl2->Update(); - mitk::ServiceReference serviceRef = mitk::GetModuleContext()->GetServiceReference(); - mitk::PlanePositionManagerService* service = dynamic_cast(mitk::GetModuleContext()->GetService(serviceRef)); + us::ServiceReference serviceRef = + us::GetModuleContext()->GetServiceReference(); + mitk::PlanePositionManagerService* service = us::GetModuleContext()->GetService(serviceRef); service->AddNewPlanePosition(slicedgeometry2->GetGeometry2D(0), 178); sliceCtrl1->ExecuteOperation(service->GetPlanePosition(0)); sliceCtrl1->Update(); mitk::Geometry2D* planeRotated = slicedgeometry2->GetGeometry2D(178); mitk::Geometry2D* planeRestored = dynamic_cast< const mitk::SlicedGeometry3D*>(sliceCtrl1->GetCurrentGeometry3D())->GetGeometry2D(178); try{ MITK_TEST_CONDITION_REQUIRED(mitk::MatrixEqualElementWise(planeRotated->GetIndexToWorldTransform()->GetMatrix(), planeRestored->GetIndexToWorldTransform()->GetMatrix()),"Testing for IndexToWorld"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(planeRotated->GetOrigin(), planeRestored->GetOrigin(),2*mitk::eps),"Testing for origin"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(planeRotated->GetSpacing(), planeRestored->GetSpacing()),"Testing for spacing"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(slicedgeometry2->GetDirectionVector(), dynamic_cast< const mitk::SlicedGeometry3D*>(sliceCtrl1->GetCurrentGeometry3D())->GetDirectionVector()),"Testing for directionvector"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(slicedgeometry2->GetSlices(), dynamic_cast< const mitk::SlicedGeometry3D*>(sliceCtrl1->GetCurrentGeometry3D())->GetSlices()),"Testing for numslices"); MITK_TEST_CONDITION_REQUIRED(mitk::MatrixEqualElementWise(slicedgeometry2->GetIndexToWorldTransform()->GetMatrix(), dynamic_cast< const mitk::SlicedGeometry3D*>(sliceCtrl1->GetCurrentGeometry3D())->GetIndexToWorldTransform()->GetMatrix()),"Testing for IndexToWorld"); } catch(...) { return EXIT_FAILURE; } return EXIT_SUCCESS; } int mitkSliceNavigationControllerTest(int /*argc*/, char* /*argv*/[]) { int result=EXIT_FAILURE; std::cout << "Creating and initializing a PlaneGeometry: "; mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); mitk::Point3D origin; mitk::Vector3D right, bottom, normal; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM, thicknessInMM; width = 100; widthInMM = width; height = 200; heightInMM = height; thicknessInMM = 1.5; // mitk::FillVector3D(origin, 0, 0, thicknessInMM*0.5); mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); mitk::FillVector3D(normal, 0, 0, thicknessInMM); mitk::Vector3D spacing; normal.Normalize(); normal *= thicknessInMM; mitk::FillVector3D(spacing, 1.0, 1.0, thicknessInMM); planegeometry->InitializeStandardPlane(right.GetVnlVector(), bottom.GetVnlVector(), &spacing); planegeometry->SetOrigin(origin); std::cout<<"[PASSED]"<InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); std::cout<<"[PASSED]"<SetBounds(slicedgeometry->GetBounds()); geometry->SetIndexToWorldTransform(slicedgeometry->GetIndexToWorldTransform()); std::cout<<"[PASSED]"<GetCornerPoint(0); result=testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; mitk::AffineTransform3D::Pointer transform = mitk::AffineTransform3D::New(); transform->SetMatrix(geometry->GetIndexToWorldTransform()->GetMatrix()); mitk::BoundingBox::Pointer boundingbox = geometry->CalculateBoundingBoxRelativeToTransform(transform); geometry->SetBounds(boundingbox->GetBounds()); cornerpoint0 = geometry->GetCornerPoint(0); result=testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; std::cout << "Changing the IndexToWorldTransform of the geometry to a rotated version by SetIndexToWorldTransform() (keep cornerpoint0): "; transform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType::InternalMatrixType vnlmatrix; vnlmatrix = planegeometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix(); mitk::VnlVector axis(3); mitk::FillVector3D(axis, 1.0, 1.0, 1.0); axis.normalize(); vnl_quaternion rotation(axis, 0.223); vnlmatrix = rotation.rotation_matrix_transpose()*vnlmatrix; mitk::Matrix3D matrix; matrix = vnlmatrix; transform->SetMatrix(matrix); transform->SetOffset(cornerpoint0.GetVectorFromOrigin()); right.SetVnlVector( rotation.rotation_matrix_transpose()*right.GetVnlVector() ); bottom.SetVnlVector(rotation.rotation_matrix_transpose()*bottom.GetVnlVector()); normal.SetVnlVector(rotation.rotation_matrix_transpose()*normal.GetVnlVector()); geometry->SetIndexToWorldTransform(transform); std::cout<<"[PASSED]"<GetCornerPoint(0); result = testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; //Testing Execute RestorePlanePositionOperation result = testRestorePlanePostionOperation(); if(result!=EXIT_SUCCESS) return result; //Testing ReorientPlanes result = testReorientPlanes(); if(result!=EXIT_SUCCESS) return result; std::cout<<"[TEST DONE]"<\2" \ "deprecatedSince{1}=\xrefitem deprecatedSince\1 \" Deprecated as of \1\" \"Functions deprecated as of \1\" " # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding # "class=itcl::class" will allow you to use the command class in the # itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this # tag. The format is ext=language, where ext is a file extension, and language # is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, # C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make # doxygen treat .inc files as Fortran files (default is PHP), and .f files as C # (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions # you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all # comments according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you # can mix doxygen, HTML, and XML commands with Markdown formatting. # Disable only in case of backward compatibilities issues. MARKDOWN_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = YES # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields will be shown inline in the documentation # of the scope in which they are defined (i.e. file, namespace, or group # documentation), provided this scope is documented. If set to NO (the default), # structs, classes, and unions are shown on a separate page (for HTML and Man # pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. SYMBOL_CACHE_SIZE = 0 # Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be # set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given # their name and scope. Since this can be an expensive process and often the # same symbol appear multiple times in the code, doxygen keeps a cache of # pre-resolved symbols. If the cache is too small doxygen will become slower. # If the cache is too large, memory is wasted. The cache size is given by this # formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_PACKAGE tag is set to YES all members with package or internal scope will be included in the documentation. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = @MITK_DOXYGEN_INTERNAL_DOCS@ # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = @MITK_DOXYGEN_HIDE_FRIEND_COMPOUNDS@ # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = @MITK_DOXYGEN_INTERNAL_DOCS@ # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = YES # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = @MITK_DOXYGEN_GENERATE_TODOLIST@ # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = @MITK_DOXYGEN_GENERATE_BUGLIST@ # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= @MITK_DOXYGEN_GENERATE_DEPRECATEDLIST@ # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = @MITK_DOXYGEN_ENABLED_SECTIONS@ # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 0 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. The create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = @MITK_SOURCE_DIR@/Documentation/MITKDoxygenLayout.xml # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style # of the bibliography can be controlled using LATEX_BIB_STYLE. To use this # feature you need bibtex and perl available in the search path. CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @MITK_SOURCE_DIR@ \ @MITK_BINARY_DIR@ \ @MITK_DOXYGEN_ADDITIONAL_INPUT_DIRS@ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = *.h \ *.cpp \ *.dox \ *.md \ *.txx \ *.tpp \ *.cxx \ *.cmake # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = @MITK_SOURCE_DIR@/BlueBerry/Documentation/reference/api/MainPage.dox \ @MITK_SOURCE_DIR@/Utilities/ann/ \ @MITK_SOURCE_DIR@/Utilities/glew/ \ @MITK_SOURCE_DIR@/Utilities/ipFunc/ \ @MITK_SOURCE_DIR@/Utilities/ipSegmentation/ \ @MITK_SOURCE_DIR@/Utilities/KWStyle/ \ @MITK_SOURCE_DIR@/Utilities/pic2vtk/ \ @MITK_SOURCE_DIR@/Utilities/Poco/ \ @MITK_SOURCE_DIR@/Utilities/qtsingleapplication/ \ @MITK_SOURCE_DIR@/Utilities/qwt/ \ @MITK_SOURCE_DIR@/Utilities/qxt/ \ @MITK_SOURCE_DIR@/Utilities/tinyxml/ \ @MITK_SOURCE_DIR@/Utilities/vecmath/ \ @MITK_SOURCE_DIR@/Applications/PluginGenerator/ \ - @MITK_SOURCE_DIR@/Core/Code/CppMicroServices/README.md \ - @MITK_SOURCE_DIR@/Core/Code/CppMicroServices/documentation/snippets/ \ - @MITK_SOURCE_DIR@/Core/Code/CppMicroServices/documentation/doxygen/standalone/ \ - @MITK_SOURCE_DIR@/Core/Code/CppMicroServices/test/ \ + @MITK_SOURCE_DIR@/Core/CppMicroServices/README.md \ + @MITK_SOURCE_DIR@/Core/CppMicroServices/documentation/snippets/ \ + @MITK_SOURCE_DIR@/Core/CppMicroServices/documentation/doxygen/standalone/ \ + @MITK_SOURCE_DIR@/Core/CppMicroServices/examples/ \ + @MITK_SOURCE_DIR@/Core/CppMicroServices/test/ \ + @MITK_SOURCE_DIR@/Core/CppMicroServices/src/util/jsoncpp.cpp \ @MITK_SOURCE_DIR@/Deprecated/ \ @MITK_SOURCE_DIR@/Build/ \ @MITK_SOURCE_DIR@/CMake/PackageDepends \ @MITK_SOURCE_DIR@/CMake/QBundleTemplate \ @MITK_SOURCE_DIR@/CMakeExternals \ @MITK_SOURCE_DIR@/Modules/QmitkExt/vtkQtChartHeaders/ \ + @MITK_BINARY_DIR@/bin/ \ @MITK_BINARY_DIR@/PT/ \ @MITK_BINARY_DIR@/GP/ \ - @MITK_BINARY_DIR@/Core/Code/CppMicroServices/ \ + @MITK_BINARY_DIR@/Core/CppMicroServices/ \ + @MITK_BINARY_DIR@/_CPack_Packages/ \ @MITK_DOXYGEN_ADDITIONAL_EXCLUDE_DIRS@ # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = moc_* \ ui_* \ qrc_* \ wrap_* \ Register* \ */files.cmake \ */.git/* \ *_p.h \ *Private.* \ */Snippets/* \ */snippets/* \ */testing/* \ */Testing/* \ @MITK_BINARY_DIR@/*.cmake \ @MITK_DOXYGEN_EXCLUDE_PATTERNS@ # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test -EXCLUDE_SYMBOLS = +EXCLUDE_SYMBOLS = *Private* \ + ModuleInfo \ + ServiceObjectsBase* \ + TrackedService* # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = @MITK_SOURCE_DIR@/Examples/ \ @MITK_SOURCE_DIR@/Examples/Tutorial/ \ @MITK_SOURCE_DIR@/Examples/Plugins/ \ @MITK_SOURCE_DIR@/Examples/QtFreeRender/ \ @MITK_SOURCE_DIR@/Core/Code/ \ - @MITK_SOURCE_DIR@/Core/Code/CppMicroServices/Documentation/Snippets/ \ + @MITK_SOURCE_DIR@/Core/CppMicroServices/documentation/snippets/ \ + @MITK_SOURCE_DIR@/Core/CppMicroServices/examples/ \ @MITK_DOXYGEN_OUTPUT_DIR@/html/extension-points/html/ \ @MITK_SOURCE_DIR@/Documentation/Snippets/ \ @MITK_SOURCE_DIR@/Documentation/Doxygen/ExampleCode/ \ @MITK_SOURCE_DIR@/Modules/OpenCL/Documentation/doxygen/snippets/ \ @MITK_SOURCE_DIR@/BlueBerry/Documentation/snippets/ # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = YES # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = @MITK_SOURCE_DIR@/Documentation/Doxygen/ \ @MITK_SOURCE_DIR@/Documentation/Doxygen/Modules/ \ @MITK_SOURCE_DIR@/Documentation/Doxygen/Tutorial/ \ @MITK_SOURCE_DIR@ # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = *.cmake=@CMakeDoxygenFilter_EXECUTABLE@ # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 3 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is advised to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # style sheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = @MITK_DOXYGEN_STYLESHEET@ # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the style sheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = @MITK_DOXYGEN_HTML_DYNAMIC_SECTIONS@ # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = @MITK_DOXYGEN_GENERATE_QHP@ # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = @MITK_DOXYGEN_QCH_FILE@ # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = "org.mitk" # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = MITK # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = @QT_HELPGENERATOR_EXECUTABLE@ # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) # at top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. Since the tabs have the same information as the # navigation tree you can set this option to NO if you already set # GENERATE_TREEVIEW to YES. DISABLE_INDEX = NO # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. # Since the tree basically has the same information as the tab index you # could consider to set DISABLE_INDEX to NO when enabling this option. GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 4 # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 300 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you may also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to # the MathJax Content Delivery Network so you can quickly see the result without # installing MathJax. # However, it is strongly recommended to install a local # copy of MathJax from http://www.mathjax.org before deployment. MATHJAX_RELPATH = http://www.mathjax.org/mathjax # The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension # names that should be enabled during MathJax rendering. MATHJAX_EXTENSIONS = # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a PHP enabled web server instead of at the web client # using Javascript. Doxygen will generate the search PHP script and index # file to put on the web server. The advantage of the server # based approach is that it scales better to large projects and allows # full text search. The disadvantages are that it is more difficult to setup # and does not have live searching capabilities. SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = amssymb # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = NO # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = NO # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See # http://en.wikipedia.org/wiki/BibTeX for more info. LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load style sheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = itkNotUsed(x)= \ "itkSetMacro(name,type)= virtual void Set##name (type _arg);" \ "itkGetMacro(name,type)= virtual type Get##name ();" \ "itkGetConstMacro(name,type)= virtual type Get##name () const;" \ "itkSetStringMacro(name)= virtual void Set##name (const char* _arg);" \ "itkGetStringMacro(name)= virtual const char* Get##name () const;" \ "itkSetClampMacro(name,type,min,max)= virtual void Set##name (type _arg);" \ "itkSetObjectMacro(name,type)= virtual void Set##name (type* _arg);" \ "itkGetObjectMacro(name,type)= virtual type* Get##name ();" \ "itkSetConstObjectMacro(name,type)= virtual void Set##name ( const type* _arg);" \ "itkGetConstObjectMacro(name,type)= virtual const type* Get##name ();" \ "itkGetConstReferenceMacro(name,type)= virtual const type& Get##name ();" \ "itkGetConstReferenceObjectMacro(name,type)= virtual const type::Pointer& Get##name () const;" \ "itkBooleanMacro(name)= virtual void name##On (); virtual void name##Off ();" \ "itkSetVector2Macro(name,type)= virtual void Set##name (type _arg1, type _arg2) virtual void Set##name (type _arg[2]);" \ "itkGetVector2Macro(name,type)= virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2) const; virtual void Get##name (type _arg[2]) const;" \ "itkSetVector3Macro(name,type)= virtual void Set##name (type _arg1, type _arg2, type _arg3) virtual void Set##name (type _arg[3]);" \ "itkGetVector3Macro(name,type)= virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3) const; virtual void Get##name (type _arg[3]) const;" \ "itkSetVector4Macro(name,type)= virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4) virtual void Set##name (type _arg[4]);" \ "itkGetVector4Macro(name,type)= virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3, type& _arg4) const; virtual void Get##name (type _arg[4]) const;" \ "itkSetVector6Macro(name,type)= virtual void Set##name (type _arg1, type _arg2, type _arg3, type _arg4, type _arg5, type _arg6) virtual void Set##name (type _arg[6]);" \ "itkGetVector6Macro(name,type)= virtual type* Get##name () const; virtual void Get##name (type& _arg1, type& _arg2, type& _arg3, type& _arg4, type& _arg5, type& _arg6) const; virtual void Get##name (type _arg[6]) const;" \ "itkSetVectorMacro(name,type,count)= virtual void Set##name(type data[]);" \ "itkGetVectorMacro(name,type,count)= virtual type* Get##name () const;" \ "itkNewMacro(type)= static Pointer New();" \ "itkTypeMacro(thisClass,superclass)= virtual const char *GetClassName() const;" \ "itkConceptMacro(name,concept)= enum { name = 0 };" \ "ITK_NUMERIC_LIMITS= std::numeric_limits" \ "ITK_TYPENAME= typename" \ "FEM_ABSTRACT_CLASS(thisClass,parentClass)= public: /** Standard Self typedef.*/ typedef thisClass Self; /** Standard Superclass typedef. */ typedef parentClass Superclass; /** Pointer or SmartPointer to an object. */ typedef Self* Pointer; /** Const pointer or SmartPointer to an object. */ typedef const Self* ConstPointer; private:" \ "FEM_CLASS(thisClass,parentClass)= FEM_ABSTRACT_CLASS(thisClass,parentClass) public: /** Create a new object from the existing one */ virtual Baseclass::Pointer Clone() const; /** Class ID for FEM object factory */ static const int CLID; /** Virtual function to access the class ID */ virtual int ClassID() const { return CLID; } /** Object creation in an itk compatible way */ static Self::Pointer New() { return new Self(); } private:" \ FREEVERSION \ ERROR_CHECKING \ HAS_TIFF \ HAS_JPEG \ HAS_NETLIB \ HAS_PNG \ HAS_ZLIB \ HAS_GLUT \ HAS_QT \ VCL_USE_NATIVE_STL=1 \ VCL_USE_NATIVE_COMPLEX=1 \ VCL_HAS_BOOL=1 \ VXL_BIG_ENDIAN=1 \ VXL_LITTLE_ENDIAN=0 \ VNL_DLL_DATA= \ size_t=vcl_size_t \ - "US_PREPEND_NAMESPACE(x)=mitk::x" \ - "US_BEGIN_NAMESPACE= namespace mitk {" \ + "US_PREPEND_NAMESPACE(x)=us::x" \ + "US_BEGIN_NAMESPACE= namespace us {" \ "US_END_NAMESPACE=}" \ - "US_BASECLASS_NAME=itk::LightObject" \ US_EXPORT= \ "DEPRECATED(func)=func" # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. For each # tag file the location of the external documentation should be added. The # format of a tag file without this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths # or URLs. Note that each tag file must have a unique name (where the name does # NOT include the path). If a tag file is not located in the directory in which # doxygen is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = @MITK_DOXYGEN_TAGFILE_NAME@ # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = NO # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = @HAVE_DOT@ # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = @MITK_DOXYGEN_DOT_NUM_THREADS@ # By default doxygen will use the Helvetica font for all dot files that # doxygen generates. When you want a differently looking font you can specify # the font name using DOT_FONTNAME. You need to make sure dot is able to find # the font, which can be done by putting it in a standard location or by setting # the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the # directory containing the font. DOT_FONTNAME = FreeSans.ttf # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the Helvetica font. # If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to # set the path where dot can find it. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = @MITK_DOXYGEN_UML_LOOK@ # If the UML_LOOK tag is enabled, the fields and methods are shown inside # the class node. If there are many fields or methods and many nodes the # graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS # threshold limits the number of items for each type to make the size more # managable. Set this to 0 for no limit. Note that the threshold may be # exceeded by 50% before the limit is enforced. UML_LIMIT_NUM_FIELDS = 10 # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = NO # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = NO # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = NO # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = @DOXYGEN_DOT_PATH@ # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES diff --git a/Examples/QtFreeRender/CMakeLists.txt b/Examples/QtFreeRender/CMakeLists.txt index 6fa0ee9549..01ca0aa51d 100644 --- a/Examples/QtFreeRender/CMakeLists.txt +++ b/Examples/QtFreeRender/CMakeLists.txt @@ -1,24 +1,26 @@ project(QtFreeRender) find_package(MITK) # Check prerequisites for this application. # We need the Mitk module. MITK_CHECK_MODULE(result Mitk) if(result) message(SEND_ERROR "MITK module(s) \"${result}\" not available from the MITK build at ${MITK_DIR}") endif() # Set-up the build system to use the Mitk module MITK_USE_MODULE(Mitk) include_directories(${ALL_INCLUDE_DIRECTORIES}) link_directories(${ALL_LIBRARY_DIRS}) -add_executable(${PROJECT_NAME} QtFreeRender.cpp) +usFunctionGenerateExecutableInit(init_src_file IDENTIFIER ${PROJECT_NAME}) + +add_executable(${PROJECT_NAME} QtFreeRender.cpp ${init_src_file}) target_link_libraries(${PROJECT_NAME} ${ALL_LIBRARIES} ) # subproject support set_property(TARGET ${PROJECT_NAME} PROPERTY LABELS ${MITK_DEFAULT_SUBPROJECTS}) foreach(subproject ${MITK_DEFAULT_SUBPROJECTS}) add_dependencies(${subproject} ${PROJECT_NAME}) endforeach() diff --git a/Examples/QtFreeRender/QtFreeRender.cpp b/Examples/QtFreeRender/QtFreeRender.cpp index cc3e897051..70dc014e96 100644 --- a/Examples/QtFreeRender/QtFreeRender.cpp +++ b/Examples/QtFreeRender/QtFreeRender.cpp @@ -1,373 +1,373 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkRenderWindow.h" #include #include #include #include #include #include #include #include "mitkProperties.h" #include "mitkGeometry2DDataMapper2D.h" #include "mitkGlobalInteraction.h" #include "mitkDisplayInteractor.h" #include "mitkPositionEvent.h" #include "mitkStateEvent.h" #include "mitkLine.h" #include "mitkInteractionConst.h" #include "mitkVtkLayerController.h" #include "mitkPositionTracker.h" #include "mitkDisplayInteractor.h" #include "mitkSlicesRotator.h" #include "mitkSlicesSwiveller.h" #include "mitkRenderWindowFrame.h" #include "mitkGradientBackground.h" #include "mitkCoordinateSupplier.h" #include "mitkDataStorage.h" #include "vtkTextProperty.h" #include "vtkCornerAnnotation.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkAnnotatedCubeActor.h" #include "vtkOrientationMarkerWidget.h" #include "vtkProperty.h" // us -#include "mitkGetModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleRegistry.h" +#include "usGetModuleContext.h" +#include "usModuleContext.h" + #include "mitkInteractionEventObserver.h" //##Documentation //## @brief Example of a NON QT DEPENDENT MITK RENDERING APPLICATION. mitk::RenderWindow::Pointer mitkWidget1; mitk::RenderWindow::Pointer mitkWidget2; mitk::RenderWindow::Pointer mitkWidget3; mitk::RenderWindow::Pointer mitkWidget4; mitk::DisplayInteractor::Pointer m_DisplayInteractor; mitk::CoordinateSupplier::Pointer m_LastLeftClickPositionSupplier; mitk::GradientBackground::Pointer m_GradientBackground4; mitk::RenderWindowFrame::Pointer m_RectangleRendering1; mitk::RenderWindowFrame::Pointer m_RectangleRendering2; mitk::RenderWindowFrame::Pointer m_RectangleRendering3; mitk::RenderWindowFrame::Pointer m_RectangleRendering4; mitk::SliceNavigationController* m_TimeNavigationController = NULL; mitk::DataStorage::Pointer m_DataStorage; mitk::DataNode::Pointer m_PlaneNode1; mitk::DataNode::Pointer m_PlaneNode2; mitk::DataNode::Pointer m_PlaneNode3; mitk::DataNode::Pointer m_Node; void InitializeWindows() { // Set default view directions for SNCs mitkWidget1->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Axial); mitkWidget2->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Sagittal); mitkWidget3->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Frontal); mitkWidget4->GetSliceNavigationController()->SetDefaultViewDirection(mitk::SliceNavigationController::Original); //initialize m_TimeNavigationController: send time via sliceNavigationControllers m_TimeNavigationController = mitk::RenderingManager::GetInstance()->GetTimeNavigationController(); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget1->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget2->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget3->GetSliceNavigationController(), false); m_TimeNavigationController->ConnectGeometryTimeEvent(mitkWidget4->GetSliceNavigationController(), false); mitkWidget1->GetSliceNavigationController()->ConnectGeometrySendEvent(mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); //reverse connection between sliceNavigationControllers and m_TimeNavigationController mitkWidget1->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget2->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget3->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget4->GetSliceNavigationController()->ConnectGeometryTimeEvent(m_TimeNavigationController, false); // Let NavigationControllers listen to GlobalInteraction mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); gi->AddListener(m_TimeNavigationController); m_LastLeftClickPositionSupplier = mitk::CoordinateSupplier::New("navigation", NULL); mitk::GlobalInteraction::GetInstance()->AddListener(m_LastLeftClickPositionSupplier); m_GradientBackground4 = mitk::GradientBackground::New(); m_GradientBackground4->SetRenderWindow(mitkWidget4->GetVtkRenderWindow()); m_GradientBackground4->SetGradientColors(0.1, 0.1, 0.1, 0.5, 0.5, 0.5); m_GradientBackground4->Enable(); m_RectangleRendering1 = mitk::RenderWindowFrame::New(); m_RectangleRendering1->SetRenderWindow(mitkWidget1->GetVtkRenderWindow()); m_RectangleRendering1->Enable(1.0, 0.0, 0.0); m_RectangleRendering2 = mitk::RenderWindowFrame::New(); m_RectangleRendering2->SetRenderWindow(mitkWidget2->GetVtkRenderWindow()); m_RectangleRendering2->Enable(0.0, 1.0, 0.0); m_RectangleRendering3 = mitk::RenderWindowFrame::New(); m_RectangleRendering3->SetRenderWindow(mitkWidget3->GetVtkRenderWindow()); m_RectangleRendering3->Enable(0.0, 0.0, 1.0); m_RectangleRendering4 = mitk::RenderWindowFrame::New(); m_RectangleRendering4->SetRenderWindow(mitkWidget4->GetVtkRenderWindow()); m_RectangleRendering4->Enable(1.0, 1.0, 0.0); } void AddDisplayPlaneSubTree() { // add the displayed planes of the multiwidget to a node to which the subtree // @a planesSubTree points ... float white[3] = { 1.0f, 1.0f, 1.0f }; mitk::Geometry2DDataMapper2D::Pointer mapper; mitk::IntProperty::Pointer layer = mitk::IntProperty::New(1000); // ... of widget 1 m_PlaneNode1 = (mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow()))->GetCurrentWorldGeometry2DNode(); m_PlaneNode1->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode1->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode1->SetProperty("name", mitk::StringProperty::New("widget1Plane")); m_PlaneNode1->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode1->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode1->SetProperty("layer", layer); m_PlaneNode1->SetColor(1.0, 0.0, 0.0); mapper = mitk::Geometry2DDataMapper2D::New(); m_PlaneNode1->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 2 m_PlaneNode2 = (mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow()))->GetCurrentWorldGeometry2DNode(); m_PlaneNode2->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode2->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode2->SetProperty("name", mitk::StringProperty::New("widget2Plane")); m_PlaneNode2->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode2->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode2->SetProperty("layer", layer); m_PlaneNode2->SetColor(0.0, 1.0, 0.0); mapper = mitk::Geometry2DDataMapper2D::New(); m_PlaneNode2->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 3 m_PlaneNode3 = (mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow()))->GetCurrentWorldGeometry2DNode(); m_PlaneNode3->SetColor(white, mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())); m_PlaneNode3->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode3->SetProperty("name", mitk::StringProperty::New("widget3Plane")); m_PlaneNode3->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode3->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PlaneNode3->SetProperty("layer", layer); m_PlaneNode3->SetColor(0.0, 0.0, 1.0); mapper = mitk::Geometry2DDataMapper2D::New(); m_PlaneNode3->SetMapper(mitk::BaseRenderer::Standard2D, mapper); m_Node = mitk::DataNode::New(); m_Node->SetProperty("name", mitk::StringProperty::New("Widgets")); m_Node->SetProperty("helper object", mitk::BoolProperty::New(true)); //AddPlanesToDataStorage if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_Node.IsNotNull()) { if (m_DataStorage.IsNotNull()) { m_DataStorage->Add(m_Node); m_DataStorage->Add(m_PlaneNode1, m_Node); m_DataStorage->Add(m_PlaneNode2, m_Node); m_DataStorage->Add(m_PlaneNode3, m_Node); static_cast(m_PlaneNode1->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); static_cast(m_PlaneNode2->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); static_cast(m_PlaneNode3->GetMapper(mitk::BaseRenderer::Standard2D))->SetDatastorageAndGeometryBaseNode( m_DataStorage, m_Node); } } } void Fit() { vtkRenderer * vtkrenderer; mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())->GetDisplayGeometry()->Fit(); int w = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget1->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget2->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget3->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetVtkRenderWindow())->GetVtkRenderer(); if (vtkrenderer != NULL) vtkrenderer->ResetCamera(); vtkObject::SetGlobalWarningDisplay(w); } int main(int argc, char* argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s [filename1] [filename2] ...\n\n", ""); return 1; } // Create a DataStorage m_DataStorage = mitk::StandaloneDataStorage::New(); //************************************************************************* // Part II: Create some data by reading files //************************************************************************* int i; for (i = 1; i < argc; ++i) { // For testing if (strcmp(argv[i], "-testing") == 0) continue; // Create a DataNodeFactory to read a data format supported // by the DataNodeFactory (many image formats, surface formats, etc.) mitk::DataNodeFactory::Pointer nodeReader = mitk::DataNodeFactory::New(); const char * filename = argv[i]; try { nodeReader->SetFileName(filename); nodeReader->Update(); // Since the DataNodeFactory directly creates a node, // use the datastorage to add the read node mitk::DataNode::Pointer node = nodeReader->GetOutput(); m_DataStorage->Add(node); mitk::Image::Pointer image = dynamic_cast(node->GetData()); if (image.IsNotNull()) { // Set the property "volumerendering" to the Boolean value "true" node->SetProperty("volumerendering", mitk::BoolProperty::New(false)); node->SetProperty("name", mitk::StringProperty::New("testimage")); node->SetProperty("layer", mitk::IntProperty::New(1)); } } catch (...) { fprintf(stderr, "Could not open file %s \n\n", filename); exit(2); } } //************************************************************************* // Part V: Create window and pass the tree to it //************************************************************************* // Global Interaction initialize // legacy because window manager relies still on existence if global interaction mitk::GlobalInteraction::GetInstance()->Initialize("global"); //mitk::GlobalInteraction::GetInstance()->AddListener(m_DisplayInteractor); // Create renderwindows mitkWidget1 = mitk::RenderWindow::New(); mitkWidget2 = mitk::RenderWindow::New(); mitkWidget3 = mitk::RenderWindow::New(); mitkWidget4 = mitk::RenderWindow::New(); // Tell the renderwindow which (part of) the datastorage to render mitkWidget1->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget2->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget3->GetRenderer()->SetDataStorage(m_DataStorage); mitkWidget4->GetRenderer()->SetDataStorage(m_DataStorage); // Let NavigationControllers listen to GlobalInteraction mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); gi->AddListener(mitkWidget1->GetSliceNavigationController()); gi->AddListener(mitkWidget2->GetSliceNavigationController()); gi->AddListener(mitkWidget3->GetSliceNavigationController()); gi->AddListener(mitkWidget4->GetSliceNavigationController()); // instantiate display interactor if (m_DisplayInteractor.IsNull()) { m_DisplayInteractor = mitk::DisplayInteractor::New(); m_DisplayInteractor->LoadStateMachine("DisplayInteraction.xml"); m_DisplayInteractor->SetEventConfig("DisplayConfigMITK.xml"); // Register as listener via micro services - mitk::ModuleContext* context = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); + us::ModuleContext* context = us::GetModuleContext(); context->RegisterService( m_DisplayInteractor.GetPointer()); } // Use it as a 2D View mitkWidget1->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget2->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget3->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard2D); mitkWidget4->GetRenderer()->SetMapperID(mitk::BaseRenderer::Standard3D); mitkWidget1->SetSize(400, 400); mitkWidget2->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0] + 420, mitkWidget1->GetVtkRenderWindow()->GetPosition()[1]); mitkWidget2->SetSize(400, 400); mitkWidget3->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0], mitkWidget1->GetVtkRenderWindow()->GetPosition()[1] + 450); mitkWidget3->SetSize(400, 400); mitkWidget4->GetVtkRenderWindow()->SetPosition(mitkWidget1->GetVtkRenderWindow()->GetPosition()[0] + 420, mitkWidget1->GetVtkRenderWindow()->GetPosition()[1] + 450); mitkWidget4->SetSize(400, 400); InitializeWindows(); AddDisplayPlaneSubTree(); Fit(); // Initialize the RenderWindows mitk::TimeSlicedGeometry::Pointer geo = m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); m_DataStorage->Print(std::cout); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // reinit the mitkVTKEventProvider; // this is only necessary once after calling // ForceImmediateUpdateAll() for the first time mitkWidget1->ReinitEventProvider(); mitkWidget2->ReinitEventProvider(); mitkWidget3->ReinitEventProvider(); mitkWidget1->GetVtkRenderWindow()->Render(); mitkWidget2->GetVtkRenderWindow()->Render(); mitkWidget3->GetVtkRenderWindow()->Render(); mitkWidget4->GetVtkRenderWindow()->Render(); mitkWidget4->GetVtkRenderWindowInteractor()->Start(); return 0; } diff --git a/MITKConfig.cmake.in b/MITKConfig.cmake.in index 2e5b1cfcec..58db3f031f 100644 --- a/MITKConfig.cmake.in +++ b/MITKConfig.cmake.in @@ -1,200 +1,200 @@ # Update the CMake module path set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "@MITK_SOURCE_DIR@/CMake") -include(@MITK_BINARY_DIR@/Core/Code/CppMicroServices/CppMicroServicesConfig.cmake) +set(CppMicroServices_DIR "@MITK_BINARY_DIR@/Core/CppMicroServices") # Include MITK macros include(MacroParseArguments) include(mitkFunctionCheckMitkCompatibility) include(mitkFunctionOrganizeSources) include(mitkFunctionCreateWindowsBatchScript) include(mitkFunctionInstallProvisioningFiles) include(mitkFunctionInstallAutoLoadModules) include(mitkFunctionGetLibrarySearchPaths) include(mitkMacroCreateModuleConf) include(mitkMacroCreateModule) include(mitkMacroCheckModule) include(mitkMacroCreateModuleTests) include(mitkFunctionAddCustomModuleTest) include(mitkMacroUseModule) include(mitkMacroMultiplexPicType) include(mitkMacroInstall) include(mitkMacroInstallHelperApp) include(mitkMacroInstallTargets) include(mitkMacroGenerateToolsLibrary) include(mitkMacroCreateCTKPlugin) include(mitkMacroGetPMDPlatformString) # The MITK version number set(MITK_VERSION_MAJOR "@MITK_VERSION_MAJOR@") set(MITK_VERSION_MINOR "@MITK_VERSION_MINOR@") set(MITK_VERSION_PATCH "@MITK_VERSION_PATCH@") set(MITK_VERSION_STRING "@MITK_VERSION_STRING@") # MITK compiler flags set(MITK_C_FLAGS "@MITK_C_FLAGS@") set(MTTK_C_FLAGS_DEBUG "@MITK_C_FLAGS_DEBUG@") set(MITK_C_FLAGS_RELEASE "@MITK_C_FLAGS_RELEASE@") set(MITK_CXX_FLAGS "@MITK_CXX_FLAGS@") set(MTTK_CXX_FLAGS_DEBUG "@MITK_CXX_FLAGS_DEBUG@") set(MITK_CXX_FLAGS_RELEASE "@MITK_CXX_FLAGS_RELEASE@") set(MITK_EXE_LINKER_FLAGS "@MITK_EXE_LINKER_FLAGS@") set(MITK_SHARED_LINKER_FLAGS "@MITK_SHARED_LINKER_FLAGS@") set(MITK_MODULE_LINKER_FLAGS "@MITK_MODULE_LINKER_FLAGS@") # Internal version numbers, used for approximate compatibility checks # of a MITK development version (non-release). set(MITK_VERSION_PLUGIN_SYSTEM 2) # dropped legacy BlueBerry plug-in CMake support # MITK specific variables set(MITK_SOURCE_DIR "@MITK_SOURCE_DIR@") set(MITK_BINARY_DIR "@MITK_BINARY_DIR@") set(UTILITIES_DIR "@UTILITIES_DIR@") set(REGISTER_QFUNCTIONALITY_CPP_IN "@REGISTER_QFUNCTIONALITY_CPP_IN@") set(MITK_MODULES_PACKAGE_DEPENDS_DIR "@MITK_MODULES_PACKAGE_DEPENDS_DIR@") set(MODULES_PACKAGE_DEPENDS_DIRS "@MODULES_PACKAGE_DEPENDS_DIRS@") set(MITK_DOXYGEN_TAGFILE_NAME "@MITK_DOXYGEN_TAGFILE_NAME@") if(MODULES_CONF_DIRS) list(APPEND MODULES_CONF_DIRS "@MODULES_CONF_DIRS@") list(REMOVE_DUPLICATES MODULES_CONF_DIRS) else() set(MODULES_CONF_DIRS "@MODULES_CONF_DIRS@") endif() set(MODULES_CONF_DIRNAME "@MODULES_CONF_DIRNAME@") foreach(_module @MITK_MODULE_NAMES@) set(${_module}_CONFIG_FILE "@MITK_BINARY_DIR@/@MODULES_CONF_DIRNAME@/${_module}Config.cmake") endforeach() # Include directory variables set(MITK_INCLUDE_DIRS "@MITK_INCLUDE_DIRS@") set(QMITK_INCLUDE_DIRS "@QMITK_INCLUDE_DIRS@") set(ANN_INCLUDE_DIR "@ANN_INCLUDE_DIR@") set(IPSEGMENTATION_INCLUDE_DIR "@IPSEGMENTATION_INCLUDE_DIR@") set(VECMATH_INCLUDE_DIR "@VECMATH_INCLUDE_DIR@") set(IPFUNC_INCLUDE_DIR "@IPFUNC_INCLUDE_DIR@") set(MITK_IGT_INCLUDE_DIRS "@MITK_IGT_INCLUDE_DIRS@") # Library variables set(MITK_LIBRARIES "@MITK_LIBRARIES@") set(QMITK_LIBRARIES "@QMITK_LIBRARIES@") # Link directory variables set(MITK_LINK_DIRECTORIES "@MITK_LINK_DIRECTORIES@") set(QMITK_LINK_DIRECTORIES "@QMITK_LINK_DIRECTORIES@") set(MITK_LIBRARY_DIRS "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@" "@CMAKE_LIBRARY_OUTPUT_DIRECTORY@/plugins" @MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS_CONFIG@) set(MITK_VTK_LIBRARY_DIRS "@MITK_VTK_LIBRARY_DIRS@") set(MITK_ITK_LIBRARY_DIRS "@MITK_ITK_LIBRARY_DIRS@") # External projects set(ITK_DIR "@ITK_DIR@") set(VTK_DIR "@VTK_DIR@") set(DCMTK_DIR "@DCMTK_DIR@") set(GDCM_DIR "@GDCM_DIR@") set(BOOST_ROOT "@BOOST_ROOT@") set(OpenCV_DIR "@OpenCV_DIR@") set(SOFA_DIR "@SOFA_DIR@") set(MITK_QMAKE_EXECUTABLE "@QT_QMAKE_EXECUTABLE@") set(MITK_DATA_DIR "@MITK_DATA_DIR@") # External SDK directories set(MITK_PMD_SDK_DIR @MITK_PMD_SDK_DIR@) # MITK use variables set(MITK_USE_QT @MITK_USE_QT@) set(MITK_USE_BLUEBERRY @MITK_USE_BLUEBERRY@) set(MITK_USE_SYSTEM_Boost @MITK_USE_SYSTEM_Boost@) set(MITK_USE_Boost @MITK_USE_Boost@) set(MITK_USE_Boost_LIBRARIES @MITK_USE_Boost_LIBRARIES@) set(MITK_USE_CTK @MITK_USE_CTK@) set(MITK_USE_DCMTK @MITK_USE_DCMTK@) set(MITK_USE_OpenCV @MITK_USE_OpenCV@) set(MITK_USE_SOFA @MITK_USE_SOFA@) set(MITK_USE_Python @MITK_USE_Python@) # MITK ToF use variables set(MITK_TOF_PMDCAMCUBE_AVAILABLE @MITK_USE_TOF_PMDCAMCUBE@) if(MITK_TOF_PMDCAMCUBE_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_PMDCAMCUBE "Enable support for PMD Cam Cube" @MITK_USE_TOF_PMDCAMCUBE@) mark_as_advanced(MITK_USE_TOF_PMDCAMCUBE) endif() set(MITK_TOF_PMDCAMBOARD_AVAILABLE @MITK_USE_TOF_PMDCAMBOARD@) if(MITK_TOF_PMDCAMBOARD_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_PMDCAMBOARD "Enable support for PMD Cam Board" @MITK_USE_TOF_PMDCAMBOARD@) mark_as_advanced(MITK_USE_TOF_PMDCAMBOARD) endif() set(MITK_TOF_PMDO3_AVAILABLE @MITK_USE_TOF_PMDO3@) if(MITK_TOF_PMDO3_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_PMDO3 "Enable support for PMD =3" @MITK_USE_TOF_PMDO3@) mark_as_advanced(MITK_USE_TOF_PMDO3) endif() set(MITK_TOF_KINECT_AVAILABLE @MITK_USE_TOF_KINECT@) if(MITK_TOF_KINECT_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_KINECT "Enable support for Kinect" @MITK_USE_TOF_KINECT@) mark_as_advanced(MITK_USE_TOF_KINECT) endif() set(MITK_TOF_MESASR4000_AVAILABLE @MITK_USE_TOF_MESASR4000@) if(MITK_TOF_MESASR4000_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_MESASR4000 "Enable support for MESA SR4000" @MITK_USE_TOF_MESASR4000@) mark_as_advanced(MITK_USE_TOF_MESASR4000) endif() # There is no PocoConfig.cmake, so we set Poco specific CMake variables # here. This way the call to find_package(Poco) in BlueBerryConfig.cmake # finds the Poco distribution supplied by MITK set(Poco_INCLUDE_DIR "@MITK_SOURCE_DIR@/Utilities/Poco") set(Poco_LIBRARY_DIR "@MITK_BINARY_DIR@/bin") if(MITK_USE_IGT) #include(${MITK_DIR}/mitkIGTConfig.cmake) endif() # Install rules for ToF libraries loaded at runtime include(@MITK_BINARY_DIR@/mitkToFHardwareInstallRules.cmake) if(NOT MITK_EXPORTS_FILE_INCLUDED) if(EXISTS "@MITK_EXPORTS_FILE@") set(MITK_EXPORTS_FILE_INCLUDED 1) include("@MITK_EXPORTS_FILE@") endif(EXISTS "@MITK_EXPORTS_FILE@") endif() # BlueBerry support if(MITK_USE_BLUEBERRY) set(BlueBerry_DIR "@MITK_BINARY_DIR@/BlueBerry") # Don't include the BlueBerry exports file, since the targets are # also exported in the MITK exports file set(BB_PLUGIN_EXPORTS_FILE_INCLUDED 1) find_package(BlueBerry) if(NOT BlueBerry_FOUND) message(SEND_ERROR "MITK does not seem to be configured with BlueBerry support. Set MITK_USE_BLUEBERRY to ON in your MITK build configuration.") endif(NOT BlueBerry_FOUND) set(MITK_PLUGIN_USE_FILE @MITK_PLUGIN_USE_FILE@) if(MITK_PLUGIN_USE_FILE) if(EXISTS ${MITK_PLUGIN_USE_FILE}) include(${MITK_PLUGIN_USE_FILE}) endif() endif() set(MITK_PLUGIN_PROVISIONING_FILE "@MITK_EXTAPP_PROVISIONING_FILE@") set(MITK_PROVISIONING_FILES "${BLUEBERRY_PLUGIN_PROVISIONING_FILE}" "${MITK_PLUGIN_PROVISIONING_FILE}") endif(MITK_USE_BLUEBERRY) # Set properties on exported targets @MITK_EXPORTED_TARGET_PROPERTIES@ diff --git a/Modules/DiffusionImaging/FiberTracking/Algorithms/GibbsTracking/mitkSphereInterpolator.cpp b/Modules/DiffusionImaging/FiberTracking/Algorithms/GibbsTracking/mitkSphereInterpolator.cpp index ae24059344..b98ade84c5 100644 --- a/Modules/DiffusionImaging/FiberTracking/Algorithms/GibbsTracking/mitkSphereInterpolator.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Algorithms/GibbsTracking/mitkSphereInterpolator.cpp @@ -1,173 +1,173 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSphereInterpolator.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include static const std::string BaryCoordsFileName = "FiberTrackingLUTBaryCoords.bin"; static const std::string IndicesFileName = "FiberTrackingLUTIndices.bin"; SphereInterpolator::SphereInterpolator(const string& lutPath) { m_ValidState = true; if (lutPath.length()==0) { if (!LoadLookuptables()) { m_ValidState = false; return; } } else { if (!LoadLookuptables(lutPath)) { m_ValidState = false; return; } } size = 301; sN = (size-1)/2; nverts = QBALL_ODFSIZE; beta = 0.5; inva = (sqrt(1+beta)-sqrt(beta)); b = 1/(1-sqrt(1/beta + 1)); } SphereInterpolator::~SphereInterpolator() { } bool SphereInterpolator::LoadLookuptables(const string& lutPath) { MITK_INFO << "SphereInterpolator: loading lookuptables from custom path: " << lutPath; string path = lutPath; path.append(BaryCoordsFileName); std::ifstream BaryCoordsStream; BaryCoordsStream.open(path.c_str(), ios::in | ios::binary); MITK_INFO << "SphereInterpolator: 1 " << path; if (!BaryCoordsStream.is_open()) { MITK_INFO << "SphereInterpolator: could not load FiberTrackingLUTBaryCoords.bin from " << path; return false; } ifstream IndicesStream; path = lutPath; path.append("FiberTrackingLUTIndices.bin"); IndicesStream.open(path.c_str(), ios::in | ios::binary); MITK_INFO << "SphereInterpolator: 1 " << path; if (!IndicesStream.is_open()) { MITK_INFO << "SphereInterpolator: could not load FiberTrackingLUTIndices.bin from " << path; return false; } if (LoadLookuptables(BaryCoordsStream, IndicesStream)) { MITK_INFO << "SphereInterpolator: first and second lut loaded successfully"; return true; } return false; } bool SphereInterpolator::LoadLookuptables() { MITK_INFO << "SphereInterpolator: loading lookuptables"; - mitk::Module* module = mitk::GetModuleContext()->GetModule(); - mitk::ModuleResource BaryCoordsRes = module->GetResource(BaryCoordsFileName); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource BaryCoordsRes = module->GetResource(BaryCoordsFileName); if (!BaryCoordsRes.IsValid()) { MITK_INFO << "Could not retrieve resource " << BaryCoordsFileName; return false; } - mitk::ModuleResource IndicesRes = module->GetResource(IndicesFileName); + us::ModuleResource IndicesRes = module->GetResource(IndicesFileName); if (!IndicesRes) { MITK_INFO << "Could not retrieve resource " << IndicesFileName; return false; } - mitk::ModuleResourceStream BaryCoordsStream(BaryCoordsRes, std::ios_base::binary); - mitk::ModuleResourceStream IndicesStream(IndicesRes, std::ios_base::binary); + us::ModuleResourceStream BaryCoordsStream(BaryCoordsRes, std::ios_base::binary); + us::ModuleResourceStream IndicesStream(IndicesRes, std::ios_base::binary); return LoadLookuptables(BaryCoordsStream, IndicesStream); } bool SphereInterpolator::LoadLookuptables(std::istream& BaryCoordsStream, std::istream& IndicesStream) { if (BaryCoordsStream) { try { float tmp; BaryCoordsStream.seekg (0, ios::beg); while (!BaryCoordsStream.eof()) { BaryCoordsStream.read((char *)&tmp, sizeof(tmp)); barycoords.push_back(tmp); } } catch (const std::exception& e) { MITK_INFO << e.what(); } } else { MITK_INFO << "SphereInterpolator: could not load FiberTrackingLUTBaryCoords.bin"; return false; } if (IndicesStream) { try { int tmp; IndicesStream.seekg (0, ios::beg); while (!IndicesStream.eof()) { IndicesStream.read((char *)&tmp, sizeof(tmp)); indices.push_back(tmp); } } catch (const std::exception& e) { MITK_INFO << e.what(); } } else { MITK_INFO << "SphereInterpolator: could not load FiberTrackingLUTIndices.bin"; return false; } return true; } diff --git a/Modules/DiffusionImaging/FiberTracking/Rendering/mitkFiberBundleXMapper2D.cpp b/Modules/DiffusionImaging/FiberTracking/Rendering/mitkFiberBundleXMapper2D.cpp index 1a89089ba8..8b3c86da81 100644 --- a/Modules/DiffusionImaging/FiberTracking/Rendering/mitkFiberBundleXMapper2D.cpp +++ b/Modules/DiffusionImaging/FiberTracking/Rendering/mitkFiberBundleXMapper2D.cpp @@ -1,278 +1,261 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /* * mitkFiberBundleMapper2D.cpp * mitk-all * * Created by HAL9000 on 1/17/11. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #include "mitkFiberBundleXMapper2D.h" #include #include #include #include #include //#include //#include #include #include #include #include #include #include #include #include //#include #include #include #include #include -#include -#include -#include +#include mitk::FiberBundleXMapper2D::FiberBundleXMapper2D() { m_lut = vtkLookupTable::New(); m_lut->Build(); } mitk::FiberBundleXMapper2D::~FiberBundleXMapper2D() { } mitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput() { return dynamic_cast< mitk::FiberBundleX * > ( GetDataNode()->GetData() ); } void mitk::FiberBundleXMapper2D::Update(mitk::BaseRenderer * renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if ( !visible ) return; MITK_DEBUG << "MapperFBX 2D update: "; // Calculate time step of the input data for the specified renderer (integer value) // this method is implemented in mitkMapper this->CalculateTimeStep( renderer ); //check if updates occured in the node or on the display FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); const DataNode *node = this->GetDataNode(); if ( (localStorage->m_LastUpdateTime < node->GetMTime()) || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) { // MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName(); this->GenerateDataForRenderer( renderer ); } if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning) { this->UpdateShaderParameter(renderer); } } void mitk::FiberBundleXMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer) { FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //get information about current position of views mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController(); mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry(); //generate according cutting planes based on the view position float sliceN[3], planeOrigin[3]; // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates planeOrigin[0] = (float) planeGeo->GetOrigin()[0]; planeOrigin[1] = (float) planeGeo->GetOrigin()[1]; planeOrigin[2] = (float) planeGeo->GetOrigin()[2]; sliceN[0] = planeGeo->GetNormal()[0]; sliceN[1] = planeGeo->GetNormal()[1]; sliceN[2] = planeGeo->GetNormal()[2]; float tmp1 = planeOrigin[0] * sliceN[0]; float tmp2 = planeOrigin[1] * sliceN[1]; float tmp3 = planeOrigin[2] * sliceN[2]; float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector float plane1[4]; plane1[0] = sliceN[0]; plane1[1] = sliceN[1]; plane1[2] = sliceN[2]; plane1[3] = d1; float thickness = 2.0; if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness)) MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR"; bool fiberfading = false; if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading)) MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR"; int fiberfading_i = 1; if (!fiberfading) fiberfading_i = 0; // set Opacity float fiberOpacity; this->GetDataNode()->GetOpacity(fiberOpacity, NULL); localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1); localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness); localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1, &fiberfading_i); localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberOpacity", 1, &fiberOpacity); } -mitk::IShaderRepository *mitk::FiberBundleXMapper2D::GetShaderRepository() -{ - ServiceReference serviceRef = GetModuleContext()->GetServiceReference(); - if (serviceRef) - { - return GetModuleContext()->GetService(serviceRef); - } - return NULL; -} - // ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE. // vtkActors and Mappers are feeded here void mitk::FiberBundleXMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { //the handler of local storage gets feeded in this method with requested data for related renderwindow FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //this procedure is depricated, //not needed after initializaton anymore mitk::DataNode* node = this->GetDataNode(); if ( node == NULL ) { MITK_INFO << "check DATANODE: ....[Fail] "; return; } /////////////////////////////////// ///THIS GET INPUT mitk::FiberBundleX* fbx = this->GetInput(); localStorage->m_PointMapper->ScalarVisibilityOn(); localStorage->m_PointMapper->SetScalarModeToUsePointFieldData(); localStorage->m_PointMapper->SetLookupTable(m_lut); //apply the properties after the slice was set localStorage->m_PointActor->GetProperty()->SetOpacity(0.999); // set color if (fbx->GetCurrentColorCoding() != NULL){ // localStorage->m_PointMapper->SelectColorArray(""); localStorage->m_PointMapper->SelectColorArray(fbx->GetCurrentColorCoding()); MITK_DEBUG << "MapperFBX 2D: " << fbx->GetCurrentColorCoding(); if(fbx->GetCurrentColorCoding() == fbx->COLORCODING_CUSTOM){ float temprgb[3]; this->GetDataNode()->GetColor( temprgb, NULL ); double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] }; localStorage->m_PointActor->GetProperty()->SetColor(trgb); } } localStorage->m_PointMapper->SetInput(fbx->GetFiberPolyData()); localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper); localStorage->m_PointActor->GetProperty()->ShadingOn(); // Applying shading properties - if (IShaderRepository* shaderRepo = GetShaderRepository()) - { - shaderRepo->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime); - } - + CoreServicePointer shaderRepo(CoreServices::GetShaderRepository()); + shaderRepo->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime); this->UpdateShaderParameter(renderer); // We have been modified => save this for next Update() localStorage->m_LastUpdateTime.Modified(); } vtkProp* mitk::FiberBundleXMapper2D::GetVtkProp(mitk::BaseRenderer *renderer) { //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)"; this->Update(renderer); return m_LSH.GetLocalStorage(renderer)->m_PointActor; } void mitk::FiberBundleXMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { //add shader to datano node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping")); - if (IShaderRepository* shaderRepo = GetShaderRepository()) - { - shaderRepo->AddDefaultProperties(node,renderer,overwrite); - } + CoreServicePointer shaderRepo(CoreServices::GetShaderRepository()); + shaderRepo->AddDefaultProperties(node,renderer,overwrite); //add other parameters to propertylist node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite ); node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite ); Superclass::SetDefaultProperties(node, renderer, overwrite); } mitk::FiberBundleXMapper2D::FBXLocalStorage::FBXLocalStorage() { m_PointActor = vtkSmartPointer::New(); m_PointMapper = vtkSmartPointer::New(); } diff --git a/Modules/DiffusionImaging/FiberTracking/Rendering/mitkFiberBundleXMapper2D.h b/Modules/DiffusionImaging/FiberTracking/Rendering/mitkFiberBundleXMapper2D.h index 757724fa08..e7b68ac9dd 100644 --- a/Modules/DiffusionImaging/FiberTracking/Rendering/mitkFiberBundleXMapper2D.h +++ b/Modules/DiffusionImaging/FiberTracking/Rendering/mitkFiberBundleXMapper2D.h @@ -1,110 +1,108 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef FIBERBUNDLEXMAPPER2D_H_HEADER_INCLUDED #define FIBERBUNDLEXMAPPER2D_H_HEADER_INCLUDED //MITK Rendering #include #include //#include "FiberTrackingExports.h" #include #include #include class vtkActor; //class vtkPropAssembly; //lets see if we need it class mitkBaseRenderer; class vtkPolyDataMapper; class vtkCutter; class vtkPlane; class vtkPolyData; namespace mitk { struct IShaderRepository; class FiberBundleXMapper2D : public VtkMapper { public: mitkClassMacro(FiberBundleXMapper2D, VtkMapper); itkNewMacro(Self); mitk::FiberBundleX* GetInput(); /** \brief Checks whether this mapper needs to update itself and generate * data. */ virtual void Update(mitk::BaseRenderer * renderer); static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = NULL, bool overwrite = false ); //### methods of MITK-VTK rendering pipeline virtual vtkProp* GetVtkProp(mitk::BaseRenderer* renderer); //### end of methods of MITK-VTK rendering pipeline class FBXLocalStorage : public mitk::Mapper::BaseLocalStorage { public: /** \brief Point Actor of a 2D render window. */ vtkSmartPointer m_PointActor; /** \brief Point Mapper of a 2D render window. */ vtkSmartPointer m_PointMapper; vtkSmartPointer m_SlicingPlane; //needed later when optimized 2D mapper vtkSmartPointer m_SlicedResult; //might be depricated in optimized 2D mapper /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** \brief Constructor of the local storage. Do as much actions as possible in here to avoid double executions. */ FBXLocalStorage(); //if u copy&paste from this 2Dmapper, be aware that the implementation of this constructor is in the cpp file ~FBXLocalStorage() { } }; /** \brief This member holds all three LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; protected: FiberBundleXMapper2D(); virtual ~FiberBundleXMapper2D(); /** Does the actual resampling, without rendering. */ virtual void GenerateDataForRenderer(mitk::BaseRenderer*); void UpdateShaderParameter(mitk::BaseRenderer*); - static IShaderRepository* GetShaderRepository(); - private: vtkSmartPointer m_lut; }; }//end namespace #endif diff --git a/Modules/IGT/IGTFilters/mitkNavigationDataSource.cpp b/Modules/IGT/IGTFilters/mitkNavigationDataSource.cpp index 691591cf06..381329b9a3 100644 --- a/Modules/IGT/IGTFilters/mitkNavigationDataSource.cpp +++ b/Modules/IGT/IGTFilters/mitkNavigationDataSource.cpp @@ -1,153 +1,153 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNavigationDataSource.h" #include "mitkUIDGenerator.h" //Microservices #include #include #include -#include "mitkModuleContext.h" +#include const std::string mitk::NavigationDataSource::US_INTERFACE_NAME = "org.mitk.services.NavigationDataSource"; const std::string mitk::NavigationDataSource::US_PROPKEY_DEVICENAME = US_INTERFACE_NAME + ".devicename"; const std::string mitk::NavigationDataSource::US_PROPKEY_ID = US_INTERFACE_NAME + ".id"; const std::string mitk::NavigationDataSource::US_PROPKEY_ISACTIVE = US_INTERFACE_NAME + ".isActive"; mitk::NavigationDataSource::NavigationDataSource() : itk::ProcessObject(), m_Name("NavigationDataSource (no defined type)") { } mitk::NavigationDataSource::~NavigationDataSource() { } mitk::NavigationData* mitk::NavigationDataSource::GetOutput() { if (this->GetNumberOfIndexedOutputs() < 1) return NULL; return static_cast(this->ProcessObject::GetPrimaryOutput()); } mitk::NavigationData* mitk::NavigationDataSource::GetOutput(DataObjectPointerArraySizeType idx) { NavigationData* out = dynamic_cast( this->ProcessObject::GetOutput(idx) ); if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL ) { itkWarningMacro (<< "Unable to convert output number " << idx << " to type " << typeid( NavigationData ).name () ); } return out; } mitk::NavigationData* mitk::NavigationDataSource::GetOutput(const std::string& navDataName) { DataObjectPointerArray outputs = this->GetOutputs(); for (DataObjectPointerArray::iterator it = outputs.begin(); it != outputs.end(); ++it) if (navDataName == (static_cast(it->GetPointer()))->GetName()) return static_cast(it->GetPointer()); return NULL; } itk::ProcessObject::DataObjectPointerArraySizeType mitk::NavigationDataSource::GetOutputIndex( std::string navDataName ) { DataObjectPointerArray outputs = this->GetOutputs(); for (DataObjectPointerArray::size_type i = 0; i < outputs.size(); ++i) if (navDataName == (static_cast(outputs.at(i).GetPointer()))->GetName()) return i; throw std::invalid_argument("output name does not exist"); } void mitk::NavigationDataSource::RegisterAsMicroservice(){ // Get Context - mitk::ModuleContext* context = GetModuleContext(); + us::ModuleContext* context = us::GetModuleContext(); // Define ServiceProps - ServiceProperties props; + us::ServiceProperties props; mitk::UIDGenerator uidGen = mitk::UIDGenerator ("org.mitk.services.NavigationDataSource.id_", 16); props[ US_PROPKEY_ID ] = uidGen.GetUID(); props[ US_PROPKEY_DEVICENAME ] = m_Name; - m_ServiceRegistration = context->RegisterService(this, props); + m_ServiceRegistration = context->RegisterService(this, props); } void mitk::NavigationDataSource::UnRegisterMicroservice(){ m_ServiceRegistration.Unregister(); m_ServiceRegistration = 0; } std::string mitk::NavigationDataSource::GetMicroserviceID(){ return this->m_ServiceRegistration.GetReference().GetProperty(US_PROPKEY_ID).ToString(); } void mitk::NavigationDataSource::GraftOutput(itk::DataObject *graft) { this->GraftNthOutput(0, graft); } void mitk::NavigationDataSource::GraftNthOutput(unsigned int idx, itk::DataObject *graft) { if ( idx >= this->GetNumberOfIndexedOutputs() ) { itkExceptionMacro(<<"Requested to graft output " << idx << " but this filter only has " << this->GetNumberOfIndexedOutputs() << " Outputs."); } if ( !graft ) { itkExceptionMacro(<<"Requested to graft output with a NULL pointer object" ); } itk::DataObject* output = this->GetOutput(idx); if ( !output ) { itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); } // Call Graft on NavigationData to copy member data output->Graft( graft ); } itk::DataObject::Pointer mitk::NavigationDataSource::MakeOutput ( DataObjectPointerArraySizeType /*idx*/ ) { return mitk::NavigationData::New().GetPointer(); } itk::DataObject::Pointer mitk::NavigationDataSource::MakeOutput( const DataObjectIdentifierType & name ) { itkDebugMacro("MakeOutput(" << name << ")"); if( this->IsIndexedOutputName(name) ) { return this->MakeOutput( this->MakeIndexFromOutputName(name) ); } return static_cast(mitk::NavigationData::New().GetPointer()); } mitk::PropertyList::ConstPointer mitk::NavigationDataSource::GetParameters() const { mitk::PropertyList::Pointer p = mitk::PropertyList::New(); // add properties to p like this: //p->SetProperty("MyFilter_MyParameter", mitk::PropertyDataType::New(m_MyParameter)); return mitk::PropertyList::ConstPointer(p); } diff --git a/Modules/IGT/IGTFilters/mitkNavigationDataSource.h b/Modules/IGT/IGTFilters/mitkNavigationDataSource.h index 85e43dad2e..0d657768ee 100644 --- a/Modules/IGT/IGTFilters/mitkNavigationDataSource.h +++ b/Modules/IGT/IGTFilters/mitkNavigationDataSource.h @@ -1,171 +1,171 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKNAVIGATIONDATASOURCE_H_HEADER_INCLUDED_ #define MITKNAVIGATIONDATASOURCE_H_HEADER_INCLUDED_ #include #include "mitkNavigationData.h" #include "mitkPropertyList.h" // Microservices #include #include namespace mitk { /**Documentation * \brief Navigation Data source * * Base class for all navigation filters that produce NavigationData objects as output. * This class defines the output-interface for NavigationDataFilters. * \warning: if Update() is called on any output object, all NavigationData filters will * generate new output data for all outputs, not just the one on which Update() was called. * * \ingroup IGT */ class MitkIGT_EXPORT NavigationDataSource : public itk::ProcessObject { public: mitkClassMacro(NavigationDataSource, itk::ProcessObject); /** @return Returns a human readable name of this source. There will be a default name, * or you can set the name with the method SetName() if you want to change it. */ itkGetMacro(Name,std::string); /** @brief Sets the human readable name of this source. There is also a default name, * but you can use this method if you need to define it on your own. */ itkSetMacro(Name,std::string); /** *\brief return the output (output with id 0) of the filter */ NavigationData* GetOutput(void); /** *\brief return the output with id idx of the filter */ NavigationData* GetOutput(DataObjectPointerArraySizeType idx); /** *\brief return the output with name navDataName of the filter */ NavigationData* GetOutput(const std::string& navDataName); /** *\brief return the index of the output with name navDataName, -1 if no output with that name was found * * \warning if a subclass has outputs that have different data type than mitk::NavigationData, they have to overwrite this method */ DataObjectPointerArraySizeType GetOutputIndex(std::string navDataName); /** *\brief Registers this object as a Microservice, making it available to every module and/or plugin. * To unregister, call UnregisterMicroservice(). */ virtual void RegisterAsMicroservice(); /** *\brief Registers this object as a Microservice, making it available to every module and/or plugin. */ virtual void UnRegisterMicroservice(); /** *\brief Returns the id that this device is registered with. The id will only be valid, if the * NavigationDataSource has been registered using RegisterAsMicroservice(). */ std::string GetMicroserviceID(); /** *\brief These Constants are used in conjunction with Microservices */ static const std::string US_INTERFACE_NAME; static const std::string US_PROPKEY_DEVICENAME; static const std::string US_PROPKEY_ID; static const std::string US_PROPKEY_ISACTIVE; //NOT IMPLEMENTED YET! /** *\brief Graft the specified DataObject onto this ProcessObject's output. * * See itk::ImageSource::GraftNthOutput for details */ virtual void GraftNthOutput(unsigned int idx, itk::DataObject *graft); /** * \brief Graft the specified DataObject onto this ProcessObject's output. * * See itk::ImageSource::Graft Output for details */ virtual void GraftOutput(itk::DataObject *graft); /** * Allocates a new output object and returns it. Currently the * index idx is not evaluated. * @param idx the index of the output for which an object should be created * @returns the new object */ virtual itk::DataObject::Pointer MakeOutput ( DataObjectPointerArraySizeType idx ); /** * This is a default implementation to make sure we have something. * Once all the subclasses of ProcessObject provide an appopriate * MakeOutput(), then ProcessObject::MakeOutput() can be made pure * virtual. */ virtual itk::DataObject::Pointer MakeOutput(const DataObjectIdentifierType &name); /** * \brief Set all filter parameters as the PropertyList p * * This method allows to set all parameters of a filter with one * method call. For the names of the parameters, take a look at * the GetParameters method of the filter * This method has to be overwritten by each MITK-IGT filter. */ virtual void SetParameters(const mitk::PropertyList*){}; /** * \brief Get all filter parameters as a PropertyList * * This method allows to get all parameters of a filter with one * method call. The returned PropertyList must be assigned to a * SmartPointer immediately, or else it will get destroyed. * Every filter must overwrite this method to create a filter-specific * PropertyList. Note that property names must be unique over all * MITK-IGT filters. Therefore each filter should use its name as a prefix * for each property name. * Secondly, each filter should list the property names and data types * in the method documentation. */ virtual mitk::PropertyList::ConstPointer GetParameters() const; protected: NavigationDataSource(); virtual ~NavigationDataSource(); std::string m_Name; private: - mitk::ServiceRegistration m_ServiceRegistration; + us::ServiceRegistration m_ServiceRegistration; }; } // namespace mitk // This is the microservice declaration. Do not meddle! US_DECLARE_SERVICE_INTERFACE(mitk::NavigationDataSource, "org.mitk.services.NavigationDataSource") #endif /* MITKNAVIGATIONDATASOURCE_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorage.cpp b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorage.cpp index 463ffbab6d..a3fee7f94f 100644 --- a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorage.cpp +++ b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorage.cpp @@ -1,129 +1,129 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkNavigationToolStorage.h" //Microservices #include #include #include -#include "mitkModuleContext.h" +#include const std::string mitk::NavigationToolStorage::US_INTERFACE_NAME = "org.mitk.services.NavigationToolStorage"; // Name of the interface const std::string mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID = US_INTERFACE_NAME + ".sourceID"; mitk::NavigationToolStorage::NavigationToolStorage() { m_ToolCollection = std::vector(); this->m_DataStorage = NULL; } mitk::NavigationToolStorage::NavigationToolStorage(mitk::DataStorage::Pointer ds) { m_ToolCollection = std::vector(); this->m_DataStorage = ds; } mitk::NavigationToolStorage::~NavigationToolStorage() { if (m_DataStorage.IsNotNull()) //remove all nodes from the data storage { for(std::vector::iterator it = m_ToolCollection.begin(); it != m_ToolCollection.end(); it++) m_DataStorage->Remove((*it)->GetDataNode()); } } void mitk::NavigationToolStorage::RegisterAsMicroservice(std::string sourceID){ if ( sourceID.empty() ) mitkThrow() << "Empty or null string passed to NavigationToolStorage::registerAsMicroservice()."; // Get Context - mitk::ModuleContext* context = GetModuleContext(); + us::ModuleContext* context = us::GetModuleContext(); // Define ServiceProps - ServiceProperties props; + us::ServiceProperties props; props[ US_PROPKEY_SOURCE_ID ] = sourceID; - m_ServiceRegistration = context->RegisterService(this, props); + m_ServiceRegistration = context->RegisterService(this, props); } void mitk::NavigationToolStorage::UnRegisterMicroservice(){ m_ServiceRegistration.Unregister(); m_ServiceRegistration = 0; } bool mitk::NavigationToolStorage::DeleteTool(int number) { if ((unsigned int)number > m_ToolCollection.size()) return false; std::vector::iterator it = m_ToolCollection.begin() + number; if(m_DataStorage.IsNotNull()) m_DataStorage->Remove((*it)->GetDataNode()); m_ToolCollection.erase(it); return true; } bool mitk::NavigationToolStorage::DeleteAllTools() { while(m_ToolCollection.size() > 0) if (!DeleteTool(0)) return false; return true; } bool mitk::NavigationToolStorage::AddTool(mitk::NavigationTool::Pointer tool) { if (GetTool(tool->GetIdentifier()).IsNotNull()) return false; else { m_ToolCollection.push_back(tool); if(m_DataStorage.IsNotNull()) { if (!m_DataStorage->Exists(tool->GetDataNode())) m_DataStorage->Add(tool->GetDataNode()); } return true; } } mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(int number) { return m_ToolCollection.at(number); } mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetTool(std::string identifier) { for (int i=0; iGetIdentifier())==identifier) return GetTool(i); return NULL; } mitk::NavigationTool::Pointer mitk::NavigationToolStorage::GetToolByName(std::string name) { for (int i=0; iGetToolName())==name) return GetTool(i); return NULL; } int mitk::NavigationToolStorage::GetToolCount() { return m_ToolCollection.size(); } bool mitk::NavigationToolStorage::isEmpty() { return m_ToolCollection.empty(); } diff --git a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorage.h b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorage.h index ead7b6ae47..177bccca22 100644 --- a/Modules/IGT/IGTToolManagement/mitkNavigationToolStorage.h +++ b/Modules/IGT/IGTToolManagement/mitkNavigationToolStorage.h @@ -1,149 +1,149 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef NAVIGATIONTOOLSTORAGE_H_INCLUDED #define NAVIGATIONTOOLSTORAGE_H_INCLUDED //itk headers #include //mitk headers #include #include #include "mitkNavigationTool.h" #include // Microservices #include #include namespace mitk { /**Documentation * \brief An object of this class represents a collection of navigation tools. * You may add/delete navigation tools or store/load the whole collection * to/from the harddisc by using the class NavigationToolStorageSerializer * and NavigationToolStorageDeserializer. * * \ingroup IGT */ class MitkIGT_EXPORT NavigationToolStorage : public itk::Object { public: mitkClassMacro(NavigationToolStorage,itk::Object); /** @brief Constructs a NavigationToolStorage without reference to a DataStorage. The Data Nodes of tools have to be added and removed to a data storage outside this class. * Normaly the other constructor should be used. */ itkNewMacro(Self); /** @brief Constructs a NavigationToolStorage with reference to a DataStorage. The Data Nodes of tools are added and removed automatically to this data storage. */ mitkNewMacro1Param(Self,mitk::DataStorage::Pointer); /** *\brief Registers this object as a Microservice, making it available to every module and/or plugin. * To unregister, call UnregisterMicroservice(). Make sure to pass the id of the Device that this tool is connected to. */ virtual void RegisterAsMicroservice(std::string sourceID); /** *\brief Registers this object as a Microservice, making it available to every module and/or plugin. */ virtual void UnRegisterMicroservice(); /** *\brief Returns the id that this device is registered with. The id will only be valid, if the * NavigationDataSource has been registered using RegisterAsMicroservice(). */ std::string GetMicroserviceID(); /** *\brief These constants are used in conjunction with Microservices */ static const std::string US_INTERFACE_NAME; // Name of the interface static const std::string US_PROPKEY_SOURCE_ID; // ID of the device this ToolStorage is associated with /** * @brief Adds a tool to the storage. Be sure that the tool has a unique * identifier which is not already part of this storage. * @return Returns true if the tool was added to the storage, false if not * (false can be returned if the identifier already exists in this storage * for example). */ bool AddTool(mitk::NavigationTool::Pointer tool); /** * @return Returns the tracking tool at the position "number" * in the storage. Returns NULL if there is no * tracking tool at this position. */ mitk::NavigationTool::Pointer GetTool(int number); /** * @return Returns the tracking tool with the given identifier. * Returns NULL if there is no * tracking tool with this identifier in the storage. */ mitk::NavigationTool::Pointer GetTool(std::string identifier); /** * @return Returns the tracking tool with the given name. * Returns NULL if there is no * tracking tool with this name in the storage. */ mitk::NavigationTool::Pointer GetToolByName(std::string name); /** * @brief Deletes a tool from the collection. */ bool DeleteTool(int number); /** * @brief Deletes all tools from the collection. */ bool DeleteAllTools(); /** * @return Returns the number of tools stored in the storage. */ int GetToolCount(); /** * @return Returns true if the storage is empty, false if not. */ bool isEmpty(); /** * @return Returns the corresponding data storage if one is set to this NavigationToolStorage. * Returns NULL if none is set. */ itkGetMacro(DataStorage,mitk::DataStorage::Pointer); protected: NavigationToolStorage(); NavigationToolStorage(mitk::DataStorage::Pointer); ~NavigationToolStorage(); std::vector m_ToolCollection; mitk::DataStorage::Pointer m_DataStorage; private: - mitk::ServiceRegistration m_ServiceRegistration; + us::ServiceRegistration m_ServiceRegistration; }; } // namespace mitk US_DECLARE_SERVICE_INTERFACE(mitk::NavigationToolStorage, "org.mitk.services.NavigationToolStorage") #endif //NAVIGATIONTOOLSTORAGE diff --git a/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.cpp b/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.cpp index f3ceebaebd..1b39a416e2 100644 --- a/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.cpp +++ b/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.cpp @@ -1,126 +1,124 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkNavigationDataSourceSelectionWidget.h" //mitk headers #include -#include -#include - +#include QmitkNavigationDataSourceSelectionWidget::QmitkNavigationDataSourceSelectionWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { m_Controls = NULL; CreateQtPartControl(this); CreateConnections(); } QmitkNavigationDataSourceSelectionWidget::~QmitkNavigationDataSourceSelectionWidget() { } void QmitkNavigationDataSourceSelectionWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkNavigationDataSourceSelectionWidgetControls; m_Controls->setupUi(parent); std::string empty = ""; m_Controls->m_NaviagationDataSourceWidget->Initialize(mitk::NavigationDataSource::US_PROPKEY_DEVICENAME,empty); } } void QmitkNavigationDataSourceSelectionWidget::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_NaviagationDataSourceWidget), SIGNAL(ServiceSelectionChanged(mitk::ServiceReference)), this, SLOT(NavigationDataSourceSelected(mitk::ServiceReference)) ); } } -void QmitkNavigationDataSourceSelectionWidget::NavigationDataSourceSelected(mitk::ServiceReference s) +void QmitkNavigationDataSourceSelectionWidget::NavigationDataSourceSelected(us::ServiceReference s) { if (!s) //no device selected { //reset everything m_CurrentSource = NULL; m_CurrentStorage = NULL; return; } // Get Source - m_CurrentSource = this->m_Controls->m_NaviagationDataSourceWidget->TranslateReference(s); + us::ModuleContext* context = us::GetModuleContext(); + m_CurrentSource = context->GetService(s); std::string id = s.GetProperty(mitk::NavigationDataSource::US_PROPKEY_ID).ToString(); - mitk::ModuleContext* context = mitk::GetModuleContext(); //Fill tool list - for(int i = 0; i < m_CurrentSource->GetNumberOfOutputs(); i++) {new QListWidgetItem(tr(m_CurrentSource->GetOutput(i)->GetName()), m_Controls->m_ToolView);} + for(std::size_t i = 0; i < m_CurrentSource->GetNumberOfOutputs(); i++) {new QListWidgetItem(tr(m_CurrentSource->GetOutput(i)->GetName()), m_Controls->m_ToolView);} // Create Filter for ToolStorage - std::string filter = "(&(" + mitk::ServiceConstants::OBJECTCLASS() + "=" + mitk::NavigationToolStorage::US_INTERFACE_NAME + ")("+ mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID + "=" + id + "))"; + std::string filter = "("+ mitk::NavigationToolStorage::US_PROPKEY_SOURCE_ID + "=" + id + ")"; // Get Storage - std::list refs = context->GetServiceReferences(mitk::NavigationToolStorage::US_INTERFACE_NAME, filter); - if (refs.size() == 0) return; //no storage was found - m_CurrentStorage = context->GetService(refs.front()); + std::vector > refs = context->GetServiceReferences(filter); + if (refs.empty()) return; //no storage was found + m_CurrentStorage = context->GetService(refs.front()); if (m_CurrentStorage.IsNull()) { MITK_WARN << "Found an invalid storage object!"; return; } if (m_CurrentStorage->GetToolCount() != m_CurrentSource->GetNumberOfOutputs()) //there is something wrong with the storage { MITK_WARN << "Found a tool storage, but it has not the same number of tools like the NavigationDataSource. This storage won't be used because it isn't the right one."; m_CurrentStorage = NULL; } } mitk::NavigationDataSource::Pointer QmitkNavigationDataSourceSelectionWidget::GetSelectedNavigationDataSource() { return this->m_CurrentSource; } int QmitkNavigationDataSourceSelectionWidget::GetSelectedToolID() { return this->m_Controls->m_ToolView->currentIndex().row(); } mitk::NavigationTool::Pointer QmitkNavigationDataSourceSelectionWidget::GetSelectedNavigationTool() { if (this->m_CurrentStorage.IsNull()) return NULL; if (m_Controls->m_ToolView->currentIndex().row() >= m_CurrentStorage->GetToolCount()) return NULL; return this->m_CurrentStorage->GetTool(m_Controls->m_ToolView->currentIndex().row()); } mitk::NavigationToolStorage::Pointer QmitkNavigationDataSourceSelectionWidget::GetNavigationToolStorageOfSource() { return this->m_CurrentStorage; - } \ No newline at end of file + } diff --git a/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.h b/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.h index d4fd5f92ca..765b2a1718 100644 --- a/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.h +++ b/Modules/IGTUI/Qmitk/QmitkNavigationDataSourceSelectionWidget.h @@ -1,89 +1,89 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkNavigationDataSourceSelectionWidget_H #define QmitkNavigationDataSourceSelectionWidget_H //QT headers #include //mitk headers #include "MitkIGTUIExports.h" #include #include -#include +#include //ui header #include "ui_QmitkNavigationDataSourceSelectionWidgetControls.h" /** Documentation: * \brief This widget allows the user to select a NavigationDataSource. Tools of this Source are also shown and the user can select one of these tools. * \ingroup IGTUI */ class MitkIGTUI_EXPORT QmitkNavigationDataSourceSelectionWidget : public QWidget { Q_OBJECT public: static const std::string VIEW_ID; QmitkNavigationDataSourceSelectionWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); ~QmitkNavigationDataSourceSelectionWidget(); /** @return Returns the currently selected NavigationDataSource. Returns null if no source is selected at the moment. */ mitk::NavigationDataSource::Pointer GetSelectedNavigationDataSource(); /** @return Returns the ID of the currently selected tool. You can get the corresponding NavigationData when calling GetOutput(id) * on the source object. Returns -1 if there is no tool selected. */ int GetSelectedToolID(); /** @return Returns the NavigationTool of the current selected tool if a NavigationToolStorage is available. Returns NULL if * there is no storage available or if no tool is selected. */ mitk::NavigationTool::Pointer GetSelectedNavigationTool(); /** @return Returns the NavigationToolStorage of the currently selected NavigationDataSource. Returns NULL if there is no * source selected or if the source has no NavigationToolStorage assigned. */ mitk::NavigationToolStorage::Pointer GetNavigationToolStorageOfSource(); signals: protected slots: - void NavigationDataSourceSelected(mitk::ServiceReference s); + void NavigationDataSourceSelected(us::ServiceReference s); protected: /// \brief Creation of the connections virtual void CreateConnections(); virtual void CreateQtPartControl(QWidget *parent); Ui::QmitkNavigationDataSourceSelectionWidgetControls* m_Controls; mitk::NavigationToolStorage::Pointer m_CurrentStorage; mitk::NavigationDataSource::Pointer m_CurrentSource; }; -#endif \ No newline at end of file +#endif diff --git a/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.cpp b/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.cpp index 3cb14a9e5a..c34b18867b 100644 --- a/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.cpp +++ b/Modules/PlanarFigure/Interactions/mitkPlanarFigureInteractor.cpp @@ -1,957 +1,952 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #define PLANARFIGUREINTERACTOR_DBG MITK_DEBUG("PlanarFigureInteractor") << __LINE__ << ": " #include "mitkPlanarFigureInteractor.h" #include "mitkPlanarFigure.h" #include "mitkPlanarPolygon.h" #include "mitkInteractionPositionEvent.h" #include "mitkInternalEvent.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" -// MicroServices -#include "mitkGetModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleRegistry.h" - //how precise must the user pick the point //default value mitk::PlanarFigureInteractor::PlanarFigureInteractor() : DataInteractor() , m_Precision( 6.5 ) , m_MinimumPointDistance( 25.0 ) , m_IsHovering( false ) , m_LastPointWasValid( false ) { } mitk::PlanarFigureInteractor::~PlanarFigureInteractor() { } void mitk::PlanarFigureInteractor::ConnectActionsAndFunctions() { CONNECT_CONDITION("figure_is_on_current_slice", CheckFigureOnRenderingGeometry); CONNECT_CONDITION("figure_is_placed", CheckFigurePlaced); CONNECT_CONDITION("minimal_figure_is_finished", CheckMinimalFigureFinished); CONNECT_CONDITION("hovering_above_figure", CheckFigureHovering); CONNECT_CONDITION("hovering_above_point", CheckControlPointHovering); CONNECT_CONDITION("figure_is_selected", CheckSelection); CONNECT_CONDITION("point_is_valid", CheckPointValidity); CONNECT_CONDITION("figure_is_finished", CheckFigureFinished); CONNECT_CONDITION("reset_on_point_select_needed", CheckResetOnPointSelect); CONNECT_CONDITION("points_can_be_added_or_removed", CheckFigureIsExtendable); CONNECT_FUNCTION( "finalize_figure", FinalizeFigure); CONNECT_FUNCTION( "hide_preview_point", HidePreviewPoint ) CONNECT_FUNCTION( "set_preview_point_position", SetPreviewPointPosition ) CONNECT_FUNCTION( "switch_to_hovering", SwitchToHovering ) CONNECT_FUNCTION( "move_current_point", MoveCurrentPoint); CONNECT_FUNCTION( "deselect_point", DeselectPoint); CONNECT_FUNCTION( "add_new_point", AddPoint); CONNECT_FUNCTION( "add_initial_point", AddInitialPoint); CONNECT_FUNCTION( "remove_selected_point", RemoveSelectedPoint); CONNECT_FUNCTION( "request_context_menu", RequestContextMenu); CONNECT_FUNCTION( "select_figure", SelectFigure ); CONNECT_FUNCTION( "select_point", SelectPoint ); CONNECT_FUNCTION( "end_interaction", EndInteraction ); } bool mitk::PlanarFigureInteractor::CheckFigurePlaced( const InteractionEvent* interactionEvent ) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); bool isFigureFinished = false; planarFigure->GetPropertyList()->GetBoolProperty( "initiallyplaced", isFigureFinished ); return planarFigure->IsPlaced() && isFigureFinished; } bool mitk::PlanarFigureInteractor::MoveCurrentPoint(StateMachineAction*, InteractionEvent* interactionEvent) { mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; bool isEditable = true; GetDataNode()->GetBoolProperty( "planarfigure.iseditable", isEditable ); mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); // Extract point in 2D world coordinates (relative to Geometry2D of // PlanarFigure) Point2D point2D; if ( !this->TransformPositionEventToPoint2D( positionEvent, planarFigureGeometry, point2D ) || !isEditable ) { return false; } // check if the control points shall be hidden during interaction bool hidecontrolpointsduringinteraction = false; GetDataNode()->GetBoolProperty( "planarfigure.hidecontrolpointsduringinteraction", hidecontrolpointsduringinteraction ); // hide the control points if necessary //interactionEvent->GetSender()->GetDataStorage()->BlockNodeModifiedEvents( true ); GetDataNode()->SetBoolProperty( "planarfigure.drawcontrolpoints", !hidecontrolpointsduringinteraction ); //interactionEvent->GetSender()->GetDataStorage()->BlockNodeModifiedEvents( false ); // Move current control point to this point planarFigure->SetCurrentControlPoint( point2D ); // Re-evaluate features planarFigure->EvaluateFeatures(); // Update rendered scene interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); return true; } bool mitk::PlanarFigureInteractor::FinalizeFigure( StateMachineAction*, InteractionEvent* interactionEvent ) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); planarFigure->Modified(); planarFigure->DeselectControlPoint(); planarFigure->RemoveLastControlPoint(); planarFigure->SetProperty( "initiallyplaced", mitk::BoolProperty::New( true ) ); GetDataNode()->SetBoolProperty( "planarfigure.drawcontrolpoints", true ); GetDataNode()->Modified(); planarFigure->InvokeEvent( EndPlacementPlanarFigureEvent() ); planarFigure->InvokeEvent( EndInteractionPlanarFigureEvent() ); interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); return false; } bool mitk::PlanarFigureInteractor::EndInteraction( StateMachineAction*, InteractionEvent* interactionEvent ) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); GetDataNode()->SetBoolProperty( "planarfigure.drawcontrolpoints", true ); planarFigure->Modified(); planarFigure->InvokeEvent( EndInteractionPlanarFigureEvent() ); interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); return false; } bool mitk::PlanarFigureInteractor::CheckMinimalFigureFinished( const InteractionEvent* interactionEvent ) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); return ( planarFigure->GetNumberOfControlPoints() >= planarFigure->GetMinimumNumberOfControlPoints() ); } bool mitk::PlanarFigureInteractor::CheckFigureFinished( const InteractionEvent* interactionEvent ) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); return ( planarFigure->GetNumberOfControlPoints() >= planarFigure->GetMaximumNumberOfControlPoints() ); } bool mitk::PlanarFigureInteractor::CheckFigureIsExtendable( const InteractionEvent* interactionEvent ) { bool isExtendable = false; GetDataNode()->GetBoolProperty("planarfigure.isextendable", isExtendable); return isExtendable; } bool mitk::PlanarFigureInteractor::DeselectPoint(StateMachineAction*, InteractionEvent* interactionEvent) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); bool wasSelected = planarFigure->DeselectControlPoint(); if ( wasSelected ) { // Issue event so that listeners may update themselves planarFigure->Modified(); planarFigure->InvokeEvent( EndInteractionPlanarFigureEvent() ); GetDataNode()->SetBoolProperty( "planarfigure.drawcontrolpoints", true ); GetDataNode()->SetBoolProperty( "planarfigure.ishovering", false ); GetDataNode()->Modified(); } return true; } bool mitk::PlanarFigureInteractor::AddPoint(StateMachineAction*, InteractionEvent* interactionEvent) { mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; bool selected = false; bool isEditable = true; GetDataNode()->GetBoolProperty("selected", selected); GetDataNode()->GetBoolProperty( "planarfigure.iseditable", isEditable ); if ( !selected || !isEditable ) { return false; } mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); // If the planarFigure already has reached the maximum number if ( planarFigure->GetNumberOfControlPoints() >= planarFigure->GetMaximumNumberOfControlPoints() ) { return false; } // Extract point in 2D world coordinates (relative to Geometry2D of // PlanarFigure) Point2D point2D, projectedPoint; if ( !this->TransformPositionEventToPoint2D( positionEvent, planarFigureGeometry, point2D ) ) { return false; } // TODO: check segment of polyline we clicked in int nextIndex = -1; // We only need to check which position to insert the control point // when interacting with a PlanarPolygon. For all other types // new control points will always be appended /* * Added check for "initiallyplaced" due to bug 13097: * * There are two possible cases in which a point can be inserted into a PlanarPolygon: * * 1. The figure is currently drawn -> the point will be appended at the end of the figure * 2. A point is inserted at a userdefined position after the initial placement of the figure is finished * * In the second case we need to determine the proper insertion index. In the first case the index always has * to be -1 so that the point is appended to the end. * * These changes are neccessary because of a mac os x specific issue: If a users draws a PlanarPolygon then the * next point to be added moves according to the mouse position. If then the user left clicks in order to add * a point one would assume the last move position is identical to the left click position. This is actually the * case for windows and linux but somehow NOT for mac. Because of the insertion logic of a new point in the * PlanarFigure then for mac the wrong current selected point is determined. * * With this check here this problem can be avoided. However a redesign of the insertion logic should be considered */ bool isFigureFinished = false; planarFigure->GetPropertyList()->GetBoolProperty( "initiallyplaced", isFigureFinished ); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); const Geometry2D *projectionPlane = renderer->GetCurrentWorldGeometry2D(); if ( dynamic_cast( planarFigure ) && isFigureFinished) { nextIndex = this->IsPositionOverFigure( positionEvent, planarFigure, planarFigureGeometry, projectionPlane, renderer->GetDisplayGeometry(), projectedPoint ); } // Add point as new control point renderer->GetDisplayGeometry()->DisplayToWorld( projectedPoint, projectedPoint ); if ( planarFigure->IsPreviewControlPointVisible() ) { point2D = planarFigure->GetPreviewControlPoint(); } planarFigure->AddControlPoint( point2D, nextIndex ); if ( planarFigure->IsPreviewControlPointVisible() ) { planarFigure->SelectControlPoint( nextIndex ); planarFigure->ResetPreviewContolPoint(); } // Re-evaluate features planarFigure->EvaluateFeatures(); //this->LogPrintPlanarFigureQuantities( planarFigure ); // Update rendered scene renderer->GetRenderingManager()->RequestUpdateAll(); return true; } bool mitk::PlanarFigureInteractor::AddInitialPoint(StateMachineAction*, InteractionEvent* interactionEvent) { mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); // Invoke event to notify listeners that placement of this PF starts now planarFigure->InvokeEvent( StartPlacementPlanarFigureEvent() ); // Use Geometry2D of the renderer clicked on for this PlanarFigure mitk::PlaneGeometry *planeGeometry = const_cast< mitk::PlaneGeometry * >( dynamic_cast< const mitk::PlaneGeometry * >( renderer->GetSliceNavigationController()->GetCurrentPlaneGeometry() ) ); if ( planeGeometry != NULL ) { planarFigureGeometry = planeGeometry; planarFigure->SetGeometry2D( planeGeometry ); } else { return false; } // Extract point in 2D world coordinates (relative to Geometry2D of // PlanarFigure) Point2D point2D; if ( !this->TransformPositionEventToPoint2D( positionEvent, planarFigureGeometry, point2D ) ) { return false; } // Place PlanarFigure at this point planarFigure->PlaceFigure( point2D ); // Re-evaluate features planarFigure->EvaluateFeatures(); //this->LogPrintPlanarFigureQuantities( planarFigure ); // Set a bool property indicating that the figure has been placed in // the current RenderWindow. This is required so that the same render // window can be re-aligned to the Geometry2D of the PlanarFigure later // on in an application. GetDataNode()->SetBoolProperty( "PlanarFigureInitializedWindow", true, renderer ); // Update rendered scene renderer->GetRenderingManager()->RequestUpdateAll(); return true; } bool mitk::PlanarFigureInteractor::SwitchToHovering( StateMachineAction*, InteractionEvent* interactionEvent ) { mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); const Geometry2D *projectionPlane = renderer->GetCurrentWorldGeometry2D(); if ( !m_IsHovering ) { // Invoke hover event once when the mouse is entering the figure area m_IsHovering = true; planarFigure->InvokeEvent( StartHoverPlanarFigureEvent() ); // Set bool property to indicate that planar figure is currently in "hovering" mode GetDataNode()->SetBoolProperty( "planarfigure.ishovering", true ); renderer->GetRenderingManager()->RequestUpdateAll(); } return true; } bool mitk::PlanarFigureInteractor::SetPreviewPointPosition( StateMachineAction*, InteractionEvent* interactionEvent ) { mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); const Geometry2D *projectionPlane = renderer->GetCurrentWorldGeometry2D(); planarFigure->DeselectControlPoint(); mitk::Point2D pointProjectedOntoLine; int previousControlPoint = mitk::PlanarFigureInteractor::IsPositionOverFigure( positionEvent, planarFigure, planarFigureGeometry, projectionPlane, renderer->GetDisplayGeometry(), pointProjectedOntoLine ); bool selected(false); bool isExtendable(false); bool isEditable(true); GetDataNode()->GetBoolProperty("selected", selected); GetDataNode()->GetBoolProperty("planarfigure.isextendable", isExtendable); GetDataNode()->GetBoolProperty( "planarfigure.iseditable", isEditable ); if ( selected && isExtendable && isEditable ) { renderer->GetDisplayGeometry()->DisplayToWorld( pointProjectedOntoLine, pointProjectedOntoLine ); planarFigure->SetPreviewControlPoint( pointProjectedOntoLine ); } renderer->GetRenderingManager()->RequestUpdateAll(); return false; } bool mitk::PlanarFigureInteractor::HidePreviewPoint( StateMachineAction*, InteractionEvent* interactionEvent ) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); planarFigure->ResetPreviewContolPoint(); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); renderer->GetRenderingManager()->RequestUpdateAll(); return false; } bool mitk::PlanarFigureInteractor::CheckFigureHovering( const InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); const Geometry2D *projectionPlane = renderer->GetCurrentWorldGeometry2D(); mitk::Point2D pointProjectedOntoLine; int previousControlPoint = mitk::PlanarFigureInteractor::IsPositionOverFigure( positionEvent, planarFigure, planarFigureGeometry, projectionPlane, renderer->GetDisplayGeometry(), pointProjectedOntoLine ); bool isHovering = ( previousControlPoint != -1 ); if ( isHovering ) { return true; } else { if ( m_IsHovering ) { planarFigure->ResetPreviewContolPoint(); // Invoke end-hover event once the mouse is exiting the figure area m_IsHovering = false; planarFigure->InvokeEvent( EndHoverPlanarFigureEvent() ); // Set bool property to indicate that planar figure is no longer in "hovering" mode GetDataNode()->SetBoolProperty( "planarfigure.ishovering", false ); renderer->GetRenderingManager()->RequestUpdateAll(); } return false; } return false; } bool mitk::PlanarFigureInteractor::CheckControlPointHovering( const InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); const Geometry2D *projectionPlane = renderer->GetCurrentWorldGeometry2D(); int pointIndex = -1; pointIndex = mitk::PlanarFigureInteractor::IsPositionInsideMarker( positionEvent, planarFigure, planarFigureGeometry, projectionPlane, renderer->GetDisplayGeometry() ); if ( pointIndex >= 0 ) { return true; } else { return false; } return false; } bool mitk::PlanarFigureInteractor::CheckSelection( const InteractionEvent* interactionEvent ) { bool selected = false; GetDataNode()->GetBoolProperty("selected", selected); return selected; } bool mitk::PlanarFigureInteractor::SelectFigure( StateMachineAction*, InteractionEvent* interactionEvent ) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); planarFigure->InvokeEvent( SelectPlanarFigureEvent() ); return false; } bool mitk::PlanarFigureInteractor::SelectPoint( StateMachineAction*, InteractionEvent* interactionEvent ) { mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); const Geometry2D *projectionPlane = renderer->GetCurrentWorldGeometry2D(); int pointIndex = -1; pointIndex = mitk::PlanarFigureInteractor::IsPositionInsideMarker( positionEvent, planarFigure, planarFigureGeometry, projectionPlane, renderer->GetDisplayGeometry() ); if ( pointIndex >= 0 ) { // If mouse is above control point, mark it as selected planarFigure->SelectControlPoint( pointIndex ); } else { planarFigure->DeselectControlPoint(); } return false; } bool mitk::PlanarFigureInteractor::CheckPointValidity( const InteractionEvent* interactionEvent ) { // Check if the distance of the current point to the previously set point in display coordinates // is sufficient (if a previous point exists) // Extract display position const mitk::InteractionPositionEvent* positionEvent = dynamic_cast( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); m_LastPointWasValid = IsMousePositionAcceptableAsNewControlPoint( positionEvent, planarFigure ); return m_LastPointWasValid; } bool mitk::PlanarFigureInteractor::RemoveSelectedPoint(StateMachineAction*, InteractionEvent* interactionEvent) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); int selectedControlPoint = planarFigure->GetSelectedControlPoint(); planarFigure->RemoveControlPoint( selectedControlPoint ); // Re-evaluate features planarFigure->EvaluateFeatures(); planarFigure->Modified(); GetDataNode()->SetBoolProperty( "planarfigure.drawcontrolpoints", true ); planarFigure->InvokeEvent( EndInteractionPlanarFigureEvent() ); renderer->GetRenderingManager()->RequestUpdateAll(); HandleEvent( mitk::InternalEvent::New( renderer, this, "Dummy-Event" ), GetDataNode() ); return true; } bool mitk::PlanarFigureInteractor::RequestContextMenu(StateMachineAction*, InteractionEvent* interactionEvent) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); bool selected = false; GetDataNode()->GetBoolProperty("selected", selected); // no need to invoke this if the figure is already selected if ( !selected ) { planarFigure->InvokeEvent( SelectPlanarFigureEvent() ); } planarFigure->InvokeEvent( ContextMenuPlanarFigureEvent() ); return true; } bool mitk::PlanarFigureInteractor::CheckResetOnPointSelect( const InteractionEvent* interactionEvent ) { mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); // Invoke tmpEvent to notify listeners that interaction with this PF starts now planarFigure->InvokeEvent( StartInteractionPlanarFigureEvent() ); // Reset the PlanarFigure if required return planarFigure->ResetOnPointSelect(); } bool mitk::PlanarFigureInteractor::CheckFigureOnRenderingGeometry( const InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* posEvent = dynamic_cast(interactionEvent); if ( posEvent == NULL ) return false; mitk::Point3D worldPoint3D = posEvent->GetPositionInWorld(); mitk::PlanarFigure *planarFigure = dynamic_cast( GetDataNode()->GetData() ); mitk::Geometry2D *planarFigureGeometry2D = dynamic_cast< Geometry2D * >( planarFigure->GetGeometry( 0 ) ); double planeThickness = planarFigureGeometry2D->GetExtentInMM( 2 ); if ( planarFigureGeometry2D->Distance( worldPoint3D ) > planeThickness ) { // don't react, when interaction is too far away return false; } return true; } void mitk::PlanarFigureInteractor::SetPrecision( mitk::ScalarType precision ) { m_Precision = precision; } void mitk::PlanarFigureInteractor::SetMinimumPointDistance( ScalarType minimumDistance ) { m_MinimumPointDistance = minimumDistance; } bool mitk::PlanarFigureInteractor::TransformPositionEventToPoint2D( const InteractionPositionEvent *positionEvent, const Geometry2D *planarFigureGeometry, Point2D &point2D ) { mitk::Point3D worldPoint3D = positionEvent->GetPositionInWorld(); // TODO: proper handling of distance tolerance if ( planarFigureGeometry->Distance( worldPoint3D ) > 0.1 ) { return false; } // Project point onto plane of this PlanarFigure planarFigureGeometry->Map( worldPoint3D, point2D ); return true; } bool mitk::PlanarFigureInteractor::TransformObjectToDisplay( const mitk::Point2D &point2D, mitk::Point2D &displayPoint, const mitk::Geometry2D *objectGeometry, const mitk::Geometry2D *rendererGeometry, const mitk::DisplayGeometry *displayGeometry ) const { mitk::Point3D point3D; // Map circle point from local 2D geometry into 3D world space objectGeometry->Map( point2D, point3D ); // TODO: proper handling of distance tolerance if ( displayGeometry->Distance( point3D ) < 0.1 ) { // Project 3D world point onto display geometry rendererGeometry->Map( point3D, displayPoint ); displayGeometry->WorldToDisplay( displayPoint, displayPoint ); return true; } return false; } bool mitk::PlanarFigureInteractor::IsPointNearLine( const mitk::Point2D& point, const mitk::Point2D& startPoint, const mitk::Point2D& endPoint, mitk::Point2D& projectedPoint ) const { mitk::Vector2D n1 = endPoint - startPoint; n1.Normalize(); // Determine dot products between line vector and startpoint-point / endpoint-point vectors double l1 = n1 * (point - startPoint); double l2 = -n1 * (point - endPoint); // Determine projection of specified point onto line defined by start / end point mitk::Point2D crossPoint = startPoint + n1 * l1; projectedPoint = crossPoint; // Point is inside encompassing rectangle IF // - its distance to its projected point is small enough // - it is not further outside of the line than the defined tolerance if (((crossPoint.SquaredEuclideanDistanceTo(point) < 20.0) && (l1 > 0.0) && (l2 > 0.0)) || endPoint.SquaredEuclideanDistanceTo(point) < 20.0 || startPoint.SquaredEuclideanDistanceTo(point) < 20.0) { return true; } return false; } int mitk::PlanarFigureInteractor::IsPositionOverFigure( const InteractionPositionEvent *positionEvent, PlanarFigure *planarFigure, const Geometry2D *planarFigureGeometry, const Geometry2D *rendererGeometry, const DisplayGeometry *displayGeometry, Point2D& pointProjectedOntoLine ) const { mitk::Point2D displayPosition = positionEvent->GetPointerPositionOnScreen(); // Iterate over all polylines of planar figure, and check if // any one is close to the current display position typedef mitk::PlanarFigure::PolyLineType VertexContainerType; Point2D polyLinePoint; Point2D firstPolyLinePoint; Point2D previousPolyLinePoint; for ( unsigned short loop=0; loopGetPolyLinesSize(); ++loop ) { const VertexContainerType polyLine = planarFigure->GetPolyLine( loop ); bool firstPoint( true ); for ( VertexContainerType::const_iterator it = polyLine.begin(); it != polyLine.end(); ++it ) { // Get plane coordinates of this point of polyline (if possible) if ( !this->TransformObjectToDisplay( it->Point, polyLinePoint, planarFigureGeometry, rendererGeometry, displayGeometry ) ) { break; // Poly line invalid (not on current 2D plane) --> skip it } if ( firstPoint ) { firstPolyLinePoint = polyLinePoint; firstPoint = false; } else if ( this->IsPointNearLine( displayPosition, previousPolyLinePoint, polyLinePoint, pointProjectedOntoLine ) ) { // Point is close enough to line segment --> Return index of the segment return it->Index; } previousPolyLinePoint = polyLinePoint; } // For closed figures, also check last line segment if ( planarFigure->IsClosed() && this->IsPointNearLine( displayPosition, polyLinePoint, firstPolyLinePoint, pointProjectedOntoLine ) ) { return 0; // Return index of first control point } } return -1; } int mitk::PlanarFigureInteractor::IsPositionInsideMarker( const InteractionPositionEvent* positionEvent, const PlanarFigure *planarFigure, const Geometry2D *planarFigureGeometry, const Geometry2D *rendererGeometry, const DisplayGeometry *displayGeometry ) const { mitk::Point2D displayPosition = positionEvent->GetPointerPositionOnScreen(); // Iterate over all control points of planar figure, and check if // any one is close to the current display position mitk::Point2D displayControlPoint; int numberOfControlPoints = planarFigure->GetNumberOfControlPoints(); for ( int i=0; iTransformObjectToDisplay( planarFigure->GetControlPoint(i), displayControlPoint, planarFigureGeometry, rendererGeometry, displayGeometry ) ) { // TODO: variable size of markers if ( displayPosition.SquaredEuclideanDistanceTo( displayControlPoint ) < 20.0 ) { return i; } } } return -1; } void mitk::PlanarFigureInteractor::LogPrintPlanarFigureQuantities( const PlanarFigure *planarFigure ) { MITK_INFO << "PlanarFigure: " << planarFigure->GetNameOfClass(); for ( unsigned int i = 0; i < planarFigure->GetNumberOfFeatures(); ++i ) { MITK_INFO << "* " << planarFigure->GetFeatureName( i ) << ": " << planarFigure->GetQuantity( i ) << " " << planarFigure->GetFeatureUnit( i ); } } bool mitk::PlanarFigureInteractor::IsMousePositionAcceptableAsNewControlPoint( const mitk::InteractionPositionEvent* positionEvent, const PlanarFigure* planarFigure ) { assert(positionEvent && planarFigure); BaseRenderer* renderer = positionEvent->GetSender(); assert(renderer); // Get the timestep to support 3D+t int timeStep( renderer->GetTimeStep( planarFigure ) ); bool tooClose(false); const Geometry2D *renderingPlane = renderer->GetCurrentWorldGeometry2D(); mitk::Geometry2D *planarFigureGeometry = dynamic_cast< mitk::Geometry2D * >( planarFigure->GetGeometry( timeStep ) ); Point2D point2D, correctedPoint; // Get the point2D from the positionEvent if ( !this->TransformPositionEventToPoint2D( positionEvent, planarFigureGeometry, point2D ) ) { return false; } // apply the controlPoint constraints of the planarFigure to get the // coordinates that would actually be used. correctedPoint = const_cast( planarFigure )->ApplyControlPointConstraints( 0, point2D ); // map the 2D coordinates of the new point to world-coordinates // and transform those to display-coordinates mitk::Point3D newPoint3D; planarFigureGeometry->Map( correctedPoint, newPoint3D ); mitk::Point2D newDisplayPosition; renderingPlane->Map( newPoint3D, newDisplayPosition ); renderer->GetDisplayGeometry()->WorldToDisplay( newDisplayPosition, newDisplayPosition ); for( int i=0; i < (int)planarFigure->GetNumberOfControlPoints(); i++ ) { if ( i != planarFigure->GetSelectedControlPoint() ) { // Try to convert previous point to current display coordinates mitk::Point3D previousPoint3D; // map the 2D coordinates of the control-point to world-coordinates planarFigureGeometry->Map( planarFigure->GetControlPoint( i ), previousPoint3D ); if ( renderer->GetDisplayGeometry()->Distance( previousPoint3D ) < 0.1 ) // ugly, but assert makes this work { mitk::Point2D previousDisplayPosition; // transform the world-coordinates into display-coordinates renderingPlane->Map( previousPoint3D, previousDisplayPosition ); renderer->GetDisplayGeometry()->WorldToDisplay( previousDisplayPosition, previousDisplayPosition ); //Calculate the distance. We use display-coordinates here to make // the check independent of the zoom-level of the rendering scene. double a = newDisplayPosition[0] - previousDisplayPosition[0]; double b = newDisplayPosition[1] - previousDisplayPosition[1]; // If point is to close, do not set a new point tooClose = (a * a + b * b < m_MinimumPointDistance ); } if ( tooClose ) return false; // abort loop early } } return !tooClose; // default } void mitk::PlanarFigureInteractor::ConfigurationChanged() { mitk::PropertyList::Pointer properties = GetAttributes(); std::string precision = ""; if (properties->GetStringProperty("precision", precision)) { m_Precision = atof(precision.c_str()); } else { m_Precision = (ScalarType) 6.5; } std::string minPointDistance = ""; if (properties->GetStringProperty("minPointDistance", minPointDistance)) { m_MinimumPointDistance = atof(minPointDistance.c_str()); } else { m_MinimumPointDistance = (ScalarType) 25.0; } } diff --git a/Modules/Properties/mitkPropertiesActivator.cpp b/Modules/Properties/mitkPropertiesActivator.cpp index e579450d61..abf62d9a8b 100644 --- a/Modules/Properties/mitkPropertiesActivator.cpp +++ b/Modules/Properties/mitkPropertiesActivator.cpp @@ -1,387 +1,387 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPropertyAliases.h" #include "mitkPropertyDescriptions.h" #include "mitkPropertyExtension.h" #include "mitkPropertyExtensions.h" #include "mitkPropertyFilters.h" #include #include #include #include class AliasEquals { public: AliasEquals(const std::string& alias) : m_Alias(alias) { } bool operator()(const std::pair& element) { return element.second == m_Alias; } private: std::string m_Alias; }; class DeleteExtension { public: void operator()(const std::pair& element) { delete element.second; } }; namespace mitk { - class PropertiesActivator : public ModuleActivator + class PropertiesActivator : public us::ModuleActivator { public: - void Load(ModuleContext* context) + void Load(us::ModuleContext* context) { m_PropertyAliases = PropertyAliasesImpl::New(); context->RegisterService(m_PropertyAliases); m_PropertyDescriptions = PropertyDescriptionsImpl::New(); context->RegisterService(m_PropertyDescriptions); m_PropertyExtensions = PropertyExtensionsImpl::New(); context->RegisterService(m_PropertyExtensions); m_PropertyFilters = PropertyFiltersImpl::New(); context->RegisterService(m_PropertyFilters); } - void Unload(ModuleContext*) + void Unload(us::ModuleContext*) { } private: class PropertyAliasesImpl : public itk::LightObject, public PropertyAliases { public: mitkClassMacro(PropertyAliasesImpl, itk::LightObject); itkNewMacro(Self); bool AddAlias(const std::string& propertyName, const std::string& alias, bool overwrite); std::string GetAlias(const std::string& propertyName) const; std::string GetPropertyName(const std::string& alias) const; bool HasAlias(const std::string& propertyName) const; void RemoveAllAliases(); void RemoveAlias(const std::string& propertyName); private: std::map m_Aliases; }; class PropertyDescriptionsImpl : public itk::LightObject, public PropertyDescriptions { public: mitkClassMacro(PropertyDescriptionsImpl, itk::LightObject); itkNewMacro(Self); bool AddDescription(const std::string& propertyName, const std::string& description, bool overwrite); std::string GetDescription(const std::string& propertyName) const; bool HasDescription(const std::string& propertyName) const; void RemoveAllDescriptions(); void RemoveDescription(const std::string& propertyName); private: std::map m_Descriptions; }; class PropertyExtensionsImpl : public itk::LightObject, public PropertyExtensions { public: mitkClassMacro(PropertyExtensionsImpl, itk::LightObject); itkNewMacro(Self); bool AddExtension(const std::string& propertyName, PropertyExtension* extension, bool overwrite); PropertyExtension* GetExtension(const std::string& propertyName) const; bool HasExtension(const std::string& propertyName) const; void RemoveAllExtensions(); void RemoveExtension(const std::string& propertyName); private: std::map m_Extensions; }; class PropertyFiltersImpl : public itk::LightObject, public PropertyFilters { public: mitkClassMacro(PropertyFiltersImpl, itk::LightObject); itkNewMacro(Self); bool AddFilter(const PropertyFilter& filter, bool overwrite); bool AddFilter(const std::string& className, const PropertyFilter& filter, bool overwrite); std::map ApplyFilter(const std::map& propertyMap) const; std::map ApplyFilter(const std::string& className, const std::map& propertyMap) const; PropertyFilter GetFilter(const std::string& className) const; bool HasFilter(const std::string& className) const; void RemoveAllFilters(); void RemoveFilter(const std::string& className); private: std::map m_Filters; }; PropertyAliasesImpl::Pointer m_PropertyAliases; PropertyDescriptionsImpl::Pointer m_PropertyDescriptions; PropertyExtensionsImpl::Pointer m_PropertyExtensions; PropertyFiltersImpl::Pointer m_PropertyFilters; }; bool PropertiesActivator::PropertyAliasesImpl::AddAlias(const std::string& propertyName, const std::string& alias, bool overwrite) { if (alias.empty()) return false; std::pair::iterator, bool> ret = m_Aliases.insert(std::make_pair(propertyName, alias)); if (!ret.second && overwrite) { ret.first->second = alias; ret.second = true; } return ret.second; } std::string PropertiesActivator::PropertyAliasesImpl::GetAlias(const std::string& propertyName) const { if (!propertyName.empty()) { std::map::const_iterator iter = m_Aliases.find(propertyName); if (iter != m_Aliases.end()) return iter->second; } return ""; } std::string PropertiesActivator::PropertyAliasesImpl::GetPropertyName(const std::string& alias) const { if (!alias.empty()) { std::map::const_iterator iter = std::find_if(m_Aliases.begin(), m_Aliases.end(), AliasEquals(alias)); if (iter != m_Aliases.end()) return iter->first; } return ""; } bool PropertiesActivator::PropertyAliasesImpl::HasAlias(const std::string& propertyName) const { return !propertyName.empty() ? m_Aliases.find(propertyName) != m_Aliases.end() : false; } void PropertiesActivator::PropertyAliasesImpl::RemoveAlias(const std::string& propertyName) { if (!propertyName.empty()) m_Aliases.erase(propertyName); } void PropertiesActivator::PropertyAliasesImpl::RemoveAllAliases() { m_Aliases.clear(); } bool PropertiesActivator::PropertyDescriptionsImpl::AddDescription(const std::string& propertyName, const std::string& description, bool overwrite) { if (!propertyName.empty()) { std::pair::iterator, bool> ret = m_Descriptions.insert(std::make_pair(propertyName, description)); if (!ret.second && overwrite) { ret.first->second = description; ret.second = true; } return ret.second; } return false; } std::string PropertiesActivator::PropertyDescriptionsImpl::GetDescription(const std::string& propertyName) const { if (!propertyName.empty()) { std::map::const_iterator iter = m_Descriptions.find(propertyName); if (iter != m_Descriptions.end()) return iter->second; } return ""; } bool PropertiesActivator::PropertyDescriptionsImpl::HasDescription(const std::string& propertyName) const { return !propertyName.empty() ? m_Descriptions.find(propertyName) != m_Descriptions.end() : false; } void PropertiesActivator::PropertyDescriptionsImpl::RemoveAllDescriptions() { m_Descriptions.clear(); } void PropertiesActivator::PropertyDescriptionsImpl::RemoveDescription(const std::string& propertyName) { if (!propertyName.empty()) m_Descriptions.erase(propertyName); } bool PropertiesActivator::PropertyExtensionsImpl::AddExtension(const std::string& propertyName, PropertyExtension* extension, bool overwrite) { if (!propertyName.empty()) { std::pair::iterator, bool> ret = m_Extensions.insert(std::make_pair(propertyName, extension)); if (!ret.second && overwrite) { ret.first->second = extension; ret.second = true; } return ret.second; } return false; } PropertyExtension* PropertiesActivator::PropertyExtensionsImpl::GetExtension(const std::string& propertyName) const { if (!propertyName.empty()) { std::map::const_iterator iter = m_Extensions.find(propertyName); if (iter != m_Extensions.end()) return iter->second; } return NULL; } bool PropertiesActivator::PropertyExtensionsImpl::HasExtension(const std::string& propertyName) const { return !propertyName.empty() ? m_Extensions.find(propertyName) != m_Extensions.end() : false; } void PropertiesActivator::PropertyExtensionsImpl::RemoveAllExtensions() { std::for_each(m_Extensions.begin(), m_Extensions.end(), DeleteExtension()); m_Extensions.clear(); } void PropertiesActivator::PropertyExtensionsImpl::RemoveExtension(const std::string& propertyName) { if (!propertyName.empty()) { delete m_Extensions[propertyName]; m_Extensions.erase(propertyName); } } bool PropertiesActivator::PropertyFiltersImpl::AddFilter(const PropertyFilter& filter, bool overwrite) { return this->AddFilter("", filter, overwrite); } bool PropertiesActivator::PropertyFiltersImpl::AddFilter(const std::string& className, const PropertyFilter& filter, bool overwrite) { if (!filter.IsEmpty()) { std::pair::iterator, bool> ret = m_Filters.insert(std::make_pair(className, filter)); if (!ret.second && overwrite) { ret.first->second = filter; ret.second = true; } return ret.second; } return false; } std::map PropertiesActivator::PropertyFiltersImpl::ApplyFilter(const std::map& propertyMap) const { return this->ApplyFilter("", propertyMap); } std::map PropertiesActivator::PropertyFiltersImpl::ApplyFilter(const std::string& className, const std::map& propertyMap) const { std::map ret = propertyMap; PropertyFilter filter = this->GetFilter(""); if (!filter.IsEmpty()) ret = filter.Apply(ret); if (!className.empty()) { filter = this->GetFilter(className); if (!filter.IsEmpty()) ret = filter.Apply(ret); } return ret; } PropertyFilter PropertiesActivator::PropertyFiltersImpl::GetFilter(const std::string& className) const { std::map::const_iterator iter = m_Filters.find(className); if (iter != m_Filters.end()) return iter->second; return PropertyFilter(); } bool PropertiesActivator::PropertyFiltersImpl::HasFilter(const std::string& className) const { return m_Filters.find(className) != m_Filters.end(); } void PropertiesActivator::PropertyFiltersImpl::RemoveAllFilters() { m_Filters.clear(); } void PropertiesActivator::PropertyFiltersImpl::RemoveFilter(const std::string& className) { m_Filters.erase(className); } } US_EXPORT_MODULE_ACTIVATOR(Properties, mitk::PropertiesActivator) diff --git a/Modules/Qmitk/QmitkApplicationCursor.cpp b/Modules/Qmitk/QmitkApplicationCursor.cpp index 4a229cd029..953cd095f0 100644 --- a/Modules/Qmitk/QmitkApplicationCursor.cpp +++ b/Modules/Qmitk/QmitkApplicationCursor.cpp @@ -1,84 +1,78 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkApplicationCursor.h" #include #include #include #include -// us -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" - QmitkApplicationCursor::QmitkApplicationCursor() { mitk::ApplicationCursor::RegisterImplementation(this); } -void QmitkApplicationCursor::PushCursor(const mitk::ModuleResource resource, int hotspotX, int hotspotY) +void QmitkApplicationCursor::PushCursor(std::istream& cursorStream, int hotspotX, int hotspotY) { - if (resource.IsValid()) + if (cursorStream) { - mitk::ModuleResourceStream resourceStream(resource, std::ios::binary); - resourceStream.seekg(0, std::ios::end); - std::ios::pos_type length = resourceStream.tellg(); - resourceStream.seekg(0, std::ios::beg); + cursorStream.seekg(0, std::ios::end); + std::ios::pos_type length = cursorStream.tellg(); + cursorStream.seekg(0, std::ios::beg); char* data = new char[length]; - resourceStream.read(data, length); + cursorStream.read(data, length); QPixmap pixmap; pixmap.loadFromData(QByteArray::fromRawData(data, length)); QCursor cursor( pixmap, hotspotX, hotspotY ); // no test for validity in QPixmap(xpm)! QApplication::setOverrideCursor( cursor ); delete[] data; - } } void QmitkApplicationCursor::PushCursor(const char* XPM[], int hotspotX, int hotspotY) { QPixmap pixmap( XPM ); QCursor cursor( pixmap, hotspotX, hotspotY ); // no test for validity in QPixmap(xpm)! QApplication::setOverrideCursor( cursor ); } void QmitkApplicationCursor::PopCursor() { QApplication::restoreOverrideCursor(); } const mitk::Point2I QmitkApplicationCursor::GetCursorPosition() { mitk::Point2I mp; QPoint qp = QCursor::pos(); mp[0] = qp.x(); mp[1] = qp.y(); return mp; } void QmitkApplicationCursor::SetCursorPosition(const mitk::Point2I& p) { static bool selfCall = false; if (selfCall) return; // this is to avoid recursive calls selfCall = true; QCursor::setPos( p[0], p[1] ); selfCall = false; } diff --git a/Modules/Qmitk/QmitkApplicationCursor.h b/Modules/Qmitk/QmitkApplicationCursor.h index 8cdba027bc..8d19454448 100644 --- a/Modules/Qmitk/QmitkApplicationCursor.h +++ b/Modules/Qmitk/QmitkApplicationCursor.h @@ -1,53 +1,49 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITK_APPLICATION_CURSOR_H_INCLUDED #define QMITK_APPLICATION_CURSOR_H_INCLUDED #include #include "mitkApplicationCursor.h" -namespace mitk { -class ModuleResource; -} - /*! \ingroup QmitkModule \brief Qt specific implementation of ApplicationCursorImplementation This class very simply calls the QApplication's methods setOverrideCursor() and restoreOverrideCursor(). */ class QMITK_EXPORT QmitkApplicationCursor : public mitk::ApplicationCursorImplementation { public: // Will be instantiated automatically from QmitkApplicationCursor.cpp once QmitkApplicationCursor(); virtual void PushCursor(const char* XPM[], int hotspotX, int hotspotY); - virtual void PushCursor(const mitk::ModuleResource, int hotspotX, int hotspotY); + virtual void PushCursor(std::istream&, int hotspotX, int hotspotY); virtual void PopCursor(); virtual const mitk::Point2I GetCursorPosition(); virtual void SetCursorPosition(const mitk::Point2I&); protected: private: }; #endif diff --git a/Modules/Qmitk/QmitkServiceListWidget.cpp b/Modules/Qmitk/QmitkServiceListWidget.cpp index 18cb4a6206..591ff01965 100644 --- a/Modules/Qmitk/QmitkServiceListWidget.cpp +++ b/Modules/Qmitk/QmitkServiceListWidget.cpp @@ -1,196 +1,196 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define _USE_MATH_DEFINES #include // STL Headers #include //microservices #include -#include +#include #include #include const std::string QmitkServiceListWidget::VIEW_ID = "org.mitk.views.QmitkServiceListWidget"; QmitkServiceListWidget::QmitkServiceListWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f) { m_Controls = NULL; CreateQtPartControl(this); } QmitkServiceListWidget::~QmitkServiceListWidget() { m_Context->RemoveServiceListener(this, &QmitkServiceListWidget::OnServiceEvent); } //////////////////// INITIALIZATION ///////////////////// void QmitkServiceListWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkServiceListWidgetControls; m_Controls->setupUi(parent); this->CreateConnections(); } - m_Context = mitk::GetModuleContext(); + m_Context = us::GetModuleContext(); } void QmitkServiceListWidget::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_ServiceList, SIGNAL(currentItemChanged( QListWidgetItem *, QListWidgetItem *)), this, SLOT(OnServiceSelectionChanged()) ); } } void QmitkServiceListWidget::InitPrivate(const std::string& namingProperty, const std::string& filter) { if (filter.empty()) - m_Filter = "(" + mitk::ServiceConstants::OBJECTCLASS() + "=" + m_Interface + ")"; + m_Filter = "(" + us::ServiceConstants::OBJECTCLASS() + "=" + m_Interface + ")"; else m_Filter = filter; m_NamingProperty = namingProperty; m_Context->RemoveServiceListener(this, &QmitkServiceListWidget::OnServiceEvent); m_Context->AddServiceListener(this, &QmitkServiceListWidget::OnServiceEvent, m_Filter); // Empty ListWidget this->m_ListContent.clear(); m_Controls->m_ServiceList->clear(); // get Services - std::list services = this->GetAllRegisteredServices(); + std::vector services = this->GetAllRegisteredServices(); // Transfer them to the List - for(std::list::iterator it = services.begin(); it != services.end(); ++it) + for(std::vector::iterator it = services.begin(); it != services.end(); ++it) AddServiceToList(*it); } ///////////// Methods & Slots Handling Direct Interaction ///////////////// bool QmitkServiceListWidget::GetIsServiceSelected(){ return (this->m_Controls->m_ServiceList->currentItem() != 0); } void QmitkServiceListWidget::OnServiceSelectionChanged(){ - mitk::ServiceReference ref = this->GetServiceForListItem(this->m_Controls->m_ServiceList->currentItem()); + us::ServiceReferenceU ref = this->GetServiceForListItem(this->m_Controls->m_ServiceList->currentItem()); if (! ref){ - emit (ServiceSelectionChanged(mitk::ServiceReference())); + emit (ServiceSelectionChanged(us::ServiceReferenceU())); return; } emit (ServiceSelectionChanged(ref)); } -mitk::ServiceReference QmitkServiceListWidget::GetSelectedServiceReference(){ +us::ServiceReferenceU QmitkServiceListWidget::GetSelectedServiceReference(){ return this->GetServiceForListItem(this->m_Controls->m_ServiceList->currentItem()); } ///////////////// Methods & Slots Handling Logic ////////////////////////// -void QmitkServiceListWidget::OnServiceEvent(const mitk::ServiceEvent event){ +void QmitkServiceListWidget::OnServiceEvent(const us::ServiceEvent event){ //MITK_INFO << "ServiceEvent" << event.GetType(); switch (event.GetType()) { - case mitk::ServiceEvent::MODIFIED: + case us::ServiceEvent::MODIFIED: emit(ServiceModified(event.GetServiceReference())); RemoveServiceFromList(event.GetServiceReference()); AddServiceToList(event.GetServiceReference()); break; - case mitk::ServiceEvent::REGISTERED: + case us::ServiceEvent::REGISTERED: emit(ServiceRegistered(event.GetServiceReference())); AddServiceToList(event.GetServiceReference()); break; - case mitk::ServiceEvent::UNREGISTERING: + case us::ServiceEvent::UNREGISTERING: emit(ServiceUnregistering(event.GetServiceReference())); RemoveServiceFromList(event.GetServiceReference()); break; - case mitk::ServiceEvent::MODIFIED_ENDMATCH: + case us::ServiceEvent::MODIFIED_ENDMATCH: emit(ServiceModifiedEndMatch(event.GetServiceReference())); RemoveServiceFromList(event.GetServiceReference()); break; } } /////////////////////// HOUSEHOLDING CODE ///////////////////////////////// -QListWidgetItem* QmitkServiceListWidget::AddServiceToList(mitk::ServiceReference serviceRef){ +QListWidgetItem* QmitkServiceListWidget::AddServiceToList(const us::ServiceReferenceU& serviceRef){ QListWidgetItem *newItem = new QListWidgetItem; std::string caption; //TODO allow more complex formatting if (m_NamingProperty.empty()) caption = m_Interface; else { - mitk::Any prop = serviceRef.GetProperty(m_NamingProperty); + us::Any prop = serviceRef.GetProperty(m_NamingProperty); if (prop.Empty()) { MITK_WARN << "QmitkServiceListWidget tried to resolve property '" + m_NamingProperty + "' but failed. Resorting to interface name for display."; caption = m_Interface; } else caption = prop.ToString(); } newItem->setText(caption.c_str()); // Add new item to QListWidget m_Controls->m_ServiceList->addItem(newItem); m_Controls->m_ServiceList->sortItems(); // Construct link and add to internal List for reference QmitkServiceListWidget::ServiceListLink link; link.service = serviceRef; link.item = newItem; m_ListContent.push_back(link); return newItem; } -bool QmitkServiceListWidget::RemoveServiceFromList(mitk::ServiceReference serviceRef){ +bool QmitkServiceListWidget::RemoveServiceFromList(const us::ServiceReferenceU& serviceRef){ for(std::vector::iterator it = m_ListContent.begin(); it != m_ListContent.end(); ++it){ if ( serviceRef == it->service ) { int row = m_Controls->m_ServiceList->row(it->item); QListWidgetItem* oldItem = m_Controls->m_ServiceList->takeItem(row); delete oldItem; this->m_ListContent.erase(it); return true; } } return false; } -mitk::ServiceReference QmitkServiceListWidget::GetServiceForListItem(QListWidgetItem* item) +us::ServiceReferenceU QmitkServiceListWidget::GetServiceForListItem(QListWidgetItem* item) { for(std::vector::iterator it = m_ListContent.begin(); it != m_ListContent.end(); ++it) if (item == it->item) return it->service; // Return invalid ServiceReference (will evaluate to false in bool expressions) - return mitk::ServiceReference(); + return us::ServiceReferenceU(); } -std::list QmitkServiceListWidget::GetAllRegisteredServices(){ +std::vector QmitkServiceListWidget::GetAllRegisteredServices(){ //Get Service References return m_Context->GetServiceReferences(m_Interface, m_Filter); -} \ No newline at end of file +} diff --git a/Modules/Qmitk/QmitkServiceListWidget.h b/Modules/Qmitk/QmitkServiceListWidget.h index 9e05ed89d3..4d65da4242 100644 --- a/Modules/Qmitk/QmitkServiceListWidget.h +++ b/Modules/Qmitk/QmitkServiceListWidget.h @@ -1,247 +1,247 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QmitkServiceListWidget_H_INCLUDED #define _QmitkServiceListWidget_H_INCLUDED #include "QmitkExports.h" #include "ui_QmitkServiceListWidgetControls.h" #include //QT headers #include #include //Microservices #include "usServiceReference.h" #include "usModuleContext.h" #include "usServiceEvent.h" #include "usServiceInterface.h" /** * \ingroup QmitkModule * * \brief This widget provides abstraction for the handling of MicroServices. * * Place one in your Plugin and set it to look for a certain interface. * One can also specify a filter and / or a property to use for captioning of * the services. It also offers functionality to signal * ServiceEvents and to return the actual classes, so only a minimum of * interaction with the MicroserviceInterface is required. * To get started, just put it in your Plugin or Widget, call the Initialize * Method and optionally connect it's signals. * As QT limits templating possibilities, events only throw ServiceReferences. * You can manually dereference them using TranslateServiceReference() */ class QMITK_EXPORT QmitkServiceListWidget :public QWidget { //this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT private: - mitk::ModuleContext* m_Context; + us::ModuleContext* m_Context; /** \brief a filter to further narrow down the list of results*/ std::string m_Filter; /** \brief The name of the ServiceInterface that this class should list */ std::string m_Interface; /** \brief The name of the ServiceProperty that will be displayed in the list to represent the service */ std::string m_NamingProperty; public: static const std::string VIEW_ID; QmitkServiceListWidget(QWidget* p = 0, Qt::WindowFlags f1 = 0); virtual ~QmitkServiceListWidget(); /** \brief This method is part of the widget an needs not to be called separately. */ virtual void CreateQtPartControl(QWidget *parent); /** \brief This method is part of the widget an needs not to be called separately. (Creation of the connections of main and control widget.)*/ virtual void CreateConnections(); /** * \brief Will return true, if a service is currently selected and false otherwise. * * Call this before requesting service references to avoid invalid ServiceReferences. */ bool GetIsServiceSelected(); /** * \brief Returns the currently selected Service as a ServiceReference. * * If no Service is selected, the result will probably be a bad pointer. call GetIsServiceSelected() * beforehand to avoid this */ - mitk::ServiceReference GetSelectedServiceReference(); + us::ServiceReferenceU GetSelectedServiceReference(); /** * \brief Use this function to return the currently selected service as a class directly. * * Make sure you pass the appropriate type, or else this call will fail. * Usually, you will pass the class itself, not the SmartPointer, but the function returns a pointer. Example: * \verbatim mitk::USDevice::Pointer device = GetSelectedService(); \endverbatim * @return Returns the current selected device. Returns NULL if no device is selected. */ template T* GetSelectedService() { if (this->m_Controls->m_ServiceList->currentRow()==-1) return NULL; - mitk::ServiceReference ref = GetServiceForListItem( this->m_Controls->m_ServiceList->currentItem() ); - return ( m_Context->GetService(ref) ); + us::ServiceReferenceU ref = GetServiceForListItem( this->m_Controls->m_ServiceList->currentItem() ); + return ( m_Context->GetService(us::ServiceReference(ref)) ); } /** * \brief Initializes the Widget with essential parameters. * * The string filter is an LDAP parsable String, compare mitk::ModuleContext for examples on filtering. * Pass class T to tell the widget which class it should filter for - only services of this class will be listed. * NamingProperty is a property that will be used to caption the Items in the list. If no filter is supplied, all * matching interfaces are shown. If no namingProperty is supplied, the interfaceName will be used to caption Items in the list. * For example, this Initialization will filter for all USDevices that are set to active. The USDevice's model will be used to display it in the list: * \verbatim - std::string filter = "(&(" + mitk::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(IsActive=true))"; + std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(IsActive=true))"; m_Controls.m_ActiveVideoDevices->Initialize(mitk::USImageMetadata::PROP_DEV_MODEL ,filter); * \endverbatim */ template void Initialize(const std::string& namingProperty = static_cast< std::string >(""),const std::string& filter = static_cast< std::string >("")) { - std::string interfaceName ( us_service_interface_iid() ); + std::string interfaceName ( us_service_interface_iid() ); m_Interface = interfaceName; InitPrivate(namingProperty, filter); } /** * \brief Translates a serviceReference to a class of the given type. * * Use this to translate the signal's parameters. To adhere to the MicroService contract, * only ServiceReferences stemming from the same widget should be used as parameters for this method. * \verbatim mitk::USDevice::Pointer device = TranslateReference(myDeviceReference); \endverbatim */ template - T* TranslateReference(mitk::ServiceReference reference) + T* TranslateReference(const us::ServiceReferenceU& reference) { - return dynamic_cast ( m_Context->GetService(reference) ); + return m_Context->GetService(us::ServiceReference(reference)); } /** *\brief This Function listens to ServiceRegistry changes and updates the list of services accordingly. * * The user of this widget does not need to call this method, it is instead used to recieve events from the module registry. */ - void OnServiceEvent(const mitk::ServiceEvent event); + void OnServiceEvent(const us::ServiceEvent event); signals: /** *\brief Emitted when a new Service matching the filter is being registered. * * Be careful if you use a filter: * If a device does not match the filter when registering, but modifies it's properties later to match the filter, * then the first signal you will see this device in will be ServiceModified. */ - void ServiceRegistered(mitk::ServiceReference); + void ServiceRegistered(us::ServiceReferenceU); /** *\brief Emitted directly before a Service matching the filter is being unregistered. */ - void ServiceUnregistering(mitk::ServiceReference); + void ServiceUnregistering(us::ServiceReferenceU); /** *\brief Emitted when a Service matching the filter changes it's properties, or when a service that formerly not matched the filter * changed it's properties and now matches the filter. */ - void ServiceModified(mitk::ServiceReference); + void ServiceModified(us::ServiceReferenceU); /** *\brief Emitted when a Service matching the filter changes it's properties, * * and the new properties make it fall trough the filter. This effectively means that * the widget will not track the service anymore. Usually, the Service should still be useable though */ - void ServiceModifiedEndMatch(mitk::ServiceReference); + void ServiceModifiedEndMatch(us::ServiceReferenceU); /** *\brief Emitted if the user selects a Service from the list. * * If no service is selected, an invalid serviceReference is returned. The user can easily check for this. * if (serviceReference) will evaluate to false, if the reference is invalid and true if valid. */ - void ServiceSelectionChanged(mitk::ServiceReference); + void ServiceSelectionChanged(us::ServiceReferenceU); public slots: protected slots: /** \brief Called, when the selection in the list of Services changes. */ void OnServiceSelectionChanged(); protected: Ui::QmitkServiceListWidgetControls* m_Controls; ///< member holding the UI elements of this widget /** * \brief Internal structure used to link ServiceReferences to their QListWidgetItems */ struct ServiceListLink { - mitk::ServiceReference service; + us::ServiceReferenceU service; QListWidgetItem* item; }; /** * \brief Finishes initialization after Initialize has been called. * * This function assumes that m_Interface is set correctly (Which Initialize does). */ void InitPrivate(const std::string& namingProperty, const std::string& filter); /** * \brief Contains a list of currently active services and their entires in the list. This is wiped with every ServiceRegistryEvent. */ std::vector m_ListContent; /** * \brief Constructs a ListItem from the given service, displays it, and locally stores the service. */ - QListWidgetItem* AddServiceToList(mitk::ServiceReference serviceRef); + QListWidgetItem* AddServiceToList(const us::ServiceReferenceU& serviceRef); /** * \brief Removes the given service from the list and cleans up. Returns true if successful, false if service was not found. */ - bool RemoveServiceFromList(mitk::ServiceReference serviceRef); + bool RemoveServiceFromList(const us::ServiceReferenceU& serviceRef); /** * \brief Returns the serviceReference corresponding to the given ListEntry or an invalid one if none was found (will evaluate to false in bool expressions). */ - mitk::ServiceReference GetServiceForListItem(QListWidgetItem* item); + us::ServiceReferenceU GetServiceForListItem(QListWidgetItem* item); /** * \brief Returns a list of ServiceReferences matching the filter criteria by querying the service registry. */ - std::list GetAllRegisteredServices(); + std::vector GetAllRegisteredServices(); }; #endif // _QmitkServiceListWidget_H_INCLUDED diff --git a/Modules/QmitkExt/QmitkModuleTableModel.cpp b/Modules/QmitkExt/QmitkModuleTableModel.cpp index 9496db0d3a..3ca717b6b4 100644 --- a/Modules/QmitkExt/QmitkModuleTableModel.cpp +++ b/Modules/QmitkExt/QmitkModuleTableModel.cpp @@ -1,168 +1,154 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkModuleTableModel.h" -#include -#include -#include +#include +#include +#include #include class QmitkModuleTableModelPrivate { public: - QmitkModuleTableModelPrivate(QmitkModuleTableModel* q, mitk::ModuleContext* mc) + QmitkModuleTableModelPrivate(QmitkModuleTableModel* q, us::ModuleContext* mc) : q(q), context(mc) { - std::vector m; + std::vector m; context->GetModules(m); - for (std::vector::const_iterator it = m.begin(); + for (std::vector::const_iterator it = m.begin(); it != m.end(); ++it) { modules[(*it)->GetModuleId()] = *it; } context->AddModuleListener(this, &QmitkModuleTableModelPrivate::ModuleChanged); } ~QmitkModuleTableModelPrivate() { context->RemoveModuleListener(this, &QmitkModuleTableModelPrivate::ModuleChanged); } - void ModuleChanged(mitk::ModuleEvent event) + void ModuleChanged(us::ModuleEvent event) { q->insertModule(event.GetModule()); } QmitkModuleTableModel* q; - mitk::ModuleContext* context; - QMap modules; + us::ModuleContext* context; + QMap modules; }; -QmitkModuleTableModel::QmitkModuleTableModel(QObject* parent, mitk::ModuleContext* mc) +QmitkModuleTableModel::QmitkModuleTableModel(QObject* parent, us::ModuleContext* mc) : QAbstractTableModel(parent), - d(new QmitkModuleTableModelPrivate(this, mc ? mc : mitk::GetModuleContext())) + d(new QmitkModuleTableModelPrivate(this, mc ? mc : us::GetModuleContext())) { } QmitkModuleTableModel::~QmitkModuleTableModel() { delete d; } int QmitkModuleTableModel::rowCount(const QModelIndex& parent) const { if (parent.isValid()) return 0; return d->modules.size(); } int QmitkModuleTableModel::columnCount(const QModelIndex& parent) const { if (parent.isValid()) return 0; - return 5; + return 4; } QVariant QmitkModuleTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole) { - mitk::Module* module = d->modules[index.row()+1]; + us::Module* module = d->modules[index.row()+1]; switch(index.column()) { case 0: return QVariant::fromValue(static_cast(module->GetModuleId())); case 1: return QString::fromStdString(module->GetName()); case 2: return QString::fromStdString(module->GetVersion().ToString()); - case 3: - { - QString deps = QString::fromStdString(module->GetProperty(mitk::Module::PROP_MODULE_DEPENDS())); - QString libDeps = QString::fromStdString(module->GetProperty(mitk::Module::PROP_LIB_DEPENDS())); - if (!libDeps.isEmpty()) - { - if (!deps.isEmpty()) deps.append(", "); - deps.append(libDeps); - } - return deps; - } - case 4: return QString::fromStdString(module->GetLocation()); + case 3: return QString::fromStdString(module->GetLocation()); } } else if (role == Qt::ForegroundRole) { - mitk::Module* module = d->modules[index.row()+1]; + us::Module* module = d->modules[index.row()+1]; if (!module->IsLoaded()) { return QBrush(Qt::gray); } } else if (role == Qt::ToolTipRole) { - mitk::Module* module = d->modules[index.row()+1]; + us::Module* module = d->modules[index.row()+1]; QString id = QString::number(module->GetModuleId()); QString name = QString::fromStdString(module->GetName()); QString version = QString::fromStdString(module->GetVersion().ToString()); - QString moduleDepends = QString::fromStdString(module->GetProperty(mitk::Module::PROP_MODULE_DEPENDS())); - QString libDepends = QString::fromStdString(module->GetProperty(mitk::Module::PROP_LIB_DEPENDS())); QString location = QString::fromStdString(module->GetLocation()); QString state = module->IsLoaded() ? "Loaded" : "Unloaded"; - QString tooltip = "Id: %1\nName: %2\nVersion: %3\nModule Dependencies: %4\nLibrary Dependencies: %6\nLocation: %7\nState: %9"; + QString tooltip = "Id: %1\nName: %2\nVersion: %3\nLocation: %7\nState: %9"; - return tooltip.arg(id, name, version, moduleDepends, libDepends, location, state); + return tooltip.arg(id, name, version, location, state); } return QVariant(); } QVariant QmitkModuleTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation != Qt::Horizontal || role != Qt::DisplayRole) return QVariant(); switch (section) { case 0: return "Id"; case 1: return "Name"; case 2: return "Version"; - case 3: return "Depends"; - case 4: return "Location"; + case 3: return "Location"; } return QVariant(); } -void QmitkModuleTableModel::insertModule(mitk::Module* module) +void QmitkModuleTableModel::insertModule(us::Module* module) { long id = module->GetModuleId(); if (d->modules.contains(id)) { d->modules[id] = module; emit dataChanged(createIndex(id-1, 0), createIndex(id-1, columnCount())); return; } else { beginInsertRows(QModelIndex(), id-1, id-1); d->modules[id] = module; endInsertRows(); } } diff --git a/Modules/QmitkExt/QmitkModuleTableModel.h b/Modules/QmitkExt/QmitkModuleTableModel.h index da32636d96..950debb206 100644 --- a/Modules/QmitkExt/QmitkModuleTableModel.h +++ b/Modules/QmitkExt/QmitkModuleTableModel.h @@ -1,59 +1,59 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKMODULETABLEMODEL_H #define QMITKMODULETABLEMODEL_H #include #include #include -namespace mitk { +namespace us { class ModuleContext; class Module; } class QmitkModuleTableModelPrivate; class QmitkExt_EXPORT QmitkModuleTableModel : public QAbstractTableModel { public: - QmitkModuleTableModel(QObject* parent = 0, mitk::ModuleContext* mc = 0); + QmitkModuleTableModel(QObject* parent = 0, us::ModuleContext* mc = 0); ~QmitkModuleTableModel(); protected: int rowCount(const QModelIndex& parent = QModelIndex()) const; int columnCount(const QModelIndex& parent = QModelIndex()) const; QVariant data(const QModelIndex& index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; private: friend class QmitkModuleTableModelPrivate; - void insertModule(mitk::Module* module); + void insertModule(us::Module* module); QmitkModuleTableModelPrivate* const d; }; #endif // QMITKMODULETABLEMODEL_H diff --git a/Modules/RigidRegistration/mitkRigidRegistrationPreset.cpp b/Modules/RigidRegistration/mitkRigidRegistrationPreset.cpp index a20acad531..e38130c85c 100644 --- a/Modules/RigidRegistration/mitkRigidRegistrationPreset.cpp +++ b/Modules/RigidRegistration/mitkRigidRegistrationPreset.cpp @@ -1,1159 +1,1159 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkRigidRegistrationPreset.h" #include "mitkMetricParameters.h" #include "mitkOptimizerParameters.h" #include "mitkTransformParameters.h" -#include "mitkGetModuleContext.h" -#include "mitkModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" +#include "usGetModuleContext.h" +#include "usModuleContext.h" +#include "usModule.h" +#include "usModuleResource.h" +#include "usModuleResourceStream.h" namespace mitk { RigidRegistrationPreset::RigidRegistrationPreset() { m_Name = ""; m_XmlFileName = "mitkRigidRegistrationPresets.xml"; } RigidRegistrationPreset::~RigidRegistrationPreset() { } bool RigidRegistrationPreset::LoadPreset() { return LoadPreset("mitkRigidRegistrationPresets.xml"); } bool RigidRegistrationPreset::LoadPreset(std::string fileName) { if ( fileName.empty() ) return false; - ModuleResource presetResource = GetModuleContext()->GetModule()->GetResource(fileName); + us::ModuleResource presetResource = us::GetModuleContext()->GetModule()->GetResource(fileName); if (!presetResource) return false; - ModuleResourceStream presetStream(presetResource); + us::ModuleResourceStream presetStream(presetResource); vtkXMLParser::SetStream(&presetStream); if ( !vtkXMLParser::Parse() ) { #ifdef INTERDEBUG MITK_INFO<<"RigidRegistrationPreset::LoadPreset xml file cannot parse!"< transformValues; transformValues.SetSize(25); transformValues.fill(0); std::string transform = ReadXMLStringAttribut( "TRANSFORM", atts ); double trans = atof(transform.c_str()); transformValues[0] = trans; transformValues = this->loadTransformValues(transformValues, trans, atts); m_TransformValues[m_Name] = transformValues; } else if (elementNameString == "metric") { itk::Array metricValues; metricValues.SetSize(25); metricValues.fill(0); std::string metric = ReadXMLStringAttribut( "METRIC", atts ); double met = atof(metric.c_str()); metricValues[0] = met; metricValues = this->loadMetricValues(metricValues, met, atts); m_MetricValues[m_Name] = metricValues; } else if (elementNameString == "optimizer") { itk::Array optimizerValues; optimizerValues.SetSize(25); optimizerValues.fill(0); std::string optimizer = ReadXMLStringAttribut( "OPTIMIZER", atts ); double opt = atof(optimizer.c_str()); optimizerValues[0] = opt; optimizerValues = this->loadOptimizerValues(optimizerValues, opt, atts); m_OptimizerValues[m_Name] = optimizerValues; } else if (elementNameString == "interpolator") { itk::Array interpolatorValues; interpolatorValues.SetSize(25); interpolatorValues.fill(0); std::string interpolator = ReadXMLStringAttribut( "INTERPOLATOR", atts ); double inter = atof(interpolator.c_str()); interpolatorValues[0] = inter; interpolatorValues = this->loadInterpolatorValues(interpolatorValues/*, inter, atts*/); m_InterpolatorValues[m_Name] = interpolatorValues; } } std::string RigidRegistrationPreset::ReadXMLStringAttribut( std::string name, const char** atts ) { if(atts) { const char** attsIter = atts; while(*attsIter) { if ( name == *attsIter ) { attsIter++; return *attsIter; } attsIter++; attsIter++; } } return std::string(); } itk::Array RigidRegistrationPreset::getTransformValues(std::string name) { return m_TransformValues[name]; } itk::Array RigidRegistrationPreset::getMetricValues(std::string name) { return m_MetricValues[name]; } itk::Array RigidRegistrationPreset::getOptimizerValues(std::string name) { return m_OptimizerValues[name]; } itk::Array RigidRegistrationPreset::getInterpolatorValues(std::string name) { return m_InterpolatorValues[name]; } std::map >& RigidRegistrationPreset::getTransformValuesPresets() { return m_TransformValues; } std::map >& RigidRegistrationPreset::getMetricValuesPresets() { return m_MetricValues; } std::map >& RigidRegistrationPreset::getOptimizerValuesPresets() { return m_OptimizerValues; } std::map >& RigidRegistrationPreset::getInterpolatorValuesPresets() { return m_InterpolatorValues; } bool RigidRegistrationPreset::save() { //XMLWriter writer(m_XmlFileName.c_str()); //return saveXML(writer); return false; } //bool RigidRegistrationPreset::saveXML(mitk::XMLWriter& xmlWriter) //{ // xmlWriter.BeginNode("mitkRigidRegistrationPresets"); // for( std::map >::iterator iter = m_TransformValues.begin(); iter != m_TransformValues.end(); iter++ ) { // std::string item = ((*iter).first.c_str()); // xmlWriter.BeginNode("preset"); // xmlWriter.WriteProperty("NAME", item); // xmlWriter.BeginNode("transform"); // this->saveTransformValues(xmlWriter, item); // xmlWriter.EndNode(); // xmlWriter.BeginNode("metric"); // this->saveMetricValues(xmlWriter, item); // xmlWriter.EndNode(); // xmlWriter.BeginNode("optimizer"); // this->saveOptimizerValues(xmlWriter, item); // xmlWriter.EndNode(); // xmlWriter.BeginNode("interpolator"); // this->saveInterpolatorValues(xmlWriter, item); // xmlWriter.EndNode(); // xmlWriter.EndNode(); // } // xmlWriter.EndNode(); // return true; //} bool RigidRegistrationPreset::newPresets(std::map > newTransformValues, std::map > newMetricValues, std::map > newOptimizerValues, std::map > newInterpolatorValues, std::string fileName) { if ( !fileName.empty() ) { m_XmlFileName = fileName; } m_TransformValues = newTransformValues; m_MetricValues = newMetricValues; m_OptimizerValues = newOptimizerValues; m_InterpolatorValues = newInterpolatorValues; return save(); } //void RigidRegistrationPreset::saveTransformValues(mitk::XMLWriter& xmlWriter, std::string item) //{ // itk::Array transformValues = m_TransformValues[item]; // double transform = transformValues[0]; // xmlWriter.WriteProperty("TRANSFORM", transformValues[0]); // if (transform == mitk::TransformParameters::TRANSLATIONTRANSFORM || transform == mitk::TransformParameters::SCALETRANSFORM || // transform == mitk::TransformParameters::SCALELOGARITHMICTRANSFORM || transform == mitk::TransformParameters::VERSORTRANSFORM || // transform == mitk::TransformParameters::RIGID2DTRANSFORM || transform == mitk::TransformParameters::EULER2DTRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // } // else if (transform == mitk::TransformParameters::AFFINETRANSFORM || transform == mitk::TransformParameters::FIXEDCENTEROFROTATIONAFFINETRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // xmlWriter.WriteProperty("SCALE4", transformValues[5]); // xmlWriter.WriteProperty("SCALE5", transformValues[6]); // xmlWriter.WriteProperty("SCALE6", transformValues[7]); // xmlWriter.WriteProperty("SCALE7", transformValues[8]); // xmlWriter.WriteProperty("SCALE8", transformValues[9]); // xmlWriter.WriteProperty("SCALE9", transformValues[10]); // xmlWriter.WriteProperty("SCALE10", transformValues[11]); // xmlWriter.WriteProperty("SCALE11", transformValues[12]); // xmlWriter.WriteProperty("SCALE12", transformValues[13]); // /* xmlWriter.WriteProperty("SCALE13", transformValues[14]); // xmlWriter.WriteProperty("SCALE14", transformValues[15]); // xmlWriter.WriteProperty("SCALE15", transformValues[16]); // xmlWriter.WriteProperty("SCALE16", transformValues[17]);*/ // xmlWriter.WriteProperty("USEINITIALIZER", transformValues[14]); // xmlWriter.WriteProperty("USEMOMENTS", transformValues[15]); // } // else if (transform == mitk::TransformParameters::RIGID3DTRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // xmlWriter.WriteProperty("SCALE4", transformValues[5]); // xmlWriter.WriteProperty("SCALE5", transformValues[6]); // xmlWriter.WriteProperty("SCALE6", transformValues[7]); // xmlWriter.WriteProperty("SCALE7", transformValues[8]); // xmlWriter.WriteProperty("SCALE8", transformValues[9]); // xmlWriter.WriteProperty("SCALE9", transformValues[10]); // xmlWriter.WriteProperty("SCALE10", transformValues[11]); // xmlWriter.WriteProperty("SCALE11", transformValues[12]); // xmlWriter.WriteProperty("SCALE12", transformValues[13]); // xmlWriter.WriteProperty("USEINITIALIZER", transformValues[14]); // xmlWriter.WriteProperty("USEMOMENTS", transformValues[15]); // } // else if (transform == mitk::TransformParameters::EULER3DTRANSFORM || transform == mitk::TransformParameters::CENTEREDEULER3DTRANSFORM // || transform == mitk::TransformParameters::VERSORRIGID3DTRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // xmlWriter.WriteProperty("SCALE4", transformValues[5]); // xmlWriter.WriteProperty("SCALE5", transformValues[6]); // xmlWriter.WriteProperty("SCALE6", transformValues[7]); // xmlWriter.WriteProperty("USEINITIALIZER", transformValues[8]); // xmlWriter.WriteProperty("USEMOMENTS", transformValues[9]); // } // else if (transform == mitk::TransformParameters::QUATERNIONRIGIDTRANSFORM || transform == mitk::TransformParameters::SIMILARITY3DTRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // xmlWriter.WriteProperty("SCALE4", transformValues[5]); // xmlWriter.WriteProperty("SCALE5", transformValues[6]); // xmlWriter.WriteProperty("SCALE6", transformValues[7]); // xmlWriter.WriteProperty("SCALE7", transformValues[8]); // xmlWriter.WriteProperty("USEINITIALIZER", transformValues[9]); // xmlWriter.WriteProperty("USEMOMENTS", transformValues[10]); // } // else if (transform == mitk::TransformParameters::SCALESKEWVERSOR3DTRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // xmlWriter.WriteProperty("SCALE4", transformValues[5]); // xmlWriter.WriteProperty("SCALE5", transformValues[6]); // xmlWriter.WriteProperty("SCALE6", transformValues[7]); // xmlWriter.WriteProperty("SCALE7", transformValues[8]); // xmlWriter.WriteProperty("SCALE8", transformValues[9]); // xmlWriter.WriteProperty("SCALE9", transformValues[10]); // xmlWriter.WriteProperty("SCALE10", transformValues[11]); // xmlWriter.WriteProperty("SCALE11", transformValues[12]); // xmlWriter.WriteProperty("SCALE12", transformValues[13]); // xmlWriter.WriteProperty("SCALE13", transformValues[14]); // xmlWriter.WriteProperty("SCALE14", transformValues[15]); // xmlWriter.WriteProperty("SCALE15", transformValues[16]); // xmlWriter.WriteProperty("USEINITIALIZER", transformValues[17]); // xmlWriter.WriteProperty("USEMOMENTS", transformValues[18]); // } // else if (transform == mitk::TransformParameters::CENTEREDRIGID2DTRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // xmlWriter.WriteProperty("SCALE4", transformValues[5]); // xmlWriter.WriteProperty("SCALE5", transformValues[6]); // xmlWriter.WriteProperty("ANGLE", transformValues[7]); // xmlWriter.WriteProperty("USEINITIALIZER", transformValues[8]); // xmlWriter.WriteProperty("USEMOMENTS", transformValues[9]); // } // else if (transform == mitk::TransformParameters::SIMILARITY2DTRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // xmlWriter.WriteProperty("SCALE4", transformValues[5]); // xmlWriter.WriteProperty("SCALE", transformValues[6]); // xmlWriter.WriteProperty("ANGLE", transformValues[7]); // xmlWriter.WriteProperty("USEINITIALIZER", transformValues[8]); // xmlWriter.WriteProperty("USEMOMENTS", transformValues[9]); // } // else if (transform == mitk::TransformParameters::CENTEREDSIMILARITY2DTRANSFORM) // { // xmlWriter.WriteProperty("USESCALES", transformValues[1]); // xmlWriter.WriteProperty("SCALE1", transformValues[2]); // xmlWriter.WriteProperty("SCALE2", transformValues[3]); // xmlWriter.WriteProperty("SCALE3", transformValues[4]); // xmlWriter.WriteProperty("SCALE4", transformValues[5]); // xmlWriter.WriteProperty("SCALE5", transformValues[6]); // xmlWriter.WriteProperty("SCALE6", transformValues[7]); // xmlWriter.WriteProperty("SCALE", transformValues[8]); // xmlWriter.WriteProperty("ANGLE", transformValues[9]); // xmlWriter.WriteProperty("USEINITIALIZER", transformValues[10]); // xmlWriter.WriteProperty("USEMOMENTS", transformValues[11]); // } //} //void RigidRegistrationPreset::saveMetricValues(mitk::XMLWriter& xmlWriter, std::string item) //{ // itk::Array metricValues = m_MetricValues[item]; // double metric = metricValues[0]; // xmlWriter.WriteProperty("METRIC", metricValues[0]); // xmlWriter.WriteProperty("COMPUTEGRADIENT", metricValues[1]); // if (metric == mitk::MetricParameters::MEANSQUARESIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::NORMALIZEDCORRELATIONIMAGETOIMAGEMETRIC // || metric == mitk::MetricParameters::GRADIENTDIFFERENCEIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::MATCHCARDINALITYIMAGETOIMAGEMETRIC // || metric == mitk::MetricParameters::KAPPASTATISTICIMAGETOIMAGEMETRIC) // { // } // else if (metric == mitk::MetricParameters::KULLBACKLEIBLERCOMPAREHISTOGRAMIMAGETOIMAGEMETRIC // || metric == mitk::MetricParameters::CORRELATIONCOEFFICIENTHISTOGRAMIMAGETOIMAGEMETRIC // || metric == mitk::MetricParameters::MEANSQUARESHISTOGRAMIMAGETOIMAGEMETRIC // || metric == mitk::MetricParameters::MUTUALINFORMATIONHISTOGRAMIMAGETOIMAGEMETRIC // || metric == mitk::MetricParameters::NORMALIZEDMUTUALINFORMATIONHISTOGRAMIMAGETOIMAGEMETRIC) // { // xmlWriter.WriteProperty("HISTOGRAMBINS", metricValues[2]); // } // else if (metric == mitk::MetricParameters::MATTESMUTUALINFORMATIONIMAGETOIMAGEMETRIC) // { // xmlWriter.WriteProperty("USESAMPLING", metricValues[2]); // xmlWriter.WriteProperty("SPATIALSAMPLES", metricValues[3]); // xmlWriter.WriteProperty("HISTOGRAMBINS", metricValues[4]); // } // else if (metric == mitk::MetricParameters::MEANRECIPROCALSQUAREDIFFERENCEIMAGETOIMAGEMETRIC) // { // xmlWriter.WriteProperty("LAMBDA", metricValues[2]); // } // else if (metric == mitk::MetricParameters::MUTUALINFORMATIONIMAGETOIMAGEMETRIC) // { // xmlWriter.WriteProperty("SPATIALSAMPLES", metricValues[2]); // xmlWriter.WriteProperty("FIXEDSTANDARDDEVIATION", metricValues[3]); // xmlWriter.WriteProperty("MOVINGSTANDARDDEVIATION", metricValues[4]); // xmlWriter.WriteProperty("USENORMALIZERANDSMOOTHER", metricValues[5]); // xmlWriter.WriteProperty("FIXEDSMOOTHERVARIANCE", metricValues[6]); // xmlWriter.WriteProperty("MOVINGSMOOTHERVARIANCE", metricValues[7]); // } //} //void RigidRegistrationPreset::saveOptimizerValues(mitk::XMLWriter& xmlWriter, std::string item) //{ // itk::Array optimizerValues = m_OptimizerValues[item]; // double optimizer = optimizerValues[0]; // xmlWriter.WriteProperty("OPTIMIZER", optimizerValues[0]); // xmlWriter.WriteProperty("MAXIMIZE", optimizerValues[1]); // if (optimizer == mitk::OptimizerParameters::EXHAUSTIVEOPTIMIZER) // { // xmlWriter.WriteProperty("STEPLENGTH", optimizerValues[2]); // xmlWriter.WriteProperty("NUMBEROFSTEPS", optimizerValues[3]); // } // else if (optimizer == mitk::OptimizerParameters::GRADIENTDESCENTOPTIMIZER // || optimizer == mitk::OptimizerParameters::QUATERNIONRIGIDTRANSFORMGRADIENTDESCENTOPTIMIZER) // { // xmlWriter.WriteProperty("LEARNINGRATE", optimizerValues[2]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[3]); // } // else if (optimizer == mitk::OptimizerParameters::LBFGSBOPTIMIZER) // { // } // else if (optimizer == mitk::OptimizerParameters::ONEPLUSONEEVOLUTIONARYOPTIMIZER) // { // xmlWriter.WriteProperty("SHRINKFACTOR", optimizerValues[2]); // xmlWriter.WriteProperty("GROWTHFACTOR", optimizerValues[3]); // xmlWriter.WriteProperty("EPSILON", optimizerValues[4]); // xmlWriter.WriteProperty("INITIALRADIUS", optimizerValues[5]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[6]); // } // else if (optimizer == mitk::OptimizerParameters::POWELLOPTIMIZER) // { // xmlWriter.WriteProperty("STEPLENGTH", optimizerValues[2]); // xmlWriter.WriteProperty("STEPTOLERANCE", optimizerValues[3]); // xmlWriter.WriteProperty("VALUETOLERANCE", optimizerValues[4]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[5]); // } // else if (optimizer == mitk::OptimizerParameters::FRPROPTIMIZER) // { // xmlWriter.WriteProperty("USEFLETCHREEVES", optimizerValues[2]); // xmlWriter.WriteProperty("STEPLENGTH", optimizerValues[3]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[4]); // } // else if (optimizer == mitk::OptimizerParameters::REGULARSTEPGRADIENTDESCENTOPTIMIZER) // { // xmlWriter.WriteProperty("GRADIENTMAGNITUDETOLERANCE", optimizerValues[2]); // xmlWriter.WriteProperty("MINSTEPLENGTH", optimizerValues[3]); // xmlWriter.WriteProperty("MAXSTEPLENGTH", optimizerValues[4]); // xmlWriter.WriteProperty("RELAXATIONFACTOR", optimizerValues[5]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[6]); // } // else if (optimizer == mitk::OptimizerParameters::VERSORTRANSFORMOPTIMIZER || optimizer == mitk::OptimizerParameters::VERSORRIGID3DTRANSFORMOPTIMIZER) // { // xmlWriter.WriteProperty("GRADIENTMAGNITUDETOLERANCE", optimizerValues[2]); // xmlWriter.WriteProperty("MINSTEPLENGTH", optimizerValues[3]); // xmlWriter.WriteProperty("MAXSTEPLENGTH", optimizerValues[4]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[5]); // } // else if (optimizer == mitk::OptimizerParameters::AMOEBAOPTIMIZER) // { // xmlWriter.WriteProperty("SIMPLEXDELTA1", optimizerValues[2]); // xmlWriter.WriteProperty("SIMPLEXDELTA2", optimizerValues[3]); // xmlWriter.WriteProperty("SIMPLEXDELTA3", optimizerValues[4]); // xmlWriter.WriteProperty("SIMPLEXDELTA4", optimizerValues[5]); // xmlWriter.WriteProperty("SIMPLEXDELTA5", optimizerValues[6]); // xmlWriter.WriteProperty("SIMPLEXDELTA6", optimizerValues[7]); // xmlWriter.WriteProperty("SIMPLEXDELTA7", optimizerValues[8]); // xmlWriter.WriteProperty("SIMPLEXDELTA8", optimizerValues[9]); // xmlWriter.WriteProperty("SIMPLEXDELTA9", optimizerValues[10]); // xmlWriter.WriteProperty("SIMPLEXDELTA10", optimizerValues[11]); // xmlWriter.WriteProperty("SIMPLEXDELTA11", optimizerValues[12]); // xmlWriter.WriteProperty("SIMPLEXDELTA12", optimizerValues[13]); // xmlWriter.WriteProperty("SIMPLEXDELTA13", optimizerValues[14]); // xmlWriter.WriteProperty("SIMPLEXDELTA14", optimizerValues[15]); // xmlWriter.WriteProperty("SIMPLEXDELTA15", optimizerValues[16]); // xmlWriter.WriteProperty("SIMPLEXDELTA16", optimizerValues[17]); // xmlWriter.WriteProperty("PARAMETERSCONVERGENCETOLERANCE", optimizerValues[18]); // xmlWriter.WriteProperty("FUNCTIONCONVERGENCETOLERANCE", optimizerValues[19]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[20]); // } // else if (optimizer == mitk::OptimizerParameters::CONJUGATEGRADIENTOPTIMIZER) // { // } // else if (optimizer == mitk::OptimizerParameters::LBFGSOPTIMIZER) // { // xmlWriter.WriteProperty("GRADIENTCONVERGENCETOLERANCE", optimizerValues[2]); // xmlWriter.WriteProperty("LINESEARCHACCURACY", optimizerValues[3]); // xmlWriter.WriteProperty("DEFAULTSTEPLENGTH", optimizerValues[4]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[5]); // xmlWriter.WriteProperty("USETRACE", optimizerValues[6]); // } // else if (optimizer == mitk::OptimizerParameters::SPSAOPTIMIZER) // { // xmlWriter.WriteProperty("a", optimizerValues[2]); // xmlWriter.WriteProperty("A", optimizerValues[3]); // xmlWriter.WriteProperty("ALPHA", optimizerValues[4]); // xmlWriter.WriteProperty("c", optimizerValues[5]); // xmlWriter.WriteProperty("GAMMA", optimizerValues[6]); // xmlWriter.WriteProperty("TOLERANCE", optimizerValues[7]); // xmlWriter.WriteProperty("STATEOFCONVERGENCEDECAYRATE", optimizerValues[8]); // xmlWriter.WriteProperty("MINNUMBERITERATIONS", optimizerValues[9]); // xmlWriter.WriteProperty("NUMBERPERTURBATIONS", optimizerValues[10]); // xmlWriter.WriteProperty("NUMBERITERATIONS", optimizerValues[11]); // } //} //void RigidRegistrationPreset::saveInterpolatorValues(mitk::XMLWriter& xmlWriter, std::string item) //{ // itk::Array interpolatorValues = m_InterpolatorValues[item]; // xmlWriter.WriteProperty("INTERPOLATOR", interpolatorValues[0]); //} itk::Array RigidRegistrationPreset::loadTransformValues(itk::Array transformValues, double transform, const char **atts) { if (transform == mitk::TransformParameters::TRANSLATIONTRANSFORM || transform == mitk::TransformParameters::SCALETRANSFORM || transform == mitk::TransformParameters::SCALELOGARITHMICTRANSFORM || transform == mitk::TransformParameters::VERSORTRANSFORM || transform == mitk::TransformParameters::RIGID2DTRANSFORM || transform == mitk::TransformParameters::EULER2DTRANSFORM) { std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); double useSca = atof(useScales.c_str()); transformValues[1] = useSca; std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); double sca1 = atof(scale1.c_str()); transformValues[2] = sca1; std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); double sca2 = atof(scale2.c_str()); transformValues[3] = sca2; std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); double sca3 = atof(scale3.c_str()); transformValues[4] = sca3; } else if (transform == mitk::TransformParameters::AFFINETRANSFORM || transform == mitk::TransformParameters::FIXEDCENTEROFROTATIONAFFINETRANSFORM) { std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); double useSca = atof(useScales.c_str()); transformValues[1] = useSca; std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); double sca1 = atof(scale1.c_str()); transformValues[2] = sca1; std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); double sca2 = atof(scale2.c_str()); transformValues[3] = sca2; std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); double sca3 = atof(scale3.c_str()); transformValues[4] = sca3; std::string scale4 = ReadXMLStringAttribut( "SCALE4", atts ); double sca4 = atof(scale4.c_str()); transformValues[5] = sca4; std::string scale5 = ReadXMLStringAttribut( "SCALE5", atts ); double sca5 = atof(scale5.c_str()); transformValues[6] = sca5; std::string scale6 = ReadXMLStringAttribut( "SCALE6", atts ); double sca6 = atof(scale6.c_str()); transformValues[7] = sca6; std::string scale7 = ReadXMLStringAttribut( "SCALE7", atts ); double sca7 = atof(scale7.c_str()); transformValues[8] = sca7; std::string scale8 = ReadXMLStringAttribut( "SCALE8", atts ); double sca8 = atof(scale8.c_str()); transformValues[9] = sca8; std::string scale9 = ReadXMLStringAttribut( "SCALE9", atts ); double sca9 = atof(scale9.c_str()); transformValues[10] = sca9; std::string scale10 = ReadXMLStringAttribut( "SCALE10", atts ); double sca10 = atof(scale10.c_str()); transformValues[11] = sca10; std::string scale11 = ReadXMLStringAttribut( "SCALE11", atts ); double sca11 = atof(scale11.c_str()); transformValues[12] = sca11; std::string scale12 = ReadXMLStringAttribut( "SCALE12", atts ); double sca12 = atof(scale12.c_str()); transformValues[13] = sca12; /* std::string scale13 = ReadXMLStringAttribut( "SCALE13", atts ); double sca13 = atof(scale13.c_str()); transformValues[14] = sca13; std::string scale14 = ReadXMLStringAttribut( "SCALE14", atts ); double sca14 = atof(scale14.c_str()); transformValues[15] = sca14; std::string scale15 = ReadXMLStringAttribut( "SCALE15", atts ); double sca15 = atof(scale15.c_str()); transformValues[16] = sca15; std::string scale16 = ReadXMLStringAttribut( "SCALE16", atts ); double sca16 = atof(scale16.c_str()); transformValues[17] = sca16; */ std::string useInitializer = ReadXMLStringAttribut( "USEINITIALIZER", atts ); double useIni = atof(useInitializer.c_str()); transformValues[14] = useIni; std::string useMoments = ReadXMLStringAttribut( "USEMOMENTS", atts ); double useMo = atof(useMoments.c_str()); transformValues[15] = useMo; } //TODO remove rigid3dTransform // else if (transform == mitk::TransformParameters::RIGID3DTRANSFORM) // { // std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); // double useSca = atof(useScales.c_str()); // transformValues[1] = useSca; // std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); // double sca1 = atof(scale1.c_str()); // transformValues[2] = sca1; // std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); // double sca2 = atof(scale2.c_str()); // transformValues[3] = sca2; // std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); // double sca3 = atof(scale3.c_str()); // transformValues[4] = sca3; // std::string scale4 = ReadXMLStringAttribut( "SCALE4", atts ); // double sca4 = atof(scale4.c_str()); // transformValues[5] = sca4; // std::string scale5 = ReadXMLStringAttribut( "SCALE5", atts ); // double sca5 = atof(scale5.c_str()); // transformValues[6] = sca5; // std::string scale6 = ReadXMLStringAttribut( "SCALE6", atts ); // double sca6 = atof(scale6.c_str()); // transformValues[7] = sca6; // std::string scale7 = ReadXMLStringAttribut( "SCALE7", atts ); // double sca7 = atof(scale7.c_str()); // transformValues[8] = sca7; // std::string scale8 = ReadXMLStringAttribut( "SCALE8", atts ); // double sca8 = atof(scale8.c_str()); // transformValues[9] = sca8; // std::string scale9 = ReadXMLStringAttribut( "SCALE9", atts ); // double sca9 = atof(scale9.c_str()); // transformValues[10] = sca9; // std::string scale10 = ReadXMLStringAttribut( "SCALE10", atts ); // double sca10 = atof(scale10.c_str()); // transformValues[11] = sca10; // std::string scale11 = ReadXMLStringAttribut( "SCALE11", atts ); // double sca11 = atof(scale11.c_str()); // transformValues[12] = sca11; // std::string scale12 = ReadXMLStringAttribut( "SCALE12", atts ); // double sca12 = atof(scale12.c_str()); // transformValues[13] = sca12; // std::string useInitializer = ReadXMLStringAttribut( "USEINITIALIZER", atts ); // double useIni = atof(useInitializer.c_str()); // transformValues[14] = useIni; // std::string useMoments = ReadXMLStringAttribut( "USEMOMENTS", atts ); // double useMo = atof(useMoments.c_str()); // transformValues[15] = useMo; // } else if (transform == mitk::TransformParameters::EULER3DTRANSFORM || transform == mitk::TransformParameters::CENTEREDEULER3DTRANSFORM || transform == mitk::TransformParameters::VERSORRIGID3DTRANSFORM) { std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); double useSca = atof(useScales.c_str()); transformValues[1] = useSca; std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); double sca1 = atof(scale1.c_str()); transformValues[2] = sca1; std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); double sca2 = atof(scale2.c_str()); transformValues[3] = sca2; std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); double sca3 = atof(scale3.c_str()); transformValues[4] = sca3; std::string scale4 = ReadXMLStringAttribut( "SCALE4", atts ); double sca4 = atof(scale4.c_str()); transformValues[5] = sca4; std::string scale5 = ReadXMLStringAttribut( "SCALE5", atts ); double sca5 = atof(scale5.c_str()); transformValues[6] = sca5; std::string scale6 = ReadXMLStringAttribut( "SCALE6", atts ); double sca6 = atof(scale6.c_str()); transformValues[7] = sca6; std::string useInitializer = ReadXMLStringAttribut( "USEINITIALIZER", atts ); double useIni = atof(useInitializer.c_str()); transformValues[8] = useIni; std::string useMoments = ReadXMLStringAttribut( "USEMOMENTS", atts ); double useMo = atof(useMoments.c_str()); transformValues[9] = useMo; } else if (transform == mitk::TransformParameters::QUATERNIONRIGIDTRANSFORM || transform == mitk::TransformParameters::SIMILARITY3DTRANSFORM) { std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); double useSca = atof(useScales.c_str()); transformValues[1] = useSca; std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); double sca1 = atof(scale1.c_str()); transformValues[2] = sca1; std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); double sca2 = atof(scale2.c_str()); transformValues[3] = sca2; std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); double sca3 = atof(scale3.c_str()); transformValues[4] = sca3; std::string scale4 = ReadXMLStringAttribut( "SCALE4", atts ); double sca4 = atof(scale4.c_str()); transformValues[5] = sca4; std::string scale5 = ReadXMLStringAttribut( "SCALE5", atts ); double sca5 = atof(scale5.c_str()); transformValues[6] = sca5; std::string scale6 = ReadXMLStringAttribut( "SCALE6", atts ); double sca6 = atof(scale6.c_str()); transformValues[7] = sca6; std::string scale7 = ReadXMLStringAttribut( "SCALE7", atts ); double sca7 = atof(scale7.c_str()); transformValues[8] = sca7; std::string useInitializer = ReadXMLStringAttribut( "USEINITIALIZER", atts ); double useIni = atof(useInitializer.c_str()); transformValues[9] = useIni; std::string useMoments = ReadXMLStringAttribut( "USEMOMENTS", atts ); double useMo = atof(useMoments.c_str()); transformValues[10] = useMo; } else if (transform == mitk::TransformParameters::SCALESKEWVERSOR3DTRANSFORM) { std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); double useSca = atof(useScales.c_str()); transformValues[1] = useSca; std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); double sca1 = atof(scale1.c_str()); transformValues[2] = sca1; std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); double sca2 = atof(scale2.c_str()); transformValues[3] = sca2; std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); double sca3 = atof(scale3.c_str()); transformValues[4] = sca3; std::string scale4 = ReadXMLStringAttribut( "SCALE4", atts ); double sca4 = atof(scale4.c_str()); transformValues[5] = sca4; std::string scale5 = ReadXMLStringAttribut( "SCALE5", atts ); double sca5 = atof(scale5.c_str()); transformValues[6] = sca5; std::string scale6 = ReadXMLStringAttribut( "SCALE6", atts ); double sca6 = atof(scale6.c_str()); transformValues[7] = sca6; std::string scale7 = ReadXMLStringAttribut( "SCALE7", atts ); double sca7 = atof(scale7.c_str()); transformValues[8] = sca7; std::string scale8 = ReadXMLStringAttribut( "SCALE8", atts ); double sca8 = atof(scale8.c_str()); transformValues[9] = sca8; std::string scale9 = ReadXMLStringAttribut( "SCALE9", atts ); double sca9 = atof(scale9.c_str()); transformValues[10] = sca9; std::string scale10 = ReadXMLStringAttribut( "SCALE10", atts ); double sca10 = atof(scale10.c_str()); transformValues[11] = sca10; std::string scale11 = ReadXMLStringAttribut( "SCALE11", atts ); double sca11 = atof(scale11.c_str()); transformValues[12] = sca11; std::string scale12 = ReadXMLStringAttribut( "SCALE12", atts ); double sca12 = atof(scale12.c_str()); transformValues[13] = sca12; std::string scale13 = ReadXMLStringAttribut( "SCALE13", atts ); double sca13 = atof(scale13.c_str()); transformValues[14] = sca13; std::string scale14 = ReadXMLStringAttribut( "SCALE14", atts ); double sca14 = atof(scale14.c_str()); transformValues[15] = sca14; std::string scale15 = ReadXMLStringAttribut( "SCALE15", atts ); double sca15 = atof(scale15.c_str()); transformValues[16] = sca15; std::string useInitializer = ReadXMLStringAttribut( "USEINITIALIZER", atts ); double useIni = atof(useInitializer.c_str()); transformValues[17] = useIni; std::string useMoments = ReadXMLStringAttribut( "USEMOMENTS", atts ); double useMo = atof(useMoments.c_str()); transformValues[18] = useMo; } else if (transform == mitk::TransformParameters::CENTEREDRIGID2DTRANSFORM) { std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); double useSca = atof(useScales.c_str()); transformValues[1] = useSca; std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); double sca1 = atof(scale1.c_str()); transformValues[2] = sca1; std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); double sca2 = atof(scale2.c_str()); transformValues[3] = sca2; std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); double sca3 = atof(scale3.c_str()); transformValues[4] = sca3; std::string scale4 = ReadXMLStringAttribut( "SCALE4", atts ); double sca4 = atof(scale4.c_str()); transformValues[5] = sca4; std::string scale5 = ReadXMLStringAttribut( "SCALE5", atts ); double sca5 = atof(scale5.c_str()); transformValues[6] = sca5; std::string angle = ReadXMLStringAttribut( "ANGLE", atts ); double ang = atof(angle.c_str()); transformValues[7] = ang; std::string useInitializer = ReadXMLStringAttribut( "USEINITIALIZER", atts ); double useIni = atof(useInitializer.c_str()); transformValues[8] = useIni; std::string useMoments = ReadXMLStringAttribut( "USEMOMENTS", atts ); double useMo = atof(useMoments.c_str()); transformValues[9] = useMo; } else if (transform == mitk::TransformParameters::SIMILARITY2DTRANSFORM) { std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); double useSca = atof(useScales.c_str()); transformValues[1] = useSca; std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); double sca1 = atof(scale1.c_str()); transformValues[2] = sca1; std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); double sca2 = atof(scale2.c_str()); transformValues[3] = sca2; std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); double sca3 = atof(scale3.c_str()); transformValues[4] = sca3; std::string scale4 = ReadXMLStringAttribut( "SCALE4", atts ); double sca4 = atof(scale4.c_str()); transformValues[5] = sca4; std::string scale = ReadXMLStringAttribut( "SCALE", atts ); double sca = atof(scale.c_str()); transformValues[6] = sca; std::string angle = ReadXMLStringAttribut( "ANGLE", atts ); double ang = atof(angle.c_str()); transformValues[7] = ang; std::string useInitializer = ReadXMLStringAttribut( "USEINITIALIZER", atts ); double useIni = atof(useInitializer.c_str()); transformValues[8] = useIni; std::string useMoments = ReadXMLStringAttribut( "USEMOMENTS", atts ); double useMo = atof(useMoments.c_str()); transformValues[9] = useMo; } else if (transform == mitk::TransformParameters::CENTEREDSIMILARITY2DTRANSFORM) { std::string useScales = ReadXMLStringAttribut( "USESCALES", atts ); double useSca = atof(useScales.c_str()); transformValues[1] = useSca; std::string scale1 = ReadXMLStringAttribut( "SCALE1", atts ); double sca1 = atof(scale1.c_str()); transformValues[2] = sca1; std::string scale2 = ReadXMLStringAttribut( "SCALE2", atts ); double sca2 = atof(scale2.c_str()); transformValues[3] = sca2; std::string scale3 = ReadXMLStringAttribut( "SCALE3", atts ); double sca3 = atof(scale3.c_str()); transformValues[4] = sca3; std::string scale4 = ReadXMLStringAttribut( "SCALE4", atts ); double sca4 = atof(scale4.c_str()); transformValues[5] = sca4; std::string scale5 = ReadXMLStringAttribut( "SCALE5", atts ); double sca5 = atof(scale5.c_str()); transformValues[6] = sca5; std::string scale6 = ReadXMLStringAttribut( "SCALE6", atts ); double sca6 = atof(scale6.c_str()); transformValues[7] = sca6; std::string scale = ReadXMLStringAttribut( "SCALE", atts ); double sca = atof(scale.c_str()); transformValues[8] = sca; std::string angle = ReadXMLStringAttribut( "ANGLE", atts ); double ang = atof(angle.c_str()); transformValues[9] = ang; std::string useInitializer = ReadXMLStringAttribut( "USEINITIALIZER", atts ); double useIni = atof(useInitializer.c_str()); transformValues[10] = useIni; std::string useMoments = ReadXMLStringAttribut( "USEMOMENTS", atts ); double useMo = atof(useMoments.c_str()); transformValues[11] = useMo; } return transformValues; } itk::Array RigidRegistrationPreset::loadMetricValues(itk::Array metricValues, double metric, const char **atts) { std::string computeGradient = ReadXMLStringAttribut( "COMPUTEGRADIENT", atts ); double compGra = atof(computeGradient.c_str()); metricValues[1] = compGra; if (metric == mitk::MetricParameters::MEANSQUARESIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::NORMALIZEDCORRELATIONIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::GRADIENTDIFFERENCEIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::MATCHCARDINALITYIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::KAPPASTATISTICIMAGETOIMAGEMETRIC) { } else if (metric == mitk::MetricParameters::KULLBACKLEIBLERCOMPAREHISTOGRAMIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::CORRELATIONCOEFFICIENTHISTOGRAMIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::MEANSQUARESHISTOGRAMIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::MUTUALINFORMATIONHISTOGRAMIMAGETOIMAGEMETRIC || metric == mitk::MetricParameters::NORMALIZEDMUTUALINFORMATIONHISTOGRAMIMAGETOIMAGEMETRIC) { std::string histogramBins = ReadXMLStringAttribut( "HISTOGRAMBINS", atts ); double histBins = atof(histogramBins.c_str()); metricValues[2] = histBins; } else if (metric == mitk::MetricParameters::MATTESMUTUALINFORMATIONIMAGETOIMAGEMETRIC) { std::string useSampling = ReadXMLStringAttribut( "USESAMPLING", atts ); double useSamp = atof(useSampling.c_str()); metricValues[2] = useSamp; std::string spatialSamples = ReadXMLStringAttribut( "SPATIALSAMPLES", atts ); double spatSamp = atof(spatialSamples.c_str()); metricValues[3] = spatSamp; std::string histogramBins = ReadXMLStringAttribut( "HISTOGRAMBINS", atts ); double histBins = atof(histogramBins.c_str()); metricValues[4] = histBins; } else if (metric == mitk::MetricParameters::MEANRECIPROCALSQUAREDIFFERENCEIMAGETOIMAGEMETRIC) { std::string lambda = ReadXMLStringAttribut( "LAMBDA", atts ); double lamb = atof(lambda.c_str()); metricValues[2] = lamb; } else if (metric == mitk::MetricParameters::MUTUALINFORMATIONIMAGETOIMAGEMETRIC) { std::string spatialSamples = ReadXMLStringAttribut( "SPATIALSAMPLES", atts ); double spatSamp = atof(spatialSamples.c_str()); metricValues[2] = spatSamp; std::string fixedStandardDeviation = ReadXMLStringAttribut( "FIXEDSTANDARDDEVIATION", atts ); double fiStaDev = atof(fixedStandardDeviation.c_str()); metricValues[3] = fiStaDev; std::string movingStandardDeviation = ReadXMLStringAttribut( "MOVINGSTANDARDDEVIATION", atts ); double moStaDev = atof(movingStandardDeviation.c_str()); metricValues[4] = moStaDev; std::string useNormalizer = ReadXMLStringAttribut( "USENORMALIZERANDSMOOTHER", atts ); double useNormal = atof(useNormalizer.c_str()); metricValues[5] = useNormal; std::string fixedSmootherVariance = ReadXMLStringAttribut( "FIXEDSMOOTHERVARIANCE", atts ); double fiSmoVa = atof(fixedSmootherVariance.c_str()); metricValues[6] = fiSmoVa; std::string movingSmootherVariance = ReadXMLStringAttribut( "MOVINGSMOOTHERVARIANCE", atts ); double moSmoVa = atof(movingSmootherVariance.c_str()); metricValues[7] = moSmoVa; } return metricValues; } itk::Array RigidRegistrationPreset::loadOptimizerValues(itk::Array optimizerValues, double optimizer, const char **atts) { std::string maximize = ReadXMLStringAttribut( "MAXIMIZE", atts ); double max = atof(maximize.c_str()); optimizerValues[1] = max; if (optimizer == mitk::OptimizerParameters::EXHAUSTIVEOPTIMIZER) { std::string stepLength = ReadXMLStringAttribut( "STEPLENGTH", atts ); double stepLe = atof(stepLength.c_str()); optimizerValues[2] = stepLe; std::string numberOfSteps = ReadXMLStringAttribut( "NUMBEROFSTEPS", atts ); double numSteps = atof(numberOfSteps.c_str()); optimizerValues[3] = numSteps; } else if (optimizer == mitk::OptimizerParameters::GRADIENTDESCENTOPTIMIZER || optimizer == mitk::OptimizerParameters::QUATERNIONRIGIDTRANSFORMGRADIENTDESCENTOPTIMIZER) { std::string learningRate = ReadXMLStringAttribut( "LEARNINGRATE", atts ); double learn = atof(learningRate.c_str()); optimizerValues[2] = learn; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[3] = numIt; } else if (optimizer == mitk::OptimizerParameters::LBFGSBOPTIMIZER) { } else if (optimizer == mitk::OptimizerParameters::ONEPLUSONEEVOLUTIONARYOPTIMIZER) { std::string shrinkFactor = ReadXMLStringAttribut( "SHRINKFACTOR", atts ); double shrink = atof(shrinkFactor.c_str()); optimizerValues[2] = shrink; std::string growthFactor = ReadXMLStringAttribut( "GROWTHFACTOR", atts ); double growth = atof(growthFactor.c_str()); optimizerValues[3] = growth; std::string epsilon = ReadXMLStringAttribut( "EPSILON", atts ); double eps = atof(epsilon.c_str()); optimizerValues[4] = eps; std::string initialRadius = ReadXMLStringAttribut( "INITIALRADIUS", atts ); double initRad = atof(initialRadius.c_str()); optimizerValues[5] = initRad; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[6] = numIt; } else if (optimizer == mitk::OptimizerParameters::POWELLOPTIMIZER) { std::string stepLength = ReadXMLStringAttribut( "STEPLENGTH", atts ); double stepLe = atof(stepLength.c_str()); optimizerValues[2] = stepLe; std::string stepTolerance = ReadXMLStringAttribut( "STEPTOLERANCE", atts ); double stepTo = atof(stepTolerance.c_str()); optimizerValues[3] = stepTo; std::string valueTolerance = ReadXMLStringAttribut( "VALUETOLERANCE", atts ); double valTo = atof(valueTolerance.c_str()); optimizerValues[4] = valTo; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[5] = numIt; } else if (optimizer == mitk::OptimizerParameters::FRPROPTIMIZER) { std::string useFletchReeves = ReadXMLStringAttribut( "USEFLETCHREEVES", atts ); double useFleRe = atof(useFletchReeves.c_str()); optimizerValues[2] = useFleRe; std::string stepLength = ReadXMLStringAttribut( "STEPLENGTH", atts ); double stepLe = atof(stepLength.c_str()); optimizerValues[3] = stepLe; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[4] = numIt; } else if (optimizer == mitk::OptimizerParameters::REGULARSTEPGRADIENTDESCENTOPTIMIZER) { std::string gradientMagnitudeTolerance = ReadXMLStringAttribut( "GRADIENTMAGNITUDETOLERANCE", atts ); double graMagTo = atof(gradientMagnitudeTolerance.c_str()); optimizerValues[2] = graMagTo; std::string minStepLength = ReadXMLStringAttribut( "MINSTEPLENGTH", atts ); double minStep = atof(minStepLength.c_str()); optimizerValues[3] = minStep; std::string maxStepLength = ReadXMLStringAttribut( "MAXSTEPLENGTH", atts ); double maxStep = atof(maxStepLength.c_str()); optimizerValues[4] = maxStep; std::string relaxationFactor = ReadXMLStringAttribut( "RELAXATIONFACTOR", atts ); double relFac = atof(relaxationFactor.c_str()); optimizerValues[5] = relFac; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[6] = numIt; } else if (optimizer == mitk::OptimizerParameters::VERSORTRANSFORMOPTIMIZER || optimizer == mitk::OptimizerParameters::VERSORRIGID3DTRANSFORMOPTIMIZER) { std::string gradientMagnitudeTolerance = ReadXMLStringAttribut( "GRADIENTMAGNITUDETOLERANCE", atts ); double graMagTo = atof(gradientMagnitudeTolerance.c_str()); optimizerValues[2] = graMagTo; std::string minStepLength = ReadXMLStringAttribut( "MINSTEPLENGTH", atts ); double minStep = atof(minStepLength.c_str()); optimizerValues[3] = minStep; std::string maxStepLength = ReadXMLStringAttribut( "MAXSTEPLENGTH", atts ); double maxStep = atof(maxStepLength.c_str()); optimizerValues[4] = maxStep; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[5] = numIt; } else if (optimizer == mitk::OptimizerParameters::AMOEBAOPTIMIZER) { std::string simplexDelta1 = ReadXMLStringAttribut( "SIMPLEXDELTA1", atts ); double simpDel1 = atof(simplexDelta1.c_str()); optimizerValues[2] = simpDel1; std::string simplexDelta2 = ReadXMLStringAttribut( "SIMPLEXDELTA2", atts ); double simpDel2 = atof(simplexDelta2.c_str()); optimizerValues[3] = simpDel2; std::string simplexDelta3 = ReadXMLStringAttribut( "SIMPLEXDELTA3", atts ); double simpDel3 = atof(simplexDelta3.c_str()); optimizerValues[4] = simpDel3; std::string simplexDelta4 = ReadXMLStringAttribut( "SIMPLEXDELTA4", atts ); double simpDel4 = atof(simplexDelta4.c_str()); optimizerValues[5] = simpDel4; std::string simplexDelta5 = ReadXMLStringAttribut( "SIMPLEXDELTA5", atts ); double simpDel5 = atof(simplexDelta5.c_str()); optimizerValues[6] = simpDel5; std::string simplexDelta6 = ReadXMLStringAttribut( "SIMPLEXDELTA6", atts ); double simpDel6 = atof(simplexDelta6.c_str()); optimizerValues[7] = simpDel6; std::string simplexDelta7 = ReadXMLStringAttribut( "SIMPLEXDELTA7", atts ); double simpDel7 = atof(simplexDelta7.c_str()); optimizerValues[8] = simpDel7; std::string simplexDelta8 = ReadXMLStringAttribut( "SIMPLEXDELTA8", atts ); double simpDel8 = atof(simplexDelta8.c_str()); optimizerValues[9] = simpDel8; std::string simplexDelta9 = ReadXMLStringAttribut( "SIMPLEXDELTA9", atts ); double simpDel9 = atof(simplexDelta9.c_str()); optimizerValues[10] = simpDel9; std::string simplexDelta10 = ReadXMLStringAttribut( "SIMPLEXDELTA10", atts ); double simpDel10 = atof(simplexDelta10.c_str()); optimizerValues[11] = simpDel10; std::string simplexDelta11 = ReadXMLStringAttribut( "SIMPLEXDELTA11", atts ); double simpDel11 = atof(simplexDelta11.c_str()); optimizerValues[12] = simpDel11; std::string simplexDelta12 = ReadXMLStringAttribut( "SIMPLEXDELTA12", atts ); double simpDel12 = atof(simplexDelta12.c_str()); optimizerValues[13] = simpDel12; std::string simplexDelta13 = ReadXMLStringAttribut( "SIMPLEXDELTA13", atts ); double simpDel13 = atof(simplexDelta13.c_str()); optimizerValues[14] = simpDel13; std::string simplexDelta14 = ReadXMLStringAttribut( "SIMPLEXDELTA14", atts ); double simpDel14 = atof(simplexDelta14.c_str()); optimizerValues[15] = simpDel14; std::string simplexDelta15 = ReadXMLStringAttribut( "SIMPLEXDELTA15", atts ); double simpDel15 = atof(simplexDelta15.c_str()); optimizerValues[16] = simpDel15; std::string simplexDelta16 = ReadXMLStringAttribut( "SIMPLEXDELTA16", atts ); double simpDel16 = atof(simplexDelta16.c_str()); optimizerValues[17] = simpDel16; std::string parametersConvergenceTolerance = ReadXMLStringAttribut( "PARAMETERSCONVERGENCETOLERANCE", atts ); double paramConv = atof(parametersConvergenceTolerance.c_str()); optimizerValues[18] = paramConv; std::string functionConvergenceTolerance = ReadXMLStringAttribut( "FUNCTIONCONVERGENCETOLERANCE", atts ); double funcConv = atof(functionConvergenceTolerance.c_str()); optimizerValues[19] = funcConv; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[20] = numIt; } else if (optimizer == mitk::OptimizerParameters::CONJUGATEGRADIENTOPTIMIZER) { } else if (optimizer == mitk::OptimizerParameters::LBFGSOPTIMIZER) { std::string GradientConvergenceTolerance = ReadXMLStringAttribut( "GRADIENTCONVERGENCETOLERANCE", atts ); double graConTo = atof(GradientConvergenceTolerance.c_str()); optimizerValues[2] = graConTo; std::string lineSearchAccuracy = ReadXMLStringAttribut( "LINESEARCHACCURACY", atts ); double lineSearch = atof(lineSearchAccuracy.c_str()); optimizerValues[3] = lineSearch; std::string defaultStepLength = ReadXMLStringAttribut( "DEFAULTSTEPLENGTH", atts ); double defStep = atof(defaultStepLength.c_str()); optimizerValues[4] = defStep; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[5] = numIt; std::string useTrace = ReadXMLStringAttribut( "USETRACE", atts ); double useTr = atof(useTrace.c_str()); optimizerValues[6] = useTr; } else if (optimizer == mitk::OptimizerParameters::SPSAOPTIMIZER) { std::string a = ReadXMLStringAttribut( "a", atts ); double a1 = atof(a.c_str()); optimizerValues[2] = a1; std::string a2 = ReadXMLStringAttribut( "A", atts ); double a3 = atof(a2.c_str()); optimizerValues[3] = a3; std::string alpha = ReadXMLStringAttribut( "ALPHA", atts ); double alp = atof(alpha.c_str()); optimizerValues[4] = alp; std::string c = ReadXMLStringAttribut( "c", atts ); double c1 = atof(c.c_str()); optimizerValues[5] = c1; std::string gamma = ReadXMLStringAttribut( "GAMMA", atts ); double gam = atof(gamma.c_str()); optimizerValues[6] = gam; std::string tolerance = ReadXMLStringAttribut( "TOLERANCE", atts ); double tol = atof(tolerance.c_str()); optimizerValues[7] = tol; std::string stateOfConvergenceDecayRate = ReadXMLStringAttribut( "STATEOFCONVERGENCEDECAYRATE", atts ); double stateOfConvergence = atof(stateOfConvergenceDecayRate.c_str()); optimizerValues[8] = stateOfConvergence; std::string minNumberIterations = ReadXMLStringAttribut( "MINNUMBERITERATIONS", atts ); double minNumIt = atof(minNumberIterations.c_str()); optimizerValues[9] = minNumIt; std::string numberPerturbations = ReadXMLStringAttribut( "NUMBERPERTURBATIONS", atts ); double numPer = atof(numberPerturbations.c_str()); optimizerValues[10] = numPer; std::string numberIterations = ReadXMLStringAttribut( "NUMBERITERATIONS", atts ); double numIt = atof(numberIterations.c_str()); optimizerValues[11] = numIt; } return optimizerValues; } itk::Array RigidRegistrationPreset::loadInterpolatorValues(itk::Array interpolatorValues/*, double interpolator, const char **atts*/) { return interpolatorValues; } } diff --git a/Modules/SceneSerialization/mitkSceneDataNodeReader.h b/Modules/SceneSerialization/mitkSceneDataNodeReader.h index ff253ef850..58320d7e5e 100644 --- a/Modules/SceneSerialization/mitkSceneDataNodeReader.h +++ b/Modules/SceneSerialization/mitkSceneDataNodeReader.h @@ -1,37 +1,35 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKSCENEDATANODEREADER_H #define MITKSCENEDATANODEREADER_H #include namespace mitk { -class SceneDataNodeReader : public itk::LightObject, public mitk::IDataNodeReader +class SceneDataNodeReader : public mitk::IDataNodeReader { public: - itkNewMacro(SceneDataNodeReader) - int Read(const std::string& fileName, mitk::DataStorage& storage); }; } #endif // MITKSCENEDATANODEREADER_H diff --git a/Modules/SceneSerialization/mitkSceneSerializationActivator.cpp b/Modules/SceneSerialization/mitkSceneSerializationActivator.cpp index cd51f73cb0..5298d4761a 100644 --- a/Modules/SceneSerialization/mitkSceneSerializationActivator.cpp +++ b/Modules/SceneSerialization/mitkSceneSerializationActivator.cpp @@ -1,49 +1,48 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSceneDataNodeReader.h" -#include -#include +#include +#include namespace mitk { /* * This is the module activator for the "SceneSerialization" module. */ -class SceneSerializationActivator : public ModuleActivator +class SceneSerializationActivator : public us::ModuleActivator { public: - void Load(mitk::ModuleContext* context) + void Load(us::ModuleContext* context) { - m_SceneDataNodeReader = mitk::SceneDataNodeReader::New(); - context->RegisterService(m_SceneDataNodeReader); + m_SceneDataNodeReader.reset(new mitk::SceneDataNodeReader); + context->RegisterService(m_SceneDataNodeReader.get()); } - void Unload(mitk::ModuleContext* ) + void Unload(us::ModuleContext* ) { } private: - SceneDataNodeReader::Pointer m_SceneDataNodeReader; + std::auto_ptr m_SceneDataNodeReader; }; } US_EXPORT_MODULE_ACTIVATOR(SceneSerialization, mitk::SceneSerializationActivator) - diff --git a/Modules/Segmentation/Controllers/mitkToolManager.cpp b/Modules/Segmentation/Controllers/mitkToolManager.cpp index c019e28930..28b3a28aef 100644 --- a/Modules/Segmentation/Controllers/mitkToolManager.cpp +++ b/Modules/Segmentation/Controllers/mitkToolManager.cpp @@ -1,540 +1,536 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkToolManager.h" #include "mitkGlobalInteraction.h" #include "mitkCoreObjectFactory.h" #include #include #include #include "mitkInteractionEventObserver.h" #include "mitkDisplayInteractor.h" #include "mitkSegTool2D.h" -// MicroServices -#include "mitkGetModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleRegistry.h" mitk::ToolManager::ToolManager(DataStorage* storage) :m_ActiveTool(NULL), m_ActiveToolID(-1), m_RegisteredClients(0), m_DataStorage(storage) { CoreObjectFactory::GetInstance(); // to make sure a CoreObjectFactory was instantiated (and in turn, possible tools are registered) - bug 1029 // get a list of all known mitk::Tools std::list thingsThatClaimToBeATool = itk::ObjectFactoryBase::CreateAllInstance("mitkTool"); // remember these tools for ( std::list::iterator iter = thingsThatClaimToBeATool.begin(); iter != thingsThatClaimToBeATool.end(); ++iter ) { if ( Tool* tool = dynamic_cast( iter->GetPointer() ) ) { tool->SetToolManager(this); // important to call right after instantiation tool->ErrorMessage += MessageDelegate1( this, &ToolManager::OnToolErrorMessage ); tool->GeneralMessage += MessageDelegate1( this, &ToolManager::OnGeneralToolMessage ); m_Tools.push_back( tool ); } } //ActivateTool(0); // first one is default } mitk::ToolManager::~ToolManager() { for (DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter) (*dataIter)->RemoveObserver(m_WorkingDataObserverTags[(*dataIter)]); if(this->GetDataStorage() != NULL) this->GetDataStorage()->RemoveNodeEvent.RemoveListener( mitk::MessageDelegate1 ( this, &ToolManager::OnNodeRemoved )); if (m_ActiveTool) { m_ActiveTool->Deactivated(); GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool ); m_ActiveTool = NULL; m_ActiveToolID = -1; // no tool active ActiveToolChanged.Send(); } for ( NodeTagMapType::iterator observerTagMapIter = m_ReferenceDataObserverTags.begin(); observerTagMapIter != m_ReferenceDataObserverTags.end(); ++observerTagMapIter ) { observerTagMapIter->first->RemoveObserver( observerTagMapIter->second ); } } void mitk::ToolManager::OnToolErrorMessage(std::string s) { this->ToolErrorMessage(s); } void mitk::ToolManager::OnGeneralToolMessage(std::string s) { this->GeneralToolMessage(s); } const mitk::ToolManager::ToolVectorTypeConst mitk::ToolManager::GetTools() { ToolVectorTypeConst resultList; for ( ToolVectorType::iterator iter = m_Tools.begin(); iter != m_Tools.end(); ++iter ) { resultList.push_back( iter->GetPointer() ); } return resultList; } mitk::Tool* mitk::ToolManager::GetToolById(int id) { try { return m_Tools.at(id); } catch(std::exception&) { return NULL; } } bool mitk::ToolManager::ActivateTool(int id) { if(this->GetDataStorage()) { this->GetDataStorage()->RemoveNodeEvent.AddListener( mitk::MessageDelegate1 ( this, &ToolManager::OnNodeRemoved ) ); } //MITK_INFO << "ToolManager::ActivateTool("<SetEventNotificationPolicy(GlobalInteraction::INFORM_MULTIPLE); } if ( GetToolById( id ) == m_ActiveTool ) return true; // no change needed static int nextTool = -1; nextTool = id; //MITK_INFO << "ToolManager::ActivateTool("<Deactivated(); GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool ); } m_ActiveTool = GetToolById( nextTool ); m_ActiveToolID = m_ActiveTool ? nextTool : -1; // current ID if tool is valid, otherwise -1 ActiveToolChanged.Send(); if (m_ActiveTool) { if (m_RegisteredClients > 0) { m_ActiveTool->Activated(); GlobalInteraction::GetInstance()->AddListener( m_ActiveTool ); //If a tool is activated set event notification policy to one if (dynamic_cast(m_ActiveTool)) GlobalInteraction::GetInstance()->SetEventNotificationPolicy(GlobalInteraction::INFORM_ONE); } } } inActivateTool = false; return (m_ActiveTool != NULL); } void mitk::ToolManager::SetReferenceData(DataVectorType data) { if (data != m_ReferenceData) { // remove observers from old nodes for ( DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter ) { NodeTagMapType::iterator searchIter = m_ReferenceDataObserverTags.find( *dataIter ); if ( searchIter != m_ReferenceDataObserverTags.end() ) { //MITK_INFO << "Stopping observation of " << (void*)(*dataIter) << std::endl; (*dataIter)->RemoveObserver( searchIter->second ); } } m_ReferenceData = data; // TODO tell active tool? // attach new observers m_ReferenceDataObserverTags.clear(); for ( DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter ) { //MITK_INFO << "Observing " << (void*)(*dataIter) << std::endl; itk::MemberCommand::Pointer command = itk::MemberCommand::New(); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheReferenceDataDeleted ); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheReferenceDataDeletedConst ); m_ReferenceDataObserverTags.insert( std::pair( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) ); } ReferenceDataChanged.Send(); } } void mitk::ToolManager::OnOneOfTheReferenceDataDeletedConst(const itk::Object* caller, const itk::EventObject& e) { OnOneOfTheReferenceDataDeleted( const_cast(caller), e ); } void mitk::ToolManager::OnOneOfTheReferenceDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e)) { //MITK_INFO << "Deleted: " << (void*)caller << " Removing from reference data list." << std::endl; DataVectorType v; for (DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter ) { //MITK_INFO << " In list: " << (void*)(*dataIter); if ( (void*)(*dataIter) != (void*)caller ) { v.push_back( *dataIter ); //MITK_INFO << " kept" << std::endl; } else { //MITK_INFO << " removed" << std::endl; m_ReferenceDataObserverTags.erase( *dataIter ); // no tag to remove anymore } } this->SetReferenceData( v ); } void mitk::ToolManager::SetReferenceData(DataNode* data) { //MITK_INFO << "ToolManager::SetReferenceData(" << (void*)data << ")" << std::endl; DataVectorType v; if (data) { v.push_back(data); } SetReferenceData(v); } void mitk::ToolManager::SetWorkingData(DataVectorType data) { if ( data != m_WorkingData ) { // remove observers from old nodes for ( DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter ) { NodeTagMapType::iterator searchIter = m_WorkingDataObserverTags.find( *dataIter ); if ( searchIter != m_WorkingDataObserverTags.end() ) { //MITK_INFO << "Stopping observation of " << (void*)(*dataIter) << std::endl; (*dataIter)->RemoveObserver( searchIter->second ); } } m_WorkingData = data; // TODO tell active tool? // attach new observers m_WorkingDataObserverTags.clear(); for ( DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter ) { //MITK_INFO << "Observing " << (void*)(*dataIter) << std::endl; itk::MemberCommand::Pointer command = itk::MemberCommand::New(); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheWorkingDataDeleted ); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheWorkingDataDeletedConst ); m_WorkingDataObserverTags.insert( std::pair( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) ); } WorkingDataChanged.Send(); } } void mitk::ToolManager::OnOneOfTheWorkingDataDeletedConst(const itk::Object* caller, const itk::EventObject& e) { OnOneOfTheWorkingDataDeleted( const_cast(caller), e ); } void mitk::ToolManager::OnOneOfTheWorkingDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e)) { //MITK_INFO << "Deleted: " << (void*)caller << " Removing from reference data list." << std::endl; DataVectorType v; for (DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter ) { //MITK_INFO << " In list: " << (void*)(*dataIter); if ( (void*)(*dataIter) != (void*)caller ) { v.push_back( *dataIter ); //MITK_INFO << " kept" << std::endl; } else { //MITK_INFO << " removed" << std::endl; m_WorkingDataObserverTags.erase( *dataIter ); // no tag to remove anymore } } this->SetWorkingData( v ); } void mitk::ToolManager::SetWorkingData(DataNode* data) { DataVectorType v; if (data) // don't allow for NULL nodes { v.push_back(data); } SetWorkingData(v); } void mitk::ToolManager::SetRoiData(DataVectorType data) { if (data != m_RoiData) { // remove observers from old nodes for ( DataVectorType::iterator dataIter = m_RoiData.begin(); dataIter != m_RoiData.end(); ++dataIter ) { NodeTagMapType::iterator searchIter = m_RoiDataObserverTags.find( *dataIter ); if ( searchIter != m_RoiDataObserverTags.end() ) { //MITK_INFO << "Stopping observation of " << (void*)(*dataIter) << std::endl; (*dataIter)->RemoveObserver( searchIter->second ); } } m_RoiData = data; // TODO tell active tool? // attach new observers m_RoiDataObserverTags.clear(); for ( DataVectorType::iterator dataIter = m_RoiData.begin(); dataIter != m_RoiData.end(); ++dataIter ) { //MITK_INFO << "Observing " << (void*)(*dataIter) << std::endl; itk::MemberCommand::Pointer command = itk::MemberCommand::New(); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheRoiDataDeleted ); command->SetCallbackFunction( this, &ToolManager::OnOneOfTheRoiDataDeletedConst ); m_RoiDataObserverTags.insert( std::pair( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) ); } RoiDataChanged.Send(); } } void mitk::ToolManager::SetRoiData(DataNode* data) { DataVectorType v; if(data) { v.push_back(data); } this->SetRoiData(v); } void mitk::ToolManager::OnOneOfTheRoiDataDeletedConst(const itk::Object* caller, const itk::EventObject& e) { OnOneOfTheRoiDataDeleted( const_cast(caller), e ); } void mitk::ToolManager::OnOneOfTheRoiDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e)) { //MITK_INFO << "Deleted: " << (void*)caller << " Removing from roi data list." << std::endl; DataVectorType v; for (DataVectorType::iterator dataIter = m_RoiData.begin(); dataIter != m_RoiData.end(); ++dataIter ) { //MITK_INFO << " In list: " << (void*)(*dataIter); if ( (void*)(*dataIter) != (void*)caller ) { v.push_back( *dataIter ); //MITK_INFO << " kept" << std::endl; } else { //MITK_INFO << " removed" << std::endl; m_RoiDataObserverTags.erase( *dataIter ); // no tag to remove anymore } } this->SetRoiData( v ); } mitk::ToolManager::DataVectorType mitk::ToolManager::GetReferenceData() { return m_ReferenceData; } mitk::DataNode* mitk::ToolManager::GetReferenceData(int idx) { try { return m_ReferenceData.at(idx); } catch(std::exception&) { return NULL; } } mitk::ToolManager::DataVectorType mitk::ToolManager::GetWorkingData() { return m_WorkingData; } mitk::ToolManager::DataVectorType mitk::ToolManager::GetRoiData() { return m_RoiData; } mitk::DataNode* mitk::ToolManager::GetRoiData(int idx) { try { return m_RoiData.at(idx); } catch(std::exception&) { return NULL; } } mitk::DataStorage* mitk::ToolManager::GetDataStorage() { if ( m_DataStorage.IsNotNull() ) { return m_DataStorage; } else { return NULL; } } void mitk::ToolManager::SetDataStorage(DataStorage& storage) { m_DataStorage = &storage; } mitk::DataNode* mitk::ToolManager::GetWorkingData(int idx) { try { return m_WorkingData.at(idx); } catch(std::exception&) { return NULL; } } int mitk::ToolManager::GetActiveToolID() { return m_ActiveToolID; } mitk::Tool* mitk::ToolManager::GetActiveTool() { return m_ActiveTool; } void mitk::ToolManager::RegisterClient() { if ( m_RegisteredClients < 1 ) { if ( m_ActiveTool ) { m_ActiveTool->Activated(); GlobalInteraction::GetInstance()->AddListener( m_ActiveTool ); } } ++m_RegisteredClients; } void mitk::ToolManager::UnregisterClient() { if ( m_RegisteredClients < 1) return; --m_RegisteredClients; if ( m_RegisteredClients < 1 ) { if ( m_ActiveTool ) { m_ActiveTool->Deactivated(); GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool ); } } } int mitk::ToolManager::GetToolID( const Tool* tool ) { int id(0); for ( ToolVectorType::iterator iter = m_Tools.begin(); iter != m_Tools.end(); ++iter, ++id ) { if ( tool == iter->GetPointer() ) { return id; } } return -1; } void mitk::ToolManager::OnNodeRemoved(const mitk::DataNode* node) { //check if the data of the node is typeof Image /*if(dynamic_cast(node->GetData())) {*/ //check all storage vectors OnOneOfTheReferenceDataDeleted(const_cast(node), itk::DeleteEvent()); OnOneOfTheRoiDataDeleted(const_cast(node),itk::DeleteEvent()); OnOneOfTheWorkingDataDeleted(const_cast(node),itk::DeleteEvent()); //} } diff --git a/Modules/Segmentation/Controllers/mitkToolManager.h b/Modules/Segmentation/Controllers/mitkToolManager.h index 925371baf1..fef2beaa9d 100644 --- a/Modules/Segmentation/Controllers/mitkToolManager.h +++ b/Modules/Segmentation/Controllers/mitkToolManager.h @@ -1,295 +1,294 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkToolManager_h_Included #define mitkToolManager_h_Included #include "mitkTool.h" #include "SegmentationExports.h" #include "mitkDataNode.h" #include "mitkDataStorage.h" #include "mitkWeakPointer.h" -#include "mitkServiceReference.h" #pragma GCC visibility push(default) #include #pragma GCC visibility pop #include #include namespace mitk { class Image; class PlaneGeometry; /** \brief Manages and coordinates instances of mitk::Tool. \sa QmitkToolSelectionBox \sa QmitkToolReferenceDataSelectionBox \sa QmitkToolWorkingDataSelectionBox \sa Tool \sa QmitkSegmentationView \ingroup Interaction \ingroup ToolManagerEtAl There is a separate page describing the general design of QmitkSegmentationView: \ref QmitkSegmentationTechnicalPage This class creates and manages several instances of mitk::Tool. \li ToolManager creates instances of mitk::Tool by asking the itk::ObjectFactory to list all known implementations of mitk::Tool. As a result, one has to implement both a subclass of mitk::Tool and a matching subclass of itk::ObjectFactoryBase that is registered to the top-level itk::ObjectFactory. For an example, see mitkContourToolFactory.h. (this limitiation of one-class-one-factory is due to the implementation of itk::ObjectFactory). In MITK, the right place to register the factories to itk::ObjectFactory is the mitk::QMCoreObjectFactory or mitk::SBCoreObjectFactory. \li One (and only one - or none at all) of the registered tools can be activated using ActivateTool. This tool is registered to mitk::GlobalInteraction as a listener and will receive all mouse clicks and keyboard strokes that get into the MITK event mechanism. Tools are automatically unregistered from GlobalInteraction when no clients are registered to ToolManager (see RegisterClient()). \li ToolManager knows a set of "reference" DataNodes and a set of "working" DataNodes. The first application are segmentation tools, where the reference is the original image and the working data the (kind of) binary segmentation. However, ToolManager is implemented more generally, so that there could be other tools that work, e.g., with surfaces. \li Any "user/client" of ToolManager, i.e. every functionality that wants to use a tool, should call RegisterClient when the tools should be active. ToolManager keeps track of how many clients want it to be used, and when this count reaches zero, it unregistes the active Tool from GlobalInteraction. In "normal" settings, the functionality does not need to care about that if it uses a QmitkToolSelectionBox, which does exactly that when it is enabled/disabled. \li There is a set of events that are sent by ToolManager. At the moment these are TODO update documentation: - mitk::ToolReferenceDataChangedEvent whenever somebody calls SetReferenceData. Most of the time this actually means that the data has changed, but there might be cases where the same data is passed to SetReferenceData a second time, so don't rely on the assumption that something actually changed. - mitk::ToolSelectedEvent is sent when a (truly) different tool was activated. In reaction to this event you can ask for the active Tool using GetActiveTool or GetActiveToolID (where NULL or -1 indicate that NO tool is active at the moment). Design descisions: \li Not a singleton, because there could be two functionalities using tools, each one with different reference/working data. $Author$ */ class Segmentation_EXPORT ToolManager : public itk::Object { public: typedef std::vector ToolVectorType; typedef std::vector ToolVectorTypeConst; typedef std::vector DataVectorType; // has to be observed for delete events! typedef std::map NodeTagMapType; Message<> NodePropertiesChanged; Message<> NewNodesGenerated; Message1 NewNodeObjectsGenerated; Message<> ActiveToolChanged; Message<> ReferenceDataChanged; Message<> WorkingDataChanged; Message<> RoiDataChanged; Message1 ToolErrorMessage; Message1 GeneralToolMessage; mitkClassMacro(ToolManager, itk::Object); mitkNewMacro1Param(ToolManager, DataStorage*); /** \brief Gives you a list of all tools. This is const on purpose. */ const ToolVectorTypeConst GetTools(); int GetToolID( const Tool* tool ); /* \param id The tool of interest. Counting starts with 0. */ Tool* GetToolById(int id); /** \param id The tool to activate. Provide -1 for disabling any tools. Counting starts with 0. Registeres a listner for NodeRemoved event at DataStorage (see mitk::ToolManager::OnNodeRemoved). */ bool ActivateTool(int id); template int GetToolIdByToolType() { int id = 0; for ( ToolVectorType::iterator iter = m_Tools.begin(); iter != m_Tools.end(); ++iter, ++id ) { if ( dynamic_cast(iter->GetPointer()) ) { return id; } } return -1; } /** \return -1 for "No tool is active" */ int GetActiveToolID(); /** \return NULL for "No tool is active" */ Tool* GetActiveTool(); /* \brief Set a list of data/images as reference objects. */ void SetReferenceData(DataVectorType); /* \brief Set single data item/image as reference object. */ void SetReferenceData(DataNode*); /* \brief Set a list of data/images as working objects. */ void SetWorkingData(DataVectorType); /* \brief Set single data item/image as working object. */ void SetWorkingData(DataNode*); /* \brief Set a list of data/images as roi objects. */ void SetRoiData(DataVectorType); /* \brief Set a single data item/image as roi object. */ void SetRoiData(DataNode*); /* \brief Get the list of reference data. */ DataVectorType GetReferenceData(); /* \brief Get the current reference data. \warning If there is a list of items, this method will only return the first list item. */ DataNode* GetReferenceData(int); /* \brief Get the list of working data. */ DataVectorType GetWorkingData(); /* \brief Get the current working data. \warning If there is a list of items, this method will only return the first list item. */ DataNode* GetWorkingData(int); /* \brief Get the current roi data */ DataVectorType GetRoiData(); /* \brief Get the roi data at position idx */ DataNode* GetRoiData(int idx); DataStorage* GetDataStorage(); void SetDataStorage(DataStorage& storage); /* \brief Tell that someone is using tools. GUI elements should call this when they become active. This method increases an internal "client count". Tools are only registered to GlobalInteraction when this count is greater than 0. This is useful to automatically deactivate tools when you hide their GUI elements. */ void RegisterClient(); /* \brief Tell that someone is NOT using tools. GUI elements should call this when they become active. This method increases an internal "client count". Tools are only registered to GlobalInteraction when this count is greater than 0. This is useful to automatically deactivate tools when you hide their GUI elements. */ void UnregisterClient(); void OnOneOfTheReferenceDataDeletedConst(const itk::Object* caller, const itk::EventObject& e); void OnOneOfTheReferenceDataDeleted (itk::Object* caller, const itk::EventObject& e); void OnOneOfTheWorkingDataDeletedConst(const itk::Object* caller, const itk::EventObject& e); void OnOneOfTheWorkingDataDeleted (itk::Object* caller, const itk::EventObject& e); void OnOneOfTheRoiDataDeletedConst(const itk::Object* caller, const itk::EventObject& e); void OnOneOfTheRoiDataDeleted (itk::Object* caller, const itk::EventObject& e); /* \brief Connected to tool's messages This method just resends error messages coming from any of the tools. This way clients (GUIs) only have to observe one message. */ void OnToolErrorMessage(std::string s); void OnGeneralToolMessage(std::string s); protected: /** You may specify a list of tool "groups" that should be available for this ToolManager. Every Tool can report its group as a string. This constructor will try to find the tool's group inside the supplied string. If there is a match, the tool is accepted. Effectively, you can provide a human readable list like "default, lymphnodevolumetry, oldERISstuff". */ ToolManager(DataStorage* storage); // purposely hidden virtual ~ToolManager(); ToolVectorType m_Tools; Tool* m_ActiveTool; int m_ActiveToolID; DataVectorType m_ReferenceData; NodeTagMapType m_ReferenceDataObserverTags; DataVectorType m_WorkingData; NodeTagMapType m_WorkingDataObserverTags; DataVectorType m_RoiData; NodeTagMapType m_RoiDataObserverTags; int m_RegisteredClients; WeakPointer m_DataStorage; /// \brief Callback for NodeRemove events void OnNodeRemoved(const mitk::DataNode* node); private: //std::map m_DisplayInteractorConfigs; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkAdaptiveRegionGrowingTool.cpp b/Modules/Segmentation/Interactions/mitkAdaptiveRegionGrowingTool.cpp index 99a5a482f4..ecbce9a0e7 100644 --- a/Modules/Segmentation/Interactions/mitkAdaptiveRegionGrowingTool.cpp +++ b/Modules/Segmentation/Interactions/mitkAdaptiveRegionGrowingTool.cpp @@ -1,100 +1,100 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkAdaptiveRegionGrowingTool.h" #include "mitkToolManager.h" #include "mitkProperties.h" #include #include "mitkGlobalInteraction.h" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, AdaptiveRegionGrowingTool, "AdaptiveRegionGrowingTool"); } mitk::AdaptiveRegionGrowingTool::AdaptiveRegionGrowingTool() { m_PointSetNode = mitk::DataNode::New(); m_PointSetNode->GetPropertyList()->SetProperty("name", mitk::StringProperty::New("3D_Regiongrowing_Seedpoint")); m_PointSetNode->GetPropertyList()->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PointSet = mitk::PointSet::New(); m_PointSetNode->SetData(m_PointSet); m_SeedPointInteractor = mitk::PointSetInteractor::New("singlepointinteractor", m_PointSetNode); } mitk::AdaptiveRegionGrowingTool::~AdaptiveRegionGrowingTool() { } const char** mitk::AdaptiveRegionGrowingTool::GetXPM() const { return NULL; } const char* mitk::AdaptiveRegionGrowingTool::GetName() const { return "RegionGrowing"; } -mitk::ModuleResource mitk::AdaptiveRegionGrowingTool::GetIconResource() const +us::ModuleResource mitk::AdaptiveRegionGrowingTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("RegionGrowing_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("RegionGrowing_48x48.png"); return resource; } void mitk::AdaptiveRegionGrowingTool::Activated() { if (!GetDataStorage()->Exists(m_PointSetNode)) GetDataStorage()->Add(m_PointSetNode, GetWorkingData()); mitk::GlobalInteraction::GetInstance()->AddInteractor(m_SeedPointInteractor); } void mitk::AdaptiveRegionGrowingTool::Deactivated() { if (m_PointSet->GetPointSet()->GetNumberOfPoints() != 0) { mitk::Point3D point = m_PointSet->GetPoint(0); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, 0); m_PointSet->ExecuteOperation(doOp); } mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_SeedPointInteractor); GetDataStorage()->Remove(m_PointSetNode); } mitk::DataNode* mitk::AdaptiveRegionGrowingTool::GetReferenceData(){ return this->m_ToolManager->GetReferenceData(0); } mitk::DataStorage* mitk::AdaptiveRegionGrowingTool::GetDataStorage(){ return this->m_ToolManager->GetDataStorage(); } mitk::DataNode* mitk::AdaptiveRegionGrowingTool::GetWorkingData(){ return this->m_ToolManager->GetWorkingData(0); } mitk::DataNode::Pointer mitk::AdaptiveRegionGrowingTool::GetPointSetNode() { return m_PointSetNode; } diff --git a/Modules/Segmentation/Interactions/mitkAdaptiveRegionGrowingTool.h b/Modules/Segmentation/Interactions/mitkAdaptiveRegionGrowingTool.h index 74a73d9c69..ab42ec3cd4 100644 --- a/Modules/Segmentation/Interactions/mitkAdaptiveRegionGrowingTool.h +++ b/Modules/Segmentation/Interactions/mitkAdaptiveRegionGrowingTool.h @@ -1,78 +1,80 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkAdaptiveRegionGrowingTool_h_Included #define mitkAdaptiveRegionGrowingTool_h_Included #include "mitkCommon.h" #include "SegmentationExports.h" #include "mitkAutoSegmentationTool.h" #include "mitkDataStorage.h" #include "mitkPointSetInteractor.h" #include "mitkPointSet.h" +namespace us { class ModuleResource; +} namespace mitk { /** \brief Dummy Tool for AdaptiveRegionGrowingToolGUI to get Tool functionality for AdaptiveRegionGrowing. The actual logic is implemented in QmitkAdaptiveRegionGrowingToolGUI. \ingroup ToolManagerEtAl \sa mitk::Tool \sa QmitkInteractiveSegmentation */ class Segmentation_EXPORT AdaptiveRegionGrowingTool : public AutoSegmentationTool { public: mitkClassMacro(AdaptiveRegionGrowingTool, AutoSegmentationTool); itkNewMacro(AdaptiveRegionGrowingTool); virtual const char** GetXPM() const; virtual const char* GetName() const; - ModuleResource GetIconResource() const; + us::ModuleResource GetIconResource() const; virtual void Activated(); virtual void Deactivated(); virtual DataNode::Pointer GetPointSetNode(); mitk::DataNode* GetReferenceData(); mitk::DataNode* GetWorkingData(); mitk::DataStorage* GetDataStorage(); protected: AdaptiveRegionGrowingTool(); // purposely hidden virtual ~AdaptiveRegionGrowingTool(); private: PointSet::Pointer m_PointSet; PointSetInteractor::Pointer m_SeedPointInteractor; DataNode::Pointer m_PointSetNode; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkAddContourTool.cpp b/Modules/Segmentation/Interactions/mitkAddContourTool.cpp index 316ed994d4..7a84c6d43e 100644 --- a/Modules/Segmentation/Interactions/mitkAddContourTool.cpp +++ b/Modules/Segmentation/Interactions/mitkAddContourTool.cpp @@ -1,62 +1,63 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkAddContourTool.h" #include "mitkAddContourTool.xpm" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, AddContourTool, "Add tool"); } mitk::AddContourTool::AddContourTool() :ContourTool(1) { } mitk::AddContourTool::~AddContourTool() { } const char** mitk::AddContourTool::GetXPM() const { return mitkAddContourTool_xpm; } -mitk::ModuleResource mitk::AddContourTool::GetIconResource() const +us::ModuleResource mitk::AddContourTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Add_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Add_48x48.png"); return resource; } -mitk::ModuleResource mitk::AddContourTool::GetCursorIconResource() const +us::ModuleResource mitk::AddContourTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Add_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Add_Cursor_32x32.png"); return resource; } const char* mitk::AddContourTool::GetName() const { return "Add"; } diff --git a/Modules/Segmentation/Interactions/mitkAddContourTool.h b/Modules/Segmentation/Interactions/mitkAddContourTool.h index bdd637de1c..0bdc39e2bf 100644 --- a/Modules/Segmentation/Interactions/mitkAddContourTool.h +++ b/Modules/Segmentation/Interactions/mitkAddContourTool.h @@ -1,71 +1,73 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkAddContourTool_h_Included #define mitkAddContourTool_h_Included #include "mitkContourTool.h" #include "SegmentationExports.h" +namespace us { class ModuleResource; +} namespace mitk { /** \brief Fill the inside of a contour with 1 \sa ContourTool \ingroup Interaction \ingroup ToolManagerEtAl Fills a visible contour (from FeedbackContourTool) during mouse dragging. When the mouse button is released, AddContourTool tries to extract a slice from the working image and fill in the (filled) contour as a binary image. All inside pixels are set to 1. While holding the CTRL key, the contour changes color and the pixels on the inside would be filled with 0. \warning Only to be instantiated by mitk::ToolManager. $Author$ */ class Segmentation_EXPORT AddContourTool : public ContourTool { public: mitkClassMacro(AddContourTool, ContourTool); itkNewMacro(AddContourTool); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; protected: AddContourTool(); // purposely hidden virtual ~AddContourTool(); }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkBinaryThresholdTool.cpp b/Modules/Segmentation/Interactions/mitkBinaryThresholdTool.cpp index 54cf1221aa..f7d5b6fab8 100644 --- a/Modules/Segmentation/Interactions/mitkBinaryThresholdTool.cpp +++ b/Modules/Segmentation/Interactions/mitkBinaryThresholdTool.cpp @@ -1,333 +1,333 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBinaryThresholdTool.h" #include "mitkBinaryThresholdTool.xpm" #include "mitkToolManager.h" #include "mitkBoundingObjectToSegmentationFilter.h" #include #include "mitkLevelWindowProperty.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkOrganTypeProperty.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkDataStorage.h" #include "mitkRenderingManager.h" #include "mitkImageCast.h" #include "mitkImageAccessByItk.h" #include "mitkImageTimeSelector.h" #include #include #include "mitkPadImageFilter.h" #include "mitkMaskAndCutRoiImageFilter.h" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkGetModuleContext.h" +#include "usModule.h" +#include "usModuleResource.h" +#include "usGetModuleContext.h" namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, BinaryThresholdTool, "Thresholding tool"); } mitk::BinaryThresholdTool::BinaryThresholdTool() :m_SensibleMinimumThresholdValue(-100), m_SensibleMaximumThresholdValue(+100), m_CurrentThresholdValue(0.0), m_IsFloatImage(false) { this->SupportRoiOn(); m_ThresholdFeedbackNode = DataNode::New(); mitk::CoreObjectFactory::GetInstance()->SetDefaultProperties( m_ThresholdFeedbackNode ); m_ThresholdFeedbackNode->SetProperty( "color", ColorProperty::New(0.0, 1.0, 0.0) ); m_ThresholdFeedbackNode->SetProperty( "texture interpolation", BoolProperty::New(false) ); m_ThresholdFeedbackNode->SetProperty( "layer", IntProperty::New( 100 ) ); m_ThresholdFeedbackNode->SetProperty( "levelwindow", LevelWindowProperty::New( LevelWindow(100, 1) ) ); m_ThresholdFeedbackNode->SetProperty( "name", StringProperty::New("Thresholding feedback") ); m_ThresholdFeedbackNode->SetProperty( "opacity", FloatProperty::New(0.3) ); m_ThresholdFeedbackNode->SetProperty( "helper object", BoolProperty::New(true) ); } mitk::BinaryThresholdTool::~BinaryThresholdTool() { } const char** mitk::BinaryThresholdTool::GetXPM() const { return NULL; } -mitk::ModuleResource mitk::BinaryThresholdTool::GetIconResource() const +us::ModuleResource mitk::BinaryThresholdTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Threshold_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Threshold_48x48.png"); return resource; } const char* mitk::BinaryThresholdTool::GetName() const { return "Threshold"; } void mitk::BinaryThresholdTool::Activated() { m_ToolManager->RoiDataChanged += mitk::MessageDelegate(this, &mitk::BinaryThresholdTool::OnRoiDataChanged); m_OriginalImageNode = m_ToolManager->GetReferenceData(0); m_NodeForThresholding = m_OriginalImageNode; if ( m_NodeForThresholding.IsNotNull() ) { SetupPreviewNodeFor( m_NodeForThresholding ); } else { m_ToolManager->ActivateTool(-1); } } void mitk::BinaryThresholdTool::Deactivated() { m_ToolManager->RoiDataChanged -= mitk::MessageDelegate(this, &mitk::BinaryThresholdTool::OnRoiDataChanged); m_NodeForThresholding = NULL; m_OriginalImageNode = NULL; try { if (DataStorage* storage = m_ToolManager->GetDataStorage()) { storage->Remove( m_ThresholdFeedbackNode ); RenderingManager::GetInstance()->RequestUpdateAll(); } } catch(...) { // don't care } m_ThresholdFeedbackNode->SetData(NULL); } void mitk::BinaryThresholdTool::SetThresholdValue(double value) { if (m_ThresholdFeedbackNode.IsNotNull()) { m_CurrentThresholdValue = value; m_ThresholdFeedbackNode->SetProperty( "levelwindow", LevelWindowProperty::New( LevelWindow(m_CurrentThresholdValue, 0.001) ) ); RenderingManager::GetInstance()->RequestUpdateAll(); } } void mitk::BinaryThresholdTool::AcceptCurrentThresholdValue() { CreateNewSegmentationFromThreshold(m_NodeForThresholding); RenderingManager::GetInstance()->RequestUpdateAll(); m_ToolManager->ActivateTool(-1); } void mitk::BinaryThresholdTool::CancelThresholding() { m_ToolManager->ActivateTool(-1); } void mitk::BinaryThresholdTool::SetupPreviewNodeFor( DataNode* nodeForThresholding ) { if (nodeForThresholding) { Image::Pointer image = dynamic_cast( nodeForThresholding->GetData() ); Image::Pointer originalImage = dynamic_cast (m_OriginalImageNode->GetData()); if (image.IsNotNull()) { // initialize and a new node with the same image as our reference image // use the level window property of this image copy to display the result of a thresholding operation m_ThresholdFeedbackNode->SetData( image ); int layer(50); nodeForThresholding->GetIntProperty("layer", layer); m_ThresholdFeedbackNode->SetIntProperty("layer", layer+1); if (DataStorage* storage = m_ToolManager->GetDataStorage()) { if (storage->Exists(m_ThresholdFeedbackNode)) storage->Remove(m_ThresholdFeedbackNode); storage->Add( m_ThresholdFeedbackNode, m_OriginalImageNode ); } if (image.GetPointer() == originalImage.GetPointer()) { if ((originalImage->GetPixelType().GetPixelType() == itk::ImageIOBase::SCALAR) &&(originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT)) m_IsFloatImage = true; else m_IsFloatImage = false; m_SensibleMinimumThresholdValue = static_cast( originalImage->GetScalarValueMin() ); m_SensibleMaximumThresholdValue = static_cast( originalImage->GetScalarValueMax() ); } LevelWindowProperty::Pointer lwp = dynamic_cast( m_ThresholdFeedbackNode->GetProperty( "levelwindow" )); if (lwp && !m_IsFloatImage ) { m_CurrentThresholdValue = static_cast( lwp->GetLevelWindow().GetLevel() ); } else { m_CurrentThresholdValue = (m_SensibleMaximumThresholdValue + m_SensibleMinimumThresholdValue)/2; } IntervalBordersChanged.Send(m_SensibleMinimumThresholdValue, m_SensibleMaximumThresholdValue, m_IsFloatImage); ThresholdingValueChanged.Send(m_CurrentThresholdValue); } } } void mitk::BinaryThresholdTool::CreateNewSegmentationFromThreshold(DataNode* node) { if (node) { Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNotNull()) { DataNode::Pointer emptySegmentation = GetTargetSegmentationNode(); if (emptySegmentation) { // actually perform a thresholding and ask for an organ type for (unsigned int timeStep = 0; timeStep < image->GetTimeSteps(); ++timeStep) { try { ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput( image ); timeSelector->SetTimeNr( timeStep ); timeSelector->UpdateLargestPossibleRegion(); Image::Pointer image3D = timeSelector->GetOutput(); if (image3D->GetDimension() == 2) { AccessFixedDimensionByItk_2( image3D, ITKThresholding, 2, dynamic_cast(emptySegmentation->GetData()), timeStep ); } else { AccessFixedDimensionByItk_2( image3D, ITKThresholding, 3, dynamic_cast(emptySegmentation->GetData()), timeStep ); } } catch(...) { Tool::ErrorMessage("Error accessing single time steps of the original image. Cannot create segmentation."); } } if (m_OriginalImageNode.GetPointer() != m_NodeForThresholding.GetPointer()) { mitk::PadImageFilter::Pointer padFilter = mitk::PadImageFilter::New(); padFilter->SetInput(0, dynamic_cast (emptySegmentation->GetData())); padFilter->SetInput(1, dynamic_cast (m_OriginalImageNode->GetData())); padFilter->SetBinaryFilter(true); padFilter->SetUpperThreshold(1); padFilter->SetLowerThreshold(1); padFilter->Update(); emptySegmentation->SetData(padFilter->GetOutput()); } m_ToolManager->SetWorkingData( emptySegmentation ); m_ToolManager->GetWorkingData(0)->Modified(); } } } } template void mitk::BinaryThresholdTool::ITKThresholding( itk::Image* originalImage, Image* segmentation, unsigned int timeStep ) { ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput( segmentation ); timeSelector->SetTimeNr( timeStep ); timeSelector->UpdateLargestPossibleRegion(); Image::Pointer segmentation3D = timeSelector->GetOutput(); typedef itk::Image< Tool::DefaultSegmentationDataType, 3> SegmentationType; // this is sure for new segmentations SegmentationType::Pointer itkSegmentation; CastToItkImage( segmentation3D, itkSegmentation ); // iterate over original and segmentation typedef itk::ImageRegionConstIterator< itk::Image > InputIteratorType; typedef itk::ImageRegionIterator< SegmentationType > SegmentationIteratorType; InputIteratorType inputIterator( originalImage, originalImage->GetLargestPossibleRegion() ); SegmentationIteratorType outputIterator( itkSegmentation, itkSegmentation->GetLargestPossibleRegion() ); inputIterator.GoToBegin(); outputIterator.GoToBegin(); while (!outputIterator.IsAtEnd()) { if ( inputIterator.Get() >= m_CurrentThresholdValue ) outputIterator.Set( 1 ); else outputIterator.Set( 0 ); ++inputIterator; ++outputIterator; } } void mitk::BinaryThresholdTool::OnRoiDataChanged() { mitk::DataNode::Pointer node = m_ToolManager->GetRoiData(0); if (node.IsNotNull()) { mitk::Image::Pointer image = dynamic_cast (m_NodeForThresholding->GetData()); if (image.IsNull()) return; mitk::MaskAndCutRoiImageFilter::Pointer roiFilter = mitk::MaskAndCutRoiImageFilter::New(); roiFilter->SetInput(image); roiFilter->SetRegionOfInterest(node->GetData()); roiFilter->Update(); mitk::DataNode::Pointer tmpNode = mitk::DataNode::New(); mitk::Image::Pointer tmpImage = roiFilter->GetOutput(); tmpNode->SetData(tmpImage); m_SensibleMaximumThresholdValue = static_cast (roiFilter->GetMaxValue()); m_SensibleMinimumThresholdValue = static_cast (roiFilter->GetMinValue()); SetupPreviewNodeFor( tmpNode ); m_NodeForThresholding = tmpNode; return; } else { this->SetupPreviewNodeFor(m_OriginalImageNode); m_NodeForThresholding = m_OriginalImageNode; return; } } diff --git a/Modules/Segmentation/Interactions/mitkBinaryThresholdTool.h b/Modules/Segmentation/Interactions/mitkBinaryThresholdTool.h index 0041c3c2bf..1f6861e0fa 100644 --- a/Modules/Segmentation/Interactions/mitkBinaryThresholdTool.h +++ b/Modules/Segmentation/Interactions/mitkBinaryThresholdTool.h @@ -1,91 +1,93 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkBinaryThresholdTool_h_Included #define mitkBinaryThresholdTool_h_Included #include "mitkCommon.h" #include "SegmentationExports.h" #include "mitkAutoSegmentationTool.h" #include "mitkDataNode.h" #include +namespace us { class ModuleResource; +} namespace mitk { /** \brief Calculates the segmented volumes for binary images. \ingroup ToolManagerEtAl \sa mitk::Tool \sa QmitkInteractiveSegmentation Last contributor: $Author$ */ class Segmentation_EXPORT BinaryThresholdTool : public AutoSegmentationTool { public: Message3 IntervalBordersChanged; Message1 ThresholdingValueChanged; mitkClassMacro(BinaryThresholdTool, AutoSegmentationTool); itkNewMacro(BinaryThresholdTool); virtual const char** GetXPM() const; - ModuleResource GetIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; virtual void Activated(); virtual void Deactivated(); virtual void SetThresholdValue(double value); virtual void AcceptCurrentThresholdValue(); virtual void CancelThresholding(); protected: BinaryThresholdTool(); // purposely hidden virtual ~BinaryThresholdTool(); void SetupPreviewNodeFor( DataNode* nodeForThresholding ); void CreateNewSegmentationFromThreshold(DataNode* node); void OnRoiDataChanged(); template void ITKThresholding( itk::Image* originalImage, mitk::Image* segmentation, unsigned int timeStep ); DataNode::Pointer m_ThresholdFeedbackNode; DataNode::Pointer m_OriginalImageNode; DataNode::Pointer m_NodeForThresholding; double m_SensibleMinimumThresholdValue; double m_SensibleMaximumThresholdValue; double m_CurrentThresholdValue; bool m_IsFloatImage; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkBinaryThresholdULTool.cpp b/Modules/Segmentation/Interactions/mitkBinaryThresholdULTool.cpp index ef77191bb3..d7c8529512 100644 --- a/Modules/Segmentation/Interactions/mitkBinaryThresholdULTool.cpp +++ b/Modules/Segmentation/Interactions/mitkBinaryThresholdULTool.cpp @@ -1,328 +1,328 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBinaryThresholdULTool.h" #include "mitkBinaryThresholdULTool.xpm" #include "mitkToolManager.h" #include "mitkLevelWindowProperty.h" #include "mitkColorProperty.h" #include "mitkProperties.h" #include "mitkDataStorage.h" #include "mitkRenderingManager.h" #include "mitkImageCast.h" #include "mitkImageAccessByItk.h" #include "mitkImageTimeSelector.h" #include #include #include "mitkMaskAndCutRoiImageFilter.h" #include "mitkPadImageFilter.h" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkGetModuleContext.h" -#include "mitkModuleContext.h" +#include "usModule.h" +#include "usModuleResource.h" +#include "usGetModuleContext.h" +#include "usModuleContext.h" namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, BinaryThresholdULTool, "ThresholdingUL tool"); } mitk::BinaryThresholdULTool::BinaryThresholdULTool() :m_SensibleMinimumThresholdValue(-100), m_SensibleMaximumThresholdValue(+100), m_CurrentLowerThresholdValue(1), m_CurrentUpperThresholdValue(1) { this->SupportRoiOn(); m_ThresholdFeedbackNode = DataNode::New(); m_ThresholdFeedbackNode->SetProperty( "color", ColorProperty::New(0.0, 1.0, 0.0) ); m_ThresholdFeedbackNode->SetProperty( "name", StringProperty::New("Thresholding feedback") ); m_ThresholdFeedbackNode->SetProperty( "opacity", FloatProperty::New(0.3) ); m_ThresholdFeedbackNode->SetProperty("binary", BoolProperty::New(true)); m_ThresholdFeedbackNode->SetProperty( "helper object", BoolProperty::New(true) ); } mitk::BinaryThresholdULTool::~BinaryThresholdULTool() { } const char** mitk::BinaryThresholdULTool::GetXPM() const { return NULL; } -mitk::ModuleResource mitk::BinaryThresholdULTool::GetIconResource() const +us::ModuleResource mitk::BinaryThresholdULTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("TwoThresholds_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("TwoThresholds_48x48.png"); return resource; } const char* mitk::BinaryThresholdULTool::GetName() const { return "Two Thresholds"; } void mitk::BinaryThresholdULTool::Activated() { m_ToolManager->RoiDataChanged += mitk::MessageDelegate(this, &mitk::BinaryThresholdULTool::OnRoiDataChanged); m_OriginalImageNode = m_ToolManager->GetReferenceData(0); m_NodeForThresholding = m_OriginalImageNode; if ( m_NodeForThresholding.IsNotNull() ) { SetupPreviewNode(); } else { m_ToolManager->ActivateTool(-1); } } void mitk::BinaryThresholdULTool::Deactivated() { m_ToolManager->RoiDataChanged -= mitk::MessageDelegate(this, &mitk::BinaryThresholdULTool::OnRoiDataChanged); m_NodeForThresholding = NULL; m_OriginalImageNode = NULL; try { if (DataStorage* storage = m_ToolManager->GetDataStorage()) { storage->Remove( m_ThresholdFeedbackNode ); RenderingManager::GetInstance()->RequestUpdateAll(); } } catch(...) { // don't care } m_ThresholdFeedbackNode->SetData(NULL); } void mitk::BinaryThresholdULTool::SetThresholdValues(int lower, int upper) { if (m_ThresholdFeedbackNode.IsNotNull()) { m_CurrentLowerThresholdValue = lower; m_CurrentUpperThresholdValue = upper; UpdatePreview(); } } void mitk::BinaryThresholdULTool::AcceptCurrentThresholdValue() { CreateNewSegmentationFromThreshold(m_NodeForThresholding); RenderingManager::GetInstance()->RequestUpdateAll(); m_ToolManager->ActivateTool(-1); } void mitk::BinaryThresholdULTool::CancelThresholding() { m_ToolManager->ActivateTool(-1); } void mitk::BinaryThresholdULTool::SetupPreviewNode() { if (m_NodeForThresholding.IsNotNull()) { Image::Pointer image = dynamic_cast( m_NodeForThresholding->GetData() ); Image::Pointer originalImage = dynamic_cast (m_OriginalImageNode->GetData()); if (image.IsNotNull()) { // initialize and a new node with the same image as our reference image // use the level window property of this image copy to display the result of a thresholding operation m_ThresholdFeedbackNode->SetData( image ); int layer(50); m_NodeForThresholding->GetIntProperty("layer", layer); m_ThresholdFeedbackNode->SetIntProperty("layer", layer+1); if (DataStorage* ds = m_ToolManager->GetDataStorage()) { if (!ds->Exists(m_ThresholdFeedbackNode)) ds->Add( m_ThresholdFeedbackNode, m_OriginalImageNode ); } if (image.GetPointer() == originalImage.GetPointer()) { m_SensibleMinimumThresholdValue = static_cast( originalImage->GetScalarValueMin() ); m_SensibleMaximumThresholdValue = static_cast( originalImage->GetScalarValueMax() ); } m_CurrentLowerThresholdValue = (m_SensibleMaximumThresholdValue + m_SensibleMinimumThresholdValue) / 3; m_CurrentUpperThresholdValue = 2*m_CurrentLowerThresholdValue; IntervalBordersChanged.Send(m_SensibleMinimumThresholdValue, m_SensibleMaximumThresholdValue); ThresholdingValuesChanged.Send(m_CurrentLowerThresholdValue, m_CurrentUpperThresholdValue); } } } void mitk::BinaryThresholdULTool::CreateNewSegmentationFromThreshold(DataNode* node) { if (node) { Image::Pointer image = dynamic_cast( m_NodeForThresholding->GetData() ); if (image.IsNotNull()) { // create a new image of the same dimensions and smallest possible pixel type DataNode::Pointer emptySegmentation = GetTargetSegmentationNode(); if (emptySegmentation) { // actually perform a thresholding and ask for an organ type for (unsigned int timeStep = 0; timeStep < image->GetTimeSteps(); ++timeStep) { try { ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput( image ); timeSelector->SetTimeNr( timeStep ); timeSelector->UpdateLargestPossibleRegion(); Image::Pointer image3D = timeSelector->GetOutput(); AccessFixedDimensionByItk_2( image3D, ITKThresholding, 3, dynamic_cast(emptySegmentation->GetData()), timeStep ); } catch(...) { Tool::ErrorMessage("Error accessing single time steps of the original image. Cannot create segmentation."); } } //since we are maybe working on a smaller image, pad it to the size of the original image if (m_OriginalImageNode.GetPointer() != m_NodeForThresholding.GetPointer()) { mitk::PadImageFilter::Pointer padFilter = mitk::PadImageFilter::New(); padFilter->SetInput(0, dynamic_cast (emptySegmentation->GetData())); padFilter->SetInput(1, dynamic_cast (m_OriginalImageNode->GetData())); padFilter->SetBinaryFilter(true); padFilter->SetUpperThreshold(1); padFilter->SetLowerThreshold(1); padFilter->Update(); emptySegmentation->SetData(padFilter->GetOutput()); } m_ToolManager->SetWorkingData( emptySegmentation ); m_ToolManager->GetWorkingData(0)->Modified(); } } } } template void mitk::BinaryThresholdULTool::ITKThresholding( itk::Image* originalImage, Image* segmentation, unsigned int timeStep ) { ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput( segmentation ); timeSelector->SetTimeNr( timeStep ); timeSelector->UpdateLargestPossibleRegion(); Image::Pointer segmentation3D = timeSelector->GetOutput(); typedef itk::Image< Tool::DefaultSegmentationDataType, 3> SegmentationType; // this is sure for new segmentations SegmentationType::Pointer itkSegmentation; CastToItkImage( segmentation3D, itkSegmentation ); // iterate over original and segmentation typedef itk::ImageRegionConstIterator< itk::Image > InputIteratorType; typedef itk::ImageRegionIterator< SegmentationType > SegmentationIteratorType; InputIteratorType inputIterator( originalImage, originalImage->GetLargestPossibleRegion() ); SegmentationIteratorType outputIterator( itkSegmentation, itkSegmentation->GetLargestPossibleRegion() ); inputIterator.GoToBegin(); outputIterator.GoToBegin(); while (!outputIterator.IsAtEnd()) { if ( (signed)inputIterator.Get() >= m_CurrentLowerThresholdValue && (signed)inputIterator.Get() <= m_CurrentUpperThresholdValue ) { outputIterator.Set( 1 ); } else { outputIterator.Set( 0 ); } ++inputIterator; ++outputIterator; } } void mitk::BinaryThresholdULTool::OnRoiDataChanged() { mitk::DataNode::Pointer node = m_ToolManager->GetRoiData(0); if (node.IsNotNull()) { mitk::MaskAndCutRoiImageFilter::Pointer roiFilter = mitk::MaskAndCutRoiImageFilter::New(); mitk::Image::Pointer image = dynamic_cast (m_NodeForThresholding->GetData()); if (image.IsNull()) return; roiFilter->SetInput(image); roiFilter->SetRegionOfInterest(node->GetData()); roiFilter->Update(); mitk::DataNode::Pointer tmpNode = mitk::DataNode::New(); tmpNode->SetData(roiFilter->GetOutput()); m_SensibleMinimumThresholdValue = static_cast( roiFilter->GetMinValue()); m_SensibleMaximumThresholdValue = static_cast( roiFilter->GetMaxValue()); m_NodeForThresholding = tmpNode; } else m_NodeForThresholding = m_OriginalImageNode; this->SetupPreviewNode(); this->UpdatePreview(); } void mitk::BinaryThresholdULTool::UpdatePreview() { typedef itk::Image ImageType; typedef itk::Image SegmentationType; typedef itk::BinaryThresholdImageFilter ThresholdFilterType; mitk::Image::Pointer thresholdimage = dynamic_cast (m_NodeForThresholding->GetData()); if(thresholdimage) { ImageType::Pointer itkImage = ImageType::New(); CastToItkImage(thresholdimage, itkImage); ThresholdFilterType::Pointer filter = ThresholdFilterType::New(); filter->SetInput(itkImage); filter->SetLowerThreshold(m_CurrentLowerThresholdValue); filter->SetUpperThreshold(m_CurrentUpperThresholdValue); filter->SetInsideValue(1); filter->SetOutsideValue(0); filter->Update(); mitk::Image::Pointer new_image = mitk::Image::New(); CastToMitkImage(filter->GetOutput(), new_image); m_ThresholdFeedbackNode->SetData(new_image); } RenderingManager::GetInstance()->RequestUpdateAll(); } diff --git a/Modules/Segmentation/Interactions/mitkBinaryThresholdULTool.h b/Modules/Segmentation/Interactions/mitkBinaryThresholdULTool.h index 6b7a0deaf0..64da3f0bd6 100644 --- a/Modules/Segmentation/Interactions/mitkBinaryThresholdULTool.h +++ b/Modules/Segmentation/Interactions/mitkBinaryThresholdULTool.h @@ -1,98 +1,100 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkBinaryThresholdULTool_h_Included #define mitkBinaryThresholdULTool_h_Included #include "mitkCommon.h" #include "SegmentationExports.h" #include "mitkAutoSegmentationTool.h" #include "mitkDataNode.h" #include #include +namespace us { class ModuleResource; +} namespace mitk { /** \brief Calculates the segmented volumes for binary images. \ingroup ToolManagerEtAl \sa mitk::Tool \sa QmitkInteractiveSegmentation Last contributor: $Author$ */ class Segmentation_EXPORT BinaryThresholdULTool : public AutoSegmentationTool { public: Message2 IntervalBordersChanged; Message2 ThresholdingValuesChanged; mitkClassMacro(BinaryThresholdULTool, AutoSegmentationTool); itkNewMacro(BinaryThresholdULTool); virtual const char** GetXPM() const; - ModuleResource GetIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; virtual void Activated(); virtual void Deactivated(); virtual void SetThresholdValues(int lower, int upper); virtual void AcceptCurrentThresholdValue(); virtual void CancelThresholding(); protected: BinaryThresholdULTool(); // purposely hidden virtual ~BinaryThresholdULTool(); void SetupPreviewNode(); void CreateNewSegmentationFromThreshold(DataNode* node); void OnRoiDataChanged(); void UpdatePreview(); template void ITKThresholding( itk::Image* originalImage, mitk::Image* segmentation, unsigned int timeStep ); DataNode::Pointer m_ThresholdFeedbackNode; DataNode::Pointer m_OriginalImageNode; DataNode::Pointer m_NodeForThresholding; mitk::ScalarType m_SensibleMinimumThresholdValue; mitk::ScalarType m_SensibleMaximumThresholdValue; mitk::ScalarType m_CurrentLowerThresholdValue; mitk::ScalarType m_CurrentUpperThresholdValue; typedef itk::Image ImageType; typedef itk::Image< Tool::DefaultSegmentationDataType, 3> SegmentationType; // this is sure for new segmentations typedef itk::BinaryThresholdImageFilter ThresholdFilterType; ThresholdFilterType::Pointer m_ThresholdFilter; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkCorrectorTool2D.cpp b/Modules/Segmentation/Interactions/mitkCorrectorTool2D.cpp index 11b69c73e9..fa2250768e 100644 --- a/Modules/Segmentation/Interactions/mitkCorrectorTool2D.cpp +++ b/Modules/Segmentation/Interactions/mitkCorrectorTool2D.cpp @@ -1,185 +1,186 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCorrectorTool2D.h" #include "mitkCorrectorAlgorithm.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include "mitkCorrectorTool2D.xpm" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, CorrectorTool2D, "Correction tool"); } mitk::CorrectorTool2D::CorrectorTool2D(int paintingPixelValue) :FeedbackContourTool("PressMoveRelease"), m_PaintingPixelValue(paintingPixelValue) { // great magic numbers CONNECT_ACTION( 80, OnMousePressed ); CONNECT_ACTION( 90, OnMouseMoved ); CONNECT_ACTION( 42, OnMouseReleased ); GetFeedbackContour()->SetIsClosed( false ); // don't close the contour to a polygon } mitk::CorrectorTool2D::~CorrectorTool2D() { } const char** mitk::CorrectorTool2D::GetXPM() const { return mitkCorrectorTool2D_xpm; } -mitk::ModuleResource mitk::CorrectorTool2D::GetIconResource() const +us::ModuleResource mitk::CorrectorTool2D::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Correction_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Correction_48x48.png"); return resource; } -mitk::ModuleResource mitk::CorrectorTool2D::GetCursorIconResource() const +us::ModuleResource mitk::CorrectorTool2D::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Correction_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Correction_Cursor_32x32.png"); return resource; } const char* mitk::CorrectorTool2D::GetName() const { return "Correction"; } void mitk::CorrectorTool2D::Activated() { Superclass::Activated(); } void mitk::CorrectorTool2D::Deactivated() { Superclass::Deactivated(); } bool mitk::CorrectorTool2D::OnMousePressed (Action* action, const StateEvent* stateEvent) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; m_LastEventSender = positionEvent->GetSender(); m_LastEventSlice = m_LastEventSender->GetSlice(); if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false; int timestep = positionEvent->GetSender()->GetTimeStep(); ContourModel* contour = FeedbackContourTool::GetFeedbackContour(); contour->Clear(); contour->Expand(timestep + 1); contour->SetIsClosed(false, timestep); contour->AddVertex( positionEvent->GetWorldPosition(), timestep ); FeedbackContourTool::SetFeedbackContourVisible(true); return true; } bool mitk::CorrectorTool2D::OnMouseMoved (Action* action, const StateEvent* stateEvent) { if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false; const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; int timestep = positionEvent->GetSender()->GetTimeStep(); ContourModel* contour = FeedbackContourTool::GetFeedbackContour(); contour->AddVertex( positionEvent->GetWorldPosition(), timestep ); assert( positionEvent->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); return true; } bool mitk::CorrectorTool2D::OnMouseReleased(Action* action, const StateEvent* stateEvent) { // 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's working image corresponds to that FeedbackContourTool::SetFeedbackContourVisible(false); const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; assert( positionEvent->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false; DataNode* workingNode( m_ToolManager->GetWorkingData(0) ); if (!workingNode) return false; Image* image = dynamic_cast(workingNode->GetData()); const PlaneGeometry* planeGeometry( dynamic_cast (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) ); if ( !image || !planeGeometry ) return false; // 2. Slice is known, now we try to get it as a 2D image and project the contour into index coordinates of this slice m_WorkingSlice = FeedbackContourTool::GetAffectedImageSliceAs2DImage( positionEvent, image ); if ( m_WorkingSlice.IsNull() ) { MITK_ERROR << "Unable to extract slice." << std::endl; return false; } int timestep = positionEvent->GetSender()->GetTimeStep(); mitk::ContourModel::Pointer singleTimestepContour = mitk::ContourModel::New(); mitk::ContourModel::VertexIterator it = FeedbackContourTool::GetFeedbackContour()->Begin(timestep); mitk::ContourModel::VertexIterator end = FeedbackContourTool::GetFeedbackContour()->End(timestep); while(it!=end) { singleTimestepContour->AddVertex((*it)->Coordinates); it++; } CorrectorAlgorithm::Pointer algorithm = CorrectorAlgorithm::New(); algorithm->SetInput( m_WorkingSlice ); algorithm->SetContour( singleTimestepContour ); try { algorithm->UpdateLargestPossibleRegion(); } catch ( std::exception& e ) { MITK_ERROR << "Caught exception '" << e.what() << "'" << std::endl; } mitk::Image::Pointer resultSlice = mitk::Image::New(); resultSlice->Initialize(algorithm->GetOutput()); resultSlice->SetVolume(algorithm->GetOutput()->GetData()); this->WriteBackSegmentationResult(positionEvent, resultSlice); return true; } diff --git a/Modules/Segmentation/Interactions/mitkCorrectorTool2D.h b/Modules/Segmentation/Interactions/mitkCorrectorTool2D.h index 0ba2cb2eea..7d95d3b510 100644 --- a/Modules/Segmentation/Interactions/mitkCorrectorTool2D.h +++ b/Modules/Segmentation/Interactions/mitkCorrectorTool2D.h @@ -1,85 +1,87 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkCorrectorTool2D_h_Included #define mitkCorrectorTool2D_h_Included #include "mitkCommon.h" #include "SegmentationExports.h" #include "mitkFeedbackContourTool.h" +namespace us { class ModuleResource; +} namespace mitk { class Image; /** \brief Corrector tool for 2D binary segmentations \sa FeedbackContourTool \sa ExtractImageFilter \sa OverwriteSliceImageFilter \ingroup Interaction \ingroup ToolManagerEtAl Lets the user draw a (multi-point) line and intelligently decides what to do. The underlying algorithm tests if the line begins and ends inside or outside a segmentation and either adds or subtracts a piece of segmentation. Algorithm is implemented in CorrectorAlgorithm (so that it could be reimplemented in a more modern fashion some time). \warning Only to be instantiated by mitk::ToolManager. $Author$ */ class Segmentation_EXPORT CorrectorTool2D : public FeedbackContourTool { public: mitkClassMacro(CorrectorTool2D, FeedbackContourTool); itkNewMacro(CorrectorTool2D); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; protected: CorrectorTool2D(int paintingPixelValue = 1); // purposely hidden virtual ~CorrectorTool2D(); virtual void Activated(); virtual void Deactivated(); virtual bool OnMousePressed (Action*, const StateEvent*); virtual bool OnMouseMoved (Action*, const StateEvent*); virtual bool OnMouseReleased(Action*, const StateEvent*); int m_PaintingPixelValue; Image::Pointer m_WorkingSlice; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkDrawPaintbrushTool.cpp b/Modules/Segmentation/Interactions/mitkDrawPaintbrushTool.cpp index 70ad899774..bde5aadaa9 100644 --- a/Modules/Segmentation/Interactions/mitkDrawPaintbrushTool.cpp +++ b/Modules/Segmentation/Interactions/mitkDrawPaintbrushTool.cpp @@ -1,62 +1,63 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkDrawPaintbrushTool.h" #include "mitkDrawPaintbrushTool.xpm" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, DrawPaintbrushTool, "Paintbrush drawing tool"); } mitk::DrawPaintbrushTool::DrawPaintbrushTool() :PaintbrushTool(1) { } mitk::DrawPaintbrushTool::~DrawPaintbrushTool() { } const char** mitk::DrawPaintbrushTool::GetXPM() const { return mitkDrawPaintbrushTool_xpm; } -mitk::ModuleResource mitk::DrawPaintbrushTool::GetIconResource() const +us::ModuleResource mitk::DrawPaintbrushTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Paint_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Paint_48x48.png"); return resource; } -mitk::ModuleResource mitk::DrawPaintbrushTool::GetCursorIconResource() const +us::ModuleResource mitk::DrawPaintbrushTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Paint_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Paint_Cursor_32x32.png"); return resource; } const char* mitk::DrawPaintbrushTool::GetName() const { return "Paint"; } diff --git a/Modules/Segmentation/Interactions/mitkDrawPaintbrushTool.h b/Modules/Segmentation/Interactions/mitkDrawPaintbrushTool.h index 0b71f8d98b..383962690d 100644 --- a/Modules/Segmentation/Interactions/mitkDrawPaintbrushTool.h +++ b/Modules/Segmentation/Interactions/mitkDrawPaintbrushTool.h @@ -1,68 +1,70 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkPaintContourTool_h_Included #define mitkPaintContourTool_h_Included #include "mitkPaintbrushTool.h" #include "SegmentationExports.h" +namespace us { class ModuleResource; +} namespace mitk { /** \brief Paintbrush tool for InteractiveSegmentation \sa FeedbackContourTool \sa ExtractImageFilter \sa OverwriteSliceImageFilter \ingroup Interaction \ingroup ToolManagerEtAl Simple paintbrush drawing tool. Right now there are only circular pens of varying size. This class specified only the drawing "color" for the super class PaintbrushTool. \warning Only to be instantiated by mitk::ToolManager. $Author: maleike $ */ class Segmentation_EXPORT DrawPaintbrushTool : public PaintbrushTool { public: mitkClassMacro(DrawPaintbrushTool, PaintbrushTool); itkNewMacro(DrawPaintbrushTool); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; protected: DrawPaintbrushTool(); // purposely hidden virtual ~DrawPaintbrushTool(); }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.cpp b/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.cpp index 2c79a783fd..15723d0f60 100644 --- a/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.cpp +++ b/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.cpp @@ -1,63 +1,64 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkErasePaintbrushTool.h" #include "mitkErasePaintbrushTool.xpm" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, ErasePaintbrushTool, "Paintbrush erasing tool"); } mitk::ErasePaintbrushTool::ErasePaintbrushTool() :PaintbrushTool(0) { FeedbackContourTool::SetFeedbackContourColor( 1.0, 0.0, 0.0 ); } mitk::ErasePaintbrushTool::~ErasePaintbrushTool() { } const char** mitk::ErasePaintbrushTool::GetXPM() const { return mitkErasePaintbrushTool_xpm; } -mitk::ModuleResource mitk::ErasePaintbrushTool::GetIconResource() const +us::ModuleResource mitk::ErasePaintbrushTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Wipe_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Wipe_48x48.png"); return resource; } -mitk::ModuleResource mitk::ErasePaintbrushTool::GetCursorIconResource() const +us::ModuleResource mitk::ErasePaintbrushTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Wipe_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Wipe_Cursor_32x32.png"); return resource; } const char* mitk::ErasePaintbrushTool::GetName() const { return "Wipe"; } diff --git a/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.h b/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.h index a9bafbf0a9..ec8ba1567d 100644 --- a/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.h +++ b/Modules/Segmentation/Interactions/mitkErasePaintbrushTool.h @@ -1,68 +1,70 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkErasePaintbrushTool_h_Included #define mitkErasePaintbrushTool_h_Included #include "mitkPaintbrushTool.h" #include "SegmentationExports.h" +namespace us { class ModuleResource; +} namespace mitk { /** \brief Paintbrush tool for InteractiveSegmentation \sa FeedbackContourTool \sa ExtractImageFilter \sa OverwriteSliceImageFilter \ingroup Interaction \ingroup ToolManagerEtAl Simple paintbrush drawing tool. Right now there are only circular pens of varying size. This class specified only the drawing "color" for the super class PaintbrushTool. \warning Only to be instantiated by mitk::ToolManager. $Author: maleike $ */ class Segmentation_EXPORT ErasePaintbrushTool : public PaintbrushTool { public: mitkClassMacro(ErasePaintbrushTool, PaintbrushTool); itkNewMacro(ErasePaintbrushTool); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; protected: ErasePaintbrushTool(); // purposely hidden virtual ~ErasePaintbrushTool(); }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkEraseRegionTool.cpp b/Modules/Segmentation/Interactions/mitkEraseRegionTool.cpp index 7aa6f279c0..1ada1853e3 100644 --- a/Modules/Segmentation/Interactions/mitkEraseRegionTool.cpp +++ b/Modules/Segmentation/Interactions/mitkEraseRegionTool.cpp @@ -1,63 +1,64 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkEraseRegionTool.h" #include "mitkEraseRegionTool.xpm" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, EraseRegionTool, "Erase tool"); } mitk::EraseRegionTool::EraseRegionTool() :SetRegionTool(0) { FeedbackContourTool::SetFeedbackContourColor( 1.0, 1.0, 0.0 ); } mitk::EraseRegionTool::~EraseRegionTool() { } const char** mitk::EraseRegionTool::GetXPM() const { return mitkEraseRegionTool_xpm; } -mitk::ModuleResource mitk::EraseRegionTool::GetIconResource() const +us::ModuleResource mitk::EraseRegionTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Erase_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Erase_48x48.png"); return resource; } -mitk::ModuleResource mitk::EraseRegionTool::GetCursorIconResource() const +us::ModuleResource mitk::EraseRegionTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Erase_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Erase_Cursor_32x32.png"); return resource; } const char* mitk::EraseRegionTool::GetName() const { return "Erase"; } diff --git a/Modules/Segmentation/Interactions/mitkEraseRegionTool.h b/Modules/Segmentation/Interactions/mitkEraseRegionTool.h index 9fe310aabf..4dab9d88fc 100644 --- a/Modules/Segmentation/Interactions/mitkEraseRegionTool.h +++ b/Modules/Segmentation/Interactions/mitkEraseRegionTool.h @@ -1,67 +1,69 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkEraseRegionTool_h_Included #define mitkEraseRegionTool_h_Included #include "mitkSetRegionTool.h" #include "SegmentationExports.h" +namespace us { class ModuleResource; +} namespace mitk { /** \brief Fill the inside of a contour with 1 \sa SetRegionTool \ingroup Interaction \ingroup ToolManagerEtAl Finds the outer contour of a shape in 2D (possibly including holes) and sets all the inside pixels to 0 (erasing a segmentation). \warning Only to be instantiated by mitk::ToolManager. $Author$ */ class Segmentation_EXPORT EraseRegionTool : public SetRegionTool { public: mitkClassMacro(EraseRegionTool, SetRegionTool); itkNewMacro(EraseRegionTool); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; protected: EraseRegionTool(); // purposely hidden virtual ~EraseRegionTool(); }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkFastMarchingTool.cpp b/Modules/Segmentation/Interactions/mitkFastMarchingTool.cpp index 23234b6c0d..fd808965b9 100644 --- a/Modules/Segmentation/Interactions/mitkFastMarchingTool.cpp +++ b/Modules/Segmentation/Interactions/mitkFastMarchingTool.cpp @@ -1,468 +1,469 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFastMarchingTool.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include "mitkInteractionConst.h" #include "itkOrImageFilter.h" #include "mitkImageTimeSelector.h" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, FastMarchingTool, "FastMarching2D tool"); } mitk::FastMarchingTool::FastMarchingTool() :FeedbackContourTool("PressMoveReleaseAndPointSetting"), m_NeedUpdate(true), m_CurrentTimeStep(0), m_LowerThreshold(0), m_UpperThreshold(200), m_StoppingValue(100), m_Sigma(1.0), m_Alpha(-0.5), m_Beta(3.0), m_PositionEvent(0) { CONNECT_ACTION( AcADDPOINTRMB, OnAddPoint ); CONNECT_ACTION( AcADDPOINT, OnAddPoint ); CONNECT_ACTION( AcREMOVEPOINT, OnDelete ); } mitk::FastMarchingTool::~FastMarchingTool() { if (this->m_SmoothFilter.IsNotNull()) this->m_SmoothFilter->RemoveAllObservers(); if (this->m_SigmoidFilter.IsNotNull()) this->m_SigmoidFilter->RemoveAllObservers(); if (this->m_GradientMagnitudeFilter.IsNotNull()) this->m_GradientMagnitudeFilter->RemoveAllObservers(); if (this->m_FastMarchingFilter.IsNotNull()) this->m_FastMarchingFilter->RemoveAllObservers(); } float mitk::FastMarchingTool::CanHandleEvent( StateEvent const *stateEvent) const { float returnValue = Superclass::CanHandleEvent(stateEvent); //we can handle delete if(stateEvent->GetId() == 12 ) { returnValue = 1.0; } return returnValue; } const char** mitk::FastMarchingTool::GetXPM() const { return NULL;//mitkFastMarchingTool_xpm; } -mitk::ModuleResource mitk::FastMarchingTool::GetIconResource() const +us::ModuleResource mitk::FastMarchingTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("FastMarching_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("FastMarching_48x48.png"); return resource; } -mitk::ModuleResource mitk::FastMarchingTool::GetCursorIconResource() const +us::ModuleResource mitk::FastMarchingTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("FastMarching_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("FastMarching_Cursor_32x32.png"); return resource; } const char* mitk::FastMarchingTool::GetName() const { return "FastMarching2D"; } void mitk::FastMarchingTool::BuildITKPipeline() { m_ReferenceImageSliceAsITK = InternalImageType::New(); m_ReferenceImageSlice = GetAffectedReferenceSlice( m_PositionEvent ); CastToItkImage(m_ReferenceImageSlice, m_ReferenceImageSliceAsITK); m_ProgressCommand = mitk::ToolCommand::New(); m_SmoothFilter = SmoothingFilterType::New(); m_SmoothFilter->SetInput( m_ReferenceImageSliceAsITK ); m_SmoothFilter->SetTimeStep( 0.05 ); m_SmoothFilter->SetNumberOfIterations( 2 ); m_SmoothFilter->SetConductanceParameter( 9.0 ); m_GradientMagnitudeFilter = GradientFilterType::New(); m_GradientMagnitudeFilter->SetSigma( m_Sigma ); m_SigmoidFilter = SigmoidFilterType::New(); m_SigmoidFilter->SetAlpha( m_Alpha ); m_SigmoidFilter->SetBeta( m_Beta ); m_SigmoidFilter->SetOutputMinimum( 0.0 ); m_SigmoidFilter->SetOutputMaximum( 1.0 ); m_FastMarchingFilter = FastMarchingFilterType::New(); m_FastMarchingFilter->SetStoppingValue( m_StoppingValue ); m_ThresholdFilter = ThresholdingFilterType::New(); m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold ); m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold ); m_ThresholdFilter->SetOutsideValue( 0 ); m_ThresholdFilter->SetInsideValue( 1.0 ); m_SeedContainer = NodeContainer::New(); m_SeedContainer->Initialize(); m_FastMarchingFilter->SetTrialPoints( m_SeedContainer ); if (this->m_SmoothFilter.IsNotNull()) this->m_SmoothFilter->RemoveAllObservers(); if (this->m_SigmoidFilter.IsNotNull()) this->m_SigmoidFilter->RemoveAllObservers(); if (this->m_GradientMagnitudeFilter.IsNotNull()) this->m_GradientMagnitudeFilter->RemoveAllObservers(); if (this->m_FastMarchingFilter.IsNotNull()) this->m_FastMarchingFilter->RemoveAllObservers(); m_SmoothFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_GradientMagnitudeFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_SigmoidFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_FastMarchingFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_SmoothFilter->SetInput( m_ReferenceImageSliceAsITK ); m_GradientMagnitudeFilter->SetInput( m_SmoothFilter->GetOutput() ); m_SigmoidFilter->SetInput( m_GradientMagnitudeFilter->GetOutput() ); m_FastMarchingFilter->SetInput( m_SigmoidFilter->GetOutput() ); m_ThresholdFilter->SetInput( m_FastMarchingFilter->GetOutput() ); m_ReferenceImageSliceAsITK = InternalImageType::New(); } void mitk::FastMarchingTool::SetUpperThreshold(double value) { if (m_UpperThreshold != value) { m_UpperThreshold = value / 10.0; m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold ); m_NeedUpdate = true; } } void mitk::FastMarchingTool::SetLowerThreshold(double value) { if (m_LowerThreshold != value) { m_LowerThreshold = value / 10.0; m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold ); m_NeedUpdate = true; } } void mitk::FastMarchingTool::SetBeta(double value) { if (m_Beta != value) { m_Beta = value; m_SigmoidFilter->SetBeta( m_Beta ); m_NeedUpdate = true; } } void mitk::FastMarchingTool::SetSigma(double value) { if (m_Sigma != value) { m_Sigma = value; m_GradientMagnitudeFilter->SetSigma( m_Sigma ); m_NeedUpdate = true; } } void mitk::FastMarchingTool::SetAlpha(double value) { if (m_Alpha != value) { m_Alpha = value; m_SigmoidFilter->SetAlpha( m_Alpha ); m_NeedUpdate = true; } } void mitk::FastMarchingTool::SetStoppingValue(double value) { if (m_StoppingValue != value) { m_StoppingValue = value; m_FastMarchingFilter->SetStoppingValue( m_StoppingValue ); m_NeedUpdate = true; } } void mitk::FastMarchingTool::Activated() { Superclass::Activated(); m_ResultImageNode = mitk::DataNode::New(); m_ResultImageNode->SetName("FastMarching_Preview"); m_ResultImageNode->SetBoolProperty("helper object", true); m_ResultImageNode->SetColor(0.0, 1.0, 0.0); m_ResultImageNode->SetVisibility(true); m_ToolManager->GetDataStorage()->Add( this->m_ResultImageNode, m_ToolManager->GetReferenceData(0)); m_SeedsAsPointSet = mitk::PointSet::New(); m_SeedsAsPointSetNode = mitk::DataNode::New(); m_SeedsAsPointSetNode->SetData(m_SeedsAsPointSet); m_SeedsAsPointSetNode->SetName("Seeds_Preview"); m_SeedsAsPointSetNode->SetBoolProperty("helper object", true); m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0); m_SeedsAsPointSetNode->SetVisibility(true); m_ToolManager->GetDataStorage()->Add( this->m_SeedsAsPointSetNode, m_ToolManager->GetReferenceData(0)); this->Initialize(); } void mitk::FastMarchingTool::Deactivated() { Superclass::Deactivated(); m_ToolManager->GetDataStorage()->Remove( this->m_ResultImageNode ); m_ToolManager->GetDataStorage()->Remove( this->m_SeedsAsPointSetNode ); this->ClearSeeds(); m_ResultImageNode = NULL; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::FastMarchingTool::Initialize() { m_ReferenceImage = dynamic_cast(m_ToolManager->GetReferenceData(0)->GetData()); if(m_ReferenceImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1) { mitk::ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput( m_ReferenceImage ); timeSelector->SetTimeNr( m_CurrentTimeStep ); timeSelector->UpdateLargestPossibleRegion(); m_ReferenceImage = timeSelector->GetOutput(); } m_NeedUpdate = true; } void mitk::FastMarchingTool::ConfirmSegmentation() { // combine preview image with current working segmentation if (dynamic_cast(m_ResultImageNode->GetData())) { //logical or combination of preview and segmentation slice OutputImageType::Pointer workingImageSliceInITK = OutputImageType::New(); mitk::Image::Pointer workingImageSlice; mitk::Image::Pointer workingImage = dynamic_cast(this->m_ToolManager->GetWorkingData(0)->GetData()); if(workingImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput( workingImage ); timeSelector->SetTimeNr( m_CurrentTimeStep ); timeSelector->UpdateLargestPossibleRegion(); // todo: make GetAffectedWorkingSlice dependant of current time step workingImageSlice = GetAffectedWorkingSlice( m_PositionEvent ); CastToItkImage( workingImageSlice, workingImageSliceInITK ); } else { workingImageSlice = GetAffectedWorkingSlice( m_PositionEvent ); CastToItkImage( workingImageSlice, workingImageSliceInITK ); } typedef itk::OrImageFilter OrImageFilterType; OrImageFilterType::Pointer orFilter = OrImageFilterType::New(); orFilter->SetInput(0, m_ThresholdFilter->GetOutput()); orFilter->SetInput(1, workingImageSliceInITK); orFilter->Update(); mitk::Image::Pointer segmentationResult = mitk::Image::New(); mitk::CastToMitkImage(orFilter->GetOutput(), segmentationResult); segmentationResult->GetGeometry()->SetOrigin(workingImageSlice->GetGeometry()->GetOrigin()); segmentationResult->GetGeometry()->SetIndexToWorldTransform(workingImageSlice->GetGeometry()->GetIndexToWorldTransform()); //write to segmentation volume and hide preview image // again, current time step is not considered this->WriteBackSegmentationResult(m_PositionEvent, segmentationResult ); this->m_ResultImageNode->SetVisibility(false); this->ClearSeeds(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } bool mitk::FastMarchingTool::OnAddPoint(Action* action, const StateEvent* stateEvent) { // Add a new seed point for FastMarching algorithm const PositionEvent* p = dynamic_cast(stateEvent->GetEvent()); if (!p) return false; if (m_PositionEvent != NULL) delete m_PositionEvent; m_PositionEvent = new PositionEvent(p->GetSender(), p->GetType(), p->GetButton(), p->GetButtonState(), p->GetKey(), p->GetDisplayPosition(), p->GetWorldPosition() ); //if click was on another renderwindow or slice then reset pipeline and preview if( (m_LastEventSender != m_PositionEvent->GetSender()) || (m_LastEventSlice != m_PositionEvent->GetSender()->GetSlice()) ) { this->BuildITKPipeline(); this->ClearSeeds(); } m_LastEventSender = m_PositionEvent->GetSender(); m_LastEventSlice = m_LastEventSender->GetSlice(); mitk::Point3D clickInIndex; m_ReferenceImageSlice->GetGeometry()->WorldToIndex(m_PositionEvent->GetWorldPosition(), clickInIndex); itk::Index<2> seedPosition; seedPosition[0] = clickInIndex[0]; seedPosition[1] = clickInIndex[1]; NodeType node; const double seedValue = 0.0; node.SetValue( seedValue ); node.SetIndex( seedPosition ); this->m_SeedContainer->InsertElement(this->m_SeedContainer->Size(), node); m_FastMarchingFilter->Modified(); m_SeedsAsPointSet->InsertPoint(m_SeedsAsPointSet->GetSize(), m_PositionEvent->GetWorldPosition()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_NeedUpdate = true; this->Update(); return true; } bool mitk::FastMarchingTool::OnDelete(Action* action, const StateEvent* stateEvent) { // delete last seed point if(!(this->m_SeedContainer->empty())) { //delete last element of seeds container this->m_SeedContainer->pop_back(); m_FastMarchingFilter->Modified(); //delete last point in pointset - somehow ugly m_SeedsAsPointSet->GetPointSet()->GetPoints()->DeleteIndex(m_SeedsAsPointSet->GetSize() - 1); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_NeedUpdate = true; this->Update(); } return true; } void mitk::FastMarchingTool::Update() { // update FastMarching pipeline and show result if (m_NeedUpdate) { m_ProgressCommand->AddStepsToDo(20); CurrentlyBusy.Send(true); try { m_ThresholdFilter->Update(); } catch( itk::ExceptionObject & excep ) { MITK_ERROR << "Exception caught: " << excep.GetDescription(); m_ProgressCommand->SetRemainingProgress(100); CurrentlyBusy.Send(false); std::string msg = excep.GetDescription(); ErrorMessage.Send(msg); return; } m_ProgressCommand->SetRemainingProgress(100); CurrentlyBusy.Send(false); //make output visible mitk::Image::Pointer result = mitk::Image::New(); CastToMitkImage( m_ThresholdFilter->GetOutput(), result); result->GetGeometry()->SetOrigin(m_ReferenceImageSlice->GetGeometry()->GetOrigin() ); result->GetGeometry()->SetIndexToWorldTransform(m_ReferenceImageSlice->GetGeometry()->GetIndexToWorldTransform() ); m_ResultImageNode->SetData(result); m_ResultImageNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void mitk::FastMarchingTool::ClearSeeds() { // clear seeds for FastMarching as well as the PointSet for visualization if(this->m_SeedContainer.IsNotNull()) this->m_SeedContainer->Initialize(); if(this->m_SeedsAsPointSet.IsNotNull()) this->m_SeedsAsPointSet->Clear(); if(this->m_FastMarchingFilter.IsNotNull()) m_FastMarchingFilter->Modified(); this->m_NeedUpdate = true; } void mitk::FastMarchingTool::Reset() { //clear all seeds and preview empty result this->ClearSeeds(); m_ResultImageNode->SetVisibility(false); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::FastMarchingTool::SetCurrentTimeStep(int t) { if( m_CurrentTimeStep != t ) { m_CurrentTimeStep = t; this->Initialize(); } } diff --git a/Modules/Segmentation/Interactions/mitkFastMarchingTool.h b/Modules/Segmentation/Interactions/mitkFastMarchingTool.h index e824a55fd1..41a04eaf48 100644 --- a/Modules/Segmentation/Interactions/mitkFastMarchingTool.h +++ b/Modules/Segmentation/Interactions/mitkFastMarchingTool.h @@ -1,170 +1,172 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkFastMarchingTool_h_Included #define mitkFastMarchingTool_h_Included #include "mitkFeedbackContourTool.h" #include "mitkLegacyAdaptors.h" #include "SegmentationExports.h" #include "mitkDataNode.h" #include "mitkPointSet.h" #include "mitkToolCommand.h" #include "mitkPositionEvent.h" #include "itkImage.h" //itk filter #include "itkFastMarchingImageFilter.h" #include "itkBinaryThresholdImageFilter.h" #include "itkGradientMagnitudeRecursiveGaussianImageFilter.h" #include "itkSigmoidImageFilter.h" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" +namespace us { class ModuleResource; +} namespace mitk { /** \brief FastMarching semgentation tool. The segmentation is done by setting one or more seed points on the image and adapting the time range and threshold. The pipeline is: Smoothing->GradientMagnitude->SigmoidFunction->FastMarching->Threshold The resulting binary image is seen as a segmentation of an object. For detailed documentation see ITK Software Guide section 9.3.1 Fast Marching Segmentation. */ class Segmentation_EXPORT FastMarchingTool : public FeedbackContourTool { public: mitkClassMacro(FastMarchingTool, FeedbackContourTool); itkNewMacro(FastMarchingTool); /* typedefs for itk pipeline */ typedef float InternalPixelType; typedef itk::Image< InternalPixelType, 2 > InternalImageType; typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, 2 > OutputImageType; typedef itk::BinaryThresholdImageFilter< InternalImageType, OutputImageType > ThresholdingFilterType; typedef itk::CurvatureAnisotropicDiffusionImageFilter< InternalImageType, InternalImageType > SmoothingFilterType; typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< InternalImageType, InternalImageType > GradientFilterType; typedef itk::SigmoidImageFilter< InternalImageType, InternalImageType > SigmoidFilterType; typedef itk::FastMarchingImageFilter< InternalImageType, InternalImageType > FastMarchingFilterType; typedef FastMarchingFilterType::NodeContainer NodeContainer; typedef FastMarchingFilterType::NodeType NodeType; /* icon stuff */ virtual const char** GetXPM() const; virtual const char* GetName() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; /// \brief Set parameter used in Threshold filter. void SetUpperThreshold(double); /// \brief Set parameter used in Threshold filter. void SetLowerThreshold(double); /// \brief Set parameter used in Fast Marching filter. void SetStoppingValue(double); /// \brief Set parameter used in Gradient Magnitude filter. void SetSigma(double); /// \brief Set parameter used in Fast Marching filter. void SetAlpha(double); /// \brief Set parameter used in Fast Marching filter. void SetBeta(double); /// \brief Adds the feedback image to the current working image. virtual void ConfirmSegmentation(); /// \brief Set the working time step. virtual void SetCurrentTimeStep(int t); /// \brief Clear all seed points. void ClearSeeds(); /// \brief Updates the itk pipeline and shows the result of FastMarching. void Update(); protected: FastMarchingTool(); virtual ~FastMarchingTool(); virtual float CanHandleEvent( StateEvent const *stateEvent) const; virtual void Activated(); virtual void Deactivated(); virtual void Initialize(); virtual void BuildITKPipeline(); /// \brief Add point action of StateMachine pattern virtual bool OnAddPoint (Action*, const StateEvent*); /// \brief Delete action of StateMachine pattern virtual bool OnDelete (Action*, const StateEvent*); /// \brief Reset all relevant inputs of the itk pipeline. void Reset(); mitk::ToolCommand::Pointer m_ProgressCommand; Image::Pointer m_ReferenceImage; Image::Pointer m_ReferenceImageSlice; bool m_NeedUpdate; int m_CurrentTimeStep; mitk::PositionEvent* m_PositionEvent; float m_LowerThreshold; //used in Threshold filter float m_UpperThreshold; //used in Threshold filter float m_StoppingValue; //used in Fast Marching filter float m_Sigma; //used in GradientMagnitude filter float m_Alpha; //used in Sigmoid filter float m_Beta; //used in Sigmoid filter NodeContainer::Pointer m_SeedContainer; //seed points for FastMarching InternalImageType::Pointer m_ReferenceImageSliceAsITK; //the reference image as itk::Image mitk::DataNode::Pointer m_ResultImageNode;//holds the result as a preview image mitk::DataNode::Pointer m_SeedsAsPointSetNode;//used to visualize the seed points mitk::PointSet::Pointer m_SeedsAsPointSet; ThresholdingFilterType::Pointer m_ThresholdFilter; SmoothingFilterType::Pointer m_SmoothFilter; GradientFilterType::Pointer m_GradientMagnitudeFilter; SigmoidFilterType::Pointer m_SigmoidFilter; FastMarchingFilterType::Pointer m_FastMarchingFilter; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkFastMarchingTool3D.cpp b/Modules/Segmentation/Interactions/mitkFastMarchingTool3D.cpp index 1476c3377a..61f13409f5 100644 --- a/Modules/Segmentation/Interactions/mitkFastMarchingTool3D.cpp +++ b/Modules/Segmentation/Interactions/mitkFastMarchingTool3D.cpp @@ -1,398 +1,399 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFastMarchingTool3D.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include "mitkInteractionConst.h" #include "mitkGlobalInteraction.h" #include "itkOrImageFilter.h" #include "mitkImageTimeSelector.h" #include "mitkImageCast.h" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, FastMarchingTool3D, "FastMarching3D tool"); } mitk::FastMarchingTool3D::FastMarchingTool3D() :/*FeedbackContourTool*/AutoSegmentationTool(), m_NeedUpdate(true), m_CurrentTimeStep(0), m_LowerThreshold(0), m_UpperThreshold(200), m_StoppingValue(100), m_Sigma(1.0), m_Alpha(-0.5), m_Beta(3.0) { } mitk::FastMarchingTool3D::~FastMarchingTool3D() { } const char** mitk::FastMarchingTool3D::GetXPM() const { return NULL;//mitkFastMarchingTool3D_xpm; } -mitk::ModuleResource mitk::FastMarchingTool3D::GetIconResource() const +us::ModuleResource mitk::FastMarchingTool3D::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("FastMarching_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("FastMarching_48x48.png"); return resource; } const char* mitk::FastMarchingTool3D::GetName() const { return "FastMarching3D"; } void mitk::FastMarchingTool3D::SetUpperThreshold(double value) { m_UpperThreshold = value / 10.0; m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::SetLowerThreshold(double value) { m_LowerThreshold = value / 10.0; m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::SetBeta(double value) { if (m_Beta != value) { m_Beta = value; m_SigmoidFilter->SetBeta( m_Beta ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::SetSigma(double value) { if (m_Sigma != value) { m_Sigma = value; m_GradientMagnitudeFilter->SetSigma( m_Sigma ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::SetAlpha(double value) { if (m_Alpha != value) { m_Alpha = value; m_SigmoidFilter->SetAlpha( m_Alpha ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::SetStoppingValue(double value) { if (m_StoppingValue != value) { m_StoppingValue = value; m_FastMarchingFilter->SetStoppingValue( m_StoppingValue ); m_NeedUpdate = true; } } void mitk::FastMarchingTool3D::Activated() { Superclass::Activated(); m_ResultImageNode = mitk::DataNode::New(); m_ResultImageNode->SetName("FastMarching_Preview"); m_ResultImageNode->SetBoolProperty("helper object", true); m_ResultImageNode->SetColor(0.0, 1.0, 0.0); m_ResultImageNode->SetVisibility(true); m_ToolManager->GetDataStorage()->Add( this->m_ResultImageNode, m_ToolManager->GetReferenceData(0)); m_SeedsAsPointSet = mitk::PointSet::New(); m_SeedsAsPointSetNode = mitk::DataNode::New(); m_SeedsAsPointSetNode->SetData(m_SeedsAsPointSet); m_SeedsAsPointSetNode->SetName("3D_FastMarching_PointSet"); m_SeedsAsPointSetNode->SetBoolProperty("helper object", true); m_SeedsAsPointSetNode->SetColor(0.0, 1.0, 0.0); m_SeedsAsPointSetNode->SetVisibility(true); m_SeedPointInteractor = mitk::PointSetInteractor::New("PressMoveReleaseAndPointSetting", m_SeedsAsPointSetNode); m_ReferenceImageAsITK = InternalImageType::New(); m_ProgressCommand = mitk::ToolCommand::New(); m_ThresholdFilter = ThresholdingFilterType::New(); m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold ); m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold ); m_ThresholdFilter->SetOutsideValue( 0 ); m_ThresholdFilter->SetInsideValue( 1.0 ); m_SmoothFilter = SmoothingFilterType::New(); m_SmoothFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_SmoothFilter->SetTimeStep( 0.05 ); m_SmoothFilter->SetNumberOfIterations( 2 ); m_SmoothFilter->SetConductanceParameter( 9.0 ); m_GradientMagnitudeFilter = GradientFilterType::New(); m_GradientMagnitudeFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_GradientMagnitudeFilter->SetSigma( m_Sigma ); m_SigmoidFilter = SigmoidFilterType::New(); m_SigmoidFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_SigmoidFilter->SetAlpha( m_Alpha ); m_SigmoidFilter->SetBeta( m_Beta ); m_SigmoidFilter->SetOutputMinimum( 0.0 ); m_SigmoidFilter->SetOutputMaximum( 1.0 ); m_FastMarchingFilter = FastMarchingFilterType::New(); m_FastMarchingFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand); m_FastMarchingFilter->SetStoppingValue( m_StoppingValue ); m_SeedContainer = NodeContainer::New(); m_SeedContainer->Initialize(); m_FastMarchingFilter->SetTrialPoints( m_SeedContainer ); //set up pipeline m_SmoothFilter->SetInput( m_ReferenceImageAsITK ); m_GradientMagnitudeFilter->SetInput( m_SmoothFilter->GetOutput() ); m_SigmoidFilter->SetInput( m_GradientMagnitudeFilter->GetOutput() ); m_FastMarchingFilter->SetInput( m_SigmoidFilter->GetOutput() ); m_ThresholdFilter->SetInput( m_FastMarchingFilter->GetOutput() ); m_ToolManager->GetDataStorage()->Add(m_SeedsAsPointSetNode, m_ToolManager->GetWorkingData(0)); mitk::GlobalInteraction::GetInstance()->AddInteractor(m_SeedPointInteractor); itk::SimpleMemberCommand::Pointer pointAddedCommand = itk::SimpleMemberCommand::New(); pointAddedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnAddPoint); m_PointSetAddObserverTag = m_SeedsAsPointSet->AddObserver( mitk::PointSetAddEvent(), pointAddedCommand); itk::SimpleMemberCommand::Pointer pointRemovedCommand = itk::SimpleMemberCommand::New(); pointRemovedCommand->SetCallbackFunction(this, &mitk::FastMarchingTool3D::OnDelete); m_PointSetRemoveObserverTag = m_SeedsAsPointSet->AddObserver( mitk::PointSetRemoveEvent(), pointRemovedCommand); this->Initialize(); } void mitk::FastMarchingTool3D::Deactivated() { Superclass::Deactivated(); m_ToolManager->GetDataStorage()->Remove( this->m_ResultImageNode ); m_ToolManager->GetDataStorage()->Remove( this->m_SeedsAsPointSetNode ); this->ClearSeeds(); this->m_SmoothFilter->RemoveAllObservers(); this->m_SigmoidFilter->RemoveAllObservers(); this->m_GradientMagnitudeFilter->RemoveAllObservers(); this->m_FastMarchingFilter->RemoveAllObservers(); m_ResultImageNode = NULL; mitk::RenderingManager::GetInstance()->RequestUpdateAll(); unsigned int numberOfPoints = m_SeedsAsPointSet->GetSize(); for (unsigned int i = 0; i < numberOfPoints; ++i) { mitk::Point3D point = m_SeedsAsPointSet->GetPoint(i); mitk::PointOperation* doOp = new mitk::PointOperation(mitk::OpREMOVE, point, 0); m_SeedsAsPointSet->ExecuteOperation(doOp); } mitk::GlobalInteraction::GetInstance()->RemoveInteractor(m_SeedPointInteractor); m_ToolManager->GetDataStorage()->Remove(m_SeedsAsPointSetNode); m_SeedsAsPointSet->RemoveObserver(m_PointSetAddObserverTag); m_SeedsAsPointSet->RemoveObserver(m_PointSetRemoveObserverTag); } void mitk::FastMarchingTool3D::Initialize() { m_ReferenceImage = dynamic_cast(m_ToolManager->GetReferenceData(0)->GetData()); if(m_ReferenceImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1) { mitk::ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput( m_ReferenceImage ); timeSelector->SetTimeNr( m_CurrentTimeStep ); timeSelector->UpdateLargestPossibleRegion(); m_ReferenceImage = timeSelector->GetOutput(); } CastToItkImage(m_ReferenceImage, m_ReferenceImageAsITK); m_SmoothFilter->SetInput( m_ReferenceImageAsITK ); m_NeedUpdate = true; } void mitk::FastMarchingTool3D::ConfirmSegmentation() { // combine preview image with current working segmentation if (dynamic_cast(m_ResultImageNode->GetData())) { //logical or combination of preview and segmentation slice OutputImageType::Pointer segmentationImageInITK = OutputImageType::New(); mitk::Image::Pointer workingImage = dynamic_cast(GetTargetSegmentationNode()->GetData()); if(workingImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput( workingImage ); timeSelector->SetTimeNr( m_CurrentTimeStep ); timeSelector->UpdateLargestPossibleRegion(); CastToItkImage( timeSelector->GetOutput(), segmentationImageInITK ); } else { CastToItkImage( workingImage, segmentationImageInITK ); } typedef itk::OrImageFilter OrImageFilterType; OrImageFilterType::Pointer orFilter = OrImageFilterType::New(); orFilter->SetInput(0, m_ThresholdFilter->GetOutput()); orFilter->SetInput(1, segmentationImageInITK); orFilter->Update(); //set image volume in current time step from itk image workingImage->SetVolume( (void*)(m_ThresholdFilter->GetOutput()->GetPixelContainer()->GetBufferPointer()), m_CurrentTimeStep); this->m_ResultImageNode->SetVisibility(false); this->ClearSeeds(); workingImage->Modified(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::FastMarchingTool3D::OnAddPoint() { // Add a new seed point for FastMarching algorithm mitk::Point3D clickInIndex; m_ReferenceImage->GetGeometry()->WorldToIndex(m_SeedsAsPointSet->GetPoint(m_SeedsAsPointSet->GetSize()-1), clickInIndex); itk::Index<3> seedPosition; seedPosition[0] = clickInIndex[0]; seedPosition[1] = clickInIndex[1]; seedPosition[2] = clickInIndex[2]; NodeType node; const double seedValue = 0.0; node.SetValue( seedValue ); node.SetIndex( seedPosition ); this->m_SeedContainer->InsertElement(this->m_SeedContainer->Size(), node); m_FastMarchingFilter->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_NeedUpdate = true; this->Update(); } void mitk::FastMarchingTool3D::OnDelete() { // delete last seed point if(!(this->m_SeedContainer->empty())) { //delete last element of seeds container this->m_SeedContainer->pop_back(); m_FastMarchingFilter->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); m_NeedUpdate = true; this->Update(); } } void mitk::FastMarchingTool3D::Update() { if (m_NeedUpdate) { m_ProgressCommand->AddStepsToDo(200); CurrentlyBusy.Send(true); try { m_ThresholdFilter->Update(); } catch( itk::ExceptionObject & excep ) { MITK_ERROR << "Exception caught: " << excep.GetDescription(); m_ProgressCommand->SetRemainingProgress(100); CurrentlyBusy.Send(false); std::string msg = excep.GetDescription(); ErrorMessage.Send(msg); return; } m_ProgressCommand->SetRemainingProgress(100); CurrentlyBusy.Send(false); //make output visible mitk::Image::Pointer result = mitk::Image::New(); CastToMitkImage( m_ThresholdFilter->GetOutput(), result); result->GetGeometry()->SetOrigin(m_ReferenceImage->GetGeometry()->GetOrigin() ); result->GetGeometry()->SetIndexToWorldTransform(m_ReferenceImage->GetGeometry()->GetIndexToWorldTransform() ); m_ResultImageNode->SetData(result); m_ResultImageNode->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void mitk::FastMarchingTool3D::ClearSeeds() { // clear seeds for FastMarching as well as the PointSet for visualization this->m_SeedContainer->Initialize(); this->m_SeedsAsPointSet->Clear(); m_FastMarchingFilter->Modified(); this->m_NeedUpdate = true; } void mitk::FastMarchingTool3D::Reset() { //clear all seeds and preview empty result this->ClearSeeds(); m_ResultImageNode->SetVisibility(false); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::FastMarchingTool3D::SetCurrentTimeStep(int t) { if( m_CurrentTimeStep != t ) { m_CurrentTimeStep = t; this->Initialize(); } } diff --git a/Modules/Segmentation/Interactions/mitkFastMarchingTool3D.h b/Modules/Segmentation/Interactions/mitkFastMarchingTool3D.h index 6b307dac50..309427692b 100644 --- a/Modules/Segmentation/Interactions/mitkFastMarchingTool3D.h +++ b/Modules/Segmentation/Interactions/mitkFastMarchingTool3D.h @@ -1,164 +1,165 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkFastMarchingTool3D_h_Included #define mitkFastMarchingTool3D_h_Included #include "mitkAutoSegmentationTool.h" #include "mitkLegacyAdaptors.h" #include "SegmentationExports.h" #include "mitkDataNode.h" #include "mitkPointSet.h" #include "mitkPointSetInteractor.h" #include "mitkToolCommand.h" #include "itkImage.h" //itk filter #include "itkFastMarchingImageFilter.h" #include "itkBinaryThresholdImageFilter.h" #include "itkGradientMagnitudeRecursiveGaussianImageFilter.h" #include "itkSigmoidImageFilter.h" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" +namespace us { class ModuleResource; - +} namespace mitk { /** \brief FastMarching semgentation tool. The segmentation is done by setting one or more seed points on the image and adapting the time range and threshold. The pipeline is: Smoothing->GradientMagnitude->SigmoidFunction->FastMarching->Threshold The resulting binary image is seen as a segmentation of an object. For detailed documentation see ITK Software Guide section 9.3.1 Fast Marching Segmentation. */ class Segmentation_EXPORT FastMarchingTool3D : public AutoSegmentationTool { public: mitkClassMacro(FastMarchingTool3D, AutoSegmentationTool) itkNewMacro(FastMarchingTool3D) /* typedefs for itk pipeline */ typedef float InternalPixelType; typedef itk::Image< InternalPixelType, 3 > InternalImageType; typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, 3 > OutputImageType; typedef itk::BinaryThresholdImageFilter< InternalImageType, OutputImageType > ThresholdingFilterType; typedef itk::CurvatureAnisotropicDiffusionImageFilter< InternalImageType, InternalImageType > SmoothingFilterType; typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< InternalImageType, InternalImageType > GradientFilterType; typedef itk::SigmoidImageFilter< InternalImageType, InternalImageType > SigmoidFilterType; typedef itk::FastMarchingImageFilter< InternalImageType, InternalImageType > FastMarchingFilterType; typedef FastMarchingFilterType::NodeContainer NodeContainer; typedef FastMarchingFilterType::NodeType NodeType; /* icon stuff */ virtual const char** GetXPM() const; virtual const char* GetName() const; - ModuleResource GetIconResource() const; + us::ModuleResource GetIconResource() const; /// \brief Set parameter used in Threshold filter. void SetUpperThreshold(double); /// \brief Set parameter used in Threshold filter. void SetLowerThreshold(double); /// \brief Set parameter used in Fast Marching filter. void SetStoppingValue(double); /// \brief Set parameter used in Gradient Magnitude filter. void SetSigma(double); /// \brief Set parameter used in Fast Marching filter. void SetAlpha(double); /// \brief Set parameter used in Fast Marching filter. void SetBeta(double); /// \brief Adds the feedback image to the current working image. virtual void ConfirmSegmentation(); /// \brief Set the working time step. virtual void SetCurrentTimeStep(int t); /// \brief Clear all seed points. void ClearSeeds(); /// \brief Updates the itk pipeline and shows the result of FastMarching. void Update(); protected: FastMarchingTool3D(); virtual ~FastMarchingTool3D(); virtual void Activated(); virtual void Deactivated(); virtual void Initialize(); /// \brief Add point action of StateMachine pattern virtual void OnAddPoint (); /// \brief Delete action of StateMachine pattern virtual void OnDelete (); /// \brief Reset all relevant inputs of the itk pipeline. void Reset(); mitk::ToolCommand::Pointer m_ProgressCommand; Image::Pointer m_ReferenceImage; bool m_NeedUpdate; int m_CurrentTimeStep; float m_LowerThreshold; //used in Threshold filter float m_UpperThreshold; //used in Threshold filter float m_StoppingValue; //used in Fast Marching filter float m_Sigma; //used in GradientMagnitude filter float m_Alpha; //used in Sigmoid filter float m_Beta; //used in Sigmoid filter NodeContainer::Pointer m_SeedContainer; //seed points for FastMarching InternalImageType::Pointer m_ReferenceImageAsITK; //the reference image as itk::Image mitk::DataNode::Pointer m_ResultImageNode;//holds the result as a preview image mitk::DataNode::Pointer m_SeedsAsPointSetNode;//used to visualize the seed points mitk::PointSet::Pointer m_SeedsAsPointSet; mitk::PointSetInteractor::Pointer m_SeedPointInteractor; unsigned int m_PointSetAddObserverTag; unsigned int m_PointSetRemoveObserverTag; ThresholdingFilterType::Pointer m_ThresholdFilter; SmoothingFilterType::Pointer m_SmoothFilter; GradientFilterType::Pointer m_GradientMagnitudeFilter; SigmoidFilterType::Pointer m_SigmoidFilter; FastMarchingFilterType::Pointer m_FastMarchingFilter; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkFillRegionTool.cpp b/Modules/Segmentation/Interactions/mitkFillRegionTool.cpp index 46b210a33a..a5cf279f24 100644 --- a/Modules/Segmentation/Interactions/mitkFillRegionTool.cpp +++ b/Modules/Segmentation/Interactions/mitkFillRegionTool.cpp @@ -1,62 +1,63 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFillRegionTool.h" #include "mitkFillRegionTool.xpm" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, FillRegionTool, "Fill tool"); } mitk::FillRegionTool::FillRegionTool() :SetRegionTool(1) { } mitk::FillRegionTool::~FillRegionTool() { } const char** mitk::FillRegionTool::GetXPM() const { return mitkFillRegionTool_xpm; } -mitk::ModuleResource mitk::FillRegionTool::GetIconResource() const +us::ModuleResource mitk::FillRegionTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Fill_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Fill_48x48.png"); return resource; } -mitk::ModuleResource mitk::FillRegionTool::GetCursorIconResource() const +us::ModuleResource mitk::FillRegionTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Fill_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Fill_Cursor_32x32.png"); return resource; } const char* mitk::FillRegionTool::GetName() const { return "Fill"; } diff --git a/Modules/Segmentation/Interactions/mitkFillRegionTool.h b/Modules/Segmentation/Interactions/mitkFillRegionTool.h index 6de5e3b29c..d6149aa890 100644 --- a/Modules/Segmentation/Interactions/mitkFillRegionTool.h +++ b/Modules/Segmentation/Interactions/mitkFillRegionTool.h @@ -1,66 +1,68 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkFillRegionTool_h_Included #define mitkFillRegionTool_h_Included #include "mitkSetRegionTool.h" #include "SegmentationExports.h" +namespace us { class ModuleResource; +} namespace mitk { /** \brief Fill the inside of a contour with 1 \sa SetRegionTool \ingroup Interaction \ingroup ToolManagerEtAl Finds the outer contour of a shape in 2D (possibly including holes) and sets all the inside pixels to 1, filling holes in a segmentation. \warning Only to be instantiated by mitk::ToolManager. $Author$ */ class Segmentation_EXPORT FillRegionTool : public SetRegionTool { public: mitkClassMacro(FillRegionTool, SetRegionTool); itkNewMacro(FillRegionTool); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; protected: FillRegionTool(); // purposely hidden virtual ~FillRegionTool(); }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkLiveWireTool2D.cpp b/Modules/Segmentation/Interactions/mitkLiveWireTool2D.cpp index 962e3de251..337dec9d12 100644 --- a/Modules/Segmentation/Interactions/mitkLiveWireTool2D.cpp +++ b/Modules/Segmentation/Interactions/mitkLiveWireTool2D.cpp @@ -1,673 +1,674 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkLiveWireTool2D.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include "mitkLiveWireTool2D.xpm" #include #include #include "mitkContourUtils.h" #include "mitkContour.h" #include // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, LiveWireTool2D, "LiveWire tool"); } mitk::LiveWireTool2D::LiveWireTool2D() :SegTool2D("LiveWireTool") { // great magic numbers CONNECT_ACTION( AcINITNEWOBJECT, OnInitLiveWire ); CONNECT_ACTION( AcADDPOINT, OnAddPoint ); CONNECT_ACTION( AcMOVE, OnMouseMoveNoDynamicCosts ); CONNECT_ACTION( AcCHECKPOINT, OnCheckPoint ); CONNECT_ACTION( AcFINISH, OnFinish ); CONNECT_ACTION( AcDELETEPOINT, OnLastSegmentDelete ); CONNECT_ACTION( AcADDLINE, OnMouseMoved ); } mitk::LiveWireTool2D::~LiveWireTool2D() { this->m_WorkingContours.clear(); this->m_EditingContours.clear(); } float mitk::LiveWireTool2D::CanHandleEvent( StateEvent const *stateEvent) const { mitk::PositionEvent const *positionEvent = dynamic_cast (stateEvent->GetEvent()); //Key event handling: if (positionEvent == NULL) { //check for delete and escape event if(stateEvent->GetId() == 12 || stateEvent->GetId() == 14) { return 1.0; } //check, if the current state has a transition waiting for that key event. else if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL) { return 0.5; } else { return 0.0; } } else { if ( positionEvent->GetSender()->GetMapperID() != BaseRenderer::Standard2D ) return 0.0; // we don't want anything but 2D return 1.0; } } const char** mitk::LiveWireTool2D::GetXPM() const { return mitkLiveWireTool2D_xpm; } -mitk::ModuleResource mitk::LiveWireTool2D::GetIconResource() const +us::ModuleResource mitk::LiveWireTool2D::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("LiveWire_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("LiveWire_48x48.png"); return resource; } -mitk::ModuleResource mitk::LiveWireTool2D::GetCursorIconResource() const +us::ModuleResource mitk::LiveWireTool2D::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("LiveWire_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("LiveWire_Cursor_32x32.png"); return resource; } const char* mitk::LiveWireTool2D::GetName() const { return "Live Wire"; } void mitk::LiveWireTool2D::Activated() { Superclass::Activated(); } void mitk::LiveWireTool2D::Deactivated() { this->ClearContours(); Superclass::Deactivated(); } void mitk::LiveWireTool2D::ClearContours() { // for all contours in list (currently created by tool) std::vector< std::pair >::iterator iter = this->m_WorkingContours.begin(); while(iter != this->m_WorkingContours.end() ) { //remove contour node from datastorage m_ToolManager->GetDataStorage()->Remove( iter->first ); ++iter; } this->m_WorkingContours.clear(); // for all contours in list (currently created by tool) std::vector< std::pair >::iterator itEditingContours = this->m_EditingContours.begin(); while(itEditingContours != this->m_EditingContours.end() ) { //remove contour node from datastorage m_ToolManager->GetDataStorage()->Remove( itEditingContours->first ); ++itEditingContours; } this->m_EditingContours.clear(); std::vector< mitk::ContourModelLiveWireInteractor::Pointer >::iterator itLiveWireInteractors = this->m_LiveWireInteractors.begin(); while(itLiveWireInteractors != this->m_LiveWireInteractors.end() ) { // remove interactors from globalInteraction instance mitk::GlobalInteraction::GetInstance()->RemoveInteractor( *itLiveWireInteractors ); ++itLiveWireInteractors; } this->m_LiveWireInteractors.clear(); } void mitk::LiveWireTool2D::ConfirmSegmentation() { DataNode* workingNode( m_ToolManager->GetWorkingData(0) ); assert ( workingNode ); Image* workingImage = dynamic_cast(workingNode->GetData()); assert ( workingImage ); ContourUtils::Pointer contourUtils = mitk::ContourUtils::New(); // for all contours in list (currently created by tool) std::vector< std::pair >::iterator itWorkingContours = this->m_WorkingContours.begin(); while(itWorkingContours != this->m_WorkingContours.end() ) { // if node contains data if( itWorkingContours->first->GetData() ) { // if this is a contourModel mitk::ContourModel* contourModel = dynamic_cast(itWorkingContours->first->GetData()); if( contourModel ) { // for each timestep of this contourModel for( int currentTimestep = 0; currentTimestep < contourModel->GetTimeSlicedGeometry()->GetTimeSteps(); currentTimestep++) { //get the segmentation image slice at current timestep mitk::Image::Pointer workingSlice = this->GetAffectedImageSliceAs2DImage(itWorkingContours->second, workingImage, currentTimestep); mitk::ContourModel::Pointer projectedContour = contourUtils->ProjectContourTo2DSlice(workingSlice, contourModel, true, false); contourUtils->FillContourInSlice(projectedContour, workingSlice, 1.0); //write back to image volume this->WriteBackSegmentationResult(itWorkingContours->second, workingSlice, currentTimestep); } //remove contour node from datastorage // m_ToolManager->GetDataStorage()->Remove( itWorkingContours->first ); } } ++itWorkingContours; } /* this->m_WorkingContours.clear(); // for all contours in list (currently created by tool) std::vector< std::pair >::iterator itEditingContours = this->m_EditingContours.begin(); while(itEditingContours != this->m_EditingContours.end() ) { //remove contour node from datastorage m_ToolManager->GetDataStorage()->Remove( itEditingContours->first ); ++itEditingContours; } this->m_EditingContours.clear(); std::vector< mitk::ContourModelLiveWireInteractor::Pointer >::iterator itLiveWireInteractors = this->m_LiveWireInteractors.begin(); while(itLiveWireInteractors != this->m_LiveWireInteractors.end() ) { // remove interactors from globalInteraction instance mitk::GlobalInteraction::GetInstance()->RemoveInteractor( *itLiveWireInteractors ); ++itLiveWireInteractors; } this->m_LiveWireInteractors.clear(); */ this->ClearContours(); } bool mitk::LiveWireTool2D::OnInitLiveWire (Action* action, const StateEvent* stateEvent) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; m_LastEventSender = positionEvent->GetSender(); m_LastEventSlice = m_LastEventSender->GetSlice(); if ( Superclass::CanHandleEvent(stateEvent) < 1.0 ) return false; int timestep = positionEvent->GetSender()->GetTimeStep(); m_Contour = mitk::ContourModel::New(); m_Contour->Expand(timestep+1); m_ContourModelNode = mitk::DataNode::New(); m_ContourModelNode->SetData( m_Contour ); m_ContourModelNode->SetName("working contour node"); m_ContourModelNode->AddProperty( "contour.color", ColorProperty::New(1, 1, 0), NULL, true ); m_ContourModelNode->AddProperty( "contour.points.color", ColorProperty::New(1.0, 0.0, 0.1), NULL, true ); m_ContourModelNode->AddProperty( "contour.controlpoints.show", BoolProperty::New(true), NULL, true ); m_LiveWireContour = mitk::ContourModel::New(); m_LiveWireContour->Expand(timestep+1); m_LiveWireContourNode = mitk::DataNode::New(); m_LiveWireContourNode->SetData( m_LiveWireContour ); m_LiveWireContourNode->SetName("active livewire node"); m_LiveWireContourNode->SetProperty( "layer", IntProperty::New(100)); m_LiveWireContourNode->SetProperty( "helper object", mitk::BoolProperty::New(true)); m_LiveWireContourNode->AddProperty( "contour.color", ColorProperty::New(0.1, 1.0, 0.1), NULL, true ); m_LiveWireContourNode->AddProperty( "contour.width", mitk::FloatProperty::New( 4.0 ), NULL, true ); m_EditingContour = mitk::ContourModel::New(); m_EditingContour->Expand(timestep+1); m_EditingContourNode = mitk::DataNode::New(); m_EditingContourNode->SetData( m_EditingContour ); m_EditingContourNode->SetName("editing node"); m_EditingContourNode->SetProperty( "layer", IntProperty::New(100)); m_EditingContourNode->SetProperty( "helper object", mitk::BoolProperty::New(true)); m_EditingContourNode->AddProperty( "contour.color", ColorProperty::New(0.1, 1.0, 0.1), NULL, true ); m_EditingContourNode->AddProperty( "contour.points.color", ColorProperty::New(0.0, 0.0, 1.0), NULL, true ); m_EditingContourNode->AddProperty( "contour.width", mitk::FloatProperty::New( 4.0 ), NULL, true ); m_ToolManager->GetDataStorage()->Add( m_ContourModelNode ); m_ToolManager->GetDataStorage()->Add( m_LiveWireContourNode ); m_ToolManager->GetDataStorage()->Add( m_EditingContourNode ); //set current slice as input for ImageToLiveWireContourFilter m_WorkingSlice = this->GetAffectedReferenceSlice(positionEvent); m_LiveWireFilter = mitk::ImageLiveWireContourModelFilter::New(); m_LiveWireFilter->SetInput(m_WorkingSlice); //map click to pixel coordinates mitk::Point3D click = const_cast(positionEvent->GetWorldPosition()); itk::Index<3> idx; m_WorkingSlice->GetGeometry()->WorldToIndex(click, idx); // get the pixel the gradient in region of 5x5 itk::Index<3> indexWithHighestGradient; AccessFixedDimensionByItk_2(m_WorkingSlice, FindHighestGradientMagnitudeByITK, 2, idx, indexWithHighestGradient); // itk::Index to mitk::Point3D click[0] = indexWithHighestGradient[0]; click[1] = indexWithHighestGradient[1]; click[2] = indexWithHighestGradient[2]; m_WorkingSlice->GetGeometry()->IndexToWorld(click, click); //set initial start point m_Contour->AddVertex( click, true, timestep ); m_LiveWireFilter->SetStartPoint(click); m_CreateAndUseDynamicCosts = true; //render assert( positionEvent->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); return true; } bool mitk::LiveWireTool2D::OnAddPoint (Action* action, const StateEvent* stateEvent) { //complete LiveWire interaction for last segment //add current LiveWire contour to the finished contour and reset //to start new segment and computation /* check if event can be handled */ const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; if ( Superclass::CanHandleEvent(stateEvent) < 1.0 ) return false; /* END check if event can be handled */ int timestep = positionEvent->GetSender()->GetTimeStep(); //add repulsive points to avoid to get the same path again typedef mitk::ImageLiveWireContourModelFilter::InternalImageType::IndexType IndexType; mitk::ContourModel::ConstVertexIterator iter = m_LiveWireContour->IteratorBegin(timestep); for (;iter != m_LiveWireContour->IteratorEnd(timestep); iter++) { IndexType idx; this->m_WorkingSlice->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx); this->m_LiveWireFilter->AddRepulsivePoint( idx ); } //remove duplicate first vertex, it's already contained in m_Contour m_LiveWireContour->RemoveVertexAt(0, timestep); // set last added point as control point m_LiveWireContour->SetControlVertexAt(m_LiveWireContour->GetNumberOfVertices(timestep)-1, timestep); //merge contours m_Contour->Concatenate(m_LiveWireContour, timestep); //clear the livewire contour and reset the corresponding datanode m_LiveWireContour->Clear(timestep); //set new start point m_LiveWireFilter->SetStartPoint(const_cast(positionEvent->GetWorldPosition())); if( m_CreateAndUseDynamicCosts ) { //use dynamic cost map for next update m_LiveWireFilter->CreateDynamicCostMap(m_Contour); m_LiveWireFilter->SetUseDynamicCostMap(true); //m_CreateAndUseDynamicCosts = false; } //render assert( positionEvent->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); return true; } bool mitk::LiveWireTool2D::OnMouseMoved( Action* action, const StateEvent* stateEvent) { //compute LiveWire segment from last control point to current mouse position // check if event can be handled if ( Superclass::CanHandleEvent(stateEvent) < 1.0 ) return false; const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; // actual LiveWire computation int timestep = positionEvent->GetSender()->GetTimeStep(); m_LiveWireFilter->SetEndPoint(const_cast(positionEvent->GetWorldPosition())); m_LiveWireFilter->SetTimeStep(m_TimeStep); m_LiveWireFilter->Update(); m_LiveWireContour = this->m_LiveWireFilter->GetOutput(); m_LiveWireContourNode->SetData( this->m_LiveWireContour ); //render assert( positionEvent->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); return true; } bool mitk::LiveWireTool2D::OnMouseMoveNoDynamicCosts(Action* action, const StateEvent* stateEvent) { //do not use dynamic cost map m_LiveWireFilter->SetUseDynamicCostMap(false); OnMouseMoved(action, stateEvent); m_LiveWireFilter->SetUseDynamicCostMap(true); return true; } bool mitk::LiveWireTool2D::OnCheckPoint( Action* action, const StateEvent* stateEvent) { //check double click on first control point to finish the LiveWire tool // //Check distance to first point. //Transition YES if click close to first control point // mitk::StateEvent* newStateEvent = NULL; const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) { //stay in current state newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent()); } else { int timestep = positionEvent->GetSender()->GetTimeStep(); mitk::Point3D click = positionEvent->GetWorldPosition(); mitk::Point3D first = this->m_Contour->GetVertexAt(0, timestep)->Coordinates; if (first.EuclideanDistanceTo(click) < 4.5) { // allow to finish newStateEvent = new mitk::StateEvent(EIDYES, stateEvent->GetEvent()); } else { //stay active newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent()); } } this->HandleEvent( newStateEvent ); return true; } bool mitk::LiveWireTool2D::OnFinish( Action* action, const StateEvent* stateEvent) { // finish livewire tool interaction // check if event can be handled if ( Superclass::CanHandleEvent(stateEvent) < 1.0 ) return false; const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; // actual timestep int timestep = positionEvent->GetSender()->GetTimeStep(); // remove last control point being added by double click m_Contour->RemoveVertexAt(m_Contour->GetNumberOfVertices(timestep) - 1, timestep); // save contour and corresponding plane geometry to list std::pair cp(m_ContourModelNode, dynamic_cast(positionEvent->GetSender()->GetCurrentWorldGeometry2D()->Clone().GetPointer()) ); this->m_WorkingContours.push_back(cp); std::pair ecp(m_EditingContourNode, dynamic_cast(positionEvent->GetSender()->GetCurrentWorldGeometry2D()->Clone().GetPointer()) ); this->m_EditingContours.push_back(ecp); m_LiveWireFilter->SetUseDynamicCostMap(false); this->FinishTool(); return true; } void mitk::LiveWireTool2D::FinishTool() { unsigned int numberOfTimesteps = m_Contour->GetTimeSlicedGeometry()->GetTimeSteps(); //close contour in each timestep for( int i = 0; i <= numberOfTimesteps; i++) { m_Contour->Close(i); } m_ToolManager->GetDataStorage()->Remove( m_LiveWireContourNode ); // clear live wire contour node m_LiveWireContourNode = NULL; m_LiveWireContour = NULL; //change color as visual feedback of completed livewire //m_ContourModelNode->AddProperty( "contour.color", ColorProperty::New(1.0, 1.0, 0.1), NULL, true ); //m_ContourModelNode->SetName("contour node"); //set the livewire interactor to edit control points m_ContourInteractor = mitk::ContourModelLiveWireInteractor::New(m_ContourModelNode); m_ContourInteractor->SetWorkingImage(this->m_WorkingSlice); m_ContourInteractor->SetEditingContourModelNode(this->m_EditingContourNode); m_ContourModelNode->SetInteractor(m_ContourInteractor); this->m_LiveWireInteractors.push_back( m_ContourInteractor ); //add interactor to globalInteraction instance mitk::GlobalInteraction::GetInstance()->AddInteractor(m_ContourInteractor); } bool mitk::LiveWireTool2D::OnLastSegmentDelete( Action* action, const StateEvent* stateEvent) { int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep(); //if last point of current contour will be removed go to start state and remove nodes if( m_Contour->GetNumberOfVertices(timestep) <= 1 ) { m_ToolManager->GetDataStorage()->Remove( m_LiveWireContourNode ); m_ToolManager->GetDataStorage()->Remove( m_ContourModelNode ); m_ToolManager->GetDataStorage()->Remove( m_EditingContourNode ); m_LiveWireContour = mitk::ContourModel::New(); m_Contour = mitk::ContourModel::New(); m_ContourModelNode->SetData( m_Contour ); m_LiveWireContourNode->SetData( m_LiveWireContour ); Superclass::Deactivated(); //go to start state } else //remove last segment from contour and reset livewire contour { m_LiveWireContour = mitk::ContourModel::New(); m_LiveWireContourNode->SetData(m_LiveWireContour); mitk::ContourModel::Pointer newContour = mitk::ContourModel::New(); newContour->Expand(m_Contour->GetTimeSteps()); mitk::ContourModel::VertexIterator begin = m_Contour->IteratorBegin(); //iterate from last point to next active point mitk::ContourModel::VertexIterator newLast = m_Contour->IteratorBegin() + (m_Contour->GetNumberOfVertices() - 1); //go at least one down if(newLast != begin) { newLast--; } //search next active control point while(newLast != begin && !((*newLast)->IsControlPoint) ) { newLast--; } //set position of start point for livewire filter to coordinates of the new last point m_LiveWireFilter->SetStartPoint((*newLast)->Coordinates); mitk::ContourModel::VertexIterator it = m_Contour->IteratorBegin(); //fill new Contour while(it <= newLast) { newContour->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timestep); it++; } newContour->SetIsClosed(m_Contour->IsClosed()); //set new contour visible m_ContourModelNode->SetData(newContour); m_Contour = newContour; assert( stateEvent->GetEvent()->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( stateEvent->GetEvent()->GetSender()->GetRenderWindow() ); } return true; } template void mitk::LiveWireTool2D::FindHighestGradientMagnitudeByITK(itk::Image* inputImage, itk::Index<3> &index, itk::Index<3> &returnIndex) { typedef itk::Image InputImageType; typedef typename InputImageType::IndexType IndexType; unsigned long xMAX = inputImage->GetLargestPossibleRegion().GetSize()[0]; unsigned long yMAX = inputImage->GetLargestPossibleRegion().GetSize()[1]; returnIndex[0] = index[0]; returnIndex[1] = index[1]; returnIndex[2] = 0.0; double gradientMagnitude = 0.0; double maxGradientMagnitude = 0.0; /* the size and thus the region of 7x7 is only used to calculate the gradient magnitude in that region not for searching the maximum value */ //maximum value in each direction for size typename InputImageType::SizeType size; size[0] = 7; size[1] = 7; //minimum value in each direction for startRegion IndexType startRegion; startRegion[0] = index[0] - 3; startRegion[1] = index[1] - 3; if(startRegion[0] < 0) startRegion[0] = 0; if(startRegion[1] < 0) startRegion[1] = 0; if(xMAX - index[0] < 7) startRegion[0] = xMAX - 7; if(yMAX - index[1] < 7) startRegion[1] = yMAX - 7; index[0] = startRegion[0] + 3; index[1] = startRegion[1] + 3; typename InputImageType::RegionType region; region.SetSize( size ); region.SetIndex( startRegion ); typedef typename itk::GradientMagnitudeImageFilter< InputImageType, InputImageType> GradientMagnitudeFilterType; typename GradientMagnitudeFilterType::Pointer gradientFilter = GradientMagnitudeFilterType::New(); gradientFilter->SetInput(inputImage); gradientFilter->GetOutput()->SetRequestedRegion(region); gradientFilter->Update(); typename InputImageType::Pointer gradientMagnImage; gradientMagnImage = gradientFilter->GetOutput(); IndexType currentIndex; currentIndex[0] = 0; currentIndex[1] = 0; // search max (approximate) gradient magnitude for( int x = -1; x <= 1; ++x) { currentIndex[0] = index[0] + x; for( int y = -1; y <= 1; ++y) { currentIndex[1] = index[1] + y; gradientMagnitude = gradientMagnImage->GetPixel(currentIndex); //check for new max if(maxGradientMagnitude < gradientMagnitude) { maxGradientMagnitude = gradientMagnitude; returnIndex[0] = currentIndex[0]; returnIndex[1] = currentIndex[1]; returnIndex[2] = 0.0; }//end if }//end for y currentIndex[1] = index[1]; }//end for x } diff --git a/Modules/Segmentation/Interactions/mitkLiveWireTool2D.h b/Modules/Segmentation/Interactions/mitkLiveWireTool2D.h index 1b7949cb01..decfade8db 100644 --- a/Modules/Segmentation/Interactions/mitkLiveWireTool2D.h +++ b/Modules/Segmentation/Interactions/mitkLiveWireTool2D.h @@ -1,145 +1,147 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkCorrectorTool2D_h_Included #define mitkCorrectorTool2D_h_Included #include "mitkCommon.h" #include "SegmentationExports.h" #include "mitkSegTool2D.h" #include #include #include +namespace us { class ModuleResource; +} namespace mitk { /** \brief A 2D segmentation tool based on LiveWire approach. The contour between the last user added point and the current mouse position is computed by searching the shortest path according to specific features of the image. The contour thus snappest to the boundary of objects. \sa SegTool2D \sa ImageLiveWireContourModelFilter \ingroup Interaction \ingroup ToolManagerEtAl \warning Only to be instantiated by mitk::ToolManager. */ class Segmentation_EXPORT LiveWireTool2D : public SegTool2D { public: mitkClassMacro(LiveWireTool2D, SegTool2D); itkNewMacro(LiveWireTool2D); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; /// \brief Convert all current contour objects to binary segmentation image. void ConfirmSegmentation(); protected: LiveWireTool2D(); virtual ~LiveWireTool2D(); /** * \brief Calculates how good the data, this statemachine handles, is hit by the event. * */ virtual float CanHandleEvent( StateEvent const *stateEvent) const; virtual void Activated(); virtual void Deactivated(); /// \brief Memory release from all used contours virtual void ClearContours(); /// \brief Initialize tool virtual bool OnInitLiveWire (Action*, const StateEvent*); /// \brief Add a control point and finish current segment virtual bool OnAddPoint (Action*, const StateEvent*); /// \brief Actual LiveWire computation virtual bool OnMouseMoved(Action*, const StateEvent*); /// \brief Check double click on first control point to finish the LiveWire tool virtual bool OnCheckPoint(Action*, const StateEvent*); /// \brief Finish LiveWire tool virtual bool OnFinish(Action*, const StateEvent*); /// \brief Close the contour virtual bool OnLastSegmentDelete(Action*, const StateEvent*); /// \brief Don't use dynamic cost map for LiveWire calculation virtual bool OnMouseMoveNoDynamicCosts(Action*, const StateEvent*); /// \brief Finish contour interaction. void FinishTool(); //the contour already set by the user mitk::ContourModel::Pointer m_Contour; //the corresponding datanode mitk::DataNode::Pointer m_ContourModelNode; //the current LiveWire computed contour mitk::ContourModel::Pointer m_LiveWireContour; //the corresponding datanode mitk::DataNode::Pointer m_LiveWireContourNode; // the contour for the editing portion mitk::ContourModel::Pointer m_EditingContour; //the corresponding datanode mitk::DataNode::Pointer m_EditingContourNode; // the corresponding contour interactor mitk::ContourModelLiveWireInteractor::Pointer m_ContourInteractor; //the current reference image mitk::Image::Pointer m_WorkingSlice; // the filter for live wire calculation mitk::ImageLiveWireContourModelFilter::Pointer m_LiveWireFilter; bool m_CreateAndUseDynamicCosts; std::vector< std::pair > m_WorkingContours; std::vector< std::pair > m_EditingContours; std::vector< mitk::ContourModelLiveWireInteractor::Pointer > m_LiveWireInteractors; template void FindHighestGradientMagnitudeByITK(itk::Image* inputImage, itk::Index<3> &index, itk::Index<3> &returnIndex); }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkOtsuTool3D.cpp b/Modules/Segmentation/Interactions/mitkOtsuTool3D.cpp index c528e5fb6c..ff87b74fad 100644 --- a/Modules/Segmentation/Interactions/mitkOtsuTool3D.cpp +++ b/Modules/Segmentation/Interactions/mitkOtsuTool3D.cpp @@ -1,217 +1,217 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // MITK #include "mitkOtsuTool3D.h" #include "mitkToolManager.h" #include "mitkRenderingManager.h" #include #include #include #include #include #include "mitkOtsuSegmentationFilter.h" // ITK #include #include #include "mitkRegionGrow3DTool.xpm" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, OtsuTool3D, "Otsu Segmentation"); } mitk::OtsuTool3D::OtsuTool3D() { } mitk::OtsuTool3D::~OtsuTool3D() { } void mitk::OtsuTool3D::Activated() { if (m_ToolManager) { m_OriginalImage = dynamic_cast(m_ToolManager->GetReferenceData(0)->GetData()); m_BinaryPreviewNode = mitk::DataNode::New(); m_BinaryPreviewNode->SetName("Binary_Preview"); //m_BinaryPreviewNode->SetBoolProperty("helper object", true); //m_BinaryPreviewNode->SetProperty("binary", mitk::BoolProperty::New(true)); m_ToolManager->GetDataStorage()->Add( this->m_BinaryPreviewNode ); m_MultiLabelResultNode = mitk::DataNode::New(); m_MultiLabelResultNode->SetName("Otsu_Preview"); //m_MultiLabelResultNode->SetBoolProperty("helper object", true); m_MultiLabelResultNode->SetVisibility(true); m_MaskedImagePreviewNode = mitk::DataNode::New(); m_MaskedImagePreviewNode->SetName("Volume_Preview"); //m_MultiLabelResultNode->SetBoolProperty("helper object", true); m_MaskedImagePreviewNode->SetVisibility(false); m_ToolManager->GetDataStorage()->Add( this->m_MultiLabelResultNode ); } } void mitk::OtsuTool3D::Deactivated() { m_ToolManager->GetDataStorage()->Remove( this->m_MultiLabelResultNode ); m_MultiLabelResultNode = NULL; m_ToolManager->GetDataStorage()->Remove( this->m_BinaryPreviewNode ); m_BinaryPreviewNode = NULL; m_ToolManager->ActivateTool(-1); } const char** mitk::OtsuTool3D::GetXPM() const { return NULL; } -mitk::ModuleResource mitk::OtsuTool3D::GetIconResource() const +us::ModuleResource mitk::OtsuTool3D::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Otsu_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Otsu_48x48.png"); return resource; } void mitk::OtsuTool3D::RunSegmentation(int regions) { //this->m_OtsuSegmentationDialog->setCursor(Qt::WaitCursor); int numberOfThresholds = regions - 1; mitk::OtsuSegmentationFilter::Pointer otsuFilter = mitk::OtsuSegmentationFilter::New(); otsuFilter->SetNumberOfThresholds( numberOfThresholds ); otsuFilter->SetInput( m_OriginalImage ); try { otsuFilter->Update(); } catch( ... ) { mitkThrow() << "itkOtsuFilter error (image dimension must be in {2, 3} and image must not be RGB)"; } m_ToolManager->GetDataStorage()->Remove( this->m_MultiLabelResultNode ); m_MultiLabelResultNode = NULL; m_MultiLabelResultNode = mitk::DataNode::New(); m_MultiLabelResultNode->SetName("Otsu_Preview"); m_MultiLabelResultNode->SetVisibility(true); m_ToolManager->GetDataStorage()->Add( this->m_MultiLabelResultNode ); m_MultiLabelResultNode->SetOpacity(1.0); this->m_MultiLabelResultNode->SetData( otsuFilter->GetOutput() ); m_MultiLabelResultNode->SetProperty("binary", mitk::BoolProperty::New(false)); mitk::RenderingModeProperty::Pointer renderingMode = mitk::RenderingModeProperty::New(); renderingMode->SetValue( mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR ); m_MultiLabelResultNode->SetProperty("Image Rendering.Mode", renderingMode); mitk::LookupTable::Pointer lut = mitk::LookupTable::New(); mitk::LookupTableProperty::Pointer prop = mitk::LookupTableProperty::New(lut); vtkLookupTable *lookupTable = vtkLookupTable::New(); lookupTable->SetHueRange(1.0, 0.0); lookupTable->SetSaturationRange(1.0, 1.0); lookupTable->SetValueRange(1.0, 1.0); lookupTable->SetTableRange(-1.0, 1.0); lookupTable->Build(); lut->SetVtkLookupTable(lookupTable); prop->SetLookupTable(lut); m_MultiLabelResultNode->SetProperty("LookupTable",prop); mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelwindow; levelwindow.SetRangeMinMax(0, numberOfThresholds + 1); levWinProp->SetLevelWindow( levelwindow ); m_MultiLabelResultNode->SetProperty( "levelwindow", levWinProp ); //m_BinaryPreviewNode->SetVisibility(false); // m_MultiLabelResultNode->SetVisibility(true); //this->m_OtsuSegmentationDialog->setCursor(Qt::ArrowCursor); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::OtsuTool3D::ConfirmSegmentation() { GetTargetSegmentationNode()->SetData(dynamic_cast(m_BinaryPreviewNode->GetData())); } void mitk::OtsuTool3D::UpdateBinaryPreview(int regionID) { m_MultiLabelResultNode->SetVisibility(false); //pixel with regionID -> binary image const unsigned short dim = 3; typedef unsigned char PixelType; typedef itk::Image< PixelType, dim > InputImageType; typedef itk::Image< PixelType, dim > OutputImageType; typedef itk::BinaryThresholdImageFilter< InputImageType, OutputImageType > FilterType; FilterType::Pointer filter = FilterType::New(); InputImageType::Pointer itkImage; mitk::Image::Pointer multiLabelSegmentation = dynamic_cast(m_MultiLabelResultNode->GetData()); mitk::CastToItkImage(multiLabelSegmentation, itkImage); filter->SetInput(itkImage); filter->SetLowerThreshold(regionID); filter->SetUpperThreshold(regionID); filter->Update(); mitk::Image::Pointer binarySegmentation; mitk::CastToMitkImage( filter->GetOutput(), binarySegmentation); m_BinaryPreviewNode->SetData(binarySegmentation); m_BinaryPreviewNode->SetVisibility(true); m_BinaryPreviewNode->SetProperty("outline binary", mitk::BoolProperty::New(false)); m_BinaryPreviewNode->SetOpacity(1.0); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } const char* mitk::OtsuTool3D::GetName() const { return "Otsu"; } void mitk::OtsuTool3D::UpdateVolumePreview(bool volumeRendering) { if (volumeRendering) { m_MaskedImagePreviewNode->SetBoolProperty("volumerendering", true); m_MaskedImagePreviewNode->SetBoolProperty("volumerendering.uselod", true); } else { m_MaskedImagePreviewNode->SetBoolProperty("volumerendering", false); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::OtsuTool3D::ShowMultiLabelResultNode(bool show) { m_MultiLabelResultNode->SetVisibility(show); m_BinaryPreviewNode->SetVisibility(!show); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } diff --git a/Modules/Segmentation/Interactions/mitkOtsuTool3D.h b/Modules/Segmentation/Interactions/mitkOtsuTool3D.h index 7c4c62a4e3..8a9cff314a 100644 --- a/Modules/Segmentation/Interactions/mitkOtsuTool3D.h +++ b/Modules/Segmentation/Interactions/mitkOtsuTool3D.h @@ -1,59 +1,61 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKOTSUTOOL3D_H #define MITKOTSUTOOL3D_H #include "SegmentationExports.h" #include "mitkAutoSegmentationTool.h" +namespace us { class ModuleResource; +} namespace mitk{ class Segmentation_EXPORT OtsuTool3D : public AutoSegmentationTool { public: mitkClassMacro(OtsuTool3D, AutoSegmentationTool); itkNewMacro(OtsuTool3D); virtual const char* GetName() const; virtual const char** GetXPM() const; - ModuleResource GetIconResource() const; + us::ModuleResource GetIconResource() const; virtual void Activated(); virtual void Deactivated(); void RunSegmentation( int regions); void ConfirmSegmentation(); void UpdateBinaryPreview(int regionID); void UpdateVolumePreview(bool volumeRendering); void ShowMultiLabelResultNode(bool); protected: OtsuTool3D(); virtual ~OtsuTool3D(); mitk::Image::Pointer m_OriginalImage; //holds the user selected binary segmentation mitk::DataNode::Pointer m_BinaryPreviewNode; //holds the multilabel result as a preview image mitk::DataNode::Pointer m_MultiLabelResultNode; //holds the user selected binary segmentation masked original image mitk::DataNode::Pointer m_MaskedImagePreviewNode; };//class }//namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkRegionGrowingTool.cpp b/Modules/Segmentation/Interactions/mitkRegionGrowingTool.cpp index c64a33863a..2137b426f7 100644 --- a/Modules/Segmentation/Interactions/mitkRegionGrowingTool.cpp +++ b/Modules/Segmentation/Interactions/mitkRegionGrowingTool.cpp @@ -1,694 +1,695 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkRegionGrowingTool.h" #include "mitkToolManager.h" #include "mitkOverwriteSliceImageFilter.h" #include "mitkImageDataItem.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include "mitkApplicationCursor.h" #include "ipSegmentation.h" #include "mitkRegionGrowingTool.xpm" #include "mitkOverwriteDirectedPlaneImageFilter.h" #include "mitkExtractDirectedPlaneImageFilterNew.h" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, RegionGrowingTool, "Region growing tool"); } #define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a))) mitk::RegionGrowingTool::RegionGrowingTool() :FeedbackContourTool("PressMoveRelease"), m_LowerThreshold(200), m_UpperThreshold(200), m_InitialLowerThreshold(200), m_InitialUpperThreshold(200), m_ScreenYDifference(0), m_OriginalPicSlice(NULL), m_SeedPointMemoryOffset(0), m_VisibleWindow(0), m_DefaultWindow(0), m_MouseDistanceScaleFactor(0.5), m_LastWorkingSeed(-1), m_FillFeedbackContour(true) { // great magic numbers CONNECT_ACTION( 80, OnMousePressed ); CONNECT_ACTION( 90, OnMouseMoved ); CONNECT_ACTION( 42, OnMouseReleased ); } mitk::RegionGrowingTool::~RegionGrowingTool() { } const char** mitk::RegionGrowingTool::GetXPM() const { return mitkRegionGrowingTool_xpm; } -mitk::ModuleResource mitk::RegionGrowingTool::GetIconResource() const +us::ModuleResource mitk::RegionGrowingTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("RegionGrowing_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("RegionGrowing_48x48.png"); return resource; } -mitk::ModuleResource mitk::RegionGrowingTool::GetCursorIconResource() const +us::ModuleResource mitk::RegionGrowingTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("RegionGrowing_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("RegionGrowing_Cursor_32x32.png"); return resource; } const char* mitk::RegionGrowingTool::GetName() const { return "Region Growing"; } void mitk::RegionGrowingTool::Activated() { Superclass::Activated(); } void mitk::RegionGrowingTool::Deactivated() { Superclass::Deactivated(); } /** 1 Determine which slice is clicked into 2 Determine if the user clicked inside or outside of the segmentation 3 Depending on the pixel value under the mouse click position, two different things happen: (separated out into OnMousePressedInside and OnMousePressedOutside) 3.1 Create a skeletonization of the segmentation and try to find a nice cut 3.1.1 Call a ipSegmentation algorithm to create a nice cut 3.1.2 Set the result of this algorithm as the feedback contour 3.2 Initialize region growing 3.2.1 Determine memory offset inside the original image 3.2.2 Determine initial region growing parameters from the level window settings of the image 3.2.3 Perform a region growing (which generates a new feedback contour) */ bool mitk::RegionGrowingTool::OnMousePressed (Action* action, const StateEvent* stateEvent) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; m_LastEventSender = positionEvent->GetSender(); m_LastEventSlice = m_LastEventSender->GetSlice(); //ToolLogger::SetVerboseness(3); MITK_DEBUG << "OnMousePressed" << std::endl; if ( FeedbackContourTool::CanHandleEvent(stateEvent) > 0.0 ) { MITK_DEBUG << "OnMousePressed: FeedbackContourTool says ok" << std::endl; // 1. Find out which slice the user clicked, find out which slice of the toolmanager's reference and working image corresponds to that if (positionEvent) { MITK_DEBUG << "OnMousePressed: got positionEvent" << std::endl; m_ReferenceSlice = FeedbackContourTool::GetAffectedReferenceSlice( positionEvent ); m_WorkingSlice = FeedbackContourTool::GetAffectedWorkingSlice( positionEvent ); if ( m_WorkingSlice.IsNotNull() ) // can't do anything without the segmentation { MITK_DEBUG << "OnMousePressed: got working slice" << std::endl; // 2. Determine if the user clicked inside or outside of the segmentation const Geometry3D* workingSliceGeometry = m_WorkingSlice->GetGeometry(); Point3D mprojectedPointIn2D; workingSliceGeometry->WorldToIndex( positionEvent->GetWorldPosition(), mprojectedPointIn2D); itk::Index<2> projectedPointInWorkingSlice2D; projectedPointInWorkingSlice2D[0] = static_cast( mprojectedPointIn2D[0] - 0.5 ); projectedPointInWorkingSlice2D[1] = static_cast( mprojectedPointIn2D[1] - 0.5 ); if ( workingSliceGeometry->IsIndexInside( projectedPointInWorkingSlice2D ) ) { MITK_DEBUG << "OnMousePressed: point " << positionEvent->GetWorldPosition() << " (index coordinates " << projectedPointInWorkingSlice2D << ") IS in working slice" << std::endl; // Convert to ipMITKSegmentationTYPE (because getting pixels relys on that data type) itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage; CastToItkImage( m_WorkingSlice, correctPixelTypeImage ); assert (correctPixelTypeImage.IsNotNull() ); // possible bug in CastToItkImage ? // direction maxtrix is wrong/broken/not working after CastToItkImage, leading to a failed assertion in // mitk/Core/DataStructures/mitkSlicedGeometry3D.cpp, 479: // virtual void mitk::SlicedGeometry3D::SetSpacing(const mitk::Vector3D&): Assertion `aSpacing[0]>0 && aSpacing[1]>0 && aSpacing[2]>0' failed // solution here: we overwrite it with an unity matrix itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection; imageDirection.SetIdentity(); correctPixelTypeImage->SetDirection(imageDirection); Image::Pointer temporarySlice = Image::New(); // temporarySlice = ImportItkImage( correctPixelTypeImage ); CastToMitkImage( correctPixelTypeImage, temporarySlice ); mitkIpPicDescriptor* workingPicSlice = mitkIpPicNew(); CastToIpPicDescriptor(temporarySlice, workingPicSlice); int initialWorkingOffset = projectedPointInWorkingSlice2D[1] * workingPicSlice->n[0] + projectedPointInWorkingSlice2D[0]; if ( initialWorkingOffset < static_cast( workingPicSlice->n[0] * workingPicSlice->n[1] ) && initialWorkingOffset >= 0 ) { // 3. determine the pixel value under the last click bool inside = static_cast(workingPicSlice->data)[initialWorkingOffset] != 0; m_PaintingPixelValue = inside ? 0 : 1; // if inside, we want to remove a part, otherwise we want to add something if ( m_LastWorkingSeed >= static_cast( workingPicSlice->n[0] * workingPicSlice->n[1] ) || m_LastWorkingSeed < 0 ) { inside = false; } if ( m_ReferenceSlice.IsNotNull() ) { MITK_DEBUG << "OnMousePressed: got reference slice" << std::endl; m_OriginalPicSlice = mitkIpPicNew(); CastToIpPicDescriptor(m_ReferenceSlice, m_OriginalPicSlice); // 3.1. Switch depending on the pixel value if (inside) { OnMousePressedInside(action, stateEvent, workingPicSlice, initialWorkingOffset); } else { OnMousePressedOutside(action, stateEvent); } } } } } } } MITK_DEBUG << "end OnMousePressed" << std::endl; return true; } /** 3.1 Create a skeletonization of the segmentation and try to find a nice cut 3.1.1 Call a ipSegmentation algorithm to create a nice cut 3.1.2 Set the result of this algorithm as the feedback contour */ bool mitk::RegionGrowingTool::OnMousePressedInside(Action* itkNotUsed( action ), const StateEvent* stateEvent, mitkIpPicDescriptor* workingPicSlice, int initialWorkingOffset) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); // checked in OnMousePressed // 3.1.1. Create a skeletonization of the segmentation and try to find a nice cut // apply the skeletonization-and-cut algorithm // generate contour to remove // set m_ReferenceSlice = NULL so nothing will happen during mouse move // remember to fill the contour with 0 in mouserelease mitkIpPicDescriptor* segmentationHistory = ipMITKSegmentationCreateGrowerHistory( workingPicSlice, m_LastWorkingSeed, NULL ); // free again if (segmentationHistory) { tCutResult cutContour = ipMITKSegmentationGetCutPoints( workingPicSlice, segmentationHistory, initialWorkingOffset ); // tCutResult is a ipSegmentation type mitkIpPicFree( segmentationHistory ); if (cutContour.cutIt) { int timestep = positionEvent->GetSender()->GetTimeStep(); // 3.1.2 copy point from float* to mitk::Contour ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New(); contourInImageIndexCoordinates->Expand(timestep + 1); contourInImageIndexCoordinates->SetIsClosed(true, timestep); Point3D newPoint; for (int index = 0; index < cutContour.deleteSize; ++index) { newPoint[0] = cutContour.deleteCurve[ 2 * index + 0 ] - 0.5;//correction is needed because the output of the algorithm is center based newPoint[1] = cutContour.deleteCurve[ 2 * index + 1 ] - 0.5;//and we want our contour displayed corner based. newPoint[2] = 0.0; contourInImageIndexCoordinates->AddVertex( newPoint, timestep ); } free(cutContour.traceline); free(cutContour.deleteCurve); // perhaps visualize this for fun? free(cutContour.onGradient); ContourModel::Pointer contourInWorldCoordinates = FeedbackContourTool::BackProjectContourFrom2DSlice( m_WorkingSlice->GetGeometry(), contourInImageIndexCoordinates, true ); // true: sub 0.5 for ipSegmentation correction FeedbackContourTool::SetFeedbackContour( *contourInWorldCoordinates ); FeedbackContourTool::SetFeedbackContourVisible(true); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); m_FillFeedbackContour = true; } else { m_FillFeedbackContour = false; } } else { m_FillFeedbackContour = false; } m_ReferenceSlice = NULL; return true; } /** 3.2 Initialize region growing 3.2.1 Determine memory offset inside the original image 3.2.2 Determine initial region growing parameters from the level window settings of the image 3.2.3 Perform a region growing (which generates a new feedback contour) */ bool mitk::RegionGrowingTool::OnMousePressedOutside(Action* itkNotUsed( action ), const StateEvent* stateEvent) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); // checked in OnMousePressed // 3.2 If we have a reference image, then perform an initial region growing, considering the reference image's level window // if click was outside the image, don't continue const Geometry3D* sliceGeometry = m_ReferenceSlice->GetGeometry(); Point3D mprojectedPointIn2D; sliceGeometry->WorldToIndex( positionEvent->GetWorldPosition(), mprojectedPointIn2D ); itk::Index<2> projectedPointIn2D; projectedPointIn2D[0] = static_cast( mprojectedPointIn2D[0] - 0.5 ); projectedPointIn2D[1] = static_cast( mprojectedPointIn2D[1] - 0.5 ); if ( sliceGeometry->IsIndexInside( mprojectedPointIn2D ) ) { MITK_DEBUG << "OnMousePressed: point " << positionEvent->GetWorldPosition() << " (index coordinates " << mprojectedPointIn2D << ") IS in reference slice" << std::endl; // 3.2.1 Remember Y cursor position and initial seed point //m_ScreenYPositionAtStart = static_cast(positionEvent->GetDisplayPosition()[1]); m_LastScreenPosition = ApplicationCursor::GetInstance()->GetCursorPosition(); m_ScreenYDifference = 0; m_SeedPointMemoryOffset = projectedPointIn2D[1] * m_OriginalPicSlice->n[0] + projectedPointIn2D[0]; m_LastWorkingSeed = m_SeedPointMemoryOffset; // remember for skeletonization if ( m_SeedPointMemoryOffset < static_cast( m_OriginalPicSlice->n[0] * m_OriginalPicSlice->n[1] ) && m_SeedPointMemoryOffset >= 0 ) { // 3.2.2 Get level window from reference DataNode // Use some logic to determine initial gray value bounds LevelWindow lw(0, 500); m_ToolManager->GetReferenceData(0)->GetLevelWindow(lw); // will fill lw if levelwindow property is present, otherwise won't touch it. ScalarType currentVisibleWindow = lw.GetWindow(); if (!mitk::Equal(currentVisibleWindow, m_VisibleWindow)) { m_InitialLowerThreshold = currentVisibleWindow / 20.0; m_InitialUpperThreshold = currentVisibleWindow / 20.0; m_LowerThreshold = m_InitialLowerThreshold; m_UpperThreshold = m_InitialUpperThreshold; // 3.2.3. Actually perform region growing mitkIpPicDescriptor* result = PerformRegionGrowingAndUpdateContour(positionEvent->GetSender()->GetTimeStep()); ipMITKSegmentationFree( result); // display the contour FeedbackContourTool::SetFeedbackContourVisible(true); mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); m_FillFeedbackContour = true; } } return true; } return false; } /** If in region growing mode (m_ReferenceSlice != NULL), then 1. Calculate the new thresholds from mouse position (relative to first position) 2. Perform a new region growing and update the feedback contour */ bool mitk::RegionGrowingTool::OnMouseMoved(Action* action, const StateEvent* stateEvent) { if ( FeedbackContourTool::CanHandleEvent(stateEvent) > 0.0 ) { if ( m_ReferenceSlice.IsNotNull() && m_OriginalPicSlice ) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (positionEvent) { ApplicationCursor* cursor = ApplicationCursor::GetInstance(); if (!cursor) return false; m_ScreenYDifference += cursor->GetCursorPosition()[1] - m_LastScreenPosition[1]; cursor->SetCursorPosition( m_LastScreenPosition ); m_LowerThreshold = std::max(0.0, m_InitialLowerThreshold - m_ScreenYDifference * m_MouseDistanceScaleFactor); m_UpperThreshold = std::max(0.0, m_InitialUpperThreshold - m_ScreenYDifference * m_MouseDistanceScaleFactor); // 2. Perform region growing again and show the result mitkIpPicDescriptor* result = PerformRegionGrowingAndUpdateContour(positionEvent->GetSender()->GetTimeStep()); ipMITKSegmentationFree( result ); // 3. Update the contour mitk::RenderingManager::GetInstance()->ForceImmediateUpdate(positionEvent->GetSender()->GetRenderWindow()); } } } return true; } /** If the feedback contour should be filled, then it is done here. (Contour is NOT filled, when skeletonization is done but no nice cut was found) */ bool mitk::RegionGrowingTool::OnMouseReleased(Action* action, const StateEvent* stateEvent) { if ( FeedbackContourTool::CanHandleEvent(stateEvent) > 0.0 ) { // 1. If we have a working slice, use the contour to fill a new piece on segmentation on it (or erase a piece that was selected by ipMITKSegmentationGetCutPoints) if ( m_WorkingSlice.IsNotNull() && m_OriginalPicSlice ) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (positionEvent) { // remember parameters for next time m_InitialLowerThreshold = m_LowerThreshold; m_InitialUpperThreshold = m_UpperThreshold; int timestep = positionEvent->GetSender()->GetTimeStep(); if (m_FillFeedbackContour) { // 3. use contour to fill a region in our working slice ContourModel* feedbackContour( FeedbackContourTool::GetFeedbackContour() ); if (feedbackContour) { ContourModel::Pointer projectedContour = FeedbackContourTool::ProjectContourTo2DSlice( m_WorkingSlice, feedbackContour, false, false ); // false: don't add any 0.5 // false: don't constrain the contour to the image's inside if (projectedContour.IsNotNull()) { FeedbackContourTool::FillContourInSlice( projectedContour, timestep, m_WorkingSlice, m_PaintingPixelValue ); const PlaneGeometry* planeGeometry( dynamic_cast (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) ); //MITK_DEBUG << "OnMouseReleased: writing back to dimension " << affectedDimension << ", slice " << affectedSlice << " in working image" << std::endl; // 4. write working slice back into image volume this->WriteBackSegmentationResult(positionEvent, m_WorkingSlice); } } } FeedbackContourTool::SetFeedbackContourVisible(false); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); } } } m_ReferenceSlice = NULL; // don't leak m_WorkingSlice = NULL; m_OriginalPicSlice = NULL; return true; } /** Uses ipSegmentation algorithms to do the actual region growing. The result (binary image) is first smoothed by a 5x5 circle mask, then its contour is extracted and converted to MITK coordinates. */ mitkIpPicDescriptor* mitk::RegionGrowingTool::PerformRegionGrowingAndUpdateContour(int timestep) { // 1. m_OriginalPicSlice and m_SeedPointMemoryOffset are set to sensitive values, as well as m_LowerThreshold and m_UpperThreshold assert (m_OriginalPicSlice); if (m_OriginalPicSlice->n[0] != 256 || m_OriginalPicSlice->n[1] != 256) // ??? assert( (m_SeedPointMemoryOffset < static_cast( m_OriginalPicSlice->n[0] * m_OriginalPicSlice->n[1] )) && (m_SeedPointMemoryOffset >= 0) ); // inside the image // 2. ipSegmentation is used to perform region growing float ignored; int oneContourOffset( 0 ); mitkIpPicDescriptor* regionGrowerResult = ipMITKSegmentationGrowRegion4N( m_OriginalPicSlice, m_SeedPointMemoryOffset, // seed point true, // grayvalue interval relative to seed point gray value? m_LowerThreshold, m_UpperThreshold, 0, // continue until done (maxIterations == 0) NULL, // allocate new memory (only this time, on mouse move we'll reuse the old buffer) oneContourOffset, // a pixel that is near the resulting contour ignored // ignored by us ); if (!regionGrowerResult || oneContourOffset == -1) { ContourModel::Pointer dummyContour = ContourModel::New(); dummyContour->Initialize(); FeedbackContourTool::SetFeedbackContour( *dummyContour ); if (regionGrowerResult) ipMITKSegmentationFree(regionGrowerResult); return NULL; } // 3. We smooth the result a little to reduce contour complexity bool smoothResult( true ); // currently fixed, perhaps remove else block mitkIpPicDescriptor* smoothedRegionGrowerResult; if (smoothResult) { // Smooth the result (otherwise very detailed contour) smoothedRegionGrowerResult = SmoothIPPicBinaryImage( regionGrowerResult, oneContourOffset ); ipMITKSegmentationFree( regionGrowerResult ); } else { smoothedRegionGrowerResult = regionGrowerResult; } // 4. convert the result of region growing into a mitk::Contour // At this point oneContourOffset could be useless, if smoothing destroyed a thin bridge. In these // cases, we have two or more unconnected segmentation regions, and we don't know, which one is touched by oneContourOffset. // In the bad case, the contour is not the one around our seedpoint, so the result looks very strange to the user. // -> we remove the point where the contour started so far. Then we look from the bottom of the image for the first segmentation pixel // and start another contour extraction from there. This is done, until the seedpoint is inside the contour int numberOfContourPoints( 0 ); int newBufferSize( 0 ); float* contourPoints = ipMITKSegmentationGetContour8N( smoothedRegionGrowerResult, oneContourOffset, numberOfContourPoints, newBufferSize ); // memory allocated with malloc if (contourPoints) { while ( !ipMITKSegmentationIsInsideContour( contourPoints, // contour numberOfContourPoints, // points in contour m_SeedPointMemoryOffset % smoothedRegionGrowerResult->n[0], // test point x m_SeedPointMemoryOffset / smoothedRegionGrowerResult->n[0] // test point y ) ) { // we decide that this cannot be part of the segmentation because the seedpoint is not contained in the contour (fill the 4-neighborhood with 0) ipMITKSegmentationReplaceRegion4N( smoothedRegionGrowerResult, oneContourOffset, 0 ); // move the contour offset to the last row (x position of the seed point) int rowLength = smoothedRegionGrowerResult->n[0]; // number of pixels in a row oneContourOffset = m_SeedPointMemoryOffset % smoothedRegionGrowerResult->n[0] // x of seed point + rowLength*(smoothedRegionGrowerResult->n[1]-1); // y of last row while ( oneContourOffset >=0 && (*(static_cast(smoothedRegionGrowerResult->data) + oneContourOffset) == 0) ) { oneContourOffset -= rowLength; // if pixel at data+oneContourOffset is 0, then move up one row } if ( oneContourOffset < 0 ) { break; // just use the last contour we found } free(contourPoints); // release contour memory contourPoints = ipMITKSegmentationGetContour8N( smoothedRegionGrowerResult, oneContourOffset, numberOfContourPoints, newBufferSize ); // memory allocated with malloc } // copy point from float* to mitk::Contour ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New(); contourInImageIndexCoordinates->Expand(timestep + 1); contourInImageIndexCoordinates->SetIsClosed(true, timestep); Point3D newPoint; for (int index = 0; index < numberOfContourPoints; ++index) { newPoint[0] = contourPoints[ 2 * index + 0 ] - 0.5;//correction is needed because the output of the algorithm is center based newPoint[1] = contourPoints[ 2 * index + 1 ] - 0.5;//and we want our contour displayed corner based. newPoint[2] = 0; contourInImageIndexCoordinates->AddVertex( newPoint, timestep ); } free(contourPoints); ContourModel::Pointer contourInWorldCoordinates = FeedbackContourTool::BackProjectContourFrom2DSlice( m_ReferenceSlice->GetGeometry(), contourInImageIndexCoordinates, true ); // true: sub 0.5 for ipSegmentation correctio FeedbackContourTool::SetFeedbackContour( *contourInWorldCoordinates ); } // 5. Result HAS TO BE freed by caller, contains the binary region growing result return smoothedRegionGrowerResult; } /** Helper method for SmoothIPPicBinaryImage. Smoothes a given part of and image. \param sourceImage The original binary image. \param dest The smoothed image (will be written without bounds checking). \param contourOfs One offset of the contour. Is updated if a pixel is changed (which might change the contour). \param maskOffsets Memory offsets that describe the smoothing mask. \param maskSize Entries of the mask. \param startOffset First pixel that should be smoothed using this mask. \param endOffset Last pixel that should be smoothed using this mask. */ void mitk::RegionGrowingTool::SmoothIPPicBinaryImageHelperForRows( mitkIpPicDescriptor* sourceImage, mitkIpPicDescriptor* dest, int &contourOfs, int* maskOffsets, int maskSize, int startOffset, int endOffset ) { // work on the very first row ipMITKSegmentationTYPE* current; ipMITKSegmentationTYPE* source = ((ipMITKSegmentationTYPE*)sourceImage->data) + startOffset; // + 1! don't read at start-1 ipMITKSegmentationTYPE* end = ((ipMITKSegmentationTYPE*)dest->data) + endOffset; int ofs = startOffset; int minority = (maskSize - 1) / 2; for (current = ((ipMITKSegmentationTYPE*)dest->data) + startOffset; current minority) { *current = 1; contourOfs = ofs; } else { *current = 0; } ++source; ++ofs; } } /** Smoothes a binary ipPic image with a 5x5 mask. The image borders (some first and last rows) are treated differently. */ mitkIpPicDescriptor* mitk::RegionGrowingTool::SmoothIPPicBinaryImage( mitkIpPicDescriptor* image, int &contourOfs, mitkIpPicDescriptor* dest ) { if (!image) return NULL; // Original code from /trunk/mbi-qm/Qmitk/Qmitk2DSegTools/RegionGrowerTool.cpp (first version by T. Boettger?). Reformatted and documented and restructured. #define MSK_SIZE5x5 21 #define MSK_SIZE3x3 5 #define MSK_SIZE3x1 3 // mask is an array of coordinates that form a rastered circle like this // // OOO // OOOOO // OOOOO // OOOOO // OOO // // int mask5x5[MSK_SIZE5x5][2] = { /******/ {-1,-2}, {0,-2}, {1,-2}, /*****/ {-2,-1}, {-1,-1}, {0,-1}, {1,-1}, {2,-1}, {-2, 0}, {-1, 0}, {0, 0}, {1, 0}, {2, 0}, {-2, 1}, {-1, 1}, {0, 1}, {1, 1}, {2, 1}, /******/ {-1, 2}, {0, 2}, {1, 2} /*****/ }; int mask3x3[MSK_SIZE3x3][2] = { /******/ {0,-1}, /*****/ {-1, 0}, {0, 0}, {1, 0}, /******/ {0, 1} /*****/ }; int mask3x1[MSK_SIZE3x1][2] = { {-1, 0}, {0, 0}, {1, 0} }; // The following lines iterate over all the pixels of a (sliced) image (except the first and last three rows). // For each pixel, all the coordinates around it (according to mask) are evaluated (this means 21 pixels). // If more than 10 of the evaluated pixels are non-zero, then the central pixel is set to 1, else to 0. // This is determining a majority. If there is no clear majority, then the central pixel itself "decides". int maskOffset5x5[MSK_SIZE5x5]; int line = image->n[0]; for (int i=0; in[0]; int spareOut1Rows = 1*image->n[0]; if ( image->n[1] > 0 ) SmoothIPPicBinaryImageHelperForRows( image, dest, contourOfs, maskOffset3x1, MSK_SIZE3x1, 1, dest->n[0] ); if ( image->n[1] > 3 ) SmoothIPPicBinaryImageHelperForRows( image, dest, contourOfs, maskOffset3x3, MSK_SIZE3x3, spareOut1Rows, dest->n[0]*3 ); if ( image->n[1] > 6 ) SmoothIPPicBinaryImageHelperForRows( image, dest, contourOfs, maskOffset5x5, MSK_SIZE5x5, spareOut3Rows, dest->n[0]*dest->n[1] - spareOut3Rows ); if ( image->n[1] > 8 ) SmoothIPPicBinaryImageHelperForRows( image, dest, contourOfs, maskOffset3x3, MSK_SIZE3x3, dest->n[0]*dest->n[1] -spareOut3Rows, dest->n[0]*dest->n[1] - spareOut1Rows ); if ( image->n[1] > 10) SmoothIPPicBinaryImageHelperForRows( image, dest, contourOfs, maskOffset3x1, MSK_SIZE3x1, dest->n[0]*dest->n[1] -spareOut1Rows, dest->n[0]*dest->n[1] - 1 ); // correction for first pixel (sorry for the ugliness) if ( *((ipMITKSegmentationTYPE*)(dest->data)+1) == 1 ) { *((ipMITKSegmentationTYPE*)(dest->data)+0) = 1; } if (dest->n[0] * dest->n[1] > 2) { // correction for last pixel if ( *((ipMITKSegmentationTYPE*)(dest->data)+dest->n[0]*dest->n[1]-2) == 1 ) { *((ipMITKSegmentationTYPE*)(dest->data)+dest->n[0]*dest->n[1]-1) = 1; } } return dest; } diff --git a/Modules/Segmentation/Interactions/mitkRegionGrowingTool.h b/Modules/Segmentation/Interactions/mitkRegionGrowingTool.h index aa243cbfb5..7923bdc597 100644 --- a/Modules/Segmentation/Interactions/mitkRegionGrowingTool.h +++ b/Modules/Segmentation/Interactions/mitkRegionGrowingTool.h @@ -1,119 +1,121 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkRegionGrowingTool_h_Included #define mitkRegionGrowingTool_h_Included #include "mitkFeedbackContourTool.h" #include "mitkLegacyAdaptors.h" #include "SegmentationExports.h" struct mitkIpPicDescriptor; +namespace us { class ModuleResource; +} namespace mitk { /** \brief A slice based region growing tool. \sa FeedbackContourTool \ingroup Interaction \ingroup ToolManagerEtAl When the user presses the mouse button, RegionGrowingTool will use the gray values at that position to initialize a region growing algorithm (in the affected 2D slice). By moving the mouse up and down while the button is still pressed, the user can change the parameters of the region growing algorithm (selecting more or less of an object). The current result of region growing will always be shown as a contour to the user. After releasing the button, the current result of the region growing algorithm will be written to the working image of this tool's ToolManager. If the first click is inside a segmentation that was generated by region growing (recently), the tool will try to cut off a part of the segmentation. For this reason a skeletonization of the segmentation is generated and the optimal cut point is determined. \warning Only to be instantiated by mitk::ToolManager. $Author$ */ class Segmentation_EXPORT RegionGrowingTool : public FeedbackContourTool { public: mitkClassMacro(RegionGrowingTool, FeedbackContourTool); itkNewMacro(RegionGrowingTool); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; protected: RegionGrowingTool(); // purposely hidden virtual ~RegionGrowingTool(); virtual void Activated(); virtual void Deactivated(); virtual bool OnMousePressed (Action*, const StateEvent*); virtual bool OnMousePressedInside (Action*, const StateEvent*, mitkIpPicDescriptor* workingPicSlice, int initialWorkingOffset); virtual bool OnMousePressedOutside (Action*, const StateEvent*); virtual bool OnMouseMoved (Action*, const StateEvent*); virtual bool OnMouseReleased(Action*, const StateEvent*); mitkIpPicDescriptor* PerformRegionGrowingAndUpdateContour(int timestep=0); Image::Pointer m_ReferenceSlice; Image::Pointer m_WorkingSlice; ScalarType m_LowerThreshold; ScalarType m_UpperThreshold; ScalarType m_InitialLowerThreshold; ScalarType m_InitialUpperThreshold; Point2I m_LastScreenPosition; int m_ScreenYDifference; private: mitkIpPicDescriptor* SmoothIPPicBinaryImage( mitkIpPicDescriptor* image, int &contourOfs, mitkIpPicDescriptor* dest = NULL ); void SmoothIPPicBinaryImageHelperForRows( mitkIpPicDescriptor* source, mitkIpPicDescriptor* dest, int &contourOfs, int* maskOffsets, int maskSize, int startOffset, int endOffset ); mitkIpPicDescriptor* m_OriginalPicSlice; int m_SeedPointMemoryOffset; ScalarType m_VisibleWindow; ScalarType m_DefaultWindow; ScalarType m_MouseDistanceScaleFactor; int m_PaintingPixelValue; int m_LastWorkingSeed; bool m_FillFeedbackContour; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkSegTool2D.cpp b/Modules/Segmentation/Interactions/mitkSegTool2D.cpp index 8fb2bbff62..d5cef9b0c4 100644 --- a/Modules/Segmentation/Interactions/mitkSegTool2D.cpp +++ b/Modules/Segmentation/Interactions/mitkSegTool2D.cpp @@ -1,400 +1,402 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSegTool2D.h" #include "mitkToolManager.h" #include "mitkDataStorage.h" #include "mitkBaseRenderer.h" #include "mitkPlaneGeometry.h" #include "mitkExtractImageFilter.h" #include "mitkExtractDirectedPlaneImageFilter.h" //Include of the new ImageExtractor #include "mitkExtractDirectedPlaneImageFilterNew.h" #include "mitkPlanarCircle.h" #include "mitkOverwriteSliceImageFilter.h" #include "mitkOverwriteDirectedPlaneImageFilter.h" -#include "mitkGetModuleContext.h" +#include "usGetModuleContext.h" //Includes for 3DSurfaceInterpolation #include "mitkImageToContourFilter.h" #include "mitkSurfaceInterpolationController.h" //includes for resling and overwriting #include #include #include #include #include #include "mitkOperationEvent.h" #include "mitkUndoController.h" #define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a))) mitk::SegTool2D::SegTool2D(const char* type) :Tool(type), m_LastEventSender(NULL), m_LastEventSlice(0), m_Contourmarkername ("Position"), m_ShowMarkerNodes (false), m_3DInterpolationEnabled(true) { } mitk::SegTool2D::~SegTool2D() { } float mitk::SegTool2D::CanHandleEvent( StateEvent const *stateEvent) const { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return 0.0; if ( positionEvent->GetSender()->GetMapperID() != BaseRenderer::Standard2D ) return 0.0; // we don't want anything but 2D //This are the mouse event that are used by the statemachine patterns for zooming and panning. This must be possible although a tool is activ if (stateEvent->GetId() == EIDRIGHTMOUSEBTN || stateEvent->GetId() == EIDMIDDLEMOUSEBTN || stateEvent->GetId() == EIDRIGHTMOUSEBTNANDCTRL || stateEvent->GetId() == EIDMIDDLEMOUSERELEASE || stateEvent->GetId() == EIDRIGHTMOUSERELEASE || stateEvent->GetId() == EIDRIGHTMOUSEBTNANDMOUSEMOVE || stateEvent->GetId() == EIDMIDDLEMOUSEBTNANDMOUSEMOVE || stateEvent->GetId() == EIDCTRLANDRIGHTMOUSEBTNANDMOUSEMOVE || stateEvent->GetId() == EIDCTRLANDRIGHTMOUSEBTNRELEASE ) { //Since the usual segmentation tools currently do not need right click interaction but the mitkDisplayVectorInteractor return 0.0; } else { return 1.0; } } bool mitk::SegTool2D::DetermineAffectedImageSlice( const Image* image, const PlaneGeometry* plane, int& affectedDimension, int& affectedSlice ) { assert(image); assert(plane); // compare normal of plane to the three axis vectors of the image Vector3D normal = plane->GetNormal(); Vector3D imageNormal0 = image->GetSlicedGeometry()->GetAxisVector(0); Vector3D imageNormal1 = image->GetSlicedGeometry()->GetAxisVector(1); Vector3D imageNormal2 = image->GetSlicedGeometry()->GetAxisVector(2); normal.Normalize(); imageNormal0.Normalize(); imageNormal1.Normalize(); imageNormal2.Normalize(); imageNormal0.SetVnlVector( vnl_cross_3d(normal.GetVnlVector(),imageNormal0.GetVnlVector()) ); imageNormal1.SetVnlVector( vnl_cross_3d(normal.GetVnlVector(),imageNormal1.GetVnlVector()) ); imageNormal2.SetVnlVector( vnl_cross_3d(normal.GetVnlVector(),imageNormal2.GetVnlVector()) ); double eps( 0.00001 ); // axial if ( imageNormal2.GetNorm() <= eps ) { affectedDimension = 2; } // sagittal else if ( imageNormal1.GetNorm() <= eps ) { affectedDimension = 1; } // frontal else if ( imageNormal0.GetNorm() <= eps ) { affectedDimension = 0; } else { affectedDimension = -1; // no idea return false; } // determine slice number in image Geometry3D* imageGeometry = image->GetGeometry(0); Point3D testPoint = imageGeometry->GetCenter(); Point3D projectedPoint; plane->Project( testPoint, projectedPoint ); Point3D indexPoint; imageGeometry->WorldToIndex( projectedPoint, indexPoint ); affectedSlice = ROUND( indexPoint[affectedDimension] ); MITK_DEBUG << "indexPoint " << indexPoint << " affectedDimension " << affectedDimension << " affectedSlice " << affectedSlice; // check if this index is still within the image if ( affectedSlice < 0 || affectedSlice >= static_cast(image->GetDimension(affectedDimension)) ) return false; return true; } mitk::Image::Pointer mitk::SegTool2D::GetAffectedImageSliceAs2DImage(const PositionEvent* positionEvent, const Image* image) { if (!positionEvent) return NULL; assert( positionEvent->GetSender() ); // sure, right? unsigned int timeStep = positionEvent->GetSender()->GetTimeStep( image ); // get the timestep of the visible part (time-wise) of the image // first, we determine, which slice is affected const PlaneGeometry* planeGeometry( dynamic_cast (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) ); return this->GetAffectedImageSliceAs2DImage(planeGeometry, image, timeStep); } mitk::Image::Pointer mitk::SegTool2D::GetAffectedImageSliceAs2DImage(const PlaneGeometry* planeGeometry, const Image* image, unsigned int timeStep) { if ( !image || !planeGeometry ) return NULL; //Make sure that for reslicing and overwriting the same alogrithm is used. We can specify the mode of the vtk reslicer vtkSmartPointer reslice = vtkSmartPointer::New(); //set to false to extract a slice reslice->SetOverwriteMode(false); reslice->Modified(); //use ExtractSliceFilter with our specific vtkImageReslice for overwriting and extracting mitk::ExtractSliceFilter::Pointer extractor = mitk::ExtractSliceFilter::New(reslice); extractor->SetInput( image ); extractor->SetTimeStep( timeStep ); extractor->SetWorldGeometry( planeGeometry ); extractor->SetVtkOutputRequest(false); extractor->SetResliceTransformByGeometry( image->GetTimeSlicedGeometry()->GetGeometry3D( timeStep ) ); extractor->Modified(); extractor->Update(); Image::Pointer slice = extractor->GetOutput(); /*============= BEGIN undo feature block ========================*/ //specify the undo operation with the non edited slice m_undoOperation = new DiffSliceOperation(const_cast(image), extractor->GetVtkOutput(), slice->GetGeometry(), timeStep, const_cast(planeGeometry)); /*============= END undo feature block ========================*/ return slice; } mitk::Image::Pointer mitk::SegTool2D::GetAffectedWorkingSlice(const PositionEvent* positionEvent) { DataNode* workingNode( m_ToolManager->GetWorkingData(0) ); if ( !workingNode ) return NULL; Image* workingImage = dynamic_cast(workingNode->GetData()); if ( !workingImage ) return NULL; return GetAffectedImageSliceAs2DImage( positionEvent, workingImage ); } mitk::Image::Pointer mitk::SegTool2D::GetAffectedReferenceSlice(const PositionEvent* positionEvent) { DataNode* referenceNode( m_ToolManager->GetReferenceData(0) ); if ( !referenceNode ) return NULL; Image* referenceImage = dynamic_cast(referenceNode->GetData()); if ( !referenceImage ) return NULL; return GetAffectedImageSliceAs2DImage( positionEvent, referenceImage ); } void mitk::SegTool2D::WriteBackSegmentationResult (const PositionEvent* positionEvent, Image* slice) { if(!positionEvent) return; const PlaneGeometry* planeGeometry( dynamic_cast (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) ); if( planeGeometry && slice) { DataNode* workingNode( m_ToolManager->GetWorkingData(0) ); Image* image = dynamic_cast(workingNode->GetData()); unsigned int timeStep = positionEvent->GetSender()->GetTimeStep( image ); this->WriteBackSegmentationResult(planeGeometry, slice, timeStep); slice->DisconnectPipeline(); ImageToContourFilter::Pointer contourExtractor = ImageToContourFilter::New(); contourExtractor->SetInput(slice); contourExtractor->Update(); mitk::Surface::Pointer contour = contourExtractor->GetOutput(); if (m_3DInterpolationEnabled && contour->GetVtkPolyData()->GetNumberOfPoints() > 0 ) { unsigned int pos = this->AddContourmarker(positionEvent); - mitk::ServiceReference serviceRef = mitk::GetModuleContext()->GetServiceReference(); - PlanePositionManagerService* service = dynamic_cast(mitk::GetModuleContext()->GetService(serviceRef)); + us::ServiceReference serviceRef = + us::GetModuleContext()->GetServiceReference(); + PlanePositionManagerService* service = us::GetModuleContext()->GetService(serviceRef); mitk::SurfaceInterpolationController::GetInstance()->AddNewContour( contour, service->GetPlanePosition(pos)); contour->DisconnectPipeline(); } } } void mitk::SegTool2D::WriteBackSegmentationResult (const PlaneGeometry* planeGeometry, Image* slice, unsigned int timeStep) { if(!planeGeometry || !slice) return; DataNode* workingNode( m_ToolManager->GetWorkingData(0) ); Image* image = dynamic_cast(workingNode->GetData()); //Make sure that for reslicing and overwriting the same alogrithm is used. We can specify the mode of the vtk reslicer vtkSmartPointer reslice = vtkSmartPointer::New(); //Set the slice as 'input' reslice->SetInputSlice(slice->GetVtkImageData()); //set overwrite mode to true to write back to the image volume reslice->SetOverwriteMode(true); reslice->Modified(); mitk::ExtractSliceFilter::Pointer extractor = mitk::ExtractSliceFilter::New(reslice); extractor->SetInput( image ); extractor->SetTimeStep( timeStep ); extractor->SetWorldGeometry( planeGeometry ); extractor->SetVtkOutputRequest(true); extractor->SetResliceTransformByGeometry( image->GetTimeSlicedGeometry()->GetGeometry3D( timeStep ) ); extractor->Modified(); extractor->Update(); //the image was modified within the pipeline, but not marked so image->Modified(); image->GetVtkImageData()->Modified(); /*============= BEGIN undo feature block ========================*/ //specify the undo operation with the edited slice m_doOperation = new DiffSliceOperation(image, extractor->GetVtkOutput(),slice->GetGeometry(), timeStep, const_cast(planeGeometry)); //create an operation event for the undo stack OperationEvent* undoStackItem = new OperationEvent( DiffSliceOperationApplier::GetInstance(), m_doOperation, m_undoOperation, "Segmentation" ); //add it to the undo controller UndoController::GetCurrentUndoModel()->SetOperationEvent( undoStackItem ); //clear the pointers as the operation are stored in the undocontroller and also deleted from there m_undoOperation = NULL; m_doOperation = NULL; /*============= END undo feature block ========================*/ mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::SegTool2D::SetShowMarkerNodes(bool status) { m_ShowMarkerNodes = status; } void mitk::SegTool2D::SetEnable3DInterpolation(bool enabled) { m_3DInterpolationEnabled = enabled; } unsigned int mitk::SegTool2D::AddContourmarker ( const PositionEvent* positionEvent ) { const mitk::Geometry2D* plane = dynamic_cast (dynamic_cast< const mitk::SlicedGeometry3D*>( positionEvent->GetSender()->GetSliceNavigationController()->GetCurrentGeometry3D())->GetGeometry2D(0)); - mitk::ServiceReference serviceRef = mitk::GetModuleContext()->GetServiceReference(); - PlanePositionManagerService* service = dynamic_cast(mitk::GetModuleContext()->GetService(serviceRef)); + us::ServiceReference serviceRef = + us::GetModuleContext()->GetServiceReference(); + PlanePositionManagerService* service = us::GetModuleContext()->GetService(serviceRef); unsigned int size = service->GetNumberOfPlanePositions(); unsigned int id = service->AddNewPlanePosition(plane, positionEvent->GetSender()->GetSliceNavigationController()->GetSlice()->GetPos()); mitk::PlanarCircle::Pointer contourMarker = mitk::PlanarCircle::New(); mitk::Point2D p1; plane->Map(plane->GetCenter(), p1); mitk::Point2D p2 = p1; p2[0] -= plane->GetSpacing()[0]; p2[1] -= plane->GetSpacing()[1]; contourMarker->PlaceFigure( p1 ); contourMarker->SetCurrentControlPoint( p1 ); contourMarker->SetGeometry2D( const_cast(plane)); std::stringstream markerStream; mitk::DataNode* workingNode (m_ToolManager->GetWorkingData(0)); markerStream << m_Contourmarkername ; markerStream << " "; markerStream << id+1; DataNode::Pointer rotatedContourNode = DataNode::New(); rotatedContourNode->SetData(contourMarker); rotatedContourNode->SetProperty( "name", StringProperty::New(markerStream.str()) ); rotatedContourNode->SetProperty( "isContourMarker", BoolProperty::New(true)); rotatedContourNode->SetBoolProperty( "PlanarFigureInitializedWindow", true, positionEvent->GetSender() ); rotatedContourNode->SetProperty( "includeInBoundingBox", BoolProperty::New(false)); rotatedContourNode->SetProperty( "helper object", mitk::BoolProperty::New(!m_ShowMarkerNodes)); rotatedContourNode->SetProperty( "planarfigure.drawcontrolpoints", BoolProperty::New(false)); rotatedContourNode->SetProperty( "planarfigure.drawname", BoolProperty::New(false)); rotatedContourNode->SetProperty( "planarfigure.drawoutline", BoolProperty::New(false)); rotatedContourNode->SetProperty( "planarfigure.drawshadow", BoolProperty::New(false)); if (plane) { if ( id == size ) { m_ToolManager->GetDataStorage()->Add(rotatedContourNode, workingNode); } else { mitk::NodePredicateProperty::Pointer isMarker = mitk::NodePredicateProperty::New("isContourMarker", mitk::BoolProperty::New(true)); mitk::DataStorage::SetOfObjects::ConstPointer markers = m_ToolManager->GetDataStorage()->GetDerivations(workingNode,isMarker); for ( mitk::DataStorage::SetOfObjects::const_iterator iter = markers->begin(); iter != markers->end(); ++iter) { std::string nodeName = (*iter)->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int markerId = atof(nodeName.substr(t+1).c_str())-1; if(id == markerId) { return id; } } m_ToolManager->GetDataStorage()->Add(rotatedContourNode, workingNode); } } return id; } void mitk::SegTool2D::InteractiveSegmentationBugMessage( const std::string& message ) { MITK_ERROR << "********************************************************************************" << std::endl << " " << message << std::endl << "********************************************************************************" << std::endl << " " << std::endl << " If your image is rotated or the 2D views don't really contain the patient image, try to press the button next to the image selection. " << std::endl << " " << std::endl << " Please file a BUG REPORT: " << std::endl << " http://bugs.mitk.org" << std::endl << " Contain the following information:" << std::endl << " - What image were you working on?" << std::endl << " - Which region of the image?" << std::endl << " - Which tool did you use?" << std::endl << " - What did you do?" << std::endl << " - What happened (not)? What did you expect?" << std::endl; } diff --git a/Modules/Segmentation/Interactions/mitkSubtractContourTool.cpp b/Modules/Segmentation/Interactions/mitkSubtractContourTool.cpp index 39e8c6b883..1a214741e7 100644 --- a/Modules/Segmentation/Interactions/mitkSubtractContourTool.cpp +++ b/Modules/Segmentation/Interactions/mitkSubtractContourTool.cpp @@ -1,63 +1,64 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSubtractContourTool.h" #include "mitkSubtractContourTool.xpm" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include +#include +#include +#include +#include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, SubtractContourTool, "Subtract tool"); } mitk::SubtractContourTool::SubtractContourTool() :ContourTool(0) { FeedbackContourTool::SetFeedbackContourColor( 1.0, 0.0, 0.0 ); } mitk::SubtractContourTool::~SubtractContourTool() { } const char** mitk::SubtractContourTool::GetXPM() const { return mitkSubtractContourTool_xpm; } -mitk::ModuleResource mitk::SubtractContourTool::GetIconResource() const +us::ModuleResource mitk::SubtractContourTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Subtract_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Subtract_48x48.png"); return resource; } -mitk::ModuleResource mitk::SubtractContourTool::GetCursorIconResource() const +us::ModuleResource mitk::SubtractContourTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Subtract_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Subtract_Cursor_32x32.png"); return resource; } const char* mitk::SubtractContourTool::GetName() const { return "Subtract"; } diff --git a/Modules/Segmentation/Interactions/mitkSubtractContourTool.h b/Modules/Segmentation/Interactions/mitkSubtractContourTool.h index 6dcbad9a6d..135824c262 100644 --- a/Modules/Segmentation/Interactions/mitkSubtractContourTool.h +++ b/Modules/Segmentation/Interactions/mitkSubtractContourTool.h @@ -1,72 +1,74 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkSubtractContourTool_h_Included #define mitkSubtractContourTool_h_Included #include "mitkContourTool.h" #include "SegmentationExports.h" +namespace us { class ModuleResource; +} namespace mitk { /** \brief Fill the inside of a contour with 1 \sa ContourTool \ingroup Interaction \ingroup ToolManagerEtAl Fills a visible contour (from FeedbackContourTool) during mouse dragging. When the mouse button is released, SubtractContourTool tries to extract a slice from the working image and fill in the (filled) contour as a binary image. All inside pixels are set to 0. While holding the CTRL key, the contour changes color and the pixels on the inside would be filled with 1. \warning Only to be instantiated by mitk::ToolManager. $Author$ */ class Segmentation_EXPORT SubtractContourTool : public ContourTool { public: mitkClassMacro(SubtractContourTool, ContourTool); itkNewMacro(SubtractContourTool); virtual const char** GetXPM() const; - virtual ModuleResource GetCursorIconResource() const; - ModuleResource GetIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; virtual const char* GetName() const; protected: SubtractContourTool(); // purposely hidden virtual ~SubtractContourTool(); }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkTool.cpp b/Modules/Segmentation/Interactions/mitkTool.cpp index bdd975220a..30a3ed1b29 100644 --- a/Modules/Segmentation/Interactions/mitkTool.cpp +++ b/Modules/Segmentation/Interactions/mitkTool.cpp @@ -1,224 +1,217 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTool.h" #include "mitkDataNodeFactory.h" #include "mitkProperties.h" #include "mitkImageWriteAccessor.h" #include "mitkLevelWindowProperty.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkImageReadAccessor.h" // us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include -#include +#include #include mitk::Tool::Tool(const char* type) : StateMachine(type), m_SupportRoi(false), // for reference images m_PredicateImages(NodePredicateDataType::New("Image")), m_PredicateDim3(NodePredicateDimension::New(3, 1)), m_PredicateDim4(NodePredicateDimension::New(4, 1)), m_PredicateDimension( mitk::NodePredicateOr::New(m_PredicateDim3, m_PredicateDim4) ), m_PredicateImage3D( NodePredicateAnd::New(m_PredicateImages, m_PredicateDimension) ), m_PredicateBinary(NodePredicateProperty::New("binary", BoolProperty::New(true))), m_PredicateNotBinary( NodePredicateNot::New(m_PredicateBinary) ), m_PredicateSegmentation(NodePredicateProperty::New("segmentation", BoolProperty::New(true))), m_PredicateNotSegmentation( NodePredicateNot::New(m_PredicateSegmentation) ), m_PredicateHelper(NodePredicateProperty::New("helper object", BoolProperty::New(true))), m_PredicateNotHelper( NodePredicateNot::New(m_PredicateHelper) ), m_PredicateImageColorful( NodePredicateAnd::New(m_PredicateNotBinary, m_PredicateNotSegmentation) ), m_PredicateImageColorfulNotHelper( NodePredicateAnd::New(m_PredicateImageColorful, m_PredicateNotHelper) ), m_PredicateReference( NodePredicateAnd::New(m_PredicateImage3D, m_PredicateImageColorfulNotHelper) ), // for working image m_IsSegmentationPredicate(NodePredicateAnd::New(NodePredicateOr::New(m_PredicateBinary, m_PredicateSegmentation), m_PredicateNotHelper)) { } mitk::Tool::~Tool() { } const char* mitk::Tool::GetGroup() const { return "default"; } void mitk::Tool::SetToolManager(ToolManager* manager) { m_ToolManager = manager; } void mitk::Tool::Activated() { } void mitk::Tool::Deactivated() { StateMachine::ResetStatemachineToStartState(); // forget about the past } itk::Object::Pointer mitk::Tool::GetGUI(const std::string& toolkitPrefix, const std::string& toolkitPostfix) { itk::Object::Pointer object; std::string classname = this->GetNameOfClass(); std::string guiClassname = toolkitPrefix + classname + toolkitPostfix; std::list allGUIs = itk::ObjectFactoryBase::CreateAllInstance(guiClassname.c_str()); for( std::list::iterator iter = allGUIs.begin(); iter != allGUIs.end(); ++iter ) { if (object.IsNull()) { object = dynamic_cast( iter->GetPointer() ); } else { MITK_ERROR << "There is more than one GUI for " << classname << " (several factories claim ability to produce a " << guiClassname << " ) " << std::endl; return NULL; // people should see and fix this error } } return object; } mitk::NodePredicateBase::ConstPointer mitk::Tool::GetReferenceDataPreference() const { return m_PredicateReference.GetPointer(); } mitk::NodePredicateBase::ConstPointer mitk::Tool::GetWorkingDataPreference() const { return m_IsSegmentationPredicate.GetPointer(); } mitk::DataNode::Pointer mitk::Tool::CreateEmptySegmentationNode( Image* original, const std::string& organName, const mitk::Color& color ) { // we NEED a reference image for size etc. if (!original) return NULL; // actually create a new empty segmentation PixelType pixelType(mitk::MakeScalarPixelType() ); Image::Pointer segmentation = Image::New(); if (original->GetDimension() == 2) { const unsigned int dimensions[] = { original->GetDimension(0), original->GetDimension(1), 1 }; segmentation->Initialize(pixelType, 3, dimensions); } else { segmentation->Initialize(pixelType, original->GetDimension(), original->GetDimensions()); } unsigned int byteSize = sizeof(DefaultSegmentationDataType); if(segmentation->GetDimension() < 4) { for (unsigned int dim = 0; dim < segmentation->GetDimension(); ++dim) { byteSize *= segmentation->GetDimension(dim); } mitk::ImageWriteAccessor writeAccess(segmentation, segmentation->GetVolumeData(0)); memset( writeAccess.GetData(), 0, byteSize ); } else {//if we have a time-resolved image we need to set memory to 0 for each time step for (unsigned int dim = 0; dim < 3; ++dim) { byteSize *= segmentation->GetDimension(dim); } for( unsigned int volumeNumber = 0; volumeNumber < segmentation->GetDimension(3); volumeNumber++) { mitk::ImageWriteAccessor writeAccess(segmentation, segmentation->GetVolumeData(volumeNumber)); memset( writeAccess.GetData(), 0, byteSize ); } } if (original->GetTimeSlicedGeometry() ) { TimeSlicedGeometry::Pointer originalGeometry = original->GetTimeSlicedGeometry()->Clone(); segmentation->SetGeometry( originalGeometry ); } else { Tool::ErrorMessage("Original image does not have a 'Time sliced geometry'! Cannot create a segmentation."); return NULL; } return CreateSegmentationNode( segmentation, organName, color ); } mitk::DataNode::Pointer mitk::Tool::CreateSegmentationNode( Image* image, const std::string& organName, const mitk::Color& color ) { if (!image) return NULL; // decorate the datatreenode with some properties DataNode::Pointer segmentationNode = DataNode::New(); segmentationNode->SetData( image ); // name segmentationNode->SetProperty( "name", StringProperty::New( organName ) ); // visualization properties segmentationNode->SetProperty( "binary", BoolProperty::New(true) ); segmentationNode->SetProperty( "color", ColorProperty::New(color) ); segmentationNode->SetProperty( "texture interpolation", BoolProperty::New(false) ); segmentationNode->SetProperty( "layer", IntProperty::New(10) ); segmentationNode->SetProperty( "levelwindow", LevelWindowProperty::New( LevelWindow(0.5, 1) ) ); segmentationNode->SetProperty( "opacity", FloatProperty::New(0.3) ); segmentationNode->SetProperty( "segmentation", BoolProperty::New(true) ); segmentationNode->SetProperty( "reslice interpolation", VtkResliceInterpolationProperty::New() ); // otherwise -> segmentation appears in 2 slices sometimes (only visual effect, not different data) // For MITK-3M3 release, the volume of all segmentations should be shown segmentationNode->SetProperty( "showVolume", BoolProperty::New( true ) ); return segmentationNode; } -mitk::ModuleResource mitk::Tool::GetIconResource() const +us::ModuleResource mitk::Tool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); // Each specific tool should load its own resource. This one will be invalid - ModuleResource resource = module->GetResource("dummy.resource"); - return resource; + return us::ModuleResource(); } -mitk::ModuleResource mitk::Tool::GetCursorIconResource() const +us::ModuleResource mitk::Tool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); // Each specific tool should load its own resource. This one will be invalid - ModuleResource resource = module->GetResource("dummy.resource"); - return resource; + return us::ModuleResource(); } diff --git a/Modules/Segmentation/Interactions/mitkTool.h b/Modules/Segmentation/Interactions/mitkTool.h index b4093560a7..d324eaa3ee 100644 --- a/Modules/Segmentation/Interactions/mitkTool.h +++ b/Modules/Segmentation/Interactions/mitkTool.h @@ -1,241 +1,244 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkTool_h_Included #define mitkTool_h_Included #include "mitkCommon.h" #include "SegmentationExports.h" #include "mitkStateMachine.h" #include "mitkToolEvents.h" #include "itkObjectFactoryBase.h" #include "itkVersion.h" #include "mitkToolFactoryMacro.h" #include "mitkMessage.h" #include "mitkDataNode.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateDimension.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateOr.h" #include "mitkNodePredicateNot.h" #include #include #include +namespace us { +class ModuleResource; +} + namespace mitk { - class ModuleResource; class ToolManager; /** \brief Base class of all tools used by mitk::ToolManager. \sa ToolManager \sa SegTool2D \ingroup Interaction \ingroup ToolManagerEtAl There is a separate page describing the \ref QmitkInteractiveSegmentationTechnicalPage. Every tool is a mitk::StateMachine, which can follow any transition pattern that it likes. One important thing to know is, that every derived tool should always call SuperClass::Deactivated() in its own implementation of Deactivated, because mitk::Tool resets the StateMachine in this method. Only if you are very sure that you covered all possible things that might happen to your own tool, you should consider not to reset the StateMachine from time to time. To learn about the MITK implementation of state machines in general, have a look at \ref InteractionPage. To derive a non-abstract tool, you inherit from mitk::Tool (or some other base class further down the inheritance tree), and in your own parameterless constructor (that is called from the itkNewMacro that you use) you pass a StateMachine pattern name to the superclass. Names for valid patterns can be found in StateMachine.xml (which might be enhanced by you). You have to implement at least GetXPM() and GetName() to provide some identification. Each Tool knows its ToolManager, which can provide the data that the tool should work on. \warning Only to be instantiated by mitk::ToolManager (because SetToolManager has to be called). All other uses are unsupported. $Author$ */ class Segmentation_EXPORT Tool : public StateMachine { public: typedef unsigned char DefaultSegmentationDataType; /** * \brief To let GUI process new events (e.g. qApp->processEvents() ) */ Message<> GUIProcessEventsMessage; /** * \brief To send error messages (to be shown by some GUI) */ Message1 ErrorMessage; /** * \brief To send whether the tool is busy (to be shown by some GUI) */ Message1 CurrentlyBusy; /** * \brief To send general messages (to be shown by some GUI) */ Message1 GeneralMessage; mitkClassMacro(Tool, StateMachine); // no New(), there should only be subclasses /** \brief Returns an icon in the XPM format. This icon has to fit into some kind of button in most applications, so make it smaller than 25x25 pixels. XPM is e.g. supported by The Gimp. But if you open any XPM file in your text editor, you will see that you could also "draw" it with an editor. */ virtual const char** GetXPM() const = 0; /** * \brief Returns the path of an icon. * * This icon is preferred to the XPM icon. */ virtual std::string GetIconPath() const { return ""; } /** * \brief Returns the path of a cursor icon. * */ - virtual ModuleResource GetCursorIconResource() const; + virtual us::ModuleResource GetCursorIconResource() const; /** * @brief Returns the tool button icon of the tool wrapped by a usModuleResource * @return a valid ModuleResource or an invalid if this function * is not reimplemented */ - virtual ModuleResource GetIconResource() const; + virtual us::ModuleResource GetIconResource() const; /** \brief Returns the name of this tool. Make it short! This name has to fit into some kind of button in most applications, so take some time to think of a good name! */ virtual const char* GetName() const = 0; /** \brief Name of a group. You can group several tools by assigning a group name. Graphical tool selectors might use this information to group tools. (What other reason could there be?) */ virtual const char* GetGroup() const; /** * \brief Interface for GUI creation. * * This is the basic interface for creation of a GUI object belonging to one tool. * * Tools that support a GUI (e.g. for display/editing of parameters) should follow some rules: * * - A Tool and its GUI are two separate classes * - There may be several instances of a GUI at the same time. * - mitk::Tool is toolkit (Qt, wxWidgets, etc.) independent, the GUI part is of course dependent * - The GUI part inherits both from itk::Object and some GUI toolkit class * - The GUI class name HAS to be constructed like "toolkitPrefix" tool->GetClassName() + "toolkitPostfix", e.g. MyTool -> wxMyToolGUI * - For each supported toolkit there is a base class for tool GUIs, which contains some convenience methods * - Tools notify the GUI about changes using ITK events. The GUI must observe interesting events. * - The GUI base class may convert all ITK events to the GUI toolkit's favoured messaging system (Qt -> signals) * - Calling methods of a tool by its GUI is done directly. * In some cases GUIs don't want to be notified by the tool when they cause a change in a tool. * There is a macro CALL_WITHOUT_NOTICE(method()), which will temporarily disable all notifications during a method call. */ virtual itk::Object::Pointer GetGUI(const std::string& toolkitPrefix, const std::string& toolkitPostfix); virtual NodePredicateBase::ConstPointer GetReferenceDataPreference() const; virtual NodePredicateBase::ConstPointer GetWorkingDataPreference() const; DataNode::Pointer CreateEmptySegmentationNode( Image* original, const std::string& organName, const mitk::Color& color ); DataNode::Pointer CreateSegmentationNode( Image* image, const std::string& organName, const mitk::Color& color ); itkGetMacro(SupportRoi, bool); itkSetMacro(SupportRoi, bool); itkBooleanMacro(SupportRoi); protected: friend class ToolManager; virtual void SetToolManager(ToolManager*); /** \brief Called when the tool gets activated (registered to mitk::GlobalInteraction). Derived tools should call their parents implementation. */ virtual void Activated(); /** \brief Called when the tool gets deactivated (unregistered from mitk::GlobalInteraction). Derived tools should call their parents implementation. */ virtual void Deactivated(); Tool(); // purposely hidden Tool( const char*); // purposely hidden virtual ~Tool(); ToolManager* m_ToolManager; bool m_SupportRoi; private: // for reference data NodePredicateDataType::Pointer m_PredicateImages; NodePredicateDimension::Pointer m_PredicateDim3; NodePredicateDimension::Pointer m_PredicateDim4; NodePredicateOr::Pointer m_PredicateDimension; NodePredicateAnd::Pointer m_PredicateImage3D; NodePredicateProperty::Pointer m_PredicateBinary; NodePredicateNot::Pointer m_PredicateNotBinary; NodePredicateProperty::Pointer m_PredicateSegmentation; NodePredicateNot::Pointer m_PredicateNotSegmentation; NodePredicateProperty::Pointer m_PredicateHelper; NodePredicateNot::Pointer m_PredicateNotHelper; NodePredicateAnd::Pointer m_PredicateImageColorful; NodePredicateAnd::Pointer m_PredicateImageColorfulNotHelper; NodePredicateAnd::Pointer m_PredicateReference; // for working data NodePredicateAnd::Pointer m_IsSegmentationPredicate; }; } // namespace #endif diff --git a/Modules/Segmentation/Interactions/mitkWatershedTool.cpp b/Modules/Segmentation/Interactions/mitkWatershedTool.cpp index f3560faa3f..438967ae9f 100644 --- a/Modules/Segmentation/Interactions/mitkWatershedTool.cpp +++ b/Modules/Segmentation/Interactions/mitkWatershedTool.cpp @@ -1,206 +1,207 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkWatershedTool.h" #include "mitkBinaryThresholdTool.xpm" #include "mitkToolManager.h" #include "mitkImageAccessByItk.h" #include "mitkImageCast.h" #include "mitkITKImageImport.h" #include "mitkRenderingManager.h" #include "mitkRenderingModeProperty.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkIOUtil.h" #include "mitkLevelWindowManager.h" #include "mitkImageStatisticsHolder.h" #include "mitkToolCommand.h" #include "mitkProgressBar.h" -#include -#include -#include -#include + +#include +#include +#include +#include #include #include #include #include namespace mitk { MITK_TOOL_MACRO(Segmentation_EXPORT, WatershedTool, "Watershed tool"); } mitk::WatershedTool::WatershedTool() : m_Level(0.), m_Threshold(0.) { } mitk::WatershedTool::~WatershedTool() { } void mitk::WatershedTool::Activated() { Superclass::Activated(); } void mitk::WatershedTool::Deactivated() { Superclass::Deactivated(); } -mitk::ModuleResource mitk::WatershedTool::GetIconResource() const +us::ModuleResource mitk::WatershedTool::GetIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Watershed_48x48.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Watershed_48x48.png"); return resource; } -mitk::ModuleResource mitk::WatershedTool::GetCursorIconResource() const +us::ModuleResource mitk::WatershedTool::GetCursorIconResource() const { - Module* module = GetModuleContext()->GetModule(); - ModuleResource resource = module->GetResource("Watershed_Cursor_32x32.png"); + us::Module* module = us::GetModuleContext()->GetModule(); + us::ModuleResource resource = module->GetResource("Watershed_Cursor_32x32.png"); return resource; } const char** mitk::WatershedTool::GetXPM() const { return NULL; } const char* mitk::WatershedTool::GetName() const { return "Watershed"; } void mitk::WatershedTool::DoIt() { // get image from tool manager mitk::DataNode::Pointer referenceData = m_ToolManager->GetReferenceData(0); mitk::Image::Pointer input = dynamic_cast(referenceData->GetData()); mitk::Image::Pointer output; try { // create and run itk filter pipeline AccessFixedDimensionByItk_1(input.GetPointer(),ITKWatershed,3,output); // create a new datanode for output mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); dataNode->SetData(output); // set properties of datanode dataNode->SetProperty("binary", mitk::BoolProperty::New(false)); dataNode->SetProperty("name", mitk::StringProperty::New("Watershed Result")); mitk::RenderingModeProperty::Pointer renderingMode = mitk::RenderingModeProperty::New(); renderingMode->SetValue( mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR ); dataNode->SetProperty("Image Rendering.Mode", renderingMode); // since we create a multi label image, define a vtk lookup table mitk::LookupTable::Pointer lut = mitk::LookupTable::New(); mitk::LookupTableProperty::Pointer prop = mitk::LookupTableProperty::New(lut); vtkLookupTable *lookupTable = vtkLookupTable::New(); lookupTable->SetHueRange(1.0, 0.0); lookupTable->SetSaturationRange(1.0, 1.0); lookupTable->SetValueRange(1.0, 1.0); lookupTable->SetTableRange(-1.0, 1.0); lookupTable->Build(); lookupTable->SetTableValue(1,0,0,0); lut->SetVtkLookupTable(lookupTable); prop->SetLookupTable(lut); dataNode->SetProperty("LookupTable",prop); // make the levelwindow fit to right values mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelwindow; levelwindow.SetRangeMinMax(0, output->GetStatistics()->GetScalarValueMax()); levWinProp->SetLevelWindow( levelwindow ); dataNode->SetProperty( "levelwindow", levWinProp ); dataNode->SetProperty( "opacity", mitk::FloatProperty::New(0.5)); // set name of data node std::string name = referenceData->GetName() + "_Watershed"; dataNode->SetName( name ); // look, if there is already a node with this name mitk::DataStorage::SetOfObjects::ConstPointer children = m_ToolManager->GetDataStorage()->GetDerivations(referenceData); mitk::DataStorage::SetOfObjects::ConstIterator currentNode = children->Begin(); mitk::DataNode::Pointer removeNode; while(currentNode != children->End()) { if(dataNode->GetName().compare(currentNode->Value()->GetName()) == 0) { removeNode = currentNode->Value(); } currentNode++; } // remove node with same name if(removeNode.IsNotNull()) m_ToolManager->GetDataStorage()->Remove(removeNode); // add output to the data storage m_ToolManager->GetDataStorage()->Add(dataNode,referenceData); } catch(itk::ExceptionObject& e) { MITK_ERROR<<"Watershed Filter Error: " << e.GetDescription(); } RenderingManager::GetInstance()->RequestUpdateAll(); } template void mitk::WatershedTool::ITKWatershed( itk::Image* originalImage, mitk::Image::Pointer& segmentation ) { typedef itk::WatershedImageFilter< itk::Image > WatershedFilter; typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< itk::Image, itk::Image > MagnitudeFilter; // at first add a gradient magnitude filter typename MagnitudeFilter::Pointer magnitude = MagnitudeFilter::New(); magnitude->SetInput(originalImage); magnitude->SetSigma(1.0); // use the progress bar mitk::ToolCommand::Pointer command = mitk::ToolCommand::New(); command->AddStepsToDo(15); // then add the watershed filter to the pipeline typename WatershedFilter::Pointer watershed = WatershedFilter::New(); watershed->SetInput(magnitude->GetOutput()); watershed->SetThreshold(m_Threshold); watershed->SetLevel(m_Level); watershed->AddObserver(itk::ProgressEvent(),command); watershed->Update(); // then make sure, that the output has the desired pixel type typedef itk::CastImageFilter > CastFilter; typename CastFilter::Pointer cast = CastFilter::New(); cast->SetInput(watershed->GetOutput()); // start the whole pipeline cast->Update(); // since we obtain a new image from our pipeline, we have to make sure, that our mitk::Image::Pointer // is responsible for the memory management of the output image segmentation = mitk::GrabItkImageMemory(cast->GetOutput()); } diff --git a/Modules/Segmentation/Interactions/mitkWatershedTool.h b/Modules/Segmentation/Interactions/mitkWatershedTool.h index 4693dc1526..b8ed493439 100644 --- a/Modules/Segmentation/Interactions/mitkWatershedTool.h +++ b/Modules/Segmentation/Interactions/mitkWatershedTool.h @@ -1,92 +1,94 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkWatershedTool_h_Included #define mitkWatershedTool_h_Included #include "mitkCommon.h" #include "SegmentationExports.h" #include "mitkAutoSegmentationTool.h" +namespace us { class ModuleResource; +} namespace mitk { class Image; /** \brief Simple watershed segmentation tool. \ingroup Interaction \ingroup ToolManagerEtAl Wraps ITK Watershed Filter into tool concept of MITK. For more information look into ITK documentation. \warning Only to be instantiated by mitk::ToolManager. $Darth Vader$ */ class Segmentation_EXPORT WatershedTool : public AutoSegmentationTool { public: mitkClassMacro(WatershedTool, AutoSegmentationTool); itkNewMacro(WatershedTool); void SetThreshold(double t) { m_Threshold = t; } void SetLevel(double l) { m_Level = l; } /** \brief Grabs the tool reference data and creates an ITK pipeline consisting of a GradientMagnitude * image filter followed by a Watershed image filter. The output of the filter pipeline is then added * to the data storage. */ void DoIt(); /** \brief Creates and runs an ITK filter pipeline consisting of the filters: GradientMagnitude-, Watershed- and CastImageFilter. * * \param originalImage The input image, which is delivered by the AccessByItk macro. * \param segmentation A pointer to the output image, which will point to the pipeline output after execution. */ template void ITKWatershed( itk::Image* originalImage, mitk::Image::Pointer& segmentation ); const char** GetXPM() const; const char* GetName() const; - ModuleResource GetIconResource() const; - ModuleResource GetCursorIconResource() const; + us::ModuleResource GetIconResource() const; + us::ModuleResource GetCursorIconResource() const; protected: WatershedTool(); // purposely hidden virtual ~WatershedTool(); virtual void Activated(); virtual void Deactivated(); /** \brief Threshold parameter of the ITK Watershed Image Filter. See ITK Documentation for more information. */ double m_Threshold; /** \brief Threshold parameter of the ITK Watershed Image Filter. See ITK Documentation for more information. */ double m_Level; }; } // namespace #endif diff --git a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp index fc346636ed..5541d8e421 100755 --- a/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp +++ b/Modules/SegmentationUI/Qmitk/QmitkToolSelectionBox.cpp @@ -1,697 +1,697 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define MBILOG_ENABLE_DEBUG 1 #include "QmitkToolSelectionBox.h" #include "QmitkToolGUI.h" #include "mitkBaseRenderer.h" #include #include #include #include #include #include #include #include -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" +#include "usModuleResource.h" +#include "usModuleResourceStream.h" QmitkToolSelectionBox::QmitkToolSelectionBox(QWidget* parent, mitk::DataStorage* storage) :QWidget(parent), m_SelfCall(false), m_DisplayedGroups("default"), m_LayoutColumns(2), m_ShowNames(true), m_AutoShowNamesWidth(0), m_GenerateAccelerators(false), m_ToolGUIWidget(NULL), m_LastToolGUI(NULL), m_ToolButtonGroup(NULL), m_ButtonLayout(NULL), m_EnabledMode(EnabledWithReferenceAndWorkingDataVisible) { QFont currentFont = QWidget::font(); currentFont.setBold(true); QWidget::setFont( currentFont ); m_ToolManager = mitk::ToolManager::New( storage ); // muellerm // QButtonGroup m_ToolButtonGroup = new QButtonGroup(this); // some features of QButtonGroup m_ToolButtonGroup->setExclusive( false ); // mutually exclusive toggle buttons RecreateButtons(); QWidget::setContentsMargins(0, 0, 0, 0); if ( layout() != NULL ) { layout()->setContentsMargins(0, 0, 0, 0); } // reactions to signals connect( m_ToolButtonGroup, SIGNAL(buttonClicked(int)), this, SLOT(toolButtonClicked(int)) ); // reactions to ToolManager events m_ToolManager->ActiveToolChanged += mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerToolModified ); m_ToolManager->ReferenceDataChanged += mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified ); m_ToolManager->WorkingDataChanged += mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified ); // show active tool SetOrUnsetButtonForActiveTool(); QWidget::setEnabled( false ); } QmitkToolSelectionBox::~QmitkToolSelectionBox() { m_ToolManager->ActiveToolChanged -= mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerToolModified ); m_ToolManager->ReferenceDataChanged -= mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified ); m_ToolManager->WorkingDataChanged -= mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified ); } void QmitkToolSelectionBox::SetEnabledMode(EnabledMode mode) { m_EnabledMode = mode; SetGUIEnabledAccordingToToolManagerState(); } mitk::ToolManager* QmitkToolSelectionBox::GetToolManager() { return m_ToolManager; } void QmitkToolSelectionBox::SetToolManager(mitk::ToolManager& newManager) // no NULL pointer allowed here, a manager is required { // say bye to the old manager m_ToolManager->ActiveToolChanged -= mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerToolModified ); m_ToolManager->ReferenceDataChanged -= mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified ); m_ToolManager->WorkingDataChanged -= mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified ); if ( QWidget::isEnabled() ) { m_ToolManager->UnregisterClient(); } m_ToolManager = &newManager; RecreateButtons(); // greet the new one m_ToolManager->ActiveToolChanged += mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerToolModified ); m_ToolManager->ReferenceDataChanged += mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerReferenceDataModified ); m_ToolManager->WorkingDataChanged += mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolManagerWorkingDataModified ); if ( QWidget::isEnabled() ) { m_ToolManager->RegisterClient(); } // ask the new one what the situation is like SetOrUnsetButtonForActiveTool(); } void QmitkToolSelectionBox::toolButtonClicked(int id) { if ( !QWidget::isEnabled() ) return; // this method could be triggered from the constructor, when we are still disabled MITK_DEBUG << "toolButtonClicked(" << id << "): id translates to tool ID " << m_ToolIDForButtonID[id]; //QToolButton* toolButton = dynamic_cast( Q3ButtonGroup::find(id) ); QToolButton* toolButton = dynamic_cast( m_ToolButtonGroup->buttons().at(id) ); if (toolButton) { if ( (m_ButtonIDForToolID.find( m_ToolManager->GetActiveToolID() ) != m_ButtonIDForToolID.end()) // if we have this tool in our box && (m_ButtonIDForToolID[ m_ToolManager->GetActiveToolID() ] == id) ) // the tool corresponding to this button is already active { // disable this button, disable all tools // mmueller toolButton->setChecked(false); m_ToolManager->ActivateTool(-1); // disable everything } else { // enable the corresponding tool m_SelfCall = true; m_ToolManager->ActivateTool( m_ToolIDForButtonID[id] ); m_SelfCall = false; } } } void QmitkToolSelectionBox::OnToolManagerToolModified() { SetOrUnsetButtonForActiveTool(); } void QmitkToolSelectionBox::SetOrUnsetButtonForActiveTool() { // we want to emit a signal in any case, whether we selected ourselves or somebody else changes "our" tool manager. --> emit before check on m_SelfCall int id = m_ToolManager->GetActiveToolID(); // don't emit signal for shape model tools bool emitSignal = true; mitk::Tool* tool = m_ToolManager->GetActiveTool(); if(tool && std::string(tool->GetGroup()) == "organ_segmentation") emitSignal = false; if(emitSignal) emit ToolSelected(id); // delete old GUI (if any) if ( m_LastToolGUI && m_ToolGUIWidget ) { if (m_ToolGUIWidget->layout()) { m_ToolGUIWidget->layout()->removeWidget(m_LastToolGUI); } //m_LastToolGUI->reparent(NULL, QPoint(0,0)); // TODO: reparent <-> setParent, Daniel fragen m_LastToolGUI->setParent(0); delete m_LastToolGUI; // will hopefully notify parent and layouts m_LastToolGUI = NULL; QLayout* layout = m_ToolGUIWidget->layout(); if (layout) { layout->activate(); } } QToolButton* toolButton(NULL); //mitk::Tool* tool = m_ToolManager->GetActiveTool(); if (m_ButtonIDForToolID.find(id) != m_ButtonIDForToolID.end()) // if this tool is in our box { //toolButton = dynamic_cast( Q3ButtonGroup::find( m_ButtonIDForToolID[id] ) ); toolButton = dynamic_cast( m_ToolButtonGroup->buttons().at( m_ButtonIDForToolID[id] ) ); } if ( toolButton ) { // mmueller // uncheck all other buttons QAbstractButton* tmpBtn = 0; QList::iterator it; for(int i=0; i < m_ToolButtonGroup->buttons().size(); ++i) { tmpBtn = m_ToolButtonGroup->buttons().at(i); if(tmpBtn != toolButton) dynamic_cast( tmpBtn )->setChecked(false); } toolButton->setChecked(true); if (m_ToolGUIWidget && tool) { // create and reparent new GUI (if any) itk::Object::Pointer possibleGUI = tool->GetGUI("Qmitk", "GUI").GetPointer(); // prefix and postfix QmitkToolGUI* gui = dynamic_cast( possibleGUI.GetPointer() ); //! m_LastToolGUI = gui; if (gui) { gui->SetTool( tool ); // mmueller //gui->reparent(m_ToolGUIWidget, gui->geometry().topLeft(), true ); gui->setParent(m_ToolGUIWidget); gui->move(gui->geometry().topLeft()); gui->show(); QLayout* layout = m_ToolGUIWidget->layout(); if (!layout) { layout = new QVBoxLayout( m_ToolGUIWidget ); } if (layout) { // mmueller layout->addWidget( gui ); //layout->add( gui ); layout->activate(); } } } } else { // disable all buttons QToolButton* selectedToolButton = dynamic_cast( m_ToolButtonGroup->checkedButton() ); //QToolButton* selectedToolButton = dynamic_cast( Q3ButtonGroup::find( Q3ButtonGroup::selectedId() ) ); if (selectedToolButton) { // mmueller selectedToolButton->setChecked(false); //selectedToolButton->setOn(false); } } } void QmitkToolSelectionBox::OnToolManagerReferenceDataModified() { if (m_SelfCall) return; MITK_DEBUG << "OnToolManagerReferenceDataModified()"; SetGUIEnabledAccordingToToolManagerState(); } void QmitkToolSelectionBox::OnToolManagerWorkingDataModified() { if (m_SelfCall) return; MITK_DEBUG << "OnToolManagerWorkingDataModified()"; SetGUIEnabledAccordingToToolManagerState(); } /** Implementes the logic, which decides, when tools are activated/deactivated. */ void QmitkToolSelectionBox::SetGUIEnabledAccordingToToolManagerState() { mitk::DataNode* referenceNode = m_ToolManager->GetReferenceData(0); mitk::DataNode* workingNode = m_ToolManager->GetWorkingData(0); //MITK_DEBUG << this->name() << ": SetGUIEnabledAccordingToToolManagerState: referenceNode " << (void*)referenceNode << " workingNode " << (void*)workingNode << " isVisible() " << isVisible(); bool enabled = true; switch ( m_EnabledMode ) { default: case EnabledWithReferenceAndWorkingDataVisible: enabled = referenceNode && workingNode && referenceNode->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))) && workingNode->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))) && isVisible(); break; case EnabledWithReferenceData: enabled = referenceNode && isVisible(); break; case EnabledWithWorkingData: enabled = workingNode && isVisible(); break; case AlwaysEnabled: enabled = isVisible(); break; } if ( QWidget::isEnabled() == enabled ) return; // nothing to change QWidget::setEnabled( enabled ); if (enabled) { m_ToolManager->RegisterClient(); int id = m_ToolManager->GetActiveToolID(); emit ToolSelected(id); } else { m_ToolManager->ActivateTool(-1); m_ToolManager->UnregisterClient(); emit ToolSelected(-1); } } /** External enableization... */ void QmitkToolSelectionBox::setEnabled( bool enable ) { QWidget::setEnabled(enable); SetGUIEnabledAccordingToToolManagerState(); } void QmitkToolSelectionBox::RecreateButtons() { if (m_ToolManager.IsNull()) return; /* // remove all buttons that are there QObjectList *l = Q3ButtonGroup::queryList( "QButton" ); QObjectListIt it( *l ); // iterate over all buttons QObject *obj; while ( (obj = it.current()) != 0 ) { ++it; QButton* button = dynamic_cast(obj); if (button) { Q3ButtonGroup::remove(button); delete button; } } delete l; // delete the list, not the objects */ // mmueller Qt4 impl QList l = m_ToolButtonGroup->buttons(); // remove all buttons that are there QList::iterator it; QAbstractButton * btn; for(it=l.begin(); it!=l.end();++it) { btn = *it; m_ToolButtonGroup->removeButton(btn); //this->removeChild(btn); delete btn; } // end mmueller Qt4 impl mitk::ToolManager::ToolVectorTypeConst allPossibleTools = m_ToolManager->GetTools(); mitk::ToolManager::ToolVectorTypeConst allTools; typedef std::pair< std::string::size_type, const mitk::Tool* > SortPairType; typedef std::priority_queue< SortPairType > SortedToolQueueType; SortedToolQueueType toolPositions; // clear and sort all tools // step one: find name/group of all tools in m_DisplayedGroups string. remember these positions for all tools. for ( mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allPossibleTools.begin(); iter != allPossibleTools.end(); ++iter) { const mitk::Tool* tool = *iter; std::string::size_type namePos = m_DisplayedGroups.find( std::string("'") + tool->GetName() + "'" ); std::string::size_type groupPos = m_DisplayedGroups.find( std::string("'") + tool->GetGroup() + "'" ); if ( !m_DisplayedGroups.empty() && namePos == std::string::npos && groupPos == std::string::npos ) continue; // skip if ( m_DisplayedGroups.empty() && std::string(tool->GetName()).length() > 0 ) { namePos = static_cast (tool->GetName()[0]); } SortPairType thisPair = std::make_pair( namePos < groupPos ? namePos : groupPos, *iter ); toolPositions.push( thisPair ); } // step two: sort tools according to previously found positions in m_DisplayedGroups MITK_DEBUG << "Sorting order of tools (lower number --> earlier in button group)"; while ( !toolPositions.empty() ) { SortPairType thisPair = toolPositions.top(); MITK_DEBUG << "Position " << thisPair.first << " : " << thisPair.second->GetName(); allTools.push_back( thisPair.second ); toolPositions.pop(); } std::reverse( allTools.begin(), allTools.end() ); MITK_DEBUG << "Sorted tools:"; for ( mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allTools.begin(); iter != allTools.end(); ++iter) { MITK_DEBUG << (*iter)->GetName(); } // try to change layout... bad? //Q3GroupBox::setColumnLayout ( m_LayoutColumns, Qt::Horizontal ); // mmueller using gridlayout instead of Q3GroupBox //this->setLayout(0); if(m_ButtonLayout == NULL) m_ButtonLayout = new QGridLayout; /*else delete m_ButtonLayout;*/ int row(0); int column(-1); int currentButtonID(0); m_ButtonIDForToolID.clear(); m_ToolIDForButtonID.clear(); QToolButton* button = 0; MITK_DEBUG << "Creating buttons for tools"; // fill group box with buttons for ( mitk::ToolManager::ToolVectorTypeConst::const_iterator iter = allTools.begin(); iter != allTools.end(); ++iter) { const mitk::Tool* tool = *iter; int currentToolID( m_ToolManager->GetToolID( tool ) ); ++column; // new line if we are at the maximum columns if(column == m_LayoutColumns) { ++row; column = 0; } button = new QToolButton; button->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum)); // add new button to the group MITK_DEBUG << "Adding button with ID " << currentToolID; m_ToolButtonGroup->addButton(button, currentButtonID); // ... and to the layout MITK_DEBUG << "Adding button in row/column " << row << "/" << column; m_ButtonLayout->addWidget(button, row, column); if (m_LayoutColumns == 1) { //button->setTextPosition( QToolButton::BesideIcon ); // mmueller button->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); } else { //button->setTextPosition( QToolButton::BelowIcon ); // mmueller button->setToolButtonStyle( Qt::ToolButtonTextUnderIcon ); } //button->setToggleButton( true ); // mmueller button->setCheckable ( true ); if(currentToolID == m_ToolManager->GetActiveToolID()) button->setChecked(true); QString label; if (m_GenerateAccelerators) { label += "&"; } label += tool->GetName(); QString tooltip = tool->GetName(); MITK_DEBUG << tool->GetName() << ", " << label.toLocal8Bit().constData() << ", '" << tooltip.toLocal8Bit().constData(); if ( m_ShowNames ) { /* button->setUsesTextLabel(true); button->setTextLabel( label ); // a label QToolTip::add( button, tooltip ); */ // mmueller Qt4 button->setText( label ); // a label button->setToolTip( tooltip ); // mmueller QFont currentFont = button->font(); currentFont.setBold(false); button->setFont( currentFont ); } - mitk::ModuleResource iconResource = tool->GetIconResource(); + us::ModuleResource iconResource = tool->GetIconResource(); if (!iconResource.IsValid()) { button->setIcon(QIcon(QPixmap(tool->GetXPM()))); } else { - mitk::ModuleResourceStream resourceStream(iconResource, std::ios::binary); + us::ModuleResourceStream resourceStream(iconResource, std::ios::binary); resourceStream.seekg(0, std::ios::end); std::ios::pos_type length = resourceStream.tellg(); resourceStream.seekg(0, std::ios::beg); char* data = new char[length]; resourceStream.read(data, length); QPixmap pixmap; pixmap.loadFromData(QByteArray::fromRawData(data, length)); QIcon* icon = new QIcon(pixmap); delete[] data; button->setIcon(*icon); if (m_ShowNames) { if (m_LayoutColumns == 1) button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); else button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); button->setIconSize(QSize(24, 24)); } else { button->setToolButtonStyle(Qt::ToolButtonIconOnly); button->setIconSize(QSize(32,32)); button->setToolTip(tooltip); } } if (m_GenerateAccelerators) { QString firstLetter = QString( tool->GetName() ); firstLetter.truncate( 1 ); button->setShortcut( firstLetter ); // a keyboard shortcut (just the first letter of the given name w/o any CTRL or something) } m_ButtonIDForToolID[currentToolID] = currentButtonID; m_ToolIDForButtonID[currentButtonID] = currentToolID; MITK_DEBUG << "m_ButtonIDForToolID[" << currentToolID << "] == " << currentButtonID; MITK_DEBUG << "m_ToolIDForButtonID[" << currentButtonID << "] == " << currentToolID; tool->GUIProcessEventsMessage += mitk::MessageDelegate( this, &QmitkToolSelectionBox::OnToolGUIProcessEventsMessage ); // will never add a listener twice, so we don't have to check here tool->ErrorMessage += mitk::MessageDelegate1( this, &QmitkToolSelectionBox::OnToolErrorMessage ); // will never add a listener twice, so we don't have to check here tool->GeneralMessage += mitk::MessageDelegate1( this, &QmitkToolSelectionBox::OnGeneralToolMessage ); ++currentButtonID; } // setting grid layout for this groupbox this->setLayout(m_ButtonLayout); //this->update(); } void QmitkToolSelectionBox::OnToolGUIProcessEventsMessage() { qApp->processEvents(); } void QmitkToolSelectionBox::OnToolErrorMessage(std::string s) { QMessageBox::critical(this, "MITK", QString( s.c_str() ), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } void QmitkToolSelectionBox::OnGeneralToolMessage(std::string s) { QMessageBox::information(this, "MITK", QString( s.c_str() ), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } void QmitkToolSelectionBox::SetDisplayedToolGroups(const std::string& toolGroups) { if (m_DisplayedGroups != toolGroups) { QString q_DisplayedGroups = toolGroups.c_str(); // quote all unquoted single words q_DisplayedGroups = q_DisplayedGroups.replace( QRegExp("\\b(\\w+)\\b|'([^']+)'"), "'\\1\\2'" ); MITK_DEBUG << "m_DisplayedGroups was \"" << toolGroups << "\""; m_DisplayedGroups = q_DisplayedGroups.toLocal8Bit().constData(); MITK_DEBUG << "m_DisplayedGroups is \"" << m_DisplayedGroups << "\""; RecreateButtons(); SetOrUnsetButtonForActiveTool(); } } void QmitkToolSelectionBox::SetLayoutColumns(int columns) { if (columns > 0 && columns != m_LayoutColumns) { m_LayoutColumns = columns; RecreateButtons(); } } void QmitkToolSelectionBox::SetShowNames(bool show) { if (show != m_ShowNames) { m_ShowNames = show; RecreateButtons(); } } void QmitkToolSelectionBox::SetAutoShowNamesWidth(int width) { width = std::max(0, width); if (m_AutoShowNamesWidth != width) { m_AutoShowNamesWidth = width; if (width != 0) this->SetShowNames(this->width() >= m_AutoShowNamesWidth); else this->SetShowNames(true); } } void QmitkToolSelectionBox::SetGenerateAccelerators(bool accel) { if (accel != m_GenerateAccelerators) { m_GenerateAccelerators = accel; RecreateButtons(); } } void QmitkToolSelectionBox::SetToolGUIArea( QWidget* parentWidget ) { m_ToolGUIWidget = parentWidget; } void QmitkToolSelectionBox::setTitle( const QString& /*title*/ ) { } void QmitkToolSelectionBox::showEvent( QShowEvent* e ) { QWidget::showEvent(e); SetGUIEnabledAccordingToToolManagerState(); } void QmitkToolSelectionBox::hideEvent( QHideEvent* e ) { QWidget::hideEvent(e); SetGUIEnabledAccordingToToolManagerState(); } void QmitkToolSelectionBox::resizeEvent( QResizeEvent* e ) { QWidget::resizeEvent(e); if (m_AutoShowNamesWidth != 0) this->SetShowNames(e->size().width() >= m_AutoShowNamesWidth); } diff --git a/Modules/ToFHardware/mitkAbstractToFDeviceFactory.cpp b/Modules/ToFHardware/mitkAbstractToFDeviceFactory.cpp index 0aa5596383..113a62aed6 100644 --- a/Modules/ToFHardware/mitkAbstractToFDeviceFactory.cpp +++ b/Modules/ToFHardware/mitkAbstractToFDeviceFactory.cpp @@ -1,83 +1,83 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkAbstractToFDeviceFactory.h" #include #include //Microservices -#include +#include #include -#include -#include -#include +#include +#include +#include //TinyXML #include mitk::ToFCameraDevice::Pointer mitk::AbstractToFDeviceFactory::ConnectToFDevice() { ToFCameraDevice::Pointer device = CreateToFCameraDevice(); mitk::CameraIntrinsics::Pointer cameraIntrinsics = GetCameraIntrinsics(); device->SetProperty("CameraIntrinsics", mitk::CameraIntrinsicsProperty::New(cameraIntrinsics)); m_Devices.push_back(device); - ModuleContext* context = mitk::GetModuleContext(); - ServiceProperties deviceProps; + us::ModuleContext* context = us::GetModuleContext(); + us::ServiceProperties deviceProps; //-------------Take a look at this part to change the name given to a device deviceProps["ToFDeviceName"] = GetCurrentDeviceName(); - m_DeviceRegistrations.insert(std::make_pair(device.GetPointer(), context->RegisterService(device.GetPointer(),deviceProps))); + m_DeviceRegistrations.insert(std::make_pair(device.GetPointer(), context->RegisterService(device.GetPointer(),deviceProps))); return device; } void mitk::AbstractToFDeviceFactory::DisconnectToFDevice(const ToFCameraDevice::Pointer& device) { - std::map::iterator i = m_DeviceRegistrations.find(device.GetPointer()); - if (i == m_DeviceRegistrations.end()) return; + std::map >::iterator i = m_DeviceRegistrations.find(device.GetPointer()); + if (i == m_DeviceRegistrations.end()) return; - i->second.Unregister(); - m_DeviceRegistrations.erase(i); + i->second.Unregister(); + m_DeviceRegistrations.erase(i); - m_Devices.erase(std::remove(m_Devices.begin(), m_Devices.end(), device), m_Devices.end()); + m_Devices.erase(std::remove(m_Devices.begin(), m_Devices.end(), device), m_Devices.end()); } mitk::CameraIntrinsics::Pointer mitk::AbstractToFDeviceFactory::GetCameraIntrinsics() { - mitk::ModuleResource resource = GetIntrinsicsResource(); + us::ModuleResource resource = GetIntrinsicsResource(); if (! resource.IsValid()) { MITK_WARN << "Could not load resource '" << resource.GetName() << "'. CameraIntrinsics are invalid!"; } // Create ResourceStream from Resource - mitk::ModuleResourceStream resStream(resource); + us::ModuleResourceStream resStream(resource); // Parse XML TiXmlDocument xmlDocument; resStream >> xmlDocument; //Retrieve Child Element and convert to CamerIntrinsics TiXmlElement* element = xmlDocument.FirstChildElement(); mitk::CameraIntrinsics::Pointer intrinsics = mitk::CameraIntrinsics::New(); intrinsics->FromXML(element); return intrinsics; } -mitk::ModuleResource mitk::AbstractToFDeviceFactory::GetIntrinsicsResource() +us::ModuleResource mitk::AbstractToFDeviceFactory::GetIntrinsicsResource() { - mitk::Module* module = mitk::GetModuleContext()->GetModule(); + us::Module* module = us::GetModuleContext()->GetModule(); return module->GetResource("CalibrationFiles/Default_Parameters.xml"); MITK_WARN << "Loaded Default CameraIntrinsics. Overwrite AbstractToFDeviceFactory::GetIntrinsicsResource() if you want to define your own."; } diff --git a/Modules/ToFHardware/mitkAbstractToFDeviceFactory.h b/Modules/ToFHardware/mitkAbstractToFDeviceFactory.h index f3498b7398..05945a0aa5 100644 --- a/Modules/ToFHardware/mitkAbstractToFDeviceFactory.h +++ b/Modules/ToFHardware/mitkAbstractToFDeviceFactory.h @@ -1,66 +1,66 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkAbstractToFDeviceFactory_h #define __mitkAbstractToFDeviceFactory_h #include "mitkToFHardwareExports.h" #include "mitkIToFDeviceFactory.h" // Microservices #include -#include +#include namespace mitk { /** * @brief Virtual interface and base class for all Time-of-Flight device factories * * @ingroup ToFHardware */ struct MITK_TOFHARDWARE_EXPORT AbstractToFDeviceFactory : public IToFDeviceFactory { public: ToFCameraDevice::Pointer ConnectToFDevice(); void DisconnectToFDevice(const ToFCameraDevice::Pointer& device); protected: /** \brief Returns the CameraIntrinsics for the cameras created by this factory. * * This Method calls the virtual method GetIntrinsicsResource() to retrieve the necessary data. * Override getIntrinsicsResource in your subclasses, also see the documentation of GetIntrinsicsResource */ CameraIntrinsics::Pointer GetCameraIntrinsics(); /** \brief Returns the ModuleResource that contains a xml definition of the CameraIntrinsics. * * The default implementation returns a default calibration. * In subclasses, you can override this method to return a different xml resource. * See this implementation for an example. */ - virtual mitk::ModuleResource GetIntrinsicsResource(); + virtual us::ModuleResource GetIntrinsicsResource(); std::vector m_Devices; - std::map m_DeviceRegistrations; + std::map > m_DeviceRegistrations; }; } #endif diff --git a/Modules/ToFHardware/mitkToFCameraDevice.cpp b/Modules/ToFHardware/mitkToFCameraDevice.cpp index 490a4bb78a..31df25a521 100644 --- a/Modules/ToFHardware/mitkToFCameraDevice.cpp +++ b/Modules/ToFHardware/mitkToFCameraDevice.cpp @@ -1,195 +1,189 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkToFCameraDevice.h" #include -//Microservices -#include -#include "mitkModuleContext.h" - namespace mitk { ToFCameraDevice::ToFCameraDevice():m_BufferSize(1),m_MaxBufferSize(100),m_CurrentPos(-1),m_FreePos(0), m_CaptureWidth(204),m_CaptureHeight(204),m_PixelNumber(41616),m_SourceDataSize(0), m_ThreadID(0),m_CameraActive(false),m_CameraConnected(false),m_ImageSequence(0) { this->m_AmplitudeArray = NULL; this->m_IntensityArray = NULL; this->m_DistanceArray = NULL; this->m_PropertyList = mitk::PropertyList::New(); //By default, all devices have no further images (just a distance image) //If a device provides more data (e.g. RGB, Intensity, Amplitde images, //the property has to be true. this->m_PropertyList->SetBoolProperty("HasRGBImage", false); this->m_PropertyList->SetBoolProperty("HasIntensityImage", false); this->m_PropertyList->SetBoolProperty("HasAmplitudeImage", false); this->m_MultiThreader = itk::MultiThreader::New(); this->m_ImageMutex = itk::FastMutexLock::New(); this->m_CameraActiveMutex = itk::FastMutexLock::New(); this->m_RGBImageWidth = this->m_CaptureWidth; this->m_RGBImageHeight = this->m_CaptureHeight; this->m_RGBPixelNumber = this->m_RGBImageWidth* this->m_RGBImageHeight; } ToFCameraDevice::~ToFCameraDevice() { } void ToFCameraDevice::SetBoolProperty( const char* propertyKey, bool boolValue ) { SetProperty(propertyKey, mitk::BoolProperty::New(boolValue)); } void ToFCameraDevice::SetIntProperty( const char* propertyKey, int intValue ) { SetProperty(propertyKey, mitk::IntProperty::New(intValue)); } void ToFCameraDevice::SetFloatProperty( const char* propertyKey, float floatValue ) { SetProperty(propertyKey, mitk::FloatProperty::New(floatValue)); } void ToFCameraDevice::SetStringProperty( const char* propertyKey, const char* stringValue ) { SetProperty(propertyKey, mitk::StringProperty::New(stringValue)); } void ToFCameraDevice::SetProperty( const char *propertyKey, BaseProperty* propertyValue ) { this->m_PropertyList->SetProperty(propertyKey, propertyValue); } BaseProperty* ToFCameraDevice::GetProperty(const char *propertyKey) { return this->m_PropertyList->GetProperty(propertyKey); } bool ToFCameraDevice::GetBoolProperty(const char *propertyKey, bool& boolValue) { mitk::BoolProperty::Pointer boolprop = dynamic_cast(this->GetProperty(propertyKey)); if(boolprop.IsNull()) return false; boolValue = boolprop->GetValue(); return true; } bool ToFCameraDevice::GetStringProperty(const char *propertyKey, std::string& string) { mitk::StringProperty::Pointer stringProp = dynamic_cast(this->GetProperty(propertyKey)); if(stringProp.IsNull()) { return false; } else { string = stringProp->GetValue(); return true; } } bool ToFCameraDevice::GetIntProperty(const char *propertyKey, int& integer) { mitk::IntProperty::Pointer intProp = dynamic_cast(this->GetProperty(propertyKey)); if(intProp.IsNull()) { return false; } else { integer = intProp->GetValue(); return true; } } void ToFCameraDevice::CleanupPixelArrays() { if (m_IntensityArray) { delete [] m_IntensityArray; } if (m_DistanceArray) { delete [] m_DistanceArray; } if (m_AmplitudeArray) { delete [] m_AmplitudeArray; } } void ToFCameraDevice::AllocatePixelArrays() { // free memory if it was already allocated CleanupPixelArrays(); // allocate buffer this->m_IntensityArray = new float[this->m_PixelNumber]; for(int i=0; im_PixelNumber; i++) {this->m_IntensityArray[i]=0.0;} this->m_DistanceArray = new float[this->m_PixelNumber]; for(int i=0; im_PixelNumber; i++) {this->m_DistanceArray[i]=0.0;} this->m_AmplitudeArray = new float[this->m_PixelNumber]; for(int i=0; im_PixelNumber; i++) {this->m_AmplitudeArray[i]=0.0;} } int ToFCameraDevice::GetRGBCaptureWidth() { return this->m_RGBImageWidth; } int ToFCameraDevice::GetRGBCaptureHeight() { return this->m_RGBImageHeight; } void ToFCameraDevice::StopCamera() { m_CameraActiveMutex->Lock(); m_CameraActive = false; m_CameraActiveMutex->Unlock(); itksys::SystemTools::Delay(100); if (m_MultiThreader.IsNotNull()) { m_MultiThreader->TerminateThread(m_ThreadID); } // wait a little to make sure that the thread is terminated itksys::SystemTools::Delay(100); } bool ToFCameraDevice::IsCameraActive() { m_CameraActiveMutex->Lock(); bool ok = m_CameraActive; m_CameraActiveMutex->Unlock(); return ok; -} + } + bool ToFCameraDevice::ConnectCamera() { - // Prepare connection, fail if this fails. - if (! this->OnConnectCamera()) return false; - - // Get Context and Module - mitk::ModuleContext* context = GetModuleContext(); - return true; + // Prepare connection, fail if this fails. + if (! this->OnConnectCamera()) return false; + return true; } bool ToFCameraDevice::IsCameraConnected() { return m_CameraConnected; } } diff --git a/Modules/ToFHardware/mitkToFCameraDevice.h b/Modules/ToFHardware/mitkToFCameraDevice.h index eff5d786e9..6c9e0781c9 100644 --- a/Modules/ToFHardware/mitkToFCameraDevice.h +++ b/Modules/ToFHardware/mitkToFCameraDevice.h @@ -1,236 +1,231 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkToFCameraDevice_h #define __mitkToFCameraDevice_h #include "mitkToFHardwareExports.h" #include "mitkCommon.h" #include "mitkStringProperty.h" #include "mitkProperties.h" #include "mitkPropertyList.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" // Microservices #include -#include namespace mitk { /** * @brief Virtual interface and base class for all Time-of-Flight devices. * * @ingroup ToFHardware */ class MITK_TOFHARDWARE_EXPORT ToFCameraDevice : public itk::Object { public: mitkClassMacro(ToFCameraDevice, itk::Object); /*! \brief opens a connection to the ToF camera */ virtual bool OnConnectCamera() = 0; virtual bool ConnectCamera(); /*! \brief closes the connection to the camera */ virtual bool DisconnectCamera() = 0; /*! \brief starts the continuous updating of the camera. A separate thread updates the source data, the main thread processes the source data and creates images and coordinates */ virtual void StartCamera() = 0; /*! \brief stops the continuous updating of the camera */ virtual void StopCamera(); /*! \brief returns true if the camera is connected and started */ virtual bool IsCameraActive(); /*! \brief returns true if the camera is connected */ virtual bool IsCameraConnected(); /*! \brief updates the camera for image acquisition */ virtual void UpdateCamera() = 0; /*! \brief gets the amplitude data from the ToF camera as the strength of the active illumination of every pixel These values can be used to determine the quality of the distance values. The higher the amplitude value, the higher the accuracy of the according distance value \param imageSequence the actually captured image sequence number \param amplitudeArray contains the returned amplitude data as an array. */ virtual void GetAmplitudes(float* amplitudeArray, int& imageSequence) = 0; /*! \brief gets the intensity data from the ToF camera as a greyscale image \param intensityArray contains the returned intensities data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetIntensities(float* intensityArray, int& imageSequence) = 0; /*! \brief gets the distance data from the ToF camera measuring the distance between the camera and the different object points in millimeters \param distanceArray contains the returned distances data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetDistances(float* distanceArray, int& imageSequence) = 0; /*! \brief gets the 3 images (distance, amplitude, intensity) from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distance data as an array. \param amplitudeArray contains the returned amplitude data as an array. \param intensityArray contains the returned intensity data as an array. \param sourceDataArray contains the complete source data from the camera device. \param requiredImageSequence the required image sequence number \param capturedImageSequence the actually captured image sequence number */ virtual void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray=NULL) = 0; // TODO: Buffer size currently set to 1. Once Buffer handling is working correctly, method may be reactivated // /* // * TODO: Reenable doxygen comment when uncommenting, disabled to fix doxygen warning see bug 12882 // \brief pure virtual method resetting the buffer using the specified bufferSize. Has to be implemented by sub-classes // \param bufferSize buffer size the buffer should be reset to // */ // virtual void ResetBuffer(int bufferSize) = 0; //TODO add/correct documentation for requiredImageSequence and capturedImageSequence in the GetAllImages, GetDistances, GetIntensities and GetAmplitudes methods. /*! \brief get the currently set capture width \return capture width */ itkGetMacro(CaptureWidth, int); /*! \brief get the currently set capture height \return capture height */ itkGetMacro(CaptureHeight, int); /*! \brief get the currently set source data size \return source data size */ itkGetMacro(SourceDataSize, int); /*! \brief get the currently set buffer size \return buffer size */ itkGetMacro(BufferSize, int); /*! \brief get the currently set max buffer size \return max buffer size */ itkGetMacro(MaxBufferSize, int); /*! \brief set a bool property in the property list */ void SetBoolProperty( const char* propertyKey, bool boolValue ); /*! \brief set an int property in the property list */ void SetIntProperty( const char* propertyKey, int intValue ); /*! \brief set a float property in the property list */ void SetFloatProperty( const char* propertyKey, float floatValue ); /*! \brief set a string property in the property list */ void SetStringProperty( const char* propertyKey, const char* stringValue ); /*! \brief set a BaseProperty property in the property list */ virtual void SetProperty( const char *propertyKey, BaseProperty* propertyValue ); /*! \brief get a BaseProperty from the property list */ virtual BaseProperty* GetProperty( const char *propertyKey ); /*! \brief get a bool from the property list */ bool GetBoolProperty(const char *propertyKey, bool& boolValue); /*! \brief get a string from the property list */ bool GetStringProperty(const char *propertyKey, std::string& string); /*! \brief get an int from the property list */ bool GetIntProperty(const char *propertyKey, int& integer); virtual int GetRGBCaptureWidth(); virtual int GetRGBCaptureHeight(); protected: ToFCameraDevice(); ~ToFCameraDevice(); /*! \brief method for allocating memory for pixel arrays m_IntensityArray, m_DistanceArray and m_AmplitudeArray */ virtual void AllocatePixelArrays(); /*! \brief method for cleanup memory allocated for pixel arrays m_IntensityArray, m_DistanceArray and m_AmplitudeArray */ virtual void CleanupPixelArrays(); float* m_IntensityArray; ///< float array holding the intensity image float* m_DistanceArray; ///< float array holding the distance image float* m_AmplitudeArray; ///< float array holding the amplitude image int m_BufferSize; ///< buffer size of the image buffer needed for loss-less acquisition of range data int m_MaxBufferSize; ///< maximal buffer size needed for initialization of data arrays. Default value is 100. int m_CurrentPos; ///< current position in the buffer which will be retrieved by the Get methods int m_FreePos; ///< current position in the buffer which will be filled with data acquired from the hardware int m_CaptureWidth; ///< width of the range image (x dimension) int m_CaptureHeight; ///< height of the range image (y dimension) int m_PixelNumber; ///< number of pixels in the range image (m_CaptureWidth*m_CaptureHeight) int m_RGBImageWidth; int m_RGBImageHeight; int m_RGBPixelNumber; int m_SourceDataSize; ///< size of the PMD source data itk::MultiThreader::Pointer m_MultiThreader; ///< itk::MultiThreader used for thread handling itk::FastMutexLock::Pointer m_ImageMutex; ///< mutex for images provided by the range camera itk::FastMutexLock::Pointer m_CameraActiveMutex; ///< mutex for the cameraActive flag int m_ThreadID; ///< ID of the started thread bool m_CameraActive; ///< flag indicating if the camera is currently active or not. Caution: thread safe access only! bool m_CameraConnected; ///< flag indicating if the camera is successfully connected or not. Caution: thread safe access only! int m_ImageSequence; ///< counter for acquired images PropertyList::Pointer m_PropertyList; ///< a list of the corresponding properties - private: - - mitk::ServiceRegistration m_ServiceRegistration; - }; } //END mitk namespace // This is the microservice declaration. Do not meddle! US_DECLARE_SERVICE_INTERFACE(mitk::ToFCameraDevice, "org.mitk.services.ToFCameraDevice") #endif diff --git a/Modules/ToFHardware/mitkToFCameraMITKPlayerDeviceFactory.h b/Modules/ToFHardware/mitkToFCameraMITKPlayerDeviceFactory.h index 98baac6c94..c55bad23ce 100644 --- a/Modules/ToFHardware/mitkToFCameraMITKPlayerDeviceFactory.h +++ b/Modules/ToFHardware/mitkToFCameraMITKPlayerDeviceFactory.h @@ -1,94 +1,94 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkToFCameraMITKPlayerDeviceFactory_h #define __mitkToFCameraMITKPlayerDeviceFactory_h #include "mitkToFHardwareExports.h" #include "mitkToFCameraMITKPlayerDevice.h" #include "mitkAbstractToFDeviceFactory.h" #include #include #include namespace mitk { /** * \brief ToFPlayerDeviceFactory is an implementation of the factory pattern to generate ToFPlayer devices. * ToFPlayerDeviceFactory inherits from AbstractToFDeviceFactory which is a MicroService interface. * This offers users the oppertunity to generate new ToFPlayerDevices via a global instance of this factory. * @ingroup ToFHardware */ -class MITK_TOFHARDWARE_EXPORT ToFCameraMITKPlayerDeviceFactory : public itk::LightObject, public AbstractToFDeviceFactory { +class MITK_TOFHARDWARE_EXPORT ToFCameraMITKPlayerDeviceFactory : public AbstractToFDeviceFactory { public: ToFCameraMITKPlayerDeviceFactory() { m_DeviceNumber = 1; } /*! - \brief Defining the Factorie´s Name, here for the ToFPlayer. + \brief Defining the Factorie's Name, here for the ToFPlayer. */ std::string GetFactoryName() { return std::string("MITK Player Factory"); } std::string GetCurrentDeviceName() { std::stringstream name; if(m_DeviceNumber>1) { name << "MITK Player "<< m_DeviceNumber; } else { name << "MITK Player"; } m_DeviceNumber++; return name.str(); } private: /*! \brief Create an instance of a ToFPlayerDevice. */ ToFCameraDevice::Pointer CreateToFCameraDevice() { ToFCameraMITKPlayerDevice::Pointer device = ToFCameraMITKPlayerDevice::New(); ////-------------------------If no Intrinsics are specified------------------------------ // //Set default camera intrinsics for the MITK-Player. // mitk::CameraIntrinsics::Pointer cameraIntrinsics = mitk::CameraIntrinsics::New(); // std::string pathToDefaulCalibrationFile(MITK_TOF_DATA_DIR); // // pathToDefaulCalibrationFile.append("/CalibrationFiles/Default_Parameters.xml"); // cameraIntrinsics->FromXMLFile(pathToDefaulCalibrationFile); // device->SetProperty("CameraIntrinsics", mitk::CameraIntrinsicsProperty::New(cameraIntrinsics)); // ////------------------------------------------------------------------------------------------ return device.GetPointer(); } int m_DeviceNumber; }; } #endif diff --git a/Modules/ToFHardware/mitkToFDeviceFactoryManager.cpp b/Modules/ToFHardware/mitkToFDeviceFactoryManager.cpp index f50c6f12cb..76ca2f2bef 100644 --- a/Modules/ToFHardware/mitkToFDeviceFactoryManager.cpp +++ b/Modules/ToFHardware/mitkToFDeviceFactoryManager.cpp @@ -1,103 +1,103 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkToFDeviceFactoryManager.h" #include "mitkAbstractToFDeviceFactory.h" //Microservices #include namespace mitk { ToFDeviceFactoryManager::ToFDeviceFactoryManager() { ModuleContext* context = GetModuleContext(); m_RegisteredFactoryRefs = context->GetServiceReferences(); if (m_RegisteredFactoryRefs.empty()) { MITK_ERROR << "No factories registered!"; } } ToFDeviceFactoryManager::~ToFDeviceFactoryManager() { } std::vector ToFDeviceFactoryManager::GetRegisteredDeviceFactories() { ModuleContext* context = GetModuleContext(); // std::string filter("(" + mitk::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.IToFDeviceFactory)"); // std::list serviceRef = context->GetServiceReference(/*filter*/); - std::list serviceRefs = context->GetServiceReferences(/*filter*/); - if (serviceRefs.size() > 0) + std::vector > serviceRefs = context->GetServiceReferences(/*filter*/); + if (!serviceRefs.empty()) { - for(std::list::iterator it = serviceRefs.begin(); it != serviceRefs.end(); ++it) + for(std::vector >::iterator it = serviceRefs.begin(); it != serviceRefs.end(); ++it) { - IToFDeviceFactory* service = context->GetService( *it ); + IToFDeviceFactory* service = context->GetService( *it ); if(service) { m_RegisteredFactoryNames.push_back(std::string(service->GetFactoryName())); } } } return m_RegisteredFactoryNames; } std::vector ToFDeviceFactoryManager::GetConnectedDevices() { - ModuleContext* context = GetModuleContext(); + us::ModuleContext* context = us::GetModuleContext(); std::vector result; - std::list serviceRefs = context->GetServiceReferences(); - if (serviceRefs.size() > 0) + std::vector > serviceRefs = context->GetServiceReferences(); + if (!serviceRefs.empty()) { - for(std::list::iterator it = serviceRefs.begin(); it != serviceRefs.end(); ++it) + for(std::empty >::iterator it = serviceRefs.begin(); it != serviceRefs.end(); ++it) { - ToFCameraDevice* service = context->GetService( *it ); + ToFCameraDevice* service = context->GetService( *it ); if(service) { result.push_back(std::string(service->GetNameOfClass())); } } } if(result.size() == 0) { MITK_ERROR << "No devices connected!"; } return result; } ToFCameraDevice* ToFDeviceFactoryManager::GetInstanceOfDevice(int index) { - ModuleContext* context = GetModuleContext(); + us::ModuleContext* context = us::GetModuleContext(); - std::list serviceRefs = context->GetServiceReferences(/*filter*/); - if (serviceRefs.size() > 0) + std::vector > serviceRefs = context->GetServiceReferences(/*filter*/); + if (!serviceRefs.empty()) { int i = 0; - for(std::list::iterator it = serviceRefs.begin(); it != serviceRefs.end(); ++it) + for(std::vector >::iterator it = serviceRefs.begin(); it != serviceRefs.end(); ++it) { - IToFDeviceFactory* service = context->GetService( *it ); + IToFDeviceFactory* service = context->GetService( *it ); if(service && (i == index)) { return dynamic_cast(service)->ConnectToFDevice(); } i++; } } MITK_ERROR << "No device generated!"; return NULL; } } diff --git a/Modules/ToFHardware/mitkToFDeviceFactoryManager.h b/Modules/ToFHardware/mitkToFDeviceFactoryManager.h index 78d7d4ae3b..5a06c965cd 100644 --- a/Modules/ToFHardware/mitkToFDeviceFactoryManager.h +++ b/Modules/ToFHardware/mitkToFDeviceFactoryManager.h @@ -1,62 +1,64 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkToFDeviceListener_h #define __mitkToFDeviceListener_h #include "mitkToFHardwareExports.h" #include "mitkToFCameraDevice.h" //Microservices #include namespace mitk { + struct IToFDeviceFactory; + /** * @brief ToFDeviceListener * * @ingroup ToFHardware */ class MITK_TOFHARDWARE_EXPORT ToFDeviceFactoryManager: public itk::Object { public: mitkClassMacro( ToFDeviceFactoryManager, itk::Object ); itkNewMacro( Self ); std::vector GetRegisteredDeviceFactories(); std::vector GetConnectedDevices(); ToFCameraDevice* GetInstanceOfDevice(int index); protected: ToFDeviceFactoryManager(); ~ToFDeviceFactoryManager(); std::vector m_RegisteredFactoryNames; - std::list m_RegisteredFactoryRefs; + std::vector > m_RegisteredFactoryRefs; private: }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/mitkToFHardwareActivator.cpp b/Modules/ToFHardware/mitkToFHardwareActivator.cpp index 866b18d2dd..2bccd0ed35 100644 --- a/Modules/ToFHardware/mitkToFHardwareActivator.cpp +++ b/Modules/ToFHardware/mitkToFHardwareActivator.cpp @@ -1,76 +1,75 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __mitkToFHardwareModuleActivator_h #define __mitkToFHardwareModuleActivator_h // Microservices #include #include -#include "mitkModuleContext.h" +#include -#include #include "mitkIToFDeviceFactory.h" #include "mitkToFConfig.h" #include "mitkToFCameraMITKPlayerDeviceFactory.h" /* * This is the module activator for the "ToFHardware" module. It registers services * like the IToFDeviceFactory. */ namespace mitk { -class ToFHardwareActivator : public mitk::ModuleActivator { +class ToFHardwareActivator : public us::ModuleActivator { public: - void Load(mitk::ModuleContext* context) + void Load(us::ModuleContext* context) { //Registering MITKPlayerDevice as MicroService ToFCameraMITKPlayerDeviceFactory* toFCameraMITKPlayerDeviceFactory = new ToFCameraMITKPlayerDeviceFactory(); - ServiceProperties mitkPlayerFactoryProps; + us::ServiceProperties mitkPlayerFactoryProps; mitkPlayerFactoryProps["ToFFactoryName"] = toFCameraMITKPlayerDeviceFactory->GetFactoryName(); context->RegisterService(toFCameraMITKPlayerDeviceFactory, mitkPlayerFactoryProps); //Create an instance of the player toFCameraMITKPlayerDeviceFactory->ConnectToFDevice(); m_Factories.push_back( toFCameraMITKPlayerDeviceFactory ); } - void Unload(mitk::ModuleContext* ) + void Unload(us::ModuleContext* ) { } ~ToFHardwareActivator() { //todo iterieren über liste m_Factories und löschen if(m_Factories.size() > 0) { for(std::list< IToFDeviceFactory* >::iterator it = m_Factories.begin(); it != m_Factories.end(); ++it) { delete (*it); //todo wie genau löschen? } } } private: std::list< IToFDeviceFactory* > m_Factories; }; } US_EXPORT_MODULE_ACTIVATOR(mitkToFHardware, mitk::ToFHardwareActivator) #endif diff --git a/Modules/ToFProcessing/mitkToFSurfaceVtkMapper3D.cpp b/Modules/ToFProcessing/mitkToFSurfaceVtkMapper3D.cpp index 8dca206acf..c2aee2d34e 100644 --- a/Modules/ToFProcessing/mitkToFSurfaceVtkMapper3D.cpp +++ b/Modules/ToFProcessing/mitkToFSurfaceVtkMapper3D.cpp @@ -1,507 +1,509 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkToFSurfaceVtkMapper3D.h" #include "mitkDataNode.h" #include "mitkProperties.h" #include "mitkColorProperty.h" #include "mitkLookupTableProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkScalarModeProperty.h" #include "mitkClippingProperty.h" +#include "mitkIShaderRepository.h" #include "mitkShaderProperty.h" -#include "mitkShaderRepository.h" +#include "mitkCoreServices.h" #include #include #include #include #include #include #include #include #include #include #include //const mitk::ToFSurface* mitk::ToFSurfaceVtkMapper3D::GetInput() const mitk::Surface* mitk::ToFSurfaceVtkMapper3D::GetInput() { //return static_cast ( GetData() ); return static_cast ( GetDataNode()->GetData() ); } mitk::ToFSurfaceVtkMapper3D::ToFSurfaceVtkMapper3D() { // m_Prop3D = vtkActor::New(); m_GenerateNormals = false; this->m_Texture = NULL; this->m_TextureWidth = 0; this->m_TextureHeight = 0; this->m_VtkScalarsToColors = NULL; } mitk::ToFSurfaceVtkMapper3D::~ToFSurfaceVtkMapper3D() { // m_Prop3D->Delete(); } void mitk::ToFSurfaceVtkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer* renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if ( !visible ) { ls->m_Actor->VisibilityOff(); return; } // // set the input-object at time t for the mapper // //mitk::ToFSurface::Pointer input = const_cast< mitk::ToFSurface* >( this->GetInput() ); mitk::Surface::Pointer input = const_cast< mitk::Surface* >( this->GetInput() ); vtkPolyData * polydata = input->GetVtkPolyData( this->GetTimestep() ); if(polydata == NULL) { ls->m_Actor->VisibilityOff(); return; } if ( m_GenerateNormals ) { ls->m_VtkPolyDataNormals->SetInput( polydata ); ls->m_VtkPolyDataMapper->SetInput( ls->m_VtkPolyDataNormals->GetOutput() ); } else { ls->m_VtkPolyDataMapper->SetInput( polydata ); } // // apply properties read from the PropertyList // ApplyProperties(ls->m_Actor, renderer); if(visible) ls->m_Actor->VisibilityOn(); // // TOF extension for visualization (color/texture mapping) // if (this->m_VtkScalarsToColors) { // set the color transfer funtion if applied ls->m_VtkPolyDataMapper->SetLookupTable(this->m_VtkScalarsToColors); } if (this->m_Texture) { ls->m_Actor->SetTexture(this->m_Texture); } else { // remove the texture ls->m_Actor->SetTexture(0); } } void mitk::ToFSurfaceVtkMapper3D::ResetMapper( BaseRenderer* renderer ) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); ls->m_Actor->VisibilityOff(); } void mitk::ToFSurfaceVtkMapper3D::ApplyMitkPropertiesToVtkProperty(mitk::DataNode *node, vtkProperty* property, mitk::BaseRenderer* renderer) { // Colors { double ambient [3] = { 0.5,0.5,0.0 }; double diffuse [3] = { 0.5,0.5,0.0 }; double specular[3] = { 1.0,1.0,1.0 }; float coeff_ambient = 0.5f; float coeff_diffuse = 0.5f; float coeff_specular= 0.5f; float power_specular=10.0f; // Color { mitk::ColorProperty::Pointer p; node->GetProperty(p, "color", renderer); if(p.IsNotNull()) { mitk::Color c = p->GetColor(); ambient[0]=c.GetRed(); ambient[1]=c.GetGreen(); ambient[2]=c.GetBlue(); diffuse[0]=c.GetRed(); diffuse[1]=c.GetGreen(); diffuse[2]=c.GetBlue(); // Setting specular color to the same, make physically no real sense, however vtk rendering slows down, if these colors are different. specular[0]=c.GetRed(); specular[1]=c.GetGreen(); specular[2]=c.GetBlue(); } } // Ambient { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.ambientColor", renderer); if(p.IsNotNull()) { mitk::Color c = p->GetColor(); ambient[0]=c.GetRed(); ambient[1]=c.GetGreen(); ambient[2]=c.GetBlue(); } } // Diffuse { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.diffuseColor", renderer); if(p.IsNotNull()) { mitk::Color c = p->GetColor(); diffuse[0]=c.GetRed(); diffuse[1]=c.GetGreen(); diffuse[2]=c.GetBlue(); } } // Specular { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.specularColor", renderer); if(p.IsNotNull()) { mitk::Color c = p->GetColor(); specular[0]=c.GetRed(); specular[1]=c.GetGreen(); specular[2]=c.GetBlue(); } } // Ambient coeff { node->GetFloatProperty("material.ambientCoefficient", coeff_ambient, renderer); } // Diffuse coeff { node->GetFloatProperty("material.diffuseCoefficient", coeff_diffuse, renderer); } // Specular coeff { node->GetFloatProperty("material.specularCoefficient", coeff_specular, renderer); } // Specular power { node->GetFloatProperty("material.specularPower", power_specular, renderer); } property->SetAmbient( coeff_ambient ); property->SetDiffuse( coeff_diffuse ); property->SetSpecular( coeff_specular ); property->SetSpecularPower( power_specular ); property->SetAmbientColor( ambient ); property->SetDiffuseColor( diffuse ); property->SetSpecularColor( specular ); } // Render mode { // Opacity { float opacity = 1.0f; if( node->GetOpacity(opacity,renderer) ) property->SetOpacity( opacity ); } // Wireframe line width { float lineWidth = 1; node->GetFloatProperty("material.wireframeLineWidth", lineWidth, renderer); property->SetLineWidth( lineWidth ); } // Representation { mitk::VtkRepresentationProperty::Pointer p; node->GetProperty(p, "material.representation", renderer); if(p.IsNotNull()) property->SetRepresentation( p->GetVtkRepresentation() ); } // Interpolation { mitk::VtkInterpolationProperty::Pointer p; node->GetProperty(p, "material.interpolation", renderer); if(p.IsNotNull()) property->SetInterpolation( p->GetVtkInterpolation() ); } } } void mitk::ToFSurfaceVtkMapper3D::ApplyProperties(vtkActor* /*actor*/, mitk::BaseRenderer* renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); // Applying shading properties { ApplyColorAndOpacityProperties( renderer, ls->m_Actor ) ; // VTK Properties ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer ); // Shaders - mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),ls->m_Actor,renderer,ls->m_ShaderTimestampUpdate); + CoreServicePointer(mitk::CoreServices::GetShaderRepository())->ApplyProperties( + this->GetDataNode(),ls->m_Actor,renderer,ls->m_ShaderTimestampUpdate); } mitk::LookupTableProperty::Pointer lookupTableProp; this->GetDataNode()->GetProperty(lookupTableProp, "LookupTable", renderer); if (lookupTableProp.IsNotNull() ) { ls->m_VtkPolyDataMapper->SetLookupTable(lookupTableProp->GetLookupTable()->GetVtkLookupTable()); } mitk::LevelWindow levelWindow; if(this->GetDataNode()->GetLevelWindow(levelWindow, renderer, "levelWindow")) { ls->m_VtkPolyDataMapper->SetScalarRange(levelWindow.GetLowerWindowBound(),levelWindow.GetUpperWindowBound()); } else if(this->GetDataNode()->GetLevelWindow(levelWindow, renderer)) { ls->m_VtkPolyDataMapper->SetScalarRange(levelWindow.GetLowerWindowBound(),levelWindow.GetUpperWindowBound()); } bool scalarVisibility = false; this->GetDataNode()->GetBoolProperty("scalar visibility", scalarVisibility); ls->m_VtkPolyDataMapper->SetScalarVisibility( (scalarVisibility ? 1 : 0) ); if(scalarVisibility) { mitk::VtkScalarModeProperty* scalarMode; if(this->GetDataNode()->GetProperty(scalarMode, "scalar mode", renderer)) { ls->m_VtkPolyDataMapper->SetScalarMode(scalarMode->GetVtkScalarMode()); } else ls->m_VtkPolyDataMapper->SetScalarModeToDefault(); bool colorMode = false; this->GetDataNode()->GetBoolProperty("color mode", colorMode); ls->m_VtkPolyDataMapper->SetColorMode( (colorMode ? 1 : 0) ); float scalarsMin = 0; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum")) != NULL) scalarsMin = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum"))->GetValue(); float scalarsMax = 1.0; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum")) != NULL) scalarsMax = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum"))->GetValue(); ls->m_VtkPolyDataMapper->SetScalarRange(scalarsMin,scalarsMax); } // deprecated settings bool deprecatedUseCellData = false; this->GetDataNode()->GetBoolProperty("deprecated useCellDataForColouring", deprecatedUseCellData); bool deprecatedUsePointData = false; this->GetDataNode()->GetBoolProperty("deprecated usePointDataForColouring", deprecatedUsePointData); if (deprecatedUseCellData) { ls->m_VtkPolyDataMapper->SetColorModeToDefault(); ls->m_VtkPolyDataMapper->SetScalarRange(0,255); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_VtkPolyDataMapper->SetScalarModeToUseCellData(); ls->m_Actor->GetProperty()->SetSpecular (1); ls->m_Actor->GetProperty()->SetSpecularPower (50); ls->m_Actor->GetProperty()->SetInterpolationToPhong(); } else if (deprecatedUsePointData) { float scalarsMin = 0; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum")) != NULL) scalarsMin = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum"))->GetValue(); float scalarsMax = 0.1; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum")) != NULL) scalarsMax = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum"))->GetValue(); ls->m_VtkPolyDataMapper->SetScalarRange(scalarsMin,scalarsMax); ls->m_VtkPolyDataMapper->SetColorModeToMapScalars(); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_Actor->GetProperty()->SetSpecular (1); ls->m_Actor->GetProperty()->SetSpecularPower (50); ls->m_Actor->GetProperty()->SetInterpolationToPhong(); } int deprecatedScalarMode = VTK_COLOR_MODE_DEFAULT; if(this->GetDataNode()->GetIntProperty("deprecated scalar mode", deprecatedScalarMode, renderer)) { ls->m_VtkPolyDataMapper->SetScalarMode(deprecatedScalarMode); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_Actor->GetProperty()->SetSpecular (1); ls->m_Actor->GetProperty()->SetSpecularPower (50); //m_Actor->GetProperty()->SetInterpolationToPhong(); } // Check whether one or more ClippingProperty objects have been defined for // this node. Check both renderer specific and global property lists, since // properties in both should be considered. const PropertyList::PropertyMap *rendererProperties = this->GetDataNode()->GetPropertyList( renderer )->GetMap(); const PropertyList::PropertyMap *globalProperties = this->GetDataNode()->GetPropertyList( NULL )->GetMap(); // Add clipping planes (if any) ls->m_ClippingPlaneCollection->RemoveAllItems(); PropertyList::PropertyMap::const_iterator it; for ( it = rendererProperties->begin(); it != rendererProperties->end(); ++it ) { this->CheckForClippingProperty( renderer,(*it).second.GetPointer() ); } for ( it = globalProperties->begin(); it != globalProperties->end(); ++it ) { this->CheckForClippingProperty( renderer,(*it).second.GetPointer() ); } if ( ls->m_ClippingPlaneCollection->GetNumberOfItems() > 0 ) { ls->m_VtkPolyDataMapper->SetClippingPlanes( ls->m_ClippingPlaneCollection ); } else { ls->m_VtkPolyDataMapper->RemoveAllClippingPlanes(); } } vtkProp *mitk::ToFSurfaceVtkMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); return ls->m_Actor; } void mitk::ToFSurfaceVtkMapper3D::CheckForClippingProperty( mitk::BaseRenderer* renderer, mitk::BaseProperty *property ) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); // m_Prop3D = ls->m_Actor; ClippingProperty *clippingProperty = dynamic_cast< ClippingProperty * >( property ); if ( (clippingProperty != NULL) && (clippingProperty->GetClippingEnabled()) ) { const Point3D &origin = clippingProperty->GetOrigin(); const Vector3D &normal = clippingProperty->GetNormal(); vtkPlane *clippingPlane = vtkPlane::New(); clippingPlane->SetOrigin( origin[0], origin[1], origin[2] ); clippingPlane->SetNormal( normal[0], normal[1], normal[2] ); ls->m_ClippingPlaneCollection->AddItem( clippingPlane ); clippingPlane->UnRegister( NULL ); } } void mitk::ToFSurfaceVtkMapper3D::SetDefaultPropertiesForVtkProperty(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { // Shading { node->AddProperty( "material.wireframeLineWidth", mitk::FloatProperty::New(1.0f) , renderer, overwrite ); node->AddProperty( "material.ambientCoefficient" , mitk::FloatProperty::New(0.05f) , renderer, overwrite ); node->AddProperty( "material.diffuseCoefficient" , mitk::FloatProperty::New(0.9f) , renderer, overwrite ); node->AddProperty( "material.specularCoefficient", mitk::FloatProperty::New(1.0f) , renderer, overwrite ); node->AddProperty( "material.specularPower" , mitk::FloatProperty::New(16.0f) , renderer, overwrite ); //node->AddProperty( "material.ambientColor" , mitk::ColorProperty::New(1.0f,1.0f,1.0f), renderer, overwrite ); //node->AddProperty( "material.diffuseColor" , mitk::ColorProperty::New(1.0f,1.0f,1.0f), renderer, overwrite ); //node->AddProperty( "material.specularColor" , mitk::ColorProperty::New(1.0f,1.0f,1.0f), renderer, overwrite ); node->AddProperty( "material.representation" , mitk::VtkRepresentationProperty::New() , renderer, overwrite ); node->AddProperty( "material.interpolation" , mitk::VtkInterpolationProperty::New() , renderer, overwrite ); } // Shaders { - mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite); + CoreServicePointer(mitk::CoreServices::GetShaderRepository())->AddDefaultProperties(node,renderer,overwrite); } } void mitk::ToFSurfaceVtkMapper3D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { node->AddProperty( "color", mitk::ColorProperty::New(1.0f,1.0f,1.0f), renderer, overwrite ); node->AddProperty( "opacity", mitk::FloatProperty::New(1.0), renderer, overwrite ); mitk::ToFSurfaceVtkMapper3D::SetDefaultPropertiesForVtkProperty(node,renderer,overwrite); // Shading node->AddProperty( "scalar visibility", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "color mode", mitk::BoolProperty::New(false), renderer, overwrite ); node->AddProperty( "scalar mode", mitk::VtkScalarModeProperty::New(), renderer, overwrite ); mitk::Surface::Pointer surface = dynamic_cast(node->GetData()); if(surface.IsNotNull()) { if((surface->GetVtkPolyData() != 0) && (surface->GetVtkPolyData()->GetPointData() != NULL) && (surface->GetVtkPolyData()->GetPointData()->GetScalars() != 0)) { node->AddProperty( "scalar visibility", mitk::BoolProperty::New(true), renderer, overwrite ); node->AddProperty( "color mode", mitk::BoolProperty::New(true), renderer, overwrite ); } } Superclass::SetDefaultProperties(node, renderer, overwrite); } void mitk::ToFSurfaceVtkMapper3D::SetImmediateModeRenderingOn(int /*on*/) { /* if (m_VtkPolyDataMapper != NULL) m_VtkPolyDataMapper->SetImmediateModeRendering(on); */ } void mitk::ToFSurfaceVtkMapper3D::SetTexture(vtkImageData *img) { this->m_Texture = vtkSmartPointer::New(); this->m_Texture->SetInput(img); // MITK_INFO << "Neuer Code"; } vtkSmartPointer mitk::ToFSurfaceVtkMapper3D::GetTexture() { return this->m_Texture; } void mitk::ToFSurfaceVtkMapper3D::SetVtkScalarsToColors(vtkScalarsToColors* vtkScalarsToColors) { this->m_VtkScalarsToColors = vtkScalarsToColors; } vtkScalarsToColors* mitk::ToFSurfaceVtkMapper3D::GetVtkScalarsToColors() { return this->m_VtkScalarsToColors; } diff --git a/Modules/US/USModel/mitkUSDevice.cpp b/Modules/US/USModel/mitkUSDevice.cpp index d5065210bf..d394e5e97e 100644 --- a/Modules/US/USModel/mitkUSDevice.cpp +++ b/Modules/US/USModel/mitkUSDevice.cpp @@ -1,312 +1,312 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkUSDevice.h" //Microservices #include #include #include -#include "mitkModuleContext.h" +#include const std::string mitk::USDevice::US_INTERFACE_NAME = "org.mitk.services.UltrasoundDevice"; const std::string mitk::USDevice::US_PROPKEY_LABEL = US_INTERFACE_NAME + ".label"; const std::string mitk::USDevice::US_PROPKEY_ISACTIVE = US_INTERFACE_NAME + ".isActive"; const std::string mitk::USDevice::US_PROPKEY_CLASS = US_INTERFACE_NAME + ".class"; mitk::USDevice::USImageCropArea mitk::USDevice::GetCropArea() { MITK_INFO << "Return Crop Area L:" << m_CropArea.cropLeft << " R:" << m_CropArea.cropRight << " T:" << m_CropArea.cropTop << " B:" << m_CropArea.cropBottom; return m_CropArea; } mitk::USDevice::USDevice(std::string manufacturer, std::string model) : mitk::ImageSource() { // Initialize Members m_Metadata = mitk::USImageMetadata::New(); m_Metadata->SetDeviceManufacturer(manufacturer); m_Metadata->SetDeviceModel(model); m_IsActive = false; USImageCropArea empty; empty.cropBottom = 0; empty.cropTop = 0; empty.cropLeft = 0; empty.cropRight = 0; this->m_CropArea = empty; m_IsConnected = false; //set number of outputs this->SetNumberOfOutputs(1); //create a new output mitk::USImage::Pointer newOutput = mitk::USImage::New(); this->SetNthOutput(0,newOutput); } mitk::USDevice::USDevice(mitk::USImageMetadata::Pointer metadata) : mitk::ImageSource() { m_Metadata = metadata; m_IsActive = false; m_IsConnected = false; USImageCropArea empty; empty.cropBottom = 0; empty.cropTop = 0; empty.cropLeft = 0; empty.cropRight = 0; this->m_CropArea = empty; //set number of outputs this->SetNumberOfOutputs(1); //create a new output mitk::USImage::Pointer newOutput = mitk::USImage::New(); this->SetNthOutput(0,newOutput); } mitk::USDevice::~USDevice() { } -mitk::ServiceProperties mitk::USDevice::ConstructServiceProperties() +us::ServiceProperties mitk::USDevice::ConstructServiceProperties() { - ServiceProperties props; + us::ServiceProperties props; std::string yes = "true"; std::string no = "false"; if(this->GetIsActive()) props[mitk::USDevice::US_PROPKEY_ISACTIVE] = yes; else props[mitk::USDevice::US_PROPKEY_ISACTIVE] = no; std::string isActive; if (GetIsActive()) isActive = " (Active)"; else isActive = " (Inactive)"; // e.g.: Zonare MyLab5 (Active) props[ mitk::USDevice::US_PROPKEY_LABEL] = m_Metadata->GetDeviceManufacturer() + " " + m_Metadata->GetDeviceModel() + isActive; if( m_Calibration.IsNotNull() ) props[ mitk::USImageMetadata::PROP_DEV_ISCALIBRATED ] = yes; else props[ mitk::USImageMetadata::PROP_DEV_ISCALIBRATED ] = no; props[ mitk::USDevice::US_PROPKEY_CLASS ] = GetDeviceClass(); props[ mitk::USImageMetadata::PROP_DEV_MANUFACTURER ] = m_Metadata->GetDeviceManufacturer(); props[ mitk::USImageMetadata::PROP_DEV_MODEL ] = m_Metadata->GetDeviceModel(); props[ mitk::USImageMetadata::PROP_DEV_COMMENT ] = m_Metadata->GetDeviceComment(); props[ mitk::USImageMetadata::PROP_PROBE_NAME ] = m_Metadata->GetProbeName(); props[ mitk::USImageMetadata::PROP_PROBE_FREQUENCY ] = m_Metadata->GetProbeFrequency(); props[ mitk::USImageMetadata::PROP_ZOOM ] = m_Metadata->GetZoom(); return props; } bool mitk::USDevice::Connect() { if (GetIsConnected()) { MITK_WARN << "Tried to connect an ultrasound device that was already connected. Ignoring call..."; return false; } // Prepare connection, fail if this fails. if (! this->OnConnection()) return false; // Update state m_IsConnected = true; // Get Context and Module - mitk::ModuleContext* context = GetModuleContext(); - ServiceProperties props = ConstructServiceProperties(); + us::ModuleContext* context = us::GetModuleContext(); + us::ServiceProperties props = ConstructServiceProperties(); - m_ServiceRegistration = context->RegisterService(this, props); + m_ServiceRegistration = context->RegisterService(this, props); // This makes sure that the SmartPointer to this device does not invalidate while the device is connected this->Register(); return true; } bool mitk::USDevice::Disconnect() { if ( ! GetIsConnected()) { MITK_WARN << "Tried to disconnect an ultrasound device that was not connected. Ignoring call..."; return false; } // Prepare connection, fail if this fails. if (! this->OnDisconnection()) return false; // Update state m_IsConnected = false; // Unregister m_ServiceRegistration.Unregister(); m_ServiceRegistration = 0; // Undo the manual registration done in Connect(). Pointer will invalidte, if no one holds a reference to this object anymore. this->UnRegister(); return true; } bool mitk::USDevice::Activate() { if (! this->GetIsConnected()) return false; m_IsActive = true; // <- Necessary to safely allow Subclasses to start threading based on activity state m_IsActive = OnActivation(); - ServiceProperties props = ConstructServiceProperties(); + us::ServiceProperties props = ConstructServiceProperties(); this->m_ServiceRegistration.SetProperties(props); return m_IsActive; } void mitk::USDevice::Deactivate() { m_IsActive= false; - ServiceProperties props = ConstructServiceProperties(); + us::ServiceProperties props = ConstructServiceProperties(); this->m_ServiceRegistration.SetProperties(props); OnDeactivation(); } void mitk::USDevice::AddProbe(mitk::USProbe::Pointer probe) { for(int i = 0; i < m_ConnectedProbes.size(); i++) { if (m_ConnectedProbes[i]->IsEqualToProbe(probe)) return; } this->m_ConnectedProbes.push_back(probe); } void mitk::USDevice::ActivateProbe(mitk::USProbe::Pointer probe){ // currently, we may just add the probe. This behaviour should be changed, should more complicated SDK applications emerge AddProbe(probe); int index = -1; for(int i = 0; i < m_ConnectedProbes.size(); i++) { if (m_ConnectedProbes[i]->IsEqualToProbe(probe)) index = i; } // index now contains the position of the original instance of this probe m_ActiveProbe = m_ConnectedProbes[index]; } void mitk::USDevice::DeactivateProbe(){ m_ActiveProbe = 0; } mitk::USImage* mitk::USDevice::GetOutput() { if (this->GetNumberOfOutputs() < 1) return NULL; return static_cast(this->ProcessObject::GetPrimaryOutput()); } mitk::USImage* mitk::USDevice::GetOutput(unsigned int idx) { if (this->GetNumberOfOutputs() < 1) return NULL; return static_cast(this->ProcessObject::GetOutput(idx)); } void mitk::USDevice::GraftOutput(itk::DataObject *graft) { this->GraftNthOutput(0, graft); } void mitk::USDevice::GraftNthOutput(unsigned int idx, itk::DataObject *graft) { if ( idx >= this->GetNumberOfOutputs() ) { itkExceptionMacro(<<"Requested to graft output " << idx << " but this filter only has " << this->GetNumberOfOutputs() << " Outputs."); } if ( !graft ) { itkExceptionMacro(<<"Requested to graft output with a NULL pointer object" ); } itk::DataObject* output = this->GetOutput(idx); if ( !output ) { itkExceptionMacro(<<"Requested to graft output that is a NULL pointer" ); } // Call Graft on USImage to copy member data output->Graft( graft ); } bool mitk::USDevice::ApplyCalibration(mitk::USImage::Pointer image){ if ( m_Calibration.IsNull() ) return false; image->GetGeometry()->SetIndexToWorldTransform(m_Calibration); return true; } //########### GETTER & SETTER ##################// void mitk::USDevice::setCalibration (mitk::AffineTransform3D::Pointer calibration){ if (calibration.IsNull()) { MITK_ERROR << "Null pointer passed to SetCalibration of mitk::USDevice. Ignoring call."; return; } m_Calibration = calibration; m_Metadata->SetDeviceIsCalibrated(true); if (m_ServiceRegistration != 0) { - ServiceProperties props = ConstructServiceProperties(); + us::ServiceProperties props = ConstructServiceProperties(); this->m_ServiceRegistration.SetProperties(props); } } bool mitk::USDevice::GetIsActive() { return m_IsActive; } bool mitk::USDevice::GetIsConnected() { // a device is connected if it is registered with the Microservice Registry return (m_ServiceRegistration != 0); } std::string mitk::USDevice::GetDeviceManufacturer(){ return this->m_Metadata->GetDeviceManufacturer(); } std::string mitk::USDevice::GetDeviceModel(){ return this->m_Metadata->GetDeviceModel(); } std::string mitk::USDevice::GetDeviceComment(){ return this->m_Metadata->GetDeviceComment(); } std::vector mitk::USDevice::GetConnectedProbes() { return m_ConnectedProbes; } diff --git a/Modules/US/USModel/mitkUSDevice.h b/Modules/US/USModel/mitkUSDevice.h index e6c8ae5465..7b5c522c81 100644 --- a/Modules/US/USModel/mitkUSDevice.h +++ b/Modules/US/USModel/mitkUSDevice.h @@ -1,313 +1,313 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKUSDevice_H_HEADER_INCLUDED_ #define MITKUSDevice_H_HEADER_INCLUDED_ // STL #include // MitkUS #include "mitkUSProbe.h" #include "mitkUSImageMetadata.h" #include "mitkUSImage.h" #include // MITK #include #include // ITK #include // Microservices #include #include #include namespace mitk { /**Documentation * \brief A device holds information about it's model, make and the connected probes. It is the * common super class for all devices and acts as an image source for mitkUSImages. It is the base class * for all US Devices, and every new device should extend it. * * US Devices support output of calibrated images, i.e. images that include a specific geometry. * To achieve this, call SetCalibration, and make sure that the subclass also calls apply * transformation at some point (The USDevice does not automatically apply the transformation to the image) * * Note that SmartPointers to USDevices will not invalidate while the device is still connected. * \ingroup US */ class MitkUS_EXPORT USDevice : public mitk::ImageSource { public: mitkClassMacro(USDevice, mitk::ImageSource); struct USImageCropArea { int cropLeft; int cropRight; int cropBottom; int cropTop; }; /** *\brief These constants are used in conjunction with Microservices */ static const std::string US_INTERFACE_NAME; // Common Interface name of all US Devices. Used to refer to this device via Microservices static const std::string US_PROPKEY_LABEL; // Human readable text represntation of this device static const std::string US_PROPKEY_ISACTIVE; // Whether this Device is active or not. static const std::string US_PROPKEY_CLASS; // Class Name of this Object /** * \brief Connects this device. A connected device is ready to deliver images (i.e. be Activated). A Connected Device can be active. A disconnected Device cannot be active. * Internally calls onConnect and then registers the device with the service. A device usually should * override the OnConnection() method, but never the Connect() method, since this will possibly exclude the device * from normal service management. The exact flow of events is: * 0. Check if the device is already connected. If yes, return true anyway, but don't do anything. * 1. Call OnConnection() Here, a device should establish it's connection with the hardware Afterwards, it should be ready to start transmitting images at any time. * 2. If OnConnection() returns true ("successful"), then the device is registered with the service. * 3. if not, it the method itself returns false or may throw an expection, depeneding on the device implementation. * */ bool Connect(); /** * \brief Works analogously to mitk::USDevice::Connect(). Don't override this Method, but onDisconnection instead. */ bool Disconnect(); /** * \brief Activates this device. After the activation process, the device will start to produce images. This Method will fail, if the device is not connected. */ bool Activate(); /** * \brief Deactivates this device. After the deactivation process, the device will no longer produce images, but still be connected. */ void Deactivate(); /** * \brief Add a probe to the device without connecting to it. * This should usually be done before connecting to the probe. */ virtual void AddProbe(mitk::USProbe::Pointer probe); /** * \brief Connect to a probe and activate it. The probe should be added first. * Usually, a VideoDevice will simply add a probe it wants to connect to, * but an SDK Device might require adding a probe first. */ virtual void ActivateProbe(mitk::USProbe::Pointer probe); /** * \brief Deactivates the currently active probe. */ virtual void DeactivateProbe(); /** * \brief Removes a probe from the ist of currently added probes. */ //virtual void removeProbe(mitk::USProbe::Pointer probe); /** * \brief Returns a vector containing all connected probes. */ std::vector GetConnectedProbes(); /** *\brief return the output (output with id 0) of the filter */ USImage* GetOutput(void); /** *\brief return the output with id idx of the filter */ USImage* GetOutput(unsigned int idx); /** *\brief Graft the specified DataObject onto this ProcessObject's output. * * See itk::ImageSource::GraftNthOutput for details */ virtual void GraftNthOutput(unsigned int idx, itk::DataObject *graft); /** * \brief Graft the specified DataObject onto this ProcessObject's output. * * See itk::ImageSource::Graft Output for details */ virtual void GraftOutput(itk::DataObject *graft); // /** // * \brief Make a DataObject of the correct type to used as the specified output. // * // * This method is automatically called when DataObject::DisconnectPipeline() // * is called. DataObject::DisconnectPipeline, disconnects a data object // * from being an output of its current source. When the data object // * is disconnected, the ProcessObject needs to construct a replacement // * output data object so that the ProcessObject is in a valid state. // * Subclasses of USImageVideoSource that have outputs of different // * data types must overwrite this method so that proper output objects // * are created. // */ // virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); //########### GETTER & SETTER ##################// /** * \brief Returns the Class of the Device. This Method must be reimplemented by every Inheriting Class. */ virtual std::string GetDeviceClass() = 0; /** * \brief True, if the device is currently generating image data, false otherwise. */ bool GetIsActive(); /** * \brief True, if the device is currently ready to start transmitting image data or is already * transmitting image data. A disconnected device cannot be activated. */ bool GetIsConnected(); /** * \brief Sets a transformation as Calibration data. It also marks the device as Calibrated. This data is not automatically applied to the image. Subclasses must call ApplyTransformation * to achieve this. */ void setCalibration (mitk::AffineTransform3D::Pointer calibration); /** * \brief Returns the current Calibration */ itkGetMacro(Calibration, mitk::AffineTransform3D::Pointer); /** * \brief Returns the currently active probe or null, if none is active */ itkGetMacro(ActiveProbe, mitk::USProbe::Pointer); /* @return Returns the area that will be cropped from the US image. Is disabled / [0,0,0,0] by default. */ mitk::USDevice::USImageCropArea GetCropArea(); std::string GetDeviceManufacturer(); std::string GetDeviceModel(); std::string GetDeviceComment(); protected: mitk::USProbe::Pointer m_ActiveProbe; std::vector m_ConnectedProbes; bool m_IsActive; bool m_IsConnected; /* @brief defines the area that should be cropped from the US image */ USImageCropArea m_CropArea; /* * \brief This Method constructs the service properties which can later be used to * register the object with the Microservices * Return service properties */ - mitk::ServiceProperties ConstructServiceProperties(); + us::ServiceProperties ConstructServiceProperties(); /** * \brief Is called during the connection process. Override this method in your subclass to handle the actual connection. * Return true if successful and false if unsuccessful. Additionally, you may throw an exception to clarify what went wrong. */ virtual bool OnConnection() = 0; /** * \brief Is called during the disconnection process. Override this method in your subclass to handle the actual disconnection. * Return true if successful and false if unsuccessful. Additionally, you may throw an exception to clarify what went wrong. */ virtual bool OnDisconnection() = 0; /** * \brief Is called during the activation process. After this method is finished, the device should be generating images */ virtual bool OnActivation() = 0; /** * \brief Is called during the deactivation process. After a call to this method the device should still be connected, but not producing images anymore. */ virtual void OnDeactivation() = 0; /** * \brief This metadata set is privately used to imprint USImages with Metadata later. * At instantiation time, it only contains Information about the Device, * At scan time, it integrates this data with the probe information and imprints it on * the produced images. This field is intentionally hidden from outside interference. */ mitk::USImageMetadata::Pointer m_Metadata; /** * \brief Enforces minimal Metadata to be set. */ USDevice(std::string manufacturer, std::string model); /** * \brief Constructs a device with the given Metadata. Make sure the Metadata contains meaningful content! */ USDevice(mitk::USImageMetadata::Pointer metadata); virtual ~USDevice(); /** * \brief Grabs the next frame from the Video input. This method is called internally, whenever Update() is invoked by an Output. */ void GenerateData() = 0; /** * \brief The Calibration Transformation of this US-Device. This will automatically be written into the image once */ mitk::AffineTransform3D::Pointer m_Calibration; /** * \brief Convenience method that can be used by subclasses to apply the Calibration Data to the image. A subclass has to call * this method or set the transformation itself for the output to be calibrated! Returns true if a Calibration was set and false otherwise * (Usually happens when no transformation was set yet). */ bool ApplyCalibration(mitk::USImage::Pointer image); private: /** * \brief The device's ServiceRegistration object that allows to modify it's Microservice registraton details. */ - mitk::ServiceRegistration m_ServiceRegistration; + us::ServiceRegistration m_ServiceRegistration; }; } // namespace mitk // This is the microservice declaration. Do not meddle! US_DECLARE_SERVICE_INTERFACE(mitk::USDevice, "org.mitk.services.UltrasoundDevice") #endif diff --git a/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.cpp b/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.cpp index a2bf5076ee..8dcdf5e677 100644 --- a/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.cpp +++ b/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.cpp @@ -1,131 +1,131 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //#define _USE_MATH_DEFINES #include -#include +#include #include #include const std::string QmitkUSDeviceManagerWidget::VIEW_ID = "org.mitk.views.QmitkUSDeviceManagerWidget"; QmitkUSDeviceManagerWidget::QmitkUSDeviceManagerWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f) { m_Controls = NULL; CreateQtPartControl(this); } QmitkUSDeviceManagerWidget::~QmitkUSDeviceManagerWidget() { } //////////////////// INITIALIZATION ///////////////////// void QmitkUSDeviceManagerWidget::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkUSDeviceManagerWidgetControls; m_Controls->setupUi(parent); this->CreateConnections(); } // Initializations std::string empty = ""; m_Controls->m_ConnectedDevices->Initialize(mitk::USDevice::US_PROPKEY_LABEL, empty); } void QmitkUSDeviceManagerWidget::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_BtnActivate, SIGNAL( clicked() ), this, SLOT(OnClickedActivateDevice()) ); connect( m_Controls->m_BtnDisconnect, SIGNAL( clicked() ), this, SLOT(OnClickedDisconnectDevice()) ); - connect( m_Controls->m_ConnectedDevices, SIGNAL( ServiceSelectionChanged(mitk::ServiceReference) ), this, SLOT(OnDeviceSelectionChanged(mitk::ServiceReference)) ); + connect( m_Controls->m_ConnectedDevices, SIGNAL( ServiceSelectionChanged(mitk::ServiceReference) ), this, SLOT(OnDeviceSelectionChanged(us::ServiceReferenceU)) ); } } ///////////// Methods & Slots Handling Direct Interaction ///////////////// void QmitkUSDeviceManagerWidget::OnClickedActivateDevice() { mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedService(); if (device.IsNull()) { return; } if (device->GetIsActive()) { device->Deactivate(); } else { device->Activate(); if ( ! device->GetIsActive() ) { QMessageBox::warning(this, "Activation failed", "Could not activate device. Check logging for details."); } } // Manually reevaluate Button logic OnDeviceSelectionChanged(m_Controls->m_ConnectedDevices->GetSelectedServiceReference()); } void QmitkUSDeviceManagerWidget::OnClickedDisconnectDevice(){ mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedService(); if (device.IsNull()) { return; } device->Disconnect(); } -void QmitkUSDeviceManagerWidget::OnDeviceSelectionChanged(mitk::ServiceReference reference){ +void QmitkUSDeviceManagerWidget::OnDeviceSelectionChanged(us::ServiceReferenceU reference){ if (! reference) { m_Controls->m_BtnActivate->setEnabled(false); m_Controls->m_BtnDisconnect->setEnabled(false); return; } std::string isActive = reference.GetProperty( mitk::USDevice::US_PROPKEY_ISACTIVE ).ToString(); if (isActive.compare("true") == 0) { m_Controls->m_BtnActivate->setEnabled(true); m_Controls->m_BtnDisconnect->setEnabled(false); m_Controls->m_BtnActivate->setText("Deactivate"); } else { m_Controls->m_BtnActivate->setEnabled(true); m_Controls->m_BtnDisconnect->setEnabled(true); m_Controls->m_BtnActivate->setText("Activate"); } } void QmitkUSDeviceManagerWidget::DisconnectAllDevices() { -//at the moment disconnects ALL devices. Maybe we only want to disconnect the devices handled by this widget? -mitk::ModuleContext* thisContext = mitk::GetModuleContext(); -std::list services = thisContext->GetServiceReferences(); -for(std::list::iterator it = services.begin(); it != services.end(); ++it) - { - mitk::USDevice::Pointer currentDevice = thisContext->GetService(*it); + //at the moment disconnects ALL devices. Maybe we only want to disconnect the devices handled by this widget? + us::ModuleContext* thisContext = us::GetModuleContext(); + std::vector > services = thisContext->GetServiceReferences(); + for(std::vector >::iterator it = services.begin(); it != services.end(); ++it) + { + mitk::USDevice* currentDevice = thisContext->GetService(*it); currentDevice->Disconnect(); - } -MITK_INFO << "Disconnected ALL US devises!"; + } + MITK_INFO << "Disconnected ALL US devises!"; } diff --git a/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.h b/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.h index 90f6ab757f..177647a928 100644 --- a/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.h +++ b/Modules/USUI/Qmitk/QmitkUSDeviceManagerWidget.h @@ -1,87 +1,87 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QmitkUSDeviceManagerWidget_H_INCLUDED #define _QmitkUSDeviceManagerWidget_H_INCLUDED #include "MitkUSUIExports.h" #include "ui_QmitkUSDeviceManagerWidgetControls.h" #include "mitkUSDevice.h" #include //QT headers #include #include /** * @brief This Widget is used to manage available Ultrasound Devices. * * It allows activation, deactivation and disconnection of connected devices. * * @ingroup USUI */ class MitkUSUI_EXPORT QmitkUSDeviceManagerWidget :public QWidget { //this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkUSDeviceManagerWidget(QWidget* p = 0, Qt::WindowFlags f1 = 0); virtual ~QmitkUSDeviceManagerWidget(); /* @brief This method is part of the widget an needs not to be called seperately. */ virtual void CreateQtPartControl(QWidget *parent); /* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/ virtual void CreateConnections(); /* @brief Disconnects all devices immediately. */ virtual void DisconnectAllDevices(); public slots: protected slots: /* \brief Called, when the button "Activate Device" was clicked. */ void OnClickedActivateDevice(); /* \brief Called, when the button "Disconnect Device" was clicked. */ void OnClickedDisconnectDevice(); /* \brief Called, when the selection in the devicelist changes. */ - void OnDeviceSelectionChanged(mitk::ServiceReference reference); + void OnDeviceSelectionChanged(us::ServiceReferenceU reference); protected: Ui::QmitkUSDeviceManagerWidgetControls* m_Controls; ///< member holding the UI elements of this widget private: }; #endif // _QmitkUSDeviceManagerWidget_H_INCLUDED diff --git a/Modules/USUI/Qmitk/mitkUSDevicePersistence.cpp b/Modules/USUI/Qmitk/mitkUSDevicePersistence.cpp index b038c4e2c9..395380ffcb 100644 --- a/Modules/USUI/Qmitk/mitkUSDevicePersistence.cpp +++ b/Modules/USUI/Qmitk/mitkUSDevicePersistence.cpp @@ -1,198 +1,198 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkUSDevicePersistence.h" //Microservices #include #include #include -#include +#include //QT #include mitk::USDevicePersistence::USDevicePersistence() : m_devices("MITK US","Device Settings") { } void mitk::USDevicePersistence::StoreCurrentDevices() { - mitk::ModuleContext* thisContext = mitk::GetModuleContext(); + us::ModuleContext* thisContext = us::GetModuleContext(); - std::list services = thisContext->GetServiceReferences(); + std::vector > services = thisContext->GetServiceReferences(); MITK_INFO << "Trying to save " << services.size() << " US devices."; int numberOfSavedDevices = 0; - for(std::list::iterator it = services.begin(); it != services.end(); ++it) + for(std::vector >::iterator it = services.begin(); it != services.end(); ++it) { - mitk::USDevice::Pointer currentDevice = thisContext->GetService(*it); + mitk::USDevice::Pointer currentDevice = thisContext->GetService(*it); //check if it is a USVideoDevice if (currentDevice->GetDeviceClass() == "org.mitk.modules.us.USVideoDevice") { mitk::USVideoDevice::Pointer currentVideoDevice = dynamic_cast(currentDevice.GetPointer()); QString identifier = "device" + QString::number(numberOfSavedDevices); m_devices.setValue(identifier,USVideoDeviceToString(currentVideoDevice)); numberOfSavedDevices++; } else { MITK_WARN << "Saving of US devices of the type " << currentDevice->GetDeviceClass() << " is not supported at the moment. Skipping device."; } } m_devices.setValue("numberOfSavedDevices",numberOfSavedDevices); MITK_INFO << "Successfully saved " << numberOfSavedDevices << " US devices."; } void mitk::USDevicePersistence::RestoreLastDevices() { int numberOfSavedDevices = m_devices.value("numberOfSavedDevices").toInt(); for(int i=0; iConnect(); } catch (...) { MITK_ERROR << "Error occured while loading a USVideoDevice from persistence. Device assumed corrupt, will be deleted."; QMessageBox::warning(NULL, "Could not load device" ,"A stored ultrasound device is corrupted and could not be loaded. The device will be deleted."); } } MITK_INFO << "Restoring " << numberOfSavedDevices << " US devices."; } QString mitk::USDevicePersistence::USVideoDeviceToString(mitk::USVideoDevice::Pointer d) { QString manufacturer = d->GetDeviceManufacturer().c_str(); QString model = d->GetDeviceModel().c_str(); QString comment = d->GetDeviceComment().c_str(); int source = d->GetDeviceID(); std::string file = d->GetFilePath(); if (file == "") file = "none"; int greyscale = d->GetSource()->GetIsGreyscale(); int resOverride = d->GetSource()->GetResolutionOverride(); int resWidth = d->GetSource()->GetResolutionOverrideWidth(); int resHight = d->GetSource()->GetResolutionOverrideHeight(); int cropRight = d->GetCropArea().cropRight; int cropLeft = d->GetCropArea().cropLeft; int cropBottom = d->GetCropArea().cropBottom; int cropTop = d->GetCropArea().cropTop; char seperator = '|'; QString returnValue = manufacturer + seperator + model + seperator + comment + seperator + QString::number(source) + seperator + file.c_str() + seperator + QString::number(greyscale) + seperator + QString::number(resOverride) + seperator + QString::number(resWidth) + seperator + QString::number(resHight) + seperator + QString::number(cropRight) + seperator + QString::number(cropLeft) + seperator + QString::number(cropBottom) + seperator + QString::number(cropTop) ; MITK_INFO << "Output String: " << returnValue.toStdString(); return returnValue; } mitk::USVideoDevice::Pointer mitk::USDevicePersistence::StringToUSVideoDevice(QString s) { MITK_INFO << "Input String: " << s.toStdString(); std::vector data; std::string seperators = "|"; std::string text = s.toStdString(); split(text,seperators,data); if(data.size() != 13) { MITK_ERROR << "Cannot parse US device! (Size: " << data.size() << ")"; return mitk::USVideoDevice::New("INVALID","INVALID","INVALID"); } std::string manufacturer = data.at(0); std::string model = data.at(1); std::string comment = data.at(2); int source = (QString(data.at(3).c_str())).toInt(); std::string file = data.at(4); bool greyscale = (QString(data.at(5).c_str())).toInt(); bool resOverride = (QString(data.at(6).c_str())).toInt(); int resWidth = (QString(data.at(7).c_str())).toInt(); int resHight = (QString(data.at(8).c_str())).toInt(); mitk::USDevice::USImageCropArea cropArea; cropArea.cropRight = (QString(data.at(9).c_str())).toInt(); cropArea.cropLeft = (QString(data.at(10).c_str())).toInt(); cropArea.cropBottom = (QString(data.at(11).c_str())).toInt(); cropArea.cropTop = (QString(data.at(12).c_str())).toInt(); // Assemble Metadata mitk::USImageMetadata::Pointer metadata = mitk::USImageMetadata::New(); metadata->SetDeviceManufacturer(manufacturer); metadata->SetDeviceComment(comment); metadata->SetDeviceModel(model); metadata->SetProbeName(""); metadata->SetZoom(""); // Create Device mitk::USVideoDevice::Pointer returnValue; if (file == "none") { returnValue = mitk::USVideoDevice::New(source, metadata); } else { returnValue = mitk::USVideoDevice::New(file, metadata); } // Set Video Options returnValue->GetSource()->SetColorOutput(!greyscale); // If Resolution override is activated, apply it if (resOverride) { returnValue->GetSource()->OverrideResolution(resWidth, resHight); returnValue->GetSource()->SetResolutionOverride(true); } // Set Crop Area returnValue->SetCropArea(cropArea); return returnValue; } void mitk::USDevicePersistence::split(std::string& text, std::string& separators, std::vector& words) { int n = text.length(); int start, stop; start = text.find_first_not_of(separators); while ((start >= 0) && (start < n)) { stop = text.find_first_of(separators, start); if ((stop < 0) || (stop > n)) stop = n; words.push_back(text.substr(start, stop - start)); start = text.find_first_not_of(separators, stop + 1); } } diff --git a/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.cpp index d57dcddf39..accaade9a7 100644 --- a/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.cpp @@ -1,277 +1,277 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPluginActivator.h" #include "mitkLog.h" #include #include #include "internal/mitkDataStorageService.h" -#include -#include -#include +#include +#include +#include + #include #include namespace mitk { -class ITKLightObjectToQObjectAdapter : public QObject +class InterfaceMapToQObjectAdapter : public QObject { public: - ITKLightObjectToQObjectAdapter(const QStringList& clazzes, itk::LightObject* service) - : interfaceNames(clazzes), mitkService(service) + InterfaceMapToQObjectAdapter(const us::InterfaceMap& im) + : interfaceMap(im) {} // This method is called by the Qt meta object system. It is usually // generated by the moc, but we create it manually to be able to return // a MITK micro service object (derived from itk::LightObject). It basically // works as if the micro service class had used the Q_INTERFACES macro in // its declaration. Now we can successfully do a // qobject_cast(lightObjectToQObjectAdapter) void* qt_metacast(const char *_clname) { if (!_clname) return 0; - if (!strcmp(_clname, "ITKLightObjectToQObjectAdapter")) - return static_cast(const_cast(this)); - if (interfaceNames.contains(QString(_clname))) - return static_cast(mitkService); + if (!strcmp(_clname, "InterfaceMapToQObjectAdapter")) + return static_cast(const_cast(this)); + + us::InterfaceMap::const_iterator iter = interfaceMap.find(_clname); + if (iter != interfaceMap.end()) + return iter->second; + return QObject::qt_metacast(_clname); } private: - QStringList interfaceNames; - itk::LightObject* mitkService; + us::InterfaceMap interfaceMap; }; const std::string org_mitk_core_services_Activator::PLUGIN_ID = "org.mitk.core.services"; void org_mitk_core_services_Activator::start(ctkPluginContext* context) { pluginContext = context; //initialize logging mitk::LoggingBackend::Register(); QString filename = "mitk.log"; QFileInfo path = context->getDataFile(filename); mitk::LoggingBackend::SetLogFile(path.absoluteFilePath().toStdString().c_str()); mitk::VtkLoggingAdapter::Initialize(); mitk::ItkLoggingAdapter::Initialize(); //initialize data storage service DataStorageService* service = new DataStorageService(); dataStorageService = IDataStorageService::Pointer(service); context->registerService(service); // Get the MitkCore Module Context - mitkContext = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); + mitkContext = us::ModuleRegistry::GetModule(1)->GetModuleContext(); // Process all already registered services - std::list refs = mitkContext->GetServiceReferences(""); - for (std::list::const_iterator i = refs.begin(); + std::vector refs = mitkContext->GetServiceReferences(""); + for (std::vector::const_iterator i = refs.begin(); i != refs.end(); ++i) { this->AddMitkService(*i); } mitkContext->AddServiceListener(this, &org_mitk_core_services_Activator::MitkServiceChanged); } void org_mitk_core_services_Activator::stop(ctkPluginContext* /*context*/) { mitkContext->RemoveServiceListener(this, &org_mitk_core_services_Activator::MitkServiceChanged); foreach(ctkServiceRegistration reg, mapMitkIdToRegistration.values()) { reg.unregister(); } mapMitkIdToRegistration.clear(); qDeleteAll(mapMitkIdToAdapter); mapMitkIdToAdapter.clear(); //clean up logging mitk::LoggingBackend::Unregister(); dataStorageService = 0; mitkContext = 0; pluginContext = 0; } -void org_mitk_core_services_Activator::MitkServiceChanged(const mitk::ServiceEvent event) +void org_mitk_core_services_Activator::MitkServiceChanged(const us::ServiceEvent event) { switch (event.GetType()) { - case mitk::ServiceEvent::REGISTERED: + case us::ServiceEvent::REGISTERED: { this->AddMitkService(event.GetServiceReference()); break; } - case mitk::ServiceEvent::UNREGISTERING: + case us::ServiceEvent::UNREGISTERING: { - long mitkServiceId = mitk::any_cast(event.GetServiceReference().GetProperty(mitk::ServiceConstants::SERVICE_ID())); + long mitkServiceId = us::any_cast(event.GetServiceReference().GetProperty(us::ServiceConstants::SERVICE_ID())); ctkServiceRegistration reg = mapMitkIdToRegistration.take(mitkServiceId); if (reg) { reg.unregister(); } delete mapMitkIdToAdapter.take(mitkServiceId); break; } - case mitk::ServiceEvent::MODIFIED: + case us::ServiceEvent::MODIFIED: { - long mitkServiceId = mitk::any_cast(event.GetServiceReference().GetProperty(mitk::ServiceConstants::SERVICE_ID())); + long mitkServiceId = us::any_cast(event.GetServiceReference().GetProperty(us::ServiceConstants::SERVICE_ID())); ctkDictionary newProps = CreateServiceProperties(event.GetServiceReference()); mapMitkIdToRegistration[mitkServiceId].setProperties(newProps); break; } default: break; // do nothing } } -void org_mitk_core_services_Activator::AddMitkService(const mitk::ServiceReference& ref) +void org_mitk_core_services_Activator::AddMitkService(const us::ServiceReferenceU& ref) { // Get the MITK micro service object - itk::LightObject* mitkService = mitkContext->GetService(ref); - if (mitkService == 0) return; + us::InterfaceMap mitkService = mitkContext->GetService(ref); + if (mitkService.empty()) return; // Get the interface names against which the service was registered - std::list clazzes = - mitk::any_cast >(ref.GetProperty(mitk::ServiceConstants::OBJECTCLASS())); - QStringList qclazzes; - for(std::list::const_iterator clazz = clazzes.begin(); - clazz != clazzes.end(); ++clazz) + for(us::InterfaceMap::const_iterator clazz = mitkService.begin(); + clazz != mitkService.end(); ++clazz) { - qclazzes << QString::fromStdString(*clazz); + qclazzes << QString::fromStdString(clazz->first); } - long mitkServiceId = mitk::any_cast(ref.GetProperty(mitk::ServiceConstants::SERVICE_ID())); + long mitkServiceId = us::any_cast(ref.GetProperty(us::ServiceConstants::SERVICE_ID())); - QObject* adapter = new ITKLightObjectToQObjectAdapter(qclazzes, mitkService); + QObject* adapter = new InterfaceMapToQObjectAdapter(mitkService); mapMitkIdToAdapter[mitkServiceId] = adapter; ctkDictionary props = CreateServiceProperties(ref); mapMitkIdToRegistration[mitkServiceId] = pluginContext->registerService(qclazzes, adapter, props); } -ctkDictionary org_mitk_core_services_Activator::CreateServiceProperties(const ServiceReference &ref) +ctkDictionary org_mitk_core_services_Activator::CreateServiceProperties(const us::ServiceReferenceU& ref) { ctkDictionary props; - long mitkServiceId = mitk::any_cast(ref.GetProperty(mitk::ServiceConstants::SERVICE_ID())); + long mitkServiceId = us::any_cast(ref.GetProperty(us::ServiceConstants::SERVICE_ID())); props.insert("mitk.serviceid", QVariant::fromValue(mitkServiceId)); // Add all other properties from the MITK micro service std::vector keys; ref.GetPropertyKeys(keys); for (std::vector::const_iterator it = keys.begin(); it != keys.end(); ++it) { QString key = QString::fromStdString(*it); - mitk::Any value = ref.GetProperty(*it); + us::Any value = ref.GetProperty(*it); // We cannot add any mitk::Any object, we need to query the type const std::type_info& objType = value.Type(); if (objType == typeid(std::string)) { - props.insert(key, QString::fromStdString(ref_any_cast(value))); + props.insert(key, QString::fromStdString(us::ref_any_cast(value))); } else if (objType == typeid(std::vector)) { - const std::vector& list = ref_any_cast >(value); + const std::vector& list = us::ref_any_cast >(value); QStringList qlist; for (std::vector::const_iterator str = list.begin(); str != list.end(); ++str) { qlist << QString::fromStdString(*str); } props.insert(key, qlist); } else if (objType == typeid(std::list)) { - const std::list& list = ref_any_cast >(value); + const std::list& list = us::ref_any_cast >(value); QStringList qlist; for (std::list::const_iterator str = list.begin(); str != list.end(); ++str) { qlist << QString::fromStdString(*str); } props.insert(key, qlist); } else if (objType == typeid(char)) { - props.insert(key, QChar(ref_any_cast(value))); + props.insert(key, QChar(us::ref_any_cast(value))); } else if (objType == typeid(unsigned char)) { - props.insert(key, QChar(ref_any_cast(value))); + props.insert(key, QChar(us::ref_any_cast(value))); } else if (objType == typeid(bool)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } else if (objType == typeid(short)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } else if (objType == typeid(unsigned short)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } else if (objType == typeid(int)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } else if (objType == typeid(unsigned int)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } else if (objType == typeid(float)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } else if (objType == typeid(double)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } else if (objType == typeid(long long int)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } else if (objType == typeid(unsigned long long int)) { - props.insert(key, any_cast(value)); + props.insert(key, us::any_cast(value)); } } return props; } org_mitk_core_services_Activator::org_mitk_core_services_Activator() : mitkContext(0), pluginContext(0) { } } Q_EXPORT_PLUGIN2(org_mitk_core_services, mitk::org_mitk_core_services_Activator) diff --git a/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.h index 66c207bcc9..770cd816f7 100644 --- a/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.core.services/src/internal/mitkPluginActivator.h @@ -1,65 +1,67 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKCORESERVICESPLUGIN_H_ #define MITKCORESERVICESPLUGIN_H_ #include #include #include "mitkIDataStorageService.h" -#include +#include + +namespace us { +class ModuleContext; +} namespace mitk { -class ModuleContext; - class org_mitk_core_services_Activator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: static const std::string PLUGIN_ID; org_mitk_core_services_Activator(); void start(ctkPluginContext* context); void stop(ctkPluginContext* context); - void MitkServiceChanged(const mitk::ServiceEvent event); + void MitkServiceChanged(const us::ServiceEvent event); private: mitk::IDataStorageService::Pointer dataStorageService; QMap mapMitkIdToAdapter; QMap mapMitkIdToRegistration; - mitk::ModuleContext* mitkContext; + us::ModuleContext* mitkContext; ctkPluginContext* pluginContext; - void AddMitkService(const mitk::ServiceReference &ref); + void AddMitkService(const us::ServiceReferenceU& ref); - ctkDictionary CreateServiceProperties(const mitk::ServiceReference& ref); + ctkDictionary CreateServiceProperties(const us::ServiceReferenceU& ref); }; typedef org_mitk_core_services_Activator PluginActivator; } #endif /*MITKCORESERVICESPLUGIN_H_*/ diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp index 0f7441b15a..690ca3d273 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp @@ -1,62 +1,56 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "org_mitk_gui_qt_application_Activator.h" #include "QmitkGeneralPreferencePage.h" #include "QmitkEditorsPreferencePage.h" #include #include -// us -#include "mitkModule.h" -#include "mitkModuleResource.h" -#include "mitkModuleResourceStream.h" -#include "mitkModuleRegistry.h" - namespace mitk { ctkPluginContext* org_mitk_gui_qt_application_Activator::m_Context = 0; void org_mitk_gui_qt_application_Activator::start(ctkPluginContext* context) { this->m_Context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkGeneralPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkEditorsPreferencePage, context) QmitkRegisterClasses(); } void org_mitk_gui_qt_application_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) this->m_Context = 0; } ctkPluginContext* org_mitk_gui_qt_application_Activator::GetContext() { return m_Context; } } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_application, mitk::org_mitk_gui_qt_application_Activator) diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp index 34b504c2a6..91d99d9795 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp @@ -1,1844 +1,1844 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkControlVisualizationPropertiesView.h" #include "mitkNodePredicateDataType.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkResliceMethodProperty.h" #include "mitkRenderingManager.h" -#include "mitkModuleRegistry.h" #include "mitkTbssImage.h" #include "mitkPlanarFigure.h" #include "mitkFiberBundleX.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkFiberBundleInteractor.h" #include "mitkPlanarFigureInteractor.h" #include #include #include #include #include "mitkGlobalInteraction.h" +#include "usModuleRegistry.h" #include "mitkGeometry2D.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryISelectionService.h" #include "berryConstants.h" #include "berryPlatformUI.h" #include "itkRGBAPixel.h" #include #include "qwidgetaction.h" #include "qcolordialog.h" #define ROUND(a) ((a)>0 ? (int)((a)+0.5) : -(int)(0.5-(a))) static bool DetermineAffectedImageSlice( const mitk::Image* image, const mitk::PlaneGeometry* plane, int& affectedDimension, int& affectedSlice ) { assert(image); assert(plane); // compare normal of plane to the three axis vectors of the image mitk::Vector3D normal = plane->GetNormal(); mitk::Vector3D imageNormal0 = image->GetSlicedGeometry()->GetAxisVector(0); mitk::Vector3D imageNormal1 = image->GetSlicedGeometry()->GetAxisVector(1); mitk::Vector3D imageNormal2 = image->GetSlicedGeometry()->GetAxisVector(2); normal.Normalize(); imageNormal0.Normalize(); imageNormal1.Normalize(); imageNormal2.Normalize(); imageNormal0.SetVnlVector( vnl_cross_3d(normal.GetVnlVector(),imageNormal0.GetVnlVector()) ); imageNormal1.SetVnlVector( vnl_cross_3d(normal.GetVnlVector(),imageNormal1.GetVnlVector()) ); imageNormal2.SetVnlVector( vnl_cross_3d(normal.GetVnlVector(),imageNormal2.GetVnlVector()) ); double eps( 0.00001 ); // axial if ( imageNormal2.GetNorm() <= eps ) { affectedDimension = 2; } // sagittal else if ( imageNormal1.GetNorm() <= eps ) { affectedDimension = 1; } // frontal else if ( imageNormal0.GetNorm() <= eps ) { affectedDimension = 0; } else { affectedDimension = -1; // no idea return false; } // determine slice number in image mitk::Geometry3D* imageGeometry = image->GetGeometry(0); mitk::Point3D testPoint = imageGeometry->GetCenter(); mitk::Point3D projectedPoint; plane->Project( testPoint, projectedPoint ); mitk::Point3D indexPoint; imageGeometry->WorldToIndex( projectedPoint, indexPoint ); affectedSlice = ROUND( indexPoint[affectedDimension] ); MITK_DEBUG << "indexPoint " << indexPoint << " affectedDimension " << affectedDimension << " affectedSlice " << affectedSlice; // check if this index is still within the image if ( affectedSlice < 0 || affectedSlice >= static_cast(image->GetDimension(affectedDimension)) ) return false; return true; } const std::string QmitkControlVisualizationPropertiesView::VIEW_ID = "org.mitk.views.controlvisualizationpropertiesview"; using namespace berry; struct CvpSelListener : ISelectionListener { berryObjectMacro(CvpSelListener); CvpSelListener(QmitkControlVisualizationPropertiesView* view) { m_View = view; } void ApplySettings(mitk::DataNode::Pointer node) { bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("ShowMaxNumber", val); m_View->m_Controls->m_ShowMaxNumber->setValue(val); m_View->m_Controls->m_NormalizationDropdown->setCurrentIndex(dynamic_cast(node->GetProperty("Normalization"))->GetValueAsId()); float fval; node->GetFloatProperty("Scaling",fval); m_View->m_Controls->m_ScalingFactor->setValue(fval); m_View->m_Controls->m_AdditionalScaling->setCurrentIndex(dynamic_cast(node->GetProperty("ScaleBy"))->GetValueAsId()); node->GetFloatProperty("IndexParam1",fval); m_View->m_Controls->m_IndexParam1->setValue(fval); node->GetFloatProperty("IndexParam2",fval); m_View->m_Controls->m_IndexParam2->setValue(fval); } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); m_View->m_Controls->m_VisibleOdfsON_T->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_S->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_C->setVisible(false); m_View->m_Controls->m_TextureIntON->setVisible(false); m_View->m_Controls->m_ImageControlsFrame->setVisible(false); m_View->m_Controls->m_PlanarFigureControlsFrame->setVisible(false); m_View->m_Controls->m_BundleControlsFrame->setVisible(false); m_View->m_SelectedNode = 0; if(m_View->m_CurrentSelection.IsNull()) return; if(m_View->m_CurrentSelection->Size() == 1) { mitk::DataNodeObject::Pointer nodeObj = m_View->m_CurrentSelection->Begin()->Cast(); if(nodeObj.IsNotNull()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // check if node has data, // if some helper nodes are shown in the DataManager, the GetData() returns 0x0 which would lead to SIGSEV mitk::BaseData* nodeData = node->GetData(); if(nodeData != NULL ) { if(dynamic_cast(nodeData) != 0) { m_View->m_Controls->m_PlanarFigureControlsFrame->setVisible(true); m_View->m_SelectedNode = node; float val; node->GetFloatProperty("planarfigure.line.width", val); m_View->m_Controls->m_PFWidth->setValue((int)(val*10.0)); QString label = "Width %1"; label = label.arg(val); m_View->m_Controls->label_pfwidth->setText(label); float color[3]; node->GetColor( color, NULL, "planarfigure.default.line.color"); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255.0)); styleSheet.append(")"); m_View->m_Controls->m_PFColor->setAutoFillBackground(true); m_View->m_Controls->m_PFColor->setStyleSheet(styleSheet); node->GetColor( color, NULL, "color"); styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255.0)); styleSheet.append(")"); m_View->PlanarFigureFocus(); } if(dynamic_cast(nodeData) != 0) { m_View->m_Controls->m_BundleControlsFrame->setVisible(true); m_View->m_SelectedNode = node; if(m_View->m_CurrentPickingNode != 0 && node.GetPointer() != m_View->m_CurrentPickingNode) { m_View->m_Controls->m_Crosshair->setEnabled(false); } else { m_View->m_Controls->m_Crosshair->setEnabled(true); } float val; node->GetFloatProperty("TubeRadius", val); m_View->m_Controls->m_TubeRadius->setValue((int)(val * 100.0)); QString label = "Radius %1"; label = label.arg(val); m_View->m_Controls->label_tuberadius->setText(label); int width; node->GetIntProperty("LineWidth", width); m_View->m_Controls->m_LineWidth->setValue(width); label = "Width %1"; label = label.arg(width); m_View->m_Controls->label_linewidth->setText(label); float range; node->GetFloatProperty("Fiber2DSliceThickness",range); label = "Range %1"; label = label.arg(range*0.1); m_View->m_Controls->label_range->setText(label); } } // check node data != NULL } } if(m_View->m_CurrentSelection->Size() > 0 && m_View->m_SelectedNode == 0) { m_View->m_Controls->m_ImageControlsFrame->setVisible(true); bool foundDiffusionImage = false; bool foundQBIVolume = false; bool foundTensorVolume = false; bool foundImage = false; bool foundMultipleOdfImages = false; bool foundRGBAImage = false; bool foundTbssImage = false; // do something with the selected items if(m_View->m_CurrentSelection) { // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); mitk::BaseData* nodeData = node->GetData(); if(nodeData != NULL ) { // only look at interesting types if(QString("DiffusionImage").compare(nodeData->GetNameOfClass())==0) { foundDiffusionImage = true; bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("DisplayChannel", val); m_View->m_Controls->m_DisplayIndex->setValue(val); m_View->m_Controls->m_DisplayIndexSpinBox->setValue(val); QString label = "Channel %1"; label = label.arg(val); m_View->m_Controls->label_channel->setText(label); int maxVal = (dynamic_cast* >(nodeData))->GetVectorImage()->GetVectorLength(); m_View->m_Controls->m_DisplayIndex->setMaximum(maxVal-1); m_View->m_Controls->m_DisplayIndexSpinBox->setMaximum(maxVal-1); } if(QString("TbssImage").compare(nodeData->GetNameOfClass())==0) { foundTbssImage = true; bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("DisplayChannel", val); m_View->m_Controls->m_DisplayIndex->setValue(val); m_View->m_Controls->m_DisplayIndexSpinBox->setValue(val); QString label = "Channel %1"; label = label.arg(val); m_View->m_Controls->label_channel->setText(label); int maxVal = (dynamic_cast(nodeData))->GetImage()->GetVectorLength(); m_View->m_Controls->m_DisplayIndex->setMaximum(maxVal-1); m_View->m_Controls->m_DisplayIndexSpinBox->setMaximum(maxVal-1); } else if(QString("QBallImage").compare(nodeData->GetNameOfClass())==0) { foundMultipleOdfImages = foundQBIVolume || foundTensorVolume; foundQBIVolume = true; ApplySettings(node); } else if(QString("TensorImage").compare(nodeData->GetNameOfClass())==0) { foundMultipleOdfImages = foundQBIVolume || foundTensorVolume; foundTensorVolume = true; ApplySettings(node); } else if(QString("Image").compare(nodeData->GetNameOfClass())==0) { foundImage = true; mitk::Image::Pointer img = dynamic_cast(nodeData); if(img.IsNotNull() && img->GetPixelType().GetPixelType() == itk::ImageIOBase::RGBA && img->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR ) { foundRGBAImage = true; } bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } } } // END CHECK node != NULL } } } m_View->m_FoundSingleOdfImage = (foundQBIVolume || foundTensorVolume) && !foundMultipleOdfImages; m_View->m_Controls->m_NumberGlyphsFrame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_NormalizationDropdown->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->label->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_ScalingFactor->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_AdditionalScaling->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_NormalizationScalingFrame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->OpacMinFrame->setVisible(foundRGBAImage || m_View->m_FoundSingleOdfImage); // changed for SPIE paper, Principle curvature scaling //m_View->m_Controls->params_frame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->params_frame->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_T->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_VisibleOdfsON_S->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_VisibleOdfsON_C->setVisible(m_View->m_FoundSingleOdfImage); bool foundAnyImage = foundDiffusionImage || foundQBIVolume || foundTensorVolume || foundImage || foundTbssImage; m_View->m_Controls->m_Reinit->setVisible(foundAnyImage); m_View->m_Controls->m_TextureIntON->setVisible(foundAnyImage); m_View->m_Controls->m_TSMenu->setVisible(foundAnyImage); } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkControlVisualizationPropertiesView* m_View; }; QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_NodeUsedForOdfVisualization(NULL), m_IconTexOFF(new QIcon(":/QmitkDiffusionImaging/texIntOFFIcon.png")), m_IconTexON(new QIcon(":/QmitkDiffusionImaging/texIntONIcon.png")), m_IconGlyOFF_T(new QIcon(":/QmitkDiffusionImaging/glyphsoff_T.png")), m_IconGlyON_T(new QIcon(":/QmitkDiffusionImaging/glyphson_T.png")), m_IconGlyOFF_C(new QIcon(":/QmitkDiffusionImaging/glyphsoff_C.png")), m_IconGlyON_C(new QIcon(":/QmitkDiffusionImaging/glyphson_C.png")), m_IconGlyOFF_S(new QIcon(":/QmitkDiffusionImaging/glyphsoff_S.png")), m_IconGlyON_S(new QIcon(":/QmitkDiffusionImaging/glyphson_S.png")), m_CurrentSelection(0), m_CurrentPickingNode(0), m_GlyIsOn_S(false), m_GlyIsOn_C(false), m_GlyIsOn_T(false), m_FiberBundleObserverTag(0), m_Color(NULL) { currentThickSlicesMode = 1; m_MyMenu = NULL; } QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView(const QmitkControlVisualizationPropertiesView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkControlVisualizationPropertiesView::~QmitkControlVisualizationPropertiesView() { if(m_SlicesRotationObserverTag1 ) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if( coordinator) coordinator->RemoveObserver(m_SlicesRotationObserverTag1); } if( m_SlicesRotationObserverTag2) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if( coordinator ) coordinator->RemoveObserver(m_SlicesRotationObserverTag1); } this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); } void QmitkControlVisualizationPropertiesView::OnThickSlicesModeSelected( QAction* action ) { currentThickSlicesMode = action->data().toInt(); switch(currentThickSlicesMode) { default: case 1: this->m_Controls->m_TSMenu->setText("MIP"); break; case 2: this->m_Controls->m_TSMenu->setText("SUM"); break; case 3: this->m_Controls->m_TSMenu->setText("WEIGH"); break; } mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow2()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow3()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer->GetRenderingManager()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::OnTSNumChanged(int num) { if(num==0) { mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); } else { mitk::DataNode* n; n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = this->m_MultiWidget->GetWidgetPlane1(); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); n = this->m_MultiWidget->GetWidgetPlane2(); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); n = this->m_MultiWidget->GetWidgetPlane3(); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); } m_TSLabel->setText(QString::number(num*2+1)); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow2()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow3()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer->GetRenderingManager()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_2DWINDOWS); } void QmitkControlVisualizationPropertiesView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkControlVisualizationPropertiesViewControls; m_Controls->setupUi(parent); this->CreateConnections(); // hide warning (ODFs in rotated planes) m_Controls->m_lblRotatedPlanesWarning->hide(); m_MyMenu = new QMenu(parent); connect( m_MyMenu, SIGNAL( aboutToShow() ), this, SLOT(OnMenuAboutToShow()) ); // button for changing rotation mode m_Controls->m_TSMenu->setMenu( m_MyMenu ); //m_CrosshairModeButton->setIcon( QIcon( iconCrosshairMode_xpm ) ); m_Controls->params_frame->setVisible(false); QIcon icon5(":/QmitkDiffusionImaging/Refresh_48.png"); m_Controls->m_Reinit->setIcon(icon5); m_Controls->m_Focus->setIcon(icon5); QIcon iconColor(":/QmitkDiffusionImaging/color24.gif"); m_Controls->m_PFColor->setIcon(iconColor); m_Controls->m_Color->setIcon(iconColor); QIcon iconReset(":/QmitkDiffusionImaging/reset.png"); m_Controls->m_ResetColoring->setIcon(iconReset); m_Controls->m_PFColor->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); QIcon iconCrosshair(":/QmitkDiffusionImaging/crosshair.png"); m_Controls->m_Crosshair->setIcon(iconCrosshair); // was is los QIcon iconPaint(":/QmitkDiffusionImaging/paint2.png"); m_Controls->m_TDI->setIcon(iconPaint); QIcon iconFiberFade(":/QmitkDiffusionImaging/MapperEfx2D.png"); m_Controls->m_FiberFading2D->setIcon(iconFiberFade); m_Controls->m_TextureIntON->setCheckable(true); #ifndef DIFFUSION_IMAGING_EXTENDED int size = m_Controls->m_AdditionalScaling->count(); for(int t=0; tm_AdditionalScaling->itemText(t).toStdString() == "Scale by ASR") { m_Controls->m_AdditionalScaling->removeItem(t); } } #endif m_Controls->m_OpacitySlider->setRange(0.0,1.0); m_Controls->m_OpacitySlider->setLowerValue(0.0); m_Controls->m_OpacitySlider->setUpperValue(0.0); m_Controls->m_ScalingFrame->setVisible(false); m_Controls->m_NormalizationFrame->setVisible(false); m_Controls->frame_tube->setVisible(false); m_Controls->frame_wire->setVisible(false); } m_IsInitialized = false; m_SelListener = berry::ISelectionListener::Pointer(new CvpSelListener(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); m_IsInitialized = true; } void QmitkControlVisualizationPropertiesView::OnMenuAboutToShow () { // THICK SLICE SUPPORT QMenu *myMenu = m_MyMenu; myMenu->clear(); QActionGroup* thickSlicesActionGroup = new QActionGroup(myMenu); thickSlicesActionGroup->setExclusive(true); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); int currentTSMode = 0; { mitk::ResliceMethodProperty::Pointer m = dynamic_cast(renderer->GetCurrentWorldGeometry2DNode()->GetProperty( "reslice.thickslices" )); if( m.IsNotNull() ) currentTSMode = m->GetValueAsId(); } const int maxTS = 30; int currentNum = 0; { mitk::IntProperty::Pointer m = dynamic_cast(renderer->GetCurrentWorldGeometry2DNode()->GetProperty( "reslice.thickslices.num" )); if( m.IsNotNull() ) { currentNum = m->GetValue(); if(currentNum < 0) currentNum = 0; if(currentNum > maxTS) currentNum = maxTS; } } if(currentTSMode==0) currentNum=0; QSlider *m_TSSlider = new QSlider(myMenu); m_TSSlider->setMinimum(0); m_TSSlider->setMaximum(maxTS-1); m_TSSlider->setValue(currentNum); m_TSSlider->setOrientation(Qt::Horizontal); connect( m_TSSlider, SIGNAL( valueChanged(int) ), this, SLOT( OnTSNumChanged(int) ) ); QHBoxLayout* _TSLayout = new QHBoxLayout; _TSLayout->setContentsMargins(4,4,4,4); _TSLayout->addWidget(m_TSSlider); _TSLayout->addWidget(m_TSLabel=new QLabel(QString::number(currentNum*2+1),myMenu)); QWidget* _TSWidget = new QWidget; _TSWidget->setLayout(_TSLayout); QActionGroup* thickSliceModeActionGroup = new QActionGroup(myMenu); thickSliceModeActionGroup->setExclusive(true); QWidgetAction *m_TSSliderAction = new QWidgetAction(myMenu); m_TSSliderAction->setDefaultWidget(_TSWidget); myMenu->addAction(m_TSSliderAction); QAction* mipThickSlicesAction = new QAction(myMenu); mipThickSlicesAction->setActionGroup(thickSliceModeActionGroup); mipThickSlicesAction->setText("MIP (max. intensity proj.)"); mipThickSlicesAction->setCheckable(true); mipThickSlicesAction->setChecked(currentThickSlicesMode==1); mipThickSlicesAction->setData(1); myMenu->addAction( mipThickSlicesAction ); QAction* sumThickSlicesAction = new QAction(myMenu); sumThickSlicesAction->setActionGroup(thickSliceModeActionGroup); sumThickSlicesAction->setText("SUM (sum intensity proj.)"); sumThickSlicesAction->setCheckable(true); sumThickSlicesAction->setChecked(currentThickSlicesMode==2); sumThickSlicesAction->setData(2); myMenu->addAction( sumThickSlicesAction ); QAction* weightedThickSlicesAction = new QAction(myMenu); weightedThickSlicesAction->setActionGroup(thickSliceModeActionGroup); weightedThickSlicesAction->setText("WEIGHTED (gaussian proj.)"); weightedThickSlicesAction->setCheckable(true); weightedThickSlicesAction->setChecked(currentThickSlicesMode==3); weightedThickSlicesAction->setData(3); myMenu->addAction( weightedThickSlicesAction ); connect( thickSliceModeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(OnThickSlicesModeSelected(QAction*)) ); } void QmitkControlVisualizationPropertiesView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; if (m_MultiWidget) { mitk::SlicesCoordinator* coordinator = m_MultiWidget->GetSlicesRotator(); if (coordinator) { itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SliceRotation ); m_SlicesRotationObserverTag1 = coordinator->AddObserver( mitk::SliceRotationEvent(), command2 ); } coordinator = m_MultiWidget->GetSlicesSwiveller(); if (coordinator) { itk::ReceptorMemberCommand::Pointer command2 = itk::ReceptorMemberCommand::New(); command2->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SliceRotation ); m_SlicesRotationObserverTag2 = coordinator->AddObserver( mitk::SliceRotationEvent(), command2 ); } } } void QmitkControlVisualizationPropertiesView::SliceRotation(const itk::EventObject&) { // test if plane rotated if( m_GlyIsOn_T || m_GlyIsOn_C || m_GlyIsOn_S ) { if( this->IsPlaneRotated() ) { // show label m_Controls->m_lblRotatedPlanesWarning->show(); } else { //hide label m_Controls->m_lblRotatedPlanesWarning->hide(); } } } void QmitkControlVisualizationPropertiesView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkControlVisualizationPropertiesView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_DisplayIndex), SIGNAL(valueChanged(int)), this, SLOT(DisplayIndexChanged(int)) ); connect( (QObject*)(m_Controls->m_DisplayIndexSpinBox), SIGNAL(valueChanged(int)), this, SLOT(DisplayIndexChanged(int)) ); connect( (QObject*)(m_Controls->m_TextureIntON), SIGNAL(clicked()), this, SLOT(TextIntON()) ); connect( (QObject*)(m_Controls->m_Reinit), SIGNAL(clicked()), this, SLOT(Reinit()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_T), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_T()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_S), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_S()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_C), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_C()) ); connect( (QObject*)(m_Controls->m_ShowMaxNumber), SIGNAL(editingFinished()), this, SLOT(ShowMaxNumberChanged()) ); connect( (QObject*)(m_Controls->m_NormalizationDropdown), SIGNAL(currentIndexChanged(int)), this, SLOT(NormalizationDropdownChanged(int)) ); connect( (QObject*)(m_Controls->m_ScalingFactor), SIGNAL(valueChanged(double)), this, SLOT(ScalingFactorChanged(double)) ); connect( (QObject*)(m_Controls->m_AdditionalScaling), SIGNAL(currentIndexChanged(int)), this, SLOT(AdditionalScaling(int)) ); connect( (QObject*)(m_Controls->m_IndexParam1), SIGNAL(valueChanged(double)), this, SLOT(IndexParam1Changed(double)) ); connect( (QObject*)(m_Controls->m_IndexParam2), SIGNAL(valueChanged(double)), this, SLOT(IndexParam2Changed(double)) ); connect( (QObject*)(m_Controls->m_ScalingCheckbox), SIGNAL(clicked()), this, SLOT(ScalingCheckbox()) ); connect( (QObject*)(m_Controls->m_OpacitySlider), SIGNAL(spanChanged(double,double)), this, SLOT(OpacityChanged(double,double)) ); connect((QObject*) m_Controls->m_Wire, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationWire())); connect((QObject*) m_Controls->m_Tube, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationTube())); connect((QObject*) m_Controls->m_Color, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationColor())); connect((QObject*) m_Controls->m_ResetColoring, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationResetColoring())); connect((QObject*) m_Controls->m_Focus, SIGNAL(clicked()), (QObject*) this, SLOT(PlanarFigureFocus())); connect((QObject*) m_Controls->m_FiberFading2D, SIGNAL(clicked()), (QObject*) this, SLOT( Fiber2DfadingEFX() ) ); connect((QObject*) m_Controls->m_FiberThicknessSlider, SIGNAL(sliderReleased()), (QObject*) this, SLOT( FiberSlicingThickness2D() ) ); connect((QObject*) m_Controls->m_FiberThicknessSlider, SIGNAL(valueChanged(int)), (QObject*) this, SLOT( FiberSlicingUpdateLabel(int) )); connect((QObject*) m_Controls->m_Crosshair, SIGNAL(clicked()), (QObject*) this, SLOT(SetInteractor())); connect((QObject*) m_Controls->m_PFWidth, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(PFWidth(int))); connect((QObject*) m_Controls->m_PFColor, SIGNAL(clicked()), (QObject*) this, SLOT(PFColor())); connect((QObject*) m_Controls->m_TDI, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateTdi())); connect((QObject*) m_Controls->m_LineWidth, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(LineWidthChanged(int))); connect((QObject*) m_Controls->m_TubeRadius, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(TubeRadiusChanged(int))); } } void QmitkControlVisualizationPropertiesView::Activated() { berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); QmitkFunctionality::Activated(); } void QmitkControlVisualizationPropertiesView::Deactivated() { QmitkFunctionality::Deactivated(); } int QmitkControlVisualizationPropertiesView::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkControlVisualizationPropertiesView::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return m_FoundSingleOdfImage ? 120 : 80; } else { return preferredResult; } } // set diffusion image channel to b0 volume void QmitkControlVisualizationPropertiesView::NodeAdded(const mitk::DataNode *node) { mitk::DataNode* notConst = const_cast(node); if (dynamic_cast*>(notConst->GetData())) { mitk::DiffusionImage::Pointer dimg = dynamic_cast*>(notConst->GetData()); // if there is no b0 image in the dataset, the GetB0Indices() returns a vector of size 0 // and hence we cannot set the Property directly to .front() int displayChannelPropertyValue = 0; if( dimg->GetB0Indices().size() > 0) displayChannelPropertyValue = dimg->GetB0Indices().front(); notConst->SetIntProperty("DisplayChannel", displayChannelPropertyValue ); } } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkControlVisualizationPropertiesView::OnSelectionChanged( std::vector nodes ) { // deactivate channel slider if no diffusion weighted image or tbss image is selected m_Controls->m_DisplayIndex->setVisible(false); m_Controls->m_DisplayIndexSpinBox->setVisible(false); m_Controls->label_channel->setVisible(false); for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; // check if node has data, // if some helper nodes are shown in the DataManager, the GetData() returns 0x0 which would lead to SIGSEV mitk::BaseData* nodeData = node->GetData(); if(nodeData == NULL) continue; if (node.IsNotNull() && (dynamic_cast(nodeData) || dynamic_cast*>(nodeData))) { m_Controls->m_DisplayIndex->setVisible(true); m_Controls->m_DisplayIndexSpinBox->setVisible(true); m_Controls->label_channel->setVisible(true); } else if (node.IsNotNull() && dynamic_cast(node->GetData())) { if (m_Color.IsNotNull()) m_Color->RemoveObserver(m_FiberBundleObserverTag); itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction( this, &QmitkControlVisualizationPropertiesView::SetFiberBundleCustomColor ); m_Color = dynamic_cast(node->GetProperty("color", NULL)); if (m_Color.IsNotNull()) m_FiberBundleObserverTag = m_Color->AddObserver( itk::ModifiedEvent(), command ); } } for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; // check if node has data, // if some helper nodes are shown in the DataManager, the GetData() returns 0x0 which would lead to SIGSEV mitk::BaseData* nodeData = node->GetData(); if(nodeData == NULL) continue; if( node.IsNotNull() && (dynamic_cast(nodeData) || dynamic_cast(nodeData)) ) { if(m_NodeUsedForOdfVisualization.IsNotNull()) { m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", false); } m_NodeUsedForOdfVisualization = node; m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); m_Controls->m_TSMenu->setVisible(false); // deactivate mip etc. for tensor and q-ball images break; } else if( node.IsNotNull() && dynamic_cast(nodeData) ) m_Controls->m_TSMenu->setVisible(false); else m_Controls->m_TSMenu->setVisible(true); } } mitk::DataStorage::SetOfObjects::Pointer QmitkControlVisualizationPropertiesView::ActiveSet(std::string classname) { if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // check if node has data, // if some helper nodes are shown in the DataManager, the GetData() returns 0x0 which would lead to SIGSEV const mitk::BaseData* nodeData = node->GetData(); if(nodeData == NULL) continue; if(QString(classname.c_str()).compare(nodeData->GetNameOfClass())==0) { set->InsertElement(at++, node); } } } return set; } return 0; } void QmitkControlVisualizationPropertiesView::SetBoolProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, bool value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetBoolProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetIntProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, int value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetIntProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetFloatProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, float value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetFloatProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetLevelWindowProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, mitk::LevelWindow value) { if(set.IsNotNull()) { mitk::LevelWindowProperty::Pointer prop = mitk::LevelWindowProperty::New(value); mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetProperty(name.c_str(), prop); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetEnumProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, mitk::EnumerationProperty::Pointer value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::DisplayIndexChanged(int dispIndex) { m_Controls->m_DisplayIndex->setValue(dispIndex); m_Controls->m_DisplayIndexSpinBox->setValue(dispIndex); QString label = "Channel %1"; label = label.arg(dispIndex); m_Controls->label_channel->setText(label); std::vector sets; sets.push_back("DiffusionImage"); sets.push_back("TbssImage"); std::vector::iterator it = sets.begin(); while(it != sets.end()) { std::string s = *it; mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet(s); if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetIntProperty("DisplayChannel", dispIndex); ++itemiter; } //m_MultiWidget->RequestUpdate(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } it++; } } void QmitkControlVisualizationPropertiesView::Reinit() { if (m_CurrentSelection) { mitk::DataNodeObject::Pointer nodeObj = m_CurrentSelection->Begin()->Cast(); mitk::DataNode::Pointer node = nodeObj->GetDataNode(); mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkControlVisualizationPropertiesView::TextIntON() { if(m_TexIsOn) { m_Controls->m_TextureIntON->setIcon(*m_IconTexOFF); } else { m_Controls->m_TextureIntON->setIcon(*m_IconTexON); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("DiffusionImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("TensorImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("QBallImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("Image"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); m_TexIsOn = !m_TexIsOn; if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_S() { m_GlyIsOn_S = m_Controls->m_VisibleOdfsON_S->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); VisibleOdfsON(0); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_T() { m_GlyIsOn_T = m_Controls->m_VisibleOdfsON_T->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); VisibleOdfsON(1); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_C() { m_GlyIsOn_C = m_Controls->m_VisibleOdfsON_C->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); VisibleOdfsON(2); } bool QmitkControlVisualizationPropertiesView::IsPlaneRotated() { // for all 2D renderwindows of m_MultiWidget check alignment mitk::PlaneGeometry::ConstPointer displayPlane = dynamic_cast( m_MultiWidget->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D() ); if (displayPlane.IsNull()) return false; mitk::Image* currentImage = dynamic_cast( m_NodeUsedForOdfVisualization->GetData() ); if( currentImage == NULL ) { MITK_ERROR << " Casting problems. Returning false"; return false; } int affectedDimension(-1); int affectedSlice(-1); return !(DetermineAffectedImageSlice( currentImage, displayPlane, affectedDimension, affectedSlice )); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON(int view) { if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::ShowMaxNumberChanged() { int maxNr = m_Controls->m_ShowMaxNumber->value(); if ( maxNr < 1 ) { m_Controls->m_ShowMaxNumber->setValue( 1 ); maxNr = 1; } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetIntProp(set,"ShowMaxNumber", maxNr); set = ActiveSet("TensorImage"); SetIntProp(set,"ShowMaxNumber", maxNr); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::NormalizationDropdownChanged(int normDropdown) { typedef mitk::OdfNormalizationMethodProperty PropType; PropType::Pointer normMeth = PropType::New(); switch(normDropdown) { case 0: normMeth->SetNormalizationToMinMax(); break; case 1: normMeth->SetNormalizationToMax(); break; case 2: normMeth->SetNormalizationToNone(); break; case 3: normMeth->SetNormalizationToGlobalMax(); break; default: normMeth->SetNormalizationToMinMax(); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetEnumProp(set,"Normalization", normMeth.GetPointer()); set = ActiveSet("TensorImage"); SetEnumProp(set,"Normalization", normMeth.GetPointer()); // if(m_MultiWidget) // m_MultiWidget->RequestUpdate(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::ScalingFactorChanged(double scalingFactor) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"Scaling", scalingFactor); set = ActiveSet("TensorImage"); SetFloatProp(set,"Scaling", scalingFactor); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::AdditionalScaling(int additionalScaling) { typedef mitk::OdfScaleByProperty PropType; PropType::Pointer scaleBy = PropType::New(); switch(additionalScaling) { case 0: scaleBy->SetScaleByNothing(); break; case 1: scaleBy->SetScaleByGFA(); //m_Controls->params_frame->setVisible(true); break; #ifdef DIFFUSION_IMAGING_EXTENDED case 2: scaleBy->SetScaleByPrincipalCurvature(); // commented in for SPIE paper, Principle curvature scaling //m_Controls->params_frame->setVisible(true); break; #endif default: scaleBy->SetScaleByNothing(); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetEnumProp(set,"ScaleBy", scaleBy.GetPointer()); set = ActiveSet("TensorImage"); SetEnumProp(set,"ScaleBy", scaleBy.GetPointer()); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::IndexParam1Changed(double param1) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"IndexParam1", param1); set = ActiveSet("TensorImage"); SetFloatProp(set,"IndexParam1", param1); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::IndexParam2Changed(double param2) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"IndexParam2", param2); set = ActiveSet("TensorImage"); SetFloatProp(set,"IndexParam2", param2); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::OpacityChanged(double l, double u) { mitk::LevelWindow olw; olw.SetRangeMinMax(l*255, u*255); mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetLevelWindowProp(set,"opaclevelwindow", olw); set = ActiveSet("TensorImage"); SetLevelWindowProp(set,"opaclevelwindow", olw); set = ActiveSet("Image"); SetLevelWindowProp(set,"opaclevelwindow", olw); m_Controls->m_OpacityMinFaLabel->setText(QString::number(l,'f',2) + " : " + QString::number(u,'f',2)); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::ScalingCheckbox() { m_Controls->m_ScalingFrame->setVisible( m_Controls->m_ScalingCheckbox->isChecked()); if(!m_Controls->m_ScalingCheckbox->isChecked()) { m_Controls->m_AdditionalScaling->setCurrentIndex(0); m_Controls->m_ScalingFactor->setValue(1.0); } } void QmitkControlVisualizationPropertiesView::Fiber2DfadingEFX() { if (m_SelectedNode) { bool currentMode; m_SelectedNode->GetBoolProperty("Fiber2DfadeEFX", currentMode); m_SelectedNode->SetProperty("Fiber2DfadeEFX", mitk::BoolProperty::New(!currentMode)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::FiberSlicingThickness2D() { if (m_SelectedNode) { float fibThickness = m_Controls->m_FiberThicknessSlider->value() * 0.1; m_SelectedNode->SetProperty("Fiber2DSliceThickness", mitk::FloatProperty::New(fibThickness)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::FiberSlicingUpdateLabel(int value) { QString label = "Range %1"; label = label.arg(value * 0.1); m_Controls->label_range->setText(label); } void QmitkControlVisualizationPropertiesView::BundleRepresentationWire() { if(m_SelectedNode) { int width = m_Controls->m_LineWidth->value(); m_SelectedNode->SetProperty("LineWidth",mitk::IntProperty::New(width)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(15)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(18)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(1)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(2)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(3)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(4)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::BundleRepresentationTube() { if(m_SelectedNode) { float radius = m_Controls->m_TubeRadius->value() / 100.0; m_SelectedNode->SetProperty("TubeRadius",mitk::FloatProperty::New(radius)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(17)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(13)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(16)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::SetFiberBundleCustomColor(const itk::EventObject& /*e*/) { float color[3]; m_SelectedNode->GetColor(color); m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255.0)); styleSheet.append(")"); m_Controls->m_Color->setStyleSheet(styleSheet); m_SelectedNode->SetProperty("color",mitk::ColorProperty::New(color[0], color[1], color[2])); mitk::FiberBundleX::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->SetColorCoding(mitk::FiberBundleX::COLORCODING_CUSTOM); m_SelectedNode->Modified(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } void QmitkControlVisualizationPropertiesView::BundleRepresentationColor() { if(m_SelectedNode) { QColor color = QColorDialog::getColor(); if (!color.isValid()) return; m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_Color->setStyleSheet(styleSheet); m_SelectedNode->SetProperty("color",mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); mitk::FiberBundleX::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->SetColorCoding(mitk::FiberBundleX::COLORCODING_CUSTOM); m_SelectedNode->Modified(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::BundleRepresentationResetColoring() { if(m_SelectedNode) { MITK_INFO << "reset colorcoding to oBased"; m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb(255,255,255)"; m_Controls->m_Color->setStyleSheet(styleSheet); // m_SelectedNode->SetProperty("color",NULL); m_SelectedNode->SetProperty("color",mitk::ColorProperty::New(1.0, 1.0, 1.0)); mitk::FiberBundleX::Pointer fib = dynamic_cast(m_SelectedNode->GetData()); fib->SetColorCoding(mitk::FiberBundleX::COLORCODING_ORIENTATION_BASED); fib->DoColorCodingOrientationBased(); m_SelectedNode->Modified(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::PlanarFigureFocus() { if(m_SelectedNode) { mitk::PlanarFigure* _PlanarFigure = 0; _PlanarFigure = dynamic_cast (m_SelectedNode->GetData()); if (_PlanarFigure && _PlanarFigure->GetGeometry2D()) { QmitkRenderWindow* selectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); if (m_SelectedNode->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } const mitk::PlaneGeometry * _PlaneGeometry = dynamic_cast (_PlanarFigure->GetGeometry2D()); mitk::VnlVector normal = _PlaneGeometry->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry1 = RenderWindow1->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane1 = dynamic_cast( worldGeometry1.GetPointer() ); mitk::VnlVector normal1 = _Plane1->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry2 = RenderWindow2->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane2 = dynamic_cast( worldGeometry2.GetPointer() ); mitk::VnlVector normal2 = _Plane2->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry3 = RenderWindow3->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane3 = dynamic_cast( worldGeometry3.GetPointer() ); mitk::VnlVector normal3 = _Plane3->GetNormalVnl(); normal[0] = fabs(normal[0]); normal[1] = fabs(normal[1]); normal[2] = fabs(normal[2]); normal1[0] = fabs(normal1[0]); normal1[1] = fabs(normal1[1]); normal1[2] = fabs(normal1[2]); normal2[0] = fabs(normal2[0]); normal2[1] = fabs(normal2[1]); normal2[2] = fabs(normal2[2]); normal3[0] = fabs(normal3[0]); normal3[1] = fabs(normal3[1]); normal3[2] = fabs(normal3[2]); double ang1 = angle(normal, normal1); double ang2 = angle(normal, normal2); double ang3 = angle(normal, normal3); if(ang1 < ang2 && ang1 < ang3) { selectedRenderWindow = RenderWindow1; } else { if(ang2 < ang3) { selectedRenderWindow = RenderWindow2; } else { selectedRenderWindow = RenderWindow3; } } // make node visible if (selectedRenderWindow) { const mitk::Point3D& centerP = _PlaneGeometry->GetOrigin(); selectedRenderWindow->GetSliceNavigationController()->ReorientSlices( centerP, _PlaneGeometry->GetNormal()); } } // set interactor for new node (if not already set) mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(m_SelectedNode->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); - mitk::Module* planarFigureModule = mitk::ModuleRegistry::GetModule( "PlanarFigure" ); + us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "PlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( m_SelectedNode ); } m_SelectedNode->SetProperty("planarfigure.iseditable",mitk::BoolProperty::New(true)); } } void QmitkControlVisualizationPropertiesView::SetInteractor() { typedef std::vector Container; Container _NodeSet = this->GetDataManagerSelection(); mitk::DataNode* node = 0; mitk::FiberBundleX* bundle = 0; mitk::FiberBundleInteractor::Pointer bundleInteractor = 0; // finally add all nodes to the model for(Container::const_iterator it=_NodeSet.begin(); it!=_NodeSet.end() ; it++) { node = const_cast(*it); bundle = dynamic_cast(node->GetData()); if(bundle) { bundleInteractor = dynamic_cast(node->GetInteractor()); if(bundleInteractor.IsNotNull()) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(bundleInteractor); if(!m_Controls->m_Crosshair->isChecked()) { m_Controls->m_Crosshair->setChecked(false); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::ArrowCursor); m_CurrentPickingNode = 0; } else { m_Controls->m_Crosshair->setChecked(true); bundleInteractor = mitk::FiberBundleInteractor::New("FiberBundleInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(bundleInteractor); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::CrossCursor); m_CurrentPickingNode = node; } } } } void QmitkControlVisualizationPropertiesView::PFWidth(int w) { double width = w/10.0; m_SelectedNode->SetProperty("planarfigure.line.width", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.outline.width", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.helperline.width", mitk::FloatProperty::New(width) ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QString label = "Width %1"; label = label.arg(width); m_Controls->label_pfwidth->setText(label); } void QmitkControlVisualizationPropertiesView::PFColor() { QColor color = QColorDialog::getColor(); if (!color.isValid()) return; m_Controls->m_PFColor->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_PFColor->setStyleSheet(styleSheet); m_SelectedNode->SetProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::GenerateTdi() { if(m_SelectedNode) { mitk::FiberBundleX* bundle = dynamic_cast(m_SelectedNode->GetData()); if(!bundle) return; typedef float OutPixType; typedef itk::Image OutImageType; // run generator itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New(); generator->SetFiberBundle(bundle); generator->SetOutputAbsoluteValues(true); generator->SetUpsamplingFactor(1); generator->Update(); // get result OutImageType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); // to datastorage mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); QString name(m_SelectedNode->GetName().c_str()); name += "_TDI"; node->SetName(name.toStdString()); node->SetVisibility(true); GetDataStorage()->Add(node); } } void QmitkControlVisualizationPropertiesView::LineWidthChanged(int w) { QString label = "Width %1"; label = label.arg(w); m_Controls->label_linewidth->setText(label); BundleRepresentationWire(); } void QmitkControlVisualizationPropertiesView::TubeRadiusChanged(int r) { QString label = "Radius %1"; label = label.arg(r / 100.0); m_Controls->label_tuberadius->setText(label); this->BundleRepresentationTube(); } void QmitkControlVisualizationPropertiesView::Welcome() { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( GetSite()->GetWorkbenchWindow(), false); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberExtractionView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberExtractionView.cpp index 8105354ab7..3349486ddc 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberExtractionView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberExtractionView.cpp @@ -1,1443 +1,1443 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkFiberExtractionView.h" #include // Qt #include // MITK #include #include #include #include #include #include #include #include #include #include #include #include -#include "mitkModuleRegistry.h" +#include "usModuleRegistry.h" // ITK #include #include #include #include #include #include #include #include const std::string QmitkFiberExtractionView::VIEW_ID = "org.mitk.views.fiberextraction"; const std::string id_DataManager = "org.mitk.views.datamanager"; using namespace mitk; QmitkFiberExtractionView::QmitkFiberExtractionView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_CircleCounter(0) , m_PolygonCounter(0) , m_UpsamplingFactor(5) { } // Destructor QmitkFiberExtractionView::~QmitkFiberExtractionView() { } void QmitkFiberExtractionView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkFiberExtractionViewControls; m_Controls->setupUi( parent ); m_Controls->doExtractFibersButton->setDisabled(true); m_Controls->PFCompoANDButton->setDisabled(true); m_Controls->PFCompoORButton->setDisabled(true); m_Controls->PFCompoNOTButton->setDisabled(true); m_Controls->m_PlanarFigureButtonsFrame->setEnabled(false); m_Controls->m_RectangleButton->setVisible(false); connect( m_Controls->m_CircleButton, SIGNAL( clicked() ), this, SLOT( OnDrawCircle() ) ); connect( m_Controls->m_PolygonButton, SIGNAL( clicked() ), this, SLOT( OnDrawPolygon() ) ); connect(m_Controls->PFCompoANDButton, SIGNAL(clicked()), this, SLOT(GenerateAndComposite()) ); connect(m_Controls->PFCompoORButton, SIGNAL(clicked()), this, SLOT(GenerateOrComposite()) ); connect(m_Controls->PFCompoNOTButton, SIGNAL(clicked()), this, SLOT(GenerateNotComposite()) ); connect(m_Controls->m_JoinBundles, SIGNAL(clicked()), this, SLOT(JoinBundles()) ); connect(m_Controls->m_SubstractBundles, SIGNAL(clicked()), this, SLOT(SubstractBundles()) ); connect(m_Controls->m_GenerateRoiImage, SIGNAL(clicked()), this, SLOT(GenerateRoiImage()) ); connect(m_Controls->m_Extract3dButton, SIGNAL(clicked()), this, SLOT(ExtractPassingMask())); connect( m_Controls->m_ExtractMask, SIGNAL(clicked()), this, SLOT(ExtractEndingInMask()) ); connect( m_Controls->doExtractFibersButton, SIGNAL(clicked()), this, SLOT(DoFiberExtraction()) ); connect( m_Controls->m_RemoveOutsideMaskButton, SIGNAL(clicked()), this, SLOT(DoRemoveOutsideMask())); connect( m_Controls->m_RemoveInsideMaskButton, SIGNAL(clicked()), this, SLOT(DoRemoveInsideMask())); } } void QmitkFiberExtractionView::DoRemoveInsideMask() { if (m_MaskImageNode.IsNull()) return; mitk::Image::Pointer mitkMask = dynamic_cast(m_MaskImageNode->GetData()); for (int i=0; i(m_SelectedFB.at(i)->GetData()); QString name(m_SelectedFB.at(i)->GetName().c_str()); itkUCharImageType::Pointer mask = itkUCharImageType::New(); mitk::CastToItkImage(mitkMask, mask); mitk::FiberBundleX::Pointer newFib = fib->RemoveFibersOutside(mask, true); if (newFib->GetNumFibers()<=0) { QMessageBox::information(NULL, "No output generated:", "The resulting fiber bundle contains no fibers."); continue; } DataNode::Pointer newNode = DataNode::New(); newNode->SetData(newFib); name += "_Cut"; newNode->SetName(name.toStdString()); GetDefaultDataStorage()->Add(newNode); m_SelectedFB.at(i)->SetVisibility(false); } } void QmitkFiberExtractionView::DoRemoveOutsideMask() { if (m_MaskImageNode.IsNull()) return; mitk::Image::Pointer mitkMask = dynamic_cast(m_MaskImageNode->GetData()); for (int i=0; i(m_SelectedFB.at(i)->GetData()); QString name(m_SelectedFB.at(i)->GetName().c_str()); itkUCharImageType::Pointer mask = itkUCharImageType::New(); mitk::CastToItkImage(mitkMask, mask); mitk::FiberBundleX::Pointer newFib = fib->RemoveFibersOutside(mask); if (newFib->GetNumFibers()<=0) { QMessageBox::information(NULL, "No output generated:", "The resulting fiber bundle contains no fibers."); continue; } DataNode::Pointer newNode = DataNode::New(); newNode->SetData(newFib); name += "_Cut"; newNode->SetName(name.toStdString()); GetDefaultDataStorage()->Add(newNode); m_SelectedFB.at(i)->SetVisibility(false); } } void QmitkFiberExtractionView::ExtractEndingInMask() { if (m_MaskImageNode.IsNull()) return; mitk::Image::Pointer mitkMask = dynamic_cast(m_MaskImageNode->GetData()); for (int i=0; i(m_SelectedFB.at(i)->GetData()); QString name(m_SelectedFB.at(i)->GetName().c_str()); itkUCharImageType::Pointer mask = itkUCharImageType::New(); mitk::CastToItkImage(mitkMask, mask); mitk::FiberBundleX::Pointer newFib = fib->ExtractFiberSubset(mask, false); if (newFib->GetNumFibers()<=0) { QMessageBox::information(NULL, "No output generated:", "The resulting fiber bundle contains no fibers."); continue; } DataNode::Pointer newNode = DataNode::New(); newNode->SetData(newFib); name += "_ending-in-mask"; newNode->SetName(name.toStdString()); GetDefaultDataStorage()->Add(newNode); m_SelectedFB.at(i)->SetVisibility(false); } } void QmitkFiberExtractionView::ExtractPassingMask() { if (m_MaskImageNode.IsNull()) return; mitk::Image::Pointer mitkMask = dynamic_cast(m_MaskImageNode->GetData()); for (int i=0; i(m_SelectedFB.at(i)->GetData()); QString name(m_SelectedFB.at(i)->GetName().c_str()); itkUCharImageType::Pointer mask = itkUCharImageType::New(); mitk::CastToItkImage(mitkMask, mask); mitk::FiberBundleX::Pointer newFib = fib->ExtractFiberSubset(mask, true); if (newFib->GetNumFibers()<=0) { QMessageBox::information(NULL, "No output generated:", "The resulting fiber bundle contains no fibers."); continue; } DataNode::Pointer newNode = DataNode::New(); newNode->SetData(newFib); name += "_passing-mask"; newNode->SetName(name.toStdString()); GetDefaultDataStorage()->Add(newNode); m_SelectedFB.at(i)->SetVisibility(false); } } void QmitkFiberExtractionView::GenerateRoiImage(){ if (m_SelectedPF.empty()) return; mitk::Geometry3D::Pointer geometry; if (!m_SelectedFB.empty()) { mitk::FiberBundleX::Pointer fib = dynamic_cast(m_SelectedFB.front()->GetData()); geometry = fib->GetGeometry(); } else return; itk::Vector spacing = geometry->GetSpacing(); spacing /= m_UpsamplingFactor; mitk::Point3D newOrigin = geometry->GetOrigin(); mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); newOrigin[0] += bounds.GetElement(0); newOrigin[1] += bounds.GetElement(2); newOrigin[2] += bounds.GetElement(4); itk::Matrix direction; itk::ImageRegion<3> imageRegion; for (int i=0; i<3; i++) for (int j=0; j<3; j++) direction[j][i] = geometry->GetMatrixColumn(i)[j]/spacing[j]; imageRegion.SetSize(0, geometry->GetExtent(0)*m_UpsamplingFactor); imageRegion.SetSize(1, geometry->GetExtent(1)*m_UpsamplingFactor); imageRegion.SetSize(2, geometry->GetExtent(2)*m_UpsamplingFactor); m_PlanarFigureImage = itkUCharImageType::New(); m_PlanarFigureImage->SetSpacing( spacing ); // Set the image spacing m_PlanarFigureImage->SetOrigin( newOrigin ); // Set the image origin m_PlanarFigureImage->SetDirection( direction ); // Set the image direction m_PlanarFigureImage->SetRegions( imageRegion ); m_PlanarFigureImage->Allocate(); m_PlanarFigureImage->FillBuffer( 0 ); Image::Pointer tmpImage = Image::New(); tmpImage->InitializeByItk(m_PlanarFigureImage.GetPointer()); tmpImage->SetVolume(m_PlanarFigureImage->GetBufferPointer()); for (int i=0; iInitializeByItk(m_PlanarFigureImage.GetPointer()); tmpImage->SetVolume(m_PlanarFigureImage->GetBufferPointer()); node->SetData(tmpImage); node->SetName("ROI Image"); this->GetDefaultDataStorage()->Add(node); } void QmitkFiberExtractionView::CompositeExtraction(mitk::DataNode::Pointer node, mitk::Image* image) { if (dynamic_cast(node.GetPointer()->GetData()) && !dynamic_cast(node.GetPointer()->GetData())) { m_PlanarFigure = dynamic_cast(node.GetPointer()->GetData()); AccessFixedDimensionByItk_2( image, InternalReorientImagePlane, 3, m_PlanarFigure->GetGeometry(), -1); AccessFixedDimensionByItk_2( m_InternalImage, InternalCalculateMaskFromPlanarFigure, 3, 2, node->GetName() ); } } template < typename TPixel, unsigned int VImageDimension > void QmitkFiberExtractionView::InternalReorientImagePlane( const itk::Image< TPixel, VImageDimension > *image, mitk::Geometry3D* planegeo3D, int additionalIndex ) { MITK_DEBUG << "InternalReorientImagePlane() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< float, VImageDimension > FloatImageType; typedef itk::ResampleImageFilter ResamplerType; typename ResamplerType::Pointer resampler = ResamplerType::New(); mitk::PlaneGeometry* planegeo = dynamic_cast(planegeo3D); float upsamp = m_UpsamplingFactor; float gausssigma = 0.5; // Spacing typename ResamplerType::SpacingType spacing = planegeo->GetSpacing(); spacing[0] = image->GetSpacing()[0] / upsamp; spacing[1] = image->GetSpacing()[1] / upsamp; spacing[2] = image->GetSpacing()[2]; resampler->SetOutputSpacing( spacing ); // Size typename ResamplerType::SizeType size; size[0] = planegeo->GetParametricExtentInMM(0) / spacing[0]; size[1] = planegeo->GetParametricExtentInMM(1) / spacing[1]; size[2] = 1; resampler->SetSize( size ); // Origin typename mitk::Point3D orig = planegeo->GetOrigin(); typename mitk::Point3D corrorig; planegeo3D->WorldToIndex(orig,corrorig); corrorig[0] += 0.5/upsamp; corrorig[1] += 0.5/upsamp; corrorig[2] += 0; planegeo3D->IndexToWorld(corrorig,corrorig); resampler->SetOutputOrigin(corrorig ); // Direction typename ResamplerType::DirectionType direction; typename mitk::AffineTransform3D::MatrixType matrix = planegeo->GetIndexToWorldTransform()->GetMatrix(); for(int c=0; cSetOutputDirection( direction ); // Gaussian interpolation if(gausssigma != 0) { double sigma[3]; for( unsigned int d = 0; d < 3; d++ ) { sigma[d] = gausssigma * image->GetSpacing()[d]; } double alpha = 2.0; typedef itk::GaussianInterpolateImageFunction GaussianInterpolatorType; typename GaussianInterpolatorType::Pointer interpolator = GaussianInterpolatorType::New(); interpolator->SetInputImage( image ); interpolator->SetParameters( sigma, alpha ); resampler->SetInterpolator( interpolator ); } else { // typedef typename itk::BSplineInterpolateImageFunction // InterpolatorType; typedef typename itk::LinearInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); resampler->SetInterpolator( interpolator ); } // Other resampling options resampler->SetInput( image ); resampler->SetDefaultPixelValue(0); MITK_DEBUG << "Resampling requested image plane ... "; resampler->Update(); MITK_DEBUG << " ... done"; if(additionalIndex < 0) { this->m_InternalImage = mitk::Image::New(); this->m_InternalImage->InitializeByItk( resampler->GetOutput() ); this->m_InternalImage->SetVolume( resampler->GetOutput()->GetBufferPointer() ); } } template < typename TPixel, unsigned int VImageDimension > void QmitkFiberExtractionView::InternalCalculateMaskFromPlanarFigure( itk::Image< TPixel, VImageDimension > *image, unsigned int axis, std::string nodeName ) { MITK_DEBUG << "InternalCalculateMaskFromPlanarFigure() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::CastImageFilter< ImageType, itkUCharImageType > CastFilterType; // Generate mask image as new image with same header as input image and // initialize with "1". itkUCharImageType::Pointer newMaskImage = itkUCharImageType::New(); newMaskImage->SetSpacing( image->GetSpacing() ); // Set the image spacing newMaskImage->SetOrigin( image->GetOrigin() ); // Set the image origin newMaskImage->SetDirection( image->GetDirection() ); // Set the image direction newMaskImage->SetRegions( image->GetLargestPossibleRegion() ); newMaskImage->Allocate(); newMaskImage->FillBuffer( 1 ); // Generate VTK polygon from (closed) PlanarFigure polyline // (The polyline points are shifted by -0.5 in z-direction to make sure // that the extrusion filter, which afterwards elevates all points by +0.5 // in z-direction, creates a 3D object which is cut by the the plane z=0) const Geometry2D *planarFigureGeometry2D = m_PlanarFigure->GetGeometry2D(); const PlanarFigure::PolyLineType planarFigurePolyline = m_PlanarFigure->GetPolyLine( 0 ); const Geometry3D *imageGeometry3D = m_InternalImage->GetGeometry( 0 ); vtkPolyData *polyline = vtkPolyData::New(); polyline->Allocate( 1, 1 ); // Determine x- and y-dimensions depending on principal axis int i0, i1; switch ( axis ) { case 0: i0 = 1; i1 = 2; break; case 1: i0 = 0; i1 = 2; break; case 2: default: i0 = 0; i1 = 1; break; } // Create VTK polydata object of polyline contour vtkPoints *points = vtkPoints::New(); PlanarFigure::PolyLineType::const_iterator it; std::vector indices; unsigned int numberOfPoints = 0; for ( it = planarFigurePolyline.begin(); it != planarFigurePolyline.end(); ++it ) { Point3D point3D; // Convert 2D point back to the local index coordinates of the selected // image Point2D point2D = it->Point; planarFigureGeometry2D->WorldToIndex(point2D, point2D); point2D[0] -= 0.5/m_UpsamplingFactor; point2D[1] -= 0.5/m_UpsamplingFactor; planarFigureGeometry2D->IndexToWorld(point2D, point2D); planarFigureGeometry2D->Map( point2D, point3D ); // Polygons (partially) outside of the image bounds can not be processed // further due to a bug in vtkPolyDataToImageStencil if ( !imageGeometry3D->IsInside( point3D ) ) { float bounds[2] = {0,0}; bounds[0] = this->m_InternalImage->GetLargestPossibleRegion().GetSize().GetElement(i0); bounds[1] = this->m_InternalImage->GetLargestPossibleRegion().GetSize().GetElement(i1); imageGeometry3D->WorldToIndex( point3D, point3D ); // if (point3D[i0]<0) // point3D[i0] = 0.5; // else if (point3D[i0]>bounds[0]) // point3D[i0] = bounds[0]-0.5; // if (point3D[i1]<0) // point3D[i1] = 0.5; // else if (point3D[i1]>bounds[1]) // point3D[i1] = bounds[1]-0.5; if (point3D[i0]<0) point3D[i0] = 0.0; else if (point3D[i0]>bounds[0]) point3D[i0] = bounds[0]-0.001; if (point3D[i1]<0) point3D[i1] = 0.0; else if (point3D[i1]>bounds[1]) point3D[i1] = bounds[1]-0.001; points->InsertNextPoint( point3D[i0], point3D[i1], -0.5 ); numberOfPoints++; } else { imageGeometry3D->WorldToIndex( point3D, point3D ); // Add point to polyline array points->InsertNextPoint( point3D[i0], point3D[i1], -0.5 ); numberOfPoints++; } } polyline->SetPoints( points ); points->Delete(); vtkIdType *ptIds = new vtkIdType[numberOfPoints]; for ( vtkIdType i = 0; i < numberOfPoints; ++i ) { ptIds[i] = i; } polyline->InsertNextCell( VTK_POLY_LINE, numberOfPoints, ptIds ); // Extrude the generated contour polygon vtkLinearExtrusionFilter *extrudeFilter = vtkLinearExtrusionFilter::New(); extrudeFilter->SetInput( polyline ); extrudeFilter->SetScaleFactor( 1 ); extrudeFilter->SetExtrusionTypeToNormalExtrusion(); extrudeFilter->SetVector( 0.0, 0.0, 1.0 ); // Make a stencil from the extruded polygon vtkPolyDataToImageStencil *polyDataToImageStencil = vtkPolyDataToImageStencil::New(); polyDataToImageStencil->SetInput( extrudeFilter->GetOutput() ); // Export from ITK to VTK (to use a VTK filter) typedef itk::VTKImageImport< itkUCharImageType > ImageImportType; typedef itk::VTKImageExport< itkUCharImageType > ImageExportType; typename ImageExportType::Pointer itkExporter = ImageExportType::New(); itkExporter->SetInput( newMaskImage ); vtkImageImport *vtkImporter = vtkImageImport::New(); this->ConnectPipelines( itkExporter, vtkImporter ); vtkImporter->Update(); // Apply the generated image stencil to the input image vtkImageStencil *imageStencilFilter = vtkImageStencil::New(); imageStencilFilter->SetInputConnection( vtkImporter->GetOutputPort() ); imageStencilFilter->SetStencil( polyDataToImageStencil->GetOutput() ); imageStencilFilter->ReverseStencilOff(); imageStencilFilter->SetBackgroundValue( 0 ); imageStencilFilter->Update(); // Export from VTK back to ITK vtkImageExport *vtkExporter = vtkImageExport::New(); vtkExporter->SetInputConnection( imageStencilFilter->GetOutputPort() ); vtkExporter->Update(); typename ImageImportType::Pointer itkImporter = ImageImportType::New(); this->ConnectPipelines( vtkExporter, itkImporter ); itkImporter->Update(); // calculate cropping bounding box m_InternalImageMask3D = itkImporter->GetOutput(); m_InternalImageMask3D->SetDirection(image->GetDirection()); itk::ImageRegionConstIterator itmask(m_InternalImageMask3D, m_InternalImageMask3D->GetLargestPossibleRegion()); itk::ImageRegionIterator itimage(image, image->GetLargestPossibleRegion()); itmask = itmask.Begin(); itimage = itimage.Begin(); typename ImageType::SizeType lowersize = {{9999999999,9999999999,9999999999}}; typename ImageType::SizeType uppersize = {{0,0,0}}; while( !itmask.IsAtEnd() ) { if(itmask.Get() == 0) { itimage.Set(0); } else { typename ImageType::IndexType index = itimage.GetIndex(); typename ImageType::SizeType signedindex; signedindex[0] = index[0]; signedindex[1] = index[1]; signedindex[2] = index[2]; lowersize[0] = signedindex[0] < lowersize[0] ? signedindex[0] : lowersize[0]; lowersize[1] = signedindex[1] < lowersize[1] ? signedindex[1] : lowersize[1]; lowersize[2] = signedindex[2] < lowersize[2] ? signedindex[2] : lowersize[2]; uppersize[0] = signedindex[0] > uppersize[0] ? signedindex[0] : uppersize[0]; uppersize[1] = signedindex[1] > uppersize[1] ? signedindex[1] : uppersize[1]; uppersize[2] = signedindex[2] > uppersize[2] ? signedindex[2] : uppersize[2]; } ++itmask; ++itimage; } typename ImageType::IndexType index; index[0] = lowersize[0]; index[1] = lowersize[1]; index[2] = lowersize[2]; typename ImageType::SizeType size; size[0] = uppersize[0] - lowersize[0] + 1; size[1] = uppersize[1] - lowersize[1] + 1; size[2] = uppersize[2] - lowersize[2] + 1; itk::ImageRegion<3> cropRegion = itk::ImageRegion<3>(index, size); // crop internal mask typedef itk::RegionOfInterestImageFilter< itkUCharImageType, itkUCharImageType > ROIMaskFilterType; typename ROIMaskFilterType::Pointer roi2 = ROIMaskFilterType::New(); roi2->SetRegionOfInterest(cropRegion); roi2->SetInput(m_InternalImageMask3D); roi2->Update(); m_InternalImageMask3D = roi2->GetOutput(); Image::Pointer tmpImage = Image::New(); tmpImage->InitializeByItk(m_InternalImageMask3D.GetPointer()); tmpImage->SetVolume(m_InternalImageMask3D->GetBufferPointer()); Image::Pointer tmpImage2 = Image::New(); tmpImage2->InitializeByItk(m_PlanarFigureImage.GetPointer()); const Geometry3D *pfImageGeometry3D = tmpImage2->GetGeometry( 0 ); const Geometry3D *intImageGeometry3D = tmpImage->GetGeometry( 0 ); typedef itk::ImageRegionIteratorWithIndex IteratorType; IteratorType imageIterator (m_InternalImageMask3D, m_InternalImageMask3D->GetRequestedRegion()); imageIterator.GoToBegin(); while ( !imageIterator.IsAtEnd() ) { unsigned char val = imageIterator.Value(); if (val>0) { itk::Index<3> index = imageIterator.GetIndex(); Point3D point; point[0] = index[0]; point[1] = index[1]; point[2] = index[2]; intImageGeometry3D->IndexToWorld(point, point); pfImageGeometry3D->WorldToIndex(point, point); point[i0] += 0.5; point[i1] += 0.5; index[0] = point[0]; index[1] = point[1]; index[2] = point[2]; if (pfImageGeometry3D->IsIndexInside(index)) m_PlanarFigureImage->SetPixel(index, 1); } ++imageIterator; } // Clean up VTK objects polyline->Delete(); extrudeFilter->Delete(); polyDataToImageStencil->Delete(); vtkImporter->Delete(); imageStencilFilter->Delete(); //vtkExporter->Delete(); // TODO: crashes when outcommented; memory leak?? delete[] ptIds; } void QmitkFiberExtractionView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkFiberExtractionView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkFiberExtractionView::UpdateGui() { m_Controls->m_Extract3dButton->setEnabled(false); m_Controls->m_ExtractMask->setEnabled(false); m_Controls->m_RemoveOutsideMaskButton->setEnabled(false); m_Controls->m_RemoveInsideMaskButton->setEnabled(false); // are fiber bundles selected? if ( m_SelectedFB.empty() ) { m_Controls->m_InputData->setTitle("Please Select Input Data"); m_Controls->m_JoinBundles->setEnabled(false); m_Controls->m_SubstractBundles->setEnabled(false); m_Controls->doExtractFibersButton->setEnabled(false); m_Controls->m_PlanarFigureButtonsFrame->setEnabled(false); } else { m_Controls->m_InputData->setTitle("Input Data"); m_Controls->m_PlanarFigureButtonsFrame->setEnabled(true); // one bundle and one planar figure needed to extract fibers if (!m_SelectedPF.empty()) m_Controls->doExtractFibersButton->setEnabled(true); // more than two bundles needed to join/subtract if (m_SelectedFB.size() > 1) { m_Controls->m_JoinBundles->setEnabled(true); m_Controls->m_SubstractBundles->setEnabled(true); } else { m_Controls->m_JoinBundles->setEnabled(false); m_Controls->m_SubstractBundles->setEnabled(false); } if (m_MaskImageNode.IsNotNull()) { m_Controls->m_Extract3dButton->setEnabled(true); m_Controls->m_ExtractMask->setEnabled(true); m_Controls->m_RemoveOutsideMaskButton->setEnabled(true); m_Controls->m_RemoveInsideMaskButton->setEnabled(true); } } // are planar figures selected? if ( m_SelectedPF.empty() ) { m_Controls->doExtractFibersButton->setEnabled(false); m_Controls->PFCompoANDButton->setEnabled(false); m_Controls->PFCompoORButton->setEnabled(false); m_Controls->PFCompoNOTButton->setEnabled(false); m_Controls->m_GenerateRoiImage->setEnabled(false); } else { if ( !m_SelectedFB.empty() ) m_Controls->m_GenerateRoiImage->setEnabled(true); else m_Controls->m_GenerateRoiImage->setEnabled(false); if (m_SelectedPF.size() > 1) { m_Controls->PFCompoANDButton->setEnabled(true); m_Controls->PFCompoORButton->setEnabled(true); m_Controls->PFCompoNOTButton->setEnabled(false); } else { m_Controls->PFCompoANDButton->setEnabled(false); m_Controls->PFCompoORButton->setEnabled(false); m_Controls->PFCompoNOTButton->setEnabled(true); } } } void QmitkFiberExtractionView::OnSelectionChanged( std::vector nodes ) { //reset existing Vectors containing FiberBundles and PlanarFigures from a previous selection m_SelectedFB.clear(); m_SelectedPF.clear(); m_SelectedSurfaces.clear(); m_SelectedImage = NULL; m_MaskImageNode = NULL; m_Controls->m_FibLabel->setText("mandatory"); m_Controls->m_PfLabel->setText("needed for extraction"); for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if ( dynamic_cast(node->GetData()) ) { m_Controls->m_FibLabel->setText(node->GetName().c_str()); m_SelectedFB.push_back(node); } else if (dynamic_cast(node->GetData())) { m_Controls->m_PfLabel->setText(node->GetName().c_str()); m_SelectedPF.push_back(node); } else if (dynamic_cast(node->GetData())) { m_SelectedImage = dynamic_cast(node->GetData()); bool isBinary = false; node->GetPropertyValue("binary", isBinary); if (isBinary) { m_MaskImageNode = node; m_Controls->m_PfLabel->setText(node->GetName().c_str()); } } else if (dynamic_cast(node->GetData())) { m_Controls->m_PfLabel->setText(node->GetName().c_str()); m_SelectedSurfaces.push_back(dynamic_cast(node->GetData())); } } UpdateGui(); GenerateStats(); } void QmitkFiberExtractionView::OnDrawPolygon() { // bool checked = m_Controls->m_PolygonButton->isChecked(); // if(!this->AssertDrawingIsPossible(checked)) // return; mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOn(); this->AddFigureToDataStorage(figure, QString("Polygon%1").arg(++m_PolygonCounter)); MITK_DEBUG << "PlanarPolygon created ..."; mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figureP = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figureP = dynamic_cast(node->GetData()); if(figureP) { figureInteractor = dynamic_cast(node->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); - mitk::Module* planarFigureModule = mitk::ModuleRegistry::GetModule( "PlanarFigure" ); + us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "PlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( node ); } } } } void QmitkFiberExtractionView::OnDrawCircle() { mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); this->AddFigureToDataStorage(figure, QString("Circle%1").arg(++m_CircleCounter)); this->GetDataStorage()->Modified(); mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figureP = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End(); it++) { node = const_cast(it->Value().GetPointer()); figureP = dynamic_cast(node->GetData()); if(figureP) { figureInteractor = dynamic_cast(node->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); - mitk::Module* planarFigureModule = mitk::ModuleRegistry::GetModule( "PlanarFigure" ); + us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "PlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( node ); } } } } void QmitkFiberExtractionView::Activated() { } void QmitkFiberExtractionView::AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey, mitk::BaseProperty *property ) { // initialize figure's geometry with empty geometry mitk::PlaneGeometry::Pointer emptygeometry = mitk::PlaneGeometry::New(); figure->SetGeometry2D( emptygeometry ); //set desired data to DataNode where Planarfigure is stored mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(name.toStdString()); newNode->SetData(figure); newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,0.0,0.0)); newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(2.0)); newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true)); newNode->AddProperty( "selected", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.ishovering", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.drawoutline", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.drawquantities", mitk::BoolProperty::New(false) ); newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(3.0) ); newNode->AddProperty( "planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.outline.width", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.helperline.width", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); newNode->AddProperty( "planarfigure.default.line.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.outline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.helperline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(0.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); newNode->AddProperty( "planarfigure.default.marker.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.line.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.outline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.helperline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.marker.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.line.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.outline.opacity", mitk::FloatProperty::New(2.0)); newNode->AddProperty( "planarfigure.selected.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.helperline.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.marker.opacity",mitk::FloatProperty::New(2.0)); // figure drawn on the topmost layer / image newNode->SetColor(1.0,1.0,1.0); newNode->SetOpacity(0.8); GetDataStorage()->Add(newNode ); std::vector selectedNodes = GetDataManagerSelection(); for(unsigned int i = 0; i < selectedNodes.size(); i++) { selectedNodes[i]->SetSelected(false); } newNode->SetSelected(true); } void QmitkFiberExtractionView::DoFiberExtraction() { if ( m_SelectedFB.empty() ){ QMessageBox::information( NULL, "Warning", "No fibe bundle selected!"); MITK_WARN("QmitkFiberExtractionView") << "no fibe bundle selected"; return; } for (int i=0; i(m_SelectedFB.at(i)->GetData()); mitk::PlanarFigure::Pointer roi = dynamic_cast (m_SelectedPF.at(0)->GetData()); mitk::FiberBundleX::Pointer extFB = fib->ExtractFiberSubset(roi); if (extFB->GetNumFibers()<=0) { QMessageBox::information(NULL, "No output generated:", "The resulting fiber bundle contains no fibers."); continue; } mitk::DataNode::Pointer node; node = mitk::DataNode::New(); node->SetData(extFB); QString name(m_SelectedFB.at(i)->GetName().c_str()); name += "_"; name += m_SelectedPF.at(0)->GetName().c_str(); node->SetName(name.toStdString()); GetDataStorage()->Add(node); m_SelectedFB.at(i)->SetVisibility(false); } } void QmitkFiberExtractionView::GenerateAndComposite() { mitk::PlanarFigureComposite::Pointer PFCAnd = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCAnd->SetGeometry2D(currentGeometry2D); PFCAnd->setOperationType(mitk::PFCOMPOSITION_AND_OPERATION); for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCAnd->addPlanarFigure( tmpPF ); PFCAnd->addDataNode( nodePF ); PFCAnd->setDisplayName("AND_COMPO"); } AddCompositeToDatastorage(PFCAnd, NULL); } void QmitkFiberExtractionView::GenerateOrComposite() { mitk::PlanarFigureComposite::Pointer PFCOr = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCOr->SetGeometry2D(currentGeometry2D); PFCOr->setOperationType(mitk::PFCOMPOSITION_OR_OPERATION); for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCOr->addPlanarFigure( tmpPF ); PFCOr->addDataNode( nodePF ); PFCOr->setDisplayName("OR_COMPO"); } AddCompositeToDatastorage(PFCOr, NULL); } void QmitkFiberExtractionView::GenerateNotComposite() { mitk::PlanarFigureComposite::Pointer PFCNot = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCNot->SetGeometry2D(currentGeometry2D); PFCNot->setOperationType(mitk::PFCOMPOSITION_NOT_OPERATION); for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCNot->addPlanarFigure( tmpPF ); PFCNot->addDataNode( nodePF ); PFCNot->setDisplayName("NOT_COMPO"); } AddCompositeToDatastorage(PFCNot, NULL); } /* CLEANUP NEEDED */ void QmitkFiberExtractionView::AddCompositeToDatastorage(mitk::PlanarFigureComposite::Pointer pfcomp, mitk::DataNode::Pointer parentDataNode ) { mitk::DataNode::Pointer newPFCNode; newPFCNode = mitk::DataNode::New(); newPFCNode->SetName( pfcomp->getDisplayName() ); newPFCNode->SetData(pfcomp); newPFCNode->SetVisibility(true); switch (pfcomp->getOperationType()) { case 0: { if (!parentDataNode.IsNull()) { GetDataStorage()->Add(newPFCNode, parentDataNode); } else { GetDataStorage()->Add(newPFCNode); } //iterate through its childs for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) { // child is of type planar Figure composite // make new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_DEBUG << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " still exists"; } } else { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; } else { MITK_DEBUG << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " still exists"; } MITK_DEBUG << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); } } GetDataStorage()->Modified(); break; } case 1: { if (!parentDataNode.IsNull()) { MITK_DEBUG << "adding " << newPFCNode->GetName() << " to " << parentDataNode->GetName() ; GetDataStorage()->Add(newPFCNode, parentDataNode); } else { MITK_DEBUG << "adding " << newPFCNode->GetName(); GetDataStorage()->Add(newPFCNode); } for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) { // child is of type planar Figure composite // make new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_DEBUG << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " still exists"; } } else { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_DEBUG << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " still exists"; } MITK_DEBUG << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); } } GetDataStorage()->Modified(); break; } case 2: { if (!parentDataNode.IsNull()) { MITK_DEBUG << "adding " << newPFCNode->GetName() << " to " << parentDataNode->GetName() ; GetDataStorage()->Add(newPFCNode, parentDataNode); } else { MITK_DEBUG << "adding " << newPFCNode->GetName(); GetDataStorage()->Add(newPFCNode); } //iterate through its childs for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) { // child is of type planar Figure composite // makeRemoveBundle new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_DEBUG << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " still exists"; } } else { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_DEBUG << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_DEBUG << savedPFchildNode->GetName() << " still exists"; } MITK_DEBUG << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); } } GetDataStorage()->Modified(); break; } default: MITK_DEBUG << "we have an UNDEFINED composition... ERROR" ; break; } } void QmitkFiberExtractionView::JoinBundles() { if ( m_SelectedFB.size()<2 ){ QMessageBox::information( NULL, "Warning", "Select at least two fiber bundles!"); MITK_WARN("QmitkFiberExtractionView") << "Select at least two fiber bundles!"; return; } mitk::FiberBundleX::Pointer newBundle = dynamic_cast(m_SelectedFB.at(0)->GetData()); m_SelectedFB.at(0)->SetVisibility(false); QString name(""); name += QString(m_SelectedFB.at(0)->GetName().c_str()); for (int i=1; iAddBundle(dynamic_cast(m_SelectedFB.at(i)->GetData())); name += "+"+QString(m_SelectedFB.at(i)->GetName().c_str()); m_SelectedFB.at(i)->SetVisibility(false); } mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); } void QmitkFiberExtractionView::SubstractBundles() { if ( m_SelectedFB.size()<2 ){ QMessageBox::information( NULL, "Warning", "Select at least two fiber bundles!"); MITK_WARN("QmitkFiberExtractionView") << "Select at least two fiber bundles!"; return; } mitk::FiberBundleX::Pointer newBundle = dynamic_cast(m_SelectedFB.at(0)->GetData()); m_SelectedFB.at(0)->SetVisibility(false); QString name(""); name += QString(m_SelectedFB.at(0)->GetName().c_str()); for (int i=1; iSubtractBundle(dynamic_cast(m_SelectedFB.at(i)->GetData())); if (newBundle.IsNull()) break; name += "-"+QString(m_SelectedFB.at(i)->GetName().c_str()); m_SelectedFB.at(i)->SetVisibility(false); } if (newBundle.IsNull()) { QMessageBox::information(NULL, "No output generated:", "The resulting fiber bundle contains no fibers. Did you select the fiber bundles in the correct order? X-Y is not equal to Y-X!"); return; } mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); } void QmitkFiberExtractionView::GenerateStats() { if ( m_SelectedFB.empty() ) return; QString stats(""); for( int i=0; i(node->GetData())) { if (i>0) stats += "\n-----------------------------\n"; stats += QString(node->GetName().c_str()) + "\n"; mitk::FiberBundleX::Pointer fib = dynamic_cast(node->GetData()); stats += "Number of fibers: "+ QString::number(fib->GetNumFibers()) + "\n"; stats += "Min. length: "+ QString::number(fib->GetMinFiberLength(),'f',1) + " mm\n"; stats += "Max. length: "+ QString::number(fib->GetMaxFiberLength(),'f',1) + " mm\n"; stats += "Mean length: "+ QString::number(fib->GetMeanFiberLength(),'f',1) + " mm\n"; stats += "Median length: "+ QString::number(fib->GetMedianFiberLength(),'f',1) + " mm\n"; stats += "Standard deviation: "+ QString::number(fib->GetLengthStDev(),'f',1) + " mm\n"; } } this->m_Controls->m_StatsTextEdit->setText(stats); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberfoxView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberfoxView.cpp index 0f670aa990..67a4c2d71a 100755 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberfoxView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberfoxView.cpp @@ -1,1991 +1,1991 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //misc #define _USE_MATH_DEFINES #include // Blueberry #include #include // Qmitk #include "QmitkFiberfoxView.h" // MITK #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include "mitkModuleRegistry.h" +#include "usModuleRegistry.h" #define _USE_MATH_DEFINES #include const std::string QmitkFiberfoxView::VIEW_ID = "org.mitk.views.fiberfoxview"; QmitkFiberfoxView::QmitkFiberfoxView() : QmitkAbstractView() , m_Controls( 0 ) , m_SelectedImage( NULL ) { } // Destructor QmitkFiberfoxView::~QmitkFiberfoxView() { } void QmitkFiberfoxView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkFiberfoxViewControls; m_Controls->setupUi( parent ); m_Controls->m_StickWidget1->setVisible(true); m_Controls->m_StickWidget2->setVisible(false); m_Controls->m_ZeppelinWidget1->setVisible(false); m_Controls->m_ZeppelinWidget2->setVisible(false); m_Controls->m_TensorWidget1->setVisible(false); m_Controls->m_TensorWidget2->setVisible(false); m_Controls->m_BallWidget1->setVisible(true); m_Controls->m_BallWidget2->setVisible(false); m_Controls->m_AstrosticksWidget1->setVisible(false); m_Controls->m_AstrosticksWidget2->setVisible(false); m_Controls->m_DotWidget1->setVisible(false); m_Controls->m_DotWidget2->setVisible(false); m_Controls->m_Comp4FractionFrame->setVisible(false); m_Controls->m_DiffusionPropsMessage->setVisible(false); m_Controls->m_GeometryMessage->setVisible(false); m_Controls->m_AdvancedSignalOptionsFrame->setVisible(false); m_Controls->m_AdvancedFiberOptionsFrame->setVisible(false); m_Controls->m_VarianceBox->setVisible(false); m_Controls->m_GibbsRingingFrame->setVisible(false); m_Controls->m_NoiseFrame->setVisible(false); m_Controls->m_GhostFrame->setVisible(false); m_Controls->m_DistortionsFrame->setVisible(false); m_Controls->m_EddyFrame->setVisible(false); m_Controls->m_FrequencyMapBox->SetDataStorage(this->GetDataStorage()); mitk::TNodePredicateDataType::Pointer isMitkImage = mitk::TNodePredicateDataType::New(); mitk::NodePredicateDataType::Pointer isDwi = mitk::NodePredicateDataType::New("DiffusionImage"); mitk::NodePredicateDataType::Pointer isDti = mitk::NodePredicateDataType::New("TensorImage"); mitk::NodePredicateDataType::Pointer isQbi = mitk::NodePredicateDataType::New("QBallImage"); mitk::NodePredicateOr::Pointer isDiffusionImage = mitk::NodePredicateOr::New(isDwi, isDti); isDiffusionImage = mitk::NodePredicateOr::New(isDiffusionImage, isQbi); mitk::NodePredicateNot::Pointer noDiffusionImage = mitk::NodePredicateNot::New(isDiffusionImage); mitk::NodePredicateAnd::Pointer finalPredicate = mitk::NodePredicateAnd::New(isMitkImage, noDiffusionImage); m_Controls->m_FrequencyMapBox->SetPredicate(finalPredicate); connect((QObject*) m_Controls->m_GenerateImageButton, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateImage())); connect((QObject*) m_Controls->m_GenerateFibersButton, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateFibers())); connect((QObject*) m_Controls->m_CircleButton, SIGNAL(clicked()), (QObject*) this, SLOT(OnDrawROI())); connect((QObject*) m_Controls->m_FlipButton, SIGNAL(clicked()), (QObject*) this, SLOT(OnFlipButton())); connect((QObject*) m_Controls->m_JoinBundlesButton, SIGNAL(clicked()), (QObject*) this, SLOT(JoinBundles())); connect((QObject*) m_Controls->m_VarianceBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnVarianceChanged(double))); connect((QObject*) m_Controls->m_DistributionBox, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(OnDistributionChanged(int))); connect((QObject*) m_Controls->m_FiberDensityBox, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(OnFiberDensityChanged(int))); connect((QObject*) m_Controls->m_FiberSamplingBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnFiberSamplingChanged(double))); connect((QObject*) m_Controls->m_TensionBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnTensionChanged(double))); connect((QObject*) m_Controls->m_ContinuityBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnContinuityChanged(double))); connect((QObject*) m_Controls->m_BiasBox, SIGNAL(valueChanged(double)), (QObject*) this, SLOT(OnBiasChanged(double))); connect((QObject*) m_Controls->m_AddGibbsRinging, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddGibbsRinging(int))); connect((QObject*) m_Controls->m_AddNoise, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddNoise(int))); connect((QObject*) m_Controls->m_AddGhosts, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddGhosts(int))); connect((QObject*) m_Controls->m_AddDistortions, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddDistortions(int))); connect((QObject*) m_Controls->m_AddEddy, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnAddEddy(int))); connect((QObject*) m_Controls->m_ConstantRadiusBox, SIGNAL(stateChanged(int)), (QObject*) this, SLOT(OnConstantRadius(int))); connect((QObject*) m_Controls->m_CopyBundlesButton, SIGNAL(clicked()), (QObject*) this, SLOT(CopyBundles())); connect((QObject*) m_Controls->m_TransformBundlesButton, SIGNAL(clicked()), (QObject*) this, SLOT(ApplyTransform())); connect((QObject*) m_Controls->m_AlignOnGrid, SIGNAL(clicked()), (QObject*) this, SLOT(AlignOnGrid())); connect((QObject*) m_Controls->m_Compartment1Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp1ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment2Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp2ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment3Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp3ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_Compartment4Box, SIGNAL(currentIndexChanged(int)), (QObject*) this, SLOT(Comp4ModelFrameVisibility(int))); connect((QObject*) m_Controls->m_AdvancedOptionsBox, SIGNAL( stateChanged(int)), (QObject*) this, SLOT(ShowAdvancedOptions(int))); connect((QObject*) m_Controls->m_AdvancedOptionsBox_2, SIGNAL( stateChanged(int)), (QObject*) this, SLOT(ShowAdvancedOptions(int))); connect((QObject*) m_Controls->m_SaveParametersButton, SIGNAL(clicked()), (QObject*) this, SLOT(SaveParameters())); connect((QObject*) m_Controls->m_LoadParametersButton, SIGNAL(clicked()), (QObject*) this, SLOT(LoadParameters())); } } void QmitkFiberfoxView::UpdateImageParameters() { m_ImageGenParameters.artifactList.clear(); m_ImageGenParameters.nonFiberModelList.clear(); m_ImageGenParameters.fiberModelList.clear(); m_ImageGenParameters.signalModelString = ""; m_ImageGenParameters.artifactModelString = ""; m_ImageGenParameters.resultNode = mitk::DataNode::New(); m_ImageGenParameters.tissueMaskImage = NULL; m_ImageGenParameters.frequencyMap = NULL; m_ImageGenParameters.gradientDirections.clear(); if (m_SelectedDWI.IsNotNull()) // use parameters of selected DWI { mitk::DiffusionImage::Pointer dwi = dynamic_cast*>(m_SelectedDWI->GetData()); m_ImageGenParameters.imageRegion = dwi->GetVectorImage()->GetLargestPossibleRegion(); m_ImageGenParameters.imageSpacing = dwi->GetVectorImage()->GetSpacing(); m_ImageGenParameters.imageOrigin = dwi->GetVectorImage()->GetOrigin(); m_ImageGenParameters.imageDirection = dwi->GetVectorImage()->GetDirection(); m_ImageGenParameters.b_value = dwi->GetB_Value(); mitk::DiffusionImage::GradientDirectionContainerType::Pointer dirs = dwi->GetDirections(); m_ImageGenParameters.numGradients = 0; for (int i=0; iSize(); i++) { DiffusionSignalModel::GradientType g; g[0] = dirs->at(i)[0]; g[1] = dirs->at(i)[1]; g[2] = dirs->at(i)[2]; m_ImageGenParameters.gradientDirections.push_back(g); if (dirs->at(i).magnitude()>0.0001) m_ImageGenParameters.numGradients++; } } else if (m_SelectedImage.IsNotNull()) // use geometry of selected image { mitk::Image::Pointer img = dynamic_cast(m_SelectedImage->GetData()); itk::Image< float, 3 >::Pointer itkImg = itk::Image< float, 3 >::New(); CastToItkImage< itk::Image< float, 3 > >(img, itkImg); m_ImageGenParameters.imageRegion = itkImg->GetLargestPossibleRegion(); m_ImageGenParameters.imageSpacing = itkImg->GetSpacing(); m_ImageGenParameters.imageOrigin = itkImg->GetOrigin(); m_ImageGenParameters.imageDirection = itkImg->GetDirection(); m_ImageGenParameters.numGradients = m_Controls->m_NumGradientsBox->value(); m_ImageGenParameters.gradientDirections = GenerateHalfShell(m_Controls->m_NumGradientsBox->value()); m_ImageGenParameters.b_value = m_Controls->m_BvalueBox->value(); } else // use GUI parameters { m_ImageGenParameters.imageRegion.SetSize(0, m_Controls->m_SizeX->value()); m_ImageGenParameters.imageRegion.SetSize(1, m_Controls->m_SizeY->value()); m_ImageGenParameters.imageRegion.SetSize(2, m_Controls->m_SizeZ->value()); m_ImageGenParameters.imageSpacing[0] = m_Controls->m_SpacingX->value(); m_ImageGenParameters.imageSpacing[1] = m_Controls->m_SpacingY->value(); m_ImageGenParameters.imageSpacing[2] = m_Controls->m_SpacingZ->value(); m_ImageGenParameters.imageOrigin[0] = m_ImageGenParameters.imageSpacing[0]/2; m_ImageGenParameters.imageOrigin[1] = m_ImageGenParameters.imageSpacing[1]/2; m_ImageGenParameters.imageOrigin[2] = m_ImageGenParameters.imageSpacing[2]/2; m_ImageGenParameters.imageDirection.SetIdentity(); m_ImageGenParameters.numGradients = m_Controls->m_NumGradientsBox->value(); m_ImageGenParameters.gradientDirections = GenerateHalfShell(m_Controls->m_NumGradientsBox->value());; m_ImageGenParameters.b_value = m_Controls->m_BvalueBox->value(); } // signal relaxation m_ImageGenParameters.doSimulateRelaxation = m_Controls->m_RelaxationBox->isChecked(); if (m_ImageGenParameters.doSimulateRelaxation) m_ImageGenParameters.artifactModelString += "_RELAX"; // N/2 ghosts if (m_Controls->m_AddGhosts->isChecked()) { m_ImageGenParameters.artifactModelString += "_GHOST"; m_ImageGenParameters.kspaceLineOffset = m_Controls->m_kOffsetBox->value(); } else m_ImageGenParameters.kspaceLineOffset = 0; m_ImageGenParameters.tLine = m_Controls->m_LineReadoutTimeBox->value(); m_ImageGenParameters.tInhom = m_Controls->m_T2starBox->value(); m_ImageGenParameters.tEcho = m_Controls->m_TEbox->value(); m_ImageGenParameters.repetitions = m_Controls->m_RepetitionsBox->value(); m_ImageGenParameters.doDisablePartialVolume = m_Controls->m_EnforcePureFiberVoxelsBox->isChecked(); m_ImageGenParameters.interpolationShrink = m_Controls->m_InterpolationShrink->value(); m_ImageGenParameters.axonRadius = m_Controls->m_FiberRadius->value(); m_ImageGenParameters.signalScale = m_Controls->m_SignalScaleBox->value(); // adjust echo time if needed if ( m_ImageGenParameters.tEcho < m_ImageGenParameters.imageRegion.GetSize(1)*m_ImageGenParameters.tLine ) { this->m_Controls->m_TEbox->setValue( m_ImageGenParameters.imageRegion.GetSize(1)*m_ImageGenParameters.tLine ); m_ImageGenParameters.tEcho = m_Controls->m_TEbox->value(); QMessageBox::information( NULL, "Warning", "Echo time is too short! Time not sufficient to read slice. Automaticall adjusted to "+QString::number(m_ImageGenParameters.tEcho)+" ms"); } // check tissue mask if (m_TissueMask.IsNotNull()) { m_ImageGenParameters.tissueMaskImage = ItkUcharImgType::New(); mitk::CastToItkImage(m_TissueMask, m_ImageGenParameters.tissueMaskImage); } // rician noise if (m_Controls->m_AddNoise->isChecked()) { double noiseVariance = m_Controls->m_NoiseLevel->value(); m_ImageGenParameters.ricianNoiseModel.SetNoiseVariance(noiseVariance); m_ImageGenParameters.artifactModelString += "_NOISE"; m_ImageGenParameters.artifactModelString += QString::number(noiseVariance); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Noise-Variance", DoubleProperty::New(noiseVariance)); } else m_ImageGenParameters.ricianNoiseModel.SetNoiseVariance(0); // gibbs ringing m_ImageGenParameters.upsampling = 1; if (m_Controls->m_AddGibbsRinging->isChecked()) { m_ImageGenParameters.artifactModelString += "_RINGING"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Ringing-Upsampling", DoubleProperty::New(m_Controls->m_ImageUpsamplingBox->value())); m_ImageGenParameters.upsampling = m_Controls->m_ImageUpsamplingBox->value(); } // adjusting line readout time to the adapted image size needed for the DFT int y = m_ImageGenParameters.imageRegion.GetSize(1); if ( y%2 == 1 ) y += 1; if ( y>m_ImageGenParameters.imageRegion.GetSize(1) ) m_ImageGenParameters.tLine *= (double)m_ImageGenParameters.imageRegion.GetSize(1)/y; // add distortions if (m_Controls->m_AddDistortions->isChecked() && m_Controls->m_FrequencyMapBox->GetSelectedNode().IsNotNull()) { mitk::DataNode::Pointer fMapNode = m_Controls->m_FrequencyMapBox->GetSelectedNode(); mitk::Image* img = dynamic_cast(fMapNode->GetData()); ItkDoubleImgType::Pointer itkImg = ItkDoubleImgType::New(); CastToItkImage< ItkDoubleImgType >(img, itkImg); if (m_ImageGenParameters.imageRegion.GetSize(0)==itkImg->GetLargestPossibleRegion().GetSize(0) && m_ImageGenParameters.imageRegion.GetSize(1)==itkImg->GetLargestPossibleRegion().GetSize(1) && m_ImageGenParameters.imageRegion.GetSize(2)==itkImg->GetLargestPossibleRegion().GetSize(2)) { m_ImageGenParameters.frequencyMap = itkImg; m_ImageGenParameters.artifactModelString += "_DISTORTED"; } } m_ImageGenParameters.doSimulateEddyCurrents = m_Controls->m_AddEddy->isChecked(); m_ImageGenParameters.eddyStrength = 0; if (m_Controls->m_AddEddy->isChecked()) { m_ImageGenParameters.eddyStrength = m_Controls->m_EddyGradientStrength->value(); m_ImageGenParameters.artifactModelString += "_EDDY"; } // signal models m_ImageGenParameters.comp3Weight = 1; m_ImageGenParameters.comp4Weight = 0; if (m_Controls->m_Compartment4Box->currentIndex()>0) { m_ImageGenParameters.comp4Weight = m_Controls->m_Comp4FractionBox->value(); m_ImageGenParameters.comp3Weight -= m_ImageGenParameters.comp4Weight; } // compartment 1 switch (m_Controls->m_Compartment1Box->currentIndex()) { case 0: m_StickModel1.SetGradientList(m_ImageGenParameters.gradientDirections); m_StickModel1.SetBvalue(m_ImageGenParameters.b_value); m_StickModel1.SetDiffusivity(m_Controls->m_StickWidget1->GetD()); m_StickModel1.SetT2(m_Controls->m_StickWidget1->GetT2()); m_ImageGenParameters.fiberModelList.push_back(&m_StickModel1); m_ImageGenParameters.signalModelString += "Stick"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Stick") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.D", DoubleProperty::New(m_Controls->m_StickWidget1->GetD()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(m_StickModel1.GetT2()) ); break; case 1: m_ZeppelinModel1.SetGradientList(m_ImageGenParameters.gradientDirections); m_ZeppelinModel1.SetBvalue(m_ImageGenParameters.b_value); m_ZeppelinModel1.SetDiffusivity1(m_Controls->m_ZeppelinWidget1->GetD1()); m_ZeppelinModel1.SetDiffusivity2(m_Controls->m_ZeppelinWidget1->GetD2()); m_ZeppelinModel1.SetDiffusivity3(m_Controls->m_ZeppelinWidget1->GetD2()); m_ZeppelinModel1.SetT2(m_Controls->m_ZeppelinWidget1->GetT2()); m_ImageGenParameters.fiberModelList.push_back(&m_ZeppelinModel1); m_ImageGenParameters.signalModelString += "Zeppelin"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Zeppelin") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.D1", DoubleProperty::New(m_Controls->m_ZeppelinWidget1->GetD1()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.D2", DoubleProperty::New(m_Controls->m_ZeppelinWidget1->GetD2()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(m_ZeppelinModel1.GetT2()) ); break; case 2: m_TensorModel1.SetGradientList(m_ImageGenParameters.gradientDirections); m_TensorModel1.SetBvalue(m_ImageGenParameters.b_value); m_TensorModel1.SetDiffusivity1(m_Controls->m_TensorWidget1->GetD1()); m_TensorModel1.SetDiffusivity2(m_Controls->m_TensorWidget1->GetD2()); m_TensorModel1.SetDiffusivity3(m_Controls->m_TensorWidget1->GetD3()); m_TensorModel1.SetT2(m_Controls->m_TensorWidget1->GetT2()); m_ImageGenParameters.fiberModelList.push_back(&m_TensorModel1); m_ImageGenParameters.signalModelString += "Tensor"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.Description", StringProperty::New("Intra-axonal compartment") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.Model", StringProperty::New("Tensor") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.D1", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD1()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.D2", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD2()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.D3", DoubleProperty::New(m_Controls->m_TensorWidget1->GetD3()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment1.T2", DoubleProperty::New(m_ZeppelinModel1.GetT2()) ); break; } // compartment 2 switch (m_Controls->m_Compartment2Box->currentIndex()) { case 0: break; case 1: m_StickModel2.SetGradientList(m_ImageGenParameters.gradientDirections); m_StickModel2.SetBvalue(m_ImageGenParameters.b_value); m_StickModel2.SetDiffusivity(m_Controls->m_StickWidget2->GetD()); m_StickModel2.SetT2(m_Controls->m_StickWidget2->GetT2()); m_ImageGenParameters.fiberModelList.push_back(&m_StickModel2); m_ImageGenParameters.signalModelString += "Stick"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Stick") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.D", DoubleProperty::New(m_Controls->m_StickWidget2->GetD()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(m_StickModel2.GetT2()) ); break; case 2: m_ZeppelinModel2.SetGradientList(m_ImageGenParameters.gradientDirections); m_ZeppelinModel2.SetBvalue(m_ImageGenParameters.b_value); m_ZeppelinModel2.SetDiffusivity1(m_Controls->m_ZeppelinWidget2->GetD1()); m_ZeppelinModel2.SetDiffusivity2(m_Controls->m_ZeppelinWidget2->GetD2()); m_ZeppelinModel2.SetDiffusivity3(m_Controls->m_ZeppelinWidget2->GetD2()); m_ZeppelinModel2.SetT2(m_Controls->m_ZeppelinWidget2->GetT2()); m_ImageGenParameters.fiberModelList.push_back(&m_ZeppelinModel2); m_ImageGenParameters.signalModelString += "Zeppelin"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Zeppelin") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.D1", DoubleProperty::New(m_Controls->m_ZeppelinWidget2->GetD1()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.D2", DoubleProperty::New(m_Controls->m_ZeppelinWidget2->GetD2()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(m_ZeppelinModel2.GetT2()) ); break; case 3: m_TensorModel2.SetGradientList(m_ImageGenParameters.gradientDirections); m_TensorModel2.SetBvalue(m_ImageGenParameters.b_value); m_TensorModel2.SetDiffusivity1(m_Controls->m_TensorWidget2->GetD1()); m_TensorModel2.SetDiffusivity2(m_Controls->m_TensorWidget2->GetD2()); m_TensorModel2.SetDiffusivity3(m_Controls->m_TensorWidget2->GetD3()); m_TensorModel2.SetT2(m_Controls->m_TensorWidget2->GetT2()); m_ImageGenParameters.fiberModelList.push_back(&m_TensorModel2); m_ImageGenParameters.signalModelString += "Tensor"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.Description", StringProperty::New("Inter-axonal compartment") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.Model", StringProperty::New("Tensor") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.D1", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD1()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.D2", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD2()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.D3", DoubleProperty::New(m_Controls->m_TensorWidget2->GetD3()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment2.T2", DoubleProperty::New(m_ZeppelinModel2.GetT2()) ); break; } // compartment 3 switch (m_Controls->m_Compartment3Box->currentIndex()) { case 0: m_BallModel1.SetGradientList(m_ImageGenParameters.gradientDirections); m_BallModel1.SetBvalue(m_ImageGenParameters.b_value); m_BallModel1.SetDiffusivity(m_Controls->m_BallWidget1->GetD()); m_BallModel1.SetT2(m_Controls->m_BallWidget1->GetT2()); m_BallModel1.SetWeight(m_ImageGenParameters.comp3Weight); m_ImageGenParameters.nonFiberModelList.push_back(&m_BallModel1); m_ImageGenParameters.signalModelString += "Ball"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Ball") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.D", DoubleProperty::New(m_Controls->m_BallWidget1->GetD()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(m_BallModel1.GetT2()) ); break; case 1: m_AstrosticksModel1.SetGradientList(m_ImageGenParameters.gradientDirections); m_AstrosticksModel1.SetBvalue(m_ImageGenParameters.b_value); m_AstrosticksModel1.SetDiffusivity(m_Controls->m_AstrosticksWidget1->GetD()); m_AstrosticksModel1.SetT2(m_Controls->m_AstrosticksWidget1->GetT2()); m_AstrosticksModel1.SetRandomizeSticks(m_Controls->m_AstrosticksWidget1->GetRandomizeSticks()); m_AstrosticksModel1.SetWeight(m_ImageGenParameters.comp3Weight); m_ImageGenParameters.nonFiberModelList.push_back(&m_AstrosticksModel1); m_ImageGenParameters.signalModelString += "Astrosticks"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Astrosticks") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.D", DoubleProperty::New(m_Controls->m_AstrosticksWidget1->GetD()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(m_AstrosticksModel1.GetT2()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.RandomSticks", BoolProperty::New(m_Controls->m_AstrosticksWidget1->GetRandomizeSticks()) ); break; case 2: m_DotModel1.SetGradientList(m_ImageGenParameters.gradientDirections); m_DotModel1.SetT2(m_Controls->m_DotWidget1->GetT2()); m_DotModel1.SetWeight(m_ImageGenParameters.comp3Weight); m_ImageGenParameters.nonFiberModelList.push_back(&m_DotModel1); m_ImageGenParameters.signalModelString += "Dot"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.Description", StringProperty::New("Extra-axonal compartment 1") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.Model", StringProperty::New("Dot") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment3.T2", DoubleProperty::New(m_DotModel1.GetT2()) ); break; } // compartment 4 switch (m_Controls->m_Compartment4Box->currentIndex()) { case 0: break; case 1: m_BallModel2.SetGradientList(m_ImageGenParameters.gradientDirections); m_BallModel2.SetBvalue(m_ImageGenParameters.b_value); m_BallModel2.SetDiffusivity(m_Controls->m_BallWidget2->GetD()); m_BallModel2.SetT2(m_Controls->m_BallWidget2->GetT2()); m_BallModel2.SetWeight(m_ImageGenParameters.comp4Weight); m_ImageGenParameters.nonFiberModelList.push_back(&m_BallModel2); m_ImageGenParameters.signalModelString += "Ball"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Ball") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.D", DoubleProperty::New(m_Controls->m_BallWidget2->GetD()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(m_BallModel2.GetT2()) ); break; case 2: m_AstrosticksModel2.SetGradientList(m_ImageGenParameters.gradientDirections); m_AstrosticksModel2.SetBvalue(m_ImageGenParameters.b_value); m_AstrosticksModel2.SetDiffusivity(m_Controls->m_AstrosticksWidget2->GetD()); m_AstrosticksModel2.SetT2(m_Controls->m_AstrosticksWidget2->GetT2()); m_AstrosticksModel2.SetRandomizeSticks(m_Controls->m_AstrosticksWidget2->GetRandomizeSticks()); m_AstrosticksModel2.SetWeight(m_ImageGenParameters.comp4Weight); m_ImageGenParameters.nonFiberModelList.push_back(&m_AstrosticksModel2); m_ImageGenParameters.signalModelString += "Astrosticks"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Astrosticks") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.D", DoubleProperty::New(m_Controls->m_AstrosticksWidget2->GetD()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(m_AstrosticksModel2.GetT2()) ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.RandomSticks", BoolProperty::New(m_Controls->m_AstrosticksWidget2->GetRandomizeSticks()) ); break; case 3: m_DotModel2.SetGradientList(m_ImageGenParameters.gradientDirections); m_DotModel2.SetT2(m_Controls->m_DotWidget2->GetT2()); m_DotModel2.SetWeight(m_ImageGenParameters.comp4Weight); m_ImageGenParameters.nonFiberModelList.push_back(&m_DotModel2); m_ImageGenParameters.signalModelString += "Dot"; m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.Description", StringProperty::New("Extra-axonal compartment 2") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.Model", StringProperty::New("Dot") ); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Compartment4.T2", DoubleProperty::New(m_DotModel2.GetT2()) ); break; } m_ImageGenParameters.resultNode->AddProperty("Fiberfox.InterpolationShrink", IntProperty::New(m_ImageGenParameters.interpolationShrink)); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.SignalScale", IntProperty::New(m_ImageGenParameters.signalScale)); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.FiberRadius", IntProperty::New(m_ImageGenParameters.axonRadius)); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Tinhom", IntProperty::New(m_ImageGenParameters.tInhom)); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Repetitions", IntProperty::New(m_ImageGenParameters.repetitions)); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.b-value", DoubleProperty::New(m_ImageGenParameters.b_value)); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.Model", StringProperty::New(m_ImageGenParameters.signalModelString.toStdString())); m_ImageGenParameters.resultNode->AddProperty("Fiberfox.PureFiberVoxels", BoolProperty::New(m_ImageGenParameters.doDisablePartialVolume)); m_ImageGenParameters.resultNode->AddProperty("binary", BoolProperty::New(false)); } void QmitkFiberfoxView::SaveParameters() { UpdateImageParameters(); QString filename = QFileDialog::getSaveFileName( 0, tr("Save Parameters"), QDir::currentPath()+"/param.ffp", tr("Fiberfox Parameters (*.ffp)") ); if(filename.isEmpty() || filename.isNull()) return; if(!filename.endsWith(".ffp")) filename += ".ffp"; boost::property_tree::ptree parameters; // fiber generation parameters parameters.put("fiberfox.fibers.realtime", m_Controls->m_RealTimeFibers->isChecked()); parameters.put("fiberfox.fibers.showadvanced", m_Controls->m_AdvancedOptionsBox->isChecked()); parameters.put("fiberfox.fibers.distribution", m_Controls->m_DistributionBox->currentIndex()); parameters.put("fiberfox.fibers.variance", m_Controls->m_VarianceBox->value()); parameters.put("fiberfox.fibers.density", m_Controls->m_FiberDensityBox->value()); parameters.put("fiberfox.fibers.spline.sampling", m_Controls->m_FiberSamplingBox->value()); parameters.put("fiberfox.fibers.spline.tension", m_Controls->m_TensionBox->value()); parameters.put("fiberfox.fibers.spline.continuity", m_Controls->m_ContinuityBox->value()); parameters.put("fiberfox.fibers.spline.bias", m_Controls->m_BiasBox->value()); parameters.put("fiberfox.fibers.constantradius", m_Controls->m_ConstantRadiusBox->isChecked()); parameters.put("fiberfox.fibers.rotation.x", m_Controls->m_XrotBox->value()); parameters.put("fiberfox.fibers.rotation.y", m_Controls->m_YrotBox->value()); parameters.put("fiberfox.fibers.rotation.z", m_Controls->m_ZrotBox->value()); parameters.put("fiberfox.fibers.translation.x", m_Controls->m_XtransBox->value()); parameters.put("fiberfox.fibers.translation.y", m_Controls->m_YtransBox->value()); parameters.put("fiberfox.fibers.translation.z", m_Controls->m_ZtransBox->value()); parameters.put("fiberfox.fibers.scale.x", m_Controls->m_XscaleBox->value()); parameters.put("fiberfox.fibers.scale.y", m_Controls->m_YscaleBox->value()); parameters.put("fiberfox.fibers.scale.z", m_Controls->m_ZscaleBox->value()); parameters.put("fiberfox.fibers.includeFiducials", m_Controls->m_IncludeFiducials->isChecked()); parameters.put("fiberfox.fibers.includeFiducials", m_Controls->m_IncludeFiducials->isChecked()); // image generation parameters parameters.put("fiberfox.image.basic.size.x", m_ImageGenParameters.imageRegion.GetSize(0)); parameters.put("fiberfox.image.basic.size.y", m_ImageGenParameters.imageRegion.GetSize(1)); parameters.put("fiberfox.image.basic.size.z", m_ImageGenParameters.imageRegion.GetSize(2)); parameters.put("fiberfox.image.basic.spacing.x", m_ImageGenParameters.imageSpacing[0]); parameters.put("fiberfox.image.basic.spacing.y", m_ImageGenParameters.imageSpacing[1]); parameters.put("fiberfox.image.basic.spacing.z", m_ImageGenParameters.imageSpacing[2]); parameters.put("fiberfox.image.basic.numgradients", m_ImageGenParameters.numGradients); parameters.put("fiberfox.image.basic.bvalue", m_ImageGenParameters.b_value); parameters.put("fiberfox.image.showadvanced", m_Controls->m_AdvancedOptionsBox_2->isChecked()); parameters.put("fiberfox.image.repetitions", m_ImageGenParameters.repetitions); parameters.put("fiberfox.image.signalScale", m_ImageGenParameters.signalScale); parameters.put("fiberfox.image.tEcho", m_ImageGenParameters.tEcho); parameters.put("fiberfox.image.tLine", m_Controls->m_LineReadoutTimeBox->value()); parameters.put("fiberfox.image.tInhom", m_ImageGenParameters.tInhom); parameters.put("fiberfox.image.axonRadius", m_ImageGenParameters.axonRadius); parameters.put("fiberfox.image.interpolationShrink", m_ImageGenParameters.interpolationShrink); parameters.put("fiberfox.image.doSimulateRelaxation", m_ImageGenParameters.doSimulateRelaxation); parameters.put("fiberfox.image.doDisablePartialVolume", m_ImageGenParameters.doDisablePartialVolume); parameters.put("fiberfox.image.outputvolumefractions", m_Controls->m_VolumeFractionsBox->isChecked()); parameters.put("fiberfox.image.artifacts.addnoise", m_Controls->m_AddNoise->isChecked()); parameters.put("fiberfox.image.artifacts.noisevariance", m_Controls->m_NoiseLevel->value()); parameters.put("fiberfox.image.artifacts.addghost", m_Controls->m_AddGhosts->isChecked()); parameters.put("fiberfox.image.artifacts.kspaceLineOffset", m_Controls->m_kOffsetBox->value()); parameters.put("fiberfox.image.artifacts.distortions", m_Controls->m_AddDistortions->isChecked()); parameters.put("fiberfox.image.artifacts.addeddy", m_Controls->m_AddEddy->isChecked()); parameters.put("fiberfox.image.artifacts.eddyStrength", m_Controls->m_EddyGradientStrength->value()); parameters.put("fiberfox.image.artifacts.addringing", m_Controls->m_AddGibbsRinging->isChecked()); parameters.put("fiberfox.image.artifacts.ringingupsampling", m_Controls->m_ImageUpsamplingBox->value()); parameters.put("fiberfox.image.compartment1.index", m_Controls->m_Compartment1Box->currentIndex()); parameters.put("fiberfox.image.compartment2.index", m_Controls->m_Compartment2Box->currentIndex()); parameters.put("fiberfox.image.compartment3.index", m_Controls->m_Compartment3Box->currentIndex()); parameters.put("fiberfox.image.compartment4.index", m_Controls->m_Compartment4Box->currentIndex()); parameters.put("fiberfox.image.compartment1.stick.d", m_Controls->m_StickWidget1->GetD()); parameters.put("fiberfox.image.compartment1.stick.t2", m_Controls->m_StickWidget1->GetT2()); parameters.put("fiberfox.image.compartment1.zeppelin.d1", m_Controls->m_ZeppelinWidget1->GetD1()); parameters.put("fiberfox.image.compartment1.zeppelin.d2", m_Controls->m_ZeppelinWidget1->GetD2()); parameters.put("fiberfox.image.compartment1.zeppelin.t2", m_Controls->m_ZeppelinWidget1->GetT2()); parameters.put("fiberfox.image.compartment1.tensor.d1", m_Controls->m_TensorWidget1->GetD1()); parameters.put("fiberfox.image.compartment1.tensor.d2", m_Controls->m_TensorWidget1->GetD2()); parameters.put("fiberfox.image.compartment1.tensor.d3", m_Controls->m_TensorWidget1->GetD3()); parameters.put("fiberfox.image.compartment1.tensor.t2", m_Controls->m_TensorWidget1->GetT2()); parameters.put("fiberfox.image.compartment2.stick.d", m_Controls->m_StickWidget2->GetD()); parameters.put("fiberfox.image.compartment2.stick.t2", m_Controls->m_StickWidget2->GetT2()); parameters.put("fiberfox.image.compartment2.zeppelin.d1", m_Controls->m_ZeppelinWidget2->GetD1()); parameters.put("fiberfox.image.compartment2.zeppelin.d2", m_Controls->m_ZeppelinWidget2->GetD2()); parameters.put("fiberfox.image.compartment2.zeppelin.t2", m_Controls->m_ZeppelinWidget2->GetT2()); parameters.put("fiberfox.image.compartment2.tensor.d1", m_Controls->m_TensorWidget2->GetD1()); parameters.put("fiberfox.image.compartment2.tensor.d2", m_Controls->m_TensorWidget2->GetD2()); parameters.put("fiberfox.image.compartment2.tensor.d3", m_Controls->m_TensorWidget2->GetD3()); parameters.put("fiberfox.image.compartment2.tensor.t2", m_Controls->m_TensorWidget2->GetT2()); parameters.put("fiberfox.image.compartment3.ball.d", m_Controls->m_BallWidget1->GetD()); parameters.put("fiberfox.image.compartment3.ball.t2", m_Controls->m_BallWidget1->GetT2()); parameters.put("fiberfox.image.compartment3.astrosticks.d", m_Controls->m_AstrosticksWidget1->GetD()); parameters.put("fiberfox.image.compartment3.astrosticks.t2", m_Controls->m_AstrosticksWidget1->GetT2()); parameters.put("fiberfox.image.compartment3.astrosticks.randomize", m_Controls->m_AstrosticksWidget1->GetRandomizeSticks()); parameters.put("fiberfox.image.compartment3.dot.t2", m_Controls->m_DotWidget1->GetT2()); parameters.put("fiberfox.image.compartment4.ball.d", m_Controls->m_BallWidget2->GetD()); parameters.put("fiberfox.image.compartment4.ball.t2", m_Controls->m_BallWidget2->GetT2()); parameters.put("fiberfox.image.compartment4.astrosticks.d", m_Controls->m_AstrosticksWidget2->GetD()); parameters.put("fiberfox.image.compartment4.astrosticks.t2", m_Controls->m_AstrosticksWidget2->GetT2()); parameters.put("fiberfox.image.compartment4.astrosticks.randomize", m_Controls->m_AstrosticksWidget2->GetRandomizeSticks()); parameters.put("fiberfox.image.compartment4.dot.t2", m_Controls->m_DotWidget2->GetT2()); parameters.put("fiberfox.image.compartment4.weight", m_Controls->m_Comp4FractionBox->value()); boost::property_tree::xml_parser::write_xml(filename.toStdString(), parameters); } void QmitkFiberfoxView::LoadParameters() { QString filename = QFileDialog::getOpenFileName(0, tr("Load Parameters"), QDir::currentPath(), tr("Fiberfox Parameters (*.ffp)") ); if(filename.isEmpty() || filename.isNull()) return; boost::property_tree::ptree parameters; boost::property_tree::xml_parser::read_xml(filename.toStdString(), parameters); BOOST_FOREACH( boost::property_tree::ptree::value_type const& v1, parameters.get_child("fiberfox") ) { if( v1.first == "fibers" ) { m_Controls->m_RealTimeFibers->setChecked(v1.second.get("realtime")); m_Controls->m_AdvancedOptionsBox->setChecked(v1.second.get("showadvanced")); m_Controls->m_DistributionBox->setCurrentIndex(v1.second.get("distribution")); m_Controls->m_VarianceBox->setValue(v1.second.get("variance")); m_Controls->m_FiberDensityBox->setValue(v1.second.get("density")); m_Controls->m_IncludeFiducials->setChecked(v1.second.get("includeFiducials")); m_Controls->m_ConstantRadiusBox->setChecked(v1.second.get("constantradius")); BOOST_FOREACH( boost::property_tree::ptree::value_type const& v2, v1.second ) { if( v2.first == "spline" ) { m_Controls->m_FiberSamplingBox->setValue(v2.second.get("sampling")); m_Controls->m_TensionBox->setValue(v2.second.get("tension")); m_Controls->m_ContinuityBox->setValue(v2.second.get("continuity")); m_Controls->m_BiasBox->setValue(v2.second.get("bias")); } if( v2.first == "rotation" ) { m_Controls->m_XrotBox->setValue(v2.second.get("x")); m_Controls->m_YrotBox->setValue(v2.second.get("y")); m_Controls->m_ZrotBox->setValue(v2.second.get("z")); } if( v2.first == "translation" ) { m_Controls->m_XtransBox->setValue(v2.second.get("x")); m_Controls->m_YtransBox->setValue(v2.second.get("y")); m_Controls->m_ZtransBox->setValue(v2.second.get("z")); } if( v2.first == "scale" ) { m_Controls->m_XscaleBox->setValue(v2.second.get("x")); m_Controls->m_YscaleBox->setValue(v2.second.get("y")); m_Controls->m_ZscaleBox->setValue(v2.second.get("z")); } } } if( v1.first == "image" ) { m_Controls->m_SizeX->setValue(v1.second.get("basic.size.x")); m_Controls->m_SizeY->setValue(v1.second.get("basic.size.y")); m_Controls->m_SizeZ->setValue(v1.second.get("basic.size.z")); m_Controls->m_SpacingX->setValue(v1.second.get("basic.spacing.x")); m_Controls->m_SpacingY->setValue(v1.second.get("basic.spacing.y")); m_Controls->m_SpacingZ->setValue(v1.second.get("basic.spacing.z")); m_Controls->m_NumGradientsBox->setValue(v1.second.get("basic.numgradients")); m_Controls->m_BvalueBox->setValue(v1.second.get("basic.bvalue")); m_Controls->m_AdvancedOptionsBox_2->setChecked(v1.second.get("showadvanced")); m_Controls->m_RepetitionsBox->setValue(v1.second.get("repetitions")); m_Controls->m_SignalScaleBox->setValue(v1.second.get("signalScale")); m_Controls->m_TEbox->setValue(v1.second.get("tEcho")); m_Controls->m_LineReadoutTimeBox->setValue(v1.second.get("tLine")); m_Controls->m_T2starBox->setValue(v1.second.get("tInhom")); m_Controls->m_FiberRadius->setValue(v1.second.get("axonRadius")); m_Controls->m_InterpolationShrink->setValue(v1.second.get("interpolationShrink")); m_Controls->m_RelaxationBox->setChecked(v1.second.get("doSimulateRelaxation")); m_Controls->m_EnforcePureFiberVoxelsBox->setChecked(v1.second.get("doDisablePartialVolume")); m_Controls->m_VolumeFractionsBox->setChecked(v1.second.get("outputvolumefractions")); m_Controls->m_AddNoise->setChecked(v1.second.get("artifacts.addnoise")); m_Controls->m_NoiseLevel->setValue(v1.second.get("artifacts.noisevariance")); m_Controls->m_AddGhosts->setChecked(v1.second.get("artifacts.addghost")); m_Controls->m_kOffsetBox->setValue(v1.second.get("artifacts.kspaceLineOffset")); m_Controls->m_AddDistortions->setChecked(v1.second.get("artifacts.distortions")); m_Controls->m_AddEddy->setChecked(v1.second.get("artifacts.addeddy")); m_Controls->m_EddyGradientStrength->setValue(v1.second.get("artifacts.eddyStrength")); m_Controls->m_AddGibbsRinging->setChecked(v1.second.get("artifacts.addringing")); m_Controls->m_ImageUpsamplingBox->setValue(v1.second.get("artifacts.ringingupsampling")); m_Controls->m_Compartment1Box->setCurrentIndex(v1.second.get("compartment1.index")); m_Controls->m_Compartment2Box->setCurrentIndex(v1.second.get("compartment2.index")); m_Controls->m_Compartment3Box->setCurrentIndex(v1.second.get("compartment3.index")); m_Controls->m_Compartment4Box->setCurrentIndex(v1.second.get("compartment4.index")); m_Controls->m_StickWidget1->SetD(v1.second.get("compartment1.stick.d")); m_Controls->m_StickWidget1->SetT2(v1.second.get("compartment1.stick.t2")); m_Controls->m_ZeppelinWidget1->SetD1(v1.second.get("compartment1.zeppelin.d1")); m_Controls->m_ZeppelinWidget1->SetD2(v1.second.get("compartment1.zeppelin.d2")); m_Controls->m_ZeppelinWidget1->SetT2(v1.second.get("compartment1.zeppelin.t2")); m_Controls->m_TensorWidget1->SetD1(v1.second.get("compartment1.tensor.d1")); m_Controls->m_TensorWidget1->SetD2(v1.second.get("compartment1.tensor.d2")); m_Controls->m_TensorWidget1->SetD3(v1.second.get("compartment1.tensor.d3")); m_Controls->m_TensorWidget1->SetT2(v1.second.get("compartment1.tensor.t2")); m_Controls->m_StickWidget2->SetD(v1.second.get("compartment2.stick.d")); m_Controls->m_StickWidget2->SetT2(v1.second.get("compartment2.stick.t2")); m_Controls->m_ZeppelinWidget2->SetD1(v1.second.get("compartment2.zeppelin.d1")); m_Controls->m_ZeppelinWidget2->SetD2(v1.second.get("compartment2.zeppelin.d2")); m_Controls->m_ZeppelinWidget2->SetT2(v1.second.get("compartment2.zeppelin.t2")); m_Controls->m_TensorWidget2->SetD1(v1.second.get("compartment2.tensor.d1")); m_Controls->m_TensorWidget2->SetD2(v1.second.get("compartment2.tensor.d2")); m_Controls->m_TensorWidget2->SetD3(v1.second.get("compartment2.tensor.d3")); m_Controls->m_TensorWidget2->SetT2(v1.second.get("compartment2.tensor.t2")); m_Controls->m_BallWidget1->SetD(v1.second.get("compartment3.ball.d")); m_Controls->m_BallWidget1->SetT2(v1.second.get("compartment3.ball.t2")); m_Controls->m_AstrosticksWidget1->SetD(v1.second.get("compartment3.astrosticks.d")); m_Controls->m_AstrosticksWidget1->SetT2(v1.second.get("compartment3.astrosticks.t2")); m_Controls->m_AstrosticksWidget1->SetRandomizeSticks(v1.second.get("compartment3.astrosticks.randomize")); m_Controls->m_DotWidget1->SetT2(v1.second.get("compartment3.dot.t2")); m_Controls->m_BallWidget2->SetD(v1.second.get("compartment4.ball.d")); m_Controls->m_BallWidget2->SetT2(v1.second.get("compartment4.ball.t2")); m_Controls->m_AstrosticksWidget2->SetD(v1.second.get("compartment4.astrosticks.d")); m_Controls->m_AstrosticksWidget2->SetT2(v1.second.get("compartment4.astrosticks.t2")); m_Controls->m_AstrosticksWidget2->SetRandomizeSticks(v1.second.get("compartment4.astrosticks.randomize")); m_Controls->m_DotWidget2->SetT2(v1.second.get("compartment4.dot.t2")); m_Controls->m_Comp4FractionBox->setValue(v1.second.get("compartment4.weight")); } } UpdateImageParameters(); } void QmitkFiberfoxView::ShowAdvancedOptions(int state) { if (state) { m_Controls->m_AdvancedFiberOptionsFrame->setVisible(true); m_Controls->m_AdvancedSignalOptionsFrame->setVisible(true); m_Controls->m_AdvancedOptionsBox->setChecked(true); m_Controls->m_AdvancedOptionsBox_2->setChecked(true); } else { m_Controls->m_AdvancedFiberOptionsFrame->setVisible(false); m_Controls->m_AdvancedSignalOptionsFrame->setVisible(false); m_Controls->m_AdvancedOptionsBox->setChecked(false); m_Controls->m_AdvancedOptionsBox_2->setChecked(false); } } void QmitkFiberfoxView::Comp1ModelFrameVisibility(int index) { m_Controls->m_StickWidget1->setVisible(false); m_Controls->m_ZeppelinWidget1->setVisible(false); m_Controls->m_TensorWidget1->setVisible(false); switch (index) { case 0: m_Controls->m_StickWidget1->setVisible(true); break; case 1: m_Controls->m_ZeppelinWidget1->setVisible(true); break; case 2: m_Controls->m_TensorWidget1->setVisible(true); break; } } void QmitkFiberfoxView::Comp2ModelFrameVisibility(int index) { m_Controls->m_StickWidget2->setVisible(false); m_Controls->m_ZeppelinWidget2->setVisible(false); m_Controls->m_TensorWidget2->setVisible(false); switch (index) { case 0: break; case 1: m_Controls->m_StickWidget2->setVisible(true); break; case 2: m_Controls->m_ZeppelinWidget2->setVisible(true); break; case 3: m_Controls->m_TensorWidget2->setVisible(true); break; } } void QmitkFiberfoxView::Comp3ModelFrameVisibility(int index) { m_Controls->m_BallWidget1->setVisible(false); m_Controls->m_AstrosticksWidget1->setVisible(false); m_Controls->m_DotWidget1->setVisible(false); switch (index) { case 0: m_Controls->m_BallWidget1->setVisible(true); break; case 1: m_Controls->m_AstrosticksWidget1->setVisible(true); break; case 2: m_Controls->m_DotWidget1->setVisible(true); break; } } void QmitkFiberfoxView::Comp4ModelFrameVisibility(int index) { m_Controls->m_BallWidget2->setVisible(false); m_Controls->m_AstrosticksWidget2->setVisible(false); m_Controls->m_DotWidget2->setVisible(false); m_Controls->m_Comp4FractionFrame->setVisible(false); switch (index) { case 0: break; case 1: m_Controls->m_BallWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; case 2: m_Controls->m_AstrosticksWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; case 3: m_Controls->m_DotWidget2->setVisible(true); m_Controls->m_Comp4FractionFrame->setVisible(true); break; } } void QmitkFiberfoxView::OnConstantRadius(int value) { if (value>0 && m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnAddEddy(int value) { if (value>0) m_Controls->m_EddyFrame->setVisible(true); else m_Controls->m_EddyFrame->setVisible(false); } void QmitkFiberfoxView::OnAddDistortions(int value) { if (value>0) m_Controls->m_DistortionsFrame->setVisible(true); else m_Controls->m_DistortionsFrame->setVisible(false); } void QmitkFiberfoxView::OnAddGhosts(int value) { if (value>0) m_Controls->m_GhostFrame->setVisible(true); else m_Controls->m_GhostFrame->setVisible(false); } void QmitkFiberfoxView::OnAddNoise(int value) { if (value>0) m_Controls->m_NoiseFrame->setVisible(true); else m_Controls->m_NoiseFrame->setVisible(false); } void QmitkFiberfoxView::OnAddGibbsRinging(int value) { if (value>0) m_Controls->m_GibbsRingingFrame->setVisible(true); else m_Controls->m_GibbsRingingFrame->setVisible(false); } void QmitkFiberfoxView::OnDistributionChanged(int value) { if (value==1) m_Controls->m_VarianceBox->setVisible(true); else m_Controls->m_VarianceBox->setVisible(false); if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnVarianceChanged(double value) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnFiberDensityChanged(int value) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnFiberSamplingChanged(double value) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnTensionChanged(double value) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnContinuityChanged(double value) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnBiasChanged(double value) { if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::AlignOnGrid() { for (int i=0; i(m_SelectedFiducials.at(i)->GetData()); mitk::Point3D wc0 = pe->GetWorldControlPoint(0); mitk::DataStorage::SetOfObjects::ConstPointer parentFibs = GetDataStorage()->GetSources(m_SelectedFiducials.at(i)); for( mitk::DataStorage::SetOfObjects::const_iterator it = parentFibs->begin(); it != parentFibs->end(); ++it ) { mitk::DataNode::Pointer pFibNode = *it; if ( pFibNode.IsNotNull() && dynamic_cast(pFibNode->GetData()) ) { mitk::DataStorage::SetOfObjects::ConstPointer parentImgs = GetDataStorage()->GetSources(pFibNode); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = parentImgs->begin(); it2 != parentImgs->end(); ++it2 ) { mitk::DataNode::Pointer pImgNode = *it2; if ( pImgNode.IsNotNull() && dynamic_cast(pImgNode->GetData()) ) { mitk::Image::Pointer img = dynamic_cast(pImgNode->GetData()); mitk::Geometry3D::Pointer geom = img->GetGeometry(); itk::Index<3> idx; geom->WorldToIndex(wc0, idx); mitk::Point3D cIdx; cIdx[0]=idx[0]; cIdx[1]=idx[1]; cIdx[2]=idx[2]; mitk::Point3D world; geom->IndexToWorld(cIdx,world); mitk::Vector3D trans = world - wc0; pe->GetGeometry()->Translate(trans); break; } } break; } } } for( int i=0; iGetSources(fibNode); for( mitk::DataStorage::SetOfObjects::const_iterator it = sources->begin(); it != sources->end(); ++it ) { mitk::DataNode::Pointer imgNode = *it; if ( imgNode.IsNotNull() && dynamic_cast(imgNode->GetData()) ) { mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(fibNode); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = derivations->begin(); it2 != derivations->end(); ++it2 ) { mitk::DataNode::Pointer fiducialNode = *it2; if ( fiducialNode.IsNotNull() && dynamic_cast(fiducialNode->GetData()) ) { mitk::PlanarEllipse::Pointer pe = dynamic_cast(fiducialNode->GetData()); mitk::Point3D wc0 = pe->GetWorldControlPoint(0); mitk::Image::Pointer img = dynamic_cast(imgNode->GetData()); mitk::Geometry3D::Pointer geom = img->GetGeometry(); itk::Index<3> idx; geom->WorldToIndex(wc0, idx); mitk::Point3D cIdx; cIdx[0]=idx[0]; cIdx[1]=idx[1]; cIdx[2]=idx[2]; mitk::Point3D world; geom->IndexToWorld(cIdx,world); mitk::Vector3D trans = world - wc0; pe->GetGeometry()->Translate(trans); } } break; } } } for( int i=0; i(m_SelectedImages.at(i)->GetData()); mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(m_SelectedImages.at(i)); for( mitk::DataStorage::SetOfObjects::const_iterator it = derivations->begin(); it != derivations->end(); ++it ) { mitk::DataNode::Pointer fibNode = *it; if ( fibNode.IsNotNull() && dynamic_cast(fibNode->GetData()) ) { mitk::DataStorage::SetOfObjects::ConstPointer derivations2 = GetDataStorage()->GetDerivations(fibNode); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = derivations2->begin(); it2 != derivations2->end(); ++it2 ) { mitk::DataNode::Pointer fiducialNode = *it2; if ( fiducialNode.IsNotNull() && dynamic_cast(fiducialNode->GetData()) ) { mitk::PlanarEllipse::Pointer pe = dynamic_cast(fiducialNode->GetData()); mitk::Point3D wc0 = pe->GetWorldControlPoint(0); mitk::Geometry3D::Pointer geom = img->GetGeometry(); itk::Index<3> idx; geom->WorldToIndex(wc0, idx); mitk::Point3D cIdx; cIdx[0]=idx[0]; cIdx[1]=idx[1]; cIdx[2]=idx[2]; mitk::Point3D world; geom->IndexToWorld(cIdx,world); mitk::Vector3D trans = world - wc0; pe->GetGeometry()->Translate(trans); } } } } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::OnFlipButton() { if (m_SelectedFiducial.IsNull()) return; std::map::iterator it = m_DataNodeToPlanarFigureData.find(m_SelectedFiducial.GetPointer()); if( it != m_DataNodeToPlanarFigureData.end() ) { QmitkPlanarFigureData& data = it->second; data.m_Flipped += 1; data.m_Flipped %= 2; } if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } QmitkFiberfoxView::GradientListType QmitkFiberfoxView::GenerateHalfShell(int NPoints) { NPoints *= 2; GradientListType pointshell; int numB0 = NPoints/20; if (numB0==0) numB0=1; GradientType g; g.Fill(0.0); for (int i=0; i theta; theta.set_size(NPoints); vnl_vector phi; phi.set_size(NPoints); double C = sqrt(4*M_PI); phi(0) = 0.0; phi(NPoints-1) = 0.0; for(int i=0; i0 && i std::vector > QmitkFiberfoxView::MakeGradientList() { std::vector > retval; vnl_matrix_fixed* U = itk::PointShell >::DistributePointShell(); // Add 0 vector for B0 int numB0 = ndirs/10; if (numB0==0) numB0=1; itk::Vector v; v.Fill(0.0); for (int i=0; i v; v[0] = U->get(0,i); v[1] = U->get(1,i); v[2] = U->get(2,i); retval.push_back(v); } return retval; } void QmitkFiberfoxView::OnAddBundle() { if (m_SelectedImage.IsNull()) return; mitk::DataStorage::SetOfObjects::ConstPointer children = GetDataStorage()->GetDerivations(m_SelectedImage); mitk::FiberBundleX::Pointer bundle = mitk::FiberBundleX::New(); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( bundle ); QString name = QString("Bundle_%1").arg(children->size()); node->SetName(name.toStdString()); m_SelectedBundles.push_back(node); UpdateGui(); GetDataStorage()->Add(node, m_SelectedImage); } void QmitkFiberfoxView::OnDrawROI() { if (m_SelectedBundles.empty()) OnAddBundle(); if (m_SelectedBundles.empty()) return; mitk::DataStorage::SetOfObjects::ConstPointer children = GetDataStorage()->GetDerivations(m_SelectedBundles.at(0)); mitk::PlanarEllipse::Pointer figure = mitk::PlanarEllipse::New(); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( figure ); QList nodes = this->GetDataManagerSelection(); for( int i=0; iSetSelected(false); m_SelectedFiducial = node; QString name = QString("Fiducial_%1").arg(children->size()); node->SetName(name.toStdString()); node->SetSelected(true); GetDataStorage()->Add(node, m_SelectedBundles.at(0)); this->DisableCrosshairNavigation(); mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(node->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); - mitk::Module* planarFigureModule = mitk::ModuleRegistry::GetModule( "PlanarFigure" ); + us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "PlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( node ); } UpdateGui(); } bool CompareLayer(mitk::DataNode::Pointer i,mitk::DataNode::Pointer j) { int li = -1; i->GetPropertyValue("layer", li); int lj = -1; j->GetPropertyValue("layer", lj); return liGetSources(m_SelectedFiducial); for( mitk::DataStorage::SetOfObjects::const_iterator it = parents->begin(); it != parents->end(); ++it ) if(dynamic_cast((*it)->GetData())) m_SelectedBundles.push_back(*it); if (m_SelectedBundles.empty()) return; } vector< vector< mitk::PlanarEllipse::Pointer > > fiducials; vector< vector< unsigned int > > fliplist; for (int i=0; iGetDerivations(m_SelectedBundles.at(i)); std::vector< mitk::DataNode::Pointer > childVector; for( mitk::DataStorage::SetOfObjects::const_iterator it = children->begin(); it != children->end(); ++it ) childVector.push_back(*it); sort(childVector.begin(), childVector.end(), CompareLayer); vector< mitk::PlanarEllipse::Pointer > fib; vector< unsigned int > flip; float radius = 1; int count = 0; for( std::vector< mitk::DataNode::Pointer >::const_iterator it = childVector.begin(); it != childVector.end(); ++it ) { mitk::DataNode::Pointer node = *it; if ( node.IsNotNull() && dynamic_cast(node->GetData()) ) { mitk::PlanarEllipse* ellipse = dynamic_cast(node->GetData()); if (m_Controls->m_ConstantRadiusBox->isChecked()) { ellipse->SetTreatAsCircle(true); mitk::Point2D c = ellipse->GetControlPoint(0); mitk::Point2D p = ellipse->GetControlPoint(1); mitk::Vector2D v = p-c; if (count==0) { radius = v.GetVnlVector().magnitude(); ellipse->SetControlPoint(1, p); } else { v.Normalize(); v *= radius; ellipse->SetControlPoint(1, c+v); } } fib.push_back(ellipse); std::map::iterator it = m_DataNodeToPlanarFigureData.find(node.GetPointer()); if( it != m_DataNodeToPlanarFigureData.end() ) { QmitkPlanarFigureData& data = it->second; flip.push_back(data.m_Flipped); } else flip.push_back(0); } count++; } if (fib.size()>1) { fiducials.push_back(fib); fliplist.push_back(flip); } else if (fib.size()>0) m_SelectedBundles.at(i)->SetData( mitk::FiberBundleX::New() ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } itk::FibersFromPlanarFiguresFilter::Pointer filter = itk::FibersFromPlanarFiguresFilter::New(); filter->SetFiducials(fiducials); filter->SetFlipList(fliplist); switch(m_Controls->m_DistributionBox->currentIndex()){ case 0: filter->SetFiberDistribution(itk::FibersFromPlanarFiguresFilter::DISTRIBUTE_UNIFORM); break; case 1: filter->SetFiberDistribution(itk::FibersFromPlanarFiguresFilter::DISTRIBUTE_GAUSSIAN); filter->SetVariance(m_Controls->m_VarianceBox->value()); break; } filter->SetDensity(m_Controls->m_FiberDensityBox->value()); filter->SetTension(m_Controls->m_TensionBox->value()); filter->SetContinuity(m_Controls->m_ContinuityBox->value()); filter->SetBias(m_Controls->m_BiasBox->value()); filter->SetFiberSampling(m_Controls->m_FiberSamplingBox->value()); filter->Update(); vector< mitk::FiberBundleX::Pointer > fiberBundles = filter->GetFiberBundles(); for (int i=0; iSetData( fiberBundles.at(i) ); if (fiberBundles.at(i)->GetNumFibers()>50000) m_SelectedBundles.at(i)->SetVisibility(false); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkFiberfoxView::GenerateImage() { UpdateImageParameters(); if (m_SelectedBundles.empty()) { if (m_SelectedDWI.IsNotNull()) // add artifacts to existing diffusion weighted image { for (int i=0; i*>(m_SelectedImages.at(i)->GetData())) continue; m_SelectedDWI = m_SelectedImages.at(i); UpdateImageParameters(); mitk::DiffusionImage::Pointer diffImg = dynamic_cast*>(m_SelectedImages.at(i)->GetData()); mitk::RicianNoiseModel noiseModel; noiseModel.SetNoiseVariance(m_ImageGenParameters.ricianNoiseModel.GetNoiseVariance()); itk::AddArtifactsToDwiImageFilter< short >::Pointer filter = itk::AddArtifactsToDwiImageFilter< short >::New(); filter->SetInput(diffImg->GetVectorImage()); filter->SettLine(m_ImageGenParameters.tLine); filter->SetkOffset(m_ImageGenParameters.kspaceLineOffset); filter->SetNoiseModel(&noiseModel); filter->SetGradientList(m_ImageGenParameters.gradientDirections); filter->SetTE(m_ImageGenParameters.tEcho); filter->SetSimulateEddyCurrents(m_ImageGenParameters.doSimulateEddyCurrents); filter->SetEddyGradientStrength(m_ImageGenParameters.eddyStrength); filter->SetUpsampling(m_ImageGenParameters.upsampling); filter->SetFrequencyMap(m_ImageGenParameters.frequencyMap); filter->Update(); mitk::DiffusionImage::Pointer image = mitk::DiffusionImage::New(); image->SetVectorImage( filter->GetOutput() ); image->SetB_Value(diffImg->GetB_Value()); image->SetDirections(diffImg->GetDirections()); image->InitializeFromVectorImage(); m_ImageGenParameters.resultNode->SetData( image ); m_ImageGenParameters.resultNode->SetName(m_SelectedImages.at(i)->GetName()+m_ImageGenParameters.artifactModelString.toStdString()); GetDataStorage()->Add(m_ImageGenParameters.resultNode); } m_SelectedDWI = m_SelectedImages.front(); return; } mitk::Image::Pointer image = mitk::ImageGenerator::GenerateGradientImage( m_Controls->m_SizeX->value(), m_Controls->m_SizeY->value(), m_Controls->m_SizeZ->value(), m_Controls->m_SpacingX->value(), m_Controls->m_SpacingY->value(), m_Controls->m_SpacingZ->value()); mitk::Geometry3D* geom = image->GetGeometry(); geom->SetOrigin(m_ImageGenParameters.imageOrigin); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName("Dummy"); unsigned int window = m_Controls->m_SizeX->value()*m_Controls->m_SizeY->value()*m_Controls->m_SizeZ->value(); unsigned int level = window/2; mitk::LevelWindow lw; lw.SetLevelWindow(level, window); node->SetProperty( "levelwindow", mitk::LevelWindowProperty::New( lw ) ); GetDataStorage()->Add(node); m_SelectedImage = node; mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } UpdateGui(); return; } for (int i=0; i(m_SelectedBundles.at(i)->GetData()); if (fiberBundle->GetNumFibers()<=0) continue; itk::TractsToDWIImageFilter< short >::Pointer tractsToDwiFilter = itk::TractsToDWIImageFilter< short >::New(); tractsToDwiFilter->SetSimulateEddyCurrents(m_ImageGenParameters.doSimulateEddyCurrents); tractsToDwiFilter->SetEddyGradientStrength(m_ImageGenParameters.eddyStrength); tractsToDwiFilter->SetUpsampling(m_ImageGenParameters.upsampling); tractsToDwiFilter->SetSimulateRelaxation(m_ImageGenParameters.doSimulateRelaxation); tractsToDwiFilter->SetImageRegion(m_ImageGenParameters.imageRegion); tractsToDwiFilter->SetSpacing(m_ImageGenParameters.imageSpacing); tractsToDwiFilter->SetOrigin(m_ImageGenParameters.imageOrigin); tractsToDwiFilter->SetDirectionMatrix(m_ImageGenParameters.imageDirection); tractsToDwiFilter->SetFiberBundle(fiberBundle); tractsToDwiFilter->SetFiberModels(m_ImageGenParameters.fiberModelList); tractsToDwiFilter->SetNonFiberModels(m_ImageGenParameters.nonFiberModelList); tractsToDwiFilter->SetNoiseModel(&m_ImageGenParameters.ricianNoiseModel); tractsToDwiFilter->SetKspaceArtifacts(m_ImageGenParameters.artifactList); tractsToDwiFilter->SetkOffset(m_ImageGenParameters.kspaceLineOffset); tractsToDwiFilter->SettLine(m_ImageGenParameters.tLine); tractsToDwiFilter->SettInhom(m_ImageGenParameters.tInhom); tractsToDwiFilter->SetTE(m_ImageGenParameters.tEcho); tractsToDwiFilter->SetNumberOfRepetitions(m_ImageGenParameters.repetitions); tractsToDwiFilter->SetEnforcePureFiberVoxels(m_ImageGenParameters.doDisablePartialVolume); tractsToDwiFilter->SetInterpolationShrink(m_ImageGenParameters.interpolationShrink); tractsToDwiFilter->SetFiberRadius(m_ImageGenParameters.axonRadius); tractsToDwiFilter->SetSignalScale(m_ImageGenParameters.signalScale); if (m_ImageGenParameters.interpolationShrink) tractsToDwiFilter->SetUseInterpolation(true); tractsToDwiFilter->SetTissueMask(m_ImageGenParameters.tissueMaskImage); tractsToDwiFilter->SetFrequencyMap(m_ImageGenParameters.frequencyMap); tractsToDwiFilter->Update(); mitk::DiffusionImage::Pointer image = mitk::DiffusionImage::New(); image->SetVectorImage( tractsToDwiFilter->GetOutput() ); image->SetB_Value(m_ImageGenParameters.b_value); image->SetDirections(m_ImageGenParameters.gradientDirections); image->InitializeFromVectorImage(); m_ImageGenParameters.resultNode->SetData( image ); m_ImageGenParameters.resultNode->SetName(m_SelectedBundles.at(i)->GetName() +"_D"+QString::number(m_ImageGenParameters.imageRegion.GetSize(0)).toStdString() +"-"+QString::number(m_ImageGenParameters.imageRegion.GetSize(1)).toStdString() +"-"+QString::number(m_ImageGenParameters.imageRegion.GetSize(2)).toStdString() +"_S"+QString::number(m_ImageGenParameters.imageSpacing[0]).toStdString() +"-"+QString::number(m_ImageGenParameters.imageSpacing[1]).toStdString() +"-"+QString::number(m_ImageGenParameters.imageSpacing[2]).toStdString() +"_b"+QString::number(m_ImageGenParameters.b_value).toStdString() +"_"+m_ImageGenParameters.signalModelString.toStdString() +m_ImageGenParameters.artifactModelString.toStdString()); GetDataStorage()->Add(m_ImageGenParameters.resultNode, m_SelectedBundles.at(i)); m_ImageGenParameters.resultNode->SetProperty( "levelwindow", mitk::LevelWindowProperty::New(tractsToDwiFilter->GetLevelWindow()) ); if (m_Controls->m_VolumeFractionsBox->isChecked()) { std::vector< itk::TractsToDWIImageFilter< short >::ItkDoubleImgType::Pointer > volumeFractions = tractsToDwiFilter->GetVolumeFractions(); for (int k=0; kInitializeByItk(volumeFractions.at(k).GetPointer()); image->SetVolume(volumeFractions.at(k)->GetBufferPointer()); mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData( image ); node->SetName(m_SelectedBundles.at(i)->GetName()+"_CompartmentVolume-"+QString::number(k).toStdString()); GetDataStorage()->Add(node, m_SelectedBundles.at(i)); } } mitk::BaseData::Pointer basedata = m_ImageGenParameters.resultNode->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkFiberfoxView::ApplyTransform() { vector< mitk::DataNode::Pointer > selectedBundles; for( int i=0; iGetDerivations(m_SelectedImages.at(i)); for( mitk::DataStorage::SetOfObjects::const_iterator it = derivations->begin(); it != derivations->end(); ++it ) { mitk::DataNode::Pointer fibNode = *it; if ( fibNode.IsNotNull() && dynamic_cast(fibNode->GetData()) ) selectedBundles.push_back(fibNode); } } if (selectedBundles.empty()) selectedBundles = m_SelectedBundles2; if (!selectedBundles.empty()) { std::vector::const_iterator it = selectedBundles.begin(); for (it; it!=selectedBundles.end(); ++it) { mitk::FiberBundleX::Pointer fib = dynamic_cast((*it)->GetData()); fib->RotateAroundAxis(m_Controls->m_XrotBox->value(), m_Controls->m_YrotBox->value(), m_Controls->m_ZrotBox->value()); fib->TranslateFibers(m_Controls->m_XtransBox->value(), m_Controls->m_YtransBox->value(), m_Controls->m_ZtransBox->value()); fib->ScaleFibers(m_Controls->m_XscaleBox->value(), m_Controls->m_YscaleBox->value(), m_Controls->m_ZscaleBox->value()); // handle child fiducials if (m_Controls->m_IncludeFiducials->isChecked()) { mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(*it); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = derivations->begin(); it2 != derivations->end(); ++it2 ) { mitk::DataNode::Pointer fiducialNode = *it2; if ( fiducialNode.IsNotNull() && dynamic_cast(fiducialNode->GetData()) ) { mitk::PlanarEllipse* pe = dynamic_cast(fiducialNode->GetData()); mitk::Geometry3D* geom = pe->GetGeometry(); // translate mitk::Vector3D world; world[0] = m_Controls->m_XtransBox->value(); world[1] = m_Controls->m_YtransBox->value(); world[2] = m_Controls->m_ZtransBox->value(); geom->Translate(world); // calculate rotation matrix double x = m_Controls->m_XrotBox->value()*M_PI/180; double y = m_Controls->m_YrotBox->value()*M_PI/180; double z = m_Controls->m_ZrotBox->value()*M_PI/180; itk::Matrix< float, 3, 3 > rotX; rotX.SetIdentity(); rotX[1][1] = cos(x); rotX[2][2] = rotX[1][1]; rotX[1][2] = -sin(x); rotX[2][1] = -rotX[1][2]; itk::Matrix< float, 3, 3 > rotY; rotY.SetIdentity(); rotY[0][0] = cos(y); rotY[2][2] = rotY[0][0]; rotY[0][2] = sin(y); rotY[2][0] = -rotY[0][2]; itk::Matrix< float, 3, 3 > rotZ; rotZ.SetIdentity(); rotZ[0][0] = cos(z); rotZ[1][1] = rotZ[0][0]; rotZ[0][1] = -sin(z); rotZ[1][0] = -rotZ[0][1]; itk::Matrix< float, 3, 3 > rot = rotZ*rotY*rotX; // transform control point coordinate into geometry translation geom->SetOrigin(pe->GetWorldControlPoint(0)); mitk::Point2D cp; cp.Fill(0.0); pe->SetControlPoint(0, cp); // rotate fiducial geom->GetIndexToWorldTransform()->SetMatrix(rot*geom->GetIndexToWorldTransform()->GetMatrix()); // implicit translation mitk::Vector3D trans; trans[0] = geom->GetOrigin()[0]-fib->GetGeometry()->GetCenter()[0]; trans[1] = geom->GetOrigin()[1]-fib->GetGeometry()->GetCenter()[1]; trans[2] = geom->GetOrigin()[2]-fib->GetGeometry()->GetCenter()[2]; mitk::Vector3D newWc = rot*trans; newWc = newWc-trans; geom->Translate(newWc); } } } } } else { for (int i=0; i(m_SelectedFiducials.at(i)->GetData()); mitk::Geometry3D* geom = pe->GetGeometry(); // translate mitk::Vector3D world; world[0] = m_Controls->m_XtransBox->value(); world[1] = m_Controls->m_YtransBox->value(); world[2] = m_Controls->m_ZtransBox->value(); geom->Translate(world); // calculate rotation matrix double x = m_Controls->m_XrotBox->value()*M_PI/180; double y = m_Controls->m_YrotBox->value()*M_PI/180; double z = m_Controls->m_ZrotBox->value()*M_PI/180; itk::Matrix< float, 3, 3 > rotX; rotX.SetIdentity(); rotX[1][1] = cos(x); rotX[2][2] = rotX[1][1]; rotX[1][2] = -sin(x); rotX[2][1] = -rotX[1][2]; itk::Matrix< float, 3, 3 > rotY; rotY.SetIdentity(); rotY[0][0] = cos(y); rotY[2][2] = rotY[0][0]; rotY[0][2] = sin(y); rotY[2][0] = -rotY[0][2]; itk::Matrix< float, 3, 3 > rotZ; rotZ.SetIdentity(); rotZ[0][0] = cos(z); rotZ[1][1] = rotZ[0][0]; rotZ[0][1] = -sin(z); rotZ[1][0] = -rotZ[0][1]; itk::Matrix< float, 3, 3 > rot = rotZ*rotY*rotX; // transform control point coordinate into geometry translation geom->SetOrigin(pe->GetWorldControlPoint(0)); mitk::Point2D cp; cp.Fill(0.0); pe->SetControlPoint(0, cp); // rotate fiducial geom->GetIndexToWorldTransform()->SetMatrix(rot*geom->GetIndexToWorldTransform()->GetMatrix()); } if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkFiberfoxView::CopyBundles() { if ( m_SelectedBundles.size()<1 ){ QMessageBox::information( NULL, "Warning", "Select at least one fiber bundle!"); MITK_WARN("QmitkFiberProcessingView") << "Select at least one fiber bundle!"; return; } std::vector::const_iterator it = m_SelectedBundles.begin(); for (it; it!=m_SelectedBundles.end(); ++it) { // find parent image mitk::DataNode::Pointer parentNode; mitk::DataStorage::SetOfObjects::ConstPointer parentImgs = GetDataStorage()->GetSources(*it); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = parentImgs->begin(); it2 != parentImgs->end(); ++it2 ) { mitk::DataNode::Pointer pImgNode = *it2; if ( pImgNode.IsNotNull() && dynamic_cast(pImgNode->GetData()) ) { parentNode = pImgNode; break; } } mitk::FiberBundleX::Pointer fib = dynamic_cast((*it)->GetData()); mitk::FiberBundleX::Pointer newBundle = fib->GetDeepCopy(); QString name((*it)->GetName().c_str()); name += "_copy"; mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); if (parentNode.IsNotNull()) GetDataStorage()->Add(fbNode, parentNode); else GetDataStorage()->Add(fbNode); // copy child fiducials if (m_Controls->m_IncludeFiducials->isChecked()) { mitk::DataStorage::SetOfObjects::ConstPointer derivations = GetDataStorage()->GetDerivations(*it); for( mitk::DataStorage::SetOfObjects::const_iterator it2 = derivations->begin(); it2 != derivations->end(); ++it2 ) { mitk::DataNode::Pointer fiducialNode = *it2; if ( fiducialNode.IsNotNull() && dynamic_cast(fiducialNode->GetData()) ) { mitk::PlanarEllipse::Pointer pe = mitk::PlanarEllipse::New(); pe->DeepCopy(dynamic_cast(fiducialNode->GetData())); mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetData(pe); newNode->SetName(fiducialNode->GetName()); GetDataStorage()->Add(newNode, fbNode); } } } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkFiberfoxView::JoinBundles() { if ( m_SelectedBundles.size()<2 ){ QMessageBox::information( NULL, "Warning", "Select at least two fiber bundles!"); MITK_WARN("QmitkFiberProcessingView") << "Select at least two fiber bundles!"; return; } std::vector::const_iterator it = m_SelectedBundles.begin(); mitk::FiberBundleX::Pointer newBundle = dynamic_cast((*it)->GetData()); QString name(""); name += QString((*it)->GetName().c_str()); ++it; for (it; it!=m_SelectedBundles.end(); ++it) { newBundle = newBundle->AddBundle(dynamic_cast((*it)->GetData())); name += "+"+QString((*it)->GetName().c_str()); } mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkFiberfoxView::UpdateGui() { m_Controls->m_FiberBundleLabel->setText("mandatory"); m_Controls->m_GeometryFrame->setEnabled(true); m_Controls->m_GeometryMessage->setVisible(false); m_Controls->m_DiffusionPropsMessage->setVisible(false); m_Controls->m_FiberGenMessage->setVisible(true); m_Controls->m_TransformBundlesButton->setEnabled(false); m_Controls->m_CopyBundlesButton->setEnabled(false); m_Controls->m_GenerateFibersButton->setEnabled(false); m_Controls->m_FlipButton->setEnabled(false); m_Controls->m_CircleButton->setEnabled(false); m_Controls->m_BvalueBox->setEnabled(true); m_Controls->m_NumGradientsBox->setEnabled(true); m_Controls->m_JoinBundlesButton->setEnabled(false); m_Controls->m_AlignOnGrid->setEnabled(false); if (m_SelectedFiducial.IsNotNull()) { m_Controls->m_TransformBundlesButton->setEnabled(true); m_Controls->m_FlipButton->setEnabled(true); m_Controls->m_AlignOnGrid->setEnabled(true); } if (m_SelectedImage.IsNotNull() || !m_SelectedBundles.empty()) { m_Controls->m_TransformBundlesButton->setEnabled(true); m_Controls->m_CircleButton->setEnabled(true); m_Controls->m_FiberGenMessage->setVisible(false); m_Controls->m_AlignOnGrid->setEnabled(true); } if (m_TissueMask.IsNotNull() || m_SelectedImage.IsNotNull()) { m_Controls->m_GeometryMessage->setVisible(true); m_Controls->m_GeometryFrame->setEnabled(false); } if (m_SelectedDWI.IsNotNull()) { m_Controls->m_DiffusionPropsMessage->setVisible(true); m_Controls->m_BvalueBox->setEnabled(false); m_Controls->m_NumGradientsBox->setEnabled(false); m_Controls->m_GeometryMessage->setVisible(true); m_Controls->m_GeometryFrame->setEnabled(false); } if (!m_SelectedBundles.empty()) { m_Controls->m_CopyBundlesButton->setEnabled(true); m_Controls->m_GenerateFibersButton->setEnabled(true); m_Controls->m_FiberBundleLabel->setText(m_SelectedBundles.at(0)->GetName().c_str()); if (m_SelectedBundles.size()>1) m_Controls->m_JoinBundlesButton->setEnabled(true); } } void QmitkFiberfoxView::OnSelectionChanged( berry::IWorkbenchPart::Pointer, const QList& nodes ) { m_SelectedBundles2.clear(); m_SelectedImages.clear(); m_SelectedFiducials.clear(); m_SelectedFiducial = NULL; m_TissueMask = NULL; m_SelectedBundles.clear(); m_SelectedImage = NULL; m_SelectedDWI = NULL; m_Controls->m_TissueMaskLabel->setText("optional"); // iterate all selected objects, adjust warning visibility for( int i=0; i*>(node->GetData()) ) { m_SelectedDWI = node; m_SelectedImage = node; m_SelectedImages.push_back(node); } else if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { m_SelectedImages.push_back(node); m_SelectedImage = node; bool isBinary = false; node->GetPropertyValue("binary", isBinary); if (isBinary) { m_TissueMask = dynamic_cast(node->GetData()); m_Controls->m_TissueMaskLabel->setText(node->GetName().c_str()); } } else if ( node.IsNotNull() && dynamic_cast(node->GetData()) ) { m_SelectedBundles2.push_back(node); if (m_Controls->m_RealTimeFibers->isChecked()) { m_SelectedBundles.push_back(node); mitk::FiberBundleX::Pointer newFib = dynamic_cast(node->GetData()); if (newFib->GetNumFibers()!=m_Controls->m_FiberDensityBox->value()) GenerateFibers(); } else m_SelectedBundles.push_back(node); } else if ( node.IsNotNull() && dynamic_cast(node->GetData()) ) { m_SelectedFiducials.push_back(node); m_SelectedFiducial = node; m_SelectedBundles.clear(); mitk::DataStorage::SetOfObjects::ConstPointer parents = GetDataStorage()->GetSources(node); for( mitk::DataStorage::SetOfObjects::const_iterator it = parents->begin(); it != parents->end(); ++it ) { mitk::DataNode::Pointer pNode = *it; if ( pNode.IsNotNull() && dynamic_cast(pNode->GetData()) ) m_SelectedBundles.push_back(pNode); } } } UpdateGui(); } void QmitkFiberfoxView::EnableCrosshairNavigation() { MITK_DEBUG << "EnableCrosshairNavigation"; // enable the crosshair navigation if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart())) { MITK_DEBUG << "enabling linked navigation"; linkedRenderWindow->EnableLinkedNavigation(true); // linkedRenderWindow->EnableSlicingPlanes(true); } if (m_Controls->m_RealTimeFibers->isChecked()) GenerateFibers(); } void QmitkFiberfoxView::DisableCrosshairNavigation() { MITK_DEBUG << "DisableCrosshairNavigation"; // disable the crosshair navigation during the drawing if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart())) { MITK_DEBUG << "disabling linked navigation"; linkedRenderWindow->EnableLinkedNavigation(false); // linkedRenderWindow->EnableSlicingPlanes(false); } } void QmitkFiberfoxView::NodeRemoved(const mitk::DataNode* node) { mitk::DataNode* nonConstNode = const_cast(node); std::map::iterator it = m_DataNodeToPlanarFigureData.find(nonConstNode); if( it != m_DataNodeToPlanarFigureData.end() ) { QmitkPlanarFigureData& data = it->second; // remove observers data.m_Figure->RemoveObserver( data.m_EndPlacementObserverTag ); data.m_Figure->RemoveObserver( data.m_SelectObserverTag ); data.m_Figure->RemoveObserver( data.m_StartInteractionObserverTag ); data.m_Figure->RemoveObserver( data.m_EndInteractionObserverTag ); m_DataNodeToPlanarFigureData.erase( it ); } } void QmitkFiberfoxView::NodeAdded( const mitk::DataNode* node ) { // add observer for selection in renderwindow mitk::PlanarFigure* figure = dynamic_cast(node->GetData()); bool isPositionMarker (false); node->GetBoolProperty("isContourMarker", isPositionMarker); if( figure && !isPositionMarker ) { MITK_DEBUG << "figure added. will add interactor if needed."; mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(node->GetDataInteractor().GetPointer()); mitk::DataNode* nonConstNode = const_cast( node ); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); - mitk::Module* planarFigureModule = mitk::ModuleRegistry::GetModule( "PlanarFigure" ); + us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "PlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( nonConstNode ); } MITK_DEBUG << "will now add observers for planarfigure"; QmitkPlanarFigureData data; data.m_Figure = figure; // // add observer for event when figure has been placed typedef itk::SimpleMemberCommand< QmitkFiberfoxView > SimpleCommandType; // SimpleCommandType::Pointer initializationCommand = SimpleCommandType::New(); // initializationCommand->SetCallbackFunction( this, &QmitkFiberfoxView::PlanarFigureInitialized ); // data.m_EndPlacementObserverTag = figure->AddObserver( mitk::EndPlacementPlanarFigureEvent(), initializationCommand ); // add observer for event when figure is picked (selected) typedef itk::MemberCommand< QmitkFiberfoxView > MemberCommandType; MemberCommandType::Pointer selectCommand = MemberCommandType::New(); selectCommand->SetCallbackFunction( this, &QmitkFiberfoxView::PlanarFigureSelected ); data.m_SelectObserverTag = figure->AddObserver( mitk::SelectPlanarFigureEvent(), selectCommand ); // add observer for event when interaction with figure starts SimpleCommandType::Pointer startInteractionCommand = SimpleCommandType::New(); startInteractionCommand->SetCallbackFunction( this, &QmitkFiberfoxView::DisableCrosshairNavigation); data.m_StartInteractionObserverTag = figure->AddObserver( mitk::StartInteractionPlanarFigureEvent(), startInteractionCommand ); // add observer for event when interaction with figure starts SimpleCommandType::Pointer endInteractionCommand = SimpleCommandType::New(); endInteractionCommand->SetCallbackFunction( this, &QmitkFiberfoxView::EnableCrosshairNavigation); data.m_EndInteractionObserverTag = figure->AddObserver( mitk::EndInteractionPlanarFigureEvent(), endInteractionCommand ); m_DataNodeToPlanarFigureData[nonConstNode] = data; } } void QmitkFiberfoxView::PlanarFigureSelected( itk::Object* object, const itk::EventObject& ) { mitk::TNodePredicateDataType::Pointer isPf = mitk::TNodePredicateDataType::New(); mitk::DataStorage::SetOfObjects::ConstPointer allPfs = this->GetDataStorage()->GetSubset( isPf ); for ( mitk::DataStorage::SetOfObjects::const_iterator it = allPfs->begin(); it!=allPfs->end(); ++it) { mitk::DataNode* node = *it; if( node->GetData() == object ) { node->SetSelected(true); m_SelectedFiducial = node; } else node->SetSelected(false); } UpdateGui(); this->RequestRenderWindowUpdate(); } void QmitkFiberfoxView::SetFocus() { m_Controls->m_CircleButton->setFocus(); } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.cpp index f88a5a0b15..735cdc6c41 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkPartialVolumeAnalysisView.cpp @@ -1,2157 +1,2157 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkPartialVolumeAnalysisView.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "QmitkStdMultiWidget.h" #include "QmitkStdMultiWidgetEditor.h" #include "QmitkSliderNavigatorWidget.h" #include #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateOr.h" #include "mitkImageTimeSelector.h" #include "mitkProperties.h" #include "mitkProgressBar.h" #include "mitkImageCast.h" #include "mitkImageToItk.h" #include "mitkITKImageImport.h" #include "mitkDataNodeObject.h" #include "mitkNodePredicateData.h" #include "mitkPlanarFigureInteractor.h" #include "mitkGlobalInteraction.h" #include "mitkTensorImage.h" #include "mitkPlanarCircle.h" #include "mitkPlanarRectangle.h" #include "mitkPlanarPolygon.h" #include "mitkPartialVolumeAnalysisClusteringCalculator.h" #include "mitkDiffusionImage.h" -#include "mitkModuleRegistry.h" +#include "usModuleRegistry.h" #include #include "itkTensorDerivedMeasurementsFilter.h" #include "itkDiffusionTensor3D.h" #include "itkCartesianToPolarVectorImageFilter.h" #include "itkPolarToCartesianVectorImageFilter.h" #include "itkBinaryThresholdImageFilter.h" #include "itkMaskImageFilter.h" #include "itkCastImageFilter.h" #include "itkImageMomentsCalculator.h" #include #include #include #include #define _USE_MATH_DEFINES #include #define PVA_PI M_PI const std::string QmitkPartialVolumeAnalysisView::VIEW_ID = "org.mitk.views.partialvolumeanalysisview"; class QmitkRequestStatisticsUpdateEvent : public QEvent { public: enum Type { StatisticsUpdateRequest = QEvent::MaxUser - 1025 }; QmitkRequestStatisticsUpdateEvent() : QEvent( (QEvent::Type) StatisticsUpdateRequest ) {}; }; typedef itk::Image ImageType; typedef itk::Image FloatImageType; typedef itk::Image, 3> VectorImageType; inline bool my_isnan(float x) { volatile float d = x; if(d!=d) return true; if(d==d) return false; return d != d; } QmitkPartialVolumeAnalysisView::QmitkPartialVolumeAnalysisView(QObject * /*parent*/, const char * /*name*/) : //QmitkFunctionality(), m_Controls( NULL ), m_TimeStepperAdapter( NULL ), m_MeasurementInfoRenderer(0), m_MeasurementInfoAnnotation(0), m_SelectedImageNodes( ), m_SelectedImage( NULL ), m_SelectedMaskNode( NULL ), m_SelectedImageMask( NULL ), m_SelectedPlanarFigureNodes(0), m_SelectedPlanarFigure( NULL ), m_IsTensorImage(false), m_FAImage(0), m_RDImage(0), m_ADImage(0), m_MDImage(0), m_CAImage(0), // m_DirectionImage(0), m_DirectionComp1Image(0), m_DirectionComp2Image(0), m_AngularErrorImage(0), m_SelectedRenderWindow(NULL), m_LastRenderWindow(NULL), m_ImageObserverTag( -1 ), m_ImageMaskObserverTag( -1 ), m_PlanarFigureObserverTag( -1 ), m_CurrentStatisticsValid( false ), m_StatisticsUpdatePending( false ), m_GaussianSigmaChangedSliding(false), m_NumberBinsSliding(false), m_UpsamplingChangedSliding(false), m_ClusteringResult(NULL), m_EllipseCounter(0), m_RectangleCounter(0), m_PolygonCounter(0), m_CurrentFigureNodeInitialized(false), m_QuantifyClass(2), m_IconTexOFF(new QIcon(":/QmitkPartialVolumeAnalysisView/texIntOFFIcon.png")), m_IconTexON(new QIcon(":/QmitkPartialVolumeAnalysisView/texIntONIcon.png")), m_TexIsOn(true), m_Visible(false) { } QmitkPartialVolumeAnalysisView::~QmitkPartialVolumeAnalysisView() { if ( m_SelectedImage.IsNotNull() ) m_SelectedImage->RemoveObserver( m_ImageObserverTag ); if ( m_SelectedImageMask.IsNotNull() ) m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); if ( m_SelectedPlanarFigure.IsNotNull() ) { m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); m_SelectedPlanarFigure->RemoveObserver( m_InitializedObserverTag ); } this->GetDataStorage()->AddNodeEvent -= mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeAddedInDataStorage ); m_SelectedPlanarFigureNodes->NodeChanged.RemoveListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeChanged ) ); m_SelectedPlanarFigureNodes->NodeRemoved.RemoveListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeRemoved ) ); m_SelectedPlanarFigureNodes->PropertyChanged.RemoveListener( mitk::MessageDelegate2( this, &QmitkPartialVolumeAnalysisView::PropertyChanged ) ); m_SelectedImageNodes->NodeChanged.RemoveListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeChanged ) ); m_SelectedImageNodes->NodeRemoved.RemoveListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeRemoved ) ); m_SelectedImageNodes->PropertyChanged.RemoveListener( mitk::MessageDelegate2( this, &QmitkPartialVolumeAnalysisView::PropertyChanged ) ); } void QmitkPartialVolumeAnalysisView::CreateQtPartControl(QWidget *parent) { if (m_Controls == NULL) { m_Controls = new Ui::QmitkPartialVolumeAnalysisViewControls; m_Controls->setupUi(parent); this->CreateConnections(); } SetHistogramVisibility(); m_Controls->m_TextureIntON->setIcon(*m_IconTexON); m_Controls->m_SimilarAnglesFrame->setVisible(false); m_Controls->m_SimilarAnglesLabel->setVisible(false); vtkTextProperty *textProp = vtkTextProperty::New(); textProp->SetColor(1.0, 1.0, 1.0); m_MeasurementInfoAnnotation = vtkCornerAnnotation::New(); m_MeasurementInfoAnnotation->SetMaximumFontSize(12); m_MeasurementInfoAnnotation->SetTextProperty(textProp); m_MeasurementInfoRenderer = vtkRenderer::New(); m_MeasurementInfoRenderer->AddActor(m_MeasurementInfoAnnotation); m_SelectedPlanarFigureNodes = mitk::DataStorageSelection::New(this->GetDataStorage(), false); m_SelectedPlanarFigureNodes->NodeChanged.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeChanged ) ); m_SelectedPlanarFigureNodes->NodeRemoved.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeRemoved ) ); m_SelectedPlanarFigureNodes->PropertyChanged.AddListener( mitk::MessageDelegate2( this, &QmitkPartialVolumeAnalysisView::PropertyChanged ) ); m_SelectedImageNodes = mitk::DataStorageSelection::New(this->GetDataStorage(), false); m_SelectedImageNodes->PropertyChanged.AddListener( mitk::MessageDelegate2( this, &QmitkPartialVolumeAnalysisView::PropertyChanged ) ); m_SelectedImageNodes->NodeChanged.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeChanged ) ); m_SelectedImageNodes->NodeRemoved.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeRemoved ) ); this->GetDataStorage()->AddNodeEvent.AddListener( mitk::MessageDelegate1( this, &QmitkPartialVolumeAnalysisView::NodeAddedInDataStorage ) ); Select(NULL,true,true); SetAdvancedVisibility(); } void QmitkPartialVolumeAnalysisView::SetHistogramVisibility() { m_Controls->m_HistogramWidget->setVisible(m_Controls->m_DisplayHistogramCheckbox->isChecked()); } void QmitkPartialVolumeAnalysisView::SetAdvancedVisibility() { m_Controls->frame_7->setVisible(m_Controls->m_AdvancedCheckbox->isChecked()); } void QmitkPartialVolumeAnalysisView::CreateConnections() { if ( m_Controls ) { connect( m_Controls->m_DisplayHistogramCheckbox, SIGNAL( clicked() ) , this, SLOT( SetHistogramVisibility() ) ); connect( m_Controls->m_AdvancedCheckbox, SIGNAL( clicked() ) , this, SLOT( SetAdvancedVisibility() ) ); connect( m_Controls->m_NumberBinsSlider, SIGNAL( sliderReleased () ), this, SLOT( NumberBinsReleasedSlider( ) ) ); connect( m_Controls->m_UpsamplingSlider, SIGNAL( sliderReleased( ) ), this, SLOT( UpsamplingReleasedSlider( ) ) ); connect( m_Controls->m_GaussianSigmaSlider, SIGNAL( sliderReleased( ) ), this, SLOT( GaussianSigmaReleasedSlider( ) ) ); connect( m_Controls->m_SimilarAnglesSlider, SIGNAL( sliderReleased( ) ), this, SLOT( SimilarAnglesReleasedSlider( ) ) ); connect( m_Controls->m_NumberBinsSlider, SIGNAL( valueChanged (int) ), this, SLOT( NumberBinsChangedSlider( int ) ) ); connect( m_Controls->m_UpsamplingSlider, SIGNAL( valueChanged( int ) ), this, SLOT( UpsamplingChangedSlider( int ) ) ); connect( m_Controls->m_GaussianSigmaSlider, SIGNAL( valueChanged( int ) ), this, SLOT( GaussianSigmaChangedSlider( int ) ) ); connect( m_Controls->m_SimilarAnglesSlider, SIGNAL( valueChanged( int ) ), this, SLOT( SimilarAnglesChangedSlider(int) ) ); connect( m_Controls->m_OpacitySlider, SIGNAL( valueChanged( int ) ), this, SLOT( OpacityChangedSlider(int) ) ); connect( (QObject*)(m_Controls->m_ButtonCopyHistogramToClipboard), SIGNAL(clicked()),(QObject*) this, SLOT(ToClipBoard())); connect( m_Controls->m_CircleButton, SIGNAL( clicked() ) , this, SLOT( ActionDrawEllipseTriggered() ) ); connect( m_Controls->m_RectangleButton, SIGNAL( clicked() ) , this, SLOT( ActionDrawRectangleTriggered() ) ); connect( m_Controls->m_PolygonButton, SIGNAL( clicked() ) , this, SLOT( ActionDrawPolygonTriggered() ) ); connect( m_Controls->m_GreenRadio, SIGNAL( clicked(bool) ) , this, SLOT( GreenRadio(bool) ) ); connect( m_Controls->m_PartialVolumeRadio, SIGNAL( clicked(bool) ) , this, SLOT( PartialVolumeRadio(bool) ) ); connect( m_Controls->m_BlueRadio, SIGNAL( clicked(bool) ) , this, SLOT( BlueRadio(bool) ) ); connect( m_Controls->m_AllRadio, SIGNAL( clicked(bool) ) , this, SLOT( AllRadio(bool) ) ); connect( m_Controls->m_EstimateCircle, SIGNAL( clicked() ) , this, SLOT( EstimateCircle() ) ); connect( (QObject*)(m_Controls->m_TextureIntON), SIGNAL(clicked()), this, SLOT(TextIntON()) ); connect( m_Controls->m_ExportClusteringResultsButton, SIGNAL(clicked()), this, SLOT(ExportClusteringResults())); } } void QmitkPartialVolumeAnalysisView::ExportClusteringResults() { if (m_ClusteringResult.IsNull() || m_SelectedImage.IsNull()) return; mitk::Geometry3D* geometry = m_SelectedImage->GetGeometry(); itk::Image< short, 3>::Pointer referenceImage = itk::Image< short, 3>::New(); itk::Vector newSpacing = geometry->GetSpacing(); mitk::Point3D newOrigin = geometry->GetOrigin(); mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); newOrigin[0] += bounds.GetElement(0); newOrigin[1] += bounds.GetElement(2); newOrigin[2] += bounds.GetElement(4); itk::Matrix newDirection; itk::ImageRegion<3> imageRegion; for (int i=0; i<3; i++) for (int j=0; j<3; j++) newDirection[j][i] = geometry->GetMatrixColumn(i)[j]/newSpacing[j]; imageRegion.SetSize(0, geometry->GetExtent(0)); imageRegion.SetSize(1, geometry->GetExtent(1)); imageRegion.SetSize(2, geometry->GetExtent(2)); // apply new image parameters referenceImage->SetSpacing( newSpacing ); referenceImage->SetOrigin( newOrigin ); referenceImage->SetDirection( newDirection ); referenceImage->SetRegions( imageRegion ); referenceImage->Allocate(); typedef itk::Image< float, 3 > OutType; mitk::Image::Pointer mitkInImage = dynamic_cast(m_ClusteringResult->GetData()); typedef itk::Image< itk::RGBAPixel, 3 > ItkRgbaImageType; typedef mitk::ImageToItk< ItkRgbaImageType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(mitkInImage); caster->Update(); ItkRgbaImageType::Pointer itkInImage = caster->GetOutput(); typedef itk::ExtractChannelFromRgbaImageFilter< itk::Image< short, 3>, OutType > ExtractionFilterType; ExtractionFilterType::Pointer filter = ExtractionFilterType::New(); filter->SetInput(itkInImage); filter->SetChannel(ExtractionFilterType::ALPHA); filter->SetReferenceImage(referenceImage); filter->Update(); OutType::Pointer outImg = filter->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); // init data node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); node->SetName("Clustering Result"); GetDataStorage()->Add(node); } void QmitkPartialVolumeAnalysisView::EstimateCircle() { typedef itk::Image SegImageType; SegImageType::Pointer mask_itk = SegImageType::New(); typedef mitk::ImageToItk CastType; CastType::Pointer caster = CastType::New(); caster->SetInput(m_SelectedImageMask); caster->Update(); typedef itk::ImageMomentsCalculator< SegImageType > MomentsType; MomentsType::Pointer momentsCalc = MomentsType::New(); momentsCalc->SetImage(caster->GetOutput()); momentsCalc->Compute(); MomentsType::VectorType cog = momentsCalc->GetCenterOfGravity(); MomentsType::MatrixType axes = momentsCalc->GetPrincipalAxes(); MomentsType::VectorType moments = momentsCalc->GetPrincipalMoments(); // moments-coord conversion // third coordinate min oder max? // max-min = extent MomentsType::AffineTransformPointer trafo = momentsCalc->GetPhysicalAxesToPrincipalAxesTransform(); itk::ImageRegionIterator itimage(caster->GetOutput(), caster->GetOutput()->GetLargestPossibleRegion()); itimage = itimage.Begin(); double max = -9999999999.0; double min = 9999999999.0; while( !itimage.IsAtEnd() ) { if(itimage.Get()) { ImageType::IndexType index = itimage.GetIndex(); itk::Point point; caster->GetOutput()->TransformIndexToPhysicalPoint(index,point); itk::Point newPoint; newPoint = trafo->TransformPoint(point); if(newPoint[2]max) max = newPoint[2]; } ++itimage; } double extent = max - min; MITK_DEBUG << "EXTENT = " << extent; mitk::Point3D origin; mitk::Vector3D right, bottom, normal; double factor = 1000.0; mitk::FillVector3D(origin, cog[0]-factor*axes[1][0]-factor*axes[2][0], cog[1]-factor*axes[1][1]-factor*axes[2][1], cog[2]-factor*axes[1][2]-factor*axes[2][2]); // mitk::FillVector3D(normal, axis[0][0],axis[0][1],axis[0][2]); mitk::FillVector3D(bottom, 2*factor*axes[1][0], 2*factor*axes[1][1], 2*factor*axes[1][2]); mitk::FillVector3D(right, 2*factor*axes[2][0], 2*factor*axes[2][1], 2*factor*axes[2][2]); mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); planegeometry->InitializeStandardPlane(right.Get_vnl_vector(), bottom.Get_vnl_vector()); planegeometry->SetOrigin(origin); double len1 = sqrt(axes[1][0]*axes[1][0] + axes[1][1]*axes[1][1] + axes[1][2]*axes[1][2]); double len2 = sqrt(axes[2][0]*axes[2][0] + axes[2][1]*axes[2][1] + axes[2][2]*axes[2][2]); mitk::Point2D point1; point1[0] = factor*len1; point1[1] = factor*len2; mitk::Point2D point2; point2[0] = factor*len1+extent*.5; point2[1] = factor*len2; mitk::PlanarCircle::Pointer circle = mitk::PlanarCircle::New(); circle->SetGeometry2D(planegeometry); circle->PlaceFigure( point1 ); circle->SetControlPoint(0,point1); circle->SetControlPoint(1,point2); //circle->SetCurrentControlPoint( point2 ); mitk::PlanarFigure::PolyLineType polyline = circle->GetPolyLine( 0 ); MITK_DEBUG << "SIZE of planar figure polyline: " << polyline.size(); AddFigureToDataStorage(circle, "Circle"); } bool QmitkPartialVolumeAnalysisView::AssertDrawingIsPossible(bool checked) { if (m_SelectedImageNodes->GetNode().IsNull()) { checked = false; this->HandleException("Please select an image!", dynamic_cast(this->parent()), true); return false; } //this->GetActiveStdMultiWidget()->SetWidgetPlanesVisibility(false); return checked; } void QmitkPartialVolumeAnalysisView::ActionDrawEllipseTriggered() { bool checked = m_Controls->m_CircleButton->isChecked(); if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); // using PV_ prefix for planar figures from this view // to distinguish them from that ones created throught the measurement view this->AddFigureToDataStorage(figure, QString("PV_Circle%1").arg(++m_EllipseCounter)); MITK_DEBUG << "PlanarCircle created ..."; } void QmitkPartialVolumeAnalysisView::ActionDrawRectangleTriggered() { bool checked = m_Controls->m_RectangleButton->isChecked(); if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarRectangle::Pointer figure = mitk::PlanarRectangle::New(); // using PV_ prefix for planar figures from this view // to distinguish them from that ones created throught the measurement view this->AddFigureToDataStorage(figure, QString("PV_Rectangle%1").arg(++m_RectangleCounter)); MITK_DEBUG << "PlanarRectangle created ..."; } void QmitkPartialVolumeAnalysisView::ActionDrawPolygonTriggered() { bool checked = m_Controls->m_PolygonButton->isChecked(); if(!this->AssertDrawingIsPossible(checked)) return; mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOn(); // using PV_ prefix for planar figures from this view // to distinguish them from that ones created throught the measurement view this->AddFigureToDataStorage(figure, QString("PV_Polygon%1").arg(++m_PolygonCounter)); MITK_DEBUG << "PlanarPolygon created ..."; } void QmitkPartialVolumeAnalysisView::AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey, mitk::BaseProperty *property ) { mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(name.toStdString()); newNode->SetData(figure); // Add custom property, if available if ( (propertyKey != NULL) && (property != NULL) ) { newNode->AddProperty( propertyKey, property ); } // figure drawn on the topmost layer / image this->GetDataStorage()->Add(newNode, m_SelectedImageNodes->GetNode() ); QList selectedNodes = this->GetDataManagerSelection(); for(unsigned int i = 0; i < selectedNodes.size(); i++) { selectedNodes[i]->SetSelected(false); } std::vector selectedPFNodes = m_SelectedPlanarFigureNodes->GetNodes(); for(unsigned int i = 0; i < selectedPFNodes.size(); i++) { selectedPFNodes[i]->SetSelected(false); } newNode->SetSelected(true); Select(newNode); } void QmitkPartialVolumeAnalysisView::PlanarFigureInitialized() { if(m_SelectedPlanarFigureNodes->GetNode().IsNull()) return; m_CurrentFigureNodeInitialized = true; this->Select(m_SelectedPlanarFigureNodes->GetNode()); m_Controls->m_CircleButton->setChecked(false); m_Controls->m_RectangleButton->setChecked(false); m_Controls->m_PolygonButton->setChecked(false); //this->GetActiveStdMultiWidget()->SetWidgetPlanesVisibility(true); this->RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::PlanarFigureFocus(mitk::DataNode* node) { mitk::PlanarFigure* _PlanarFigure = 0; _PlanarFigure = dynamic_cast (node->GetData()); if (_PlanarFigure) { FindRenderWindow(node); const mitk::PlaneGeometry * _PlaneGeometry = dynamic_cast (_PlanarFigure->GetGeometry2D()); // make node visible if (m_SelectedRenderWindow) { mitk::Point3D centerP = _PlaneGeometry->GetOrigin(); m_SelectedRenderWindow->GetSliceNavigationController()->ReorientSlices( centerP, _PlaneGeometry->GetNormal()); m_SelectedRenderWindow->GetSliceNavigationController()->SelectSliceByPoint( centerP); } } } void QmitkPartialVolumeAnalysisView::FindRenderWindow(mitk::DataNode* node) { if (node && dynamic_cast (node->GetData())) { m_SelectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; foreach(QmitkRenderWindow * window, this->GetRenderWindowPart()->GetQmitkRenderWindows().values()) { if (!m_SelectedRenderWindow && node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, window->GetRenderer())) { m_SelectedRenderWindow = window; } } } } void QmitkPartialVolumeAnalysisView::OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList &nodes) { m_Controls->m_InputData->setTitle("Please Select Input Data"); if (!m_Visible) return; if ( nodes.empty() ) { if (m_ClusteringResult.IsNotNull()) { this->GetDataStorage()->Remove(m_ClusteringResult); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } Select(NULL, true, true); } for (int i=0; iRemoveOrphanImages(); bool somethingChanged = false; if(node.IsNull()) { somethingChanged = true; if(clearMaskOnFirstArgNULL) { if ( (m_SelectedImageMask.IsNotNull()) && (m_ImageMaskObserverTag >= 0) ) { m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); m_ImageMaskObserverTag = -1; } if ( (m_SelectedPlanarFigure.IsNotNull()) && (m_PlanarFigureObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); m_PlanarFigureObserverTag = -1; } if ( (m_SelectedPlanarFigure.IsNotNull()) && (m_InitializedObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_InitializedObserverTag ); m_InitializedObserverTag = -1; } m_SelectedPlanarFigure = NULL; m_SelectedPlanarFigureNodes->RemoveAllNodes(); m_CurrentFigureNodeInitialized = false; m_SelectedRenderWindow = 0; m_SelectedMaskNode = NULL; m_SelectedImageMask = NULL; } if(clearImageOnFirstArgNULL) { if ( (m_SelectedImage.IsNotNull()) && (m_ImageObserverTag >= 0) ) { m_SelectedImage->RemoveObserver( m_ImageObserverTag ); m_ImageObserverTag = -1; } m_SelectedImageNodes->RemoveAllNodes(); m_SelectedImage = NULL; m_IsTensorImage = false; m_FAImage = NULL; m_RDImage = NULL; m_ADImage = NULL; m_MDImage = NULL; m_CAImage = NULL; m_DirectionComp1Image = NULL; m_DirectionComp2Image = NULL; m_AngularErrorImage = NULL; m_Controls->m_SimilarAnglesFrame->setVisible(false); m_Controls->m_SimilarAnglesLabel->setVisible(false); } } else { typedef itk::SimpleMemberCommand< QmitkPartialVolumeAnalysisView > ITKCommandType; ITKCommandType::Pointer changeListener; changeListener = ITKCommandType::New(); changeListener->SetCallbackFunction( this, &QmitkPartialVolumeAnalysisView::RequestStatisticsUpdate ); // Get selected element mitk::TensorImage *selectedTensorImage = dynamic_cast< mitk::TensorImage * >( node->GetData() ); mitk::Image *selectedImage = dynamic_cast< mitk::Image * >( node->GetData() ); mitk::PlanarFigure *selectedPlanar = dynamic_cast< mitk::PlanarFigure * >( node->GetData() ); bool isMask = false; bool isImage = false; bool isPlanar = false; bool isTensorImage = false; if (selectedTensorImage != NULL) { isTensorImage = true; } else if(selectedImage != NULL) { node->GetPropertyValue("binary", isMask); isImage = !isMask; } else if ( (selectedPlanar != NULL) ) { isPlanar = true; } // image if(isImage && selectedImage->GetDimension()==3) { if(selectedImage != m_SelectedImage.GetPointer()) { somethingChanged = true; if ( (m_SelectedImage.IsNotNull()) && (m_ImageObserverTag >= 0) ) { m_SelectedImage->RemoveObserver( m_ImageObserverTag ); m_ImageObserverTag = -1; } *m_SelectedImageNodes = node; m_SelectedImage = selectedImage; m_IsTensorImage = false; m_FAImage = NULL; m_RDImage = NULL; m_ADImage = NULL; m_MDImage = NULL; m_CAImage = NULL; m_DirectionComp1Image = NULL; m_DirectionComp2Image = NULL; m_AngularErrorImage = NULL; // Add change listeners to selected objects m_ImageObserverTag = m_SelectedImage->AddObserver( itk::ModifiedEvent(), changeListener ); m_Controls->m_SimilarAnglesFrame->setVisible(false); m_Controls->m_SimilarAnglesLabel->setVisible(false); m_Controls->m_SelectedImageLabel->setText( m_SelectedImageNodes->GetNode()->GetName().c_str() ); } } //planar if(isPlanar) { if(selectedPlanar != m_SelectedPlanarFigure.GetPointer()) { MITK_DEBUG << "Planar selection changed"; somethingChanged = true; // Possibly previous change listeners if ( (m_SelectedPlanarFigure.IsNotNull()) && (m_PlanarFigureObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); m_PlanarFigureObserverTag = -1; } if ( (m_SelectedPlanarFigure.IsNotNull()) && (m_InitializedObserverTag >= 0) ) { m_SelectedPlanarFigure->RemoveObserver( m_InitializedObserverTag ); m_InitializedObserverTag = -1; } m_SelectedPlanarFigure = selectedPlanar; *m_SelectedPlanarFigureNodes = node; m_CurrentFigureNodeInitialized = selectedPlanar->IsPlaced(); m_SelectedMaskNode = NULL; m_SelectedImageMask = NULL; m_PlanarFigureObserverTag = m_SelectedPlanarFigure->AddObserver( mitk::EndInteractionPlanarFigureEvent(), changeListener ); if(!m_CurrentFigureNodeInitialized) { typedef itk::SimpleMemberCommand< QmitkPartialVolumeAnalysisView > ITKCommandType; ITKCommandType::Pointer initializationCommand; initializationCommand = ITKCommandType::New(); // set the callback function of the member command initializationCommand->SetCallbackFunction( this, &QmitkPartialVolumeAnalysisView::PlanarFigureInitialized ); // add an observer m_InitializedObserverTag = selectedPlanar->AddObserver( mitk::EndPlacementPlanarFigureEvent(), initializationCommand ); } m_Controls->m_SelectedMaskLabel->setText( m_SelectedPlanarFigureNodes->GetNode()->GetName().c_str() ); PlanarFigureFocus(node); } } //mask this->m_Controls->m_EstimateCircle->setEnabled(isMask && selectedImage->GetDimension()==3); if(isMask && selectedImage->GetDimension()==3) { if(selectedImage != m_SelectedImage.GetPointer()) { somethingChanged = true; if ( (m_SelectedImageMask.IsNotNull()) && (m_ImageMaskObserverTag >= 0) ) { m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); m_ImageMaskObserverTag = -1; } m_SelectedMaskNode = node; m_SelectedImageMask = selectedImage; m_SelectedPlanarFigure = NULL; m_SelectedPlanarFigureNodes->RemoveAllNodes(); m_ImageMaskObserverTag = m_SelectedImageMask->AddObserver( itk::ModifiedEvent(), changeListener ); m_Controls->m_SelectedMaskLabel->setText( m_SelectedMaskNode->GetName().c_str() ); } } //tensor image if(isTensorImage && selectedTensorImage->GetDimension()==3) { if(selectedImage != m_SelectedImage.GetPointer()) { somethingChanged = true; if ( (m_SelectedImage.IsNotNull()) && (m_ImageObserverTag >= 0) ) { m_SelectedImage->RemoveObserver( m_ImageObserverTag ); m_ImageObserverTag = -1; } *m_SelectedImageNodes = node; m_SelectedImage = selectedImage; m_IsTensorImage = true; ExtractTensorImages(selectedImage); // Add change listeners to selected objects m_ImageObserverTag = m_SelectedImage->AddObserver( itk::ModifiedEvent(), changeListener ); m_Controls->m_SimilarAnglesFrame->setVisible(true); m_Controls->m_SimilarAnglesLabel->setVisible(true); m_Controls->m_SelectedImageLabel->setText( m_SelectedImageNodes->GetNode()->GetName().c_str() ); } } } if(somethingChanged) { this->SetMeasurementInfoToRenderWindow(""); if(m_SelectedPlanarFigure.IsNull() && m_SelectedImageMask.IsNull() ) { m_Controls->m_SelectedMaskLabel->setText("mandatory"); m_Controls->m_ResampleOptionsFrame->setEnabled(false); m_Controls->m_HistogramWidget->setEnabled(false); m_Controls->m_ClassSelector->setEnabled(false); m_Controls->m_DisplayHistogramCheckbox->setEnabled(false); m_Controls->m_AdvancedCheckbox->setEnabled(false); m_Controls->frame_7->setEnabled(false); } else { m_Controls->m_ResampleOptionsFrame->setEnabled(true); m_Controls->m_HistogramWidget->setEnabled(true); m_Controls->m_ClassSelector->setEnabled(true); m_Controls->m_DisplayHistogramCheckbox->setEnabled(true); m_Controls->m_AdvancedCheckbox->setEnabled(true); m_Controls->frame_7->setEnabled(true); } // Clear statistics / histogram GUI if nothing is selected if ( m_SelectedImage.IsNull() ) { m_Controls->m_PlanarFigureButtonsFrame->setEnabled(false); m_Controls->m_OpacityFrame->setEnabled(false); m_Controls->m_SelectedImageLabel->setText("mandatory"); } else { m_Controls->m_PlanarFigureButtonsFrame->setEnabled(true); m_Controls->m_OpacityFrame->setEnabled(true); } if( !m_Visible || m_SelectedImage.IsNull() || (m_SelectedPlanarFigure.IsNull() && m_SelectedImageMask.IsNull()) ) { m_Controls->m_InputData->setTitle("Please Select Input Data"); m_Controls->m_HistogramWidget->ClearItemModel(); m_CurrentStatisticsValid = false; } else { m_Controls->m_InputData->setTitle("Input Data"); this->RequestStatisticsUpdate(); } } } void QmitkPartialVolumeAnalysisView::ShowClusteringResults() { typedef itk::Image MaskImageType; mitk::Image::Pointer mask = 0; MaskImageType::Pointer itkmask = 0; if(m_IsTensorImage && m_Controls->m_SimilarAnglesSlider->value() != 0) { typedef itk::Image AngularErrorImageType; typedef mitk::ImageToItk CastType; CastType::Pointer caster = CastType::New(); caster->SetInput(m_AngularErrorImage); caster->Update(); typedef itk::BinaryThresholdImageFilter< AngularErrorImageType, MaskImageType > ThreshType; ThreshType::Pointer thresh = ThreshType::New(); thresh->SetUpperThreshold((90-m_Controls->m_SimilarAnglesSlider->value())*(PVA_PI/180.0)); thresh->SetInsideValue(1.0); thresh->SetInput(caster->GetOutput()); thresh->Update(); itkmask = thresh->GetOutput(); mask = mitk::Image::New(); mask->InitializeByItk(itkmask.GetPointer()); mask->SetVolume(itkmask->GetBufferPointer()); // GetDefaultDataStorage()->Remove(m_newnode); // m_newnode = mitk::DataNode::New(); // m_newnode->SetData(mask); // m_newnode->SetName("masking node"); // m_newnode->SetIntProperty( "layer", 1002 ); // GetDefaultDataStorage()->Add(m_newnode, m_SelectedImageNodes->GetNode()); } mitk::Image::Pointer clusteredImage; ClusteringType::Pointer clusterer = ClusteringType::New(); if(m_QuantifyClass==3) { if(m_IsTensorImage) { double *green_fa, *green_rd, *green_ad, *green_md; //double *greengray_fa, *greengray_rd, *greengray_ad, *greengray_md; double *gray_fa, *gray_rd, *gray_ad, *gray_md; //double *redgray_fa, *redgray_rd, *redgray_ad, *redgray_md; double *red_fa, *red_rd, *red_ad, *red_md; mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(0); mitk::Image::ConstPointer imgToCluster = tmpImg; red_fa = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->r, mask); green_fa = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->g, mask); gray_fa = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->b, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(3); mitk::Image::ConstPointer imgToCluster3 = tmpImg; red_rd = clusterer->PerformQuantification(imgToCluster3, m_CurrentRGBClusteringResults->rgbChannels->r, mask); green_rd = clusterer->PerformQuantification(imgToCluster3, m_CurrentRGBClusteringResults->rgbChannels->g, mask); gray_rd = clusterer->PerformQuantification(imgToCluster3, m_CurrentRGBClusteringResults->rgbChannels->b, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(4); mitk::Image::ConstPointer imgToCluster4 = tmpImg; red_ad = clusterer->PerformQuantification(imgToCluster4, m_CurrentRGBClusteringResults->rgbChannels->r, mask); green_ad = clusterer->PerformQuantification(imgToCluster4, m_CurrentRGBClusteringResults->rgbChannels->g, mask); gray_ad = clusterer->PerformQuantification(imgToCluster4, m_CurrentRGBClusteringResults->rgbChannels->b, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(5); mitk::Image::ConstPointer imgToCluster5 = tmpImg; red_md = clusterer->PerformQuantification(imgToCluster5, m_CurrentRGBClusteringResults->rgbChannels->r, mask); green_md = clusterer->PerformQuantification(imgToCluster5, m_CurrentRGBClusteringResults->rgbChannels->g, mask); gray_md = clusterer->PerformQuantification(imgToCluster5, m_CurrentRGBClusteringResults->rgbChannels->b, mask); // clipboard QString clipboardText("FA\t%1\t%2\t\t%3\t%4\t\t%5\t%6\t"); clipboardText = clipboardText .arg(red_fa[0]).arg(red_fa[1]) .arg(gray_fa[0]).arg(gray_fa[1]) .arg(green_fa[0]).arg(green_fa[1]); QString clipboardText3("RD\t%1\t%2\t\t%3\t%4\t\t%5\t%6\t"); clipboardText3 = clipboardText3 .arg(red_rd[0]).arg(red_rd[1]) .arg(gray_rd[0]).arg(gray_rd[1]) .arg(green_rd[0]).arg(green_rd[1]); QString clipboardText4("AD\t%1\t%2\t\t%3\t%4\t\t%5\t%6\t"); clipboardText4 = clipboardText4 .arg(red_ad[0]).arg(red_ad[1]) .arg(gray_ad[0]).arg(gray_ad[1]) .arg(green_ad[0]).arg(green_ad[1]); QString clipboardText5("MD\t%1\t%2\t\t%3\t%4\t\t%5\t%6"); clipboardText5 = clipboardText5 .arg(red_md[0]).arg(red_md[1]) .arg(gray_md[0]).arg(gray_md[1]) .arg(green_md[0]).arg(green_md[1]); QApplication::clipboard()->setText(clipboardText+clipboardText3+clipboardText4+clipboardText5, QClipboard::Clipboard); // now paint infos also on renderwindow QString plainInfoText("%1 %2 %3 \n"); plainInfoText = plainInfoText .arg("Red ", 20) .arg("Gray ", 20) .arg("Green", 20); QString plainInfoText0("FA:%1 ± %2%3 ± %4%5 ± %6\n"); plainInfoText0 = plainInfoText0 .arg(red_fa[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(red_fa[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(gray_fa[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(gray_fa[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(green_fa[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(green_fa[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText3("RDx10³:%1 ± %2%3 ± %4%5 ± %6\n"); plainInfoText3 = plainInfoText3 .arg(1000.0 * red_rd[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_rd[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * gray_rd[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * gray_rd[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * green_rd[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * green_rd[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText4("ADx10³:%1 ± %2%3 ± %4%5 ± %6\n"); plainInfoText4 = plainInfoText4 .arg(1000.0 * red_ad[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_ad[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * gray_ad[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * gray_ad[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * green_ad[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * green_ad[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText5("MDx10³:%1 ± %2%3 ± %4%5 ± %6"); plainInfoText5 = plainInfoText5 .arg(1000.0 * red_md[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_md[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * gray_md[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * gray_md[1], -10, 'g', 2, QLatin1Char( ' ' )) .arg(1000.0 * green_md[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * green_md[1], -10, 'g', 2, QLatin1Char( ' ' )); this->SetMeasurementInfoToRenderWindow(plainInfoText+plainInfoText0+plainInfoText3+plainInfoText4+plainInfoText5); } else { double* green; double* gray; double* red; mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalImage(); mitk::Image::ConstPointer imgToCluster = tmpImg; red = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->r); green = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->g); gray = clusterer->PerformQuantification(imgToCluster, m_CurrentRGBClusteringResults->rgbChannels->b); // clipboard QString clipboardText("%1\t%2\t\t%3\t%4\t\t%5\t%6"); clipboardText = clipboardText.arg(red[0]).arg(red[1]) .arg(gray[0]).arg(gray[1]) .arg(green[0]).arg(green[1]); QApplication::clipboard()->setText(clipboardText, QClipboard::Clipboard); // now paint infos also on renderwindow QString plainInfoText("Red: %1 ± %2\nGray: %3 ± %4\nGreen: %5 ± %6"); plainInfoText = plainInfoText.arg(red[0]).arg(red[1]) .arg(gray[0]).arg(gray[1]) .arg(green[0]).arg(green[1]); this->SetMeasurementInfoToRenderWindow(plainInfoText); } clusteredImage = m_CurrentRGBClusteringResults->rgb; } else { if(m_IsTensorImage) { double *red_fa, *red_rd, *red_ad, *red_md; mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(0); mitk::Image::ConstPointer imgToCluster = tmpImg; red_fa = clusterer->PerformQuantification(imgToCluster, m_CurrentPerformClusteringResults->clusteredImage, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(3); mitk::Image::ConstPointer imgToCluster3 = tmpImg; red_rd = clusterer->PerformQuantification(imgToCluster3, m_CurrentPerformClusteringResults->clusteredImage, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(4); mitk::Image::ConstPointer imgToCluster4 = tmpImg; red_ad = clusterer->PerformQuantification(imgToCluster4, m_CurrentPerformClusteringResults->clusteredImage, mask); tmpImg = m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(5); mitk::Image::ConstPointer imgToCluster5 = tmpImg; red_md = clusterer->PerformQuantification(imgToCluster5, m_CurrentPerformClusteringResults->clusteredImage, mask); // clipboard QString clipboardText("FA\t%1\t%2\t"); clipboardText = clipboardText .arg(red_fa[0]).arg(red_fa[1]); QString clipboardText3("RD\t%1\t%2\t"); clipboardText3 = clipboardText3 .arg(red_rd[0]).arg(red_rd[1]); QString clipboardText4("AD\t%1\t%2\t"); clipboardText4 = clipboardText4 .arg(red_ad[0]).arg(red_ad[1]); QString clipboardText5("MD\t%1\t%2\t"); clipboardText5 = clipboardText5 .arg(red_md[0]).arg(red_md[1]); QApplication::clipboard()->setText(clipboardText+clipboardText3+clipboardText4+clipboardText5, QClipboard::Clipboard); // now paint infos also on renderwindow QString plainInfoText("%1 \n"); plainInfoText = plainInfoText .arg("Red ", 20); QString plainInfoText0("FA:%1 ± %2\n"); plainInfoText0 = plainInfoText0 .arg(red_fa[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(red_fa[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText3("RDx10³:%1 ± %2\n"); plainInfoText3 = plainInfoText3 .arg(1000.0 * red_rd[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_rd[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText4("ADx10³:%1 ± %2\n"); plainInfoText4 = plainInfoText4 .arg(1000.0 * red_ad[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_ad[1], -10, 'g', 2, QLatin1Char( ' ' )); QString plainInfoText5("MDx10³:%1 ± %2"); plainInfoText5 = plainInfoText5 .arg(1000.0 * red_md[0], 10, 'g', 2, QLatin1Char( ' ' )).arg(1000.0 * red_md[1], -10, 'g', 2, QLatin1Char( ' ' )); this->SetMeasurementInfoToRenderWindow(plainInfoText+plainInfoText0+plainInfoText3+plainInfoText4+plainInfoText5); } else { double* quant; mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalImage(); mitk::Image::ConstPointer imgToCluster = tmpImg; quant = clusterer->PerformQuantification(imgToCluster, m_CurrentPerformClusteringResults->clusteredImage); // clipboard QString clipboardText("%1\t%2"); clipboardText = clipboardText.arg(quant[0]).arg(quant[1]); QApplication::clipboard()->setText(clipboardText, QClipboard::Clipboard); // now paint infos also on renderwindow QString plainInfoText("Measurement: %1 ± %2"); plainInfoText = plainInfoText.arg(quant[0]).arg(quant[1]); this->SetMeasurementInfoToRenderWindow(plainInfoText); } clusteredImage = m_CurrentPerformClusteringResults->displayImage; } if(mask.IsNotNull()) { typedef itk::Image,3> RGBImageType; typedef mitk::ImageToItk ClusterCasterType; ClusterCasterType::Pointer clCaster = ClusterCasterType::New(); clCaster->SetInput(clusteredImage); clCaster->Update(); clCaster->GetOutput(); typedef itk::MaskImageFilter< RGBImageType, MaskImageType, RGBImageType > MaskType; MaskType::Pointer masker = MaskType::New(); masker->SetInput1(clCaster->GetOutput()); masker->SetInput2(itkmask); masker->Update(); clusteredImage = mitk::Image::New(); clusteredImage->InitializeByItk(masker->GetOutput()); clusteredImage->SetVolume(masker->GetOutput()->GetBufferPointer()); } if(m_ClusteringResult.IsNotNull()) { this->GetDataStorage()->Remove(m_ClusteringResult); } m_ClusteringResult = mitk::DataNode::New(); m_ClusteringResult->SetBoolProperty("helper object", true); m_ClusteringResult->SetIntProperty( "layer", 1000 ); m_ClusteringResult->SetBoolProperty("texture interpolation", m_TexIsOn); m_ClusteringResult->SetData(clusteredImage); m_ClusteringResult->SetName("Clusterprobs"); this->GetDataStorage()->Add(m_ClusteringResult, m_SelectedImageNodes->GetNode()); if(m_SelectedPlanarFigure.IsNotNull() && m_SelectedPlanarFigureNodes->GetNode().IsNotNull()) { m_SelectedPlanarFigureNodes->GetNode()->SetIntProperty( "layer", 1001 ); } this->RequestRenderWindowUpdate(); } void QmitkPartialVolumeAnalysisView::UpdateStatistics() { if(!m_CurrentFigureNodeInitialized && m_SelectedPlanarFigure.IsNotNull()) { MITK_DEBUG << "Selected planar figure not initialized. No stats calculation performed."; return; } // Remove any cached images that are no longer referenced elsewhere this->RemoveOrphanImages(); QmitkStdMultiWidget *multiWidget = 0; QmitkStdMultiWidgetEditor * multiWidgetEdit = 0; multiWidgetEdit = dynamic_cast(this->GetRenderWindowPart()); if(multiWidgetEdit){ multiWidget = multiWidgetEdit->GetStdMultiWidget(); } if ( multiWidget == NULL ) { return; } if ( m_SelectedImage.IsNotNull() ) { // Check if a the selected image is a multi-channel image. If yes, statistics // cannot be calculated currently. if ( !m_IsTensorImage && m_SelectedImage->GetPixelType().GetNumberOfComponents() > 1 ) { QMessageBox::information( NULL, "Warning", "Non-tensor multi-component images not supported."); m_Controls->m_HistogramWidget->ClearItemModel(); m_CurrentStatisticsValid = false; return; } // Retrieve HistogramStatisticsCalculator from has map (or create a new one // for this image if non-existant) PartialVolumeAnalysisMapType::iterator it = m_PartialVolumeAnalysisMap.find( m_SelectedImage ); if ( it != m_PartialVolumeAnalysisMap.end() ) { m_CurrentStatisticsCalculator = it->second; } else { m_CurrentStatisticsCalculator = mitk::PartialVolumeAnalysisHistogramCalculator::New(); m_CurrentStatisticsCalculator->SetPlanarFigureThickness(m_Controls->m_PlanarFiguresThickness->value()); if(m_IsTensorImage) { m_CurrentStatisticsCalculator->SetImage( m_CAImage ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_FAImage ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_DirectionComp1Image ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_DirectionComp2Image ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_RDImage ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_ADImage ); m_CurrentStatisticsCalculator->AddAdditionalResamplingImage( m_MDImage ); } else { m_CurrentStatisticsCalculator->SetImage( m_SelectedImage ); } m_PartialVolumeAnalysisMap[m_SelectedImage] = m_CurrentStatisticsCalculator; MITK_DEBUG << "Creating StatisticsCalculator"; } std::string maskName; std::string maskType; unsigned int maskDimension; if ( m_SelectedImageMask.IsNotNull() ) { mitk::PixelType pixelType = m_SelectedImageMask->GetPixelType(); MITK_DEBUG << pixelType.GetPixelTypeAsString(); if(pixelType.GetBitsPerComponent() == 16) { //convert from short to uchar typedef itk::Image ShortImageType; typedef itk::Image CharImageType; CharImageType::Pointer charImage; ShortImageType::Pointer shortImage; mitk::CastToItkImage(m_SelectedImageMask, shortImage); typedef itk::CastImageFilter ImageCasterType; ImageCasterType::Pointer caster = ImageCasterType::New(); caster->SetInput( shortImage ); caster->Update(); charImage = caster->GetOutput(); mitk::CastToMitkImage(charImage, m_SelectedImageMask); } m_CurrentStatisticsCalculator->SetImageMask( m_SelectedImageMask ); m_CurrentStatisticsCalculator->SetMaskingModeToImage(); maskName = m_SelectedMaskNode->GetName(); maskType = m_SelectedImageMask->GetNameOfClass(); maskDimension = 3; std::stringstream maskLabel; maskLabel << maskName; if ( maskDimension > 0 ) { maskLabel << " [" << maskDimension << "D " << maskType << "]"; } m_Controls->m_SelectedMaskLabel->setText( maskLabel.str().c_str() ); } else if ( m_SelectedPlanarFigure.IsNotNull() && m_SelectedPlanarFigureNodes->GetNode().IsNotNull()) { m_CurrentStatisticsCalculator->SetPlanarFigure( m_SelectedPlanarFigure ); m_CurrentStatisticsCalculator->SetMaskingModeToPlanarFigure(); maskName = m_SelectedPlanarFigureNodes->GetNode()->GetName(); maskType = m_SelectedPlanarFigure->GetNameOfClass(); maskDimension = 2; } else { m_CurrentStatisticsCalculator->SetMaskingModeToNone(); maskName = "-"; maskType = ""; maskDimension = 0; } bool statisticsChanged = false; bool statisticsCalculationSuccessful = false; // Initialize progress bar mitk::ProgressBar::GetInstance()->AddStepsToDo( 100 ); // Install listener for progress events and initialize progress bar typedef itk::SimpleMemberCommand< QmitkPartialVolumeAnalysisView > ITKCommandType; ITKCommandType::Pointer progressListener; progressListener = ITKCommandType::New(); progressListener->SetCallbackFunction( this, &QmitkPartialVolumeAnalysisView::UpdateProgressBar ); unsigned long progressObserverTag = m_CurrentStatisticsCalculator ->AddObserver( itk::ProgressEvent(), progressListener ); ClusteringType::ParamsType *cparams = 0; ClusteringType::ClusterResultType *cresult = 0; ClusteringType::HistType *chist = 0; try { m_CurrentStatisticsCalculator->SetNumberOfBins(m_Controls->m_NumberBins->text().toInt()); m_CurrentStatisticsCalculator->SetUpsamplingFactor(m_Controls->m_Upsampling->text().toDouble()); m_CurrentStatisticsCalculator->SetGaussianSigma(m_Controls->m_GaussianSigma->text().toDouble()); // Compute statistics statisticsChanged = m_CurrentStatisticsCalculator->ComputeStatistics( ); mitk::Image* tmpImg = m_CurrentStatisticsCalculator->GetInternalImage(); mitk::Image::ConstPointer imgToCluster = tmpImg; if(imgToCluster.IsNotNull()) { // perform clustering const HistogramType *histogram = m_CurrentStatisticsCalculator->GetHistogram( ); if(histogram != NULL) { ClusteringType::Pointer clusterer = ClusteringType::New(); clusterer->SetStepsNumIntegration(200); clusterer->SetMaxIt(1000); mitk::Image::Pointer pFiberImg; if(m_QuantifyClass==3) { if(m_Controls->m_Quantiles->isChecked()) { m_CurrentRGBClusteringResults = clusterer->PerformRGBQuantiles(imgToCluster, histogram, m_Controls->m_q1->value(),m_Controls->m_q2->value()); } else { m_CurrentRGBClusteringResults = clusterer->PerformRGBClustering(imgToCluster, histogram); } pFiberImg = m_CurrentRGBClusteringResults->rgbChannels->r; cparams = m_CurrentRGBClusteringResults->params; cresult = m_CurrentRGBClusteringResults->result; chist = m_CurrentRGBClusteringResults->hist; } else { if(m_Controls->m_Quantiles->isChecked()) { m_CurrentPerformClusteringResults = clusterer->PerformQuantiles(imgToCluster, histogram, m_Controls->m_q1->value(),m_Controls->m_q2->value()); } else { m_CurrentPerformClusteringResults = clusterer->PerformClustering(imgToCluster, histogram, m_QuantifyClass); } pFiberImg = m_CurrentPerformClusteringResults->clusteredImage; cparams = m_CurrentPerformClusteringResults->params; cresult = m_CurrentPerformClusteringResults->result; chist = m_CurrentPerformClusteringResults->hist; } if(m_IsTensorImage) { m_AngularErrorImage = clusterer->CaculateAngularErrorImage( m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(1), m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(2), pFiberImg); // GetDefaultDataStorage()->Remove(m_newnode2); // m_newnode2 = mitk::DataNode::New(); // m_newnode2->SetData(m_AngularErrorImage); // m_newnode2->SetName(("AngularError")); // m_newnode2->SetIntProperty( "layer", 1003 ); // GetDefaultDataStorage()->Add(m_newnode2, m_SelectedImageNodes->GetNode()); // newnode = mitk::DataNode::New(); // newnode->SetData(m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(1)); // newnode->SetName(("Comp1")); // GetDefaultDataStorage()->Add(newnode, m_SelectedImageNodes->GetNode()); // newnode = mitk::DataNode::New(); // newnode->SetData(m_CurrentStatisticsCalculator->GetInternalAdditionalResampledImage(2)); // newnode->SetName(("Comp2")); // GetDefaultDataStorage()->Add(newnode, m_SelectedImageNodes->GetNode()); } ShowClusteringResults(); } } statisticsCalculationSuccessful = true; } catch ( const std::runtime_error &e ) { QMessageBox::information( NULL, "Warning", e.what()); } catch ( const std::exception &e ) { MITK_ERROR << "Caught exception: " << e.what(); QMessageBox::information( NULL, "Warning", e.what()); } m_CurrentStatisticsCalculator->RemoveObserver( progressObserverTag ); // Make sure that progress bar closes mitk::ProgressBar::GetInstance()->Progress( 100 ); if ( statisticsCalculationSuccessful ) { if ( statisticsChanged ) { // Do not show any error messages m_CurrentStatisticsValid = true; } // m_Controls->m_HistogramWidget->SetHistogramModeToDirectHistogram(); m_Controls->m_HistogramWidget->SetParameters( cparams, cresult, chist ); // m_Controls->m_HistogramWidget->UpdateItemModelFromHistogram(); } else { m_Controls->m_SelectedMaskLabel->setText("mandatory"); // Clear statistics and histogram m_Controls->m_HistogramWidget->ClearItemModel(); m_CurrentStatisticsValid = false; // If a (non-closed) PlanarFigure is selected, display a line profile widget if ( m_SelectedPlanarFigure.IsNotNull() ) { // TODO: enable line profile widget //m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 1 ); //m_Controls->m_LineProfileWidget->SetImage( m_SelectedImage ); //m_Controls->m_LineProfileWidget->SetPlanarFigure( m_SelectedPlanarFigure ); //m_Controls->m_LineProfileWidget->UpdateItemModelFromPath(); } } } } void QmitkPartialVolumeAnalysisView::SetMeasurementInfoToRenderWindow(const QString& text) { FindRenderWindow(m_SelectedPlanarFigureNodes->GetNode()); if(m_LastRenderWindow != m_SelectedRenderWindow) { if(m_LastRenderWindow) { QObject::disconnect( m_LastRenderWindow, SIGNAL( destroyed(QObject*) ) , this, SLOT( OnRenderWindowDelete(QObject*) ) ); } m_LastRenderWindow = m_SelectedRenderWindow; if(m_LastRenderWindow) { QObject::connect( m_LastRenderWindow, SIGNAL( destroyed(QObject*) ) , this, SLOT( OnRenderWindowDelete(QObject*) ) ); } } if(m_LastRenderWindow && m_SelectedPlanarFigureNodes->GetNode().IsNotNull()) { if (!text.isEmpty()) { m_MeasurementInfoAnnotation->SetText(1, text.toLatin1().data()); mitk::VtkLayerController::GetInstance(m_LastRenderWindow->GetRenderWindow())->InsertForegroundRenderer( m_MeasurementInfoRenderer, true); } else { if (mitk::VtkLayerController::GetInstance( m_LastRenderWindow->GetRenderWindow()) ->IsRendererInserted( m_MeasurementInfoRenderer)) mitk::VtkLayerController::GetInstance(m_LastRenderWindow->GetRenderWindow())->RemoveRenderer( m_MeasurementInfoRenderer); } } else { QmitkStdMultiWidget *multiWidget = 0; QmitkStdMultiWidgetEditor * multiWidgetEdit = 0; multiWidgetEdit = dynamic_cast(this->GetRenderWindowPart()); if(multiWidgetEdit){ multiWidget = multiWidgetEdit->GetStdMultiWidget(); } if ( multiWidget == NULL ) { return; } if (!text.isEmpty()) { m_MeasurementInfoAnnotation->SetText(1, text.toLatin1().data()); mitk::VtkLayerController::GetInstance(multiWidget->GetRenderWindow1()->GetRenderWindow())->InsertForegroundRenderer( m_MeasurementInfoRenderer, true); } else { if (mitk::VtkLayerController::GetInstance( multiWidget->GetRenderWindow1()->GetRenderWindow()) ->IsRendererInserted( m_MeasurementInfoRenderer)) mitk::VtkLayerController::GetInstance(multiWidget->GetRenderWindow1()->GetRenderWindow())->RemoveRenderer( m_MeasurementInfoRenderer); } } } void QmitkPartialVolumeAnalysisView::UpdateProgressBar() { mitk::ProgressBar::GetInstance()->Progress(); } void QmitkPartialVolumeAnalysisView::RequestStatisticsUpdate() { if ( !m_StatisticsUpdatePending ) { QApplication::postEvent( this, new QmitkRequestStatisticsUpdateEvent ); m_StatisticsUpdatePending = true; } } void QmitkPartialVolumeAnalysisView::RemoveOrphanImages() { PartialVolumeAnalysisMapType::iterator it = m_PartialVolumeAnalysisMap.begin(); while ( it != m_PartialVolumeAnalysisMap.end() ) { mitk::Image *image = it->first; mitk::PartialVolumeAnalysisHistogramCalculator *calculator = it->second; ++it; mitk::NodePredicateData::Pointer hasImage = mitk::NodePredicateData::New( image ); if ( this->GetDataStorage()->GetNode( hasImage ) == NULL ) { if ( m_SelectedImage == image ) { m_SelectedImage = NULL; m_SelectedImageNodes->RemoveAllNodes(); } if ( m_CurrentStatisticsCalculator == calculator ) { m_CurrentStatisticsCalculator = NULL; } m_PartialVolumeAnalysisMap.erase( image ); it = m_PartialVolumeAnalysisMap.begin(); } } } void QmitkPartialVolumeAnalysisView::ExtractTensorImages( mitk::Image::Pointer tensorimage) { typedef itk::Image< itk::DiffusionTensor3D, 3> TensorImageType; typedef mitk::ImageToItk CastType; CastType::Pointer caster = CastType::New(); caster->SetInput(tensorimage); caster->Update(); TensorImageType::Pointer image = caster->GetOutput(); typedef itk::TensorDerivedMeasurementsFilter MeasurementsType; MeasurementsType::Pointer measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::FA); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer fa = measurementsCalculator->GetOutput(); m_FAImage = mitk::Image::New(); m_FAImage->InitializeByItk(fa.GetPointer()); m_FAImage->SetVolume(fa->GetBufferPointer()); // mitk::DataNode::Pointer node = mitk::DataNode::New(); // node->SetData(m_FAImage); // GetDefaultDataStorage()->Add(node); measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::CA); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer ca = measurementsCalculator->GetOutput(); m_CAImage = mitk::Image::New(); m_CAImage->InitializeByItk(ca.GetPointer()); m_CAImage->SetVolume(ca->GetBufferPointer()); // node = mitk::DataNode::New(); // node->SetData(m_CAImage); // GetDefaultDataStorage()->Add(node); measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::RD); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer rd = measurementsCalculator->GetOutput(); m_RDImage = mitk::Image::New(); m_RDImage->InitializeByItk(rd.GetPointer()); m_RDImage->SetVolume(rd->GetBufferPointer()); // node = mitk::DataNode::New(); // node->SetData(m_CAImage); // GetDefaultDataStorage()->Add(node); measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::AD); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer ad = measurementsCalculator->GetOutput(); m_ADImage = mitk::Image::New(); m_ADImage->InitializeByItk(ad.GetPointer()); m_ADImage->SetVolume(ad->GetBufferPointer()); // node = mitk::DataNode::New(); // node->SetData(m_CAImage); // GetDefaultDataStorage()->Add(node); measurementsCalculator = MeasurementsType::New(); measurementsCalculator->SetInput(image ); measurementsCalculator->SetMeasure(MeasurementsType::RA); measurementsCalculator->Update(); MeasurementsType::OutputImageType::Pointer md = measurementsCalculator->GetOutput(); m_MDImage = mitk::Image::New(); m_MDImage->InitializeByItk(md.GetPointer()); m_MDImage->SetVolume(md->GetBufferPointer()); // node = mitk::DataNode::New(); // node->SetData(m_CAImage); // GetDefaultDataStorage()->Add(node); typedef DirectionsFilterType::OutputImageType DirImageType; DirectionsFilterType::Pointer dirFilter = DirectionsFilterType::New(); dirFilter->SetInput(image ); dirFilter->Update(); itk::ImageRegionIterator itd(dirFilter->GetOutput(), dirFilter->GetOutput()->GetLargestPossibleRegion()); itd = itd.Begin(); while( !itd.IsAtEnd() ) { DirImageType::PixelType direction = itd.Get(); direction[0] = fabs(direction[0]); direction[1] = fabs(direction[1]); direction[2] = fabs(direction[2]); itd.Set(direction); ++itd; } typedef itk::CartesianToPolarVectorImageFilter< DirImageType, DirImageType, true> C2PFilterType; C2PFilterType::Pointer cpFilter = C2PFilterType::New(); cpFilter->SetInput(dirFilter->GetOutput()); cpFilter->Update(); DirImageType::Pointer dir = cpFilter->GetOutput(); typedef itk::Image CompImageType; CompImageType::Pointer comp1 = CompImageType::New(); comp1->SetSpacing( dir->GetSpacing() ); // Set the image spacing comp1->SetOrigin( dir->GetOrigin() ); // Set the image origin comp1->SetDirection( dir->GetDirection() ); // Set the image direction comp1->SetRegions( dir->GetLargestPossibleRegion() ); comp1->Allocate(); CompImageType::Pointer comp2 = CompImageType::New(); comp2->SetSpacing( dir->GetSpacing() ); // Set the image spacing comp2->SetOrigin( dir->GetOrigin() ); // Set the image origin comp2->SetDirection( dir->GetDirection() ); // Set the image direction comp2->SetRegions( dir->GetLargestPossibleRegion() ); comp2->Allocate(); itk::ImageRegionConstIterator it(dir, dir->GetLargestPossibleRegion()); itk::ImageRegionIterator it1(comp1, comp1->GetLargestPossibleRegion()); itk::ImageRegionIterator it2(comp2, comp2->GetLargestPossibleRegion()); it = it.Begin(); it1 = it1.Begin(); it2 = it2.Begin(); while( !it.IsAtEnd() ) { it1.Set(it.Get()[1]); it2.Set(it.Get()[2]); ++it; ++it1; ++it2; } m_DirectionComp1Image = mitk::Image::New(); m_DirectionComp1Image->InitializeByItk(comp1.GetPointer()); m_DirectionComp1Image->SetVolume(comp1->GetBufferPointer()); m_DirectionComp2Image = mitk::Image::New(); m_DirectionComp2Image->InitializeByItk(comp2.GetPointer()); m_DirectionComp2Image->SetVolume(comp2->GetBufferPointer()); } void QmitkPartialVolumeAnalysisView::OnRenderWindowDelete(QObject * obj) { if(obj == m_LastRenderWindow) m_LastRenderWindow = 0; if(obj == m_SelectedRenderWindow) m_SelectedRenderWindow = 0; } bool QmitkPartialVolumeAnalysisView::event( QEvent *event ) { if ( event->type() == (QEvent::Type) QmitkRequestStatisticsUpdateEvent::StatisticsUpdateRequest ) { // Update statistics m_StatisticsUpdatePending = false; this->UpdateStatistics(); return true; } return false; } bool QmitkPartialVolumeAnalysisView::IsExclusiveFunctionality() const { return true; } void QmitkPartialVolumeAnalysisView::Activated() { mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigure* figure = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; // finally add all nodes to the model for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figure = dynamic_cast(node->GetData()); if(figure) { figureInteractor = dynamic_cast(node->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); - mitk::Module* planarFigureModule = mitk::ModuleRegistry::GetModule( "PlanarFigure" ); + us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "PlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( node ); } } } } void QmitkPartialVolumeAnalysisView::Deactivated() { } void QmitkPartialVolumeAnalysisView::ActivatedZombieView(berry::IWorkbenchPartReference::Pointer reference) { this->SetMeasurementInfoToRenderWindow(""); mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigure* figure = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; // finally add all nodes to the model for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figure = dynamic_cast(node->GetData()); if(figure) { figureInteractor = dynamic_cast(node->GetDataInteractor().GetPointer()); if(figureInteractor) figureInteractor->SetDataNode( NULL ); } } } void QmitkPartialVolumeAnalysisView::Hidden() { if (m_ClusteringResult.IsNotNull()) { this->GetDataStorage()->Remove(m_ClusteringResult); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } Select(NULL, true, true); m_Visible = false; } void QmitkPartialVolumeAnalysisView::Visible() { m_Visible = true; berry::IWorkbenchPart::Pointer bla; if (!this->GetCurrentSelection().empty()) { this->OnSelectionChanged(bla, this->GetCurrentSelection()); } else { this->OnSelectionChanged(bla, this->GetDataManagerSelection()); } } void QmitkPartialVolumeAnalysisView::SetFocus() { } void QmitkPartialVolumeAnalysisView::GreenRadio(bool checked) { if(checked) { m_Controls->m_PartialVolumeRadio->setChecked(false); m_Controls->m_BlueRadio->setChecked(false); m_Controls->m_AllRadio->setChecked(false); m_Controls->m_ExportClusteringResultsButton->setEnabled(true); } m_QuantifyClass = 0; RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::PartialVolumeRadio(bool checked) { if(checked) { m_Controls->m_GreenRadio->setChecked(false); m_Controls->m_BlueRadio->setChecked(false); m_Controls->m_AllRadio->setChecked(false); m_Controls->m_ExportClusteringResultsButton->setEnabled(true); } m_QuantifyClass = 1; RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::BlueRadio(bool checked) { if(checked) { m_Controls->m_PartialVolumeRadio->setChecked(false); m_Controls->m_GreenRadio->setChecked(false); m_Controls->m_AllRadio->setChecked(false); m_Controls->m_ExportClusteringResultsButton->setEnabled(true); } m_QuantifyClass = 2; RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::AllRadio(bool checked) { if(checked) { m_Controls->m_BlueRadio->setChecked(false); m_Controls->m_PartialVolumeRadio->setChecked(false); m_Controls->m_GreenRadio->setChecked(false); m_Controls->m_ExportClusteringResultsButton->setEnabled(false); } m_QuantifyClass = 3; RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::NumberBinsChangedSlider(int v ) { m_Controls->m_NumberBins->setText(QString("%1").arg(m_Controls->m_NumberBinsSlider->value()*5.0)); } void QmitkPartialVolumeAnalysisView::UpsamplingChangedSlider( int v) { m_Controls->m_Upsampling->setText(QString("%1").arg(m_Controls->m_UpsamplingSlider->value()/10.0)); } void QmitkPartialVolumeAnalysisView::GaussianSigmaChangedSlider(int v ) { m_Controls->m_GaussianSigma->setText(QString("%1").arg(m_Controls->m_GaussianSigmaSlider->value()/100.0)); } void QmitkPartialVolumeAnalysisView::SimilarAnglesChangedSlider(int v ) { m_Controls->m_SimilarAngles->setText(QString("%1°").arg(90-m_Controls->m_SimilarAnglesSlider->value())); ShowClusteringResults(); } void QmitkPartialVolumeAnalysisView::OpacityChangedSlider(int v ) { if(m_SelectedImageNodes->GetNode().IsNotNull()) { float opacImag = 1.0f-(v-5)/5.0f; opacImag = opacImag < 0 ? 0 : opacImag; m_SelectedImageNodes->GetNode()->SetFloatProperty("opacity", opacImag); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } if(m_ClusteringResult.IsNotNull()) { float opacClust = v/5.0f; opacClust = opacClust > 1 ? 1 : opacClust; m_ClusteringResult->SetFloatProperty("opacity", opacClust); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkPartialVolumeAnalysisView::NumberBinsReleasedSlider( ) { RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::UpsamplingReleasedSlider( ) { RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::GaussianSigmaReleasedSlider( ) { RequestStatisticsUpdate(); } void QmitkPartialVolumeAnalysisView::SimilarAnglesReleasedSlider( ) { } void QmitkPartialVolumeAnalysisView::ToClipBoard() { std::vector* > vals = m_Controls->m_HistogramWidget->m_Vals; QString clipboardText; for (std::vector* >::iterator it = vals.begin(); it != vals.end(); ++it) { for (std::vector::iterator it2 = (**it).begin(); it2 != (**it).end(); ++it2) { clipboardText.append(QString("%1 \t").arg(*it2)); } clipboardText.append(QString("\n")); } QApplication::clipboard()->setText(clipboardText, QClipboard::Clipboard); } void QmitkPartialVolumeAnalysisView::PropertyChanged(const mitk::DataNode* /*node*/, const mitk::BaseProperty* /*prop*/) { } void QmitkPartialVolumeAnalysisView::NodeChanged(const mitk::DataNode* /*node*/) { } void QmitkPartialVolumeAnalysisView::NodeRemoved(const mitk::DataNode* node) { if (dynamic_cast(node->GetData())) this->GetDataStorage()->Remove(m_ClusteringResult); if( node == m_SelectedPlanarFigureNodes->GetNode().GetPointer() || node == m_SelectedMaskNode.GetPointer() ) { this->Select(NULL,true,false); SetMeasurementInfoToRenderWindow(""); } if( node == m_SelectedImageNodes->GetNode().GetPointer() ) { this->Select(NULL,false,true); SetMeasurementInfoToRenderWindow(""); } } void QmitkPartialVolumeAnalysisView::NodeAddedInDataStorage(const mitk::DataNode* node) { if(!m_Visible) return; mitk::DataNode* nonConstNode = const_cast(node); mitk::PlanarFigure* figure = dynamic_cast(nonConstNode->GetData()); if(figure) { // set interactor for new node (if not already set) mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(node->GetDataInteractor().GetPointer()); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); - mitk::Module* planarFigureModule = mitk::ModuleRegistry::GetModule( "PlanarFigure" ); + us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "PlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( nonConstNode ); } // remove uninitialized old planars if( m_SelectedPlanarFigureNodes->GetNode().IsNotNull() && m_CurrentFigureNodeInitialized == false ) { mitk::Interactor::Pointer oldInteractor = m_SelectedPlanarFigureNodes->GetNode()->GetInteractor(); if(oldInteractor.IsNotNull()) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(oldInteractor); this->GetDataStorage()->Remove(m_SelectedPlanarFigureNodes->GetNode()); } } } void QmitkPartialVolumeAnalysisView::TextIntON() { if(m_ClusteringResult.IsNotNull()) { if(m_TexIsOn) { m_Controls->m_TextureIntON->setIcon(*m_IconTexOFF); } else { m_Controls->m_TextureIntON->setIcon(*m_IconTexON); } m_ClusteringResult->SetBoolProperty("texture interpolation", !m_TexIsOn); m_TexIsOn = !m_TexIsOn; this->RequestRenderWindowUpdate(); } } diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp index 8277566398..ceff8ce888 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp @@ -1,274 +1,270 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkMITKSurfaceMaterialEditorView.h" #include "mitkBaseRenderer.h" #include "mitkNodePredicateDataType.h" #include "mitkProperties.h" #include "mitkIDataStorageService.h" #include "mitkDataNodeObject.h" #include "berryIEditorPart.h" #include "berryIWorkbenchPage.h" #include "mitkShaderProperty.h" -#include "mitkShaderRepository.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkStandaloneDataStorage.h" const std::string QmitkMITKSurfaceMaterialEditorView::VIEW_ID = "org.mitk.views.mitksurfacematerialeditor"; QmitkMITKSurfaceMaterialEditorView::QmitkMITKSurfaceMaterialEditorView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL) { fixedProperties.push_back( "shader" ); fixedProperties.push_back( "material.representation" ); fixedProperties.push_back( "color" ); fixedProperties.push_back( "opacity" ); fixedProperties.push_back( "material.wireframeLineWidth" ); fixedProperties.push_back( "material.ambientCoefficient" ); fixedProperties.push_back( "material.diffuseCoefficient" ); fixedProperties.push_back( "material.ambientColor" ); fixedProperties.push_back( "material.diffuseColor" ); fixedProperties.push_back( "material.specularColor" ); fixedProperties.push_back( "material.specularCoefficient" ); fixedProperties.push_back( "material.specularPower" ); fixedProperties.push_back( "material.interpolation" ); shaderProperties.push_back( "shader" ); shaderProperties.push_back( "material.representation" ); shaderProperties.push_back( "color" ); shaderProperties.push_back( "opacity" ); shaderProperties.push_back( "material.wireframeLineWidth" ); observerAllocated = false; - - - mitk::ShaderRepository::GetGlobalShaderRepository(); } QmitkMITKSurfaceMaterialEditorView::~QmitkMITKSurfaceMaterialEditorView() { } void QmitkMITKSurfaceMaterialEditorView::InitPreviewWindow() { usedTimer=0; vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetThetaResolution(25); sphereSource->SetPhiResolution(25); sphereSource->Update(); vtkPolyData* sphere = sphereSource->GetOutput(); m_Surface = mitk::Surface::New(); m_Surface->SetVtkPolyData( sphere ); m_DataNode = mitk::DataNode::New(); m_DataNode->SetData( m_Surface ); m_DataTree = mitk::StandaloneDataStorage::New(); m_DataTree->Add( m_DataNode , (mitk::DataNode *)0 ); m_Controls->m_PreviewRenderWindow->GetRenderer()->SetDataStorage( m_DataTree ); m_Controls->m_PreviewRenderWindow->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); sphereSource->Delete(); } void QmitkMITKSurfaceMaterialEditorView::RefreshPropertiesList() { mitk::DataNode* SrcND = m_SelectedDataNode; mitk::DataNode* DstND = m_DataNode; mitk::PropertyList* DstPL = DstND->GetPropertyList(); m_Controls->m_ShaderPropertyList->SetPropertyList( 0 ); DstPL->Clear(); if(observerAllocated) { observedProperty->RemoveObserver( observerIndex ); observerAllocated=false; } if(SrcND) { mitk::PropertyList* SrcPL = SrcND->GetPropertyList(); mitk::ShaderProperty::Pointer shaderEnum = dynamic_cast(SrcPL->GetProperty("shader")); std::string shaderState = "fixed"; if(shaderEnum.IsNotNull()) { shaderState = shaderEnum->GetValueAsString(); itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); propertyModifiedCommand->SetCallbackFunction(this, &QmitkMITKSurfaceMaterialEditorView::shaderEnumChange); observerIndex = shaderEnum->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); observedProperty = shaderEnum; observerAllocated=true; } MITK_INFO << "PROPERTIES SCAN BEGIN"; for(mitk::PropertyList::PropertyMap::const_iterator it=SrcPL->GetMap()->begin(); it!=SrcPL->GetMap()->end(); it++) { std::string name=it->first; mitk::BaseProperty *p=it->second; // MITK_INFO << "property '" << name << "' found"; if(shaderState.compare("fixed")==0) { if(std::find(fixedProperties.begin(), fixedProperties.end(), name) != fixedProperties.end()) { DstPL->SetProperty(name,p); } } else { //if(std::find(shaderProperties.begin(), shaderProperties.end(), name) != shaderProperties.end()) { DstPL->SetProperty(name,p); } } } MITK_INFO << "PROPERTIES SCAN END"; } m_Controls->m_ShaderPropertyList->SetPropertyList( DstPL ); //m_Controls->m_PreviewRenderWindow->GetRenderer()->GetVtkRenderer()->ResetCameraClippingRange(); } void QmitkMITKSurfaceMaterialEditorView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkMITKSurfaceMaterialEditorViewControls; m_Controls->setupUi(parent); this->CreateConnections(); InitPreviewWindow(); RefreshPropertiesList(); } } void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkMITKSurfaceMaterialEditorView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkMITKSurfaceMaterialEditorView::CreateConnections() { } void QmitkMITKSurfaceMaterialEditorView::Activated() { QmitkFunctionality::Activated(); } void QmitkMITKSurfaceMaterialEditorView::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkMITKSurfaceMaterialEditorView::OnSelectionChanged(std::vector nodes) { if(!nodes.empty()) { m_SelectedDataNode = nodes.at(0); MITK_INFO << "Node '" << m_SelectedDataNode->GetName() << "' selected"; SurfaceSelected(); } } void QmitkMITKSurfaceMaterialEditorView::SurfaceSelected() { postRefresh(); } void QmitkMITKSurfaceMaterialEditorView::shaderEnumChange(const itk::Object * /*caller*/, const itk::EventObject & /*event*/) { postRefresh(); } void QmitkMITKSurfaceMaterialEditorView::postRefresh() { if(usedTimer) return; usedTimer=startTimer(0); } void QmitkMITKSurfaceMaterialEditorView::timerEvent( QTimerEvent *e ) { if(usedTimer!=e->timerId()) { MITK_ERROR << "INTERNAL ERROR: usedTimer[" << usedTimer << "] != timerId[" << e->timerId() << "]"; } if(usedTimer) { killTimer(usedTimer); usedTimer=0; } RefreshPropertiesList(); } diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp index 742109799e..a8f794102b 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkMeasurementView.cpp @@ -1,760 +1,760 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #define MEASUREMENT_DEBUG MITK_DEBUG("QmitkMeasurementView") << __LINE__ << ": " #include "QmitkMeasurementView.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include "mitkModuleRegistry.h" +#include "usModuleRegistry.h" struct QmitkPlanarFigureData { QmitkPlanarFigureData() : m_Figure(0), m_EndPlacementObserverTag(0), m_SelectObserverTag(0), m_StartInteractionObserverTag(0), m_EndInteractionObserverTag(0) { } mitk::PlanarFigure* m_Figure; unsigned int m_EndPlacementObserverTag; unsigned int m_SelectObserverTag; unsigned int m_StartInteractionObserverTag; unsigned int m_EndInteractionObserverTag; }; struct QmitkMeasurementViewData { QmitkMeasurementViewData() : m_LineCounter(0), m_PathCounter(0), m_AngleCounter(0), m_FourPointAngleCounter(0), m_EllipseCounter(0), m_RectangleCounter(0), m_PolygonCounter(0), m_UnintializedPlanarFigure(false) { } // internal vars unsigned int m_LineCounter; unsigned int m_PathCounter; unsigned int m_AngleCounter; unsigned int m_FourPointAngleCounter; unsigned int m_EllipseCounter; unsigned int m_RectangleCounter; unsigned int m_PolygonCounter; QList m_CurrentSelection; std::map m_DataNodeToPlanarFigureData; mitk::WeakPointer m_SelectedImageNode; bool m_UnintializedPlanarFigure; // WIDGETS QWidget* m_Parent; QLabel* m_SelectedImageLabel; QAction* m_DrawLine; QAction* m_DrawPath; QAction* m_DrawAngle; QAction* m_DrawFourPointAngle; QAction* m_DrawEllipse; QAction* m_DrawRectangle; QAction* m_DrawPolygon; QToolBar* m_DrawActionsToolBar; QActionGroup* m_DrawActionsGroup; QTextBrowser* m_SelectedPlanarFiguresText; QPushButton* m_CopyToClipboard; QGridLayout* m_Layout; }; const std::string QmitkMeasurementView::VIEW_ID = "org.mitk.views.measurement"; QmitkMeasurementView::QmitkMeasurementView() : d( new QmitkMeasurementViewData ) { } QmitkMeasurementView::~QmitkMeasurementView() { this->RemoveAllInteractors(); delete d; } void QmitkMeasurementView::CreateQtPartControl(QWidget* parent) { d->m_Parent = parent; // image label QLabel* selectedImageLabel = new QLabel("Reference Image: "); d->m_SelectedImageLabel = new QLabel; d->m_SelectedImageLabel->setStyleSheet("font-weight: bold;"); d->m_DrawActionsToolBar = new QToolBar; d->m_DrawActionsGroup = new QActionGroup(this); d->m_DrawActionsGroup->setExclusive(true); //# add actions MEASUREMENT_DEBUG << "Draw Line"; QAction* currentAction = d->m_DrawActionsToolBar->addAction(QIcon( ":/measurement/line.png"), "Draw Line"); currentAction->setCheckable(true); d->m_DrawLine = currentAction; d->m_DrawActionsToolBar->addAction(currentAction); d->m_DrawActionsGroup->addAction(currentAction); MEASUREMENT_DEBUG << "Draw Path"; currentAction = d->m_DrawActionsToolBar->addAction(QIcon( ":/measurement/path.png"), "Draw Path"); currentAction->setCheckable(true); d->m_DrawPath = currentAction; d->m_DrawActionsToolBar->addAction(currentAction); d->m_DrawActionsGroup->addAction(currentAction); MEASUREMENT_DEBUG << "Draw Angle"; currentAction = d->m_DrawActionsToolBar->addAction(QIcon( ":/measurement/angle.png"), "Draw Angle"); currentAction->setCheckable(true); d->m_DrawAngle = currentAction; d->m_DrawActionsToolBar->addAction(currentAction); d->m_DrawActionsGroup->addAction(currentAction); MEASUREMENT_DEBUG << "Draw Four Point Angle"; currentAction = d->m_DrawActionsToolBar->addAction(QIcon( ":/measurement/four-point-angle.png"), "Draw Four Point Angle"); currentAction->setCheckable(true); d->m_DrawFourPointAngle = currentAction; d->m_DrawActionsToolBar->addAction(currentAction); d->m_DrawActionsGroup->addAction(currentAction); MEASUREMENT_DEBUG << "Draw Circle"; currentAction = d->m_DrawActionsToolBar->addAction(QIcon( ":/measurement/circle.png"), "Draw Circle"); currentAction->setCheckable(true); d->m_DrawEllipse = currentAction; d->m_DrawActionsToolBar->addAction(currentAction); d->m_DrawActionsGroup->addAction(currentAction); MEASUREMENT_DEBUG << "Draw Rectangle"; currentAction = d->m_DrawActionsToolBar->addAction(QIcon( ":/measurement/rectangle.png"), "Draw Rectangle"); currentAction->setCheckable(true); d->m_DrawRectangle = currentAction; d->m_DrawActionsToolBar->addAction(currentAction); d->m_DrawActionsGroup->addAction(currentAction); MEASUREMENT_DEBUG << "Draw Polygon"; currentAction = d->m_DrawActionsToolBar->addAction(QIcon( ":/measurement/polygon.png"), "Draw Polygon"); currentAction->setCheckable(true); d->m_DrawPolygon = currentAction; d->m_DrawActionsToolBar->addAction(currentAction); d->m_DrawActionsGroup->addAction(currentAction); // planar figure details text d->m_SelectedPlanarFiguresText = new QTextBrowser; // copy to clipboard button d->m_CopyToClipboard = new QPushButton("Copy to Clipboard"); d->m_Layout = new QGridLayout; d->m_Layout->addWidget(selectedImageLabel, 0, 0, 1, 1); d->m_Layout->addWidget(d->m_SelectedImageLabel, 0, 1, 1, 1); d->m_Layout->addWidget(d->m_DrawActionsToolBar, 1, 0, 1, 2); d->m_Layout->addWidget(d->m_SelectedPlanarFiguresText, 2, 0, 1, 2); d->m_Layout->addWidget(d->m_CopyToClipboard, 3, 0, 1, 2); d->m_Parent->setLayout(d->m_Layout); // create connections this->CreateConnections(); // readd interactors and observers this->AddAllInteractors(); } void QmitkMeasurementView::CreateConnections() { QObject::connect( d->m_DrawLine, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawLineTriggered(bool) ) ); QObject::connect( d->m_DrawPath, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawPathTriggered(bool) ) ); QObject::connect( d->m_DrawAngle, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawAngleTriggered(bool) ) ); QObject::connect( d->m_DrawFourPointAngle, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawFourPointAngleTriggered(bool) ) ); QObject::connect( d->m_DrawEllipse, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawEllipseTriggered(bool) ) ); QObject::connect( d->m_DrawRectangle, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawRectangleTriggered(bool) ) ); QObject::connect( d->m_DrawPolygon, SIGNAL( triggered(bool) ) , this, SLOT( ActionDrawPolygonTriggered(bool) ) ); QObject::connect( d->m_CopyToClipboard, SIGNAL( clicked(bool) ) , this, SLOT( CopyToClipboard(bool) ) ); } void QmitkMeasurementView::NodeAdded( const mitk::DataNode* node ) { // add observer for selection in renderwindow mitk::PlanarFigure* figure = dynamic_cast(node->GetData()); bool isPositionMarker (false); node->GetBoolProperty("isContourMarker", isPositionMarker); if( figure && !isPositionMarker ) { MEASUREMENT_DEBUG << "figure added. will add interactor if needed."; mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(node->GetDataInteractor().GetPointer() ); mitk::DataNode* nonConstNode = const_cast( node ); if(figureInteractor.IsNull()) { figureInteractor = mitk::PlanarFigureInteractor::New(); - mitk::Module* planarFigureModule = mitk::ModuleRegistry::GetModule( "PlanarFigure" ); + us::Module* planarFigureModule = us::ModuleRegistry::GetModule( "PlanarFigure" ); figureInteractor->LoadStateMachine("PlanarFigureInteraction.xml", planarFigureModule ); figureInteractor->SetEventConfig( "PlanarFigureConfig.xml", planarFigureModule ); figureInteractor->SetDataNode( nonConstNode ); nonConstNode->SetBoolProperty( "planarfigure.isextendable", true ); } else { // just to be sure that the interactor is not added twice // mitk::GlobalInteraction::GetInstance()->RemoveInteractor(figureInteractor); } MEASUREMENT_DEBUG << "adding interactor to globalinteraction"; // mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); MEASUREMENT_DEBUG << "will now add observers for planarfigure"; QmitkPlanarFigureData data; data.m_Figure = figure; // add observer for event when figure has been placed typedef itk::SimpleMemberCommand< QmitkMeasurementView > SimpleCommandType; SimpleCommandType::Pointer initializationCommand = SimpleCommandType::New(); initializationCommand->SetCallbackFunction( this, &QmitkMeasurementView::PlanarFigureInitialized ); data.m_EndPlacementObserverTag = figure->AddObserver( mitk::EndPlacementPlanarFigureEvent(), initializationCommand ); // add observer for event when figure is picked (selected) typedef itk::MemberCommand< QmitkMeasurementView > MemberCommandType; MemberCommandType::Pointer selectCommand = MemberCommandType::New(); selectCommand->SetCallbackFunction( this, &QmitkMeasurementView::PlanarFigureSelected ); data.m_SelectObserverTag = figure->AddObserver( mitk::SelectPlanarFigureEvent(), selectCommand ); // add observer for event when interaction with figure starts SimpleCommandType::Pointer startInteractionCommand = SimpleCommandType::New(); startInteractionCommand->SetCallbackFunction( this, &QmitkMeasurementView::DisableCrosshairNavigation); data.m_StartInteractionObserverTag = figure->AddObserver( mitk::StartInteractionPlanarFigureEvent(), startInteractionCommand ); // add observer for event when interaction with figure starts SimpleCommandType::Pointer endInteractionCommand = SimpleCommandType::New(); endInteractionCommand->SetCallbackFunction( this, &QmitkMeasurementView::EnableCrosshairNavigation); data.m_EndInteractionObserverTag = figure->AddObserver( mitk::EndInteractionPlanarFigureEvent(), endInteractionCommand ); // adding to the map of tracked planarfigures d->m_DataNodeToPlanarFigureData[nonConstNode] = data; } this->CheckForTopMostVisibleImage(); } void QmitkMeasurementView::NodeChanged(const mitk::DataNode* node) { // DETERMINE IF WE HAVE TO RENEW OUR DETAILS TEXT (ANY NODE CHANGED IN OUR SELECTION?) bool renewText = false; for( int i=0; i < d->m_CurrentSelection.size(); ++i ) { if( node == d->m_CurrentSelection.at(i) ) { renewText = true; break; } } if(renewText) { MEASUREMENT_DEBUG << "Selected nodes changed. Refreshing text."; this->UpdateMeasurementText(); } this->CheckForTopMostVisibleImage(); } void QmitkMeasurementView::CheckForTopMostVisibleImage(mitk::DataNode* _NodeToNeglect) { d->m_SelectedImageNode = this->DetectTopMostVisibleImage().GetPointer(); if( d->m_SelectedImageNode.GetPointer() == _NodeToNeglect ) d->m_SelectedImageNode = 0; if( d->m_SelectedImageNode.IsNotNull() && d->m_UnintializedPlanarFigure == false ) { MEASUREMENT_DEBUG << "Reference image found"; d->m_SelectedImageLabel->setText( QString::fromStdString( d->m_SelectedImageNode->GetName() ) ); d->m_DrawActionsToolBar->setEnabled(true); MEASUREMENT_DEBUG << "Updating Measurement text"; } else { MEASUREMENT_DEBUG << "No reference image available. Will disable actions for creating new planarfigures"; if( d->m_UnintializedPlanarFigure == false ) d->m_SelectedImageLabel->setText( "No visible image available." ); d->m_DrawActionsToolBar->setEnabled(false); } } void QmitkMeasurementView::NodeRemoved(const mitk::DataNode* node) { MEASUREMENT_DEBUG << "node removed from data storage"; mitk::DataNode* nonConstNode = const_cast(node); std::map::iterator it = d->m_DataNodeToPlanarFigureData.find(nonConstNode); bool isFigureFinished = false; bool isPlaced = false; if( it != d->m_DataNodeToPlanarFigureData.end() ) { QmitkPlanarFigureData& data = it->second; // remove observers data.m_Figure->RemoveObserver( data.m_EndPlacementObserverTag ); data.m_Figure->RemoveObserver( data.m_SelectObserverTag ); data.m_Figure->RemoveObserver( data.m_StartInteractionObserverTag ); data.m_Figure->RemoveObserver( data.m_EndInteractionObserverTag ); MEASUREMENT_DEBUG << "removing from the list of tracked planar figures"; isFigureFinished = data.m_Figure->GetPropertyList()->GetBoolProperty("initiallyplaced",isPlaced); if (!isFigureFinished) { // if the property does not yet exist or is false, drop the datanode PlanarFigureInitialized(); // normally called when a figure is finished, to reset all buttons } d->m_DataNodeToPlanarFigureData.erase( it ); } mitk::TNodePredicateDataType::Pointer isPlanarFigure = mitk::TNodePredicateDataType::New(); mitk::DataStorage::SetOfObjects::ConstPointer nodes = GetDataStorage()->GetDerivations(node,isPlanarFigure); for (unsigned int x = 0; x < nodes->size(); x++) { mitk::PlanarFigure* planarFigure = dynamic_cast (nodes->at(x)->GetData()); if (planarFigure != NULL) { isFigureFinished = planarFigure->GetPropertyList()->GetBoolProperty("initiallyplaced",isPlaced); if (!isFigureFinished) { // if the property does not yet exist or is false, drop the datanode GetDataStorage()->Remove(nodes->at(x)); if( !d->m_DataNodeToPlanarFigureData.empty() ) { std::map::iterator it2 = d->m_DataNodeToPlanarFigureData.find(nodes->at(x)); //check if returned it2 valid if( it2 != d->m_DataNodeToPlanarFigureData.end() ) { d->m_DataNodeToPlanarFigureData.erase( it2 );// removing planar figure from tracked figure list PlanarFigureInitialized(); // normally called when a figure is finished, to reset all buttons EnableCrosshairNavigation(); } } } } } this->CheckForTopMostVisibleImage(nonConstNode); } void QmitkMeasurementView::PlanarFigureSelected( itk::Object* object, const itk::EventObject& ) { MEASUREMENT_DEBUG << "planar figure " << object << " selected"; std::map::iterator it = d->m_DataNodeToPlanarFigureData.begin(); d->m_CurrentSelection.clear(); while( it != d->m_DataNodeToPlanarFigureData.end()) { mitk::DataNode* node = it->first; QmitkPlanarFigureData& data = it->second; if( data.m_Figure == object ) { MITK_DEBUG << "selected node found. enabling selection"; node->SetSelected(true); d->m_CurrentSelection.push_back( node ); } else { node->SetSelected(false); } ++it; } this->UpdateMeasurementText(); this->RequestRenderWindowUpdate(); } void QmitkMeasurementView::PlanarFigureInitialized() { MEASUREMENT_DEBUG << "planar figure initialized"; d->m_UnintializedPlanarFigure = false; d->m_DrawActionsToolBar->setEnabled(true); d->m_DrawLine->setChecked(false); d->m_DrawPath->setChecked(false); d->m_DrawAngle->setChecked(false); d->m_DrawFourPointAngle->setChecked(false); d->m_DrawEllipse->setChecked(false); d->m_DrawRectangle->setChecked(false); d->m_DrawPolygon->setChecked(false); } void QmitkMeasurementView::SetFocus() { d->m_SelectedImageLabel->setFocus(); } void QmitkMeasurementView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList &nodes) { MEASUREMENT_DEBUG << "Determine the top most visible image"; MEASUREMENT_DEBUG << "The PlanarFigure interactor will take the currently visible PlaneGeometry from the slice navigation controller"; this->CheckForTopMostVisibleImage(); MEASUREMENT_DEBUG << "refreshing selection and detailed text"; d->m_CurrentSelection = nodes; this->UpdateMeasurementText(); for( int i=d->m_CurrentSelection.size()-1; i>= 0; --i) { mitk::DataNode* node = d->m_CurrentSelection.at(i); mitk::PlanarFigure* _PlanarFigure = dynamic_cast (node->GetData()); // the last selected planar figure if( _PlanarFigure ) { mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart()); if( linkedRenderWindow ) { mitk::Point3D centerP = _PlanarFigure->GetGeometry()->GetOrigin(); linkedRenderWindow->GetQmitkRenderWindow("axial")->GetSliceNavigationController()->SelectSliceByPoint(centerP); } break; } } this->RequestRenderWindowUpdate(); } void QmitkMeasurementView::ActionDrawLineTriggered(bool checked) { Q_UNUSED(checked) mitk::PlanarLine::Pointer figure = mitk::PlanarLine::New(); QString qString = QString("Line%1").arg(++d->m_LineCounter); this->AddFigureToDataStorage(figure, qString); MEASUREMENT_DEBUG << "PlanarLine initialized..."; } void QmitkMeasurementView::ActionDrawPathTriggered(bool checked) { Q_UNUSED(checked) mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOff(); QString qString = QString("Path%1").arg(++d->m_PathCounter); mitk::DataNode::Pointer node = this->AddFigureToDataStorage(figure, qString); mitk::BoolProperty::Pointer closedProperty = mitk::BoolProperty::New( false ); node->SetProperty("ClosedPlanarPolygon", closedProperty); MEASUREMENT_DEBUG << "PlanarPath initialized..."; } void QmitkMeasurementView::ActionDrawAngleTriggered(bool checked) { Q_UNUSED(checked) mitk::PlanarAngle::Pointer figure = mitk::PlanarAngle::New(); QString qString = QString("Angle%1").arg(++d->m_AngleCounter); this->AddFigureToDataStorage(figure, qString); MEASUREMENT_DEBUG << "PlanarAngle initialized..."; } void QmitkMeasurementView::ActionDrawFourPointAngleTriggered(bool checked) { Q_UNUSED(checked) mitk::PlanarFourPointAngle::Pointer figure = mitk::PlanarFourPointAngle::New(); QString qString = QString("Four Point Angle%1").arg(++d->m_FourPointAngleCounter); this->AddFigureToDataStorage(figure, qString); MEASUREMENT_DEBUG << "PlanarFourPointAngle initialized..."; } void QmitkMeasurementView::ActionDrawEllipseTriggered(bool checked) { Q_UNUSED(checked) mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); QString qString = QString("Circle%1").arg(++d->m_EllipseCounter); this->AddFigureToDataStorage(figure, qString); MEASUREMENT_DEBUG << "PlanarCircle initialized..."; } void QmitkMeasurementView::ActionDrawRectangleTriggered(bool checked) { Q_UNUSED(checked) mitk::PlanarRectangle::Pointer figure = mitk::PlanarRectangle::New(); QString qString = QString("Rectangle%1").arg(++d->m_RectangleCounter); this->AddFigureToDataStorage(figure, qString); MEASUREMENT_DEBUG << "PlanarRectangle initialized..."; } void QmitkMeasurementView::ActionDrawPolygonTriggered(bool checked) { Q_UNUSED(checked) mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOn(); QString qString = QString("Polygon%1").arg(++d->m_PolygonCounter); this->AddFigureToDataStorage(figure, qString); MEASUREMENT_DEBUG << "PlanarPolygon initialized..."; } void QmitkMeasurementView::CopyToClipboard( bool checked ) { Q_UNUSED(checked) MEASUREMENT_DEBUG << "Copying current Text to clipboard..."; QString clipboardText = d->m_SelectedPlanarFiguresText->toPlainText(); QApplication::clipboard()->setText(clipboardText, QClipboard::Clipboard); } mitk::DataNode::Pointer QmitkMeasurementView::AddFigureToDataStorage( mitk::PlanarFigure* figure, const QString& name) { // add as MEASUREMENT_DEBUG << "Adding new figure to datastorage..."; if( d->m_SelectedImageNode.IsNull() ) { MITK_ERROR << "No reference image available"; return 0; } mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(name.toStdString()); newNode->SetData(figure); // set as selected newNode->SetSelected( true ); this->GetDataStorage()->Add(newNode, d->m_SelectedImageNode); // set all others in selection as deselected for( int i=0; im_CurrentSelection.size(); ++i) d->m_CurrentSelection.at(i)->SetSelected(false); d->m_CurrentSelection.clear(); d->m_CurrentSelection.push_back( newNode ); this->UpdateMeasurementText(); this->DisableCrosshairNavigation(); d->m_DrawActionsToolBar->setEnabled(false); d->m_UnintializedPlanarFigure = true; return newNode; } void QmitkMeasurementView::UpdateMeasurementText() { d->m_SelectedPlanarFiguresText->clear(); QString infoText; QString plainInfoText; int j = 1; mitk::PlanarFigure* _PlanarFigure = 0; mitk::PlanarAngle* planarAngle = 0; mitk::PlanarFourPointAngle* planarFourPointAngle = 0; mitk::DataNode::Pointer node = 0; for (int i=0; im_CurrentSelection.size(); ++i, ++j) { plainInfoText.clear(); node = d->m_CurrentSelection.at(i); _PlanarFigure = dynamic_cast (node->GetData()); if( !_PlanarFigure ) continue; if(j>1) infoText.append("
"); infoText.append(QString("%1


").arg(QString::fromStdString( node->GetName()))); plainInfoText.append(QString("%1").arg(QString::fromStdString( node->GetName()))); planarAngle = dynamic_cast (_PlanarFigure); if(!planarAngle) { planarFourPointAngle = dynamic_cast (_PlanarFigure); } double featureQuantity = 0.0; for (unsigned int k = 0; k < _PlanarFigure->GetNumberOfFeatures(); ++k) { if ( !_PlanarFigure->IsFeatureActive( k ) ) continue; featureQuantity = _PlanarFigure->GetQuantity(k); if ((planarAngle && k == planarAngle->FEATURE_ID_ANGLE) || (planarFourPointAngle && k == planarFourPointAngle->FEATURE_ID_ANGLE)) featureQuantity = featureQuantity * 180 / vnl_math::pi; infoText.append( QString("%1: %2 %3") .arg(QString( _PlanarFigure->GetFeatureName(k))) .arg(featureQuantity, 0, 'f', 2) .arg(QString(_PlanarFigure->GetFeatureUnit(k)))); plainInfoText.append( QString("\n%1: %2 %3") .arg(QString(_PlanarFigure->GetFeatureName(k))) .arg( featureQuantity, 0, 'f', 2) .arg(QString( _PlanarFigure->GetFeatureUnit(k)))); if(k+1 != _PlanarFigure->GetNumberOfFeatures()) infoText.append("
"); } if (j != d->m_CurrentSelection.size()) infoText.append("
"); } d->m_SelectedPlanarFiguresText->setHtml(infoText); } void QmitkMeasurementView::AddAllInteractors() { MEASUREMENT_DEBUG << "Adding interactors to all planar figures"; mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDataStorage()->GetAll(); const mitk::DataNode* node = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); this->NodeAdded( node ); } } void QmitkMeasurementView::RemoveAllInteractors() { MEASUREMENT_DEBUG << "Removing interactors and observers from all planar figures"; mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDataStorage()->GetAll(); const mitk::DataNode* node = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); this->NodeRemoved( node ); } } mitk::DataNode::Pointer QmitkMeasurementView::DetectTopMostVisibleImage() { // get all images from the data storage which are not a segmentation mitk::TNodePredicateDataType::Pointer isImage = mitk::TNodePredicateDataType::New(); mitk::NodePredicateProperty::Pointer isBinary = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); mitk::NodePredicateNot::Pointer isNotBinary = mitk::NodePredicateNot::New( isBinary ); mitk::NodePredicateAnd::Pointer isNormalImage = mitk::NodePredicateAnd::New( isImage, isNotBinary ); mitk::DataStorage::SetOfObjects::ConstPointer Images = this->GetDataStorage()->GetSubset( isNormalImage ); mitk::DataNode::Pointer currentNode; int maxLayer = itk::NumericTraits::min(); // iterate over selection for (mitk::DataStorage::SetOfObjects::ConstIterator sofIt = Images->Begin(); sofIt != Images->End(); ++sofIt) { mitk::DataNode::Pointer node = sofIt->Value(); if ( node.IsNull() ) continue; if (node->IsVisible(NULL) == false) continue; // we also do not want to assign planar figures to helper objects ( even if they are of type image ) if (node->GetProperty("helper object")) continue; int layer = 0; node->GetIntProperty("layer", layer); if ( layer < maxLayer ) { continue; } else { maxLayer = layer; currentNode = node; } } return currentNode; } void QmitkMeasurementView::EnableCrosshairNavigation() { MEASUREMENT_DEBUG << "EnableCrosshairNavigation"; // enable the crosshair navigation if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart())) { MEASUREMENT_DEBUG << "enabling linked navigation"; linkedRenderWindow->EnableLinkedNavigation(true); linkedRenderWindow->EnableSlicingPlanes(true); } } void QmitkMeasurementView::DisableCrosshairNavigation() { MEASUREMENT_DEBUG << "DisableCrosshairNavigation"; // disable the crosshair navigation during the drawing if (mitk::ILinkedRenderWindowPart* linkedRenderWindow = dynamic_cast(this->GetRenderWindowPart())) { MEASUREMENT_DEBUG << "disabling linked navigation"; linkedRenderWindow->EnableLinkedNavigation(false); linkedRenderWindow->EnableSlicingPlanes(false); } } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp index b34e611f13..94e38de516 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp @@ -1,1145 +1,1144 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkProperties.h" #include "mitkSegTool2D.h" +#include "mitkStatusBar.h" #include "QmitkStdMultiWidget.h" #include "QmitkNewSegmentationDialog.h" #include #include #include "QmitkSegmentationView.h" #include "QmitkSegmentationOrganNamesHandling.cpp" #include #include "mitkVtkResliceInterpolationProperty.h" -#include "mitkGetModuleContext.h" -#include "mitkModule.h" -#include "mitkModuleRegistry.h" -#include "mitkModuleResource.h" -#include "mitkStatusBar.h" #include "mitkApplicationCursor.h" - #include "mitkSegmentationObjectFactory.h" +#include "mitkPluginActivator.h" + +#include "usModuleResource.h" +#include "usModuleResourceStream.h" const std::string QmitkSegmentationView::VIEW_ID = "org.mitk.views.segmentation"; // public methods QmitkSegmentationView::QmitkSegmentationView() :m_Parent(NULL) ,m_Controls(NULL) ,m_MultiWidget(NULL) ,m_DataSelectionChanged(false) ,m_MouseCursorSet(false) { RegisterSegmentationObjectFactory(); mitk::NodePredicateDataType::Pointer isDwi = mitk::NodePredicateDataType::New("DiffusionImage"); mitk::NodePredicateDataType::Pointer isDti = mitk::NodePredicateDataType::New("TensorImage"); mitk::NodePredicateDataType::Pointer isQbi = mitk::NodePredicateDataType::New("QBallImage"); mitk::NodePredicateOr::Pointer isDiffusionImage = mitk::NodePredicateOr::New(isDwi, isDti); isDiffusionImage = mitk::NodePredicateOr::New(isDiffusionImage, isQbi); m_IsOfTypeImagePredicate = mitk::NodePredicateOr::New(isDiffusionImage, mitk::TNodePredicateDataType::New()); m_IsBinaryPredicate = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); m_IsNotBinaryPredicate = mitk::NodePredicateNot::New( m_IsBinaryPredicate ); m_IsNotABinaryImagePredicate = mitk::NodePredicateAnd::New( m_IsOfTypeImagePredicate, m_IsNotBinaryPredicate ); m_IsABinaryImagePredicate = mitk::NodePredicateAnd::New( m_IsOfTypeImagePredicate, m_IsBinaryPredicate); } QmitkSegmentationView::~QmitkSegmentationView() { delete m_Controls; } void QmitkSegmentationView::NewNodesGenerated() { MITK_WARN<<"Use of deprecated function: NewNodesGenerated!! This function is empty and will be removed in the next time!"; } void QmitkSegmentationView::NewNodeObjectsGenerated(mitk::ToolManager::DataVectorType* nodes) { if (!nodes) return; mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox2D->GetToolManager(); if (!toolManager) return; for (mitk::ToolManager::DataVectorType::iterator iter = nodes->begin(); iter != nodes->end(); ++iter) { this->FireNodeSelected( *iter ); // only last iteration meaningful, multiple generated objects are not taken into account here } } void QmitkSegmentationView::Visible() { if (m_DataSelectionChanged) { this->OnSelectionChanged(this->GetDataManagerSelection()); } } void QmitkSegmentationView::Activated() { // should be moved to ::BecomesVisible() or similar if( m_Controls ) { //m_Controls->m_ManualToolSelectionBox2D->SetAutoShowNamesWidth(m_Controls->m_ManualToolSelectionBox2D->minimumSizeHint().width()+1); m_Controls->m_ManualToolSelectionBox2D->SetAutoShowNamesWidth(250); m_Controls->m_ManualToolSelectionBox2D->setEnabled( true ); //m_Controls->m_ManualToolSelectionBox3D->SetAutoShowNamesWidth(m_Controls->m_ManualToolSelectionBox3D->minimumSizeHint().width()+1); m_Controls->m_ManualToolSelectionBox3D->SetAutoShowNamesWidth(260); m_Controls->m_ManualToolSelectionBox3D->setEnabled( true ); // m_Controls->m_OrganToolSelectionBox->setEnabled( true ); // m_Controls->m_LesionToolSelectionBox->setEnabled( true ); // m_Controls->m_SlicesInterpolator->Enable3DInterpolation( m_Controls->widgetStack->currentWidget() == m_Controls->pageManual ); mitk::DataStorage::SetOfObjects::ConstPointer segmentations = this->GetDefaultDataStorage()->GetSubset( m_IsABinaryImagePredicate ); mitk::DataStorage::SetOfObjects::ConstPointer image = this->GetDefaultDataStorage()->GetSubset( m_IsNotABinaryImagePredicate ); if (!image->empty()) { OnSelectionChanged(*image->begin()); } for ( mitk::DataStorage::SetOfObjects::const_iterator iter = segmentations->begin(); iter != segmentations->end(); ++iter) { mitk::DataNode* node = *iter; itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( node, node->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); itk::SimpleMemberCommand::Pointer command2 = itk::SimpleMemberCommand::New(); command2->SetCallbackFunction(this, &QmitkSegmentationView::OnBinaryPropertyChanged); m_BinaryPropertyObserverTags.insert( std::pair( node, node->GetProperty("binary")->AddObserver( itk::ModifiedEvent(), command2 ) ) ); } } this->SetToolManagerSelection(m_Controls->patImageSelector->GetSelectedNode(), m_Controls->segImageSelector->GetSelectedNode()); } void QmitkSegmentationView::Deactivated() { if( m_Controls ) { m_Controls->m_ManualToolSelectionBox2D->setEnabled( false ); m_Controls->m_ManualToolSelectionBox3D->setEnabled( false ); //deactivate all tools m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->ActivateTool(-1); // m_Controls->m_OrganToolSelectionBox->setEnabled( false ); // m_Controls->m_LesionToolSelectionBox->setEnabled( false ); m_Controls->m_SlicesInterpolator->EnableInterpolation( false ); //Removing all observers for ( NodeTagMapType::iterator dataIter = m_WorkingDataObserverTags.begin(); dataIter != m_WorkingDataObserverTags.end(); ++dataIter ) { (*dataIter).first->GetProperty("visible")->RemoveObserver( (*dataIter).second ); } m_WorkingDataObserverTags.clear(); for ( NodeTagMapType::iterator dataIter = m_BinaryPropertyObserverTags.begin(); dataIter != m_BinaryPropertyObserverTags.end(); ++dataIter ) { (*dataIter).first->GetProperty("binary")->RemoveObserver( (*dataIter).second ); } m_BinaryPropertyObserverTags.clear(); - // gets the context of the "Mitk" (Core) module (always has id 1) - // TODO Workaround until CTK plugincontext is available - mitk::ModuleContext* context = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); - // Workaround end - mitk::ServiceReference serviceRef = context->GetServiceReference(); - mitk::PlanePositionManagerService* service = dynamic_cast(context->GetService(serviceRef)); + ctkPluginContext* context = mitk::PluginActivator::getContext(); + ctkServiceReference ppmRef = context->getServiceReference(); + mitk::PlanePositionManagerService* service = context->getService(ppmRef); service->RemoveAllPlanePositions(); + context->ungetService(ppmRef); } } void QmitkSegmentationView::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ) { SetMultiWidget(&stdMultiWidget); } void QmitkSegmentationView::StdMultiWidgetNotAvailable() { SetMultiWidget(NULL); } void QmitkSegmentationView::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { SetMultiWidget(NULL); } void QmitkSegmentationView::SetMultiWidget(QmitkStdMultiWidget* multiWidget) { // save the current multiwidget as the working widget m_MultiWidget = multiWidget; if (m_Parent) { m_Parent->setEnabled(m_MultiWidget); } // tell the interpolation about toolmanager and multiwidget (and data storage) if (m_Controls && m_MultiWidget) { mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox2D->GetToolManager(); m_Controls->m_SlicesInterpolator->SetDataStorage( this->GetDefaultDataStorage()); QList controllers; controllers.push_back(m_MultiWidget->GetRenderWindow1()->GetSliceNavigationController()); controllers.push_back(m_MultiWidget->GetRenderWindow2()->GetSliceNavigationController()); controllers.push_back(m_MultiWidget->GetRenderWindow3()->GetSliceNavigationController()); m_Controls->m_SlicesInterpolator->Initialize( toolManager, controllers ); } } void QmitkSegmentationView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { m_AutoSelectionEnabled = prefs->GetBool("auto selection", false); } void QmitkSegmentationView::CreateNewSegmentation() { mitk::DataNode::Pointer node = m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetReferenceData(0); if (node.IsNotNull()) { mitk::Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNotNull()) { if (image->GetDimension()>1) { // ask about the name and organ type of the new segmentation QmitkNewSegmentationDialog* dialog = new QmitkNewSegmentationDialog( m_Parent ); // needs a QWidget as parent, "this" is not QWidget QString storedList = QString::fromStdString( this->GetPreferences()->GetByteArray("Organ-Color-List","") ); QStringList organColors; if (storedList.isEmpty()) { organColors = GetDefaultOrganColorString(); } else { /* a couple of examples of how organ names are stored: a simple item is built up like 'name#AABBCC' where #AABBCC is the hexadecimal notation of a color as known from HTML items are stored separated by ';' this makes it necessary to escape occurrences of ';' in name. otherwise the string "hugo;ypsilon#AABBCC;eugen#AABBCC" could not be parsed as two organs but we would get "hugo" and "ypsilon#AABBCC" and "eugen#AABBCC" so the organ name "hugo;ypsilon" is stored as "hugo\;ypsilon" and must be unescaped after loading the following lines could be one split with Perl's negative lookbehind */ // recover string list from BlueBerry view's preferences QString storedString = QString::fromStdString( this->GetPreferences()->GetByteArray("Organ-Color-List","") ); MITK_DEBUG << "storedString: " << storedString.toStdString(); // match a string consisting of any number of repetitions of either "anything but ;" or "\;". This matches everything until the next unescaped ';' QRegExp onePart("(?:[^;]|\\\\;)*"); MITK_DEBUG << "matching " << onePart.pattern().toStdString(); int count = 0; int pos = 0; while( (pos = onePart.indexIn( storedString, pos )) != -1 ) { ++count; int length = onePart.matchedLength(); if (length == 0) break; QString matchedString = storedString.mid(pos, length); MITK_DEBUG << " Captured length " << length << ": " << matchedString.toStdString(); pos += length + 1; // skip separating ';' // unescape possible occurrences of '\;' in the string matchedString.replace("\\;", ";"); // add matched string part to output list organColors << matchedString; } MITK_DEBUG << "Captured " << count << " organ name/colors"; } dialog->SetSuggestionList( organColors ); int dialogReturnValue = dialog->exec(); if ( dialogReturnValue == QDialog::Rejected ) return; // user clicked cancel or pressed Esc or something similar // ask the user about an organ type and name, add this information to the image's (!) propertylist // create a new image of the same dimensions and smallest possible pixel type mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox2D->GetToolManager(); mitk::Tool* firstTool = toolManager->GetToolById(0); if (firstTool) { try { std::string newNodeName = dialog->GetSegmentationName().toStdString(); if(newNodeName.empty()) newNodeName = "no_name"; mitk::DataNode::Pointer emptySegmentation = firstTool->CreateEmptySegmentationNode( image, newNodeName, dialog->GetColor() ); // initialize showVolume to false to prevent recalculating the volume while working on the segmentation emptySegmentation->SetProperty( "showVolume", mitk::BoolProperty::New( false ) ); if (!emptySegmentation) return; // could be aborted by user UpdateOrganList( organColors, dialog->GetSegmentationName(), dialog->GetColor() ); /* escape ';' here (replace by '\;'), see longer comment above */ std::string stringForStorage = organColors.replaceInStrings(";","\\;").join(";").toStdString(); MITK_DEBUG << "Will store: " << stringForStorage; this->GetPreferences()->PutByteArray("Organ-Color-List", stringForStorage ); this->GetPreferences()->Flush(); if(m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetWorkingData(0)) { m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetWorkingData(0)->SetSelected(false); } emptySegmentation->SetSelected(true); this->GetDefaultDataStorage()->Add( emptySegmentation, node ); // add as a child, because the segmentation "derives" from the original itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( emptySegmentation, emptySegmentation->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); itk::SimpleMemberCommand::Pointer command2 = itk::SimpleMemberCommand::New(); command2->SetCallbackFunction(this, &QmitkSegmentationView::OnBinaryPropertyChanged); m_BinaryPropertyObserverTags.insert( std::pair( emptySegmentation, emptySegmentation->GetProperty("binary")->AddObserver( itk::ModifiedEvent(), command2 ) ) ); this->ApplyDisplayOptions( emptySegmentation ); this->FireNodeSelected( emptySegmentation ); this->OnSelectionChanged( emptySegmentation ); m_Controls->segImageSelector->SetSelectedNode(emptySegmentation); } catch (std::bad_alloc) { QMessageBox::warning(NULL,"Create new segmentation","Could not allocate memory for new segmentation"); } } } else { QMessageBox::information(NULL,"Segmentation","Segmentation is currently not supported for 2D images"); } } } else { MITK_ERROR << "'Create new segmentation' button should never be clickable unless a patient image is selected..."; } } void QmitkSegmentationView::OnWorkingNodeVisibilityChanged() { mitk::DataNode* selectedNode = m_Controls->segImageSelector->GetSelectedNode(); bool selectedNodeIsVisible = selectedNode->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))); if (m_Controls->tab2DTools->isVisible() && !selectedNodeIsVisible) { m_Controls->m_ManualToolSelectionBox2D->setEnabled(false); this->UpdateWarningLabel("The selected segmentation is currently not visible!"); m_Controls->m_SlicesInterpolator->Show3DInterpolationResult(false); m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->ActivateTool(-1); } else { m_Controls->m_ManualToolSelectionBox2D->setEnabled(true); this->UpdateWarningLabel(""); //Trigger 3d interpolation is selected segmentation is visible again mitk::SurfaceInterpolationController::GetInstance()->Modified(); } } void QmitkSegmentationView::OnBinaryPropertyChanged() { mitk::DataStorage::SetOfObjects::ConstPointer patImages = m_Controls->patImageSelector->GetNodes(); bool isBinary(false); for (mitk::DataStorage::SetOfObjects::ConstIterator it = patImages->Begin(); it != patImages->End(); ++it) { const mitk::DataNode* node = it->Value(); node->GetBoolProperty("binary", isBinary); if(isBinary) { m_Controls->patImageSelector->RemoveNode(node); m_Controls->segImageSelector->AddNode(node); this->SetToolManagerSelection(NULL,NULL); return; } } mitk::DataStorage::SetOfObjects::ConstPointer segImages = m_Controls->segImageSelector->GetNodes(); isBinary = true; for (mitk::DataStorage::SetOfObjects::ConstIterator it = segImages->Begin(); it != segImages->End(); ++it) { const mitk::DataNode* node = it->Value(); node->GetBoolProperty("binary", isBinary); if(!isBinary) { m_Controls->segImageSelector->RemoveNode(node); m_Controls->patImageSelector->AddNode(node); if (m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetWorkingData(0) == node) m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->SetWorkingData(NULL); return; } } } void QmitkSegmentationView::NodeAdded(const mitk::DataNode *node) { bool isBinary (false); bool isHelperObject (false); node->GetBoolProperty("binary", isBinary); node->GetBoolProperty("helper object", isHelperObject); if (m_AutoSelectionEnabled) { if (!isBinary && dynamic_cast(node->GetData())) { FireNodeSelected(const_cast(node)); } } if (isBinary && !isHelperObject) { itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( const_cast(node), node->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); itk::SimpleMemberCommand::Pointer command2 = itk::SimpleMemberCommand::New(); command2->SetCallbackFunction(this, &QmitkSegmentationView::OnBinaryPropertyChanged); m_BinaryPropertyObserverTags.insert( std::pair( const_cast(node), node->GetProperty("binary")->AddObserver( itk::ModifiedEvent(), command2 ) ) ); this->ApplyDisplayOptions( const_cast(node) ); } } void QmitkSegmentationView::NodeRemoved(const mitk::DataNode* node) { bool isSeg(false); bool isHelperObject(false); node->GetBoolProperty("helper object", isHelperObject); node->GetBoolProperty("binary", isSeg); mitk::Image* image = dynamic_cast(node->GetData()); if(isSeg && !isHelperObject && image) { //First of all remove all possible contour markers of the segmentation mitk::DataStorage::SetOfObjects::ConstPointer allContourMarkers = this->GetDataStorage()->GetDerivations(node, mitk::NodePredicateProperty::New("isContourMarker" , mitk::BoolProperty::New(true))); - // gets the context of the "Mitk" (Core) module (always has id 1) - // TODO Workaround until CTK plugincontext is available - mitk::ModuleContext* context = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); - // Workaround end - mitk::ServiceReference serviceRef = context->GetServiceReference(); - - mitk::PlanePositionManagerService* service = dynamic_cast(context->GetService(serviceRef)); + ctkPluginContext* context = mitk::PluginActivator::getContext(); + ctkServiceReference ppmRef = context->getServiceReference(); + mitk::PlanePositionManagerService* service = context->getService(ppmRef); for (mitk::DataStorage::SetOfObjects::ConstIterator it = allContourMarkers->Begin(); it != allContourMarkers->End(); ++it) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t+1).c_str())-1; service->RemovePlanePosition(id); this->GetDataStorage()->Remove(it->Value()); } + context->ungetService(ppmRef); + service = NULL; + if ((m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetWorkingData(0) == node) && m_Controls->patImageSelector->GetSelectedNode().IsNotNull()) { this->SetToolManagerSelection(m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetReferenceData(0), NULL); this->UpdateWarningLabel("Select or create a segmentation!"); } mitk::SurfaceInterpolationController::GetInstance()->RemoveSegmentationFromContourList(image); } mitk::DataNode* tempNode = const_cast(node); //Since the binary property could be changed during runtime by the user if (image && !isHelperObject) { node->GetProperty("visible")->RemoveObserver( m_WorkingDataObserverTags[tempNode] ); m_WorkingDataObserverTags.erase(tempNode); node->GetProperty("binary")->RemoveObserver( m_BinaryPropertyObserverTags[tempNode] ); m_BinaryPropertyObserverTags.erase(tempNode); } if((m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetReferenceData(0) == node)) { //as we don't know which node was actually removed e.g. our reference node, disable 'New Segmentation' button. //consider the case that there is no more image in the datastorage this->SetToolManagerSelection(NULL, NULL); } } //void QmitkSegmentationView::CreateSegmentationFromSurface() //{ // mitk::DataNode::Pointer surfaceNode = // m_Controls->MaskSurfaces->GetSelectedNode(); // mitk::Surface::Pointer surface(0); // if(surfaceNode.IsNotNull()) // surface = dynamic_cast ( surfaceNode->GetData() ); // if(surface.IsNull()) // { // this->HandleException( "No surface selected.", m_Parent, true); // return; // } // mitk::DataNode::Pointer imageNode // = m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetReferenceData(0); // mitk::Image::Pointer image(0); // if (imageNode.IsNotNull()) // image = dynamic_cast( imageNode->GetData() ); // if(image.IsNull()) // { // this->HandleException( "No image selected.", m_Parent, true); // return; // } // mitk::SurfaceToImageFilter::Pointer s2iFilter // = mitk::SurfaceToImageFilter::New(); // s2iFilter->MakeOutputBinaryOn(); // s2iFilter->SetInput(surface); // s2iFilter->SetImage(image); // s2iFilter->Update(); // mitk::DataNode::Pointer resultNode = mitk::DataNode::New(); // std::string nameOfResultImage = imageNode->GetName(); // nameOfResultImage.append(surfaceNode->GetName()); // resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) ); // resultNode->SetProperty("binary", mitk::BoolProperty::New(true) ); // resultNode->SetData( s2iFilter->GetOutput() ); // this->GetDataStorage()->Add(resultNode, imageNode); //} //void QmitkSegmentationView::ToolboxStackPageChanged(int id) //{ // // interpolation only with manual tools visible // m_Controls->m_SlicesInterpolator->EnableInterpolation( id == 0 ); // if( id == 0 ) // { // mitk::DataNode::Pointer workingData = m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetWorkingData(0); // if( workingData.IsNotNull() ) // { // m_Controls->segImageSelector->setCurrentIndex( m_Controls->segImageSelector->Find(workingData) ); // } // } // // this is just a workaround, should be removed when all tools support 3D+t // if (id==2) // lesions // { // mitk::DataNode::Pointer node = m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetReferenceData(0); // if (node.IsNotNull()) // { // mitk::Image::Pointer image = dynamic_cast( node->GetData() ); // if (image.IsNotNull()) // { // if (image->GetDimension()>3) // { // m_Controls->widgetStack->setCurrentIndex(0); // QMessageBox::information(NULL,"Segmentation","Lesion segmentation is currently not supported for 4D images"); // } // } // } // } //} // protected void QmitkSegmentationView::OnPatientComboBoxSelectionChanged( const mitk::DataNode* node ) { //mitk::DataNode* selectedNode = const_cast(node); if( node != NULL ) { this->UpdateWarningLabel(""); mitk::DataNode* segNode = m_Controls->segImageSelector->GetSelectedNode(); if (segNode) { mitk::DataStorage::SetOfObjects::ConstPointer possibleParents = this->GetDefaultDataStorage()->GetSources( segNode, m_IsNotABinaryImagePredicate ); bool isSourceNode(false); for (mitk::DataStorage::SetOfObjects::ConstIterator it = possibleParents->Begin(); it != possibleParents->End(); it++) { if (it.Value() == node) isSourceNode = true; } if ( !isSourceNode && (!this->CheckForSameGeometry(segNode, node) || possibleParents->Size() > 0 )) { this->SetToolManagerSelection(node, NULL); this->UpdateWarningLabel("The selected patient image does not\nmatch with the selected segmentation!"); } else if ((!isSourceNode && this->CheckForSameGeometry(segNode, node)) || isSourceNode ) { this->SetToolManagerSelection(node, segNode); //Doing this we can assure that the segmenation is always visible if the segmentation and the patient image are //loaded separately int layer(10); node->GetIntProperty("layer", layer); layer++; segNode->SetProperty("layer", mitk::IntProperty::New(layer)); this->UpdateWarningLabel(""); } } else { this->SetToolManagerSelection(node, NULL); this->UpdateWarningLabel("Select or create a segmentation"); } } else { this->UpdateWarningLabel("Please load an image!"); } } void QmitkSegmentationView::OnSegmentationComboBoxSelectionChanged(const mitk::DataNode *node) { if ( node == 0) return; mitk::DataNode* refNode = m_Controls->patImageSelector->GetSelectedNode(); if (m_AutoSelectionEnabled) { this->OnSelectionChanged(const_cast(node)); } else { mitk::DataStorage::SetOfObjects::ConstPointer possibleParents = this->GetDefaultDataStorage()->GetSources( node, m_IsNotABinaryImagePredicate ); if ( possibleParents->Size() == 1 ) { mitk::DataNode* parentNode = possibleParents->ElementAt(0); if (parentNode != refNode) { this->UpdateWarningLabel("The selected segmentation does not\nmatch with the selected patient image!"); this->SetToolManagerSelection(NULL, node); } else { this->UpdateWarningLabel(""); this->SetToolManagerSelection(refNode, node); } } else if (refNode && this->CheckForSameGeometry(node, refNode)) { this->UpdateWarningLabel(""); this->SetToolManagerSelection(refNode, node); } else if (!refNode || !this->CheckForSameGeometry(node, refNode)) { this->UpdateWarningLabel("Please select or load the according patient image!"); } } if (!node->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1")))) this->UpdateWarningLabel("The selected segmentation is currently not visible!"); } void QmitkSegmentationView::OnShowMarkerNodes (bool state) { mitk::SegTool2D::Pointer manualSegmentationTool; unsigned int numberOfExistingTools = m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetTools().size(); for(unsigned int i = 0; i < numberOfExistingTools; i++) { manualSegmentationTool = dynamic_cast(m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetToolById(i)); if (manualSegmentationTool) { if(state == true) { manualSegmentationTool->SetShowMarkerNodes( true ); } else { manualSegmentationTool->SetShowMarkerNodes( false ); } } } } void QmitkSegmentationView::OnSelectionChanged(mitk::DataNode* node) { std::vector nodes; nodes.push_back( node ); this->OnSelectionChanged( nodes ); } //void QmitkSegmentationView::OnSurfaceSelectionChanged() //{ // // if Image and Surface are selected, enable button // if ( (m_Controls->patImageSelector->GetSelectedNode().IsNull()) || // (m_Controls->MaskSurfaces->GetSelectedNode().IsNull())) // m_Controls->CreateSegmentationFromSurface->setEnabled(false); // else // m_Controls->CreateSegmentationFromSurface->setEnabled(true); //} void QmitkSegmentationView::OnSelectionChanged(std::vector nodes) { if (nodes.size() != 0) { std::string markerName = "Position"; unsigned int numberOfNodes = nodes.size(); std::string nodeName = nodes.at( 0 )->GetName(); if ( ( numberOfNodes == 1 ) && ( nodeName.find( markerName ) == 0) ) { this->OnContourMarkerSelected( nodes.at( 0 ) ); return; } } if (m_AutoSelectionEnabled && this->IsActivated()) { if (nodes.size() == 0 && m_Controls->patImageSelector->GetSelectedNode().IsNull()) { SetToolManagerSelection(NULL,NULL); } else if (nodes.size() == 1) { mitk::DataNode::Pointer selectedNode = nodes.at(0); if(selectedNode.IsNull()) { return; } mitk::Image::Pointer selectedImage = dynamic_cast(selectedNode->GetData()); if (selectedImage.IsNull()) { SetToolManagerSelection(NULL,NULL); return; } else { bool isASegmentation(false); selectedNode->GetBoolProperty("binary", isASegmentation); if (isASegmentation) { //If a segmentation is selected find a possible reference image: mitk::DataStorage::SetOfObjects::ConstPointer sources = this->GetDataStorage()->GetSources(selectedNode, m_IsNotABinaryImagePredicate); mitk::DataNode::Pointer refNode; if (sources->Size() != 0) { refNode = sources->ElementAt(0); refNode->SetVisibility(true); selectedNode->SetVisibility(true); SetToolManagerSelection(refNode,selectedNode); mitk::DataStorage::SetOfObjects::ConstPointer otherSegmentations = this->GetDataStorage()->GetSubset(m_IsABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherSegmentations->begin(); iter != otherSegmentations->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != selectedImage.GetPointer()) node->SetVisibility(false); } mitk::DataStorage::SetOfObjects::ConstPointer otherPatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherPatientImages->begin(); iter != otherPatientImages->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != dynamic_cast(refNode->GetData())) node->SetVisibility(false); } } else { mitk::DataStorage::SetOfObjects::ConstPointer possiblePatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for (mitk::DataStorage::SetOfObjects::ConstIterator it = possiblePatientImages->Begin(); it != possiblePatientImages->End(); it++) { refNode = it->Value(); if (this->CheckForSameGeometry(selectedNode, it->Value())) { refNode->SetVisibility(true); selectedNode->SetVisibility(true); mitk::DataStorage::SetOfObjects::ConstPointer otherSegmentations = this->GetDataStorage()->GetSubset(m_IsABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherSegmentations->begin(); iter != otherSegmentations->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != selectedImage.GetPointer()) node->SetVisibility(false); } mitk::DataStorage::SetOfObjects::ConstPointer otherPatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherPatientImages->begin(); iter != otherPatientImages->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != dynamic_cast(refNode->GetData())) node->SetVisibility(false); } this->SetToolManagerSelection(refNode, selectedNode); //Doing this we can assure that the segmenation is always visible if the segmentation and the patient image are at the //same level in the datamanager int layer(10); refNode->GetIntProperty("layer", layer); layer++; selectedNode->SetProperty("layer", mitk::IntProperty::New(layer)); return; } } this->SetToolManagerSelection(NULL, selectedNode); } } else { if (m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->GetReferenceData(0) != selectedNode) { SetToolManagerSelection(selectedNode, NULL); //May be a bug in the selection services. A node which is deselected will be passed as selected node to the OnSelectionChanged function if (!selectedNode->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1")))) selectedNode->SetVisibility(true); this->UpdateWarningLabel("The selected patient image does not\nmatchwith the selected segmentation!"); } } } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkSegmentationView::OnContourMarkerSelected(const mitk::DataNode *node) { QmitkRenderWindow* selectedRenderWindow = 0; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); bool PlanarFigureInitializedWindow = false; // find initialized renderwindow if (node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } // make node visible if (selectedRenderWindow) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t+1).c_str())-1; - // gets the context of the "Mitk" (Core) module (always has id 1) - // TODO Workaround until CTL plugincontext is available - mitk::ModuleContext* context = mitk::ModuleRegistry::GetModule(1)->GetModuleContext(); - // Workaround end - mitk::ServiceReference serviceRef = context->GetServiceReference(); + { + ctkPluginContext* context = mitk::PluginActivator::getContext(); + ctkServiceReference ppmRef = context->getServiceReference(); + mitk::PlanePositionManagerService* service = context->getService(ppmRef); + selectedRenderWindow->GetSliceNavigationController()->ExecuteOperation(service->GetPlanePosition(id)); + context->ungetService(ppmRef); + } - mitk::PlanePositionManagerService* service = dynamic_cast(context->GetService(serviceRef)); - selectedRenderWindow->GetSliceNavigationController()->ExecuteOperation(service->GetPlanePosition(id)); selectedRenderWindow->GetRenderer()->GetDisplayGeometry()->Fit(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkSegmentationView::OnTabWidgetChanged(int id) { //2D Tab ID = 0 //3D Tab ID = 1 if (id == 0) { //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox3D->hide(); m_Controls->m_ManualToolSelectionBox2D->show(); //Deactivate possible active tool m_Controls->m_ManualToolSelectionBox3D->GetToolManager()->ActivateTool(-1); //TODO Remove possible visible interpolations -> Maybe changes in SlicesInterpolator } else { //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox2D->hide(); m_Controls->m_ManualToolSelectionBox3D->show(); //Deactivate possible active tool m_Controls->m_ManualToolSelectionBox2D->GetToolManager()->ActivateTool(-1); } } void QmitkSegmentationView::SetToolManagerSelection(const mitk::DataNode* referenceData, const mitk::DataNode* workingData) { // called as a result of new BlueBerry selections // tells the ToolManager for manual segmentation about new selections // updates GUI information about what the user should select mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox2D->GetToolManager(); toolManager->SetReferenceData(const_cast(referenceData)); toolManager->SetWorkingData( const_cast(workingData)); // check original image m_Controls->btnNewSegmentation->setEnabled(referenceData != NULL); if (referenceData) { this->UpdateWarningLabel(""); disconnect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->patImageSelector->setCurrentIndex( m_Controls->patImageSelector->Find(referenceData) ); connect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); } // check segmentation if (referenceData) { if (workingData) { this->FireNodeSelected(const_cast(workingData)); // mitk::RenderingManager::GetInstance()->InitializeViews(workingData->GetData()->GetTimeSlicedGeometry(), // mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); // if( m_Controls->widgetStack->currentIndex() == 0 ) // { disconnect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->segImageSelector->setCurrentIndex(m_Controls->segImageSelector->Find(workingData)); connect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged(const mitk::DataNode*)) ); // } } } } void QmitkSegmentationView::ApplyDisplayOptions(mitk::DataNode* node) { if (!node) return; bool isBinary(false); node->GetPropertyValue("binary", isBinary); if (isBinary) { node->SetProperty( "outline binary", mitk::BoolProperty::New( this->GetPreferences()->GetBool("draw outline", true)) ); node->SetProperty( "outline width", mitk::FloatProperty::New( 2.0 ) ); node->SetProperty( "opacity", mitk::FloatProperty::New( this->GetPreferences()->GetBool("draw outline", true) ? 1.0 : 0.3 ) ); node->SetProperty( "volumerendering", mitk::BoolProperty::New( this->GetPreferences()->GetBool("volume rendering", false) ) ); } } bool QmitkSegmentationView::CheckForSameGeometry(const mitk::DataNode *node1, const mitk::DataNode *node2) const { bool isSameGeometry(true); mitk::Image* image1 = dynamic_cast(node1->GetData()); mitk::Image* image2 = dynamic_cast(node2->GetData()); if (image1 && image2) { mitk::Geometry3D* geo1 = image1->GetGeometry(); mitk::Geometry3D* geo2 = image2->GetGeometry(); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetOrigin(), geo2->GetOrigin()); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(0), geo2->GetExtent(0)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(1), geo2->GetExtent(1)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(2), geo2->GetExtent(2)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetSpacing(), geo2->GetSpacing()); isSameGeometry = isSameGeometry && mitk::MatrixEqualElementWise(geo1->GetIndexToWorldTransform()->GetMatrix(), geo2->GetIndexToWorldTransform()->GetMatrix()); return isSameGeometry; } else { return false; } } void QmitkSegmentationView::UpdateWarningLabel(QString text) { if (text.size() == 0) m_Controls->lblSegmentationWarnings->hide(); else m_Controls->lblSegmentationWarnings->show(); m_Controls->lblSegmentationWarnings->setText(text); } void QmitkSegmentationView::CreateQtPartControl(QWidget* parent) { // setup the basic GUI of this view m_Parent = parent; m_Controls = new Ui::QmitkSegmentationControls; m_Controls->setupUi(parent); m_Controls->patImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->patImageSelector->SetPredicate(m_IsNotABinaryImagePredicate); this->UpdateWarningLabel("Please load an image"); if( m_Controls->patImageSelector->GetSelectedNode().IsNotNull() ) this->UpdateWarningLabel("Select or create a new segmentation"); m_Controls->segImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->segImageSelector->SetPredicate(m_IsABinaryImagePredicate); if( m_Controls->segImageSelector->GetSelectedNode().IsNotNull() ) this->UpdateWarningLabel(""); mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox2D->GetToolManager(); toolManager->SetDataStorage( *(this->GetDefaultDataStorage()) ); assert ( toolManager ); //use the same ToolManager instance for our 3D Tools m_Controls->m_ManualToolSelectionBox3D->SetToolManager(*toolManager); // all part of open source MITK m_Controls->m_ManualToolSelectionBox2D->SetGenerateAccelerators(true); m_Controls->m_ManualToolSelectionBox2D->SetToolGUIArea( m_Controls->m_ManualToolGUIContainer2D ); m_Controls->m_ManualToolSelectionBox2D->SetDisplayedToolGroups("Add Subtract Correction Paint Wipe 'Region Growing' Fill Erase 'Live Wire' 'FastMarching2D'"); m_Controls->m_ManualToolSelectionBox2D->SetLayoutColumns(3); m_Controls->m_ManualToolSelectionBox2D->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible ); connect( m_Controls->m_ManualToolSelectionBox2D, SIGNAL(ToolSelected(int)), this, SLOT(OnManualTool2DSelected(int)) ); //setup 3D Tools m_Controls->m_ManualToolSelectionBox3D->SetGenerateAccelerators(true); m_Controls->m_ManualToolSelectionBox3D->SetToolGUIArea( m_Controls->m_ManualToolGUIContainer3D ); //specify tools to be added to 3D Tool area m_Controls->m_ManualToolSelectionBox3D->SetDisplayedToolGroups("Threshold 'Two Thresholds' Otsu FastMarching3D RegionGrowing Watershed"); m_Controls->m_ManualToolSelectionBox3D->SetLayoutColumns(3); m_Controls->m_ManualToolSelectionBox3D->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible ); //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox3D->hide(); m_Controls->m_ManualToolSelectionBox2D->show(); toolManager->NewNodesGenerated += mitk::MessageDelegate( this, &QmitkSegmentationView::NewNodesGenerated ); // update the list of segmentations toolManager->NewNodeObjectsGenerated += mitk::MessageDelegate1( this, &QmitkSegmentationView::NewNodeObjectsGenerated ); // update the list of segmentations // create signal/slot connections connect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); connect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged( const mitk::DataNode* ) ) ); connect( m_Controls->btnNewSegmentation, SIGNAL(clicked()), this, SLOT(CreateNewSegmentation()) ); // connect( m_Controls->CreateSegmentationFromSurface, SIGNAL(clicked()), this, SLOT(CreateSegmentationFromSurface()) ); // connect( m_Controls->widgetStack, SIGNAL(currentChanged(int)), this, SLOT(ToolboxStackPageChanged(int)) ); connect( m_Controls->tabWidgetSegmentationTools, SIGNAL(currentChanged(int)), this, SLOT(OnTabWidgetChanged(int))); // connect(m_Controls->MaskSurfaces, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), // this, SLOT( OnSurfaceSelectionChanged( ) ) ); connect(m_Controls->m_SlicesInterpolator, SIGNAL(SignalShowMarkerNodes(bool)), this, SLOT(OnShowMarkerNodes(bool))); connect(m_Controls->m_SlicesInterpolator, SIGNAL(Signal3DInterpolationEnabled(bool)), this, SLOT(On3DInterpolationEnabled(bool))); // m_Controls->MaskSurfaces->SetDataStorage(this->GetDefaultDataStorage()); // m_Controls->MaskSurfaces->SetPredicate(mitk::NodePredicateDataType::New("Surface")); } void QmitkSegmentationView::OnManualTool2DSelected(int id) { if (id >= 0) { std::string text = "Active Tool: \""; mitk::ToolManager* toolManager = m_Controls->m_ManualToolSelectionBox2D->GetToolManager(); text += toolManager->GetToolById(id)->GetName(); text += "\""; mitk::StatusBar::GetInstance()->DisplayText(text.c_str()); - mitk::ModuleResource resource = toolManager->GetToolById(id)->GetCursorIconResource(); + us::ModuleResource resource = toolManager->GetToolById(id)->GetCursorIconResource(); this->SetMouseCursor(resource, 0, 0); } else { this->ResetMouseCursor(); mitk::StatusBar::GetInstance()->DisplayText(""); } } void QmitkSegmentationView::ResetMouseCursor() { if ( m_MouseCursorSet ) { mitk::ApplicationCursor::GetInstance()->PopCursor(); m_MouseCursorSet = false; } } -void QmitkSegmentationView::SetMouseCursor( const mitk::ModuleResource resource, int hotspotX, int hotspotY ) +void QmitkSegmentationView::SetMouseCursor( const us::ModuleResource& resource, int hotspotX, int hotspotY ) { + if (!resource) return; + // Remove previously set mouse cursor if ( m_MouseCursorSet ) { mitk::ApplicationCursor::GetInstance()->PopCursor(); } - mitk::ApplicationCursor::GetInstance()->PushCursor( resource, hotspotX, hotspotY ); + us::ModuleResourceStream cursor(resource, std::ios::binary); + mitk::ApplicationCursor::GetInstance()->PushCursor( cursor, hotspotX, hotspotY ); m_MouseCursorSet = true; } // ATTENTION some methods for handling the known list of (organ names, colors) are defined in QmitkSegmentationOrganNamesHandling.cpp diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h index 16cf39a985..b1825cacc8 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.h @@ -1,184 +1,184 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkSegmentationView_h #define QmitkSegmentationView_h #include "QmitkFunctionality.h" #include #include "ui_QmitkSegmentationControls.h" class QmitkRenderWindow; /** * \ingroup ToolManagerEtAl * \ingroup org_mitk_gui_qt_segmentation_internal * \warning Implementation of this class is split up into two .cpp files to make things more compact. Check both this file and QmitkSegmentationOrganNamesHandling.cpp */ class QmitkSegmentationView : public QmitkFunctionality { Q_OBJECT public: QmitkSegmentationView(); virtual ~QmitkSegmentationView(); typedef std::map NodeTagMapType; /*! \brief Invoked when the DataManager selection changed */ virtual void OnSelectionChanged(mitk::DataNode* node); virtual void OnSelectionChanged(std::vector nodes); // reaction to new segmentations being created by segmentation tools void NewNodesGenerated(); void NewNodeObjectsGenerated(mitk::ToolManager::DataVectorType*); // QmitkFunctionality's activate/deactivate virtual void Activated(); virtual void Deactivated(); virtual void Visible(); // QmitkFunctionality's changes regarding THE QmitkStdMultiWidget virtual void StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void StdMultiWidgetClosed(QmitkStdMultiWidget& stdMultiWidget); // BlueBerry's notification about preference changes (e.g. from a dialog) virtual void OnPreferencesChanged(const berry::IBerryPreferences* prefs); // observer to mitk::RenderingManager's RenderingManagerViewsInitializedEvent event void RenderingManagerReinitialized(const itk::EventObject&); // observer to mitk::SliceController's SliceRotation event void SliceRotation(const itk::EventObject&); static const std::string VIEW_ID; protected slots: void OnPatientComboBoxSelectionChanged(const mitk::DataNode* node); void OnSegmentationComboBoxSelectionChanged(const mitk::DataNode* node); // reaction to the button "New segmentation" void CreateNewSegmentation(); void OnManualTool2DSelected(int id); // reaction to the button "New segmentation" // void CreateSegmentationFromSurface(); // called when one of "Manual", "Organ", "Lesion" pages of the QToolbox is selected // void ToolboxStackPageChanged(int id); // void OnSurfaceSelectionChanged(); void OnWorkingNodeVisibilityChanged(); // called if a node's binary property has changed void OnBinaryPropertyChanged(); void OnShowMarkerNodes(bool); void OnTabWidgetChanged(int); protected: // a type for handling lists of DataNodes typedef std::vector NodeList; // set available multiwidget void SetMultiWidget(QmitkStdMultiWidget* multiWidget); // actively query the current selection of data manager //void PullCurrentDataManagerSelection(); // reactions to selection events from data manager (and potential other senders) //void BlueBerrySelectionChanged(berry::IWorkbenchPart::Pointer sourcepart, berry::ISelection::ConstPointer selection); mitk::DataNode::Pointer FindFirstRegularImage( std::vector nodes ); mitk::DataNode::Pointer FindFirstSegmentation( std::vector nodes ); // propagate BlueBerry selection to ToolManager for manual segmentation void SetToolManagerSelection(const mitk::DataNode* referenceData, const mitk::DataNode* workingData); // checks if given render window aligns with the slices of given image bool IsRenderWindowAligned(QmitkRenderWindow* renderWindow, mitk::Image* image); // make sure all images/segmentations look as selected by the users in this view's preferences void ForceDisplayPreferencesUponAllImages(); // decorates a DataNode according to the user preference settings void ApplyDisplayOptions(mitk::DataNode* node); // GUI setup void CreateQtPartControl(QWidget* parent); void ResetMouseCursor( ); - void SetMouseCursor(const mitk::ModuleResource, int hotspotX, int hotspotY ); + void SetMouseCursor(const us::ModuleResource&, int hotspotX, int hotspotY ); bool m_MouseCursorSet; // handling of a list of known (organ name, organ color) combination // ATTENTION these methods are defined in QmitkSegmentationOrganNamesHandling.cpp QStringList GetDefaultOrganColorString(); void UpdateOrganList(QStringList& organColors, const QString& organname, mitk::Color colorname); void AppendToOrganList(QStringList& organColors, const QString& organname, int r, int g, int b); // If a contourmarker is selected, the plane in the related widget will be reoriented according to the marker`s geometry void OnContourMarkerSelected (const mitk::DataNode* node); void NodeRemoved(const mitk::DataNode* node); void NodeAdded(const mitk::DataNode *node); bool CheckForSameGeometry(const mitk::DataNode*, const mitk::DataNode*) const; void UpdateWarningLabel(QString text/*, bool overwriteExistingText = true*/); // the Qt parent of our GUI (NOT of this object) QWidget* m_Parent; // our GUI Ui::QmitkSegmentationControls * m_Controls; // THE currently existing QmitkStdMultiWidget QmitkStdMultiWidget * m_MultiWidget; unsigned long m_VisibilityChangedObserverTag; bool m_DataSelectionChanged; NodeTagMapType m_WorkingDataObserverTags; NodeTagMapType m_BinaryPropertyObserverTags; bool m_AutoSelectionEnabled; mitk::NodePredicateOr::Pointer m_IsOfTypeImagePredicate; mitk::NodePredicateProperty::Pointer m_IsBinaryPredicate; mitk::NodePredicateNot::Pointer m_IsNotBinaryPredicate; mitk::NodePredicateAnd::Pointer m_IsNotABinaryImagePredicate; mitk::NodePredicateAnd::Pointer m_IsABinaryImagePredicate; }; #endif /*QMITKsegmentationVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp index d5a7819068..31b2d61769 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.cpp @@ -1,45 +1,55 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPluginActivator.h" #include "QmitkSegmentationView.h" #include "QmitkThresholdAction.h" #include "QmitkOtsuAction.h" #include "QmitkCreatePolygonModelAction.h" #include "QmitkAutocropAction.h" #include "QmitkSegmentationPreferencePage.h" #include "QmitkDeformableClippingPlaneView.h" #include "SegmentationUtilities/QmitkSegmentationUtilitiesView.h" using namespace mitk; +ctkPluginContext* PluginActivator::m_context = NULL; + void PluginActivator::start(ctkPluginContext *context) { BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkThresholdAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkOtsuAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkCreatePolygonModelAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkAutocropAction, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDeformableClippingPlaneView, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkSegmentationUtilitiesView, context) + + this->m_context = context; } void PluginActivator::stop(ctkPluginContext *) { + this->m_context = NULL; +} + +ctkPluginContext*PluginActivator::getContext() +{ + return m_context; } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_segmentation, mitk::PluginActivator) diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.h index 476ae5d4c3..d0c6e5f9e2 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/mitkPluginActivator.h @@ -1,37 +1,43 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKPLUGINACTIVATOR_H #define MITKPLUGINACTIVATOR_H // Parent classes #include #include #include namespace mitk { class MITK_LOCAL PluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: void start(ctkPluginContext *context); void stop(ctkPluginContext *context); + + static ctkPluginContext* getContext(); + + private: + + static ctkPluginContext* m_context; }; } #endif diff --git a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFDeviceGeneration.cpp b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFDeviceGeneration.cpp index 82300e28f9..59b413a273 100644 --- a/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFDeviceGeneration.cpp +++ b/Plugins/org.mitk.gui.qt.tofutil/src/internal/QmitkToFDeviceGeneration.cpp @@ -1,91 +1,80 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Qmitk #include "QmitkToFDeviceGeneration.h" // Qt #include #include #include -#include -#include #include #include #include #include #include - -//Microservices -#include -#include -#include "mitkModuleContext.h" -#include -#include - - const std::string QmitkToFDeviceGeneration::VIEW_ID = "org.mitk.views.tofgeneration"; QmitkToFDeviceGeneration::QmitkToFDeviceGeneration() : QmitkAbstractView() { } QmitkToFDeviceGeneration::~QmitkToFDeviceGeneration() { } void QmitkToFDeviceGeneration::SetFocus() { } void QmitkToFDeviceGeneration::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi( parent ); //CreateDevice-Button connect( (QObject*)(m_Controls.m_CreateDevice), SIGNAL(clicked()), this, SLOT(OnToFCameraConnected()) ); //Initializing the ServiceListWidget with DeviceFactories and Devices on start-uo std::string empty= ""; m_Controls.m_DeviceFactoryServiceListWidget->Initialize("ToFFactoryName", empty); m_Controls.m_ConnectedDeviceServiceListWidget->Initialize("ToFDeviceName", empty); } //Creating a Device void QmitkToFDeviceGeneration::OnToFCameraConnected() { if (m_Controls.m_DeviceFactoryServiceListWidget->GetIsServiceSelected() ) { MITK_INFO << m_Controls.m_DeviceFactoryServiceListWidget->GetSelectedService()->GetFactoryName(); mitk::IToFDeviceFactory* factory = m_Controls.m_DeviceFactoryServiceListWidget->GetSelectedService(); dynamic_cast(factory)->ConnectToFDevice(); // This line should be copied to the DeviceActivator to produce a device on startr up } else { QMessageBox::warning(NULL, "Warning", QString("No Device Factory selected. Unable to create a Device!\nPlease select an other Factory!")); } } diff --git a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.cpp b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.cpp index 48bcc422eb..194aed4f4a 100644 --- a/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.cpp +++ b/Plugins/org.mitk.gui.qt.ultrasound/src/internal/UltrasoundSupport.cpp @@ -1,211 +1,211 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Blueberry #include #include //Mitk #include #include #include // Qmitk #include "UltrasoundSupport.h" #include // Qt #include // Ultrasound #include "mitkUSDevice.h" const std::string UltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport"; void UltrasoundSupport::SetFocus() { m_Controls.m_AddDevice->setFocus(); } void UltrasoundSupport::CreateQtPartControl( QWidget *parent ) { m_Timer = new QTimer(this); // create GUI widgets from the Qt Designer's .ui file m_Controls.setupUi( parent ); connect( m_Controls.m_AddDevice, SIGNAL(clicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities connect( m_Controls.m_AddDevice, SIGNAL(clicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) ); connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage())); connect( m_Controls.crop_left, SIGNAL(valueChanged(int)), this, SLOT(OnCropAreaChanged()) ); connect( m_Controls.crop_right, SIGNAL(valueChanged(int)), this, SLOT(OnCropAreaChanged()) ); connect( m_Controls.crop_top, SIGNAL(valueChanged(int)), this, SLOT(OnCropAreaChanged()) ); connect( m_Controls.crop_bot, SIGNAL(valueChanged(int)), this, SLOT(OnCropAreaChanged()) ); //connect (m_Controls.m_ActiveVideoDevices, SIGNAL()) // Initializations m_Controls.m_NewVideoDeviceWidget->setVisible(false); - std::string filter = "(&(" + mitk::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(" + mitk::USDevice::US_PROPKEY_ISACTIVE + "=true))"; + std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "=" + "org.mitk.services.UltrasoundDevice)(" + mitk::USDevice::US_PROPKEY_ISACTIVE + "=true))"; m_Controls.m_ActiveVideoDevices->Initialize(mitk::USDevice::US_PROPKEY_LABEL ,filter); //UI initializations m_Controls.crop_left->setEnabled(false); m_Controls.crop_right->setEnabled(false); m_Controls.crop_bot->setEnabled(false); m_Controls.crop_top->setEnabled(false); m_Node = mitk::DataNode::New(); m_Node->SetName("US Image Stream"); this->GetDataStorage()->Add(m_Node); } void UltrasoundSupport::OnClickedAddNewDevice() { m_Controls.m_NewVideoDeviceWidget->setVisible(true); m_Controls.m_DeviceManagerWidget->setVisible(false); m_Controls.m_AddDevice->setVisible(false); m_Controls.m_Headline->setText("Add New Device:"); } void UltrasoundSupport::DisplayImage() { m_Device->UpdateOutputData(0); m_Node->SetData(m_Device->GetOutput()); this->RequestRenderWindowUpdate(); m_FrameCounter ++; if (m_FrameCounter == 10) { int nMilliseconds = m_Clock.restart(); int fps = 10000.0f / (nMilliseconds ); m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS"); m_FrameCounter = 0; } } void UltrasoundSupport::OnCropAreaChanged() { if (m_Device->GetDeviceClass()=="org.mitk.modules.us.USVideoDevice") { mitk::USVideoDevice::Pointer currentVideoDevice = dynamic_cast(m_Device.GetPointer()); mitk::USDevice::USImageCropArea newArea; newArea.cropLeft = m_Controls.crop_left->value(); newArea.cropTop = m_Controls.crop_top->value(); newArea.cropRight = m_Controls.crop_right->value(); newArea.cropBottom = m_Controls.crop_bot->value(); //check enabled: if not we are in the initializing step and don't need to do anything //otherwise: update crop area if (m_Controls.crop_right->isEnabled()) currentVideoDevice->SetCropArea(newArea); GlobalReinit(); } else { MITK_WARN << "No USVideoDevice: Cannot Crop!"; } } void UltrasoundSupport::OnClickedViewDevice() { m_FrameCounter = 0; // We use the activity state of the timer to determine whether we are currently viewing images if ( ! m_Timer->isActive() ) // Activate Imaging { //get device & set data node m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService(); if (m_Device.IsNull()){ m_Timer->stop(); return; } m_Device->Update(); m_Node->SetData(m_Device->GetOutput()); //start timer int interval = (1000 / m_Controls.m_FrameRate->value()); m_Timer->setInterval(interval); m_Timer->start(); //reinit view GlobalReinit(); //change UI elements m_Controls.m_BtnView->setText("Stop Viewing"); m_Controls.m_FrameRate->setEnabled(false); m_Controls.crop_left->setValue(m_Device->GetCropArea().cropLeft); m_Controls.crop_right->setValue(m_Device->GetCropArea().cropRight); m_Controls.crop_bot->setValue(m_Device->GetCropArea().cropBottom); m_Controls.crop_top->setValue(m_Device->GetCropArea().cropTop); m_Controls.crop_left->setEnabled(true); m_Controls.crop_right->setEnabled(true); m_Controls.crop_bot->setEnabled(true); m_Controls.crop_top->setEnabled(true); } else //deactivate imaging { //stop timer & release data m_Timer->stop(); m_Node->ReleaseData(); this->RequestRenderWindowUpdate(); //change UI elements m_Controls.m_BtnView->setText("Start Viewing"); m_Controls.m_FrameRate->setEnabled(true); m_Controls.crop_left->setEnabled(false); m_Controls.crop_right->setEnabled(false); m_Controls.crop_bot->setEnabled(false); m_Controls.crop_top->setEnabled(false); } } void UltrasoundSupport::OnNewDeviceWidgetDone() { m_Controls.m_NewVideoDeviceWidget->setVisible(false); m_Controls.m_DeviceManagerWidget->setVisible(true); m_Controls.m_AddDevice->setVisible(true); m_Controls.m_Headline->setText("Connected Devices:"); } void UltrasoundSupport::GlobalReinit() { // get all nodes that have not set "includeInBoundingBox" to false mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); // calculate bounding geometry of these nodes mitk::TimeSlicedGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible"); // initialize the views to the bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } UltrasoundSupport::UltrasoundSupport() { m_DevicePersistence = mitk::USDevicePersistence::New(); m_DevicePersistence->RestoreLastDevices(); } UltrasoundSupport::~UltrasoundSupport() { m_DevicePersistence->StoreCurrentDevices(); m_Controls.m_DeviceManagerWidget->DisconnectAllDevices(); -} \ No newline at end of file +}